aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/satellite_map.rs
blob: d1d11ce3110f2cbb403dc29f074c88bbc83fb0f3 (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
//! Resources used by the satellite map overlay.

use crate::{
    mission_pager::{scale, UiFrame},
    ui_configuration::{field, number, object, read},
};
use fparkan_nres::{decode, EntryId, ReadProfile};
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_resource::{resource_name, CachedResourceRepository, ResourceRepository};
use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage};
use fparkan_vfs::Vfs;
use std::sync::Arc;

/// Framed map bounds in the original 640×480 coordinates (iron3d+0x733e0).
pub const MAP_RECT: [u32; 4] = [374, 0, 640, 266];
/// Inset between the frame and the mission image (iron3d+0x74cf0).
pub const MAP_INSET: u32 = 5;

/// The mission map, compass and contact atlas from the installed game.
pub struct SatelliteMapAssets {
    pub frame: RgbaImage,
    pub background: RgbaImage,
    pub compass: RgbaImage,
    pub icons: RgbaImage,
}

/// Resolves `minimap` through the mission CFG and the compass through the game UI CFG.
pub fn load_satellite_map(
    vfs: Arc<dyn Vfs>,
    mission: &str,
) -> Result<Option<SatelliteMapAssets>, String> {
    let cfg = mission.rsplit_once('/').map_or_else(
        || "mission.cfg".to_owned(),
        |(dir, _)| format!("{dir}/mission.cfg"),
    );
    let bytes = read(vfs.as_ref(), &cfg)?;
    let cfg = String::from_utf8_lossy(&bytes);
    let Some(minimap) = object(&cfg, "minimap") else {
        return Ok(None);
    };
    let archive = normalize_relative(
        field(&minimap, "LIBRARY")?.as_bytes(),
        PathPolicy::StrictLegacy,
    )
    .map_err(|error| error.to_string())?;
    let repo = CachedResourceRepository::new(vfs.clone());
    let archive_id = repo
        .open_archive(&archive)
        .map_err(|error| error.to_string())?;
    let file = field(&minimap, "MINIMAP")?;
    let entry = repo
        .find(archive_id, &resource_name(file))
        .map_err(|error| error.to_string())?
        .ok_or_else(|| format!("missing mission map {file} in {}", archive.as_str()))?;
    let payload = repo.read(entry).map_err(|error| error.to_string())?;
    let background = texture(payload.as_slice())?;

    let hq = read(vfs.as_ref(), "ui/hq.cfg")?;
    let hq = String::from_utf8_lossy(&hq);
    let icon = object(&hq, "map_compass_icon").ok_or("missing map_compass_icon in ui/hq.cfg")?;
    let game = read(vfs.as_ref(), "ui/game_resources.cfg")?;
    let game = String::from_utf8_lossy(&game);
    let textures = object(&game, "textures").ok_or("missing textures in ui/game_resources.cfg")?;
    let atlas = field(&textures, "LIBRARY")?;
    let page = field(&icon, "TEXTURE")?.to_ascii_uppercase();
    let pages = decode(read(vfs.as_ref(), atlas)?, ReadProfile::Strict)
        .map_err(|error| error.to_string())?;
    let page = pages
        .payload(EntryId(number(&textures, &page)?))
        .map_err(|error| error.to_string())?;
    let compass = crop(
        &texture(page)?,
        [number(&icon, "OFFSET_X")?, number(&icon, "OFFSET_Y")?],
        [number(&icon, "WIDTH")?, number(&icon, "HEIGHT")?],
    )?;
    let icon_page = pages
        .payload(EntryId(number(&textures, "ICONS")?))
        .map_err(|error| error.to_string())?;
    let icons = texture(icon_page)?;
    if icons.width != 256 || icons.height != 256 {
        return Err("unexpected satellite icon atlas dimensions".into());
    }
    let [left, top, right, bottom] = MAP_RECT;
    let bounds = [0, 0, right - left, bottom - top];
    let [_, _, width, height] = bounds.map(scale);
    let mut frame = RgbaImage {
        width,
        height,
        rgba8: vec![0; (width * height * 4) as usize],
    };
    UiFrame::load(vfs.as_ref())?.paint(&mut frame, bounds, [0; 4]);
    Ok(Some(SatelliteMapAssets {
        frame,
        background,
        compass,
        icons,
    }))
}

fn texture(bytes: &[u8]) -> Result<RgbaImage, String> {
    let document = decode_texm(Arc::from(bytes)).map_err(|error| error.to_string())?;
    decode_mip_rgba8(&document, 0).map_err(|error| error.to_string())
}

fn crop(
    image: &RgbaImage,
    [x, y]: [u32; 2],
    [width, height]: [u32; 2],
) -> Result<RgbaImage, String> {
    let right = x
        .checked_add(width)
        .filter(|&right| right <= image.width && width != 0);
    let bottom = y
        .checked_add(height)
        .filter(|&bottom| bottom <= image.height && height != 0);
    let (Some(right), Some(bottom)) = (right, bottom) else {
        return Err("map compass rectangle is outside the texture atlas".into());
    };
    let stride = image.width as usize * 4;
    let mut rgba8 = Vec::new();
    for row in y as usize..bottom as usize {
        rgba8.extend_from_slice(
            &image.rgba8[row * stride + x as usize * 4..row * stride + right as usize * 4],
        );
    }
    Ok(RgbaImage {
        width,
        height,
        rgba8,
    })
}

#[cfg(test)]
mod tests {
    use super::load_satellite_map;
    use fparkan_vfs::DirectoryVfs;
    use std::sync::Arc;

    #[test]
    #[ignore = "requires licensed corpus"]
    fn loads_distinct_mission_textures_and_the_shared_compass() {
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
        let vfs = Arc::new(DirectoryVfs::new(root));
        let load = |mission| {
            load_satellite_map(vfs.clone(), &format!("MISSIONS/{mission}/data.tma"))
                .unwrap()
                .expect("authored map")
        };
        let range = load("CAMPAIGN/CAMPAIGN.00/Mission.01");
        let fortresses = load("Single.01");
        assert_eq!(
            [range.background.width, range.background.height],
            [256, 256]
        );
        assert_eq!([range.compass.width, range.compass.height], [21, 42]);
        assert_eq!([range.frame.width, range.frame.height], [332, 332]);
        assert_eq!(range.frame, fortresses.frame);
        assert!(range.frame.rgba8[..332 * 4]
            .chunks_exact(4)
            .any(|pixel| pixel[3] != 0));
        assert_eq!(range.frame.rgba8[(166 * 332 + 166) * 4 + 3], 0);
        assert_ne!(range.background.rgba8, fortresses.background.rgba8);
        assert_eq!(range.compass, fortresses.compass);
        assert!(range
            .compass
            .rgba8
            .chunks_exact(4)
            .any(|pixel| pixel[3] != 0));
    }
}