use core::{hash::Hash, num::NonZeroU32}; use bevy_asset::AssetId; use bevy_ecs::{ entity::{Entity, EntityHashMap, EntityHashSet}, query::{Changed, Or, With}, system::Query, }; use bevy_math::{Affine3, Affine3Ext, Vec4}; use bevy_mesh::Mesh; use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial}; use bevy_platform::collections::HashMap; use bevy_render::{ impl_atomic_pod, mesh::allocator::MeshAllocator, render_resource::{ AtomicPod, AtomicSparseBufferVec, Buffer, BufferId, BufferUsages, TextureId, TextureView, }, }; use bevy_tape_load::{Tape, render::allocator::TapeAllocator}; use bevy_transform::components::GlobalTransform; use bevy_utils::once; use bytemuck::{Pod, Zeroable}; use tracing::{info_span, warn}; use wgpu_types::TextureViewDescriptor; use super::{ MeshBlasKey, MeshBlasManager, MeshBlasOpacity, RaytracingMesh3d, RaytracingSceneBindings, Tape3d, TapeBlasKey, TapeBlasManager, TapeBlasOpacity, allocator::{IndexAllocator, RetainedBindingArray}, assets::AssetState, lights::{GpuLightSource, LightSourceId, LightState}, }; pub const MAX_MESH_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap(); pub const MAX_TAPE_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap(); pub const MAX_SPATIAL_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5000).unwrap(); #[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)] #[repr(C)] pub struct GpuInstanceGeometryIds { vertex_buffer_id: u32, vertex_buffer_offset: u32, index_buffer_id: u32, index_buffer_offset: u32, triangle_count: u32, } #[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)] #[repr(C)] pub struct GpuInstanceTapeIds { aabb_buffer_id: u32, aabb_buffer_offset: u32, aabb_count: u32, spatial_texture_id: u32, metadata_buffer_id: u32, metadata_buffer_offset: u32, } /// A world-from-local affine transform, stored transposed as three rows. #[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)] #[repr(C)] pub struct GpuTransform([Vec4; 3]); impl GpuTransform { /// The three rows as the flat row-major 3x4 a [`TlasInstance`] wants. /// /// [`TlasInstance`]: bevy_render::render_resource::TlasInstance fn rows(self) -> [f32; 12] { bytemuck::cast(self) } } /// The device address of a slot's acceleration structure. Zero marks an /// inactive slot. #[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)] #[repr(transparent)] pub struct GpuBlasRef(u64); impl GpuBlasRef { const NONE: Self = Self(0); } impl_atomic_pod!(GpuInstanceGeometryIds, GpuInstanceGeometryIdsBlob); impl_atomic_pod!(GpuInstanceTapeIds, GpuInstanceTapeIdsBlob); impl_atomic_pod!(GpuTransform, GpuTransformBlob); impl_atomic_pod!(GpuBlasRef, GpuBlasRefBlob); fn storage_buffer(label: &str) -> AtomicSparseBufferVec { AtomicSparseBufferVec::new(BufferUsages::STORAGE, label.into()) } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum Object { Mesh(AssetId), Tape(AssetId), } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum BlasKey { Mesh(MeshBlasKey), Tape(TapeBlasKey), } type MeshBuffers = (BufferId, BufferId); type TapeBuffers = (BufferId, BufferId, TextureId); pub enum Buffers { Mesh(MeshBuffers), Tape(TapeBuffers), } impl Buffers { fn as_mesh(self) -> MeshBuffers { match self { Buffers::Mesh(b) => b, Buffers::Tape(_) => unreachable!(), } } fn as_tape(self) -> TapeBuffers { match self { Buffers::Mesh(_) => unreachable!(), Buffers::Tape(b) => b, } } } /// Everything tracked per raytracing instance. #[derive(Clone, Copy)] struct MeshInstance { slot: u32, mesh: AssetId, material: AssetId, opacity: MeshBlasOpacity, buffers: Option, } /// Everything tracked per raytracing instance. #[derive(Clone, Copy)] struct TapeInstance { slot: u32, tape: AssetId, material: AssetId, opacity: TapeBlasOpacity, buffers: Option, } impl MeshInstance { fn blas_key(&self) -> MeshBlasKey { MeshBlasKey { mesh: self.mesh, opacity: self.opacity, } } } impl TapeInstance { fn blas_key(&self) -> TapeBlasKey { TapeBlasKey { tape: self.tape, opacity: self.opacity, } } } #[derive(Clone, Copy)] enum Instance { Mesh(MeshInstance), Tape(TapeInstance), } impl Instance { fn get_key(&self) -> BlasKey { match self { Instance::Mesh(mesh_instance) => BlasKey::Mesh(mesh_instance.blas_key()), Instance::Tape(tape_instance) => BlasKey::Tape(tape_instance.blas_key()), } } fn get_slot(&self) -> u32 { match self { Instance::Mesh(mesh_instance) => mesh_instance.slot, Instance::Tape(tape_instance) => tape_instance.slot, } } fn get_material(&self) -> AssetId { match self { Instance::Mesh(mesh_instance) => mesh_instance.material, Instance::Tape(tape_instance) => tape_instance.material, } } fn get_buffers(&self) -> Option { match self { Instance::Mesh(mesh_instance) => mesh_instance.buffers.map(|b| Buffers::Mesh(b)), Instance::Tape(tape_instance) => tape_instance.buffers.map(|b| Buffers::Tape(b)), } } fn get_object(&self) -> Object { match self { Instance::Mesh(mesh_instance) => Object::Mesh(mesh_instance.mesh), Instance::Tape(tape_instance) => Object::Tape(tape_instance.tape), } } fn new( slot: u32, object: Object, material: AssetId, buffers: Option, ) -> Self { match object { Object::Mesh(mesh) => Instance::Mesh(MeshInstance { slot, mesh, material, opacity: MeshBlasOpacity::Opaque, buffers: buffers.map(Buffers::as_mesh), }), Object::Tape(tape) => Instance::Tape(TapeInstance { slot, tape, material, opacity: TapeBlasOpacity::Opaque, buffers: buffers.map(Buffers::as_tape), }), } } fn set_slot(&mut self, slot: u32) { match self { Instance::Mesh(mesh_instance) => mesh_instance.slot = slot, Instance::Tape(tape_instance) => tape_instance.slot = slot, } } fn set_material(&mut self, material: AssetId) { match self { Instance::Mesh(mesh_instance) => mesh_instance.material = material, Instance::Tape(tape_instance) => tape_instance.material = material, } } fn set_buffers(&mut self, buffers: Option) { match self { Instance::Mesh(mesh_instance) => mesh_instance.buffers = buffers.map(Buffers::as_mesh), Instance::Tape(tape_instance) => tape_instance.buffers = buffers.map(Buffers::as_tape), } } fn get_shared(&self) -> (u32, AssetId, Option) { (self.get_slot(), self.get_material(), self.get_buffers()) } } /// Stable slots, reverse dependency indices and GPU data owned by raytracing /// instances. pub struct InstanceState { pub vertex_buffers: RetainedBindingArray, pub index_buffers: RetainedBindingArray, pub aabb_buffers: RetainedBindingArray, pub tape_metadata_buffers: RetainedBindingArray, pub spatial_textures: RetainedBindingArray, pub transforms: AtomicSparseBufferVec, pub previous_frame_transforms: AtomicSparseBufferVec, pub geometry_ids: AtomicSparseBufferVec, pub tape_ids: AtomicSparseBufferVec, pub material_ids: AtomicSparseBufferVec, pub blas_refs: AtomicSparseBufferVec, pub slots: IndexAllocator, /// Slab buffer references dropped this frame, released next frame since the /// previous frame's TLAS can still reach them through `geometry_ids`. retired_mesh_buffers: Vec, retired_tape_buffers: Vec, records: EntityHashMap, pub live_count: u32, pub pending_refresh: EntityHashSet, object_instances: HashMap, pub material_instances: HashMap, EntityHashSet>, } impl InstanceState { pub fn new() -> Self { Self { vertex_buffers: RetainedBindingArray::new(), index_buffers: RetainedBindingArray::new(), aabb_buffers: RetainedBindingArray::new(), tape_metadata_buffers: RetainedBindingArray::new(), spatial_textures: RetainedBindingArray::new(), transforms: storage_buffer("solari_transforms"), previous_frame_transforms: storage_buffer("solari_previous_frame_transforms"), geometry_ids: storage_buffer("solari_geometry_ids"), tape_ids: storage_buffer("solari_tape_ids"), material_ids: storage_buffer("solari_material_ids"), blas_refs: storage_buffer("solari_blas_refs"), slots: IndexAllocator::new(), retired_mesh_buffers: Vec::new(), retired_tape_buffers: Vec::new(), records: EntityHashMap::default(), live_count: 0, pending_refresh: EntityHashSet::default(), object_instances: HashMap::default(), material_instances: HashMap::default(), } } /// Every drawable instance's slot, mesh and world-from-local transform. /// /// Only the `wgpu-core` TLAS build path needs this, to fill in the instance /// descriptors that the raw path sets up on the GPU. Slots with a null /// acceleration structure reference are not currently drawable, and are /// left out. pub fn drawable(&self) -> impl Iterator + '_ { self.records.values().filter_map(|instance| { let slot = instance.get_slot(); (self.blas_refs.get(slot) != GpuBlasRef::NONE) .then(|| (slot, instance.get_key(), self.transforms.get(slot).rows())) }) } /// Queues every instance using `material_id` to be re-resolved. pub fn invalidate_material(&mut self, material_id: AssetId) { if let Some(instances) = self.material_instances.get(&material_id) { self.pending_refresh.extend(instances.iter().copied()); } } } pub type MeshInstanceQueryData<'w> = ( &'w RaytracingMesh3d, &'w MeshMaterial3d, &'w GlobalTransform, &'w PreviousGlobalTransform, ); pub type TapeInstanceQueryData<'w> = ( &'w Tape3d, &'w MeshMaterial3d, &'w GlobalTransform, &'w PreviousGlobalTransform, ); pub enum InstanceQueryData<'w> { Mesh(MeshInstanceQueryData<'w>), Tape(TapeInstanceQueryData<'w>), } pub type ChangedMeshInstanceFilter = ( With, Or<( Changed, Changed>, )>, ); pub type ChangedTapeInstanceFilter = ( With, Or<(Changed, Changed>)>, ); /// The scene state an instance resolves its GPU data against. pub struct InstanceInputs<'a> { pub assets: &'a AssetState, pub mesh_blas_manager: &'a MeshBlasManager, pub mesh_allocator: &'a MeshAllocator, pub tape_blas_manager: &'a TapeBlasManager, pub tape_allocator: &'a TapeAllocator, } fn unlink(map: &mut HashMap, key: &K, entity: Entity) { let now_empty = map.get_mut(key).is_some_and(|instances| { instances.remove(&entity); instances.is_empty() }); if now_empty { map.remove(key); } } fn relink( map: &mut HashMap, entity: Entity, previous: Option, key: K, ) { if previous == Some(key) { return; } if let Some(previous) = previous { unlink(map, &previous, entity); } map.entry(key).or_default().insert(entity); } impl InstanceState { /// Frees slots and slab buffers dropped last frame, now that the previous /// frame's TLAS no longer references them. pub fn begin_frame(&mut self) { self.slots.recycle_retired(); for (vertex_key, index_key) in core::mem::take(&mut self.retired_mesh_buffers) { self.vertex_buffers.release(&vertex_key); self.index_buffers.release(&index_key); } for (aabb_key, metadata_key, spatial_key) in core::mem::take(&mut self.retired_tape_buffers) { self.aabb_buffers.release(&aabb_key); self.tape_metadata_buffers.release(&metadata_key); self.spatial_textures.release(&spatial_key); } } pub fn remove_instances( &mut self, lights: &mut LightState, removed: impl IntoIterator, ) { let _span = info_span!("remove_instances").entered(); for entity in removed { self.remove_instance(lights, entity); } } pub fn refresh_instances( &mut self, inputs: &InstanceInputs, lights: &mut LightState, mesh_instances: &Query, changed_mesh_instances: &Query, tape_instances: &Query, changed_tape_instances: &Query, ) { let _span = info_span!("refresh_instances").entered(); let mut refresh = core::mem::take(&mut self.pending_refresh); refresh.extend(changed_mesh_instances.iter()); refresh.extend(changed_tape_instances.iter()); let moved_meshes = inputs.mesh_allocator.meshes_displaced_by_slab_growth(); for mesh_id in inputs .mesh_blas_manager .changed_meshes() .iter() .copied() .chain(moved_meshes) { if let Some(mesh_instances) = self.object_instances.get(&Object::Mesh(mesh_id)) { refresh.extend(mesh_instances.iter().copied()); } } let moved_tapes = inputs.tape_allocator.tapes_displaced_by_slab_growth(); for tape_id in inputs .tape_blas_manager .changed_tapes() .iter() .copied() .chain(moved_tapes) { if let Some(tape_instances) = self.object_instances.get(&Object::Tape(tape_id)) { refresh.extend(tape_instances.iter().copied()); } } for entity in refresh { match mesh_instances.get(entity) { Ok(data) => { self.refresh_instance(inputs, lights, entity, InstanceQueryData::Mesh(data)) } Err(_) => match tape_instances.get(entity) { Ok(data) => { self.refresh_instance(inputs, lights, entity, InstanceQueryData::Tape(data)) } Err(_) => self.remove_instance(lights, entity), }, } } } fn reserve_slot(&mut self, slot: u32) { let len = slot + 1; self.transforms.grow(len); self.previous_frame_transforms.grow(len); self.blas_refs.grow(len); } fn refresh_instance( &mut self, inputs: &InstanceInputs, lights: &mut LightState, entity: Entity, data: InstanceQueryData, ) { let previous = self.records.get(&entity).copied(); let (id, material, transform, previous_frame_transform) = match data { InstanceQueryData::Mesh((mesh, material, transform, previous_frame_transform)) => ( Object::Mesh(mesh.id()), material, transform, previous_frame_transform, ), InstanceQueryData::Tape((tape, material, transform, previous_frame_transform)) => ( Object::Tape(tape.id()), material, transform, previous_frame_transform, ), }; let material_id = material.id(); relink( &mut self.material_instances, entity, previous.map(|instance| instance.get_material()), material_id, ); let slot = match previous { Some(previous) => previous.get_slot(), None => self.slots.allocate(), }; self.reserve_slot(slot); // Seed only once. Later refreshes must not overwrite transforms written // by extraction. if previous.is_none() { self.write_transforms(slot, transform, previous_frame_transform); } let mut instance = Instance::new( slot, id, material_id, previous.and_then(|instance| instance.get_buffers()), ); let resolved = self.resolve_instance(inputs, lights, entity, &mut instance); self.records.insert(entity, instance); if !resolved { self.pending_refresh.insert(entity); } } fn resolve_instance( &mut self, inputs: &InstanceInputs, lights: &mut LightState, entity: Entity, instance: &mut Instance, ) -> bool { match instance { Instance::Mesh(instance) => { self.resolve_mesh_instance(inputs, lights, entity, instance) } Instance::Tape(instance) => { self.resolve_tape_instance(inputs, lights, entity, instance) } } } fn resolve_mesh_instance( &mut self, inputs: &InstanceInputs, lights: &mut LightState, entity: Entity, instance: &mut MeshInstance, ) -> bool { bevy_log::debug!("Resolving mesh instance {}", instance.mesh); let slot = instance.slot; let material_slot = inputs.assets.material_slots.get(&instance.material); instance.opacity = if inputs .assets .non_opaque_materials .contains(&instance.material) { MeshBlasOpacity::NonOpaque } else { MeshBlasOpacity::Opaque }; let blas_key = instance.blas_key(); let blas_address = inputs.mesh_blas_manager.device_address(&blas_key); if blas_address.is_none() && material_slot.is_some() && inputs.mesh_blas_manager.is_undeclared(&blas_key) { once!(warn!( "RaytracingMesh3d entity {entity} uses a material that needs `{flag:?}`, but \ `Mesh::raytracing` of mesh {mesh} lacks it. Entities like it will not be \ raytraced.", flag = instance.opacity.flag(), mesh = instance.mesh, )); } let (Some(vertex_slice), Some(index_slice), Some(material_slot), Some(blas_address)) = ( inputs.mesh_allocator.mesh_vertex_slice(&instance.mesh), inputs.mesh_allocator.mesh_index_slice(&instance.mesh), material_slot, blas_address, ) else { self.deactivate_mesh_instance(lights, entity, instance); return false; }; let vertex_buffer_key = vertex_slice.buffer.id(); let index_buffer_key = index_slice.buffer.id(); let capacity = MAX_MESH_SLAB_COUNT.get(); if !self.vertex_buffers.has_room(&vertex_buffer_key, capacity) || !self.index_buffers.has_room(&index_buffer_key, capacity) { once!(warn!( "Solari scene needs more than {} mesh slabs. Instances past that limit will not \ be rendered.", MAX_MESH_SLAB_COUNT.get() )); self.deactivate_mesh_instance(lights, entity, instance); return false; } let previous_buffers = instance.buffers.take(); let vertex_buffer_id = self .vertex_buffers .acquire(vertex_buffer_key, capacity, || vertex_slice.buffer.clone()) .expect("vertex slab binding array had room but handed out no slot"); let index_buffer_id = self .index_buffers .acquire(index_buffer_key, capacity, || index_slice.buffer.clone()) .expect("index slab binding array had room but handed out no slot"); instance.buffers = Some((vertex_buffer_key, index_buffer_key)); self.release_mesh_buffers(previous_buffers); let triangle_count = (index_slice.range.len() / 3) as u32; self.geometry_ids.grow_and_set( slot, GpuInstanceGeometryIds { vertex_buffer_id, vertex_buffer_offset: vertex_slice.range.start, index_buffer_id, index_buffer_offset: index_slice.range.start, triangle_count, }, ); self.material_ids.grow_and_set(slot, material_slot); self.set_blas_ref(slot, GpuBlasRef(blas_address)); let is_emissive = inputs .assets .emissive_materials .contains(&instance.material); if is_emissive { lights.add_light( LightSourceId::EmissiveMesh(entity), GpuLightSource::new_emissive_mesh_light(slot, triangle_count), ); } else { lights.remove_light(LightSourceId::EmissiveMesh(entity)); } true } fn resolve_tape_instance( &mut self, inputs: &InstanceInputs, lights: &mut LightState, entity: Entity, instance: &mut TapeInstance, ) -> bool { bevy_log::debug!("Resolving tape instance {}", instance.tape); let slot = instance.slot; let material_slot = inputs.assets.material_slots.get(&instance.material); instance.opacity = if inputs .assets .non_opaque_materials .contains(&instance.material) { TapeBlasOpacity::NonOpaque } else { TapeBlasOpacity::Opaque }; let blas_key = instance.blas_key(); let blas_address = inputs.tape_blas_manager.device_address(&blas_key); if blas_address.is_none() && material_slot.is_some() && inputs.tape_blas_manager.is_undeclared(&blas_key) { once!(warn!( "Tape3d entity {entity} uses a material that needs `{flag:?}`, but \ `Tape::raytracing` of tape {tape} lacks it. Entities like it will not be \ raytraced.", flag = instance.opacity.flag(), tape = instance.tape, )); } let ( Some(aabb_slice), Some(metadata_slice), Some(spatial_texture), Some(material_slot), Some(blas_address), ) = ( inputs.tape_allocator.tape_aabb_slice(&instance.tape), inputs.tape_allocator.tape_metadata_slice(&instance.tape), inputs.tape_allocator.tape_spatial_texture(&instance.tape), material_slot, blas_address, ) else { bevy_log::info!("Deactivating tape instance {}", instance.tape); self.deactivate_tape_instance(lights, entity, instance); return false; }; bevy_log::info!("Tape {} aabb_slice: {:?}", instance.tape, aabb_slice.range); bevy_log::info!( "Tape {} metadata_slice: {:?}", instance.tape, metadata_slice.range ); bevy_log::info!("Tape {} material_slot: {material_slot}", instance.tape); bevy_log::info!("Tape {} blas_address: {blas_address}", instance.tape); let aabb_buffer_key = aabb_slice.buffer.id(); let metadata_buffer_key = metadata_slice.buffer.id(); let capacity = MAX_TAPE_SLAB_COUNT.get(); if !self.aabb_buffers.has_room(&aabb_buffer_key, capacity) || !self .tape_metadata_buffers .has_room(&metadata_buffer_key, capacity) { once!(warn!( "Solari scene needs more than {} tape slabs. Instances past that limit will not \ be rendered.", MAX_TAPE_SLAB_COUNT.get() )); self.deactivate_tape_instance(lights, entity, instance); return false; } let spatial_texture_key = spatial_texture.0.id(); let spatial_capacity = MAX_SPATIAL_TEXTURE_COUNT.get(); if !self .spatial_textures .has_room(&spatial_texture_key, spatial_capacity) { once!(warn!( "Solari scene needs more than {} spatial textures. Instances past that limit will not \ be rendered.", MAX_SPATIAL_TEXTURE_COUNT.get() )); self.deactivate_tape_instance(lights, entity, instance); return false; } let previous_buffers = instance.buffers.take(); let aabb_buffer_id = self .aabb_buffers .acquire(aabb_buffer_key, capacity, || aabb_slice.buffer.clone()) .expect("aabb slab binding array had room but handed out no slot"); let metadata_buffer_id = self .tape_metadata_buffers .acquire(metadata_buffer_key, capacity, || { metadata_slice.buffer.clone() }) .expect("tape metadata slab binding array had room but handed out no slot"); let spatial_texture_id = self .spatial_textures .acquire(spatial_texture_key, spatial_capacity, || { spatial_texture.1.clone() }) .expect("spatial vslab binding array had room but handed out no slot"); instance.buffers = Some((aabb_buffer_key, metadata_buffer_key, spatial_texture_key)); self.release_tape_buffers(previous_buffers); let aabb_count = (aabb_slice.range.len()) as u32; self.tape_ids.grow_and_set( slot, GpuInstanceTapeIds { aabb_buffer_id, aabb_buffer_offset: aabb_slice.range.start, aabb_count, spatial_texture_id, metadata_buffer_id, metadata_buffer_offset: metadata_slice.range.start, }, ); self.material_ids.grow_and_set(slot, material_slot); self.set_blas_ref(slot, GpuBlasRef(blas_address)); /* let is_emissive = inputs .assets .emissive_materials .contains(&instance.material); if is_emissive { lights.add_light( LightSourceId::EmissiveMesh(entity), GpuLightSource::new_emissive_mesh_light(slot, triangle_count), ); } else { lights.remove_light(LightSourceId::EmissiveMesh(entity)); } */ bevy_log::info!("Tape {} resolved", instance.tape); true } fn write_transforms( &self, slot: u32, transform: &GlobalTransform, previous_frame_transform: &PreviousGlobalTransform, ) { self.transforms.set_if_changed( slot, GpuTransform(Affine3::from(transform.affine()).to_transpose()), ); self.previous_frame_transforms.set_if_changed( slot, GpuTransform(Affine3::from(previous_frame_transform.0).to_transpose()), ); } /// Points a slot at an acceleration structure, or at nothing, keeping /// `live_count` in step. fn set_blas_ref(&mut self, slot: u32, reference: GpuBlasRef) { self.blas_refs.grow(slot + 1); let previous = self.blas_refs.get(slot); if previous == reference { return; } self.blas_refs.set(slot, reference); if previous == GpuBlasRef::NONE { self.live_count += 1; } else if reference == GpuBlasRef::NONE { self.live_count -= 1; } } fn deactivate_instance_common( &mut self, lights: &mut LightState, entity: Entity, instance: &Instance, ) { self.set_blas_ref(instance.get_slot(), GpuBlasRef::NONE); lights.remove_light(LightSourceId::EmissiveMesh(entity)); } fn deactivate_mesh_instance( &mut self, lights: &mut LightState, entity: Entity, instance: &mut MeshInstance, ) { self.deactivate_instance_common(lights, entity, &Instance::Mesh(*instance)); self.release_mesh_buffers(instance.buffers.take()); } fn deactivate_tape_instance( &mut self, lights: &mut LightState, entity: Entity, instance: &mut TapeInstance, ) { self.deactivate_instance_common(lights, entity, &Instance::Tape(*instance)); self.release_tape_buffers(instance.buffers.take()); } fn release_mesh_buffers(&mut self, buffers: Option) { self.retired_mesh_buffers.extend(buffers); } fn release_tape_buffers(&mut self, buffers: Option) { self.retired_tape_buffers.extend(buffers); } fn remove_instance(&mut self, lights: &mut LightState, entity: Entity) { let Some(instance) = self.records.remove(&entity) else { return; }; match instance { Instance::Mesh(mut instance) => { self.deactivate_mesh_instance(lights, entity, &mut instance) } Instance::Tape(mut instance) => { self.deactivate_tape_instance(lights, entity, &mut instance) } } self.slots.retire(instance.get_slot()); self.pending_refresh.remove(&entity); unlink(&mut self.object_instances, &instance.get_object(), entity); unlink( &mut self.material_instances, &instance.get_material(), entity, ); } } impl RaytracingSceneBindings { /// Parallel hot path: one entity lookup, then two allocation-free sparse /// writes. pub fn move_instance( &self, entity: Entity, transform: &GlobalTransform, previous_frame_transform: &PreviousGlobalTransform, ) { if let Some(instance) = self.instances.records.get(&entity) { self.instances.write_transforms( instance.get_slot(), transform, previous_frame_transform, ); } } }