aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/ui_sprite.rs
blob: 78843a25d2291e718f4d42e28225cccc061b024f (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
//! 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?];
        let image = atlas_region(image, [x, y, width, height])
            .ok_or_else(|| format!("UI sprite {name} is outside atlas page {page}"))?;
        let angle = if region.contains_key("ROTATE") {
            number(&region, "ROTATE")?
        } else {
            0
        };
        sprites.push(rotate(image, angle)?);
    }
    Ok(sprites
        .try_into()
        .expect("one rectangle per UI sprite name"))
}

pub(crate) fn atlas_region(
    image: &RgbaImage,
    [x, y, width, height]: [u32; 4],
) -> Option<RgbaImage> {
    let right = x.checked_add(width)?;
    let bottom = y.checked_add(height)?;
    if width == 0 || height == 0 || right > image.width || bottom > image.height {
        return None;
    }
    let rgba8 = (y..bottom)
        .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();
    Some(RgbaImage {
        width,
        height,
        rgba8,
    })
}

fn rotate(image: RgbaImage, angle: u32) -> Result<RgbaImage, String> {
    let (w, h) = (image.width, image.height);
    let (width, height) = match angle {
        0 => return Ok(image),
        90 | 270 => (h, w),
        180 => (w, h),
        _ => return Err(format!("invalid UI sprite rotation {angle}")),
    };
    let mut rgba8 = Vec::with_capacity(image.rgba8.len());
    for y in 0..height {
        for x in 0..width {
            let (u, v) = match angle {
                90 => (y, h - 1 - x),
                180 => (w - 1 - x, h - 1 - y),
                _ => (w - 1 - y, x),
            };
            let start = ((v * w + u) * 4) as usize;
            rgba8.extend_from_slice(&image.rgba8[start..start + 4]);
        }
    }
    Ok(RgbaImage {
        width,
        height,
        rgba8,
    })
}

/// Composes a source UI pixel with its alpha mask over the destination pixel.
pub fn source_over(pixel: &mut [u8], source: &[u8]) {
    let alpha = u32::from(source[3]);
    if alpha == 0 {
        return;
    }
    let under = (u32::from(pixel[3]) * (255 - alpha) + 127) / 255;
    let combined = alpha + under;
    for index in 0..3 {
        pixel[index] =
            ((u32::from(source[index]) * alpha + u32::from(pixel[index]) * under + combined / 2)
                / combined) as u8;
    }
    pixel[3] = combined as u8;
}

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())
}