aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/mission_hints.rs
blob: bd643aa3238ce04f5d809b29ccb9e04484fcf2b6 (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
use super::{
    append_environment_gradient_material, append_environment_range, audio, environment_vertex,
    quad_indices, screen_tl_quad_vertices_pixels, world_pipeline_state, DirectoryVfs,
    EnvironmentGpuRange, LegacyBlendMode, LegacyDepthMode, StaticPreviewScene, Vfs,
    VulkanSmokeRenderer, VulkanStaticMesh, VulkanStaticTexture,
};
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_platform_winit::text::{caption, StringResources};
use fparkan_runtime::MissionScriptOutcome;
use fparkan_vfs::VfsError;
use std::{collections::VecDeque, path::Path, sync::Arc};

const WIDTH: u16 = 640;
const HEIGHT: u16 = 384;
const UV: [[f32; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];

pub(super) struct MissionHints {
    messages: Option<MessageResources>,
    range: EnvironmentGpuRange,
    waiting: VecDeque<(u32, String)>,
    active: Option<(u32, u32, u32)>,
    outcome: Option<(MissionScriptOutcome, u32)>,
}

struct MessageResources {
    config: Arc<[u8]>,
    catalog: Arc<[u8]>,
    strings: StringResources,
}

impl MissionHints {
    pub(super) fn range_index(&self) -> usize {
        self.range.range_index
    }

    pub(super) fn load(
        root: &Path,
        mission: &str,
        preview: &mut StaticPreviewScene,
    ) -> Result<Self, String> {
        let messages = MessageResources::load(root, mission).unwrap_or_else(|error| {
            eprintln!("sim_coverage mission_text_unavailable=1 reason={error}");
            None
        });
        eprintln!("sim_coverage mission_outcome_display_approx=1");
        let material = append_environment_gradient_material(&mut preview.materials)?;
        preview.materials[material].screen_tl = true;
        preview.materials[material].sky_far_depth = false;
        preview.materials[material].texture =
            texture(vec![0; usize::from(WIDTH) * usize::from(HEIGHT) * 4]);
        let range = append_environment_range(
            &mut preview.mesh,
            material,
            vec![environment_vertex([0.0; 3], [1.0; 3], [0.0; 2]); 4],
            quad_indices(1)?,
            world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled),
        )?;
        // Keep the degenerate reservation until the renderer receives live caption vertices.
        Ok(Self {
            messages,
            range,
            waiting: VecDeque::new(),
            active: None,
            outcome: None,
        })
    }

    pub(super) fn enqueue(&mut self, index: u32) -> Result<(), String> {
        let messages = self
            .messages
            .as_ref()
            .ok_or("missing mission message resources")?;
        let symbol = audio::message_symbol(&messages.config, index, "TEXT_RESOURCE")?
            .ok_or_else(|| format!("missing TEXT_RESOURCE for message {index}"))?;
        let symbol = symbol.to_ascii_uppercase();
        let text = String::from_utf8_lossy(&messages.catalog);
        let id = audio::config_objects(&text)
            .find_map(|object| object.get(&symbol).and_then(|value| value.parse().ok()))
            .ok_or_else(|| format!("missing string ID for {symbol}"))?;
        let body = messages
            .strings
            .get(id)
            .filter(|text| !text.trim().is_empty())
            .ok_or_else(|| format!("missing string {id} for {symbol}"))?;
        self.waiting.push_back((index, body));
        Ok(())
    }

    pub(super) fn draw(
        &mut self,
        renderer: &mut VulkanSmokeRenderer,
        mesh: &mut VulkanStaticMesh,
        clock: u32,
        viewport: [f32; 2],
        outcome: MissionScriptOutcome,
    ) -> Result<(), String> {
        if let Some(body) = outcome_text(outcome) {
            let occupied =
                if let Some((_, height)) = self.outcome.filter(|&(last, _)| last == outcome) {
                    height
                } else {
                    let (height, rgba) = caption(body, WIDTH, HEIGHT)?;
                    renderer
                        .update_material_texture(self.range.material_index, 0, &texture(rgba))
                        .map_err(|error| error.to_string())?;
                    self.outcome = Some((outcome, height));
                    self.active = None;
                    self.waiting.clear();
                    eprintln!("mission_outcome_text outcome={outcome:?} queue_time_ms={clock}");
                    height
                };
            self.place_caption(mesh, viewport, occupied);
            return renderer
                .set_draw_range_index_count(self.range.range_index, 6)
                .map_err(|error| error.to_string());
        }
        self.outcome = None;
        if self
            .active
            .is_some_and(|(start, duration, _)| clock.wrapping_sub(start) >= duration)
        {
            self.active = None;
        }
        if self.active.is_none() {
            if let Some((index, body)) = self.waiting.pop_front() {
                let (height, rgba) = match caption(&body, WIDTH, HEIGHT) {
                    Ok(caption) => caption,
                    Err(error) => {
                        eprintln!(
                            "sim_coverage mission_text_unavailable=1 index={index} reason={error}"
                        );
                        return renderer
                            .set_draw_range_index_count(self.range.range_index, 0)
                            .map_err(|error| error.to_string());
                    }
                };
                renderer
                    .update_material_texture(self.range.material_index, 0, &texture(rgba))
                    .map_err(|error| error.to_string())?;
                // shortcut: reading time from character count until pager timing is recovered.
                let duration = (body.chars().count() as u32)
                    .saturating_mul(45)
                    .clamp(3500, 18_000);
                self.active = Some((clock, duration, height));
                eprintln!(
                    "mission_text index={index} queue_time_ms={clock} duration_ms={duration}"
                );
            }
        }
        if let Some((_, _, occupied)) = self.active {
            self.place_caption(mesh, viewport, occupied);
        }
        renderer
            .set_draw_range_index_count(
                self.range.range_index,
                if self.active.is_some() { 6 } else { 0 },
            )
            .map_err(|error| error.to_string())
    }

    fn place_caption(&self, mesh: &mut VulkanStaticMesh, viewport: [f32; 2], occupied: u32) {
        let scale = ((viewport[0] - 32.0) / f32::from(WIDTH)).clamp(0.01, 1.0);
        let [width, height] = [f32::from(WIDTH) * scale, occupied as f32 * scale];
        let mut uv = UV;
        uv[1][1] = occupied as f32 / f32::from(HEIGHT);
        uv[2][1] = uv[1][1];
        let vertices = screen_tl_quad_vertices_pixels(
            [viewport[0] * 0.5, 16.0 + height * 0.5],
            width * 0.5,
            height * 0.5,
            viewport,
            [1.0; 3],
            1.0,
            uv,
        );
        mesh.vertices[self.range.vertex_start..self.range.vertex_start + vertices.len()]
            .copy_from_slice(&vertices);
    }
}

impl MessageResources {
    fn load(root: &Path, mission: &str) -> Result<Option<Self>, String> {
        let vfs = DirectoryVfs::new(root);
        let path = mission.rsplit_once('/').map_or_else(
            || "messages.cfg".into(),
            |(dir, _)| format!("{dir}/messages.cfg"),
        );
        let config = match vfs.read(
            &normalize_relative(path.as_bytes(), PathPolicy::StrictLegacy)
                .map_err(|error| error.to_string())?,
        ) {
            Ok(bytes) => bytes,
            Err(VfsError::NotFound(_)) => return Ok(None),
            Err(error) => return Err(error.to_string()),
        };
        let catalog_path =
            normalize_relative(b"DATA/TextRes.cfg", PathPolicy::StrictLegacy).unwrap();
        let catalog = vfs.read(&catalog_path).map_err(|error| error.to_string())?;
        let text = String::from_utf8_lossy(&catalog);
        let library = audio::config_objects(&text)
            .find_map(|object| object.get("LIBRARY").copied())
            .ok_or_else(|| "missing text resource library".to_owned())?;
        let library = audio::parse_cfg_value(library)?;
        let library = normalize_relative(library.as_bytes(), PathPolicy::StrictLegacy)
            .map_err(|error| error.to_string())?;
        let strings = StringResources::open(&root.join(library.as_str()))?;
        eprintln!("sim_coverage mission_text_display_approx=1");
        Ok(Some(Self {
            config,
            catalog,
            strings,
        }))
    }
}

fn outcome_text(outcome: MissionScriptOutcome) -> Option<&'static str> {
    // shortcut: use the caption panel until the native result dialog and its controls are reproduced.
    match outcome {
        MissionScriptOutcome::Active => None,
        MissionScriptOutcome::Completed => Some("Миссия выполнена"),
        MissionScriptOutcome::Failed => Some("Миссия не выполнена"),
    }
}

fn texture(rgba8: Vec<u8>) -> VulkanStaticTexture {
    VulkanStaticTexture {
        width: u32::from(WIDTH),
        height: u32::from(HEIGHT),
        rgba8,
        mip_levels: Vec::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn outcome_captions_only_show_for_terminal_states() {
        assert!(outcome_text(MissionScriptOutcome::Active).is_none());
        let victory = outcome_text(MissionScriptOutcome::Completed).unwrap();
        let defeat = outcome_text(MissionScriptOutcome::Failed).unwrap();
        assert_ne!(victory, defeat);
        for text in [victory, defeat] {
            let (height, rgba) = caption(text, WIDTH, HEIGHT).unwrap();
            assert!(height > 24);
            assert!(rgba.chunks_exact(4).any(|pixel| pixel[0] != 0));
        }
    }
}