diff options
Diffstat (limited to 'adapters/fparkan-render-vulkan/src')
4 files changed, 372 insertions, 76 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<_>>(); |
