use std::collections::HashMap;
use glam::{Mat4, Vec2, Vec3, Vec4};
use wgpu::util::DeviceExt;
mod shadows;
pub use shadows::shadow_triangles;
use shadows::{ShadowVertex, grown_shadow_capacity, max_shadow_vertices, shadow_triangles_limited};
use crate::assets::{Handle, Texture};
use crate::canvas::camera::WorldUnits;
use crate::canvas::sprite::TextureError;
pub const MAX_LIGHTS: usize = 32;
pub const MAX_SHADOW_LIGHTS: usize = 8;
const SHADOW_FAR: f32 = 4096.0;
pub const ACCUM_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
pub const SHADOW_MASK_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm;
#[derive(Debug, Clone, Copy)]
pub struct PointLight {
pub pos: Vec2,
pub cookie: Option<Handle<Texture>>,
pub radius: f32,
pub falloff: f32,
pub color: [f32; 3],
pub energy: f32,
pub texture_scale: f32,
pub height: f32,
pub item_mask: u32,
pub shadows: bool,
}
impl PointLight {
pub fn new(cookie: Handle<Texture>, pos: Vec2) -> Self {
Self {
pos,
cookie: Some(cookie),
radius: 0.0,
falloff: 0.0,
color: [1.0, 1.0, 1.0],
energy: 1.0,
texture_scale: 1.0,
height: 128.0,
item_mask: 1,
shadows: false,
}
}
pub fn analytic(pos: Vec2, radius: f32, falloff: f32) -> Self {
Self {
pos,
cookie: None,
radius,
falloff,
color: [1.0, 1.0, 1.0],
energy: 1.0,
texture_scale: 1.0,
height: 128.0,
item_mask: 1,
shadows: false,
}
}
}
#[derive(Debug, Clone)]
pub struct LightFrame {
pub canvas_modulate: [f32; 4],
pub lights: Vec<PointLight>,
pub occluders: Vec<Vec<Vec2>>,
}
impl Default for LightFrame {
fn default() -> Self {
Self {
canvas_modulate: [1.0, 1.0, 1.0, 1.0],
lights: Vec::new(),
occluders: Vec::new(),
}
}
}
#[must_use]
pub fn analytic_params_valid(radius: f32, falloff: f32) -> bool {
radius.is_finite() && radius > 0.0 && falloff.is_finite() && falloff >= 0.0
}
#[must_use]
pub fn analytic_attenuation(dist: f32, radius: f32, falloff: f32) -> f32 {
if !analytic_params_valid(radius, falloff) {
return 0.0;
}
let s = dist / radius;
let s2 = s * s;
let bell = (1.0 - s2).max(0.0);
bell * bell / (1.0 + falloff * s2)
}
#[must_use]
pub fn normal_factor(light_pos: Vec2, height: f32, frag_pos: Vec2, normal: [f32; 3]) -> f32 {
let n = Vec3::from_array(normal);
let n_len = n.length();
if n_len < 1e-3 {
return 1.0;
}
let l = Vec3::new(light_pos.x - frag_pos.x, light_pos.y - frag_pos.y, height);
let l_len = l.length();
if l_len < 1e-6 {
return 1.0;
}
((n / n_len).dot(l / l_len)).max(0.0)
}
#[must_use]
pub fn cookie_half_extent(cookie_px: Vec2, texture_scale: f32, pixels_per_unit: f32) -> Vec2 {
cookie_px * texture_scale * 0.5 / pixels_per_unit
}
#[must_use]
pub fn mask_bits(mask: u32) -> [f32; 3] {
[
if mask & 1 != 0 { 1.0 } else { 0.0 },
if mask & 2 != 0 { 1.0 } else { 0.0 },
if mask & 4 != 0 { 1.0 } else { 0.0 },
]
}
#[must_use]
pub fn mask_matches(light_mask: u32, item_mask: u32) -> bool {
light_mask & item_mask & 0b111 != 0
}
#[must_use]
pub fn coverage(mask_rgb: [f32; 3], item_mask: u32) -> f32 {
let bits = mask_bits(item_mask);
(mask_rgb[0] * bits[0] + mask_rgb[1] * bits[1] + mask_rgb[2] * bits[2]).clamp(0.0, 1.0)
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct LightRaw {
pos_half: [f32; 4],
color_energy: [f32; 4],
params: [f32; 4],
mask: [f32; 4],
}
impl LightRaw {
const ZERO: Self = Self {
pos_half: [0.0; 4],
color_energy: [0.0; 4],
params: [0.0; 4],
mask: [0.0; 4],
};
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct LightsUniform {
view_proj: [[f32; 4]; 4],
screen: [f32; 4],
lights: [LightRaw; MAX_LIGHTS],
}
struct Cookie {
bind_group: wgpu::BindGroup,
size: Vec2,
}
struct LightDraw {
index: u32,
cookie: Option<Handle<Texture>>,
shadow: Option<std::ops::Range<u32>>,
}
pub struct LightPass {
accum_texture: wgpu::Texture,
accum_view: wgpu::TextureView,
shadow_mask_view: wgpu::TextureView,
light_pipeline: wgpu::RenderPipeline,
shadow_pipeline: wgpu::RenderPipeline,
uniform: wgpu::Buffer,
frame_bgl: wgpu::BindGroupLayout,
frame_bind_group: wgpu::BindGroup,
shadow_bind_group: wgpu::BindGroup,
cookie_bgl: wgpu::BindGroupLayout,
cookie_sampler: wgpu::Sampler,
cookies: HashMap<Handle<Texture>, Cookie>,
analytic_bind_group: wgpu::BindGroup,
shadow_vb: wgpu::Buffer,
shadow_capacity: u64,
verts: Vec<ShadowVertex>,
plan: Vec<LightDraw>,
}
const INITIAL_SHADOW_VERTS: u64 = 1024;
fn light_targets(
device: &wgpu::Device,
width: u32,
height: u32,
) -> (wgpu::Texture, wgpu::TextureView) {
let target = |label: &str, format: wgpu::TextureFormat, extra: wgpu::TextureUsages| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| extra,
view_formats: &[],
})
};
(
target(
"light accumulation target",
ACCUM_FORMAT,
wgpu::TextureUsages::COPY_SRC,
),
target(
"shadow mask target",
SHADOW_MASK_FORMAT,
wgpu::TextureUsages::empty(),
)
.create_view(&wgpu::TextureViewDescriptor::default()),
)
}
fn cookie_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
sampler: &wgpu::Sampler,
view: &wgpu::TextureView,
) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("light cookie bind group"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(sampler),
},
],
})
}
fn frame_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
uniform: &wgpu::Buffer,
normal_view: &wgpu::TextureView,
mask_view: &wgpu::TextureView,
shadow_mask_view: &wgpu::TextureView,
) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("light frame bind group"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(normal_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(mask_view),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(shadow_mask_view),
},
],
})
}
impl LightPass {
pub fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
normal_view: &wgpu::TextureView,
mask_view: &wgpu::TextureView,
logical_width: u32,
logical_height: u32,
) -> Self {
let (accum_texture, shadow_mask_view) =
light_targets(device, logical_width, logical_height);
let accum_view = accum_texture.create_view(&wgpu::TextureViewDescriptor::default());
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("light shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("light.wgsl").into()),
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("lights uniform"),
size: size_of::<LightsUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let uniform_entry = wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let tex_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let frame_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("light frame bgl"),
entries: &[uniform_entry, tex_entry(1), tex_entry(2), tex_entry(3)],
});
let frame_bind_group = frame_bind_group(
device,
&frame_bgl,
&uniform,
normal_view,
mask_view,
&shadow_mask_view,
);
let shadow_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("shadow bgl"),
entries: &[uniform_entry],
});
let shadow_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("shadow bind group"),
layout: &shadow_bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
}],
});
let cookie_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("light cookie bgl"),
entries: &[
tex_entry(0),
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let cookie_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("light cookie sampler (linear)"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let white = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
label: Some("analytic light dummy cookie (1x1 white)"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&[255, 255, 255, 255],
);
let analytic_bind_group = cookie_bind_group(
device,
&cookie_bgl,
&cookie_sampler,
&white.create_view(&wgpu::TextureViewDescriptor::default()),
);
let light_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("light pipeline layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&cookie_bgl)],
immediate_size: 0,
});
let light_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("light pipeline"),
layout: Some(&light_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_light"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_light"),
targets: &[Some(wgpu::ColorTargetState {
format: ACCUM_FORMAT,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("shadow pipeline layout"),
bind_group_layouts: &[Some(&shadow_bgl)],
immediate_size: 0,
});
let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("shadow mask pipeline"),
layout: Some(&shadow_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_shadow"),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: size_of::<ShadowVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x2],
})],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_shadow"),
targets: &[Some(wgpu::ColorTargetState {
format: SHADOW_MASK_FORMAT,
blend: None, write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let shadow_capacity =
INITIAL_SHADOW_VERTS.min(max_shadow_vertices(device.limits().max_buffer_size));
let shadow_vb = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("shadow vertex buffer"),
size: shadow_capacity * size_of::<ShadowVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
Self {
accum_texture,
accum_view,
shadow_mask_view,
light_pipeline,
shadow_pipeline,
uniform,
frame_bgl,
frame_bind_group,
shadow_bind_group,
cookie_bgl,
cookie_sampler,
cookies: HashMap::new(),
analytic_bind_group,
shadow_vb,
shadow_capacity,
verts: Vec::new(),
plan: Vec::new(),
}
}
pub fn resize(
&mut self,
device: &wgpu::Device,
normal_view: &wgpu::TextureView,
mask_view: &wgpu::TextureView,
width: u32,
height: u32,
) {
let (accum_texture, shadow_mask_view) = light_targets(device, width, height);
self.frame_bind_group = frame_bind_group(
device,
&self.frame_bgl,
&self.uniform,
normal_view,
mask_view,
&shadow_mask_view,
);
self.accum_view = accum_texture.create_view(&wgpu::TextureViewDescriptor::default());
self.accum_texture = accum_texture;
self.shadow_mask_view = shadow_mask_view;
}
pub fn accum_view(&self) -> &wgpu::TextureView {
&self.accum_view
}
pub fn accum_texture(&self) -> &wgpu::Texture {
&self.accum_texture
}
pub fn upload_cookie(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
handle: Handle<Texture>,
tex: &Texture,
) -> Result<(), TextureError> {
TextureError::check(device, tex)?;
if self.cookies.contains_key(&handle) {
return Ok(());
}
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("light cookie"),
size: wgpu::Extent3d {
width: tex.width,
height: tex.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&tex.rgba,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * tex.width),
rows_per_image: Some(tex.height),
},
wgpu::Extent3d {
width: tex.width,
height: tex.height,
depth_or_array_layers: 1,
},
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let bind_group = cookie_bind_group(device, &self.cookie_bgl, &self.cookie_sampler, &view);
self.cookies.insert(
handle,
Cookie {
bind_group,
size: Vec2::new(tex.width as f32, tex.height as f32),
},
);
Ok(())
}
pub fn prepare(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
view_proj: Mat4,
units: WorldUnits,
frame: &LightFrame,
logical_size: (u32, u32),
) {
self.plan.clear();
self.verts.clear();
let max_vertices = max_shadow_vertices(device.limits().max_buffer_size);
let inv = view_proj.inverse();
let mut view_min = Vec2::splat(f32::MAX);
let mut view_max = Vec2::splat(f32::MIN);
for (cx, cy) in [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] {
let w = inv * Vec4::new(cx, cy, 0.5, 1.0);
view_min = view_min.min(Vec2::new(w.x, w.y));
view_max = view_max.max(Vec2::new(w.x, w.y));
}
let mut raw = [LightRaw::ZERO; MAX_LIGHTS];
let mut shadow_count = 0usize;
let mut shadow_full = false;
for want_shadow in [false, true] {
for light in &frame.lights {
if self.plan.len() == MAX_LIGHTS {
break;
}
if light.shadows != want_shadow || light.energy <= 0.0 {
continue;
}
let (half, radius, falloff) = if let Some(handle) = light.cookie {
let Some(cookie) = self.cookies.get(&handle) else {
continue; };
(
cookie_half_extent(cookie.size, light.texture_scale, units.pixels_per_unit),
0.0,
0.0,
)
} else {
if !analytic_params_valid(light.radius, light.falloff) {
continue; }
(Vec2::splat(light.radius), light.radius, light.falloff)
};
if light.pos.x - half.x > view_max.x
|| light.pos.x + half.x < view_min.x
|| light.pos.y - half.y > view_max.y
|| light.pos.y + half.y < view_min.y
{
continue; }
let shadow = if light.shadows && shadow_count < MAX_SHADOW_LIGHTS && !shadow_full {
let start = self.verts.len() as u32;
shadow_full = shadow_triangles_limited(
light.pos,
half,
&frame.occluders,
(SHADOW_FAR / units.pixels_per_unit).max(2.0 * half.max_element()),
&mut self.verts,
max_vertices,
);
let end = self.verts.len() as u32;
if end > start {
shadow_count += 1;
Some(start..end)
} else {
None }
} else {
None
};
let index = self.plan.len();
let bits = mask_bits(light.item_mask);
raw[index] = LightRaw {
pos_half: [light.pos.x, light.pos.y, half.x, half.y],
color_energy: [light.color[0], light.color[1], light.color[2], light.energy],
params: [
light.height,
if shadow.is_some() { 1.0 } else { 0.0 },
radius,
falloff,
],
mask: [bits[0], bits[1], bits[2], 0.0],
};
self.plan.push(LightDraw {
index: index as u32,
cookie: light.cookie,
shadow,
});
}
}
let uniform = LightsUniform {
view_proj: view_proj.to_cols_array_2d(),
screen: [
logical_size.0 as f32,
logical_size.1 as f32,
units.screen_y_sign(),
0.0,
],
lights: raw,
};
queue.write_buffer(&self.uniform, 0, bytemuck::cast_slice(&[uniform]));
if !self.verts.is_empty() {
let needed = self.verts.len() as u64;
if needed > self.shadow_capacity {
let new_cap = grown_shadow_capacity(needed, max_vertices);
self.shadow_vb = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("shadow vertex buffer"),
size: new_cap * size_of::<ShadowVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
self.shadow_capacity = new_cap;
}
queue.write_buffer(&self.shadow_vb, 0, bytemuck::cast_slice(&self.verts));
}
}
fn cookie_bind_group_for(&self, draw: &LightDraw) -> &wgpu::BindGroup {
draw.cookie.map_or(&self.analytic_bind_group, |handle| {
&self.cookies[&handle].bind_group
})
}
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn shadow_capacity(&self) -> u64 {
self.shadow_capacity
}
pub fn run(&self, encoder: &mut wgpu::CommandEncoder) {
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("light accumulation pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &self.accum_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.light_pipeline);
pass.set_bind_group(0, &self.frame_bind_group, &[]);
for draw in self.plan.iter().filter(|d| d.shadow.is_none()) {
pass.set_bind_group(1, self.cookie_bind_group_for(draw), &[]);
pass.draw(0..6, draw.index..draw.index + 1);
}
}
for draw in &self.plan {
let Some(range) = &draw.shadow else { continue };
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("shadow mask pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &self.shadow_mask_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::WHITE),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.shadow_pipeline);
pass.set_bind_group(0, &self.shadow_bind_group, &[]);
pass.set_vertex_buffer(0, self.shadow_vb.slice(..));
pass.draw(range.clone(), 0..1);
}
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("shadowed light pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &self.accum_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.light_pipeline);
pass.set_bind_group(0, &self.frame_bind_group, &[]);
pass.set_bind_group(1, self.cookie_bind_group_for(draw), &[]);
pass.draw(0..6, draw.index..draw.index + 1);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use wasm_bindgen_test::wasm_bindgen_test;
#[wasm_bindgen_test(unsupported = test)]
fn normal_factor_overhead_flat_is_one() {
let f = normal_factor(
Vec2::new(10.0, 10.0),
128.0,
Vec2::new(10.0, 10.0),
[0.0, 0.0, 1.0],
);
assert!((f - 1.0).abs() < 1e-6);
}
#[wasm_bindgen_test(unsupported = test)]
fn normal_factor_offset_flat_is_cos45() {
let f = normal_factor(Vec2::ZERO, 128.0, Vec2::new(128.0, 0.0), [0.0, 0.0, 1.0]);
assert!((f - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5, "{f}");
}
#[wasm_bindgen_test(unsupported = test)]
fn normal_factor_tilt_toward_and_away() {
let inv = std::f32::consts::FRAC_1_SQRT_2;
let toward = normal_factor(Vec2::ZERO, 128.0, Vec2::new(128.0, 0.0), [-inv, 0.0, inv]);
assert!((toward - 1.0).abs() < 1e-5, "{toward}");
let away = normal_factor(Vec2::ZERO, 1.0, Vec2::new(128.0, 0.0), [inv, 0.0, -inv]);
assert_eq!(away, 0.0);
}
#[wasm_bindgen_test(unsupported = test)]
fn normal_factor_degenerate_normal_is_one() {
let f = normal_factor(Vec2::ZERO, 128.0, Vec2::new(500.0, 0.0), [0.0, 0.0, 0.0]);
assert_eq!(f, 1.0);
}
#[wasm_bindgen_test(unsupported = test)]
fn normal_factor_normalizes_input() {
let a = normal_factor(Vec2::ZERO, 128.0, Vec2::new(64.0, 32.0), [0.0, 0.0, 1.0]);
let b = normal_factor(Vec2::ZERO, 128.0, Vec2::new(64.0, 32.0), [0.0, 0.0, 7.5]);
assert!((a - b).abs() < 1e-6);
}
#[wasm_bindgen_test(unsupported = test)]
fn analytic_attenuation_matches_hand_values() {
assert_eq!(analytic_attenuation(0.0, 16.0, 72.0), 1.0);
let mid = analytic_attenuation(8.0, 16.0, 72.0);
assert!((mid - 0.029_605).abs() < 1e-5, "{mid}");
assert_eq!(analytic_attenuation(16.0, 16.0, 72.0), 0.0);
assert_eq!(analytic_attenuation(20.0, 16.0, 72.0), 0.0);
assert!((analytic_attenuation(8.0, 16.0, 0.0) - 0.5625).abs() < 1e-6);
assert_eq!(
analytic_attenuation(4.0, 8.0, 72.0),
analytic_attenuation(8.0, 16.0, 72.0)
);
}
#[wasm_bindgen_test(unsupported = test)]
fn analytic_attenuation_rejects_degenerate_params() {
assert_eq!(analytic_attenuation(0.0, 0.0, 72.0), 0.0);
assert_eq!(analytic_attenuation(0.0, -16.0, 72.0), 0.0);
assert_eq!(analytic_attenuation(0.0, f32::NAN, 72.0), 0.0);
assert_eq!(analytic_attenuation(0.0, f32::INFINITY, 72.0), 0.0);
assert_eq!(analytic_attenuation(0.0, 16.0, -1.0), 0.0);
assert_eq!(analytic_attenuation(0.0, 16.0, f32::NAN), 0.0);
assert!(!analytic_params_valid(16.0, f32::INFINITY));
assert!(analytic_params_valid(16.0, 0.0));
}
#[wasm_bindgen_test(unsupported = test)]
fn cookie_half_extent_is_in_camera_units() {
assert_eq!(
cookie_half_extent(Vec2::splat(512.0), 2.0, 1.0),
Vec2::splat(512.0)
);
assert_eq!(
cookie_half_extent(Vec2::splat(512.0), 2.0, 32.0),
Vec2::splat(16.0)
);
}
#[wasm_bindgen_test(unsupported = test)]
fn mask_bits_split_layers() {
assert_eq!(mask_bits(1), [1.0, 0.0, 0.0]);
assert_eq!(mask_bits(2), [0.0, 1.0, 0.0]);
assert_eq!(mask_bits(4), [0.0, 0.0, 1.0]);
assert_eq!(mask_bits(7), [1.0, 1.0, 1.0]);
assert_eq!(mask_bits(8), [0.0, 0.0, 0.0]);
}
#[wasm_bindgen_test(unsupported = test)]
fn mask_matching_is_bit_intersection() {
assert!(mask_matches(1, 1));
assert!(mask_matches(7, 2));
assert!(!mask_matches(1, 2));
assert!(!mask_matches(4, 3));
assert!(!mask_matches(8, 8), "layers above 4 never match");
}
#[wasm_bindgen_test(unsupported = test)]
fn coverage_selects_and_clamps() {
assert_eq!(coverage([1.0, 0.0, 0.0], 2), 0.0);
assert_eq!(coverage([0.0, 0.75, 0.0], 2), 0.75);
assert_eq!(coverage([1.0, 1.0, 1.0], 7), 1.0);
assert_eq!(coverage([0.5, 0.5, 0.0], 3), 1.0);
}
#[wasm_bindgen_test(unsupported = test)]
fn default_light_frame_is_identity() {
let frame = LightFrame::default();
assert_eq!(frame.canvas_modulate, [1.0, 1.0, 1.0, 1.0]);
assert!(frame.lights.is_empty());
assert!(frame.occluders.is_empty());
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod gpu_tests {
use super::*;
use crate::canvas::camera::Camera;
use crate::canvas::sprite::{MASK_FORMAT, NORMAL_FORMAT};
use crate::canvas::test_gpu::{device, read_texture, rgba16f_to_f32};
const SIZE: u32 = 64;
struct Rig {
device: wgpu::Device,
queue: wgpu::Queue,
pass: LightPass,
}
fn rig() -> Option<Rig> {
let (device, queue) = device()?;
Some(rig_on(device, queue))
}
fn rig_on(device: wgpu::Device, queue: wgpu::Queue) -> Rig {
let filled = |label: &str, format: wgpu::TextureFormat, texel: [u8; 4]| {
device
.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: SIZE,
height: SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&texel.repeat((SIZE * SIZE) as usize),
)
.create_view(&wgpu::TextureViewDescriptor::default())
};
let normal = filled("test normal target", NORMAL_FORMAT, [128, 128, 255, 0]);
let mask = filled("test mask target", MASK_FORMAT, [255, 0, 0, 0]);
let pass = LightPass::new(&device, &queue, &normal, &mask, SIZE, SIZE);
Rig {
device,
queue,
pass,
}
}
impl Rig {
fn render(&mut self, frame: &LightFrame) -> Vec<f32> {
let view_proj = Camera::new(SIZE, SIZE).view_proj();
self.pass.prepare(
&self.device,
&self.queue,
view_proj,
WorldUnits::default(),
frame,
(SIZE, SIZE),
);
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
self.pass.run(&mut encoder);
self.queue.submit(Some(encoder.finish()));
let bytes = read_texture(
&self.device,
&self.queue,
self.pass.accum_texture(),
SIZE,
SIZE,
8,
);
rgba16f_to_f32(&bytes)
}
}
fn rgb(px: &[f32], x: u32, y: u32) -> [f32; 3] {
let i = ((y * SIZE + x) * 4) as usize;
[px[i], px[i + 1], px[i + 2]]
}
#[test]
fn shadow_geometry_past_the_device_buffer_limit_is_dropped() {
if device().is_none() {
return;
}
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
.expect("an adapter, as device() found one");
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_limits: wgpu::Limits {
max_buffer_size: 4099 * 8,
..wgpu::Limits::default()
},
..Default::default()
}))
.unwrap();
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
let mut rig = rig_on(device, queue);
let right_wall = vec![Vec2::new(20.5, 31.0), Vec2::new(20.5, 34.0)];
let upper_wall = vec![Vec2::new(9.0, 20.5), Vec2::new(12.0, 20.5)];
let mut occluders = vec![right_wall; 400];
occluders.push(upper_wall.clone());
let mut frame = LightFrame {
lights: vec![PointLight {
shadows: true,
..PointLight::analytic(Vec2::new(10.5, 32.5), 100.0, 0.0)
}],
occluders,
..LightFrame::default()
};
let pixels = rig.render(&frame);
assert!(
rgb(&pixels, 40, 32)[0] < 1e-3,
"retained right wall lost its shadow"
);
assert!(
rgb(&pixels, 10, 10)[0] > 0.5,
"surplus upper wall cast a shadow"
);
frame.occluders = vec![upper_wall];
let pixels = rig.render(&frame);
assert!(
rgb(&pixels, 10, 10)[0] < 1e-3,
"upper wall should fit the next frame"
);
assert!(
rgb(&pixels, 40, 32)[0] > 0.5,
"old right wall survived prepare"
);
rig.device
.poll(wgpu::PollType::wait_indefinitely())
.unwrap();
if let Some(error) = pollster::block_on(validation.pop()) {
panic!("{error}");
}
}
#[test]
fn a_light_close_to_a_long_wall_is_blocked_behind_it() {
let Some(mut rig) = rig() else { return };
let frame = LightFrame {
lights: vec![PointLight {
shadows: true,
..PointLight::analytic(Vec2::new(32.5, 20.5), 40.0, 0.0)
}],
occluders: vec![vec![
Vec2::new(-1000.0, 22.5),
Vec2::new(1000.0, 22.5),
Vec2::new(1000.0, 24.5),
Vec2::new(-1000.0, 24.5),
]],
..LightFrame::default()
};
let px = rig.render(&frame);
assert_eq!(rgb(&px, 32, 44), [0.0; 3], "behind the wall");
assert!(rgb(&px, 8, 20)[0] > 0.3, "the light's side is lit");
}
#[test]
fn analytic_light_accumulates_the_falloff_curve() {
let Some(mut rig) = rig() else { return };
let frame = LightFrame {
lights: vec![PointLight {
color: [1.0, 0.5, 0.0],
energy: 0.75,
..PointLight::analytic(Vec2::new(32.5, 32.5), 16.0, 72.0)
}],
..LightFrame::default()
};
let px = rig.render(&frame);
let close = |got: [f32; 3], want: [f32; 3], tol: f32| {
got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol)
};
let center = rgb(&px, 32, 32);
assert!(close(center, [0.75, 0.375, 0.0], 2e-3), "center {center:?}");
let mid = rgb(&px, 40, 32);
let want = 0.029_605 * 0.75;
assert!(close(mid, [want, want * 0.5, 0.0], 3e-4), "s=0.5 {mid:?}");
let far = rgb(&px, 32, 44);
let want = 0.004_612_2 * 0.75;
assert!(close(far, [want, want * 0.5, 0.0], 1e-4), "s=0.75 {far:?}");
assert_eq!(rgb(&px, 46, 46), [0.0; 3], "quad corner past the radius");
assert_eq!(rgb(&px, 32, 52), [0.0; 3], "outside the footprint");
}
#[test]
fn cookie_light_samples_the_cookie_everywhere_in_its_footprint() {
let Some(mut rig) = rig() else { return };
let mut assets = crate::assets::Assets::<Texture>::new();
let handle = assets.insert(
"cookie.png".into(),
Texture {
width: 1,
height: 1,
rgba: vec![255, 255, 255, 128],
},
);
let empty = Texture {
width: 0,
height: 1,
rgba: Vec::new(),
};
assert_eq!(
rig.pass
.upload_cookie(&rig.device, &rig.queue, handle, &empty),
Err(TextureError::Empty {
width: 0,
height: 1
})
);
let tex = assets.get(handle).expect("just inserted");
rig.pass
.upload_cookie(&rig.device, &rig.queue, handle, tex)
.unwrap();
let frame = LightFrame {
lights: vec![PointLight {
texture_scale: 32.0,
energy: 0.5,
..PointLight::new(handle, Vec2::new(32.5, 32.5))
}],
..LightFrame::default()
};
let px = rig.render(&frame);
let want = 128.0 / 255.0 * 0.5;
for (x, y) in [(32, 32), (40, 32), (46, 46), (17, 17)] {
let got = rgb(&px, x, y);
assert!(
got.iter().all(|c| (c - want).abs() < 2e-3),
"({x}, {y}) = {got:?}, want {want}"
);
}
assert_eq!(rgb(&px, 32, 52), [0.0; 3], "outside the footprint");
}
#[test]
fn invalid_lights_are_skipped_without_panicking() {
let Some(mut rig) = rig() else { return };
let center = Vec2::new(32.5, 32.5);
let frame = LightFrame {
lights: vec![
PointLight::analytic(center, 0.0, 72.0),
PointLight::analytic(center, -16.0, 72.0),
PointLight::analytic(center, f32::NAN, 72.0),
PointLight::analytic(center, f32::INFINITY, 72.0),
PointLight::analytic(center, 16.0, -1.0),
PointLight::analytic(center, 16.0, f32::NAN),
],
..LightFrame::default()
};
let px = rig.render(&frame);
assert!(rig.pass.plan.is_empty());
assert!(px.chunks_exact(4).all(|p| p[..3] == [0.0; 3]));
}
}