split into two crates
This commit is contained in:
Generated
+7224
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,72 @@
|
||||
[package]
|
||||
name = "bevy_tape_drive_solari"
|
||||
version = "0.20.0-dev"
|
||||
edition = "2024"
|
||||
description = "Renders tapes with a modified version of Bevy's Solari"
|
||||
license = "Apache-2.0"
|
||||
keywords = ["bevy"]
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_anti_alias = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_app = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_asset = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_camera = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_color = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_core_pipeline = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_derive = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_diagnostic = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_ecs = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_image = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_light = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_log = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_math = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_mesh = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_pbr = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [
|
||||
"dfg_lut",
|
||||
] }
|
||||
bevy_platform = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", default-features = false, features = [
|
||||
"std",
|
||||
] }
|
||||
bevy_reflect = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_render = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [
|
||||
"spirv_shader_passthrough",
|
||||
] }
|
||||
bevy_shader = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_shape = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_transform = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_utils = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
|
||||
# tape load
|
||||
bevy_tape_load = { path = "../bevy_tape_load", version = "0.20.0-dev" }
|
||||
|
||||
# other
|
||||
bytemuck = { version = "1" }
|
||||
derive_more = { version = "2", default-features = false, features = ["from"] }
|
||||
tracing = { version = "0.1", default-features = false, features = ["std"] }
|
||||
wgpu = { version = "30", default-features = false }
|
||||
|
||||
[features]
|
||||
dlss = ["bevy_anti_alias/dlss"]
|
||||
force_disable_dlss = ["bevy_anti_alias/force_disable_dlss"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustdoc-args = [
|
||||
"-Zunstable-options",
|
||||
"--generate-link-to-definition",
|
||||
"--generate-macro-expansion",
|
||||
]
|
||||
all-features = true
|
||||
|
||||
[package.metadata.wgsl-analyzer]
|
||||
edition = "2026_pre"
|
||||
root = "src"
|
||||
|
||||
[package.metadata.wgsl-analyzer.dependencies]
|
||||
bevy_render = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_pbr = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_core_pipeline = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
constants = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
@@ -0,0 +1,60 @@
|
||||
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
|
||||
|
||||
//! Provides raytraced lighting.
|
||||
//!
|
||||
//! See [`SolariPlugins`] for more info.
|
||||
//!
|
||||
//! 
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
pub mod pathtracer;
|
||||
pub mod realtime;
|
||||
pub mod scene;
|
||||
|
||||
/// The solari prelude.
|
||||
///
|
||||
/// 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, scene::RaytracingMesh3d};
|
||||
}
|
||||
|
||||
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:
|
||||
/// * [`SolariLightingPlugin`] - Raytraced direct and indirect lighting.
|
||||
/// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding.
|
||||
///
|
||||
/// There's also:
|
||||
/// * [`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.
|
||||
pub struct SolariPlugins;
|
||||
|
||||
impl PluginGroup for SolariPlugins {
|
||||
fn build(self) -> PluginGroupBuilder {
|
||||
PluginGroupBuilder::start::<Self>()
|
||||
.add(RaytracingScenePlugin)
|
||||
.add(SolariLightingPlugin)
|
||||
}
|
||||
}
|
||||
|
||||
impl SolariPlugins {
|
||||
/// [`WgpuFeatures`] required for these plugins to function.
|
||||
pub fn required_wgpu_features() -> WgpuFeatures {
|
||||
WgpuFeatures::EXPERIMENTAL_RAY_QUERY
|
||||
| WgpuFeatures::BUFFER_BINDING_ARRAY
|
||||
| WgpuFeatures::TEXTURE_BINDING_ARRAY
|
||||
| WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
|
||||
| WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use super::{prepare::PathtracerAccumulationTexture, Pathtracer};
|
||||
use bevy_camera::Camera;
|
||||
use bevy_ecs::{
|
||||
change_detection::DetectChanges,
|
||||
system::{Commands, Query},
|
||||
world::Ref,
|
||||
};
|
||||
use bevy_render::{sync_world::RenderEntity, Extract};
|
||||
use bevy_transform::components::GlobalTransform;
|
||||
|
||||
pub fn extract_pathtracer(
|
||||
cameras_3d: Extract<
|
||||
Query<(
|
||||
RenderEntity,
|
||||
&Camera,
|
||||
Ref<GlobalTransform>,
|
||||
Option<&Pathtracer>,
|
||||
)>,
|
||||
>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for (entity, camera, global_transform, pathtracer) in &cameras_3d {
|
||||
let mut entity_commands = commands
|
||||
.get_entity(entity)
|
||||
.expect("Camera entity wasn't synced.");
|
||||
if let Some(pathtracer) = pathtracer
|
||||
&& camera.is_active
|
||||
{
|
||||
let mut pathtracer = pathtracer.clone();
|
||||
pathtracer.reset |= global_transform.is_changed();
|
||||
entity_commands.insert(pathtracer);
|
||||
} else {
|
||||
entity_commands.remove::<(Pathtracer, PathtracerAccumulationTexture)>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
mod extract;
|
||||
mod node;
|
||||
mod prepare;
|
||||
|
||||
use crate::{scene::RaytracingSceneBindings, SolariPlugins};
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::embedded_asset;
|
||||
use bevy_camera::Hdr;
|
||||
use bevy_core_pipeline::{
|
||||
schedule::{Core3d, Core3dSystems},
|
||||
tonemapping::tonemapping,
|
||||
};
|
||||
use bevy_ecs::{component::Component, reflect::ReflectComponent, schedule::IntoScheduleConfigs};
|
||||
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
|
||||
use bevy_render::{
|
||||
init_gpu_resource, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup,
|
||||
RenderSystems,
|
||||
};
|
||||
use extract::extract_pathtracer;
|
||||
use node::{init_pathtracer_pipelines, pathtracer};
|
||||
use prepare::prepare_pathtracer_accumulation_texture;
|
||||
use tracing::warn;
|
||||
|
||||
/// Non-realtime pathtracing.
|
||||
///
|
||||
/// This plugin is meant to generate reference screenshots to compare against,
|
||||
/// and is not intended to be used by games.
|
||||
pub struct PathtracingPlugin;
|
||||
|
||||
impl Plugin for PathtracingPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
embedded_asset!(app, "pathtracer.wesl");
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let render_app = app.sub_app_mut(RenderApp);
|
||||
|
||||
let render_device = render_app.world().resource::<RenderDevice>();
|
||||
let features = render_device.features();
|
||||
if !features.contains(SolariPlugins::required_wgpu_features()) {
|
||||
warn!(
|
||||
"PathtracingPlugin not loaded. GPU lacks support for required features: {:?}.",
|
||||
SolariPlugins::required_wgpu_features().difference(features)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
render_app
|
||||
.add_systems(
|
||||
RenderStartup,
|
||||
init_pathtracer_pipelines.after(init_gpu_resource::<RaytracingSceneBindings>),
|
||||
)
|
||||
.add_systems(ExtractSchedule, extract_pathtracer)
|
||||
.add_systems(
|
||||
Render,
|
||||
prepare_pathtracer_accumulation_texture.in_set(RenderSystems::PrepareResources),
|
||||
)
|
||||
.add_systems(
|
||||
Core3d,
|
||||
pathtracer
|
||||
.after(Core3dSystems::MainPass)
|
||||
.before(tonemapping),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
#[reflect(Component, Default, Clone)]
|
||||
#[require(Hdr)]
|
||||
pub struct Pathtracer {
|
||||
pub reset: bool,
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
use super::{prepare::PathtracerAccumulationTexture, Pathtracer};
|
||||
use crate::scene::RaytracingSceneBindings;
|
||||
use bevy_asset::{load_embedded_asset, AssetServer};
|
||||
use bevy_ecs::{prelude::*, resource::Resource, system::Commands};
|
||||
use bevy_render::{
|
||||
camera::ExtractedCamera,
|
||||
render_resource::{
|
||||
binding_types::{texture_storage_2d, uniform_buffer},
|
||||
BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries,
|
||||
CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor,
|
||||
ImageSubresourceRange, PipelineCache, ShaderStages, StorageTextureAccess, TextureFormat,
|
||||
},
|
||||
renderer::{RenderContext, RenderDevice, ViewQuery},
|
||||
view::{ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms},
|
||||
};
|
||||
use bevy_utils::default;
|
||||
|
||||
/// Resource holding the pathtracer pipeline configuration.
|
||||
#[derive(Resource)]
|
||||
pub struct PathtracerPipelines {
|
||||
bind_group_layout: BindGroupLayoutDescriptor,
|
||||
pipeline: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
/// Initializes the pathtracer pipelines at render startup.
|
||||
pub fn init_pathtracer_pipelines(
|
||||
mut commands: Commands,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
scene_bindings: Res<RaytracingSceneBindings>,
|
||||
asset_server: Res<AssetServer>,
|
||||
) {
|
||||
let bind_group_layout = BindGroupLayoutDescriptor::new(
|
||||
"pathtracer_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
texture_storage_2d(TextureFormat::Rgba32Float, StorageTextureAccess::ReadWrite),
|
||||
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
|
||||
uniform_buffer::<ViewUniform>(true),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some("pathtracer_pipeline".into()),
|
||||
layout: vec![
|
||||
scene_bindings.bind_group_layout.clone(),
|
||||
bind_group_layout.clone(),
|
||||
],
|
||||
shader: load_embedded_asset!(asset_server.as_ref(), "pathtracer.wesl"),
|
||||
..default()
|
||||
});
|
||||
|
||||
commands.insert_resource(PathtracerPipelines {
|
||||
bind_group_layout,
|
||||
pipeline,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn pathtracer(
|
||||
view: ViewQuery<(
|
||||
&Pathtracer,
|
||||
&PathtracerAccumulationTexture,
|
||||
&ExtractedCamera,
|
||||
&ViewTarget,
|
||||
&ViewUniformOffset,
|
||||
)>,
|
||||
pathtracer_pipelines: Option<Res<PathtracerPipelines>>,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
scene_bindings: Res<RaytracingSceneBindings>,
|
||||
view_uniforms: Res<ViewUniforms>,
|
||||
render_device: Res<RenderDevice>,
|
||||
mut ctx: RenderContext,
|
||||
) {
|
||||
let (pathtracer_settings, accumulation_texture, camera, view_target, view_uniform_offset) =
|
||||
view.into_inner();
|
||||
|
||||
let Some(pathtracer_pipelines) = pathtracer_pipelines else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (Some(pipeline), Some(scene_bind_group), Some(viewport), Some(view_uniforms_binding)) = (
|
||||
pipeline_cache.get_compute_pipeline(pathtracer_pipelines.pipeline),
|
||||
&scene_bindings.bind_group,
|
||||
camera.physical_viewport_size,
|
||||
view_uniforms.uniforms.binding(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let bind_group = render_device.create_bind_group(
|
||||
"pathtracer_bind_group",
|
||||
&pipeline_cache.get_bind_group_layout(&pathtracer_pipelines.bind_group_layout),
|
||||
&BindGroupEntries::sequential((
|
||||
&accumulation_texture.0.default_view,
|
||||
view_target.get_unsampled_color_attachment().view,
|
||||
view_uniforms_binding,
|
||||
)),
|
||||
);
|
||||
|
||||
let command_encoder = ctx.command_encoder();
|
||||
|
||||
if pathtracer_settings.reset {
|
||||
command_encoder.clear_texture(
|
||||
&accumulation_texture.0.texture,
|
||||
&ImageSubresourceRange::default(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
|
||||
label: Some("pathtracer"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, scene_bind_group, &[]);
|
||||
pass.set_bind_group(1, &bind_group, &[view_uniform_offset.offset]);
|
||||
pass.dispatch_workgroups(viewport.x.div_ceil(8), viewport.y.div_ceil(8), 1);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
|
||||
import bevy_pbr::render::utils::{rand_f, rand_vec2f};
|
||||
import bevy_render::view::View;
|
||||
import package::scene::brdf::{evaluate_brdf, evaluate_and_sample_brdf, brdf_pdf, F_AB};
|
||||
import package::scene::sampling::{sample_random_light, random_emissive_light_pdf, power_heuristic, sample_environment_map_light};
|
||||
import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN, RAY_T_MAX, MIRROR_ROUGHNESS_THRESHOLD};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@group(1) @binding(0) var accumulation_texture: texture_storage_2d<rgba32float, read_write>;
|
||||
@group(1) @binding(1) var view_output: texture_storage_2d<rgba16float, write>;
|
||||
@group(1) @binding(2) var<uniform> view: View;
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn pathtrace(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
if any(global_id.xy >= vec2u(view.viewport.zw)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let old_color = textureLoad(accumulation_texture, global_id.xy);
|
||||
|
||||
// Setup RNG
|
||||
let pixel_index = global_id.x + global_id.y * u32(view.viewport.z);
|
||||
let frame_index = u32(old_color.a) * 5782582u;
|
||||
var rng = pixel_index + frame_index;
|
||||
|
||||
// Shoot the first ray from the camera
|
||||
let pixel_center = vec2<f32>(global_id.xy) + 0.5;
|
||||
let jitter = rand_vec2f(&rng) - 0.5;
|
||||
let pixel_uv = (pixel_center + jitter) / view.viewport.zw;
|
||||
let pixel_ndc = (pixel_uv * 2.0) - 1.0;
|
||||
let primary_ray_target = view.world_from_clip * vec4(pixel_ndc.x, -pixel_ndc.y, 1.0, 1.0);
|
||||
var ray_origin = view.world_position;
|
||||
var ray_direction = normalize((primary_ray_target.xyz / primary_ray_target.w) - ray_origin);
|
||||
var ray_t_min = 0.0;
|
||||
|
||||
// Path trace
|
||||
var radiance = vec3(0.0);
|
||||
var throughput = vec3(1.0);
|
||||
var p_bounce = 0.0;
|
||||
loop {
|
||||
let ray = trace_ray(ray_origin, ray_direction, ray_t_min, RAY_T_MAX, RAY_FLAG_NONE);
|
||||
if ray.kind != RAY_QUERY_INTERSECTION_NONE {
|
||||
let ray_hit = resolve_ray_hit_full(ray);
|
||||
let wo = -ray_direction;
|
||||
let NdotV = max(dot(ray_hit.world_normal, wo), 0.0001);
|
||||
let F_ab = F_AB(ray_hit.material.perceptual_roughness, NdotV);
|
||||
|
||||
// Emissive contribution
|
||||
var mis_weight = 1.0;
|
||||
if p_bounce != 0.0 { // Not first bounce
|
||||
let p_light = random_emissive_light_pdf(ray_hit, ray.t, NdotV);
|
||||
mis_weight = power_heuristic(p_bounce, p_light);
|
||||
}
|
||||
if dot(ray_hit.world_normal, wo) > 0.0 {
|
||||
radiance += mis_weight * throughput * ray_hit.material.emissive;
|
||||
}
|
||||
|
||||
// Sample direct lighting, but only if the surface is not mirror-like
|
||||
let is_perfectly_specular = ray_hit.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD && ray_hit.material.metallic > 0.9999;
|
||||
if !is_perfectly_specular {
|
||||
let direct_lighting = sample_random_light(ray_hit.world_position, ray_hit.world_normal, &rng);
|
||||
|
||||
mis_weight = 1.0;
|
||||
if direct_lighting.brdf_rays_can_hit {
|
||||
let pdf_of_bounce = brdf_pdf(wo, direct_lighting.wi, ray_hit.world_normal, ray_hit.material, F_ab);
|
||||
mis_weight = power_heuristic(1.0 / direct_lighting.inverse_solid_angle_pdf, pdf_of_bounce);
|
||||
}
|
||||
|
||||
let direct_lighting_brdf = evaluate_brdf(wo, direct_lighting.wi, ray_hit.world_normal, ray_hit.material, F_ab);
|
||||
radiance += mis_weight * throughput * direct_lighting.radiance * direct_lighting.inverse_pdf * direct_lighting_brdf;
|
||||
}
|
||||
|
||||
// Sample new ray direction from the material BRDF for next bounce and apply BRDF
|
||||
let next_bounce = evaluate_and_sample_brdf(wo, ray_hit.world_normal, ray_hit.material, F_ab, &rng);
|
||||
if next_bounce.pdf == 0.0 { break; }
|
||||
ray_direction = next_bounce.wi;
|
||||
ray_origin = ray_hit.world_position + (ray_hit.geometric_world_normal * RAY_T_MIN);
|
||||
ray_t_min = RAY_T_MIN;
|
||||
p_bounce = next_bounce.pdf;
|
||||
throughput *= next_bounce.throughput;
|
||||
|
||||
// Russian roulette for early termination
|
||||
let rr = saturate(luminance(throughput));
|
||||
if rand_f(&rng) >= rr { break; }
|
||||
throughput /= rr;
|
||||
} else {
|
||||
radiance += throughput * sample_environment_map_light(ray_direction);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Camera exposure
|
||||
radiance *= view.exposure;
|
||||
|
||||
// Accumulation over time via running average
|
||||
let new_color = mix(old_color.rgb, radiance, 1.0 / (old_color.a + 1.0));
|
||||
textureStore(accumulation_texture, global_id.xy, vec4(new_color, old_color.a + 1.0));
|
||||
textureStore(view_output, global_id.xy, vec4(new_color, 1.0));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use super::Pathtracer;
|
||||
use bevy_ecs::{
|
||||
component::Component,
|
||||
entity::Entity,
|
||||
query::With,
|
||||
system::{Commands, Query, Res, ResMut},
|
||||
};
|
||||
use bevy_image::ToExtents;
|
||||
use bevy_render::{
|
||||
camera::ExtractedCamera,
|
||||
render_resource::{TextureDescriptor, TextureDimension, TextureFormat, TextureUsages},
|
||||
renderer::RenderDevice,
|
||||
texture::{CachedTexture, TextureCache},
|
||||
};
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct PathtracerAccumulationTexture(pub CachedTexture);
|
||||
|
||||
pub fn prepare_pathtracer_accumulation_texture(
|
||||
query: Query<(Entity, &ExtractedCamera), With<Pathtracer>>,
|
||||
mut texture_cache: ResMut<TextureCache>,
|
||||
render_device: Res<RenderDevice>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for (entity, camera) in &query {
|
||||
let Some(viewport) = camera.physical_viewport_size else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let descriptor = TextureDescriptor {
|
||||
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: &[],
|
||||
};
|
||||
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(PathtracerAccumulationTexture(
|
||||
texture_cache.get(&render_device, descriptor),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import bevy_render::view::View;
|
||||
import bevy_pbr::prepass::bindings::PreviousViewUniforms;
|
||||
import package::scene::sampling::{LightSample, NULL_LIGHT_ID};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@group(1) @binding(0) var view_output: texture_storage_2d<rgba16float, read_write>;
|
||||
@group(1) @binding(1) var<storage, read_write> light_tile_samples: array<LightSample>;
|
||||
@group(1) @binding(2) var<storage, read_write> light_tile_resolved_samples: array<ResolvedLightSamplePacked>;
|
||||
@group(1) @binding(3) var gbuffer: texture_2d<u32>;
|
||||
@group(1) @binding(4) var depth_buffer: texture_depth_2d;
|
||||
@if(MOTION_VECTORS_READ_WRITE)
|
||||
@group(1) @binding(5) var motion_vectors: texture_storage_2d<rg16float, read_write>;
|
||||
@if(!MOTION_VECTORS_READ_WRITE)
|
||||
@group(1) @binding(5) var motion_vectors: texture_2d<f32>;
|
||||
@group(1) @binding(6) var<uniform> view: View;
|
||||
@group(1) @binding(7) var<uniform> previous_view: PreviousViewUniforms;
|
||||
@group(1) @binding(8) var<storage, read_write> world_cache: WorldCache;
|
||||
@group(1) @binding(9) var<uniform> constants: SolariLightingSettings;
|
||||
|
||||
@if(RESTIR) {
|
||||
@group(1) @binding(10) var previous_gbuffer: texture_2d<u32>;
|
||||
@group(1) @binding(11) var previous_depth_buffer: texture_depth_2d;
|
||||
@group(1) @binding(12) var<storage, read_write> reservoirs_a: array<Reservoir>;
|
||||
@group(1) @binding(13) var<storage, read_write> reservoirs_b: array<Reservoir>;
|
||||
}
|
||||
|
||||
@if(DLSS_RR_GUIDE_BUFFERS) {
|
||||
@group(2) @binding(0) var diffuse_albedo: texture_storage_2d<rgba8unorm, write>;
|
||||
@group(2) @binding(1) var specular_albedo: texture_storage_2d<rgba8unorm, write>;
|
||||
@group(2) @binding(2) var normal_roughness: texture_storage_2d<rgba16float, write>;
|
||||
@group(2) @binding(3) var dlss_rr_depth: texture_storage_2d<r32float, write>;
|
||||
@group(2) @binding(4) var specular_motion_vectors: texture_storage_2d<rg16float, write>;
|
||||
}
|
||||
|
||||
fn load_motion_vector(pixel_id: vec2<u32>) -> vec2<f32> {
|
||||
@if(MOTION_VECTORS_READ_WRITE)
|
||||
return textureLoad(motion_vectors, pixel_id).xy;
|
||||
@if(!MOTION_VECTORS_READ_WRITE)
|
||||
return textureLoad(motion_vectors, pixel_id, 0).xy;
|
||||
}
|
||||
|
||||
/// User-configurable settings from the `SolariLighting` component, plus per-frame
|
||||
/// state. Field order and types must match `SolariLightingUniforms` in `prepare.rs`.
|
||||
struct SolariLightingSettings {
|
||||
confidence_weight_cap: f32,
|
||||
primary_di_samples: u32,
|
||||
secondary_di_samples: u32,
|
||||
max_bounces: u32,
|
||||
world_cache_max_temporal_samples: f32,
|
||||
world_cache_direct_light_sample_count: u32,
|
||||
world_cache_max_gi_ray_distance: f32,
|
||||
world_cache_cell_updates_soft_target: u32,
|
||||
world_cache_position_base_cell_size: f32,
|
||||
world_cache_position_lod_scale: f32,
|
||||
frame_rng: u32,
|
||||
reset: u32,
|
||||
}
|
||||
|
||||
/// Don't adjust the size of this struct without also adjusting `prepare::RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE`.
|
||||
struct ResolvedLightSamplePacked {
|
||||
world_position_x: f32,
|
||||
world_position_y: f32,
|
||||
world_position_z: f32,
|
||||
world_normal: u32,
|
||||
radiance: u32,
|
||||
inverse_pdf: f32,
|
||||
}
|
||||
|
||||
/// Don't adjust the size of this struct without also adjusting `prepare::RESERVOIR_STRUCT_SIZE`.
|
||||
struct Reservoir {
|
||||
sample_point_world_position: vec3<f32>,
|
||||
unbiased_contribution_weight: f32,
|
||||
radiance: vec3<f32>,
|
||||
confidence_weight: f32,
|
||||
sample_point_world_normal: vec2<f32>,
|
||||
light_sample: LightSample,
|
||||
}
|
||||
|
||||
fn empty_reservoir() -> Reservoir {
|
||||
return Reservoir(
|
||||
vec3(0.0),
|
||||
0.0,
|
||||
vec3(0.0),
|
||||
0.0,
|
||||
vec2(0.0),
|
||||
LightSample(NULL_LIGHT_ID, 0u),
|
||||
);
|
||||
}
|
||||
|
||||
struct WorldCacheGeometryData {
|
||||
world_position: vec3<f32>,
|
||||
padding_a: u32,
|
||||
world_normal: vec3<f32>,
|
||||
padding_b: u32,
|
||||
}
|
||||
|
||||
/// Keep in sync with the packed world-cache layout constants in `prepare.rs`.
|
||||
struct WorldCache {
|
||||
checksums: array<atomic<u32>, constants::WORLD_CACHE_SIZE>,
|
||||
@if(WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER)
|
||||
life: array<u32, constants::WORLD_CACHE_SIZE>,
|
||||
@if(!WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER)
|
||||
life: array<atomic<u32>, constants::WORLD_CACHE_SIZE>,
|
||||
radiance: array<vec4<f32>, constants::WORLD_CACHE_SIZE>,
|
||||
geometry_data: array<WorldCacheGeometryData, constants::WORLD_CACHE_SIZE>,
|
||||
luminance_deltas: array<f32, constants::WORLD_CACHE_SIZE>,
|
||||
active_cells_new_radiance: array<vec3<f32>, constants::WORLD_CACHE_SIZE>,
|
||||
a: array<u32, constants::WORLD_CACHE_SIZE>,
|
||||
b: array<u32, 1024u>,
|
||||
active_cell_indices: array<u32, constants::WORLD_CACHE_SIZE>,
|
||||
active_cells_count: u32,
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use super::{prepare::SolariLightingResources, SolariLighting};
|
||||
use bevy_camera::Camera;
|
||||
use bevy_ecs::system::{Commands, ResMut};
|
||||
use bevy_pbr::deferred::SkipDeferredLighting;
|
||||
use bevy_render::{sync_world::RenderEntity, MainWorld};
|
||||
|
||||
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>)>();
|
||||
|
||||
for (entity, camera, solari_lighting) in cameras_3d.iter_mut(&mut main_world) {
|
||||
let mut entity_commands = commands
|
||||
.get_entity(entity)
|
||||
.expect("Camera entity wasn't synced.");
|
||||
if let Some(mut solari_lighting) = solari_lighting
|
||||
&& camera.is_active
|
||||
{
|
||||
entity_commands.insert((solari_lighting.clone(), SkipDeferredLighting));
|
||||
solari_lighting.reset = false;
|
||||
} else {
|
||||
entity_commands.remove::<(
|
||||
SolariLighting,
|
||||
SolariLightingResources,
|
||||
SkipDeferredLighting,
|
||||
)>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import bevy_pbr::deferred::types::unpack_24bit_normal;
|
||||
import bevy_pbr::render::rgb9e5::rgb9e5_to_vec3_;
|
||||
import bevy_render::utils::octahedral_decode;
|
||||
import bevy_render::view::{View, depth_ndc_to_view_z};
|
||||
import package::scene::bindings::ResolvedMaterial;
|
||||
|
||||
struct ResolvedGPixel {
|
||||
world_position: vec3<f32>,
|
||||
world_normal: vec3<f32>,
|
||||
material: ResolvedMaterial,
|
||||
}
|
||||
|
||||
fn gpixel_resolve(gpixel: vec4<u32>, depth: f32, pixel_id: vec2<u32>, view_size: vec2<f32>, world_from_clip: mat4x4<f32>) -> ResolvedGPixel {
|
||||
let world_position = reconstruct_world_position(pixel_id, depth, view_size, world_from_clip);
|
||||
let world_normal = octahedral_decode(unpack_24bit_normal(gpixel.a));
|
||||
|
||||
let base_rough = unpack4x8unorm(gpixel.r);
|
||||
let base_color = pow(base_rough.rgb, vec3(2.2));
|
||||
let perceptual_roughness = base_rough.a;
|
||||
let roughness = perceptual_roughness * perceptual_roughness;
|
||||
let props = unpack4x8unorm(gpixel.b);
|
||||
let reflectance = props.r;
|
||||
let metallic = props.g;
|
||||
let emissive = rgb9e5_to_vec3_(gpixel.g);
|
||||
let material = ResolvedMaterial(base_color, emissive, reflectance, perceptual_roughness, roughness, metallic);
|
||||
|
||||
return ResolvedGPixel(world_position, world_normal, material);
|
||||
}
|
||||
|
||||
fn reconstruct_world_position(pixel_id: vec2<u32>, depth: f32, view_size: vec2<f32>, world_from_clip: mat4x4<f32>) -> vec3<f32> {
|
||||
let uv = (vec2<f32>(pixel_id) + 0.5) / view_size;
|
||||
let xy_ndc = (uv - vec2(0.5)) * vec2(2.0, -2.0);
|
||||
let world_pos = world_from_clip * vec4(xy_ndc, depth, 1.0);
|
||||
return world_pos.xyz / world_pos.w;
|
||||
}
|
||||
|
||||
/// Reject if tangent plane differs more than 0.3% or angle between normals more than 90 degrees
|
||||
fn pixel_dissimilar(depth: f32, world_position: vec3<f32>, other_world_position: vec3<f32>, normal: vec3<f32>, other_normal: vec3<f32>, view: View) -> bool {
|
||||
// https://developer.download.nvidia.com/video/gputechconf/gtc/2020/presentations/s22699-fast-denoising-with-self-stabilizing-recurrent-blurs.pdf#page=45
|
||||
let tangent_plane_distance = abs(dot(normal, other_world_position - world_position));
|
||||
let view_z = -depth_ndc_to_view_z(depth, view.clip_from_view, view.view_from_clip);
|
||||
|
||||
return tangent_plane_distance / view_z > 0.003 || dot(normal, other_normal) < 0.0;
|
||||
}
|
||||
|
||||
fn permute_pixel(pixel_id: vec2<u32>, frame_index: u32, view_size: vec2<f32>) -> vec2<u32> {
|
||||
let r = frame_index;
|
||||
let offset = vec2<i32>(i32(r & 3u), i32((r >> 2u) & 3u));
|
||||
var shifted_pixel_id = vec2<i32>(pixel_id) + offset;
|
||||
shifted_pixel_id ^= vec2<i32>(3);
|
||||
shifted_pixel_id -= offset;
|
||||
if any(shifted_pixel_id < vec2<i32>(0)) || any(shifted_pixel_id >= vec2<i32>(view_size)) {
|
||||
return pixel_id;
|
||||
}
|
||||
return vec2<u32>(shifted_pixel_id);
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
|
||||
import bevy_pbr::render::utils::{rand_f, rand_range_u};
|
||||
import bevy_render::maths::PI;
|
||||
import bevy_render::utils::octahedral_encode;
|
||||
import package::scene::brdf::{brdf_pdf, evaluate_and_sample_brdf, evaluate_brdf, EvaluateAndSampleBrdfResult, F_AB};
|
||||
import package::realtime::presample_light_tiles::unpack_resolved_light_sample;
|
||||
import package::realtime::bindings::{empty_reservoir, light_tile_resolved_samples, light_tile_samples, Reservoir, constants, view};
|
||||
import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light};
|
||||
import package::scene::bindings::{light_sources, RAY_T_MAX, RAY_T_MIN, resolve_ray_hit_full, ResolvedMaterial, ResolvedRayHitFull, trace_ray};
|
||||
import package::realtime::world_cache_query::{get_cell_size, query_world_cache, WORLD_CACHE_CELL_LIFETIME};
|
||||
|
||||
@if(DLSS_RR_GUIDE_BUFFERS)
|
||||
import package::realtime::resolve_dlss_rr_textures::{is_delta_mirror, primary_surface_glossy, psr_bounce_reflectance, psr_chain_mirror, psr_environment_miss, psr_init, replace_primary_surface};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
const RECONNECTION_FOOTPRINT_KAPPA = 0.02;
|
||||
const RECONNECTION_ROUGHNESS_MIN = 0.6;
|
||||
const RECONNECTION_RELAX_DISTANCE = 1.0;
|
||||
|
||||
const CACHE_TERMINATION_MIN_SOLID_ANGLE = PI;
|
||||
|
||||
/// What tracing one path produced.
|
||||
///
|
||||
/// `radiance` is shaded straight into the pixel. With ReSTIR the reservoir additionally carries the
|
||||
/// candidate chosen for reuse, and `radiance` holds the radiance that can not be reused.
|
||||
/// Without ReSTIR there is no reservoir and `radiance` is the entire estimate.
|
||||
struct InitialSamplingResult {
|
||||
@if(RESTIR) reservoir: Reservoir,
|
||||
radiance: vec3<f32>,
|
||||
}
|
||||
|
||||
/// Path vertices use the following convention: x0 = camera, x1 = primary ray hit (the G-buffer
|
||||
/// surface), x2 = first BRDF-sampled hit (the reconnection vertex).
|
||||
struct PathState {
|
||||
ray_origin: vec3<f32>,
|
||||
normal: vec3<f32>,
|
||||
wo: vec3<f32>,
|
||||
material: ResolvedMaterial,
|
||||
/// Throughput past x1. With ReSTIR the brdf*cos at x1 is factored out of it, see x1_brdf.
|
||||
throughput_past_first_hit: vec3<f32>,
|
||||
/// Reconnection vertex x2, the first BRDF-sampled hit shared by every length >= 2 candidate
|
||||
@if(RESTIR) x2_position: vec3<f32>,
|
||||
@if(RESTIR) x2_normal: vec3<f32>,
|
||||
/// If false, candidates built on x2 are shaded directly into radiance instead of
|
||||
/// published to the reservoir
|
||||
@if(RESTIR) x2_reusable: bool,
|
||||
/// brdf*cos at x1 for the direction toward x2, applied at shade time
|
||||
@if(RESTIR) x1_brdf: vec3<f32>,
|
||||
/// Radiance shaded directly at this pixel
|
||||
radiance: vec3<f32>,
|
||||
@if(RESTIR) reservoir: Reservoir,
|
||||
@if(RESTIR) weight_sum: f32,
|
||||
@if(RESTIR) selected_target_function: f32,
|
||||
}
|
||||
|
||||
fn new_path_state(world_position: vec3<f32>, world_normal: vec3<f32>, wo: vec3<f32>, material: ResolvedMaterial) -> PathState {
|
||||
var path: PathState;
|
||||
path.ray_origin = world_position + (world_normal * RAY_T_MIN);
|
||||
path.normal = world_normal;
|
||||
path.wo = wo;
|
||||
path.material = material;
|
||||
path.throughput_past_first_hit = vec3(1.0);
|
||||
path.radiance = vec3(0.0);
|
||||
@if(RESTIR) {
|
||||
path.x1_brdf = vec3(0.0);
|
||||
path.x2_position = vec3(0.0);
|
||||
path.x2_normal = vec3(0.0);
|
||||
path.x2_reusable = false;
|
||||
path.reservoir = empty_reservoir();
|
||||
path.reservoir.confidence_weight = 1.0;
|
||||
path.weight_sum = 0.0;
|
||||
path.selected_target_function = 0.0;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, workgroup_id: vec2<u32>, pixel_id: vec2<u32>, rng: ptr<function, u32>) -> InitialSamplingResult {
|
||||
let wo = normalize(view.world_position - world_position);
|
||||
let primary_NdotV = max(dot(world_normal, wo), 0.0001);
|
||||
let primary_F_ab = F_AB(material.perceptual_roughness, primary_NdotV);
|
||||
|
||||
var path = new_path_state(world_position, world_normal, wo, material);
|
||||
|
||||
@if(DLSS_RR_GUIDE_BUFFERS)
|
||||
var psr = psr_init(world_normal, material);
|
||||
|
||||
for (var bounce = 0u; bounce < constants.max_bounces; bounce++) {
|
||||
let NdotV = max(dot(path.normal, path.wo), 0.0001);
|
||||
let F_ab = F_AB(path.material.perceptual_roughness, NdotV);
|
||||
|
||||
// Stochastic NEE, with probability proportional to how diffuse the vertex is. Mirror-like
|
||||
// metals have too narrow a lobe for NEE to help, so mostly skip it there and let
|
||||
// BRDF-sampled emissive do the work. Pure dielectrics always run NEE.
|
||||
let p_nee = mix(1.0, path.material.perceptual_roughness, path.material.metallic);
|
||||
let di_samples = select(constants.secondary_di_samples, constants.primary_di_samples, bounce == 0u);
|
||||
generate_nee_candidate(&path, F_ab, p_nee, di_samples, workgroup_id, bounce, rng);
|
||||
|
||||
// Sample the BRDF and trace the next ray
|
||||
let next_bounce = evaluate_and_sample_brdf(path.wo, path.normal, path.material, F_ab, rng);
|
||||
if next_bounce.pdf == 0.0 { break; }
|
||||
let ray = trace_ray(path.ray_origin, next_bounce.wi, RAY_T_MIN, RAY_T_MAX, RAY_FLAG_NONE);
|
||||
|
||||
if ray.kind == RAY_QUERY_INTERSECTION_NONE {
|
||||
@if(DLSS_RR_GUIDE_BUFFERS)
|
||||
if !psr.finished && !next_bounce.diffuse_selected {
|
||||
psr_environment_miss(pixel_id, wo);
|
||||
}
|
||||
|
||||
let environment_map_light_radiance = sample_environment_map_light(next_bounce.wi);
|
||||
@if(RESTIR) {
|
||||
generate_environment_map_light_candidate(&path, next_bounce, environment_map_light_radiance, primary_F_ab, bounce, rng);
|
||||
} @else {
|
||||
path.radiance += path.throughput_past_first_hit * next_bounce.throughput * environment_map_light_radiance;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
let ray_hit = resolve_ray_hit_full(ray);
|
||||
let p_brdf = next_bounce.pdf;
|
||||
|
||||
@if(DLSS_RR_GUIDE_BUFFERS)
|
||||
if !psr.finished {
|
||||
if next_bounce.diffuse_selected {
|
||||
// Took the non-specular lobe, so not a mirror reflection. Keep the guide-buffer defaults.
|
||||
psr.finished = true;
|
||||
} else {
|
||||
psr.throughput *= psr_bounce_reflectance(path.wo, next_bounce.wi, path.normal, path.material, F_ab, isinf(p_brdf));
|
||||
psr.reflection_length += ray.t;
|
||||
|
||||
if !primary_surface_glossy(material) && is_delta_mirror(ray_hit.material) {
|
||||
// Still in the mirror chain, fold this mirror's reflection into the chain.
|
||||
psr = psr_chain_mirror(psr, ray_hit.world_normal);
|
||||
} else {
|
||||
psr.finished = true;
|
||||
replace_primary_surface(pixel_id, psr, ray_hit, material, world_position, world_normal, wo, primary_F_ab);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Capture x2, the first BRDF-sampled hit
|
||||
if bounce == 0u {
|
||||
@if(RESTIR) {
|
||||
path.x2_position = ray_hit.world_position;
|
||||
path.x2_normal = ray_hit.world_normal;
|
||||
|
||||
path.x1_brdf = evaluate_brdf(wo, next_bounce.wi, world_normal, material, primary_F_ab);
|
||||
|
||||
path.x2_reusable = reconnection_reusable(ray.t, p_brdf, next_bounce.wi, next_bounce.diffuse_selected, ray_hit, world_position, material.perceptual_roughness, primary_NdotV);
|
||||
|
||||
// The primary brdf*cos is applied at shade time, so divide it out of next_bounce.throughput
|
||||
// to leave 1/pdf (or 1/specular_weight for mirrors, avoiding the 1/INF = 0 that would kill
|
||||
// mirror GI).
|
||||
path.throughput_past_first_hit *= next_bounce.throughput / max(path.x1_brdf, vec3(0.0001));
|
||||
} @else {
|
||||
// Nothing is reused, so there is no shade-time reconnection to factor the primary
|
||||
// brdf*cos out for.
|
||||
path.throughput_past_first_hit *= next_bounce.throughput;
|
||||
}
|
||||
} else {
|
||||
// Later bounces keep the full brdf*cos/pdf for L_at_reconnection.
|
||||
path.throughput_past_first_hit *= next_bounce.throughput;
|
||||
}
|
||||
|
||||
// Resample emissive hits
|
||||
if any(ray_hit.material.emissive > vec3(0.0)) && dot(ray_hit.world_normal, -next_bounce.wi) > 0.0 {
|
||||
generate_emissive_candidate(&path, ray_hit, next_bounce.wi, p_brdf, ray.t, p_nee, di_samples, bounce, rng);
|
||||
}
|
||||
|
||||
// Try terminating into the world cache
|
||||
if terminate_into_cache(&path, ray_hit, ray.t, p_brdf, bounce, rng) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Advance to the next vertex
|
||||
path.ray_origin = ray_hit.world_position + (ray_hit.geometric_world_normal * RAY_T_MIN);
|
||||
path.normal = ray_hit.world_normal;
|
||||
path.wo = -next_bounce.wi;
|
||||
path.material = ray_hit.material;
|
||||
|
||||
// Russian roulette for early termination
|
||||
if bounce > 0u {
|
||||
// With ReSTIR, throughput_past_first_hit has the primary brdf*cos divided out (so it can be
|
||||
// re-applied at shade time), which inflates it. Multiply x1_brdf back in to get the true
|
||||
// energy-bounded path throughput, which is the correct quantity for the RR survival
|
||||
// probability. Without ReSTIR it already is that quantity.
|
||||
var full_throughput = path.throughput_past_first_hit;
|
||||
@if(RESTIR)
|
||||
full_throughput *= max(path.x1_brdf, vec3(0.0001));
|
||||
let rr = saturate(luminance(full_throughput));
|
||||
if rand_f(rng) >= rr { break; }
|
||||
path.throughput_past_first_hit /= rr;
|
||||
}
|
||||
}
|
||||
|
||||
var result: InitialSamplingResult;
|
||||
result.radiance = path.radiance;
|
||||
@if(RESTIR) {
|
||||
if path.selected_target_function > 0.0 {
|
||||
path.reservoir.unbiased_contribution_weight = path.weight_sum / path.selected_target_function;
|
||||
}
|
||||
result.reservoir = path.reservoir;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
fn generate_nee_candidate(
|
||||
path: ptr<function, PathState>,
|
||||
F_ab: vec2<f32>,
|
||||
p_nee: f32,
|
||||
di_samples: u32,
|
||||
workgroup_id: vec2<u32>,
|
||||
bounce: u32,
|
||||
rng: ptr<function, u32>,
|
||||
) {
|
||||
if rand_f(rng) >= p_nee { return; }
|
||||
|
||||
let di = sample_light_ris((*path).ray_origin, (*path).normal, (*path).wo, (*path).material, F_ab, di_samples, workgroup_id, bounce, rng);
|
||||
let di_target_function = luminance(di.brdf_radiance);
|
||||
if di_target_function <= 0.0 { return; }
|
||||
|
||||
// MIS against the BRDF strategy. RIS over N candidates makes the effective NEE pdf at the
|
||||
// winner roughly N * light_pdf(winner), so scale by p_nee for the stochastic gate.
|
||||
var nee_mis_weight = 1.0;
|
||||
if di.brdf_rays_can_hit && di.inverse_solid_angle_pdf > 0.0 {
|
||||
let p_nee_strategy = f32(di_samples) * (1.0 / di.inverse_solid_angle_pdf) * p_nee;
|
||||
let p_brdf_at_nee = brdf_pdf((*path).wo, di.wi, (*path).normal, (*path).material, F_ab);
|
||||
nee_mis_weight = power_heuristic(p_nee_strategy, p_brdf_at_nee);
|
||||
}
|
||||
|
||||
if bounce == 0u {
|
||||
@if(RESTIR) {
|
||||
// Bounce 0: Candidate is the light sample, stored by reference and re-resolved each frame
|
||||
// nee_mis_weight goes into the target function since it gets recomputed per-pixel during reuse
|
||||
let target_function = di_target_function * nee_mis_weight;
|
||||
let resampling_weight = target_function * di.unbiased_contribution_weight / p_nee;
|
||||
|
||||
(*path).weight_sum += resampling_weight;
|
||||
if rand_f(rng) * (*path).weight_sum < resampling_weight {
|
||||
(*path).reservoir.light_sample = di.light_sample;
|
||||
(*path).selected_target_function = target_function;
|
||||
}
|
||||
} @else {
|
||||
(*path).radiance += di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_nee;
|
||||
}
|
||||
} else {
|
||||
// Deeper bounces: Candidate is the reconnection radiance at x2
|
||||
let L_at_reconnection = (*path).throughput_past_first_hit * di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_nee;
|
||||
|
||||
@if(RESTIR) {
|
||||
resample_reconnection_candidate(path, L_at_reconnection, rng);
|
||||
} @else {
|
||||
(*path).radiance += L_at_reconnection;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DiSample {
|
||||
unbiased_contribution_weight: f32,
|
||||
light_sample: LightSample,
|
||||
wi: vec3<f32>,
|
||||
brdf_radiance: vec3<f32>,
|
||||
inverse_solid_angle_pdf: f32,
|
||||
brdf_rays_can_hit: bool,
|
||||
}
|
||||
|
||||
fn sample_light_ris(ray_origin: vec3<f32>, normal: vec3<f32>, wo: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>, di_samples: u32, workgroup_id: vec2<u32>, bounce: u32, rng: ptr<function, u32>) -> DiSample {
|
||||
var workgroup_rng = (workgroup_id.x * 5782582u) + workgroup_id.y + bounce;
|
||||
let light_tile_start = rand_range_u(128u, &workgroup_rng) * 1024u;
|
||||
|
||||
var weight_sum = 0.0;
|
||||
var selected_target_function = 0.0;
|
||||
var selected_tile_sample = 0u;
|
||||
var selected_world_position = vec4(0.0);
|
||||
var selected_wi = vec3(0.0);
|
||||
var selected_brdf_radiance = vec3(0.0);
|
||||
var selected_inverse_solid_angle_pdf = 0.0;
|
||||
var selected_brdf_rays_can_hit = false;
|
||||
let mis_weight = 1.0 / f32(di_samples);
|
||||
for (var i = 0u; i < di_samples; i++) {
|
||||
let tile_sample = light_tile_start + rand_range_u(1024u, rng);
|
||||
let resolved_light_sample = unpack_resolved_light_sample(light_tile_resolved_samples[tile_sample], view.exposure);
|
||||
let light_contribution = calculate_resolved_light_contribution(resolved_light_sample, ray_origin, normal);
|
||||
let brdf_current = evaluate_brdf(wo, light_contribution.wi, normal, material, F_ab);
|
||||
let brdf_radiance = brdf_current * light_contribution.radiance;
|
||||
|
||||
let target_function = luminance(brdf_radiance);
|
||||
let resampling_weight = mis_weight * (target_function * light_contribution.inverse_pdf);
|
||||
|
||||
weight_sum += resampling_weight;
|
||||
|
||||
if rand_f(rng) * weight_sum < resampling_weight {
|
||||
selected_target_function = target_function;
|
||||
selected_tile_sample = tile_sample;
|
||||
selected_world_position = resolved_light_sample.world_position;
|
||||
selected_wi = light_contribution.wi;
|
||||
selected_inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf;
|
||||
selected_brdf_rays_can_hit = light_contribution.brdf_rays_can_hit;
|
||||
selected_brdf_radiance = brdf_radiance;
|
||||
}
|
||||
}
|
||||
|
||||
var unbiased_contribution_weight = 0.0;
|
||||
if selected_target_function > 0.0 {
|
||||
unbiased_contribution_weight = weight_sum / selected_target_function;
|
||||
unbiased_contribution_weight *= trace_visibility(ray_origin, selected_world_position);
|
||||
}
|
||||
|
||||
return DiSample(unbiased_contribution_weight, light_tile_samples[selected_tile_sample], selected_wi, selected_brdf_radiance, selected_inverse_solid_angle_pdf, selected_brdf_rays_can_hit);
|
||||
}
|
||||
|
||||
fn generate_emissive_candidate(
|
||||
path: ptr<function, PathState>,
|
||||
ray_hit: ResolvedRayHitFull,
|
||||
wi: vec3<f32>,
|
||||
p_brdf: f32,
|
||||
ray_t: f32,
|
||||
p_nee: f32,
|
||||
di_samples: u32,
|
||||
bounce: u32,
|
||||
rng: ptr<function, u32>,
|
||||
) {
|
||||
let NdotV_hit = max(dot(ray_hit.world_normal, -wi), 0.0001);
|
||||
let light_count = arrayLength(&light_sources);
|
||||
let area_pdf = 1.0 / (f32(light_count) * f32(ray_hit.triangle_count) * ray_hit.triangle_area);
|
||||
let p_light = area_pdf * ray_t * ray_t / NdotV_hit;
|
||||
let emissive_mis_weight = power_heuristic(p_brdf, p_light * p_nee * f32(di_samples));
|
||||
|
||||
@if(RESTIR) {
|
||||
if !(*path).x2_reusable {
|
||||
// x1 -> x2 not reuse-safe (mirror/sharp lobe or failed gate): shade directly at this pixel
|
||||
// instead of publishing, since a reuse shift would waste it or make a firefly. Mirror lobes
|
||||
// always land here (p_brdf = INF, footprint 0), where emissive_mis_weight is 1.
|
||||
(*path).radiance += (*path).x1_brdf * (*path).throughput_past_first_hit * ray_hit.material.emissive * emissive_mis_weight;
|
||||
} else if bounce == 0u {
|
||||
// Bounce 0: Candidate is the emissive hit
|
||||
let target_function = luminance((*path).x1_brdf * ray_hit.material.emissive) * emissive_mis_weight;
|
||||
let resampling_weight = luminance((*path).x1_brdf * (*path).throughput_past_first_hit * ray_hit.material.emissive) * emissive_mis_weight;
|
||||
|
||||
(*path).weight_sum += resampling_weight;
|
||||
if rand_f(rng) * (*path).weight_sum < resampling_weight {
|
||||
(*path).reservoir.light_sample = LightSample(NULL_LIGHT_ID, bitcast<u32>(area_pdf));
|
||||
(*path).reservoir.sample_point_world_position = (*path).x2_position;
|
||||
(*path).reservoir.sample_point_world_normal = octahedral_encode((*path).x2_normal);
|
||||
(*path).reservoir.radiance = ray_hit.material.emissive;
|
||||
(*path).selected_target_function = target_function;
|
||||
}
|
||||
} else {
|
||||
// Deeper bounces: Candidate is the reconnection radiance at x2
|
||||
let emissive_L_at_reconnection = (*path).throughput_past_first_hit * ray_hit.material.emissive * emissive_mis_weight;
|
||||
resample_reconnection_candidate(path, emissive_L_at_reconnection, rng);
|
||||
}
|
||||
} @else {
|
||||
(*path).radiance += (*path).throughput_past_first_hit * ray_hit.material.emissive * emissive_mis_weight;
|
||||
}
|
||||
}
|
||||
|
||||
@if(RESTIR)
|
||||
fn generate_environment_map_light_candidate(
|
||||
path: ptr<function, PathState>,
|
||||
next_bounce: EvaluateAndSampleBrdfResult,
|
||||
environment_map_light_radiance: vec3<f32>,
|
||||
primary_F_ab: vec2<f32>,
|
||||
bounce: u32,
|
||||
rng: ptr<function, u32>,
|
||||
) {
|
||||
if all(environment_map_light_radiance == vec3(0.0)) { return; }
|
||||
|
||||
if bounce == 0u {
|
||||
// Bounce 0: Candidate is the sky direction
|
||||
if !x1_lobe_reusable(next_bounce.pdf, next_bounce.diffuse_selected, (*path).material.perceptual_roughness) {
|
||||
(*path).radiance += next_bounce.throughput * environment_map_light_radiance;
|
||||
return;
|
||||
}
|
||||
|
||||
// Publish the candidate as a point RAY_T_MAX along wi.
|
||||
// Neighbors see almost the same direction, and the reconnection jacobian evaluates to ~1.
|
||||
//
|
||||
// TODO: Once the environment map light is a proper LightSource that we sample during NEE,
|
||||
// store this as a LightSample instead.
|
||||
let x1_brdf = evaluate_brdf((*path).wo, next_bounce.wi, (*path).normal, (*path).material, primary_F_ab);
|
||||
let target_function = luminance(x1_brdf * environment_map_light_radiance);
|
||||
let resampling_weight = luminance(next_bounce.throughput * environment_map_light_radiance);
|
||||
|
||||
(*path).weight_sum += resampling_weight;
|
||||
if rand_f(rng) * (*path).weight_sum < resampling_weight {
|
||||
(*path).reservoir.light_sample = LightSample(NULL_LIGHT_ID, 0u);
|
||||
(*path).reservoir.sample_point_world_position = (*path).ray_origin + next_bounce.wi * RAY_T_MAX;
|
||||
(*path).reservoir.sample_point_world_normal = octahedral_encode(-next_bounce.wi);
|
||||
(*path).reservoir.radiance = environment_map_light_radiance;
|
||||
(*path).selected_target_function = target_function;
|
||||
}
|
||||
} else {
|
||||
// Deeper bounces: Candidate is the reconnection radiance at x2
|
||||
let L_at_reconnection = (*path).throughput_past_first_hit * next_bounce.throughput * environment_map_light_radiance;
|
||||
resample_reconnection_candidate(path, L_at_reconnection, rng);
|
||||
}
|
||||
}
|
||||
|
||||
fn terminate_into_cache(
|
||||
path: ptr<function, PathState>,
|
||||
ray_hit: ResolvedRayHitFull,
|
||||
ray_t: f32,
|
||||
p_brdf: f32,
|
||||
bounce: u32,
|
||||
rng: ptr<function, u32>,
|
||||
) -> bool {
|
||||
// Only terminate into the world cache when the bounce was from a wide-enough BRDF sample
|
||||
// because the cache is less noisy than continuing the path for rough surfaces,
|
||||
// but less accurate for smooth surfaces
|
||||
let lobe_solid_angle = 1.0 / p_brdf;
|
||||
let broad_enough_to_terminate = lobe_solid_angle >= CACHE_TERMINATION_MIN_SOLID_ANGLE;
|
||||
let forced_terminate = bounce == constants.max_bounces - 1u;
|
||||
if !(broad_enough_to_terminate || forced_terminate) { return false; }
|
||||
|
||||
// Only use the cache when the ray cleared the cache cell (diagonal = sqrt(3) * cell_size). Short
|
||||
// rays land in a cell that may straddle occluders and leak light through corners.
|
||||
var rng_copy = *rng;
|
||||
let world_cache_cell_size = get_cell_size(ray_hit.world_position, view.world_position, ray_t, &rng_copy);
|
||||
if ray_t <= sqrt(3.0) * world_cache_cell_size { return false; }
|
||||
|
||||
let cached_radiance = query_world_cache(ray_hit.world_position, ray_hit.geometric_world_normal, view.world_position, ray_t, WORLD_CACHE_CELL_LIFETIME, rng);
|
||||
|
||||
let cache_outgoing = (ray_hit.material.base_color / PI) * cached_radiance;
|
||||
let cache_L_at_reconnection = (*path).throughput_past_first_hit * cache_outgoing;
|
||||
|
||||
@if(RESTIR) {
|
||||
resample_reconnection_candidate(path, cache_L_at_reconnection, rng);
|
||||
} @else {
|
||||
(*path).radiance += cache_L_at_reconnection;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Resample radiance arriving at x1 through the reconnection vertex x2. `L_at_reconnection` excludes the
|
||||
/// brdf*cos at x1, which is re-applied at shade time from whichever pixel ends up reusing the candidate.
|
||||
@if(RESTIR)
|
||||
fn resample_reconnection_candidate(path: ptr<function, PathState>, L_at_reconnection: vec3<f32>, rng: ptr<function, u32>) {
|
||||
if !(*path).x2_reusable {
|
||||
// x1 -> x2 not reuse-safe: shade directly at this pixel instead of publishing.
|
||||
(*path).radiance += (*path).x1_brdf * L_at_reconnection;
|
||||
return;
|
||||
}
|
||||
|
||||
let target_function = luminance((*path).x1_brdf * L_at_reconnection);
|
||||
let resampling_weight = target_function;
|
||||
|
||||
(*path).weight_sum += resampling_weight;
|
||||
if rand_f(rng) * (*path).weight_sum < resampling_weight {
|
||||
(*path).reservoir.light_sample = LightSample(NULL_LIGHT_ID, 0u);
|
||||
(*path).reservoir.sample_point_world_position = (*path).x2_position;
|
||||
(*path).reservoir.sample_point_world_normal = octahedral_encode((*path).x2_normal);
|
||||
(*path).reservoir.radiance = L_at_reconnection;
|
||||
(*path).selected_target_function = target_function;
|
||||
}
|
||||
}
|
||||
|
||||
/// ReSTIR PT Enhanced: Algorithmic Advances for Faster and More Robust ReSTIR Path Tracing
|
||||
/// Section 4 (sorta)
|
||||
/// https://research.nvidia.com/labs/rtr/publication/lin2026restirptenhanced/lin2026restirptenhanced.pdf
|
||||
@if(RESTIR)
|
||||
fn reconnection_reusable(ray_t: f32, p_brdf: f32, wi: vec3<f32>, diffuse_selected: bool, ray_hit: ResolvedRayHitFull, world_position: vec3<f32>, x1_perceptual_roughness: f32, primary_NdotV: f32) -> bool {
|
||||
// ray_footprint = t^2 / (p_brdf * cos_x2) is the area a sample represents at x2. It goes to 0 for
|
||||
// mirror lobes (p_brdf = INF) and shrinks for sharp lobes or short segments. Compared against a
|
||||
// uniform 1/(4*PI) primary footprint, so the test trades roughness against distance.
|
||||
let cos_x2 = max(dot(ray_hit.world_normal, -wi), 0.0001);
|
||||
let ray_footprint = (ray_t * ray_t) / (p_brdf * cos_x2);
|
||||
let primary_dist = length(view.world_position - world_position);
|
||||
let primary_footprint = 4.0 * PI * primary_dist * primary_dist / primary_NdotV;
|
||||
let footprint_ok = ray_footprint >= (RECONNECTION_FOOTPRINT_KAPPA / 100.0) * primary_footprint;
|
||||
|
||||
let x1_lobe_ok = x1_lobe_reusable(p_brdf, diffuse_selected, x1_perceptual_roughness);
|
||||
|
||||
// Guard at x2. A sharp reflector there makes the stored radiance view-dependent and wrong to
|
||||
// reuse from a neighbor's direction. The roughness floor relaxes with segment length: a distant
|
||||
// glossy x2 is seen by neighbors from nearly the same direction, so the view-dependence washes out.
|
||||
// Diffuse, rough, and emissive vertices are always reuse-safe.
|
||||
let x2_is_light = any(ray_hit.material.emissive > vec3(0.0));
|
||||
let x2_roughness = mix(1.0, ray_hit.material.perceptual_roughness, ray_hit.material.metallic);
|
||||
let x2_roughness_floor = RECONNECTION_ROUGHNESS_MIN * saturate(RECONNECTION_RELAX_DISTANCE / ray_t);
|
||||
let x2_end_ok = x2_is_light || x2_roughness >= x2_roughness_floor;
|
||||
|
||||
return footprint_ok && x1_lobe_ok && x2_end_ok;
|
||||
}
|
||||
|
||||
/// Whether the lobe sampled at x1 is wide enough for its candidates to be reused by neighbors.
|
||||
@if(RESTIR)
|
||||
fn x1_lobe_reusable(p_brdf: f32, diffuse_selected: bool, x1_perceptual_roughness: f32) -> bool {
|
||||
return !isinf(p_brdf) && (diffuse_selected || x1_perceptual_roughness >= RECONNECTION_ROUGHNESS_MIN);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
mod extract;
|
||||
mod node;
|
||||
mod prepare;
|
||||
|
||||
use crate::{
|
||||
scene::{prepare_raytracing_scene_resources, RaytracingSceneBindings},
|
||||
SolariPlugins,
|
||||
};
|
||||
use bevy_app::{App, Plugin, PostUpdate};
|
||||
use bevy_asset::embedded_asset;
|
||||
use bevy_camera::Hdr;
|
||||
use bevy_core_pipeline::{
|
||||
core_3d::main_opaque_pass_3d,
|
||||
prepass::{
|
||||
DeferredPrepass, DeferredPrepassDoubleBuffer, DepthPrepass, DepthPrepassDoubleBuffer,
|
||||
MotionVectorPrepass,
|
||||
},
|
||||
schedule::{Core3d, Core3dSystems},
|
||||
};
|
||||
use bevy_ecs::{
|
||||
component::Component,
|
||||
entity::Entity,
|
||||
query::Has,
|
||||
reflect::ReflectComponent,
|
||||
schedule::IntoScheduleConfigs,
|
||||
system::{Commands, Query},
|
||||
};
|
||||
use bevy_pbr::DefaultOpaqueRendererMethod;
|
||||
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
|
||||
use bevy_render::{
|
||||
init_gpu_resource, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup,
|
||||
RenderSystems,
|
||||
};
|
||||
use bevy_shader::load_shader_library;
|
||||
use extract::extract_solari_lighting;
|
||||
use node::{init_solari_lighting_pipelines, solari_lighting};
|
||||
use prepare::{
|
||||
prepare_solari_lighting_resources, setup_raytracing_scene_needs_previous_frame_data,
|
||||
};
|
||||
use tracing::warn;
|
||||
|
||||
/// 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.
|
||||
pub struct SolariLightingPlugin;
|
||||
|
||||
impl Plugin for SolariLightingPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
load_shader_library!(app, "gbuffer_utils.wesl");
|
||||
load_shader_library!(app, "bindings.wesl");
|
||||
load_shader_library!(app, "presample_light_tiles.wesl");
|
||||
load_shader_library!(app, "initial_path.wesl");
|
||||
embedded_asset!(app, "restir.wesl");
|
||||
embedded_asset!(app, "no_restir.wesl");
|
||||
load_shader_library!(app, "world_cache_query.wesl");
|
||||
embedded_asset!(app, "world_cache_compact.wesl");
|
||||
embedded_asset!(app, "world_cache_update.wesl");
|
||||
|
||||
load_shader_library!(app, "resolve_dlss_rr_textures.wesl");
|
||||
|
||||
app.insert_resource(DefaultOpaqueRendererMethod::deferred());
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let features = app
|
||||
.sub_app(RenderApp)
|
||||
.world()
|
||||
.resource::<RenderDevice>()
|
||||
.features();
|
||||
if !features.contains(SolariPlugins::required_wgpu_features()) {
|
||||
warn!(
|
||||
"SolariLightingPlugin not loaded. GPU lacks support for required features: {:?}.",
|
||||
SolariPlugins::required_wgpu_features().difference(features)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
app.add_systems(PostUpdate, manage_prepass_double_buffers);
|
||||
|
||||
app.sub_app_mut(RenderApp)
|
||||
.add_systems(
|
||||
RenderStartup,
|
||||
init_solari_lighting_pipelines.after(init_gpu_resource::<RaytracingSceneBindings>),
|
||||
)
|
||||
.add_systems(ExtractSchedule, extract_solari_lighting)
|
||||
.add_systems(
|
||||
Render,
|
||||
(
|
||||
prepare_solari_lighting_resources,
|
||||
setup_raytracing_scene_needs_previous_frame_data
|
||||
.before(prepare_raytracing_scene_resources),
|
||||
)
|
||||
.in_set(RenderSystems::PrepareResources),
|
||||
)
|
||||
.add_systems(
|
||||
Core3d,
|
||||
solari_lighting
|
||||
.before(main_opaque_pass_3d)
|
||||
.in_set(Core3dSystems::MainPass),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
#[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.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// Whether to enable this setting or not will be very scene dependent.
|
||||
///
|
||||
/// Defaults to `false`.
|
||||
pub restir: bool,
|
||||
|
||||
/// Maximum confidence weight (effective temporal history length) a pixel
|
||||
/// can accumulate during temporal resampling.
|
||||
///
|
||||
/// Has no effect when [`SolariLighting::restir`] is `false`.
|
||||
///
|
||||
/// Higher values are more stable but slower to react to lighting changes
|
||||
/// and will lead to increased artifacts.
|
||||
pub confidence_weight_cap: f32,
|
||||
|
||||
/// 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.
|
||||
pub primary_di_samples: u32,
|
||||
|
||||
/// Number of direct light samples taken at each indirect bounce during
|
||||
/// initial sampling.
|
||||
///
|
||||
/// Higher values reduce noise in indirect lighting at the cost of more work
|
||||
/// per frame. Lower values are faster but noisier.
|
||||
pub secondary_di_samples: u32,
|
||||
|
||||
/// 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.
|
||||
pub max_bounces: u32,
|
||||
|
||||
/// How responsive the world cache is to changes in lighting.
|
||||
///
|
||||
/// Higher values accumulate more temporal history, giving more stable but
|
||||
/// less responsive (slower to update) lighting. Lower values react faster
|
||||
/// but are noisier and less stable.
|
||||
pub world_cache_max_temporal_samples: f32,
|
||||
|
||||
/// How many direct light samples each world cache cell takes when updating
|
||||
/// each frame.
|
||||
///
|
||||
/// Higher values reduce noise in cached lighting at the cost of more work
|
||||
/// per frame. Lower values are faster but noisier.
|
||||
pub world_cache_direct_light_sample_count: u32,
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// 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
|
||||
/// probability `target / active_cells`, so on average this many cells
|
||||
/// update, though individual frames may update more or fewer. When there
|
||||
/// are fewer active cells than the target, all of them update every frame.
|
||||
pub world_cache_cell_updates_soft_target: u32,
|
||||
|
||||
/// Size of a world cache cell at the lowest LOD, in meters.
|
||||
///
|
||||
/// Smaller values give finer spatial resolution and more detailed indirect
|
||||
/// lighting at the cost of more cells to fill and update. Larger values are
|
||||
/// cheaper but coarser, which can cause light leaking.
|
||||
pub world_cache_position_base_cell_size: f32,
|
||||
|
||||
/// 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.
|
||||
pub world_cache_position_lod_scale: f32,
|
||||
|
||||
/// Set to true to delete the saved temporal history (past frames).
|
||||
///
|
||||
/// Useful for preventing ghosting when the history is no longer
|
||||
/// representative of the current frame, such as in sudden camera cuts.
|
||||
///
|
||||
/// After setting this to true, it will automatically be toggled
|
||||
/// back to false at the end of the frame.
|
||||
pub reset: bool,
|
||||
}
|
||||
|
||||
impl Default for SolariLighting {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
restir: false,
|
||||
confidence_weight_cap: 8.0,
|
||||
primary_di_samples: 8,
|
||||
secondary_di_samples: 4,
|
||||
max_bounces: 3,
|
||||
world_cache_max_temporal_samples: 32.0,
|
||||
world_cache_direct_light_sample_count: 32,
|
||||
world_cache_max_gi_ray_distance: 50.0,
|
||||
world_cache_cell_updates_soft_target: 40000,
|
||||
world_cache_position_base_cell_size: 0.15,
|
||||
world_cache_position_lod_scale: 15.0,
|
||||
reset: true, // No temporal history on the first frame
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or removes the prepass double-buffer components according to [`SolariLighting::restir`].
|
||||
fn manage_prepass_double_buffers(
|
||||
views: Query<(
|
||||
Entity,
|
||||
&SolariLighting,
|
||||
Has<DeferredPrepassDoubleBuffer>,
|
||||
Has<DepthPrepassDoubleBuffer>,
|
||||
)>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for (entity, solari_lighting, deferred_double_buffered, depth_double_buffered) in &views {
|
||||
let mut entity = commands.entity(entity);
|
||||
if solari_lighting.restir {
|
||||
if !deferred_double_buffered {
|
||||
entity.insert(DeferredPrepassDoubleBuffer);
|
||||
}
|
||||
if !depth_double_buffered {
|
||||
entity.insert(DepthPrepassDoubleBuffer);
|
||||
}
|
||||
} else {
|
||||
if deferred_double_buffered {
|
||||
entity.remove::<DeferredPrepassDoubleBuffer>();
|
||||
}
|
||||
if depth_double_buffered {
|
||||
entity.remove::<DepthPrepassDoubleBuffer>();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import package::realtime::gbuffer_utils::gpixel_resolve;
|
||||
import package::realtime::initial_path::generate_initial_path;
|
||||
import package::realtime::bindings::{constants, depth_buffer, gbuffer, view, view_output};
|
||||
import package::scene::bindings::RAY_T_MAX;
|
||||
import package::realtime::world_cache_query::{query_world_cache, WORLD_CACHE_CELL_LIFETIME};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn initial_and_shade(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
|
||||
|
||||
let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
|
||||
var rng = pixel_index + constants.frame_rng;
|
||||
|
||||
let depth = textureLoad(depth_buffer, global_id.xy, 0);
|
||||
if depth == 0.0 { return; }
|
||||
|
||||
let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
|
||||
|
||||
let path = generate_initial_path(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
|
||||
|
||||
var pixel_color = path.radiance;
|
||||
pixel_color += surface.material.emissive;
|
||||
pixel_color *= view.exposure;
|
||||
textureStore(view_output, global_id.xy, vec4(pixel_color, 1.0));
|
||||
|
||||
@if(VISUALIZE_WORLD_CACHE)
|
||||
textureStore(view_output, global_id.xy, vec4(query_world_cache(surface.world_position, surface.world_normal, view.world_position, RAY_T_MAX, WORLD_CACHE_CELL_LIFETIME, &rng) * view.exposure, 1.0));
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
use super::prepare::{
|
||||
SolariLightingResources, LIGHT_TILE_BLOCKS, 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::{load_embedded_asset, AssetServer, Handle};
|
||||
use bevy_core_pipeline::prepass::{
|
||||
PreviousViewData, PreviousViewUniformOffset, PreviousViewUniforms, ViewPrepassTextures,
|
||||
MOTION_VECTOR_PREPASS_FORMAT,
|
||||
};
|
||||
use bevy_ecs::{prelude::*, resource::Resource, system::Commands};
|
||||
use bevy_render::{
|
||||
diagnostic::RecordDiagnostics as _,
|
||||
render_resource::{
|
||||
binding_types::{
|
||||
storage_buffer_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer,
|
||||
uniform_buffer_sized,
|
||||
},
|
||||
BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries,
|
||||
CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor, LoadOp,
|
||||
PipelineCache, RenderPassDescriptor, ShaderStages, StorageTextureAccess, TextureFormat,
|
||||
TextureFormatFeatureFlags, TextureSampleType,
|
||||
},
|
||||
renderer::{RenderAdapter, RenderContext, RenderDevice, ViewQuery},
|
||||
view::{ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms},
|
||||
};
|
||||
use bevy_shader::{Shader, ShaderDefVal};
|
||||
use bevy_utils::default;
|
||||
|
||||
/// Resource holding the Solari lighting pipeline configuration.
|
||||
#[derive(Resource)]
|
||||
pub struct SolariLightingPipelines {
|
||||
bind_group_layout: BindGroupLayoutDescriptor,
|
||||
bind_group_layout_restir: BindGroupLayoutDescriptor,
|
||||
bind_group_layout_world_cache_active_cells_dispatch: BindGroupLayoutDescriptor,
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
bind_group_layout_resolve_dlss_rr_textures: BindGroupLayoutDescriptor,
|
||||
decay_world_cache_pipeline: CachedComputePipelineId,
|
||||
compact_world_cache_single_block_pipeline: CachedComputePipelineId,
|
||||
compact_world_cache_blocks_pipeline: CachedComputePipelineId,
|
||||
compact_world_cache_write_active_cells_pipeline: CachedComputePipelineId,
|
||||
sample_di_for_world_cache_pipeline: CachedComputePipelineId,
|
||||
sample_gi_for_world_cache_pipeline: CachedComputePipelineId,
|
||||
blend_new_world_cache_samples_pipeline: CachedComputePipelineId,
|
||||
presample_light_tiles_pipeline: CachedComputePipelineId,
|
||||
restir: RestirPipelines,
|
||||
no_restir: NoRestirPipelines,
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
resolve_dlss_rr_textures_pipeline: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
struct RestirPipelines {
|
||||
initial_and_temporal: CachedComputePipelineId,
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
initial_and_temporal_with_psr: CachedComputePipelineId,
|
||||
spatial_and_shade: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
struct NoRestirPipelines {
|
||||
initial_and_shade: CachedComputePipelineId,
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
initial_and_shade_with_psr: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
|
||||
type SolariLightingViewQuery = (
|
||||
&'static SolariLightingResources,
|
||||
&'static ViewTarget,
|
||||
&'static ViewPrepassTextures,
|
||||
&'static ViewUniformOffset,
|
||||
&'static PreviousViewUniformOffset,
|
||||
);
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
type SolariLightingViewQuery = (
|
||||
&'static SolariLightingResources,
|
||||
&'static ViewTarget,
|
||||
&'static ViewPrepassTextures,
|
||||
&'static ViewUniformOffset,
|
||||
&'static PreviousViewUniformOffset,
|
||||
Option<&'static ViewDlssRayReconstructionTextures>,
|
||||
);
|
||||
|
||||
pub fn solari_lighting(
|
||||
view: ViewQuery<SolariLightingViewQuery>,
|
||||
solari_pipelines: Option<Res<SolariLightingPipelines>>,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
scene_bindings: Res<RaytracingSceneBindings>,
|
||||
view_uniforms: Res<ViewUniforms>,
|
||||
previous_view_uniforms: Res<PreviousViewUniforms>,
|
||||
render_device: Res<RenderDevice>,
|
||||
mut ctx: RenderContext,
|
||||
) {
|
||||
#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
|
||||
let (
|
||||
solari_lighting_resources,
|
||||
view_target,
|
||||
view_prepass_textures,
|
||||
view_uniform_offset,
|
||||
previous_view_uniform_offset,
|
||||
) = view.into_inner();
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
let (
|
||||
solari_lighting_resources,
|
||||
view_target,
|
||||
view_prepass_textures,
|
||||
view_uniform_offset,
|
||||
previous_view_uniform_offset,
|
||||
view_dlss_rr_textures,
|
||||
) = view.into_inner();
|
||||
|
||||
let Some(pipelines) = solari_pipelines else {
|
||||
return;
|
||||
};
|
||||
|
||||
let restir = solari_lighting_resources.reservoirs.as_ref().zip(
|
||||
view_prepass_textures
|
||||
.previous_deferred_view()
|
||||
.zip(view_prepass_textures.previous_depth_only_view()),
|
||||
);
|
||||
|
||||
#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
|
||||
let (initial_pipeline_id, spatial_pipeline_id) = if restir.is_some() {
|
||||
(
|
||||
pipelines.restir.initial_and_temporal,
|
||||
Some(pipelines.restir.spatial_and_shade),
|
||||
)
|
||||
} else {
|
||||
(pipelines.no_restir.initial_and_shade, None)
|
||||
};
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
let (initial_pipeline_id, spatial_pipeline_id) =
|
||||
match (restir.is_some(), view_dlss_rr_textures.is_some()) {
|
||||
(true, true) => (
|
||||
pipelines.restir.initial_and_temporal_with_psr,
|
||||
Some(pipelines.restir.spatial_and_shade),
|
||||
),
|
||||
(true, false) => (
|
||||
pipelines.restir.initial_and_temporal,
|
||||
Some(pipelines.restir.spatial_and_shade),
|
||||
),
|
||||
(false, true) => (pipelines.no_restir.initial_and_shade_with_psr, None),
|
||||
(false, false) => (pipelines.no_restir.initial_and_shade, None),
|
||||
};
|
||||
|
||||
let (
|
||||
Some(decay_world_cache_pipeline),
|
||||
Some(compact_world_cache_single_block_pipeline),
|
||||
Some(compact_world_cache_blocks_pipeline),
|
||||
Some(compact_world_cache_write_active_cells_pipeline),
|
||||
Some(sample_di_for_world_cache_pipeline),
|
||||
Some(sample_gi_for_world_cache_pipeline),
|
||||
Some(blend_new_world_cache_samples_pipeline),
|
||||
Some(presample_light_tiles_pipeline),
|
||||
Some(initial_pipeline),
|
||||
Some(scene_bind_group),
|
||||
Some(gbuffer),
|
||||
Some(depth_buffer),
|
||||
Some(motion_vectors),
|
||||
Some(view_uniforms_binding),
|
||||
Some(previous_view_uniforms_binding),
|
||||
) = (
|
||||
pipeline_cache.get_compute_pipeline(pipelines.decay_world_cache_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(pipelines.compact_world_cache_single_block_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(pipelines.compact_world_cache_blocks_pipeline),
|
||||
pipeline_cache
|
||||
.get_compute_pipeline(pipelines.compact_world_cache_write_active_cells_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(pipelines.sample_di_for_world_cache_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(pipelines.sample_gi_for_world_cache_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(pipelines.blend_new_world_cache_samples_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(pipelines.presample_light_tiles_pipeline),
|
||||
pipeline_cache.get_compute_pipeline(initial_pipeline_id),
|
||||
&scene_bindings.bind_group,
|
||||
view_prepass_textures.deferred_view(),
|
||||
view_prepass_textures.depth_only_view(),
|
||||
view_prepass_textures.motion_vectors_view(),
|
||||
view_uniforms.uniforms.binding(),
|
||||
previous_view_uniforms.uniforms.binding(),
|
||||
)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let spatial_and_shade_pipeline = match spatial_pipeline_id {
|
||||
Some(id) => match pipeline_cache.get_compute_pipeline(id) {
|
||||
None => return,
|
||||
pipeline => pipeline,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
let Some(resolve_dlss_rr_textures_pipeline) =
|
||||
pipeline_cache.get_compute_pipeline(pipelines.resolve_dlss_rr_textures_pipeline)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
let view_target_attachment = view_target.get_unsampled_color_attachment();
|
||||
|
||||
let s = solari_lighting_resources;
|
||||
let bind_group = render_device.create_bind_group(
|
||||
"solari_lighting_bind_group",
|
||||
&pipeline_cache.get_bind_group_layout(&pipelines.bind_group_layout),
|
||||
&BindGroupEntries::sequential((
|
||||
view_target_attachment.view,
|
||||
s.light_tile_samples.as_entire_binding(),
|
||||
s.light_tile_resolved_samples.as_entire_binding(),
|
||||
gbuffer,
|
||||
depth_buffer,
|
||||
motion_vectors,
|
||||
view_uniforms_binding.clone(),
|
||||
previous_view_uniforms_binding.clone(),
|
||||
s.world_cache.as_entire_binding(),
|
||||
s.constants.as_entire_binding(),
|
||||
)),
|
||||
);
|
||||
|
||||
let bind_group_restir =
|
||||
restir.map(|(reservoirs, (previous_gbuffer, previous_depth_buffer))| {
|
||||
render_device.create_bind_group(
|
||||
"solari_lighting_bind_group_restir",
|
||||
&pipeline_cache.get_bind_group_layout(&pipelines.bind_group_layout_restir),
|
||||
&BindGroupEntries::sequential((
|
||||
view_target_attachment.view,
|
||||
s.light_tile_samples.as_entire_binding(),
|
||||
s.light_tile_resolved_samples.as_entire_binding(),
|
||||
gbuffer,
|
||||
depth_buffer,
|
||||
motion_vectors,
|
||||
view_uniforms_binding,
|
||||
previous_view_uniforms_binding,
|
||||
s.world_cache.as_entire_binding(),
|
||||
s.constants.as_entire_binding(),
|
||||
previous_gbuffer,
|
||||
previous_depth_buffer,
|
||||
reservoirs.a.as_entire_binding(),
|
||||
reservoirs.b.as_entire_binding(),
|
||||
)),
|
||||
)
|
||||
});
|
||||
|
||||
let bind_group_world_cache_active_cells_dispatch = render_device.create_bind_group(
|
||||
"solari_lighting_bind_group_world_cache_active_cells_dispatch",
|
||||
&pipeline_cache
|
||||
.get_bind_group_layout(&pipelines.bind_group_layout_world_cache_active_cells_dispatch),
|
||||
&BindGroupEntries::single(s.world_cache_active_cells_dispatch.as_entire_binding()),
|
||||
);
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
let bind_group_resolve_dlss_rr_textures = view_dlss_rr_textures.map(|d| {
|
||||
render_device.create_bind_group(
|
||||
"solari_lighting_bind_group_resolve_dlss_rr_textures",
|
||||
&pipeline_cache
|
||||
.get_bind_group_layout(&pipelines.bind_group_layout_resolve_dlss_rr_textures),
|
||||
&BindGroupEntries::sequential((
|
||||
&d.diffuse_albedo.default_view,
|
||||
&d.specular_albedo.default_view,
|
||||
&d.normal_roughness.default_view,
|
||||
&d.depth.default_view,
|
||||
&d.specular_motion_vectors.default_view,
|
||||
)),
|
||||
)
|
||||
});
|
||||
|
||||
let diagnostics = ctx.diagnostic_recorder();
|
||||
let diagnostics = diagnostics.as_deref();
|
||||
|
||||
let command_encoder = ctx.command_encoder();
|
||||
|
||||
// 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)],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
}
|
||||
|
||||
let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
|
||||
label: Some("solari_lighting"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
let dx = solari_lighting_resources.view_size.x.div_ceil(8);
|
||||
let dy = solari_lighting_resources.view_size.y.div_ceil(8);
|
||||
|
||||
pass.set_bind_group(0, scene_bind_group, &[]);
|
||||
pass.set_bind_group(
|
||||
1,
|
||||
&bind_group,
|
||||
&[
|
||||
view_uniform_offset.offset,
|
||||
previous_view_uniform_offset.offset,
|
||||
],
|
||||
);
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {
|
||||
pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);
|
||||
pass.set_pipeline(resolve_dlss_rr_textures_pipeline);
|
||||
pass.dispatch_workgroups(dx, dy, 1);
|
||||
}
|
||||
|
||||
let d = diagnostics.time_span(&mut pass, "solari_lighting/presample_light_tiles");
|
||||
pass.set_pipeline(presample_light_tiles_pipeline);
|
||||
pass.dispatch_workgroups(LIGHT_TILE_BLOCKS as u32, 1, 1);
|
||||
d.end(&mut pass);
|
||||
|
||||
let d = diagnostics.time_span(&mut pass, "solari_lighting/world_cache");
|
||||
|
||||
pass.set_bind_group(2, &bind_group_world_cache_active_cells_dispatch, &[]);
|
||||
|
||||
pass.set_pipeline(decay_world_cache_pipeline);
|
||||
pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
|
||||
|
||||
pass.set_pipeline(compact_world_cache_single_block_pipeline);
|
||||
pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
|
||||
|
||||
pass.set_pipeline(compact_world_cache_blocks_pipeline);
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
|
||||
pass.set_pipeline(compact_world_cache_write_active_cells_pipeline);
|
||||
pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
|
||||
|
||||
pass.set_bind_group(2, None, &[]);
|
||||
|
||||
pass.set_pipeline(sample_di_for_world_cache_pipeline);
|
||||
pass.dispatch_workgroups_indirect(
|
||||
&solari_lighting_resources.world_cache_active_cells_dispatch,
|
||||
0,
|
||||
);
|
||||
|
||||
pass.set_pipeline(sample_gi_for_world_cache_pipeline);
|
||||
pass.dispatch_workgroups_indirect(
|
||||
&solari_lighting_resources.world_cache_active_cells_dispatch,
|
||||
0,
|
||||
);
|
||||
|
||||
pass.set_pipeline(blend_new_world_cache_samples_pipeline);
|
||||
pass.dispatch_workgroups_indirect(
|
||||
&solari_lighting_resources.world_cache_active_cells_dispatch,
|
||||
0,
|
||||
);
|
||||
|
||||
d.end(&mut pass);
|
||||
|
||||
let d = diagnostics.time_span(&mut pass, "solari_lighting/lighting");
|
||||
|
||||
if let Some(bind_group_restir) = &bind_group_restir {
|
||||
pass.set_bind_group(
|
||||
1,
|
||||
bind_group_restir,
|
||||
&[
|
||||
view_uniform_offset.offset,
|
||||
previous_view_uniform_offset.offset,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {
|
||||
pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);
|
||||
}
|
||||
pass.set_pipeline(initial_pipeline);
|
||||
pass.dispatch_workgroups(dx, dy, 1);
|
||||
|
||||
if let Some(spatial_and_shade_pipeline) = spatial_and_shade_pipeline {
|
||||
pass.set_pipeline(spatial_and_shade_pipeline);
|
||||
pass.dispatch_workgroups(dx, dy, 1);
|
||||
}
|
||||
|
||||
d.end(&mut pass);
|
||||
|
||||
drop(pass);
|
||||
|
||||
// Active cell count readback.
|
||||
diagnostics.record_u32(
|
||||
ctx.command_encoder(),
|
||||
&s.world_cache.slice(
|
||||
WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET
|
||||
..WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET + size_of::<u32>() as u64,
|
||||
),
|
||||
"solari_lighting/world_cache_active_cells_count",
|
||||
);
|
||||
}
|
||||
|
||||
/// Initializes the Solari lighting pipelines at render startup.
|
||||
pub fn init_solari_lighting_pipelines(
|
||||
mut commands: Commands,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
scene_bindings: Res<RaytracingSceneBindings>,
|
||||
asset_server: Res<AssetServer>,
|
||||
render_adapter: Res<RenderAdapter>,
|
||||
) {
|
||||
let motion_vectors_storage_read_write = render_adapter
|
||||
.get_texture_format_features(MOTION_VECTOR_PREPASS_FORMAT)
|
||||
.flags
|
||||
.contains(TextureFormatFeatureFlags::STORAGE_READ_WRITE);
|
||||
let motion_vectors_binding = if motion_vectors_storage_read_write {
|
||||
texture_storage_2d(TextureFormat::Rg16Float, StorageTextureAccess::ReadWrite)
|
||||
} else {
|
||||
texture_2d(TextureSampleType::Float { filterable: false })
|
||||
};
|
||||
|
||||
let bind_group_layout = BindGroupLayoutDescriptor::new(
|
||||
"solari_lighting_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::ReadWrite),
|
||||
storage_buffer_sized(false, None),
|
||||
storage_buffer_sized(false, None),
|
||||
texture_2d(TextureSampleType::Uint),
|
||||
texture_depth_2d(),
|
||||
motion_vectors_binding,
|
||||
uniform_buffer::<ViewUniform>(true),
|
||||
uniform_buffer::<PreviousViewData>(true),
|
||||
storage_buffer_sized(false, None),
|
||||
uniform_buffer_sized(false, None),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let bind_group_layout_restir = BindGroupLayoutDescriptor::new(
|
||||
"solari_lighting_bind_group_layout_restir",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::ReadWrite),
|
||||
storage_buffer_sized(false, None),
|
||||
storage_buffer_sized(false, None),
|
||||
texture_2d(TextureSampleType::Uint),
|
||||
texture_depth_2d(),
|
||||
motion_vectors_binding,
|
||||
uniform_buffer::<ViewUniform>(true),
|
||||
uniform_buffer::<PreviousViewData>(true),
|
||||
storage_buffer_sized(false, None),
|
||||
uniform_buffer_sized(false, None),
|
||||
texture_2d(TextureSampleType::Uint),
|
||||
texture_depth_2d(),
|
||||
storage_buffer_sized(false, None),
|
||||
storage_buffer_sized(false, None),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let bind_group_layout_world_cache_active_cells_dispatch = BindGroupLayoutDescriptor::new(
|
||||
"solari_lighting_bind_group_layout_world_cache_active_cells_dispatch",
|
||||
&BindGroupLayoutEntries::single(ShaderStages::COMPUTE, storage_buffer_sized(false, None)),
|
||||
);
|
||||
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
let bind_group_layout_resolve_dlss_rr_textures = BindGroupLayoutDescriptor::new(
|
||||
"solari_lighting_bind_group_layout_resolve_dlss_rr_textures",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
texture_storage_2d(TextureFormat::Rgba8Unorm, StorageTextureAccess::WriteOnly),
|
||||
texture_storage_2d(TextureFormat::Rgba8Unorm, StorageTextureAccess::WriteOnly),
|
||||
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
|
||||
texture_storage_2d(TextureFormat::R32Float, StorageTextureAccess::WriteOnly),
|
||||
texture_storage_2d(TextureFormat::Rg16Float, StorageTextureAccess::WriteOnly),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let create_pipeline = |label: &'static str,
|
||||
entry_point: &'static str,
|
||||
shader: Handle<Shader>,
|
||||
restir: bool,
|
||||
extra_bind_group: ExtraBindGroup,
|
||||
extra_shader_defs: Vec<ShaderDefVal>| {
|
||||
let group_1 = if restir {
|
||||
&bind_group_layout_restir
|
||||
} else {
|
||||
&bind_group_layout
|
||||
};
|
||||
let mut layout = vec![scene_bindings.bind_group_layout.clone(), group_1.clone()];
|
||||
match extra_bind_group {
|
||||
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(
|
||||
"WORLD_CACHE_SIZE".into(),
|
||||
WORLD_CACHE_SIZE as u32,
|
||||
)];
|
||||
if motion_vectors_storage_read_write {
|
||||
shader_defs.push("MOTION_VECTORS_READ_WRITE".into());
|
||||
}
|
||||
if restir {
|
||||
shader_defs.push("RESTIR".into());
|
||||
}
|
||||
match extra_bind_group {
|
||||
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);
|
||||
|
||||
pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some(label.into()),
|
||||
layout,
|
||||
shader,
|
||||
shader_defs,
|
||||
entry_point: Some(entry_point.into()),
|
||||
..default()
|
||||
})
|
||||
};
|
||||
|
||||
commands.insert_resource(SolariLightingPipelines {
|
||||
bind_group_layout: bind_group_layout.clone(),
|
||||
bind_group_layout_restir: bind_group_layout_restir.clone(),
|
||||
bind_group_layout_world_cache_active_cells_dispatch:
|
||||
bind_group_layout_world_cache_active_cells_dispatch.clone(),
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
bind_group_layout_resolve_dlss_rr_textures: bind_group_layout_resolve_dlss_rr_textures
|
||||
.clone(),
|
||||
decay_world_cache_pipeline: create_pipeline(
|
||||
"solari_lighting_decay_world_cache_pipeline",
|
||||
"decay_world_cache",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::WorldCacheDispatch,
|
||||
vec![],
|
||||
),
|
||||
compact_world_cache_single_block_pipeline: create_pipeline(
|
||||
"solari_lighting_compact_world_cache_single_block_pipeline",
|
||||
"compact_world_cache_single_block",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::WorldCacheDispatch,
|
||||
vec![],
|
||||
),
|
||||
compact_world_cache_blocks_pipeline: create_pipeline(
|
||||
"solari_lighting_compact_world_cache_blocks_pipeline",
|
||||
"compact_world_cache_blocks",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::WorldCacheDispatch,
|
||||
vec![],
|
||||
),
|
||||
compact_world_cache_write_active_cells_pipeline: create_pipeline(
|
||||
"solari_lighting_compact_world_cache_write_active_cells_pipeline",
|
||||
"compact_world_cache_write_active_cells",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::WorldCacheDispatch,
|
||||
vec![],
|
||||
),
|
||||
sample_di_for_world_cache_pipeline: create_pipeline(
|
||||
"solari_lighting_sample_di_for_world_cache_pipeline",
|
||||
"sample_di",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_update.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::None,
|
||||
vec![],
|
||||
),
|
||||
sample_gi_for_world_cache_pipeline: create_pipeline(
|
||||
"solari_lighting_sample_gi_for_world_cache_pipeline",
|
||||
"sample_gi",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_update.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::None,
|
||||
vec!["WORLD_CACHE_QUERY_ATOMIC_MAX_LIFETIME".into()],
|
||||
),
|
||||
blend_new_world_cache_samples_pipeline: create_pipeline(
|
||||
"solari_lighting_blend_new_world_cache_samples_pipeline",
|
||||
"blend_new_samples",
|
||||
load_embedded_asset!(asset_server.as_ref(), "world_cache_update.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::None,
|
||||
vec![],
|
||||
),
|
||||
presample_light_tiles_pipeline: create_pipeline(
|
||||
"solari_lighting_presample_light_tiles_pipeline",
|
||||
"presample_light_tiles",
|
||||
load_embedded_asset!(asset_server.as_ref(), "presample_light_tiles.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::None,
|
||||
vec![],
|
||||
),
|
||||
restir: RestirPipelines {
|
||||
initial_and_temporal: create_pipeline(
|
||||
"solari_lighting_initial_and_temporal_pipeline",
|
||||
"initial_and_temporal",
|
||||
load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
|
||||
true,
|
||||
ExtraBindGroup::None,
|
||||
vec![],
|
||||
),
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
initial_and_temporal_with_psr: create_pipeline(
|
||||
"solari_lighting_initial_and_temporal_with_psr_pipeline",
|
||||
"initial_and_temporal",
|
||||
load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
|
||||
true,
|
||||
ExtraBindGroup::DlssRrGuideBuffers,
|
||||
vec![],
|
||||
),
|
||||
spatial_and_shade: create_pipeline(
|
||||
"solari_lighting_spatial_and_shade_pipeline",
|
||||
"spatial_and_shade",
|
||||
load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
|
||||
true,
|
||||
ExtraBindGroup::None,
|
||||
vec!["SPATIAL_MERGE".into()],
|
||||
),
|
||||
},
|
||||
no_restir: NoRestirPipelines {
|
||||
initial_and_shade: create_pipeline(
|
||||
"solari_lighting_initial_and_shade_pipeline",
|
||||
"initial_and_shade",
|
||||
load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::None,
|
||||
vec![],
|
||||
),
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
initial_and_shade_with_psr: create_pipeline(
|
||||
"solari_lighting_initial_and_shade_with_psr_pipeline",
|
||||
"initial_and_shade",
|
||||
load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::DlssRrGuideBuffers,
|
||||
vec![],
|
||||
),
|
||||
},
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
resolve_dlss_rr_textures_pipeline: create_pipeline(
|
||||
"solari_lighting_resolve_dlss_rr_textures_pipeline",
|
||||
"resolve_dlss_rr_textures",
|
||||
load_embedded_asset!(asset_server.as_ref(), "resolve_dlss_rr_textures.wesl"),
|
||||
false,
|
||||
ExtraBindGroup::DlssRrGuideBuffers,
|
||||
vec![],
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
enum ExtraBindGroup {
|
||||
None,
|
||||
WorldCacheDispatch,
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
DlssRrGuideBuffers,
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
use super::SolariLighting;
|
||||
use crate::scene::RaytracingSceneNeedsPreviousFrameData;
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
use bevy_anti_alias::dlss::{
|
||||
Dlss, DlssRayReconstructionFeature, ViewDlssRayReconstructionTextures,
|
||||
};
|
||||
use bevy_camera::MainPassResolutionOverride;
|
||||
use bevy_diagnostic::FrameCount;
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
use bevy_ecs::query::Has;
|
||||
use bevy_ecs::{
|
||||
component::Component,
|
||||
entity::Entity,
|
||||
system::{Commands, Query, Res},
|
||||
};
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
use bevy_image::ToExtents;
|
||||
use bevy_math::UVec2;
|
||||
use bevy_render::{
|
||||
camera::ExtractedCamera,
|
||||
render_resource::{Buffer, BufferDescriptor, BufferInitDescriptor, BufferUsages},
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
};
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
use bevy_render::{
|
||||
render_resource::{
|
||||
TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, TextureViewDescriptor,
|
||||
},
|
||||
texture::CachedTexture,
|
||||
};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
|
||||
/// Size of the `LightSample` shader struct in bytes.
|
||||
const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8;
|
||||
|
||||
/// Size of the `ResolvedLightSamplePacked` shader struct in bytes.
|
||||
const RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE: u64 = 24;
|
||||
|
||||
/// Size of the `Reservoir` shader struct in bytes.
|
||||
const RESERVOIR_STRUCT_SIZE: u64 = 48;
|
||||
|
||||
pub const LIGHT_TILE_BLOCKS: u64 = 128;
|
||||
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`.
|
||||
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).
|
||||
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.
|
||||
///
|
||||
/// Field order and types must match the `SolariLightingSettings` struct in
|
||||
/// `realtime_bindings.wgsl`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
struct SolariLightingUniforms {
|
||||
confidence_weight_cap: f32,
|
||||
primary_di_samples: u32,
|
||||
secondary_di_samples: u32,
|
||||
max_bounces: u32,
|
||||
world_cache_max_temporal_samples: f32,
|
||||
world_cache_direct_light_sample_count: u32,
|
||||
world_cache_max_gi_ray_distance: f32,
|
||||
world_cache_cell_updates_soft_target: u32,
|
||||
world_cache_position_base_cell_size: f32,
|
||||
world_cache_position_lod_scale: f32,
|
||||
frame_rng: u32,
|
||||
reset: u32,
|
||||
}
|
||||
|
||||
impl SolariLightingUniforms {
|
||||
fn new(settings: &SolariLighting, frame_count: u32, force_reset: bool) -> Self {
|
||||
Self {
|
||||
confidence_weight_cap: settings.confidence_weight_cap,
|
||||
primary_di_samples: settings.primary_di_samples,
|
||||
secondary_di_samples: settings.secondary_di_samples,
|
||||
max_bounces: settings.max_bounces,
|
||||
world_cache_max_temporal_samples: settings.world_cache_max_temporal_samples,
|
||||
world_cache_direct_light_sample_count: settings.world_cache_direct_light_sample_count,
|
||||
world_cache_max_gi_ray_distance: settings.world_cache_max_gi_ray_distance,
|
||||
world_cache_cell_updates_soft_target: settings.world_cache_cell_updates_soft_target,
|
||||
world_cache_position_base_cell_size: settings.world_cache_position_base_cell_size,
|
||||
world_cache_position_lod_scale: settings.world_cache_position_lod_scale,
|
||||
frame_rng: frame_count.wrapping_mul(5782582),
|
||||
reset: (settings.reset || force_reset) as u32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let restir_used = views.iter().any(|solari_lighting| solari_lighting.restir);
|
||||
match (restir_used, needs_previous_frame_data.is_some()) {
|
||||
(true, false) => commands.insert_resource(RaytracingSceneNeedsPreviousFrameData),
|
||||
(false, true) => commands.remove_resource::<RaytracingSceneNeedsPreviousFrameData>(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal rendering resources used for Solari lighting.
|
||||
#[derive(Component)]
|
||||
pub struct SolariLightingResources {
|
||||
pub constants: Buffer,
|
||||
pub light_tile_samples: Buffer,
|
||||
pub light_tile_resolved_samples: Buffer,
|
||||
pub reservoirs: Option<SolariReservoirBuffers>,
|
||||
pub world_cache: Buffer,
|
||||
pub world_cache_active_cells_dispatch: Buffer,
|
||||
pub view_size: UVec2,
|
||||
}
|
||||
|
||||
pub struct SolariReservoirBuffers {
|
||||
pub a: Buffer,
|
||||
pub b: Buffer,
|
||||
}
|
||||
|
||||
pub fn prepare_solari_lighting_resources(
|
||||
#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] query: Query<(
|
||||
Entity,
|
||||
&ExtractedCamera,
|
||||
&SolariLighting,
|
||||
Option<&SolariLightingResources>,
|
||||
Option<&MainPassResolutionOverride>,
|
||||
)>,
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] query: Query<(
|
||||
Entity,
|
||||
&ExtractedCamera,
|
||||
&SolariLighting,
|
||||
Option<&SolariLightingResources>,
|
||||
Option<&MainPassResolutionOverride>,
|
||||
Has<Dlss<DlssRayReconstructionFeature>>,
|
||||
)>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
frame_count: Res<FrameCount>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for query_item in &query {
|
||||
#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
|
||||
let (entity, camera, solari_lighting, solari_lighting_resources, resolution_override) =
|
||||
query_item;
|
||||
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
|
||||
let (
|
||||
entity,
|
||||
camera,
|
||||
solari_lighting,
|
||||
solari_lighting_resources,
|
||||
resolution_override,
|
||||
has_dlss_rr,
|
||||
) = query_item;
|
||||
|
||||
let Some(mut view_size) = camera.physical_viewport_size else {
|
||||
continue;
|
||||
};
|
||||
if let Some(MainPassResolutionOverride(resolution_override)) = resolution_override {
|
||||
view_size = *resolution_override;
|
||||
}
|
||||
|
||||
let reusable = solari_lighting_resources.filter(|r| {
|
||||
r.view_size == view_size && r.reservoirs.is_some() == solari_lighting.restir
|
||||
});
|
||||
let uniforms =
|
||||
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.
|
||||
render_queue.write_buffer(
|
||||
&solari_lighting_resources.constants,
|
||||
0,
|
||||
bytemuck::bytes_of(&uniforms),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let constants = render_device.create_buffer_with_data(&BufferInitDescriptor {
|
||||
label: Some("solari_lighting_constants"),
|
||||
contents: bytemuck::bytes_of(&uniforms),
|
||||
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,
|
||||
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
|
||||
* LIGHT_TILE_SAMPLES_PER_BLOCK
|
||||
* RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE,
|
||||
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,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
};
|
||||
SolariReservoirBuffers {
|
||||
a: reservoirs_buffer("solari_lighting_reservoirs_a"),
|
||||
b: reservoirs_buffer("solari_lighting_reservoirs_b"),
|
||||
}
|
||||
});
|
||||
|
||||
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,
|
||||
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,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
commands.entity(entity).insert(SolariLightingResources {
|
||||
constants,
|
||||
light_tile_samples,
|
||||
light_tile_resolved_samples,
|
||||
reservoirs,
|
||||
world_cache,
|
||||
world_cache_active_cells_dispatch,
|
||||
view_size,
|
||||
});
|
||||
|
||||
#[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(),
|
||||
mip_level_count: 1,
|
||||
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(),
|
||||
mip_level_count: 1,
|
||||
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(),
|
||||
mip_level_count: 1,
|
||||
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(),
|
||||
mip_level_count: 1,
|
||||
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(),
|
||||
mip_level_count: 1,
|
||||
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());
|
||||
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(ViewDlssRayReconstructionTextures {
|
||||
diffuse_albedo: CachedTexture {
|
||||
texture: diffuse_albedo,
|
||||
default_view: diffuse_albedo_view,
|
||||
},
|
||||
specular_albedo: CachedTexture {
|
||||
texture: specular_albedo,
|
||||
default_view: specular_albedo_view,
|
||||
},
|
||||
normal_roughness: CachedTexture {
|
||||
texture: normal_roughness,
|
||||
default_view: normal_roughness_view,
|
||||
},
|
||||
depth: CachedTexture {
|
||||
texture: dlss_rr_depth,
|
||||
default_view: dlss_rr_depth_view,
|
||||
},
|
||||
specular_motion_vectors: CachedTexture {
|
||||
texture: specular_motion_vectors,
|
||||
default_view: specular_motion_vectors_view,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// https://cwyman.org/papers/hpg21_rearchitectingReSTIR.pdf
|
||||
|
||||
import bevy_pbr::render::rgb9e5::{vec3_to_rgb9e5_, rgb9e5_to_vec3_};
|
||||
import bevy_render::utils::{octahedral_encode, octahedral_decode};
|
||||
import package::scene::sampling::{generate_random_light_sample, ResolvedLightSample};
|
||||
import package::realtime::bindings::{light_tile_samples, light_tile_resolved_samples, view, constants, ResolvedLightSamplePacked};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@compute @workgroup_size(1024, 1, 1)
|
||||
fn presample_light_tiles(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(local_invocation_index) sample_index: u32) {
|
||||
let tile_id = workgroup_id.x;
|
||||
var rng = (tile_id * 0x9E3779B9u) + sample_index + constants.frame_rng;
|
||||
|
||||
let sample = generate_random_light_sample(&rng);
|
||||
|
||||
let i = (tile_id * 1024u) + sample_index;
|
||||
light_tile_samples[i] = sample.light_sample;
|
||||
light_tile_resolved_samples[i] = pack_resolved_light_sample(sample.resolved_light_sample);
|
||||
}
|
||||
|
||||
fn pack_resolved_light_sample(sample: ResolvedLightSample) -> ResolvedLightSamplePacked {
|
||||
return ResolvedLightSamplePacked(
|
||||
sample.world_position.x,
|
||||
sample.world_position.y,
|
||||
sample.world_position.z,
|
||||
pack2x16unorm(octahedral_encode(sample.world_normal)),
|
||||
vec3_to_rgb9e5_(log2(sample.radiance * view.exposure + 1.0)),
|
||||
sample.inverse_pdf * select(1.0, -1.0, sample.world_position.w == 0.0),
|
||||
);
|
||||
}
|
||||
|
||||
fn unpack_resolved_light_sample(packed: ResolvedLightSamplePacked, exposure: f32) -> ResolvedLightSample {
|
||||
return ResolvedLightSample(
|
||||
vec4(packed.world_position_x, packed.world_position_y, packed.world_position_z, select(1.0, 0.0, packed.inverse_pdf < 0.0)),
|
||||
octahedral_decode(unpack2x16unorm(packed.world_normal)),
|
||||
(exp2(rgb9e5_to_vec3_(packed.radiance)) - 1.0) / exposure,
|
||||
abs(packed.inverse_pdf),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
|
||||
import bevy_pbr::deferred::types::unpack_24bit_normal;
|
||||
import bevy_pbr::render::pbr_functions::{calculate_diffuse_color, calculate_F0, calculate_F0_dielectric};
|
||||
import bevy_render::utils::octahedral_decode;
|
||||
import package::realtime::gbuffer_utils::gpixel_resolve;
|
||||
import package::realtime::bindings::{gbuffer, depth_buffer, load_motion_vector, motion_vectors, previous_view, view, diffuse_albedo, specular_albedo, normal_roughness, dlss_rr_depth, specular_motion_vectors};
|
||||
import package::scene::brdf::{evaluate_specular_brdf, F_AB, lobe_reflectances};
|
||||
import package::scene::bindings::{MIRROR_ROUGHNESS_THRESHOLD, ResolvedMaterial, ResolvedRayHitFull};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
/// A surface is replaced outright only when nearly all of its reflectance leaves through the delta
|
||||
/// lobe.
|
||||
const FULL_REPLACEMENT_FRACTION = 0.9;
|
||||
|
||||
/// How far a reflector's virtual image may shift between neighboring pixels, as a fraction of the
|
||||
/// virtual distance itself, before the surface is treated as too curved to replace.
|
||||
const MAX_VIRTUAL_DEPTH_JITTER = 0.002;
|
||||
|
||||
/// Even a perfectly flat surface measures a small nonzero normal change, because G-buffer normals are
|
||||
/// 24-bit octahedral and neighboring texels round differently.
|
||||
const NORMAL_QUANTIZATION_FLOOR = 0.002;
|
||||
|
||||
/// Distance, in meters, standing in for "infinitely far" when a mirror ray finds nothing.
|
||||
const ENVIRONMENT_VIRTUAL_DISTANCE = 10000.0;
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn resolve_dlss_rr_textures(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
let pixel_id = global_id.xy;
|
||||
if any(pixel_id >= vec2u(view.main_pass_viewport.zw)) { return; }
|
||||
|
||||
let depth = textureLoad(depth_buffer, global_id.xy, 0);
|
||||
let surface_motion_vector = load_motion_vector(pixel_id);
|
||||
|
||||
textureStore(dlss_rr_depth, pixel_id, vec4(depth));
|
||||
|
||||
if depth == 0.0 {
|
||||
textureStore(specular_motion_vectors, pixel_id, vec4(surface_motion_vector, vec2(0.0)));
|
||||
textureStore(diffuse_albedo, pixel_id, vec4(0.0));
|
||||
textureStore(specular_albedo, pixel_id, vec4(0.5));
|
||||
textureStore(normal_roughness, pixel_id, vec4(0.0, 0.0, 1.0, 0.0));
|
||||
return;
|
||||
}
|
||||
|
||||
let surface = gpixel_resolve(textureLoad(gbuffer, pixel_id, 0), depth, pixel_id, view.main_pass_viewport.zw, view.world_from_clip);
|
||||
let F0 = calculate_F0(surface.material.base_color, surface.material.metallic, vec3(surface.material.reflectance));
|
||||
let wo = normalize(view.world_position - surface.world_position);
|
||||
|
||||
textureStore(diffuse_albedo, pixel_id, vec4(calculate_diffuse_color(surface.material.base_color, surface.material.metallic, 0.0, 0.0), 0.0));
|
||||
textureStore(specular_albedo, pixel_id, vec4(env_brdf_approx2(F0, surface.material.roughness, surface.world_normal, wo), 0.0));
|
||||
textureStore(normal_roughness, pixel_id, vec4(surface.world_normal, surface.material.perceptual_roughness));
|
||||
|
||||
// Resetting to the specular motion vector on the frames we draw a diffuse lobe means we
|
||||
// wouldn't be writing the motion vectors that frame, so it would alternate the guide between
|
||||
// to values, and the denoiser blurs the reflection rather than reprojecting it.
|
||||
if !needs_specular_motion_vector(surface.material.roughness) {
|
||||
textureStore(specular_motion_vectors, pixel_id, vec4(surface_motion_vector, vec2(0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
fn needs_specular_motion_vector(roughness: f32) -> bool {
|
||||
return roughness <= 0.0625;
|
||||
}
|
||||
|
||||
/// Carried across every bounce of the path walk, so anything derivable from a value the walk already
|
||||
/// holds is derived at the end instead of stored. What is left is only what the walk itself produces.
|
||||
struct PsrState {
|
||||
finished: bool,
|
||||
/// Whether this pixel's surface is being swapped out for the reflected one, or is only having its
|
||||
/// reflection's motion described. Keyed on the primary surface only, and false for anything glossy.
|
||||
replace_fully: bool,
|
||||
/// The chain's cumulative transform - the product of one Householder reflection per mirror, in
|
||||
/// chain order - stored as a rotor plus the parity of the reflection count rather than as the 3x3
|
||||
/// matrix it denotes.
|
||||
mirror_rotor: vec4<f32>,
|
||||
mirror_parity_odd: bool,
|
||||
/// Distance traveled since the primary surface, camera through every mirror. Not the total path
|
||||
/// length: keeping the reflection's own share means the primary distance is only ever added, never
|
||||
/// subtracted back out, so it can be recovered at the end without the two disagreeing.
|
||||
reflection_length: f32,
|
||||
/// Product of the Fresnel term at each mirror in the chain: what the reflected surface's color is
|
||||
/// multiplied by on its way back to the eye.
|
||||
throughput: vec3<f32>,
|
||||
}
|
||||
|
||||
fn psr_init(world_normal: vec3<f32>, material: ResolvedMaterial) -> PsrState {
|
||||
var psr: PsrState;
|
||||
psr.finished = !needs_specular_motion_vector(material.roughness);
|
||||
psr.replace_fully = is_delta_mirror(material);
|
||||
// The chain opens with the primary surface's own reflection, so parity starts odd.
|
||||
psr.mirror_rotor = mirror_chain_rotor(world_normal, false);
|
||||
psr.mirror_parity_odd = true;
|
||||
psr.reflection_length = 0.0;
|
||||
psr.throughput = vec3(1.0);
|
||||
return psr;
|
||||
}
|
||||
|
||||
/// Fold one more mirror into the chain, equivalent to right-multiplying the chain's matrix by this
|
||||
/// mirror's Householder reflection.
|
||||
/// https://en.wikipedia.org/wiki/Householder_transformation
|
||||
///
|
||||
/// A product of k Householder reflections is orthogonal with determinant (-1)^k, so it is a rotation
|
||||
/// when k is even, and a rotation composed with any one fixed reflection when k is odd.
|
||||
fn psr_chain_mirror(psr: PsrState, plane_normal: vec3<f32>) -> PsrState {
|
||||
var chained = psr;
|
||||
chained.mirror_rotor = quaternion_multiply(psr.mirror_rotor, mirror_chain_rotor(plane_normal, psr.mirror_parity_odd));
|
||||
chained.mirror_parity_odd = !psr.mirror_parity_odd;
|
||||
return chained;
|
||||
}
|
||||
|
||||
fn psr_environment_miss(pixel_id: vec2<u32>, primary_wo: vec3<f32>) {
|
||||
let far_position = view.world_position - (primary_wo * ENVIRONMENT_VIRTUAL_DISTANCE);
|
||||
textureStore(specular_motion_vectors, pixel_id, vec4(calculate_motion_vector(far_position, far_position), vec2(0.0)));
|
||||
}
|
||||
|
||||
/// Primary surface replacement for perfect mirrors. The reflection chain has been followed to its
|
||||
/// first non-mirror hit; write that surface's attributes, reflected into the mirror's virtual space,
|
||||
/// to the DLSS RR guide buffers so the denoiser treats this pixel as directly seeing it.
|
||||
/// https://developer.nvidia.com/blog/rendering-perfect-reflections-and-refractions-in-path-traced-games/#primary_surface_replacement
|
||||
fn replace_primary_surface(
|
||||
pixel_id: vec2<u32>,
|
||||
psr: PsrState,
|
||||
ray_hit: ResolvedRayHitFull,
|
||||
primary_material: ResolvedMaterial,
|
||||
primary_world_position: vec3<f32>,
|
||||
primary_normal: vec3<f32>,
|
||||
primary_wo: vec3<f32>,
|
||||
primary_F_ab: vec2<f32>,
|
||||
) {
|
||||
let primary_distance = length(primary_world_position - view.world_position);
|
||||
let path_length = primary_distance + psr.reflection_length;
|
||||
|
||||
// Too curved to track the reflection; fall back to the surface's own motion so the guide is not stale
|
||||
if psr.replace_fully && 2.0 * reflector_curvature(pixel_id, primary_normal) * psr.reflection_length > MAX_VIRTUAL_DEPTH_JITTER * path_length {
|
||||
textureStore(specular_motion_vectors, pixel_id, vec4(load_motion_vector(pixel_id), vec2(0.0)));
|
||||
return;
|
||||
}
|
||||
|
||||
let virtual_position = primary_world_position - (primary_wo * psr.reflection_length);
|
||||
let world_motion = ray_hit.previous_frame_world_position - ray_hit.world_position;
|
||||
let virtual_previous_position = virtual_position + apply_mirror_chain(psr, world_motion);
|
||||
let specular_motion_vector = calculate_motion_vector(virtual_position, virtual_previous_position);
|
||||
|
||||
textureStore(specular_motion_vectors, pixel_id, vec4(specular_motion_vector, vec2(0.0)));
|
||||
|
||||
if !psr.replace_fully {
|
||||
return;
|
||||
}
|
||||
|
||||
let wo = normalize(view.world_position - virtual_position);
|
||||
let virtual_normal = normalize(apply_mirror_chain(psr, ray_hit.world_normal));
|
||||
|
||||
let primary_depth = textureLoad(depth_buffer, pixel_id, 0);
|
||||
textureStore(dlss_rr_depth, pixel_id, vec4(primary_depth * primary_distance / path_length));
|
||||
@if(MOTION_VECTORS_READ_WRITE)
|
||||
textureStore(motion_vectors, pixel_id, vec4(specular_motion_vector, vec2(0.0)));
|
||||
|
||||
let reflected_diffuse = calculate_diffuse_color(ray_hit.material.base_color, ray_hit.material.metallic, 0.0, 0.0);
|
||||
let reflected_F0 = calculate_F0(ray_hit.material.base_color, ray_hit.material.metallic, vec3(ray_hit.material.reflectance));
|
||||
let reflected_specular = env_brdf_approx2(reflected_F0, ray_hit.material.roughness, virtual_normal, wo);
|
||||
|
||||
let own_diffuse = calculate_diffuse_color(primary_material.base_color, primary_material.metallic, 0.0, 0.0);
|
||||
let own_F0 = calculate_F0(primary_material.base_color, primary_material.metallic, vec3(primary_material.reflectance));
|
||||
let own_specular = env_brdf_approx2(own_F0, primary_material.roughness, primary_normal, primary_wo);
|
||||
|
||||
let specular_fraction = specular_fraction(primary_material, primary_F_ab);
|
||||
|
||||
textureStore(diffuse_albedo, pixel_id, vec4(psr.throughput * reflected_diffuse + own_diffuse, 0.0));
|
||||
textureStore(specular_albedo, pixel_id, vec4(mix(own_specular, psr.throughput * reflected_specular, specular_fraction), 0.0));
|
||||
textureStore(normal_roughness, pixel_id, vec4(virtual_normal, ray_hit.material.perceptual_roughness));
|
||||
}
|
||||
|
||||
fn primary_surface_glossy(material: ResolvedMaterial) -> bool {
|
||||
return material.roughness > MIRROR_ROUGHNESS_THRESHOLD;
|
||||
}
|
||||
|
||||
fn is_delta_mirror(material: ResolvedMaterial) -> bool {
|
||||
return material.roughness <= MIRROR_ROUGHNESS_THRESHOLD
|
||||
&& specular_fraction(material, F_AB(material.perceptual_roughness, 1.0)) >= FULL_REPLACEMENT_FRACTION;
|
||||
}
|
||||
|
||||
/// Share of a surface's total reflectance that leaves through the specular lobe, in 0..1.
|
||||
fn specular_fraction(material: ResolvedMaterial, F_ab: vec2<f32>) -> f32 {
|
||||
let rho = lobe_reflectances(material.base_color, calculate_F0_dielectric(vec3(material.reflectance)), material, F_ab);
|
||||
let specular_luminance = luminance(rho.specular);
|
||||
return specular_luminance / max(specular_luminance + luminance(rho.diffuse), 0.0001);
|
||||
}
|
||||
|
||||
fn psr_bounce_reflectance(wo: vec3<f32>, wi: vec3<f32>, normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>, delta: bool) -> vec3<f32> {
|
||||
if delta {
|
||||
return evaluate_specular_brdf(wo, wi, normal, material, F_ab);
|
||||
}
|
||||
return lobe_reflectances(material.base_color, calculate_F0_dielectric(vec3(material.reflectance)), material, F_ab).specular;
|
||||
}
|
||||
|
||||
/// Angle, in radians, that the shading normal changes over one pixel in screen space.
|
||||
fn reflector_curvature(pixel_id: vec2<u32>, normal: vec3<f32>) -> f32 {
|
||||
let max_pixel_id = vec2<u32>(view.main_pass_viewport.zw) - vec2(1u);
|
||||
let right = load_gbuffer_normal(min(pixel_id + vec2(1u, 0u), max_pixel_id));
|
||||
let down = load_gbuffer_normal(min(pixel_id + vec2(0u, 1u), max_pixel_id));
|
||||
let min_cos = min(dot(normal, right), dot(normal, down));
|
||||
let angle = sqrt(max(0.0, 2.0 * (1.0 - min_cos)));
|
||||
return max(0.0, angle - NORMAL_QUANTIZATION_FLOOR);
|
||||
}
|
||||
|
||||
fn load_gbuffer_normal(pixel_id: vec2<u32>) -> vec3<f32> {
|
||||
return octahedral_decode(unpack_24bit_normal(textureLoad(gbuffer, pixel_id, 0).a));
|
||||
}
|
||||
|
||||
fn apply_mirror_chain(psr: PsrState, v: vec3<f32>) -> vec3<f32> {
|
||||
var reflected = v;
|
||||
if psr.mirror_parity_odd {
|
||||
reflected.z = -reflected.z;
|
||||
}
|
||||
let t = 2.0 * cross(psr.mirror_rotor.xyz, reflected);
|
||||
return reflected + psr.mirror_rotor.w * t + cross(psr.mirror_rotor.xyz, t);
|
||||
}
|
||||
|
||||
/// The rotation half of `H(n) * F` at even parity, or of `F * H(n)` at odd, where `H(n)` is the
|
||||
/// Householder reflection about `plane_normal` and `F` the fixed z-axis one.
|
||||
fn mirror_chain_rotor(plane_normal: vec3<f32>, parity_odd: bool) -> vec4<f32> {
|
||||
if parity_odd {
|
||||
return vec4(plane_normal.y, -plane_normal.x, 0.0, plane_normal.z);
|
||||
}
|
||||
return vec4(-plane_normal.y, plane_normal.x, 0.0, plane_normal.z);
|
||||
}
|
||||
|
||||
fn quaternion_multiply(a: vec4<f32>, b: vec4<f32>) -> vec4<f32> {
|
||||
return vec4(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
|
||||
}
|
||||
|
||||
fn calculate_motion_vector(world_position: vec3<f32>, previous_world_position: vec3<f32>) -> vec2<f32> {
|
||||
let clip_position_t = view.unjittered_clip_from_world * vec4(world_position, 1.0);
|
||||
let clip_position = clip_position_t.xy / clip_position_t.w;
|
||||
let previous_clip_position_t = previous_view.unjittered_clip_from_world * vec4(previous_world_position, 1.0);
|
||||
let previous_clip_position = previous_clip_position_t.xy / previous_clip_position_t.w;
|
||||
// Motion vectors are UV-space offsets in [-1, 1], from one corner to the diagonally-opposite one.
|
||||
// A clip-space diagonal difference is in [-2, 2], so scale by 0.5, and flip y since V goes down
|
||||
// where clip-space y goes up.
|
||||
return (clip_position - previous_clip_position) * vec2(0.5, -0.5);
|
||||
}
|
||||
|
||||
fn env_brdf_approx2(specular_color: vec3<f32>, alpha: f32, N: vec3<f32>, V: vec3<f32>) -> vec3<f32> {
|
||||
let NoV = abs(dot(N, V));
|
||||
|
||||
var X: vec4<f32>;
|
||||
X.x = 1.0;
|
||||
X.y = NoV;
|
||||
X.z = NoV * NoV;
|
||||
X.w = NoV * X.z;
|
||||
|
||||
var Y: vec4<f32>;
|
||||
Y.x = 1.0;
|
||||
Y.y = alpha;
|
||||
Y.z = alpha * alpha;
|
||||
Y.w = alpha * Y.z;
|
||||
|
||||
let M1 = mat2x2<f32>(0.99044, 1.29678, -1.28514, -0.755907);
|
||||
let M2 = mat3x3<f32>(1.0, 20.3225, 121.563, 2.92338, -27.0302, 626.13, 59.4188, 222.592, 316.627);
|
||||
let M3 = mat2x2<f32>(0.0365463, 9.0632, 3.32707, -9.04756);
|
||||
let M4 = mat3x3<f32>(1.0, 9.04401, 5.56589, 3.59685, -16.3174, 19.7886, -1.36772, 9.22949, -20.2123);
|
||||
|
||||
var bias = dot(M1 * X.xy, Y.xy) / dot(M2 * X.xyw, Y.xyw);
|
||||
let scale = dot(M3 * X.xy, Y.xy) / dot(M4 * X.xzw, Y.xyw);
|
||||
|
||||
bias *= saturate(specular_color.g * 50.0);
|
||||
|
||||
return fma(specular_color, vec3(max(0.0, scale)), vec3(max(0.0, bias)));
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
//! https://intro-to-restir.cwyman.org/presentations/2023ReSTIR_Course_Notes.pdf
|
||||
|
||||
import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
|
||||
import bevy_pbr::render::utils::{rand_f, rand_u, sample_disk};
|
||||
import bevy_render::utils::octahedral_decode;
|
||||
import package::scene::brdf::{brdf_pdf, evaluate_brdf, F_AB};
|
||||
import package::realtime::gbuffer_utils::{gpixel_resolve, permute_pixel, pixel_dissimilar};
|
||||
import package::realtime::initial_path::{generate_initial_path, InitialSamplingResult};
|
||||
import package::realtime::bindings::{depth_buffer, empty_reservoir, gbuffer, load_motion_vector, previous_depth_buffer, previous_gbuffer, previous_view, reservoirs_a, reservoirs_b, Reservoir, constants, view, view_output};
|
||||
import package::scene::sampling::{balance_heuristic, calculate_resolved_light_contribution, isinf, isnan, LightSample, NULL_LIGHT_ID, power_heuristic, resolve_light_sample, ResolvedLightSample, trace_visibility, trace_visibility_previous_frame};
|
||||
import package::scene::bindings::{light_sources, LIGHT_NOT_PRESENT_THIS_FRAME, previous_frame_light_id_translations, RAY_T_MAX, RAY_T_MIN, ResolvedMaterial};
|
||||
import package::realtime::world_cache_query::{query_world_cache, WORLD_CACHE_CELL_LIFETIME};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
const SPATIAL_REUSE_RADIUS_PIXELS = 30.0;
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn initial_and_temporal(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
|
||||
|
||||
let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
|
||||
var rng = pixel_index + constants.frame_rng;
|
||||
|
||||
let depth = textureLoad(depth_buffer, global_id.xy, 0);
|
||||
if depth == 0.0 {
|
||||
reservoirs_b[pixel_index] = empty_reservoir();
|
||||
return;
|
||||
}
|
||||
let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
|
||||
|
||||
let initial = generate_initial_path(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
|
||||
textureStore(view_output, global_id.xy, vec4(initial.radiance, 0.0));
|
||||
|
||||
let temporal = load_temporal_reservoir(global_id.xy, depth, surface.world_position, surface.world_normal);
|
||||
let previous_camera_homogeneous = previous_view.world_from_clip * (previous_view.clip_from_view * vec4(0.0, 0.0, 0.0, 1.0));
|
||||
let previous_camera_world_position = previous_camera_homogeneous.xyz / previous_camera_homogeneous.w;
|
||||
let merge_result = merge_reservoirs(initial.reservoir, surface.world_position, surface.world_normal, surface.material,
|
||||
temporal.reservoir, temporal.world_position, temporal.world_normal, temporal.material, previous_camera_world_position, &rng);
|
||||
|
||||
reservoirs_b[pixel_index] = merge_result.merged_reservoir;
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn spatial_and_shade(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
|
||||
|
||||
let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
|
||||
var rng = pixel_index + constants.frame_rng + 0x6A09E667u;
|
||||
|
||||
let depth = textureLoad(depth_buffer, global_id.xy, 0);
|
||||
if depth == 0.0 {
|
||||
reservoirs_a[pixel_index] = empty_reservoir();
|
||||
return;
|
||||
}
|
||||
let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
|
||||
|
||||
let input_reservoir = reservoirs_b[pixel_index];
|
||||
let spatial = load_spatial_reservoir(global_id.xy, depth, surface.world_position, surface.world_normal, &rng);
|
||||
let merge_result = merge_reservoirs(input_reservoir, surface.world_position, surface.world_normal, surface.material,
|
||||
spatial.reservoir, spatial.world_position, spatial.world_normal, spatial.material, view.world_position, &rng);
|
||||
|
||||
reservoirs_a[pixel_index] = merge_result.merged_reservoir;
|
||||
|
||||
var pixel_color = merge_result.selected_sample_brdf_radiance * merge_result.merged_reservoir.unbiased_contribution_weight;
|
||||
pixel_color += surface.material.emissive;
|
||||
pixel_color += textureLoad(view_output, global_id.xy).rgb;
|
||||
pixel_color *= view.exposure;
|
||||
textureStore(view_output, global_id.xy, vec4(pixel_color, 1.0));
|
||||
|
||||
@if(VISUALIZE_WORLD_CACHE)
|
||||
textureStore(view_output, global_id.xy, vec4(query_world_cache(surface.world_position, surface.world_normal, view.world_position, RAY_T_MAX, WORLD_CACHE_CELL_LIFETIME, &rng) * view.exposure, 1.0));
|
||||
}
|
||||
|
||||
fn load_temporal_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3<f32>, world_normal: vec3<f32>) -> NeighborInfo {
|
||||
if bool(constants.reset) {
|
||||
return NeighborInfo(empty_reservoir(), vec3(0.0), vec3(0.0), empty_material());
|
||||
}
|
||||
|
||||
let motion_vector = load_motion_vector(pixel_id);
|
||||
let temporal_pixel_id_float = round(vec2<f32>(pixel_id) - (motion_vector * view.main_pass_viewport.zw));
|
||||
|
||||
// If reprojection lands off-screen, fall back to this pixel's own previous reservoir rather than
|
||||
// dropping history. The dissimilarity check below still validates the surface, and a same-pixel
|
||||
// guess that passes it beats restarting from a confidence-1 reservoir at the screen edge.
|
||||
var point_temporal_pixel_id = pixel_id;
|
||||
if all(temporal_pixel_id_float >= vec2(0.0)) && all(temporal_pixel_id_float < view.main_pass_viewport.zw) {
|
||||
point_temporal_pixel_id = vec2<u32>(temporal_pixel_id_float);
|
||||
}
|
||||
|
||||
var permute_rng = constants.frame_rng;
|
||||
let permuted_temporal_pixel_id = permute_pixel(point_temporal_pixel_id, rand_u(&permute_rng), view.main_pass_viewport.zw);
|
||||
|
||||
// Check if the pixel features have changed heavily between the current and previous frame
|
||||
let temporal_depth = textureLoad(previous_depth_buffer, permuted_temporal_pixel_id, 0);
|
||||
let temporal_surface = gpixel_resolve(textureLoad(previous_gbuffer, permuted_temporal_pixel_id, 0), temporal_depth, permuted_temporal_pixel_id, view.main_pass_viewport.zw, previous_view.world_from_clip);
|
||||
if pixel_dissimilar(depth, world_position, temporal_surface.world_position, world_normal, temporal_surface.world_normal, view) {
|
||||
return NeighborInfo(empty_reservoir(), vec3(0.0), vec3(0.0), empty_material());
|
||||
}
|
||||
|
||||
let temporal_pixel_index = permuted_temporal_pixel_id.x + permuted_temporal_pixel_id.y * u32(view.main_pass_viewport.z);
|
||||
var temporal = NeighborInfo(reservoirs_a[temporal_pixel_index], temporal_surface.world_position, temporal_surface.world_normal, temporal_surface.material);
|
||||
|
||||
// Check if the light selected in the previous frame no longer exists in the current frame (e.g. entity despawned)
|
||||
if temporal.reservoir.light_sample.light_id != NULL_LIGHT_ID {
|
||||
let previous_light_id = temporal.reservoir.light_sample.light_id >> 16u;
|
||||
let triangle_id = temporal.reservoir.light_sample.light_id & 0xFFFFu;
|
||||
let light_id = previous_frame_light_id_translations[previous_light_id];
|
||||
if light_id == LIGHT_NOT_PRESENT_THIS_FRAME {
|
||||
return NeighborInfo(empty_reservoir(), vec3(0.0), vec3(0.0), empty_material());
|
||||
}
|
||||
temporal.reservoir.light_sample.light_id = (light_id << 16u) | triangle_id;
|
||||
}
|
||||
|
||||
temporal.reservoir.confidence_weight = min(temporal.reservoir.confidence_weight, constants.confidence_weight_cap);
|
||||
|
||||
return temporal;
|
||||
}
|
||||
|
||||
fn load_spatial_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3<f32>, world_normal: vec3<f32>, rng: ptr<function, u32>) -> NeighborInfo {
|
||||
for (var i = 0u; i < 5u; i++) {
|
||||
let spatial_pixel_id = get_neighbor_pixel_id(pixel_id, SPATIAL_REUSE_RADIUS_PIXELS, rng);
|
||||
|
||||
if all(spatial_pixel_id == pixel_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let spatial_depth = textureLoad(depth_buffer, spatial_pixel_id, 0);
|
||||
let spatial_surface = gpixel_resolve(textureLoad(gbuffer, spatial_pixel_id, 0), spatial_depth, spatial_pixel_id, view.main_pass_viewport.zw, view.world_from_clip);
|
||||
if pixel_dissimilar(depth, world_position, spatial_surface.world_position, world_normal, spatial_surface.world_normal, view) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let spatial_pixel_index = spatial_pixel_id.x + spatial_pixel_id.y * u32(view.main_pass_viewport.z);
|
||||
return NeighborInfo(reservoirs_b[spatial_pixel_index], spatial_surface.world_position, spatial_surface.world_normal, spatial_surface.material);
|
||||
}
|
||||
|
||||
return NeighborInfo(empty_reservoir(), world_position, world_normal, empty_material());
|
||||
}
|
||||
|
||||
fn get_neighbor_pixel_id(center_pixel_id: vec2<u32>, search_radius: f32, rng: ptr<function, u32>) -> vec2<u32> {
|
||||
var spatial_id = vec2<f32>(center_pixel_id) + sample_disk(search_radius, rng);
|
||||
spatial_id = clamp(spatial_id, vec2(0.0), view.main_pass_viewport.zw - 1.0);
|
||||
return vec2<u32>(spatial_id);
|
||||
}
|
||||
|
||||
struct NeighborInfo {
|
||||
reservoir: Reservoir,
|
||||
world_position: vec3<f32>,
|
||||
world_normal: vec3<f32>,
|
||||
material: ResolvedMaterial,
|
||||
}
|
||||
|
||||
fn empty_material() -> ResolvedMaterial {
|
||||
return ResolvedMaterial(vec3(0.0), vec3(0.0), 0.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
|
||||
fn jacobian(
|
||||
new_world_position: vec3<f32>,
|
||||
original_world_position: vec3<f32>,
|
||||
sample_point_world_position: vec3<f32>,
|
||||
sample_point_world_normal: vec3<f32>,
|
||||
) -> f32 {
|
||||
let r = new_world_position - sample_point_world_position;
|
||||
let q = original_world_position - sample_point_world_position;
|
||||
let rl = length(r);
|
||||
let ql = length(q);
|
||||
let phi_r = saturate(dot(r / rl, sample_point_world_normal));
|
||||
let phi_q = saturate(dot(q / ql, sample_point_world_normal));
|
||||
let jacobian = (phi_r * ql * ql) / (phi_q * rl * rl);
|
||||
return select(jacobian, 0.0, isinf(jacobian) || isnan(jacobian));
|
||||
}
|
||||
|
||||
struct ReservoirMergeResult {
|
||||
merged_reservoir: Reservoir,
|
||||
selected_sample_brdf_radiance: vec3<f32>,
|
||||
}
|
||||
|
||||
fn merge_reservoirs(
|
||||
canonical_reservoir: Reservoir,
|
||||
canonical_world_position: vec3<f32>,
|
||||
canonical_world_normal: vec3<f32>,
|
||||
canonical_material: ResolvedMaterial,
|
||||
other_reservoir: Reservoir,
|
||||
other_world_position: vec3<f32>,
|
||||
other_world_normal: vec3<f32>,
|
||||
other_material: ResolvedMaterial,
|
||||
other_view_position: vec3<f32>,
|
||||
rng: ptr<function, u32>,
|
||||
) -> ReservoirMergeResult {
|
||||
var canonical_resolved: ResolvedLightSample;
|
||||
if canonical_reservoir.light_sample.light_id != NULL_LIGHT_ID {
|
||||
canonical_resolved = resolve_light_sample(canonical_reservoir.light_sample, light_sources[canonical_reservoir.light_sample.light_id >> 16u]);
|
||||
}
|
||||
|
||||
let canonical_wo = normalize(view.world_position - canonical_world_position);
|
||||
let canonical_NdotV = max(dot(canonical_world_normal, canonical_wo), 0.0001);
|
||||
let canonical_F_ab = F_AB(canonical_material.perceptual_roughness, canonical_NdotV);
|
||||
let canonical_sample_at_canonical = reservoir_contribution(canonical_reservoir, canonical_resolved, canonical_world_position, canonical_world_normal, canonical_wo, canonical_material, canonical_F_ab);
|
||||
|
||||
// Skip resampling empty reservoirs
|
||||
if other_reservoir.confidence_weight == 0.0 {
|
||||
return ReservoirMergeResult(canonical_reservoir, canonical_sample_at_canonical.brdf_radiance);
|
||||
}
|
||||
|
||||
var other_resolved: ResolvedLightSample;
|
||||
if other_reservoir.light_sample.light_id != NULL_LIGHT_ID {
|
||||
other_resolved = resolve_light_sample(other_reservoir.light_sample, light_sources[other_reservoir.light_sample.light_id >> 16u]);
|
||||
}
|
||||
let other_wo = normalize(other_view_position - other_world_position);
|
||||
let other_NdotV = max(dot(other_world_normal, other_wo), 0.0001);
|
||||
let other_F_ab = F_AB(other_material.perceptual_roughness, other_NdotV);
|
||||
|
||||
// Contributions for resampling and MIS
|
||||
var other_sample_at_canonical = reservoir_contribution(other_reservoir, other_resolved, canonical_world_position, canonical_world_normal, canonical_wo, canonical_material, canonical_F_ab);
|
||||
var canonical_sample_at_other = reservoir_contribution(canonical_reservoir, canonical_resolved, other_world_position, other_world_normal, other_wo, other_material, other_F_ab);
|
||||
let other_sample_at_other = reservoir_contribution(other_reservoir, other_resolved, other_world_position, other_world_normal, other_wo, other_material, other_F_ab);
|
||||
|
||||
// Jacobians for resampling and MIS. Light samples don't need a reprojection jacobian,
|
||||
// since calculate_resolved_light_contribution already accounts for the shading point's geometry.
|
||||
var other_sample_at_canonical_jacobian = 1.0;
|
||||
if other_reservoir.light_sample.light_id == NULL_LIGHT_ID {
|
||||
other_sample_at_canonical_jacobian = jacobian(
|
||||
canonical_world_position,
|
||||
other_world_position,
|
||||
other_reservoir.sample_point_world_position,
|
||||
octahedral_decode(other_reservoir.sample_point_world_normal)
|
||||
);
|
||||
}
|
||||
var canonical_sample_at_other_jacobian = 1.0;
|
||||
if canonical_reservoir.light_sample.light_id == NULL_LIGHT_ID {
|
||||
canonical_sample_at_other_jacobian = jacobian(
|
||||
other_world_position,
|
||||
canonical_world_position,
|
||||
canonical_reservoir.sample_point_world_position,
|
||||
octahedral_decode(canonical_reservoir.sample_point_world_normal)
|
||||
);
|
||||
}
|
||||
|
||||
// Don't merge samples with huge jacobians, as it explodes the variance
|
||||
if other_sample_at_canonical_jacobian < 0.125 || other_sample_at_canonical_jacobian > 8.0 {
|
||||
other_sample_at_canonical_jacobian = 0.0;
|
||||
}
|
||||
if canonical_sample_at_other_jacobian < 0.125 || canonical_sample_at_other_jacobian > 8.0 {
|
||||
canonical_sample_at_other_jacobian = 0.0;
|
||||
}
|
||||
|
||||
// Visibility for the cross-domain targets
|
||||
if other_sample_at_canonical.target_function > 0.0 && other_sample_at_canonical_jacobian > 0.0 {
|
||||
let visibility = trace_visibility(canonical_world_position + canonical_world_normal * RAY_T_MIN, other_sample_at_canonical.sample_world_position);
|
||||
other_sample_at_canonical.target_function *= visibility;
|
||||
}
|
||||
if canonical_sample_at_other.target_function > 0.0 && canonical_sample_at_other_jacobian > 0.0 {
|
||||
@if(SPATIAL_MERGE)
|
||||
let visibility = trace_visibility(other_world_position + other_world_normal * RAY_T_MIN, canonical_sample_at_other.sample_world_position);
|
||||
@else
|
||||
let visibility = trace_visibility_previous_frame(other_world_position + other_world_normal * RAY_T_MIN, canonical_sample_at_other.sample_world_position);
|
||||
canonical_sample_at_other.target_function *= visibility;
|
||||
}
|
||||
|
||||
// Defensive balance heuristic MIS (for spatial reuse only)
|
||||
let total_confidence_weight = canonical_reservoir.confidence_weight + other_reservoir.confidence_weight;
|
||||
var defensive_t_c = 0.0;
|
||||
@if(SPATIAL_MERGE)
|
||||
defensive_t_c = select(1.0, canonical_reservoir.confidence_weight / total_confidence_weight, total_confidence_weight > 0.0);
|
||||
|
||||
// Resampling weight for canonical sample
|
||||
let canonical_balance_mis_weight = balance_heuristic(
|
||||
canonical_reservoir.confidence_weight * canonical_sample_at_canonical.target_function,
|
||||
other_reservoir.confidence_weight * canonical_sample_at_other.target_function * canonical_sample_at_other_jacobian,
|
||||
);
|
||||
let canonical_sample_mis_weight = mix(canonical_balance_mis_weight, 1.0, defensive_t_c);
|
||||
let canonical_sample_resampling_weight = canonical_sample_mis_weight * canonical_sample_at_canonical.target_function * canonical_reservoir.unbiased_contribution_weight;
|
||||
|
||||
// Resampling weight for other sample
|
||||
let other_balance_mis_weight = balance_heuristic(
|
||||
other_reservoir.confidence_weight * other_sample_at_other.target_function,
|
||||
canonical_reservoir.confidence_weight * other_sample_at_canonical.target_function * other_sample_at_canonical_jacobian,
|
||||
);
|
||||
let other_sample_mis_weight = mix(other_balance_mis_weight, 0.0, defensive_t_c);
|
||||
let other_sample_resampling_weight = other_sample_mis_weight * other_sample_at_canonical.target_function * other_reservoir.unbiased_contribution_weight * other_sample_at_canonical_jacobian;
|
||||
|
||||
// Perform resampling
|
||||
var combined_reservoir = empty_reservoir();
|
||||
combined_reservoir.confidence_weight = canonical_reservoir.confidence_weight + other_reservoir.confidence_weight;
|
||||
let weight_sum = canonical_sample_resampling_weight + other_sample_resampling_weight;
|
||||
|
||||
if rand_f(rng) * weight_sum < other_sample_resampling_weight {
|
||||
combined_reservoir.sample_point_world_position = other_reservoir.sample_point_world_position;
|
||||
combined_reservoir.sample_point_world_normal = other_reservoir.sample_point_world_normal;
|
||||
combined_reservoir.radiance = other_reservoir.radiance;
|
||||
combined_reservoir.light_sample = other_reservoir.light_sample;
|
||||
|
||||
let inverse_target_function = select(0.0, 1.0 / other_sample_at_canonical.target_function, other_sample_at_canonical.target_function > 0.0);
|
||||
combined_reservoir.unbiased_contribution_weight = weight_sum * inverse_target_function;
|
||||
|
||||
return ReservoirMergeResult(combined_reservoir, other_sample_at_canonical.brdf_radiance);
|
||||
} else {
|
||||
combined_reservoir.sample_point_world_position = canonical_reservoir.sample_point_world_position;
|
||||
combined_reservoir.sample_point_world_normal = canonical_reservoir.sample_point_world_normal;
|
||||
combined_reservoir.radiance = canonical_reservoir.radiance;
|
||||
combined_reservoir.light_sample = canonical_reservoir.light_sample;
|
||||
|
||||
let inverse_target_function = select(0.0, 1.0 / canonical_sample_at_canonical.target_function, canonical_sample_at_canonical.target_function > 0.0);
|
||||
combined_reservoir.unbiased_contribution_weight = weight_sum * inverse_target_function;
|
||||
|
||||
return ReservoirMergeResult(combined_reservoir, canonical_sample_at_canonical.brdf_radiance);
|
||||
}
|
||||
}
|
||||
|
||||
struct ReservoirContribution {
|
||||
brdf_radiance: vec3<f32>,
|
||||
target_function: f32,
|
||||
sample_world_position: vec4<f32>,
|
||||
}
|
||||
|
||||
fn reservoir_contribution(reservoir: Reservoir, resolved: ResolvedLightSample, world_position: vec3<f32>, world_normal: vec3<f32>, wo: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> ReservoirContribution {
|
||||
if reservoir.light_sample.light_id != NULL_LIGHT_ID {
|
||||
let light_contribution = calculate_resolved_light_contribution(resolved, world_position, world_normal);
|
||||
|
||||
// MIS weight against the bounce-0 BRDF-emissive strategy, recomputed from this surface's
|
||||
// brdf and material rather than baked into the unbiased contribution weight at generation. Mirrors the bounce-0
|
||||
// nee_mis_weight in generate_nee_candidate and generate_emissive_candidate, which puts the same factor in the target.
|
||||
var nee_mis_weight = 1.0;
|
||||
if light_contribution.brdf_rays_can_hit && light_contribution.inverse_solid_angle_pdf > 0.0 {
|
||||
let light_count = arrayLength(&light_sources);
|
||||
let inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf * f32(light_count);
|
||||
let p_nee = mix(1.0, material.perceptual_roughness, material.metallic);
|
||||
let p_nee_strategy = f32(constants.primary_di_samples) * (1.0 / inverse_solid_angle_pdf) * p_nee;
|
||||
let p_brdf_at_nee = brdf_pdf(wo, light_contribution.wi, world_normal, material, F_ab);
|
||||
nee_mis_weight = power_heuristic(p_nee_strategy, p_brdf_at_nee);
|
||||
}
|
||||
|
||||
let brdf_radiance = light_contribution.radiance * evaluate_brdf(wo, light_contribution.wi, world_normal, material, F_ab) * nee_mis_weight;
|
||||
return ReservoirContribution(brdf_radiance, luminance(brdf_radiance), resolved.world_position);
|
||||
} else if any(reservoir.radiance != vec3(0.0)) {
|
||||
let delta = reservoir.sample_point_world_position - (world_position + world_normal * RAY_T_MIN);
|
||||
let sample_distance = length(delta);
|
||||
let wi = delta / sample_distance;
|
||||
var brdf_radiance = reservoir.radiance * evaluate_brdf(wo, wi, world_normal, material, F_ab);
|
||||
|
||||
// Bounce-0 BRDF-emissive sample (directly-visible light). The seed field carries the light
|
||||
// triangle's bitcast area pdf, and the stored radiance is the raw emission. Rebuild the MIS
|
||||
// weight against this surface's NEE strategy, the dual of nee_mis_weight above and a mirror
|
||||
// of the emissive candidate in generate_initial_path.
|
||||
if reservoir.light_sample.seed != 0u {
|
||||
let area_pdf = bitcast<f32>(reservoir.light_sample.seed);
|
||||
let light_normal = octahedral_decode(reservoir.sample_point_world_normal);
|
||||
let cos_theta_light = dot(-wi, light_normal);
|
||||
if cos_theta_light <= 0.0 {
|
||||
brdf_radiance = vec3(0.0);
|
||||
} else {
|
||||
let p_light = area_pdf * sample_distance * sample_distance / cos_theta_light;
|
||||
let p_nee = mix(1.0, material.perceptual_roughness, material.metallic);
|
||||
let p_brdf = brdf_pdf(wo, wi, world_normal, material, F_ab);
|
||||
brdf_radiance *= power_heuristic(p_brdf, p_light * p_nee * f32(constants.primary_di_samples));
|
||||
}
|
||||
}
|
||||
|
||||
return ReservoirContribution(brdf_radiance, luminance(brdf_radiance), vec4(reservoir.sample_point_world_position, 1.0));
|
||||
} else {
|
||||
return ReservoirContribution(vec3(0.0), 0.0, vec4(reservoir.sample_point_world_position, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import package::realtime::world_cache_query::WORLD_CACHE_EMPTY_CELL;
|
||||
import package::realtime::bindings::{
|
||||
world_cache,
|
||||
};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@group(2) @binding(0) var<storage, read_write> world_cache_active_cells_dispatch: vec3<u32>;
|
||||
|
||||
var<workgroup> w1: array<u32, 1024u>;
|
||||
var<workgroup> w2: array<u32, 1024u>;
|
||||
|
||||
@compute @workgroup_size(1024, 1, 1)
|
||||
fn decay_world_cache(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
var life = world_cache.life[global_id.x];
|
||||
if life > 0u {
|
||||
life -= 1u;
|
||||
world_cache.life[global_id.x] = life;
|
||||
|
||||
if life == 0u {
|
||||
world_cache.checksums[global_id.x] = WORLD_CACHE_EMPTY_CELL;
|
||||
world_cache.radiance[global_id.x] = vec4(0.0);
|
||||
world_cache.luminance_deltas[global_id.x] = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@compute @workgroup_size(1024, 1, 1)
|
||||
fn compact_world_cache_single_block(
|
||||
@builtin(global_invocation_id) cell_id: vec3<u32>,
|
||||
@builtin(local_invocation_index) t: u32,
|
||||
) {
|
||||
if t == 0u { w1[0u] = 0u; } else { w1[t] = u32(world_cache.life[cell_id.x - 1u] != 0u); }; workgroupBarrier();
|
||||
if t < 1u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 1u]; } workgroupBarrier();
|
||||
if t < 2u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 2u]; } workgroupBarrier();
|
||||
if t < 4u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 4u]; } workgroupBarrier();
|
||||
if t < 8u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 8u]; } workgroupBarrier();
|
||||
if t < 16u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 16u]; } workgroupBarrier();
|
||||
if t < 32u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 32u]; } workgroupBarrier();
|
||||
if t < 64u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 64u]; } workgroupBarrier();
|
||||
if t < 128u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 128u]; } workgroupBarrier();
|
||||
if t < 256u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 256u]; } workgroupBarrier();
|
||||
if t < 512u { world_cache.a[cell_id.x] = w2[t]; } else { world_cache.a[cell_id.x] = w2[t] + w2[t - 512u]; }
|
||||
}
|
||||
|
||||
@compute @workgroup_size(1024, 1, 1)
|
||||
fn compact_world_cache_blocks(@builtin(local_invocation_index) t: u32) {
|
||||
if t == 0u { w1[0u] = 0u; } else { w1[t] = world_cache.a[t * 1024u - 1u] + u32(world_cache.life[t * 1024u - 1u] != 0u); }; workgroupBarrier();
|
||||
if t < 1u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 1u]; } workgroupBarrier();
|
||||
if t < 2u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 2u]; } workgroupBarrier();
|
||||
if t < 4u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 4u]; } workgroupBarrier();
|
||||
if t < 8u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 8u]; } workgroupBarrier();
|
||||
if t < 16u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 16u]; } workgroupBarrier();
|
||||
if t < 32u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 32u]; } workgroupBarrier();
|
||||
if t < 64u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 64u]; } workgroupBarrier();
|
||||
if t < 128u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 128u]; } workgroupBarrier();
|
||||
if t < 256u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 256u]; } workgroupBarrier();
|
||||
if t < 512u { world_cache.b[t] = w2[t]; } else { world_cache.b[t] = w2[t] + w2[t - 512u]; }
|
||||
}
|
||||
|
||||
@compute @workgroup_size(1024, 1, 1)
|
||||
fn compact_world_cache_write_active_cells(
|
||||
@builtin(global_invocation_id) cell_id: vec3<u32>,
|
||||
@builtin(workgroup_id) workgroup_id: vec3<u32>,
|
||||
@builtin(local_invocation_index) thread_index: u32,
|
||||
) {
|
||||
let compacted_index = world_cache.a[cell_id.x] + world_cache.b[workgroup_id.x];
|
||||
let cell_active = world_cache.life[cell_id.x] != 0u;
|
||||
|
||||
if cell_active {
|
||||
world_cache.active_cell_indices[compacted_index] = cell_id.x;
|
||||
}
|
||||
|
||||
if thread_index == 1023u && workgroup_id.x == 1023u {
|
||||
let active_cell_count = compacted_index + u32(cell_active);
|
||||
world_cache.active_cells_count = active_cell_count;
|
||||
world_cache_active_cells_dispatch = vec3((active_cell_count + 63u) / 64u, 1u, 1u);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import constants::WORLD_CACHE_SIZE;
|
||||
import bevy_pbr::render::utils::{rand_f, rand_vec2f};
|
||||
import bevy_render::maths::orthonormalize;
|
||||
import package::realtime::bindings::{
|
||||
world_cache,
|
||||
constants,
|
||||
};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
/// Maximum amount of frames a cell can live for without being queried
|
||||
const WORLD_CACHE_CELL_LIFETIME: u32 = 10u;
|
||||
/// Maximum amount of attempts to find a cache entry after a hash collision
|
||||
const WORLD_CACHE_MAX_SEARCH_STEPS: u32 = 3u;
|
||||
|
||||
/// Marker value for an empty cell
|
||||
const WORLD_CACHE_EMPTY_CELL: u32 = 0u;
|
||||
|
||||
@if(!WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER)
|
||||
fn query_world_cache(world_position_in: vec3<f32>, world_normal: vec3<f32>, view_position: vec3<f32>, ray_t: f32, cell_lifetime: u32, rng: ptr<function, u32>) -> vec3<f32> {
|
||||
var world_position = world_position_in;
|
||||
var cell_size = get_cell_size(world_position, view_position, ray_t, rng);
|
||||
|
||||
@if(!NO_JITTER_WORLD_CACHE) {
|
||||
// Jitter query point, which essentially blurs the cache a bit so it's not so grid-like
|
||||
// https://tomclabault.github.io/blog/2025/regir, jitter_world_position_tangent_plane
|
||||
let TBN = orthonormalize(world_normal);
|
||||
let offset = (rand_vec2f(rng) * 2.0 - 1.0) * cell_size * 0.5;
|
||||
world_position += offset.x * TBN[0] + offset.y * TBN[1];
|
||||
cell_size = get_cell_size(world_position, view_position, ray_t, rng);
|
||||
}
|
||||
|
||||
let world_position_quantized = bitcast<vec3<u32>>(quantize_position(world_position, cell_size));
|
||||
let world_normal_quantized = bitcast<vec3<u32>>(quantize_normal(world_normal));
|
||||
var key = compute_key(world_position_quantized, world_normal_quantized);
|
||||
let checksum = compute_checksum(world_position_quantized, world_normal_quantized);
|
||||
|
||||
for (var i = 0u; i < WORLD_CACHE_MAX_SEARCH_STEPS; i++) {
|
||||
let cas = atomicCompareExchangeWeak(&world_cache.checksums[key], WORLD_CACHE_EMPTY_CELL, checksum);
|
||||
let existing_checksum = cas.old_value;
|
||||
|
||||
// Cell already exists or is empty - reset lifetime
|
||||
if existing_checksum == checksum || existing_checksum == WORLD_CACHE_EMPTY_CELL {
|
||||
@if(!WORLD_CACHE_QUERY_ATOMIC_MAX_LIFETIME)
|
||||
atomicStore(&world_cache.life[key], cell_lifetime);
|
||||
@else
|
||||
atomicMax(&world_cache.life[key], cell_lifetime);
|
||||
}
|
||||
|
||||
if existing_checksum == checksum {
|
||||
// Cache entry already exists - get radiance
|
||||
return world_cache.radiance[key].rgb;
|
||||
} else if existing_checksum == WORLD_CACHE_EMPTY_CELL && cas.exchanged {
|
||||
// Cell is empty - initialize it
|
||||
world_cache.geometry_data[key].world_position = world_position;
|
||||
world_cache.geometry_data[key].world_normal = world_normal;
|
||||
return vec3(0.0);
|
||||
} else {
|
||||
// Collision - linear probe to next entry
|
||||
key += 1u;
|
||||
}
|
||||
}
|
||||
|
||||
return vec3(0.0);
|
||||
}
|
||||
|
||||
fn get_cell_size(world_position: vec3<f32>, view_position: vec3<f32>, ray_t: f32, rng: ptr<function, u32>) -> f32 {
|
||||
let camera_distance = distance(view_position, world_position) / constants.world_cache_position_lod_scale;
|
||||
let lod_f = log2(1.0 + camera_distance);
|
||||
let lod_fract = fract(lod_f);
|
||||
let lod = floor(lod_f) + select(0.0, 1.0, rand_f(rng) < lod_fract * lod_fract * lod_fract);
|
||||
return constants.world_cache_position_base_cell_size * exp2(lod);
|
||||
}
|
||||
|
||||
fn quantize_position(world_position: vec3<f32>, quantization_factor: f32) -> vec3<f32> {
|
||||
return floor(world_position / quantization_factor + 0.0001);
|
||||
}
|
||||
|
||||
fn quantize_normal(world_normal: vec3<f32>) -> vec3<f32> {
|
||||
return floor(world_normal + 0.0001);
|
||||
}
|
||||
|
||||
fn compute_key(world_position: vec3<u32>, world_normal: vec3<u32>) -> u32 {
|
||||
var key = pcg_hash(world_position.x);
|
||||
key = pcg_hash(key + world_position.y);
|
||||
key = pcg_hash(key + world_position.z);
|
||||
key = pcg_hash(key + world_normal.x);
|
||||
key = pcg_hash(key + world_normal.y);
|
||||
key = pcg_hash(key + world_normal.z);
|
||||
return wrap_key(key);
|
||||
}
|
||||
|
||||
fn compute_checksum(world_position: vec3<u32>, world_normal: vec3<u32>) -> u32 {
|
||||
var key = iqint_hash(world_position.x);
|
||||
key = iqint_hash(key + world_position.y);
|
||||
key = iqint_hash(key + world_position.z);
|
||||
key = iqint_hash(key + world_normal.x);
|
||||
key = iqint_hash(key + world_normal.y);
|
||||
key = iqint_hash(key + world_normal.z);
|
||||
return max(key, 1u); // 0u is reserved for WORLD_CACHE_EMPTY_CELL
|
||||
}
|
||||
|
||||
fn pcg_hash(input: u32) -> u32 {
|
||||
let state = input * 747796405u + 2891336453u;
|
||||
let word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
|
||||
return (word >> 22u) ^ word;
|
||||
}
|
||||
|
||||
fn iqint_hash(input: u32) -> u32 {
|
||||
let n = (input << 13u) ^ input;
|
||||
return n * (n * n * 15731u + 789221u) + 1376312589u;
|
||||
}
|
||||
|
||||
fn wrap_key(key: u32) -> u32 {
|
||||
return key & (u32(WORLD_CACHE_SIZE) - 1u);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
|
||||
import bevy_pbr::render::utils::{rand_f, rand_range_u, sample_cosine_hemisphere};
|
||||
import bevy_render::maths::PI;
|
||||
import package::realtime::presample_light_tiles::unpack_resolved_light_sample;
|
||||
import package::scene::sampling::{calculate_resolved_light_contribution, trace_visibility, sample_environment_map_light};
|
||||
import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN};
|
||||
import package::realtime::world_cache_query::query_world_cache;
|
||||
import package::realtime::bindings::{
|
||||
light_tile_resolved_samples,
|
||||
view,
|
||||
constants,
|
||||
world_cache,
|
||||
};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@compute @workgroup_size(64, 1, 1)
|
||||
fn sample_di(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) active_cell_id: vec3<u32>) {
|
||||
if active_cell_id.x >= world_cache.active_cells_count { return; }
|
||||
|
||||
let cell_index = world_cache.active_cell_indices[active_cell_id.x];
|
||||
let geometry_data = world_cache.geometry_data[cell_index];
|
||||
var rng = cell_index + constants.frame_rng;
|
||||
|
||||
if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
|
||||
|
||||
let new_radiance = sample_random_light_ris(geometry_data.world_position, geometry_data.world_normal, workgroup_id.xy, &rng);
|
||||
|
||||
world_cache.active_cells_new_radiance[active_cell_id.x] = new_radiance;
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64, 1, 1)
|
||||
fn sample_gi(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) active_cell_id: vec3<u32>) {
|
||||
if active_cell_id.x >= world_cache.active_cells_count { return; }
|
||||
|
||||
let cell_index = world_cache.active_cell_indices[active_cell_id.x];
|
||||
let geometry_data = world_cache.geometry_data[cell_index];
|
||||
var rng = cell_index + constants.frame_rng;
|
||||
|
||||
if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
|
||||
|
||||
let ray_direction = sample_cosine_hemisphere(geometry_data.world_normal, &rng);
|
||||
let ray = trace_ray(geometry_data.world_position + (geometry_data.world_normal * RAY_T_MIN), ray_direction, RAY_T_MIN, constants.world_cache_max_gi_ray_distance, RAY_FLAG_NONE);
|
||||
if ray.kind != RAY_QUERY_INTERSECTION_NONE {
|
||||
let ray_hit = resolve_ray_hit_full(ray);
|
||||
let cell_life = atomicLoad(&world_cache.life[cell_index]);
|
||||
let radiance = query_world_cache(ray_hit.world_position, ray_hit.geometric_world_normal, view.world_position, ray.t, cell_life, &rng);
|
||||
world_cache.active_cells_new_radiance[active_cell_id.x] += ray_hit.material.base_color * radiance;
|
||||
} else {
|
||||
// The ray is cut short at world_cache_max_gi_ray_distance to save on traversal costs.
|
||||
// A miss here may actually have been a surface further away if we kept tracing, and not actually have been a miss.
|
||||
// We could be leaking sky light due to this if world_cache_max_gi_ray_distance is too small.
|
||||
world_cache.active_cells_new_radiance[active_cell_id.x] += PI * sample_environment_map_light(ray_direction);
|
||||
}
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64, 1, 1)
|
||||
fn blend_new_samples(@builtin(global_invocation_id) active_cell_id: vec3<u32>) {
|
||||
if active_cell_id.x >= world_cache.active_cells_count { return; }
|
||||
|
||||
let cell_index = world_cache.active_cell_indices[active_cell_id.x];
|
||||
var rng = cell_index + constants.frame_rng;
|
||||
|
||||
if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
|
||||
|
||||
let old_radiance = world_cache.radiance[cell_index];
|
||||
let new_radiance = world_cache.active_cells_new_radiance[active_cell_id.x];
|
||||
let luminance_delta = world_cache.luminance_deltas[cell_index];
|
||||
|
||||
// https://bsky.app/profile/gboisse.bsky.social/post/3m5blga3ftk2a
|
||||
let sample_count = min(old_radiance.a + 1.0, constants.world_cache_max_temporal_samples);
|
||||
let alpha = abs(luminance_delta) / max(luminance(old_radiance.rgb), 0.001);
|
||||
let max_sample_count = mix(constants.world_cache_max_temporal_samples, 1.0, pow(saturate(alpha), 1.0 / 8.0));
|
||||
var blend_amount = 1.0 / min(sample_count, max_sample_count);
|
||||
if bool(constants.reset) {
|
||||
blend_amount = 1.0;
|
||||
}
|
||||
|
||||
let blended_radiance = mix(old_radiance.rgb, new_radiance, blend_amount);
|
||||
let blended_luminance_delta = select(mix(luminance_delta, luminance(blended_radiance) - luminance(old_radiance.rgb), 1.0 / 8.0), 0.0, bool(constants.reset));
|
||||
|
||||
world_cache.radiance[cell_index] = vec4(blended_radiance, sample_count);
|
||||
world_cache.luminance_deltas[cell_index] = blended_luminance_delta;
|
||||
}
|
||||
|
||||
fn sample_random_light_ris(world_position: vec3<f32>, world_normal: vec3<f32>, workgroup_id: vec2<u32>, rng: ptr<function, u32>) -> vec3<f32> {
|
||||
var workgroup_rng = (workgroup_id.x * 5782582u) + workgroup_id.y;
|
||||
let light_tile_start = rand_range_u(128u, &workgroup_rng) * 1024u;
|
||||
|
||||
var weight_sum = 0.0;
|
||||
var selected_sample_radiance = vec3(0.0);
|
||||
var selected_sample_target_function = 0.0;
|
||||
var selected_sample_world_position = vec4(0.0);
|
||||
let mis_weight = 1.0 / f32(constants.world_cache_direct_light_sample_count);
|
||||
for (var i = 0u; i < constants.world_cache_direct_light_sample_count; i++) {
|
||||
let tile_sample = light_tile_start + rand_range_u(1024u, rng);
|
||||
let resolved_light_sample = unpack_resolved_light_sample(light_tile_resolved_samples[tile_sample], view.exposure);
|
||||
let light_contribution = calculate_resolved_light_contribution(resolved_light_sample, world_position, world_normal);
|
||||
|
||||
let contribution = light_contribution.radiance * saturate(dot(light_contribution.wi, world_normal));
|
||||
let target_function = luminance(contribution);
|
||||
let resampling_weight = mis_weight * (target_function * light_contribution.inverse_pdf);
|
||||
|
||||
weight_sum += resampling_weight;
|
||||
|
||||
if rand_f(rng) * weight_sum < resampling_weight {
|
||||
selected_sample_radiance = contribution;
|
||||
selected_sample_target_function = target_function;
|
||||
selected_sample_world_position = resolved_light_sample.world_position;
|
||||
}
|
||||
}
|
||||
|
||||
var unbiased_contribution_weight = 0.0;
|
||||
if any(selected_sample_radiance != vec3(0.0)) {
|
||||
let inverse_target_function = select(0.0, 1.0 / selected_sample_target_function, selected_sample_target_function > 0.0);
|
||||
unbiased_contribution_weight = weight_sum * inverse_target_function;
|
||||
|
||||
unbiased_contribution_weight *= trace_visibility(world_position + (world_normal * RAY_T_MIN), selected_sample_world_position);
|
||||
}
|
||||
|
||||
return selected_sample_radiance * unbiased_contribution_weight;
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use bevy_platform::collections::HashMap;
|
||||
use core::{hash::Hash, num::NonZeroU32};
|
||||
|
||||
/// A free-list allocator for `u32` array indices meant for GPU allocations.
|
||||
pub struct IndexAllocator {
|
||||
free: Vec<u32>,
|
||||
high_water_mark: u32,
|
||||
}
|
||||
|
||||
impl IndexAllocator {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
free: Vec::new(),
|
||||
high_water_mark: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn high_water_mark(&self) -> u32 {
|
||||
self.high_water_mark
|
||||
}
|
||||
|
||||
pub fn allocate(&mut self) -> u32 {
|
||||
self.free.pop().unwrap_or_else(|| {
|
||||
let index = self.high_water_mark;
|
||||
self.high_water_mark += 1;
|
||||
index
|
||||
})
|
||||
}
|
||||
|
||||
pub fn release(&mut self, index: u32) {
|
||||
self.free.push(index);
|
||||
}
|
||||
|
||||
/// How many more indices can be handed out before running past `capacity`.
|
||||
fn vacancies(&self, capacity: u32) -> u32 {
|
||||
capacity.saturating_sub(self.high_water_mark) + self.free.len() as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// Assigns each key an index that stays put for as long as the key is live.
|
||||
pub struct SlotAllocator<K> {
|
||||
slots: HashMap<K, u32>,
|
||||
indices: IndexAllocator,
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash> SlotAllocator<K> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: HashMap::default(),
|
||||
indices: IndexAllocator::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &K) -> Option<u32> {
|
||||
self.slots.get(key).copied()
|
||||
}
|
||||
|
||||
pub fn contains(&self, key: &K) -> bool {
|
||||
self.slots.contains_key(key)
|
||||
}
|
||||
|
||||
pub fn keys(&self) -> impl Iterator<Item = &K> {
|
||||
self.slots.keys()
|
||||
}
|
||||
|
||||
pub fn get_or_allocate(&mut self, key: K) -> u32 {
|
||||
if let Some(&slot) = self.slots.get(&key) {
|
||||
return slot;
|
||||
}
|
||||
|
||||
let slot = self.indices.allocate();
|
||||
self.slots.insert(key, slot);
|
||||
slot
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, key: &K) -> Option<u32> {
|
||||
let slot = self.slots.remove(key)?;
|
||||
self.indices.release(slot);
|
||||
Some(slot)
|
||||
}
|
||||
|
||||
/// How many more distinct keys can be taken on before running past `capacity`.
|
||||
fn vacancies(&self, capacity: u32) -> u32 {
|
||||
self.indices.vacancies(capacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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.
|
||||
///
|
||||
/// `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>>>,
|
||||
pub dirty: bool,
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
allocator: SlotAllocator::new(),
|
||||
slots: Vec::new(),
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(&self, key: &K) -> bool {
|
||||
self.allocator.contains(key)
|
||||
}
|
||||
|
||||
/// How many more distinct keys can be held before running past `capacity`.
|
||||
pub fn vacancies(&self, capacity: u32) -> u32 {
|
||||
self.allocator.vacancies(capacity)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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.
|
||||
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.
|
||||
///
|
||||
/// 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;
|
||||
}
|
||||
|
||||
let slot = self.allocator.get_or_allocate(key);
|
||||
let index = slot as usize;
|
||||
|
||||
if self.slots.len() <= index {
|
||||
self.slots.resize_with(index + 1, || None);
|
||||
}
|
||||
|
||||
if let Some(occupied) = self.slots[index].as_mut() {
|
||||
occupied.references = occupied.references.saturating_add(1);
|
||||
} else {
|
||||
self.slots[index] = Some(BindingSlot {
|
||||
item: item(),
|
||||
references: NonZeroU32::MIN,
|
||||
});
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
Some(slot)
|
||||
}
|
||||
|
||||
/// Drops a reference to `key`'s slot, freeing it if that was the last one.
|
||||
pub fn release(&mut self, key: &K) {
|
||||
let Some(slot) = self.allocator.get(key) else {
|
||||
return;
|
||||
};
|
||||
let index = slot as usize;
|
||||
let Some(occupied) = self.slots[index].as_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(remaining) = NonZeroU32::new(occupied.references.get() - 1) {
|
||||
occupied.references = remaining;
|
||||
return;
|
||||
}
|
||||
|
||||
self.slots[index] = None;
|
||||
self.allocator.remove(key);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// 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()
|
||||
{
|
||||
occupied.item = item;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{IndexAllocator, RetainedBindingArray};
|
||||
|
||||
#[test]
|
||||
fn index_allocator_reuses_released_slots_without_growing() {
|
||||
let mut slots = IndexAllocator::new();
|
||||
|
||||
assert_eq!(slots.allocate(), 0);
|
||||
assert_eq!(slots.allocate(), 1);
|
||||
assert_eq!(slots.high_water_mark(), 2);
|
||||
|
||||
slots.release(0);
|
||||
assert_eq!(slots.allocate(), 0);
|
||||
assert_eq!(slots.high_water_mark(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_binding_array_only_dirties_on_binding_changes() {
|
||||
let mut bindings = RetainedBindingArray::new();
|
||||
|
||||
assert_eq!(bindings.acquire(7, 2, || 11), Some(0));
|
||||
assert!(bindings.dirty);
|
||||
bindings.dirty = false;
|
||||
|
||||
// Sharing the existing stable slot only changes its refcount
|
||||
assert_eq!(bindings.acquire(7, 2, || 99), Some(0));
|
||||
assert!(!bindings.dirty);
|
||||
assert_eq!(bindings.iter().next(), Some(Some(&11)));
|
||||
|
||||
bindings.release(&7);
|
||||
assert!(!bindings.dirty);
|
||||
assert!(bindings.contains(&7));
|
||||
|
||||
// The final release changes the binding array and makes the slot reusable
|
||||
bindings.release(&7);
|
||||
assert!(bindings.dirty);
|
||||
assert!(!bindings.contains(&7));
|
||||
assert_eq!(bindings.acquire(8, 2, || 22), Some(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
use super::{
|
||||
allocator::{RetainedBindingArray, SlotAllocator},
|
||||
instances::InstanceState,
|
||||
StandardMaterialAssets,
|
||||
};
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_color::{ColorToComponents, LinearRgba};
|
||||
use bevy_image::Image;
|
||||
use bevy_math::Vec3;
|
||||
use bevy_pbr::StandardMaterial;
|
||||
use bevy_platform::collections::{HashMap, HashSet};
|
||||
use bevy_render::{
|
||||
impl_atomic_pod,
|
||||
render_asset::{ExtractedAssets, RenderAssets},
|
||||
render_resource::{AtomicPod, AtomicSparseBufferVec, BufferUsages, Sampler, TextureView},
|
||||
texture::GpuImage,
|
||||
};
|
||||
use bevy_utils::once;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core::num::NonZeroU32;
|
||||
use tracing::{info_span, warn};
|
||||
|
||||
pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap();
|
||||
const TEXTURE_MAP_NONE: u32 = u32::MAX;
|
||||
|
||||
/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`] field order.
|
||||
type MaterialTextures = [Option<AssetId<Image>>; 4];
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuMaterial {
|
||||
normal_map_texture_id: u32,
|
||||
base_color_texture_id: u32,
|
||||
emissive_texture_id: u32,
|
||||
metallic_roughness_texture_id: u32,
|
||||
|
||||
base_color: Vec3,
|
||||
perceptual_roughness: f32,
|
||||
emissive: Vec3,
|
||||
metallic: f32,
|
||||
_padding: Vec3,
|
||||
reflectance: f32,
|
||||
}
|
||||
|
||||
impl_atomic_pod!(GpuMaterial, GpuMaterialBlob);
|
||||
|
||||
/// 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>>,
|
||||
/// 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>>,
|
||||
}
|
||||
|
||||
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(),
|
||||
unresolved_materials: HashSet::default(),
|
||||
pending_texture_updates: HashSet::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_materials(
|
||||
&mut self,
|
||||
instances: &mut InstanceState,
|
||||
material_assets: &StandardMaterialAssets,
|
||||
texture_assets: &RenderAssets<GpuImage>,
|
||||
) {
|
||||
let _span = info_span!("update_materials").entered();
|
||||
|
||||
for material_id in &material_assets.removed {
|
||||
self.remove_material(*material_id, instances);
|
||||
}
|
||||
for material_id in &material_assets.changed {
|
||||
self.update_material(*material_id, instances, material_assets, texture_assets);
|
||||
}
|
||||
}
|
||||
|
||||
/// Swaps in uploaded replacements and retries materials waiting on images.
|
||||
pub fn update_textures(
|
||||
&mut self,
|
||||
instances: &mut InstanceState,
|
||||
extracted_images: &ExtractedAssets<GpuImage>,
|
||||
texture_assets: &RenderAssets<GpuImage>,
|
||||
material_assets: &StandardMaterialAssets,
|
||||
) {
|
||||
let _span = info_span!("update_textures").entered();
|
||||
|
||||
let mut pending = core::mem::take(&mut self.pending_texture_updates);
|
||||
pending.extend(extracted_images.added.iter().copied());
|
||||
|
||||
for image_id in pending {
|
||||
if !self.textures.contains(&image_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match texture_assets.get(image_id) {
|
||||
Some(image) => self.textures.replace(
|
||||
&image_id,
|
||||
(image.texture_view.clone(), image.sampler.clone()),
|
||||
),
|
||||
None => {
|
||||
self.pending_texture_updates.insert(image_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for material_id in core::mem::take(&mut self.unresolved_materials) {
|
||||
self.update_material(material_id, instances, material_assets, texture_assets);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a material's textures and writes it into its stable slot.
|
||||
fn update_material(
|
||||
&mut self,
|
||||
material_id: AssetId<StandardMaterial>,
|
||||
instances: &mut InstanceState,
|
||||
material_assets: &StandardMaterialAssets,
|
||||
texture_assets: &RenderAssets<GpuImage>,
|
||||
) {
|
||||
let Some(material) = material_assets.get(&material_id) else {
|
||||
self.remove_material(material_id, instances);
|
||||
return;
|
||||
};
|
||||
|
||||
let was_resolved = self.material_slots.contains(&material_id);
|
||||
let handles = [
|
||||
&material.normal_map_texture,
|
||||
&material.base_color_texture,
|
||||
&material.emissive_texture,
|
||||
&material.metallic_roughness_texture,
|
||||
];
|
||||
|
||||
// Resolve first so a missing texture leaves no partially acquired slots
|
||||
let mut textures: MaterialTextures = [None; 4];
|
||||
for (slot, handle) in textures.iter_mut().zip(handles) {
|
||||
let Some(handle) = handle else { continue };
|
||||
let image_id = handle.id();
|
||||
if texture_assets.get(image_id).is_none() {
|
||||
self.defer_material(material_id, instances);
|
||||
return;
|
||||
}
|
||||
*slot = Some(image_id);
|
||||
}
|
||||
|
||||
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
|
||||
self.release_material_textures(material_id);
|
||||
self.material_textures.remove(&material_id);
|
||||
|
||||
if self.new_texture_count(&textures) > self.textures.vacancies(MAX_TEXTURE_COUNT.get())
|
||||
{
|
||||
once!(warn!(
|
||||
"Solari scene needs more than {} textures. Materials past that limit will not \
|
||||
be rendered.",
|
||||
MAX_TEXTURE_COUNT.get()
|
||||
));
|
||||
self.defer_material(material_id, instances);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let mut texture_ids = [TEXTURE_MAP_NONE; 4];
|
||||
for (texture_id, image_id) in texture_ids.iter_mut().zip(textures) {
|
||||
let Some(image_id) = image_id else { continue };
|
||||
let image = texture_assets.get(image_id).unwrap();
|
||||
if let Some(slot) = self
|
||||
.textures
|
||||
.acquire(image_id, MAX_TEXTURE_COUNT.get(), || {
|
||||
(image.texture_view.clone(), image.sampler.clone())
|
||||
})
|
||||
{
|
||||
*texture_id = slot;
|
||||
}
|
||||
}
|
||||
|
||||
self.release_material_textures(material_id);
|
||||
self.material_textures.insert(material_id, textures);
|
||||
self.unresolved_materials.remove(&material_id);
|
||||
|
||||
let slot = self.material_slots.get_or_allocate(material_id);
|
||||
let emissive = material.emissive.to_vec3();
|
||||
let is_emissive = emissive != Vec3::ZERO;
|
||||
self.materials.grow_and_set(
|
||||
slot,
|
||||
GpuMaterial {
|
||||
normal_map_texture_id: texture_ids[0],
|
||||
base_color_texture_id: texture_ids[1],
|
||||
emissive_texture_id: texture_ids[2],
|
||||
metallic_roughness_texture_id: texture_ids[3],
|
||||
base_color: LinearRgba::from(material.base_color).to_vec3(),
|
||||
perceptual_roughness: material.perceptual_roughness.clamp(0.0, 1.0),
|
||||
emissive,
|
||||
metallic: material.metallic.clamp(0.0, 1.0),
|
||||
reflectance: material.reflectance,
|
||||
_padding: Vec3::ZERO,
|
||||
},
|
||||
);
|
||||
|
||||
let was_emissive = if is_emissive {
|
||||
!self.emissive_materials.insert(material_id)
|
||||
} else {
|
||||
self.emissive_materials.remove(&material_id)
|
||||
};
|
||||
if !was_resolved || was_emissive != is_emissive {
|
||||
instances.invalidate_material(material_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn new_texture_count(&self, textures: &MaterialTextures) -> u32 {
|
||||
let mut count = 0;
|
||||
for (index, image_id) in textures.iter().enumerate() {
|
||||
let Some(image_id) = image_id else { continue };
|
||||
let counted_already = textures[..index].contains(&Some(*image_id));
|
||||
if !counted_already && !self.textures.contains(image_id) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn defer_material(
|
||||
&mut self,
|
||||
material_id: AssetId<StandardMaterial>,
|
||||
instances: &mut InstanceState,
|
||||
) {
|
||||
self.remove_material(material_id, instances);
|
||||
self.unresolved_materials.insert(material_id);
|
||||
}
|
||||
|
||||
fn remove_material(
|
||||
&mut self,
|
||||
material_id: AssetId<StandardMaterial>,
|
||||
instances: &mut InstanceState,
|
||||
) {
|
||||
self.unresolved_materials.remove(&material_id);
|
||||
if self.material_slots.remove(&material_id).is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.release_material_textures(material_id);
|
||||
self.material_textures.remove(&material_id);
|
||||
self.emissive_materials.remove(&material_id);
|
||||
instances.invalidate_material(material_id);
|
||||
}
|
||||
|
||||
fn release_material_textures(&mut self, material_id: AssetId<StandardMaterial>) {
|
||||
let Some(textures) = self.material_textures.get(&material_id).copied() else {
|
||||
return;
|
||||
};
|
||||
for image_id in textures.into_iter().flatten() {
|
||||
self.textures.release(&image_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
use core::{mem::size_of, ops::Deref};
|
||||
|
||||
use bevy_ecs::system::{Res, ResMut};
|
||||
use bevy_math::Mat3;
|
||||
use bevy_pbr::DfgLut;
|
||||
use bevy_render::{
|
||||
render_asset::RenderAssets,
|
||||
render_resource::{
|
||||
BindGroup, BindGroupEntries, BindGroupLayout, Buffer, BufferBinding, BufferDescriptor,
|
||||
BufferId, BufferSize, BufferUsages, PipelineCache, Sampler, SamplerId, ShaderType,
|
||||
SparseBufferUpdateBindGroups, SparseBufferUpdateJobs, SparseBufferUpdatePipelines,
|
||||
StorageBuffer, TextureView, TextureViewId,
|
||||
},
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
texture::{FallbackImage, GpuImage},
|
||||
};
|
||||
use tracing::info_span;
|
||||
|
||||
use super::{
|
||||
RaytracingSceneBindings, TlasInstanceSetupPipeline, allocator::RetainedBindingArray,
|
||||
lights::GpuLightSource,
|
||||
};
|
||||
use crate::scene::extract::ExtractedEnvironmentMapLight;
|
||||
|
||||
pub struct BindGroupCacheState {
|
||||
cached: [Option<BindGroup>; 2],
|
||||
pub invalid: bool,
|
||||
last_buffer_ids: [Option<BufferId>; 11],
|
||||
last_light_count: u32,
|
||||
last_dfg_ids: Option<(TextureViewId, SamplerId)>,
|
||||
last_environment_map_light_id: Option<TextureViewId>,
|
||||
pub dummy_buffer: Buffer,
|
||||
}
|
||||
|
||||
impl BindGroupCacheState {
|
||||
pub fn new(render_device: &RenderDevice) -> Self {
|
||||
// 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,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
Self {
|
||||
cached: [None, None],
|
||||
invalid: true,
|
||||
last_buffer_ids: [None; 11],
|
||||
last_light_count: 0,
|
||||
last_dfg_ids: None,
|
||||
last_environment_map_light_id: None,
|
||||
dummy_buffer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_bindings<'a>(
|
||||
buffers: &'a RetainedBindingArray<BufferId, Buffer>,
|
||||
dummy: &'a Buffer,
|
||||
) -> Vec<BufferBinding<'a>> {
|
||||
buffers
|
||||
.iter()
|
||||
.map(|buffer| buffer.unwrap_or(dummy).as_entire_buffer_binding())
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl RaytracingSceneBindings {
|
||||
/// Each sparse buffer's GPU buffer id, or `None` where it has not been
|
||||
/// created yet.
|
||||
fn buffer_ids(&self) -> [Option<BufferId>; 11] {
|
||||
[
|
||||
self.assets.materials.buffer().map(Buffer::id),
|
||||
self.instances.transforms.buffer().map(Buffer::id),
|
||||
self.instances
|
||||
.previous_frame_transforms
|
||||
.buffer()
|
||||
.map(Buffer::id),
|
||||
self.instances.geometry_ids.buffer().map(Buffer::id),
|
||||
self.instances.tape_ids.buffer().map(Buffer::id),
|
||||
self.instances.material_ids.buffer().map(Buffer::id),
|
||||
self.instances.blas_refs.buffer().map(Buffer::id),
|
||||
self.lights.sources.buffer().map(Buffer::id),
|
||||
self.lights.directional_lights.buffer().map(Buffer::id),
|
||||
self.lights
|
||||
.previous_frame_id_translations
|
||||
.buffer()
|
||||
.map(Buffer::id),
|
||||
self.environment_map_light_buffer.buffer().map(Buffer::id),
|
||||
]
|
||||
}
|
||||
|
||||
fn take_bind_group_invalidation(
|
||||
&mut self,
|
||||
dfg_view: &TextureView,
|
||||
dfg_sampler: &Sampler,
|
||||
environment_map_light: &TextureView,
|
||||
) -> bool {
|
||||
let mut invalid = self.bind_groups.invalid;
|
||||
self.bind_groups.invalid = false;
|
||||
|
||||
for dirty in [
|
||||
&mut self.instances.vertex_buffers.dirty,
|
||||
&mut self.instances.index_buffers.dirty,
|
||||
&mut self.instances.aabb_buffers.dirty,
|
||||
&mut self.assets.textures.dirty,
|
||||
] {
|
||||
invalid |= core::mem::replace(dirty, false);
|
||||
}
|
||||
|
||||
let buffer_ids = self.buffer_ids();
|
||||
if self.bind_groups.last_buffer_ids != buffer_ids {
|
||||
self.bind_groups.last_buffer_ids = buffer_ids;
|
||||
invalid = true;
|
||||
}
|
||||
|
||||
let light_count = self.lights.index.len() as u32;
|
||||
if self.bind_groups.last_light_count != light_count {
|
||||
self.bind_groups.last_light_count = light_count;
|
||||
invalid = true;
|
||||
}
|
||||
|
||||
let dfg_ids = Some((dfg_view.id(), dfg_sampler.id()));
|
||||
if self.bind_groups.last_dfg_ids != dfg_ids {
|
||||
self.bind_groups.last_dfg_ids = dfg_ids;
|
||||
invalid = true;
|
||||
}
|
||||
|
||||
let environment_map_light_id = Some(environment_map_light.id());
|
||||
if self.bind_groups.last_environment_map_light_id != environment_map_light_id {
|
||||
self.bind_groups.last_environment_map_light_id = environment_map_light_id;
|
||||
invalid = true;
|
||||
}
|
||||
|
||||
invalid
|
||||
}
|
||||
|
||||
fn create_bind_group(
|
||||
&self,
|
||||
current_index: usize,
|
||||
render_device: &RenderDevice,
|
||||
layout: &BindGroupLayout,
|
||||
fallback_texture: &FallbackImage,
|
||||
dfg_view: &TextureView,
|
||||
dfg_sampler: &Sampler,
|
||||
environment_map_light: &TextureView,
|
||||
) -> BindGroup {
|
||||
let _span = info_span!("create_bind_group").entered();
|
||||
let dummy = &self.bind_groups.dummy_buffer;
|
||||
let vertex_buffers = buffer_bindings(&self.instances.vertex_buffers, dummy);
|
||||
let index_buffers = buffer_bindings(&self.instances.index_buffers, dummy);
|
||||
let aabb_buffers = buffer_bindings(&self.instances.aabb_buffers, dummy);
|
||||
|
||||
let (mut textures, mut samplers): (Vec<_>, Vec<_>) = self
|
||||
.assets
|
||||
.textures
|
||||
.iter()
|
||||
.map(|texture| match texture {
|
||||
Some((view, sampler)) => (view.deref(), sampler.deref()),
|
||||
None => (
|
||||
fallback_texture.d2.texture_view.deref(),
|
||||
fallback_texture.d2.sampler.deref(),
|
||||
),
|
||||
})
|
||||
.unzip();
|
||||
if textures.is_empty() {
|
||||
textures.push(fallback_texture.d2.texture_view.deref());
|
||||
samplers.push(fallback_texture.d2.sampler.deref());
|
||||
}
|
||||
|
||||
let light_sources = BufferBinding {
|
||||
buffer: self.lights.sources.buffer().unwrap(),
|
||||
offset: 0,
|
||||
size: BufferSize::new(
|
||||
self.lights.index.len() as u64 * size_of::<GpuLightSource>() as u64,
|
||||
),
|
||||
};
|
||||
|
||||
let materials = self
|
||||
.assets
|
||||
.materials
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let transforms = self
|
||||
.instances
|
||||
.transforms
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let previous_frame_transforms = self
|
||||
.instances
|
||||
.previous_frame_transforms
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let geometry_ids = self
|
||||
.instances
|
||||
.geometry_ids
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let tape_ids = self
|
||||
.instances
|
||||
.tape_ids
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let material_ids = self
|
||||
.instances
|
||||
.material_ids
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let directional_lights = self
|
||||
.lights
|
||||
.directional_lights
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
let translations = self
|
||||
.lights
|
||||
.previous_frame_id_translations
|
||||
.buffer()
|
||||
.unwrap()
|
||||
.as_entire_buffer_binding();
|
||||
|
||||
let current = self.tlas.structures[current_index].as_ref().unwrap();
|
||||
let previous = self.tlas.structures[current_index ^ 1]
|
||||
.as_ref()
|
||||
.filter(|_| self.tlas.built[current_index ^ 1])
|
||||
.unwrap_or(current);
|
||||
|
||||
render_device.create_bind_group(
|
||||
"raytracing_scene_bind_group",
|
||||
layout,
|
||||
&BindGroupEntries::sequential((
|
||||
vertex_buffers.as_slice(),
|
||||
index_buffers.as_slice(),
|
||||
aabb_buffers.as_slice(),
|
||||
textures.as_slice(),
|
||||
samplers.as_slice(),
|
||||
materials,
|
||||
current.as_binding(),
|
||||
previous.as_binding(),
|
||||
transforms,
|
||||
previous_frame_transforms,
|
||||
geometry_ids,
|
||||
tape_ids,
|
||||
material_ids,
|
||||
light_sources,
|
||||
directional_lights,
|
||||
translations,
|
||||
dfg_view,
|
||||
dfg_sampler,
|
||||
environment_map_light,
|
||||
&self.environment_map_light_sampler,
|
||||
&self.environment_map_light_buffer,
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn cache_bind_group(
|
||||
&mut self,
|
||||
current_index: usize,
|
||||
render_device: &RenderDevice,
|
||||
pipeline_cache: &PipelineCache,
|
||||
fallback_texture: &FallbackImage,
|
||||
dfg_view: &TextureView,
|
||||
dfg_sampler: &Sampler,
|
||||
environment_map_light: &TextureView,
|
||||
) -> BindGroup {
|
||||
if let Some(bind_group) = &self.bind_groups.cached[current_index] {
|
||||
return bind_group.clone();
|
||||
}
|
||||
|
||||
// Only resolve the layout on a miss, as it locks and hashes the whole
|
||||
// descriptor
|
||||
let layout = pipeline_cache.get_bind_group_layout(&self.bind_group_layout);
|
||||
let bind_group = self.create_bind_group(
|
||||
current_index,
|
||||
render_device,
|
||||
&layout,
|
||||
fallback_texture,
|
||||
dfg_view,
|
||||
dfg_sampler,
|
||||
environment_map_light,
|
||||
);
|
||||
if self.tlas.previous_binding_is_stable() {
|
||||
self.bind_groups.cached[current_index] = Some(bind_group.clone());
|
||||
}
|
||||
bind_group
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalizes sparse uploads and selects the cached bind group for this frame's
|
||||
/// TLAS.
|
||||
pub fn prepare_raytracing_scene_bind_group(
|
||||
texture_assets: Res<RenderAssets<GpuImage>>,
|
||||
fallback_texture: Res<FallbackImage>,
|
||||
dfg_lut: Res<DfgLut>,
|
||||
extracted_environment_map_light: Res<ExtractedEnvironmentMapLight>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
sparse_buffer_update_pipelines: Res<SparseBufferUpdatePipelines>,
|
||||
instance_setup_pipeline: Res<TlasInstanceSetupPipeline>,
|
||||
mut sparse_buffer_update_jobs: ResMut<SparseBufferUpdateJobs>,
|
||||
mut sparse_buffer_update_bind_groups: ResMut<SparseBufferUpdateBindGroups>,
|
||||
mut bindings: ResMut<RaytracingSceneBindings>,
|
||||
) {
|
||||
let bindings = &mut *bindings;
|
||||
|
||||
prepare_sparse_uploads(
|
||||
bindings,
|
||||
&render_device,
|
||||
&pipeline_cache,
|
||||
&mut sparse_buffer_update_jobs,
|
||||
&mut sparse_buffer_update_bind_groups,
|
||||
&sparse_buffer_update_pipelines,
|
||||
);
|
||||
|
||||
bindings.tlas.update_instance_setup_bind_group(
|
||||
&bindings.instances,
|
||||
&render_device,
|
||||
&pipeline_cache,
|
||||
&instance_setup_pipeline,
|
||||
);
|
||||
bindings.bind_group = None;
|
||||
|
||||
if bindings.instances.live_count == 0 || bindings.lights.index.is_empty() {
|
||||
return;
|
||||
}
|
||||
if bindings.tlas.structures[bindings.tlas.current_index].is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let (dfg_view, dfg_sampler) = texture_assets
|
||||
.get(&dfg_lut.texture)
|
||||
.map(|image| (&image.texture_view, &image.sampler))
|
||||
.unwrap_or((
|
||||
&fallback_texture.d2.texture_view,
|
||||
&fallback_texture.d2.sampler,
|
||||
));
|
||||
|
||||
let environment_map_light = prepare_environment_map_light(
|
||||
&extracted_environment_map_light,
|
||||
&texture_assets,
|
||||
&fallback_texture,
|
||||
&mut bindings.environment_map_light_buffer,
|
||||
&render_device,
|
||||
&render_queue,
|
||||
);
|
||||
|
||||
if bindings.take_bind_group_invalidation(dfg_view, dfg_sampler, environment_map_light) {
|
||||
bindings.bind_groups.cached = [None, None];
|
||||
}
|
||||
|
||||
let current_index = bindings.tlas.current_index;
|
||||
bindings.bind_group = Some(bindings.cache_bind_group(
|
||||
current_index,
|
||||
&render_device,
|
||||
&pipeline_cache,
|
||||
&fallback_texture,
|
||||
dfg_view,
|
||||
dfg_sampler,
|
||||
environment_map_light,
|
||||
));
|
||||
}
|
||||
|
||||
#[derive(ShaderType, Default)]
|
||||
pub struct GpuEnvironmentMapLight {
|
||||
pub light_from_world: Mat3,
|
||||
pub intensity: f32,
|
||||
}
|
||||
|
||||
fn prepare_environment_map_light<'a>(
|
||||
extracted_environment_map_light: &ExtractedEnvironmentMapLight,
|
||||
texture_assets: &'a RenderAssets<GpuImage>,
|
||||
fallback_texture: &'a FallbackImage,
|
||||
buffer: &mut StorageBuffer<GpuEnvironmentMapLight>,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) -> &'a TextureView {
|
||||
let cubemap = extracted_environment_map_light
|
||||
.cubemap
|
||||
.as_ref()
|
||||
.and_then(|cubemap| texture_assets.get(cubemap));
|
||||
|
||||
let (texture, uniform) = match cubemap {
|
||||
Some(cubemap) => (
|
||||
&cubemap.texture_view,
|
||||
GpuEnvironmentMapLight {
|
||||
light_from_world: Mat3::from_quat(
|
||||
extracted_environment_map_light.rotation.inverse(),
|
||||
),
|
||||
intensity: extracted_environment_map_light.intensity,
|
||||
},
|
||||
),
|
||||
None => (
|
||||
&fallback_texture.cube.texture_view,
|
||||
GpuEnvironmentMapLight::default(),
|
||||
),
|
||||
};
|
||||
|
||||
buffer.set(uniform);
|
||||
buffer.write_buffer(render_device, render_queue);
|
||||
texture
|
||||
}
|
||||
|
||||
/// Queues the compute jobs that scatter each buffer's staged elements into its
|
||||
/// GPU buffer.
|
||||
fn prepare_sparse_uploads(
|
||||
bindings: &mut RaytracingSceneBindings,
|
||||
device: &RenderDevice,
|
||||
cache: &PipelineCache,
|
||||
jobs: &mut SparseBufferUpdateJobs,
|
||||
groups: &mut SparseBufferUpdateBindGroups,
|
||||
pipelines: &SparseBufferUpdatePipelines,
|
||||
) {
|
||||
let _span = info_span!("prepare_sparse_uploads").entered();
|
||||
|
||||
bindings
|
||||
.assets
|
||||
.materials
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
|
||||
let instances = &mut bindings.instances;
|
||||
instances
|
||||
.transforms
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
instances
|
||||
.previous_frame_transforms
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
instances
|
||||
.geometry_ids
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
instances
|
||||
.tape_ids
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
instances
|
||||
.material_ids
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
if bindings.tlas.uses_raw_build() {
|
||||
instances
|
||||
.blas_refs
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
}
|
||||
|
||||
let lights = &mut bindings.lights;
|
||||
lights
|
||||
.sources
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
lights
|
||||
.directional_lights
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
lights
|
||||
.previous_frame_id_translations
|
||||
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
use core::{hash::Hash, num::NonZeroU32};
|
||||
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_ecs::{
|
||||
entity::{Entity, EntityHashMap, EntityHashSet},
|
||||
query::{Changed, Or, With},
|
||||
system::Query,
|
||||
};
|
||||
use bevy_math::{Affine3, Affine3Ext, Vec4};
|
||||
use bevy_mesh::Mesh;
|
||||
use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial};
|
||||
use bevy_platform::collections::HashMap;
|
||||
use bevy_render::{
|
||||
impl_atomic_pod,
|
||||
mesh::allocator::MeshAllocator,
|
||||
render_resource::{AtomicPod, AtomicSparseBufferVec, Buffer, BufferId, BufferUsages},
|
||||
};
|
||||
use bevy_tape_load::{Tape, render::allocator::TapeAllocator};
|
||||
use bevy_transform::components::GlobalTransform;
|
||||
use bevy_utils::once;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use tracing::{info_span, warn};
|
||||
|
||||
use super::{
|
||||
MeshBlasManager, RaytracingMesh3d, RaytracingSceneBindings, Tape3d, TapeBlasManager,
|
||||
allocator::{IndexAllocator, RetainedBindingArray},
|
||||
assets::AssetState,
|
||||
lights::{GpuLightSource, LightSourceId, LightState},
|
||||
};
|
||||
|
||||
pub const MAX_MESH_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap();
|
||||
pub const MAX_TAPE_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap();
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuInstanceGeometryIds {
|
||||
vertex_buffer_id: u32,
|
||||
vertex_buffer_offset: u32,
|
||||
index_buffer_id: u32,
|
||||
index_buffer_offset: u32,
|
||||
triangle_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuInstanceTapeIds {
|
||||
aabb_buffer_id: u32,
|
||||
aabb_buffer_offset: u32,
|
||||
aabb_count: u32,
|
||||
}
|
||||
|
||||
/// A world-from-local affine transform, stored transposed as three rows.
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuTransform([Vec4; 3]);
|
||||
|
||||
impl GpuTransform {
|
||||
/// The three rows as the flat row-major 3x4 a [`TlasInstance`] wants.
|
||||
///
|
||||
/// [`TlasInstance`]: bevy_render::render_resource::TlasInstance
|
||||
fn rows(self) -> [f32; 12] {
|
||||
bytemuck::cast(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The device address of a slot's acceleration structure. Zero marks an
|
||||
/// inactive slot.
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(transparent)]
|
||||
pub struct GpuBlasRef(u64);
|
||||
|
||||
impl GpuBlasRef {
|
||||
const NONE: Self = Self(0);
|
||||
}
|
||||
|
||||
impl_atomic_pod!(GpuInstanceGeometryIds, GpuInstanceGeometryIdsBlob);
|
||||
impl_atomic_pod!(GpuInstanceTapeIds, GpuInstanceTapeIdsBlob);
|
||||
impl_atomic_pod!(GpuTransform, GpuTransformBlob);
|
||||
impl_atomic_pod!(GpuBlasRef, GpuBlasRefBlob);
|
||||
|
||||
fn storage_buffer<T: AtomicPod>(label: &str) -> AtomicSparseBufferVec<T> {
|
||||
AtomicSparseBufferVec::new(BufferUsages::STORAGE, label.into())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Object {
|
||||
Mesh(AssetId<Mesh>),
|
||||
Tape(AssetId<Tape>),
|
||||
}
|
||||
|
||||
/// Everything tracked per raytracing mesh instance.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Instance {
|
||||
slot: u32,
|
||||
object: Object,
|
||||
material: AssetId<StandardMaterial>,
|
||||
buffers: Option<(BufferId, BufferId)>,
|
||||
}
|
||||
|
||||
/// Stable slots, reverse dependency indices and GPU data owned by raytracing
|
||||
/// instances.
|
||||
pub struct InstanceState {
|
||||
pub vertex_buffers: RetainedBindingArray<BufferId, Buffer>,
|
||||
pub index_buffers: RetainedBindingArray<BufferId, Buffer>,
|
||||
pub aabb_buffers: RetainedBindingArray<BufferId, Buffer>,
|
||||
pub transforms: AtomicSparseBufferVec<GpuTransform>,
|
||||
pub previous_frame_transforms: AtomicSparseBufferVec<GpuTransform>,
|
||||
pub geometry_ids: AtomicSparseBufferVec<GpuInstanceGeometryIds>,
|
||||
pub tape_ids: AtomicSparseBufferVec<GpuInstanceTapeIds>,
|
||||
pub material_ids: AtomicSparseBufferVec<u32>,
|
||||
pub blas_refs: AtomicSparseBufferVec<GpuBlasRef>,
|
||||
pub slots: IndexAllocator,
|
||||
records: EntityHashMap<Instance>,
|
||||
pub live_count: u32,
|
||||
pub pending_refresh: EntityHashSet,
|
||||
object_instances: HashMap<Object, EntityHashSet>,
|
||||
pub material_instances: HashMap<AssetId<StandardMaterial>, EntityHashSet>,
|
||||
}
|
||||
|
||||
impl InstanceState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
vertex_buffers: RetainedBindingArray::new(),
|
||||
index_buffers: RetainedBindingArray::new(),
|
||||
aabb_buffers: RetainedBindingArray::new(),
|
||||
transforms: storage_buffer("solari_transforms"),
|
||||
previous_frame_transforms: storage_buffer("solari_previous_frame_transforms"),
|
||||
geometry_ids: storage_buffer("solari_geometry_ids"),
|
||||
tape_ids: storage_buffer("solari_tape_ids"),
|
||||
material_ids: storage_buffer("solari_material_ids"),
|
||||
blas_refs: storage_buffer("solari_blas_refs"),
|
||||
slots: IndexAllocator::new(),
|
||||
records: EntityHashMap::default(),
|
||||
live_count: 0,
|
||||
pending_refresh: EntityHashSet::default(),
|
||||
object_instances: HashMap::default(),
|
||||
material_instances: HashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every drawable instance's slot, mesh and world-from-local transform.
|
||||
///
|
||||
/// Only the `wgpu-core` TLAS build path needs this, to fill in the instance
|
||||
/// descriptors that the raw path sets up on the GPU. Slots with a null
|
||||
/// acceleration structure reference are not currently drawable, and are
|
||||
/// left out.
|
||||
pub fn drawable(&self) -> impl Iterator<Item = (u32, Object, [f32; 12])> + '_ {
|
||||
self.records.values().filter_map(|instance| {
|
||||
let slot = instance.slot;
|
||||
(self.blas_refs.get(slot) != GpuBlasRef::NONE)
|
||||
.then(|| (slot, instance.object, self.transforms.get(slot).rows()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Queues every instance using `material_id` to be re-resolved.
|
||||
pub fn invalidate_material(&mut self, material_id: AssetId<StandardMaterial>) {
|
||||
if let Some(instances) = self.material_instances.get(&material_id) {
|
||||
self.pending_refresh.extend(instances.iter().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type MeshInstanceQueryData<'w> = (
|
||||
&'w RaytracingMesh3d,
|
||||
&'w MeshMaterial3d<StandardMaterial>,
|
||||
&'w GlobalTransform,
|
||||
&'w PreviousGlobalTransform,
|
||||
);
|
||||
|
||||
pub type TapeInstanceQueryData<'w> = (
|
||||
&'w Tape3d,
|
||||
&'w MeshMaterial3d<StandardMaterial>,
|
||||
&'w GlobalTransform,
|
||||
&'w PreviousGlobalTransform,
|
||||
);
|
||||
|
||||
pub enum InstanceQueryData<'w> {
|
||||
Mesh(MeshInstanceQueryData<'w>),
|
||||
Tape(TapeInstanceQueryData<'w>),
|
||||
}
|
||||
|
||||
pub type ChangedMeshInstanceFilter = (
|
||||
With<RaytracingMesh3d>,
|
||||
Or<(
|
||||
Changed<RaytracingMesh3d>,
|
||||
Changed<MeshMaterial3d<StandardMaterial>>,
|
||||
)>,
|
||||
);
|
||||
|
||||
pub type ChangedTapeInstanceFilter = (
|
||||
With<Tape3d>,
|
||||
Or<(Changed<Tape3d>, Changed<MeshMaterial3d<StandardMaterial>>)>,
|
||||
);
|
||||
|
||||
/// The scene state an instance resolves its GPU data against.
|
||||
pub struct InstanceInputs<'a> {
|
||||
pub assets: &'a AssetState,
|
||||
pub mesh_blas_manager: &'a MeshBlasManager,
|
||||
pub mesh_allocator: &'a MeshAllocator,
|
||||
pub tape_blas_manager: &'a TapeBlasManager,
|
||||
pub tape_allocator: &'a TapeAllocator,
|
||||
}
|
||||
|
||||
fn unlink<K: Eq + Hash>(map: &mut HashMap<K, EntityHashSet>, key: &K, entity: Entity) {
|
||||
let now_empty = map.get_mut(key).is_some_and(|instances| {
|
||||
instances.remove(&entity);
|
||||
instances.is_empty()
|
||||
});
|
||||
if now_empty {
|
||||
map.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
fn relink<K: Copy + Eq + Hash>(
|
||||
map: &mut HashMap<K, EntityHashSet>,
|
||||
entity: Entity,
|
||||
previous: Option<K>,
|
||||
key: K,
|
||||
) {
|
||||
if previous == Some(key) {
|
||||
return;
|
||||
}
|
||||
if let Some(previous) = previous {
|
||||
unlink(map, &previous, entity);
|
||||
}
|
||||
map.entry(key).or_default().insert(entity);
|
||||
}
|
||||
|
||||
impl InstanceState {
|
||||
pub fn remove_instances(
|
||||
&mut self,
|
||||
lights: &mut LightState,
|
||||
removed: impl IntoIterator<Item = Entity>,
|
||||
) {
|
||||
let _span = info_span!("remove_instances").entered();
|
||||
for entity in removed {
|
||||
self.remove_instance(lights, entity);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh_instances(
|
||||
&mut self,
|
||||
inputs: &InstanceInputs,
|
||||
lights: &mut LightState,
|
||||
mesh_instances: &Query<MeshInstanceQueryData>,
|
||||
changed_mesh_instances: &Query<Entity, ChangedMeshInstanceFilter>,
|
||||
tape_instances: &Query<TapeInstanceQueryData>,
|
||||
changed_tape_instances: &Query<Entity, ChangedTapeInstanceFilter>,
|
||||
) {
|
||||
let _span = info_span!("refresh_instances").entered();
|
||||
|
||||
let mut refresh = core::mem::take(&mut self.pending_refresh);
|
||||
refresh.extend(changed_mesh_instances.iter());
|
||||
refresh.extend(changed_tape_instances.iter());
|
||||
|
||||
let moved_meshes = inputs.mesh_allocator.meshes_displaced_by_slab_growth();
|
||||
for mesh_id in inputs
|
||||
.mesh_blas_manager
|
||||
.changed_meshes()
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(moved_meshes)
|
||||
{
|
||||
if let Some(mesh_instances) = self.object_instances.get(&Object::Mesh(mesh_id)) {
|
||||
refresh.extend(mesh_instances.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
let moved_tapes = inputs.tape_allocator.tapes_displaced_by_slab_growth();
|
||||
for tape_id in inputs
|
||||
.tape_blas_manager
|
||||
.changed_tapes()
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(moved_tapes)
|
||||
{
|
||||
if let Some(tape_instances) = self.object_instances.get(&Object::Tape(tape_id)) {
|
||||
refresh.extend(tape_instances.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
for entity in refresh {
|
||||
match mesh_instances.get(entity) {
|
||||
Ok(data) => {
|
||||
self.refresh_instance(inputs, lights, entity, InstanceQueryData::Mesh(data))
|
||||
},
|
||||
Err(_) => match tape_instances.get(entity) {
|
||||
Ok(data) => {
|
||||
self.refresh_instance(inputs, lights, entity, InstanceQueryData::Tape(data))
|
||||
},
|
||||
Err(_) => self.remove_instance(lights, entity),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reserve_slot(&mut self, slot: u32) {
|
||||
let len = slot + 1;
|
||||
self.transforms.grow(len);
|
||||
self.previous_frame_transforms.grow(len);
|
||||
self.blas_refs.grow(len);
|
||||
}
|
||||
|
||||
fn refresh_instance(
|
||||
&mut self,
|
||||
inputs: &InstanceInputs,
|
||||
lights: &mut LightState,
|
||||
entity: Entity,
|
||||
data: InstanceQueryData,
|
||||
) {
|
||||
let previous = self.records.get(&entity).copied();
|
||||
|
||||
let (id, material, transform, previous_frame_transform) = match data {
|
||||
InstanceQueryData::Mesh((mesh, material, transform, previous_frame_transform)) => (
|
||||
Object::Mesh(mesh.id()),
|
||||
material,
|
||||
transform,
|
||||
previous_frame_transform,
|
||||
),
|
||||
InstanceQueryData::Tape((tape, material, transform, previous_frame_transform)) => (
|
||||
Object::Tape(tape.id()),
|
||||
material,
|
||||
transform,
|
||||
previous_frame_transform,
|
||||
),
|
||||
};
|
||||
|
||||
let material_id = material.id();
|
||||
|
||||
relink(
|
||||
&mut self.object_instances,
|
||||
entity,
|
||||
previous.map(|instance| instance.object),
|
||||
id,
|
||||
);
|
||||
relink(
|
||||
&mut self.material_instances,
|
||||
entity,
|
||||
previous.map(|instance| instance.material),
|
||||
material_id,
|
||||
);
|
||||
|
||||
let slot = match previous {
|
||||
Some(previous) => previous.slot,
|
||||
None => self.slots.allocate(),
|
||||
};
|
||||
self.reserve_slot(slot);
|
||||
|
||||
// Seed only once. Later refreshes must not overwrite transforms written
|
||||
// by extraction.
|
||||
if previous.is_none() {
|
||||
self.write_transforms(slot, transform, previous_frame_transform);
|
||||
}
|
||||
|
||||
let mut instance = Instance {
|
||||
slot,
|
||||
object: id,
|
||||
material: material_id,
|
||||
buffers: previous.and_then(|instance| instance.buffers),
|
||||
};
|
||||
let resolved = self.resolve_instance(inputs, lights, entity, &mut instance);
|
||||
|
||||
self.records.insert(entity, instance);
|
||||
if !resolved {
|
||||
self.pending_refresh.insert(entity);
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_instance(
|
||||
&mut self,
|
||||
inputs: &InstanceInputs,
|
||||
lights: &mut LightState,
|
||||
entity: Entity,
|
||||
instance: &mut Instance,
|
||||
) -> bool {
|
||||
match instance.object {
|
||||
Object::Mesh(asset_id) => {
|
||||
self.resolve_mesh_instance(inputs, lights, entity, asset_id, instance)
|
||||
},
|
||||
Object::Tape(asset_id) => {
|
||||
self.resolve_tape_instance(inputs, lights, entity, asset_id, instance)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_mesh_instance(
|
||||
&mut self,
|
||||
inputs: &InstanceInputs,
|
||||
lights: &mut LightState,
|
||||
entity: Entity,
|
||||
mesh_id: AssetId<Mesh>,
|
||||
instance: &mut Instance,
|
||||
) -> bool {
|
||||
bevy_log::debug!("Resolving mesh instance {mesh_id}");
|
||||
let slot = instance.slot;
|
||||
let (Some(vertex_slice), Some(index_slice), Some(material_slot), Some(blas_address)) = (
|
||||
inputs.mesh_allocator.mesh_vertex_slice(&mesh_id),
|
||||
inputs.mesh_allocator.mesh_index_slice(&mesh_id),
|
||||
inputs.assets.material_slots.get(&instance.material),
|
||||
inputs.mesh_blas_manager.device_address(&mesh_id),
|
||||
) else {
|
||||
self.deactivate_instance(lights, entity, instance);
|
||||
return false;
|
||||
};
|
||||
|
||||
let vertex_buffer_key = vertex_slice.buffer.id();
|
||||
let index_buffer_key = index_slice.buffer.id();
|
||||
let capacity = MAX_MESH_SLAB_COUNT.get();
|
||||
if !self.vertex_buffers.has_room(&vertex_buffer_key, capacity)
|
||||
|| !self.index_buffers.has_room(&index_buffer_key, capacity)
|
||||
{
|
||||
once!(warn!(
|
||||
"Solari scene needs more than {} mesh slabs. Instances past that limit will not \
|
||||
be rendered.",
|
||||
MAX_MESH_SLAB_COUNT.get()
|
||||
));
|
||||
self.deactivate_instance(lights, entity, instance);
|
||||
return false;
|
||||
}
|
||||
|
||||
let previous_buffers = instance.buffers.take();
|
||||
let vertex_buffer_id = self
|
||||
.vertex_buffers
|
||||
.acquire(vertex_buffer_key, capacity, || vertex_slice.buffer.clone())
|
||||
.expect("vertex slab binding array had room but handed out no slot");
|
||||
let index_buffer_id = self
|
||||
.index_buffers
|
||||
.acquire(index_buffer_key, capacity, || index_slice.buffer.clone())
|
||||
.expect("index slab binding array had room but handed out no slot");
|
||||
instance.buffers = Some((vertex_buffer_key, index_buffer_key));
|
||||
self.release_mesh_buffers(previous_buffers);
|
||||
|
||||
let triangle_count = (index_slice.range.len() / 3) as u32;
|
||||
self.geometry_ids.grow_and_set(
|
||||
slot,
|
||||
GpuInstanceGeometryIds {
|
||||
vertex_buffer_id,
|
||||
vertex_buffer_offset: vertex_slice.range.start,
|
||||
index_buffer_id,
|
||||
index_buffer_offset: index_slice.range.start,
|
||||
triangle_count,
|
||||
},
|
||||
);
|
||||
self.material_ids.grow_and_set(slot, material_slot);
|
||||
self.set_blas_ref(slot, GpuBlasRef(blas_address));
|
||||
|
||||
let is_emissive = inputs
|
||||
.assets
|
||||
.emissive_materials
|
||||
.contains(&instance.material);
|
||||
if is_emissive {
|
||||
lights.add_light(
|
||||
LightSourceId::EmissiveMesh(entity),
|
||||
GpuLightSource::new_emissive_mesh_light(slot, triangle_count),
|
||||
);
|
||||
} else {
|
||||
lights.remove_light(LightSourceId::EmissiveMesh(entity));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn resolve_tape_instance(
|
||||
&mut self,
|
||||
inputs: &InstanceInputs,
|
||||
lights: &mut LightState,
|
||||
entity: Entity,
|
||||
tape_id: AssetId<Tape>,
|
||||
instance: &mut Instance,
|
||||
) -> bool {
|
||||
bevy_log::debug!("Resolving tape instance {tape_id}");
|
||||
let slot = instance.slot;
|
||||
let (Some(aabb_slice), Some(material_slot), Some(blas_address)) = (
|
||||
inputs.tape_allocator.tape_aabb_slice(&tape_id),
|
||||
inputs.assets.material_slots.get(&instance.material),
|
||||
inputs.tape_blas_manager.device_address(&tape_id),
|
||||
) else {
|
||||
self.deactivate_instance(lights, entity, instance);
|
||||
return false;
|
||||
};
|
||||
|
||||
let aabb_buffer_key = aabb_slice.buffer.id();
|
||||
let capacity = MAX_TAPE_SLAB_COUNT.get();
|
||||
if !self.aabb_buffers.has_room(&aabb_buffer_key, capacity) {
|
||||
once!(warn!(
|
||||
"Solari scene needs more than {} tape slabs. Instances past that limit will not \
|
||||
be rendered.",
|
||||
MAX_TAPE_SLAB_COUNT.get()
|
||||
));
|
||||
self.deactivate_instance(lights, entity, instance);
|
||||
return false;
|
||||
}
|
||||
|
||||
let previous_buffers = instance.buffers.take();
|
||||
let aabb_buffer_id = self
|
||||
.aabb_buffers
|
||||
.acquire(aabb_buffer_key, capacity, || aabb_slice.buffer.clone())
|
||||
.expect("aabb slab binding array had room but handed out no slot");
|
||||
instance.buffers = Some((aabb_buffer_key, aabb_buffer_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,
|
||||
},
|
||||
);
|
||||
self.material_ids.grow_and_set(slot, material_slot);
|
||||
self.set_blas_ref(slot, GpuBlasRef(blas_address));
|
||||
|
||||
/*
|
||||
let is_emissive = inputs
|
||||
.assets
|
||||
.emissive_materials
|
||||
.contains(&instance.material);
|
||||
if is_emissive {
|
||||
lights.add_light(
|
||||
LightSourceId::EmissiveMesh(entity),
|
||||
GpuLightSource::new_emissive_mesh_light(slot, triangle_count),
|
||||
);
|
||||
} else {
|
||||
lights.remove_light(LightSourceId::EmissiveMesh(entity));
|
||||
}
|
||||
*/
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn write_transforms(
|
||||
&self,
|
||||
slot: u32,
|
||||
transform: &GlobalTransform,
|
||||
previous_frame_transform: &PreviousGlobalTransform,
|
||||
) {
|
||||
self.transforms.set_if_changed(
|
||||
slot,
|
||||
GpuTransform(Affine3::from(transform.affine()).to_transpose()),
|
||||
);
|
||||
self.previous_frame_transforms.set_if_changed(
|
||||
slot,
|
||||
GpuTransform(Affine3::from(previous_frame_transform.0).to_transpose()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Points a slot at an acceleration structure, or at nothing, keeping
|
||||
/// `live_count` in step.
|
||||
fn set_blas_ref(&mut self, slot: u32, reference: GpuBlasRef) {
|
||||
self.blas_refs.grow(slot + 1);
|
||||
let previous = self.blas_refs.get(slot);
|
||||
if previous == reference {
|
||||
return;
|
||||
}
|
||||
self.blas_refs.set(slot, reference);
|
||||
|
||||
if previous == GpuBlasRef::NONE {
|
||||
self.live_count += 1;
|
||||
} else if reference == GpuBlasRef::NONE {
|
||||
self.live_count -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn deactivate_instance(
|
||||
&mut self,
|
||||
lights: &mut LightState,
|
||||
entity: Entity,
|
||||
instance: &mut Instance,
|
||||
) {
|
||||
self.set_blas_ref(instance.slot, GpuBlasRef::NONE);
|
||||
lights.remove_light(LightSourceId::EmissiveMesh(entity));
|
||||
match instance.object {
|
||||
Object::Mesh(_) => self.release_mesh_buffers(instance.buffers.take()),
|
||||
Object::Tape(_) => self.release_tape_buffers(instance.buffers.take()),
|
||||
}
|
||||
}
|
||||
|
||||
fn release_mesh_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
|
||||
if let Some((vertex_key, index_key)) = buffers {
|
||||
self.vertex_buffers.release(&vertex_key);
|
||||
self.index_buffers.release(&index_key);
|
||||
}
|
||||
}
|
||||
|
||||
fn release_tape_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
|
||||
if let Some((aabb_key, _)) = buffers {
|
||||
self.aabb_buffers.release(&aabb_key);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_instance(&mut self, lights: &mut LightState, entity: Entity) {
|
||||
let Some(mut instance) = self.records.remove(&entity) else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.deactivate_instance(lights, entity, &mut instance);
|
||||
self.slots.release(instance.slot);
|
||||
self.pending_refresh.remove(&entity);
|
||||
unlink(&mut self.object_instances, &instance.object, entity);
|
||||
unlink(&mut self.material_instances, &instance.material, entity);
|
||||
}
|
||||
}
|
||||
|
||||
impl RaytracingSceneBindings {
|
||||
/// Parallel hot path: one entity lookup, then two allocation-free sparse
|
||||
/// writes.
|
||||
pub fn move_instance(
|
||||
&self,
|
||||
entity: Entity,
|
||||
transform: &GlobalTransform,
|
||||
previous_frame_transform: &PreviousGlobalTransform,
|
||||
) {
|
||||
if let Some(instance) = self.instances.records.get(&entity) {
|
||||
self.instances
|
||||
.write_transforms(instance.slot, transform, previous_frame_transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
use super::allocator::SlotAllocator;
|
||||
use bevy_color::ColorToComponents;
|
||||
use bevy_ecs::{
|
||||
entity::{Entity, EntityHashSet},
|
||||
system::Query,
|
||||
};
|
||||
use bevy_math::{ops::cos, Vec3};
|
||||
use bevy_pbr::ExtractedDirectionalLight;
|
||||
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};
|
||||
use tracing::info_span;
|
||||
|
||||
const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX;
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuLightSource {
|
||||
kind: u32,
|
||||
id: u32,
|
||||
}
|
||||
|
||||
/// Stable identity for one source in the light array.
|
||||
///
|
||||
/// An entity can contribute both kinds at once, so the entity alone is not enough to identify a
|
||||
/// source.
|
||||
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
|
||||
pub enum LightSourceId {
|
||||
EmissiveMesh(Entity),
|
||||
Directional(Entity),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct LightIndex {
|
||||
indices: HashMap<LightSourceId, u32>,
|
||||
ids: Vec<LightSourceId>,
|
||||
changed: HashSet<LightSourceId>,
|
||||
}
|
||||
|
||||
impl LightIndex {
|
||||
pub fn len(&self) -> usize {
|
||||
self.ids.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.ids.is_empty()
|
||||
}
|
||||
|
||||
fn get(&self, id: &LightSourceId) -> Option<u32> {
|
||||
self.indices.get(id).copied()
|
||||
}
|
||||
|
||||
fn insert(&mut self, id: LightSourceId) -> u32 {
|
||||
if let Some(&index) = self.indices.get(&id) {
|
||||
return index;
|
||||
}
|
||||
|
||||
let index = self.ids.len() as u32;
|
||||
self.ids.push(id);
|
||||
self.indices.insert(id, index);
|
||||
self.changed.insert(id);
|
||||
index
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn remove(&mut self, id: LightSourceId) -> Option<(u32, u32)> {
|
||||
let index = self.indices.remove(&id)?;
|
||||
self.changed.insert(id);
|
||||
|
||||
let last = self.ids.len() as u32 - 1;
|
||||
self.ids.swap_remove(index as usize);
|
||||
|
||||
if index != last {
|
||||
let moved = self.ids[index as usize];
|
||||
self.indices.insert(moved, index);
|
||||
self.changed.insert(moved);
|
||||
}
|
||||
|
||||
Some((index, last))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuLightSource {
|
||||
pub fn new_emissive_mesh_light(instance_id: u32, triangle_count: u32) -> GpuLightSource {
|
||||
if triangle_count > u16::MAX as u32 {
|
||||
panic!("Too many triangles ({triangle_count}) in an emissive mesh, maximum is 65535.");
|
||||
}
|
||||
|
||||
Self {
|
||||
kind: triangle_count << 1,
|
||||
id: instance_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_directional_light(directional_light_id: u32) -> GpuLightSource {
|
||||
Self {
|
||||
kind: 1,
|
||||
id: directional_light_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuDirectionalLight {
|
||||
direction_to_light: Vec3,
|
||||
cos_theta_max: f32,
|
||||
luminance: Vec3,
|
||||
inverse_pdf: f32,
|
||||
}
|
||||
|
||||
impl_atomic_pod!(GpuLightSource, GpuLightSourceBlob);
|
||||
impl_atomic_pod!(GpuDirectionalLight, GpuDirectionalLightBlob);
|
||||
|
||||
impl GpuDirectionalLight {
|
||||
fn new(directional_light: &ExtractedDirectionalLight) -> Self {
|
||||
let cos_theta_max = cos(directional_light.sun_disk_angular_size / 2.0);
|
||||
let solid_angle = TAU * (1.0 - cos_theta_max);
|
||||
let luminance =
|
||||
(directional_light.color.to_vec3() * directional_light.illuminance) / solid_angle;
|
||||
|
||||
Self {
|
||||
direction_to_light: directional_light.transform.back().into(),
|
||||
cos_theta_max,
|
||||
luminance,
|
||||
inverse_pdf: solid_angle,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Light slots and the incremental previous-frame id translation state.
|
||||
pub struct LightState {
|
||||
/// Kept gap-free because shaders derive the light count with `arrayLength`.
|
||||
pub sources: AtomicSparseBufferVec<GpuLightSource>,
|
||||
pub directional_lights: AtomicSparseBufferVec<GpuDirectionalLight>,
|
||||
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.
|
||||
previous_index: HashMap<LightSourceId, u32>,
|
||||
nonidentity_translations: Vec<u32>,
|
||||
directional_slots: SlotAllocator<Entity>,
|
||||
/// Set by the lighting node once it has recorded work reading the translation table.
|
||||
translations_consumed: AtomicBool,
|
||||
}
|
||||
|
||||
impl LightState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
sources: AtomicSparseBufferVec::new(
|
||||
BufferUsages::STORAGE,
|
||||
"solari_light_sources".into(),
|
||||
),
|
||||
directional_lights: AtomicSparseBufferVec::new(
|
||||
BufferUsages::STORAGE,
|
||||
"solari_directional_lights".into(),
|
||||
),
|
||||
previous_frame_id_translations: AtomicSparseBufferVec::new(
|
||||
BufferUsages::STORAGE,
|
||||
"solari_previous_frame_light_id_translations".into(),
|
||||
),
|
||||
index: LightIndex::default(),
|
||||
previous_index: HashMap::default(),
|
||||
nonidentity_translations: Vec::new(),
|
||||
directional_slots: SlotAllocator::new(),
|
||||
translations_consumed: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, directional_lights: &Query<(Entity, &ExtractedDirectionalLight)>) {
|
||||
// There are few enough directional lights to just walk them every frame
|
||||
let _span = info_span!("update_lights").entered();
|
||||
|
||||
let mut live_directional_lights = EntityHashSet::default();
|
||||
for (entity, directional_light) in directional_lights {
|
||||
live_directional_lights.insert(entity);
|
||||
|
||||
let slot = self.directional_slots.get_or_allocate(entity);
|
||||
self.directional_lights
|
||||
.grow_and_set(slot, GpuDirectionalLight::new(directional_light));
|
||||
self.add_light(
|
||||
LightSourceId::Directional(entity),
|
||||
GpuLightSource::new_directional_light(slot),
|
||||
);
|
||||
}
|
||||
|
||||
let stale: Vec<Entity> = self
|
||||
.directional_slots
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|entity| !live_directional_lights.contains(entity))
|
||||
.collect();
|
||||
for entity in stale {
|
||||
self.directional_slots.remove(&entity);
|
||||
self.remove_light(LightSourceId::Directional(entity));
|
||||
}
|
||||
|
||||
self.write_light_id_translations();
|
||||
|
||||
if self.index.len() > u16::MAX as usize {
|
||||
panic!("Too many light sources in the scene, maximum is 65535.");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_light(&mut self, id: LightSourceId, source: GpuLightSource) {
|
||||
let index = self.index.insert(id);
|
||||
self.sources.grow_and_set(index, source);
|
||||
}
|
||||
|
||||
/// 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;
|
||||
};
|
||||
|
||||
if index != last {
|
||||
let source = self.sources.get(last);
|
||||
self.sources.grow_and_set(index, source);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// without bound.
|
||||
pub fn begin_frame(&mut self, has_consumers: bool) {
|
||||
for index in core::mem::take(&mut self.nonidentity_translations) {
|
||||
self.previous_frame_id_translations
|
||||
.grow_and_set(index, index);
|
||||
}
|
||||
|
||||
if !has_consumers || self.translations_consumed.swap(false, Ordering::Relaxed) {
|
||||
for id in core::mem::take(&mut self.index.changed) {
|
||||
match self.index.get(&id) {
|
||||
Some(index) => self.previous_index.insert(id, index),
|
||||
None => self.previous_index.remove(&id),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records that the lighting shader read this frame's translation table.
|
||||
pub fn note_translations_consumed(&self) {
|
||||
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.
|
||||
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
|
||||
let Some(&previous) = self.previous_index.get(id) else {
|
||||
continue;
|
||||
};
|
||||
let current = self.index.get(id).unwrap_or(LIGHT_NOT_PRESENT_THIS_FRAME);
|
||||
|
||||
if current != previous {
|
||||
self.previous_frame_id_translations
|
||||
.grow_and_set(previous, current);
|
||||
self.nonidentity_translations.push(previous);
|
||||
}
|
||||
}
|
||||
|
||||
// Every index the shader might read has to be backed by a real element
|
||||
let light_count = self.index.len() as u32;
|
||||
let translations = &mut self.previous_frame_id_translations;
|
||||
if translations.len() < light_count {
|
||||
let start = translations.len();
|
||||
translations.grow(light_count);
|
||||
for index in start..light_count {
|
||||
translations.set(index, index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{LightIndex, LightSourceId};
|
||||
use bevy_ecs::entity::Entity;
|
||||
|
||||
#[test]
|
||||
fn light_index_keeps_sources_on_the_same_entity_independent() {
|
||||
let entity = Entity::PLACEHOLDER;
|
||||
let emissive = LightSourceId::EmissiveMesh(entity);
|
||||
let directional = LightSourceId::Directional(entity);
|
||||
let mut lights = LightIndex::default();
|
||||
|
||||
assert_eq!(lights.insert(emissive), 0);
|
||||
assert_eq!(lights.insert(directional), 1);
|
||||
assert_eq!(lights.insert(emissive), 0);
|
||||
assert_eq!(lights.len(), 2);
|
||||
|
||||
assert_eq!(lights.remove(emissive), Some((0, 1)));
|
||||
assert_eq!(lights.get(&emissive), None);
|
||||
assert_eq!(lights.get(&directional), Some(0));
|
||||
assert_eq!(lights.len(), 1);
|
||||
|
||||
assert_eq!(lights.remove(directional), Some((0, 0)));
|
||||
assert!(lights.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
mod allocator;
|
||||
mod assets;
|
||||
mod bind_group;
|
||||
mod instances;
|
||||
mod lights;
|
||||
mod tlas;
|
||||
mod tlas_build;
|
||||
|
||||
use bevy_ecs::{
|
||||
entity::Entity,
|
||||
lifecycle::RemovedComponents,
|
||||
resource::Resource,
|
||||
system::{Query, Res, ResMut},
|
||||
world::{FromWorld, World},
|
||||
};
|
||||
use bevy_pbr::ExtractedDirectionalLight;
|
||||
use bevy_render::{
|
||||
mesh::allocator::MeshAllocator,
|
||||
render_asset::{ExtractedAssets, RenderAssets},
|
||||
render_resource::{binding_types::*, *},
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
texture::GpuImage,
|
||||
};
|
||||
use bevy_tape_load::render::allocator::TapeAllocator;
|
||||
use tracing::info_span;
|
||||
|
||||
use self::{
|
||||
assets::{AssetState, MAX_TEXTURE_COUNT},
|
||||
bind_group::{BindGroupCacheState, GpuEnvironmentMapLight},
|
||||
instances::{
|
||||
ChangedMeshInstanceFilter, ChangedTapeInstanceFilter, InstanceInputs, InstanceState,
|
||||
MAX_MESH_SLAB_COUNT, MeshInstanceQueryData, TapeInstanceQueryData,
|
||||
},
|
||||
lights::LightState,
|
||||
tlas::TlasState,
|
||||
};
|
||||
pub use self::{
|
||||
bind_group::prepare_raytracing_scene_bind_group,
|
||||
tlas::{TlasInstanceSetupPipeline, build_raytracing_tlas},
|
||||
};
|
||||
use super::{
|
||||
RaytracingMesh3d, Tape3d, extract::StandardMaterialAssets,
|
||||
meshes::blas::BlasManager as MeshBlasManager, tapes::blas::BlasManager as TapeBlasManager,
|
||||
};
|
||||
|
||||
/// Insert this resource into the render world to make the raytracing scene
|
||||
/// retain the previous frame's TLAS and the light id translation table that
|
||||
/// maps into it.
|
||||
///
|
||||
/// This is useful for temporal techniques that need last frame's data.
|
||||
/// Retaining it costs a second TLAS allocation and rebuild, so the scene only
|
||||
/// does so while something asks for it.
|
||||
#[derive(Resource, Default)]
|
||||
pub struct RaytracingSceneNeedsPreviousFrameData;
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct RaytracingSceneBindings {
|
||||
pub bind_group: Option<BindGroup>,
|
||||
pub bind_group_layout: BindGroupLayoutDescriptor,
|
||||
assets: AssetState,
|
||||
instances: InstanceState,
|
||||
lights: LightState,
|
||||
tlas: TlasState,
|
||||
bind_groups: BindGroupCacheState,
|
||||
environment_map_light_sampler: Sampler,
|
||||
environment_map_light_buffer: StorageBuffer<GpuEnvironmentMapLight>,
|
||||
}
|
||||
|
||||
impl RaytracingSceneBindings {
|
||||
/// Records that a lighting pass read
|
||||
/// `previous_frame_light_id_translations`, so the next frame's table
|
||||
/// translates from this frame's light ids rather than older ones.
|
||||
pub fn note_light_translations_consumed(&self) {
|
||||
self.lights.note_translations_consumed();
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for RaytracingSceneBindings {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
let render_device = world.resource::<RenderDevice>();
|
||||
|
||||
let bind_group_layout = BindGroupLayoutDescriptor::new(
|
||||
"raytracing_scene_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
|
||||
storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
|
||||
storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
|
||||
texture_2d(TextureSampleType::Float { filterable: true })
|
||||
.count(MAX_TEXTURE_COUNT),
|
||||
sampler(SamplerBindingType::Filtering).count(MAX_TEXTURE_COUNT),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
acceleration_structure(),
|
||||
acceleration_structure(),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
texture_cube(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let environment_map_light_sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
label: Some("solari_environment_map_light_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()
|
||||
});
|
||||
|
||||
let mut environment_map_light_buffer = StorageBuffer::<GpuEnvironmentMapLight>::default();
|
||||
environment_map_light_buffer.set_label(Some("solari_environment_map_light"));
|
||||
|
||||
Self {
|
||||
bind_group: None,
|
||||
bind_group_layout,
|
||||
assets: AssetState::new(),
|
||||
instances: InstanceState::new(),
|
||||
lights: LightState::new(),
|
||||
tlas: TlasState::new(render_device),
|
||||
bind_groups: BindGroupCacheState::new(render_device),
|
||||
environment_map_light_sampler,
|
||||
environment_map_light_buffer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies this frame's scene changes to the retained buffers, binding arrays
|
||||
/// and TLAS.
|
||||
pub fn prepare_raytracing_scene_resources(
|
||||
(mesh_instances, tape_instances): (Query<MeshInstanceQueryData>, Query<TapeInstanceQueryData>),
|
||||
(changed_mesh_instances, changed_tape_instances): (
|
||||
Query<Entity, ChangedMeshInstanceFilter>,
|
||||
Query<Entity, ChangedTapeInstanceFilter>,
|
||||
),
|
||||
(mut removed_mesh_instances, mut removed_tape_instances): (
|
||||
RemovedComponents<RaytracingMesh3d>,
|
||||
RemovedComponents<Tape3d>,
|
||||
),
|
||||
directional_lights: Query<(Entity, &ExtractedDirectionalLight)>,
|
||||
needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
|
||||
(mesh_allocator, tape_allocator): (Res<MeshAllocator>, Res<TapeAllocator>),
|
||||
(mesh_blas_manager, tape_blas_manager): (Res<MeshBlasManager>, Res<TapeBlasManager>),
|
||||
material_assets: Res<StandardMaterialAssets>,
|
||||
texture_assets: Res<RenderAssets<GpuImage>>,
|
||||
extracted_images: Res<ExtractedAssets<GpuImage>>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
instance_setup_pipeline: Res<TlasInstanceSetupPipeline>,
|
||||
mut bindings: ResMut<RaytracingSceneBindings>,
|
||||
) {
|
||||
let bindings = &mut *bindings;
|
||||
let needs_previous_frame_data = needs_previous_frame_data.is_some();
|
||||
|
||||
// Roll light ids over before any removal or compaction writes this frame's
|
||||
// translations
|
||||
bindings.lights.begin_frame(needs_previous_frame_data);
|
||||
|
||||
// Update material and texture assets
|
||||
bindings
|
||||
.assets
|
||||
.update_materials(&mut bindings.instances, &material_assets, &texture_assets);
|
||||
bindings.assets.update_textures(
|
||||
&mut bindings.instances,
|
||||
&extracted_images,
|
||||
&texture_assets,
|
||||
&material_assets,
|
||||
);
|
||||
|
||||
// Apply structural instance changes, now that asset slots are current
|
||||
bindings
|
||||
.instances
|
||||
.remove_instances(&mut bindings.lights, removed_mesh_instances.read());
|
||||
bindings
|
||||
.instances
|
||||
.remove_instances(&mut bindings.lights, removed_tape_instances.read());
|
||||
let inputs = InstanceInputs {
|
||||
assets: &bindings.assets,
|
||||
mesh_blas_manager: &mesh_blas_manager,
|
||||
mesh_allocator: &mesh_allocator,
|
||||
tape_blas_manager: &tape_blas_manager,
|
||||
tape_allocator: &tape_allocator,
|
||||
};
|
||||
bindings.instances.refresh_instances(
|
||||
&inputs,
|
||||
&mut bindings.lights,
|
||||
&mesh_instances,
|
||||
&changed_mesh_instances,
|
||||
&tape_instances,
|
||||
&changed_tape_instances,
|
||||
);
|
||||
|
||||
// Update the light set, now that emissive instances are resolved
|
||||
bindings.lights.update(&directional_lights);
|
||||
|
||||
// Upload the above writes
|
||||
write_sparse_buffers(bindings, &render_device, &render_queue);
|
||||
|
||||
// Prepare the next TLAS
|
||||
let build_ready = !bindings.tlas.uses_raw_build()
|
||||
|| instance_setup_pipeline
|
||||
.id
|
||||
.and_then(|id| pipeline_cache.get_compute_pipeline(id))
|
||||
.is_some();
|
||||
bindings.tlas.advance(
|
||||
&bindings.instances,
|
||||
&mut bindings.bind_groups,
|
||||
&render_device,
|
||||
build_ready,
|
||||
needs_previous_frame_data,
|
||||
);
|
||||
}
|
||||
|
||||
/// Grows every sparse buffer to hold at least one element, then snapshots its
|
||||
/// dirty set into either a staged sparse update or a full reupload.
|
||||
fn write_sparse_buffers(
|
||||
bindings: &mut RaytracingSceneBindings,
|
||||
device: &RenderDevice,
|
||||
queue: &RenderQueue,
|
||||
) {
|
||||
let _span = info_span!("write_buffers").entered();
|
||||
|
||||
let assets = &mut bindings.assets;
|
||||
assets.materials.grow(1);
|
||||
assets.materials.write_buffers(device, queue);
|
||||
|
||||
let instances = &mut bindings.instances;
|
||||
instances.transforms.grow(1);
|
||||
instances.transforms.write_buffers(device, queue);
|
||||
instances.previous_frame_transforms.grow(1);
|
||||
instances
|
||||
.previous_frame_transforms
|
||||
.write_buffers(device, queue);
|
||||
instances.geometry_ids.grow(1);
|
||||
instances.geometry_ids.write_buffers(device, queue);
|
||||
instances.tape_ids.grow(1);
|
||||
instances.tape_ids.write_buffers(device, queue);
|
||||
instances.material_ids.grow(1);
|
||||
instances.material_ids.write_buffers(device, queue);
|
||||
if bindings.tlas.uses_raw_build() {
|
||||
instances.blas_refs.grow(1);
|
||||
instances.blas_refs.write_buffers(device, queue);
|
||||
}
|
||||
|
||||
let lights = &mut bindings.lights;
|
||||
lights.sources.grow(1);
|
||||
lights.sources.write_buffers(device, queue);
|
||||
lights.directional_lights.grow(1);
|
||||
lights.directional_lights.write_buffers(device, queue);
|
||||
lights.previous_frame_id_translations.grow(1);
|
||||
lights
|
||||
.previous_frame_id_translations
|
||||
.write_buffers(device, queue);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
@group(0) @binding(0) var<storage, read> transforms: array<array<vec4<f32>, 3>>;
|
||||
@group(0) @binding(1) var<storage, read> blas_refs: array<vec2<u32>>;
|
||||
@group(0) @binding(2) var<storage, read_write> instances: array<TlasInstance>;
|
||||
|
||||
struct TlasInstance {
|
||||
transform: array<vec4<f32>, 3>,
|
||||
custom_data_and_mask: u32,
|
||||
sbt_offset_and_flags: u32,
|
||||
blas_ref: vec2<u32>,
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64, 1, 1)
|
||||
fn setup_tlas_instances(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
let slot = global_id.x;
|
||||
if slot >= arrayLength(&instances) || slot >= arrayLength(&blas_refs) || slot >= arrayLength(&transforms) {
|
||||
return;
|
||||
}
|
||||
|
||||
instances[slot] = TlasInstance(
|
||||
transforms[slot],
|
||||
(slot & 0xFFFFFFu) | 0xFF000000u,
|
||||
0u,
|
||||
blas_refs[slot],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
use bevy_asset::load_embedded_asset;
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
system::{Res, ResMut},
|
||||
world::{FromWorld, World},
|
||||
};
|
||||
use bevy_render::{
|
||||
diagnostic::RecordDiagnostics,
|
||||
render_resource::{
|
||||
AccelerationStructureFlags, AccelerationStructureUpdateMode, BindGroup, BindGroupEntries,
|
||||
BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, BufferDescriptor, BufferId,
|
||||
BufferUsages, CachedComputePipelineId, CommandEncoderDescriptor, ComputePassDescriptor,
|
||||
ComputePipelineDescriptor, CreateTlasDescriptor, PipelineCache, ShaderStages, Tlas,
|
||||
TlasInstance,
|
||||
binding_types::{storage_buffer_read_only_sized, storage_buffer_sized},
|
||||
},
|
||||
renderer::{RenderContext, RenderDevice},
|
||||
};
|
||||
use bevy_utils::{default, once};
|
||||
use tracing::{info_span, warn};
|
||||
use wgpu::{BufferTransition, BufferUses};
|
||||
|
||||
use super::{
|
||||
MeshBlasManager, RaytracingSceneBindings, TapeBlasManager, bind_group::BindGroupCacheState,
|
||||
instances::InstanceState, tlas_build,
|
||||
};
|
||||
use crate::scene::binder::instances::Object;
|
||||
|
||||
/// Compute pipeline that writes per-slot transforms and BLAS addresses into
|
||||
/// TLAS descriptors.
|
||||
#[derive(Resource)]
|
||||
pub struct TlasInstanceSetupPipeline {
|
||||
pub layout: BindGroupLayoutDescriptor,
|
||||
pub id: Option<CachedComputePipelineId>,
|
||||
}
|
||||
|
||||
impl FromWorld for TlasInstanceSetupPipeline {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
let layout = BindGroupLayoutDescriptor::new(
|
||||
"tlas_instance_setup_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_read_only_sized(false, None),
|
||||
storage_buffer_sized(false, None),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if tlas_build::resolve(world.resource::<RenderDevice>()).is_none() {
|
||||
return Self { layout, id: None };
|
||||
}
|
||||
|
||||
let shader = load_embedded_asset!(world, "setup_tlas_instances.wesl");
|
||||
let id =
|
||||
world
|
||||
.resource::<PipelineCache>()
|
||||
.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some("tlas_instance_setup_pipeline".into()),
|
||||
layout: vec![layout.clone()],
|
||||
shader,
|
||||
entry_point: Some("setup_tlas_instances".into()),
|
||||
..default()
|
||||
});
|
||||
|
||||
Self {
|
||||
layout,
|
||||
id: Some(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Smallest TLAS instance capacity handed out, and the floor
|
||||
/// [`tlas_capacity_for`] grows from.
|
||||
const TLAS_MIN_CAPACITY: u32 = 128;
|
||||
|
||||
/// Width of a TLAS instance's custom data in both Vulkan
|
||||
/// (`instanceCustomIndex`) and DXR (`InstanceID`). `setup_tlas_instances.wgsl`
|
||||
/// writes instance slots into that field, so they have to fit.
|
||||
const TLAS_CUSTOM_DATA_BITS: u32 = 24;
|
||||
|
||||
/// Instance capacity to allocate to hold `instance_count` slots.
|
||||
///
|
||||
/// Grows geometrically rather than by a fixed step, so reallocations over a
|
||||
/// scene's lifetime are logarithmic in its size. Being a pure function of the
|
||||
/// count keeps the descriptor buffer and both TLASes on the same capacity curve
|
||||
/// without having to coordinate their previous sizes.
|
||||
fn tlas_capacity_for(instance_count: u32) -> u32 {
|
||||
let mut capacity = TLAS_MIN_CAPACITY;
|
||||
while capacity < instance_count {
|
||||
capacity = capacity.saturating_add(capacity.div_ceil(2));
|
||||
}
|
||||
capacity
|
||||
}
|
||||
|
||||
/// The TLAS and its capacity state, double buffered only while something traces
|
||||
/// last frame's.
|
||||
///
|
||||
/// An acceleration structure is only bindable once it has been built. Nothing
|
||||
/// here owns a BLAS: keeping the ones a built structure points at alive is
|
||||
/// [`BlasManager`]'s job, which defers every retirement until
|
||||
/// [`BlasManager::note_tlas_build`] has seen both structures rebuilt.
|
||||
pub struct TlasState {
|
||||
/// The backend to build through, or `None` to go through `wgpu-core`.
|
||||
raw: Option<&'static dyn tlas_build::RawTlasBackend>,
|
||||
/// Whether last frame's structure is being retained alongside this frame's.
|
||||
double_buffered: bool,
|
||||
/// Alternating current/previous acceleration structures. The second is
|
||||
/// `None` while single buffered.
|
||||
pub structures: [Option<Tlas>; 2],
|
||||
capacity: [u32; 2],
|
||||
/// Whether each structure has had a build recorded since its latest
|
||||
/// allocation.
|
||||
pub built: [bool; 2],
|
||||
/// Which of [`Self::structures`] this frame builds into. The other holds
|
||||
/// last frame's.
|
||||
pub current_index: usize,
|
||||
pub instance_descriptors: Option<Buffer>,
|
||||
instance_descriptor_capacity: u32,
|
||||
pub scratch: Option<Buffer>,
|
||||
scratch_capacity: u64,
|
||||
scratch_sized_for: u32,
|
||||
pub instance_setup_bind_group: Option<BindGroup>,
|
||||
instance_setup_buffer_ids: Option<[BufferId; 3]>,
|
||||
}
|
||||
|
||||
impl TlasState {
|
||||
pub fn new(render_device: &RenderDevice) -> Self {
|
||||
Self {
|
||||
raw: tlas_build::resolve(render_device),
|
||||
double_buffered: false,
|
||||
structures: [None, None],
|
||||
capacity: [0, 0],
|
||||
built: [false, false],
|
||||
current_index: 0,
|
||||
instance_descriptors: None,
|
||||
instance_descriptor_capacity: 0,
|
||||
scratch: None,
|
||||
scratch_capacity: 0,
|
||||
scratch_sized_for: 0,
|
||||
instance_setup_bind_group: None,
|
||||
instance_setup_buffer_ids: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether builds go through [`tlas_build`]'s raw path rather than
|
||||
/// `wgpu-core`.
|
||||
pub fn uses_raw_build(&self) -> bool {
|
||||
self.raw.is_some()
|
||||
}
|
||||
|
||||
/// Brings the acceleration structure up to date with this frame's changes.
|
||||
///
|
||||
/// While `double_buffered`, the two structures alternate: this frame's is
|
||||
/// rebuilt, and last frame's stays intact so the shaders can trace
|
||||
/// against it. Otherwise the single structure is rebuilt in place,
|
||||
/// which is safe because the build is recorded before any pass that traces
|
||||
/// it and nothing reads last frame's contents.
|
||||
///
|
||||
/// `build_ready` reports whether this frame will be able to record a build.
|
||||
/// When false nothing is allocated or swapped, though an unused
|
||||
/// structure is still released.
|
||||
pub fn advance(
|
||||
&mut self,
|
||||
instances: &InstanceState,
|
||||
bind_groups: &mut BindGroupCacheState,
|
||||
render_device: &RenderDevice,
|
||||
build_ready: bool,
|
||||
double_buffered: bool,
|
||||
) {
|
||||
let _span = info_span!("advance_tlas").entered();
|
||||
|
||||
// Free the retained structure as soon as nothing wants it
|
||||
self.set_double_buffered(double_buffered, bind_groups);
|
||||
|
||||
// An empty scene must not allocate an unbuilt TLAS that could resurface
|
||||
// as a later previous-frame entry
|
||||
if !build_ready || instances.slots.high_water_mark() == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
debug_assert!(
|
||||
instances.slots.high_water_mark() < 1 << TLAS_CUSTOM_DATA_BITS,
|
||||
"instance slot count {} does not fit in a TLAS instance's custom data",
|
||||
instances.slots.high_water_mark()
|
||||
);
|
||||
|
||||
// Secure every build input before committing the swap. Neither buffer
|
||||
// exists on the wgpu-core path, which builds from instances
|
||||
// written into the TLAS itself.
|
||||
let instance_count = instances.slots.high_water_mark();
|
||||
if self.raw.is_some() {
|
||||
self.reserve_instance_descriptors(instance_count, render_device);
|
||||
self.reserve_tlas_scratch(render_device);
|
||||
if self.instance_descriptors.is_none() || self.scratch.is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if self.double_buffered {
|
||||
self.current_index ^= 1;
|
||||
}
|
||||
let current_index = self.current_index;
|
||||
self.reserve_tlas(current_index, instance_count, render_device, bind_groups);
|
||||
}
|
||||
|
||||
/// Switches between retaining last frame's structure and rebuilding a
|
||||
/// single one in place, dropping the structure that is no longer
|
||||
/// traced.
|
||||
fn set_double_buffered(
|
||||
&mut self,
|
||||
double_buffered: bool,
|
||||
bind_groups: &mut BindGroupCacheState,
|
||||
) {
|
||||
if self.double_buffered != double_buffered {
|
||||
self.double_buffered = double_buffered;
|
||||
bind_groups.invalid = true;
|
||||
}
|
||||
if double_buffered {
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep building into whichever structure is already current, so the
|
||||
// frame this turns off does not have to allocate
|
||||
let previous_index = self.current_index ^ 1;
|
||||
if self.structures[previous_index].take().is_some() {
|
||||
self.capacity[previous_index] = 0;
|
||||
self.built[previous_index] = false;
|
||||
bind_groups.invalid = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the previous-frame slot's binding will still be correct next
|
||||
/// frame, and so whether a bind group using it can be cached.
|
||||
pub fn previous_binding_is_stable(&self) -> bool {
|
||||
!self.double_buffered || self.built[self.current_index ^ 1]
|
||||
}
|
||||
|
||||
/// Rebuilds the setup shader's bind group only when one of its three
|
||||
/// buffers moves.
|
||||
pub fn update_instance_setup_bind_group(
|
||||
&mut self,
|
||||
instances: &InstanceState,
|
||||
render_device: &RenderDevice,
|
||||
pipeline_cache: &PipelineCache,
|
||||
pipeline: &TlasInstanceSetupPipeline,
|
||||
) {
|
||||
let (Some(transforms), Some(blas_refs), Some(instances)) = (
|
||||
instances.transforms.buffer(),
|
||||
instances.blas_refs.buffer(),
|
||||
self.instance_descriptors.as_ref(),
|
||||
) else {
|
||||
self.instance_setup_bind_group = None;
|
||||
return;
|
||||
};
|
||||
|
||||
let ids = [transforms.id(), blas_refs.id(), instances.id()];
|
||||
if self.instance_setup_bind_group.is_some() && self.instance_setup_buffer_ids == Some(ids) {
|
||||
return;
|
||||
}
|
||||
|
||||
let layout = pipeline_cache.get_bind_group_layout(&pipeline.layout);
|
||||
self.instance_setup_bind_group = Some(render_device.create_bind_group(
|
||||
"tlas_instance_setup_bind_group",
|
||||
&layout,
|
||||
&BindGroupEntries::sequential((
|
||||
transforms.as_entire_binding(),
|
||||
blas_refs.as_entire_binding(),
|
||||
instances.as_entire_binding(),
|
||||
)),
|
||||
));
|
||||
self.instance_setup_buffer_ids = Some(ids);
|
||||
}
|
||||
|
||||
/// Makes sure the instance descriptor buffer covers every stable slot.
|
||||
fn reserve_instance_descriptors(&mut self, needed: u32, render_device: &RenderDevice) {
|
||||
if self.instance_descriptors.is_some() && needed <= self.instance_descriptor_capacity {
|
||||
return;
|
||||
}
|
||||
|
||||
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,
|
||||
mapped_at_creation: false,
|
||||
}));
|
||||
self.instance_descriptor_capacity = capacity;
|
||||
self.instance_setup_bind_group = None;
|
||||
}
|
||||
|
||||
/// Makes sure the build scratch buffer is big enough for this frame's
|
||||
/// descriptor capacity.
|
||||
fn reserve_tlas_scratch(&mut self, render_device: &RenderDevice) {
|
||||
let capacity = self.instance_descriptor_capacity;
|
||||
if self.scratch.is_some() && capacity <= self.scratch_sized_for {
|
||||
return;
|
||||
}
|
||||
|
||||
let (Some(backend), Some(instances)) = (self.raw, self.instance_descriptors.as_ref())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(needed) = backend.scratch_size(render_device, instances, capacity) else {
|
||||
return;
|
||||
};
|
||||
self.scratch_sized_for = capacity;
|
||||
|
||||
if self.scratch.is_some() && needed <= self.scratch_capacity {
|
||||
return;
|
||||
}
|
||||
|
||||
// The setup transition lets wgpu retain an outgrown scratch buffer
|
||||
// until in-flight work releases it
|
||||
self.scratch = backend.create_scratch_buffer(render_device, needed);
|
||||
self.scratch_capacity = if self.scratch.is_some() { needed } else { 0 };
|
||||
}
|
||||
|
||||
/// Makes sure one of the two structures can hold every instance slot,
|
||||
/// leaving the other alone.
|
||||
fn reserve_tlas(
|
||||
&mut self,
|
||||
current_index: usize,
|
||||
needed: u32,
|
||||
render_device: &RenderDevice,
|
||||
bind_groups: &mut BindGroupCacheState,
|
||||
) {
|
||||
if self.structures[current_index].is_some() && needed <= self.capacity[current_index] {
|
||||
return;
|
||||
}
|
||||
|
||||
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,
|
||||
max_instances: capacity,
|
||||
},
|
||||
));
|
||||
self.capacity[current_index] = capacity;
|
||||
self.built[current_index] = false;
|
||||
bind_groups.invalid = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Records this frame's TLAS build into the render graph's command encoder.
|
||||
pub fn build_raytracing_tlas(
|
||||
mut bindings: ResMut<RaytracingSceneBindings>,
|
||||
mut mesh_blas_manager: ResMut<MeshBlasManager>,
|
||||
mut tape_blas_manager: ResMut<TapeBlasManager>,
|
||||
pipeline_cache: Res<PipelineCache>,
|
||||
pipeline: Res<TlasInstanceSetupPipeline>,
|
||||
mut render_context: RenderContext,
|
||||
) {
|
||||
let bindings = &mut *bindings;
|
||||
let current_index = bindings.tlas.current_index;
|
||||
|
||||
let built = match bindings.tlas.raw {
|
||||
Some(backend) => {
|
||||
setup_tlas_instances(bindings, &pipeline_cache, &pipeline, &mut render_context)
|
||||
&& build_tlas_raw(bindings, backend, &mut render_context)
|
||||
},
|
||||
None => build_tlas_through_wgpu_core(
|
||||
bindings,
|
||||
&mesh_blas_manager,
|
||||
&tape_blas_manager,
|
||||
&mut render_context,
|
||||
),
|
||||
};
|
||||
|
||||
if built {
|
||||
bindings.tlas.built[current_index] = true;
|
||||
// This structure no longer points at whatever was retired before it,
|
||||
// which is what lets the oldest retirements go
|
||||
mesh_blas_manager.note_tlas_build();
|
||||
tape_blas_manager.note_tlas_build();
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes this frame's TLAS instance descriptors on the GPU, ready for
|
||||
/// [`build_tlas_raw`].
|
||||
///
|
||||
/// Returns whether the pass was recorded. The build has nothing to read when it
|
||||
/// wasn't.
|
||||
fn setup_tlas_instances(
|
||||
bindings: &mut RaytracingSceneBindings,
|
||||
pipeline_cache: &PipelineCache,
|
||||
pipeline: &TlasInstanceSetupPipeline,
|
||||
render_context: &mut RenderContext,
|
||||
) -> bool {
|
||||
if bindings.tlas.structures[bindings.tlas.current_index].is_none() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (Some(bind_group), Some(compute_pipeline), Some(instances), Some(scratch)) = (
|
||||
bindings.tlas.instance_setup_bind_group.as_ref(),
|
||||
pipeline
|
||||
.id
|
||||
.and_then(|id| pipeline_cache.get_compute_pipeline(id)),
|
||||
bindings.tlas.instance_descriptors.as_ref(),
|
||||
bindings.tlas.scratch.as_ref(),
|
||||
) else {
|
||||
// `advance` secures all of these before it allocates the TLAS this is
|
||||
// setting up for
|
||||
once!(warn!(
|
||||
"TLAS allocated but its instance setup pass could not be recorded: bind group={}, \
|
||||
descriptors={}, scratch={}",
|
||||
bindings.tlas.instance_setup_bind_group.is_some(),
|
||||
bindings.tlas.instance_descriptors.is_some(),
|
||||
bindings.tlas.scratch.is_some(),
|
||||
));
|
||||
return false;
|
||||
};
|
||||
|
||||
let slot_count = bindings.instances.slots.high_water_mark();
|
||||
if slot_count == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let diagnostics = render_context.diagnostic_recorder();
|
||||
let diagnostics = diagnostics.as_deref();
|
||||
let command_encoder = render_context.command_encoder();
|
||||
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"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_pipeline(compute_pipeline);
|
||||
pass.set_bind_group(0, bind_group, &[]);
|
||||
pass.dispatch_workgroups(slot_count.div_ceil(64), 1, 1);
|
||||
}
|
||||
time_span.end(command_encoder);
|
||||
|
||||
command_encoder.transition_resources(
|
||||
[
|
||||
BufferTransition {
|
||||
buffer: &**instances,
|
||||
state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
|
||||
},
|
||||
BufferTransition {
|
||||
buffer: &**scratch,
|
||||
state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
|
||||
},
|
||||
]
|
||||
.into_iter(),
|
||||
core::iter::empty(),
|
||||
);
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Builds from the descriptors [`setup_tlas_instances`] wrote, straight through
|
||||
/// `wgpu_hal`.
|
||||
fn build_tlas_raw(
|
||||
bindings: &mut RaytracingSceneBindings,
|
||||
backend: &dyn tlas_build::RawTlasBackend,
|
||||
render_context: &mut RenderContext,
|
||||
) -> bool {
|
||||
let current_index = bindings.tlas.current_index;
|
||||
let (Some(tlas), Some(instances), Some(scratch)) = (
|
||||
bindings.tlas.structures[current_index].as_mut(),
|
||||
bindings.tlas.instance_descriptors.as_ref(),
|
||||
bindings.tlas.scratch.as_ref(),
|
||||
) else {
|
||||
once!(warn!(
|
||||
"TLAS instances were set up but not built: structure={}, descriptors={}, scratch={}",
|
||||
bindings.tlas.structures[current_index].is_some(),
|
||||
bindings.tlas.instance_descriptors.is_some(),
|
||||
bindings.tlas.scratch.is_some(),
|
||||
));
|
||||
return false;
|
||||
};
|
||||
|
||||
let render_device = render_context.render_device().clone();
|
||||
let diagnostics = render_context.diagnostic_recorder();
|
||||
let diagnostics = diagnostics.as_deref();
|
||||
let time_span = diagnostics.time_span(render_context.command_encoder(), "tlas_build");
|
||||
|
||||
let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
|
||||
label: Some("tlas_build_command_encoder"),
|
||||
});
|
||||
let built = backend.build_tlas(
|
||||
&mut command_encoder,
|
||||
tlas,
|
||||
instances,
|
||||
bindings.instances.slots.high_water_mark(),
|
||||
scratch,
|
||||
);
|
||||
render_context.add_command_buffer(command_encoder.finish());
|
||||
|
||||
time_span.end(render_context.command_encoder());
|
||||
if !built {
|
||||
once!(warn!(
|
||||
"TLAS build recorded nothing; the resolved backend does not own the build resources."
|
||||
));
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// Builds from instance descriptors filled in on the CPU, through `wgpu-core`.
|
||||
///
|
||||
/// The portable path, and the only one Metal can use. It costs work per
|
||||
/// instance every frame rather than only for the ones that moved, and
|
||||
/// `wgpu-core` then re-derives the whole build from what it is handed here,
|
||||
/// which is the cost [`tlas_build`] exists to avoid.
|
||||
fn build_tlas_through_wgpu_core(
|
||||
bindings: &mut RaytracingSceneBindings,
|
||||
mesh_blas_manager: &MeshBlasManager,
|
||||
tape_blas_manager: &TapeBlasManager,
|
||||
render_context: &mut RenderContext,
|
||||
) -> bool {
|
||||
// An empty scene leaves the index unswapped, so whatever is here belongs to
|
||||
// an earlier frame and is still being traced as the previous one
|
||||
if bindings.instances.slots.high_water_mark() == 0 {
|
||||
return false;
|
||||
}
|
||||
let current_index = bindings.tlas.current_index;
|
||||
let Some(tlas) = bindings.tlas.structures[current_index].as_mut() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
{
|
||||
let _span = info_span!("fill_tlas_instances").entered();
|
||||
|
||||
// The TLAS outlives the frame, so a slot freed or deactivated since its
|
||||
// last build still holds that build's instance and has to be
|
||||
// cleared before this frame's are written
|
||||
let capacity = tlas.get().len();
|
||||
tlas[0..capacity].iter_mut().for_each(|entry| *entry = None);
|
||||
|
||||
for (slot, object, transform) in bindings.instances.drawable() {
|
||||
// A mesh can lose its acceleration structure after the instance
|
||||
// resolved against it, which leaves the slot with
|
||||
// nothing to point at for a frame
|
||||
let Some(blas) = (match object {
|
||||
Object::Mesh(mesh) => mesh_blas_manager.get(&mesh),
|
||||
Object::Tape(tape) => tape_blas_manager.get(&tape),
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
tlas[slot as usize] = Some(TlasInstance::new(blas, transform, slot, 0xFF));
|
||||
}
|
||||
}
|
||||
|
||||
let diagnostics = render_context.diagnostic_recorder();
|
||||
let diagnostics = diagnostics.as_deref();
|
||||
let command_encoder = render_context.command_encoder();
|
||||
let time_span = diagnostics.time_span(command_encoder, "tlas_build");
|
||||
command_encoder.build_acceleration_structures(&[], [&*tlas]);
|
||||
time_span.end(command_encoder);
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{TLAS_MIN_CAPACITY, tlas_capacity_for};
|
||||
|
||||
#[test]
|
||||
fn tlas_capacity_grows_geometrically_at_boundaries() {
|
||||
assert_eq!(tlas_capacity_for(0), TLAS_MIN_CAPACITY);
|
||||
assert_eq!(tlas_capacity_for(TLAS_MIN_CAPACITY), TLAS_MIN_CAPACITY);
|
||||
assert_eq!(tlas_capacity_for(TLAS_MIN_CAPACITY + 1), 192);
|
||||
assert_eq!(tlas_capacity_for(192), 192);
|
||||
assert_eq!(tlas_capacity_for(193), 288);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! 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`].
|
||||
//!
|
||||
//! 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,
|
||||
reason = "Building the TLAS without wgpu-core's per-instance cost requires wgpu_hal."
|
||||
)]
|
||||
// With neither backend compiled in every arm is cfg'd away, so nothing here is instantiated. It
|
||||
// still has to exist, because Solari compiles everywhere and only declines to load at runtime.
|
||||
#![cfg_attr(
|
||||
not(any(
|
||||
windows,
|
||||
target_os = "linux",
|
||||
target_os = "android",
|
||||
target_os = "freebsd"
|
||||
)),
|
||||
expect(
|
||||
dead_code,
|
||||
unused_variables,
|
||||
reason = "no backend with a raw TLAS build path is compiled in for this target"
|
||||
)
|
||||
)]
|
||||
|
||||
use bevy_render::{
|
||||
render_resource::{Blas, Buffer, BufferDescriptor, BufferUsages, CommandEncoder, Tlas},
|
||||
renderer::RenderDevice,
|
||||
};
|
||||
use core::marker::PhantomData;
|
||||
use wgpu::{hal, BufferUses};
|
||||
|
||||
/// Size of one TLAS instance descriptor, on both Vulkan and DXR.
|
||||
pub const INSTANCE_DESCRIPTOR_SIZE: u64 = 64;
|
||||
|
||||
/// Flags the TLAS is created with, which its build has to be given again.
|
||||
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`].
|
||||
pub trait RawTlasBackend: Send + Sync {
|
||||
/// Scratch space a TLAS build over `instance_count` instances of `instances` needs.
|
||||
fn scratch_size(
|
||||
&self,
|
||||
render_device: &RenderDevice,
|
||||
instances: &Buffer,
|
||||
instance_count: u32,
|
||||
) -> Option<u64>;
|
||||
|
||||
/// 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.
|
||||
fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer>;
|
||||
|
||||
/// 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'
|
||||
/// 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.
|
||||
///
|
||||
/// 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,
|
||||
tlas: &mut Tlas,
|
||||
instances: &Buffer,
|
||||
instance_count: u32,
|
||||
scratch: &Buffer,
|
||||
) -> bool;
|
||||
}
|
||||
|
||||
/// The backend to build through, or `None` where this device has no raw path.
|
||||
pub fn resolve(render_device: &RenderDevice) -> Option<&'static dyn RawTlasBackend> {
|
||||
let device = render_device.wgpu_device();
|
||||
|
||||
#[cfg(any(
|
||||
windows,
|
||||
target_os = "linux",
|
||||
target_os = "android",
|
||||
target_os = "freebsd"
|
||||
))]
|
||||
// SAFETY: the handle is only read, and is dropped with the guard
|
||||
if unsafe { device.as_hal::<hal::api::Vulkan>() }.is_some() {
|
||||
return Some(&Hal::<hal::api::Vulkan>::NEW);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
// SAFETY: the handle is only read, and is dropped with the guard
|
||||
if unsafe { device.as_hal::<hal::api::Dx12>() }.is_some() {
|
||||
return Some(&Hal::<hal::api::Dx12>::NEW);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// [`RawTlasBackend`] for one hal backend.
|
||||
///
|
||||
/// `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.
|
||||
fn record_build(
|
||||
&self,
|
||||
encoder: &mut CommandEncoder,
|
||||
tlas: &mut Tlas,
|
||||
instances: &Buffer,
|
||||
instance_count: u32,
|
||||
scratch: &Buffer,
|
||||
) -> Option<()> {
|
||||
use hal::CommandEncoder as _;
|
||||
|
||||
// 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
|
||||
let guard = unsafe { buffer.as_hal::<A>() }?;
|
||||
Some(core::ptr::from_ref::<A::Buffer>(&*guard))
|
||||
};
|
||||
let hal_instances = buffer_address(instances)?;
|
||||
let hal_scratch = buffer_address(scratch)?;
|
||||
// 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
|
||||
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,
|
||||
});
|
||||
|
||||
let descriptor = hal::BuildAccelerationStructureDescriptor {
|
||||
entries: &entries,
|
||||
mode: hal::AccelerationStructureBuildMode::Build,
|
||||
flags: TLAS_BUILD_FLAGS,
|
||||
source_acceleration_structure: None,
|
||||
destination_acceleration_structure: &*hal_tlas,
|
||||
scratch_buffer: hal_scratch,
|
||||
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.
|
||||
//
|
||||
// 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.
|
||||
encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
|
||||
usage: hal::StateTransition {
|
||||
from: hal::AccelerationStructureUses::SHADER_INPUT
|
||||
| hal::AccelerationStructureUses::COPY_DST,
|
||||
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
|
||||
encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
|
||||
usage: hal::StateTransition {
|
||||
from: hal::AccelerationStructureUses::BUILD_OUTPUT,
|
||||
to: hal::AccelerationStructureUses::SHADER_INPUT,
|
||||
},
|
||||
});
|
||||
|
||||
Some(())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: hal::Api> RawTlasBackend for Hal<A> {
|
||||
fn scratch_size(
|
||||
&self,
|
||||
render_device: &RenderDevice,
|
||||
instances: &Buffer,
|
||||
instance_count: u32,
|
||||
) -> Option<u64> {
|
||||
use hal::Device as _;
|
||||
|
||||
// SAFETY: the handle is only read, and is dropped with the guard
|
||||
let hal_device = unsafe { render_device.wgpu_device().as_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
|
||||
let entries =
|
||||
hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
|
||||
buffer: Some(&*hal_instances),
|
||||
offset: 0,
|
||||
count: instance_count,
|
||||
});
|
||||
|
||||
// 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,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
Some(sizes.build_scratch_size)
|
||||
}
|
||||
|
||||
fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer> {
|
||||
use hal::Device as _;
|
||||
|
||||
let device = render_device.wgpu_device();
|
||||
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
|
||||
unsafe {
|
||||
hal_device.create_buffer(&hal::BufferDescriptor {
|
||||
label: Some("solari_tlas_scratch"),
|
||||
size,
|
||||
usage: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
|
||||
memory_flags: hal::MemoryFlags::empty(),
|
||||
})
|
||||
}
|
||||
.ok()?
|
||||
};
|
||||
|
||||
// `usage` is only consulted for wgpu-level validation, which this buffer never sees
|
||||
let descriptor = BufferDescriptor {
|
||||
label: Some("solari_tlas_scratch"),
|
||||
size,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
};
|
||||
|
||||
// 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())
|
||||
}
|
||||
|
||||
fn build_tlas(
|
||||
&self,
|
||||
encoder: &mut CommandEncoder,
|
||||
tlas: &mut Tlas,
|
||||
instances: &Buffer,
|
||||
instance_count: u32,
|
||||
scratch: &Buffer,
|
||||
) -> bool {
|
||||
if self
|
||||
.record_build(encoder, tlas, instances, instance_count, scratch)
|
||||
.is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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`
|
||||
unsafe {
|
||||
encoder.mark_acceleration_structures_built(core::iter::empty::<&Blas>(), [&*tlas]);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import bevy_pbr::render::pbr_functions::calculate_tbn_mikktspace;
|
||||
import bevy_render::maths::affine3_to_square;
|
||||
|
||||
enable wgpu_ray_query;
|
||||
enable wgpu_binding_array;
|
||||
|
||||
struct InstanceGeometryIds {
|
||||
vertex_buffer_id: u32,
|
||||
vertex_buffer_offset: u32,
|
||||
index_buffer_id: u32,
|
||||
index_buffer_offset: u32,
|
||||
triangle_count: u32,
|
||||
}
|
||||
|
||||
struct InstanceTapeIds {
|
||||
aabb_buffer_id: u32,
|
||||
aabb_buffer_offset: u32,
|
||||
aabb_count: u32,
|
||||
}
|
||||
|
||||
struct VertexBuffer { vertices: array<PackedVertex> }
|
||||
|
||||
struct IndexBuffer { indices: array<u32> }
|
||||
|
||||
struct AabbBuffer { indices: array<PackedAabb> }
|
||||
|
||||
struct PackedVertex {
|
||||
a: vec4<f32>,
|
||||
b: vec4<f32>,
|
||||
tangent: vec4<f32>,
|
||||
}
|
||||
|
||||
struct PackedAabb {
|
||||
min: vec3<f32>,
|
||||
max: vec3<f32>,
|
||||
}
|
||||
|
||||
struct Vertex {
|
||||
position: vec3<f32>,
|
||||
normal: vec3<f32>,
|
||||
uv: vec2<f32>,
|
||||
tangent: vec4<f32>,
|
||||
}
|
||||
|
||||
fn unpack_vertex(packed: PackedVertex) -> Vertex {
|
||||
var vertex: Vertex;
|
||||
vertex.position = packed.a.xyz;
|
||||
vertex.normal = vec3(packed.a.w, packed.b.xy);
|
||||
vertex.uv = packed.b.zw;
|
||||
vertex.tangent = packed.tangent;
|
||||
return vertex;
|
||||
}
|
||||
|
||||
struct Material {
|
||||
normal_map_texture_id: u32,
|
||||
base_color_texture_id: u32,
|
||||
emissive_texture_id: u32,
|
||||
metallic_roughness_texture_id: u32,
|
||||
|
||||
base_color: vec3<f32>,
|
||||
perceptual_roughness: f32,
|
||||
emissive: vec3<f32>,
|
||||
metallic: f32,
|
||||
_padding: vec3<f32>,
|
||||
reflectance: f32,
|
||||
}
|
||||
|
||||
const TEXTURE_MAP_NONE = 0xFFFFFFFFu;
|
||||
|
||||
const MIRROR_ROUGHNESS_THRESHOLD = 0.001f;
|
||||
|
||||
struct LightSource {
|
||||
kind: u32, // 1 bit for kind, 31 bits for extra data
|
||||
id: u32,
|
||||
}
|
||||
|
||||
const LIGHT_SOURCE_KIND_EMISSIVE_MESH = 0u;
|
||||
const LIGHT_SOURCE_KIND_DIRECTIONAL = 1u;
|
||||
|
||||
struct DirectionalLight {
|
||||
direction_to_light: vec3<f32>,
|
||||
cos_theta_max: f32,
|
||||
luminance: vec3<f32>,
|
||||
inverse_pdf: f32,
|
||||
}
|
||||
|
||||
struct EnvironmentMapLight {
|
||||
light_from_world: mat3x3<f32>,
|
||||
intensity: f32,
|
||||
}
|
||||
|
||||
const LIGHT_NOT_PRESENT_THIS_FRAME = 0xFFFFFFFFu;
|
||||
|
||||
@group(0) @binding(0) var<storage> vertex_buffers: binding_array<VertexBuffer>;
|
||||
@group(0) @binding(1) var<storage> index_buffers: binding_array<IndexBuffer>;
|
||||
@group(0) @binding(2) var<storage> aabb_buffers: binding_array<AabbBuffer>;
|
||||
@group(0) @binding(3) var textures: binding_array<texture_2d<f32>>;
|
||||
@group(0) @binding(4) var samplers: binding_array<sampler>;
|
||||
@group(0) @binding(5) var<storage> materials: array<Material>;
|
||||
@group(0) @binding(6) var tlas: acceleration_structure;
|
||||
@group(0) @binding(7) var previous_frame_tlas: acceleration_structure;
|
||||
@group(0) @binding(8) var<storage> transforms: array<mat3x4<f32>>;
|
||||
@group(0) @binding(9) var<storage> previous_frame_transforms: array<mat3x4<f32>>;
|
||||
@group(0) @binding(10) var<storage> geometry_ids: array<InstanceGeometryIds>;
|
||||
@group(0) @binding(11) var<storage> tape_ids: array<InstanceTapeIds>;
|
||||
@group(0) @binding(12) var<storage> material_ids: array<u32>;
|
||||
@group(0) @binding(13) var<storage> light_sources: array<LightSource>;
|
||||
@group(0) @binding(14) var<storage> directional_lights: array<DirectionalLight>;
|
||||
@group(0) @binding(15) var<storage> previous_frame_light_id_translations: 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 environment_map: texture_cube<f32>;
|
||||
@group(0) @binding(19) var environment_map_sampler: sampler;
|
||||
@group(0) @binding(20) var<storage> environment_map_light: EnvironmentMapLight;
|
||||
|
||||
const RAY_T_MIN = 0.001f;
|
||||
const RAY_T_MAX = 100000.0f;
|
||||
|
||||
const RAY_NO_CULL = 0xFFu;
|
||||
|
||||
fn trace_ray(ray_origin: vec3<f32>, ray_direction: vec3<f32>, ray_t_min: f32, ray_t_max: f32, ray_flag: u32) -> RayIntersection {
|
||||
let ray = RayDesc(ray_flag, RAY_NO_CULL, ray_t_min, ray_t_max, ray_origin, ray_direction);
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, tlas, ray);
|
||||
rayQueryProceed(&rq);
|
||||
return rayQueryGetCommittedIntersection(&rq);
|
||||
}
|
||||
|
||||
fn trace_ray_previous_frame(ray_origin: vec3<f32>, ray_direction: vec3<f32>, ray_t_min: f32, ray_t_max: f32, ray_flag: u32) -> RayIntersection {
|
||||
let ray = RayDesc(ray_flag, RAY_NO_CULL, ray_t_min, ray_t_max, ray_origin, ray_direction);
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, previous_frame_tlas, ray);
|
||||
rayQueryProceed(&rq);
|
||||
return rayQueryGetCommittedIntersection(&rq);
|
||||
}
|
||||
|
||||
fn sample_texture(id: u32, uv: vec2<f32>) -> vec3<f32> {
|
||||
return textureSampleLevel(textures[id], samplers[id], uv, 0.0).rgb; // TODO: Mipmap
|
||||
}
|
||||
|
||||
struct ResolvedMaterial {
|
||||
base_color: vec3<f32>,
|
||||
emissive: vec3<f32>,
|
||||
reflectance: f32,
|
||||
perceptual_roughness: f32,
|
||||
roughness: f32,
|
||||
metallic: f32,
|
||||
}
|
||||
|
||||
struct ResolvedRayHitFull {
|
||||
world_position: vec3<f32>,
|
||||
previous_frame_world_position: vec3<f32>,
|
||||
world_normal: vec3<f32>,
|
||||
geometric_world_normal: vec3<f32>,
|
||||
world_tangent: vec4<f32>,
|
||||
uv: vec2<f32>,
|
||||
triangle_area: f32,
|
||||
triangle_count: u32,
|
||||
material: ResolvedMaterial,
|
||||
}
|
||||
|
||||
fn resolve_material(material: Material, uv: vec2<f32>) -> ResolvedMaterial {
|
||||
var m: ResolvedMaterial;
|
||||
|
||||
m.base_color = material.base_color.rgb;
|
||||
if material.base_color_texture_id != TEXTURE_MAP_NONE {
|
||||
m.base_color *= sample_texture(material.base_color_texture_id, uv);
|
||||
}
|
||||
|
||||
m.emissive = material.emissive.rgb;
|
||||
if material.emissive_texture_id != TEXTURE_MAP_NONE {
|
||||
m.emissive *= sample_texture(material.emissive_texture_id, uv);
|
||||
}
|
||||
|
||||
m.reflectance = material.reflectance;
|
||||
|
||||
m.perceptual_roughness = material.perceptual_roughness;
|
||||
m.metallic = material.metallic;
|
||||
if material.metallic_roughness_texture_id != TEXTURE_MAP_NONE {
|
||||
let metallic_roughness = sample_texture(material.metallic_roughness_texture_id, uv);
|
||||
m.perceptual_roughness *= metallic_roughness.g;
|
||||
m.metallic *= metallic_roughness.b;
|
||||
}
|
||||
|
||||
m.roughness = m.perceptual_roughness * m.perceptual_roughness;
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
fn resolve_ray_hit_full(ray_hit: RayIntersection) -> ResolvedRayHitFull {
|
||||
let barycentrics = vec3(1.0 - ray_hit.barycentrics.x - ray_hit.barycentrics.y, ray_hit.barycentrics);
|
||||
return resolve_triangle_data_full(ray_hit.instance_custom_data, ray_hit.primitive_index, barycentrics);
|
||||
}
|
||||
|
||||
fn load_vertices(instance_geometry_ids: InstanceGeometryIds, triangle_id: u32) -> array<Vertex, 3> {
|
||||
let index_buffer = &index_buffers[instance_geometry_ids.index_buffer_id].indices;
|
||||
let vertex_buffer = &vertex_buffers[instance_geometry_ids.vertex_buffer_id].vertices;
|
||||
|
||||
let indices_i = (triangle_id * 3u) + vec3(0u, 1u, 2u) + instance_geometry_ids.index_buffer_offset;
|
||||
let indices = vec3((*index_buffer)[indices_i.x], (*index_buffer)[indices_i.y], (*index_buffer)[indices_i.z]) + instance_geometry_ids.vertex_buffer_offset;
|
||||
|
||||
return array<Vertex, 3>(
|
||||
unpack_vertex((*vertex_buffer)[indices.x]),
|
||||
unpack_vertex((*vertex_buffer)[indices.y]),
|
||||
unpack_vertex((*vertex_buffer)[indices.z])
|
||||
);
|
||||
}
|
||||
|
||||
fn transform_positions(transform: mat4x4<f32>, vertices: array<Vertex, 3>) -> array<vec3<f32>, 3> {
|
||||
return array<vec3<f32>, 3>(
|
||||
(transform * vec4(vertices[0].position, 1.0)).xyz,
|
||||
(transform * vec4(vertices[1].position, 1.0)).xyz,
|
||||
(transform * vec4(vertices[2].position, 1.0)).xyz
|
||||
);
|
||||
}
|
||||
|
||||
fn resolve_triangle_data_full(instance_id: u32, triangle_id: u32, barycentrics: vec3<f32>) -> ResolvedRayHitFull {
|
||||
let material_id = material_ids[instance_id];
|
||||
let material = materials[material_id];
|
||||
|
||||
let transform = affine3_to_square(transforms[instance_id]);
|
||||
let previous_frame_transform = affine3_to_square(previous_frame_transforms[instance_id]);
|
||||
|
||||
let instance_geometry_ids = geometry_ids[instance_id];
|
||||
let vertices = load_vertices(instance_geometry_ids, triangle_id);
|
||||
|
||||
let world_vertices = transform_positions(transform, vertices);
|
||||
let world_position = mat3x3(world_vertices[0], world_vertices[1], world_vertices[2]) * barycentrics;
|
||||
|
||||
let previous_frame_world_vertices = transform_positions(previous_frame_transform, vertices);
|
||||
let previous_frame_world_position = mat3x3(previous_frame_world_vertices[0], previous_frame_world_vertices[1], previous_frame_world_vertices[2]) * barycentrics;
|
||||
|
||||
let uv = mat3x2(vertices[0].uv, vertices[1].uv, vertices[2].uv) * barycentrics;
|
||||
|
||||
let transform_3x3 = mat3x3(transform[0].xyz, transform[1].xyz, transform[2].xyz);
|
||||
|
||||
let cofactor = mat3x3(cross(transform_3x3[1], transform_3x3[2]), cross(transform_3x3[2], transform_3x3[0]), cross(transform_3x3[0], transform_3x3[1]));
|
||||
let determinant = dot(transform_3x3[0], cofactor[0]);
|
||||
let determinant_sign = select(sign(determinant), 1.0, determinant == 0.0);
|
||||
|
||||
let local_tangent = mat3x3(vertices[0].tangent.xyz, vertices[1].tangent.xyz, vertices[2].tangent.xyz) * barycentrics;
|
||||
let world_tangent = vec4(normalize(transform_3x3 * local_tangent), vertices[0].tangent.w * determinant_sign);
|
||||
|
||||
let local_normal = mat3x3(vertices[0].normal, vertices[1].normal, vertices[2].normal) * barycentrics; // TODO: Use barycentric lerp, ray_hit.object_to_world, cross product geo normal
|
||||
var world_normal = normalize(determinant_sign * (cofactor * local_normal));
|
||||
|
||||
let geometric_world_normal = world_normal;
|
||||
if material.normal_map_texture_id != TEXTURE_MAP_NONE {
|
||||
let TBN = calculate_tbn_mikktspace(world_normal, world_tangent);
|
||||
let T = TBN[0];
|
||||
let B = TBN[1];
|
||||
let N = TBN[2];
|
||||
var Nt = sample_texture(material.normal_map_texture_id, uv) * 2.0 - 1.0;
|
||||
Nt.z = sqrt(max(1.0 - dot(Nt.xy, Nt.xy), 0.0)); // Reconstruct Z to support two-channel normal maps
|
||||
world_normal = normalize(Nt.x * T + Nt.y * B + Nt.z * N);
|
||||
}
|
||||
|
||||
let triangle_edge0 = world_vertices[0] - world_vertices[1];
|
||||
let triangle_edge1 = world_vertices[0] - world_vertices[2];
|
||||
let triangle_area = length(cross(triangle_edge0, triangle_edge1)) / 2.0;
|
||||
|
||||
let resolved_material = resolve_material(material, uv);
|
||||
|
||||
return ResolvedRayHitFull(
|
||||
world_position,
|
||||
previous_frame_world_position,
|
||||
world_normal,
|
||||
geometric_world_normal,
|
||||
world_tangent,
|
||||
uv,
|
||||
triangle_area,
|
||||
instance_geometry_ids.triangle_count,
|
||||
resolved_material,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
|
||||
import bevy_pbr::render::pbr_lighting::{D_GGX, V_SmithGGXCorrelated, specular_multiscatter};
|
||||
import bevy_pbr::render::pbr_functions::calculate_F0_dielectric;
|
||||
import bevy_pbr::render::utils::{rand_f, sample_cosine_hemisphere};
|
||||
import bevy_render::maths::{PI, orthonormalize};
|
||||
import package::scene::sampling::{sample_ggx_vndf, ggx_vndf_pdf, ggx_vndf_sample_invalid};
|
||||
import package::scene::bindings::{ResolvedMaterial, MIRROR_ROUGHNESS_THRESHOLD, brdf_dfg_lut, brdf_dfg_lut_sampler};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
struct EvaluateAndSampleBrdfResult {
|
||||
wi: vec3<f32>,
|
||||
throughput: vec3<f32>,
|
||||
pdf: f32,
|
||||
diffuse_selected: bool,
|
||||
}
|
||||
|
||||
struct LobeReflectances {
|
||||
specular: vec3<f32>,
|
||||
diffuse: vec3<f32>,
|
||||
}
|
||||
|
||||
/// Hemispherical reflectance of each lobe
|
||||
fn lobe_reflectances(F0_metal: vec3<f32>, F0_dielectric: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> LobeReflectances {
|
||||
let multiscattering_factor = 1.0 / (F_ab.x + F_ab.y) - 1.0;
|
||||
let rho_specular_metallic = (F0_metal * F_ab.x + F_ab.y) * (1.0 + F0_metal * multiscattering_factor);
|
||||
let rho_specular_dielectric = (F0_dielectric * F_ab.x + F_ab.y) * (1.0 + F0_dielectric * multiscattering_factor);
|
||||
return LobeReflectances(
|
||||
mix(rho_specular_dielectric, rho_specular_metallic, material.metallic),
|
||||
(1.0 - material.metallic) * (1.0 - rho_specular_dielectric) * material.base_color,
|
||||
);
|
||||
}
|
||||
|
||||
fn specular_lobe_sampling_probability(rho: LobeReflectances, perceptual_roughness: f32) -> f32 {
|
||||
let specular_luminance = luminance(rho.specular);
|
||||
let total_luminance = specular_luminance + luminance(rho.diffuse);
|
||||
let energy_probability = specular_luminance / max(total_luminance, 0.0001);
|
||||
|
||||
// Give smooth dielectric reflections more specular samples to prevent undersampling
|
||||
let roughness_biased_probability = mix(0.5, energy_probability, perceptual_roughness);
|
||||
return max(energy_probability, roughness_biased_probability);
|
||||
}
|
||||
|
||||
fn evaluate_and_sample_brdf(
|
||||
wo: vec3<f32>,
|
||||
world_normal: vec3<f32>,
|
||||
material: ResolvedMaterial,
|
||||
F_ab: vec2<f32>,
|
||||
rng: ptr<function, u32>,
|
||||
) -> EvaluateAndSampleBrdfResult {
|
||||
let NdotV = dot(world_normal, wo);
|
||||
if NdotV < 0.0001 { return EvaluateAndSampleBrdfResult(vec3(0.0), vec3(0.0), 0.0, false); }
|
||||
let F0_metal = material.base_color;
|
||||
let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
|
||||
let rho = lobe_reflectances(F0_metal, F0_dielectric, material, F_ab);
|
||||
let specular_weight = specular_lobe_sampling_probability(rho, material.perceptual_roughness);
|
||||
let diffuse_weight = 1.0 - specular_weight;
|
||||
|
||||
let TBN = orthonormalize(world_normal);
|
||||
let T = TBN[0];
|
||||
let B = TBN[1];
|
||||
let N = TBN[2];
|
||||
|
||||
let wo_tangent = vec3(dot(wo, T), dot(wo, B), dot(wo, N));
|
||||
|
||||
var wi: vec3<f32>;
|
||||
var wi_tangent: vec3<f32>;
|
||||
let diffuse_selected = rand_f(rng) < diffuse_weight;
|
||||
if diffuse_selected {
|
||||
wi = sample_cosine_hemisphere(world_normal, rng);
|
||||
wi_tangent = vec3(dot(wi, T), dot(wi, B), dot(wi, N));
|
||||
} else {
|
||||
wi_tangent = sample_ggx_vndf(wo_tangent, material.roughness, rng);
|
||||
if ggx_vndf_sample_invalid(wi_tangent) {
|
||||
return EvaluateAndSampleBrdfResult(vec3(0.0), vec3(0.0), 0.0, false);
|
||||
}
|
||||
wi = wi_tangent.x * T + wi_tangent.y * B + wi_tangent.z * N;
|
||||
|
||||
// Mirror specular is a delta function
|
||||
if material.roughness <= MIRROR_ROUGHNESS_THRESHOLD {
|
||||
return EvaluateAndSampleBrdfResult(
|
||||
wi,
|
||||
evaluate_specular_brdf(wo, wi, world_normal, material, F_ab) / specular_weight,
|
||||
bitcast<f32>(0x7F800000u), // INF
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let diffuse_pdf = wi_tangent.z / PI;
|
||||
let specular_pdf = ggx_vndf_pdf(wo_tangent, wi_tangent, material.roughness);
|
||||
let pdf = (diffuse_weight * diffuse_pdf) + (specular_weight * specular_pdf);
|
||||
let throughput = evaluate_brdf(wo, wi, world_normal, material, F_ab) / pdf;
|
||||
return EvaluateAndSampleBrdfResult(wi, throughput, pdf, diffuse_selected);
|
||||
}
|
||||
|
||||
fn evaluate_brdf(
|
||||
wo: vec3<f32>,
|
||||
wi: vec3<f32>,
|
||||
world_normal: vec3<f32>,
|
||||
material: ResolvedMaterial,
|
||||
F_ab: vec2<f32>,
|
||||
) -> vec3<f32> {
|
||||
return evaluate_diffuse_brdf(wo, wi, world_normal, material, F_ab) + evaluate_specular_brdf(wo, wi, world_normal, material, F_ab);
|
||||
}
|
||||
|
||||
fn evaluate_diffuse_brdf(wo: vec3<f32>, wi: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> vec3<f32> {
|
||||
let NdotL = dot(world_normal, wi);
|
||||
let NdotV = dot(world_normal, wo);
|
||||
if NdotL < 0.0001 || NdotV < 0.0001 { return vec3(0.0); }
|
||||
let F0_metal = material.base_color;
|
||||
let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
|
||||
let rho = lobe_reflectances(F0_metal, F0_dielectric, material, F_ab);
|
||||
return rho.diffuse / PI * NdotL;
|
||||
}
|
||||
|
||||
fn evaluate_specular_brdf(wo: vec3<f32>, wi: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> vec3<f32> {
|
||||
let H = normalize(wi + wo);
|
||||
let NdotL = dot(world_normal, wi);
|
||||
let NdotH = min(dot(world_normal, H), 1.0);
|
||||
let LdotH = dot(wi, H);
|
||||
let NdotV = dot(world_normal, wo);
|
||||
if NdotL < 0.0001 || NdotH < 0.0001 || LdotH < 0.0001 || NdotV < 0.0001 { return vec3(0.0); }
|
||||
|
||||
let F0_metal = material.base_color;
|
||||
let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
|
||||
|
||||
if material.roughness <= MIRROR_ROUGHNESS_THRESHOLD {
|
||||
let mirror_wi = 2.0 * NdotV * world_normal - wo;
|
||||
if distance(mirror_wi, wi) < 0.0001 {
|
||||
let F_metal = fresnel(F0_metal, LdotH);
|
||||
let F_dielectric = fresnel(F0_dielectric, LdotH);
|
||||
return mix(F_dielectric, F_metal, material.metallic);
|
||||
} else {
|
||||
return vec3(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
let D = D_GGX(material.roughness, NdotH);
|
||||
let Vs = V_SmithGGXCorrelated(material.roughness, NdotV, NdotL);
|
||||
let F_metal = fresnel(F0_metal, LdotH);
|
||||
let F_dielectric = fresnel(F0_dielectric, LdotH);
|
||||
return mix(specular_multiscatter(D, Vs, F_dielectric, F0_dielectric, F_ab, 1.0),
|
||||
specular_multiscatter(D, Vs, F_metal, F0_metal, F_ab, 1.0),
|
||||
material.metallic) * NdotL;
|
||||
}
|
||||
|
||||
fn brdf_pdf(wo: vec3<f32>, wi: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> f32 {
|
||||
let NdotV = max(dot(world_normal, wo), 0.0001);
|
||||
let F0_metal = material.base_color;
|
||||
let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
|
||||
let rho = lobe_reflectances(F0_metal, F0_dielectric, material, F_ab);
|
||||
let specular_weight = specular_lobe_sampling_probability(rho, material.perceptual_roughness);
|
||||
let diffuse_weight = 1.0 - specular_weight;
|
||||
|
||||
let TBN = orthonormalize(world_normal);
|
||||
let T = TBN[0];
|
||||
let B = TBN[1];
|
||||
let N = TBN[2];
|
||||
|
||||
let wo_tangent = vec3(dot(wo, T), dot(wo, B), dot(wo, N));
|
||||
let wi_tangent = vec3(dot(wi, T), dot(wi, B), dot(wi, N));
|
||||
|
||||
let diffuse_pdf = wi_tangent.z / PI;
|
||||
let specular_pdf = ggx_vndf_pdf(wo_tangent, wi_tangent, material.roughness);
|
||||
return (diffuse_weight * diffuse_pdf) + (specular_weight * specular_pdf);
|
||||
}
|
||||
|
||||
fn fresnel(f0: vec3<f32>, LdotH: f32) -> vec3<f32> {
|
||||
return f0 + (1.0 - f0) * pow(saturate(1.0 - LdotH), 5.0);
|
||||
}
|
||||
|
||||
/// Scale/bias approximation
|
||||
fn F_AB(perceptual_roughness: f32, NdotV: f32) -> vec2<f32> {
|
||||
return textureSampleLevel(brdf_dfg_lut, brdf_dfg_lut_sampler, vec2<f32>(NdotV, perceptual_roughness), 0.0).rg;
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
use bevy_asset::{AssetEvent, AssetId, Assets, Handle};
|
||||
use bevy_camera::Camera;
|
||||
use bevy_ecs::{
|
||||
lifecycle::RemovedComponents,
|
||||
message::MessageReader,
|
||||
query::{Added, Changed, Or, With},
|
||||
resource::Resource,
|
||||
system::{Commands, Query, Res, ResMut},
|
||||
};
|
||||
use bevy_image::Image;
|
||||
use bevy_light::{EnvironmentMapLight, GeneratedEnvironmentMapLight};
|
||||
use bevy_math::Quat;
|
||||
use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial};
|
||||
use bevy_platform::collections::HashMap;
|
||||
use bevy_render::{Extract, sync_world::RenderEntity};
|
||||
use bevy_transform::components::GlobalTransform;
|
||||
use bevy_utils::once;
|
||||
use tracing::warn;
|
||||
|
||||
use super::{RaytracingMesh3d, RaytracingSceneBindings};
|
||||
use crate::scene::Tape3d;
|
||||
|
||||
/// Creates or removes components in the render world related to raytracing
|
||||
/// mesh instances.
|
||||
pub fn extract_raytracing_scene_meshes_structural(
|
||||
new_instances: Extract<
|
||||
Query<
|
||||
(
|
||||
RenderEntity,
|
||||
&RaytracingMesh3d,
|
||||
&MeshMaterial3d<StandardMaterial>,
|
||||
&GlobalTransform,
|
||||
Option<&PreviousGlobalTransform>,
|
||||
),
|
||||
Added<RaytracingMesh3d>,
|
||||
>,
|
||||
>,
|
||||
mut removed_raytracing_meshes: Extract<RemovedComponents<RaytracingMesh3d>>,
|
||||
render_entities: Extract<Query<RenderEntity>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
// Process removed components before additions, that way it properly handles
|
||||
// same-frame removal->insertion
|
||||
for main_entity in removed_raytracing_meshes.read() {
|
||||
if let Ok(render_entity) = render_entities.get(main_entity) {
|
||||
commands.entity(render_entity).remove::<RaytracingMesh3d>();
|
||||
}
|
||||
}
|
||||
|
||||
for (render_entity, mesh, material, transform, previous_frame_transform) in &new_instances {
|
||||
commands.entity(render_entity).insert((
|
||||
mesh.clone(),
|
||||
material.clone(),
|
||||
*transform,
|
||||
previous_frame_transform
|
||||
.cloned()
|
||||
.unwrap_or(PreviousGlobalTransform(transform.affine())),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates or removes components in the render world related to raytracing
|
||||
/// tape instances.
|
||||
pub fn extract_raytracing_scene_tapes_structural(
|
||||
new_instances: Extract<
|
||||
Query<
|
||||
(
|
||||
RenderEntity,
|
||||
&Tape3d,
|
||||
&MeshMaterial3d<StandardMaterial>,
|
||||
&GlobalTransform,
|
||||
Option<&PreviousGlobalTransform>,
|
||||
),
|
||||
Added<Tape3d>,
|
||||
>,
|
||||
>,
|
||||
mut removed_raytracing_tapes: Extract<RemovedComponents<Tape3d>>,
|
||||
render_entities: Extract<Query<RenderEntity>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
// Process removed components before additions, that way it properly handles
|
||||
// same-frame removal->insertion
|
||||
for main_entity in removed_raytracing_tapes.read() {
|
||||
if let Ok(render_entity) = render_entities.get(main_entity) {
|
||||
commands.entity(render_entity).remove::<Tape3d>();
|
||||
}
|
||||
}
|
||||
|
||||
for (render_entity, tape, material, transform, previous_frame_transform) in &new_instances {
|
||||
commands.entity(render_entity).insert((
|
||||
tape.clone(),
|
||||
material.clone(),
|
||||
*transform,
|
||||
previous_frame_transform
|
||||
.cloned()
|
||||
.unwrap_or(PreviousGlobalTransform(transform.affine())),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the transforms of moved raytracing instances from the main world
|
||||
/// straight into their GPU buffers.
|
||||
pub fn extract_raytracing_scene_transforms(
|
||||
main_instances: Extract<
|
||||
Query<
|
||||
(
|
||||
RenderEntity,
|
||||
&GlobalTransform,
|
||||
Option<&PreviousGlobalTransform>,
|
||||
),
|
||||
(
|
||||
Or<(Changed<GlobalTransform>, Changed<PreviousGlobalTransform>)>,
|
||||
Or<(With<RaytracingMesh3d>, With<Tape3d>)>,
|
||||
),
|
||||
>,
|
||||
>,
|
||||
bindings: Res<RaytracingSceneBindings>,
|
||||
) {
|
||||
main_instances
|
||||
.par_iter()
|
||||
.for_each(|(render_entity, transform, previous_frame_transform)| {
|
||||
let previous_frame_transform = previous_frame_transform
|
||||
.cloned()
|
||||
.unwrap_or(PreviousGlobalTransform(transform.affine()));
|
||||
|
||||
bindings.move_instance(render_entity, transform, &previous_frame_transform);
|
||||
});
|
||||
}
|
||||
|
||||
/// Updates the mesh and material of existing raytracing instances in the render
|
||||
/// world.
|
||||
pub fn extract_raytracing_scene_meshes_and_materials(
|
||||
main_instances: Extract<
|
||||
Query<
|
||||
(
|
||||
RenderEntity,
|
||||
&RaytracingMesh3d,
|
||||
&MeshMaterial3d<StandardMaterial>,
|
||||
),
|
||||
Or<(
|
||||
Changed<RaytracingMesh3d>,
|
||||
Changed<MeshMaterial3d<StandardMaterial>>,
|
||||
)>,
|
||||
>,
|
||||
>,
|
||||
mut render_instances: Query<(&mut RaytracingMesh3d, &mut MeshMaterial3d<StandardMaterial>)>,
|
||||
) {
|
||||
for (render_entity, new_mesh, new_material) in &main_instances {
|
||||
if let Ok((mut mesh, mut material)) = render_instances.get_mut(render_entity) {
|
||||
*mesh = new_mesh.clone();
|
||||
*material = new_material.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the tape and material of existing raytracing instances in the render
|
||||
/// world.
|
||||
pub fn extract_raytracing_scene_tapes_and_materials(
|
||||
main_instances: Extract<
|
||||
Query<
|
||||
(RenderEntity, &Tape3d, &MeshMaterial3d<StandardMaterial>),
|
||||
Or<(Changed<Tape3d>, Changed<MeshMaterial3d<StandardMaterial>>)>,
|
||||
>,
|
||||
>,
|
||||
mut render_instances: Query<(&mut Tape3d, &mut MeshMaterial3d<StandardMaterial>)>,
|
||||
) {
|
||||
for (render_entity, new_tape, new_material) in &main_instances {
|
||||
if let Ok((mut tape, mut material)) = render_instances.get_mut(render_entity) {
|
||||
*tape = new_tape.clone();
|
||||
*material = new_material.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The set of [`StandardMaterial`] in the scene, mirrored into the render
|
||||
/// world.
|
||||
#[derive(Resource, Default)]
|
||||
pub struct StandardMaterialAssets {
|
||||
materials: HashMap<AssetId<StandardMaterial>, StandardMaterial>,
|
||||
/// Materials added or modified this frame.
|
||||
pub changed: Vec<AssetId<StandardMaterial>>,
|
||||
/// Materials removed this frame.
|
||||
pub removed: Vec<AssetId<StandardMaterial>>,
|
||||
}
|
||||
|
||||
impl StandardMaterialAssets {
|
||||
pub fn get(&self, id: &AssetId<StandardMaterial>) -> Option<&StandardMaterial> {
|
||||
self.materials.get(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps [`StandardMaterialAssets`] up to date in the render world.
|
||||
pub fn extract_raytracing_material_assets(
|
||||
main_materials: Extract<Res<Assets<StandardMaterial>>>,
|
||||
mut render_materials: ResMut<StandardMaterialAssets>,
|
||||
mut events: Extract<MessageReader<AssetEvent<StandardMaterial>>>,
|
||||
) {
|
||||
let render_materials = &mut *render_materials;
|
||||
|
||||
render_materials.changed.clear();
|
||||
render_materials.removed.clear();
|
||||
|
||||
for event in events.read() {
|
||||
match event {
|
||||
AssetEvent::Added { id } | AssetEvent::Modified { id } => {
|
||||
if let Some(material) = main_materials.get(*id) {
|
||||
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 { .. } => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Clone, PartialEq)]
|
||||
pub struct ExtractedEnvironmentMapLight {
|
||||
pub cubemap: Option<Handle<Image>>,
|
||||
pub intensity: f32,
|
||||
pub rotation: Quat,
|
||||
}
|
||||
|
||||
/// Finds the environment map light to use for the raytraced scene, if any.
|
||||
pub fn extract_raytracing_environment_map_light(
|
||||
cameras: Extract<
|
||||
Query<(
|
||||
&Camera,
|
||||
Option<&GeneratedEnvironmentMapLight>,
|
||||
Option<&EnvironmentMapLight>,
|
||||
)>,
|
||||
>,
|
||||
mut environment_map_light: ResMut<ExtractedEnvironmentMapLight>,
|
||||
) {
|
||||
let mut extracted_env_map_light = ExtractedEnvironmentMapLight::default();
|
||||
|
||||
for (camera, generated, pregenerated) in &cameras {
|
||||
if !camera.is_active {
|
||||
continue;
|
||||
}
|
||||
|
||||
let env_map_light = match (generated, pregenerated) {
|
||||
(Some(generated), _) => ExtractedEnvironmentMapLight {
|
||||
cubemap: Some(generated.environment_map.clone()),
|
||||
intensity: generated.intensity,
|
||||
rotation: generated.rotation,
|
||||
},
|
||||
(None, Some(pregenerated)) => ExtractedEnvironmentMapLight {
|
||||
cubemap: Some(pregenerated.specular_map.clone()),
|
||||
intensity: pregenerated.intensity,
|
||||
rotation: pregenerated.rotation,
|
||||
},
|
||||
(None, None) => continue,
|
||||
};
|
||||
|
||||
if extracted_env_map_light.cubemap.is_none() {
|
||||
extracted_env_map_light = env_map_light;
|
||||
} else if extracted_env_map_light != env_map_light {
|
||||
once!(warn!(
|
||||
"bevy_solari only supports a single environment light for the whole scene, but \
|
||||
multiple cameras have differing environment lights. Using the first one found."
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
*environment_map_light = extracted_env_map_light;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use alloc::collections::VecDeque;
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
system::{Res, ResMut},
|
||||
};
|
||||
use bevy_mesh::{Indices, Mesh};
|
||||
use bevy_platform::collections::HashMap;
|
||||
use bevy_render::{
|
||||
diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
|
||||
mesh::{
|
||||
allocator::{MeshAllocator, MeshBufferSlice},
|
||||
RenderMesh,
|
||||
},
|
||||
render_asset::ExtractedAssets,
|
||||
render_resource::*,
|
||||
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.
|
||||
const MAX_COMPACTION_VERTICES_PER_FRAME: u32 = 400_000;
|
||||
|
||||
/// Under the `wgpu_hal` build path, we need to manage BLAS lifetimes ourselves.
|
||||
/// Since solari keeps both current and previous frame TLAS's around, only after
|
||||
/// two TLAS builds since we marked it for deletion is it safe to delete a BLAS.
|
||||
const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct BlasManager {
|
||||
blas: HashMap<AssetId<Mesh>, Blas>,
|
||||
compaction_queue: VecDeque<(AssetId<Mesh>, 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>>,
|
||||
}
|
||||
|
||||
impl BlasManager {
|
||||
pub fn get(&self, mesh: &AssetId<Mesh>) -> Option<&Blas> {
|
||||
self.blas.get(mesh)
|
||||
}
|
||||
|
||||
pub fn device_address(&self, mesh: &AssetId<Mesh>) -> Option<u64> {
|
||||
self.blas.get(mesh)?.handle()
|
||||
}
|
||||
|
||||
pub fn changed_meshes(&self) -> &[AssetId<Mesh>] {
|
||||
&self.changed
|
||||
}
|
||||
|
||||
pub fn note_tlas_build(&mut self) {
|
||||
if !self.pending_deletions.is_empty() {
|
||||
self.pending_deletions.push_back(Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(&mut self, mesh: AssetId<Mesh>, blas: Blas) {
|
||||
if let Some(old) = self.blas.insert(mesh, blas) {
|
||||
self.retire(old);
|
||||
}
|
||||
|
||||
self.changed.push(mesh);
|
||||
}
|
||||
|
||||
fn remove(&mut self, mesh: AssetId<Mesh>) {
|
||||
self.changed.push(mesh);
|
||||
|
||||
if let Some(removed) = self.blas.remove(&mesh) {
|
||||
self.retire(removed);
|
||||
}
|
||||
}
|
||||
|
||||
fn retire(&mut self, blas: Blas) {
|
||||
match self.pending_deletions.back_mut() {
|
||||
Some(batch) => batch.push(blas),
|
||||
None => self.pending_deletions.push_back(vec![blas]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare_raytracing_blas(
|
||||
mut blas_manager: ResMut<BlasManager>,
|
||||
extracted_meshes: Res<ExtractedAssets<RenderMesh>>,
|
||||
mesh_allocator: Res<MeshAllocator>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
mut diagnostics: Option<ResMut<DiagnosticsRecorder>>,
|
||||
) {
|
||||
blas_manager.changed.clear();
|
||||
|
||||
// Delete BLAS for deleted or modified meshes
|
||||
for asset_id in extracted_meshes
|
||||
.removed
|
||||
.iter()
|
||||
.chain(extracted_meshes.modified.iter())
|
||||
{
|
||||
blas_manager.remove(*asset_id);
|
||||
}
|
||||
|
||||
if extracted_meshes.extracted.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create new BLAS for added or changed meshes
|
||||
let blas_resources = extracted_meshes
|
||||
.extracted
|
||||
.iter()
|
||||
.filter(|(_, mesh)| is_mesh_raytracing_compatible(mesh))
|
||||
.map(|(asset_id, _)| {
|
||||
let vertex_slice = mesh_allocator.mesh_vertex_slice(asset_id).unwrap();
|
||||
let index_slice = mesh_allocator.mesh_index_slice(asset_id).unwrap();
|
||||
|
||||
let (blas, blas_size) =
|
||||
allocate_blas(&vertex_slice, &index_slice, asset_id, &render_device);
|
||||
|
||||
blas_manager.insert(*asset_id, blas);
|
||||
blas_manager
|
||||
.compaction_queue
|
||||
.push_back((*asset_id, blas_size.vertex_count, false));
|
||||
|
||||
(*asset_id, vertex_slice, index_slice, blas_size)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Build geometry into each BLAS
|
||||
let build_entries = blas_resources
|
||||
.iter()
|
||||
.map(|(asset_id, 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,
|
||||
transform_buffer_offset: None,
|
||||
};
|
||||
BlasBuildEntry {
|
||||
blas: &blas_manager.blas[asset_id],
|
||||
geometry: BlasGeometries::TriangleGeometries(vec![geometry]),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
|
||||
label: Some("blas_build_command_encoder"),
|
||||
});
|
||||
let time_span = diagnostics
|
||||
.as_mut()
|
||||
.map(|diagnostics| diagnostics.time_span(&mut command_encoder, "blas_build"));
|
||||
command_encoder.build_acceleration_structures(&build_entries, &[]);
|
||||
if let Some(time_span) = time_span {
|
||||
time_span.end(&mut command_encoder);
|
||||
}
|
||||
render_queue.submit([command_encoder.finish()]);
|
||||
}
|
||||
|
||||
pub fn compact_raytracing_blas(
|
||||
mut blas_manager: ResMut<BlasManager>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
) {
|
||||
let queue_size = blas_manager.compaction_queue.len();
|
||||
let mut meshes_processed = 0;
|
||||
let mut vertices_compacted = 0;
|
||||
|
||||
while !blas_manager.compaction_queue.is_empty()
|
||||
&& vertices_compacted < MAX_COMPACTION_VERTICES_PER_FRAME
|
||||
&& meshes_processed < queue_size
|
||||
{
|
||||
meshes_processed += 1;
|
||||
|
||||
let (mesh, vertex_count, compaction_started) =
|
||||
blas_manager.compaction_queue.pop_front().unwrap();
|
||||
|
||||
let Some(blas) = blas_manager.get(&mesh) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if !compaction_started {
|
||||
blas.prepare_compaction_async(|_| {});
|
||||
}
|
||||
|
||||
if blas.ready_for_compaction() {
|
||||
let compacted_blas = render_queue.compact_blas(blas);
|
||||
blas_manager.insert(mesh, compacted_blas);
|
||||
|
||||
vertices_compacted += vertex_count;
|
||||
continue;
|
||||
}
|
||||
|
||||
// BLAS not ready for compaction, put back in queue
|
||||
blas_manager
|
||||
.compaction_queue
|
||||
.push_back((mesh, vertex_count, true));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_raytracing_blas(
|
||||
mut blas_manager: ResMut<BlasManager>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
) {
|
||||
if blas_manager.pending_deletions.len() <= TLAS_BUILDS_BEFORE_DELETION_ALLOWED {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(deletable) = blas_manager
|
||||
.pending_deletions
|
||||
.pop_front()
|
||||
.filter(|b| !b.is_empty())
|
||||
{
|
||||
render_queue.on_submitted_work_done(move || drop(deletable));
|
||||
}
|
||||
}
|
||||
|
||||
fn allocate_blas(
|
||||
vertex_slice: &MeshBufferSlice,
|
||||
index_slice: &MeshBufferSlice,
|
||||
asset_id: &AssetId<Mesh>,
|
||||
render_device: &RenderDevice,
|
||||
) -> (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: AccelerationStructureGeometryFlags::OPAQUE,
|
||||
};
|
||||
|
||||
// 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(&asset_id.to_string()),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
|
||||
| AccelerationStructureFlags::ALLOW_COMPACTION,
|
||||
update_mode: AccelerationStructureUpdateMode::Build,
|
||||
},
|
||||
BlasGeometrySizeDescriptors::Triangles {
|
||||
descriptors: vec![blas_size.clone()],
|
||||
},
|
||||
);
|
||||
|
||||
(blas, blas_size)
|
||||
}
|
||||
|
||||
fn is_mesh_raytracing_compatible(mesh: &Mesh) -> bool {
|
||||
let triangle_list = mesh.primitive_topology() == PrimitiveTopology::TriangleList;
|
||||
let vertex_attributes = mesh
|
||||
.attributes()
|
||||
.map(|(attribute, _)| (attribute.id, attribute.format))
|
||||
.eq([
|
||||
(Mesh::ATTRIBUTE_POSITION.id, Mesh::ATTRIBUTE_POSITION.format),
|
||||
(Mesh::ATTRIBUTE_NORMAL.id, Mesh::ATTRIBUTE_NORMAL.format),
|
||||
(Mesh::ATTRIBUTE_UV_0.id, Mesh::ATTRIBUTE_UV_0.format),
|
||||
(Mesh::ATTRIBUTE_TANGENT.id, Mesh::ATTRIBUTE_TANGENT.format),
|
||||
]);
|
||||
let indexed_32 = matches!(mesh.indices(), Some(Indices::U32(..)));
|
||||
mesh.enable_raytracing && triangle_list && vertex_attributes && indexed_32
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod blas;
|
||||
pub mod types;
|
||||
@@ -0,0 +1,25 @@
|
||||
use bevy_asset::Handle;
|
||||
use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{component::Component, prelude::ReflectComponent, template::FromTemplate};
|
||||
use bevy_mesh::Mesh;
|
||||
use bevy_pbr::{MeshMaterial3d, StandardMaterial};
|
||||
use bevy_reflect::{Reflect, prelude::ReflectDefault};
|
||||
use bevy_render::sync_world::SyncToRenderWorld;
|
||||
use bevy_transform::components::Transform;
|
||||
use derive_more::derive::From;
|
||||
|
||||
/// A mesh component used for raytracing.
|
||||
///
|
||||
/// The mesh used in this component must have [`Mesh::enable_raytracing`] set to
|
||||
/// true, 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>`].
|
||||
#[derive(
|
||||
Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From,
|
||||
)]
|
||||
#[reflect(Component, Default, Clone, PartialEq)]
|
||||
#[require(MeshMaterial3d<StandardMaterial>, Transform, SyncToRenderWorld)]
|
||||
pub struct RaytracingMesh3d(pub Handle<Mesh>);
|
||||
@@ -0,0 +1,129 @@
|
||||
mod binder;
|
||||
mod extract;
|
||||
mod meshes;
|
||||
|
||||
mod tapes;
|
||||
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::embedded_asset;
|
||||
use bevy_ecs::schedule::IntoScheduleConfigs;
|
||||
use bevy_render::{
|
||||
ExtractSchedule, GpuResourceAppExt, Render, RenderApp, RenderSystems,
|
||||
mesh::{
|
||||
RenderMesh,
|
||||
allocator::{MeshAllocatorSettings, allocate_and_free_meshes},
|
||||
},
|
||||
render_asset::prepare_assets,
|
||||
render_resource::{BufferUsages, update_sparse_buffers},
|
||||
renderer::{RenderDevice, RenderGraph, RenderGraphSystems},
|
||||
};
|
||||
use bevy_shader::load_shader_library;
|
||||
pub use bevy_tape_load::{
|
||||
Tape, Tape3d, TapePlugin,
|
||||
render::{
|
||||
RenderTape, TapeRenderAssetPlugin,
|
||||
allocator::{TapeAllocatorPlugin, allocate_and_free_tapes},
|
||||
},
|
||||
};
|
||||
pub use binder::{
|
||||
RaytracingSceneBindings, RaytracingSceneNeedsPreviousFrameData,
|
||||
prepare_raytracing_scene_resources,
|
||||
};
|
||||
use binder::{
|
||||
TlasInstanceSetupPipeline, build_raytracing_tlas, prepare_raytracing_scene_bind_group,
|
||||
};
|
||||
use extract::{
|
||||
ExtractedEnvironmentMapLight, StandardMaterialAssets, extract_raytracing_environment_map_light,
|
||||
extract_raytracing_material_assets, extract_raytracing_scene_meshes_and_materials,
|
||||
extract_raytracing_scene_transforms,
|
||||
};
|
||||
pub use meshes::types::RaytracingMesh3d;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{
|
||||
SolariPlugins,
|
||||
scene::extract::{
|
||||
extract_raytracing_scene_meshes_structural, extract_raytracing_scene_tapes_and_materials,
|
||||
extract_raytracing_scene_tapes_structural,
|
||||
},
|
||||
};
|
||||
|
||||
/// Creates acceleration structures and binding arrays of resources for
|
||||
/// raytracing.
|
||||
pub struct RaytracingScenePlugin;
|
||||
|
||||
impl Plugin for RaytracingScenePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
load_shader_library!(app, "brdf.wesl");
|
||||
load_shader_library!(app, "bindings.wesl");
|
||||
load_shader_library!(app, "sampling.wesl");
|
||||
embedded_asset!(app, "binder/setup_tlas_instances.wesl");
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let render_app = app.sub_app_mut(RenderApp);
|
||||
|
||||
let render_device = render_app.world().resource::<RenderDevice>();
|
||||
let features = render_device.features();
|
||||
if !features.contains(SolariPlugins::required_wgpu_features()) {
|
||||
warn!(
|
||||
"RaytracingScenePlugin not loaded. GPU lacks support for required features: {:?}.",
|
||||
SolariPlugins::required_wgpu_features().difference(features)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
render_app
|
||||
.world_mut()
|
||||
.resource_mut::<MeshAllocatorSettings>()
|
||||
.extra_buffer_usages |= BufferUsages::BLAS_INPUT | BufferUsages::STORAGE;
|
||||
|
||||
render_app
|
||||
.init_resource::<ExtractedEnvironmentMapLight>()
|
||||
.init_gpu_resource::<meshes::blas::BlasManager>()
|
||||
.init_gpu_resource::<tapes::blas::BlasManager>()
|
||||
.init_gpu_resource::<StandardMaterialAssets>()
|
||||
.init_gpu_resource::<RaytracingSceneBindings>()
|
||||
.init_gpu_resource::<TlasInstanceSetupPipeline>()
|
||||
.add_systems(
|
||||
ExtractSchedule,
|
||||
(
|
||||
extract_raytracing_scene_meshes_structural,
|
||||
extract_raytracing_scene_tapes_structural,
|
||||
extract_raytracing_scene_transforms,
|
||||
extract_raytracing_scene_meshes_and_materials,
|
||||
extract_raytracing_scene_tapes_and_materials,
|
||||
extract_raytracing_material_assets,
|
||||
extract_raytracing_environment_map_light,
|
||||
),
|
||||
)
|
||||
.add_systems(
|
||||
Render,
|
||||
(
|
||||
meshes::blas::prepare_raytracing_blas
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.before(prepare_assets::<RenderMesh>)
|
||||
.after(allocate_and_free_meshes),
|
||||
meshes::blas::compact_raytracing_blas
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.after(meshes::blas::prepare_raytracing_blas),
|
||||
tapes::blas::prepare_raytracing_blas
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.before(prepare_assets::<RenderTape>)
|
||||
.after(allocate_and_free_tapes),
|
||||
prepare_raytracing_scene_resources.in_set(RenderSystems::PrepareResources),
|
||||
prepare_raytracing_scene_bind_group.in_set(RenderSystems::PrepareBindGroups),
|
||||
),
|
||||
)
|
||||
.add_systems(
|
||||
RenderGraph,
|
||||
(
|
||||
build_raytracing_tlas
|
||||
.after(update_sparse_buffers)
|
||||
.in_set(RenderGraphSystems::Begin),
|
||||
meshes::blas::delete_raytracing_blas.in_set(RenderGraphSystems::Finish),
|
||||
tapes::blas::delete_raytracing_blas.in_set(RenderGraphSystems::Finish),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import bevy_pbr::render::pbr_lighting::D_GGX;
|
||||
import bevy_pbr::render::utils::{rand_vec2f, rand_u, rand_range_u};
|
||||
import bevy_render::maths::{PI_2, orthonormalize};
|
||||
import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, LIGHT_SOURCE_KIND_DIRECTIONAL, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD};
|
||||
|
||||
enable wgpu_ray_query;
|
||||
|
||||
fn power_heuristic(f: f32, g: f32) -> f32 {
|
||||
return balance_heuristic(f * f, g * g);
|
||||
}
|
||||
|
||||
fn balance_heuristic(f: f32, g: f32) -> f32 {
|
||||
// Need to guard against NaNs since ReSTIR reservoirs can have UCW=0
|
||||
if f == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
// When NaN, fall back to even weights of 0.5 : 0.5
|
||||
let weight = 1.0 / (1.0 + (g / f));
|
||||
return select(weight, 0.5, isnan(weight));
|
||||
}
|
||||
|
||||
/// https://gpuopen.com/download/Bounded_VNDF_Sampling_for_Smith-GGX_Reflections.pdf (Listing 1)
|
||||
/// Result is invalid when output.z <= 0.0, and must be discarded
|
||||
fn sample_ggx_vndf(wi_tangent: vec3<f32>, roughness: f32, rng: ptr<function, u32>) -> vec3<f32> {
|
||||
// Mirror BRDF case
|
||||
if roughness <= MIRROR_ROUGHNESS_THRESHOLD {
|
||||
return vec3(-wi_tangent.xy, wi_tangent.z);
|
||||
}
|
||||
|
||||
let i = wi_tangent;
|
||||
let rand = rand_vec2f(rng);
|
||||
let i_std = normalize(vec3(i.xy * roughness, i.z));
|
||||
let phi = PI_2 * rand.x;
|
||||
let a = roughness;
|
||||
let s = 1.0 + length(vec2(i.xy));
|
||||
let a2 = a * a;
|
||||
let s2 = s * s;
|
||||
let k = (1.0 - a2) * s2 / (s2 + a2 * i.z * i.z);
|
||||
let b = select(i_std.z, k * i_std.z, i.z > 0.0);
|
||||
let z = fma(1.0 - rand.y, 1.0 + b, -b);
|
||||
let sin_theta = sqrt(saturate(1.0 - z * z));
|
||||
let o_std = vec3(sin_theta * cos(phi), sin_theta * sin(phi), z);
|
||||
let m_std = i_std + o_std;
|
||||
let m = normalize(vec3(m_std.xy * roughness, m_std.z));
|
||||
return 2.0 * dot(i, m) * m - i;
|
||||
}
|
||||
|
||||
fn ggx_vndf_sample_invalid(ray_tangent: vec3<f32>) -> bool {
|
||||
return !(ray_tangent.z > 0.0);
|
||||
}
|
||||
|
||||
/// https://gpuopen.com/download/Bounded_VNDF_Sampling_for_Smith-GGX_Reflections.pdf (Listing 2)
|
||||
fn ggx_vndf_pdf(wi_tangent: vec3<f32>, wo_tangent: vec3<f32>, roughness: f32) -> f32 {
|
||||
// Mirror BRDF case
|
||||
if roughness <= MIRROR_ROUGHNESS_THRESHOLD {
|
||||
let mirror_wo = vec3(-wi_tangent.xy, wi_tangent.z);
|
||||
if distance(mirror_wo, wo_tangent) < 0.0001 {
|
||||
return bitcast<f32>(0x7F800000u); // INF
|
||||
} else {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
let i = wi_tangent;
|
||||
let o = wo_tangent;
|
||||
let m = normalize(i + o);
|
||||
let ndf = D_GGX(roughness, saturate(m.z));
|
||||
let ai = roughness * i.xy;
|
||||
let len2 = dot(ai, ai);
|
||||
let t = sqrt(len2 + i.z * i.z);
|
||||
var pdf: f32;
|
||||
if i.z >= 0.0 {
|
||||
let a = roughness;
|
||||
let s = 1.0 + length(i.xy);
|
||||
let a2 = a * a;
|
||||
let s2 = s * s;
|
||||
let k = (1.0 - a2) * s2 / (s2 + a2 * i.z * i.z);
|
||||
pdf = ndf / (2.0 * (k * i.z + t));
|
||||
} else {
|
||||
pdf = ndf * (t - i.z) / (2.0 * len2);
|
||||
}
|
||||
|
||||
return select(pdf, 0.0, isnan(pdf));
|
||||
}
|
||||
|
||||
fn isinf(x: f32) -> bool {
|
||||
return (bitcast<u32>(x) & 0x7fffffffu) == 0x7f800000u;
|
||||
}
|
||||
|
||||
fn isnan(x: f32) -> bool {
|
||||
return (bitcast<u32>(x) & 0x7fffffffu) > 0x7f800000u;
|
||||
}
|
||||
|
||||
const NULL_LIGHT_ID = 0xFFFFFFFFu;
|
||||
|
||||
struct LightSample {
|
||||
light_id: u32,
|
||||
seed: u32,
|
||||
}
|
||||
|
||||
struct ResolvedLightSample {
|
||||
world_position: vec4<f32>,
|
||||
world_normal: vec3<f32>,
|
||||
radiance: vec3<f32>,
|
||||
inverse_pdf: f32,
|
||||
}
|
||||
|
||||
struct LightContribution {
|
||||
radiance: vec3<f32>,
|
||||
inverse_pdf: f32,
|
||||
/// inverse_pdf may not be in solid angle measure (e.g. area measure)
|
||||
/// but inverse_solid_angle_pdf is always in solid angle measure
|
||||
/// for cases where it's required, e.g. MIS between light sampling techniques
|
||||
inverse_solid_angle_pdf: f32,
|
||||
wi: vec3<f32>,
|
||||
brdf_rays_can_hit: bool,
|
||||
}
|
||||
|
||||
struct GenerateRandomLightSampleResult {
|
||||
light_sample: LightSample,
|
||||
resolved_light_sample: ResolvedLightSample,
|
||||
}
|
||||
|
||||
fn sample_random_light(ray_origin: vec3<f32>, origin_world_normal: vec3<f32>, rng: ptr<function, u32>) -> LightContribution {
|
||||
let sample = generate_random_light_sample(rng);
|
||||
var light_contribution = calculate_resolved_light_contribution(sample.resolved_light_sample, ray_origin, origin_world_normal);
|
||||
light_contribution.radiance *= trace_visibility(ray_origin, sample.resolved_light_sample.world_position);
|
||||
return light_contribution;
|
||||
}
|
||||
|
||||
fn random_emissive_light_pdf(hit: ResolvedRayHitFull, ray_distance: f32, NdotV: f32) -> f32 {
|
||||
let light_count = arrayLength(&light_sources);
|
||||
let area_pdf = 1.0 / (f32(light_count) * f32(hit.triangle_count) * hit.triangle_area);
|
||||
return area_pdf * (ray_distance * ray_distance) / NdotV;
|
||||
}
|
||||
|
||||
fn sample_environment_map_light(world_direction: vec3<f32>) -> vec3<f32> {
|
||||
if environment_map_light.intensity == 0.0 { return vec3(0.0); }
|
||||
|
||||
var sample_direction = environment_map_light.light_from_world * world_direction;
|
||||
sample_direction.z = -sample_direction.z;
|
||||
|
||||
// Hardcoded to sample mip 0 (unfiltered radiance)
|
||||
return textureSampleLevel(environment_map, environment_map_sampler, sample_direction, 0.0).rgb * environment_map_light.intensity;
|
||||
}
|
||||
|
||||
fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightSampleResult {
|
||||
let light_count = arrayLength(&light_sources);
|
||||
let light_id = rand_range_u(light_count, rng);
|
||||
|
||||
let light_source = light_sources[light_id];
|
||||
|
||||
var triangle_id = 0u;
|
||||
if light_source.kind != LIGHT_SOURCE_KIND_DIRECTIONAL {
|
||||
let triangle_count = light_source.kind >> 1u;
|
||||
triangle_id = rand_range_u(triangle_count, rng);
|
||||
}
|
||||
|
||||
let seed = rand_u(rng);
|
||||
let light_sample = LightSample((light_id << 16u) | triangle_id, seed);
|
||||
|
||||
var resolved_light_sample = resolve_light_sample(light_sample, light_source);
|
||||
resolved_light_sample.inverse_pdf *= f32(light_count);
|
||||
|
||||
return GenerateRandomLightSampleResult(light_sample, resolved_light_sample);
|
||||
}
|
||||
|
||||
fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) -> ResolvedLightSample {
|
||||
if light_source.kind == LIGHT_SOURCE_KIND_DIRECTIONAL {
|
||||
let directional_light = directional_lights[light_source.id];
|
||||
|
||||
var direction_to_light: vec3<f32>;
|
||||
@if(!NO_DIRECTIONAL_LIGHT_SOFT_SHADOWS) {
|
||||
// Sample a random direction within a cone whose base is the sun approximated as a disk
|
||||
// https://www.realtimerendering.com/raytracinggems/unofficial_RayTracingGems_v1.9.pdf#0004286901.INDD%3ASec30%3A305
|
||||
var rng = light_sample.seed;
|
||||
let random = rand_vec2f(&rng);
|
||||
let cos_theta = (1.0 - random.x) + random.x * directional_light.cos_theta_max;
|
||||
let sin_theta = sqrt(1.0 - cos_theta * cos_theta);
|
||||
let phi = random.y * PI_2;
|
||||
let x = cos(phi) * sin_theta;
|
||||
let y = sin(phi) * sin_theta;
|
||||
direction_to_light = vec3(x, y, cos_theta);
|
||||
|
||||
// Rotate the ray so that the cone it was sampled from is aligned with the light direction
|
||||
direction_to_light = orthonormalize(directional_light.direction_to_light) * direction_to_light;
|
||||
} @else {
|
||||
direction_to_light = directional_light.direction_to_light;
|
||||
}
|
||||
|
||||
return ResolvedLightSample(
|
||||
vec4(direction_to_light, 0.0),
|
||||
-direction_to_light,
|
||||
directional_light.luminance,
|
||||
directional_light.inverse_pdf,
|
||||
);
|
||||
} else {
|
||||
let triangle_count = light_source.kind >> 1u;
|
||||
let triangle_id = light_sample.light_id & 0xFFFFu;
|
||||
let barycentrics = triangle_barycentrics(light_sample.seed);
|
||||
let triangle_data = resolve_triangle_data_full(light_source.id, triangle_id, barycentrics);
|
||||
|
||||
return ResolvedLightSample(
|
||||
vec4(triangle_data.world_position, 1.0),
|
||||
triangle_data.world_normal,
|
||||
triangle_data.material.emissive.rgb,
|
||||
f32(triangle_count) * triangle_data.triangle_area,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_resolved_light_contribution(resolved_light_sample: ResolvedLightSample, ray_origin: vec3<f32>, origin_world_normal: vec3<f32>) -> LightContribution {
|
||||
let ray = resolved_light_sample.world_position.xyz - (resolved_light_sample.world_position.w * ray_origin);
|
||||
let light_distance = length(ray);
|
||||
let wi = ray / light_distance;
|
||||
|
||||
let cos_theta_light = saturate(dot(-wi, resolved_light_sample.world_normal));
|
||||
let light_distance_squared = light_distance * light_distance;
|
||||
let denominator = cos_theta_light / light_distance_squared;
|
||||
|
||||
let radiance = resolved_light_sample.radiance * denominator;
|
||||
let inverse_solid_angle_pdf = resolved_light_sample.inverse_pdf * denominator;
|
||||
|
||||
return LightContribution(radiance, resolved_light_sample.inverse_pdf, inverse_solid_angle_pdf, wi, resolved_light_sample.world_position.w == 1.0);
|
||||
}
|
||||
|
||||
fn trace_visibility(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {
|
||||
var ray_direction = point.xyz;
|
||||
var ray_t_max = RAY_T_MAX;
|
||||
|
||||
if point.w == 1.0 {
|
||||
let ray = ray_direction - ray_origin;
|
||||
let dist = length(ray);
|
||||
ray_direction = ray / dist;
|
||||
ray_t_max = dist - RAY_T_MIN;
|
||||
}
|
||||
|
||||
if ray_t_max < RAY_T_MIN { return 0.0; }
|
||||
|
||||
let ray_hit = trace_ray(ray_origin, ray_direction, RAY_T_MIN, ray_t_max, RAY_FLAG_TERMINATE_ON_FIRST_HIT);
|
||||
return f32(ray_hit.kind == RAY_QUERY_INTERSECTION_NONE);
|
||||
}
|
||||
|
||||
fn trace_visibility_previous_frame(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {
|
||||
var ray_direction = point.xyz;
|
||||
var ray_t_max = RAY_T_MAX;
|
||||
|
||||
if point.w == 1.0 {
|
||||
let ray = ray_direction - ray_origin;
|
||||
let dist = length(ray);
|
||||
ray_direction = ray / dist;
|
||||
ray_t_max = dist - RAY_T_MIN;
|
||||
}
|
||||
|
||||
if ray_t_max < RAY_T_MIN { return 0.0; }
|
||||
|
||||
let ray_hit = trace_ray_previous_frame(ray_origin, ray_direction, RAY_T_MIN, ray_t_max, RAY_FLAG_TERMINATE_ON_FIRST_HIT);
|
||||
return f32(ray_hit.kind == RAY_QUERY_INTERSECTION_NONE);
|
||||
}
|
||||
|
||||
/// https://www.realtimerendering.com/raytracinggems/unofficial_RayTracingGems_v1.9.pdf#0004286901.INDD%3ASec22%3A297
|
||||
fn triangle_barycentrics(seed: u32) -> vec3<f32> {
|
||||
var rng = seed;
|
||||
var barycentrics = rand_vec2f(&rng);
|
||||
if barycentrics.x + barycentrics.y > 1.0 { barycentrics = 1.0 - barycentrics; }
|
||||
return vec3(1.0 - barycentrics.x - barycentrics.y, barycentrics);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
use alloc::collections::VecDeque;
|
||||
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
system::{Res, ResMut},
|
||||
};
|
||||
use bevy_platform::collections::HashMap;
|
||||
use bevy_render::{
|
||||
diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
|
||||
render_asset::ExtractedAssets,
|
||||
render_resource::*,
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
};
|
||||
use bevy_tape_load::{
|
||||
Tape,
|
||||
render::{
|
||||
RenderTape,
|
||||
allocator::{TapeAllocator, TapeBufferSlice},
|
||||
},
|
||||
};
|
||||
use wgpu::{BlasAabbGeometry, wgt::BlasAABBGeometrySizeDescriptor};
|
||||
|
||||
/// Under the `wgpu_hal` build path, we need to manage BLAS lifetimes ourselves.
|
||||
/// Since solari keeps both current and previous frame TLAS's around, only after
|
||||
/// two TLAS builds since we marked it for deletion is it safe to delete a BLAS.
|
||||
const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct BlasManager {
|
||||
blas: HashMap<AssetId<Tape>, Blas>,
|
||||
changed: 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.
|
||||
pending_deletions: VecDeque<Vec<Blas>>,
|
||||
}
|
||||
|
||||
impl BlasManager {
|
||||
pub fn get(&self, tape: &AssetId<Tape>) -> Option<&Blas> {
|
||||
self.blas.get(tape)
|
||||
}
|
||||
|
||||
pub fn device_address(&self, tape: &AssetId<Tape>) -> Option<u64> {
|
||||
self.blas.get(tape)?.handle()
|
||||
}
|
||||
|
||||
pub fn changed_tapes(&self) -> &[AssetId<Tape>] {
|
||||
&self.changed
|
||||
}
|
||||
|
||||
pub fn note_tlas_build(&mut self) {
|
||||
if !self.pending_deletions.is_empty() {
|
||||
self.pending_deletions.push_back(Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(&mut self, tape: AssetId<Tape>, blas: Blas) {
|
||||
if let Some(old) = self.blas.insert(tape, blas) {
|
||||
self.retire(old);
|
||||
}
|
||||
|
||||
self.changed.push(tape);
|
||||
}
|
||||
|
||||
fn remove(&mut self, tape: AssetId<Tape>) {
|
||||
self.changed.push(tape);
|
||||
|
||||
if let Some(removed) = self.blas.remove(&tape) {
|
||||
self.retire(removed);
|
||||
}
|
||||
}
|
||||
|
||||
fn retire(&mut self, blas: Blas) {
|
||||
match self.pending_deletions.back_mut() {
|
||||
Some(batch) => batch.push(blas),
|
||||
None => self.pending_deletions.push_back(vec![blas]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare_raytracing_blas(
|
||||
mut blas_manager: ResMut<BlasManager>,
|
||||
extracted_tapes: Res<ExtractedAssets<RenderTape>>,
|
||||
tape_allocator: Res<TapeAllocator>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
mut diagnostics: Option<ResMut<DiagnosticsRecorder>>,
|
||||
) {
|
||||
blas_manager.changed.clear();
|
||||
|
||||
// Delete BLAS for deleted or modified tapes
|
||||
for asset_id in extracted_tapes
|
||||
.removed
|
||||
.iter()
|
||||
.chain(extracted_tapes.modified.iter())
|
||||
{
|
||||
blas_manager.remove(*asset_id);
|
||||
}
|
||||
|
||||
if extracted_tapes.extracted.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create new BLAS for added or changed tapes
|
||||
let blas_resources = extracted_tapes
|
||||
.extracted
|
||||
.iter()
|
||||
.map(|(asset_id, _)| {
|
||||
bevy_log::info!("Tape {}: Getting the aabb slice", asset_id);
|
||||
let aabbs_slice = tape_allocator.tape_aabb_slice(asset_id).unwrap();
|
||||
|
||||
let (blas, blas_size) = allocate_blas(&aabbs_slice, asset_id, &render_device);
|
||||
|
||||
blas_manager.insert(*asset_id, blas);
|
||||
|
||||
(*asset_id, aabbs_slice, blas_size)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Build geometry into each BLAS
|
||||
let build_entries = blas_resources
|
||||
.iter()
|
||||
.map(|(asset_id, aabbs_slice, blas_size)| {
|
||||
let geometry = BlasAabbGeometry {
|
||||
size: blas_size,
|
||||
stride: size_of::<bevy_tape_load::render::Aabb>() as u64,
|
||||
aabb_buffer: aabbs_slice.buffer,
|
||||
primitive_offset: aabbs_slice.range.start,
|
||||
};
|
||||
BlasBuildEntry {
|
||||
blas: &blas_manager.blas[asset_id],
|
||||
geometry: BlasGeometries::AabbGeometries(vec![geometry]),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
|
||||
label: Some("blas_build_command_encoder"),
|
||||
});
|
||||
let time_span = diagnostics
|
||||
.as_mut()
|
||||
.map(|diagnostics| diagnostics.time_span(&mut command_encoder, "tape_blas_build"));
|
||||
command_encoder.build_acceleration_structures(&build_entries, &[]);
|
||||
if let Some(time_span) = time_span {
|
||||
time_span.end(&mut command_encoder);
|
||||
}
|
||||
render_queue.submit([command_encoder.finish()]);
|
||||
}
|
||||
|
||||
pub fn delete_raytracing_blas(
|
||||
mut blas_manager: ResMut<BlasManager>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
) {
|
||||
if blas_manager.pending_deletions.len() <= TLAS_BUILDS_BEFORE_DELETION_ALLOWED {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(deletable) = blas_manager
|
||||
.pending_deletions
|
||||
.pop_front()
|
||||
.filter(|b| !b.is_empty())
|
||||
{
|
||||
render_queue.on_submitted_work_done(move || drop(deletable));
|
||||
}
|
||||
}
|
||||
|
||||
fn allocate_blas(
|
||||
aabbs_slice: &TapeBufferSlice,
|
||||
asset_id: &AssetId<Tape>,
|
||||
render_device: &RenderDevice,
|
||||
) -> (Blas, BlasAABBGeometrySizeDescriptor) {
|
||||
let blas_size = BlasAABBGeometrySizeDescriptor {
|
||||
primitive_count: aabbs_slice.range.len() as u32,
|
||||
flags: AccelerationStructureGeometryFlags::OPAQUE,
|
||||
};
|
||||
|
||||
// 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(&asset_id.to_string()),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
|
||||
| AccelerationStructureFlags::ALLOW_COMPACTION,
|
||||
update_mode: AccelerationStructureUpdateMode::Build,
|
||||
},
|
||||
BlasGeometrySizeDescriptors::AABBs {
|
||||
descriptors: vec![blas_size.clone()],
|
||||
},
|
||||
);
|
||||
|
||||
(blas, blas_size)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod blas;
|
||||
@@ -0,0 +1,83 @@
|
||||
[package]
|
||||
name = "bevy_tape_load"
|
||||
version = "0.20.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides tape types for Bevy Engine"
|
||||
license = "Apache-2.0"
|
||||
keywords = ["bevy"]
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_app = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_asset = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_camera = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_color = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_core_pipeline = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_derive = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_diagnostic = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_ecs = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_image = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_light = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_log = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_math = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_mesh = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_pbr = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [
|
||||
"dfg_lut",
|
||||
] }
|
||||
bevy_platform = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", default-features = false, features = [
|
||||
"std",
|
||||
"serialize",
|
||||
] }
|
||||
bevy_reflect = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_render = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [
|
||||
"spirv_shader_passthrough",
|
||||
] }
|
||||
bevy_shader = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_shape = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [
|
||||
"bevy_reflect",
|
||||
] }
|
||||
bevy_transform = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
bevy_utils = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
|
||||
|
||||
# tape drive
|
||||
tape-load = { git = "https://git.stargaze.group/molive/tape-drive.git", rev = "19b241637be770db5ee6201951138f41b1f9f467", features = [
|
||||
"bevy",
|
||||
] }
|
||||
rspirv = "0.13"
|
||||
|
||||
# other
|
||||
bitflags = { version = "2.3", features = ["serde"] }
|
||||
bytemuck = { version = "1.5", features = ["must_cast"] }
|
||||
wgpu = { version = "30", default-features = false }
|
||||
wgpu-types = { version = "30", default-features = false }
|
||||
serde = { version = "1", default-features = false, features = [
|
||||
"derive",
|
||||
], optional = true }
|
||||
hexasphere = "19.0"
|
||||
thiserror = { version = "2", default-features = false }
|
||||
tracing = { version = "0.1", default-features = false, features = ["std"] }
|
||||
derive_more = { version = "2", default-features = false, features = ["from"] }
|
||||
half = { version = "2.4.1", features = ["bytemuck"] }
|
||||
encase = "0.13"
|
||||
glam = { version = "0.33.9", default-features = false, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
approx = "0.5"
|
||||
serde_json = "1.0.140"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
## Adds serialization support through `serde`.
|
||||
serialize = ["dep:serde", "wgpu-types/serde", "half/serde"]
|
||||
morph = ["glam/encase-013"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustdoc-args = [
|
||||
"-Zunstable-options",
|
||||
"--generate-link-to-definition",
|
||||
"--generate-macro-expansion",
|
||||
]
|
||||
all-features = true
|
||||
@@ -0,0 +1,77 @@
|
||||
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
|
||||
/**
|
||||
* Defines the [Tape] asset, which responds to a Tape Drive tape.
|
||||
*/
|
||||
use bevy_app::{App, Plugin, PostUpdate};
|
||||
use bevy_asset::{AssetApp as _, AssetEvent, AssetEventSystems, AssetId, Handle};
|
||||
use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{
|
||||
change_detection::DetectChangesMut as _, component::Component, message::MessageReader,
|
||||
prelude::*, system::Query, template::FromTemplate,
|
||||
};
|
||||
use bevy_pbr::{MeshMaterial3d, StandardMaterial};
|
||||
use bevy_platform::{collections::HashSet, hash::FixedHasher};
|
||||
use bevy_reflect::{Reflect, prelude::ReflectDefault};
|
||||
use bevy_render::sync_world::SyncToRenderWorld;
|
||||
use bevy_transform::components::Transform;
|
||||
use derive_more::derive::From;
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
pub mod primitives;
|
||||
pub mod render;
|
||||
pub mod tape;
|
||||
|
||||
pub use tape_load::ssa;
|
||||
|
||||
pub use crate::tape::Tape;
|
||||
|
||||
/// A tape drive tape.
|
||||
///
|
||||
/// The material used for this entity must be
|
||||
/// [`MeshMaterial3d<StandardMaterial>`].
|
||||
#[derive(
|
||||
Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From,
|
||||
)]
|
||||
#[reflect(Component, Default, Clone, PartialEq)]
|
||||
#[require(MeshMaterial3d<StandardMaterial>, Transform, SyncToRenderWorld)]
|
||||
pub struct Tape3d(pub Handle<Tape>);
|
||||
|
||||
/// A system that marks a [`Tape3d`] as changed if the associated [`Tape`] asset
|
||||
/// has changed.
|
||||
pub fn mark_tapes_as_changed_if_their_assets_changed(
|
||||
mut tapes: Query<&mut Tape3d>,
|
||||
mut tape_asset_events: MessageReader<AssetEvent<Tape>>,
|
||||
) {
|
||||
let mut changed_tapes: HashSet<AssetId<Tape>, FixedHasher> = HashSet::default();
|
||||
for tape_asset_event in tape_asset_events.read() {
|
||||
if let AssetEvent::Modified { id } = tape_asset_event {
|
||||
changed_tapes.insert(*id);
|
||||
}
|
||||
}
|
||||
|
||||
if changed_tapes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
tapes.par_iter_mut().for_each(|mut tape| {
|
||||
if changed_tapes.contains(&tape.0.id()) {
|
||||
tape.set_changed();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Adds [`Tape`] as an asset.
|
||||
#[derive(Default)]
|
||||
pub struct TapePlugin;
|
||||
|
||||
impl Plugin for TapePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_asset::<Tape>()
|
||||
.register_asset_reflect::<Tape>()
|
||||
.add_systems(
|
||||
PostUpdate,
|
||||
mark_tapes_as_changed_if_their_assets_changed.after(AssetEventSystems),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Tape generation for [primitive shapes](bevy_shape).
|
||||
//!
|
||||
//! Primitives that support taping implement the [`Tapeable`] trait.
|
||||
//! Calling [`tape`](Tapeable::tape) will return either a [`Tape`] or a builder
|
||||
//! that can be used to specify shape-specific configuration for creating the
|
||||
//! [`Tape`].
|
||||
//!
|
||||
//! ```
|
||||
//! # use bevy_asset::Assets;
|
||||
//! # use bevy_ecs::prelude::ResMut;
|
||||
//! # use bevy_shape::Circle;
|
||||
//! # use bevy_tape_load::*;
|
||||
//! #
|
||||
//! # fn setup(mut tapes: ResMut<Assets<Tape>>) {
|
||||
//! // Create circle tape with default configuration
|
||||
//! let circle = tapes.add(Circle { radius: 25.0 });
|
||||
//!
|
||||
//! // Specify number of vertices
|
||||
//! let circle = tapes.add(Circle { radius: 25.0 }.tape().resolution(64));
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
pub mod sphere;
|
||||
|
||||
use super::Tape;
|
||||
|
||||
/// A trait for shapes that can be turned into a [`Tape`].
|
||||
pub trait Tapeable {
|
||||
/// The output of [`Self::tape`]. This will be a [`TapeBuilder`] used for
|
||||
/// creating a [`Tape`].
|
||||
type Output: TapeBuilder;
|
||||
|
||||
/// Creates a [`Tape`] for a shape.
|
||||
fn tape(&self) -> Self::Output;
|
||||
}
|
||||
|
||||
/// A trait used to build [`Tape`]s from a configuration
|
||||
pub trait TapeBuilder {
|
||||
/// Builds a [`Tape`] based on the configuration in `self`.
|
||||
fn build(&self) -> Tape;
|
||||
}
|
||||
|
||||
impl<T: TapeBuilder> From<T> for Tape {
|
||||
fn from(builder: T) -> Self {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use bevy_reflect::prelude::*;
|
||||
use bevy_shape::Sphere;
|
||||
|
||||
use crate::{
|
||||
Tape,
|
||||
primitives::{TapeBuilder, Tapeable},
|
||||
ssa::{SSAInput, SSAOpcode, SSAOpcodeSized, SSATape},
|
||||
};
|
||||
|
||||
/// A builder used for creating a [`Tape`] with an [`Sphere`] shape.
|
||||
#[derive(Clone, Copy, Debug, Default, Reflect)]
|
||||
#[reflect(Default, Debug, Clone)]
|
||||
pub struct SphereTapeBuilder {
|
||||
/// The [`Sphere`] shape.
|
||||
pub sphere: Sphere,
|
||||
}
|
||||
|
||||
impl SphereTapeBuilder {
|
||||
/// Creates a new [`SphereTapeBuilder`] from a radius.
|
||||
#[inline]
|
||||
pub const fn new(radius: f32) -> Self {
|
||||
Self {
|
||||
sphere: Sphere { radius },
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a sphere [`Tape`] with the given radius.
|
||||
/// TODO: make it so that this is composable.
|
||||
pub fn build_with_radius(radius: f32) -> Tape {
|
||||
let mut tape = SSATape::default();
|
||||
let pos = tape.push_instruction(
|
||||
SSAOpcodeSized {
|
||||
opcode: SSAOpcode::SSAPosition,
|
||||
size: 1,
|
||||
},
|
||||
vec![],
|
||||
);
|
||||
let sphere = tape.push_instruction(
|
||||
SSAOpcodeSized {
|
||||
opcode: SSAOpcode::SSASDFSphere,
|
||||
size: 1,
|
||||
},
|
||||
vec![pos[0], pos[1], pos[2], SSAInput::Constant(radius)],
|
||||
);
|
||||
tape.push_instruction(
|
||||
SSAOpcodeSized {
|
||||
opcode: SSAOpcode::SSAReturn,
|
||||
size: 1,
|
||||
},
|
||||
sphere,
|
||||
);
|
||||
Tape {
|
||||
parts: tape,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TapeBuilder for SphereTapeBuilder {
|
||||
/// Builds a [`Tape`] according to the configuration in `self`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the sphere is a [`SphereKind::Ico`] with a subdivision count
|
||||
/// that is greater than or equal to `80` because there will be too many
|
||||
/// vertices.
|
||||
fn build(&self) -> Tape {
|
||||
Self::build_with_radius(self.sphere.radius)
|
||||
}
|
||||
}
|
||||
|
||||
impl Tapeable for Sphere {
|
||||
type Output = SphereTapeBuilder;
|
||||
|
||||
fn tape(&self) -> Self::Output {
|
||||
SphereTapeBuilder {
|
||||
sphere: *self,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Sphere> for Tape {
|
||||
fn from(sphere: Sphere) -> Self {
|
||||
sphere.tape().build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
//! Manages tape aabb buffers.
|
||||
|
||||
use alloc::borrow::Cow;
|
||||
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
schedule::IntoScheduleConfigs as _,
|
||||
system::{Res, ResMut},
|
||||
world::{FromWorld, World},
|
||||
};
|
||||
use bevy_log::warn;
|
||||
use bevy_render::{
|
||||
GpuResourceAppExt, Render, RenderApp, RenderSystems,
|
||||
render_asset::{ExtractedAssets, prepare_assets},
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
slab_allocator::{
|
||||
Slab, SlabAllocationBufferSlice, SlabAllocator, SlabAllocatorSettings, SlabId, SlabItem,
|
||||
SlabItemLayout,
|
||||
},
|
||||
};
|
||||
use bevy_shape::BoundingVolume;
|
||||
use wgpu::{BufferUsages, COPY_BUFFER_ALIGNMENT};
|
||||
|
||||
use super::{Aabb, RenderTape, TapeMetadata};
|
||||
use crate::tape::Tape;
|
||||
|
||||
/// A plugin that manages GPU memory for tape data.
|
||||
pub struct TapeAllocatorPlugin;
|
||||
|
||||
/// Manages the assignment of tape data to GPU buffers.
|
||||
///
|
||||
/// The Bevy renderer tries to pack vertex and index data for multiple tapes
|
||||
/// together so that multiple tapes can be drawn back-to-back without any
|
||||
/// rebinding. This resource manages these buffers.
|
||||
///
|
||||
/// The [`TapeAllocatorSettings`] allows you to tune the behavior of the
|
||||
/// allocator for better performance with your use case. Most applications won't
|
||||
/// need to change the settings from their default values.
|
||||
#[derive(Resource, Deref, DerefMut)]
|
||||
pub struct TapeAllocator {
|
||||
/// Holds all buffers and offset allocators.
|
||||
#[deref]
|
||||
slab_allocator: SlabAllocator<TapeSlabItem>,
|
||||
}
|
||||
|
||||
/// Tunable parameters that customize the behavior of the allocator.
|
||||
///
|
||||
/// Generally, these parameters adjust the tradeoff between memory fragmentation
|
||||
/// and speed. You can adjust them as desired for your application. Most
|
||||
/// applications can stick with the default values.
|
||||
#[derive(Resource, Deref, DerefMut)]
|
||||
pub struct TapeAllocatorSettings {
|
||||
#[deref]
|
||||
pub slab_allocator_settings: SlabAllocatorSettings,
|
||||
|
||||
/// Additional buffer usages to add to any vertex or index buffers created.
|
||||
pub extra_buffer_usages: BufferUsages,
|
||||
}
|
||||
|
||||
impl Default for TapeAllocatorSettings {
|
||||
fn default() -> TapeAllocatorSettings {
|
||||
TapeAllocatorSettings {
|
||||
slab_allocator_settings: SlabAllocatorSettings::default(),
|
||||
extra_buffer_usages: BufferUsages::empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ID of a single slab.
|
||||
pub type TapeSlabId = SlabId<TapeSlabItem>;
|
||||
|
||||
/// The slab buffer and location within that slab in which each tape is
|
||||
/// allocated.
|
||||
pub type TapeBufferSlice<'a> = SlabAllocationBufferSlice<'a, TapeSlabItem>;
|
||||
|
||||
/// The [`SlabItem`] implementation that describes the information needed to
|
||||
/// allocate and free tapes.
|
||||
pub struct TapeSlabItem;
|
||||
|
||||
impl SlabItem for TapeSlabItem {
|
||||
type Key = TapeAllocationKey;
|
||||
type Layout = ElementLayout;
|
||||
|
||||
fn label() -> Cow<'static, str> {
|
||||
"tape".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// IDs of the slabs associated with a single tape.
|
||||
#[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,
|
||||
/// The slab storing the tape's metadata.
|
||||
pub metadata_slab_id: Option<TapeSlabId>,
|
||||
}
|
||||
|
||||
/// Returns the type of buffer that this is: vertex, index, metadata.
|
||||
fn element_class(slab: &Slab<TapeSlabItem>) -> ElementClass {
|
||||
slab.element_layout().class
|
||||
}
|
||||
|
||||
/// The handle used to retrieve a single tape allocation.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
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,
|
||||
}
|
||||
|
||||
impl TapeAllocationKey {
|
||||
/// Creates a new [`TapeAllocationKey`] for the given tape asset ID and
|
||||
/// class.
|
||||
pub fn new(tape_id: AssetId<Tape>, class: ElementClass) -> Self {
|
||||
Self { tape_id, class }
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of element that a tape slab can store.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum ElementClass {
|
||||
/// Per-tape metadata
|
||||
Metadata,
|
||||
/// Data for the aabbs.
|
||||
Aabb,
|
||||
}
|
||||
|
||||
/// Information about the size of individual elements within a slab.
|
||||
///
|
||||
/// Slab objects are allocated in units of *slots*. Usually, each element takes
|
||||
/// up one slot, and so elements and slots are equivalent. Occasionally,
|
||||
/// however, a slot may consist of 2 or even 4 elements. This occurs when the
|
||||
/// size of an element isn't divisible by [`COPY_BUFFER_ALIGNMENT`]. When we
|
||||
/// resize buffers, we perform GPU-to-GPU copies to shuffle the existing
|
||||
/// elements into their new positions, and such copies must be on
|
||||
/// [`COPY_BUFFER_ALIGNMENT`] boundaries. Slots solve this problem by
|
||||
/// guaranteeing that the size of an allocation quantum is divisible by both the
|
||||
/// size of an element and [`COPY_BUFFER_ALIGNMENT`], so we can relocate it
|
||||
/// freely.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ElementLayout {
|
||||
class: ElementClass,
|
||||
|
||||
/// The size in bytes of a single element.
|
||||
size: u64,
|
||||
|
||||
/// The number of elements that make up a single slot.
|
||||
///
|
||||
/// Usually, this is 1, but it can be different if [`ElementLayout::size`]
|
||||
/// isn't divisible by 4. See the comment in [`ElementLayout`] for more
|
||||
/// details.
|
||||
elements_per_slot: u32,
|
||||
|
||||
buffer_usages: BufferUsages,
|
||||
}
|
||||
|
||||
impl Plugin for TapeAllocatorPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app
|
||||
.init_resource::<TapeAllocatorSettings>()
|
||||
.add_systems(
|
||||
Render,
|
||||
allocate_and_free_tapes
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.before(prepare_assets::<RenderTape>),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The `RenderAdapter` isn't available until now, so we can't do this in
|
||||
// [`Plugin::build`].
|
||||
render_app.init_gpu_resource::<TapeAllocator>();
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for TapeAllocator {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
// Take the `extra_buffer_usages` from the tape allocator settings into
|
||||
// account.
|
||||
let tape_allocator_settings = world.resource::<TapeAllocatorSettings>();
|
||||
let mut slab_allocator = SlabAllocator::new();
|
||||
slab_allocator.extra_buffer_usages |= tape_allocator_settings.extra_buffer_usages;
|
||||
|
||||
Self { slab_allocator }
|
||||
}
|
||||
}
|
||||
|
||||
/// A system that processes newly-extracted or newly-removed tapes and writes
|
||||
/// their data into buffers or frees their data as appropriate.
|
||||
pub fn allocate_and_free_tapes(
|
||||
mut tape_allocator: ResMut<TapeAllocator>,
|
||||
tape_allocator_settings: Res<TapeAllocatorSettings>,
|
||||
extracted_tapes: Res<ExtractedAssets<RenderTape>>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
) {
|
||||
bevy_log::debug!("Allocating and freeing tapes");
|
||||
bevy_log::debug!(
|
||||
"extracted tapes ({}): {:?}",
|
||||
extracted_tapes.extracted.len(),
|
||||
extracted_tapes.extracted
|
||||
);
|
||||
// Clear the list of tapes displaced by last frame's slab growth.
|
||||
tape_allocator.clear_displaced_keys();
|
||||
|
||||
// Process removed or modified tapes.
|
||||
tape_allocator.free_tapes(&extracted_tapes);
|
||||
|
||||
// Process newly-added or modified tapes.
|
||||
tape_allocator.allocate_tapes(
|
||||
&tape_allocator_settings,
|
||||
&extracted_tapes,
|
||||
&render_device,
|
||||
&render_queue,
|
||||
);
|
||||
}
|
||||
|
||||
impl TapeAllocator {
|
||||
/// Returns the buffer and range within that buffer of the metadata for
|
||||
/// the tape with the given ID.
|
||||
///
|
||||
/// If the tape wasn't allocated, returns None.
|
||||
pub fn tape_metadata_slice(&self, tape_id: &AssetId<Tape>) -> Option<TapeBufferSlice<'_>> {
|
||||
self.slab_allocation_slice(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Metadata),
|
||||
*self.tape_id_to_metadata_slab(tape_id)?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tapes that had the buffer under their aabb data replaced
|
||||
/// this frame by a slab they were already resident in growing, so that
|
||||
/// anything caching those buffers can rebuild just the affected
|
||||
/// entries.
|
||||
///
|
||||
/// **It is not the full set of tapes whose buffers changed this frame, and
|
||||
/// is not meant to be.** Callers must handle [`ExtractedAssets`]
|
||||
/// themselves if they want the full set of changed buffers.
|
||||
///
|
||||
/// See [`SlabAllocator::keys_displaced_by_slab_growth`], which this wraps.
|
||||
pub fn tapes_displaced_by_slab_growth(&self) -> impl Iterator<Item = AssetId<Tape>> {
|
||||
self.keys_displaced_by_slab_growth()
|
||||
.iter()
|
||||
.filter(|key| matches!(key.class, ElementClass::Aabb))
|
||||
.map(|key| key.tape_id)
|
||||
}
|
||||
|
||||
/// Returns the buffer and range within that buffer of the aabb data for
|
||||
/// the tape with the given ID.
|
||||
///
|
||||
/// If the tape wasn't allocated, returns None.
|
||||
pub fn tape_aabb_slice(&self, tape_id: &AssetId<Tape>) -> Option<TapeBufferSlice<'_>> {
|
||||
self.slab_allocation_slice(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Aabb),
|
||||
*self.tape_id_to_aabb_slab(tape_id)?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the IDs of the vertex buffer and index buffer respectively for
|
||||
/// the tape with the given ID.
|
||||
///
|
||||
/// If the tape wasn't allocated, or has no index data in the case of the
|
||||
/// index buffer, the corresponding element in the returned tuple will be
|
||||
/// 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()?,
|
||||
metadata_slab_id: self.tape_id_to_metadata_slab(tape_id).cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the number of aabb allocations that this tape allocator
|
||||
/// manages.
|
||||
pub fn aabb_allocation_count(&self) -> usize {
|
||||
self.key_to_slab
|
||||
.keys()
|
||||
.filter(|key| key.class == ElementClass::Aabb)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Given the ID of a tape, returns the ID of the slab that contains the
|
||||
/// metadata for that tape, if it exists.
|
||||
fn tape_id_to_metadata_slab(&self, tape_id: &AssetId<Tape>) -> Option<&SlabId<TapeSlabItem>> {
|
||||
self.key_to_slab
|
||||
.get(&TapeAllocationKey::new(*tape_id, ElementClass::Metadata))
|
||||
}
|
||||
|
||||
/// Given the ID of a tape, returns the ID of the slab that contains the
|
||||
/// aabb data for that tape, if it exists.
|
||||
fn tape_id_to_aabb_slab(&self, tape_id: &AssetId<Tape>) -> Option<&SlabId<TapeSlabItem>> {
|
||||
self.key_to_slab
|
||||
.get(&TapeAllocationKey::new(*tape_id, ElementClass::Aabb))
|
||||
}
|
||||
|
||||
pub fn metadata_slabs(&self) -> impl Iterator<Item = TapeSlabId> {
|
||||
self.slabs.iter().filter_map(|(slab_id, slab)| {
|
||||
if matches!(element_class(slab), ElementClass::Metadata) {
|
||||
Some(*slab_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Processes newly-loaded tapes, allocating room in the slabs for their
|
||||
/// tape data and performing upload operations as appropriate.
|
||||
fn allocate_tapes(
|
||||
&mut self,
|
||||
tape_allocator_settings: &TapeAllocatorSettings,
|
||||
extracted_tapes: &ExtractedAssets<RenderTape>,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) {
|
||||
let mut allocation_stage = self.slab_allocator.stage_allocation();
|
||||
|
||||
// Loop over each tape that was extracted this frame.
|
||||
for (tape_id, tape) in &extracted_tapes.extracted {
|
||||
let aabb_buffer_size = tape.get_aabb_buffer_size() as u64;
|
||||
bevy_log::debug!("Tape {:?} has buffer size {}", tape_id, aabb_buffer_size);
|
||||
if aabb_buffer_size == 0 {
|
||||
warn!("Tape {:?} contains no aabbs.", tape_id);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Allocate metadata.
|
||||
let metadata_element_layout = ElementLayout::metadata(tape);
|
||||
bevy_log::debug!(
|
||||
"Tape {:?} has metadata element layout {:?}",
|
||||
tape_id,
|
||||
metadata_element_layout
|
||||
);
|
||||
allocation_stage.allocate(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Metadata),
|
||||
size_of::<TapeMetadata>() as u64,
|
||||
metadata_element_layout,
|
||||
tape_allocator_settings,
|
||||
);
|
||||
|
||||
// Allocate aabb data.
|
||||
let aabb_element_layout = ElementLayout::aabb(tape);
|
||||
bevy_log::debug!(
|
||||
"Tape {:?} has aabb element layout {:?}",
|
||||
tape_id,
|
||||
aabb_element_layout
|
||||
);
|
||||
allocation_stage.allocate(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Aabb),
|
||||
aabb_buffer_size,
|
||||
aabb_element_layout,
|
||||
tape_allocator_settings,
|
||||
);
|
||||
}
|
||||
|
||||
// Perform growth.
|
||||
allocation_stage.commit(render_device, render_queue);
|
||||
for (tape_id, _) in &extracted_tapes.extracted {
|
||||
bevy_log::debug!("Tape {}: Aabb slice allocated", tape_id);
|
||||
debug_assert!(self.tape_id_to_aabb_slab(tape_id).is_some())
|
||||
}
|
||||
|
||||
// Copy new tape data in.
|
||||
for (tape_id, tape) in &extracted_tapes.extracted {
|
||||
let aabb_buffer_size = tape.get_aabb_buffer_size() as u64;
|
||||
if aabb_buffer_size == 0 {
|
||||
continue;
|
||||
}
|
||||
self.copy_tape_aabb(tape_id, tape, render_device, render_queue);
|
||||
self.copy_tape_metadata(tape_id, tape, render_device, render_queue);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies metadata from a tape into the appropriate spot in the slab.
|
||||
fn copy_tape_metadata(
|
||||
&mut self,
|
||||
tape_id: &AssetId<Tape>,
|
||||
tape: &Tape,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) {
|
||||
let metadata = {
|
||||
let aabb = tape.get_aabb(0.0);
|
||||
let aabb_center = aabb.center().into();
|
||||
let aabb_half_extents = aabb.half_size().into();
|
||||
TapeMetadata {
|
||||
aabb_center,
|
||||
aabb_half_extents,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
// Call the generic function.
|
||||
self.copy_element_data(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Metadata),
|
||||
size_of::<TapeMetadata>(),
|
||||
|mut slice| slice.copy_from_slice(bytemuck::cast_slice(&[metadata])),
|
||||
render_device,
|
||||
render_queue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Fills the tape AABB buffer with zeros.
|
||||
fn copy_tape_aabb(
|
||||
&mut self,
|
||||
tape_id: &AssetId<Tape>,
|
||||
tape: &Tape,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) {
|
||||
let length = tape.get_aabb_buffer_size();
|
||||
// Call the generic function.
|
||||
self.copy_element_data(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Aabb),
|
||||
length as _,
|
||||
|mut slice| slice.fill(0),
|
||||
render_device,
|
||||
render_queue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Frees allocations for tapes that were removed, modified, or
|
||||
/// re-extracted this frame.
|
||||
fn free_tapes(&mut self, extracted_tapes: &ExtractedAssets<RenderTape>) {
|
||||
let mut deallocation_stage = self.slab_allocator.stage_deallocation();
|
||||
|
||||
// TODO: Consider explicitly reusing allocations for changed tapes of
|
||||
// the same size
|
||||
|
||||
// Free every tape that `allocate_tapes` is about to reallocate.
|
||||
// Despite its name, `added` holds every tape extracted this
|
||||
// frame rather than only the new ones, so it's exactly that
|
||||
// set. This catches a tape removed from `Assets` and reinserted
|
||||
// under the same ID, which arrives as `Removed` then `Added`
|
||||
// and so never appears in `modified`.
|
||||
let tapes_to_free = extracted_tapes
|
||||
.removed
|
||||
.iter()
|
||||
.chain(extracted_tapes.modified.iter())
|
||||
.chain(extracted_tapes.added.iter());
|
||||
|
||||
for tape_id in tapes_to_free {
|
||||
deallocation_stage.free(&TapeAllocationKey::new(*tape_id, ElementClass::Metadata));
|
||||
deallocation_stage.free(&TapeAllocationKey::new(*tape_id, ElementClass::Aabb));
|
||||
}
|
||||
|
||||
deallocation_stage.commit();
|
||||
}
|
||||
}
|
||||
|
||||
impl ElementLayout {
|
||||
/// Creates an [`ElementLayout`] for tape data of the given class (vertex or
|
||||
/// index) with the given byte size.
|
||||
fn new(class: ElementClass, size: u64) -> ElementLayout {
|
||||
const {
|
||||
assert!(4 == COPY_BUFFER_ALIGNMENT);
|
||||
}
|
||||
|
||||
// this is equivalent to `4 / gcd(4,size)` but lets us not implement
|
||||
// gcd. ping @atlv if above assert ever fails (likely never)
|
||||
let elements_per_slot = [1, 4, 2, 4][size as usize & 3];
|
||||
ElementLayout {
|
||||
class,
|
||||
size,
|
||||
// Make sure that slot boundaries begin and end on
|
||||
// `COPY_BUFFER_ALIGNMENT`-byte (4-byte) boundaries.
|
||||
elements_per_slot,
|
||||
buffer_usages: class.buffer_usages(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the appropriate [`ElementLayout`] for the given tape's metadata
|
||||
/// data.
|
||||
fn metadata(_tape: &Tape) -> ElementLayout {
|
||||
ElementLayout {
|
||||
class: ElementClass::Metadata,
|
||||
size: size_of::<TapeMetadata>() as u64,
|
||||
elements_per_slot: 1,
|
||||
buffer_usages: ElementClass::Metadata.buffer_usages(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the appropriate [`ElementLayout`] for the given tape's aabb
|
||||
/// data.
|
||||
fn aabb(_tape: &Tape) -> ElementLayout {
|
||||
ElementLayout::new(ElementClass::Aabb, size_of::<Aabb>() as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl SlabItemLayout for ElementLayout {
|
||||
fn size(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
|
||||
fn elements_per_slot(&self) -> u32 {
|
||||
self.elements_per_slot
|
||||
}
|
||||
|
||||
fn buffer_usages(&self) -> BufferUsages {
|
||||
self.buffer_usages
|
||||
}
|
||||
}
|
||||
|
||||
impl ElementClass {
|
||||
/// Returns the `wgpu` [`BufferUsages`] appropriate for a buffer of this
|
||||
/// class.
|
||||
const fn buffer_usages(&self) -> BufferUsages {
|
||||
match *self {
|
||||
ElementClass::Metadata => BufferUsages::STORAGE,
|
||||
ElementClass::Aabb => {
|
||||
BufferUsages::union(BufferUsages::STORAGE, BufferUsages::BLAS_INPUT)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
struct TapeMetadata {
|
||||
/// AABB for decompressing positions.
|
||||
aabb_center: vec3<f32>,
|
||||
pad_a: u32,
|
||||
aabb_half_extents: vec3<f32>,
|
||||
pad_b: u32,
|
||||
};
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Vaguely analagous to bevy_render::mesh
|
||||
*/
|
||||
pub mod allocator;
|
||||
|
||||
use allocator::TapeAllocatorPlugin;
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::{AssetId, AssetServer, Assets, Handle};
|
||||
use bevy_ecs::{
|
||||
prelude::*,
|
||||
system::{SystemParamItem, lifetimeless::SRes},
|
||||
};
|
||||
use bevy_math::Vec3;
|
||||
use bevy_reflect::Reflect;
|
||||
use bevy_render::{
|
||||
Render, RenderApp, RenderSystems,
|
||||
render_asset::{
|
||||
AssetExtractionError, PrepareAssetError, RenderAsset, RenderAssetPlugin, prepare_assets,
|
||||
},
|
||||
render_resource::{
|
||||
BindGroupLayoutDescriptor, Buffer, CachedComputePipelineId, ComputePipelineDescriptor,
|
||||
PipelineCache, ShaderType,
|
||||
},
|
||||
};
|
||||
use bevy_shader::{Shader, load_shader_library};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use rspirv::dr::Module;
|
||||
|
||||
use crate::{
|
||||
render::allocator::{ElementClass, TapeAllocationKey, TapeAllocator, TapeSlabId},
|
||||
tape::Tape,
|
||||
};
|
||||
|
||||
/// Makes sure that [`Tape`]es are extracted and prepared for the GPU.
|
||||
/// Does *not* add the [`Tape`] as an asset. Use [`TapePlugin`] for that.
|
||||
pub struct TapeRenderAssetPlugin;
|
||||
|
||||
impl Plugin for TapeRenderAssetPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
load_shader_library!(app, "metadata_types.wesl");
|
||||
|
||||
app.add_plugins(RenderAssetPlugin::<RenderTape>::default())
|
||||
.add_plugins(TapeAllocatorPlugin);
|
||||
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app.add_systems(
|
||||
Render,
|
||||
prepare_tape_metadata_fallback_buffer
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.after(prepare_assets::<RenderTape>),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let mut tape_assets = app.world_mut().resource_mut::<Assets<Tape>>();
|
||||
let handle =
|
||||
tape_assets.add(crate::primitives::sphere::SphereTapeBuilder::build_with_radius(1.0));
|
||||
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app.insert_resource(TapeMetadataFallbackTape(handle));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct TapeMetadataFallbackTape(pub Handle<Tape>);
|
||||
|
||||
/// Metadata slab ID and buffer of [`TapeMetadataFallbackTape`],
|
||||
/// used to fill bind group for tape without metadata.
|
||||
#[derive(Resource)]
|
||||
pub struct TapeMetadataFallbackBuffer {
|
||||
pub slab_id: TapeSlabId,
|
||||
pub buffer: Buffer,
|
||||
}
|
||||
|
||||
pub fn prepare_tape_metadata_fallback_buffer(
|
||||
mut commands: Commands,
|
||||
tape_allocator: Res<TapeAllocator>,
|
||||
metadata_fallback_tape: Res<TapeMetadataFallbackTape>,
|
||||
) {
|
||||
let slab_id = tape_allocator
|
||||
.key_to_slab
|
||||
.get(&TapeAllocationKey::new(
|
||||
metadata_fallback_tape.0.id(),
|
||||
ElementClass::Metadata,
|
||||
))
|
||||
.cloned()
|
||||
.unwrap();
|
||||
let buffer = tape_allocator.buffer_for_slab(slab_id).unwrap().clone();
|
||||
commands.insert_resource(TapeMetadataFallbackBuffer { slab_id, buffer });
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Copy, Reflect)]
|
||||
#[reflect(Debug, PartialEq, Clone)]
|
||||
pub struct Aabb {
|
||||
/// The minimum point of the box
|
||||
pub min: Vec3,
|
||||
/// The maximum point of the box
|
||||
pub max: Vec3,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct ReplacementModules {
|
||||
pub enable_gen: Module,
|
||||
pub fuzz: Module,
|
||||
pub normals: Module,
|
||||
pub spatial_texture: Module,
|
||||
pub trace: Module,
|
||||
|
||||
pub enable_gen_layout: BindGroupLayoutDescriptor,
|
||||
pub fuzz_layout: BindGroupLayoutDescriptor,
|
||||
pub spatial_texture_layout: BindGroupLayoutDescriptor,
|
||||
}
|
||||
|
||||
/// Per-tape metadata, stored in [`super::allocator::TapeAllocator`].
|
||||
/// Currently this is used to decompress vertex.
|
||||
#[derive(Default, Pod, Zeroable, Clone, Copy, Debug, ShaderType)]
|
||||
#[repr(C)]
|
||||
pub struct TapeMetadata {
|
||||
// AABB for decompressing positions.
|
||||
pub aabb_center: Vec3,
|
||||
pub pad1: u32,
|
||||
// AABB for decompressing positions.
|
||||
pub aabb_half_extents: Vec3,
|
||||
pub pad2: u32,
|
||||
}
|
||||
|
||||
/// The render world representation of a [`Tape`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RenderTape {
|
||||
pub seed: u64,
|
||||
pub subdivision: u32,
|
||||
|
||||
pub enable_gen: Handle<Shader>,
|
||||
pub fuzz: Handle<Shader>,
|
||||
pub normals: Handle<Shader>,
|
||||
pub spatial_texture: Handle<Shader>,
|
||||
pub trace: Handle<Shader>,
|
||||
|
||||
pub enable_gen_pipeline: CachedComputePipelineId,
|
||||
pub fuzz_pipeline: CachedComputePipelineId,
|
||||
pub spatial_texture_pipeline: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
impl RenderAsset for RenderTape {
|
||||
type Param = (
|
||||
SRes<AssetServer>,
|
||||
SRes<ReplacementModules>,
|
||||
SRes<PipelineCache>,
|
||||
);
|
||||
type SourceAsset = Tape;
|
||||
|
||||
fn take_gpu_data(
|
||||
source: &mut Self::SourceAsset,
|
||||
_previous_gpu_asset: Option<&Self>,
|
||||
) -> Result<Self::SourceAsset, AssetExtractionError> {
|
||||
Ok(source.clone())
|
||||
}
|
||||
|
||||
fn byte_len(_tape: &Self::SourceAsset) -> Option<usize> {
|
||||
// Some(0) // Is this really correct?
|
||||
None
|
||||
}
|
||||
|
||||
/// Converts the extracted tape into a [`RenderTape`].
|
||||
fn prepare_asset(
|
||||
tape: Self::SourceAsset,
|
||||
_tape_id: AssetId<Self::SourceAsset>,
|
||||
(asset_server, replacement_modules, pipeline_cache): &mut SystemParamItem<Self::Param>,
|
||||
_: Option<&Self>,
|
||||
) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
|
||||
let key = tape.get_tape_key();
|
||||
|
||||
let enable_gen = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.enable_gen.clone(),
|
||||
"enable_gen",
|
||||
));
|
||||
let fuzz = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.fuzz.clone(),
|
||||
"fuzz",
|
||||
));
|
||||
let normals = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.normals.clone(),
|
||||
"normals",
|
||||
));
|
||||
let spatial_texture = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.spatial_texture.clone(),
|
||||
"spatial_texture",
|
||||
));
|
||||
let trace = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.trace.clone(),
|
||||
"trace",
|
||||
));
|
||||
|
||||
let enable_gen_pipeline =
|
||||
pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some(format!("bevy_tape_drive::gen_shader::enable_gen::{key}").into()),
|
||||
layout: vec![replacement_modules.enable_gen_layout.clone()],
|
||||
shader: enable_gen.clone(),
|
||||
entry_point: Some("enable_gen_entry".into()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let fuzz_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some(format!("bevy_tape_drive::gen_shader::fuzz::{key}").into()),
|
||||
layout: vec![replacement_modules.fuzz_layout.clone()],
|
||||
shader: fuzz.clone(),
|
||||
entry_point: Some("fuzz_entry".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(),
|
||||
entry_point: Some("spatial_texture_entry".into()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Ok(RenderTape {
|
||||
seed: tape.seed,
|
||||
subdivision: tape.subdivision,
|
||||
enable_gen,
|
||||
fuzz,
|
||||
normals,
|
||||
spatial_texture,
|
||||
trace,
|
||||
enable_gen_pipeline,
|
||||
fuzz_pipeline,
|
||||
spatial_texture_pipeline,
|
||||
})
|
||||
}
|
||||
|
||||
fn unload_asset(_tape_id: AssetId<Self::SourceAsset>, (..): &mut SystemParamItem<Self::Param>) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use bevy_asset::Asset;
|
||||
use bevy_reflect::Reflect;
|
||||
use bevy_shader::Shader;
|
||||
use bevy_shape::Aabb3d;
|
||||
use rspirv::{binary::Assemble as _, dr::Module};
|
||||
|
||||
use crate::{render::Aabb, ssa::*};
|
||||
|
||||
/// A tape drive tape.
|
||||
#[derive(Asset, Clone, Debug, Reflect, PartialEq, Hash)]
|
||||
#[reflect(Clone)]
|
||||
pub struct Tape {
|
||||
pub parts: SSATape,
|
||||
pub seed: u64,
|
||||
pub subdivision: u32,
|
||||
}
|
||||
|
||||
impl Default for Tape {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
parts: Default::default(),
|
||||
seed: 0,
|
||||
subdivision: 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tape {
|
||||
pub fn get_aabb(&self, time: f32) -> Aabb3d {
|
||||
let (lowest_corner, highest_corner) = self.parts.get_aabb(time);
|
||||
|
||||
Aabb3d::from_min_max(lowest_corner, highest_corner)
|
||||
}
|
||||
|
||||
pub fn get_aabb_buffer_size(&self) -> u64 {
|
||||
((self.subdivision * self.subdivision * self.subdivision) as u64) * size_of::<Aabb>() as u64
|
||||
}
|
||||
|
||||
pub fn get_tape_key(&self) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
self.parts.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
pub(crate) fn sdf_specialize_module(&self, module: Module, name: &str) -> Shader {
|
||||
self.sdf_specialize_module_with_key(self.get_tape_key(), module, name)
|
||||
}
|
||||
|
||||
pub(crate) fn sdf_specialize_module_with_key(
|
||||
&self,
|
||||
key: u64,
|
||||
module: Module,
|
||||
name: &str,
|
||||
) -> Shader {
|
||||
let new_module = self.parts.compile_to_spirv(Some(module));
|
||||
|
||||
let assembled_module = new_module.assemble();
|
||||
let bytes = assembled_module
|
||||
.iter()
|
||||
.cloned()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let path = format!("bevy_tape_drive::gen_shader::{name}::{key}");
|
||||
|
||||
Shader::from_spirv(bytes, path)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user