From 41b27347cb6d30cedb12f46675bf679c1702c21b Mon Sep 17 00:00:00 2001 From: Molive Date: Tue, 20 Oct 2026 22:03:16 +0100 Subject: [PATCH] Spatial texture writing works --- .../src/scene/binder/instances.rs | 10 +- .../src/scene/tapes/blas.rs | 80 ++++++++------ crates/bevy_tape_load/build.rs | 6 +- crates/bevy_tape_load/shaders/enable_gen.wesl | 104 +++++++++++------- .../shaders/metadata_types.wesl | 3 +- crates/bevy_tape_load/src/render/allocator.rs | 48 ++++---- crates/bevy_tape_load/src/render/mod.rs | 83 +++----------- 7 files changed, 154 insertions(+), 180 deletions(-) diff --git a/crates/bevy_tape_drive_solari/src/scene/binder/instances.rs b/crates/bevy_tape_drive_solari/src/scene/binder/instances.rs index 7483243..94946cb 100644 --- a/crates/bevy_tape_drive_solari/src/scene/binder/instances.rs +++ b/crates/bevy_tape_drive_solari/src/scene/binder/instances.rs @@ -745,7 +745,7 @@ impl InstanceState { return false; } - let spatial_texture_key = spatial_texture.id(); + let spatial_texture_key = spatial_texture.0.id(); let spatial_capacity = MAX_SPATIAL_TEXTURE_COUNT.get(); if !self .spatial_textures @@ -774,13 +774,7 @@ impl InstanceState { let spatial_texture_id = self .spatial_textures .acquire(spatial_texture_key, spatial_capacity, || { - spatial_texture.create_view(&TextureViewDescriptor { - label: Some(&format!( - "Tape {} slot {} spatial texture view", - instance.tape, instance.slot - )), - ..Default::default() - }) + 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)); diff --git a/crates/bevy_tape_drive_solari/src/scene/tapes/blas.rs b/crates/bevy_tape_drive_solari/src/scene/tapes/blas.rs index b44e411..979002e 100644 --- a/crates/bevy_tape_drive_solari/src/scene/tapes/blas.rs +++ b/crates/bevy_tape_drive_solari/src/scene/tapes/blas.rs @@ -243,9 +243,12 @@ pub fn compile_raytracing_blas( struct PushConstants { aabb_buffer_offset: u32, metadata_buffer_offset: u32, - time: f32, + flags: u32, } + const FLAG_FILL_ENABLE_GEN: u32 = 1 << 0; + const FLAG_FILL_SPATIAL_TEXTURE: u32 = 1 << 1; + let tape_info = tapes .iter() .filter(|(asset_id, _)| blas_manager.needs_new_blas.contains(asset_id)) @@ -257,13 +260,21 @@ pub fn compile_raytracing_blas( let aabbs_slice = tape_allocator.tape_aabb_slice(&asset_id).unwrap(); let metadata_slice = tape_allocator.tape_metadata_slice(&asset_id).unwrap(); + let spatial_texture = tape_allocator.tape_spatial_texture(&asset_id).unwrap(); let blas_size = BlasAABBGeometrySizeDescriptor { primitive_count: aabbs_slice.range.len() as u32, flags: key.opacity.geometry_flags(), }; - (key, tape, aabbs_slice, metadata_slice, blas_size) + ( + key, + tape, + aabbs_slice, + metadata_slice, + spatial_texture, + blas_size, + ) }) .collect::>(); @@ -271,42 +282,45 @@ pub fn compile_raytracing_blas( let mut updated_blases = vec![]; let build_entries = tape_info .iter() - .filter_map(|(key, tape, aabbs_slice, metadata_slice, blas_size)| { - let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?; + .filter_map( + |(key, tape, aabbs_slice, metadata_slice, spatial_texture, blas_size)| { + let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?; - let bind_group = render_device.create_bind_group( - "enable_gen_bind_group", - &pipeline_cache.get_bind_group_layout(&replacement_modules.enable_gen_layout), - &BindGroupEntries::sequential(( - aabbs_slice.buffer.as_entire_buffer_binding(), - metadata_slice.buffer.as_entire_buffer_binding(), - )), - ); + let bind_group = render_device.create_bind_group( + "enable_gen_bind_group", + &pipeline_cache.get_bind_group_layout(&replacement_modules.enable_gen_layout), + &BindGroupEntries::sequential(( + aabbs_slice.buffer.as_entire_buffer_binding(), + metadata_slice.buffer.as_entire_buffer_binding(), + &spatial_texture.1, + )), + ); - let pc = PushConstants { - aabb_buffer_offset: aabbs_slice.range.start, - metadata_buffer_offset: metadata_slice.range.start, - time: 0.0, - }; + let pc = PushConstants { + aabb_buffer_offset: aabbs_slice.range.start, + metadata_buffer_offset: metadata_slice.range.start, + flags: FLAG_FILL_ENABLE_GEN | FLAG_FILL_SPATIAL_TEXTURE, + }; - compute_pass.set_pipeline(pipeline); - compute_pass.set_bind_group(0, &bind_group, &[]); - compute_pass.set_immediates(0, bytemuck::bytes_of(&pc)); - compute_pass.dispatch_workgroups(1, 1, 1); + compute_pass.set_pipeline(pipeline); + compute_pass.set_bind_group(0, &bind_group, &[]); + compute_pass.set_immediates(0, bytemuck::bytes_of(&pc)); + compute_pass.dispatch_workgroups(1, 1, 1); - updated_blases.push(key.tape); + updated_blases.push(key.tape); - let geometry = BlasAabbGeometry { - size: blas_size, - stride: size_of::() as u64, - aabb_buffer: aabbs_slice.buffer, - primitive_offset: aabbs_slice.range.start, - }; - Some(BlasBuildEntry { - blas: blas_manager.get(&key).unwrap(), - geometry: BlasGeometries::AabbGeometries(vec![geometry]), - }) - }) + let geometry = BlasAabbGeometry { + size: blas_size, + stride: size_of::() as u64, + aabb_buffer: aabbs_slice.buffer, + primitive_offset: aabbs_slice.range.start, + }; + Some(BlasBuildEntry { + blas: blas_manager.get(&key).unwrap(), + geometry: BlasGeometries::AabbGeometries(vec![geometry]), + }) + }, + ) .collect::>(); drop(compute_pass); diff --git a/crates/bevy_tape_load/build.rs b/crates/bevy_tape_load/build.rs index 23ce6da..c79eaa8 100644 --- a/crates/bevy_tape_load/build.rs +++ b/crates/bevy_tape_load/build.rs @@ -78,8 +78,8 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad let asm = std::fs::read_to_string(format!("{SHADERS_OUT}/{name}.stage0.spv-dis")).unwrap(); let asm = - regex::regex!("(?ms)%package_implicit__1scene =.*?OpFunctionEnd").replace_all(&asm, ""); - let asm = regex::regex!("%package_implicit__1scene").replace_all(&asm, "%10000"); + regex::regex!("(?ms)%package_implicit_scene =.*?OpFunctionEnd").replace_all(&asm, ""); + let asm = regex::regex!("%package_implicit_scene").replace_all(&asm, "%10000"); let asm = regex::regex!("(?ms)%package_implicit__1interval_scene =.*?OpFunctionEnd") .replace_all(&asm, ""); let asm = regex::regex!("%package_implicit__1interval_scene").replace_all(&asm, "%20000"); @@ -95,7 +95,7 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad let asm = regex::regex!("OpName %gradient_scene_input_one \"gradient_scene_input_one\"") .replace_all(&asm, ""); - let asm = regex::regex!("OpName %10000 \"package_implicit__1scene\"").replace_all(&asm, ""); + let asm = regex::regex!("OpName %10000 \"package_implicit_scene\"").replace_all(&asm, ""); let asm = regex::regex!("OpName %20000 \"package_implicit__1interval_scene\"").replace_all(&asm, ""); let asm = diff --git a/crates/bevy_tape_load/shaders/enable_gen.wesl b/crates/bevy_tape_load/shaders/enable_gen.wesl index 68701c8..e6fd05d 100644 --- a/crates/bevy_tape_load/shaders/enable_gen.wesl +++ b/crates/bevy_tape_load/shaders/enable_gen.wesl @@ -1,6 +1,6 @@ import package::aabb::PackedAabb; import package::metadata_types::TapeMetadata; -import package::implicit::interval_scene; +import package::implicit::{interval_scene, scene}; import package::NAN; enable wgpu_binding_array; @@ -14,13 +14,18 @@ struct TapeMetadataBuffer { struct PushConstants { aabb_buffer_offset: u32, metadata_buffer_offset: u32, - time: f32, + flags: u32 } +const FLAG_FILL_ENABLE_GEN = 1 << 0; +const FLAG_FILL_SPATIAL_TEXTURE = 1 << 1; + @group(0) @binding(0) var aabb_buffer: AabbBuffer; @group(0) @binding(1) var tape_metadata_buffer: TapeMetadataBuffer; +@group(0) @binding(2) +var spatial_texture: texture_storage_3d; var push_constants: PushConstants; @@ -34,51 +39,66 @@ struct ComputeInput { fn main(compute_input: ComputeInput) { let metadata = &tape_metadata_buffer.metadata[push_constants.metadata_buffer_offset]; - let total_invocations = compute_input.num_workgroups * vec3u(8); - let base_index = - (((compute_input.global_invocation_id.z * total_invocations.y) - + compute_input.global_invocation_id.y) * total_invocations.x) - + compute_input.global_invocation_id.x; + if (push_constants.flags & FLAG_FILL_ENABLE_GEN) > 0 { + let total_invocations = compute_input.num_workgroups * vec3u(8); + let base_index = + (((compute_input.global_invocation_id.z * total_invocations.y) + + compute_input.global_invocation_id.y) * total_invocations.x) + + compute_input.global_invocation_id.x; - let internal_pos = vec3( - f32( - (base_index >> (metadata.subdivision_log2 * 2)) - & u32((1 << metadata.subdivision_log2) - 1), - ) / f32(1 << metadata.subdivision_log2), - f32( - (base_index >> (metadata.subdivision_log2 * 1)) - & u32((1 << metadata.subdivision_log2) - 1), - ) / f32(1 << metadata.subdivision_log2), - f32( - (base_index >> (metadata.subdivision_log2 * 0)) - & u32((1 << metadata.subdivision_log2) - 1), - ) / f32(1 << metadata.subdivision_log2), - ); + let internal_pos = vec3( + f32( + (base_index >> (metadata.subdivision_log2 * 2)) + & u32((1 << metadata.subdivision_log2) - 1), + ) / f32(1 << metadata.subdivision_log2), + f32( + (base_index >> (metadata.subdivision_log2 * 1)) + & u32((1 << metadata.subdivision_log2) - 1), + ) / f32(1 << metadata.subdivision_log2), + f32( + (base_index >> (metadata.subdivision_log2 * 0)) + & u32((1 << metadata.subdivision_log2) - 1), + ) / f32(1 << metadata.subdivision_log2), + ); - let low_corner = - (((vec3(0.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions) - + metadata.lowest_corner; - let high_corner = - (((vec3(1.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions) - + metadata.lowest_corner; - let interval = interval_scene( - vec4(low_corner, push_constants.time), - vec4(high_corner, push_constants.time), - ); + let low_corner = + (((vec3(0.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions) + + metadata.lowest_corner; + let high_corner = + (((vec3(1.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions) + + metadata.lowest_corner; - let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index]; + let interval = interval_scene( + vec4(low_corner, metadata.time), + vec4(high_corner, metadata.time), + ); - let en = (interval.x < 0) && (interval.y > 0); + let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index]; - if en { - aabb.min_x = low_corner.x; - aabb.min_y = low_corner.y; - aabb.min_z = low_corner.z; - aabb.max_x = high_corner.x; - aabb.max_y = high_corner.y; - aabb.max_z = high_corner.z; - } else { - aabb.min_x = NAN(); + let en = (interval.x < 0) && (interval.y > 0); + + if en { + aabb.min_x = low_corner.x; + aabb.min_y = low_corner.y; + aabb.min_z = low_corner.z; + aabb.max_x = high_corner.x; + aabb.max_y = high_corner.y; + aabb.max_z = high_corner.z; + } else { + aabb.min_x = NAN(); + } + } + + if (push_constants.flags & FLAG_FILL_SPATIAL_TEXTURE) > 0 { + let internal_pos = vec3f(compute_input.global_invocation_id); + + let mid_point = + (((internal_pos + 0.5f) / f32(1 << metadata.subdivision_log2)) * metadata.dimensions) + + metadata.lowest_corner; + + let point = scene(vec4(mid_point, metadata.time)); + + textureStore(spatial_texture, compute_input.global_invocation_id, vec4(point, 0., 0., 0.)); } } diff --git a/crates/bevy_tape_load/shaders/metadata_types.wesl b/crates/bevy_tape_load/shaders/metadata_types.wesl index e0b67a3..e196d1e 100644 --- a/crates/bevy_tape_load/shaders/metadata_types.wesl +++ b/crates/bevy_tape_load/shaders/metadata_types.wesl @@ -1,7 +1,6 @@ struct TapeMetadata { - /// AABB for decompressing positions. lowest_corner: vec3, - pad_a: u32, + time: f32, dimensions: vec3, subdivision_log2: u32, } diff --git a/crates/bevy_tape_load/src/render/allocator.rs b/crates/bevy_tape_load/src/render/allocator.rs index aa87058..a1c19f3 100644 --- a/crates/bevy_tape_load/src/render/allocator.rs +++ b/crates/bevy_tape_load/src/render/allocator.rs @@ -16,7 +16,7 @@ use bevy_platform::collections::HashMap; use bevy_render::{ GpuResourceAppExt, Render, RenderApp, RenderSystems, render_asset::{ExtractedAssets, prepare_assets}, - render_resource::Texture, + render_resource::{Texture, TextureView}, renderer::{RenderDevice, RenderQueue}, slab_allocator::{ Slab, SlabAllocationBufferSlice, SlabAllocator, SlabAllocatorSettings, SlabId, SlabItem, @@ -26,7 +26,7 @@ use bevy_render::{ use wgpu::{ BufferUsages, COPY_BUFFER_ALIGNMENT, Extent3d, TextureDimension, TextureFormat, TextureUsages, }; -use wgpu_types::TextureDescriptor; +use wgpu_types::{TextureDescriptor, TextureViewDescriptor}; use super::{PackedAabb, RenderTape, TapeMetadata}; use crate::tape::Tape; @@ -48,7 +48,7 @@ pub struct TapeAllocator { /// Holds all buffers and offset allocators. #[deref] slab_allocator: SlabAllocator, - spatial_texture_allocator: HashMap, Texture>, + spatial_texture_allocator: HashMap, (Texture, TextureView)>, } /// Tunable parameters that customize the behavior of the allocator. @@ -278,7 +278,7 @@ impl TapeAllocator { /// Returns the spatial texture for the tape with the given ID. /// /// If the tape wasn't allocated, returns None. - pub fn tape_spatial_texture(&self, tape_id: &AssetId) -> Option<&Texture> { + pub fn tape_spatial_texture(&self, tape_id: &AssetId) -> Option<&(Texture, TextureView)> { self.spatial_texture_allocator.get(tape_id) } @@ -376,24 +376,28 @@ impl TapeAllocator { tape_allocator_settings, ); + let texture = render_device.create_texture(&TextureDescriptor { + label: Some(&format!("Tape {} spatial texture", tape_id)), + format: TextureFormat::R32Float, + dimension: TextureDimension::D3, + usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING, + mip_level_count: 1, + sample_count: 1, + view_formats: &[TextureFormat::R32Float], + size: Extent3d { + width: tape.subdivision, + height: tape.subdivision, + depth_or_array_layers: tape.subdivision, + }, + }); + let texture_view = texture.create_view(&TextureViewDescriptor { + label: Some(&format!("Tape {} spatial texture view", tape_id)), + ..Default::default() + }); + // Allocate spatial texture. - self.spatial_texture_allocator.insert( - *tape_id, - render_device.create_texture(&TextureDescriptor { - label: Some(&format!("Tape {} spatial texture", tape_id)), - format: TextureFormat::R32Float, - dimension: TextureDimension::D3, - usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING, - mip_level_count: 1, - sample_count: 1, - view_formats: &[TextureFormat::R32Float], - size: Extent3d { - width: tape.subdivision, - height: tape.subdivision, - depth_or_array_layers: tape.subdivision, - }, - }), - ); + self.spatial_texture_allocator + .insert(*tape_id, (texture, texture_view)); } // Perform growth. @@ -430,7 +434,7 @@ impl TapeAllocator { lowest_corner, dimensions, subdivision_log2: tape.subdivision.ilog2(), - ..Default::default() + time: tape.time, } }; // Call the generic function. diff --git a/crates/bevy_tape_load/src/render/mod.rs b/crates/bevy_tape_load/src/render/mod.rs index 135a92e..204e7ef 100644 --- a/crates/bevy_tape_load/src/render/mod.rs +++ b/crates/bevy_tape_load/src/render/mod.rs @@ -19,13 +19,19 @@ use bevy_render::{ render_resource::{ BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, CachedComputePipelineId, ComputePipelineDescriptor, PipelineCache, ShaderType, - binding_types::{storage_buffer, storage_buffer_read_only}, + binding_types::{ + storage_buffer, storage_buffer_read_only, texture_3d, texture_storage_2d_array, + texture_storage_3d, + }, }, }; use bevy_shader::{Shader, load_shader_library}; use bytemuck::{Pod, Zeroable}; use rspirv::dr::Module; -use wgpu::{ShaderModuleDescriptorPassthrough, ShaderStages, include_spirv_raw}; +use wgpu::{ + ShaderModuleDescriptorPassthrough, ShaderStages, StorageTextureAccess, TextureFormat, + TextureSampleType, include_spirv_raw, +}; use crate::{ render::allocator::{ElementClass, TapeAllocationKey, TapeAllocator, TapeSlabId}, @@ -47,7 +53,7 @@ pub struct PackedAabb { #[repr(C)] pub struct TapeMetadata { lowest_corner: Vec3, - pad_a: u32, + time: f32, dimensions: Vec3, subdivision_log2: u32, } @@ -82,9 +88,7 @@ impl Plugin for TapeRenderAssetPlugin { let modules = ReplacementModules { enable_gen: get_module(enable_gen.clone()), - fuzz: get_module(enable_gen.clone()), normals: get_module(enable_gen.clone()), - spatial_texture: get_module(enable_gen.clone()), trace: get_module(enable_gen.clone()), enable_gen_layout: BindGroupLayoutDescriptor::new( "Enable Gen Layout", @@ -93,26 +97,10 @@ impl Plugin for TapeRenderAssetPlugin { ( storage_buffer::(false), storage_buffer_read_only::(false), - ), - ), - ), - fuzz_layout: BindGroupLayoutDescriptor::new( - "Tape Fuzz Layout", - &BindGroupLayoutEntries::sequential( - ShaderStages::COMPUTE, - ( - storage_buffer::(false), - storage_buffer_read_only::(false), - ), - ), - ), - spatial_texture_layout: BindGroupLayoutDescriptor::new( - "Spatial Texture Layout", - &BindGroupLayoutEntries::sequential( - ShaderStages::COMPUTE, - ( - storage_buffer::(false), - storage_buffer_read_only::(false), + texture_storage_3d( + TextureFormat::R32Float, + StorageTextureAccess::WriteOnly, + ), ), ), ), @@ -172,14 +160,10 @@ pub fn prepare_tape_metadata_fallback_buffer( #[derive(Resource)] pub struct ReplacementModules { pub enable_gen: Module, - pub fuzz: Module, pub normals: Module, - pub spatial_texture: Module, pub trace: Module, pub enable_gen_layout: BindGroupLayoutDescriptor, - pub fuzz_layout: BindGroupLayoutDescriptor, - pub spatial_texture_layout: BindGroupLayoutDescriptor, } /// The render world representation of a [`Tape`]. @@ -191,14 +175,10 @@ pub struct RenderTape { pub key: u64, pub enable_gen: Handle, - pub fuzz: Handle, pub normals: Handle, - pub spatial_texture: Handle, pub trace: Handle, pub enable_gen_pipeline: CachedComputePipelineId, - pub fuzz_pipeline: CachedComputePipelineId, - pub spatial_texture_pipeline: CachedComputePipelineId, } impl RenderAsset for RenderTape { @@ -239,13 +219,9 @@ impl RenderAsset for RenderTape { time: tape.time, key, enable_gen: previous.enable_gen.clone(), - fuzz: previous.fuzz.clone(), normals: previous.normals.clone(), - spatial_texture: previous.spatial_texture.clone(), trace: previous.trace.clone(), enable_gen_pipeline: previous.enable_gen_pipeline, - fuzz_pipeline: previous.fuzz_pipeline, - spatial_texture_pipeline: previous.spatial_texture_pipeline, }); } @@ -254,21 +230,11 @@ impl RenderAsset for RenderTape { replacement_modules.enable_gen.clone(), "enable_gen", )); - let fuzz = asset_server.add(tape.sdf_specialize_module_with_key( - key, - replacement_modules.fuzz.clone(), - "fuzz", - )); let normals = asset_server.add(tape.sdf_specialize_module_with_key( key, replacement_modules.normals.clone(), "normals", )); - let spatial_texture = asset_server.add(tape.sdf_specialize_module_with_key( - key, - replacement_modules.spatial_texture.clone(), - "spatial_texture", - )); let trace = asset_server.add(tape.sdf_specialize_module_with_key( key, replacement_modules.trace.clone(), @@ -285,38 +251,15 @@ impl RenderAsset for RenderTape { ..Default::default() }); - let fuzz_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor { - label: Some(format!("bevy_tape_drive::gen_shader::fuzz::{key}").into()), - layout: vec![replacement_modules.fuzz_layout.clone()], - shader: fuzz.clone(), - immediate_size: 12, - entry_point: Some("main".into()), - ..Default::default() - }); - - let spatial_texture_pipeline = - pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor { - label: Some(format!("bevy_tape_drive::gen_shader::spatial_texture::{key}").into()), - layout: vec![replacement_modules.spatial_texture_layout.clone()], - shader: spatial_texture.clone(), - immediate_size: 12, - entry_point: Some("main".into()), - ..Default::default() - }); - Ok(RenderTape { seed: tape.seed, subdivision: tape.subdivision, time: tape.time, key, enable_gen, - fuzz, normals, - spatial_texture, trace, enable_gen_pipeline, - fuzz_pipeline, - spatial_texture_pipeline, }) }