aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/weapon_hud.rs
blob: 0cfcaca763493c2258adac955b2548ebf8bb1fe7 (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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use super::{
    append_environment_gradient_material, append_environment_range, environment_vertex,
    quad_indices, screen_tl_quad_vertices_pixels, world_pipeline_state, DirectoryVfs,
    EnvironmentGpuRange, LegacyBlendMode, LegacyDepthMode, StaticPreviewScene, VulkanSmokeRenderer,
    VulkanStaticMesh, VulkanStaticTexture,
};
use fparkan_assets::{
    game_font::{load_layout_font, BitmapFont},
    object_descriptions::ObjectDescriptions,
    ui_sprite::load_ui_sprites,
    RgbaImage,
};
use fparkan_platform_winit::text::StringResources;
use fparkan_prototype::UnitComponentRecord;
use fparkan_runtime::{PlayerWeapons, WeaponIndicator, WeaponLamp};
use fparkan_world::ObjectHandle;
use std::path::Path;

const ROW_HEIGHT: u16 = 19;
const AMMO_WIDTH: u16 = 24;
const SLOT_WIDTH: u16 = 12;
const NAME_WIDTH: u16 = 120;
const HERO_ROWS: usize = 4;
const VISIBLE_ROWS: usize = 480_usize.div_ceil(ROW_HEIGHT as usize);
// The native renderer lays out cells from the right edge, with a one-pixel overlap.
const WIDTH: u32 = 202;
const UV: [[f32; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];

pub(super) struct WeaponHud {
    hero: ObjectHandle,
    range: EnvironmentGpuRange,
    height: u32,
    hero_labels: [RgbaImage; HERO_ROWS],
    descriptions: Option<ObjectDescriptions>,
    font: BitmapFont,
    unlimited: String,
    lamps: [RgbaImage; 5],
    end: RgbaImage,
    digits: RgbaImage,
    separator: RgbaImage,
    emitter: RgbaImage,
    body: RgbaImage,
    cap: RgbaImage,
    previous: Option<(ObjectHandle, Vec<WeaponIndicator>)>,
}

impl WeaponHud {
    pub(super) fn load(
        root: &Path,
        hero: ObjectHandle,
        preview: &mut StaticPreviewScene,
    ) -> Result<Self, String> {
        let vfs = DirectoryVfs::new(root);
        let [red, yellow1, yellow2, green, black, end, digits, separator, emitter, body, cap] =
            load_ui_sprites(
                &vfs,
                "ui/compaund.cfg",
                [
                    "ccres_red_lamp",
                    "ccres_yellow1_lamp",
                    "ccres_yellow2_lamp",
                    "ccres_green_lamp",
                    "ccres_black_lamp",
                    "ccres_ending_text",
                    "ccres_body_text",
                    "ccres_separator_left_text",
                    "ccres_ray_emitter_off",
                    "ccres_ray_body",
                    "ccres_ray_ending",
                ],
            )?;
        let lamps = [red, yellow1, yellow2, green, black];
        if lamps
            .iter()
            .chain([&end, &digits, &separator, &emitter, &body, &cap])
            .any(|sprite| sprite.height != u32::from(ROW_HEIGHT))
            || lamps.iter().any(|lamp| lamp.width != 19)
            || [end.width, separator.width, emitter.width, cap.width] != [5, 5, 10, 6]
        {
            return Err("inconsistent original weapon HUD sprite dimensions".into());
        }
        let font = load_layout_font(&vfs)?;
        let strings = StringResources::open(&root.join("iron3d.dll"))?;
        let descriptions = ObjectDescriptions::load(&vfs)
            .map_err(|error| eprintln!("weapon_descriptions_unavailable reason={error}"))
            .ok();
        let mut labels = Vec::with_capacity(HERO_ROWS);
        // The hero uses the ordered labels loaded by iron3d+0x74f40.
        for id in 0x0bff..=0x0c02 {
            let text = strings
                .get(id)
                .ok_or_else(|| format!("missing weapon label {id:#x}"))?;
            labels.push(font.centered_line(&text, NAME_WIDTH, ROW_HEIGHT)?);
        }
        let unlimited = strings
            .get(0x13e6)
            .ok_or("missing unlimited-ammunition label")?;
        let material = append_environment_gradient_material(&mut preview.materials)?;
        preview.materials[material].screen_tl = true;
        preview.materials[material].sky_far_depth = false;
        let height = VISIBLE_ROWS as u32 * u32::from(ROW_HEIGHT);
        preview.materials[material].texture = blank_texture(height);
        let range = append_environment_range(
            &mut preview.mesh,
            material,
            vec![environment_vertex([0.0; 3], [1.0; 3], [0.0; 2]); 4],
            quad_indices(1)?,
            world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled),
        )?;
        Ok(Self {
            hero,
            range,
            height,
            descriptions,
            font,
            unlimited,
            end,
            digits,
            separator,
            emitter,
            body,
            cap,
            hero_labels: labels
                .try_into()
                .map_err(|_| "unexpected weapon label count")?,
            lamps,
            previous: None,
        })
    }

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

    pub(super) fn draw(
        &mut self,
        renderer: &mut VulkanSmokeRenderer,
        mesh: &mut VulkanStaticMesh,
        viewport: [f32; 2],
        current: Option<(ObjectHandle, &PlayerWeapons, &[UnitComponentRecord])>,
    ) -> Result<(), String> {
        let bank = current.filter(|(_, bank, _)| !bank.weapons().is_empty());
        renderer
            .set_draw_range_index_count(self.range_index(), if bank.is_some() { 6 } else { 0 })
            .map_err(|error| error.to_string())?;
        let Some((owner, bank, components)) = bank else {
            return Ok(());
        };
        let state = (
            owner,
            bank.indicators()
                .take((self.height / u32::from(ROW_HEIGHT)) as usize)
                .collect::<Vec<_>>(),
        );
        if self.previous.as_ref() != Some(&state) {
            let mut image = blank_texture(self.height);
            for (index, (&indicator, weapon)) in state.1.iter().zip(bank.weapons()).enumerate() {
                let vehicle_label;
                let label = if let Some(label) =
                    self.hero_labels.get(index).filter(|_| owner == self.hero)
                {
                    label
                } else {
                    let name = components
                        .get(weapon.component_index)
                        .and_then(|component| {
                            let name = component.resource_raw.split(|&byte| byte == 0).next()?;
                            self.descriptions.as_ref()?.short_name(name)
                        });
                    // iron3d+0x75e7f initializes the device label before looking up its prototype.
                    vehicle_label = self.font.centered_line_bytes(
                        name.unwrap_or(b"NONAME"),
                        NAME_WIDTH,
                        ROW_HEIGHT,
                    )?;
                    &vehicle_label
                };
                self.draw_row(&mut image, index, indicator, label)?;
            }
            renderer
                .update_material_texture(self.range.material_index, 0, &image)
                .map_err(|error| error.to_string())?;
            self.previous = Some(state);
        }
        let width = WIDTH as f32 * viewport[0] / 640.0;
        let height = self.height as f32 * viewport[1] / 480.0;
        let start = self.range.vertex_start;
        mesh.vertices[start..start + 4].copy_from_slice(&screen_tl_quad_vertices_pixels(
            [viewport[0] - width * 0.5, height * 0.5],
            width * 0.5,
            height * 0.5,
            viewport,
            [1.0; 3],
            1.0,
            UV,
        ));
        Ok(())
    }

    fn draw_row(
        &self,
        image: &mut VulkanStaticTexture,
        index: usize,
        state: WeaponIndicator,
        label: &RgbaImage,
    ) -> Result<(), String> {
        let y = index as u32 * u32::from(ROW_HEIGHT);
        let lamp = &self.lamps[match state.lamp {
            WeaponLamp::Unavailable => 0,
            WeaponLamp::Reloading => 1,
            WeaponLamp::Cycling => 2,
            WeaponLamp::Ready => 3,
            WeaponLamp::Unselected => 4,
        }];
        let mut right = WIDTH;
        let mut cell = |sprite: &RgbaImage, width: u32| {
            right -= width;
            paint(image, sprite, right - 1, y, width + 1);
            right
        };
        cell(&self.end, self.end.width);
        let slot_x = cell(&self.digits, u32::from(SLOT_WIDTH));
        cell(lamp, lamp.width);
        let ammo_x = cell(&self.digits, u32::from(AMMO_WIDTH));
        cell(&self.separator, self.separator.width);
        cell(&self.emitter, self.emitter.width);
        let name_x = cell(&self.body, u32::from(NAME_WIDTH));
        cell(&self.cap, self.cap.width);
        let tint = match state.charge_percent {
            0..=19 => [128, 0, 0, 128],
            20..=79 => [128, 128, 0, 128],
            _ => [0, 128, 0, 128],
        };
        let charged = (f64::from(state.charge_percent) * f64::from(NAME_WIDTH) / 100.0)
            .round_ties_even() as u32;
        for row in y + 3..y + u32::from(ROW_HEIGHT) - 3 {
            for x in name_x + u32::from(NAME_WIDTH) - charged..name_x + u32::from(NAME_WIDTH) - 2 {
                paint_pixel(image, x, row, &tint);
            }
        }
        let slot = self
            .font
            .centered_line(&(index + 1).to_string(), SLOT_WIDTH, ROW_HEIGHT)?;
        let rounds = state
            .rounds
            .map_or_else(|| self.unlimited.clone(), |count| count.to_string());
        let ammo = self.font.centered_line(&rounds, AMMO_WIDTH, ROW_HEIGHT)?;
        for (x, glyphs) in [(slot_x, &slot), (ammo_x, &ammo), (name_x, label)] {
            paint(image, glyphs, x, y, glyphs.width);
        }
        Ok(())
    }
}

fn blank_texture(height: u32) -> VulkanStaticTexture {
    VulkanStaticTexture {
        width: WIDTH,
        height,
        rgba8: vec![0; (WIDTH * height * 4) as usize],
        mip_levels: Vec::new(),
    }
}

fn paint(image: &mut VulkanStaticTexture, sprite: &RgbaImage, left: u32, top: u32, width: u32) {
    for y in 0..sprite.height {
        for x in 0..width {
            let source_x = x * sprite.width / width;
            let offset = ((y * sprite.width + source_x) * 4) as usize;
            paint_pixel(image, left + x, top + y, &sprite.rgba8[offset..offset + 4]);
        }
    }
}

fn paint_pixel(image: &mut VulkanStaticTexture, x: u32, y: u32, source: &[u8]) {
    let start = ((y * WIDTH + x) * 4) as usize;
    super::mission_overlay::source_over(&mut image.rgba8[start..start + 4], source);
}