diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 4f891c649..9b8fbb756 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -471,6 +471,8 @@ pub struct Renderer { /// Per-frame scratch, kept to avoid allocating every frame. visible: Vec, visible_lods: Vec, + /// The sections a shader pack's shadow camera sees (`pack_post::ShadowView`). + shadow_visible: Vec, translucent_draws: Vec<(u64, usize, [u32; 5], (u32, Option))>, origins: Vec<[f32; 4]>, /// `DrawIndexedIndirectArgs` words: index count, instance count, first @@ -485,6 +487,8 @@ pub struct Renderer { /// Each section's solid draws, to group them by arena page. solid_runs: page_runs::PageRuns, phase2_runs: page_runs::PageRuns, + /// The shadow camera's draws by page, in bands of distance from the light. + shadow_runs: page_runs::PageRuns, /// Block-entity blocks per meshed section (world position, state id). block_entities: HashMap>, /// Changes whenever `block_entities` does (unique across renderers). @@ -2390,6 +2394,7 @@ impl Renderer { multi_draw, visible: Vec::new(), visible_lods: Vec::new(), + shadow_visible: Vec::new(), translucent_draws: Vec::new(), origins: Vec::new(), draws: Vec::new(), @@ -2398,6 +2403,7 @@ impl Renderer { phase2_pages: Vec::new(), solid_runs: page_runs::PageRuns::default(), phase2_runs: page_runs::PageRuns::default(), + shadow_runs: page_runs::PageRuns::default(), block_entities: HashMap::new(), block_entity_revision: next_block_entity_revision(), occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), @@ -3314,8 +3320,43 @@ impl Renderer { ); visible_lods.sort_unstable_by_key(|v| (v.distance, v.key)); } + // A shader pack's shadow pass draws the sections in its camera's box, all of them (the + // occlusion graph follows the eye, not the light), within shadowDistanceRenderMul. + let shadow_view = self + .pack_post + .as_ref() + .and_then(|p| p.1.as_ref()) + .filter(|_| !frame.title) + .and_then(|p| p.shadow_view(frame)); + let mut shadow_visible = std::mem::take(&mut self.shadow_visible); + shadow_visible.clear(); + if let Some(v) = &shadow_view { + let radius = (frame.detail_distance / 16.0) as i32; + let radius = v + .distance + .map_or(radius, |d| radius.min((d / 16.0).ceil() as i32)); + let light = Frustum { + planes: frustum(v.cull), + }; + crate::spans::time("shadow visibility", || { + self.sections.visible( + camera, + radius, + &light, + |_| true, + |_, _| false, + &mut shadow_visible, + ) + }); + // Nearest the light first, so the depth test rejects what lies under it. + let light = v.light; + shadow_visible.sort_unstable_by(|a, b| { + let height = |s: &resident::Visible| glam::Vec3::from(s.origin).dot(light); + height(b).total_cmp(&height(a)) + }); + } self.drawn_sections = visible.len() + visible_lods.len(); - let instances = self.drawn_sections; + let instances = self.drawn_sections + shadow_visible.len(); if instances as u64 > self.instance_capacity { self.instance_capacity = (instances as u64).next_power_of_two(); self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { @@ -3332,7 +3373,8 @@ impl Renderer { visible .iter() .map(|v| section_instance(v.origin)) - .chain(visible_lods.iter().map(|v| lod::instance(v.origin))), + .chain(visible_lods.iter().map(|v| lod::instance(v.origin))) + .chain(shadow_visible.iter().map(|v| section_instance(v.origin))), ); if !self.origins.is_empty() { self.uploads.buffer( @@ -3536,9 +3578,87 @@ impl Renderer { self.translucency_cursor += budget; let translucent_draws = self.draws.len() as u32 - solid_draws; self.section_draws = self.draws.len(); + // The shadow camera's sections after the camera's: quads that can face the light, then + // translucent ones (in their last sorted order; depth decides there). + let shadow_first = self.draws.len() as u32; + let mut shadow_translucent = Vec::new(); + self.shadow_runs.clear(); + if let Some(view) = &shadow_view { + let base = self.drawn_sections; + let toward = view.light * 1.0e5; + // How far below the nearest section to the light (squared, as bits, as `PageRuns` + // takes distances): each band's draws go by page, a call per page and band. + let height = |v: &resident::Visible| glam::Vec3::from(v.origin).dot(view.light); + let top = shadow_visible.first().map_or(0.0, height); + for (k, v) in shadow_visible.iter().enumerate() { + let s = self.sections.get_mut(v.slot); + let instance = (base + k) as u32; + let depth = f64::from(top - height(v)).max(0.0); + let distance = (depth * depth).to_bits(); + // A section the camera never saw has no sorted indices yet: sorted once now. + if let Some((index_page, index_start)) = s.sorted_indices + && !s.sort.is_sorted() + { + let origin = [ + v.key.0 * 16, + crate::chunk::MIN_Y + v.key.1 * 16, + v.key.2 * 16, + ]; + if let Some(indices) = + s.sort + .update(camera.to_array(), origin, &mut self.translucent_sorter) + { + self.uploads.buffer( + &mut encoder, + self.sorted_indices.buffer(index_page), + index_start * 4, + bytemuck::cast_slice(indices), + ); + } + } + let before = self.draws.len(); + facing_runs(&s.sides, Some(toward), v.origin, |first, quads| { + let start = s.start as u32 + first * 4; + self.draws.push([quads * 6, 1, 0, start, instance]); + self.draw_pages.push((s.page, None)); + }); + let len = self.draws.len() - before; + self.shadow_runs.push(distance, s.page, before, len, [0; 3]); + if let Some((index_page, index_start)) = s.sorted_indices { + let start = s.start + u64::from(s.solid) * 4; + shadow_translucent.push(( + distance, + [ + s.translucent * 6, + 1, + index_start as u32, + start as u32, + instance, + ], + (s.page, Some(index_page)), + )); + } + } + } + let shadow_solid = self.draws.len() as u32 - shadow_first; + self.shadow_runs + .regroup(&mut self.draws, &mut self.draw_pages, shadow_first as usize); + self.shadow_runs.clear(); + for (distance, draw, pages) in shadow_translucent { + self.shadow_runs + .push(distance, pages.0, self.draws.len(), 1, [0; 3]); + self.draws.push(draw); + self.draw_pages.push(pages); + } + self.shadow_runs.regroup( + &mut self.draws, + &mut self.draw_pages, + (shadow_first + shadow_solid) as usize, + ); + let shadow_translucent = self.draws.len() as u32 - shadow_first - shadow_solid; // Metal replays a multi-draw as one draw call per entry. self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal { - (0..self.draws.len()) + (0..self.section_draws) .filter(|&i| { i == 0 || i == phase1_draws as usize @@ -3547,7 +3667,7 @@ impl Renderer { }) .count() } else { - self.draws.len() + self.section_draws }; let debug_depth = frame.debug_lines.len() as u32; let debug_top = frame.debug_lines_on_top.len() as u32; @@ -3784,7 +3904,9 @@ impl Renderer { Some(flat) if self.flat_on && !self.draws.is_empty() - && (self.drawn_sections >= flat.min_sections || pack_terrain) => + && (self.drawn_sections >= flat.min_sections + || pack_terrain + || shadow_view.is_some()) => { let sections = &self.sections; let lods = &self.lods; @@ -3799,9 +3921,11 @@ impl Renderer { &self.draw_pages, phase1_draws as usize, solid_draws as usize, + [shadow_first, shadow_first + shadow_solid].map(|d| d as usize), phase2, visible .iter() + .chain(&shadow_visible) .filter_map(|v| { let id = sections.get(v.slot).flat_id?; Some((id, section_instance(v.origin))) @@ -3817,7 +3941,7 @@ impl Renderer { _ => false, }; if flat_frame { - self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len()); + self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.shadow_calls[0]); } else if self.multi_draw && !self.draws.is_empty() { if self.draws.len() as u64 > self.indirect_capacity { self.indirect_capacity = (self.draws.len() as u64).next_power_of_two(); @@ -3846,6 +3970,8 @@ impl Renderer { let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some()); // The pack's program reads the vertices this frame's draws bind. let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat; + // The shadow camera's lists, drawn by the pack's shadow programs. + let pack_draws_shadow = shadow_view.is_some() && flat_frame == self.pack_terrain_flat; let pack_draws_sky = pack_post && self .pack_post @@ -4115,7 +4241,7 @@ impl Renderer { _ if pack_draws_water => {} Some(flat) => { pass.set_pipeline(&flat.translucent); - flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| { + flat.draw(&mut pass, flat.translucent_calls(), |p| { self.arena.buffer(p) }); pass.set_bind_group(0, &self.group, &[]); @@ -4222,7 +4348,7 @@ impl Renderer { post.set_weather(weather); let flat = self.flat.as_ref().filter(|_| flat_frame); let pages: Vec<(u32, wgpu::Buffer)> = match flat { - Some(_) if pack_draws_terrain => self + Some(_) if pack_draws_terrain || pack_draws_shadow => self .arena .page_buffers() .map(|(p, b)| (p, b.clone())) @@ -4231,27 +4357,38 @@ impl Renderer { }; let mut terrain = |rp: &mut wgpu::RenderPass<'_>, - translucent: bool, + list: pack_post::TerrainList, page: &dyn Fn(&mut wgpu::RenderPass<'_>, u32)| { - if !pack_draws_terrain { + use pack_post::TerrainList as L; + let shadow = matches!(list, L::ShadowSolid | L::ShadowTranslucent); + if !(if shadow { + pack_draws_shadow + } else { + pack_draws_terrain + }) { return; } match flat { Some(flat) => { - let calls = if translucent { - &flat.calls[flat.solid_calls..] - } else { - &flat.calls[..flat.solid_calls] + let [shadow, shadow_translucent] = flat.shadow_calls; + let calls = match list { + L::Solid => &flat.calls[..flat.solid_calls], + L::Translucent => flat.translucent_calls(), + L::ShadowSolid => &flat.calls[shadow..shadow_translucent], + L::ShadowTranslucent => &flat.calls[shadow_translucent..], }; flat.draw_with(rp, calls, |p| self.arena.buffer(p), page); } None => { rp.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); rp.set_vertex_buffer(1, self.instances.slice(..)); - let (first, count) = if translucent { - (solid_draws, translucent_draws) - } else { - (0, solid_draws) + let (first, count) = match list { + L::Solid => (0, solid_draws), + L::Translucent => (solid_draws, translucent_draws), + L::ShadowSolid => (shadow_first, shadow_solid), + L::ShadowTranslucent => { + (shadow_first + shadow_solid, shadow_translucent) + } }; self.draw_sections(rp, &self.indirect, 0, first, count); } @@ -4486,6 +4623,7 @@ impl Renderer { let _ = self.started; self.visible = visible; self.visible_lods = visible_lods; + self.shadow_visible = shadow_visible; Ok(true) } } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index 6b71a16f7..5d86888da 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -40,6 +40,8 @@ enum Source { struct Plan { phase1_calls: usize, solid_calls: usize, + /// Where the shadow camera's solid and translucent calls begin. + shadow_calls: [usize; 2], total: u64, } const QUADS: u32 = u32::MAX; @@ -97,6 +99,10 @@ pub struct Flat { pub calls: Vec, pub phase1_calls: usize, pub solid_calls: usize, + /// Where a shader pack's shadow camera's solid and translucent calls + /// begin (`calls.len()` without them): the camera's translucent calls + /// end at the first. + pub shadow_calls: [usize; 2], /// Frames with fewer sections in view keep the per-section draws. pub min_sections: usize, range_align: u64, @@ -164,12 +170,16 @@ fn buffer( /// draw calls, one per run of draws in the same vertex page, phase 1's solid /// ones, phase 2's (draws `phase1_draws..solid_draws`) and translucent ones /// apart. A phase 2 range names its draw in phase 2 and its call in phase 2 -/// instead of a destination: the call's room holds all of its draws. +/// instead of a destination: the call's room holds all of its draws. Draws +/// from `shadow[0]` (solid) and `shadow[1]` (translucent) on are a shader +/// pack's shadow camera's, with calls of their own. +#[allow(clippy::too_many_arguments)] fn plan( draws: &[[u32; 5]], pages: &[(u32, Option)], phase1_draws: usize, solid_draws: usize, + shadow: [usize; 2], align: u64, calls: &mut Vec, ranges: &mut Vec, @@ -179,6 +189,7 @@ fn plan( ranges.clear(); segments.clear(); let (mut phase1_calls, mut solid_calls) = (None, None); + let mut shadow_calls = [None; 2]; let mut total = 0u64; let mut by_source: Vec<(Source, Vec)> = Vec::new(); for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() { @@ -188,10 +199,14 @@ fn plan( if i == solid_draws { solid_calls = Some(calls.len()); } - match calls.last_mut() { - Some(last) if last.page == page && i != phase1_draws && i != solid_draws => { - last.count += d[0] + for (k, &from) in shadow.iter().enumerate() { + if i == from { + shadow_calls[k].get_or_insert(calls.len()); } + } + let starts = i == phase1_draws || i == solid_draws || shadow.contains(&i); + match calls.last_mut() { + Some(last) if last.page == page && !starts => last.count += d[0], _ => calls.push(Call { page, first: total as u32, @@ -227,6 +242,7 @@ fn plan( Plan { phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls), solid_calls, + shadow_calls: shadow_calls.map(|c| c.unwrap_or(calls.len())), total, } } @@ -340,6 +356,7 @@ impl Flat { calls: Vec::new(), phase1_calls: 0, solid_calls: 0, + shadow_calls: [0; 2], min_sections: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") { 0 } else { @@ -412,6 +429,7 @@ impl Flat { /// /// When culling, the solid draws from `phase1_draws` are phase 2's, which /// `phase2` holds as the test leaves them: `flatten_phase2` copies them. + /// Draws from `shadow` on are a shader pack's shadow camera's (`plan`). #[allow(clippy::too_many_arguments)] pub fn prepare( &mut self, @@ -422,6 +440,7 @@ impl Flat { pages: &[(u32, Option)], phase1_draws: usize, solid_draws: usize, + shadow: [usize; 2], phase2: Option<&wgpu::Buffer>, origins: impl Iterator, sorted_page: impl Fn(u32) -> wgpu::Buffer, @@ -464,12 +483,14 @@ impl Flat { let Plan { phase1_calls, solid_calls, + shadow_calls, total, } = plan( draws, pages, phase1_draws, solid_draws, + shadow, self.range_align, &mut self.calls, &mut self.range_data, @@ -477,10 +498,12 @@ impl Flat { ); self.phase1_calls = phase1_calls; self.solid_calls = solid_calls; + self.shadow_calls = shadow_calls; if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size { self.calls.clear(); self.phase1_calls = 0; self.solid_calls = 0; + self.shadow_calls = [0; 2]; return false; } if self.range_data.len() as u64 > self.range_capacity { @@ -644,6 +667,11 @@ impl Flat { pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1); } + /// The camera's translucent calls. + pub fn translucent_calls(&self) -> &[Call] { + &self.calls[self.solid_calls..self.shadow_calls[0]] + } + /// Draws `calls` with a flat pipeline set and `vertices` giving each /// page's vertex buffer. pub fn draw<'a>( @@ -735,11 +763,13 @@ mod tests { phase1_calls, solid_calls, total, + .. } = plan( &draws, &pages, solid, solid, + [draws.len(); 2], 4, &mut calls, &mut ranges, @@ -774,6 +804,35 @@ mod tests { assert_eq!(ranges.len(), 12); } + /// A shader pack's shadow draws follow the camera's, in calls of their + /// own even from the same page: solid ones, then translucent ones. + #[test] + fn plan_gives_the_shadow_lists_calls_of_their_own() { + let (mut draws, mut pages, solid) = sample(); + let camera = draws.len(); + draws.extend([[6, 1, 0, 40, 6], [6 * 2, 1, 0, 64, 7], [6, 1, 6, 80, 7]]); + pages.extend([(0, None), (0, None), (0, Some(0))]); + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let plan = plan( + &draws, + &pages, + solid, + solid, + [camera, camera + 2], + 4, + &mut calls, + &mut ranges, + &mut segments, + ); + assert_eq!((plan.solid_calls, plan.shadow_calls), (3, [4, 5])); + let call = |page, first, count| Call { page, first, count }; + assert_eq!( + &calls[3..], + [call(0, 60, 18), call(0, 78, 18), call(0, 96, 6)] + ); + assert_eq!(plan.total, 6 * 17); + } + /// Phase 2's draws (here the third and fourth) get calls of their own, /// each with room for all of its draws, and ranges naming their draw /// and call in phase 2. @@ -786,6 +845,7 @@ mod tests { &pages, 2, solid, + [draws.len(); 2], 4, &mut calls, &mut ranges, @@ -796,6 +856,7 @@ mod tests { Plan { phase1_calls: 1, solid_calls: 3, + shadow_calls: [4, 4], total: 6 * 13 } ); @@ -899,6 +960,7 @@ mod tests { &pages, phase1, solid, + [draws.len(); 2], align, &mut calls, &mut ranges, diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index fdc4563ef..57ce0b147 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -270,6 +270,9 @@ pub struct PackPost { depth1: bool, /// The shadow buffers, when the shadow pass runs (2.5), and the `shadowcomp` programs. shadow_targets: Option, + /// What draws terrain from the light (`shadow`), and translucent terrain (`shadow_water`). + shadow_terrain: Option, + shadow_water: Option, shadow_comp: Vec, /// Buffers with mipmaps (filterable ones a program asks them for). mipped: u16, @@ -598,10 +601,35 @@ fn attach( }) } -/// Draws the game's terrain (`true`: translucent) into a pass; calls its third argument with -/// each arena page before drawing from it. +/// Which of the frame's terrain draws: the camera's solid or translucent ones, or the shadow +/// camera's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum TerrainList { + Solid, + Translucent, + ShadowSolid, + ShadowTranslucent, +} + +impl TerrainList { + fn translucent(self) -> bool { + matches!(self, Self::Translucent | Self::ShadowTranslucent) + } +} + +/// Draws the game's terrain of one list into a pass; calls its third argument with each arena +/// page before drawing from it. pub(super) type TerrainDraw<'a> = - dyn FnMut(&mut wgpu::RenderPass<'_>, bool, &dyn Fn(&mut wgpu::RenderPass<'_>, u32)) + 'a; + dyn FnMut(&mut wgpu::RenderPass<'_>, TerrainList, &dyn Fn(&mut wgpu::RenderPass<'_>, u32)) + 'a; + +/// What the shadow camera sees of the terrain, for the game's draw lists: its view and +/// projection in wgpu's clip space, the direction toward the light, and how far from the camera +/// terrain is drawn (`shadowDistanceRenderMul`). +pub(super) struct ShadowView { + pub cull: glam::Mat4, + pub light: glam::Vec3, + pub distance: Option, +} /// Set 3 of flat terrain, read by the vertex stage: `mc_Entity`'s table (-1 pairs when empty) /// and, per arena page, the page's vertices (a vertex reads its quad's corners for its normal). @@ -1007,6 +1035,14 @@ impl PackPost { .water .zip(terrain_geometry.as_ref()) .and_then(|(p, g)| build(p, Some(g))); + let shadow_terrain = post + .shadow + .zip(terrain_geometry.as_ref()) + .and_then(|(p, g)| build(p, Some(g))); + let shadow_water = post + .shadow_water + .zip(terrain_geometry.as_ref()) + .and_then(|(p, g)| build(p, Some(g))); let sky = (post.sky.is_some() || post.sky_textured.is_some()).then(|| { let geometry = PackSky::new(device); let basic = Geometry { @@ -1124,9 +1160,22 @@ impl PackPost { if let Some(t) = &terrain { notes.push(format!("terrain draws with {}", t.name)); } + for (part, pass) in [ + ("terrain", &shadow_terrain), + ("translucent terrain", &shadow_water), + ] { + if let Some(p) = pass { + notes.push(format!("{part} casts shadows with {}", p.name)); + } + } if let Some(w) = &water { notes.push(format!("translucent terrain draws with {}", w.name)); } + // Timed (and labelled) apart from the solid shadow pass that runs the same program. + let mut shadow_water = shadow_water; + if let Some(p) = &mut shadow_water { + p.name.push_str(" (translucent)"); + } for (part, pass) in sky .iter() .flat_map(|s| [("sky", &s.basic), ("sun and moon", &s.textured)]) @@ -1168,6 +1217,7 @@ impl PackPost { .chain(&shadow_comp) .chain(&terrain) .chain(&water)) + .chain(shadow_terrain.iter().chain(&shadow_water)) .chain(sky.iter().flat_map(|s| s.basic.iter().chain(&s.textured))) .chain(entities.iter().flat_map(|e| e.passes.iter().flatten())) .chain(&clouds) @@ -1189,9 +1239,11 @@ impl PackPost { let t = super::pack_shadow::ShadowTargets::new(device, &shadow_config, f, colors, depth1); notes.push(format!( - "shadow map {0}x{0}, shadowcolor buffers {colors:#b}{1}", + "shadow map {0}x{0} over {2} blocks, sunPathRotation {3}, shadowcolor buffers {colors:#b}{1}", t.size, - if depth1 { ", shadowtex1" } else { "" } + if depth1 { ", shadowtex1" } else { "" }, + shadow_config.distance, + shadow_config.sun_path_rotation, )); t }); @@ -1334,6 +1386,8 @@ impl PackPost { hand, depth1, shadow_targets, + shadow_terrain, + shadow_water, shadow_comp, mipped, mips_valid: 0, @@ -1545,7 +1599,12 @@ impl PackPost { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, }; - // The shadow pass draws into the shadow buffers and the shadow map. + // The shadow pass draws into the shadow buffers and the shadow map, the frame's first + // one clearing them. + let (depth_ops, shadow_ops) = match &mut self.shadow_targets { + Some(s) if pass.group.shadow() => s.clear_ops(pass.writes.iter().map(|w| w.1)), + _ => (super::pack_shadow::load(), [load; 2]), + }; let shadow = self.shadow_targets.as_ref().filter(|_| pass.group.shadow()); let mut attachments: Vec> = Vec::new(); for &(location, buffer) in &pass.writes { @@ -1554,7 +1613,9 @@ impl PackPost { attachments.resize(l + 1, None); } attachments[l] = match shadow { - Some(s) => s.color(buffer, false).and_then(|v| attach(v, load)), + Some(s) => s + .color(buffer, false) + .and_then(|v| attach(v, shadow_ops.get(buffer).copied().unwrap_or(load))), None => targets.color[buffer] .as_ref() .and_then(|t| attach(&t[usize::from(self.main & 1 << buffer != 0)], load)), @@ -1567,10 +1628,7 @@ impl PackPost { timestamp_writes, depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: shadow.map_or(&targets.depth, |s| &s.depth.1), - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }), + depth_ops: Some(depth_ops), stencil_ops: None, }), ..Default::default() @@ -1585,18 +1643,20 @@ impl PackPost { queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, size: [u32; 2], - translucent: bool, + list: TerrainList, draw: &mut TerrainDraw<'_>, ) { - let slot = if translucent { - &mut self.water - } else { - &mut self.terrain + let slot = match list { + TerrainList::Solid => &mut self.terrain, + TerrainList::Translucent => &mut self.water, + TerrainList::ShadowSolid => &mut self.shadow_terrain, + TerrainList::ShadowTranslucent => &mut self.shadow_water, }; let Some(mut pass) = slot.take() else { return; }; - if translucent + let translucent = list.translucent(); + if list == TerrainList::Translucent && let Some(t) = &self.targets && let Some((copy, _)) = &t.depth1 { @@ -1625,14 +1685,17 @@ impl PackPost { rp.set_bind_group(3, group, &[]); } }; - draw(&mut rp, translucent, &page); + draw(&mut rp, list, &page); } - self.mips_valid &= !pass.written; - if translucent { - self.water = Some(pass); - } else { - self.terrain = Some(pass); + if !pass.group.shadow() { + self.mips_valid &= !pass.written; } + *match list { + TerrainList::Solid => &mut self.terrain, + TerrainList::Translucent => &mut self.water, + TerrainList::ShadowSolid => &mut self.shadow_terrain, + TerrainList::ShadowTranslucent => &mut self.shadow_water, + } = Some(pass); } /// The sky's parts in vanilla's order, each with the program that draws it; one render pass @@ -1782,7 +1845,7 @@ impl PackPost { if super::sky_visible(frame) { self.draw_sky(device, queue, encoder, size, frame); } - self.draw_terrain(device, queue, encoder, size, false, terrain); + self.draw_terrain(device, queue, encoder, size, TerrainList::Solid, terrain); self.draw_entities(device, queue, encoder, size, false); self.draw_clouds(device, queue, encoder, size); self.draw_hand(device, queue, encoder, size, frame); @@ -1878,7 +1941,14 @@ impl PackPost { size: [u32; 2], terrain: &mut TerrainDraw<'_>, ) { - self.draw_terrain(device, queue, encoder, size, true, terrain); + self.draw_terrain( + device, + queue, + encoder, + size, + TerrainList::Translucent, + terrain, + ); self.draw_entities(device, queue, encoder, size, true); self.draw_weather(device, queue, encoder, size); } @@ -1960,6 +2030,20 @@ impl PackPost { } /// Whether the pack draws terrain itself. + /// What the shadow camera draws of the terrain this frame, when the pack draws it. + pub fn shadow_view(&self, frame: &super::Frame) -> Option { + self.shadow_targets.as_ref()?; + if self.shadow_terrain.is_none() && self.shadow_water.is_none() { + return None; + } + let shadow = &self.uniforms.shadow; + Some(ShadowView { + cull: pack_uniforms::shadow_culling(frame, shadow), + light: pack_uniforms::shadow_light(frame, shadow), + distance: (shadow.render_mul > 0.0).then_some(shadow.distance * shadow.render_mul), + }) + } + pub fn has_terrain(&self) -> bool { self.terrain.is_some() } @@ -2088,13 +2172,32 @@ impl PackPost { device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, + terrain: &mut TerrainDraw<'_>, ) { - let Some(t) = &self.shadow_targets else { + let Some(t) = &mut self.shadow_targets else { return; }; - t.clear(encoder); - t.copy_depth1(encoder); + t.begin_frame(); let size = [t.size; 2]; + self.draw_terrain( + device, + queue, + encoder, + size, + TerrainList::ShadowSolid, + terrain, + ); + let t = self.shadow_targets.as_mut().expect("shadow pass"); + t.clear_rest(encoder); + t.copy_depth1(encoder); + self.draw_terrain( + device, + queue, + encoder, + size, + TerrainList::ShadowTranslucent, + terrain, + ); let mut comp = std::mem::take(&mut self.shadow_comp); for pass in &mut comp { let group = self.bind(device, queue, pass, size); @@ -2181,7 +2284,7 @@ impl PackPost { if self.targets.is_none() { return; } - self.run_shadow(device, queue, encoder); + self.run_shadow(device, queue, encoder, terrain); let Some(targets) = &self.targets else { return }; let main = |m: u16, i: usize| usize::from(m & 1 << i != 0); let view = |m: u16, i: usize, alt: bool| { diff --git a/crates/horizon-client/src/gfx/pack_shadow.rs b/crates/horizon-client/src/gfx/pack_shadow.rs index 7688d1250..92f0aeda0 100644 --- a/crates/horizon-client/src/gfx/pack_shadow.rs +++ b/crates/horizon-client/src/gfx/pack_shadow.rs @@ -3,6 +3,29 @@ //! with two sides that `shadowcomp` programs flip as composite programs flip colortex (6.1.6). //! Square, `shadowMapResolution` pixels. +type Ops = wgpu::Operations; +type Color = wgpu::Color; + +/// Loaded and stored. +pub(super) fn load() -> Ops { + wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + } +} + +fn clear(c: [f32; 4]) -> Ops { + wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: c[0].into(), + g: c[1].into(), + b: c[2].into(), + a: c[3].into(), + }), + store: wgpu::StoreOp::Store, + } +} + /// What the shadow pass writes and the programs read. pub(super) struct ShadowTargets { pub size: u32, @@ -16,6 +39,11 @@ pub(super) struct ShadowTargets { pub clears: [Option<[f32; 4]>; 2], /// Bit n set: B is shadowcolor n's "main". pub main: u16, + /// Nothing cleared yet this frame: the first pass into the shadow buffers clears them as it + /// begins (`clear_ops`), which saves a pass that loads and stores them all on tiled GPUs. + fresh: bool, + /// Bit n set: shadowcolor n was cleared that way. + cleared: u8, /// Depth comparison for `sampler2DShadow` (hardware filtering): linear, as GL filters it. pub comparison: wgpu::Sampler, } @@ -85,6 +113,8 @@ impl ShadowTargets { b.clear.then(|| b.clear_color.unwrap_or([1.0; 4])) }), main: 0, + fresh: false, + cleared: 0, comparison: device.create_sampler(&wgpu::SamplerDescriptor { label: Some("Shader pack shadow comparison"), compare: Some(wgpu::CompareFunction::LessEqual), @@ -101,31 +131,59 @@ impl ShadowTargets { self.color.get(n)?.as_ref().map(|c| &c[side]) } - /// Clears the shadow map and the shadowcolor buffers cleared every frame (6.3). - pub fn clear(&self, encoder: &mut wgpu::CommandEncoder) { + /// A new frame: the shadow map and the shadowcolor buffers cleared every frame (6.3) are + /// cleared by the first pass that begins (`clear_ops`), or else by `clear_rest`. + pub fn begin_frame(&mut self) { + self.fresh = true; + self.cleared = 0; + } + + /// The load operations of a pass into the shadow map and shadowcolor buffers `writes`: + /// clears in the frame's first one, loads after. + pub fn clear_ops( + &mut self, + writes: impl Iterator, + ) -> (Ops, [Ops; 2]) { + if !std::mem::take(&mut self.fresh) { + return (load(), [load(); 2]); + } + let mut colors = [load(); 2]; + for n in writes.filter(|&n| n < 2) { + if let Some(c) = self.clears[n] { + colors[n] = clear(c); + self.cleared |= 1 << n; + } + } + let depth = wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }; + (depth, colors) + } + + /// Clears what no pass has cleared this frame: all of it when no shadow program drew, the + /// cleared shadowcolor buffers the first one did not write. + pub fn clear_rest(&mut self, encoder: &mut wgpu::CommandEncoder) { + let depth = std::mem::take(&mut self.fresh); + let cleared = std::mem::replace(&mut self.cleared, 0b11); let attachments: Vec<_> = (0..2) + .filter(|n| cleared & 1 << n == 0) .filter_map(|n| { - let c = self.clears[n]?; Some(Some(wgpu::RenderPassColorAttachment { view: self.color(n, false)?, depth_slice: None, resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color { - r: c[0].into(), - g: c[1].into(), - b: c[2].into(), - a: c[3].into(), - }), - store: wgpu::StoreOp::Store, - }, + ops: clear(self.clears[n]?), })) }) .collect(); + if !depth && attachments.is_empty() { + return; + } encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Shader pack shadow clear"), color_attachments: &attachments, - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + depth_stencil_attachment: depth.then_some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth.1, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), diff --git a/crates/horizon-client/src/gfx/pack_uniforms.rs b/crates/horizon-client/src/gfx/pack_uniforms.rs index d1a85a1ba..c4df4377b 100644 --- a/crates/horizon-client/src/gfx/pack_uniforms.rs +++ b/crates/horizon-client/src/gfx/pack_uniforms.rs @@ -209,7 +209,7 @@ pub fn tilt_matrix(tilt: f32) -> Mat4 { } /// The world direction of the shadow light (7.1): the sun by day, the moon by night. -fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 { +pub fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 { let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0); let angle = if sun_angle < 0.5 { frame.sky.sun_angle @@ -219,6 +219,19 @@ fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 { body(angle, shadow.sun_path_rotation).normalize() } +/// `shadow_camera`'s view and projection in wgpu's clip space (depth 0..1), for culling. +pub fn shadow_culling(frame: &Frame, shadow: &Shadow) -> Mat4 { + let (view, gl) = shadow_camera(shadow_light(frame, shadow), frame.camera, shadow); + // GL's depth -w..w to wgpu's 0..w. + let depth = Mat4::from_cols( + Vec4::X, + Vec4::Y, + Vec4::new(0.0, 0.0, 0.5, 0.0), + Vec4::new(0.0, 0.0, 0.5, 1.0), + ); + depth * gl * view +} + /// Distance from the snapped point to the shadow camera, toward the light: the middle of the /// default near and far planes (OQ-6). const SHADOW_EYE: f64 = 128.0; diff --git a/crates/horizon-shaders/src/post.rs b/crates/horizon-shaders/src/post.rs index 95b8c3663..dd062b508 100644 --- a/crates/horizon-shaders/src/post.rs +++ b/crates/horizon-shaders/src/post.rs @@ -531,8 +531,12 @@ fn load_shadow(loader: &mut Loader<'_>, terrain: Option<&GbuffersInputs>) { }) }) }; - let shadow = load(&["shadow"]); - let water = load(&["shadow_water", "shadow"]); + // `shadowTerrain` and `shadowTranslucent` (3.2) leave terrain out of the shadow pass. + let keep = |key: &str| properties.get(key).is_none_or(|v| v.trim() != "false"); + let shadow = keep("shadowTerrain").then(|| load(&["shadow"])).flatten(); + let water = keep("shadowTranslucent") + .then(|| load(&["shadow_water", "shadow"])) + .flatten(); if shadow.is_none() { loader .post @@ -868,6 +872,8 @@ mod tests { }; assert!(!none("").shadow_pass); assert!(none("shadow.enabled=true").shadow.is_some()); + let post = none("shadow.enabled=true\nshadowTranslucent=false"); + assert!(post.shadow.is_some() && post.shadow_water.is_none()); } /// Water falls back to the terrain chain and blends by default, as the sky does; entities