split into two crates

This commit is contained in:
2026-10-02 18:01:02 +01:00
parent 10ca25b695
commit 663f67ae3c
55 changed files with 8405 additions and 614 deletions
@@ -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;