aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/factory_menu.rs
diff options
context:
space:
mode:
Diffstat (limited to 'apps/fparkan-game/src/factory_menu.rs')
-rw-r--r--apps/fparkan-game/src/factory_menu.rs276
1 files changed, 276 insertions, 0 deletions
diff --git a/apps/fparkan-game/src/factory_menu.rs b/apps/fparkan-game/src/factory_menu.rs
new file mode 100644
index 00000000..8f307cfc
--- /dev/null
+++ b/apps/fparkan-game/src/factory_menu.rs
@@ -0,0 +1,276 @@
+use super::{
+ append_environment_gradient_material, append_environment_range, quad_indices,
+ screen_tl_quad_vertices_pixels, world_pipeline_state, DirectoryVfs, EnvironmentGpuRange,
+ LegacyBlendMode, LegacyDepthMode, StaticPreviewScene, StaticVulkanApp, VulkanSmokeRenderer,
+ VulkanStaticTexture,
+};
+use fparkan_assets::factory_projects::{
+ hit_test, FactoryProjectAction, FactoryProjectImages, EXTENT, ORIGIN, PROJECT_SLOTS,
+};
+use fparkan_world::ObjectHandle;
+use std::{ops::Range, path::Path};
+use winit::{
+ event::{ElementState, MouseButton, WindowEvent},
+ keyboard::KeyCode,
+};
+
+#[derive(Clone)]
+pub(super) struct FactoryChoice {
+ pub(super) factory: Option<ObjectHandle>,
+ pub(super) scheme: usize,
+ pub(super) name: String,
+}
+
+pub(super) struct FactoryMenu {
+ choices: Vec<FactoryChoice>,
+ selected: usize,
+ cursor: [f32; 2],
+ pressed: Option<usize>,
+}
+
+impl FactoryMenu {
+ pub(super) fn new(choices: Vec<FactoryChoice>) -> Self {
+ debug_assert!(!choices.is_empty());
+ Self {
+ choices,
+ selected: 0,
+ cursor: [f32::NAN; 2],
+ pressed: None,
+ }
+ }
+
+ pub(super) fn selected(&self) -> &FactoryChoice {
+ &self.choices[self.selected]
+ }
+
+ fn navigate(&mut self, backwards: bool) {
+ let len = self.choices.len();
+ let offset = if backwards { len - 1 } else { 1 };
+ self.selected = (self.selected + offset) % len;
+ }
+
+ fn visible_slots(&self) -> Range<usize> {
+ let factory = self.selected().factory;
+ let group_start = self.choices[..self.selected]
+ .iter()
+ .rposition(|choice| choice.factory != factory)
+ .map_or(0, |previous| previous + 1);
+ let start = group_start + (self.selected - group_start) / PROJECT_SLOTS * PROJECT_SLOTS;
+ let count = self.choices[start..]
+ .iter()
+ .take(PROJECT_SLOTS)
+ .take_while(|choice| choice.factory == factory)
+ .count();
+ start..start + count
+ }
+
+ pub(super) fn title(&self) -> String {
+ let choice = self.selected();
+ let factory = choice.factory.map_or_else(
+ || "Завод".to_owned(),
+ |factory| format!("Завод №{}", factory.slot + 1),
+ );
+ format!(
+ "{factory} — {}/{} {} · ↑/↓ выбор · B или Enter заказ · Esc отмена",
+ self.selected + 1,
+ self.choices.len(),
+ choice.name,
+ )
+ }
+}
+
+pub(super) struct FactoryProjectPanel {
+ images: FactoryProjectImages,
+ range: EnvironmentGpuRange,
+ displayed: Option<ProjectPicture>,
+}
+
+#[derive(PartialEq, Eq)]
+struct ProjectPicture {
+ count: usize,
+ selected: usize,
+ pressed: Option<usize>,
+ name: String,
+}
+
+impl FactoryProjectPanel {
+ pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
+ let images = FactoryProjectImages::load(&DirectoryVfs::new(root))?;
+ 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; (EXTENT[0] * EXTENT[1] * 4) as usize]);
+ let half = EXTENT.map(|dimension| dimension as f32 * 0.5);
+ let vertices = screen_tl_quad_vertices_pixels(
+ [ORIGIN[0] as f32 + half[0], ORIGIN[1] as f32 + half[1]],
+ half[0],
+ half[1],
+ [640.0, 480.0],
+ [1.0; 3],
+ 1.0,
+ [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]],
+ );
+ let range = append_environment_range(
+ &mut preview.mesh,
+ material,
+ vertices.to_vec(),
+ quad_indices(1)?,
+ world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled),
+ )?;
+ Ok(Self {
+ images,
+ range,
+ displayed: None,
+ })
+ }
+
+ pub(super) fn range_index(&self) -> usize {
+ self.range.range_index
+ }
+
+ pub(super) fn draw(
+ &mut self,
+ renderer: &mut VulkanSmokeRenderer,
+ menu: Option<&mut FactoryMenu>,
+ ) -> Result<(), String> {
+ if let Some(menu) = menu {
+ let slots = menu.visible_slots();
+ let count = slots.len();
+ let selected = menu.selected - slots.start;
+ let pressed = menu.pressed.take();
+ let name = &menu.selected().name;
+ let unchanged = self.displayed.as_ref().is_some_and(|picture| {
+ picture.count == count
+ && picture.selected == selected
+ && picture.pressed == pressed
+ && picture.name == *name
+ });
+ if !unchanged {
+ let image = self.images.paint(count, selected, pressed, name)?;
+ renderer
+ .update_material_texture(self.range.material_index, 0, &texture(image.rgba8))
+ .map_err(|error| error.to_string())?;
+ self.displayed = Some(ProjectPicture {
+ count,
+ selected,
+ pressed,
+ name: name.clone(),
+ });
+ }
+ renderer
+ .set_draw_range_index_count(self.range.range_index, 6)
+ .map_err(|error| error.to_string())
+ } else {
+ renderer
+ .set_draw_range_index_count(self.range.range_index, 0)
+ .map_err(|error| error.to_string())
+ }
+ }
+}
+
+impl StaticVulkanApp {
+ pub(super) fn handle_factory_key(
+ &mut self,
+ code: KeyCode,
+ state: ElementState,
+ repeat: bool,
+ ) -> bool {
+ let Some(menu) = &mut self.factory_menu else {
+ return false;
+ };
+ if state == ElementState::Pressed && !repeat && !self.mission_paused {
+ match code {
+ KeyCode::ArrowUp => menu.navigate(true),
+ KeyCode::ArrowDown => menu.navigate(false),
+ KeyCode::KeyB | KeyCode::Enter | KeyCode::NumpadEnter => {
+ self.player_build_pressed = true;
+ }
+ KeyCode::Escape => {
+ self.factory_menu = None;
+ self.set_mouse_look(self.window_focused && self.cockpit.is_some());
+ }
+ _ => {}
+ }
+ self.update_mission_title();
+ }
+ true
+ }
+
+ pub(super) fn handle_factory_pointer(&mut self, event: &WindowEvent) -> bool {
+ let Some(menu) = &mut self.factory_menu else {
+ return false;
+ };
+ match event {
+ WindowEvent::CursorMoved { position, .. } => {
+ if let Some(window) = self.window.as_ref() {
+ let size = window.inner_size();
+ if size.width != 0 && size.height != 0 {
+ menu.cursor = [
+ position.x as f32 * 640.0 / size.width as f32,
+ position.y as f32 * 480.0 / size.height as f32,
+ ];
+ }
+ }
+ true
+ }
+ WindowEvent::CursorLeft { .. } | WindowEvent::Focused(false) => {
+ menu.cursor = [f32::NAN; 2];
+ false
+ }
+ WindowEvent::MouseInput { state, button, .. } => {
+ if *state == ElementState::Pressed
+ && *button == MouseButton::Left
+ && !self.mission_paused
+ {
+ let slots = menu.visible_slots();
+ match hit_test(menu.cursor, slots.len()) {
+ Some(FactoryProjectAction::Select(index)) => {
+ menu.selected = slots.start + index;
+ menu.pressed = Some(index);
+ self.update_mission_title();
+ }
+ Some(FactoryProjectAction::Build) => self.player_build_pressed = true,
+ None => {}
+ }
+ }
+ true
+ }
+ _ => false,
+ }
+ }
+}
+
+fn texture(rgba8: Vec<u8>) -> VulkanStaticTexture {
+ VulkanStaticTexture {
+ width: EXTENT[0],
+ height: EXTENT[1],
+ rgba8,
+ mip_levels: Vec::new(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn project_slots_are_scoped_to_the_selected_factory() {
+ let choices = (0..8)
+ .map(|scheme| FactoryChoice {
+ factory: Some(ObjectHandle {
+ slot: u32::from(scheme >= 6),
+ generation: 0,
+ }),
+ scheme,
+ name: format!("{scheme}.dat"),
+ })
+ .collect();
+ let mut menu = FactoryMenu::new(choices);
+ assert_eq!(menu.visible_slots(), 0..5);
+ menu.selected = 5;
+ assert_eq!(menu.visible_slots(), 5..6);
+ menu.navigate(false);
+ assert_eq!(menu.visible_slots(), 6..8);
+ }
+}