Spatial texture writing works

This commit is contained in:
2026-10-20 22:03:16 +01:00
parent 2c05cc28a0
commit 41b27347cb
7 changed files with 154 additions and 180 deletions
@@ -745,7 +745,7 @@ impl InstanceState {
return false; 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(); let spatial_capacity = MAX_SPATIAL_TEXTURE_COUNT.get();
if !self if !self
.spatial_textures .spatial_textures
@@ -774,13 +774,7 @@ impl InstanceState {
let spatial_texture_id = self let spatial_texture_id = self
.spatial_textures .spatial_textures
.acquire(spatial_texture_key, spatial_capacity, || { .acquire(spatial_texture_key, spatial_capacity, || {
spatial_texture.create_view(&TextureViewDescriptor { spatial_texture.1.clone()
label: Some(&format!(
"Tape {} slot {} spatial texture view",
instance.tape, instance.slot
)),
..Default::default()
})
}) })
.expect("spatial vslab binding array had room but handed out no slot"); .expect("spatial vslab binding array had room but handed out no slot");
instance.buffers = Some((aabb_buffer_key, metadata_buffer_key, spatial_texture_key)); instance.buffers = Some((aabb_buffer_key, metadata_buffer_key, spatial_texture_key));
@@ -243,9 +243,12 @@ pub fn compile_raytracing_blas(
struct PushConstants { struct PushConstants {
aabb_buffer_offset: u32, aabb_buffer_offset: u32,
metadata_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 let tape_info = tapes
.iter() .iter()
.filter(|(asset_id, _)| blas_manager.needs_new_blas.contains(asset_id)) .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 aabbs_slice = tape_allocator.tape_aabb_slice(&asset_id).unwrap();
let metadata_slice = tape_allocator.tape_metadata_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 { let blas_size = BlasAABBGeometrySizeDescriptor {
primitive_count: aabbs_slice.range.len() as u32, primitive_count: aabbs_slice.range.len() as u32,
flags: key.opacity.geometry_flags(), flags: key.opacity.geometry_flags(),
}; };
(key, tape, aabbs_slice, metadata_slice, blas_size) (
key,
tape,
aabbs_slice,
metadata_slice,
spatial_texture,
blas_size,
)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -271,7 +282,8 @@ pub fn compile_raytracing_blas(
let mut updated_blases = vec![]; let mut updated_blases = vec![];
let build_entries = tape_info let build_entries = tape_info
.iter() .iter()
.filter_map(|(key, tape, aabbs_slice, metadata_slice, blas_size)| { .filter_map(
|(key, tape, aabbs_slice, metadata_slice, spatial_texture, blas_size)| {
let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?; let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?;
let bind_group = render_device.create_bind_group( let bind_group = render_device.create_bind_group(
@@ -280,13 +292,14 @@ pub fn compile_raytracing_blas(
&BindGroupEntries::sequential(( &BindGroupEntries::sequential((
aabbs_slice.buffer.as_entire_buffer_binding(), aabbs_slice.buffer.as_entire_buffer_binding(),
metadata_slice.buffer.as_entire_buffer_binding(), metadata_slice.buffer.as_entire_buffer_binding(),
&spatial_texture.1,
)), )),
); );
let pc = PushConstants { let pc = PushConstants {
aabb_buffer_offset: aabbs_slice.range.start, aabb_buffer_offset: aabbs_slice.range.start,
metadata_buffer_offset: metadata_slice.range.start, metadata_buffer_offset: metadata_slice.range.start,
time: 0.0, flags: FLAG_FILL_ENABLE_GEN | FLAG_FILL_SPATIAL_TEXTURE,
}; };
compute_pass.set_pipeline(pipeline); compute_pass.set_pipeline(pipeline);
@@ -306,7 +319,8 @@ pub fn compile_raytracing_blas(
blas: blas_manager.get(&key).unwrap(), blas: blas_manager.get(&key).unwrap(),
geometry: BlasGeometries::AabbGeometries(vec![geometry]), geometry: BlasGeometries::AabbGeometries(vec![geometry]),
}) })
}) },
)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
drop(compute_pass); drop(compute_pass);
+3 -3
View File
@@ -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 = std::fs::read_to_string(format!("{SHADERS_OUT}/{name}.stage0.spv-dis")).unwrap();
let asm = let asm =
regex::regex!("(?ms)%package_implicit__1scene =.*?OpFunctionEnd").replace_all(&asm, ""); regex::regex!("(?ms)%package_implicit_scene =.*?OpFunctionEnd").replace_all(&asm, "");
let asm = regex::regex!("%package_implicit__1scene").replace_all(&asm, "%10000"); let asm = regex::regex!("%package_implicit_scene").replace_all(&asm, "%10000");
let asm = regex::regex!("(?ms)%package_implicit__1interval_scene =.*?OpFunctionEnd") let asm = regex::regex!("(?ms)%package_implicit__1interval_scene =.*?OpFunctionEnd")
.replace_all(&asm, ""); .replace_all(&asm, "");
let asm = regex::regex!("%package_implicit__1interval_scene").replace_all(&asm, "%20000"); 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\"") let asm = regex::regex!("OpName %gradient_scene_input_one \"gradient_scene_input_one\"")
.replace_all(&asm, ""); .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 = let asm =
regex::regex!("OpName %20000 \"package_implicit__1interval_scene\"").replace_all(&asm, ""); regex::regex!("OpName %20000 \"package_implicit__1interval_scene\"").replace_all(&asm, "");
let asm = let asm =
+24 -4
View File
@@ -1,6 +1,6 @@
import package::aabb::PackedAabb; import package::aabb::PackedAabb;
import package::metadata_types::TapeMetadata; import package::metadata_types::TapeMetadata;
import package::implicit::interval_scene; import package::implicit::{interval_scene, scene};
import package::NAN; import package::NAN;
enable wgpu_binding_array; enable wgpu_binding_array;
@@ -14,13 +14,18 @@ struct TapeMetadataBuffer {
struct PushConstants { struct PushConstants {
aabb_buffer_offset: u32, aabb_buffer_offset: u32,
metadata_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) @group(0) @binding(0)
var<storage, read_write> aabb_buffer: AabbBuffer; var<storage, read_write> aabb_buffer: AabbBuffer;
@group(0) @binding(1) @group(0) @binding(1)
var<storage> tape_metadata_buffer: TapeMetadataBuffer; var<storage> tape_metadata_buffer: TapeMetadataBuffer;
@group(0) @binding(2)
var spatial_texture: texture_storage_3d<r32float, write>;
var<immediate> push_constants: PushConstants; var<immediate> push_constants: PushConstants;
@@ -34,6 +39,7 @@ struct ComputeInput {
fn main(compute_input: ComputeInput) { fn main(compute_input: ComputeInput) {
let metadata = &tape_metadata_buffer.metadata[push_constants.metadata_buffer_offset]; let metadata = &tape_metadata_buffer.metadata[push_constants.metadata_buffer_offset];
if (push_constants.flags & FLAG_FILL_ENABLE_GEN) > 0 {
let total_invocations = compute_input.num_workgroups * vec3u(8); let total_invocations = compute_input.num_workgroups * vec3u(8);
let base_index = let base_index =
(((compute_input.global_invocation_id.z * total_invocations.y) (((compute_input.global_invocation_id.z * total_invocations.y)
@@ -55,6 +61,7 @@ fn main(compute_input: ComputeInput) {
) / f32(1 << metadata.subdivision_log2), ) / f32(1 << metadata.subdivision_log2),
); );
let low_corner = let low_corner =
(((vec3(0.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions) (((vec3(0.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions)
+ metadata.lowest_corner; + metadata.lowest_corner;
@@ -63,8 +70,8 @@ fn main(compute_input: ComputeInput) {
+ metadata.lowest_corner; + metadata.lowest_corner;
let interval = interval_scene( let interval = interval_scene(
vec4(low_corner, push_constants.time), vec4(low_corner, metadata.time),
vec4(high_corner, push_constants.time), vec4(high_corner, metadata.time),
); );
let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index]; let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index];
@@ -82,3 +89,16 @@ fn main(compute_input: ComputeInput) {
aabb.min_x = NAN(); 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.));
}
}
@@ -1,7 +1,6 @@
struct TapeMetadata { struct TapeMetadata {
/// AABB for decompressing positions.
lowest_corner: vec3<f32>, lowest_corner: vec3<f32>,
pad_a: u32, time: f32,
dimensions: vec3<f32>, dimensions: vec3<f32>,
subdivision_log2: u32, subdivision_log2: u32,
} }
+15 -11
View File
@@ -16,7 +16,7 @@ use bevy_platform::collections::HashMap;
use bevy_render::{ use bevy_render::{
GpuResourceAppExt, Render, RenderApp, RenderSystems, GpuResourceAppExt, Render, RenderApp, RenderSystems,
render_asset::{ExtractedAssets, prepare_assets}, render_asset::{ExtractedAssets, prepare_assets},
render_resource::Texture, render_resource::{Texture, TextureView},
renderer::{RenderDevice, RenderQueue}, renderer::{RenderDevice, RenderQueue},
slab_allocator::{ slab_allocator::{
Slab, SlabAllocationBufferSlice, SlabAllocator, SlabAllocatorSettings, SlabId, SlabItem, Slab, SlabAllocationBufferSlice, SlabAllocator, SlabAllocatorSettings, SlabId, SlabItem,
@@ -26,7 +26,7 @@ use bevy_render::{
use wgpu::{ use wgpu::{
BufferUsages, COPY_BUFFER_ALIGNMENT, Extent3d, TextureDimension, TextureFormat, TextureUsages, BufferUsages, COPY_BUFFER_ALIGNMENT, Extent3d, TextureDimension, TextureFormat, TextureUsages,
}; };
use wgpu_types::TextureDescriptor; use wgpu_types::{TextureDescriptor, TextureViewDescriptor};
use super::{PackedAabb, RenderTape, TapeMetadata}; use super::{PackedAabb, RenderTape, TapeMetadata};
use crate::tape::Tape; use crate::tape::Tape;
@@ -48,7 +48,7 @@ pub struct TapeAllocator {
/// Holds all buffers and offset allocators. /// Holds all buffers and offset allocators.
#[deref] #[deref]
slab_allocator: SlabAllocator<TapeSlabItem>, slab_allocator: SlabAllocator<TapeSlabItem>,
spatial_texture_allocator: HashMap<AssetId<Tape>, Texture>, spatial_texture_allocator: HashMap<AssetId<Tape>, (Texture, TextureView)>,
} }
/// Tunable parameters that customize the behavior of the allocator. /// 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. /// Returns the spatial texture for the tape with the given ID.
/// ///
/// If the tape wasn't allocated, returns None. /// If the tape wasn't allocated, returns None.
pub fn tape_spatial_texture(&self, tape_id: &AssetId<Tape>) -> Option<&Texture> { pub fn tape_spatial_texture(&self, tape_id: &AssetId<Tape>) -> Option<&(Texture, TextureView)> {
self.spatial_texture_allocator.get(tape_id) self.spatial_texture_allocator.get(tape_id)
} }
@@ -376,10 +376,7 @@ impl TapeAllocator {
tape_allocator_settings, tape_allocator_settings,
); );
// Allocate spatial texture. let texture = render_device.create_texture(&TextureDescriptor {
self.spatial_texture_allocator.insert(
*tape_id,
render_device.create_texture(&TextureDescriptor {
label: Some(&format!("Tape {} spatial texture", tape_id)), label: Some(&format!("Tape {} spatial texture", tape_id)),
format: TextureFormat::R32Float, format: TextureFormat::R32Float,
dimension: TextureDimension::D3, dimension: TextureDimension::D3,
@@ -392,8 +389,15 @@ impl TapeAllocator {
height: tape.subdivision, height: tape.subdivision,
depth_or_array_layers: 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, (texture, texture_view));
} }
// Perform growth. // Perform growth.
@@ -430,7 +434,7 @@ impl TapeAllocator {
lowest_corner, lowest_corner,
dimensions, dimensions,
subdivision_log2: tape.subdivision.ilog2(), subdivision_log2: tape.subdivision.ilog2(),
..Default::default() time: tape.time,
} }
}; };
// Call the generic function. // Call the generic function.
+12 -69
View File
@@ -19,13 +19,19 @@ use bevy_render::{
render_resource::{ render_resource::{
BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, CachedComputePipelineId, BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, CachedComputePipelineId,
ComputePipelineDescriptor, PipelineCache, ShaderType, 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 bevy_shader::{Shader, load_shader_library};
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use rspirv::dr::Module; use rspirv::dr::Module;
use wgpu::{ShaderModuleDescriptorPassthrough, ShaderStages, include_spirv_raw}; use wgpu::{
ShaderModuleDescriptorPassthrough, ShaderStages, StorageTextureAccess, TextureFormat,
TextureSampleType, include_spirv_raw,
};
use crate::{ use crate::{
render::allocator::{ElementClass, TapeAllocationKey, TapeAllocator, TapeSlabId}, render::allocator::{ElementClass, TapeAllocationKey, TapeAllocator, TapeSlabId},
@@ -47,7 +53,7 @@ pub struct PackedAabb {
#[repr(C)] #[repr(C)]
pub struct TapeMetadata { pub struct TapeMetadata {
lowest_corner: Vec3, lowest_corner: Vec3,
pad_a: u32, time: f32,
dimensions: Vec3, dimensions: Vec3,
subdivision_log2: u32, subdivision_log2: u32,
} }
@@ -82,9 +88,7 @@ impl Plugin for TapeRenderAssetPlugin {
let modules = ReplacementModules { let modules = ReplacementModules {
enable_gen: get_module(enable_gen.clone()), enable_gen: get_module(enable_gen.clone()),
fuzz: get_module(enable_gen.clone()),
normals: get_module(enable_gen.clone()), normals: get_module(enable_gen.clone()),
spatial_texture: get_module(enable_gen.clone()),
trace: get_module(enable_gen.clone()), trace: get_module(enable_gen.clone()),
enable_gen_layout: BindGroupLayoutDescriptor::new( enable_gen_layout: BindGroupLayoutDescriptor::new(
"Enable Gen Layout", "Enable Gen Layout",
@@ -93,28 +97,12 @@ impl Plugin for TapeRenderAssetPlugin {
( (
storage_buffer::<PackedAabb>(false), storage_buffer::<PackedAabb>(false),
storage_buffer_read_only::<TapeMetadata>(false), storage_buffer_read_only::<TapeMetadata>(false),
texture_storage_3d(
TextureFormat::R32Float,
StorageTextureAccess::WriteOnly,
), ),
), ),
), ),
fuzz_layout: BindGroupLayoutDescriptor::new(
"Tape Fuzz Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer::<PackedAabb>(false),
storage_buffer_read_only::<TapeMetadata>(false),
),
),
),
spatial_texture_layout: BindGroupLayoutDescriptor::new(
"Spatial Texture Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer::<PackedAabb>(false),
storage_buffer_read_only::<TapeMetadata>(false),
),
),
), ),
}; };
@@ -172,14 +160,10 @@ pub fn prepare_tape_metadata_fallback_buffer(
#[derive(Resource)] #[derive(Resource)]
pub struct ReplacementModules { pub struct ReplacementModules {
pub enable_gen: Module, pub enable_gen: Module,
pub fuzz: Module,
pub normals: Module, pub normals: Module,
pub spatial_texture: Module,
pub trace: Module, pub trace: Module,
pub enable_gen_layout: BindGroupLayoutDescriptor, pub enable_gen_layout: BindGroupLayoutDescriptor,
pub fuzz_layout: BindGroupLayoutDescriptor,
pub spatial_texture_layout: BindGroupLayoutDescriptor,
} }
/// The render world representation of a [`Tape`]. /// The render world representation of a [`Tape`].
@@ -191,14 +175,10 @@ pub struct RenderTape {
pub key: u64, pub key: u64,
pub enable_gen: Handle<Shader>, pub enable_gen: Handle<Shader>,
pub fuzz: Handle<Shader>,
pub normals: Handle<Shader>, pub normals: Handle<Shader>,
pub spatial_texture: Handle<Shader>,
pub trace: Handle<Shader>, pub trace: Handle<Shader>,
pub enable_gen_pipeline: CachedComputePipelineId, pub enable_gen_pipeline: CachedComputePipelineId,
pub fuzz_pipeline: CachedComputePipelineId,
pub spatial_texture_pipeline: CachedComputePipelineId,
} }
impl RenderAsset for RenderTape { impl RenderAsset for RenderTape {
@@ -239,13 +219,9 @@ impl RenderAsset for RenderTape {
time: tape.time, time: tape.time,
key, key,
enable_gen: previous.enable_gen.clone(), enable_gen: previous.enable_gen.clone(),
fuzz: previous.fuzz.clone(),
normals: previous.normals.clone(), normals: previous.normals.clone(),
spatial_texture: previous.spatial_texture.clone(),
trace: previous.trace.clone(), trace: previous.trace.clone(),
enable_gen_pipeline: previous.enable_gen_pipeline, 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(), replacement_modules.enable_gen.clone(),
"enable_gen", "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( let normals = asset_server.add(tape.sdf_specialize_module_with_key(
key, key,
replacement_modules.normals.clone(), replacement_modules.normals.clone(),
"normals", "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( let trace = asset_server.add(tape.sdf_specialize_module_with_key(
key, key,
replacement_modules.trace.clone(), replacement_modules.trace.clone(),
@@ -285,38 +251,15 @@ impl RenderAsset for RenderTape {
..Default::default() ..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 { Ok(RenderTape {
seed: tape.seed, seed: tape.seed,
subdivision: tape.subdivision, subdivision: tape.subdivision,
time: tape.time, time: tape.time,
key, key,
enable_gen, enable_gen,
fuzz,
normals, normals,
spatial_texture,
trace, trace,
enable_gen_pipeline, enable_gen_pipeline,
fuzz_pipeline,
spatial_texture_pipeline,
}) })
} }