aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/strategic_factory_hud.rs
blob: 0e865c3054f0de32f7c8798075f5c29dbc9c94f7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use super::{
    mission_overlay::{add_overlay_sprite, overlay_texture},
    DirectoryVfs, EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer,
};
use fparkan_assets::{
    strategic_factory::{
        FactoryControls, FactoryImages, FactoryOrders, FactoryPicture, FactoryRow, EXTENT, ORIGIN,
    },
    warbot_card::{CardLabels, RatingScale},
};
use fparkan_platform_winit::text::StringResources;
use fparkan_runtime::{factory_panel_project, Engine, FactoryPanelPlant};
use std::path::Path;

#[derive(PartialEq, Eq)]
pub(super) struct FactoryFrame {
    pub plants: Vec<FactoryPanelPlant>,
    pub active_plant: usize,
    pub selected: Option<usize>,
    pub viewing_active: bool,
    pub model_started_ms: u32,
    pub designer_available: bool,
}

impl FactoryFrame {
    pub(super) fn scheme(&self) -> Option<usize> {
        let plant = &self.plants[self.active_plant];
        if self.viewing_active {
            plant.active_project
        } else {
            self.selected
                .and_then(|slot| plant.projects.get(slot).copied())
        }
    }

    pub(super) fn controls(&self) -> FactoryControls {
        let plant = &self.plants[self.active_plant];
        FactoryControls {
            plants: self.plants.len(),
            projects: plant.projects.len(),
            orders: FactoryOrders::for_plant(
                plant.batch,
                plant.progress.is_some(),
                self.scheme().is_some(),
                plant.free_minds,
            ),
            designer_available: self.designer_available,
            active_available: plant.active_project.is_some(),
            free_build: plant.free_build,
        }
    }
}

pub(super) struct StrategicFactoryHud {
    range: EnvironmentGpuRange,
    strings: StringResources,
    images: FactoryImages,
    labels: CardLabels,
    scale: RatingScale,
    displayed: Option<FactoryFrame>,
}

impl StrategicFactoryHud {
    pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
        let strings = StringResources::open(&root.join("iron3d.dll"))?;
        let read = |id| {
            strings
                .get(id)
                .ok_or_else(|| format!("missing factory card string {id:#x}"))
        };
        let images = FactoryImages::load(&DirectoryVfs::new(root), &read(0x647)?)?;
        let labels = CardLabels {
            labels: [
                read(0x13cd)?,
                read(0x13ce)?,
                read(0x13cf)?,
                read(0x13d0)?,
                read(0x13d1)?,
            ],
            tonnes: read(0x183e)?,
            speed: read(0x1820)?,
            metres: read(0x1822)?,
        };
        let scale = match std::fs::read(root.join("iron_3d.ini")) {
            Ok(bytes) => RatingScale::from_ini(&String::from_utf8_lossy(&bytes)),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => RatingScale::default(),
            Err(error) => return Err(error.to_string()),
        };
        let [width, height] = EXTENT;
        let [x, y] = ORIGIN.map(|axis| axis as f32);
        let range = add_overlay_sprite(
            preview,
            fparkan_assets::RgbaImage {
                width,
                height,
                rgba8: vec![0; (width * height * 4) as usize],
            },
            [x, y, x + width as f32, y + height as f32],
            [1.0; 3],
            1.0,
        )?;
        Ok(Self {
            range,
            strings,
            images,
            labels,
            scale,
            displayed: None,
        })
    }

    pub(super) fn range_index(&self) -> usize {
        self.range.range_index
    }

    pub(super) fn draw(
        &mut self,
        renderer: &mut VulkanSmokeRenderer,
        frame: Option<FactoryFrame>,
        engine: Option<&Engine>,
        now_ms: u32,
    ) -> Result<Option<(usize, u32)>, String> {
        renderer
            .set_draw_range_index_count(self.range_index(), if frame.is_some() { 6 } else { 0 })
            .map_err(|error| error.to_string())?;
        let Some(frame) = frame else { return Ok(None) };
        let active_model = frame
            .scheme()
            .map(|scheme| (scheme, now_ms.wrapping_sub(frame.model_started_ms)));
        if self.displayed.as_ref() == Some(&frame) {
            return Ok(active_model);
        }
        let names = frame
            .plants
            .iter()
            .map(|plant| {
                self.strings
                    .get(plant.label_id)
                    .ok_or_else(|| format!("missing factory class {:#x}", plant.label_id))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let rows = names
            .iter()
            .enumerate()
            .map(|(index, name)| FactoryRow {
                name,
                selected: index == frame.active_plant,
            })
            .collect::<Vec<_>>();
        let plant = &frame.plants[frame.active_plant];
        let current_factory = frame.viewing_active.then_some(plant.handle);
        let project = engine
            .zip(frame.scheme())
            .and_then(|(engine, scheme)| factory_panel_project(engine, scheme, current_factory));
        let name = project.as_ref().and_then(|project| {
            let prefix = project.prefix.iter().collect::<String>();
            Some(format!(
                "{prefix}-X {}",
                self.strings.get(project.label_id)?
            ))
        });
        let stats = project.as_ref().map_or_else(
            || [None, None, None, None, None],
            |project| {
                let stats = project.stats;
                self.labels.lines(
                    stats.weight,
                    [stats.speed, stats.defence, stats.offence, stats.radar],
                    &self.scale,
                )
            },
        );
        let image = self.images.paint(FactoryPicture {
            rows: &rows,
            project_name: name.as_deref(),
            stats: &stats,
            controls: frame.controls(),
            selected_project: frame.selected,
            viewing_active: frame.viewing_active,
            progress: plant.progress,
            free_minds: plant.free_minds,
        })?;
        renderer
            .update_material_texture(self.range.material_index, 0, &overlay_texture(image))
            .map_err(|error| error.to_string())?;
        self.displayed = Some(frame);
        Ok(active_model)
    }
}