6 Commits

Author SHA1 Message Date
molive cdfa783908 wip 2026-11-24 00:20:02 +00:00
molive 2ebc29cae3 tiletree work queue system works 2026-11-12 00:45:43 +00:00
molive 8c87c549d3 split out shaders 2026-11-11 20:56:03 +00:00
molive d4bdb18a14 write normals to tiletree texture 2026-11-02 23:34:10 +00:00
molive ec7c5623de tiletrees? 2026-11-02 22:00:01 +00:00
molive 78df66b46c defer blas until ready 2026-11-02 21:47:11 +00:00
33 changed files with 1213 additions and 660 deletions
+9 -7
View File
@@ -15,18 +15,18 @@ pub mod scene;
/// The solari prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
/// This includes the most common types in this crate, re-exported for your
/// convenience.
pub mod prelude {
pub use super::SolariPlugins;
pub use crate::realtime::SolariLighting;
pub use crate::scene::RaytracingMesh3d;
pub use crate::{realtime::SolariLighting, scene::RaytracingMesh3d};
}
use crate::realtime::SolariLightingPlugin;
use crate::scene::RaytracingScenePlugin;
use bevy_app::{PluginGroup, PluginGroupBuilder};
use bevy_render::settings::WgpuFeatures;
use crate::{realtime::SolariLightingPlugin, scene::RaytracingScenePlugin};
/// An experimental set of plugins for raytraced lighting.
///
/// This plugin group provides:
@@ -34,9 +34,11 @@ use bevy_render::settings::WgpuFeatures;
/// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding.
///
/// There's also:
/// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for validation purposes (not added by default).
/// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for
/// validation purposes (not added by default).
///
/// To get started, add this plugin to your app, and then add `RaytracingMesh3d` and `MeshMaterial3d::<StandardMaterial>` to your entities.
/// To get started, add this plugin to your app, and then add `RaytracingMesh3d`
/// and `MeshMaterial3d::<StandardMaterial>` to your entities.
pub struct SolariPlugins;
impl PluginGroup for SolariPlugins {
@@ -1,4 +1,3 @@
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
use bevy_camera::Camera;
use bevy_ecs::{
change_detection::DetectChanges,
@@ -8,6 +7,8 @@ use bevy_ecs::{
use bevy_render::{Extract, sync_world::RenderEntity};
use bevy_transform::components::GlobalTransform;
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
pub fn extract_pathtracer(
cameras_3d: Extract<
Query<(
@@ -2,7 +2,6 @@ mod extract;
mod node;
mod prepare;
use crate::{SolariPlugins, scene::RaytracingSceneBindings};
use bevy_app::{App, Plugin, PostUpdate};
use bevy_asset::embedded_asset;
use bevy_camera::Hdr;
@@ -29,6 +28,8 @@ use node::{init_pathtracer_pipelines, pathtracer};
use prepare::prepare_pathtracer_accumulation_texture;
use tracing::warn;
use crate::{SolariPlugins, scene::RaytracingSceneBindings};
/// Non-realtime pathtracing.
///
/// This plugin is meant to generate reference screenshots to compare against,
@@ -81,7 +82,8 @@ pub struct Pathtracer {
pub reset: bool,
}
/// Turn off atmosphere cubemap filtering for pathtracer cameras to save performance, since the pathtracer does not require it.
/// Turn off atmosphere cubemap filtering for pathtracer cameras to save
/// performance, since the pathtracer does not require it.
fn disable_atmosphere_env_map_filtering(
mut commands: Commands,
lights: Query<(Entity, &AtmosphereEnvironmentMapLight), With<Pathtracer>>,
@@ -91,7 +93,8 @@ fn disable_atmosphere_env_map_filtering(
continue;
}
// Re-insert so the insert observer rebuilds the env map without filtering.
// Re-insert so the insert observer rebuilds the env map without
// filtering.
commands
.entity(entity)
.insert(AtmosphereEnvironmentMapLight {
@@ -1,5 +1,3 @@
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
use crate::scene::RaytracingSceneBindings;
use bevy_asset::{AssetServer, load_embedded_asset};
use bevy_ecs::{prelude::*, resource::Resource, system::Commands};
use bevy_render::{
@@ -15,11 +13,14 @@ use bevy_render::{
};
use bevy_utils::default;
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
use crate::scene::RaytracingSceneBindings;
/// Resource holding the pathtracer pipeline configuration.
#[derive(Resource)]
pub struct PathtracerPipelines {
bind_group_layout: BindGroupLayoutDescriptor,
pipeline: CachedComputePipelineId,
pipeline: CachedComputePipelineId,
}
/// Initializes the pathtracer pipelines at render startup.
@@ -108,7 +109,7 @@ pub fn pathtracer(
}
let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("pathtracer"),
label: Some("pathtracer"),
timestamp_writes: None,
});
pass.set_pipeline(pipeline);
@@ -1,4 +1,3 @@
use super::Pathtracer;
use bevy_ecs::{
component::Component,
entity::Entity,
@@ -13,6 +12,8 @@ use bevy_render::{
texture::{CachedTexture, TextureCache},
};
use super::Pathtracer;
#[derive(Component)]
pub struct PathtracerAccumulationTexture(pub CachedTexture);
@@ -28,14 +29,14 @@ pub fn prepare_pathtracer_accumulation_texture(
};
let descriptor = TextureDescriptor {
label: Some("pathtracer_accumulation_texture"),
size: viewport.to_extents(),
label: Some("pathtracer_accumulation_texture"),
size: viewport.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba32Float,
usage: TextureUsages::STORAGE_BINDING,
view_formats: &[],
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba32Float,
usage: TextureUsages::STORAGE_BINDING,
view_formats: &[],
};
commands
@@ -1,9 +1,10 @@
use super::{SolariLighting, prepare::SolariLightingResources};
use bevy_camera::Camera;
use bevy_ecs::system::{Commands, ResMut};
use bevy_pbr::deferred::SkipDeferredLighting;
use bevy_render::{MainWorld, sync_world::RenderEntity};
use super::{SolariLighting, prepare::SolariLightingResources};
pub fn extract_solari_lighting(mut main_world: ResMut<MainWorld>, mut commands: Commands) {
let mut cameras_3d = main_world.query::<(RenderEntity, &Camera, Option<&mut SolariLighting>)>();
@@ -2,10 +2,6 @@ mod extract;
mod node;
mod prepare;
use crate::{
SolariPlugins,
scene::{RaytracingSceneBindings, prepare_raytracing_scene_resources},
};
use bevy_app::{App, Plugin, PostUpdate};
use bevy_asset::embedded_asset;
use bevy_camera::Hdr;
@@ -40,10 +36,15 @@ use prepare::{
};
use tracing::warn;
use crate::{
SolariPlugins,
scene::{RaytracingSceneBindings, prepare_raytracing_scene_resources},
};
/// Raytraced direct and indirect lighting.
///
/// When using this plugin, it's highly recommended to set `shadow_maps_enabled: false` on all lights, as Solari replaces
/// traditional shadow mapping.
/// When using this plugin, it's highly recommended to set `shadow_maps_enabled:
/// false` on all lights, as Solari replaces traditional shadow mapping.
pub struct SolariLightingPlugin;
impl Plugin for SolariLightingPlugin {
@@ -109,22 +110,27 @@ impl Plugin for SolariLightingPlugin {
}
}
/// A component for a 3d camera entity to enable the Solari raytraced lighting system.
/// A component for a 3d camera entity to enable the Solari raytraced lighting
/// system.
///
/// Must be used with `CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING)`, and
/// `Msaa::Off`.
/// Must be used with
/// `CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING)`,
/// and `Msaa::Off`.
#[derive(Component, Reflect, Clone)]
#[reflect(Component, Default, Clone)]
#[require(Hdr, DeferredPrepass, DepthPrepass, MotionVectorPrepass)]
pub struct SolariLighting {
/// [ReSTIR](https://en.wikipedia.org/wiki/Spatiotemporal_reservoir_resampling) is a technique to reuse path samples
/// between pixels and frames. This dramatically reduces noise, at the cost of a few extra rays per pixel.
/// between pixels and frames. This dramatically reduces noise, at the cost
/// of a few extra rays per pixel.
///
/// However, modern denoisers cope well with very noisy input. In many cases, turning this on
/// won't dramatically improve quality after denoising.
/// However, modern denoisers cope well with very noisy input. In many
/// cases, turning this on won't dramatically improve quality after
/// denoising.
///
/// If you want more fine shadow detail, or have scenes with more difficult lighting conditions,
/// turning this on may improve quality and stability, at the cost of a decent chunk of performance.
/// If you want more fine shadow detail, or have scenes with more difficult
/// lighting conditions, turning this on may improve quality and stability,
/// at the cost of a decent chunk of performance.
///
/// Whether to enable this setting or not will be very scene dependent.
///
@@ -143,8 +149,8 @@ pub struct SolariLighting {
/// Number of direct light samples taken for the camera's primary hit during
/// initial sampling.
///
/// Higher values reduce noise in directly-lit areas at the cost of more work
/// per frame. Lower values are faster but noisier.
/// Higher values reduce noise in directly-lit areas at the cost of more
/// work per frame. Lower values are faster but noisier.
pub primary_di_samples: u32,
/// Number of direct light samples taken at each indirect bounce during
@@ -156,9 +162,9 @@ pub struct SolariLighting {
/// Maximum number of bounces traced when generating an initial path.
///
/// Higher values capture more detail in nested reflections and more indirect lighting,
/// at the cost of more rays traced per frame. Lower values are faster but lose
/// multi-bounce lighting for specular paths.
/// Higher values capture more detail in nested reflections and more
/// indirect lighting, at the cost of more rays traced per frame. Lower
/// values are faster but lose multi-bounce lighting for specular paths.
pub max_bounces: u32,
/// How responsive the world cache is to changes in lighting.
@@ -178,18 +184,20 @@ pub struct SolariLighting {
/// Maximum distance to trace GI rays between two world cache cells.
///
/// Higher values capture indirect light from farther away for more accurate
/// GI at the cost of longer (more expensive) ray traversal and increased noise.
/// Lower values are faster and less noisy but may miss distant lighting or leak sky lighting.
/// GI at the cost of longer (more expensive) ray traversal and increased
/// noise. Lower values are faster and less noisy but may miss distant
/// lighting or leak sky lighting.
///
/// Rays that miss within this distance are treated as reaching the environment
/// map light, and leak sky lighting into the cache.
/// Rays that miss within this distance are treated as reaching the
/// environment map light, and leak sky lighting into the cache.
pub world_cache_max_gi_ray_distance: f32,
/// Soft upper limit on the number of world cache cells to update each frame.
/// Soft upper limit on the number of world cache cells to update each
/// frame.
///
/// Higher values let the cache converge faster after lighting changes at the
/// cost of more work per frame. Lower values are cheaper but make the cache
/// slower to update.
/// Higher values let the cache converge faster after lighting changes at
/// the cost of more work per frame. Lower values are cheaper but make the
/// cache slower to update.
///
/// This is a stochastic target that only takes effect when the number of
/// active cells exceeds it: each active cell is then updated with
@@ -208,10 +216,10 @@ pub struct SolariLighting {
/// How fast the world cache transitions between LODs as a function of
/// distance to the camera.
///
/// Higher values keep cells small (high detail) out to greater distances for
/// better quality at the cost of more cells to fill. Lower values transition
/// to larger cells sooner, which is cheaper but coarser farther from the
/// camera.
/// Higher values keep cells small (high detail) out to greater distances
/// for better quality at the cost of more cells to fill. Lower values
/// transition to larger cells sooner, which is cheaper but coarser farther
/// from the camera.
pub world_cache_position_lod_scale: f32,
/// Set to true to delete the saved temporal history (past frames).
@@ -243,7 +251,8 @@ impl Default for SolariLighting {
}
}
/// Adds or removes the prepass double-buffer components according to [`SolariLighting::restir`].
/// Adds or removes the prepass double-buffer components according to
/// [`SolariLighting::restir`].
fn manage_prepass_double_buffers(
views: Query<(
Entity,
@@ -273,7 +282,8 @@ fn manage_prepass_double_buffers(
}
}
/// Turn off atmosphere cubemap filtering for Solari cameras to save performance, since Solari does not require it.
/// Turn off atmosphere cubemap filtering for Solari cameras to save
/// performance, since Solari does not require it.
fn disable_atmosphere_env_map_filtering(
mut commands: Commands,
lights: Query<(Entity, &AtmosphereEnvironmentMapLight), With<SolariLighting>>,
@@ -283,7 +293,8 @@ fn disable_atmosphere_env_map_filtering(
continue;
}
// Re-insert so the insert observer rebuilds the env map without filtering.
// Re-insert so the insert observer rebuilds the env map without
// filtering.
commands
.entity(entity)
.insert(AtmosphereEnvironmentMapLight {
@@ -1,8 +1,3 @@
use super::prepare::{
LIGHT_TILE_BLOCKS, SolariLightingResources, WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET,
WORLD_CACHE_SIZE,
};
use crate::scene::RaytracingSceneBindings;
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
use bevy_anti_alias::dlss::ViewDlssRayReconstructionTextures;
use bevy_asset::{AssetServer, Handle, load_embedded_asset};
@@ -29,6 +24,12 @@ use bevy_render::{
use bevy_shader::{Shader, ShaderDefVal};
use bevy_utils::default;
use super::prepare::{
LIGHT_TILE_BLOCKS, SolariLightingResources, WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET,
WORLD_CACHE_SIZE,
};
use crate::scene::RaytracingSceneBindings;
/// Resource holding the Solari lighting pipeline configuration.
#[derive(Resource)]
pub struct SolariLightingPipelines {
@@ -52,14 +53,14 @@ pub struct SolariLightingPipelines {
}
struct RestirPipelines {
initial_and_temporal: CachedComputePipelineId,
initial_and_temporal: CachedComputePipelineId,
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
initial_and_temporal_with_psr: CachedComputePipelineId,
spatial_and_shade: CachedComputePipelineId,
spatial_and_shade: CachedComputePipelineId,
}
struct NoRestirPipelines {
initial_and_shade: CachedComputePipelineId,
initial_and_shade: CachedComputePipelineId,
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
initial_and_shade_with_psr: CachedComputePipelineId,
}
@@ -200,7 +201,8 @@ pub fn solari_lighting(
return;
};
// Past every bail-out, so this view's reservoirs will be brought up to this frame's light ids
// Past every bail-out, so this view's reservoirs will be brought up to this
// frame's light ids
if restir.is_some() {
scene_bindings.note_light_translations_consumed();
}
@@ -280,17 +282,17 @@ pub fn solari_lighting(
// Clear the view target if we're the first node to write to it
if matches!(view_target_attachment.ops.load, LoadOp::Clear(_)) {
command_encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("solari_lighting_clear"),
color_attachments: &[Some(view_target_attachment)],
label: Some("solari_lighting_clear"),
color_attachments: &[Some(view_target_attachment)],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
}
let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("solari_lighting"),
label: Some("solari_lighting"),
timestamp_writes: None,
});
@@ -490,14 +492,14 @@ pub fn init_solari_lighting_pipelines(
};
let mut layout = vec![scene_bindings.bind_group_layout.clone(), group_1.clone()];
match extra_bind_group {
ExtraBindGroup::None => {}
ExtraBindGroup::None => {},
ExtraBindGroup::WorldCacheDispatch => {
layout.push(bind_group_layout_world_cache_active_cells_dispatch.clone());
}
},
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
ExtraBindGroup::DlssRrGuideBuffers => {
layout.push(bind_group_layout_resolve_dlss_rr_textures.clone());
}
},
}
let mut shader_defs = vec![ShaderDefVal::UInt(
@@ -511,14 +513,14 @@ pub fn init_solari_lighting_pipelines(
shader_defs.push("RESTIR".into());
}
match extra_bind_group {
ExtraBindGroup::None => {}
ExtraBindGroup::None => {},
ExtraBindGroup::WorldCacheDispatch => {
shader_defs.push("WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into());
}
},
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
ExtraBindGroup::DlssRrGuideBuffers => {
shader_defs.push("DLSS_RR_GUIDE_BUFFERS".into());
}
},
}
shader_defs.extend_from_slice(&extra_shader_defs);
@@ -605,7 +607,7 @@ pub fn init_solari_lighting_pipelines(
vec![],
),
restir: RestirPipelines {
initial_and_temporal: create_pipeline(
initial_and_temporal: create_pipeline(
"solari_lighting_initial_and_temporal_pipeline",
"initial_and_temporal",
load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
@@ -622,7 +624,7 @@ pub fn init_solari_lighting_pipelines(
ExtraBindGroup::DlssRrGuideBuffers,
vec![],
),
spatial_and_shade: create_pipeline(
spatial_and_shade: create_pipeline(
"solari_lighting_spatial_and_shade_pipeline",
"spatial_and_shade",
load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
@@ -632,7 +634,7 @@ pub fn init_solari_lighting_pipelines(
),
},
no_restir: NoRestirPipelines {
initial_and_shade: create_pipeline(
initial_and_shade: create_pipeline(
"solari_lighting_initial_and_shade_pipeline",
"initial_and_shade",
load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),
@@ -1,5 +1,3 @@
use super::SolariLighting;
use crate::scene::RaytracingSceneNeedsPreviousFrameData;
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
use bevy_anti_alias::dlss::{
Dlss, DlssRayReconstructionFeature, ViewDlssRayReconstructionTextures,
@@ -30,6 +28,9 @@ use bevy_render::{
};
use bytemuck::{Pod, Zeroable};
use super::SolariLighting;
use crate::scene::RaytracingSceneNeedsPreviousFrameData;
/// Size of the `LightSample` shader struct in bytes.
const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8;
@@ -44,19 +45,21 @@ pub const LIGHT_TILE_SAMPLES_PER_BLOCK: u64 = 1024;
/// Amount of entries in the world cache (must be a power of 2, and >= 2^10)
pub const WORLD_CACHE_SIZE: u64 = 2u64.pow(20);
/// Sum of per-cell field sizes in `WorldCache`. Keep in sync with `realtime_bindings.wgsl`.
/// Sum of per-cell field sizes in `WorldCache`. Keep in sync with
/// `realtime_bindings.wgsl`.
const WORLD_CACHE_ENTRY_SIZE: u64 = 84;
/// Size of the fixed `b` array (`array<u32, WORLD_CACHE_SIZE / 1024>`).
const WORLD_CACHE_B_SIZE: u64 = (WORLD_CACHE_SIZE / 1024) * size_of::<u32>() as u64;
/// Offset of `active_cells_count`.
pub const WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET: u64 =
WORLD_CACHE_SIZE * WORLD_CACHE_ENTRY_SIZE + WORLD_CACHE_B_SIZE;
/// Must stay under wgpu's default `max_storage_buffer_binding_size` (128 MiB or 2^27 bytes).
/// Must stay under wgpu's default `max_storage_buffer_binding_size` (128 MiB or
/// 2^27 bytes).
pub const WORLD_CACHE_BUFFER_SIZE: u64 =
(WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET + size_of::<u32>() as u64).next_multiple_of(16);
/// GPU representation of the user-configurable [`SolariLighting`] settings, plus
/// per-frame state.
/// GPU representation of the user-configurable [`SolariLighting`] settings,
/// plus per-frame state.
///
/// Field order and types must match the `SolariLightingSettings` struct in
/// `realtime_bindings.wgsl`.
@@ -96,7 +99,8 @@ impl SolariLightingUniforms {
}
}
/// Declares to the raytracing scene whether any view needs last frame's TLAS and light ids.
/// Declares to the raytracing scene whether any view needs last frame's TLAS
/// and light ids.
pub fn setup_raytracing_scene_needs_previous_frame_data(
views: Query<&SolariLighting>,
needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
@@ -106,7 +110,7 @@ pub fn setup_raytracing_scene_needs_previous_frame_data(
match (restir_used, needs_previous_frame_data.is_some()) {
(true, false) => commands.insert_resource(RaytracingSceneNeedsPreviousFrameData),
(false, true) => commands.remove_resource::<RaytracingSceneNeedsPreviousFrameData>(),
_ => {}
_ => {},
}
}
@@ -176,7 +180,8 @@ pub fn prepare_solari_lighting_resources(
SolariLightingUniforms::new(solari_lighting, frame_count.0, reusable.is_none());
if let Some(solari_lighting_resources) = reusable {
// The constants uniform can change every frame, so always upload it.
// The constants uniform can change every frame, so always upload
// it.
render_queue.write_buffer(
&solari_lighting_resources.constants,
0,
@@ -186,33 +191,35 @@ pub fn prepare_solari_lighting_resources(
}
let constants = render_device.create_buffer_with_data(&BufferInitDescriptor {
label: Some("solari_lighting_constants"),
label: Some("solari_lighting_constants"),
contents: bytemuck::bytes_of(&uniforms),
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
});
let light_tile_samples = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_light_tile_samples"),
size: LIGHT_TILE_BLOCKS * LIGHT_TILE_SAMPLES_PER_BLOCK * LIGHT_SAMPLE_STRUCT_SIZE,
usage: BufferUsages::STORAGE,
label: Some("solari_lighting_light_tile_samples"),
size: LIGHT_TILE_BLOCKS
* LIGHT_TILE_SAMPLES_PER_BLOCK
* LIGHT_SAMPLE_STRUCT_SIZE,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let light_tile_resolved_samples = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_light_tile_resolved_samples"),
size: LIGHT_TILE_BLOCKS
label: Some("solari_lighting_light_tile_resolved_samples"),
size: LIGHT_TILE_BLOCKS
* LIGHT_TILE_SAMPLES_PER_BLOCK
* RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE,
usage: BufferUsages::STORAGE,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let reservoirs = solari_lighting.restir.then(|| {
let reservoirs_buffer = |name| {
render_device.create_buffer(&BufferDescriptor {
label: Some(name),
size: (view_size.x * view_size.y) as u64 * RESERVOIR_STRUCT_SIZE,
usage: BufferUsages::STORAGE,
label: Some(name),
size: (view_size.x * view_size.y) as u64 * RESERVOIR_STRUCT_SIZE,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
})
};
@@ -223,16 +230,16 @@ pub fn prepare_solari_lighting_resources(
});
let world_cache = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_world_cache"),
size: WORLD_CACHE_BUFFER_SIZE,
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
label: Some("solari_lighting_world_cache"),
size: WORLD_CACHE_BUFFER_SIZE,
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let world_cache_active_cells_dispatch = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_world_cache_active_cells_dispatch"),
size: size_of::<[u32; 3]>() as u64,
usage: BufferUsages::INDIRECT | BufferUsages::STORAGE,
label: Some("solari_lighting_world_cache_active_cells_dispatch"),
size: size_of::<[u32; 3]>() as u64,
usage: BufferUsages::INDIRECT | BufferUsages::STORAGE,
mapped_at_creation: false,
});
@@ -249,64 +256,64 @@ pub fn prepare_solari_lighting_resources(
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
if has_dlss_rr {
let diffuse_albedo = render_device.create_texture(&TextureDescriptor {
label: Some("solari_lighting_diffuse_albedo"),
size: view_size.to_extents(),
label: Some("solari_lighting_diffuse_albedo"),
size: view_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
});
let diffuse_albedo_view = diffuse_albedo.create_view(&TextureViewDescriptor::default());
let specular_albedo = render_device.create_texture(&TextureDescriptor {
label: Some("solari_lighting_specular_albedo"),
size: view_size.to_extents(),
label: Some("solari_lighting_specular_albedo"),
size: view_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
});
let specular_albedo_view =
specular_albedo.create_view(&TextureViewDescriptor::default());
let normal_roughness = render_device.create_texture(&TextureDescriptor {
label: Some("solari_lighting_normal_roughness"),
size: view_size.to_extents(),
label: Some("solari_lighting_normal_roughness"),
size: view_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba16Float,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba16Float,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
});
let normal_roughness_view =
normal_roughness.create_view(&TextureViewDescriptor::default());
let dlss_rr_depth = render_device.create_texture(&TextureDescriptor {
label: Some("solari_lighting_dlss_rr_depth"),
size: view_size.to_extents(),
label: Some("solari_lighting_dlss_rr_depth"),
size: view_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::R32Float,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::R32Float,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
});
let dlss_rr_depth_view = dlss_rr_depth.create_view(&TextureViewDescriptor::default());
let specular_motion_vectors = render_device.create_texture(&TextureDescriptor {
label: Some("solari_lighting_specular_motion_vectors"),
size: view_size.to_extents(),
label: Some("solari_lighting_specular_motion_vectors"),
size: view_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rg16Float,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rg16Float,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
view_formats: &[],
});
let specular_motion_vectors_view =
specular_motion_vectors.create_view(&TextureViewDescriptor::default());
@@ -314,24 +321,24 @@ pub fn prepare_solari_lighting_resources(
commands
.entity(entity)
.insert(ViewDlssRayReconstructionTextures {
diffuse_albedo: CachedTexture {
texture: diffuse_albedo,
diffuse_albedo: CachedTexture {
texture: diffuse_albedo,
default_view: diffuse_albedo_view,
},
specular_albedo: CachedTexture {
texture: specular_albedo,
specular_albedo: CachedTexture {
texture: specular_albedo,
default_view: specular_albedo_view,
},
normal_roughness: CachedTexture {
texture: normal_roughness,
normal_roughness: CachedTexture {
texture: normal_roughness,
default_view: normal_roughness_view,
},
depth: CachedTexture {
texture: dlss_rr_depth,
depth: CachedTexture {
texture: dlss_rr_depth,
default_view: dlss_rr_depth_view,
},
specular_motion_vectors: CachedTexture {
texture: specular_motion_vectors,
texture: specular_motion_vectors,
default_view: specular_motion_vectors_view,
},
});
@@ -1,27 +1,30 @@
use bevy_platform::collections::HashMap;
use core::{hash::Hash, num::NonZeroU32};
use bevy_platform::collections::HashMap;
/// A free-list allocator for `u32` array indices meant for GPU allocations.
pub struct IndexAllocator {
free: Vec<u32>,
/// Released by [`IndexAllocator::retire`], and not reusable until [`IndexAllocator::recycle_retired`].
retired: Vec<u32>,
free: Vec<u32>,
/// Released by [`IndexAllocator::retire`], and not reusable until
/// [`IndexAllocator::recycle_retired`].
retired: Vec<u32>,
high_water_mark: u32,
}
impl IndexAllocator {
pub fn new() -> Self {
Self {
free: Vec::new(),
retired: Vec::new(),
free: Vec::new(),
retired: Vec::new(),
high_water_mark: 0,
}
}
/// An exclusive upper bound on every index handed out, for sizing and dispatching over the data
/// they key.
/// An exclusive upper bound on every index handed out, for sizing and
/// dispatching over the data they key.
///
/// Not a live count: released indices leave holes below it, and it never shrinks.
/// Not a live count: released indices leave holes below it, and it never
/// shrinks.
pub fn high_water_mark(&self) -> u32 {
self.high_water_mark
}
@@ -38,7 +41,8 @@ impl IndexAllocator {
self.free.push(index);
}
/// Releases an index, but holds it back from reuse until the next [`IndexAllocator::recycle_retired`].
/// Releases an index, but holds it back from reuse until the next
/// [`IndexAllocator::recycle_retired`].
///
/// For indices that last frame's GPU data can still reference.
pub fn retire(&mut self, index: u32) {
@@ -58,14 +62,14 @@ impl IndexAllocator {
/// Assigns each key an index that stays put for as long as the key is live.
pub struct SlotAllocator<K> {
slots: HashMap<K, u32>,
slots: HashMap<K, u32>,
indices: IndexAllocator,
}
impl<K: Eq + Hash> SlotAllocator<K> {
pub fn new() -> Self {
Self {
slots: HashMap::default(),
slots: HashMap::default(),
indices: IndexAllocator::new(),
}
}
@@ -94,7 +98,8 @@ impl<K: Eq + Hash> SlotAllocator<K> {
Some(slot)
}
/// How many more distinct keys can be taken on before running past `capacity`.
/// How many more distinct keys can be taken on before running past
/// `capacity`.
fn vacancies(&self, capacity: u32) -> u32 {
self.indices.vacancies(capacity)
}
@@ -102,20 +107,23 @@ impl<K: Eq + Hash> SlotAllocator<K> {
/// One occupied slot of a [`RetainedBindingArray`].
struct BindingSlot<T> {
item: T,
/// Live references to this slot. An occupied slot always has at least one live reference.
item: T,
/// Live references to this slot. An occupied slot always has at least one
/// live reference.
references: NonZeroU32,
}
/// A binding array whose indices are stable across frames.
///
/// Slots are reference counted by whatever points at them (e.g. materials for textures, instances for
/// mesh slab buffers), and are reused once the last reference goes away.
/// Slots are reference counted by whatever points at them (e.g. materials for
/// textures, instances for mesh slab buffers), and are reused once the last
/// reference goes away.
///
/// `dirty` marks that the contents have changed and the bind group has to be rebuilt.
/// `dirty` marks that the contents have changed and the bind group has to be
/// rebuilt.
pub struct RetainedBindingArray<K, T> {
allocator: SlotAllocator<K>,
slots: Vec<Option<BindingSlot<T>>>,
slots: Vec<Option<BindingSlot<T>>>,
pub dirty: bool,
}
@@ -123,8 +131,8 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
pub fn new() -> Self {
Self {
allocator: SlotAllocator::new(),
slots: Vec::new(),
dirty: false,
slots: Vec::new(),
dirty: false,
}
}
@@ -137,26 +145,31 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
self.allocator.vacancies(capacity)
}
/// Whether [`Self::acquire`] would be able to hand out a reference to `key`.
/// Whether [`Self::acquire`] would be able to hand out a reference to
/// `key`.
///
/// Callers that need more than one slot at once check this for all of them before acquiring
/// any, so that they never have to hand a slot straight back.
/// Callers that need more than one slot at once check this for all of them
/// before acquiring any, so that they never have to hand a slot straight
/// back.
pub fn has_room(&self, key: &K, capacity: u32) -> bool {
self.contains(key) || self.vacancies(capacity) > 0
}
/// The array's contents in slot order, with `None` for slots that are currently free.
/// The array's contents in slot order, with `None` for slots that are
/// currently free.
pub fn iter(&self) -> impl Iterator<Item = Option<&T>> {
self.slots
.iter()
.map(|slot| slot.as_ref().map(|slot| &slot.item))
}
/// Takes a reference to `key`'s slot, allocating and filling it if this is the first one.
/// Takes a reference to `key`'s slot, allocating and filling it if this is
/// the first one.
///
/// Returns `None` if `key` would need a new slot and every slot below `capacity` is taken. The
/// bind group layout declares these arrays with a fixed length, so running past it makes
/// `create_bind_group` fail outright, and callers have to drop whatever wanted the slot.
/// Returns `None` if `key` would need a new slot and every slot below
/// `capacity` is taken. The bind group layout declares these arrays with a
/// fixed length, so running past it makes `create_bind_group` fail
/// outright, and callers have to drop whatever wanted the slot.
pub fn acquire(&mut self, key: K, capacity: u32, item: impl FnOnce() -> T) -> Option<u32> {
if !self.has_room(&key, capacity) {
return None;
@@ -173,7 +186,7 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
occupied.references = occupied.references.saturating_add(1);
} else {
self.slots[index] = Some(BindingSlot {
item: item(),
item: item(),
references: NonZeroU32::MIN,
});
self.dirty = true;
@@ -202,7 +215,8 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
self.dirty = true;
}
/// Repoints an already-allocated slot at a new value, leaving its index and refcount alone.
/// Repoints an already-allocated slot at a new value, leaving its index and
/// refcount alone.
pub fn replace(&mut self, key: &K, item: T) {
if let Some(slot) = self.allocator.get(key)
&& let Some(occupied) = self.slots[slot as usize].as_mut()
@@ -260,7 +274,8 @@ mod tests {
assert!(!bindings.dirty);
assert!(bindings.contains(&7));
// The final release changes the binding array and makes the slot reusable
// The final release changes the binding array and makes the slot
// reusable
bindings.release(&7);
assert!(bindings.dirty);
assert!(!bindings.contains(&7));
@@ -1,8 +1,5 @@
use super::{
StandardMaterialAssets,
allocator::{RetainedBindingArray, SlotAllocator},
instances::InstanceState,
};
use core::num::NonZeroU32;
use bevy_asset::AssetId;
use bevy_color::{ColorToComponents, LinearRgba};
use bevy_image::Image;
@@ -18,16 +15,22 @@ use bevy_render::{
};
use bevy_utils::once;
use bytemuck::{Pod, Zeroable};
use core::num::NonZeroU32;
use tracing::{info_span, warn};
use super::{
StandardMaterialAssets,
allocator::{RetainedBindingArray, SlotAllocator},
instances::InstanceState,
};
pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap();
const TEXTURE_MAP_NONE: u32 = u32::MAX;
const MATERIAL_FLAG_DOUBLE_SIDED: u32 = 1 << 0;
const MATERIAL_FLAG_FLIP_NORMAL_MAP_Y: u32 = 1 << 1;
/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`] field order.
/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`]
/// field order.
type MaterialTextures = [Option<AssetId<Image>>; 4];
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
@@ -52,30 +55,35 @@ pub struct GpuMaterial {
impl_atomic_pod!(GpuMaterial, GpuMaterialBlob);
/// Stable material and texture slots, plus the retry state for assets that aren't ready yet.
/// Stable material and texture slots, plus the retry state for assets that
/// aren't ready yet.
pub struct AssetState {
pub textures: RetainedBindingArray<AssetId<Image>, (TextureView, Sampler)>,
pub materials: AtomicSparseBufferVec<GpuMaterial>,
pub material_slots: SlotAllocator<AssetId<StandardMaterial>>,
material_textures: HashMap<AssetId<StandardMaterial>, MaterialTextures>,
pub emissive_materials: HashSet<AssetId<StandardMaterial>>,
pub textures: RetainedBindingArray<AssetId<Image>, (TextureView, Sampler)>,
pub materials: AtomicSparseBufferVec<GpuMaterial>,
pub material_slots: SlotAllocator<AssetId<StandardMaterial>>,
material_textures: HashMap<AssetId<StandardMaterial>, MaterialTextures>,
pub emissive_materials: HashSet<AssetId<StandardMaterial>>,
pub non_opaque_materials: HashSet<AssetId<StandardMaterial>>,
/// Materials to retry because at least one required texture is not on the GPU yet.
unresolved_materials: HashSet<AssetId<StandardMaterial>>,
/// Materials to retry because at least one required texture is not on the
/// GPU yet.
unresolved_materials: HashSet<AssetId<StandardMaterial>>,
/// Bound images whose replacement GPU data has not landed yet.
pending_texture_updates: HashSet<AssetId<Image>>,
pending_texture_updates: HashSet<AssetId<Image>>,
}
impl AssetState {
pub fn new() -> Self {
Self {
textures: RetainedBindingArray::new(),
materials: AtomicSparseBufferVec::new(BufferUsages::STORAGE, "solari_materials".into()),
material_slots: SlotAllocator::new(),
material_textures: HashMap::default(),
emissive_materials: HashSet::default(),
non_opaque_materials: HashSet::default(),
unresolved_materials: HashSet::default(),
textures: RetainedBindingArray::new(),
materials: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_materials".into(),
),
material_slots: SlotAllocator::new(),
material_textures: HashMap::default(),
emissive_materials: HashSet::default(),
non_opaque_materials: HashSet::default(),
unresolved_materials: HashSet::default(),
pending_texture_updates: HashSet::default(),
}
}
@@ -121,7 +129,7 @@ impl AssetState {
),
None => {
self.pending_texture_updates.insert(image_id);
}
},
}
}
@@ -164,7 +172,8 @@ impl AssetState {
}
if self.new_texture_count(&textures) > self.textures.vacancies(MAX_TEXTURE_COUNT.get()) {
// At the limit, release the old set once so a replacement can reuse those slots
// At the limit, release the old set once so a replacement can reuse
// those slots
self.release_material_textures(material_id);
self.material_textures.remove(&material_id);
@@ -206,7 +215,8 @@ impl AssetState {
let alpha_cutoff = match material.alpha_mode {
AlphaMode::Mask(cutoff) => cutoff,
// Without MSAA alpha to coverage is treated as a mask with a cutoff of 0.5
// Without MSAA alpha to coverage is treated as a mask with a cutoff
// of 0.5
AlphaMode::AlphaToCoverage => 0.5,
AlphaMode::Opaque
| AlphaMode::Blend
@@ -217,11 +227,12 @@ impl AssetState {
let is_opaque = match material.alpha_mode {
AlphaMode::Opaque => true,
AlphaMode::Mask(_) | AlphaMode::AlphaToCoverage => false,
// TODO: Solari doesn't support transparency yet, so these are traced as opaque for now
// TODO: Solari doesn't support transparency yet, so these are
// traced as opaque for now
#[expect(clippy::match_same_arms, reason = "Transparency not yet supported")]
AlphaMode::Blend | AlphaMode::Premultiplied | AlphaMode::Add | AlphaMode::Multiply => {
true
}
},
};
let mut flags = 0;
@@ -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,
});
@@ -104,6 +104,7 @@ impl RaytracingSceneBindings {
&mut self.instances.aabb_buffers.dirty,
&mut self.instances.tape_metadata_buffers.dirty,
&mut self.instances.spatial_textures.dirty,
&mut self.instances.tiletrees.dirty,
&mut self.assets.textures.dirty,
] {
invalid |= core::mem::replace(dirty, false);
@@ -173,6 +174,19 @@ impl RaytracingSceneBindings {
spatial_textures.push(fallback_texture.d3.texture_view.deref());
}
let mut tiletrees: Vec<_> = self
.instances
.tiletrees
.iter()
.map(|texture| match texture {
Some(view) => view.deref(),
None => fallback_texture.d3.texture_view.deref(),
})
.collect();
if tiletrees.is_empty() {
tiletrees.push(fallback_texture.d3.texture_view.deref());
}
let (mut textures, mut samplers): (Vec<_>, Vec<_>) = self
.assets
.textures
@@ -193,7 +207,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,
),
};
@@ -215,6 +229,8 @@ impl RaytracingSceneBindings {
tape_metadata_buffers.as_slice(),
spatial_textures.as_slice(),
&self.spatial_texture_sampler,
tiletrees.as_slice(),
&self.tiletree_sampler,
textures.as_slice(),
samplers.as_slice(),
self.assets.materials.binding().unwrap(),
@@ -357,7 +373,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>(
@@ -380,7 +396,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,25 +35,26 @@ use super::{
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();
pub const MAX_TILETREE_COUNT: NonZeroU32 = NonZeroU32::new(5000).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,
spatial_texture_id: u32,
metadata_buffer_id: u32,
aabb_buffer_id: u32,
aabb_buffer_offset: u32,
spatial_texture_id: u32,
tiletree_id: u32,
metadata_buffer_id: u32,
metadata_buffer_offset: u32,
}
@@ -103,7 +104,7 @@ pub enum BlasKey {
}
type MeshBuffers = (BufferId, BufferId);
type TapeBuffers = (BufferId, BufferId, TextureId);
type TapeBuffers = (BufferId, BufferId, TextureId, TextureId);
pub enum Buffers {
Mesh(MeshBuffers),
@@ -129,27 +130,27 @@ impl Buffers {
/// 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<MeshBuffers>,
opacity: MeshBlasOpacity,
buffers: Option<MeshBuffers>,
}
/// 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<TapeBuffers>,
opacity: TapeBlasOpacity,
buffers: Option<TapeBuffers>,
}
impl MeshInstance {
fn blas_key(&self) -> MeshBlasKey {
MeshBlasKey {
mesh: self.mesh,
mesh: self.mesh,
opacity: self.opacity,
}
}
@@ -158,7 +159,7 @@ impl MeshInstance {
impl TapeInstance {
fn blas_key(&self) -> TapeBlasKey {
TapeBlasKey {
tape: self.tape,
tape: self.tape,
opacity: self.opacity,
}
}
@@ -264,6 +265,7 @@ pub struct InstanceState {
pub aabb_buffers: RetainedBindingArray<BufferId, Buffer>,
pub tape_metadata_buffers: RetainedBindingArray<BufferId, Buffer>,
pub spatial_textures: RetainedBindingArray<TextureId, TextureView>,
pub tiletrees: RetainedBindingArray<TextureId, TextureView>,
pub transforms: AtomicSparseBufferVec<GpuTransform>,
pub previous_frame_transforms: AtomicSparseBufferVec<GpuTransform>,
pub geometry_ids: AtomicSparseBufferVec<GpuInstanceGeometryIds>,
@@ -285,25 +287,26 @@ 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(),
spatial_textures: RetainedBindingArray::new(),
transforms: storage_buffer("solari_transforms"),
vertex_buffers: RetainedBindingArray::new(),
index_buffers: RetainedBindingArray::new(),
aabb_buffers: RetainedBindingArray::new(),
tape_metadata_buffers: RetainedBindingArray::new(),
spatial_textures: RetainedBindingArray::new(),
tiletrees: 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(),
}
}
@@ -363,11 +366,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) {
@@ -404,11 +407,13 @@ impl InstanceState {
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)
for (aabb_key, metadata_key, spatial_key, tiletree_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);
self.tiletrees.release(&tiletree_key);
}
}
@@ -468,11 +473,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),
},
}
@@ -555,10 +560,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)
}
},
}
}
@@ -704,12 +709,14 @@ impl InstanceState {
Some(aabb_slice),
Some(metadata_slice),
Some(spatial_texture),
Some(tiletree),
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),
inputs.tape_allocator.tape_tiletree(&instance.tape),
material_slot,
blas_address,
)
@@ -752,14 +759,26 @@ impl InstanceState {
.has_room(&spatial_texture_key, spatial_capacity)
{
once!(warn!(
"Solari scene needs more than {} spatial textures. Instances past that limit will not \
be rendered.",
"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 tiletree_key = tiletree.0.id();
let tiletree_capacity = MAX_TILETREE_COUNT.get();
if !self.tiletrees.has_room(&tiletree_key, spatial_capacity) {
once!(warn!(
"Solari scene needs more than {} tiletrees. Instances past that limit will not be \
rendered.",
MAX_TILETREE_COUNT.get()
));
self.deactivate_tape_instance(lights, entity, instance);
return false;
}
let previous_buffers = instance.buffers.take();
let aabb_buffer_id = self
.aabb_buffers
@@ -776,18 +795,26 @@ impl InstanceState {
.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));
.expect("spatial texture binding array had room but handed out no slot");
let tiletree_id = self
.tiletrees
.acquire(tiletree_key, tiletree_capacity, || tiletree.1.clone())
.expect("tiletree binding array had room but handed out no slot");
instance.buffers = Some((
aabb_buffer_key,
metadata_buffer_key,
spatial_texture_key,
tiletree_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,
tiletree_id,
metadata_buffer_id,
metadata_buffer_offset: metadata_slice.range.start,
},
@@ -894,10 +921,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());
@@ -1,16 +1,23 @@
use core::{
f32::consts::TAU,
hash::Hash,
sync::atomic::{AtomicBool, Ordering},
};
use bevy_ecs::{entity::Entity, query::Changed, system::Query};
use bevy_math::{Vec3, ops::cos};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_render::{
impl_atomic_pod,
render_resource::{AtomicPod, AtomicSparseBufferVec, BufferUsages},
};
use bytemuck::{Pod, Zeroable};
use super::allocator::SlotAllocator;
use crate::scene::extract::{
ExtractedRaytracingDirectionalLight, ExtractedRaytracingPointLight,
ExtractedRaytracingRectLight, ExtractedRaytracingSpotLight,
};
use bevy_ecs::{entity::Entity, query::Changed, system::Query};
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};
use bytemuck::{Pod, Zeroable};
use core::sync::atomic::{AtomicBool, Ordering};
use core::{f32::consts::TAU, hash::Hash};
const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX;
@@ -25,7 +32,7 @@ const LIGHT_SOURCE_KIND_RECT: u32 = 3;
#[repr(C)]
pub struct GpuLightSource {
kind: u32,
id: u32,
id: u32,
}
/// Stable identity for one light in the light array.
@@ -41,7 +48,7 @@ pub enum LightSourceId {
#[derive(Default)]
pub struct LightIndex {
indices: HashMap<LightSourceId, u32>,
ids: Vec<LightSourceId>,
ids: Vec<LightSourceId>,
changed: HashSet<LightSourceId>,
}
@@ -72,8 +79,9 @@ impl LightIndex {
/// Removes `id` and reports both its old index and the old final index.
///
/// Only the ids tracked here are swapped down. When the two indices differ, the caller has to
/// mirror that swap in `sources`, copying the element at the old final index into the hole.
/// Only the ids tracked here are swapped down. When the two indices differ,
/// the caller has to mirror that swap in `sources`, copying the element at
/// the old final index into the hole.
fn remove(&mut self, id: LightSourceId) -> Option<(u32, u32)> {
let index = self.indices.remove(&id)?;
self.changed.insert(id);
@@ -99,28 +107,28 @@ impl GpuLightSource {
Self {
kind: (triangle_count << LIGHT_SOURCE_KIND_BITS) | LIGHT_SOURCE_KIND_EMISSIVE_MESH,
id: instance_id,
id: instance_id,
}
}
fn new_directional_light(directional_light_id: u32) -> GpuLightSource {
Self {
kind: LIGHT_SOURCE_KIND_DIRECTIONAL,
id: directional_light_id,
id: directional_light_id,
}
}
fn new_point_light(point_light_id: u32) -> GpuLightSource {
Self {
kind: LIGHT_SOURCE_KIND_POINT,
id: point_light_id,
id: point_light_id,
}
}
fn new_rect_light(rect_light_id: u32) -> GpuLightSource {
Self {
kind: LIGHT_SOURCE_KIND_RECT,
id: rect_light_id,
id: rect_light_id,
}
}
}
@@ -129,32 +137,32 @@ impl GpuLightSource {
#[repr(C)]
pub struct GpuDirectionalLight {
direction_to_light: Vec3,
cos_theta_max: f32,
luminance: Vec3,
inverse_pdf: f32,
cos_theta_max: f32,
luminance: Vec3,
inverse_pdf: f32,
}
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuPointLight {
position: Vec3,
radius: f32,
position: Vec3,
radius: f32,
intensity: Vec3,
cos_inner: f32,
axis: Vec3,
axis: Vec3,
cos_outer: f32,
}
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuRectLight {
center: Vec3,
area: f32,
edge_x: Vec3,
center: Vec3,
area: f32,
edge_x: Vec3,
_padding0: f32,
edge_y: Vec3,
edge_y: Vec3,
_padding1: f32,
radiance: Vec3,
radiance: Vec3,
_padding2: f32,
}
@@ -187,22 +195,22 @@ impl GpuPointLight {
fn new_point(point_light: &ExtractedRaytracingPointLight) -> Self {
// Point lights get a cone that never cuts anything off
Self {
position: point_light.position,
radius: point_light.radius,
position: point_light.position,
radius: point_light.radius,
intensity: point_light.intensity,
cos_inner: -1.0,
axis: Vec3::NEG_Z,
axis: Vec3::NEG_Z,
cos_outer: -1.0,
}
}
fn new_spot(spot_light: &ExtractedRaytracingSpotLight) -> Self {
Self {
position: spot_light.position,
radius: spot_light.radius,
position: spot_light.position,
radius: spot_light.radius,
intensity: spot_light.intensity,
cos_inner: spot_light.cos_inner,
axis: spot_light.axis,
axis: spot_light.axis,
cos_outer: spot_light.cos_outer,
}
}
@@ -211,13 +219,13 @@ impl GpuPointLight {
impl GpuRectLight {
fn new(rect_light: &ExtractedRaytracingRectLight) -> Self {
Self {
center: rect_light.center,
area: rect_light.area,
edge_x: rect_light.edge_x,
center: rect_light.center,
area: rect_light.area,
edge_x: rect_light.edge_x,
_padding0: 0.0,
edge_y: rect_light.edge_y,
edge_y: rect_light.edge_y,
_padding1: 0.0,
radiance: rect_light.radiance,
radiance: rect_light.radiance,
_padding2: 0.0,
}
}
@@ -232,14 +240,17 @@ pub struct LightState {
pub rect_lights: AtomicSparseBufferVec<GpuRectLight>,
pub previous_frame_id_translations: AtomicSparseBufferVec<u32>,
pub index: LightIndex,
/// Light ids as of the last frame whose translation table the lighting shader actually read.
/// Light ids as of the last frame whose translation table the lighting
/// shader actually read.
previous_index: HashMap<LightSourceId, u32>,
nonidentity_translations: Vec<u32>,
directional_light_slots: SlotAllocator<Entity>,
/// Spot lights share the point light buffer, and so cannot be keyed by just Entity.
/// Spot lights share the point light buffer, and so cannot be keyed by just
/// Entity.
point_light_slots: SlotAllocator<LightSourceId>,
rect_light_slots: SlotAllocator<Entity>,
/// Set by the lighting node once it has recorded work reading the translation table.
/// Set by the lighting node once it has recorded work reading the
/// translation table.
translations_consumed: AtomicBool,
}
@@ -278,8 +289,9 @@ impl LightState {
/// Applies this frame's light changes.
///
/// Lights are retained, so only the ones that changed are processed. Removals go first so that
/// a light removed and re-added in the same frame ends up present.
/// Lights are retained, so only the ones that changed are processed.
/// Removals go first so that a light removed and re-added in the same frame
/// ends up present.
pub fn update_directional_lights(
&mut self,
changed: &Query<
@@ -288,7 +300,8 @@ impl LightState {
>,
removed: impl IntoIterator<Item = Entity>,
) {
// Removals go first so that a light removed and re-added in the same frame ends up present
// Removals go first so that a light removed and re-added in the same
// frame ends up present
for entity in removed {
if self.directional_light_slots.remove(&entity).is_some() {
self.remove_light(LightSourceId::DirectionalLight(entity));
@@ -392,7 +405,8 @@ impl LightState {
self.sources.grow_and_set(index, source);
}
/// Removes a light, moving the last one down into the hole so the array stays gap-free.
/// Removes a light, moving the last one down into the hole so the array
/// stays gap-free.
pub fn remove_light(&mut self, id: LightSourceId) {
let Some((index, last)) = self.index.remove(id) else {
return;
@@ -406,10 +420,11 @@ impl LightState {
/// Rolls the translation table over for a new frame.
///
/// `previous_index` and `changed` only advance once the shader has read the table. The
/// lighting node bails out while its pipelines compile, and the reservoirs keep the older ids
/// across such a gap, so the next table has to translate from those instead. `has_consumers`
/// is false when no view runs Solari lighting, where deferring forever would grow both
/// `previous_index` and `changed` only advance once the shader has read the
/// table. The lighting node bails out while its pipelines compile, and the
/// reservoirs keep the older ids across such a gap, so the next table has
/// to translate from those instead. `has_consumers` is false when no view
/// runs Solari lighting, where deferring forever would grow both
/// without bound.
pub fn begin_frame(&mut self, has_consumers: bool) {
for index in core::mem::take(&mut self.nonidentity_translations) {
@@ -432,11 +447,13 @@ impl LightState {
self.translations_consumed.store(true, Ordering::Relaxed);
}
/// Records where each light that moved or disappeared this frame ended up, so that reservoirs
/// still carrying last frame's light ids can be remapped.
/// Records where each light that moved or disappeared this frame ended up,
/// so that reservoirs still carrying last frame's light ids can be
/// remapped.
fn write_light_id_translations(&mut self) {
for id in &self.index.changed {
// Lights that first appeared since the last read table have no previous id
// Lights that first appeared since the last read table have no
// previous id
let Some(&previous) = self.previous_index.get(id) else {
continue;
};
@@ -464,9 +481,10 @@ impl LightState {
#[cfg(test)]
mod tests {
use super::{LightIndex, LightSourceId};
use bevy_ecs::entity::Entity;
use super::{LightIndex, LightSourceId};
const ENTITY: Entity = Entity::PLACEHOLDER;
#[test]
@@ -49,7 +49,7 @@ use super::{
},
};
use crate::scene::{
binder::instances::{MAX_SPATIAL_TEXTURE_COUNT, MAX_TAPE_SLAB_COUNT},
binder::instances::{MAX_SPATIAL_TEXTURE_COUNT, MAX_TAPE_SLAB_COUNT, MAX_TILETREE_COUNT},
extract::{
ExtractedRaytracingDirectionalLight, ExtractedRaytracingPointLight,
ExtractedRaytracingRectLight, ExtractedRaytracingSpotLight,
@@ -78,6 +78,7 @@ pub struct RaytracingSceneBindings {
tlas: TlasState,
bind_groups: BindGroupCacheState,
spatial_texture_sampler: Sampler,
tiletree_sampler: Sampler,
}
impl RaytracingSceneBindings {
@@ -105,6 +106,9 @@ impl FromWorld for RaytracingSceneBindings {
texture_3d(TextureSampleType::Float { filterable: true })
.count(MAX_SPATIAL_TEXTURE_COUNT),
sampler(SamplerBindingType::Filtering),
texture_3d(TextureSampleType::Float { filterable: true })
.count(MAX_TILETREE_COUNT),
sampler(SamplerBindingType::Filtering),
texture_2d(TextureSampleType::Float { filterable: true })
.count(MAX_TEXTURE_COUNT),
sampler(SamplerBindingType::Filtering).count(MAX_TEXTURE_COUNT),
@@ -155,6 +159,17 @@ impl FromWorld for RaytracingSceneBindings {
..Default::default()
});
let tiletree_sampler = render_device.create_sampler(&SamplerDescriptor {
label: Some("tape_drive_tiletree_sampler"),
address_mode_u: AddressMode::ClampToEdge,
address_mode_v: AddressMode::ClampToEdge,
address_mode_w: AddressMode::ClampToEdge,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
mipmap_filter: MipmapFilterMode::Linear,
..Default::default()
});
Self {
bind_group: None,
bind_group_layout,
@@ -166,6 +181,7 @@ impl FromWorld for RaytracingSceneBindings {
tlas: TlasState::new(render_device),
bind_groups: BindGroupCacheState::new(render_device),
spatial_texture_sampler,
tiletree_sampler,
}
}
}
@@ -243,11 +259,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,
},
));
@@ -361,7 +361,7 @@ pub fn build_raytracing_tlas(
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,
@@ -433,7 +433,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);
@@ -446,11 +446,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(),
@@ -1,15 +1,17 @@
//! Building the binder's TLAS through `wgpu_hal` directly, bypassing `wgpu-core` and using
//! an indirect acceleration structure build.
//! Building the binder's TLAS through `wgpu_hal` directly, bypassing
//! `wgpu-core` and using an indirect acceleration structure build.
//!
//! Vulkan and DX12 only, as their instance descriptors are byte-identical. Metal cannot work this
//! way: `wgpu-core` makes a TLAS's BLASes resident from its dependency list, and
//! `mark_acceleration_structures_built` clears that list, so traversal would read memory Metal is
//! free to have evicted. Every other backend falls back to the `wgpu-core` build in [`super::tlas`].
//! Vulkan and DX12 only, as their instance descriptors are byte-identical.
//! Metal cannot work this way: `wgpu-core` makes a TLAS's BLASes resident from
//! its dependency list, and `mark_acceleration_structures_built` clears that
//! list, so traversal would read memory Metal is free to have evicted. Every
//! other backend falls back to the `wgpu-core` build in [`super::tlas`].
//!
//! Every operation has to be instantiated per backend, as `as_hal` is generic over the hal type and
//! wgpu exposes no dynamic equivalent. [`resolve`] does that once, by trying each compiled-in
//! backend and relying on `as_hal` returning `None` for a device that isn't its own, which can't
//! disagree with the adapter actually in use.
//! Every operation has to be instantiated per backend, as `as_hal` is generic
//! over the hal type and wgpu exposes no dynamic equivalent. [`resolve`] does
//! that once, by trying each compiled-in backend and relying on `as_hal`
//! returning `None` for a device that isn't its own, which can't disagree with
//! the adapter actually in use.
#![expect(
unsafe_code,
@@ -31,11 +33,12 @@
)
)]
use core::marker::PhantomData;
use bevy_render::{
render_resource::{Blas, Buffer, BufferDescriptor, BufferUsages, CommandEncoder, Tlas},
renderer::RenderDevice,
};
use core::marker::PhantomData;
use wgpu::{BufferUses, hal};
/// Size of one TLAS instance descriptor, on both Vulkan and DXR.
@@ -45,9 +48,11 @@ pub const INSTANCE_DESCRIPTOR_SIZE: u64 = 64;
const TLAS_BUILD_FLAGS: wgpu::AccelerationStructureFlags =
wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE;
/// The `wgpu_hal` operations a raw TLAS build needs, bound to one backend by [`resolve`].
/// The `wgpu_hal` operations a raw TLAS build needs, bound to one backend by
/// [`resolve`].
pub trait RawTlasBackend: Send + Sync {
/// Scratch space a TLAS build over `instance_count` instances of `instances` needs.
/// Scratch space a TLAS build over `instance_count` instances of
/// `instances` needs.
fn scratch_size(
&self,
render_device: &RenderDevice,
@@ -57,27 +62,32 @@ pub trait RawTlasBackend: Send + Sync {
/// Allocates a buffer usable as acceleration structure build scratch.
///
/// There is no [`BufferUsages`] for scratch and `STORAGE` won't do, as Vulkan only adds
/// `SHADER_DEVICE_ADDRESS` for acceleration structure usages. So it is created through hal and
/// handed to `wgpu-core` to own. `wgpu-core` only defers freeing what a submission's tracker
/// references, so the caller transitioning it each frame is what makes replacing it safe.
/// There is no [`BufferUsages`] for scratch and `STORAGE` won't do, as
/// Vulkan only adds `SHADER_DEVICE_ADDRESS` for acceleration structure
/// usages. So it is created through hal and handed to `wgpu-core` to own.
/// `wgpu-core` only defers freeing what a submission's tracker references,
/// so the caller transitioning it each frame is what makes replacing it
/// safe.
fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer>;
/// Records a TLAS build reading instance descriptors straight out of `instances`.
/// Records a TLAS build reading instance descriptors straight out of
/// `instances`.
///
/// The caller must already have transitioned `instances` to
/// `BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT` and `scratch` to
/// `BufferUses::ACCELERATION_STRUCTURE_SCRATCH`, on an earlier command buffer in the same
/// submission. The scratch transition is not optional even when its state is unchanged: scratch
/// is an exclusive usage, so the redundant-looking transition is what keeps consecutive frames'
/// `BufferUses::ACCELERATION_STRUCTURE_SCRATCH`, on an earlier command
/// buffer in the same submission. The scratch transition is not optional
/// even when its state is unchanged: scratch is an exclusive usage, so the
/// redundant-looking transition is what keeps consecutive frames'
/// builds from overlapping in it.
///
/// `encoder` must have no wgpu command recorded into it, including timestamp writes, as
/// `wgpu-core` panics if an encoder mixes the wgpu and raw encoding APIs.
/// `encoder` must have no wgpu command recorded into it, including
/// timestamp writes, as `wgpu-core` panics if an encoder mixes the wgpu and
/// raw encoding APIs.
///
/// Marking the build clears the TLAS's dependency list, which is what otherwise keeps the
/// BLASes it points at alive. The caller has to retain them past every submission that might
/// still trace it.
/// Marking the build clears the TLAS's dependency list, which is what
/// otherwise keeps the BLASes it points at alive. The caller has to retain
/// them past every submission that might still trace it.
fn build_tlas(
&self,
encoder: &mut CommandEncoder,
@@ -114,13 +124,15 @@ pub fn resolve(render_device: &RenderDevice) -> Option<&'static dyn RawTlasBacke
/// [`RawTlasBackend`] for one hal backend.
///
/// `fn() -> A` rather than `A`, so the marker is [`Send`] and [`Sync`] whatever `A` is.
/// `fn() -> A` rather than `A`, so the marker is [`Send`] and [`Sync`] whatever
/// `A` is.
struct Hal<A>(PhantomData<fn() -> A>);
impl<A: hal::Api> Hal<A> {
const NEW: Self = Self(PhantomData);
/// Records the build itself, leaving [`RawTlasBackend::build_tlas`] to mark it.
/// Records the build itself, leaving [`RawTlasBackend::build_tlas`] to mark
/// it.
fn record_build(
&self,
encoder: &mut CommandEncoder,
@@ -133,7 +145,8 @@ impl<A: hal::Api> Hal<A> {
// Workaround for https://github.com/gfx-rs/wgpu/issues/10191
let buffer_address = |buffer: &Buffer| {
// SAFETY: the handle is only read, and the buffer is not destroyed here
// SAFETY: the handle is only read, and the buffer is not destroyed
// here
let guard = unsafe { buffer.as_hal::<A>() }?;
Some(core::ptr::from_ref::<A::Buffer>(&*guard))
};
@@ -142,15 +155,16 @@ impl<A: hal::Api> Hal<A> {
// SAFETY: the handle is only read, and the TLAS is not destroyed here
let hal_tlas = unsafe { tlas.as_hal::<A>() }?;
// SAFETY: both buffers outlive this call through the caller's borrows, and neither is
// destroyed between reading its address and the build recording
// SAFETY: both buffers outlive this call through the caller's borrows,
// and neither is destroyed between reading its address and the build
// recording
let (hal_instances, hal_scratch) = unsafe { (&*hal_instances, &*hal_scratch) };
let entries =
hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
buffer: Some(hal_instances),
offset: 0,
count: instance_count,
count: instance_count,
});
let descriptor = hal::BuildAccelerationStructureDescriptor {
@@ -163,35 +177,38 @@ impl<A: hal::Api> Hal<A> {
scratch_buffer_offset: 0,
};
// The caller transitioned both buffers, so the only barriers left are the acceleration
// structure's own, which have no public spelling.
// The caller transitioned both buffers, so the only barriers left are
// the acceleration structure's own, which have no public spelling.
//
// SAFETY: every resource in `descriptor` belongs to backend `A` and to this device, the
// scratch buffer is sized by `scratch_size` and used by no other build in this submission,
// and the encoder is neither ended nor its raw handle destroyed here
// SAFETY: every resource in `descriptor` belongs to backend `A` and to
// this device, the scratch buffer is sized by `scratch_size` and used
// by no other build in this submission, and the encoder is neither
// ended nor its raw handle destroyed here
unsafe {
encoder.as_hal_mut::<A, _, _>(|encoder| {
let encoder = encoder?;
// Write-after-read against submissions still tracing this TLAS as their previous
// frame, and against a BLAS compaction copy submitted ahead of this build. A
// barrier's first scope covers everything already submitted, which covers both.
// Write-after-read against submissions still tracing this TLAS
// as their previous frame, and against a BLAS compaction copy
// submitted ahead of this build. A barrier's first scope covers
// everything already submitted, which covers both.
encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
usage: hal::StateTransition {
from: hal::AccelerationStructureUses::SHADER_INPUT
| hal::AccelerationStructureUses::COPY_DST,
to: hal::AccelerationStructureUses::BUILD_OUTPUT
to: hal::AccelerationStructureUses::BUILD_OUTPUT
| hal::AccelerationStructureUses::BUILD_INPUT,
},
});
encoder.build_acceleration_structures(1, [descriptor]);
// And read-after-write, for the passes later this frame that trace the result
// And read-after-write, for the passes later this frame that
// trace the result
encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
usage: hal::StateTransition {
from: hal::AccelerationStructureUses::BUILD_OUTPUT,
to: hal::AccelerationStructureUses::SHADER_INPUT,
to: hal::AccelerationStructureUses::SHADER_INPUT,
},
});
@@ -215,22 +232,22 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
// SAFETY: the handle is only read, and is dropped with the guard
let hal_instances = unsafe { instances.as_hal::<A>() }?;
// Sizing ignores the buffer itself, but `wgpu_hal`'s Metal path unwraps it unconditionally,
// so a real one has to be handed over
// Sizing ignores the buffer itself, but `wgpu_hal`'s Metal path unwraps
// it unconditionally, so a real one has to be handed over
let entries =
hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
buffer: Some(&*hal_instances),
offset: 0,
count: instance_count,
count: instance_count,
});
// SAFETY: `entries` describes a buffer belonging to backend `A`, and the query records
// nothing and reads no memory through it
// SAFETY: `entries` describes a buffer belonging to backend `A`, and
// the query records nothing and reads no memory through it
let sizes = unsafe {
hal_device.get_acceleration_structure_build_sizes(
&hal::GetAccelerationStructureBuildSizesDescriptor {
entries: &entries,
flags: TLAS_BUILD_FLAGS,
flags: TLAS_BUILD_FLAGS,
},
)
};
@@ -245,8 +262,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
let hal_buffer = {
// SAFETY: the handle is only read, and is dropped with the guard
let hal_device = unsafe { device.as_hal::<A>() }?;
// SAFETY: the descriptor is valid and the buffer is handed to `wgpu-core` below, which
// takes over destroying it
// SAFETY: the descriptor is valid and the buffer is handed to
// `wgpu-core` below, which takes over destroying it
unsafe {
hal_device.create_buffer(&hal::BufferDescriptor {
label: Some("solari_tlas_scratch"),
@@ -258,7 +275,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
.ok()?
};
// `usage` is only consulted for wgpu-level validation, which this buffer never sees
// `usage` is only consulted for wgpu-level validation, which this
// buffer never sees
let descriptor = BufferDescriptor {
label: Some("solari_tlas_scratch"),
size,
@@ -266,8 +284,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
mapped_at_creation: false,
};
// SAFETY: `hal_buffer` was created from this device, matches `descriptor`, and has nonzero
// size
// SAFETY: `hal_buffer` was created from this device, matches
// `descriptor`, and has nonzero size
Some(unsafe { device.create_buffer_from_hal::<A>(hal_buffer, &descriptor) }.into())
}
@@ -286,10 +304,12 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
return false;
}
// Without this the build is invisible to `wgpu-core` and it rejects the TLAS when bound
// Without this the build is invisible to `wgpu-core` and it rejects the
// TLAS when bound
//
// SAFETY: the TLAS was just built into this encoder, and every BLAS its instances point at
// was built and submitted earlier in the frame by `prepare_raytracing_blas`
// SAFETY: the TLAS was just built into this encoder, and every BLAS its
// instances point at was built and submitted earlier in the frame by
// `prepare_raytracing_blas`
unsafe {
encoder.mark_acceleration_structures_built(core::iter::empty::<&Blas>(), [&*tlas]);
}
@@ -19,8 +19,8 @@ struct InstanceGeometryIds {
struct InstanceTapeIds {
aabb_buffer_id: u32,
aabb_buffer_offset: u32,
aabb_count: u32,
spatial_texture_id: u32,
tiletree_id: u32,
metadata_buffer_id: u32,
metadata_buffer_offset: u32,
}
@@ -149,26 +149,28 @@ const LIGHT_NOT_PRESENT_THIS_FRAME = 0xFFFFFFFFu;
@group(0) @binding(2) var<storage> aabb_buffers: binding_array<AabbBuffer>;
@group(0) @binding(3) var<storage> tape_metadata_buffers: binding_array<TapeMetadataBuffer>;
@group(0) @binding(6) var textures: binding_array<texture_2d<f32>>;
@group(0) @binding(7) var samplers: binding_array<sampler>;
@group(0) @binding(8) var<storage> materials: array<Material>;
@group(0) @binding(9) var tlas: acceleration_structure;
@group(0) @binding(10) var previous_frame_tlas: acceleration_structure;
@group(0) @binding(11) var<storage> transforms: array<mat3x4<f32>>;
@group(0) @binding(12) var<storage> previous_frame_transforms: array<mat3x4<f32>>;
@group(0) @binding(13) var<storage> geometry_ids: array<InstanceGeometryIds>;
@group(0) @binding(14) var<storage> tape_ids: array<InstanceTapeIds>;
@group(0) @binding(15) var<storage> material_ids: array<u32>;
@group(0) @binding(16) var brdf_dfg_lut: texture_2d<f32>;
@group(0) @binding(17) var brdf_dfg_lut_sampler: sampler;
@group(0) @binding(18) var<storage> light_sources: array<LightSource>;
@group(0) @binding(19) var<storage> directional_lights: array<DirectionalLight>;
@group(0) @binding(20) var<storage> point_lights: array<PointLight>;
@group(0) @binding(21) var<storage> rect_lights: array<RectLight>;
@group(0) @binding(22) var environment_map: texture_cube<f32>;
@group(0) @binding(23) var environment_map_sampler: sampler;
@group(0) @binding(24) var<storage> environment_map_light: EnvironmentMapLight;
@group(0) @binding(25) var<storage> previous_frame_light_id_translations: array<u32>;
@group(0) @binding(6) var tiletrees: binding_array<texture_3d<f32>>;
@group(0) @binding(7) var tiletree_sampler: sampler;
@group(0) @binding(8) var textures: binding_array<texture_2d<f32>>;
@group(0) @binding(9) var samplers: binding_array<sampler>;
@group(0) @binding(10) var<storage> materials: array<Material>;
@group(0) @binding(11) var tlas: acceleration_structure;
@group(0) @binding(12) var previous_frame_tlas: acceleration_structure;
@group(0) @binding(13) var<storage> transforms: array<mat3x4<f32>>;
@group(0) @binding(14) var<storage> previous_frame_transforms: array<mat3x4<f32>>;
@group(0) @binding(15) var<storage> geometry_ids: array<InstanceGeometryIds>;
@group(0) @binding(16) var<storage> tape_ids: array<InstanceTapeIds>;
@group(0) @binding(17) var<storage> material_ids: array<u32>;
@group(0) @binding(18) var brdf_dfg_lut: texture_2d<f32>;
@group(0) @binding(19) var brdf_dfg_lut_sampler: sampler;
@group(0) @binding(20) var<storage> light_sources: array<LightSource>;
@group(0) @binding(21) var<storage> directional_lights: array<DirectionalLight>;
@group(0) @binding(22) var<storage> point_lights: array<PointLight>;
@group(0) @binding(23) var<storage> rect_lights: array<RectLight>;
@group(0) @binding(24) var environment_map: texture_cube<f32>;
@group(0) @binding(25) var environment_map_sampler: sampler;
@group(0) @binding(26) var<storage> environment_map_light: EnvironmentMapLight;
@group(0) @binding(27) var<storage> previous_frame_light_id_translations: array<u32>;
const RAY_T_MIN = 0.001f;
const RAY_T_MAX = 100000.0f;
@@ -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,9 +370,10 @@ pub fn extract_raytracing_point_lights(
}
entity_commands.insert(ExtractedRaytracingPointLight {
position: transform.translation(),
radius: point_light.radius,
// Map from luminous power in lumens to luminous intensity in candela
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 +408,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 +479,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() {
@@ -1,4 +1,5 @@
use alloc::collections::VecDeque;
use bevy_asset::AssetId;
use bevy_ecs::{
resource::Resource,
@@ -17,8 +18,9 @@ use bevy_render::{
renderer::{RenderDevice, RenderQueue},
};
/// After compacting this many vertices worth of meshes per frame, no further BLAS will be compacted.
/// Lower this number to distribute the work across more frames.
/// After compacting this many vertices worth of meshes per frame, no further
/// BLAS will be compacted. Lower this number to distribute the work across more
/// frames.
const MAX_COMPACTION_VERTICES_PER_FRAME: u32 = 400_000;
/// Under the `wgpu_hal` build path, we need to manage BLAS lifetimes ourselves.
@@ -28,12 +30,12 @@ const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
#[derive(Resource, Default)]
pub struct BlasManager {
blas: HashMap<AssetId<Mesh>, MeshBlas>,
compaction_queue: VecDeque<(BlasKey, u32, bool)>,
changed: Vec<AssetId<Mesh>>,
/// BLAS that are pending deletion, one batch per TLAS build. The back batch collects
/// retirements since the last build, and every batch ahead of it has one more build to wait
/// out.
blas: HashMap<AssetId<Mesh>, MeshBlas>,
compaction_queue: VecDeque<(BlasKey, u32, bool)>,
changed: Vec<AssetId<Mesh>>,
/// BLAS that are pending deletion, one batch per TLAS build. The back batch
/// collects retirements since the last build, and every batch ahead of it
/// has one more build to wait out.
pending_deletions: VecDeque<Vec<Blas>>,
}
@@ -46,8 +48,8 @@ impl BlasManager {
self.get(key)?.handle()
}
/// If a mesh is raytracing compatible, but its [`Mesh::raytracing`] flags don't declare
/// the required opacity.
/// If a mesh is raytracing compatible, but its [`Mesh::raytracing`] flags
/// don't declare the required opacity.
pub fn is_undeclared(&self, key: &BlasKey) -> bool {
self.blas
.get(&key.mesh)
@@ -97,16 +99,16 @@ impl BlasManager {
}
struct MeshBlas {
requires: MeshRaytracingFlags,
opaque: Option<Blas>,
requires: MeshRaytracingFlags,
opaque: Option<Blas>,
non_opaque: Option<Blas>,
}
impl Default for MeshBlas {
fn default() -> Self {
Self {
requires: MeshRaytracingFlags::empty(),
opaque: None,
requires: MeshRaytracingFlags::empty(),
opaque: None,
non_opaque: None,
}
}
@@ -134,7 +136,7 @@ impl MeshBlas {
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BlasKey {
pub mesh: AssetId<Mesh>,
pub mesh: AssetId<Mesh>,
pub opacity: BlasOpacity,
}
@@ -232,17 +234,17 @@ pub fn prepare_raytracing_blas(
.iter()
.map(|(key, vertex_slice, index_slice, blas_size)| {
let geometry = BlasTriangleGeometry {
size: blas_size,
vertex_buffer: vertex_slice.buffer,
first_vertex: vertex_slice.range.start,
vertex_stride: 48,
index_buffer: Some(index_slice.buffer),
first_index: Some(index_slice.range.start),
transform_buffer: None,
size: blas_size,
vertex_buffer: vertex_slice.buffer,
first_vertex: vertex_slice.range.start,
vertex_stride: 48,
index_buffer: Some(index_slice.buffer),
first_index: Some(index_slice.range.start),
transform_buffer: None,
transform_buffer_offset: None,
};
BlasBuildEntry {
blas: blas_manager.get(key).unwrap(),
blas: blas_manager.get(key).unwrap(),
geometry: BlasGeometries::TriangleGeometries(vec![geometry]),
}
})
@@ -326,18 +328,18 @@ fn allocate_blas(
) -> (Blas, BlasTriangleGeometrySizeDescriptor) {
let blas_size = BlasTriangleGeometrySizeDescriptor {
vertex_format: Mesh::ATTRIBUTE_POSITION.format,
vertex_count: vertex_slice.range.len() as u32,
index_format: Some(IndexFormat::Uint32),
index_count: Some(index_slice.range.len() as u32),
flags: key.opacity.geometry_flags(),
vertex_count: vertex_slice.range.len() as u32,
index_format: Some(IndexFormat::Uint32),
index_count: Some(index_slice.range.len() as u32),
flags: key.opacity.geometry_flags(),
};
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS double-buffer
// to avoid invalidating the previous frame TLAS
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS
// double-buffer to avoid invalidating the previous frame TLAS
let blas = render_device.wgpu_device().create_blas(
&CreateBlasDescriptor {
label: Some(&format!("{} {:?}", key.mesh, key.opacity)),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
label: Some(&format!("{} {:?}", key.mesh, key.opacity)),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
| AccelerationStructureFlags::ALLOW_COMPACTION,
update_mode: AccelerationStructureUpdateMode::Build,
},
@@ -12,10 +12,12 @@ use derive_more::derive::From;
///
/// The mesh used in this component must declare the BLAS its material needs in
/// [`Mesh::raytracing`],
/// use the following set of vertex attributes: `{POSITION, NORMAL, UV_0, TANGENT}`, use [`bevy_mesh::PrimitiveTopology::TriangleList`],
/// use the following set of vertex attributes: `{POSITION, NORMAL, UV_0,
/// TANGENT}`, use [`bevy_mesh::PrimitiveTopology::TriangleList`],
/// and use [`bevy_mesh::Indices::U32`].
///
/// The material used for this entity must be [`MeshMaterial3d<StandardMaterial>`].
/// The material used for this entity must be
/// [`MeshMaterial3d<StandardMaterial>`].
#[derive(
Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From,
)]
@@ -30,9 +30,9 @@ const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
#[derive(Resource, Default)]
pub struct BlasManager {
blas: HashMap<AssetId<Tape>, TapeBlas>,
changed: Vec<AssetId<Tape>>,
needs_new_blas: Vec<AssetId<Tape>>,
blas: HashMap<AssetId<Tape>, TapeBlas>,
changed: Vec<AssetId<Tape>>,
needs_new_blas: Vec<AssetId<Tape>>,
/// BLAS that are pending deletion, one batch per TLAS build. The back batch
/// collects retirements since the last build, and every batch ahead of
/// it has one more build to wait out.
@@ -41,6 +41,14 @@ pub struct BlasManager {
impl BlasManager {
pub fn get(&self, key: &BlasKey) -> Option<&Blas> {
if self.needs_new_blas.contains(&key.tape) {
None
} else {
self.get_uninit(key)
}
}
pub fn get_uninit(&self, key: &BlasKey) -> Option<&Blas> {
self.blas.get(&key.tape)?.get(key.opacity)
}
@@ -98,16 +106,16 @@ impl BlasManager {
}
struct TapeBlas {
requires: MeshRaytracingFlags,
opaque: Option<Blas>,
requires: MeshRaytracingFlags,
opaque: Option<Blas>,
non_opaque: Option<Blas>,
}
impl Default for TapeBlas {
fn default() -> Self {
Self {
requires: MeshRaytracingFlags::empty(),
opaque: None,
requires: MeshRaytracingFlags::empty(),
opaque: None,
non_opaque: None,
}
}
@@ -135,7 +143,7 @@ impl TapeBlas {
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BlasKey {
pub tape: AssetId<Tape>,
pub tape: AssetId<Tape>,
pub opacity: BlasOpacity,
}
@@ -234,37 +242,34 @@ pub fn compile_raytracing_blas(
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"),
label: Some("enable_gen"),
timestamp_writes: None,
});
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
#[repr(C)]
struct PushConstants {
aabb_buffer_offset: u32,
aabb_buffer_offset: u32,
metadata_buffer_offset: u32,
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))
.map(|(asset_id, tape)| {
let key = BlasKey {
tape: asset_id,
tape: asset_id,
opacity: BlasOpacity::Opaque,
};
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 tiletree = tape_allocator.tape_tiletree(&asset_id).unwrap();
let blas_size = BlasAABBGeometrySizeDescriptor {
primitive_count: aabbs_slice.range.len() as u32,
flags: key.opacity.geometry_flags(),
flags: key.opacity.geometry_flags(),
};
(
@@ -273,6 +278,7 @@ pub fn compile_raytracing_blas(
aabbs_slice,
metadata_slice,
spatial_texture,
tiletree,
blas_size,
)
})
@@ -283,35 +289,66 @@ pub fn compile_raytracing_blas(
let build_entries = tape_info
.iter()
.filter_map(
|(key, tape, aabbs_slice, metadata_slice, spatial_texture, blas_size)| {
let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?;
|(key, tape, aabbs_slice, metadata_slice, spatial_texture, tiletree, blas_size)| {
let enable_gen_pipeline =
pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?;
let spatial_texture_pipeline =
pipeline_cache.get_compute_pipeline(tape.spatial_texture_pipeline)?;
let tiletree_pipeline =
pipeline_cache.get_compute_pipeline(tape.tiletree_pipeline)?;
let bind_group = render_device.create_bind_group(
let enable_gen_bind_group = render_device.create_bind_group(
"enable_gen_bind_group",
&pipeline_cache.get_bind_group_layout(&replacement_modules.enable_gen_layout),
&BindGroupEntries::sequential((
metadata_slice.buffer.as_entire_buffer_binding(),
aabbs_slice.buffer.as_entire_buffer_binding(),
)),
);
let spatial_texture_bind_group = render_device.create_bind_group(
"spatial_texture_bind_group",
&pipeline_cache
.get_bind_group_layout(&replacement_modules.spatial_texture_layout),
&BindGroupEntries::sequential((
metadata_slice.buffer.as_entire_buffer_binding(),
&spatial_texture.1,
)),
);
let mut pc = PushConstants {
aabb_buffer_offset: aabbs_slice.range.start,
let tiletree_bind_group = render_device.create_bind_group(
"tiletree_bind_group",
&pipeline_cache.get_bind_group_layout(&replacement_modules.tiletree_layout),
&BindGroupEntries::sequential((
metadata_slice.buffer.as_entire_buffer_binding(),
aabbs_slice.buffer.as_entire_buffer_binding(),
&spatial_texture.1,
&tiletree.1,
)),
);
let pc = PushConstants {
aabb_buffer_offset: aabbs_slice.range.start,
metadata_buffer_offset: metadata_slice.range.start,
flags: FLAG_FILL_ENABLE_GEN,
};
compute_pass.set_pipeline(pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.set_pipeline(enable_gen_pipeline);
compute_pass.set_immediates(0, bytemuck::bytes_of(&pc));
compute_pass.set_bind_group(0, &enable_gen_bind_group, &[]);
compute_pass.dispatch_workgroups(
tape.subdivision / 8,
tape.subdivision / 8,
tape.subdivision / 8,
tape.subdivision / 4,
tape.subdivision / 4,
tape.subdivision / 4,
);
pc.flags = FLAG_FILL_SPATIAL_TEXTURE;
compute_pass.set_immediates(0, bytemuck::bytes_of(&pc));
compute_pass.set_pipeline(spatial_texture_pipeline);
compute_pass.set_bind_group(0, &spatial_texture_bind_group, &[]);
compute_pass.dispatch_workgroups(
tape.subdivision * 2,
tape.subdivision * 2,
tape.subdivision * 2,
);
compute_pass.set_pipeline(tiletree_pipeline);
compute_pass.set_bind_group(0, &tiletree_bind_group, &[]);
compute_pass.dispatch_workgroups(
tape.subdivision,
tape.subdivision,
@@ -321,13 +358,13 @@ pub fn compile_raytracing_blas(
updated_blases.push(key.tape);
let geometry = BlasAabbGeometry {
size: blas_size,
stride: size_of::<bevy_tape_load::render::PackedAabb>() as u64,
aabb_buffer: aabbs_slice.buffer,
size: blas_size,
stride: size_of::<bevy_tape_load::render::PackedAabb>() as u64,
aabb_buffer: aabbs_slice.buffer,
primitive_offset: aabbs_slice.range.start,
};
Some(BlasBuildEntry {
blas: blas_manager.get(&key).unwrap(),
blas: blas_manager.get_uninit(&key).unwrap(),
geometry: BlasGeometries::AabbGeometries(vec![geometry]),
})
},
@@ -367,15 +404,15 @@ fn allocate_blas(
) -> (Blas, BlasAABBGeometrySizeDescriptor) {
let blas_size = BlasAABBGeometrySizeDescriptor {
primitive_count: aabbs_slice.range.len() as u32,
flags: key.opacity.geometry_flags(),
flags: key.opacity.geometry_flags(),
};
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS
// double-buffer to avoid invalidating the previous frame TLAS
let blas = render_device.wgpu_device().create_blas(
&CreateBlasDescriptor {
label: Some(&format!("{} {:?}", key.tape, key.opacity)),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
label: Some(&format!("{} {:?}", key.tape, key.opacity)),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
| AccelerationStructureFlags::ALLOW_COMPACTION,
update_mode: AccelerationStructureUpdateMode::Build,
},
+66 -25
View File
@@ -1,33 +1,52 @@
use naga::back::spv::PipelineOptions;
use wesl::{CompileOptions, syntax::ModulePath};
use wesl::Feature;
const SHADERS_ROOT_DIR: &str = "src";
const SHADERS_IN: &str = "render";
const SHADERS_OUT: &str = "shaders_out/";
fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::ShaderStage) {
let compiler = wesl::Compiler::new(CompileOptions {
fn compile_replacement_shader(
name_in: &str,
name_out: &str,
entry_point: String,
stage: naga::ShaderStage,
flags: &[(&str, Feature)],
) {
let compiler = wesl::Compiler::new(wesl::CompileOptions {
imports: true,
condcomp: true,
features: wesl::Features {
default: Feature::Disable,
flags: flags
.into_iter()
.map(|(k, v)| (k.to_string(), *v))
.collect(),
},
..Default::default()
});
let shader = match compiler.compile_module(
SHADERS_ROOT_DIR,
&ModulePath::from_path(format!("/{SHADERS_IN}/{name}")),
&wesl::syntax::ModulePath::from_path(format!("/{SHADERS_IN}/{name_in}")),
) {
Ok(s) => s,
Err(e) => panic!("{}", e.diagnostic().render_colored()),
};
shader.emit_rerun_if_changed();
shader
.write_to_file(format!("{SHADERS_OUT}/{name}.wgsl"))
.write_to_file(format!("{SHADERS_OUT}/{name_out}.wgsl"))
.unwrap();
let shader = shader.to_string();
// Parse the source into a Module.
let module: naga::Module = naga::front::wgsl::parse_str(&shader)
.inspect_err(|e| e.emit_to_stderr_with_path(&shader, format!("{SHADERS_IN}/{name}.wesl")))
let module: naga::Module =
naga::front::wgsl::Frontend::new_with_options(naga::front::wgsl::Options {
parse_doc_comments: false,
capabilities: naga::valid::Capabilities::all(),
})
.parse(&shader)
.inspect_err(|e| {
e.emit_to_stderr_with_path(&shader, format!("{SHADERS_IN}/{name_in}.wesl"))
})
.expect("Failed to parse WGSL");
// Validate the module.
// Validation can be made less restrictive by changing the ValidationFlags.
@@ -38,7 +57,7 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
.subgroup_stages(naga::valid::ShaderStages::all())
.subgroup_operations(naga::valid::SubgroupOperationSet::all())
.validate(&module)
.inspect_err(|e| e.emit_to_stderr_with_path(&shader, &format!("{SHADERS_IN}/{name}.wesl")))
.inspect_err(|e| e.emit_to_stderr_with_path(&shader, &format!("{SHADERS_IN}/{name_in}.wesl")))
.unwrap();
// Translate the module.
@@ -55,7 +74,7 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
.write(
&module,
&module_info,
Some(&PipelineOptions {
Some(&spv::PipelineOptions {
shader_stage: stage,
entry_point,
}),
@@ -65,7 +84,7 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
.unwrap();
std::fs::write(
format!("{SHADERS_OUT}/{name}.orig.spv"),
format!("{SHADERS_OUT}/{name_out}.orig.spv"),
spv_out
.into_iter()
.flat_map(|f| f.to_le_bytes())
@@ -74,13 +93,13 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
.unwrap();
std::process::Command::new("spirv-dis")
.arg(format!("{SHADERS_OUT}/{name}.orig.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.orig.spv"))
.arg("-o")
.arg(format!("{SHADERS_OUT}/{name}.stage0.spv-dis"))
.arg(format!("{SHADERS_OUT}/{name_out}.stage0.spv-dis"))
.status()
.expect("Failed to disassemble shader");
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_out}.stage0.spv-dis")).unwrap();
let asm = regex::regex!("(?ms)%package_render_implicit_scene =.*?OpFunctionEnd")
.replace_all(&asm, "");
@@ -111,15 +130,15 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
let asm = asm.into_owned();
std::fs::write(format!("{SHADERS_OUT}/{name}.stage1.spv-dis"), &asm).unwrap();
std::fs::write(format!("{SHADERS_OUT}/{name_out}.stage1.spv-dis"), &asm).unwrap();
std::process::Command::new("spirv-as")
.arg("--preserve-numeric-ids")
.arg("--target-env")
.arg("vulkan1.4")
.arg("-o")
.arg(format!("{SHADERS_OUT}/{name}.opt0.spv"))
.arg(format!("{SHADERS_OUT}/{name}.stage1.spv-dis"))
.arg(format!("{SHADERS_OUT}/{name_out}.opt0.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.stage1.spv-dis"))
.status()
.expect("Failed to assemble shader");
@@ -128,23 +147,23 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
.arg("--strip-debug")
.arg("--strip-nonsemantic")
.arg("-o")
.arg(format!("{SHADERS_OUT}/{name}.opt1.spv"))
.arg(format!("{SHADERS_OUT}/{name}.opt0.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.opt1.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.opt0.spv"))
.status()
.expect("Failed to optimise shader");
std::process::Command::new("spirv-opt")
.arg("-O")
.arg("-o")
.arg(format!("{SHADERS_OUT}/{name}.spv"))
.arg(format!("{SHADERS_OUT}/{name}.opt1.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.opt1.spv"))
.status()
.expect("Failed to optimise shader");
std::process::Command::new("spirv-dis")
.arg(format!("{SHADERS_OUT}/{name}.spv"))
.arg(format!("{SHADERS_OUT}/{name_out}.spv"))
.arg("-o")
.arg(format!("{SHADERS_OUT}/{name}.stage2.spv-dis"))
.arg(format!("{SHADERS_OUT}/{name_out}.stage2.spv-dis"))
.status()
.expect("Failed to disassemble final shader");
}
@@ -155,7 +174,29 @@ fn main() {
}
std::fs::create_dir_all("shaders_out").unwrap();
for (shader, entry, stage) in [("enable_gen", "main", naga::ShaderStage::Compute)] {
compile_replacement_shader(shader, entry.into(), stage);
for (shader_in, shader_out, entry, stage, flags) in [
(
"enable_gen",
"enable_gen",
"main",
naga::ShaderStage::Compute,
vec![("fill_enable_gen", Feature::Enable)],
),
(
"enable_gen",
"spatial_texture",
"main",
naga::ShaderStage::Compute,
vec![("fill_spatial_texture", Feature::Enable)],
),
(
"tiletree",
"tiletree",
"main",
naga::ShaderStage::Compute,
vec![],
),
] {
compile_replacement_shader(shader_in, shader_out, entry.into(), stage, &flags);
}
}
@@ -31,21 +31,21 @@ impl SphereTapeBuilder {
let pos = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAPosition,
size: 1,
size: 1,
},
vec![],
);
let sphere = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSASDFSphere,
size: 1,
size: 1,
},
vec![pos[0], pos[1], pos[2], SSAInput::Constant(radius)],
);
tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAReturn,
size: 1,
size: 1,
},
sphere,
);
+2 -2
View File
@@ -5,6 +5,6 @@ struct PackedAabb {
max_x: f32,
max_y: f32,
max_z: f32,
pad_a: u32,
pad_b: u32,
tiletree_index: u32,
padding: u32,
}
+52 -20
View File
@@ -47,8 +47,9 @@ pub struct TapeAllocatorPlugin;
pub struct TapeAllocator {
/// Holds all buffers and offset allocators.
#[deref]
slab_allocator: SlabAllocator<TapeSlabItem>,
slab_allocator: SlabAllocator<TapeSlabItem>,
spatial_texture_allocator: HashMap<AssetId<Tape>, (Texture, TextureView)>,
tiletree_allocator: HashMap<AssetId<Tape>, (Texture, TextureView)>,
}
/// Tunable parameters that customize the behavior of the allocator.
@@ -69,7 +70,7 @@ impl Default for TapeAllocatorSettings {
fn default() -> TapeAllocatorSettings {
TapeAllocatorSettings {
slab_allocator_settings: SlabAllocatorSettings::default(),
extra_buffer_usages: BufferUsages::empty(),
extra_buffer_usages: BufferUsages::empty(),
}
}
}
@@ -98,7 +99,7 @@ impl SlabItem for TapeSlabItem {
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct TapeSlabs {
/// The slab storing the tape's aabb data.
pub aabb_slab_id: TapeSlabId,
pub aabb_slab_id: TapeSlabId,
/// The slab storing the tape's metadata.
pub metadata_slab_id: TapeSlabId,
}
@@ -114,7 +115,7 @@ pub struct TapeAllocationKey {
/// The ID of the tape asset.
pub tape_id: AssetId<Tape>,
/// The type of data: vertex data, index data
pub class: ElementClass,
pub class: ElementClass,
}
impl TapeAllocationKey {
@@ -201,6 +202,7 @@ impl FromWorld for TapeAllocator {
Self {
slab_allocator,
spatial_texture_allocator: HashMap::new(),
tiletree_allocator: HashMap::new(),
}
}
}
@@ -282,6 +284,13 @@ impl TapeAllocator {
self.spatial_texture_allocator.get(tape_id)
}
/// Returns the spatial texture for the tape with the given ID.
///
/// If the tape wasn't allocated, returns None.
pub fn tape_tiletree(&self, tape_id: &AssetId<Tape>) -> Option<&(Texture, TextureView)> {
self.tiletree_allocator.get(tape_id)
}
/// Returns the IDs of the vertex buffer and index buffer respectively for
/// the tape with the given ID.
///
@@ -290,7 +299,7 @@ impl TapeAllocator {
/// None.
pub fn tape_slabs(&self, tape_id: &AssetId<Tape>) -> Option<TapeSlabs> {
Some(TapeSlabs {
aabb_slab_id: self.tape_id_to_aabb_slab(tape_id).cloned()?,
aabb_slab_id: self.tape_id_to_aabb_slab(tape_id).cloned()?,
metadata_slab_id: self.tape_id_to_metadata_slab(tape_id).cloned()?,
})
}
@@ -376,17 +385,18 @@ impl TapeAllocator {
tape_allocator_settings,
);
// Allocate spatial texture.
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,
label: Some(&format!("Tape {} spatial texture", tape_id)),
format: TextureFormat::R16Float,
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 * 8,
height: tape.subdivision * 8,
sample_count: 1,
view_formats: &[TextureFormat::R16Float],
size: Extent3d {
width: tape.subdivision * 8,
height: tape.subdivision * 8,
depth_or_array_layers: tape.subdivision * 8,
},
});
@@ -394,10 +404,31 @@ impl TapeAllocator {
label: Some(&format!("Tape {} spatial texture view", tape_id)),
..Default::default()
});
// Allocate spatial texture.
self.spatial_texture_allocator
.insert(*tape_id, (texture, texture_view));
// Allocate worst-case tiletree
let texture = render_device.create_texture(&TextureDescriptor {
label: Some(&format!("Tape {} tiletree", tape_id)),
format: TextureFormat::Rgb10a2Unorm,
dimension: TextureDimension::D3,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
mip_level_count: 1,
sample_count: 1,
view_formats: &[TextureFormat::Rgb10a2Unorm],
size: Extent3d {
width: tape.subdivision * 4 * 2 * 2,
height: tape.subdivision * 4 * 2 * 2,
depth_or_array_layers: tape.subdivision * 4 * 2 * 2,
},
});
let texture_view = texture.create_view(&TextureViewDescriptor {
label: Some(&format!("Tape {} tiletree view", tape_id)),
..Default::default()
});
self.tiletree_allocator
.insert(*tape_id, (texture, texture_view));
}
// Perform growth.
@@ -490,6 +521,7 @@ impl TapeAllocator {
deallocation_stage.free(&TapeAllocationKey::new(*tape_id, ElementClass::Metadata));
deallocation_stage.free(&TapeAllocationKey::new(*tape_id, ElementClass::Aabb));
self.spatial_texture_allocator.remove(tape_id);
self.tiletree_allocator.remove(tape_id);
}
deallocation_stage.commit();
@@ -521,10 +553,10 @@ impl ElementLayout {
/// data.
fn metadata(_tape: &Tape) -> ElementLayout {
ElementLayout {
class: ElementClass::Metadata,
size: size_of::<TapeMetadata>() as u64,
class: ElementClass::Metadata,
size: size_of::<TapeMetadata>() as u64,
elements_per_slot: 1,
buffer_usages: ElementClass::Metadata.buffer_usages(),
buffer_usages: ElementClass::Metadata.buffer_usages(),
}
}
@@ -557,7 +589,7 @@ impl ElementClass {
ElementClass::Metadata => BufferUsages::STORAGE,
ElementClass::Aabb => {
BufferUsages::union(BufferUsages::STORAGE, BufferUsages::BLAS_INPUT)
}
},
}
}
}
@@ -14,19 +14,14 @@ struct TapeMetadataBuffer {
}
struct PushConstants {
aabb_buffer_offset: u32,
metadata_buffer_offset: u32,
flags: u32
metadata_buffer_offset: u32
}
const FLAG_FILL_ENABLE_GEN = 1 << 0;
const FLAG_FILL_SPATIAL_TEXTURE = 1 << 1;
@group(0) @binding(0)
var<storage, read_write> aabb_buffer: AabbBuffer;
@group(0) @binding(1)
var<storage> tape_metadata_buffer: TapeMetadataBuffer;
@group(0) @binding(2)
var spatial_texture: texture_storage_3d<r32float, write>;
@group(0) @binding(0) var<storage> tape_metadata_buffer: TapeMetadataBuffer;
@if(fill_enable_gen)
@group(0) @binding(1) var<storage, read_write> aabb_buffer: AabbBuffer;
@if(fill_spatial_texture)
@group(0) @binding(1) var spatial_texture: texture_storage_3d<r16float, write>;
var<immediate> push_constants: PushConstants;
@@ -34,14 +29,14 @@ struct ComputeInput {
@builtin(global_invocation_id) global_invocation_id: vec3u
}
@compute @workgroup_size(8, 8, 8)
@compute @workgroup_size(4, 4, 4)
fn main(compute_input: ComputeInput) {
var metadata = tape_metadata_buffer.metadata[push_constants.metadata_buffer_offset];
let uinternal_pos = compute_input.global_invocation_id;
let internal_pos = vec3f(uinternal_pos);
if (push_constants.flags & FLAG_FILL_ENABLE_GEN) > 0 {
@if(fill_enable_gen) {
let low_corner = internal_to_external_pos(internal_pos + vec3(0.0), metadata);
let high_corner = internal_to_external_pos(internal_pos + vec3(1.0), metadata);
@@ -50,7 +45,7 @@ fn main(compute_input: ComputeInput) {
vec4(high_corner, metadata.time),
);
let base_index = encode_internal_pos(uinternal_pos, metadata.subdivision_log2);
let base_index = encode_internal_pos(uinternal_pos);
let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index];
let en = (interval.x < 0) && (interval.y > 0);
@@ -67,7 +62,7 @@ fn main(compute_input: ComputeInput) {
}
}
if (push_constants.flags & FLAG_FILL_SPATIAL_TEXTURE) > 0 {
@if(fill_spatial_texture) {
metadata.lowest_corner -= SPATIAL_SCENE_OFFSET;
metadata.dimensions *= INVERSE_SPATIAL_SCENE_SCALE;
metadata.subdivision_log2 += 3;
@@ -76,6 +71,6 @@ fn main(compute_input: ComputeInput) {
let point = scene(vec4(mid_point, metadata.time));
textureStore(spatial_texture, compute_input.global_invocation_id, vec4(point, 0., 0., 0.));
textureStore(spatial_texture, uinternal_pos, vec4(point, 0., 0., 0.));
}
}
+89 -37
View File
@@ -19,10 +19,7 @@ use bevy_render::{
render_resource::{
BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, CachedComputePipelineId,
ComputePipelineDescriptor, PipelineCache, ShaderType,
binding_types::{
storage_buffer, storage_buffer_read_only, texture_3d, texture_storage_2d_array,
texture_storage_3d,
},
binding_types::{storage_buffer, storage_buffer_read_only, texture_3d, texture_storage_3d},
},
};
use bevy_shader::{Shader, load_shader_library};
@@ -41,8 +38,8 @@ use crate::{
#[derive(Default, Pod, Zeroable, Clone, Copy, Debug, ShaderType)]
#[repr(C)]
pub struct PackedAabb {
min: Vec3,
max: Vec3,
min: Vec3,
max: Vec3,
pad_a: u32,
pad_b: u32,
}
@@ -52,9 +49,9 @@ pub struct PackedAabb {
#[derive(Default, Pod, Zeroable, Clone, Copy, Debug, ShaderType)]
#[repr(C)]
pub struct TapeMetadata {
lowest_corner: Vec3,
time: f32,
dimensions: Vec3,
lowest_corner: Vec3,
time: f32,
dimensions: Vec3,
subdivision_log2: u32,
}
@@ -89,20 +86,46 @@ impl Plugin for TapeRenderAssetPlugin {
};
let enable_gen = include_spirv_raw!("../../shaders_out/enable_gen.spv");
let spatial_texture = include_spirv_raw!("../../shaders_out/spatial_texture.spv");
let tiletree = include_spirv_raw!("../../shaders_out/tiletree.spv");
let modules = ReplacementModules {
enable_gen: get_module(enable_gen.clone()),
normals: get_module(enable_gen.clone()),
trace: get_module(enable_gen.clone()),
enable_gen_layout: BindGroupLayoutDescriptor::new(
enable_gen: get_module(enable_gen),
spatial_texture: get_module(spatial_texture),
tiletree: get_module(tiletree),
enable_gen_layout: BindGroupLayoutDescriptor::new(
"Enable Gen Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer_read_only::<TapeMetadata>(false),
storage_buffer::<PackedAabb>(false),
),
),
),
spatial_texture_layout: BindGroupLayoutDescriptor::new(
"Spatial texture Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer_read_only::<TapeMetadata>(false),
texture_storage_3d(
TextureFormat::R32Float,
TextureFormat::R16Float,
StorageTextureAccess::WriteOnly,
),
),
),
),
tiletree_layout: BindGroupLayoutDescriptor::new(
"Tiletree Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer_read_only::<TapeMetadata>(false),
storage_buffer_read_only::<PackedAabb>(false),
texture_3d(TextureSampleType::Float { filterable: true }),
texture_storage_3d(
TextureFormat::Rgb10a2Unorm,
StorageTextureAccess::WriteOnly,
),
),
@@ -110,6 +133,8 @@ impl Plugin for TapeRenderAssetPlugin {
),
};
dbg!(&modules.spatial_texture_layout);
render_app.insert_resource(modules);
render_app.add_systems(
@@ -141,7 +166,7 @@ pub struct TapeMetadataFallbackTape(pub Handle<Tape>);
#[derive(Resource)]
pub struct TapeMetadataFallbackBuffer {
pub slab_id: TapeSlabId,
pub buffer: Buffer,
pub buffer: Buffer,
}
pub fn prepare_tape_metadata_fallback_buffer(
@@ -163,26 +188,30 @@ pub fn prepare_tape_metadata_fallback_buffer(
#[derive(Resource)]
pub struct ReplacementModules {
pub enable_gen: Module,
pub normals: Module,
pub trace: Module,
pub enable_gen: Module,
pub spatial_texture: Module,
pub tiletree: Module,
pub enable_gen_layout: BindGroupLayoutDescriptor,
pub enable_gen_layout: BindGroupLayoutDescriptor,
pub spatial_texture_layout: BindGroupLayoutDescriptor,
pub tiletree_layout: BindGroupLayoutDescriptor,
}
/// The render world representation of a [`Tape`].
#[derive(Debug, Clone)]
pub struct RenderTape {
pub seed: u64,
pub seed: u64,
pub subdivision: u32,
pub time: f32,
pub key: u64,
pub time: f32,
pub key: u64,
pub enable_gen: Handle<Shader>,
pub normals: Handle<Shader>,
pub trace: Handle<Shader>,
pub enable_gen: Handle<Shader>,
pub spatial_texture: Handle<Shader>,
pub tiletree: Handle<Shader>,
pub enable_gen_pipeline: CachedComputePipelineId,
pub enable_gen_pipeline: CachedComputePipelineId,
pub spatial_texture_pipeline: CachedComputePipelineId,
pub tiletree_pipeline: CachedComputePipelineId,
}
impl RenderAsset for RenderTape {
@@ -223,9 +252,11 @@ impl RenderAsset for RenderTape {
time: tape.time,
key,
enable_gen: previous.enable_gen.clone(),
normals: previous.normals.clone(),
trace: previous.trace.clone(),
spatial_texture: previous.spatial_texture.clone(),
tiletree: previous.tiletree.clone(),
enable_gen_pipeline: previous.enable_gen_pipeline,
spatial_texture_pipeline: previous.spatial_texture_pipeline,
tiletree_pipeline: previous.tiletree_pipeline,
});
}
@@ -234,15 +265,15 @@ impl RenderAsset for RenderTape {
replacement_modules.enable_gen.clone(),
"enable_gen",
));
let normals = asset_server.add(tape.sdf_specialize_module_with_key(
let spatial_texture = asset_server.add(tape.sdf_specialize_module_with_key(
key,
replacement_modules.normals.clone(),
"normals",
replacement_modules.spatial_texture.clone(),
"spatial_texture",
));
let trace = asset_server.add(tape.sdf_specialize_module_with_key(
let tiletree = asset_server.add(tape.sdf_specialize_module_with_key(
key,
replacement_modules.trace.clone(),
"trace",
replacement_modules.tiletree.clone(),
"tiletree",
));
let enable_gen_pipeline =
@@ -250,20 +281,41 @@ impl RenderAsset for RenderTape {
label: Some(format!("bevy_tape_drive::gen_shader::enable_gen::{key}").into()),
layout: vec![replacement_modules.enable_gen_layout.clone()],
shader: enable_gen.clone(),
immediate_size: 12,
immediate_size: 8,
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: 8,
entry_point: Some("main".into()),
..Default::default()
});
let tiletree_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
label: Some(format!("bevy_tape_drive::gen_shader::tiletree::{key}").into()),
layout: vec![replacement_modules.tiletree_layout.clone()],
shader: tiletree.clone(),
immediate_size: 8,
entry_point: Some("main".into()),
..Default::default()
});
Ok(RenderTape {
seed: tape.seed,
subdivision: tape.subdivision,
time: tape.time,
key,
enable_gen,
normals,
trace,
spatial_texture,
tiletree,
enable_gen_pipeline,
spatial_texture_pipeline,
tiletree_pipeline,
})
}
@@ -0,0 +1,203 @@
import package::render::aabb::PackedAabb;
import package::render::metadata_types::TapeMetadata;
import package::render::implicit::{interval_scene, scene, gradient_scene};
import package::render::util::{NAN, decode_internal_pos, encode_internal_pos, internal_to_external_pos};
import package::render::spatial_implicit::{SPATIAL_SCENE_OFFSET, INVERSE_SPATIAL_SCENE_SCALE};
enable wgpu_binding_array;
struct AabbBuffer {
aabbs: array<PackedAabb>,
}
struct TapeMetadataBuffer {
metadata: array<TapeMetadata>,
}
struct PushConstants {
aabb_buffer_offset: u32,
metadata_buffer_offset: u32,
}
@group(0) @binding(0)
var<storage> tape_metadata_buffer: TapeMetadataBuffer;
@group(0) @binding(1)
var<storage, read> aabb_buffer: AabbBuffer;
@group(0) @binding(2)
var spatial_texture: texture_3d<f32>;
@group(0) @binding(3)
var tiletree: texture_storage_3d<rgb10a2unorm, write>;
//@group(0) @binding(4)
//var tiletree_pointer: atomic<u32>;
const SUBDIVIDE_LOOPS: i32 = 2;
const SOLVE_ARRAY_LEN: u32 = 16 * 16 * 16;
const OCTREE_LEN: u32 = SOLVE_ARRAY_LEN * 6;
struct Octree {
bitmask: array<u32, OCTREE_LEN / 32>,
summary_0: array<u32, OCTREE_LEN / 32 / 2>,
summary_1: array<u32, OCTREE_LEN / 32 / 32>,
}
var<workgroup> octree: Octree;
var<immediate> push_constants: PushConstants;
struct ComputeInput {
@builtin(workgroup_id) workgroup_id: vec3u,
@builtin(num_subgroups) num_subgroups: u32,
@builtin(subgroup_id) subgroup_id: u32,
@builtin(subgroup_invocation_id) subgroup_invocation_id: u32,
@builtin(subgroup_size) subgroup_size: u32,
}
fn in_aabb(metadata: TapeMetadata, internal_pos: vec3f) -> bool {
let low_corner = internal_to_external_pos(internal_pos + vec3(0.0), metadata);
let high_corner = internal_to_external_pos(internal_pos + vec3(1.0), metadata);
let interval = interval_scene(
vec4(low_corner, metadata.time),
vec4(high_corner, metadata.time),
);
return (interval.x < 0) && (interval.y > 0);
}
fn init_octree() {
let stride = get_stride(3);
octree.bitmask[(stride * 0) >> 5] = 1;
octree.bitmask[(stride * 1) >> 5] = 1;
octree.bitmask[(stride * 2) >> 5] = 1;
octree.bitmask[(stride * 3) >> 5] = 1;
octree.bitmask[(stride * 4) >> 5] = 1;
octree.bitmask[(stride * 5) >> 5] = 1;
octree.bitmask[(stride * 6) >> 5] = 1;
octree.bitmask[(stride * 7) >> 5] = 1;
}
fn get_stride(level: u32) -> u32 {
return encode_internal_pos(vec3u(1u << level, 0, 0));
}
fn write_work_item_level_0(subgroup_width: u32, cursor: u32, en: bool) {
let ballot = subgroupBallot(en);
if subgroup_elect() {
octree.bitmask[cursor >> 5] = ballot.x;
if subgroup_width > 32 {
octree.bitmask[(cursor >> 5) + 1] = ballot.y;
}
}
}
fn write_work_item(subgroup_width: u32, stride: u32, cursor: u32, en: u32) {
if stride == 1 {
write_work_item_level_0(subgroup_width, cursor, en != 0);
return;
}
var working_write = 0u;
var cursor_head = cursor;
for (var i = 0; i < 8; i++) {
let bit_pos = (cursor_head & 31);
working_write |= (en << bit_pos);
if bit_pos + stride > 31 {
octree.bitmask[cursor_head >> 5] = working_write;
working_write = 0;
}
cursor_head += stride;
}
}
// subgroupElect is not implemented in naga
fn subgroup_elect() -> bool {
let index = subgroupExclusiveAdd(1);
return subgroupBroadcastFirst(index) == index;
}
fn workgroup_elect(subgroup_id: u32) -> bool {
return subgroup_id == 0 && subgroup_elect();
}
const WORKGROUP_SIZE = vec3u(4, 4, 4);
@compute @workgroup_size(4 * 4 * 4)
fn main(compute_input: ComputeInput) {
var metadata = tape_metadata_buffer.metadata[push_constants.metadata_buffer_offset];
var exit = 0;
if subgroup_elect() {
let base_index = encode_internal_pos(compute_input.workgroup_id);
let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index];
if bitcast<u32>(aabb.min_x) == 0xFFC00000u {
exit = 1;
}
}
exit = subgroupBroadcastFirst(exit);
if exit == 1 {
return;
}
if (workgroup_elect(compute_input.subgroup_id)) {
init_octree();
}
let global_offset = compute_input.workgroup_id * 16;
metadata.subdivision_log2 += 2;
let subgroup_stride = SOLVE_ARRAY_LEN / compute_input.num_subgroups;
for (var level = 3; level >= 0; level--) {
workgroupBarrier();
let level_stride = get_stride(u32(level));
let cursor_start = (subgroup_stride * compute_input.subgroup_id) + (level_stride * compute_input.subgroup_invocation_id);
let cursor_end = (subgroup_stride * (compute_input.subgroup_id + 1));
let cursor_stride = (level_stride * compute_input.subgroup_size);
if level > 0 {
for (var cursor = cursor_start ; cursor < cursor_end; cursor += cursor_stride) {
var solve_item = 0u;
if cursor < SOLVE_ARRAY_LEN {
solve_item = (octree.bitmask[cursor >> 5] >> (cursor & 31)) & 1;
if solve_item != 0 {
let uinternal_pos_local = decode_internal_pos(cursor);
let uinternal_pos_global = ((uinternal_pos_local + global_offset) / (1u << u32(level + 1))) ;
solve_item = u32(in_aabb(metadata, vec3f(uinternal_pos_global)));
}
}
write_work_item(compute_input.subgroup_size, level_stride / 8, cursor, solve_item);
}
if level > 1 {
metadata.subdivision_log2 += 1;
}
} else {
for (var cursor = cursor_start ; cursor < cursor_end; cursor += cursor_stride) {
if cursor < SOLVE_ARRAY_LEN {
let solve_item = (octree.bitmask[cursor >> 5] >> (cursor & 31)) & 1;
let uinternal_pos_local = decode_internal_pos(cursor);
let uinternal_pos_global = uinternal_pos_local + global_offset;
let position = internal_to_external_pos(vec3f(uinternal_pos_global), metadata);
let leaf_face_mask = solve_item * 0xb111111u;
for (var i = 0u; i < 6; i++) {
write_work_item_level_0(compute_input.subgroup_size, cursor + (SOLVE_ARRAY_LEN * i), (leaf_face_mask & (1u << i)) > 0);
}
if solve_item != 0 {
//let grad = gradient_scene(vec4(position, metadata.time));
const EPSILON = 0.001;
let n = vec3(
scene(vec4(position.x + EPSILON, position.y, position.z, metadata.time)),
scene(vec4(position.x, position.y + EPSILON, position.z, metadata.time)),
scene(vec4(position.x, position.y, position.z + EPSILON, metadata.time)),
);
let grad = normalize(n - (scene(vec4(position, metadata.time))));
textureStore(tiletree, uinternal_pos_global, vec4(grad * 0.5 + 0.5, 1.0));
}
}
}
}
}
}
+1 -1
View File
@@ -86,7 +86,7 @@ fn sebastian_trace(metadata: TapeMetadata, spatial_texture: u32, near_plane: f32
}
fn trace_tape(metadata: TapeMetadata, spatial_texture: u32, primitive_id: u32, ray_pos: vec3<f32>, ray_dir: vec3<f32>, primary_ray: bool) -> f32 {
let uinternal_pos = decode_internal_pos(primitive_id, metadata.subdivision_log2);
let uinternal_pos = decode_internal_pos(primitive_id);
let internal_pos = vec3f(uinternal_pos);
let dimensions = internal_to_external_pos(vec3(1.0), metadata) - metadata.lowest_corner;
+39 -7
View File
@@ -2,18 +2,50 @@ import package::render::metadata_types::TapeMetadata;
fn NAN() -> f32 {
return bitcast<f32>(0xFFC00000u);
}
// https://github.com/Forceflow/libmorton/blob/main/include/libmorton/morton3D.h
fn morton_split_by_3(a: u32) -> u32 {
var x = a & 0x000003ff;
x = (x | (x << 16)) & 0x30000ff;
x = (x | (x << 8)) & 0x0300f00f;
x = (x | (x << 4)) & 0x30c30c3;
x = (x | (x << 2)) & 0x9249249;
return x;
}
fn decode_internal_pos(base_index: u32, subdivision_log2: u32) -> vec3<u32> {
// ENCODE 3D Morton code : Magic bits method
// This method uses certain bit patterns (magic bits) to split bits in the coordinates
fn morton_encode(pos: vec3<u32>) -> u32 {
return morton_split_by_3(pos.x) | (morton_split_by_3(pos.y) << 1) | (morton_split_by_3(pos.z) << 2);
}
fn morton_get_third_bits(m: u32) -> u32 {
var x = m & 0x9249249;
x = (x ^ (x >> 2)) & 0x30c30c3;
x = (x ^ (x >> 4)) & 0x0300f00f;
x = (x ^ (x >> 8)) & 0x30000ff;
x = (x ^ (x >> 16)) & 0x000003ff;
return x;
}
// DECODE 3D Morton code : Magic bits
// This method splits the morton codes bits by using certain patterns (magic bits)
fn morton_decode(m: u32) -> vec3<u32> {
return vec3u(
(base_index >> (subdivision_log2 * 0)),
(base_index >> (subdivision_log2 * 1)),
(base_index >> (subdivision_log2 * 2)),
) & vec3u(u32((1 << subdivision_log2) - 1));
morton_get_third_bits(m),
morton_get_third_bits(m >> 1),
morton_get_third_bits(m >> 2),
);
}
fn encode_internal_pos(internal_pos: vec3<u32>, subdivision_log2: u32) -> u32 {
return (((internal_pos.z << subdivision_log2) + internal_pos.y) << subdivision_log2) + internal_pos.x;
fn decode_internal_pos(base_index: u32) -> vec3<u32> {
return morton_decode(base_index);
}
fn encode_internal_pos(internal_pos: vec3<u32>) -> u32 {
return morton_encode(internal_pos);
}
fn internal_to_external_pos(internal_pos: vec3<f32>, metadata: TapeMetadata) -> vec3<f32> {
+8 -8
View File
@@ -13,21 +13,21 @@ use crate::{render::PackedAabb, ssa::*};
#[derive(Asset, Clone, Debug, Reflect, PartialEq)]
#[reflect(Clone)]
pub struct Tape {
pub raytracing: MeshRaytracingFlags,
pub parts: SSATape,
pub seed: u64,
pub raytracing: MeshRaytracingFlags,
pub parts: SSATape,
pub seed: u64,
pub subdivision: u32,
pub time: f32,
pub time: f32,
}
impl Default for Tape {
fn default() -> Self {
Self {
raytracing: MeshRaytracingFlags::OPAQUE,
parts: Default::default(),
seed: 0,
raytracing: MeshRaytracingFlags::OPAQUE,
parts: Default::default(),
seed: 0,
subdivision: 8,
time: 0.0,
time: 0.0,
}
}
}
+29 -27
View File
@@ -42,7 +42,7 @@ use rand::{RngExt, SeedableRng, rngs::SmallRng};
struct Args {
/// use the reference pathtracer instead of the realtime lighting system.
#[argh(switch)]
pathtracer: Option<bool>,
pathtracer: Option<bool>,
/// stress test a scene with many lights.
#[argh(switch)]
many_lights: Option<bool>,
@@ -102,14 +102,14 @@ fn create_csg(seed: u64) -> SSATape {
let pos = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAPosition,
size: 1,
size: 1,
},
vec![],
);
let offset = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAAdd,
size: 3,
size: 3,
},
vec![
pos[0],
@@ -123,14 +123,14 @@ fn create_csg(seed: u64) -> SSATape {
let sin = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSASin,
size: 1,
size: 1,
},
vec![pos[3]],
);
let offset = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAAdd,
size: 3,
size: 3,
},
vec![
offset[0],
@@ -144,7 +144,7 @@ fn create_csg(seed: u64) -> SSATape {
let sphere = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSASDFSphere,
size: 1,
size: 1,
},
vec![
offset[0],
@@ -156,7 +156,7 @@ fn create_csg(seed: u64) -> SSATape {
let torus = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSASDFTorus,
size: 1,
size: 1,
},
vec![
pos[0],
@@ -171,21 +171,21 @@ fn create_csg(seed: u64) -> SSATape {
let min = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAMin,
size: 1,
size: 1,
},
vec![sphere[0], torus[0]],
);
let scaled_time = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAMul,
size: 1,
size: 1,
},
vec![pos[3], SSAInput::Constant(0.2)],
);
let moving_pos = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAAdd,
size: 3,
size: 3,
},
vec![
pos[0],
@@ -199,7 +199,7 @@ fn create_csg(seed: u64) -> SSATape {
let pos_times_20 = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAMul,
size: 3,
size: 3,
},
vec![
moving_pos[0],
@@ -213,14 +213,14 @@ fn create_csg(seed: u64) -> SSATape {
let sine_of_the_times = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSASin,
size: 3,
size: 3,
},
pos_times_20,
);
let sine_of_the_times = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAMul,
size: 3,
size: 3,
},
vec![
sine_of_the_times[0],
@@ -234,28 +234,28 @@ fn create_csg(seed: u64) -> SSATape {
let multiply_out_1 = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAMul,
size: 1,
size: 1,
},
vec![sine_of_the_times[0], sine_of_the_times[1]],
);
let multiply_out_2 = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAMul,
size: 1,
size: 1,
},
vec![multiply_out_1[0], sine_of_the_times[2]],
);
let displacement = tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAAdd,
size: 1,
size: 1,
},
vec![min[0], multiply_out_2[0]],
);
tape.push_instruction(
SSAOpcodeSized {
opcode: SSAOpcode::SSAReturn,
size: 1,
size: 1,
},
displacement,
);
@@ -322,11 +322,11 @@ fn setup_pica_pica(
let csg = create_csg(0);
let tape = Tape {
raytracing: MeshRaytracingFlags::OPAQUE,
parts: csg,
seed: 0,
raytracing: MeshRaytracingFlags::OPAQUE,
parts: csg,
seed: 0,
subdivision: 8,
time: 0.0,
time: 0.0,
};
let loaded_tape = asset_server.add(tape);
@@ -356,7 +356,8 @@ fn setup_pica_pica(
Transform::from_translation(Vec3::new(0.219417, 2.5764852, 6.9718704)).with_rotation(
Quat::from_xyzw(-0.1466768, 0.013738206, 0.002037309, 0.989087),
),
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are
// required for Solari
CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING),
Msaa::Off,
));
@@ -426,7 +427,7 @@ fn setup_many_lights(
match plane_mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0).unwrap() {
VertexAttributeValues::Float32x2(items) => {
items.iter_mut().flatten().for_each(|x| *x *= 3.0);
}
},
_ => unreachable!(),
}
let plane_mesh = meshes.add(plane_mesh);
@@ -534,7 +535,8 @@ fn setup_many_lights(
Transform::from_translation(Vec3::new(6.11329, 166.74896, 451.8226)).with_rotation(
Quat::from_xyzw(-0.183938, 0.009093744, 0.0017017953, 0.9828943),
),
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are
// required for Solari
CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING),
Msaa::Off,
Bloom {
@@ -740,7 +742,7 @@ fn toggle_lights(
#[derive(Component)]
struct PatrolPath {
path: Vec<(Vec3, Quat)>,
i: usize,
i: usize,
}
fn patrol_path(mut query: Query<(&mut PatrolPath, &mut Transform)>, time: Res<Time<Virtual>>) {
@@ -805,10 +807,10 @@ fn update_control_text(
match robot_light_material.and_then(|m| materials.get(&m.0)) {
Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => {
text.0.push_str("\n(2): Disable robot emissive light");
}
},
_ => {
text.0.push_str("\n(2): Enable robot emissive light");
}
},
}
}