aboutsummaryrefslogtreecommitdiff
path: root/adapters/fparkan-render-vulkan/src/ffi/scene_append.rs
blob: cffcb3535e1f88fad460b4f09ec2ba1e3096a12c (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
//! Installing additional batches in the shared world buffers during a mission.

use super::preview_mesh::{detail_texture, material_texture_sources, overlay_texture};
use super::{
    create_static_mesh_index_buffer, create_static_mesh_vertex_buffer, create_static_texture_image,
    create_swapchain_resources, destroy_allocated_buffer, destroy_allocated_image,
    destroy_swapchain_resources, resolve_draw_texture_indices, sorted_world_draw_order,
    validate_geometry_upload, vk, RollbackOnDrop, VulkanSmokeRenderer, VulkanSmokeRendererError,
    VulkanStaticMaterial,
};
use crate::ffi::VulkanStaticMesh;

impl VulkanSmokeRenderer {
    /// Extends the world scene while preserving existing draw and material handles.
    /// Transient geometry past `scratch_start` is regenerated by the caller's
    /// next frame. The separate model viewport can be uploaded again when needed.
    pub fn append_scene_mesh(
        &mut self,
        mesh: &VulkanStaticMesh,
        materials: &[VulkanStaticMaterial],
        scratch_start: usize,
        draw_before: usize,
    ) -> Result<(), VulkanSmokeRendererError> {
        let invalid = |context| VulkanSmokeRendererError::InvalidStaticMesh { context };
        validate_geometry_upload(
            &mesh.vertices,
            &mesh.indices,
            &mesh.draw_ranges,
            &[],
            self.vertex_count,
            self.index_capacity,
        )?;
        let (range_start, material_start) = self.preview_mesh.as_ref().map_or(
            (self.draw_ranges.len(), self.material_alphas.len()),
            |preview| (preview.range_start, preview.material_start),
        );
        if draw_before >= range_start
            || scratch_start > mesh.indices.len()
            || mesh.draw_ranges.len() <= range_start
            || self
                .scene_append_order
                .is_some_and(|(_, anchor)| anchor != draw_before)
        {
            return Err(invalid("invalid scene extension boundaries"));
        }
        let added = &mesh.draw_ranges[range_start..];
        let local_materials = resolve_draw_texture_indices(added, materials).map_err(invalid)?;
        let detail = detail_texture();
        let overlay = overlay_texture();
        let (sources, new_slots) = material_texture_sources(materials, &detail, &overlay);
        let mut states = self.draw_range_base_pipeline_states[..range_start].to_vec();
        states.extend(added.iter().map(|range| range.pipeline_state));
        let (vertex, index, images, slots, resources) = {
            let instance = self.instance_ref()?;
            let device = self.device_ref()?;
            // SAFETY: Replacing resources requires all work on the live device to finish.
            unsafe { device.device().device_wait_idle() }.map_err(|result| {
                VulkanSmokeRendererError::VulkanOperation {
                    context: "vkDeviceWaitIdle(world scene extension)",
                    result,
                }
            })?;
            let vertex = RollbackOnDrop::new(
                create_static_mesh_vertex_buffer(instance, device, mesh)?,
                |buffer| destroy_allocated_buffer(device, &buffer),
            );
            let index = RollbackOnDrop::new(
                create_static_mesh_index_buffer(instance, device, mesh)?,
                |buffer| destroy_allocated_buffer(device, &buffer),
            );
            let mut images =
                RollbackOnDrop::new(Vec::with_capacity(sources.len()), |images: Vec<_>| {
                    for image in images {
                        destroy_allocated_image(device, &image);
                    }
                });
            let pending = images.value.as_mut().expect("uncommitted scene textures");
            for source in sources {
                pending.push(create_static_texture_image(
                    instance,
                    device,
                    self.command_pool,
                    source,
                )?);
            }
            let (mut views, mut slots) = self.material_image_views(None);
            let image_offset = views.len();
            views.extend(pending.iter().map(|image| image.view));
            slots.extend(new_slots.into_iter().map(|slot| image_offset + slot));
            let resources = create_swapchain_resources(
                instance,
                device,
                self.swapchain_ref()?,
                self.command_pool,
                self.pipeline_cache,
                vertex.value.as_ref().expect("uncommitted scene vertices"),
                index.value.as_ref().expect("uncommitted scene indices"),
                &views,
                &slots,
                &states,
                mesh.draw_ranges
                    .iter()
                    .any(|range| range.terrain_reflection),
                self.depth_request,
                false,
            )?;
            (
                vertex.commit(),
                index.commit(),
                images.commit(),
                slots,
                resources,
            )
        };

        let old_resources = self.swapchain_resources.replace(resources);
        let old_vertices = self.vertex_buffer.replace(vertex);
        let old_indices = self.index_buffer.replace(index);
        let old_preview = self.preview_mesh.take();
        let device = self.device_ref()?;
        if let Some(resources) = old_resources {
            destroy_swapchain_resources(device, self.command_pool, resources);
        }
        for buffer in [old_vertices, old_indices].into_iter().flatten() {
            destroy_allocated_buffer(device, &buffer);
        }
        if let Some(preview) = old_preview {
            preview.destroy(device);
        }
        self.model_preview = None;
        self.images_in_flight.fill(vk::Fence::null());
        self.last_readback_image_index = None;
        self.textures.extend(images);
        self.texture_slot_indices = slots;
        self.vertex_count = mesh.vertices.len();
        self.index_capacity = mesh.indices.len();
        self.draw_ranges.truncate(range_start);
        for (current, original) in self.draw_ranges.iter_mut().zip(&mesh.draw_ranges) {
            if current.first_index as usize >= scratch_start {
                current.first_index = original.first_index;
                current.index_count = 0;
            }
        }
        self.draw_ranges
            .extend(added.iter().map(|range| crate::ffi::VulkanStaticDrawRange {
                index_count: 0,
                ..*range
            }));
        self.replace_draw_state(range_start, material_start, added, local_materials);
        self.replace_material_state(material_start, materials);
        self.draw_range_base_pipeline_states = states;
        self.scene_append_order
            .get_or_insert((range_start, draw_before));
        self.material_specular_dirty = true;
        self.draw_order_dirty = true;
        Ok(())
    }

    /// Recomputes the stable command-recording order. Without explicit
    /// backgrounds, opaque world ranges followed by the sorted transparent
    /// world ranges replace the existing world slots. With explicit
    /// backgrounds, opaque ranges compact into the world slots and sorted
    /// transparent ranges are inserted after the last background; unrelated
    /// fixed ranges keep relative order but may shift slots. The transparent
    /// queue matches the native descending key comparator.
    pub(super) fn rebuild_draw_order(&mut self) {
        let mut seed_order = (0..self.draw_ranges.len()).collect::<Vec<_>>();
        if let Some((start, before)) = self.scene_append_order {
            let end = self
                .preview_mesh
                .as_ref()
                .map_or(seed_order.len(), |preview| preview.range_start);
            seed_order[before..end].rotate_right(end - start);
        }
        self.draw_order = sorted_world_draw_order(
            seed_order,
            &self.draw_ranges,
            &self.draw_range_world_queue,
            &self.draw_range_sort_keys,
            &self.world_transparent_background_ranges,
        );
    }
}