aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/mission_pager.rs
blob: ba3e7596392fe1bfd2c51f089f2ff920c793119a (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
//! Current-message panel drawn in the original cockpit coordinate space.

use crate::{
    game_font::{load_game_font, BitmapFont},
    ui_sprite::{load_ui_sprites, source_over},
    RgbaImage,
};
use fparkan_vfs::Vfs;

const PANEL: [u32; 3] = [230, 0, 182];
const WRAP_WIDTH: u32 = 172;
const FONT_SCALE: f64 = 1.25;
const MAX_BODY_LINES: usize = 6;

/// Original frame parts and the gameplay bitmap font.
pub struct MissionPager {
    frame: UiFrame,
    font: BitmapFont,
}

pub(crate) struct UiFrame([RgbaImage; 6]);

impl UiFrame {
    pub(crate) fn load(vfs: &dyn Vfs) -> Result<Self, String> {
        load_ui_sprites(
            vfs,
            "ui/compaund.cfg",
            [
                "ccres_frame_corner_1",
                "ccres_frame_corner_2",
                "ccres_frame_corner_3",
                "ccres_frame_corner_4",
                "ccres_frame_edge_h",
                "ccres_frame_edge_v",
            ],
        )
        .map(Self)
    }
}

impl MissionPager {
    /// Loads the frame and 800×600 font from the installed game.
    pub fn load(vfs: &dyn Vfs) -> Result<Self, String> {
        Ok(Self {
            frame: UiFrame::load(vfs)?,
            font: load_game_font(vfs)?,
        })
    }

    /// Produces the panel texture and its logical left, top, width and height.
    pub fn paint(
        &self,
        sender: &str,
        body: &str,
        overflow_hint: &str,
    ) -> Result<(RgbaImage, [f32; 4]), String> {
        let line_width = (f64::from(WRAP_WIDTH) * FONT_SCALE * 0.98).round_ties_even() as u16;
        let mut lines = self.font.wrap_pager_lines(body, line_width)?;
        let overflow = lines.len() > MAX_BODY_LINES;
        if overflow {
            lines.truncate(MAX_BODY_LINES);
            let last = lines.last_mut().expect("pager retains six lines");
            last.truncate(last.trim_end().len());
            let limit = f64::from(WRAP_WIDTH) * FONT_SCALE * 0.95;
            let mut end = last.len();
            last.push_str("...");
            while f64::from(self.font.line_metrics(last)?[0]) > limit {
                let Some((index, _)) = last[..end].char_indices().next_back() else {
                    break;
                };
                last.replace_range(index..end, "");
                end = index;
            }
        }
        let [_, glyph_height] = self.font.line_metrics("")?;
        // The glyph raster includes the last row beyond the TFNT vertical extent.
        let advance = (f64::from(glyph_height + 1) / FONT_SCALE).round_ties_even() as u32;
        let [x, y, width] = PANEL;
        let footer = overflow && !overflow_hint.is_empty();
        let [sender_y, first_line_y, height] = panel_rows(advance, lines.len() as u32, footer);
        let pixels = [scale(width), scale(height)];
        let mut panel = RgbaImage {
            width: pixels[0],
            height: pixels[1],
            rgba8: vec![0; (pixels[0] * pixels[1] * 4) as usize],
        };
        self.frame
            .paint(&mut panel, [0, 0, width, height], [0, 128, 0, 128]);
        self.paint_text(&mut panel, sender, sender_y, 255)?;
        for (index, line) in lines.iter().enumerate() {
            self.paint_text(&mut panel, line, first_line_y + index as u32 * advance, 220)?;
        }
        if footer {
            let y = first_line_y + lines.len() as u32 * advance + advance / 2;
            self.paint_text(&mut panel, overflow_hint, y, 255)?;
        }
        Ok((panel, [x as f32, y as f32, width as f32, height as f32]))
    }

    fn paint_text(
        &self,
        panel: &mut RgbaImage,
        text: &str,
        y: u32,
        tint: u8,
    ) -> Result<(), String> {
        let [w, h] = self.font.line_metrics(text)?;
        if w == 0 {
            return Ok(());
        }
        let sprite = self.font.centered_line(text, w, h)?;
        let [x, y] = [scale(8), scale(y)];
        copy_sprite(
            panel,
            &sprite,
            [x, y, x + sprite.width, y + sprite.height],
            [false, false],
            [tint; 3],
        );
        Ok(())
    }
}

impl UiFrame {
    pub(crate) fn paint(
        &self,
        panel: &mut RgbaImage,
        [x, y, right, bottom]: [u32; 4],
        fill: [u8; 4],
    ) {
        let [tl, tr, br, bl, horizontal, vertical] = &self.0;
        let width = right - x;
        let height = bottom - y;
        let middle = [8, 8, width - 8, height - 8];
        for (sprite, rect, flip) in [
            (tl, [0, 0, 8, 8], [false, false]),
            (tr, [width - 8, 0, width, 8], [false, false]),
            (br, [width - 8, height - 8, width, height], [false, false]),
            (bl, [0, height - 8, 8, height], [false, false]),
            (
                horizontal,
                [middle[0], 0, middle[2], horizontal.height],
                [false, false],
            ),
            (
                horizontal,
                [middle[0], height - horizontal.height, middle[2], height],
                [false, true],
            ),
            (
                vertical,
                [0, middle[1], vertical.width, middle[3]],
                [true, false],
            ),
            (
                vertical,
                [width - vertical.width, middle[1], width, middle[3]],
                [false, false],
            ),
        ] {
            let [l, t, r, b] = rect;
            copy_sprite(
                panel,
                sprite,
                [x + l, y + t, x + r, y + b].map(scale),
                flip,
                [255; 3],
            );
        }
        let inset = horizontal.height;
        let [left, top, right, bottom] =
            [x + inset, y + inset, right - inset, bottom - inset].map(scale);
        for y in top..bottom {
            for x in left..right {
                let dest = offset(panel.width, x, y);
                source_over(&mut panel.rgba8[dest..dest + 4], &fill);
            }
        }
    }
}

fn panel_rows(advance: u32, lines: u32, footer: bool) -> [u32; 3] {
    let labels = 1 + u32::from(footer);
    [
        9,
        9 + 3 * advance / 2,
        16 + labels * advance / 2 + (lines + labels) * advance,
    ]
}

pub(crate) fn scale(coordinate: u32) -> u32 {
    (f64::from(coordinate) * FONT_SCALE).round_ties_even() as u32
}

pub(crate) fn copy_sprite(
    panel: &mut RgbaImage,
    sprite: &RgbaImage,
    [left, top, right, bottom]: [u32; 4],
    [flip_x, flip_y]: [bool; 2],
    tint: [u8; 3],
) {
    for y in top..bottom.min(panel.height) {
        let mut v = (y - top) * sprite.height / (bottom - top);
        if flip_y {
            v = sprite.height - 1 - v;
        }
        for x in left..right.min(panel.width) {
            let mut u = (x - left) * sprite.width / (right - left);
            if flip_x {
                u = sprite.width - 1 - u;
            }
            let src = offset(sprite.width, u, v);
            let dest = offset(panel.width, x, y);
            let mut texel = [0; 4];
            texel.copy_from_slice(&sprite.rgba8[src..src + 4]);
            for (component, weight) in texel[..3].iter_mut().zip(tint) {
                *component = (u16::from(*component) * u16::from(weight) / 255) as u8;
            }
            source_over(&mut panel.rgba8[dest..dest + 4], &texel);
        }
    }
}

fn offset(width: u32, x: u32, y: u32) -> usize {
    ((y * width + x) * 4) as usize
}

#[cfg(test)]
mod tests {
    #[test]
    fn cockpit_panel_grows_by_one_native_line_per_wrapped_row() {
        assert_eq!(super::PANEL, [230, 0, 182]);
        assert_eq!(super::panel_rows(10, 2, false), [9, 24, 51]);
        assert_eq!(super::panel_rows(10, 2, true), [9, 24, 66]);
    }
}