aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/satellite_map.rs
blob: 26db6c3da589237da4ea9d9539e45afc8e2689bd (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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
use super::{
    mission_overlay::{add_overlay_sprite, overlay_texture},
    strategic_view::ActiveCommandView,
    EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer, VulkanStaticMesh,
};
use fparkan_assets::{
    satellite_map::{load_satellite_map, MAP_INSET, MAP_RECT},
    RgbaImage,
};
use fparkan_runtime::{satellite_contacts, Engine, StartingCockpit};
use fparkan_vfs::DirectoryVfs;
use fparkan_world::ObjectHandle;
use std::{path::Path, sync::Arc};

// Native initial background colour, iron3d+0x74cf0.
const MAP_TINT: [f32; 3] = [55.0 / 255.0, 1.0, 55.0 / 255.0];
const MAP_ALPHA: f32 = 128.0 / 255.0;
const MAP_SIZE: usize = 256;
// iron3d+0x733e0 gives the mode-2 map its own frame, below the command readouts.
const COMMAND_TOP: u32 = 63;
const COMMAND_FRAME_SHIFT: f32 = COMMAND_TOP as f32 * (2.0 / 480.0);

pub(super) struct SatelliteMap {
    frame: EnvironmentGpuRange,
    background: EnvironmentGpuRange,
    compass: EnvironmentGpuRange,
    contact_layer: EnvironmentGpuRange,
    icons: RgbaImage,
    extent: Option<f32>,
    buildings: Vec<satellite_contacts::BuildingContact>,
    units: Vec<satellite_contacts::UnitContact>,
    visible: bool,
    command_layout: bool,
    #[cfg(windows)]
    chrome: Option<super::satellite_map_chrome::SatelliteMapChrome>,
}

impl SatelliteMap {
    pub(super) fn load(
        root: &Path,
        mission: &str,
        engine: &Engine,
        _command_enabled: bool,
        preview: &mut StaticPreviewScene,
    ) -> Result<Option<Self>, String> {
        let Some(assets) = load_satellite_map(Arc::new(DirectoryVfs::new(root)), mission)? else {
            return Ok(None);
        };
        let bounds = MAP_RECT.map(|axis| axis as f32);
        let [left, top, right, bottom] = bounds;
        let inset = MAP_INSET as f32;
        let image = [left + inset, top + inset, right - inset, bottom - inset];
        let [compass_right, compass_bottom] = [image[2] - 1.0, image[3] - 1.0];
        let compass = [
            compass_right - assets.compass.width as f32,
            compass_bottom - assets.compass.height as f32,
            compass_right,
            compass_bottom,
        ];
        let frame = add_overlay_sprite(preview, assets.frame, bounds, [1.0; 3], 1.0)?;
        let background =
            add_overlay_sprite(preview, assets.background, image, MAP_TINT, MAP_ALPHA)?;
        let compass = add_overlay_sprite(preview, assets.compass, compass, [1.0; 3], 1.0)?;
        let contact_layer = add_overlay_sprite(preview, empty_layer(), image, [1.0; 3], 1.0)?;
        #[cfg(windows)]
        let chrome = _command_enabled
            .then(|| {
                super::satellite_map_chrome::SatelliteMapChrome::load(
                    root,
                    assets.icons.clone(),
                    preview,
                )
            })
            .and_then(|result| {
                result
                    .inspect_err(|error| {
                        eprintln!("satellite_map_chrome_unavailable reason={error}")
                    })
                    .ok()
            });
        Ok(Some(Self {
            frame,
            background,
            compass,
            contact_layer,
            icons: assets.icons,
            extent: satellite_contacts::landscape_extent(engine),
            buildings: Vec::new(),
            units: Vec::new(),
            visible: false,
            command_layout: false,
            #[cfg(windows)]
            chrome,
        }))
    }

    pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
        let ranges = self.map_ranges().into_iter();
        #[cfg(windows)]
        let ranges = ranges.chain(self.chrome.iter().flat_map(|chrome| chrome.ranges()));
        ranges
    }

    fn map_ranges(&self) -> [usize; 4] {
        [
            self.frame.range_index,
            self.background.range_index,
            self.compass.range_index,
            self.contact_layer.range_index,
        ]
    }

    pub(super) fn toggle(&mut self) {
        self.visible = !self.visible;
    }

    pub(super) fn show(&mut self) {
        self.visible = true;
    }

    pub(super) fn is_visible(&self) -> bool {
        self.visible
    }

    pub(super) fn hide(&mut self) -> bool {
        std::mem::replace(&mut self.visible, false)
    }

    pub(super) fn command_destination(&self, point: [f32; 2]) -> Option<[f32; 2]> {
        let extent = self.extent.filter(|_| self.visible)?;
        let x = point[0] - (MAP_RECT[0] + MAP_INSET) as f32;
        let y = point[1] - (MAP_RECT[1] + MAP_INSET + COMMAND_TOP) as f32;
        let size = MAP_SIZE as f32;
        ((0.0..size).contains(&x) && (0.0..size).contains(&y))
            .then_some([x * extent / size, (size - y) * extent / size])
    }

    pub(super) fn covers_command_point(&self, [x, y]: [f32; 2]) -> bool {
        let [left, top, right, bottom] = MAP_RECT.map(|value| value as f32);
        let y = y - COMMAND_TOP as f32;
        self.visible && (left..right).contains(&x) && (top..bottom).contains(&y)
    }

    pub(super) fn chrome_at(&self, _pointer: [f32; 2]) -> bool {
        #[cfg(windows)]
        return self.visible
            && self.chrome.is_some()
            && fparkan_assets::satellite_map_chrome::covers_pointer(_pointer);
        #[cfg(not(windows))]
        false
    }

    pub(super) fn close_command_at(&mut self, _pointer: [f32; 2]) -> bool {
        #[cfg(windows)]
        if self.visible
            && self.chrome.is_some()
            && fparkan_assets::satellite_map_chrome::close_at(_pointer)
        {
            return self.hide();
        }
        false
    }

    pub(super) fn draw(
        &mut self,
        renderer: &mut VulkanSmokeRenderer,
        mesh: &mut VulkanStaticMesh,
        player: Option<(&Engine, StartingCockpit, Option<ObjectHandle>)>,
        automatic: bool,
        command: Option<&ActiveCommandView>,
    ) -> Result<(), String> {
        let visible = self.visible || automatic;
        let count = if visible { 6 } else { 0 };
        for index in self.map_ranges() {
            renderer
                .set_draw_range_index_count(index, count)
                .map_err(|error| error.to_string())?;
        }
        let command_layout = command.is_some();
        #[cfg(windows)]
        {
            let contact = command
                .and_then(ActiveCommandView::pointer)
                .and_then(|point| self.command_destination(point))
                .zip(player)
                .and_then(|(xy, (engine, cockpit, _))| {
                    fparkan_runtime::strategic_map_readout::contact_at(engine, cockpit, xy)
                });
            if let Some(chrome) = &mut self.chrome {
                chrome.draw(renderer, visible && command_layout, contact)?;
            }
        }
        if !visible {
            return Ok(());
        }
        if self.command_layout != command_layout {
            self.command_layout = command_layout;
            let shift = if command_layout {
                COMMAND_FRAME_SHIFT
            } else {
                -COMMAND_FRAME_SHIFT
            };
            for range in [
                self.frame,
                self.background,
                self.compass,
                self.contact_layer,
            ] {
                let start = range.vertex_start;
                for vertex in &mut mesh.vertices[start..start + 4] {
                    vertex.position[1] += shift;
                }
            }
        }
        self.update_contacts(
            renderer,
            player,
            command.and_then(ActiveCommandView::route_draft),
        )?;
        Ok(())
    }

    fn update_contacts(
        &mut self,
        renderer: &mut VulkanSmokeRenderer,
        player: Option<(&Engine, StartingCockpit, Option<ObjectHandle>)>,
        draft: Option<&[[f32; 2]]>,
    ) -> Result<(), String> {
        let (buildings, units) = player.zip(self.extent).map_or_else(
            || (Vec::new(), Vec::new()),
            |((engine, cockpit, selected), extent)| {
                (
                    satellite_contacts::visible_buildings(engine, cockpit, extent, selected)
                        .collect(),
                    satellite_contacts::visible_units(engine, cockpit, extent, selected)
                        .map(|mut unit| {
                            if let Some(points) = draft
                                .filter(|_| unit.heading.is_some_and(|heading| heading.selected))
                            {
                                unit.route = points
                                    .iter()
                                    .filter_map(|&point| satellite_contacts::project(point, extent))
                                    .collect();
                            }
                            unit
                        })
                        .collect(),
                )
            },
        );
        if buildings != self.buildings || units != self.units {
            let mut layer = empty_layer();
            for building in &buildings {
                paint_building(&self.icons, &mut layer, *building);
            }
            for unit in &units {
                paint_unit(&mut layer, unit);
            }
            renderer
                .update_material_texture(
                    self.contact_layer.material_index,
                    0,
                    &overlay_texture(layer),
                )
                .map_err(|error| error.to_string())?;
            self.buildings = buildings;
            self.units = units;
        }
        Ok(())
    }
}

fn empty_layer() -> RgbaImage {
    RgbaImage {
        width: MAP_SIZE as u32,
        height: MAP_SIZE as u32,
        rgba8: vec![0; MAP_SIZE * MAP_SIZE * 4],
    }
}

fn paint_unit(layer: &mut RgbaImage, unit: &satellite_contacts::UnitContact) {
    let mut from = unit.pixel;
    for &point in &unit.route {
        paint_line(layer, from, point, [100, 200, 100, 255]);
        for dy in -1..=1 {
            for dx in -1..=1 {
                paint_unit_pixel(layer, point, [dx, dy], [200, 200, 100, 255]);
            }
        }
        from = point;
    }
    let radius = if unit.cross { 2 } else { 1 };
    let [r, g, b] = unit.tint;
    for dy in -radius..=radius {
        for dx in -radius..=radius {
            if !unit.cross || dx == 0 || dy == 0 {
                paint_unit_pixel(layer, unit.pixel, [dx, dy], [r, g, b, 255]);
            }
        }
    }

    let Some(heading) = unit.heading else {
        return;
    };
    let color = if heading.selected {
        [255; 4]
    } else {
        [0, 255, 0, 255]
    };
    let border = radius + 2;
    for offset in -border..=border {
        for point in [
            [offset, -border],
            [offset, border],
            [-border, offset],
            [border, offset],
        ] {
            paint_unit_pixel(layer, unit.pixel, point, color);
        }
    }
    let tip = std::array::from_fn(|axis| unit.pixel[axis].saturating_add(heading.tip_offset[axis]));
    paint_line(layer, unit.pixel, tip, color);
}

fn paint_line(layer: &mut RgbaImage, from: [i32; 2], to: [i32; 2], color: [u8; 4]) {
    let [dx, dy] = std::array::from_fn(|axis| i128::from(to[axis]) - i128::from(from[axis]));
    let major = usize::from(dy.abs() > dx.abs());
    let minor = 1 - major;
    let span = [dx, dy][major].abs();
    if span == 0 {
        paint_unit_pixel(layer, from, [0, 0], color);
        return;
    }
    // Intersect the major-axis interval with the map before rasterizing. Off-map
    // orders retain the direction of the original segment without a long loop.
    let start = from[major].min(to[major]).max(0);
    let end = from[major].max(to[major]).min(MAP_SIZE as i32 - 1);
    let rise = [dx, dy][minor];
    for coordinate in start..=end {
        let step = (i128::from(coordinate) - i128::from(from[major])).abs();
        let offset = ((step * rise.abs() + span / 2) / span) * rise.signum();
        let mut point = from;
        point[major] = coordinate;
        point[minor] = (i128::from(from[minor]) + offset) as i32;
        paint_unit_pixel(layer, point, [0, 0], color);
    }
}

fn paint_unit_pixel(layer: &mut RgbaImage, center: [i32; 2], offset: [i32; 2], color: [u8; 4]) {
    let [x, y] = std::array::from_fn(|axis| center[axis].saturating_add(offset[axis]));
    if (0..MAP_SIZE as i32).contains(&x) && (0..MAP_SIZE as i32).contains(&y) {
        let dst = (y as usize * MAP_SIZE + x as usize) * 4;
        layer.rgba8[dst..dst + 4].copy_from_slice(&color);
    }
}

fn paint_building(
    atlas: &RgbaImage,
    layer: &mut RgbaImage,
    building: satellite_contacts::BuildingContact,
) {
    let [left, top] = building.pixel.map(|center| center.saturating_sub(10));
    // Native 24×24 icon tile at y=24, displayed as a 20×20 square.
    for dy in 0..20 {
        let y = top.saturating_add(dy);
        if !(0..MAP_SIZE as i32).contains(&y) {
            continue;
        }
        for dx in 0..20 {
            let x = left.saturating_add(dx);
            if !(0..MAP_SIZE as i32).contains(&x) {
                continue;
            }
            let src_x = building.icon_x as usize + (dx as usize * 24 + 12) / 20;
            let src_y = 24 + (dy as usize * 24 + 12) / 20;
            let src = (src_y * atlas.width as usize + src_x) * 4;
            let dst = (y as usize * MAP_SIZE + x as usize) * 4;
            let alpha = u32::from(atlas.rgba8[src + 3]);
            if alpha == 0 {
                continue;
            }
            let retained = u32::from(layer.rgba8[dst + 3]) * (255 - alpha) / 255;
            let coverage = alpha + retained;
            for (axis, tint) in building.tint.into_iter().enumerate() {
                let source = u32::from(atlas.rgba8[src + axis]) * u32::from(tint) / 255;
                let under = u32::from(layer.rgba8[dst + axis]);
                layer.rgba8[dst + axis] = ((source * alpha + under * retained) / coverage) as u8;
            }
            layer.rgba8[dst + 3] = coverage as u8;
        }
    }
}