aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/ui_sprite.rs
blob: fe4c77e8a8b6c083f8f472321223c8631f1dd4e4 (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
//! Original UI atlas rectangles selected through the game resource table.

use crate::ui_configuration::{field, number, object, read};
use fparkan_nres::{decode, EntryId, NresDocument, ReadProfile};
use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage};
use fparkan_vfs::Vfs;
use std::{collections::HashMap, sync::Arc};

/// Load a named page from the original game UI texture catalog.
pub fn load_ui_page(vfs: &dyn Vfs, name: &str) -> Result<RgbaImage, String> {
    let game = read(vfs, "ui/game_resources.cfg")?;
    let game = String::from_utf8_lossy(&game);
    let textures = object(&game, "textures").ok_or("missing UI texture catalog")?;
    let page = number(&textures, &name.to_ascii_uppercase())?;
    let archive = open_atlas(vfs, field(&textures, "LIBRARY")?)?;
    decode_page(&archive, page)
}

pub fn load_ui_sprites<const N: usize>(
    vfs: &dyn Vfs,
    config: &str,
    names: [&str; N],
) -> Result<[RgbaImage; N], String> {
    let definitions = read(vfs, config)?;
    let definitions = String::from_utf8_lossy(&definitions);
    let game = read(vfs, "ui/game_resources.cfg")?;
    let game = String::from_utf8_lossy(&game);
    let textures = object(&game, "textures").ok_or("missing UI texture catalog")?;
    let archive = open_atlas(vfs, field(&textures, "LIBRARY")?)?;
    let mut pages = HashMap::new();
    let mut sprites = Vec::with_capacity(N);
    for name in names {
        let region =
            object(&definitions, name).ok_or_else(|| format!("missing UI sprite {name}"))?;
        let page = number(&textures, &field(&region, "TEXTURE")?.to_ascii_uppercase())?;
        let image = match pages.entry(page) {
            std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
            std::collections::hash_map::Entry::Vacant(entry) => {
                entry.insert(decode_page(&archive, page)?)
            }
        };
        let [x, y, width, height] =
            ["OFFSET_X", "OFFSET_Y", "WIDTH", "HEIGHT"].map(|key| number(&region, key));
        let [x, y, width, height] = [x?, y?, width?, height?];
        if width == 0
            || height == 0
            || x.checked_add(width).is_none_or(|right| right > image.width)
            || y.checked_add(height)
                .is_none_or(|bottom| bottom > image.height)
        {
            return Err(format!("UI sprite {name} is outside atlas page {page}"));
        }
        let rgba8 = (y..y + height)
            .flat_map(|row| {
                let start = (row as usize * image.width as usize + x as usize) * 4;
                image.rgba8[start..start + width as usize * 4]
                    .iter()
                    .copied()
            })
            .collect();
        sprites.push(RgbaImage {
            width,
            height,
            rgba8,
        });
    }
    Ok(sprites
        .try_into()
        .expect("one rectangle per UI sprite name"))
}

fn open_atlas(vfs: &dyn Vfs, path: &str) -> Result<NresDocument, String> {
    decode(read(vfs, path)?, ReadProfile::Strict).map_err(|error| error.to_string())
}

fn decode_page(archive: &NresDocument, page: u32) -> Result<RgbaImage, String> {
    let payload = archive
        .payload(EntryId(page))
        .map_err(|error| error.to_string())?;
    let texture = decode_texm(Arc::from(payload)).map_err(|error| error.to_string())?;
    decode_mip_rgba8(&texture, 0).map_err(|error| error.to_string())
}