diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-02 06:24:01 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-02 06:24:01 +0300 |
| commit | b0c3a064c29c2bf97981f45806696c2dd0d4dd90 (patch) | |
| tree | a677357a8519520a49cd4ccad3daa9cfde68d28e | |
| parent | 7b3a106ff7a376b95b3bb9e52d3186ebe1a9bcaa (diff) | |
| download | fparkan-b0c3a064c29c2bf97981f45806696c2dd0d4dd90.tar.xz fparkan-b0c3a064c29c2bf97981f45806696c2dd0d4dd90.zip | |
feat(ui): preview new warbot geometry during a mission
On stock Field Camp, open a compatible Unit DAT created after start, resize the preview, switch to a resident project, reopen the new project, and return to the mission with Vulkan validation clean. The factory reserve for new geometry is still prepared at mission load.
| -rw-r--r-- | adapters/fparkan-render-vulkan/src/ffi/preview_mesh.rs | 299 | ||||
| -rw-r--r-- | adapters/fparkan-render-vulkan/src/ffi/smoke.rs | 127 | ||||
| -rw-r--r-- | adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs | 12 | ||||
| -rw-r--r-- | adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs | 10 | ||||
| -rw-r--r-- | apps/fparkan-game/src/designer_geometry.rs | 162 | ||||
| -rw-r--r-- | apps/fparkan-game/src/designer_model.rs | 13 | ||||
| -rw-r--r-- | apps/fparkan-game/src/designer_projects.rs | 53 | ||||
| -rw-r--r-- | apps/fparkan-game/src/factory_menu.rs | 78 | ||||
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 136 | ||||
| -rw-r--r-- | apps/fparkan-game/src/model_mounts.rs | 53 | ||||
| -rw-r--r-- | apps/fparkan-game/src/robot_designer.rs | 75 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/designer_screen.rs | 12 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 4 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 21 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/saved_factory_projects.rs | 210 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 11 |
16 files changed, 977 insertions, 299 deletions
diff --git a/adapters/fparkan-render-vulkan/src/ffi/preview_mesh.rs b/adapters/fparkan-render-vulkan/src/ffi/preview_mesh.rs new file mode 100644 index 00000000..3ff1e4db --- /dev/null +++ b/adapters/fparkan-render-vulkan/src/ffi/preview_mesh.rs @@ -0,0 +1,299 @@ +//! Separately uploaded geometry for the model viewport. + +use super::{ + create_static_mesh_index_buffer, create_static_mesh_vertex_buffer, create_static_texture_image, + create_swapchain_resources, deduplicate_texture_sources, destroy_allocated_buffer, + destroy_allocated_image, destroy_swapchain_resources, resolve_draw_texture_indices, vk, + RollbackOnDrop, VulkanLogicalDeviceProbe, VulkanSmokeRenderer, VulkanSmokeRendererError, + VulkanStaticMaterial, +}; +use crate::ffi::smoke_types::VulkanPreviewMesh; +use crate::ffi::{VulkanStaticMesh, VulkanStaticTexture}; +use std::ops::Range; + +impl VulkanPreviewMesh { + pub(super) fn destroy(self, device: &VulkanLogicalDeviceProbe) { + destroy_allocated_buffer(device, &self.vertex); + destroy_allocated_buffer(device, &self.index); + for image in &self.images { + destroy_allocated_image(device, image); + } + } +} + +impl VulkanSmokeRenderer { + /// Selects the model to draw over the interface with its own camera and + /// depth buffer region. Only the main pass draws these ranges. + pub fn set_model_preview( + &mut self, + preview: Option<crate::ffi::VulkanModelPreview>, + ) -> Result<(), VulkanSmokeRendererError> { + if let Some(model) = &preview { + let [left, top, right, bottom] = model.viewport; + if !model.camera.is_finite() || !model.eye.iter().all(|value| value.is_finite()) { + return Err(VulkanSmokeRendererError::InvalidStaticCamera { + context: "non-finite model preview camera", + }); + } + if model.ranges.is_empty() || model.ranges.end > self.draw_ranges.len() { + return Err(VulkanSmokeRendererError::InvalidStaticMesh { + context: "invalid model preview draw ranges", + }); + } + let scene_ranges = self + .preview_mesh + .as_ref() + .map_or(self.draw_ranges.len(), |mesh| mesh.range_start); + let valid_ranges = match model.draw_before { + Some(anchor) => anchor < scene_ranges && model.ranges.start == scene_ranges, + None => model.ranges.end <= scene_ranges, + }; + if !valid_ranges { + return Err(VulkanSmokeRendererError::InvalidStaticMesh { + context: "preview draw placement does not match its geometry", + }); + } + if !(left >= 0.0 + && top >= 0.0 + && right <= 1.0 + && bottom <= 1.0 + && left < right + && top < bottom) + { + return Err(VulkanSmokeRendererError::InvalidStaticCamera { + context: "invalid model preview viewport", + }); + } + } + self.model_preview = preview; + Ok(()) + } + + pub(super) fn material_image_views( + &self, + preview: Option<&VulkanPreviewMesh>, + ) -> (Vec<vk::ImageView>, Vec<usize>) { + let mut views = self + .textures + .iter() + .map(|image| image.view) + .collect::<Vec<_>>(); + let mut slots = self.texture_slot_indices.clone(); + if let Some(preview) = preview { + let offset = views.len(); + views.extend(preview.images.iter().map(|image| image.view)); + slots.extend(preview.slots.iter().map(|&index| offset + index)); + } + (views, slots) + } + + /// Uploads a single model for the separate viewport and returns its draw handles. + /// + /// The model uses its own geometry and texture images. Replacing it keeps + /// scene ranges, textures and their current settings intact. + pub fn upload_preview_mesh( + &mut self, + mesh: &VulkanStaticMesh, + materials: &[VulkanStaticMaterial], + ) -> Result<Range<usize>, VulkanSmokeRendererError> { + let invalid = |context| VulkanSmokeRendererError::InvalidStaticMesh { context }; + mesh.validate().map_err(invalid)?; + let local_materials = + resolve_draw_texture_indices(&mesh.draw_ranges, materials).map_err(invalid)?; + if materials.is_empty() || mesh.draw_ranges.is_empty() { + return Err(invalid( + "uploaded preview has no model batches or materials", + )); + } + let (range_start, material_start) = self.preview_mesh.as_ref().map_or( + (self.draw_ranges.len(), self.material_alphas.len()), + |mesh| (mesh.range_start, mesh.material_start), + ); + let neutral = |rgba8: [u8; 4]| VulkanStaticTexture { + width: 1, + height: 1, + rgba8: rgba8.to_vec(), + mip_levels: Vec::new(), + }; + let detail = neutral([128, 128, 128, 255]); + let overlay = neutral([255, 255, 255, 0]); + let sources = materials + .iter() + .flat_map(|material| { + [ + &material.texture, + material.detail_texture.as_ref().unwrap_or(&detail), + material.overlay_texture.as_ref().unwrap_or(&overlay), + material.overlay_detail_texture.as_ref().unwrap_or(&detail), + ] + }) + .collect::<Vec<_>>(); + let (sources, slots) = deduplicate_texture_sources(&sources); + let mut pipeline_states = self.draw_range_base_pipeline_states[..range_start].to_vec(); + pipeline_states.extend(mesh.draw_ranges.iter().map(|range| range.pipeline_state)); + let (preview, resources) = { + let instance = self.instance_ref()?; + let device = self.device_ref()?; + // SAFETY: Outstanding graphics and presentation work must finish + // before replacing the render-pass resources for the live swapchain. + unsafe { device.device().device_wait_idle() }.map_err(|result| { + VulkanSmokeRendererError::VulkanOperation { + context: "vkDeviceWaitIdle(preview material installation)", + result, + } + })?; + let vertex = RollbackOnDrop::new( + create_static_mesh_vertex_buffer(instance, device, mesh)?, + |buffer| destroy_allocated_buffer(device, &buffer), + ); + let index = create_static_mesh_index_buffer(instance, device, mesh)?; + let mut preview = RollbackOnDrop::new( + VulkanPreviewMesh { + vertex: vertex.commit(), + index, + images: Vec::with_capacity(sources.len()), + slots, + range_start, + material_start, + }, + |mesh: VulkanPreviewMesh| mesh.destroy(device), + ); + let pending = preview.value.as_mut().expect("uncommitted preview"); + for source in sources { + pending.images.push(create_static_texture_image( + instance, + device, + self.command_pool, + source, + )?); + } + let (views, slots) = self.material_image_views(Some(pending)); + let resources = create_swapchain_resources( + instance, + device, + self.swapchain_ref()?, + self.command_pool, + self.pipeline_cache, + self.vertex_buffer_ref()?, + self.index_buffer_ref()?, + &views, + &slots, + &pipeline_states, + self.draw_ranges[..range_start] + .iter() + .any(|range| range.terrain_reflection), + self.depth_request, + false, + )?; + (preview.commit(), resources) + }; + + let old_resources = self.swapchain_resources.replace(resources); + let old_preview = self.preview_mesh.replace(preview); + let device = self.device_ref()?; + if let Some(resources) = old_resources { + destroy_swapchain_resources(device, self.command_pool, resources); + } + if let Some(preview) = old_preview { + preview.destroy(device); + } + self.images_in_flight.fill(vk::Fence::null()); + self.last_readback_image_index = None; + self.model_preview = None; + self.material_specular_dirty = true; + self.draw_order_dirty = true; + + self.draw_ranges.truncate(range_start); + self.draw_ranges.extend(&mesh.draw_ranges); + self.draw_range_capacities.truncate(range_start); + self.draw_range_capacities + .extend(mesh.draw_ranges.iter().map(|range| range.index_count)); + self.draw_texture_indices.truncate(range_start); + self.draw_texture_indices.extend( + local_materials + .into_iter() + .map(|index| material_start + index), + ); + self.reflection_planes.truncate(range_start); + self.reflection_planes.resize(self.draw_ranges.len(), None); + self.draw_range_base_pipeline_states = pipeline_states; + self.draw_range_sort_keys.truncate(range_start); + self.draw_range_sort_keys + .resize(self.draw_ranges.len(), None); + self.draw_range_world_queue.truncate(range_start); + self.draw_range_world_queue + .resize(self.draw_ranges.len(), None); + self.draw_range_diffuse_alpha_overrides + .truncate(range_start); + self.draw_range_diffuse_alpha_overrides + .resize(self.draw_ranges.len(), None); + + self.material_alphas.truncate(material_start); + self.material_lighting.truncate(material_start); + self.material_uv_transforms.truncate(material_start); + self.material_unlit.truncate(material_start); + self.material_specular.truncate(material_start); + self.material_selectors.truncate(material_start); + for material in materials { + self.material_alphas.push([ + material.diffuse_alpha, + material.overlay_diffuse_alpha.unwrap_or(0.0), + ]); + self.material_lighting.push([ + material.directional_rgb, + material.additive_rgb, + material.overlay_directional_rgb.unwrap_or([1.0; 3]), + material.overlay_additive_rgb.unwrap_or([0.0; 3]), + ]); + self.material_uv_transforms.push([ + material.uv_transform, + material.detail_uv_transform, + material + .overlay_uv_transform + .unwrap_or([0.0, 0.0, 1.0, 1.0]), + material + .overlay_detail_uv_transform + .unwrap_or([0.0, 0.0, 1.0, 1.0]), + ]); + let base = material.specular_rgb; + let overlay = material.overlay_specular_rgb.unwrap_or([0.0; 3]); + self.material_specular.push([ + [ + base[0], + base[1], + base[2], + f32::from(material.specular_power), + ], + [ + overlay[0], + overlay[1], + overlay[2], + f32::from(material.overlay_specular_power.unwrap_or(0)), + ], + ]); + self.material_selectors.push(material.material_index); + self.material_unlit.push(material.encoded_material_mode()); + } + Ok(range_start..self.draw_ranges.len()) + } +} + +pub(super) fn preview_rect((width, height): (u32, u32), viewport: [f32; 4]) -> vk::Rect2D { + let [left, top, right, bottom] = viewport; + let x = (left * width as f32).round() as u32; + let y = (top * height as f32).round() as u32; + let x = x.min(width - 1); + let y = y.min(height - 1); + let right = ((right * width as f32).round() as u32).clamp(x + 1, width); + let bottom = ((bottom * height as f32).round() as u32).clamp(y + 1, height); + vk::Rect2D { + offset: vk::Offset2D { + x: x as i32, + y: y as i32, + }, + extent: vk::Extent2D { + width: right - x, + height: bottom - y, + }, + } +} diff --git a/adapters/fparkan-render-vulkan/src/ffi/smoke.rs b/adapters/fparkan-render-vulkan/src/ffi/smoke.rs index 9c6b9f11..2111e6ff 100644 --- a/adapters/fparkan-render-vulkan/src/ffi/smoke.rs +++ b/adapters/fparkan-render-vulkan/src/ffi/smoke.rs @@ -23,6 +23,10 @@ use super::{ use crate::policy::KHR_PORTABILITY_SUBSET_EXTENSION; use crate::shader::validate_triangle_shaders; +#[path = "preview_mesh.rs"] +mod preview_mesh; +use preview_mesh::preview_rect; + #[cfg(test)] fn take_runtime_owners_in_dependency_order<Instance, Validation, Surface, Device, Swapchain>( instance: &mut Option<Instance>, @@ -434,6 +438,7 @@ impl VulkanSmokeRenderer { frame_uniforms, cockpit_camera: None, model_preview: None, + preview_mesh: None, point_lights: Vec::new(), point_lights_explicit: false, frame_sync: Vec::new(), @@ -612,40 +617,6 @@ impl VulkanSmokeRenderer { Ok(()) } - /// Selects the model to draw over the interface with its own camera and - /// depth buffer region. Only the main pass draws these ranges. - pub fn set_model_preview( - &mut self, - preview: Option<super::VulkanModelPreview>, - ) -> Result<(), VulkanSmokeRendererError> { - if let Some(model) = &preview { - let [left, top, right, bottom] = model.viewport; - if !model.camera.is_finite() || !model.eye.iter().all(|value| value.is_finite()) { - return Err(VulkanSmokeRendererError::InvalidStaticCamera { - context: "non-finite model preview camera", - }); - } - if model.ranges.is_empty() || model.ranges.end > self.draw_ranges.len() { - return Err(VulkanSmokeRendererError::InvalidStaticMesh { - context: "invalid model preview draw ranges", - }); - } - if !(left >= 0.0 - && top >= 0.0 - && right <= 1.0 - && bottom <= 1.0 - && left < right - && top < bottom) - { - return Err(VulkanSmokeRendererError::InvalidStaticCamera { - context: "invalid model preview viewport", - }); - } - } - self.model_preview = preview; - Ok(()) - } - /// Replaces lighting, fog, camera-position and matrix state for /// subsequent frames without recreating GPU resources. /// @@ -758,7 +729,10 @@ impl VulkanSmokeRenderer { validate_geometry_upload( vertices, indices, - &self.draw_ranges, + &self.draw_ranges[..self + .preview_mesh + .as_ref() + .map_or(self.draw_ranges.len(), |mesh| mesh.range_start)], geometry_ranges, self.vertex_count, self.index_capacity, @@ -1445,16 +1419,6 @@ impl VulkanSmokeRenderer { }) } - fn textures_ref(&self) -> Result<&[super::VulkanAllocatedImage], VulkanSmokeRendererError> { - if self.textures.is_empty() { - Err(VulkanSmokeRendererError::InvariantViolation { - context: "static material textures", - }) - } else { - Ok(&self.textures) - } - } - fn surface_ref(&self) -> Result<&VulkanSurfaceProbe, VulkanSmokeRendererError> { self.surface .as_ref() @@ -1844,6 +1808,7 @@ impl VulkanSmokeRenderer { ) -> Result<(), VulkanSmokeRendererError> { let device = self.device_ref()?; let swapchain = self.swapchain_ref()?; + let (views, slots) = self.material_image_views(self.preview_mesh.as_ref()); let resources = RollbackOnDrop::new( create_swapchain_resources( self.instance_ref()?, @@ -1853,8 +1818,8 @@ impl VulkanSmokeRenderer { self.pipeline_cache, self.vertex_buffer_ref()?, self.index_buffer_ref()?, - self.textures_ref()?, - &self.texture_slot_indices, + &views, + &slots, &self.draw_range_base_pipeline_states, self.draw_ranges .iter() @@ -2034,13 +1999,28 @@ impl VulkanSmokeRenderer { .as_ref() .map(|preview| preview_rect(extent, preview.viewport)); let mut preview_depth_cleared = false; + let mut bound_uploaded_mesh = false; + let uploaded = self.preview_mesh.as_ref(); + let inserted = self.model_preview.as_ref().filter(|_| !reflected); + let ordered = self + .draw_order + .iter() + .copied() + .filter(|&index| uploaded.is_none_or(|mesh| index < mesh.range_start)) + .flat_map(|index| { + inserted + .filter(|preview| preview.draw_before == Some(index)) + .map(|preview| preview.ranges.clone()) + .into_iter() + .flatten() + .chain(std::iter::once(index)) + }); // Native reflection queues the translucent water after the reflected world. let draw_order = - self.draw_order - .iter() - .copied() + ordered + .clone() .filter(|&index| !reflected || !self.draw_ranges[index].terrain_reflection) - .chain(self.draw_order.iter().copied().filter(|&index| { + .chain(ordered.filter(|&index| { reflected && self.draw_ranges[index].terrain_reflection })); for range_index in draw_order { @@ -2072,6 +2052,28 @@ impl VulkanSmokeRenderer { if reflected && mode & 8 != 0 { continue; } + let use_uploaded = uploaded.is_some_and(|mesh| range_index >= mesh.range_start); + if use_uploaded != bound_uploaded_mesh { + let (vertex, index) = if let Some(mesh) = uploaded.filter(|_| use_uploaded) + { + (&mesh.vertex, &mesh.index) + } else { + (self.vertex_buffer_ref()?, self.index_buffer_ref()?) + }; + device.device().cmd_bind_vertex_buffers( + command_buffer, + 0, + &[vertex.buffer], + &offsets, + ); + device.device().cmd_bind_index_buffer( + command_buffer, + index.buffer, + 0, + vk::IndexType::UINT32, + ); + bound_uploaded_mesh = use_uploaded; + } let state = if reflected { super::reflection::reflected_draw_pipeline_state(range, shifted_reflection) } else { @@ -2428,6 +2430,9 @@ impl VulkanSmokeRenderer { fn destroy_device_owned_resources(&mut self) { self.destroy_swapchain_resources(); if let Some(device) = self.device.as_ref() { + if let Some(mesh) = self.preview_mesh.take() { + mesh.destroy(device); + } if self.pipeline_cache != vk::PipelineCache::null() { // SAFETY: All pipeline creation has finished on this device. unsafe { @@ -2827,26 +2832,6 @@ fn world_material_pipeline_states( /// compacted into world positions and sorted transparent ranges are inserted /// after the last active background; fixed passes keep their relative order but /// can shift slots. Zero-index-count ranges are inactive and are omitted. -fn preview_rect((width, height): (u32, u32), viewport: [f32; 4]) -> vk::Rect2D { - let [left, top, right, bottom] = viewport; - let x = (left * width as f32).round() as u32; - let y = (top * height as f32).round() as u32; - let x = x.min(width - 1); - let y = y.min(height - 1); - let right = ((right * width as f32).round() as u32).clamp(x + 1, width); - let bottom = ((bottom * height as f32).round() as u32).clamp(y + 1, height); - vk::Rect2D { - offset: vk::Offset2D { - x: x as i32, - y: y as i32, - }, - extent: vk::Extent2D { - width: right - x, - height: bottom - y, - }, - } -} - fn sorted_world_draw_order( range_count: usize, ranges: &[super::VulkanStaticDrawRange], diff --git a/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs b/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs index cf795ccf..33917925 100644 --- a/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs +++ b/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs @@ -79,6 +79,8 @@ pub struct VulkanStaticCamera { pub struct VulkanModelPreview { /// Contiguous preview draw ranges, appended above the UI background. pub ranges: std::ops::Range<usize>, + /// Draw the separately uploaded model before this interface range. + pub draw_before: Option<usize>, /// Left, top, right and bottom as fractions of the main drawable. pub viewport: [f32; 4], /// Projection and view of the preview model. @@ -1637,6 +1639,7 @@ pub struct VulkanSmokeRenderer { pub(super) frame_uniforms: VulkanFrameUniforms, pub(super) cockpit_camera: Option<(std::ops::Range<usize>, VulkanStaticCamera)>, pub(super) model_preview: Option<VulkanModelPreview>, + pub(super) preview_mesh: Option<VulkanPreviewMesh>, /// Dynamically sized point-light records submitted by the client. pub(super) point_lights: Vec<VulkanPointLight>, /// Whether `set_point_lights` has replaced legacy `frame_uniforms.point_light`. @@ -1653,3 +1656,12 @@ pub struct VulkanSmokeRenderer { pub(super) swapchain_recreate_count: u32, pub(super) report: VulkanSmokeRendererReport, } + +pub(super) struct VulkanPreviewMesh { + pub(super) vertex: VulkanAllocatedBuffer, + pub(super) index: VulkanAllocatedBuffer, + pub(super) images: Vec<VulkanAllocatedImage>, + pub(super) slots: Vec<usize>, + pub(super) range_start: usize, + pub(super) material_start: usize, +} diff --git a/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs b/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs index 295cd70b..a20f184d 100644 --- a/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs +++ b/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs @@ -179,7 +179,7 @@ pub(super) fn create_swapchain_resources( pipeline_cache: vk::PipelineCache, vertex_buffer: &VulkanAllocatedBuffer, index_buffer: &VulkanAllocatedBuffer, - textures: &[VulkanAllocatedImage], + textures: &[vk::ImageView], texture_slot_indices: &[usize], base_pipeline_states: &[LegacyPipelineState], reflection_enabled: bool, @@ -502,7 +502,7 @@ fn create_swapchain_pipeline_bundle( pipeline_cache: vk::PipelineCache, format: i32, extent: (u32, u32), - textures: &[VulkanAllocatedImage], + textures: &[vk::ImageView], texture_slot_indices: &[usize], base_pipeline_states: &[LegacyPipelineState], reflection_layout: vk::DescriptorSetLayout, @@ -777,7 +777,7 @@ fn create_pipeline_layout( fn create_texture_descriptor_bundle( device: &VulkanLogicalDeviceProbe, - textures: &[VulkanAllocatedImage], + textures: &[vk::ImageView], texture_slot_indices: &[usize], frame_uniform_buffer: &VulkanAllocatedBuffer, material_specular_buffer: &VulkanAllocatedBuffer, @@ -931,10 +931,10 @@ fn create_texture_descriptor_bundle( let image_infos = texture_slot_indices .iter() .map(|texture_index| { - let texture = &textures[*texture_index]; + let texture = textures[*texture_index]; vk::DescriptorImageInfo::default() .sampler(sampler) - .image_view(texture.view) + .image_view(texture) .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL) }) .collect::<Vec<_>>(); diff --git a/apps/fparkan-game/src/designer_geometry.rs b/apps/fparkan-game/src/designer_geometry.rs new file mode 100644 index 00000000..db754a41 --- /dev/null +++ b/apps/fparkan-game/src/designer_geometry.rs @@ -0,0 +1,162 @@ +//! Standalone Unit DAT assembly for the constructor's model viewport. + +use super::{ + add3, aggregate_component_sphere, append_static_preview_component_with_lightmaps, + configure_world_material_categories, length3, model_mounts::initial_mount, + mounted_shadow_sphere, native_msh_cull_mode, native_msh_handedness, + node38_pose_relative_to_root, node38_pose_relative_to_root_from_hierarchy, + project_msh_to_static_mesh_in_world_space_with_node_fallback_poses, + project_msh_to_static_mesh_in_world_space_with_node_fallback_poses_and_mount, + project_msh_to_static_mesh_in_world_space_with_node_pose_buffer, + project_msh_to_static_mesh_in_world_space_with_node_pose_buffer_and_mount, scale3, + static_preview_component_materials, static_preview_component_pose_buffer, + static_preview_lightmap_textures, sub3, unit_component_is_visible, LegacyIron3dEulerTransform, + MissionAssets, VulkanStaticMaterial, VulkanStaticMesh, +}; +use fparkan_prototype::{unit_component_tree, UnitDat}; + +pub(super) struct DesignerGeometry { + pub(super) mesh: VulkanStaticMesh, + pub(super) materials: Vec<VulkanStaticMaterial>, + pub(super) center: [f32; 3], + pub(super) radius: f32, +} + +impl DesignerGeometry { + pub(super) fn prepare(project: &UnitDat, assets: &MissionAssets) -> Result<Self, String> { + let tree = unit_component_tree(&project.records).map_err(|error| error.to_string())?; + let components = assets + .visuals_for_object(0) + .iter() + .map(|id| { + let visual = assets.visual_by_id(*id).ok_or("missing designer visual")?; + let model = visual.model_id.and_then(|id| assets.model_by_id(id)); + Ok((visual, model)) + }) + .collect::<Result<Vec<_>, &str>>()?; + if components.len() != tree.len() { + return Err("designer visuals do not match project components".into()); + } + let mut poses = vec![None; components.len()]; + let mut mounts = vec![None; components.len()]; + let mut mesh = VulkanStaticMesh { + vertices: Vec::new(), + indices: Vec::new(), + draw_ranges: Vec::new(), + }; + let mut materials = Vec::new(); + let mut animations = Vec::new(); + let mut spheres = Vec::new(); + let transform = LegacyIron3dEulerTransform { + translation: [0.0; 3], + orientation_radians: [0.0; 3], + }; + let scale = [1.0; 3]; + for (index, &(visual, model)) in components.iter().enumerate() { + if !unit_component_is_visible(index, visual.source_type) { + continue; + } + let model = &model.ok_or("missing external designer model")?.validated; + let control = assets + .object_component_controls + .first() + .and_then(|controls| controls.get(index)) + .and_then(Option::as_ref); + let bindings = control.map_or(&[][..], |control| control.bindings.as_slice()); + poses[index] = static_preview_component_pose_buffer(model, bindings, None)?; + mounts[index] = initial_mount( + index, + &project.records, + &tree, + &components, + &poses, + &mounts, + None, + )?; + let mounted_root = mounts[index].and_then(|_| match poses[index].as_ref() { + Some(poses) => node38_pose_relative_to_root_from_hierarchy(poses, 1), + None => node38_pose_relative_to_root(model, None, 1), + }); + spheres.extend(mounted_shadow_sphere( + model.bounding_sphere_center, + model.bounding_sphere_radius, + mounts[index], + mounted_root, + )); + let mut component = match (poses[index].as_ref(), mounts[index]) { + (Some(poses), Some(mount)) => { + project_msh_to_static_mesh_in_world_space_with_node_pose_buffer_and_mount( + model, transform, scale, poses, mount, + ) + } + (Some(poses), None) => { + project_msh_to_static_mesh_in_world_space_with_node_pose_buffer( + model, transform, scale, poses, + ) + } + (None, Some(mount)) => { + project_msh_to_static_mesh_in_world_space_with_node_fallback_poses_and_mount( + model, transform, scale, mount, + ) + } + (None, None) => project_msh_to_static_mesh_in_world_space_with_node_fallback_poses( + model, transform, scale, + ), + } + .map_err(|error| error.to_string())?; + let handedness = native_msh_handedness(transform, scale); + for range in &mut component.draw_ranges { + range.pipeline_state.cull = native_msh_cull_mode(range.batch_flags, handedness); + } + let selectors = static_preview_component_materials( + assets, + visual, + &component, + Some(0), + &mut materials, + &mut animations, + )?; + let lightmaps = static_preview_lightmap_textures(assets, visual)?; + append_static_preview_component_with_lightmaps( + &mut mesh, + component, + &selectors, + Some(&mut materials), + &lightmaps, + Some(&mut animations), + )?; + } + let ranges = (0..mesh.draw_ranges.len()).collect::<Vec<_>>(); + configure_world_material_categories(&mut mesh, &materials, &ranges)?; + if let Some(sphere) = aggregate_component_sphere(&spheres) { + return Ok(Self { + mesh, + materials, + center: sphere.center, + radius: sphere.radius, + }); + } + let first = mesh + .vertices + .first() + .ok_or("project has no visible geometry")? + .position; + let (lo, hi) = mesh + .vertices + .iter() + .fold((first, first), |(lo, hi), vertex| { + ( + std::array::from_fn(|axis| lo[axis].min(vertex.position[axis])), + std::array::from_fn(|axis| hi[axis].max(vertex.position[axis])), + ) + }); + let center = scale3(add3(lo, hi), 0.5); + let radius = length3(sub3(hi, lo)).ok_or("project geometry has no finite bounds")? * 0.5; + Ok(Self { + mesh, + materials, + center, + radius, + }) + } +} diff --git a/apps/fparkan-game/src/designer_model.rs b/apps/fparkan-game/src/designer_model.rs index 19f3fba2..9bf24600 100644 --- a/apps/fparkan-game/src/designer_model.rs +++ b/apps/fparkan-game/src/designer_model.rs @@ -13,7 +13,7 @@ const HALF_FOV: f32 = std::f32::consts::FRAC_PI_6; pub(super) struct DesignerModels(Vec<Option<DesignerModel>>); -struct DesignerModel { +pub(super) struct DesignerModel { draws: Range<usize>, counts: Vec<u32>, center: [f32; 3], @@ -67,6 +67,14 @@ impl DesignerModels { } impl DesignerModel { + pub(super) fn uploaded(draws: Range<usize>, center: [f32; 3], radius: f32) -> Self { + Self { + draws, + counts: Vec::new(), + center, + radius, + } + } fn prepare(root: usize, scene: &mut StaticPreviewScene) -> Result<Option<Self>, String> { let source = scene.dynamic_component_geometry[root] .iter() @@ -151,7 +159,7 @@ impl DesignerModel { })) } - fn view(&self, elapsed_ms: u32, drawable: [f32; 2]) -> VulkanModelPreview { + pub(super) fn view(&self, elapsed_ms: u32, drawable: [f32; 2]) -> VulkanModelPreview { let yaw = elapsed_ms as f64 * f64::from(SPIN_RADIANS_PER_MS); let (sin_yaw, cos_yaw) = yaw.sin_cos(); let (sin_elevation, cos_elevation) = ELEVATION.sin_cos(); @@ -190,6 +198,7 @@ impl DesignerModel { }; VulkanModelPreview { ranges: self.draws.clone(), + draw_before: None, viewport, camera, eye, diff --git a/apps/fparkan-game/src/designer_projects.rs b/apps/fparkan-game/src/designer_projects.rs index 1a485fee..a5d3ddf3 100644 --- a/apps/fparkan-game/src/designer_projects.rs +++ b/apps/fparkan-game/src/designer_projects.rs @@ -1,18 +1,35 @@ //! The original designer's named Unit DAT files under the game root. +use fparkan_prototype::UnitDat; use fparkan_runtime::{ - is_saved_factory_project_name, restore_factory_design, Engine, FactoryPartChange, - StartingCockpit, + inspect_saved_factory_project, is_saved_factory_project_name, restore_factory_design, Engine, + FactoryPartChange, StartingCockpit, }; -use std::{fs, io, io::Write, path::Path}; +use fparkan_world::ObjectHandle; +use std::{fs, io, io::Write, path::Path, sync::Arc}; pub(super) const NAME_LIMIT: usize = 16; pub(super) struct SavedProject { pub(super) name: String, - pub(super) choice: Option<usize>, - pub(super) scheme: usize, - pub(super) changes: Vec<FactoryPartChange>, + pub(super) layout: SavedLayout, +} + +pub(super) enum SavedLayout { + Factory { + choice: Option<usize>, + scheme: usize, + changes: Vec<FactoryPartChange>, + }, + Preview { + project: UnitDat, + bytes: Arc<[u8]>, + }, +} + +pub(super) struct PreparedProjectModel { + pub(super) project: UnitDat, + pub(super) geometry: super::designer_geometry::DesignerGeometry, } pub(super) enum ProjectDialog { @@ -65,6 +82,7 @@ pub(super) fn browse_projects( directory: &Path, engine: &Engine, cockpit: StartingCockpit, + plant: Option<ObjectHandle>, choices: &[(usize, usize)], prepared: &[usize], ) -> io::Result<Vec<SavedProject>> { @@ -89,17 +107,30 @@ pub(super) fn browse_projects( .iter() .map(|&(_, scheme)| scheme) .chain(prepared.iter().copied()); - if let Some((scheme, changes)) = restore_factory_design(engine, cockpit, schemes, &bytes) { + let layout = if let Some((scheme, changes)) = + restore_factory_design(engine, cockpit, schemes, &bytes) + { let choice = choices .iter() .find_map(|&(choice, index)| (index == scheme).then_some(choice)); - projects.push(SavedProject { - name: name.to_owned(), + SavedLayout::Factory { choice, scheme, changes, - }); - } + } + } else if let Some(project) = inspect_saved_factory_project(engine, cockpit, plant, &bytes) + { + SavedLayout::Preview { + project, + bytes: bytes.into(), + } + } else { + continue; + }; + projects.push(SavedProject { + name: name.to_owned(), + layout, + }); } projects.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase())); Ok(projects) diff --git a/apps/fparkan-game/src/factory_menu.rs b/apps/fparkan-game/src/factory_menu.rs index 78226641..9d0a8dea 100644 --- a/apps/fparkan-game/src/factory_menu.rs +++ b/apps/fparkan-game/src/factory_menu.rs @@ -1,5 +1,6 @@ use super::designer_projects::{ - browse_projects, name_character, save_project, ProjectDialog, NAME_LIMIT, + browse_projects, name_character, save_project, PreparedProjectModel, ProjectDialog, + SavedLayout, NAME_LIMIT, }; #[cfg(windows)] use super::robot_designer::RobotDesignerPanel; @@ -15,12 +16,13 @@ use fparkan_assets::factory_projects::{ }; use fparkan_runtime::{ check_factory_design, factory_design_bytes, factory_part_variants, factory_project_components, - factory_saved_schemes, Engine, FactoryPartChange, + factory_saved_schemes, prepare_saved_factory_preview, Engine, FactoryPartChange, }; use fparkan_world::ObjectHandle; use std::{ ops::Range, path::{Path, PathBuf}, + sync::Arc, }; use winit::{ event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent}, @@ -55,6 +57,7 @@ pub(super) struct DesignerSession { pub(super) file_dialog: Option<ProjectDialog>, pub(super) file_status: Option<String>, pub(super) file_name: Option<String>, + pub(super) preview_project: Option<Arc<PreparedProjectModel>>, imported_scheme: Option<usize>, } @@ -141,6 +144,7 @@ impl FactoryMenu { file_dialog: None, file_status: None, file_name: None, + preview_project: None, imported_scheme: None, }; designer.point(self.cursor); @@ -163,6 +167,7 @@ impl FactoryMenu { designer.variants = None; designer.file_name = None; designer.imported_scheme = None; + designer.preview_project = None; designer.file_status = None; } DesignerAction::Send => { @@ -200,7 +205,7 @@ impl FactoryMenu { } } - fn choose_project_file(&mut self, clock_ms: u32) { + fn choose_project_file(&mut self, engine: &Engine, clock_ms: u32) { let Some(dialog) = self .designer .as_mut() @@ -217,20 +222,55 @@ impl FactoryMenu { return; }; let file = projects.remove(*first + row); - let slots = file.choice.map(|choice| self.slots_for(choice)); + let (choice, scheme, changes, model) = match file.layout { + SavedLayout::Factory { + choice, + scheme, + changes, + } => (choice, choice.is_none().then_some(scheme), changes, None), + SavedLayout::Preview { project, bytes } => { + let geometry = match prepare_saved_factory_preview(engine, &project, bytes) + .map_err(|error| error.to_string()) + .and_then(|assets| { + super::designer_geometry::DesignerGeometry::prepare(&project, &assets) + }) { + Ok(geometry) => geometry, + Err(error) => { + eprintln!( + "designer_project_geometry_failed file={:?} {error}", + file.name + ); + let designer = self.designer.as_mut().expect("the designer is open"); + designer.file_status = Some("Не удалось загрузить модель".into()); + designer.dirty = true; + return; + } + }; + ( + None, + None, + Vec::new(), + Some(Arc::new(PreparedProjectModel { project, geometry })), + ) + } + }; + let slots = choice.map(|choice| self.slots_for(choice)); let designer = self.designer.as_mut().expect("the designer is open"); - designer.selected = file - .choice + designer.selected = choice .zip(slots.as_ref()) .map(|(choice, slots)| choice - slots.start); if let Some(slots) = slots { designer.slots = slots; } - designer.imported_scheme = file.choice.is_none().then_some(file.scheme); - designer.changes = file.changes; + designer.imported_scheme = scheme; + designer.preview_project = model; + designer.changes = changes; designer.file_name = Some(file.name); designer.file_dialog = None; - designer.file_status = None; + designer.file_status = designer + .preview_project + .as_ref() + .map(|_| "Для заказа войдите в миссию заново".into()); designer.first_part = 0; designer.variants = None; designer.model_started_ms = clock_ms; @@ -568,9 +608,18 @@ impl StaticVulkanApp { designer.scroll_files(-y.signum() as isize); return true; } - if let Some(parts) = designer.active_scheme(&menu.choices).and_then(|scheme| { - factory_project_components(self.mission_engine.as_ref()?, scheme) - }) { + let parts = designer + .active_scheme(&menu.choices) + .and_then(|scheme| { + factory_project_components(self.mission_engine.as_ref()?, scheme) + }) + .or_else(|| { + designer + .preview_project + .as_ref() + .map(|model| model.project.records.as_slice()) + }); + if let Some(parts) = parts { let first_part = designer .first_part .saturating_add_signed(-y.signum() as isize) @@ -587,7 +636,9 @@ impl StaticVulkanApp { { if let Some(designer) = &menu.designer { if designer.file_dialog.is_some() { - menu.choose_project_file(self.simulation_time_ms); + if let Some(engine) = &self.mission_engine { + menu.choose_project_file(engine, self.simulation_time_ms); + } return true; } match designer.hover { @@ -623,6 +674,7 @@ impl StaticVulkanApp { &panel.units_directory, engine, cockpit, + factory, &choices, &prepared, ) { diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 475ed8b3..b8536c48 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -16,6 +16,7 @@ mod control_effects; use control_effects::advance_control_effect_instances; mod damage_visibility; mod debris; +mod designer_geometry; mod designer_projects; mod destruction_effects; mod factory_menu; @@ -27,6 +28,7 @@ mod mission_loading; mod mission_notices; mod mission_overlay; mod mission_pause; +mod model_mounts; mod motion_effects; mod player_collision; mod satellite_map; @@ -2686,17 +2688,9 @@ fn mounted_shadow_sphere( .then_some(ShadowComponentSphere { center, radius }) } -fn aggregate_shadow_caster( - id: u32, - native_kind: u32, - transform: LegacyIron3dEulerTransform, - scale: [f32; 3], - triangles: Vec<ShadowTriangle>, +fn aggregate_component_sphere( component_spheres: &[ShadowComponentSphere], -) -> Option<ShadowCaster> { - if triangles.is_empty() { - return None; - } +) -> Option<ShadowComponentSphere> { let weight = component_spheres .iter() .map(|sphere| sphere.radius) @@ -2714,15 +2708,37 @@ fn aggregate_shadow_caster( .iter() .map(|sphere| length3(sub3(sphere.center, aggregate_center)).unwrap_or(0.0) + sphere.radius) .fold(0.0, f32::max); - let max_scale = scale.iter().copied().fold(f32::NEG_INFINITY, f32::max); if !aggregate_center.iter().all(|value| value.is_finite()) || !radius.is_finite() || radius <= f32::EPSILON - || !max_scale.is_finite() - || max_scale <= 0.0 { return None; } + Some(ShadowComponentSphere { + center: aggregate_center, + radius, + }) +} + +fn aggregate_shadow_caster( + id: u32, + native_kind: u32, + transform: LegacyIron3dEulerTransform, + scale: [f32; 3], + triangles: Vec<ShadowTriangle>, + component_spheres: &[ShadowComponentSphere], +) -> Option<ShadowCaster> { + if triangles.is_empty() { + return None; + } + let ShadowComponentSphere { + center: aggregate_center, + radius, + } = aggregate_component_sphere(component_spheres)?; + let max_scale = scale.iter().copied().fold(f32::NEG_INFINITY, f32::max); + if !max_scale.is_finite() || max_scale <= 0.0 { + return None; + } // The native scale flag applies to the aggregate exactly once. The // mission Euler transform then rotates/translates that scaled sphere. let scaled_center = [ @@ -8309,89 +8325,17 @@ fn static_preview_mesh_and_materials( // geometry. Internal INTO components use controller/equipment // slots, whose `parent_or_link` values are not MSH node indices. // Do not ask the MSH hierarchy to resolve hidden internal parts. - let mount_pose = if should_render { - if let Some(tree) = tree.as_ref() { - let record = records.get(component_index).ok_or_else(|| { - format!("unit component {component_index} is outside decoded records") - })?; - let parent_index = tree[component_index].parent_index; - match parent_index { - None => None, - Some(parent_index) => { - let parent_visible = component_refs.get(parent_index).is_some_and( - |(parent_visual, _)| { - unit_component_is_visible( - parent_index, - parent_visual.source_type, - ) - }, - ); - if !parent_visible { - None - } else { - let parent_model = component_refs - .get(parent_index) - .and_then(|(_, model)| *model) - .ok_or_else(|| { - format!( - "unit component {component_index} parent {parent_index} has no model for mount socket" - ) - })?; - let parent_hierarchy = component_pose_buffers - .get(parent_index) - .and_then(Option::as_ref); - let parent_is_mounted = - component_mount_poses[parent_index].is_some(); - let socket = - usize::try_from(record.parent_or_link).map_err(|_| { - format!( - "unit component {component_index} has negative mount socket {}", - record.parent_or_link - ) - })?; - let parent_socket = match parent_hierarchy { - Some(hierarchy) if parent_is_mounted => { - node38_pose_relative_to_root_from_hierarchy( - hierarchy, socket, - ) - } - Some(hierarchy) => { - node38_pose_from_hierarchy(hierarchy, socket) - } - None if parent_is_mounted => node38_pose_relative_to_root( - &parent_model.validated, - static_animation_frame, - socket, - ), - None => node38_pose( - &parent_model.validated, - static_animation_frame, - socket, - ), - } - .ok_or_else(|| { - format!( - "unit component {component_index} mount socket {socket} is absent from parent {parent_index} (parent source={:?}, node_count={}, slots={}, animation={})", - parent_model.source, - parent_model.validated.node_count, - parent_model.validated.slots.len(), - parent_model.validated.animation.is_some(), - ) - })?; - let parent_root_pose = component_mount_poses[parent_index] - .unwrap_or(VulkanNodePose { - translation: [0.0; 3], - rotation: [0.0, 0.0, 0.0, 1.0], - }); - Some(compose_unit_pose(parent_root_pose, parent_socket)) - } - } - } - } else { - None - } - } else { - None + let mount_pose = match tree.as_deref().filter(|_| should_render) { + Some(tree) => model_mounts::initial_mount( + component_index, + records, + tree, + &component_refs, + &component_pose_buffers, + &component_mount_poses, + static_animation_frame, + )?, + None => None, }; if let Some(mount_pose) = mount_pose { component_mount_poses[component_index] = Some(mount_pose); diff --git a/apps/fparkan-game/src/model_mounts.rs b/apps/fparkan-game/src/model_mounts.rs new file mode 100644 index 00000000..331e616a --- /dev/null +++ b/apps/fparkan-game/src/model_mounts.rs @@ -0,0 +1,53 @@ +//! Initial AniMesh attachment transforms shared by placed and previewed units. + +use super::{ + compose_unit_pose, node38_pose, node38_pose_from_hierarchy, node38_pose_relative_to_root, + node38_pose_relative_to_root_from_hierarchy, unit_component_is_visible, NodePoseBuffer, + PreparedModel, PreparedVisual, VulkanNodePose, +}; +use fparkan_prototype::{UnitComponentRecord, UnitComponentTreeNode}; + +pub(super) fn initial_mount( + index: usize, + records: &[UnitComponentRecord], + tree: &[UnitComponentTreeNode], + components: &[(&PreparedVisual, Option<&PreparedModel>)], + poses: &[Option<NodePoseBuffer>], + mounts: &[Option<VulkanNodePose>], + animation_frame: Option<u16>, +) -> Result<Option<VulkanNodePose>, String> { + let Some(parent) = tree[index].parent_index else { + return Ok(None); + }; + let Some((visual, model)) = components.get(parent) else { + return Ok(None); + }; + if !unit_component_is_visible(parent, visual.source_type) { + return Ok(None); + } + let model = model.ok_or_else(|| { + format!("unit component {index} parent {parent} has no model for mount socket") + })?; + let link = records[index].parent_or_link; + let socket = usize::try_from(link) + .map_err(|_| format!("unit component {index} has negative mount socket {link}"))?; + let parent_mount = mounts[parent]; + let parent_socket = match (poses[parent].as_ref(), parent_mount.is_some()) { + (Some(hierarchy), true) => node38_pose_relative_to_root_from_hierarchy(hierarchy, socket), + (Some(hierarchy), false) => node38_pose_from_hierarchy(hierarchy, socket), + (None, true) => node38_pose_relative_to_root(&model.validated, animation_frame, socket), + (None, false) => node38_pose(&model.validated, animation_frame, socket), + }.ok_or_else(|| { + format!( + "unit component {index} mount socket {socket} is absent from parent {parent} (parent source={:?}, node_count={}, slots={}, animation={})", + model.source, model.validated.node_count, model.validated.slots.len(), model.validated.animation.is_some() + ) + })?; + Ok(Some(compose_unit_pose( + parent_mount.unwrap_or(VulkanNodePose { + translation: [0.0; 3], + rotation: [0.0, 0.0, 0.0, 1.0], + }), + parent_socket, + ))) +} diff --git a/apps/fparkan-game/src/robot_designer.rs b/apps/fparkan-game/src/robot_designer.rs index c53fef01..26436d94 100644 --- a/apps/fparkan-game/src/robot_designer.rs +++ b/apps/fparkan-game/src/robot_designer.rs @@ -1,6 +1,6 @@ use super::{ - designer_model::DesignerModels, - designer_projects::ProjectDialog, + designer_model::{DesignerModel, DesignerModels}, + designer_projects::{PreparedProjectModel, ProjectDialog}, factory_menu::{append_picture, picture_texture, FactoryMenu}, DirectoryVfs, EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer, }; @@ -9,12 +9,16 @@ use fparkan_assets::designer_screen::{ }; use fparkan_platform_winit::text::StringResources; use fparkan_runtime::{factory_design_parts, factory_project_components, Engine}; -use std::path::Path; +use std::{ + path::Path, + sync::{Arc, Weak}, +}; pub(super) struct RobotDesignerPanel { assets: DesignerScreen, background: EnvironmentGpuRange, models: DesignerModels, + uploaded: Option<(Weak<PreparedProjectModel>, DesignerModel)>, range: EnvironmentGpuRange, } @@ -52,6 +56,7 @@ impl RobotDesignerPanel { assets, background, models, + uploaded: None, range, }) } @@ -79,18 +84,61 @@ impl RobotDesignerPanel { )) }); self.models.draw(renderer, active, viewport)?; + if let Some((project, elapsed)) = menu.as_ref().and_then(|menu| { + let designer = menu.designer.as_ref()?; + Some(( + designer.preview_project.as_ref()?, + clock_ms.saturating_sub(designer.model_started_ms), + )) + }) { + let source = Arc::downgrade(project); + if !self + .uploaded + .as_ref() + .is_some_and(|(previous, _)| Weak::ptr_eq(previous, &source)) + { + let geometry = &project.geometry; + let ranges = renderer + .upload_preview_mesh(&geometry.mesh, &geometry.materials) + .map_err(|error| error.to_string())?; + self.uploaded = Some(( + source, + DesignerModel::uploaded(ranges, geometry.center, geometry.radius), + )); + } + let mut view = self + .uploaded + .as_ref() + .expect("uploaded designer mesh") + .1 + .view(elapsed, viewport); + view.draw_before = Some(self.range.range_index); + renderer + .set_model_preview(Some(view)) + .map_err(|error| error.to_string())?; + } if let Some(menu) = menu { if let Some(designer) = menu.designer.as_mut().filter(|view| view.dirty) { - let project = designer.active_scheme(&menu.choices).and_then(|scheme| { - let parts = factory_project_components(engine?, scheme)?; - let slot = designer.selected.unwrap_or(designer.slots.len()); - let name = designer.file_name.as_deref().or_else(|| { - designer - .selected - .map(|slot| menu.choices[designer.slots.start + slot].name.as_str()) - })?; - Some((slot, name, parts)) - }); + let buildable = designer.active_scheme(&menu.choices); + let project = buildable + .and_then(|scheme| { + let parts = factory_project_components(engine?, scheme)?; + let slot = designer.selected.unwrap_or(designer.slots.len()); + let name = designer.file_name.as_deref().or_else(|| { + designer + .selected + .map(|slot| menu.choices[designer.slots.start + slot].name.as_str()) + })?; + Some((slot, name, parts)) + }) + .or_else(|| { + let project = designer.preview_project.as_ref()?; + Some(( + designer.slots.len(), + designer.file_name.as_deref()?, + project.project.records.as_slice(), + )) + }); let modified = project .filter(|_| !designer.changes.is_empty()) .map(|(_, _, parts)| factory_design_parts(parts, &designer.changes)) @@ -123,6 +171,7 @@ impl RobotDesignerPanel { hover: designer.hover, file_dialog, file_status: designer.file_status.as_deref(), + buildable: buildable.is_some(), })?; renderer .update_material_texture( diff --git a/crates/fparkan-assets/src/designer_screen.rs b/crates/fparkan-assets/src/designer_screen.rs index 3b9399f6..2a6fd7f1 100644 --- a/crates/fparkan-assets/src/designer_screen.rs +++ b/crates/fparkan-assets/src/designer_screen.rs @@ -98,6 +98,8 @@ pub struct DesignerPicture<'a> { pub file_dialog: Option<DesignerFileView<'a>>, /// Result of the last file operation. pub file_status: Option<&'a str>, + /// Whether the displayed model is connected to a production scheme. + pub buildable: bool, } /// View of the name editor or the current page of saved projects. @@ -201,10 +203,12 @@ impl DesignerScreen { self.paint_row(&mut image, label, 9, 170, row, tint)?; } } - sprite(&mut image, &self.send_frame, SEND, [255; 3]); - sprite(&mut image, &self.send, [201, 450, 225, 474], [255; 3]); - sprite(&mut image, &self.send_frame, SAVE, [255; 3]); - sprite(&mut image, &self.save, [278, 450, 302, 474], [255; 3]); + if view.buildable { + sprite(&mut image, &self.send_frame, SEND, [255; 3]); + sprite(&mut image, &self.send, [201, 450, 225, 474], [255; 3]); + sprite(&mut image, &self.send_frame, SAVE, [255; 3]); + sprite(&mut image, &self.save, [278, 450, 302, 474], [255; 3]); + } } sprite(&mut image, &self.load_frame, LOAD, [255; 3]); sprite(&mut image, &self.load, [308, 450, 332, 474], [255; 3]); diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index fa2bfb33..2381c1ab 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -215,7 +215,9 @@ pub use robot_designer::{ check_factory_design, factory_design_bytes, factory_design_parts, load_gameplay_mission, load_gameplay_mission_with_build_parts, restore_factory_design, FactoryPartChange, }; -pub use saved_factory_projects::is_saved_factory_project_name; +pub use saved_factory_projects::{ + inspect_saved_factory_project, is_saved_factory_project_name, prepare_saved_factory_preview, +}; pub use unit_combat::{ autonomous_firing_effect_phases, AutoDemoCombatEvent, AutoDemoProjectileType, FiringEffectInstance, diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index 3502c45d..0817cfb8 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -467,7 +467,19 @@ pub fn factory_saved_schemes( plant: Option<ObjectHandle>, ) -> Result<Vec<usize>, EngineError> { let (mission, production) = loaded_production(engine)?; - let index = match plant { + let index = player_factory_index(engine, cockpit, plant)?; + Ok(schemes_for_plant(mission, production, index) + .filter_map(|(scheme, _)| production.saved_schemes.contains(&scheme).then_some(scheme)) + .collect()) +} + +pub(super) fn player_factory_index( + engine: &Engine, + cockpit: StartingCockpit, + plant: Option<ObjectHandle>, +) -> Result<usize, EngineError> { + let (mission, production) = loaded_production(engine)?; + Ok(match plant { Some(plant) => { let owner = player_owner(&engine.world, cockpit)?; owned_factories(&engine.world, mission, production, owner) @@ -478,10 +490,7 @@ pub fn factory_saved_schemes( })? } None => factory_at_communicator(&engine.world, mission, production, cockpit)?.0, - }; - Ok(schemes_for_plant(mission, production, index) - .filter_map(|(scheme, _)| production.saved_schemes.contains(&scheme).then_some(scheme)) - .collect()) + }) } fn recent_schemes_for_plant<'a>( @@ -929,7 +938,7 @@ fn set_factory_power( Ok(()) } -fn free_duration_ms(plant: &[u8; 32], robot: &[u8; 32]) -> Option<u32> { +pub(super) fn free_duration_ms(plant: &[u8; 32], robot: &[u8; 32]) -> Option<u32> { // shortcut: stock chassis and factory keys supply sizes until the // calculated capacity and assembled-scheme descriptors are wired. let plant = plant.split(|&byte| byte == 0).next()?; diff --git a/crates/fparkan-runtime/src/saved_factory_projects.rs b/crates/fparkan-runtime/src/saved_factory_projects.rs index 907a45d1..b785f23d 100644 --- a/crates/fparkan-runtime/src/saved_factory_projects.rs +++ b/crates/fparkan-runtime/src/saved_factory_projects.rs @@ -4,15 +4,19 @@ use crate::{ boarding::WARBOT_CLASS, build_prototype_graph_report, extend_graph_report_with_visual_dependencies, normalize_engine_path, - production::scheme_cost, + production::{ + clan_scheme_cost, free_duration_ms, player_factory_index, player_owner, scheme_cost, + }, research::load_technology_table, resource_name, robot_designer::{mission_player, restore_mounts}, - AssetManager, MissionDocument, ResourceRepository, PROTOTYPE_TYPE_EXTO, + AssetManager, CachedResourceRepository, Engine, EngineError, MissionAssets, MissionDocument, + ResourceRepository, StartingCockpit, PROTOTYPE_TYPE_EXTO, }; use fparkan_path::NormalizedPath; -use fparkan_prototype::{decode_unit_dat, unit_component_tree}; +use fparkan_prototype::{decode_unit_dat, unit_component_tree, UnitDat}; use fparkan_vfs::{MemoryVfs, OverlayVfs, Vfs, VfsError}; +use fparkan_world::ObjectHandle; use std::sync::Arc; /// A named Unit DAT from the original designer directory. @@ -24,6 +28,49 @@ pub fn is_saved_factory_project_name(filename: &str) -> bool { .any(|prefix| lower.starts_with(prefix)) } +/// Reads a saved robot if its size and equipment are available to this factory. +pub fn inspect_saved_factory_project( + engine: &Engine, + cockpit: StartingCockpit, + plant: Option<ObjectHandle>, + bytes: &[u8], +) -> Option<UnitDat> { + let project = decode_unit_dat(bytes).ok()?; + if !warbot_header(project.header_opaque) { + return None; + } + let mission = engine.loaded.as_ref()?; + let index = player_factory_index(engine, cockpit, plant).ok()?; + let chassis = &project.records.first()?.resource_raw; + free_duration_ms( + &mission.object_drafts[index] + .unit_components + .first()? + .resource_raw, + chassis, + )?; + let owner = player_owner(&engine.world, cockpit).ok()?; + clan_scheme_cost(&engine.services.vfs, mission, owner, &project.records).ok()?; + Some(project) +} + +/// Resolves the model and materials of an inspected project without changing the mission. +pub fn prepare_saved_factory_preview( + engine: &Engine, + project: &UnitDat, + bytes: Arc<[u8]>, +) -> Result<MissionAssets, EngineError> { + let vfs = engine.services.vfs.clone().ok_or(EngineError::MissingVfs)?; + let manager = AssetManager::new(CachedResourceRepository::new(vfs.clone())); + let path = normalize_engine_path("project preview", "fparkan/preview-project.dat")?; + prepare_geometry(&vfs, &manager, &path, project, bytes) +} + +fn warbot_header(header: [u8; 8]) -> bool { + let flags = WARBOT_CLASS.to_le_bytes(); + header[..4] == 0xf0f1_u32.to_le_bytes() && header[4..] == flags +} + #[cfg(test)] mod tests { use super::*; @@ -86,6 +133,11 @@ mod tests { let (scheme, changes) = restore_factory_design(&engine, cockpit, saved, &bytes).unwrap(); assert!(changes.is_empty()); assert!(factory_project_schemes(&engine).any(|index| index == scheme)); + let roots = loaded_mission_object_drafts(&engine).unwrap().len(); + let loose = inspect_saved_factory_project(&engine, cockpit, Some(plant), &bytes).unwrap(); + let preview = prepare_saved_factory_preview(&engine, &loose, bytes.clone()).unwrap(); + assert_eq!(preview.visuals_for_object(0).len(), loose.records.len()); + assert_eq!(loaded_mission_object_drafts(&engine).unwrap().len(), roots); let expected = decode_unit_dat(&bytes).unwrap().records; assert_eq!( factory_project_components(&engine, scheme).unwrap(), @@ -185,91 +237,24 @@ pub(super) fn prepare<R: ResourceRepository>( let Ok(project) = decode_unit_dat(&bytes) else { continue; }; - let mut header = [0; 8]; - header[..4].copy_from_slice(&0xf0f1_u32.to_le_bytes()); - header[4..].copy_from_slice(&WARBOT_CLASS.to_le_bytes()); // A part may become known during the mission. The designer checks // actual research again when it lists the file. - if project.header_opaque != header + if !warbot_header(project.header_opaque) || scheme_cost(&project.records, &research, |_| true).is_err() || shapes.iter().any(|base| { - base.header_opaque == header + base.header_opaque == project.header_opaque && restore_mounts(&base.records, &project.records).is_some() }) { continue; } - let mut candidate = MemoryVfs::default(); - candidate.insert(path.clone(), bytes.clone()); - let source = OverlayVfs::from_layers(vec![Arc::new(candidate), vfs.clone()]); - let (mut graph, prototypes, mut report) = build_prototype_graph_report( - manager.repository(), - &source, - &[resource_name(path.as_bytes())], - ); - extend_graph_report_with_visual_dependencies( - manager.repository(), - &mut report, - &mut graph, - &prototypes, - ); - if !report.is_success() { + if let Err(error) = prepare_geometry(&vfs, manager, &path, &project, bytes.clone()) { eprintln!( - "factory_project_geometry_unavailable path={}", + "factory_project_geometry_unavailable path={} {error}", path.as_str() ); continue; } - let assets = match manager - .prepare_mission_assets(&graph.root_prototype_request_spans, &prototypes) - { - Ok(assets) => assets, - Err(error) => { - eprintln!( - "factory_project_geometry_unavailable path={} {error}", - path.as_str() - ); - continue; - } - }; - let tree = unit_component_tree(&project.records).expect("validated by scheme cost"); - let model_nodes = assets - .visuals_for_object(0) - .iter() - .map(|id| { - assets - .visual_by_id(*id) - .map(|visual| (visual.source_type, visual.model_nodes)) - }) - .collect::<Vec<_>>(); - let mounts_available = model_nodes.len() == project.records.len() - && matches!(model_nodes.first(), Some(Some((_, nodes))) if *nodes != 0) - && model_nodes - .iter() - .enumerate() - .skip(1) - .all(|(index, visual)| { - let Some((kind, nodes)) = visual else { - return false; - }; - if *kind != Some(PROTOTYPE_TYPE_EXTO) { - return true; - } - let Some(parent) = tree[index].parent_index else { - return false; - }; - let Some((parent_kind, parent_nodes)) = model_nodes[parent] else { - return false; - }; - *nodes != 0 - && (parent == 0 || parent_kind == Some(PROTOTYPE_TYPE_EXTO)) - && usize::try_from(project.records[index].parent_or_link) - .is_ok_and(|socket| socket < parent_nodes) - }); - if !mounts_available { - eprintln!("factory_project_mount_unavailable path={}", path.as_str()); - continue; - } snapshot.insert(path.clone(), bytes); projects.push(path); shapes.push(project); @@ -283,3 +268,80 @@ pub(super) fn prepare<R: ResourceRepository>( ) } } + +fn prepare_geometry<R: ResourceRepository>( + vfs: &Arc<dyn Vfs>, + manager: &AssetManager<R>, + path: &NormalizedPath, + project: &UnitDat, + bytes: Arc<[u8]>, +) -> Result<MissionAssets, EngineError> { + let invalid = |message: &str| EngineError::Production(message.into()); + let mut candidate = MemoryVfs::default(); + candidate.insert(path.clone(), bytes); + let source = OverlayVfs::from_layers(vec![Arc::new(candidate), vfs.clone()]); + let (mut graph, prototypes, mut report) = build_prototype_graph_report( + manager.repository(), + &source, + &[resource_name(path.as_bytes())], + ); + extend_graph_report_with_visual_dependencies( + manager.repository(), + &mut report, + &mut graph, + &prototypes, + ); + if !report.is_success() { + return Err(EngineError::PrototypeGraph { + failures: report.failures, + }); + } + if graph.root_unit_components.first() != Some(&project.records) { + return Err(invalid("project preview records do not match Unit DAT")); + } + let assets = manager + .prepare_mission_assets(&graph.root_prototype_request_spans, &prototypes) + .map_err(|source| EngineError::AssetPreparation { + mission: path.as_str().into(), + source, + })?; + let tree = unit_component_tree(&project.records) + .map_err(|error| EngineError::Production(error.to_string()))?; + let model_nodes = assets + .visuals_for_object(0) + .iter() + .map(|id| { + assets + .visual_by_id(*id) + .map(|visual| (visual.source_type, visual.model_nodes)) + }) + .collect::<Vec<_>>(); + let mounts_available = model_nodes.len() == project.records.len() + && matches!(model_nodes.first(), Some(Some((_, nodes))) if *nodes != 0) + && model_nodes + .iter() + .enumerate() + .skip(1) + .all(|(index, visual)| { + let Some((kind, nodes)) = visual else { + return false; + }; + if *kind != Some(PROTOTYPE_TYPE_EXTO) { + return true; + } + let Some(parent) = tree[index].parent_index else { + return false; + }; + let Some((parent_kind, parent_nodes)) = model_nodes[parent] else { + return false; + }; + *nodes != 0 + && (parent == 0 || parent_kind == Some(PROTOTYPE_TYPE_EXTO)) + && usize::try_from(project.records[index].parent_or_link) + .is_ok_and(|socket| socket < parent_nodes) + }); + if !mounts_available { + return Err(invalid("project has an unavailable model mount")); + } + Ok(assets) +} diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 9a61a71d..ba78b00f 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -3824,9 +3824,14 @@ RVA `0x555b0` и `0x56f50`). FParkan сохраняет выбранные заÐ вместе с заводскими резервами. Совпадающие деревья креплений с разным внутренним оборудованием используют одну подготовленную геометрию. Список готовых проектов завода пополняется после передачи проекта из -конструктора. Файл, добавленный во время миссии, можно открыть сразу, -если геометрия уже подготовлена. Для новой геометрии требуется заново -войти в миссию. +конструктора. Файл с новой геометрией, добавленный во время миссии, тоже +можно открыть и осмотреть. Движок разрешает крепления по тем же узлам +AniMesh, что и для размещённых на карте машин. Vulkan загружает модель +в отдельные буферы и рисует её между фоном и надписями конструктора. +Камера получает границы сборки из радиусов корпуса и навесных частей, +как и при просмотре подготовленного проекта. +Для заказа такой модели пока требуется заново войти в миссию, чтобы +подготовить заводские резервы. На коммуникаторе B показывает схемы этого завода. При запуске можно указать одну схему через `--build-scheme`. Повторяемый параметр |
