aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/mission_loading.rs
blob: 4054e9c908f3daf8086bd78706972f5523ade563 (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Lifecycle of the single window used for loading and playing a mission.

use super::{
    launch_menu::{LaunchMenu, MenuEvent},
    mission_startup::{self, PreparedMission},
    Args, Engine, LegacyCameraCapture, StaticVulkanApp,
};
use fparkan_assets::game_settings::{DisplaySettings, GameSettings};
use fparkan_platform_winit::{new_game_event_loop, WinitWindowPlan};
use fparkan_vfs::DirectoryVfs;
use std::{
    panic::{catch_unwind, AssertUnwindSafe},
    path::Path,
    sync::mpsc,
    thread,
};
use winit::{
    application::ApplicationHandler,
    dpi::PhysicalSize,
    event::{DeviceEvent, DeviceId, WindowEvent},
    event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy},
    monitor::MonitorHandle,
    window::{Fullscreen, Window, WindowId},
};

#[cfg(windows)]
use {
    super::startup_intro::StartupIntro,
    fparkan_assets::mission_loader::MissionLoader,
    fparkan_platform_winit::{startup_window, text::StringResources},
    std::time::{Duration, Instant},
    winit::event::{ElementState, MouseButton},
};

#[derive(Clone, Copy)]
pub(super) enum Stage {
    World,
    Atmosphere,
    Objects,
    Camera,
    Ready,
}

enum LoadEvent {
    Stage(Stage),
    Prepared(Result<Box<PreparedMission>, String>),
}

pub(super) fn fullscreen_mode(
    display: DisplaySettings,
    monitor: Option<MonitorHandle>,
) -> Result<Option<Fullscreen>, String> {
    if display.windowed || !cfg!(windows) {
        return Ok(None);
    }
    let mode = monitor.and_then(|monitor| {
        monitor.video_modes().min_by_key(|mode| {
            let size = mode.size();
            display.mode_distance([size.width, size.height], mode.bit_depth().into())
        })
    });
    mode.map(|mode| Some(Fullscreen::Exclusive(mode)))
        .ok_or_else(|| "Iron_3D.ini requests fullscreen with no video modes".into())
}

pub(super) fn run(
    args: Args,
    engine: Engine,
    camera: Option<LegacyCameraCapture>,
    menu: Option<LaunchMenu>,
) -> Result<String, String> {
    let plan = WinitWindowPlan::smoke()
        .validate()
        .map_err(|error| error.to_string())?;
    let capture = camera
        .as_ref()
        .map(LegacyCameraCapture::captured_viewport)
        .transpose()?;
    let display = if capture.is_none() && !args.viewer {
        GameSettings::load(&DirectoryVfs::new(&args.root))
            .map_err(|error| format!("read Iron_3D.ini: {error}"))?
            .display()
    } else {
        None
    };
    let extent = capture.map_or_else(
        || display.map_or([plan.width, plan.height], |display| display.extent),
        |viewport| viewport.extent,
    );
    let event_loop = new_game_event_loop().map_err(|error| format!("winit event loop: {error}"))?;
    event_loop.set_control_flow(ControlFlow::Wait);
    let mut startup = WindowedMission {
        #[cfg(windows)]
        intro: menu.as_ref().and_then(|_| StartupIntro::open(&args.root)),
        args,
        extent,
        exclusive_display: display.filter(|display| cfg!(windows) && !display.windowed),
        resizable: capture.is_none(),
        menu,
        loading: MissionLoading::default(),
        load_request: Some(Box::new(LoadRequest {
            engine,
            camera,
            proxy: event_loop.create_proxy(),
        })),
        receive: None,
        window: None,
        prepared: None,
        game: None,
        error: None,
    };
    if startup.menu.is_none() {
        startup.start_loading()?;
    }
    event_loop
        .run_app(&mut startup)
        .map_err(|error| format!("winit event loop: {error}"))?;
    if let Some(error) = startup.error {
        return Err(error);
    }
    startup.game.map_or_else(
        || {
            let report = if startup.menu.is_some() {
                "mission menu closed"
            } else {
                "mission loading cancelled"
            };
            Ok(report.into())
        },
        |mut game| game.finish(),
    )
}

struct LoadRequest {
    engine: Engine,
    camera: Option<LegacyCameraCapture>,
    proxy: EventLoopProxy<()>,
}

struct WindowedMission {
    args: Args,
    extent: [u32; 2],
    exclusive_display: Option<DisplaySettings>,
    resizable: bool,
    menu: Option<LaunchMenu>,
    // The DirectShow child and its graph must release before the window.
    #[cfg(windows)]
    intro: Option<StartupIntro>,
    loading: MissionLoading,
    load_request: Option<Box<LoadRequest>>,
    receive: Option<mpsc::Receiver<LoadEvent>>,
    window: Option<Window>,
    prepared: Option<Box<PreparedMission>>,
    game: Option<Box<StaticVulkanApp>>,
    error: Option<String>,
}

impl WindowedMission {
    fn start_loading(&mut self) -> Result<(), String> {
        let LoadRequest {
            engine,
            camera,
            proxy,
        } = *self.load_request.take().expect("window loads one mission");
        if let Some(window) = &self.window {
            let size = window.inner_size();
            if size.width > 0 && size.height > 0 {
                self.extent = [size.width, size.height];
            }
        }
        self.loading = MissionLoading::open(&self.args.root, self.extent);
        let worker_args = self.args.clone();
        let (send, receive) = mpsc::channel();
        thread::Builder::new()
            .name("mission-loader".into())
            .spawn(move || {
                let publish = |message| {
                    if send.send(message).is_ok() {
                        let _ = proxy.send_event(());
                    }
                };
                let prepared = catch_unwind(AssertUnwindSafe(|| {
                    mission_startup::prepare(&worker_args, engine, camera, |stage| {
                        publish(LoadEvent::Stage(stage))
                    })
                }))
                .map_err(|_| "mission preparation panicked".to_string())
                .and_then(|result| result.map(Box::new));
                publish(LoadEvent::Prepared(prepared));
            })
            .map_err(|error| format!("start mission loader: {error}"))?;
        self.receive = Some(receive);
        Ok(())
    }

    fn attach_game(&mut self, event_loop: &ActiveEventLoop) -> Result<(), String> {
        let Some(window) = &self.window else {
            return Ok(());
        };
        let size = window.inner_size();
        if size.width == 0 || size.height == 0 || window.is_minimized() == Some(true) {
            return Ok(());
        }
        let Some(prepared) = self.prepared.take() else {
            return Ok(());
        };
        let mut game = prepared.into_app(&self.args)?;
        self.loading.stage(Stage::Camera);
        self.loading.paint(window);
        let window = self.window.take().expect("loading owns the window");
        game.initialize_window(event_loop, window);
        if let Some(window) = &game.window {
            self.loading.stage(Stage::Ready);
            self.loading.paint(window);
        }
        self.loading = MissionLoading::default();
        self.game = Some(game);
        Ok(())
    }
}

impl ApplicationHandler for WindowedMission {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_some() || self.game.is_some() {
            return;
        }
        let [width, height] = self.extent;
        let fullscreen = match self.exclusive_display.map_or(Ok(None), |display| {
            fullscreen_mode(display, event_loop.primary_monitor())
        }) {
            Ok(fullscreen) => fullscreen,
            Err(error) => {
                self.error = Some(error);
                event_loop.exit();
                return;
            }
        };
        let attributes = Window::default_attributes()
            .with_title("FParkan")
            .with_inner_size(PhysicalSize::new(width, height))
            .with_fullscreen(fullscreen)
            // Preserve the recorded crop when playing from a captured camera.
            .with_resizable(self.resizable);
        match event_loop.create_window(attributes) {
            Ok(window) => {
                window.request_redraw();
                self.window = Some(window);
            }
            Err(error) => {
                self.error = Some(format!("winit window: {error}"));
                event_loop.exit();
            }
        }
    }

    fn user_event(&mut self, event_loop: &ActiveEventLoop, (): ()) {
        let Some(receive) = &self.receive else {
            return;
        };
        while let Ok(event) = receive.try_recv() {
            match event {
                LoadEvent::Stage(stage) => self.loading.stage(stage),
                LoadEvent::Prepared(Ok(prepared)) => self.prepared = Some(prepared),
                LoadEvent::Prepared(Err(error)) => {
                    self.error = Some(error);
                    event_loop.exit();
                    return;
                }
            }
        }
        if let Some(window) = &self.window {
            window.request_redraw();
        }
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
        if let Some(game) = &mut self.game {
            game.window_event(event_loop, id, event);
            return;
        }
        let Some(window) = self.window.as_ref().filter(|window| window.id() == id) else {
            return;
        };
        if matches!(event, WindowEvent::CloseRequested) {
            event_loop.exit();
            return;
        }
        #[cfg(windows)]
        if let Some(intro) = &self.intro {
            match event {
                WindowEvent::KeyboardInput { event, .. }
                    if event.state == ElementState::Pressed && !event.repeat =>
                {
                    self.intro = None;
                    window.request_redraw();
                }
                WindowEvent::MouseInput {
                    state: ElementState::Pressed,
                    button: MouseButton::Left,
                    ..
                } => {
                    self.intro = None;
                    window.request_redraw();
                }
                WindowEvent::Resized(_) => intro.resize(window),
                _ => {}
            }
            return;
        }
        if let Some(menu) = &mut self.menu {
            if matches!(event, WindowEvent::RedrawRequested) {
                if let Err(error) = menu.paint(window) {
                    self.error = Some(error);
                    event_loop.exit();
                }
                return;
            }
            if matches!(
                event,
                WindowEvent::Resized(_) | WindowEvent::Occluded(false)
            ) {
                window.request_redraw();
            }
            match menu.input(&event, window) {
                MenuEvent::None => {}
                MenuEvent::Redraw => window.request_redraw(),
                MenuEvent::Exit => event_loop.exit(),
                MenuEvent::Launch(mission) => {
                    self.args.mission = mission;
                    self.menu = None;
                    window.request_redraw();
                    if let Err(error) = self.start_loading() {
                        self.error = Some(error);
                        event_loop.exit();
                    }
                }
            }
            return;
        }
        match event {
            WindowEvent::Resized(_) | WindowEvent::Occluded(false) => window.request_redraw(),
            WindowEvent::RedrawRequested => {
                self.loading.paint(window);
                if let Err(error) = self.attach_game(event_loop) {
                    self.error = Some(error);
                    event_loop.exit();
                }
            }
            _ => {}
        }
    }

    fn device_event(&mut self, event_loop: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) {
        if let Some(game) = &mut self.game {
            game.device_event(event_loop, id, event);
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        if event_loop.exiting() {
            return;
        }
        if let Some(game) = &mut self.game {
            game.about_to_wait(event_loop);
            return;
        }
        #[cfg(windows)]
        if let Some((intro, window)) = self.intro.as_mut().zip(self.window.as_ref()) {
            if intro.update(window) {
                event_loop.set_control_flow(ControlFlow::WaitUntil(
                    Instant::now() + Duration::from_millis(50),
                ));
            } else {
                self.intro = None;
                event_loop.set_control_flow(ControlFlow::Wait);
                window.request_redraw();
            }
        } else if self.menu.is_some() {
            event_loop.set_control_flow(ControlFlow::Wait);
        }
    }
}

#[derive(Default)]
struct MissionLoading {
    #[cfg(windows)]
    presentation: Option<Box<Presentation>>,
}

#[cfg(windows)]
struct Presentation {
    extent: [u32; 2],
    frame: Vec<u32>,
    screen: MissionLoader,
    strings: StringResources,
}

impl MissionLoading {
    fn open(_root: &Path, _extent: [u32; 2]) -> Self {
        #[cfg(windows)]
        {
            let presentation = Presentation::open(_root, _extent)
                .map_err(|error| eprintln!("mission loader: {error}"))
                .ok()
                .map(Box::new);
            Self { presentation }
        }
        #[cfg(not(windows))]
        Self::default()
    }

    fn stage(&mut self, _stage: Stage) {
        #[cfg(windows)]
        if let Some(presentation) = &mut self.presentation {
            if let Err(error) = presentation.update(_stage) {
                eprintln!("mission loader: {error}");
            }
        }
    }

    fn paint(&self, _window: &Window) {
        #[cfg(windows)]
        if let Some(presentation) = &self.presentation {
            if let Err(error) =
                startup_window::paint(_window, presentation.extent, &presentation.frame)
            {
                eprintln!("mission loader: {error}");
            }
        }
    }
}

#[cfg(windows)]
impl Presentation {
    fn open(root: &Path, extent: [u32; 2]) -> Result<Self, String> {
        let strings = StringResources::open(&root.join("iron3d.dll"))?;
        let mut screen = MissionLoader::new(
            &DirectoryVfs::new(root),
            extent,
            &original_text(&strings, 0x13e3)?,
        )?;
        screen.append(&original_text(&strings, 0x1194)?)?;
        let frame = screen.frame(10);
        Ok(Self {
            extent,
            frame,
            screen,
            strings,
        })
    }

    fn update(&mut self, stage: Stage) -> Result<(), String> {
        // The Rust loader prepares several original stages in one operation.
        // Publish their messages together when that operation has completed.
        let (ids, percent): (&[u32], u8) = match stage {
            Stage::World => (&[0x1198, 0x1199, 0x119a], 45),
            Stage::Atmosphere => (&[0x119b], 48),
            Stage::Objects => (&[0x119c, 0x119d, 0x119e, 0x119f, 0x11a0, 0x11a2], 90),
            Stage::Camera => (&[0x11a3], 95),
            Stage::Ready => (&[0x11a4], 100),
        };
        for &id in ids {
            self.screen.append(&original_text(&self.strings, id)?)?;
        }
        self.frame = self.screen.frame(percent);
        Ok(())
    }
}

#[cfg(windows)]
fn original_text(strings: &StringResources, id: u32) -> Result<String, String> {
    strings
        .get(id)
        .ok_or_else(|| format!("missing iron3d.dll string {id:#06x}"))
}