1pub(crate) mod atlas;
35mod cache;
36mod plan;
37mod shape;
38
39use crate::Scene;
40use crate::shading::lights::LocalShadowRecord;
41use crate::timing::GpuTiming;
42use crate::view::bindings::FrameBindings;
43use crate::view::draw_list::DrawInstances;
44use crate::view::frame::FrameContext;
45use crate::view::pipelines::{GeometryPass, GeometryPipelines};
46use glam::{Mat4, Vec3};
47pub(crate) use plan::ShadowFrame;
48use plan::{Face, Work};
49use std::sync::OnceLock;
50
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54pub struct LocalShadowStats {
55 pub shadowed: usize,
57 pub unshadowed: usize,
60 pub layers_drawn: usize,
62 pub faces_drawn: usize,
64 pub draws: usize,
66}
67
68struct FaceView {
71 buffer: wgpu::Buffer,
72 group: wgpu::BindGroup,
73}
74
75pub(crate) struct CaptureShadows {
80 pub records: wgpu::Buffer,
81 groups: Vec<wgpu::BindGroup>,
82}
83
84pub(crate) struct Local {
85 frame: Atlas,
87 layers: Atlas,
89 pub records: wgpu::Buffer,
91 written: Vec<LocalShadowRecord>,
93 face_shader: OnceLock<wgpu::ShaderModule>,
94 clear: OnceLock<wgpu::RenderPipeline>,
95 copy: OnceLock<wgpu::RenderPipeline>,
96 copy_layout: wgpu::BindGroupLayout,
97 copy_group: wgpu::BindGroup,
98 plan: plan::Plan,
99 views: Vec<FaceView>,
101}
102
103struct Atlas {
107 target: wgpu::TextureView,
108 sampled: wgpu::TextureView,
109}
110
111impl Atlas {
112 fn new(device: &wgpu::Device, label: &str, size: u32) -> Self {
114 let texture = device.create_texture(&wgpu::TextureDescriptor {
115 label: Some(label),
116 size: wgpu::Extent3d {
117 width: size,
118 height: size,
119 depth_or_array_layers: 1,
120 },
121 mip_level_count: 1,
122 sample_count: 1,
123 dimension: wgpu::TextureDimension::D2,
124 format: crate::shading::gbuffer::DEPTH,
125 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
126 view_formats: &[],
127 });
128 Self {
129 target: texture.create_view(&wgpu::TextureViewDescriptor {
130 dimension: Some(wgpu::TextureViewDimension::D2),
131 ..Default::default()
132 }),
133 sampled: texture.create_view(&wgpu::TextureViewDescriptor {
134 dimension: Some(wgpu::TextureViewDimension::D2Array),
135 ..Default::default()
136 }),
137 }
138 }
139}
140
141pub(crate) static COPY: crate::shading::Module = crate::shading::Module {
144 name: "local_shadow_copy",
145 source: include_str!("local/copy.wgsl"),
146 deps: &[&crate::shading::FULLSCREEN_VS],
147};
148pub(crate) const COPY_FS_ENTRY: &str = "copy_fs";
151
152fn records_buffer(device: &wgpu::Device, count: usize) -> wgpu::Buffer {
153 crate::counters::buffer(
154 device,
155 &wgpu::BufferDescriptor {
156 label: Some("local light shadow records"),
157 size: (count.max(1) * std::mem::size_of::<LocalShadowRecord>()) as u64,
158 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
159 mapped_at_creation: false,
160 },
161 )
162}
163
164fn face_pipeline(
167 device: &wgpu::Device,
168 label: &str,
169 module: &wgpu::ShaderModule,
170 groups: &[Option<&wgpu::BindGroupLayout>],
171 fragment: Option<&str>,
172) -> wgpu::RenderPipeline {
173 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
174 label: Some(label),
175 bind_group_layouts: groups,
176 immediate_size: 0,
177 });
178 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
179 label: Some(label),
180 layout: Some(&layout),
181 vertex: wgpu::VertexState {
182 module,
183 entry_point: Some(crate::shading::FULLSCREEN_VS_ENTRY),
184 compilation_options: Default::default(),
185 buffers: &[],
186 },
187 fragment: fragment.map(|entry_point| wgpu::FragmentState {
188 module,
189 entry_point: Some(entry_point),
190 compilation_options: Default::default(),
191 targets: &[],
192 }),
193 primitive: Default::default(),
194 depth_stencil: Some(wgpu::DepthStencilState {
195 format: crate::shading::gbuffer::DEPTH,
196 depth_write_enabled: Some(true),
197 depth_compare: Some(wgpu::CompareFunction::Always),
198 stencil: Default::default(),
199 bias: Default::default(),
200 }),
201 multisample: Default::default(),
202 multiview_mask: None,
203 cache: None,
204 })
205}
206
207fn copy_group(
209 device: &wgpu::Device,
210 layout: &wgpu::BindGroupLayout,
211 layers: &Atlas,
212) -> wgpu::BindGroup {
213 device.create_bind_group(&wgpu::BindGroupDescriptor {
214 label: Some("local light shadow static layers"),
215 layout,
216 entries: &[wgpu::BindGroupEntry {
217 binding: 0,
218 resource: wgpu::BindingResource::TextureView(&layers.target),
219 }],
220 })
221}
222
223impl Local {
224 pub fn new(device: &wgpu::Device, size: u32) -> Self {
226 let layers = Atlas::new(device, "local light shadow static layers", size);
227 let copy_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
228 label: Some("local light shadow static layers"),
229 entries: &[wgpu::BindGroupLayoutEntry {
230 binding: 0,
231 visibility: wgpu::ShaderStages::FRAGMENT,
232 ty: wgpu::BindingType::Texture {
233 sample_type: wgpu::TextureSampleType::Depth,
234 view_dimension: wgpu::TextureViewDimension::D2,
235 multisampled: false,
236 },
237 count: None,
238 }],
239 });
240 Self {
241 frame: Atlas::new(device, "local light shadow atlas", size),
242 copy_group: copy_group(device, ©_layout, &layers),
243 layers,
244 records: records_buffer(device, 1),
245 written: vec![LocalShadowRecord::NONE],
246 face_shader: OnceLock::new(),
247 clear: OnceLock::new(),
248 copy: OnceLock::new(),
249 copy_layout,
250 plan: plan::Plan::new(size),
251 views: Vec::new(),
252 }
253 }
254
255 fn face_shader(&self, device: &wgpu::Device) -> &wgpu::ShaderModule {
256 self.face_shader.get_or_init(|| {
257 device.create_shader_module(wgpu::ShaderModuleDescriptor {
258 label: Some("local light shadow copy"),
259 source: wgpu::ShaderSource::Wgsl(crate::shading::compose(&[©]).into()),
260 })
261 })
262 }
263
264 fn clear_pipeline(&self, device: &wgpu::Device) -> &wgpu::RenderPipeline {
265 self.clear.get_or_init(|| {
266 face_pipeline(
267 device,
268 "local light shadow face clear",
269 self.face_shader(device),
270 &[],
271 None,
272 )
273 })
274 }
275
276 fn copy_pipeline(&self, device: &wgpu::Device) -> &wgpu::RenderPipeline {
277 self.copy.get_or_init(|| {
278 face_pipeline(
279 device,
280 "local light shadow layer copy",
281 self.face_shader(device),
282 &[Some(&self.copy_layout)],
283 Some(COPY_FS_ENTRY),
284 )
285 })
286 }
287
288 pub fn resize(&mut self, device: &wgpu::Device, size: u32) {
292 if self.frame.target.texture().width() == size {
293 return;
294 }
295 self.frame = Atlas::new(device, "local light shadow atlas", size);
296 self.layers = Atlas::new(device, "local light shadow static layers", size);
297 self.copy_group = copy_group(device, &self.copy_layout, &self.layers);
298 self.plan = plan::Plan::new(size);
299 }
300
301 pub fn atlas(&self) -> &wgpu::TextureView {
303 &self.frame.sampled
304 }
305
306 pub fn layers(&self) -> &wgpu::TextureView {
308 &self.layers.sampled
309 }
310
311 pub fn stats(&self) -> LocalShadowStats {
313 self.plan.stats
314 }
315
316 pub fn ranking(&self) -> &[crate::content::identity::LightId] {
320 self.plan.ranking()
321 }
322
323 #[allow(clippy::too_many_arguments)]
328 pub fn prepare(
329 &mut self,
330 device: &wgpu::Device,
331 queue: &wgpu::Queue,
332 bindings: &FrameBindings,
333 (scene, drawn): (&Scene, &mut DrawInstances),
334 camera: (Mat4, Mat4),
335 frame: ShadowFrame,
336 enabled: bool,
337 ) {
338 self.plan.prepare(drawn, scene, camera, frame, enabled);
339 self.upload_views(device, queue, bindings);
340 let records = self.plan.records();
341 if self.written.len() < records.len() {
342 self.records = records_buffer(device, records.len());
344 self.written = vec![LocalShadowRecord::NONE; records.len()];
345 }
346 write_changed(queue, &self.records, &mut self.written, records);
347 }
348
349 #[allow(clippy::too_many_arguments)]
357 pub fn plan_capture(
358 &mut self,
359 device: &wgpu::Device,
360 queue: &wgpu::Queue,
361 bindings: &FrameBindings,
362 (scene, drawn): (&Scene, &mut DrawInstances),
363 (center, uniform): (Vec3, &wgpu::Buffer),
364 frame: ShadowFrame,
365 enabled: bool,
366 ) -> CaptureShadows {
367 self.plan
368 .prepare_capture(drawn, scene, center, frame, enabled);
369 self.upload_views(device, queue, bindings);
370 let faces = self.plan.faces().len();
371 CaptureShadows {
372 records: crate::scene::buffer(
373 device,
374 "probe capture local light shadow records",
375 bytemuck::cast_slice(self.plan.records()),
376 wgpu::BufferUsages::STORAGE,
377 ),
378 groups: self.views[..faces]
379 .iter()
380 .map(|view| bindings.shadow_group(device, &view.buffer, uniform))
381 .collect(),
382 }
383 }
384
385 pub fn encode_capture(
388 &self,
389 device: &wgpu::Device,
390 encoder: &mut wgpu::CommandEncoder,
391 capture: &CaptureShadows,
392 (scene, pipelines): (&Scene, &mut GeometryPipelines),
393 drawn: &DrawInstances,
394 ) {
395 self.encode_layers(
396 device,
397 encoder,
398 None,
399 |index| &capture.groups[index],
400 (scene, pipelines, drawn),
401 );
402 }
403
404 pub fn finish_capture(&mut self) {
406 self.plan.finish();
407 }
408
409 fn upload_views(
411 &mut self,
412 device: &wgpu::Device,
413 queue: &wgpu::Queue,
414 bindings: &FrameBindings,
415 ) {
416 for (index, face) in self.plan.faces().iter().enumerate() {
417 let uniform = bytemuck::bytes_of(&face.view.uniform);
418 if let Some(view) = self.views.get(index) {
419 crate::counters::write_buffer(queue, &view.buffer, 0, uniform);
420 } else {
421 let buffer = crate::scene::buffer(
422 device,
423 "local light shadow face",
424 uniform,
425 wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
426 );
427 let group = bindings.shadow_group(device, &buffer, &bindings.frame);
428 self.views.push(FaceView { buffer, group });
429 }
430 }
431 }
432
433 pub fn encode(&mut self, ctx: &mut FrameContext<'_>) {
436 let (scene, pipelines, drawn) = (ctx.scene, &mut *ctx.pipelines, &ctx.views.instances);
437 let mut draws = self.encode_layers(
438 ctx.device,
439 ctx.encoder,
440 ctx.timing,
441 |index| &self.views[index].group,
442 (scene, pipelines, drawn),
443 );
444 let faces = self.plan.faces();
445 if !faces.is_empty() {
446 let mut pass = begin(ctx.encoder, ctx.timing, &self.frame.target, "local shadows");
447 for (index, face) in faces.iter().enumerate() {
448 limit(&mut pass, face);
449 let casters = if face.work == Work::Full {
450 pass.set_pipeline(self.clear_pipeline(ctx.device));
451 &face.casters
452 } else {
453 pass.set_pipeline(self.copy_pipeline(ctx.device));
454 pass.set_bind_group(0, &self.copy_group, &[]);
455 &face.moving
456 };
457 pass.draw(0..3, 0..1);
458 pass.set_bind_group(0, &self.views[index].group, &[]);
459 draws += 1 + casters.draw(
460 scene,
461 pipelines,
462 drawn,
463 &mut pass,
464 GeometryPass::LocalShadow,
465 );
466 }
467 }
468 self.plan.stats.draws = draws;
469 }
470
471 fn encode_layers<'a>(
475 &self,
476 device: &wgpu::Device,
477 encoder: &mut wgpu::CommandEncoder,
478 timing: Option<&GpuTiming>,
479 group: impl Fn(usize) -> &'a wgpu::BindGroup,
480 (scene, pipelines, drawn): (&Scene, &mut GeometryPipelines, &DrawInstances),
481 ) -> usize {
482 let mut layers = self
483 .plan
484 .faces()
485 .iter()
486 .enumerate()
487 .filter(|(_, face)| face.work == Work::Layer)
488 .peekable();
489 if layers.peek().is_none() {
490 return 0;
491 }
492 let mut draws = 0;
493 let mut pass = begin(encoder, timing, &self.layers.target, "local shadow layers");
494 for (index, face) in layers {
495 limit(&mut pass, face);
496 pass.set_pipeline(self.clear_pipeline(device));
497 pass.draw(0..3, 0..1);
498 pass.set_bind_group(0, group(index), &[]);
499 draws += 1 + face.casters.draw(
500 scene,
501 pipelines,
502 drawn,
503 &mut pass,
504 GeometryPass::LocalShadow,
505 );
506 }
507 draws
508 }
509
510 pub fn finish_frame(&mut self) {
512 self.plan.finish();
513 }
514}
515
516fn write_changed(
519 queue: &wgpu::Queue,
520 buffer: &wgpu::Buffer,
521 written: &mut [LocalShadowRecord],
522 records: &[LocalShadowRecord],
523) {
524 let changed = |written: &[LocalShadowRecord], index: usize| {
525 bytemuck::bytes_of(&records[index]) != bytemuck::bytes_of(&written[index])
526 };
527 let mut index = 0;
528 while index < records.len() {
529 if !changed(written, index) {
530 index += 1;
531 continue;
532 }
533 let start = index;
534 while index < records.len() && changed(written, index) {
535 index += 1;
536 }
537 written[start..index].copy_from_slice(&records[start..index]);
538 crate::counters::write_buffer(
539 queue,
540 buffer,
541 (start * std::mem::size_of::<LocalShadowRecord>()) as u64,
542 bytemuck::cast_slice(&records[start..index]),
543 );
544 }
545}
546
547fn begin<'a>(
549 encoder: &'a mut wgpu::CommandEncoder,
550 timing: Option<&GpuTiming>,
551 target: &wgpu::TextureView,
552 label: &'static str,
553) -> wgpu::RenderPass<'a> {
554 encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
555 label: Some(label),
556 color_attachments: &[],
557 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
558 view: target,
559 depth_ops: Some(wgpu::Operations {
560 load: wgpu::LoadOp::Load,
561 store: wgpu::StoreOp::Store,
562 }),
563 stencil_ops: None,
564 }),
565 timestamp_writes: timing.and_then(|timing| timing.render_pass(label)),
566 ..Default::default()
567 })
568}
569
570fn limit(pass: &mut wgpu::RenderPass<'_>, face: &Face) {
572 let [x, y] = face.origin;
573 let size = face.size as f32;
574 pass.set_viewport(x as f32, y as f32, size, size, 0., 1.);
575 pass.set_scissor_rect(x, y, face.size, face.size);
576}
577
578#[cfg(all(test, not(target_arch = "wasm32")))]
579mod tests;