aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/launch_menu.rs
blob: 73495c37f3a8231e791805fb277a90a6a9136ec1 (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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Mission selection before loading a world into the game window.

use fparkan_assets::{
    game_font::{load_menu_font, BitmapFont},
    mission_catalog::MissionCatalog,
};
use fparkan_vfs::Vfs;
use std::path::{Path, PathBuf};
use winit::{
    dpi::{PhysicalPosition, PhysicalSize},
    event::{ElementState, MouseButton, WindowEvent},
    keyboard::{Key, NamedKey},
    window::Window,
};

mod graphics;
mod profile;
mod sound;
use graphics::{GraphicsControl, GraphicsSettings};
use sound::{SoundSettings, Volume};

const EXTENT: [u32; 2] = [960, 540];
const LEFT: usize = 56;
const TOP: usize = 132;
const WIDTH: usize = 848;
const ROW_HEIGHT: usize = 42;
const VISIBLE_ROWS: usize = 8;
const GAP: usize = 6;
const BACKGROUND: u32 = 0x141c24;
const VOLUME_LEFT: usize = 480;
const VOLUME_WIDTH: usize = 300;
const GRAPHICS_VALUE_LEFT: usize = 480;
const RESOLUTION_STEP_WIDTH: usize = 180;

pub(super) struct LaunchMenu {
    catalog: MissionCatalog,
    font: BitmapFont,
    root: PathBuf,
    screen: Screen,
    selected: usize,
    pointer: Option<PhysicalPosition<f64>>,
    sound: Option<SoundSettings>,
    graphics: Option<GraphicsSettings>,
}

#[derive(Clone, Copy)]
enum Screen {
    Main,
    Start,
    Campaigns,
    Campaign(usize),
    Single,
    Settings,
    Sound,
    Graphics,
}

struct Row<'a> {
    label: &'a str,
    action: Action<'a>,
}

#[derive(Clone, Copy)]
enum Action<'a> {
    Open(Screen),
    Launch(&'a str),
    Volume(Volume),
    ToggleMusic,
    ApplySound,
    Graphics(GraphicsControl),
    ApplyGraphics,
    Exit,
}

pub(super) enum MenuEvent {
    None,
    Redraw,
    Launch(String),
    Exit,
}

impl LaunchMenu {
    pub(super) fn open(vfs: &dyn Vfs, root: &Path) -> Result<Self, String> {
        if !cfg!(windows) {
            return Err("the mission menu requires a Win32 window; specify --mission".into());
        }
        let catalog = MissionCatalog::load(vfs)?;
        if catalog.campaigns.is_empty() && catalog.single.is_empty() && catalog.demo.is_none() {
            return Err("no missions with a descr caption found in the game directory".into());
        }
        Ok(Self {
            catalog,
            font: load_menu_font(vfs)?,
            root: root.to_path_buf(),
            screen: Screen::Main,
            selected: 0,
            pointer: None,
            sound: None,
            graphics: None,
        })
    }

    fn rows(&self) -> Vec<Row<'_>> {
        let mut rows = Vec::new();
        match self.screen {
            Screen::Main => {
                if let Some(demo) = &self.catalog.demo {
                    rows.push(Row {
                        label: "Демо",
                        action: Action::Launch(&demo.key),
                    });
                }
                if !self.catalog.campaigns.is_empty() || !self.catalog.single.is_empty() {
                    rows.push(Row {
                        label: "Начать игру",
                        action: Action::Open(Screen::Start),
                    });
                }
                rows.push(Row {
                    label: "Настройки",
                    action: Action::Open(Screen::Settings),
                });
                rows.push(Row {
                    label: "Выход",
                    action: Action::Exit,
                });
            }
            Screen::Start => {
                if !self.catalog.campaigns.is_empty() {
                    rows.push(Row {
                        label: "Кампании",
                        action: Action::Open(Screen::Campaigns),
                    });
                }
                if !self.catalog.single.is_empty() {
                    rows.push(Row {
                        label: "Одиночные миссии",
                        action: Action::Open(Screen::Single),
                    });
                }
            }
            Screen::Campaigns => {
                rows.extend(
                    self.catalog
                        .campaigns
                        .iter()
                        .enumerate()
                        .map(|(index, campaign)| Row {
                            label: &campaign.title,
                            action: Action::Open(Screen::Campaign(index)),
                        }),
                );
            }
            Screen::Campaign(index) => {
                rows.extend(
                    self.catalog.campaigns[index]
                        .missions
                        .iter()
                        .map(|mission| Row {
                            label: &mission.title,
                            action: Action::Launch(&mission.key),
                        }),
                );
            }
            Screen::Single => {
                rows.extend(self.catalog.single.iter().map(|mission| Row {
                    label: &mission.title,
                    action: Action::Launch(&mission.key),
                }));
            }
            Screen::Settings => rows.extend([
                Row {
                    label: "Графика",
                    action: Action::Open(Screen::Graphics),
                },
                Row {
                    label: "Звук",
                    action: Action::Open(Screen::Sound),
                },
            ]),
            Screen::Sound => {
                if self.sound.is_some() {
                    rows.extend([
                        Row {
                            label: "Громкость эффектов",
                            action: Action::Volume(Volume::Effects),
                        },
                        Row {
                            label: "Громкость музыки",
                            action: Action::Volume(Volume::Music),
                        },
                        Row {
                            label: "Музыка",
                            action: Action::ToggleMusic,
                        },
                        Row {
                            label: "Применить",
                            action: Action::ApplySound,
                        },
                    ]);
                }
            }
            Screen::Graphics => {
                if self.graphics.is_some() {
                    rows.extend([
                        Row {
                            label: "Разрешение",
                            action: Action::Graphics(GraphicsControl::Resolution),
                        },
                        Row {
                            label: "Режим экрана",
                            action: Action::Graphics(GraphicsControl::WindowMode),
                        },
                        Row {
                            label: "Отражения на воде",
                            action: Action::Graphics(GraphicsControl::Reflections),
                        },
                        Row {
                            label: "Применить",
                            action: Action::ApplyGraphics,
                        },
                    ]);
                }
            }
        }
        if let Some(parent) = self.parent() {
            rows.push(Row {
                label: "Назад",
                action: Action::Open(parent),
            });
        }
        rows
    }

    fn parent(&self) -> Option<Screen> {
        match self.screen {
            Screen::Main => None,
            Screen::Start | Screen::Settings => Some(Screen::Main),
            Screen::Campaigns | Screen::Single => Some(Screen::Start),
            Screen::Campaign(_) => Some(Screen::Campaigns),
            Screen::Sound | Screen::Graphics => Some(Screen::Settings),
        }
    }

    fn enter(&mut self, screen: Screen, window: &Window) -> MenuEvent {
        self.sound = if matches!(screen, Screen::Sound) {
            SoundSettings::open(&self.root)
                .map_err(|error| eprintln!("read Iron_3D.ini: {error}"))
                .ok()
        } else {
            None
        };
        self.graphics = if matches!(screen, Screen::Graphics) {
            GraphicsSettings::open(&self.root, window)
                .map_err(|error| eprintln!("read Iron_3D.ini: {error}"))
                .ok()
        } else {
            None
        };
        self.screen = screen;
        self.selected = 0;
        MenuEvent::Redraw
    }

    fn activate(&mut self, index: usize, window: &Window) -> MenuEvent {
        match self.rows().get(index).map(|row| row.action) {
            Some(Action::Open(screen)) => self.enter(screen, window),
            Some(Action::Launch(key)) => MenuEvent::Launch(key.to_string()),
            Some(Action::ToggleMusic) => {
                if let Some(sound) = &mut self.sound {
                    sound.toggle_music();
                }
                MenuEvent::Redraw
            }
            Some(Action::ApplySound) => {
                if let Some(sound) = &mut self.sound {
                    if let Err(error) = sound.apply(&self.root) {
                        eprintln!("save Iron_3D.ini: {error}");
                        sound.status = "Не удалось сохранить настройки";
                    }
                }
                MenuEvent::Redraw
            }
            Some(Action::Graphics(control)) => self.change_graphics(control, true),
            Some(Action::ApplyGraphics) => {
                if let Some(graphics) = &mut self.graphics {
                    if let Err(error) = graphics.apply(&self.root, window) {
                        eprintln!("apply graphics settings: {error}");
                        graphics.status = "Не удалось применить настройки";
                    }
                }
                MenuEvent::Redraw
            }
            Some(Action::Exit) => MenuEvent::Exit,
            Some(Action::Volume(_)) | None => MenuEvent::None,
        }
    }

    fn change_graphics(&mut self, control: GraphicsControl, forward: bool) -> MenuEvent {
        if let Some(graphics) = &mut self.graphics {
            graphics.change(control, forward);
        }
        MenuEvent::Redraw
    }

    pub(super) fn input(&mut self, event: &WindowEvent, window: &Window) -> MenuEvent {
        let size = window.inner_size();
        match event {
            WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
                match event.logical_key {
                    Key::Named(NamedKey::ArrowUp | NamedKey::ArrowDown) => {
                        let count = self.rows().len();
                        let step = if event.logical_key == Key::Named(NamedKey::ArrowUp) {
                            count - 1
                        } else {
                            1
                        };
                        self.selected = (self.selected + step) % count;
                        MenuEvent::Redraw
                    }
                    Key::Named(NamedKey::Enter) if !event.repeat => {
                        self.activate(self.selected, window)
                    }
                    Key::Named(NamedKey::ArrowLeft | NamedKey::ArrowRight) => {
                        let forward = event.logical_key == Key::Named(NamedKey::ArrowRight);
                        match self.rows().get(self.selected).map(|row| row.action) {
                            Some(Action::Volume(volume)) => {
                                if let Some(sound) = &mut self.sound {
                                    let step = if forward { 1 } else { -1 };
                                    sound.set_volume(
                                        volume,
                                        sound.volume(volume).saturating_add_signed(step),
                                    );
                                }
                                MenuEvent::Redraw
                            }
                            Some(Action::Graphics(control)) => {
                                self.change_graphics(control, forward)
                            }
                            _ => MenuEvent::None,
                        }
                    }
                    Key::Named(NamedKey::Escape) if !event.repeat => match self.parent() {
                        Some(parent) => self.enter(parent, window),
                        None => MenuEvent::Exit,
                    },
                    _ => MenuEvent::None,
                }
            }
            WindowEvent::CursorMoved { position, .. } => {
                self.pointer = Some(*position);
                let x = self.pointer_x(size);
                if let Some((sound, x)) = self.sound.as_mut().zip(x) {
                    if let Some(volume) = sound.drag {
                        sound.set_volume(volume, slider_percent(x));
                        return MenuEvent::Redraw;
                    }
                }
                match self.hit(size) {
                    Some(index) if index != self.selected => {
                        self.selected = index;
                        MenuEvent::Redraw
                    }
                    _ => MenuEvent::None,
                }
            }
            WindowEvent::CursorLeft { .. } | WindowEvent::Resized(_) => {
                self.pointer = None;
                if let Some(sound) = &mut self.sound {
                    sound.drag = None;
                }
                MenuEvent::None
            }
            WindowEvent::MouseInput {
                state: ElementState::Pressed,
                button: MouseButton::Left,
                ..
            } => {
                let Some(index) = self.hit(size) else {
                    return MenuEvent::None;
                };
                if let Some(Action::Volume(volume)) = self.rows().get(index).map(|row| row.action) {
                    let x = self.pointer_x(size).filter(|x| *x >= VOLUME_LEFT as f64);
                    if let Some((sound, x)) = self.sound.as_mut().zip(x) {
                        sound.drag = Some(volume);
                        sound.set_volume(volume, slider_percent(x));
                        return MenuEvent::Redraw;
                    }
                    return MenuEvent::None;
                }
                if let Some(Action::Graphics(GraphicsControl::Resolution)) =
                    self.rows().get(index).map(|row| row.action)
                {
                    let center = (GRAPHICS_VALUE_LEFT + RESOLUTION_STEP_WIDTH / 2) as f64;
                    return self.change_graphics(
                        GraphicsControl::Resolution,
                        self.pointer_x(size).is_some_and(|x| x >= center),
                    );
                }
                self.activate(index, window)
            }
            WindowEvent::MouseInput {
                state: ElementState::Released,
                button: MouseButton::Left,
                ..
            }
            | WindowEvent::Focused(false) => {
                if let Some(sound) = &mut self.sound {
                    sound.drag = None;
                }
                MenuEvent::None
            }
            _ => MenuEvent::None,
        }
    }

    fn pointer_x(&self, size: PhysicalSize<u32>) -> Option<f64> {
        if size.width == 0 {
            return None;
        }
        Some(self.pointer?.x * f64::from(EXTENT[0]) / f64::from(size.width))
    }

    fn hit(&self, size: PhysicalSize<u32>) -> Option<usize> {
        let cursor = self.pointer?;
        if size.width == 0 || size.height == 0 {
            return None;
        }
        let x = cursor.x * f64::from(EXTENT[0]) / f64::from(size.width);
        let y = cursor.y * f64::from(EXTENT[1]) / f64::from(size.height);
        if x < LEFT as f64 || x >= (LEFT + WIDTH) as f64 || y < TOP as f64 {
            return None;
        }
        let row = (y as usize - TOP) / ROW_HEIGHT;
        let first = self.first_row();
        (row < VISIBLE_ROWS
            && (y as usize - TOP) % ROW_HEIGHT < ROW_HEIGHT - GAP
            && first + row < self.rows().len())
        .then_some(first + row)
    }

    fn first_row(&self) -> usize {
        self.selected.saturating_sub(VISIBLE_ROWS - 1)
    }

    pub(super) fn paint(&self, _window: &Window) -> Result<(), String> {
        #[cfg(windows)]
        {
            let pixels = self.frame()?;
            fparkan_platform_winit::startup_window::paint(_window, EXTENT, &pixels)
                .map_err(|error| format!("draw mission menu: {error}"))?;
        }
        Ok(())
    }

    fn frame(&self) -> Result<Vec<u32>, String> {
        let mut frame = vec![BACKGROUND; EXTENT[0] as usize * EXTENT[1] as usize];
        let title = match self.screen {
            Screen::Main => "FParkan",
            Screen::Start => "Начать игру",
            Screen::Campaigns => "Кампании",
            Screen::Campaign(index) => &self.catalog.campaigns[index].title,
            Screen::Single => "Одиночные миссии",
            Screen::Settings => "Настройки",
            Screen::Sound => "Звук",
            Screen::Graphics => "Графика",
        };
        self.text(&mut frame, title, [LEFT, 57], 2)?;
        let rows = self.rows();
        let first = self.first_row();
        for (visible, row) in rows[first..].iter().take(VISIBLE_ROWS).enumerate() {
            let top = TOP + visible * ROW_HEIGHT;
            let selected = first + visible == self.selected;
            let color = if selected { 0x205960 } else { 0x26333d };
            fill(&mut frame, LEFT, top, WIDTH, ROW_HEIGHT - GAP, color);
            if selected {
                fill(&mut frame, LEFT, top, 4, ROW_HEIGHT - GAP, 0x65dacc);
            }
            self.text(&mut frame, row.label, [LEFT + 20, top + 9], 1)?;
            if let Some(sound) = &self.sound {
                match row.action {
                    Action::Volume(volume) => {
                        let value = usize::from(sound.volume(volume));
                        let thumb = VOLUME_LEFT + value * VOLUME_WIDTH / 100;
                        fill(&mut frame, VOLUME_LEFT, top + 16, VOLUME_WIDTH, 4, 0x141c24);
                        fill(&mut frame, thumb - 3, top + 10, 6, 16, 0x65dacc);
                        self.text(
                            &mut frame,
                            &format!("{value}%"),
                            [VOLUME_LEFT + VOLUME_WIDTH + 24, top + 9],
                            1,
                        )?;
                    }
                    Action::ToggleMusic => {
                        let value = if sound.music_enabled() {
                            "Вкл"
                        } else {
                            "Выкл"
                        };
                        self.text(&mut frame, value, [VOLUME_LEFT, top + 9], 1)?;
                    }
                    _ => {}
                }
            }
            if let (Some(graphics), Action::Graphics(control)) = (&self.graphics, row.action) {
                let mut left = GRAPHICS_VALUE_LEFT;
                if matches!(control, GraphicsControl::Resolution) {
                    self.text(&mut frame, "<", [left, top + 9], 1)?;
                    self.text(&mut frame, ">", [left + RESOLUTION_STEP_WIDTH, top + 9], 1)?;
                    left += 32;
                }
                self.text(&mut frame, &graphics.value(control), [left, top + 9], 1)?;
            }
        }
        let status = match self.screen {
            Screen::Sound => self.sound.as_ref().map(|sound| sound.status),
            Screen::Graphics => self.graphics.as_ref().map(|graphics| graphics.status),
            _ => Some(""),
        }
        .unwrap_or("Не удалось прочитать настройки");
        if !status.is_empty() {
            self.text(&mut frame, status, [LEFT + 20, TOP + ROW_HEIGHT * 5 + 9], 1)?;
        }
        Ok(frame)
    }

    fn text(
        &self,
        frame: &mut [u32],
        label: &str,
        at: [usize; 2],
        scale: usize,
    ) -> Result<(), String> {
        let [width, height] = self.font.line_metrics(label)?;
        let source = self.font.centered_line(label, width, height)?;
        for y in 0..source.height as usize * scale {
            if at[1] + y >= EXTENT[1] as usize {
                break;
            }
            for x in 0..(source.width as usize * scale).min(LEFT + WIDTH - at[0]) {
                let src = (y / scale * source.width as usize + x / scale) * 4;
                let index = (at[1] + y) * EXTENT[0] as usize + at[0] + x;
                let alpha = u32::from(source.rgba8[src + 3]);
                if alpha == 0 {
                    continue;
                }
                let background = frame[index];
                let mut pixel = 0;
                for (channel, shift) in [16, 8, 0].into_iter().enumerate() {
                    let foreground = u32::from(source.rgba8[src + channel]);
                    let back = (background >> shift) & 0xff;
                    pixel |= ((foreground * alpha + back * (255 - alpha)) / 255) << shift;
                }
                frame[index] = pixel;
            }
        }
        Ok(())
    }
}

fn slider_percent(x: f64) -> u8 {
    ((x - VOLUME_LEFT as f64) * 100.0 / VOLUME_WIDTH as f64)
        .round()
        .clamp(0.0, 100.0) as u8
}

#[cfg(test)]
#[test]
fn volume_slider_maps_its_track_to_profile_percent() {
    let start = VOLUME_LEFT as f64;
    let width = VOLUME_WIDTH as f64;
    assert_eq!(slider_percent(start - 15.0), 0);
    assert_eq!(slider_percent(start + width * 0.2), 20);
    assert_eq!(slider_percent(start + width), 100);
    assert_eq!(slider_percent(start + width + 15.0), 100);
}

#[cfg(all(test, windows))]
#[test]
#[ignore = "requires licensed corpus"]
fn licensed_campaign_menu_launches_the_same_missions_as_numbered_cli() {
    use fparkan_assets::mission_catalog::list_mission_keys;
    use fparkan_vfs::DirectoryVfs;

    let root =
        PathBuf::from(std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus"));
    let vfs = DirectoryVfs::new(&root);
    let mut menu = LaunchMenu::open(&vfs, &root).expect("campaign menu");
    menu.screen = Screen::Campaigns;
    let campaigns = menu
        .rows()
        .into_iter()
        .filter_map(|row| match row.action {
            Action::Open(Screen::Campaign(index)) => Some(index),
            Action::Open(Screen::Start) => None,
            _ => panic!("missing campaign action for {}", row.label),
        })
        .collect::<Vec<_>>();
    assert_eq!(campaigns.len(), 6);

    let mut menu_keys = Vec::new();
    for index in campaigns {
        menu.screen = Screen::Campaign(index);
        menu_keys.extend(menu.rows().into_iter().filter_map(|row| match row.action {
            Action::Launch(key) => Some(key.to_string()),
            Action::Open(Screen::Campaigns) => None,
            _ => panic!("missing mission action for {}", row.label),
        }));
    }
    let cli_keys = list_mission_keys(&vfs)
        .expect("numbered missions")
        .into_iter()
        .filter(|key| key.to_ascii_lowercase().starts_with("missions/campaign/"))
        .collect::<Vec<_>>();
    assert_eq!(menu_keys.len(), 20);
    assert_eq!(menu_keys, cli_keys);
}

fn fill(frame: &mut [u32], x: usize, y: usize, width: usize, height: usize, color: u32) {
    for row in y..y + height {
        let start = row * EXTENT[0] as usize + x;
        frame[start..start + width].fill(color);
    }
}