fix the segfault

This commit is contained in:
2026-10-14 21:55:08 +01:00
parent ec97a06a48
commit e98dba8c45
22 changed files with 178 additions and 173 deletions
@@ -1,7 +1,7 @@
use super::{
StandardMaterialAssets,
allocator::{RetainedBindingArray, SlotAllocator},
instances::InstanceState,
StandardMaterialAssets,
};
use bevy_asset::AssetId;
use bevy_color::{ColorToComponents, LinearRgba};
@@ -37,9 +37,9 @@ impl BindGroupCacheState {
// Binding arrays are dense, so freed slots still need something valid
// bound into them
let dummy_buffer = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_dummy_binding_array_buffer"),
size: 48,
usage: BufferUsages::STORAGE,
label: Some("solari_dummy_binding_array_buffer"),
size: 48,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
@@ -179,7 +179,7 @@ impl RaytracingSceneBindings {
let light_sources = BufferBinding {
buffer: self.lights.sources.buffer().unwrap(),
offset: 0,
size: BufferSize::new(
size: BufferSize::new(
self.lights.index.len() as u64 * size_of::<GpuLightSource>() as u64,
),
};
@@ -341,7 +341,7 @@ pub fn prepare_raytracing_scene_bind_group(
#[derive(ShaderType, Default)]
pub struct GpuEnvironmentMapLight {
pub light_from_world: Mat3,
pub intensity: f32,
pub intensity: f32,
}
fn prepare_environment_map_light<'a>(
@@ -364,7 +364,7 @@ fn prepare_environment_map_light<'a>(
light_from_world: Mat3::from_quat(
extracted_environment_map_light.rotation.inverse(),
),
intensity: extracted_environment_map_light.intensity,
intensity: extracted_environment_map_light.intensity,
},
),
None => (
@@ -35,20 +35,20 @@ pub const MAX_TAPE_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap();
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuInstanceGeometryIds {
vertex_buffer_id: u32,
vertex_buffer_id: u32,
vertex_buffer_offset: u32,
index_buffer_id: u32,
index_buffer_offset: u32,
triangle_count: 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,
metadata_buffer_id: u32,
aabb_buffer_id: u32,
aabb_buffer_offset: u32,
aabb_count: u32,
metadata_buffer_id: u32,
metadata_buffer_offset: u32,
}
@@ -100,27 +100,27 @@ pub enum BlasKey {
/// Everything tracked per raytracing instance.
#[derive(Clone, Copy)]
struct MeshInstance {
slot: u32,
mesh: AssetId<Mesh>,
slot: u32,
mesh: AssetId<Mesh>,
material: AssetId<StandardMaterial>,
opacity: MeshBlasOpacity,
buffers: Option<(BufferId, BufferId)>,
opacity: MeshBlasOpacity,
buffers: Option<(BufferId, BufferId)>,
}
/// Everything tracked per raytracing instance.
#[derive(Clone, Copy)]
struct TapeInstance {
slot: u32,
tape: AssetId<Tape>,
slot: u32,
tape: AssetId<Tape>,
material: AssetId<StandardMaterial>,
opacity: TapeBlasOpacity,
buffers: Option<(BufferId, BufferId)>,
opacity: TapeBlasOpacity,
buffers: Option<(BufferId, BufferId)>,
}
impl MeshInstance {
fn blas_key(&self) -> MeshBlasKey {
MeshBlasKey {
mesh: self.mesh,
mesh: self.mesh,
opacity: self.opacity,
}
}
@@ -129,7 +129,7 @@ impl MeshInstance {
impl TapeInstance {
fn blas_key(&self) -> TapeBlasKey {
TapeBlasKey {
tape: self.tape,
tape: self.tape,
opacity: self.opacity,
}
}
@@ -262,24 +262,24 @@ pub struct InstanceState {
impl InstanceState {
pub fn new() -> Self {
Self {
vertex_buffers: RetainedBindingArray::new(),
index_buffers: RetainedBindingArray::new(),
aabb_buffers: RetainedBindingArray::new(),
tape_metadata_buffers: RetainedBindingArray::new(),
transforms: storage_buffer("solari_transforms"),
vertex_buffers: RetainedBindingArray::new(),
index_buffers: RetainedBindingArray::new(),
aabb_buffers: RetainedBindingArray::new(),
tape_metadata_buffers: 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(),
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(),
}
}
@@ -339,11 +339,11 @@ pub type ChangedTapeInstanceFilter = (
/// The scene state an instance resolves its GPU data against.
pub struct InstanceInputs<'a> {
pub assets: &'a AssetState,
pub assets: &'a AssetState,
pub mesh_blas_manager: &'a MeshBlasManager,
pub mesh_allocator: &'a MeshAllocator,
pub mesh_allocator: &'a MeshAllocator,
pub tape_blas_manager: &'a TapeBlasManager,
pub tape_allocator: &'a TapeAllocator,
pub tape_allocator: &'a TapeAllocator,
}
fn unlink<K: Eq + Hash>(map: &mut HashMap<K, EntityHashSet>, key: &K, entity: Entity) {
@@ -442,11 +442,11 @@ impl InstanceState {
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),
},
}
@@ -529,10 +529,10 @@ impl InstanceState {
match instance {
Instance::Mesh(instance) => {
self.resolve_mesh_instance(inputs, lights, entity, instance)
},
}
Instance::Tape(instance) => {
self.resolve_tape_instance(inputs, lights, entity, instance)
},
}
}
}
@@ -838,10 +838,10 @@ impl InstanceState {
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());
@@ -4,7 +4,7 @@ use crate::scene::extract::{
ExtractedRaytracingRectLight, ExtractedRaytracingSpotLight,
};
use bevy_ecs::{entity::Entity, query::Changed, system::Query};
use bevy_math::{ops::cos, Vec3};
use bevy_math::{Vec3, ops::cos};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_render::render_resource::{AtomicSparseBufferVec, BufferUsages};
use bevy_render::{impl_atomic_pod, render_resource::AtomicPod};
@@ -227,11 +227,11 @@ pub fn prepare_raytracing_scene_resources(
.instances
.remove_instances(&mut bindings.lights, removed_tape_instances.read());
let inputs = InstanceInputs {
assets: &bindings.assets,
assets: &bindings.assets,
mesh_blas_manager: &mesh_blas_manager,
mesh_allocator: &mesh_allocator,
mesh_allocator: &mesh_allocator,
tape_blas_manager: &tape_blas_manager,
tape_allocator: &tape_allocator,
tape_allocator: &tape_allocator,
};
bindings.instances.refresh_instances(
&inputs,
@@ -30,7 +30,7 @@ use super::{
#[derive(Resource)]
pub struct TlasInstanceSetupPipeline {
pub layout: BindGroupLayoutDescriptor,
pub id: Option<CachedComputePipelineId>,
pub id: Option<CachedComputePipelineId>,
}
impl FromWorld for TlasInstanceSetupPipeline {
@@ -280,9 +280,9 @@ impl TlasState {
let capacity = tlas_capacity_for(needed);
self.instance_descriptors = Some(render_device.create_buffer(&BufferDescriptor {
label: Some("solari_tlas_instance_descriptors"),
size: u64::from(capacity) * tlas_build::INSTANCE_DESCRIPTOR_SIZE,
usage: BufferUsages::STORAGE | BufferUsages::TLAS_INPUT,
label: Some("solari_tlas_instance_descriptors"),
size: u64::from(capacity) * tlas_build::INSTANCE_DESCRIPTOR_SIZE,
usage: BufferUsages::STORAGE | BufferUsages::TLAS_INPUT,
mapped_at_creation: false,
}));
self.instance_descriptor_capacity = capacity;
@@ -332,9 +332,9 @@ impl TlasState {
let capacity = tlas_capacity_for(needed);
self.structures[current_index] = Some(render_device.wgpu_device().create_tlas(
&CreateTlasDescriptor {
label: Some("tlas"),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE,
update_mode: AccelerationStructureUpdateMode::Build,
label: Some("tlas"),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE,
update_mode: AccelerationStructureUpdateMode::Build,
max_instances: capacity,
},
));
@@ -356,18 +356,25 @@ pub fn build_raytracing_tlas(
let bindings = &mut *bindings;
let current_index = bindings.tlas.current_index;
let built = match bindings.tlas.raw {
Some(backend) => {
setup_tlas_instances(bindings, &pipeline_cache, &pipeline, &mut render_context)
&& build_tlas_raw(bindings, backend, &mut render_context)
},
None => build_tlas_through_wgpu_core(
bindings,
&mesh_blas_manager,
&tape_blas_manager,
&mut render_context,
),
};
//let built = match bindings.tlas.raw {
// Some(backend) => {
// setup_tlas_instances(bindings, &pipeline_cache, &pipeline, &mut render_context)
// && build_tlas_raw(bindings, backend, &mut render_context)
// }
// None => build_tlas_through_wgpu_core(
// bindings,
// &mesh_blas_manager,
// &tape_blas_manager,
// &mut render_context,
// ),
//};
let built = build_tlas_through_wgpu_core(
bindings,
&mesh_blas_manager,
&tape_blas_manager,
&mut render_context,
);
if built {
bindings.tlas.built[current_index] = true;
@@ -424,7 +431,7 @@ fn setup_tlas_instances(
let time_span = diagnostics.time_span(command_encoder, "setup_tlas_instances");
{
let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("setup_tlas_instances"),
label: Some("setup_tlas_instances"),
timestamp_writes: None,
});
pass.set_pipeline(compute_pipeline);
@@ -437,11 +444,11 @@ fn setup_tlas_instances(
[
BufferTransition {
buffer: &**instances,
state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
},
BufferTransition {
buffer: &**scratch,
state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
},
]
.into_iter(),
@@ -36,7 +36,7 @@ use bevy_render::{
renderer::RenderDevice,
};
use core::marker::PhantomData;
use wgpu::{hal, BufferUses};
use wgpu::{BufferUses, hal};
/// Size of one TLAS instance descriptor, on both Vulkan and DXR.
pub const INSTANCE_DESCRIPTOR_SIZE: u64 = 64;
@@ -182,7 +182,7 @@ pub fn extract_raytracing_scene_tapes_and_materials(
/// world.
#[derive(Resource, Default)]
pub struct StandardMaterialAssets {
materials: HashMap<AssetId<StandardMaterial>, StandardMaterial>,
materials: HashMap<AssetId<StandardMaterial>, StandardMaterial>,
/// Materials added or modified this frame.
pub changed: Vec<AssetId<StandardMaterial>>,
/// Materials removed this frame.
@@ -213,54 +213,54 @@ pub fn extract_raytracing_material_assets(
render_materials.materials.insert(*id, material.clone());
render_materials.changed.push(*id);
}
},
}
AssetEvent::Removed { id } => {
render_materials.materials.remove(id);
render_materials.removed.push(*id);
},
AssetEvent::Unused { .. } | AssetEvent::LoadedWithDependencies { .. } => {},
}
AssetEvent::Unused { .. } | AssetEvent::LoadedWithDependencies { .. } => {}
}
}
}
#[derive(Component, Clone, Copy, PartialEq, Debug)]
pub struct ExtractedRaytracingDirectionalLight {
pub direction_to_light: Vec3,
pub illuminance: Vec3,
pub direction_to_light: Vec3,
pub illuminance: Vec3,
pub sun_disk_angular_size: f32,
}
#[derive(Component, Clone, Copy, PartialEq, Debug)]
pub struct ExtractedRaytracingPointLight {
pub position: Vec3,
pub radius: f32,
pub position: Vec3,
pub radius: f32,
pub intensity: Vec3,
}
#[derive(Component, Clone, Copy, PartialEq, Debug)]
pub struct ExtractedRaytracingSpotLight {
pub position: Vec3,
pub radius: f32,
pub position: Vec3,
pub radius: f32,
pub intensity: Vec3,
pub axis: Vec3,
pub axis: Vec3,
pub cos_inner: f32,
pub cos_outer: f32,
}
#[derive(Component, Clone, Copy, PartialEq, Debug)]
pub struct ExtractedRaytracingRectLight {
pub center: Vec3,
pub edge_x: Vec3,
pub edge_y: Vec3,
pub area: f32,
pub center: Vec3,
pub edge_x: Vec3,
pub edge_y: Vec3,
pub area: f32,
pub radiance: Vec3,
}
#[derive(Resource, Default, Clone, PartialEq)]
pub struct ExtractedEnvironmentMapLight {
pub cubemap: Option<Handle<Image>>,
pub cubemap: Option<Handle<Image>>,
pub intensity: f32,
pub rotation: Quat,
pub rotation: Quat,
}
/// Lights whose extracted data needs updating.
@@ -337,8 +337,8 @@ pub fn extract_raytracing_directional_lights(
}
entity_commands.insert(ExtractedRaytracingDirectionalLight {
direction_to_light: transform.back().into(),
illuminance: LinearRgba::from(directional_light.color).to_vec3()
direction_to_light: transform.back().into(),
illuminance: LinearRgba::from(directional_light.color).to_vec3()
* directional_light.illuminance,
sun_disk_angular_size: sun_disk.unwrap_or_default().angular_size,
});
@@ -370,8 +370,8 @@ pub fn extract_raytracing_point_lights(
}
entity_commands.insert(ExtractedRaytracingPointLight {
position: transform.translation(),
radius: point_light.radius,
position: transform.translation(),
radius: point_light.radius,
// Map from luminous power in lumens to luminous intensity in candela
intensity: LinearRgba::from(point_light.color).to_vec3() * point_light.intensity
/ (4.0 * PI),
@@ -407,11 +407,11 @@ pub fn extract_raytracing_spot_lights(
let inner_angle = spot_light.inner_angle.min(outer_angle);
entity_commands.insert(ExtractedRaytracingSpotLight {
position: transform.translation(),
radius: spot_light.radius,
position: transform.translation(),
radius: spot_light.radius,
intensity: LinearRgba::from(spot_light.color).to_vec3() * spot_light.intensity
/ (4.0 * PI),
axis: transform.forward().into(),
axis: transform.forward().into(),
cos_inner: cos(inner_angle),
cos_outer: cos(outer_angle),
});
@@ -478,9 +478,9 @@ pub fn extract_raytracing_environment_map_light(
};
let env_map_light = ExtractedEnvironmentMapLight {
cubemap: Some(env_map.specular_map.clone()),
cubemap: Some(env_map.specular_map.clone()),
intensity: env_map.intensity,
rotation: env_map.rotation,
rotation: env_map.rotation,
};
if extracted_env_map_light.cubemap.is_none() {
@@ -9,8 +9,8 @@ use bevy_platform::collections::HashMap;
use bevy_render::{
diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
mesh::{
allocator::{MeshAllocator, MeshBufferSlice},
RenderMesh,
allocator::{MeshAllocator, MeshBufferSlice},
},
render_asset::ExtractedAssets,
render_resource::*,
@@ -174,6 +174,11 @@ pub fn prepare_raytracing_blas(
render_queue: Res<RenderQueue>,
mut diagnostics: Option<ResMut<DiagnosticsRecorder>>,
) {
std::process::Command::new("touch")
.arg("/tmp/trigger")
.status()
.unwrap();
blas_manager.changed.clear();
// Delete BLAS for deleted or modified meshes
@@ -3,7 +3,7 @@ use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{component::Component, prelude::ReflectComponent, template::FromTemplate};
use bevy_mesh::Mesh;
use bevy_pbr::{MeshMaterial3d, StandardMaterial};
use bevy_reflect::{prelude::ReflectDefault, Reflect};
use bevy_reflect::{Reflect, prelude::ReflectDefault};
use bevy_render::sync_world::SyncToRenderWorld;
use bevy_transform::components::Transform;
use derive_more::derive::From;
@@ -8,10 +8,10 @@ use bevy_ecs::{
use bevy_mesh::MeshRaytracingFlags;
use bevy_platform::collections::HashMap;
use bevy_render::{
diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
diagnostic::RecordDiagnostics,
render_asset::{ExtractedAssets, RenderAssets},
render_resource::*,
renderer::{RenderDevice, RenderQueue},
renderer::{RenderContext, RenderDevice, RenderQueue},
};
use bevy_tape_load::{
Tape,
@@ -217,17 +217,14 @@ pub fn compile_raytracing_blas(
tapes: Res<RenderAssets<RenderTape>>,
tape_allocator: Res<TapeAllocator>,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
mut render_context: RenderContext,
pipeline_cache: Res<PipelineCache>,
replacement_modules: Res<ReplacementModules>,
mut diagnostics: Option<ResMut<DiagnosticsRecorder>>,
) {
let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
label: Some("blas_build_command_encoder"),
});
let time_span = diagnostics
.as_mut()
.map(|diagnostics| diagnostics.time_span(&mut command_encoder, "tape_blas_build"));
let diagnostics = render_context.diagnostic_recorder();
let diagnostics = diagnostics.as_deref();
let mut command_encoder = render_context.command_encoder();
let time_span = diagnostics.time_span(command_encoder, "tape_blas_build");
let mut compute_pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("enable_gen"),
timestamp_writes: None,
@@ -303,10 +300,7 @@ pub fn compile_raytracing_blas(
drop(compute_pass);
command_encoder.build_acceleration_structures(&build_entries, &[]);
if let Some(time_span) = time_span {
time_span.end(&mut command_encoder);
}
render_queue.submit([command_encoder.finish()]);
time_span.end(&mut command_encoder);
}
pub fn delete_raytracing_blas(