diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 054ed25a9..a4ac42e04 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2779,17 +2779,21 @@ 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 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, &[]); @@ -2797,27 +2801,39 @@ impl Renderer { }; pass.set_bind_group(2, pipelines.group, &[]); match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { + // Without occlusion culling, phase 1 is every solid call. (Some(flat), Some(pipeline)) => { + let vertices = |p| self.arena.buffer(p); pass.set_pipeline(pipeline); - let calls = if translucent { - &flat.calls[flat.solid_calls..] - } else { - &flat.calls[..flat.solid_calls] - }; - flat.draw(pass, calls, |p| self.arena.buffer(p), page); + match layer { + Layer::Solid => { + flat.draw(pass, &flat.calls[..flat.phase1_calls], vertices, page) + } + Layer::Revealed if culling => flat.draw_phase2(pass, vertices, page), + Layer::Revealed => {} + Layer::Translucent => { + flat.draw(pass, &flat.calls[flat.solid_calls..], vertices, page) + } + } } (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); } } } @@ -3423,8 +3439,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)); @@ -3435,11 +3451,7 @@ impl Renderer { .cull .as_mut() .filter(|c| { - self.cull_on - && !frame.title - && self.multi_draw - && self.section_draws >= c.min_draws - && !java_terrain + self.cull_on && !frame.title && self.multi_draw && self.section_draws >= c.min_draws }) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); @@ -4084,7 +4096,7 @@ impl Renderer { ); pass.set_bind_group(0, &self.group, &[]); pass.set_pipeline(&flat.solid); - flat.draw_phase2(&mut pass, vertices); + flat.draw_phase2(&mut pass, vertices, |_, _| {}); } None => flat.draw( &mut pass, @@ -4308,11 +4320,21 @@ 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(&self.device, encoder, depth); + // The flat path's phase 2: the calls the test saw. + if let Some(flat) = self.flat.as_ref().filter(|_| flat_frame) { + flat.flatten_phase2(encoder); + } + } }; let world = java_terrain::JavaWorld { sprites: &self.sprite_textures, @@ -4321,6 +4343,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 57049eb4d..65700cb49 100644 --- a/crates/horizon-client/src/gfx/cull.rs +++ b/crates/horizon-client/src/gfx/cull.rs @@ -108,6 +108,14 @@ fn fs_box_early(in: Box) -> @location(0) vec4 { see(in.test); return vec4(0.0); } + +// fs_box_early against a Java shader pack's depth (`vs_box_gl`), in a pass +// without colour targets. +@fragment +@early_depth_test(force) +fn fs_box_early_depth(in: Box) { + see(in.test); +} "; /// The test's depth texture binding (`InShader`), for the view it was made with. @@ -118,6 +126,8 @@ struct DepthGroup { 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, depth_test: DepthTest, @@ -261,53 +271,76 @@ impl Cull { bind_group_layouts: &[Some(&layout), depth_layout.as_ref()], ..Default::default() }); - // In the shader: no colour target, and phase 1's depth attached read - // only (a pass needs an attachment), its test left to the shader. - let (fragment_entry, targets, depth_compare) = match depth_test { - DepthTest::Early => ( - "fs_box_early", - &[Some(wgpu::ColorTargetState { - format: color, - blend: None, - write_mask: wgpu::ColorWrites::empty(), - })][..], - wgpu::CompareFunction::GreaterEqual, - ), - DepthTest::InShader => ("fs_box", &[][..], wgpu::CompareFunction::Always), + // `gl`: a Java shader pack's depth (`test_gl`), in OpenGL's layout + // (y flipped, and with it the faces' winding; 0 near), without a + // colour target. In the shader (`InShader`): no colour target, and + // the depth attached read only (a pass needs an attachment), its + // test left to the shader. + let pipeline = |label, gl: bool| { + let color_target = [Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })]; + let (fragment_entry, targets, depth_compare) = match (depth_test, gl) { + (DepthTest::Early, false) => ( + "fs_box_early", + &color_target[..], + wgpu::CompareFunction::GreaterEqual, + ), + (DepthTest::Early, true) => ( + "fs_box_early_depth", + &[][..], + wgpu::CompareFunction::LessEqual, + ), + (DepthTest::InShader, false) => ("fs_box", &[][..], wgpu::CompareFunction::Always), + (DepthTest::InShader, true) => { + ("fs_box_gl", &[][..], wgpu::CompareFunction::Always) + } + }; + 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: &[], + }, + 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(depth_compare), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(fragment_entry), + compilation_options: Default::default(), + targets, + }), + multiview_mask: None, + cache: None, + }) }; - 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(depth_compare), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(fragment_entry), - 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); Self { pipeline, + gl_pipeline, layout, group: None, depth_test, @@ -553,6 +586,51 @@ 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), attached + /// read only, and also read by the shader where the test runs there + /// (`InShader`). + pub fn test_gl( + &self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + depth: &wgpu::TextureView, + ) { + let Some(Group { group, .. }) = &self.group else { + return; + }; + if self.test_data.is_empty() { + return; + } + let depth_group = self.depth_layout.as_ref().map(|layout| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Section culling depth, Java shader pack"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(depth), + }], + }) + }); + 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: None, + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_pipeline(&self.gl_pipeline); + pass.set_bind_group(0, group, &[]); + if let Some(depth) = &depth_group { + pass.set_bind_group(1, depth, &[]); + } + 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 b06d4ccc2..07a04ebc4 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,6 +90,15 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box return out; } +// 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; +} + // The box is seen at this fragment: store the stamp, and give its phase 2 // draws their instance. fn see(t: u32) { @@ -111,3 +124,12 @@ fn fs_box(in: Box) { see(in.test); } } + +// fs_box against a Java shader pack's depth in OpenGL's layout (`vs_box_gl`): +// less or equal passing. +@fragment +fn fs_box_gl(in: Box) { + if in.position.z <= textureLoad(depth, vec2(in.position.xy), 0) { + see(in.test); + } +} diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index f6e4e2d7a..4c491315c 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -663,11 +663,13 @@ impl Flat { pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); } } - /// Draws phase 2's calls, as `flatten_phase2` left them. + /// Draws phase 2's calls, as `flatten_phase2` left them; `page` as in + /// [`Self::draw`]. pub fn draw_phase2<'a>( &self, pass: &mut wgpu::RenderPass<'_>, vertices: impl Fn(u32) -> &'a wgpu::Buffer, + page: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); for (k, call) in self.calls[self.phase1_calls..self.solid_calls] @@ -675,6 +677,7 @@ impl Flat { .enumerate() { self.bind_page(pass, call.page, &vertices); + page(pass, call.page); pass.draw_indexed_indirect(&self.phase2_calls, k as u64 * 20); } } diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index ebb8acfc7..f4f7d21f6 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -15,7 +15,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, noise, rgba_view}; use crate::java_pack::{JavaFolder, JavaPasses, NOISE_KEY, blend_state, pass_blends, texture_key}; use crate::shader_pack::Rgba; @@ -1797,28 +1797,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 0b1214557..a752937c4 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -416,6 +416,11 @@ 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; on Metal the test reads the depth in the shader, as Horizon's does), and the +pack's program then draws the ones in sight, flat draws included. + 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 @@ -452,8 +457,7 @@ depth read as far. Horizon's world goes into the target the pack's `gbuffers_ter to) draws to first: `colortex0` for most packs, `colortex1` for MakeUp. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but ignored), `.dat` and resource-location custom textures (PNG files in the pack only); shadow matrices are identity. With the pack's terrain: -entities, the sky, the hand, weather and clouds are still Horizon's (in that first target only), GPU occlusion culling -is off, block ids come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, +entities, the sky, the hand, weather and clouds are still Horizon's (in that first target 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. ### Compatibility