diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index bc49052f1..1d924e229 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2541,17 +2541,22 @@ impl Renderer { i += run; } } - /// Horizon's terrain, solid or `translucent`, with a Java pack's - /// geometry pipelines (`java_terrain::DrawTerrain`): the frame's flat - /// draws or its section draws, each page with its group 3. + /// One `layer` of Horizon's terrain with a Java pack's geometry + /// pipelines (`java_terrain::DrawTerrain`): the frame's flat draws or its + /// section draws, each page with its group 3. `draws` are the frame's + /// phase 1 solid draws, all its solid draws and its translucent ones; + /// `culling` tells whether phase 2's come from occlusion culling. fn draw_java_terrain( &self, pass: &mut wgpu::RenderPass<'_>, - translucent: bool, + layer: java_terrain::Layer, pipelines: &java_terrain::TerrainPipelines, flat_frame: bool, - draws: [u32; 2], + draws: [u32; 3], + culling: bool, ) { + use java_terrain::Layer; + let translucent = layer == Layer::Translucent; let page = |pass: &mut wgpu::RenderPass<'_>, page: u32| { if let Some(Some((_, group))) = self.java_pages.get(page as usize) { pass.set_bind_group(3, group, &[]); @@ -2559,6 +2564,8 @@ impl Renderer { }; pass.set_bind_group(2, pipelines.group, &[]); match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { + // The flat path doesn't cull by occlusion: phase 1 is everything. + (Some(_), Some(_)) if layer == Layer::Revealed => {} (Some(flat), Some(pipeline)) => { pass.set_pipeline(pipeline); let calls = if translucent { @@ -2570,16 +2577,22 @@ impl Renderer { } (Some(_), None) => {} (None, _) => { + let [phase1, solid, translucent_draws] = draws; + let cull = self.cull.as_ref().filter(|_| culling); + let (indirect, base, first, count) = match (layer, cull) { + (Layer::Solid, Some(_)) => (&self.indirect, 0, 0, phase1), + (Layer::Solid, None) => (&self.indirect, 0, 0, solid), + (Layer::Revealed, Some(c)) => (&c.phase2, phase1, phase1, solid - phase1), + (Layer::Revealed, None) => return, + (Layer::Translucent, _) => (&self.indirect, 0, solid, translucent_draws), + }; + if count == 0 { + return; + } pass.set_pipeline(pipelines.instanced); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); - let [solid, translucent_draws] = draws; - let (first, count) = if translucent { - (solid, translucent_draws) - } else { - (0, solid) - }; - self.draw_sections_with(pass, &self.indirect, 0, first, count, page); + self.draw_sections_with(pass, indirect, base, first, count, page); } } } @@ -3185,8 +3198,8 @@ impl Renderer { .inverse() .transform_point3(Vec3::ZERO); // A Java pack that draws the terrain (`gfx/java_terrain.rs`): the - // world pass leaves it out, and occlusion culling (which tests - // against its depth) is off. + // world pass leaves it out, and occlusion culling tests against the + // pack's depth (`Cull::test_gl`). let java_terrain = !frame.title && self.java_table.is_some() && matches!(&self.pack, Some(Pack::Java(j)) if j.draws_terrain(frame.shader.dimension)); @@ -3200,7 +3213,6 @@ impl Renderer { && !frame.title && self.multi_draw && !(self.flat_on && self.flat.is_some()) - && !java_terrain }) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); @@ -3887,11 +3899,17 @@ impl Renderer { && let Some(mut stages) = self.pack.take() { // The pack's terrain programs draw with the frame's draws. - let draws = [solid_draws, translucent_draws]; + let draws = [phase1_draws, solid_draws, translucent_draws]; let draw = |render: &mut wgpu::RenderPass<'_>, - translucent: bool, + layer: java_terrain::Layer, pipelines: &java_terrain::TerrainPipelines| { - self.draw_java_terrain(render, translucent, pipelines, flat_frame, draws); + self.draw_java_terrain(render, layer, pipelines, flat_frame, draws, culling); + }; + let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); + let occlusion = |encoder: &mut wgpu::CommandEncoder, depth: &wgpu::TextureView| { + if let Some(cull) = cull { + cull.test_gl(encoder, depth); + } }; let world = java_terrain::JavaWorld { sprites: &self.sprite_textures, @@ -3900,6 +3918,9 @@ impl Renderer { animated: &self.animated, lightmap: &self.lightmap_view, draw: &draw, + occlusion: cull + .is_some() + .then_some(&occlusion as &java_terrain::OcclusionTest), }; let output = match &mut stages { Pack::Horizon(stages) => stages.run( diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs index bcb738de3..57acec5f5 100644 --- a/crates/horizon-client/src/gfx/cull.rs +++ b/crates/horizon-client/src/gfx/cull.rs @@ -76,6 +76,8 @@ struct Group { pub struct Cull { pipeline: wgpu::RenderPipeline, + /// [`Self::test_gl`]'s: a depth-only pass in OpenGL's layout. + gl_pipeline: wgpu::RenderPipeline, layout: wgpu::BindGroupLayout, group: Option, params: wgpu::Buffer, @@ -187,43 +189,63 @@ impl Cull { bind_group_layouts: &[Some(&layout)], ..Default::default() }); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Section culling"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &module, - entry_point: Some("vs_box"), - compilation_options: Default::default(), - buffers: &[], - }, - primitive: wgpu::PrimitiveState { - cull_mode: Some(wgpu::Face::Back), - ..Default::default() - }, - // The world pass's reversed depth test, without writes. - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::GreaterEqual), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs_box"), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: color, - blend: None, - write_mask: wgpu::ColorWrites::empty(), - })], - }), - multiview_mask: None, - cache: None, - }); + let pipeline = |label, gl: bool, targets: &[Option]| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(if gl { "vs_box_gl" } else { "vs_box" }), + compilation_options: Default::default(), + buffers: &[], + }, + // OpenGL's layout flips y, and with it the faces' winding. + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + front_face: if gl { + wgpu::FrontFace::Cw + } else { + wgpu::FrontFace::Ccw + }, + ..Default::default() + }, + // The pass's depth test (reversed in the world pass, OpenGL's + // in a Java pack's), without writes. + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(if gl { + wgpu::CompareFunction::LessEqual + } else { + wgpu::CompareFunction::GreaterEqual + }), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(if gl { "fs_box_depth" } else { "fs_box" }), + compilation_options: Default::default(), + targets, + }), + multiview_mask: None, + cache: None, + }) + }; + let gl_pipeline = pipeline("Section culling, OpenGL layout", true, &[]); + let pipeline = pipeline( + "Section culling", + false, + &[Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })], + ); Self { pipeline, + gl_pipeline, layout, group: None, params: buffer( @@ -413,6 +435,34 @@ impl Cull { pass.draw(0..36, 0..self.test_data.len() as u32); } + /// [`Self::test`] for a Java shader pack that draws the terrain + /// (`gfx/java_stages.rs`): in a pass of its own against `depth`, the + /// pack's depth after phase 1 in OpenGL's layout (y up, 0 near). + pub fn test_gl(&self, encoder: &mut wgpu::CommandEncoder, depth: &wgpu::TextureView) { + let Some(Group { group, .. }) = &self.group else { + return; + }; + if self.test_data.is_empty() { + return; + } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Section culling, Java shader pack"), + color_attachments: &[], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_pipeline(&self.gl_pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..36, 0..self.test_data.len() as u32); + } + /// After the world passes: copy the results for reading back, when a /// readback buffer is free. pub fn end(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) { diff --git a/crates/horizon-client/src/gfx/cull.wgsl b/crates/horizon-client/src/gfx/cull.wgsl index faa495caf..8345c15ae 100644 --- a/crates/horizon-client/src/gfx/cull.wgsl +++ b/crates/horizon-client/src/gfx/cull.wgsl @@ -52,6 +52,10 @@ fn corner(origin: vec3, c: u32) -> vec3 { // section fail the depth test against the final depth, which is only nearer. @vertex fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + return box_vertex(v, t); +} + +fn box_vertex(v: u32, t: u32) -> Box { let origin = origins[tests[t].x].xyz; var out: Box; out.test = t; @@ -86,16 +90,36 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box return out; } -// Runs only for fragments that pass the depth test (forced early). -@fragment -@early_depth_test(force) -fn fs_box(in: Box) -> @location(0) vec4 { - if results[in.test] != params.stamp { - results[in.test] = params.stamp; - let test = tests[in.test]; +// The same box in OpenGL's layout, for a Java shader pack's terrain depth +// (gfx/java_stages.rs): y flipped, depth from 0 near to 1 far. +@vertex +fn vs_box_gl(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + var out = box_vertex(v, t); + out.position = vec4(out.position.x, -out.position.y, out.position.w - out.position.z, out.position.w); + return out; +} + +fn seen(index: u32) { + if results[index] != params.stamp { + results[index] = params.stamp; + let test = tests[index]; for (var k = 0u; k < test.z; k++) { phase2[(test.y + k) * 5u + 1u] = 1u; } } +} + +// Runs only for fragments that pass the depth test (forced early). +@fragment +@early_depth_test(force) +fn fs_box(in: Box) -> @location(0) vec4 { + seen(in.test); return vec4(0.0); } + +// fs_box in a pass without colour targets. +@fragment +@early_depth_test(force) +fn fs_box_depth(in: Box) { + seen(in.test); +} diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index 19e2109e0..52bba0893 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -13,7 +13,7 @@ //! into the pack's targets right after, against the world's depth, and its //! `gbuffers_water` draws the translucent terrain after `deferred`, as in //! Iris. `depthtex1` and `depthtex2` then hold the depth before it. -use super::java_terrain::{Atlas, JavaWorld, TerrainPipelines}; +use super::java_terrain::{Atlas, JavaWorld, Layer, TerrainPipelines}; use super::pack_stages::FrameUniform; use crate::java_pack::{JavaFolder, JavaPasses}; use glam::{Mat3, Mat4, Vec3, Vec4}; @@ -1748,28 +1748,38 @@ impl PassGpu { Some(color_attachment(side, None)) }) .collect(); - let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some(&self.program), - color_attachments: &attachments, - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: depth, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, + let pipelines = TerrainPipelines { + instanced: &self.pipeline, + flat: self.flat_pipeline.as_ref(), + group, + }; + let draw = |encoder: &mut wgpu::CommandEncoder, layer| { + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&self.program), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, }), - stencil_ops: None, - }), - ..Default::default() - }); - (world.draw)( - &mut render, - translucent, - &TerrainPipelines { - instanced: &self.pipeline, - flat: self.flat_pipeline.as_ref(), - group, - }, - ); + ..Default::default() + }); + (world.draw)(&mut render, layer, &pipelines); + }; + if translucent { + draw(encoder, Layer::Translucent); + return; + } + draw(encoder, Layer::Solid); + // Occlusion culling: the sections left out, tested against what + // phase 1 drew, then the ones in sight. + if let Some(test) = world.occlusion { + test(encoder, depth); + draw(encoder, Layer::Revealed); + } } /// Draw into the targets of `draw_buffers`, on the side it doesn't read. diff --git a/crates/horizon-client/src/gfx/java_terrain.rs b/crates/horizon-client/src/gfx/java_terrain.rs index 6411efda1..dd0416428 100644 --- a/crates/horizon-client/src/gfx/java_terrain.rs +++ b/crates/horizon-client/src/gfx/java_terrain.rs @@ -204,9 +204,25 @@ pub fn page_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { }) } -/// Draws Horizon's terrain with a pack's pipelines: the solid layer or the -/// translucent one. Set by the renderer, which owns the sections. -pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, bool, &TerrainPipelines<'_>) + 'a; +/// Which of Horizon's terrain draws a pack's program draws. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Layer { + /// The solid sections: all of them, or with occlusion culling + /// ([`JavaWorld::occlusion`]) the ones the last test saw (phase 1). + Solid, + /// With occlusion culling, the solid sections the test after phase 1 + /// found in sight (phase 2). + Revealed, + Translucent, +} + +/// Draws Horizon's terrain with a pack's pipelines. Set by the renderer, +/// which owns the sections. +pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, Layer, &TerrainPipelines<'_>) + 'a; + +/// Occlusion culling's test between [`Layer::Solid`] and +/// [`Layer::Revealed`], against the pack's depth (OpenGL's layout). +pub type OcclusionTest<'a> = dyn Fn(&mut wgpu::CommandEncoder, &wgpu::TextureView) + 'a; /// What the renderer binds to draw with a pack's geometry program: the /// pipeline of its draw path and the pack's group (group 2). Group 1 is the @@ -229,6 +245,8 @@ pub struct JavaWorld<'a> { pub animated: &'a [(u32, u32)], pub lightmap: &'a wgpu::TextureView, pub draw: &'a DrawTerrain<'a>, + /// Set when the frame culls solid sections by occlusion. + pub occlusion: Option<&'a OcclusionTest<'a>>, } const ATLAS: &str = r#" diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3d32e37f6..263372d16 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -367,6 +367,10 @@ sprite arrays (animated sprites copied in each frame), `lightmap` is Horizon's l and fragments under alpha 0.1 are discarded (`alphaTestRef`). `RGBA16` targets are 16-bit unorm where the GPU can render them (Chocapic13' packs its G-buffer into them; half floats broke it). +Occlusion culling works as in Horizon's world pass where the GPU has it: the pack's terrain program draws the +sections the last test saw, the boxes of the others are tested against that depth (in OpenGL's layout, in a pass of +their own since the pack's targets vary), and the pack's program then draws the ones in sight. + What makes Horizon look like OpenGL to the pack: - **Layout.** The translator ends every vertex shader by flipping `gl_Position.y` and moving depth from `[-w, w]` to @@ -401,7 +405,7 @@ grade and light Horizon's world as their post-processing would. Sildur's Vibrant Without the other `gbuffers_*` and `shadow`, no pack has its shadows or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but ignored), custom textures, the option screen; shadow matrices are identity. With the pack's terrain: entities, the -sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), GPU occlusion culling is off, block ids +sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), block ids come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, and only the overworld has been checked.