From 6a58fc20dadaeed3e0e0af151c5b8ad59ca84c60 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:50:37 +0200 Subject: [PATCH] Java shader packs: the pack's gbuffers_terrain and gbuffers_water draw the terrain When a Java pack has a terrain program (gbuffers_terrain, or the program Iris falls back to), Horizon's world pass skips its own terrain and the pack's program draws every visible section into its render targets, tested against the depth of the rest of the world; gbuffers_water draws the translucent layer before the first composite with the pack's blend modes. depthtex0/depthtex1 get the depth before and after water. - translate: a geometry mode (group 2, attributes as globals a glue function fills before main, alpha test) and a pass that ends switch cases which return, which naga's WGSL writer otherwise rejects (Photon). - java_terrain: the glue decoding Horizon's terrain vertices from the arena pages into Iris's attributes, the block.properties id table by sprite name, and a 2D atlas built from the sprite arrays (animated sprites copied in). - RGBA16/RG16/R16 targets are 16-bit unorm where the GPU renders them: Chocapic13' packs its G-buffer into them. MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water on the M4 Pro; Photon still draws black (compute and .dat textures). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/Cargo.toml | 2 +- .../horizon-client/src/game/shader_packs.rs | 7 +- crates/horizon-client/src/gfx.rs | 213 ++++- crates/horizon-client/src/gfx/arena.rs | 9 +- crates/horizon-client/src/gfx/flat.rs | 10 + crates/horizon-client/src/gfx/java_stages.rs | 818 ++++++++++++++++-- crates/horizon-client/src/gfx/java_terrain.rs | 645 ++++++++++++++ crates/horizon-client/src/java_pack.rs | 162 +++- crates/horizon-shaderpack/src/lib.rs | 16 + crates/horizon-shaderpack/src/pipeline.rs | 107 ++- crates/horizon-shaderpack/src/properties.rs | 88 ++ crates/horizon-shaderpack/src/translate.rs | 157 +++- crates/horizon-shaderpack/tests/translate.rs | 91 +- docs/shader-packs.md | 48 +- 14 files changed, 2245 insertions(+), 128 deletions(-) create mode 100644 crates/horizon-client/src/gfx/java_terrain.rs diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 48e2e57d4..33e383907 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -84,4 +84,4 @@ workspace = true [dev-dependencies] # Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests). -naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] } +naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] } diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index 7d628ef44..851a92e44 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -69,7 +69,7 @@ impl Game<'_> { } }; if let Some(r) = self.renderer.as_mut() - && let Err(e) = r.set_shader_pack(pack.as_ref()) + && let Err(e) = r.set_shader_pack(pack.as_ref(), &self.pack.render.sprite_layers) { return self.shader_pack_error(&id, &e.to_string()); } @@ -79,7 +79,10 @@ impl Game<'_> { /// Give the loaded pack to the renderer (also after it is rebuilt). pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { match self.renderer.as_mut() { - Some(r) => r.set_shader_pack(self.shader_packs.pack.as_ref()), + Some(r) => r.set_shader_pack( + self.shader_packs.pack.as_ref(), + &self.pack.render.sprite_layers, + ), None => Ok(()), } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 14c040c5c..bc49052f1 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -62,7 +62,8 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod cull; mod flat; -mod java_stages; +pub(crate) mod java_stages; +pub(crate) mod java_terrain; mod lod; mod occlusion; mod pack_stages; @@ -436,6 +437,15 @@ pub struct Renderer { world_post: world_post::Post, /// The selected shader pack's stages (Horizon setting; none by default). pack: Option, + /// A Java pack's terrain programs (`gfx/java_terrain.rs`): their page + /// groups' layout, the glue's table, each arena page's group. + java_page_layout: wgpu::BindGroupLayout, + /// The device renders to and filters 16-bit normalized formats. + java_norm16: bool, + java_table: Option, + java_pages: Vec>, + /// The sprite layers and mip levels `animate` wrote this frame. + animated: Vec<(u32, u32)>, pub hud: HudRenderer, /// The menus' backdrop blur, made on first use. post: Option, @@ -784,7 +794,10 @@ async fn open_device( | cull::Cull::features(&adapter) | (adapter.features() & (wgpu::Features::INDIRECT_FIRST_INSTANCE - | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)); + | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS + // Java shader packs' 16-bit colour targets. + | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM + | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES)); let driver = format!("{} {}", info.driver, info.driver_info); startup_step(format_args!( "requesting the device (driver {}) with features [{features}] and the adapter's \ @@ -1274,7 +1287,10 @@ impl Renderer { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + // COPY_SRC: animated sprites into a Java pack's atlas. + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }, wgpu::util::TextureDataOrder::LayerMajor, @@ -2001,6 +2017,8 @@ impl Renderer { std::mem::size_of::() as u64, 1 << 20, ); + let java_page_layout = java_terrain::page_layout(&device); + let java_norm16 = java_terrain::norm16_targets(&adapter, &device); // Sections as one index list per frame where multi-draw is emulated. let flat = flat::wanted(&adapter, &device).then(|| { let buffers = [Some(wgpu::VertexBufferLayout { @@ -2180,6 +2198,11 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, pack: None, + java_page_layout, + java_norm16, + java_table: None, + java_pages: Vec::new(), + animated: Vec::new(), hud, post: None, menu_blur: None, @@ -2483,6 +2506,18 @@ impl Renderer { base: u32, first: u32, count: u32, + ) { + self.draw_sections_with(pass, indirect, base, first, count, |_, _| {}); + } + /// [`Self::draw_sections`]; `page` binds what else a page's draws need. + fn draw_sections_with( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + base: u32, + first: u32, + count: u32, + page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { @@ -2492,6 +2527,7 @@ impl Renderer { .take_while(|&&p| p == (page, index_page)) .count(); pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..)); + page_group(pass, page); let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); if self.multi_draw { @@ -2505,6 +2541,88 @@ 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. + fn draw_java_terrain( + &self, + pass: &mut wgpu::RenderPass<'_>, + translucent: bool, + pipelines: &java_terrain::TerrainPipelines, + flat_frame: bool, + draws: [u32; 2], + ) { + 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, &[]); + } + }; + pass.set_bind_group(2, pipelines.group, &[]); + match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { + (Some(flat), Some(pipeline)) => { + 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); + } + (Some(_), None) => {} + (None, _) => { + 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); + } + } + } + /// Each arena page's group for a Java pack's terrain programs: its + /// vertices and the glue's table. + fn prepare_java_pages(&mut self) { + let Some(table) = &self.java_table else { + return; + }; + let count = self.arena.page_count() as usize; + self.java_pages.resize_with(count, || None); + let limit = self.device.limits().max_storage_buffer_binding_size; + for page in 0..count { + if !self.arena.has_page(page as u32) { + self.java_pages[page] = None; + continue; + } + let buffer = self.arena.buffer(page as u32); + if matches!(&self.java_pages[page], Some((b, _)) if b == buffer) { + continue; + } + let size = buffer.size().min(limit / 4 * 4); + let group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack terrain page"), + layout: &self.java_page_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset: 0, + size: std::num::NonZeroU64::new(size), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: table.as_entire_binding(), + }, + ], + }); + self.java_pages[page] = Some((buffer.clone(), group)); + } + } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { self.release_mesh(s); @@ -2588,9 +2706,29 @@ impl Renderer { } } /// Run `pack`'s stages over the world from now on (`None`: no pack, the - /// vanilla frame). On error the previous pack stays. - pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> { + /// vanilla frame). On error the previous pack stays. `sprite_layers` + /// names the block sprites, for a Java pack's `block.properties`. + pub fn set_shader_pack( + &mut self, + pack: Option<&crate::shader_pack::ShaderPack>, + sprite_layers: &std::collections::BTreeMap, + ) -> Result<()> { let format = self.config.format.remove_srgb_suffix(); + let layouts = java_stages::GeometryLayouts { + flat: self.flat.as_ref().map(|f| f.draw_layout()), + page: &self.java_page_layout, + }; + let table = pack.and_then(|p| p.java.as_ref()).map(|java| { + let table = java_terrain::table(sprite_layers, &java.block_ids); + wgpu::util::DeviceExt::create_buffer_init( + &self.device, + &wgpu::util::BufferInitDescriptor { + label: Some("Java shader pack terrain table"), + contents: bytemuck::cast_slice(&table), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + }, + ) + }); self.pack = match pack { Some(pack) => Some(match &pack.java { Some(java) => Pack::Java(java_stages::JavaStages::new( @@ -2599,11 +2737,15 @@ impl Renderer { format, &pack.id, java, + &layouts, + self.java_norm16, )?), None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?), }), None => None, }; + self.java_table = table; + self.java_pages.clear(); Ok(()) } /// The folder name of the pack `set_shader_pack` gave. @@ -2733,11 +2875,13 @@ impl Renderer { self.lightmap_uploaded = true; } fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) { + self.animated.clear(); animate_sprites( &mut self.animations, tick, self.mip_levels, |layer, level, size, pixels| { + self.animated.push((layer, level)); self.uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -3040,6 +3184,12 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .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. + let java_terrain = !frame.title + && self.java_table.is_some() + && matches!(&self.pack, Some(Pack::Java(j)) if j.draws_terrain(frame.shader.dimension)); // Occlusion culling leaves the sections its last result did not see // to phase 2, after the others, with instance counts of 0. let mut cull = self @@ -3050,6 +3200,7 @@ 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(); @@ -3439,6 +3590,14 @@ impl Renderer { ); } } + if java_terrain { + self.prepare_java_pages(); + if let Some(table) = &self.java_table { + let nether = i32::from(frame.shader.dimension == -1); + self.queue + .write_buffer(table, 4, bytemuck::bytes_of(&nether)); + } + } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), ..Default::default() @@ -3528,11 +3687,15 @@ impl Renderer { } } match self.flat.as_ref().filter(|_| flat_frame) { + _ if java_terrain => {} Some(flat) => { pass.set_pipeline(&flat.solid); - flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| { - self.arena.buffer(p) - }); + flat.draw( + &mut pass, + &flat.calls[..flat.solid_calls], + |p| self.arena.buffer(p), + |_, _| {}, + ); pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } @@ -3645,11 +3808,15 @@ impl Renderer { pass.draw(0..4, debug_depth..debug_depth + debug_top); } match self.flat.as_ref().filter(|_| flat_frame) { + _ if java_terrain => {} Some(flat) => { pass.set_pipeline(&flat.translucent); - flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| { - self.arena.buffer(p) - }); + flat.draw( + &mut pass, + &flat.calls[flat.solid_calls..], + |p| self.arena.buffer(p), + |_, _| {}, + ); pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } @@ -3715,10 +3882,26 @@ impl Renderer { ); } } - if let (true, Some((color, depth)), Some(size), Some(stages)) = - (pack, &scaled, self.world_post.size(), self.pack.as_mut()) + if pack + && let (Some((color, depth)), Some(size)) = (&scaled, self.world_post.size()) + && let Some(mut stages) = self.pack.take() { - let output = match stages { + // The pack's terrain programs draw with the frame's draws. + let draws = [solid_draws, translucent_draws]; + let draw = |render: &mut wgpu::RenderPass<'_>, + translucent: bool, + pipelines: &java_terrain::TerrainPipelines| { + self.draw_java_terrain(render, translucent, pipelines, flat_frame, draws); + }; + let world = java_terrain::JavaWorld { + sprites: &self.sprite_textures, + split: self.sprite_split, + levels: self.mipmaps, + animated: &self.animated, + lightmap: &self.lightmap_view, + draw: &draw, + }; + let output = match &mut stages { Pack::Horizon(stages) => stages.run( &self.device, &self.queue, @@ -3743,10 +3926,12 @@ impl Renderer { sun_angle: frame.sky.sun_angle, moon_angle: frame.sky.moon_angle, }, + java_terrain.then_some(&world), ), }; self.world_post .finish_with(&mut encoder, &view_target, output); + self.pack = Some(stages); } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 8da835aa2..14a264cd2 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -65,8 +65,11 @@ pub struct Arena { } impl Arena { + /// Vertices; also storage, which a Java shader pack's terrain programs + /// read a quad's corners from (`gfx/java_terrain.rs`). pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self { - Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX) + let usage = wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE; + Self::with_usage(device, stride, capacity, usage) } /// Sorted translucent indices; `storage` when compute passes read them. pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self { @@ -145,6 +148,10 @@ impl Arena { pub fn page_vertices(&self) -> u64 { self.page_limit } + /// One past the last page index. + pub fn page_count(&self) -> u32 { + self.pages.len() as u32 + } pub fn has_page(&self, page: u32) -> bool { self.pages.get(page as usize).is_some_and(Option::is_some) } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index a1ae20d09..8da19d7c5 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -466,11 +466,20 @@ impl Flat { } /// Draws `calls` with a flat pipeline set and `vertices` giving each /// page's vertex buffer. + /// The bind group layout of the draws' group 1 (block slots, slot + /// origins). + pub fn draw_layout(&self) -> &wgpu::BindGroupLayout { + &self.draw_layout + } + + /// Draw `calls`; `page` binds what else a page's draws need (a Java + /// pack's terrain reads the page's vertices). pub fn draw<'a>( &self, pass: &mut wgpu::RenderPass<'_>, calls: &[Call], 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 call in calls { @@ -480,6 +489,7 @@ impl Flat { .expect("prepared page"); pass.set_vertex_buffer(0, vertices(call.page).slice(..)); pass.set_bind_group(1, table, &[]); + page(pass, call.page); pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); } } diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index e9f8ddbb1..19e2109e0 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -7,9 +7,17 @@ //! drawn, and the last picture goes to `world_post`. The targets keep GL's //! layout (row 0 at the bottom, which the translated vertex programs //! produce), so the world is flipped going in and the picture coming out. +//! +//! When the pack has terrain programs (`gfx/java_terrain.rs`), Horizon's +//! world comes without its terrain: the pack's `gbuffers_terrain` draws it +//! 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::pack_stages::FrameUniform; use crate::java_pack::{JavaFolder, JavaPasses}; use glam::{Mat3, Mat4, Vec3, Vec4}; +use horizon_shaderpack::pipeline::GeometryProgram; use horizon_shaderpack::pipeline::TargetSettings; use horizon_shaderpack::pipeline::{Directives, Program, target_index}; use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState}; @@ -32,7 +40,7 @@ const NOISE_SIZE: u32 = 256; /// The vertex buffers a pass may read (wgpu's default limit). const MAX_ATTRIBUTES: usize = 8; -const BLIT: &str = r#" +pub(super) const BLIT: &str = r#" @group(0) @binding(0) var color: texture_2d; @group(0) @binding(1) var depth: texture_depth_2d; @@ -49,13 +57,49 @@ struct World { // The world's colour and depth, upside down into GL's layout; Horizon's // reversed depth (near 1) as GL's (near 0). -@fragment -fn world_in(@builtin(position) p: vec4f) -> World { +fn world_texel(p: vec4f) -> World { let size = textureDimensions(depth); let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y)); return World(textureLoad(color, xy, 0), vec4f(1.0 - textureLoad(depth, xy, 0))); } +@fragment +fn world_in(@builtin(position) p: vec4f) -> World { + return world_texel(p); +} + +struct WorldDepth { + @location(0) color: vec4f, + @location(1) depth: vec4f, + @builtin(frag_depth) test: f32, +} + +// The same, and the depth into the depth buffer the pack's geometry +// programs test against. +@fragment +fn world_in_depth(@builtin(position) p: vec4f) -> WorldDepth { + let world = world_texel(p); + return WorldDepth(world.color, world.depth, world.depth.x); +} + +struct Depths { + @location(0) all: vec4f, + @location(1) solid: vec4f, +} + +// The depth buffer after the pack's geometry into `depthtex0` (and +// `depthtex1`, after solid terrain), both in GL's layout already. +@fragment +fn depth_out_both(@builtin(position) p: vec4f) -> Depths { + let d = vec4f(textureLoad(depth, vec2u(p.xy), 0)); + return Depths(d, d); +} + +@fragment +fn depth_out(@builtin(position) p: vec4f) -> @location(0) vec4f { + return vec4f(textureLoad(depth, vec2u(p.xy), 0)); +} + // A target, upside down back into wgpu's layout. @fragment fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { @@ -67,7 +111,10 @@ fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { /// A wgpu format for each of Iris's (`InternalTextureFormat`), renderable /// everywhere: 8-bit unsigned normalized formats stay, signed normalized, /// 16-bit and packed float ones become half floats, integer ones 32-bit. -fn target_format(iris: &str) -> wgpu::TextureFormat { +/// `norm16`: the device has 16-bit normalized formats, which keep packed +/// G-buffers (Chocapic13' packs two 8-bit values per `RGBA16` channel) +/// exact where a half float rounds them. +fn target_format(iris: &str, norm16: bool) -> wgpu::TextureFormat { use wgpu::TextureFormat as F; let channels = if iris.starts_with("RGB") || iris.contains("_B") { 4 @@ -84,6 +131,12 @@ fn target_format(iris: &str) -> wgpu::TextureFormat { match iris { "R8" | "RG8" | "RGB8" | "RGBA8" | "RGBA" | "RGBA2" | "RGBA4" | "R3_G3_B2" | "RGB5_A1" | "RGB565" => pick(F::R8Unorm, F::Rg8Unorm, F::Rgba8Unorm), + "R16" | "RG16" | "RGB16" | "RGBA16" if norm16 => { + pick(F::R16Unorm, F::Rg16Unorm, F::Rgba16Unorm) + } + "R16_SNORM" | "RG16_SNORM" | "RGB16_SNORM" | "RGBA16_SNORM" if norm16 => { + pick(F::R16Snorm, F::Rg16Snorm, F::Rgba16Snorm) + } "RGB10_A2" => F::Rgb10a2Unorm, "RGB10_A2UI" => F::Rgb10a2Uint, f if f.ends_with("32F") => pick(F::R32Float, F::Rg32Float, F::Rgba32Float), @@ -109,6 +162,14 @@ fn sample_type(format: wgpu::TextureFormat) -> wgpu::TextureSampleType { } } +/// The textures besides the targets a pass may read. +struct Views<'a> { + depth: &'a wgpu::TextureView, + depth_solid: &'a wgpu::TextureView, + atlas: Option<&'a wgpu::TextureView>, + lightmap: Option<&'a wgpu::TextureView>, +} + /// A colour target's two sides. struct Target { format: wgpu::TextureFormat, @@ -123,19 +184,33 @@ struct Target { #[derive(Clone, Copy, Debug, PartialEq)] enum Source { Target(u32), - /// `depthtex0..2`: the world's depth. + /// `depthtex0`: the world's depth. Depth, + /// `depthtex1` and `depthtex2`: the depth before translucent terrain + /// (the world's depth when the pack doesn't draw the terrain). + DepthSolid, Noise, /// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow); /// also Distant Horizons' and Voxy's depth, as without those mods. Shadow, /// Anything else (`shadowcolor*`, custom textures): white or black. Blank(bool), + /// In geometry programs: the block atlas (`gtexture`), the lightmap, + /// and a flat normal map for `normals` (sprites have no LabPBR maps). + Atlas, + Lightmap, + FlatNormal, } -fn source(name: &str) -> Source { +/// What sampler `name` reads, in a geometry program or a full-screen one. +fn source(name: &str, geometry: bool) -> Source { match name { - "depthtex0" | "depthtex1" | "depthtex2" | "gdepthtex" => Source::Depth, + "texture" | "gtexture" | "tex" if geometry => Source::Atlas, + "lightmap" if geometry => Source::Lightmap, + "normals" if geometry => Source::FlatNormal, + "specular" if geometry => Source::Blank(false), + "depthtex0" | "gdepthtex" => Source::Depth, + "depthtex1" | "depthtex2" => Source::DepthSolid, "noisetex" => Source::Noise, "shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow, n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow, @@ -174,11 +249,48 @@ struct PassGpu { draw_buffers: Vec, reads_alt: BTreeSet, scale: f32, + /// Geometry programs: the flat draws' pipeline (where the renderer has + /// them), and the targets written on their alternate side. + flat_pipeline: Option, + geometry: Option>, +} + +/// What a pass draws into. +enum Output<'a> { + /// A full-screen pass: its targets, or for `final` the screen's format. + Screen(Option), + /// A geometry program over Horizon's terrain. + Geometry(GeometrySetup<'a>), +} + +struct GeometrySetup<'a> { + /// The vertex program for flat draws. + flat_vertex: &'a horizon_shaderpack::translate::Translated, + /// Each draw buffer's blending. + blends: &'a [Option], + layouts: &'a GeometryLayouts<'a>, +} + +/// The renderer's bind group layouts a geometry program's pipelines use: +/// the flat draws' group 1 (`gfx/flat.rs`, when it has them) and the page +/// group 3 ([`super::java_terrain::page_layout`]). +pub struct GeometryLayouts<'a> { + pub flat: Option<&'a wgpu::BindGroupLayout>, + pub page: &'a wgpu::BindGroupLayout, +} + +/// A folder's terrain and water programs. +struct FolderGeometry { + terrain: PassGpu, + water: Option, + translucent_at: usize, } /// What every pass of the pack shares. struct Common { linear: wgpu::Sampler, + /// The block atlas's, as vanilla's: nearest, mipmapped. + atlas: wgpu::Sampler, nearest: wgpu::Sampler, repeat: wgpu::Sampler, compare: wgpu::Sampler, @@ -187,6 +299,8 @@ struct Common { vertices: [wgpu::Buffer; 4], world_layout: wgpu::BindGroupLayout, present_layout: wgpu::BindGroupLayout, + /// The geometry's depth buffer, read into `depthtex0` and `depthtex1`. + depth_layout: wgpu::BindGroupLayout, blit: wgpu::ShaderModule, } @@ -196,8 +310,11 @@ struct Bound { size: [u32; 2], targets: BTreeMap, depth: wgpu::TextureView, + /// `depthtex1`: `depth` before translucent terrain, or `depth` itself. + depth_solid: wgpu::TextureView, /// Per pass, then `final`. groups: Vec, + geometry: Option, world_in: (wgpu::RenderPipeline, wgpu::BindGroup), /// The world goes to colortex0's alternate side. world_alt: bool, @@ -209,6 +326,21 @@ struct Bound { _blank: Vec, } +/// What a folder's geometry programs draw with at one size. +struct BoundGeometry { + /// The depth buffer the geometry tests against: the world's, then the + /// terrain's. + test: wgpu::TextureView, + terrain: wgpu::BindGroup, + water: Option, + /// `world_in` that also fills `test`. + world_in: wgpu::RenderPipeline, + /// `test` into `depthtex0` and `depthtex1`, and into `depthtex0` alone. + out_both: wgpu::RenderPipeline, + out: wgpu::RenderPipeline, + out_group: wgpu::BindGroup, +} + struct Folder { targets: Vec, world_at: usize, @@ -217,6 +349,7 @@ struct Folder { passes: Vec, final_pass: Option, directives: Directives, + geometry: Option, } pub struct JavaStages { @@ -234,16 +367,24 @@ pub struct JavaStages { uniform_state: UniformState, /// `eyeBrightnessSmooth`, block then sky. eye_smooth: [SmoothFloat; 2], + /// The block atlas of the geometry programs. + atlas: Option, + /// The device has 16-bit normalized formats ([`target_format`]). + norm16: bool, } impl JavaStages { - /// The pipelines of a loaded Java pack, or wgpu's error. + /// The pipelines of a loaded Java pack, or wgpu's error. `norm16`: the + /// device has 16-bit normalized targets ([`target_format`]). + #[allow(clippy::too_many_arguments)] pub fn new( device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat, id: &str, pack: &JavaPasses, + layouts: &GeometryLayouts, + norm16: bool, ) -> Result { let common = Common::new(device, queue); let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d)); @@ -255,17 +396,17 @@ impl JavaStages { let formats: Vec = plan .targets .iter() - .map(|t| target_format(&t.format)) + .map(|t| target_format(&t.format, norm16)) .collect(); let passes = plan .passes .iter() - .map(|p| PassGpu::new(device, p, &formats, None)) + .map(|p| PassGpu::new(device, p, &formats, Output::Screen(None))) .collect::, _>>()?; let final_pass = plan .final_pass .as_ref() - .map(|p| PassGpu::new(device, p, &formats, Some(format))) + .map(|p| PassGpu::new(device, p, &formats, Output::Screen(Some(format)))) .transpose()?; Ok::<_, String>(Folder { targets: plan.targets.clone(), @@ -275,6 +416,7 @@ impl JavaStages { passes, final_pass, directives: plan.directives, + geometry: folder_geometry(device, plan, &formats, layouts), }) }) .collect::, _>>()?; @@ -295,11 +437,26 @@ impl JavaStages { uniforms: pack.uniforms.clone(), uniform_state: UniformState::default(), eye_smooth: [SmoothFloat::default(); 2], + atlas: None, + norm16, }) } + /// Whether the pack draws the terrain in `dimension` (0 overworld, -1 + /// the Nether, 1 the End): the renderer then leaves it out of the world + /// and gives `run` a [`JavaWorld`]. + pub fn draws_terrain(&self, dimension: i8) -> bool { + let d = i32::from(dimension).clamp(-1, 1); + let folder = self.folder_for[(d + 1) as usize].unwrap_or(0); + self.folders + .get(folder) + .is_some_and(|f| f.geometry.is_some()) + } + /// Run the passes of the world's dimension over its `color` and `depth` - /// (`size`) and return `post`'s bindings of the picture. + /// (`size`) and return `post`'s bindings of the picture. `world` is given + /// when the world was drawn without its terrain ([`Self::draws_terrain`]): + /// the pack's geometry programs draw it. #[allow(clippy::too_many_arguments)] pub fn run( &mut self, @@ -312,15 +469,21 @@ impl JavaStages { post: &super::world_post::Post, frame: FrameUniform, world: JavaFrame, + terrain: Option<&JavaWorld>, ) -> &wgpu::BindGroup { let dimension = (frame.dimension[0] as i32).clamp(-1, 1); let folder = self.folder_for[(dimension + 1) as usize].unwrap_or(0); - if self - .bound - .as_ref() - .is_none_or(|b| b.folder != folder || b.size != size) + let terrain = terrain.filter(|_| self.folders[folder].geometry.is_some()); + if let Some(w) = terrain + && self.atlas.as_ref().is_none_or(|a| !a.fits(w)) { - self.bound = Some(self.bind(device, queue, folder, color, depth, size, post)); + self.atlas = Atlas::new(device, queue, w); + self.bound = None; + } + if self.bound.as_ref().is_none_or(|b| { + b.folder != folder || b.size != size || b.geometry.is_some() != terrain.is_some() + }) { + self.bound = Some(self.bind(device, queue, folder, color, depth, size, post, terrain)); } let now = std::time::Instant::now(); let frame_time = self.last.map_or(0.0, |t| (now - t).as_secs_f32()); @@ -335,6 +498,9 @@ impl JavaStages { self.previous, ); inputs.set_world(&world, directives.sun_path_rotation); + if let Some(atlas) = &self.atlas { + inputs.atlas_size = atlas.size().map(|v| v as f32); + } let half_life = directives.eye_brightness_half_life; for (i, smooth) in self.eye_smooth.iter_mut().enumerate() { inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time); @@ -357,15 +523,40 @@ impl JavaStages { } } } - let world_at = folder.world_at; - for (i, (pass, group)) in folder.passes.iter().zip(&bound.groups).enumerate() { + if let (Some(w), Some(atlas)) = (terrain, &mut self.atlas) { + atlas.update(device, encoder, w); + } + // The world after `prepare`, the terrain with it; translucent + // terrain after `deferred`. + let world_at = folder.world_at.min(folder.passes.len()); + let geometry = folder + .geometry + .as_ref() + .zip(bound.geometry.as_ref()) + .zip(terrain); + let translucent_at = geometry.map_or(usize::MAX, |((g, _), _)| { + g.translucent_at.min(folder.passes.len()) + }); + for i in 0..=folder.passes.len() { if i == world_at { world_in(encoder, bound); + if let Some(((g, b), w)) = geometry { + g.terrain.draw_geometry( + queue, encoder, bound, &b.terrain, &b.test, &inputs, w, false, + ); + depth_out(encoder, bound, true); + } + } + if i == translucent_at + && let Some(((g, b), w)) = geometry + && let (Some(water), Some(group)) = (&g.water, &b.water) + { + water.draw_geometry(queue, encoder, bound, group, &b.test, &inputs, w, true); + depth_out(encoder, bound, false); + } + if let (Some(pass), Some(group)) = (folder.passes.get(i), bound.groups.get(i)) { + pass.draw(queue, encoder, bound, group, &self.common, &inputs); } - pass.draw(queue, encoder, bound, group, &self.common, &inputs); - } - if folder.passes.len() <= world_at { - world_in(encoder, bound); } if let (Some(pass), Some(view)) = (&folder.final_pass, &bound.final_target) { let group = bound.groups.last().expect("final's group"); @@ -413,13 +604,18 @@ impl JavaStages { world_depth: &wgpu::TextureView, size: [u32; 2], post: &super::world_post::Post, + world: Option<&JavaWorld>, ) -> Bound { let folder = &self.folders[folder_index]; let plan = folder; let all = folder.passes.iter().chain(&folder.final_pass); + let geometry = folder.geometry.as_ref().filter(|_| world.is_some()); + let geometry_passes = geometry + .into_iter() + .flat_map(|g| std::iter::once(&g.terrain).chain(&g.water)); // Every target a pass reads or writes, and colortex0 (the world). let mut used: BTreeSet = [0].into(); - for pass in all.clone() { + for pass in all.clone().chain(geometry_passes) { used.extend(pass.draw_buffers.iter().copied()); used.extend(pass.samplers.iter().filter_map(|s| match s.source { Source::Target(i) => Some(i), @@ -450,7 +646,7 @@ impl JavaStages { .iter() .filter_map(|&i| { let settings = plan.targets.get(i as usize)?; - let format = target_format(&settings.format); + let format = target_format(&settings.format, self.norm16); let target_size = match settings.size { Some(horizon_shaderpack::pipeline::TargetSize::Relative(w, h)) if i != 0 => [ (size[0] as f32 * w).round() as u32, @@ -496,11 +692,78 @@ impl JavaStages { size, ) .create_view(&Default::default()); + let depth_solid = match geometry { + Some(_) => texture( + "Java shader pack depth before translucent terrain", + wgpu::TextureFormat::R32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + size, + ) + .create_view(&Default::default()), + None => depth.clone(), + }; + let views = Views { + depth: &depth, + depth_solid: &depth_solid, + atlas: self.atlas.as_ref().map(|a| &a.view), + lightmap: world.map(|w| w.lightmap), + }; let mut blank = Vec::new(); let groups = all .clone() - .map(|pass| pass.bind(device, queue, &targets, &depth, &self.common, &mut blank)) + .map(|pass| pass.bind(device, queue, &targets, &views, &self.common, &mut blank)) .collect(); + let geometry = geometry.map(|g| { + let test = texture( + "Java shader pack geometry depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + size, + ) + .create_view(&Default::default()); + let r32 = wgpu::TextureFormat::R32Float; + let out_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack geometry depth"), + layout: &self.common.depth_layout, + entries: &[wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&test), + }], + }); + let mut bind = |pass: &PassGpu| { + pass.bind(device, queue, &targets, &views, &self.common, &mut blank) + }; + BoundGeometry { + terrain: bind(&g.terrain), + water: g.water.as_ref().map(&mut bind), + world_in: blit_pipeline( + device, + &self.common, + &self.common.world_layout, + "world_in_depth", + &[targets[&0].format, r32], + true, + ), + out_both: blit_pipeline( + device, + &self.common, + &self.common.depth_layout, + "depth_out_both", + &[r32, r32], + false, + ), + out: blit_pipeline( + device, + &self.common, + &self.common.depth_layout, + "depth_out", + &[r32], + false, + ), + out_group, + test, + } + }); // The world goes into colortex0's side the gbuffers would write. let colortex0 = &targets[&0]; @@ -510,6 +773,7 @@ impl JavaStages { &self.common.world_layout, "world_in", &[colortex0.format, wgpu::TextureFormat::R32Float], + false, ); let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack world"), @@ -549,6 +813,7 @@ impl JavaStages { &self.common.present_layout, "present", &[self.format], + false, ); let present_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack picture"), @@ -571,7 +836,9 @@ impl JavaStages { size, targets, depth, + depth_solid, groups, + geometry, world_in: (world_pipeline, world_group), world_alt: plan.flipped_after_prepare.contains(&0), final_target, @@ -583,6 +850,54 @@ impl JavaStages { } } +/// A folder's terrain and water programs on the GPU, or `None` (with a +/// warning: the terrain is then Horizon's) when wgpu refuses them. +fn folder_geometry( + device: &wgpu::Device, + plan: &JavaFolder, + formats: &[wgpu::TextureFormat], + layouts: &GeometryLayouts, +) -> Option { + let terrain = plan.terrain.as_ref()?; + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let gpu = |g: &GeometryProgram, blends: &[Option]| { + PassGpu::new( + device, + &g.program, + formats, + Output::Geometry(GeometrySetup { + flat_vertex: g.variants.first().unwrap_or(&g.program.vertex), + blends, + layouts, + }), + ) + }; + let made = gpu(terrain, &plan.terrain_blends).and_then(|terrain| { + let water = plan + .water + .as_ref() + .map(|w| gpu(w, &plan.water_blends)) + .transpose()?; + Ok(FolderGeometry { + terrain, + water, + translucent_at: plan.translucent_at, + }) + }); + let error = pollster::block_on(scope.pop()); + match (made, error) { + (Ok(geometry), None) => Some(geometry), + (Err(e), _) => { + log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); + None + } + (_, Some(e)) => { + log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); + None + } + } +} + fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let colortex0 = &bound.targets[&0]; let side = if bound.world_alt { @@ -597,13 +912,46 @@ fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Java shader pack world"), color_attachments: &attachments, + depth_stencil_attachment: bound.geometry.as_ref().map(|g| { + wgpu::RenderPassDepthStencilAttachment { + view: &g.test, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + } + }), ..Default::default() }); - render.set_pipeline(&bound.world_in.0); + match &bound.geometry { + Some(g) => render.set_pipeline(&g.world_in), + None => render.set_pipeline(&bound.world_in.0), + } render.set_bind_group(0, &bound.world_in.1, &[]); render.draw(0..3, 0..1); } +/// The geometry's depth buffer into `depthtex0`, and `depthtex1` too after +/// solid terrain. +fn depth_out(encoder: &mut wgpu::CommandEncoder, bound: &Bound, solid: bool) { + let Some(g) = &bound.geometry else { + return; + }; + let mut attachments = vec![Some(color_attachment(&bound.depth, None))]; + if solid { + attachments.push(Some(color_attachment(&bound.depth_solid, None))); + } + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack geometry depth"), + color_attachments: &attachments, + ..Default::default() + }); + render.set_pipeline(if solid { &g.out_both } else { &g.out }); + render.set_bind_group(0, &g.out_group, &[]); + render.draw(0..3, 0..1); +} + fn color_attachment( view: &wgpu::TextureView, clear: Option, @@ -628,12 +976,15 @@ fn clear_view(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, colo }); } +/// A full-screen pipeline of `BLIT`'s `entry`; `depth`: it writes the +/// geometry's depth buffer. fn blit_pipeline( device: &wgpu::Device, common: &Common, layout: &wgpu::BindGroupLayout, entry: &str, formats: &[wgpu::TextureFormat], + depth: bool, ) -> wgpu::RenderPipeline { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Java shader pack blit"), @@ -652,7 +1003,13 @@ fn blit_pipeline( buffers: &[], }, primitive: Default::default(), - depth_stencil: None, + depth_stencil: depth.then_some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &common.blit, @@ -750,6 +1107,13 @@ impl Common { let unfilterable = wgpu::TextureSampleType::Float { filterable: false }; Self { linear: sampler(Linear, ClampToEdge, None), + atlas: device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Java shader pack block atlas"), + mag_filter: Nearest, + min_filter: Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }), nearest: sampler(Nearest, ClampToEdge, None), repeat: sampler(Linear, Repeat, None), compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)), @@ -766,6 +1130,10 @@ impl Common { label: Some("Java shader pack picture"), entries: &[texture_entry(0, unfilterable)], }), + depth_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack geometry depth"), + entries: &[texture_entry(1, wgpu::TextureSampleType::Depth)], + }), blit: device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Java shader pack blit"), source: wgpu::ShaderSource::Wgsl(BLIT.into()), @@ -808,8 +1176,12 @@ impl PassGpu { device: &wgpu::Device, program: &Program, formats: &[wgpu::TextureFormat], - screen: Option, + output: Output, ) -> Result { + let (screen, setup) = match output { + Output::Screen(screen) => (screen, None), + Output::Geometry(setup) => (None, Some(setup)), + }; let name = program.pass.program.clone(); let link = &program.link; let mut samplers = Vec::new(); @@ -841,7 +1213,7 @@ impl PassGpu { .cloned() .unwrap_or_else(|| format!("{sampler}_s")); samplers.push(SamplerBinding { - source: source(sampler), + source: source(sampler, setup.is_some()), dimension, signed, texture: binding(&format!("{sampler}_t"))?, @@ -885,7 +1257,7 @@ impl PassGpu { )), ) } - (false, Source::Depth | Source::Shadow) => ( + (false, Source::Depth | Source::DepthSolid | Source::Shadow) => ( wgpu::TextureSampleType::Float { filterable: false }, Some(false), ), @@ -934,6 +1306,9 @@ impl PassGpu { label: Some(&name), entries: &entries, }); + if let Some(setup) = setup { + return Self::geometry(device, program, formats, setup, layout, samplers, block); + } let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(&name), bind_group_layouts: &[Some(&layout)], @@ -1064,19 +1439,164 @@ impl PassGpu { }, reads_alt: program.pass.reads_alt.clone(), scale: program.pass.scale.clamp(0.0, 1.0), + flat_pipeline: None, + geometry: None, }) } - /// The pass's bind group over `targets`. + /// A geometry program's pipelines over Horizon's terrain vertices + /// (instanced and flat draws), into its draw buffers on the side the + /// next passes read, tested against the world's depth. + #[allow(clippy::too_many_arguments)] + fn geometry( + device: &wgpu::Device, + program: &Program, + formats: &[wgpu::TextureFormat], + setup: GeometrySetup, + layout: wgpu::BindGroupLayout, + samplers: Vec, + block: Option<(u32, Vec<(String, Vec)>)>, + ) -> Result { + let name = program.pass.program.clone(); + let outputs = &program.fragment.interface.outputs; + let targets: Vec> = program + .draw_buffers + .iter() + .enumerate() + .map(|(l, &i)| { + let format = formats + .get(i as usize) + .copied() + .unwrap_or(wgpu::TextureFormat::Rgba8Unorm); + let blendable = matches!( + sample_type(format), + wgpu::TextureSampleType::Float { filterable: true } + ); + Some(wgpu::ColorTargetState { + format, + blend: setup.blends.get(l).copied().flatten().filter(|_| blendable), + write_mask: if outputs.contains_key(&(l as u32)) { + wgpu::ColorWrites::ALL + } else { + wgpu::ColorWrites::empty() + }, + }) + }) + .collect(); + let vertex = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &super::TERRAIN_ATTRIBUTES, + }; + let instance_attributes = wgpu::vertex_attr_array![5 => Float32x4]; + let instance = wgpu::VertexBufferLayout { + array_stride: 16, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &instance_attributes, + }; + let fragment_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&format!("{name}.fsh")), + source: wgpu::ShaderSource::Wgsl(program.fragment.wgsl.as_str().into()), + }); + let pipeline = |vertex_program: &horizon_shaderpack::translate::Translated, + flat: Option<&wgpu::BindGroupLayout>| { + let vertex_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&format!("{name}.vsh")), + source: wgpu::ShaderSource::Wgsl(vertex_program.wgsl.as_str().into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some(&name), + bind_group_layouts: &[None, flat, Some(&layout), Some(setup.layouts.page)], + ..Default::default() + }); + let buffers = if flat.is_some() { + vec![Some(vertex.clone())] + } else { + vec![Some(vertex.clone()), Some(instance.clone())] + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&name), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &vertex_module, + entry_point: Some("main"), + compilation_options: Default::default(), + buffers: &buffers, + }, + // The y flip into GL's layout turns the faces around. + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + front_face: wgpu::FrontFace::Cw, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &fragment_module, + entry_point: Some("main"), + compilation_options: Default::default(), + targets: &targets, + }), + multiview_mask: None, + cache: None, + }) + }; + let instanced = pipeline(&program.vertex, None); + let flat_pipeline = setup + .layouts + .flat + .map(|flat| pipeline(setup.flat_vertex, Some(flat))); + let uniform = block.as_ref().map(|(size, _)| { + ( + *size, + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack uniforms"), + size: u64::from(*size).max(16), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + ) + }); + // It reads the side the next passes read, but the other side of the + // targets it writes: wgpu can't read and write a texture at once. + let flipped = program.pass.reads_alt.clone(); + let written: BTreeSet = program.draw_buffers.iter().copied().collect(); + let reads_alt = (0..horizon_shaderpack::pipeline::MAX_COLOR_BUFFERS) + .filter(|i| flipped.contains(i) != written.contains(i)) + .collect(); + Ok(Self { + program: name, + pipeline: instanced, + layout, + samplers, + uniforms: block.map(|(_, members)| members).unwrap_or_default(), + uniform, + attributes: Vec::new(), + draw_buffers: program.draw_buffers.clone(), + reads_alt, + scale: 1.0, + flat_pipeline, + geometry: Some(flipped), + }) + } + + /// The pass's bind group over `targets` and `views`. fn bind( &self, device: &wgpu::Device, queue: &wgpu::Queue, targets: &BTreeMap, - depth: &wgpu::TextureView, + textures: &Views, common: &Common, blank: &mut Vec, ) -> wgpu::BindGroup { + let depth = textures.depth; let mut views = Vec::new(); for s in &self.samplers { let view = match (s.compare, s.source) { @@ -1091,6 +1611,24 @@ impl PassGpu { (false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => { depth.clone() } + (false, Source::DepthSolid) if s.dimension == wgpu::TextureViewDimension::D2 => { + textures.depth_solid.clone() + } + (false, Source::Atlas) if s.dimension == wgpu::TextureViewDimension::D2 => { + match textures.atlas { + Some(v) => v.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(true)), + } + } + (false, Source::Lightmap) if s.dimension == wgpu::TextureViewDimension::D2 => { + match textures.lightmap { + Some(v) => v.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(true)), + } + } + (false, Source::FlatNormal) => { + blank_view(device, queue, blank, s, BlankKind::FlatNormal) + } (false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far), (false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => { common.noise.clone() @@ -1110,7 +1648,8 @@ impl PassGpu { (true, _) => &common.compare, _ if s.signed.is_some() => &common.nearest, (false, Source::Noise) => &common.repeat, - (false, Source::Depth | Source::Shadow) => &common.nearest, + (false, Source::Depth | Source::DepthSolid | Source::Shadow) => &common.nearest, + (false, Source::Atlas) => &common.atlas, (false, Source::Target(i)) => { match targets.get(&i).map(|t| sample_type(t.format)) { Some(wgpu::TextureSampleType::Float { filterable: true }) | None => { @@ -1151,6 +1690,88 @@ impl PassGpu { }) } + /// This frame's values of its uniforms. + fn write_uniforms(&self, queue: &wgpu::Queue, inputs: &Inputs) { + let Some((block_size, buffer)) = &self.uniform else { + return; + }; + let mut bytes = vec![0u8; *block_size as usize]; + for (name, slots) in &self.uniforms { + if let Some(values) = inputs.value(name, self.geometry.is_some()) { + for (&(offset, int), value) in slots.iter().zip(values) { + let at = offset as usize..offset as usize + 4; + bytes[at].copy_from_slice(&if int { + (value as i32).to_ne_bytes() + } else { + value.to_ne_bytes() + }); + } + } + } + queue.write_buffer(buffer, 0, &bytes); + } + + /// A geometry program: Horizon's terrain (solid or `translucent`) into + /// its draw buffers on the side the next passes read, against `depth`. + #[allow(clippy::too_many_arguments)] + fn draw_geometry( + &self, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + bound: &Bound, + group: &wgpu::BindGroup, + depth: &wgpu::TextureView, + inputs: &Inputs, + world: &JavaWorld, + translucent: bool, + ) { + let Some(flipped) = &self.geometry else { + return; + }; + self.write_uniforms(queue, inputs); + // Targets of another size than the world's can't be drawn with it. + let size = wgpu::Extent3d { + width: bound.size[0].max(1), + height: bound.size[1].max(1), + depth_or_array_layers: 1, + }; + let attachments: Vec> = self + .draw_buffers + .iter() + .map(|i| { + let t = bound.targets.get(i).filter(|t| t.main.size() == size)?; + let side = if flipped.contains(i) { + &t.alt_view + } else { + &t.main_view + }; + 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, + }), + stencil_ops: None, + }), + ..Default::default() + }); + (world.draw)( + &mut render, + translucent, + &TerrainPipelines { + instanced: &self.pipeline, + flat: self.flat_pipeline.as_ref(), + group, + }, + ); + } + /// Draw into the targets of `draw_buffers`, on the side it doesn't read. fn draw( &self, @@ -1196,22 +1817,7 @@ impl PassGpu { common: &Common, inputs: &Inputs, ) { - if let Some((block_size, buffer)) = &self.uniform { - let mut bytes = vec![0u8; *block_size as usize]; - for (name, slots) in &self.uniforms { - if let Some(values) = inputs.value(name) { - for (&(offset, int), value) in slots.iter().zip(values) { - let at = offset as usize..offset as usize + 4; - bytes[at].copy_from_slice(&if int { - (value as i32).to_ne_bytes() - } else { - value.to_ne_bytes() - }); - } - } - } - queue.write_buffer(buffer, 0, &bytes); - } + self.write_uniforms(queue, inputs); let attachments: Vec> = views .iter() .map(|v| v.map(|v| color_attachment(v, None))) @@ -1234,6 +1840,8 @@ impl PassGpu { enum BlankKind { Color(bool), + /// A normal map's flat normal, (0.5, 0.5, 1). + FlatNormal, /// An `R32Float` 1.0: the far plane. Far, /// A depth texture at the far plane, for comparison samplers. @@ -1256,6 +1864,7 @@ fn blank_view( wgpu::TextureFormat::Rgba8Unorm, vec![if white { 255 } else { 0 }; 4], ), + (BlankKind::FlatNormal, _) => (wgpu::TextureFormat::Rgba8Unorm, vec![128, 128, 255, 255]), (BlankKind::Far, _) => (wgpu::TextureFormat::R32Float, 1.0f32.to_ne_bytes().to_vec()), (BlankKind::FarDepth, _) => (wgpu::TextureFormat::Depth32Float, Vec::new()), }; @@ -1452,6 +2061,8 @@ struct Inputs { is_day: bool, /// The pack's custom uniforms this frame. custom: HashMap>, + /// `atlasSize`, in geometry programs. + atlas_size: [f32; 2], } /// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360 @@ -1506,6 +2117,7 @@ impl Inputs { shadow_angle: 0.0, is_day: true, custom: HashMap::new(), + atlas_size: [0.0; 2], }; out.set_world(&JavaFrame::default(), 0.0); out @@ -1541,16 +2153,55 @@ impl Inputs { /// The value of uniform `name`, as its scalars in order: Iris's own, /// else the pack's custom uniform; `None` for one Horizon doesn't /// provide (it stays zero). - fn value(&self, name: &str) -> Option> { - self.builtin(name) + fn value(&self, name: &str, geometry: bool) -> Option> { + geometry + .then(|| self.geometry(name)) + .flatten() + .or_else(|| self.builtin(name)) .or_else(|| self.custom.get(name).cloned()) } + /// The uniforms whose value differs in geometry programs: the + /// camera's matrices (camera-relative positions, as Iris's terrain), + /// the lightmap's texture matrix, the atlas's size. + fn geometry(&self, name: &str) -> Option> { + let mat = |m: Mat4| m.to_cols_array().to_vec(); + Some(match name { + "iris_ModelViewMatrix" | "modelViewMatrix" => mat(self.view), + "iris_ModelViewMatrixInverse" | "modelViewMatrixInverse" => mat(self.view.inverse()), + "iris_ProjectionMatrix" | "projectionMatrix" => mat(self.projection), + "iris_ProjectionMatrixInverse" | "projectionMatrixInverse" => { + mat(self.projection.inverse()) + } + "iris_ModelViewProjectionMatrix" => mat(self.projection * self.view), + "iris_NormalMatrix" | "normalMatrix" => Mat3::from_mat4(self.view) + .inverse() + .transpose() + .to_cols_array() + .to_vec(), + // Unit 1, the lightmap: 0..240 to texel centres (Iris's + // `LIGHTMAP_TEXTURE_MATRIX`). + "iris_TextureMatrix" => { + let lightmap = Mat4::from_scale(Vec3::splat(1.0 / 256.0)) + * Mat4::from_translation(Vec3::splat(8.0)); + (0..8) + .flat_map(|i| mat(if i == 1 { lightmap } else { Mat4::IDENTITY })) + .collect() + } + "textureMatrix" => mat(Mat4::IDENTITY), + "chunkOffset" => vec![0.0; 3], + "alphaTestRef" => vec![0.1], + "atlasSize" => self.atlas_size.to_vec(), + "entityId" | "blockEntityId" | "currentRenderedItemId" => vec![-1.0], + _ => return None, + }) + } + /// The value of Iris uniform `name`; `None` for one Horizon doesn't /// provide. fn builtin(&self, name: &str) -> Option> { if let Some(flag) = name.strip_prefix("iris_bool_") { - return self.value(flag); + return self.value(flag, false); } let f = &self.frame; let mat = |m: Mat4| m.to_cols_array().to_vec(); @@ -1638,8 +2289,11 @@ mod tests { ("R32UI", F::R32Uint), ("RGBA16I", F::Rgba32Sint), ] { - assert_eq!(target_format(iris), wgpu, "{iris}"); + assert_eq!(target_format(iris, false), wgpu, "{iris}"); } + assert_eq!(target_format("RGBA16", true), F::Rgba16Unorm); + assert_eq!(target_format("RG16_SNORM", true), F::Rg16Snorm); + assert_eq!(target_format("RGBA16F", true), F::Rgba16Float); assert_eq!( sample_type(F::R32Float), wgpu::TextureSampleType::Float { filterable: false } @@ -1648,13 +2302,20 @@ mod tests { #[test] fn samplers_read_what_iris_binds() { - assert_eq!(source("colortex4"), Source::Target(4)); - assert_eq!(source("gaux1"), Source::Target(4)); - assert_eq!(source("gdepthtex"), Source::Depth); - assert_eq!(source("shadowtex1"), Source::Shadow); - assert_eq!(source("dhDepthTex0"), Source::Shadow); - assert_eq!(source("shadowcolor0"), Source::Blank(true)); - assert_eq!(source("cloudTexture"), Source::Blank(false)); + assert_eq!(source("colortex4", false), Source::Target(4)); + assert_eq!(source("gaux1", false), Source::Target(4)); + assert_eq!(source("gdepthtex", false), Source::Depth); + assert_eq!(source("shadowtex1", false), Source::Shadow); + assert_eq!(source("dhDepthTex0", false), Source::Shadow); + assert_eq!(source("shadowcolor0", false), Source::Blank(true)); + assert_eq!(source("cloudTexture", false), Source::Blank(false)); + // Before translucent terrain; geometry programs' own textures. + assert_eq!(source("depthtex1", false), Source::DepthSolid); + assert_eq!(source("gtexture", true), Source::Atlas); + assert_eq!(source("texture", true), Source::Atlas); + assert_eq!(source("lightmap", true), Source::Lightmap); + assert_eq!(source("normals", true), Source::FlatNormal); + assert_eq!(source("colortex1", true), Source::Target(1)); let (d, signed, shadow) = sampler_kind("usampler2D").unwrap(); assert_eq!( (d, signed, shadow), @@ -1688,21 +2349,24 @@ mod tests { moon_angle: sun_angle + 180.0, }; inputs.set_world(&world(-90.0), 0.0); - close(inputs.value("sunPosition"), [100.0, 0.0, 0.0]); - close(inputs.value("moonPosition"), [-100.0, 0.0, 0.0]); - close(inputs.value("upPosition"), [0.0, 100.0, 0.0]); - assert_eq!(inputs.value("sunAngle"), Some(vec![0.0])); - assert_eq!(inputs.value("eyeBrightness"), Some(vec![48.0, 240.0])); + close(inputs.value("sunPosition", false), [100.0, 0.0, 0.0]); + close(inputs.value("moonPosition", false), [-100.0, 0.0, 0.0]); + close(inputs.value("upPosition", false), [0.0, 100.0, 0.0]); + assert_eq!(inputs.value("sunAngle", false), Some(vec![0.0])); + assert_eq!( + inputs.value("eyeBrightness", false), + Some(vec![48.0, 240.0]) + ); // Complementary Unbound's sunPathRotation of -40 at noon: the sun // where its GetSunVector puts it, (0, cos 40, sin 40). let tilt = (-40f32).to_radians(); inputs.set_world(&world(0.0), -40.0); close( - inputs.value("sunPosition"), + inputs.value("sunPosition", false), [0.0, 100.0 * tilt.cos(), -100.0 * tilt.sin()], ); - assert_eq!(inputs.value("sunAngle"), Some(vec![0.25])); - close(inputs.value("shadowLightPosition"), { + assert_eq!(inputs.value("sunAngle", false), Some(vec![0.25])); + close(inputs.value("shadowLightPosition", false), { let s = inputs.sun_position; [s.x, s.y, s.z] }); @@ -1710,15 +2374,15 @@ mod tests { inputs.set_world(&world(150.0), 0.0); assert!(!inputs.is_day); assert_eq!( - inputs.value("shadowLightPosition"), - inputs.value("moonPosition") + inputs.value("shadowLightPosition", false), + inputs.value("moonPosition", false) ); - assert!((inputs.value("shadowAngle").unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); + assert!((inputs.value("shadowAngle", false).unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); // Custom uniforms come after Iris's own. inputs.custom.insert("eyeBrightnessM".into(), vec![0.5]); inputs.custom.insert("sunAngle".into(), vec![9.0]); - assert_eq!(inputs.value("eyeBrightnessM"), Some(vec![0.5])); - assert_ne!(inputs.value("sunAngle"), Some(vec![9.0])); + assert_eq!(inputs.value("eyeBrightnessM", false), Some(vec![0.5])); + assert_ne!(inputs.value("sunAngle", false), Some(vec![9.0])); } #[test] @@ -1737,10 +2401,10 @@ mod tests { }; assert!((depth(near) + 1.0).abs() < 1e-4, "{}", depth(near)); assert!((depth(far) - 1.0).abs() < 1e-3, "{}", depth(far)); - assert_eq!(inputs.value("viewWidth"), Some(vec![300.0])); + assert_eq!(inputs.value("viewWidth", false), Some(vec![300.0])); assert_eq!( - inputs.value("iris_bool_hasSkylight"), - inputs.value("hasSkylight") + inputs.value("iris_bool_hasSkylight", false), + inputs.value("hasSkylight", false) ); } } diff --git a/crates/horizon-client/src/gfx/java_terrain.rs b/crates/horizon-client/src/gfx/java_terrain.rs new file mode 100644 index 000000000..6411efda1 --- /dev/null +++ b/crates/horizon-client/src/gfx/java_terrain.rs @@ -0,0 +1,645 @@ +//! Horizon's terrain drawn with a Java pack's `gbuffers_terrain` and +//! `gbuffers_water` (docs/shader-packs.md). The pack's vertex program runs +//! after a glue that rebuilds what Iris would feed it from Horizon's +//! `TerrainVertex`: the camera-relative position, the quad's normal and +//! tangent (from its four corners, read from the arena page as storage), +//! the colour without vanilla's directional shade, the lightmap +//! coordinates, the sprite's place in a block atlas laid out from Horizon's +//! sprite arrays, and `mc_Entity` from the pack's `block.properties`, by +//! sprite name. +use horizon_shaderpack::translate::Geometry; +use std::collections::BTreeMap; + +/// `TerrainVertex` in 32-bit words. +const VERTEX_WORDS: u32 = 6; + +/// The glue's declarations and `hz_vertex`; `HZ_ORIGIN_DECL` and +/// `HZ_ORIGIN` are the variant's (instanced or flat draws). +const GLUE: &str = r#" +layout(location = 0) in vec3 hz_position; +layout(location = 1) in uvec2 hz_uv; +layout(location = 2) in uint hz_layer; +layout(location = 3) in vec4 hz_color; +layout(location = 4) in uvec2 hz_light; +HZ_ORIGIN_DECL +layout(std430, set = 3, binding = 0) readonly buffer HzVertices { uint hz_vertices[]; }; +// [0]: atlas columns, [1]: 1 in the Nether, then each sprite layer's block id. +layout(std430, set = 3, binding = 1) readonly buffer HzTable { int hz_table[]; }; +vec4 hz_pos; +vec3 hz_normal; +vec4 hz_tangent; +vec4 hz_tint; +vec2 hz_atlas; +vec2 hz_mid; +vec2 hz_lightmap; +float hz_block; +vec3 hz_mid_block; +vec3 hz_corner(uint v) { + uint b = v * HZ_WORDSu; + return vec3(uintBitsToFloat(hz_vertices[b]), uintBitsToFloat(hz_vertices[b + 1u]), + uintBitsToFloat(hz_vertices[b + 2u])); +} +vec2 hz_corner_uv(uint v) { + uint w = hz_vertices[v * HZ_WORDSu + 3u]; + return vec2(float(w & 65535u), float(w >> 16u)); +} +void hz_vertex() { + vec4 origin = HZ_ORIGIN; + hz_pos = vec4(hz_position + origin.xyz, 1.0); + // The quad's corners: quads are four vertices from a multiple of four. + uint q = uint(gl_VertexIndex) & 4294967292u; + vec3 p0 = hz_corner(q); + vec3 e1 = hz_corner(q + 1u) - p0; + vec3 e2 = hz_corner(q + 2u) - p0; + vec3 n = cross(e1, e2); + if (dot(n, n) < 1e-12) { + n = cross(e2, hz_corner(q + 3u) - p0); + } + hz_normal = dot(n, n) > 0.0 ? normalize(n) : vec3(0.0, 1.0, 0.0); + vec2 t0 = hz_corner_uv(q); + vec2 d1 = hz_corner_uv(q + 1u) - t0; + vec2 d2 = hz_corner_uv(q + 2u) - t0; + float s = d1.x * d2.y - d2.x * d1.y < 0.0 ? -1.0 : 1.0; + vec3 t = (e1 * d2.y - e2 * d1.y) * s; + vec3 b = (e2 * d1.x - e1 * d2.x) * s; + t = t - hz_normal * dot(hz_normal, t); + t = dot(t, t) > 0.0 ? normalize(t) : vec3(1.0, 0.0, 0.0); + hz_tangent = vec4(t, dot(cross(hz_normal, t), b) < 0.0 ? -1.0 : 1.0); + // Iris turns vanilla's directional shade off: undo it on axis faces. + vec3 a = abs(hz_normal); + bool nether = hz_table[1] != 0; + float shade = 1.0; + if (a.y > 0.999) { + shade = nether ? 0.9 : (hz_normal.y > 0.0 ? 1.0 : 0.5); + } else if (a.z > 0.999) { + shade = 0.8; + } else if (a.x > 0.999) { + shade = 0.6; + } + hz_tint = vec4(min(hz_color.rgb / shade, vec3(1.0)), hz_color.a); + // The sprite's cell in the atlas, columns of square cells. + int layer = int(hz_layer & 16383u); + int cols = max(hz_table[0], 1); + vec2 cell = vec2(float(layer % cols), float(layer / cols)); + vec2 uv = clamp(vec2(hz_uv) * origin.w, 0.0, 1.0); + hz_atlas = (cell + uv) / float(cols); + hz_mid = (cell + 0.5) / float(cols); + // Vanilla's UV2: block light, then sky light, 0..240. + hz_lightmap = vec2(float(hz_light.y), float(hz_light.x)); + hz_block = float(hz_table[2 + layer]); + hz_mid_block = (floor(hz_position - hz_normal * 0.01) + 0.5 - hz_position) * 64.0; +} +"#; + +/// The glue of one draw path: instanced section draws (the origin is an +/// instance attribute) or flat ones (`gfx/flat.rs`: from the block's slot). +pub fn glue(flat: bool, alpha_test: Option) -> Geometry { + let (decl, origin) = if flat { + ( + "layout(std430, set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\ + layout(std430, set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };", + "hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]", + ) + } else { + ("layout(location = 5) in vec4 hz_origin;", "hz_origin") + }; + let vertex_glue = GLUE + .replace("HZ_ORIGIN_DECL", decl) + .replace("HZ_ORIGIN", origin) + .replace("HZ_WORDS", &VERTEX_WORDS.to_string()); + let lightmap = "vec4(hz_lightmap, 0.0, 1.0)"; + let attributes: BTreeMap = [ + ("iris_Vertex", "hz_pos"), + ("vaPosition", "hz_pos"), + ("iris_Normal", "vec4(hz_normal, 0.0)"), + ("vaNormal", "vec4(hz_normal, 0.0)"), + ("iris_Color", "hz_tint"), + ("vaColor", "hz_tint"), + ("iris_MultiTexCoord0", "vec4(hz_atlas, 0.0, 1.0)"), + ("vaUV0", "vec4(hz_atlas, 0.0, 1.0)"), + ("iris_MultiTexCoord1", lightmap), + ("iris_MultiTexCoord2", lightmap), + ("vaUV2", lightmap), + // OverlayTexture.NO_OVERLAY. + ("vaUV1", "vec4(0.0, 10.0, 0.0, 0.0)"), + ("mc_Entity", "vec4(hz_block, -1.0, 0.0, 0.0)"), + ("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"), + ("at_tangent", "hz_tangent"), + ("at_midBlock", "vec4(hz_mid_block, 0.0)"), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + Geometry { + vertex_glue, + attributes, + alpha_test, + } +} + +/// The glue's table: atlas columns, the Nether flag, then each sprite +/// layer's block id from `block.properties` (-1 for blocks it doesn't +/// list, as Iris). +pub fn table(sprite_layers: &BTreeMap, block_ids: &BTreeMap) -> Vec { + let layers = sprite_layers.values().max().map_or(0, |&m| m as usize + 1); + let mut out = vec![-1; layers + 2]; + out[0] = atlas_columns(layers as u32) as i32; + out[1] = 0; + for (name, &layer) in sprite_layers { + if let Some(id) = horizon_shaderpack::properties::sprite_block_id(name, block_ids) { + out[layer as usize + 2] = id; + } + } + out +} + +/// The atlas's columns (and rows) of sprite cells for `layers` sprites. +pub fn atlas_columns(layers: u32) -> u32 { + (f64::from(layers.max(1)).sqrt().ceil() as u32).max(1) +} + +/// Whether `device` renders to and filters the 16-bit normalized formats +/// a Java pack's `RGBA16` targets become (`java_stages::target_format`). +pub fn norm16_targets(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + use wgpu::TextureFormat as F; + let wanted = wgpu::Features::TEXTURE_FORMAT_16BIT_NORM + | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES; + device.features().contains(wanted) + && [ + F::R16Unorm, + F::Rg16Unorm, + F::Rgba16Unorm, + F::R16Snorm, + F::Rg16Snorm, + F::Rgba16Snorm, + ] + .into_iter() + .all(|f| { + let features = adapter.get_texture_format_features(f); + features + .allowed_usages + .contains(wgpu::TextureUsages::RENDER_ATTACHMENT) + && features + .flags + .contains(wgpu::TextureFormatFeatureFlags::FILTERABLE) + }) +} + +/// The bind group layout of a page group: the page's vertices and the glue's +/// table, read by the vertex stage. +pub fn page_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + let storage = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack terrain page"), + entries: &[storage(0), storage(1)], + }) +} + +/// 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; + +/// 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 +/// flat path's, group 3 the page's ([`page_layout`]). `flat` is `None` when +/// the renderer has no flat draws. +pub struct TerrainPipelines<'a> { + pub instanced: &'a wgpu::RenderPipeline, + pub flat: Option<&'a wgpu::RenderPipeline>, + pub group: &'a wgpu::BindGroup, +} + +/// What a Java pack's geometry reads from the renderer each frame. +pub struct JavaWorld<'a> { + /// The block sprite arrays, [`super::SPRITE_SPLIT`]-layer each. + pub sprites: &'a [wgpu::Texture], + pub split: u32, + /// Mipmap levels the terrain samples. + pub levels: u32, + /// The sprite layers and mip levels animation rewrote this frame. + pub animated: &'a [(u32, u32)], + pub lightmap: &'a wgpu::TextureView, + pub draw: &'a DrawTerrain<'a>, +} + +const ATLAS: &str = r#" +struct Atlas { cols: u32, layers: u32, split: u32, pad: u32 } +@group(0) @binding(0) var atlas: Atlas; +@group(0) @binding(1) var s0: texture_2d_array; +@group(0) @binding(2) var s1: texture_2d_array; +@group(0) @binding(3) var s2: texture_2d_array; +@group(0) @binding(4) var s3: texture_2d_array; +@group(0) @binding(5) var s4: texture_2d_array; +@group(0) @binding(6) var s5: texture_2d_array; +@group(0) @binding(7) var s6: texture_2d_array; +@group(0) @binding(8) var s7: texture_2d_array; + +struct Out { + @builtin(position) p: vec4f, + @location(0) @interpolate(flat) mip: u32, +} + +@vertex +fn vs(@builtin(vertex_index) i: u32, @builtin(instance_index) mip: u32) -> Out { + let uv = vec2f(f32((i << 1u) & 2u), f32(i & 2u)); + return Out(vec4f(uv * 2.0 - 1.0, 0.0, 1.0), mip); +} + +// Each sprite layer into its cell, at mip level `mip`. +@fragment +fn fs(in: Out) -> @location(0) vec4f { + let cell = max(textureDimensions(s0, in.mip).x, 1u); + let px = vec2u(in.p.xy); + let c = px / cell; + let layer = c.y * atlas.cols + c.x; + if c.x >= atlas.cols || layer >= atlas.layers { + return vec4f(0.0); + } + let at = px % cell; + let l = i32(layer % atlas.split); + let m = i32(in.mip); + switch layer / atlas.split { + case 0u: { return textureLoad(s0, at, l, m); } + case 1u: { return textureLoad(s1, at, l, m); } + case 2u: { return textureLoad(s2, at, l, m); } + case 3u: { return textureLoad(s3, at, l, m); } + case 4u: { return textureLoad(s4, at, l, m); } + case 5u: { return textureLoad(s5, at, l, m); } + case 6u: { return textureLoad(s6, at, l, m); } + default: { return textureLoad(s7, at, l, m); } + } +} +"#; + +/// Horizon's block sprites as one 2D atlas, as Iris binds `gtexture`: +/// square cells, [`atlas_columns`] to a row. Drawn from the sprite arrays +/// once, then animated sprites are copied in as they change. +pub struct Atlas { + texture: wgpu::Texture, + pub view: wgpu::TextureView, + mips: Vec, + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + uniform: wgpu::Buffer, + /// Layers, sprite size, mip levels it was made for. + key: (u32, u32, u32), + /// The first sprite array it was drawn from (resource reloads make + /// new ones). + source: wgpu::Texture, + drawn: bool, +} + +impl Atlas { + /// The atlas for `world`'s sprites; `None` without any. + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, world: &JavaWorld) -> Option { + let key = Self::key(world)?; + let (layers, size, levels) = key; + let cols = atlas_columns(layers); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Java shader pack block atlas"), + size: wgpu::Extent3d { + width: cols * size, + height: cols * size, + depth_or_array_layers: 1, + }, + mip_level_count: levels, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let mips = (0..levels) + .map(|level| { + texture.create_view(&wgpu::TextureViewDescriptor { + base_mip_level: level, + mip_level_count: Some(1), + ..Default::default() + }) + }) + .collect(); + let mut entries = vec![wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }]; + entries.extend((1..=8).map(|binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2Array, + multisampled: false, + }, + count: None, + })); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack block atlas"), + entries: &entries, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Java shader pack block atlas"), + source: wgpu::ShaderSource::Wgsl(ATLAS.into()), + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Java shader pack block atlas"), + layout: Some( + &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Java shader pack block atlas"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }), + ), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())], + }), + multiview_mask: None, + cache: None, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack block atlas"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer( + &uniform, + 0, + bytemuck::cast_slice(&[cols, layers, world.split.max(1), 0]), + ); + Some(Self { + view: texture.create_view(&Default::default()), + texture, + mips, + pipeline, + layout, + uniform, + key, + source: world.sprites[0].clone(), + drawn: false, + }) + } + + fn key(world: &JavaWorld) -> Option<(u32, u32, u32)> { + let first = world.sprites.first()?; + let layers = world + .sprites + .iter() + .map(|t| t.depth_or_array_layers()) + .sum(); + let levels = (world.levels + 1).min(first.mip_level_count()).max(1); + Some((layers, first.width(), levels)) + } + + /// Whether it was made for `world`'s sprites. + pub fn fits(&self, world: &JavaWorld) -> bool { + Self::key(world) == Some(self.key) && world.sprites.first() == Some(&self.source) + } + + /// Bring it up to date: drawn the first time, then the sprites + /// animation rewrote copied into their cells. + pub fn update( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + world: &JavaWorld, + ) { + if !self.drawn { + self.draw(device, encoder, world); + self.drawn = true; + return; + } + let (layers, size, levels) = self.key; + let cols = atlas_columns(layers); + let split = world.split.max(1); + for &(layer, level) in world.animated { + let Some(array) = world.sprites.get((layer / split) as usize) else { + continue; + }; + if level >= levels || layer >= layers { + continue; + } + let edge = (size >> level).max(1); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: array, + mip_level: level, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: layer % split, + }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &self.texture, + mip_level: level, + origin: wgpu::Origin3d { + x: (layer % cols) * edge, + y: (layer / cols) * edge, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { + width: edge, + height: edge, + depth_or_array_layers: 1, + }, + ); + } + } + + /// The atlas's size in pixels (`atlasSize`). + pub fn size(&self) -> [u32; 2] { + [self.texture.width(), self.texture.height()] + } + + /// Draw the sprites into the atlas, every mip level. + fn draw(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, world: &JavaWorld) { + let views: Vec = (0..8) + .map(|i| { + let t = world.sprites.get(i).unwrap_or(&world.sprites[0]); + t.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + mip_level_count: Some(self.key.2), + ..Default::default() + }) + }) + .collect(); + let mut entries = vec![wgpu::BindGroupEntry { + binding: 0, + resource: self.uniform.as_entire_binding(), + }]; + entries.extend(views.iter().enumerate().map(|(i, v)| wgpu::BindGroupEntry { + binding: i as u32 + 1, + resource: wgpu::BindingResource::TextureView(v), + })); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack block atlas"), + layout: &self.layout, + entries: &entries, + }); + for (mip, view) in self.mips.iter().enumerate() { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack block atlas"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &group, &[]); + pass.draw(0..3, mip as u32..mip as u32 + 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `module` validates and translates for Metal, Vulkan and DirectX 12. + fn backends(module: &naga::Module, label: &str) { + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(module) + .unwrap_or_else(|e| panic!("{label}: {e:?}")); + naga::back::msl::write_string( + module, + &info, + // wgpu's Metal backend asks for MSL 2.x. + &naga::back::msl::Options { + lang_version: (2, 4), + ..Default::default() + }, + &naga::back::msl::PipelineOptions::default(), + ) + .unwrap_or_else(|e| panic!("{label} (MSL): {e}")); + naga::back::spv::write_vec(module, &info, &Default::default(), None) + .unwrap_or_else(|e| panic!("{label} (SPIR-V): {e}")); + for entry in &module.entry_points { + let mut hlsl = String::new(); + naga::back::hlsl::Writer::new( + &mut hlsl, + &naga::back::hlsl::Options::default(), + &naga::back::hlsl::PipelineOptions { + entry_point: Some((entry.stage, entry.name.clone())), + }, + ) + .write(module, &info, None) + .unwrap_or_else(|e| panic!("{label} {} (HLSL): {e}", entry.name)); + } + } + + /// A terrain program reading every attribute the glue fills, run after + /// each draw path's glue, and the atlas shader, on every backend. + #[test] + fn the_glue_feeds_a_terrain_program_on_every_backend() { + let program = "#version 120 +attribute vec4 mc_Entity; +attribute vec4 mc_midTexCoord; +attribute vec4 at_tangent; +attribute vec3 at_midBlock; +varying vec4 color; +varying vec2 uv; +varying vec2 lm; +varying vec3 normal; +varying float id; +void main() { + vec4 p = gl_ModelViewMatrix * gl_Vertex; + p.xyz += at_midBlock / 64.0 * 0.0 + at_tangent.xyz * 0.0; + gl_Position = gl_ProjectionMatrix * p; + color = gl_Color; + uv = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy + mc_midTexCoord.xy * 0.0; + lm = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + normal = gl_NormalMatrix * gl_Normal; + id = mc_Entity.x; +} +"; + for flat in [false, true] { + let mut link = horizon_shaderpack::translate::Link { + set: 2, + geometry: Some(glue(flat, Some(0.1))), + ..Default::default() + }; + let t = horizon_shaderpack::translate::translate( + horizon_shaderpack::Stage::Vertex, + program, + &mut link, + &|l| format!("line {l}"), + ) + .unwrap_or_else(|e| panic!("flat {flat}: {e}")); + for wanted in ["hz_vertex();", "mc_Entity = vec4(vec4(hz_block"] { + assert!(t.glsl.contains(wanted), "{wanted}\n{}", t.glsl); + } + // The glue's inputs are Horizon's vertex layout. + let inputs = t.module.entry_points[0].function.arguments.len(); + assert_eq!(inputs, if flat { 6 } else { 7 }, "{}", t.wgsl); + let reparsed = naga::front::wgsl::parse_str(&t.wgsl).unwrap(); + backends(&reparsed, &format!("terrain glue (flat {flat})")); + } + backends(&naga::front::wgsl::parse_str(ATLAS).unwrap(), "atlas"); + backends( + &naga::front::wgsl::parse_str(super::super::java_stages::BLIT).unwrap(), + "Java shader pack blits", + ); + } + + #[test] + fn sprites_take_their_blocks_ids() { + let layers: BTreeMap = [ + ("minecraft:block/oak_leaves", 0), + ("minecraft:block/water_still", 1), + ("minecraft:block/stone", 2), + ("minecraft:block/oak_log_top", 3), + ] + .into_iter() + .map(|(n, l)| (n.to_owned(), l)) + .collect(); + let ids: BTreeMap = [("oak_leaves", 10003), ("water", 8), ("oak_log", 7)] + .into_iter() + .map(|(n, i)| (n.to_owned(), i)) + .collect(); + assert_eq!(table(&layers, &ids), [2, 0, 10003, 8, -1, 7]); + assert_eq!(atlas_columns(5), 3); + assert_eq!(atlas_columns(0), 1); + } +} diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index e6bd28c7f..f0a1b85f0 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -2,11 +2,12 @@ //! a folder holding `shaders/`, or a `.zip`. `horizon-shaderpack` translates //! their full-screen programs (`begin`, `prepare`, `deferred`, `composite`, //! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world -//! as Iris runs them over its own. Geometry programs (`gbuffers_*`, -//! `shadow`) don't run yet: the world is drawn by Horizon. +//! as Iris runs them over its own. Of the geometry programs, the terrain's +//! (`gbuffers_terrain`, `gbuffers_water` and their fallbacks) draw Horizon's +//! terrain (`gfx/java_terrain.rs`); the rest of the world is Horizon's. use horizon_shaderpack::{ JavaPack, - pipeline::{Directives, Program, TargetSettings}, + pipeline::{Directives, GeometryProgram, Program, TargetSettings}, preprocess::Environment, properties::SkyDirectives, uniforms::CustomUniforms, @@ -32,6 +33,17 @@ pub struct JavaFolder { pub flipped_at_end: BTreeSet, /// `sunPathRotation` and `eyeBrightnessHalflife`. pub directives: Directives, + /// The programs Horizon's solid and translucent terrain are drawn with, + /// each translated for instanced and flat draws (`variants[0]`). + pub terrain: Option, + pub water: Option, + /// How many of `passes` run before translucent terrain (`begin*`, + /// `prepare*`, `deferred*`). + pub translucent_at: usize, + pub flipped_after_translucent: BTreeSet, + /// Each draw buffer's blending in `terrain` and `water`. + pub terrain_blends: Vec>, + pub water_blends: Vec>, } /// A loaded Java pack. @@ -41,6 +53,8 @@ pub struct JavaPasses { pub uniforms: CustomUniforms, /// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`). pub sky: SkyDirectives, + /// `block.properties`: block name → `mc_Entity` id. + pub block_ids: BTreeMap, } impl JavaPasses { @@ -122,6 +136,50 @@ pub fn load( if passes.is_empty() && final_pass.is_none() { continue; } + // A geometry program that doesn't translate leaves that terrain to + // Horizon, with a warning. + let geometry = |pass: &Option, alpha_test| { + let pass = pass.as_ref()?; + let glues = [false, true].map(|flat| crate::gfx::java_terrain::glue(flat, alpha_test)); + match pack.compile_geometry(pass, &plan.targets, &values, &env, &properties, &glues) { + Ok(program) => Some(program), + Err(e) => { + log::warn!("Horizon: shader pack {}: {e}", pass.program); + None + } + } + }; + // Iris's alpha test of cutout terrain (`AlphaTests.ONE_TENTH_ALPHA`). + let terrain = geometry(&plan.terrain, Some(0.1)); + let water = terrain.as_ref().and_then(|_| geometry(&plan.water, None)); + let translucent_at = early.clone().count() + plan.deferred.len(); + let blends = |g: &Option, default| { + g.as_ref().map_or_else(Vec::new, |g| { + geometry_blends( + &properties, + &g.program.pass.program, + &g.program.draw_buffers, + default, + ) + }) + }; + let terrain_blends = blends(&terrain, None); + // Vanilla's translucent blending (`BlendFunction.TRANSLUCENT`). + let water_blends = blends( + &water, + Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }), + ); folders.push(JavaFolder { folder: name.to_owned(), targets: plan.targets, @@ -131,6 +189,12 @@ pub fn load( final_pass, flipped_at_end: plan.flipped_at_end, directives: plan.directives, + terrain, + water, + translucent_at, + flipped_after_translucent: plan.flipped_after_translucent, + terrain_blends, + water_blends, }); } if folders.is_empty() { @@ -140,10 +204,84 @@ pub fn load( for problem in &uniforms.problems { log::warn!("Horizon: shader pack custom uniform {problem}"); } + let block_ids = pack.block_ids(&values, &env).unwrap_or_else(|e| { + log::warn!("Horizon: shader pack {e}"); + BTreeMap::new() + }); Ok(JavaPasses { folders, uniforms, sky: properties.sky(), + block_ids, + }) +} + +/// A geometry program's blending per draw buffer: `default`, or the +/// pack's `blend.` and `blend..` (Iris's +/// `BlendModeOverride`; the folder isn't part of the name). +fn geometry_blends( + properties: &horizon_shaderpack::properties::ShaderProperties, + program: &str, + draw_buffers: &[u32], + default: Option, +) -> Vec> { + use horizon_shaderpack::properties::Blend; + let name = program.rsplit('/').next().unwrap_or(program); + let state = |blend: &Result| match blend { + Ok(Blend::Off) => Some(None), + Ok(Blend::Factors(f)) => { + let [a, b, c, d] = f.each_ref().map(|f| blend_factor(f)); + Some(Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: a?, + dst_factor: b?, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: c?, + dst_factor: d?, + operation: wgpu::BlendOperation::Add, + }, + })) + } + Err(e) => { + log::warn!("Horizon: shader pack blend.{name}: {e}"); + None + } + }; + let all = properties + .blend(name) + .and_then(|b| state(&b)) + .unwrap_or(default); + let buffers = properties.buffer_blends(name); + draw_buffers + .iter() + .map(|i| { + buffers + .iter() + .find(|(b, _)| b == i) + .and_then(|(_, b)| state(b)) + .unwrap_or(all) + }) + .collect() +} + +/// A GL blend factor's wgpu one. +fn blend_factor(name: &str) -> Option { + use wgpu::BlendFactor as F; + Some(match name { + "ZERO" => F::Zero, + "ONE" => F::One, + "SRC_COLOR" => F::Src, + "ONE_MINUS_SRC_COLOR" => F::OneMinusSrc, + "DST_COLOR" => F::Dst, + "ONE_MINUS_DST_COLOR" => F::OneMinusDst, + "SRC_ALPHA" => F::SrcAlpha, + "ONE_MINUS_SRC_ALPHA" => F::OneMinusSrcAlpha, + "DST_ALPHA" => F::DstAlpha, + "ONE_MINUS_DST_ALPHA" => F::OneMinusDstAlpha, + "SRC_ALPHA_SATURATE" => F::SrcAlphaSaturated, + _ => return None, }) } @@ -186,8 +324,18 @@ mod tests { .folders .iter() .flat_map(|f| f.passes.iter().chain(&f.final_pass)); + let geometry = pack + .folders + .iter() + .flat_map(|f| f.terrain.iter().chain(&f.water)); passes .flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]) + .chain(geometry.flat_map(|g| { + let p = &g.program; + [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")] + .into_iter() + .chain(g.variants.iter().map(move |v| (p, v, "vsh (flat)"))) + })) .find_map(|(p, t, ext)| { let e = naga::front::wgsl::parse_str(&t.wgsl).err()?; Some(format!( @@ -227,7 +375,13 @@ mod tests { .iter() .map(|f| { let n = f.passes.len() + usize::from(f.final_pass.is_some()); - format!("{} {n} passes", f.folder) + let geometry: Vec<&str> = f + .terrain + .iter() + .chain(&f.water) + .map(|g| g.program.pass.program.as_str()) + .collect(); + format!("{} {n} passes, terrain {geometry:?}", f.folder) }) .collect(); println!("{name}: loads ({})", folders.join(", ")); diff --git a/crates/horizon-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs index 71b6abbd3..981cbc654 100644 --- a/crates/horizon-shaderpack/src/lib.rs +++ b/crates/horizon-shaderpack/src/lib.rs @@ -156,6 +156,22 @@ impl JavaPack { } } +impl JavaPack { + /// The block ids of the pack's `block.properties` (empty without one), + /// [`properties::block_ids`]. + pub fn block_ids( + &self, + values: &OptionValues, + env: &Environment, + ) -> Result, String> { + match self.files.read("block.properties") { + Some(text) => properties::block_ids(&text, env, &self.options, values) + .map_err(|e| format!("block.properties: {e}")), + None => Ok(BTreeMap::new()), + } + } +} + /// A program's name in `shaders.properties` (`world-1/composite1.fsh` is /// `world-1/composite1`). pub fn program_name(program: &str) -> &str { diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index 7ebb35442..bcc1f310d 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -12,7 +12,7 @@ use crate::{ options::OptionValues, preprocess::Environment, properties::{LEGACY_TARGETS, ShaderProperties}, - translate::{Link, Translated}, + translate::{Geometry, Link, Translated}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -319,8 +319,33 @@ pub struct Passes { /// next frame starts unflipped. pub flipped_at_end: BTreeSet, pub directives: Directives, + /// The program Horizon's solid terrain is drawn with + /// ([`TERRAIN_PROGRAMS`]), before `deferred`. + pub terrain: Option, + /// The program its translucent terrain is drawn with + /// ([`WATER_PROGRAMS`]), after `deferred`. + pub water: Option, } +/// The programs Iris draws solid terrain with, the first the pack has +/// (`ProgramId.Terrain`'s fallbacks). +pub const TERRAIN_PROGRAMS: &[&str] = &[ + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + +/// The programs Iris draws translucent terrain with (`ProgramId.Water`'s +/// fallbacks). +pub const WATER_PROGRAMS: &[&str] = &[ + "gbuffers_water", + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + /// The `const` directives of a program folder that aren't about targets /// (`PackDirectives`), read from the same programs in the same order. #[derive(Clone, Copy, Debug, PartialEq)] @@ -510,6 +535,22 @@ impl JavaPack { out.flipped_after_translucent = flipped.clone(); out.composite = run(&groups[3], "composite_pre", &mut flipped)?; out.flipped_at_end = flipped; + // Geometry writes the side the next passes read. + let geometry = |chain: &[&str], flipped: &BTreeSet| { + let Some(name) = chain.iter().find(|n| exists(n)) else { + return Ok::<_, String>(None); + }; + let text = fragment(name)?; + Ok(Some(Pass { + program: path(name), + draw_buffers: draw_buffers(&text).map_err(|e| format!("{}: {e}", path(name)))?, + reads_alt: flipped.clone(), + mipmapped: BTreeSet::new(), + scale: 1.0, + })) + }; + out.terrain = geometry(TERRAIN_PROGRAMS, &out.flipped_after_prepare)?; + out.water = geometry(WATER_PROGRAMS, &out.flipped_after_translucent)?; if exists("final") { out.final_pass = Some(Pass { program: path("final"), @@ -566,6 +607,70 @@ impl JavaPack { } } +/// A geometry program translated: the program (its vertex with the first +/// glue), and its vertex with each other glue. +pub struct GeometryProgram { + pub program: Program, + pub variants: Vec, +} + +impl JavaPack { + /// Translate geometry program `pass` (`gbuffers_*`) to run over + /// Horizon's geometry: its bindings in group 2, its attributes from + /// each of `glues` (the vertex program is translated once per glue). + #[allow(clippy::too_many_arguments)] + pub fn compile_geometry( + &self, + pass: &Pass, + targets: &[TargetSettings], + values: &OptionValues, + env: &Environment, + properties: &ShaderProperties, + glues: &[Geometry], + ) -> Result { + let (first, rest) = glues + .split_first() + .ok_or("a geometry program needs a glue")?; + let mut link = Link { + image_formats: properties.image_formats(), + shared_samplers: shared_samplers(targets), + set: 2, + geometry: Some(first.clone()), + ..Link::default() + }; + let vertex = self.translate(&format!("{}.vsh", pass.program), values, env, &mut link)?; + let fragment = self.translate(&format!("{}.fsh", pass.program), values, env, &mut link)?; + let mut variants = Vec::new(); + for glue in rest { + let mut other = link.clone(); + other.geometry = Some(glue.clone()); + variants.push(self.translate( + &format!("{}.vsh", pass.program), + values, + env, + &mut other, + )?); + if other.uniforms != link.uniforms || other.bindings != link.bindings { + return Err(format!("{}: its variants bind differently", pass.program)); + } + } + let draw_buffers = match &pass.draw_buffers { + Some(buffers) => buffers.clone(), + None => (0..fragment.interface.outputs.keys().max().map_or(1, |m| m + 1)).collect(), + }; + Ok(GeometryProgram { + program: Program { + pass: pass.clone(), + vertex, + fragment, + draw_buffers, + link, + }, + variants, + }) + } +} + /// Iris's sampler states for the textures it binds: colour targets /// linear (nearest for integer formats, and for 32-bit floats, which wgpu /// can't filter everywhere), depth nearest, noise repeating. For diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 703d696cf..548fee50f 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -587,6 +587,58 @@ impl ShaderProperties { } } +/// `block.properties` (`block.=`), preprocessed as +/// `shaders.properties` is: each block's id by its name without namespace +/// (`oak_leaves`). A block listed with a state (`grass_block:snowy=true`) +/// takes that id only when no entry names it without one; numeric ids +/// (before 1.13) are skipped. +pub fn block_ids( + text: &str, + env: &Environment, + options: &OptionSet, + values: &OptionValues, +) -> Result, String> { + let properties = Properties::parse(&preprocess(text, env, options, values)?); + let mut plain = BTreeMap::new(); + let mut with_state = BTreeMap::new(); + for (key, value) in properties.iter() { + let Some(Ok(id)) = key.strip_prefix("block.").map(str::parse::) else { + continue; + }; + for entry in value.split_whitespace() { + let entry = entry.strip_prefix("minecraft:").unwrap_or(entry); + if entry.contains(':') && entry.split(':').nth(1).is_some_and(|s| s.contains('=')) { + let name = entry.split(':').next().unwrap_or(entry); + with_state.entry(name.to_owned()).or_insert(id); + } else if !entry.chars().all(|c| c.is_ascii_digit()) && !entry.contains('=') { + plain.insert(entry.to_owned(), id); + } + } + } + for (name, id) in with_state { + plain.entry(name).or_insert(id); + } + Ok(plain) +} + +/// The block a block sprite (`minecraft:block/oak_log_top`) belongs to in +/// `ids` ([`block_ids`]): the block named like it, else the longest one its +/// name starts with followed by `_` (`oak_log`, `water` for `water_still`). +pub fn sprite_block_id(sprite: &str, ids: &BTreeMap) -> Option { + let name = sprite.rsplit(['/', ':']).next()?; + if let Some(&id) = ids.get(name) { + return Some(id); + } + let mut end = name.len(); + while let Some(cut) = name[..end].rfind('_') { + if let Some(&id) = ids.get(&name[..cut]) { + return Some(id); + } + end = cut; + } + None +} + /// Iris's `BooleanParser`: options joined by `!`, `&&`, `||` and brackets, /// `&&` binding tighter. `true`/`1` and `false`/`0` are literals; a name that /// isn't a boolean option is true; a malformed expression is true. @@ -705,6 +757,42 @@ mod tests { set } + /// `block.properties` as Chocapic13' writes it, and sprites matched to + /// its blocks. + #[test] + fn block_ids_and_the_sprites_of_their_blocks() { + let text = "\ +#if MC_VERSION >= 11300 +block.10001= minecraft:wheat minecraft:short_grass +block.10003 = minecraft:oak_leaves \\ + minecraft:vine +block.10006 = minecraft:grass_block:snowy=true minecraft:snow +block.8 = minecraft:water +block.2 = minecraft:grass_block +#else +block.10001= 6 31 +#endif +layer.translucent=minecraft:glass +"; + let env = Environment { + defines: vec![("MC_VERSION".into(), "260300".into())], + }; + let ids = block_ids(text, &env, &OptionSet::default(), &OptionValues::default()).unwrap(); + assert_eq!(ids.get("vine"), Some(&10003)); + // The stateless entry wins over the snowy one. + assert_eq!(ids.get("grass_block"), Some(&2)); + assert!(!ids.contains_key("6") && !ids.contains_key("glass")); + for (sprite, id) in [ + ("minecraft:block/oak_leaves", Some(10003)), + ("minecraft:block/water_still", Some(8)), + ("minecraft:block/grass_block_top", Some(2)), + ("minecraft:block/wheat_stage7", Some(10001)), + ("minecraft:block/stone", None), + ] { + assert_eq!(sprite_block_id(sprite, &ids), id, "{sprite}"); + } + } + #[test] fn java_properties_syntax() { let p = Properties::parse( diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index e53b4895b..208fe84b5 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -40,7 +40,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; /// Locations, bindings and uniforms shared by the programs of one pass: a /// pass's vertex program is translated first, its fragment program second. -#[derive(Default, Debug)] +#[derive(Clone, Default, Debug)] pub struct Link { /// Varying name → location (split matrices and arrays as `name#i`). pub varyings: BTreeMap, @@ -59,6 +59,27 @@ pub struct Link { /// 16). Once any is named, comparison samplers share `iris_compare` and /// integer ones `iris_nearest`; textures not named keep `{name}_s`. pub shared_samplers: BTreeMap, + /// The bind group of the pack's bindings (0; 2 for geometry programs, + /// whose first groups are Horizon's). + pub set: u32, + /// Set for `gbuffers_*` programs drawn over Horizon's own geometry. + pub geometry: Option, +} + +/// How a `gbuffers_*` program runs over Horizon's geometry: its vertex +/// attributes aren't inputs but globals the glue fills from Horizon's +/// vertices before the program's `main`. +#[derive(Clone, Debug, Default)] +pub struct Geometry { + /// GLSL put before the vertex program: Horizon's vertex inputs and + /// buffers, and a `void hz_vertex()` run first in `main`. + pub vertex_glue: String, + /// Each attribute's value as a `vec4` expression of the glue + /// (`iris_Vertex`, `mc_Entity`, `vaUV0`...). Others are zero. + pub attributes: BTreeMap, + /// Iris's alpha test: the fragment is discarded unless output 0's + /// alpha is above it. + pub alpha_test: Option, } impl Link { @@ -368,6 +389,7 @@ pub fn translate( .parse(&options, &glsl) .map_err(|e| first_lines(&e.emit_to_string(&glsl)))?; unpad_private_arrays(&mut module); + end_returning_cases(&mut module); let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all(), @@ -387,6 +409,49 @@ pub fn translate( }) } +/// A `case` that ends with `return` or `discard` rather than `break` +/// (Photon's displacement) is a fall-through one to naga's GLSL front end, +/// which its WGSL writer refuses: nothing falls through it. +fn end_returning_cases(module: &mut naga::Module) { + fn block(b: &mut naga::Block) { + for s in b.iter_mut() { + match s { + naga::Statement::Block(inner) => block(inner), + naga::Statement::If { accept, reject, .. } => { + block(accept); + block(reject); + } + naga::Statement::Loop { + body, continuing, .. + } => { + block(body); + block(continuing); + } + naga::Statement::Switch { cases, .. } => { + for case in cases { + block(&mut case.body); + if case.fall_through + && matches!( + case.body.last(), + Some(naga::Statement::Return { .. } | naga::Statement::Kill) + ) + { + case.fall_through = false; + } + } + } + _ => {} + } + } + } + for (_, f) in module.functions.iter_mut() { + block(&mut f.body); + } + for e in &mut module.entry_points { + block(&mut e.function.body); + } +} + /// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it /// implements), besides type constructors. const FOLDABLE: &[&str] = &[ @@ -612,6 +677,8 @@ struct Legaliser<'a> { gather: bool, /// Constants turned into globals ([`needs_runtime`]). runtime_constants: HashSet, + /// Geometry programs: each attribute's type, for the glue. + attribute_types: BTreeMap, } fn var(name: &str) -> ast::Expr { @@ -897,6 +964,7 @@ impl<'a> Legaliser<'a> { nan: false, gather: false, runtime_constants: HashSet::new(), + attribute_types: BTreeMap::new(), } } @@ -969,7 +1037,8 @@ impl<'a> Legaliser<'a> { show_declaration(&mut text, d, &mut FormattingState::default()) .map_err(|e| e.to_string())?; self.header.push(format!( - "layout({kind}, set = 0, binding = {binding}) {}", + "layout({kind}, set = {}, binding = {binding}) {}", + self.link.set, text.trim() )); Ok(false) @@ -1028,7 +1097,8 @@ impl<'a> Legaliser<'a> { for (name, _) in &names { let t = self.link.binding(&format!("{name}_t")); self.header.push(format!( - "layout(set = 0, binding = {t}) uniform {texture} {name}_t;" + "layout(set = {}, binding = {t}) uniform {texture} {name}_t;", + self.link.set )); let shared = &self.link.shared_samplers; let var = if shared.is_empty() { @@ -1046,7 +1116,8 @@ impl<'a> Legaliser<'a> { if self.sampler_vars.insert(var.clone()) { let s = self.link.binding(&var); self.header.push(format!( - "layout(set = 0, binding = {s}) uniform {sampler} {var};" + "layout(set = {}, binding = {s}) uniform {sampler} {var};", + self.link.set )); } self.interface @@ -1085,7 +1156,8 @@ impl<'a> Legaliser<'a> { .unwrap_or_else(|| "rgba8".to_owned()); let binding = self.link.binding(name); layout.push(format!( - "layout({f}, set = 0, binding = {binding}) {memory}uniform {ty} {name};" + "layout({f}, set = {}, binding = {binding}) {memory}uniform {ty} {name};", + self.link.set )); self.interface.images.push((name.clone(), f)); } @@ -1146,9 +1218,8 @@ impl<'a> Legaliser<'a> { for (i, (name, array)) in names.iter().enumerate() { let full = format!("{ty}{ty_array}"); if input { - let at = Link::location(&mut self.link.attributes, name); - self.header - .push(format!("layout(location = {at}) in {full} {name}{array};")); + let decl = self.attribute(&full, name, array); + self.header.push(decl); self.interface.attributes.insert(name.clone()); } else if !varying { let at = explicit @@ -1640,9 +1711,8 @@ impl<'a> Legaliser<'a> { let ty = LEGACY_ATTRIBUTES.iter().find(|(a, _)| *a == n).unwrap().1; let renamed = n.replacen("gl_", "iris_", 1); if self.interface.attributes.insert(renamed.clone()) { - let at = Link::location(&mut self.link.attributes, &renamed); - self.header - .push(format!("layout(location = {at}) in {ty} {renamed};")); + let decl = self.attribute(ty, &renamed, ""); + self.header.push(decl); } renamed } @@ -1664,6 +1734,21 @@ impl<'a> Legaliser<'a> { } } + /// A vertex attribute's declaration: an input, or for geometry programs + /// a global the glue fills ([`Geometry`]). + fn attribute(&mut self, ty: &str, name: &str, array: &str) -> String { + match &self.link.geometry { + Some(_) => { + self.attribute_types.insert(name.to_owned(), ty.to_owned()); + format!("{ty} {name}{array};") + } + None => { + let at = Link::location(&mut self.link.attributes, name); + format!("layout(location = {at}) in {ty} {name}{array};") + } + } + } + fn frag_data(&mut self, n: u32) -> ast::Expr { let name = format!("iris_FragData{n}"); if self.interface.outputs.insert(n, name.clone()).is_none() { @@ -1896,9 +1981,8 @@ impl<'a> Legaliser<'a> { continue; } if attribute && self.stage == Stage::Vertex { - let at = Link::location(&mut self.link.attributes, name); - self.header - .push(format!("layout(location = {at}) in {ty} {name};")); + let decl = self.attribute(ty, name, ""); + self.header.push(decl); self.interface.attributes.insert(name.to_owned()); } else if !attribute { self.link.uniform(name, format!("{ty} {name}"))?; @@ -1908,6 +1992,42 @@ impl<'a> Legaliser<'a> { if !self.errors.is_empty() { return Err(self.errors.join("\n")); } + if let Some(geometry) = &self.link.geometry { + match self.stage { + Stage::Vertex => { + // The glue first, then the attributes from it, before + // the global initialisers (which may read them). + let mut first = vec!["hz_vertex();".to_owned()]; + for (name, ty) in &self.attribute_types { + first.push(match geometry.attributes.get(name) { + Some(value) => format!("{name} = {ty}({value});"), + None => format!("{name} = {ty}(0);"), + }); + } + self.prologue.splice(0..0, first); + } + Stage::Fragment => { + if let (Some(reference), Some(name)) = + (geometry.alpha_test, self.interface.outputs.get(&0)) + { + let written = format!("iris_out_{name}"); + let name = if self.declared.contains(&written) + || self + .header + .iter() + .any(|h| h.ends_with(&format!(" {written};"))) + { + written + } else { + name.clone() + }; + self.epilogue + .push(format!("if (!({name}.a > {reference:?})) discard;")); + } + } + _ => {} + } + } if self.stage == Stage::Vertex { // GL's clip space to wgpu's: y flipped, so texture row 0 stays // the bottom of the picture as in GL (texture coordinates and @@ -1919,6 +2039,10 @@ impl<'a> Legaliser<'a> { } let mut out = String::from("#version 450 core\n"); out.push_str(HELPERS); + if let (Some(geometry), Stage::Vertex) = (&self.link.geometry, self.stage) { + out.push_str(&geometry.vertex_glue); + out.push('\n'); + } if self.modulo { out.push_str(&modulo_helpers()); } @@ -1929,7 +2053,10 @@ impl<'a> Legaliser<'a> { out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); } if !self.link.uniforms.is_empty() { - out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n"); + out.push_str(&format!( + "layout(std140, set = {}, binding = 0) uniform IrisUniforms {{\n", + self.link.set + )); for (_, decl) in &self.link.uniforms { out.push_str(&format!(" {decl};\n")); } diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index f34c90520..e6068aaea 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -7,7 +7,7 @@ use horizon_shaderpack::{ include::Inlined, preprocess::{Environment, preprocess}, program_name, - translate::{Link, Translated, translate}, + translate::{Geometry, Link, Translated, translate}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -403,6 +403,95 @@ void main() {{ ); } +/// A `gbuffers_*` program over Horizon's geometry: its attributes are +/// globals the glue fills before `main`, its bindings in group 2, and its +/// fragment discards below Iris's alpha test. A `case` ending in `return` +/// (Photon's displacement) isn't a fall-through for naga. +#[test] +fn geometry_programs_take_their_attributes_from_the_glue() { + let glue = Geometry { + vertex_glue: "layout(location = 0) in vec3 hz_position; +layout(std430, set = 3, binding = 0) readonly buffer HzTable { int hz_table[]; }; +vec4 hz_pos; +void hz_vertex() { hz_pos = vec4(hz_position, 1.0) + float(hz_table[0]); }" + .into(), + attributes: [ + ("iris_Vertex".to_owned(), "hz_pos".to_owned()), + ( + "mc_Entity".to_owned(), + "vec4(8.0, -1.0, 0.0, 0.0)".to_owned(), + ), + ] + .into(), + alpha_test: Some(0.1), + }; + let mut link = Link { + set: 2, + geometry: Some(glue), + ..Link::default() + }; + let vs = run( + Stage::Vertex, + "uniform sampler2D noisetex; +attribute vec4 mc_Entity; +attribute vec2 mc_midTexCoord; +varying vec2 uv; +vec3 sway(vec3 p, int id) { + switch (id) { + case 8: + return p + 1.0; + case 9: + case 10: + return p - 1.0; + default: + return p; + } +} +void main() { + uv = gl_MultiTexCoord0.xy + mc_midTexCoord; + gl_Position = gl_ModelViewProjectionMatrix * vec4(sway(gl_Vertex.xyz, int(mc_Entity.x)), 1.0); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "hz_vertex();", + "mc_Entity = vec4(vec4(8.0, -1.0, 0.0, 0.0));", + "iris_Vertex = vec4(hz_pos);", + "mc_midTexCoord = vec2(0);", + "set = 2, binding = 0) uniform IrisUniforms", + ] { + assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl); + } + // Horizon's vertex input is the only one. + assert_eq!( + io(&vs, false).into_keys().collect::>(), + ["hz_position"] + ); + reparse(&vs.wgsl).unwrap(); + let fs = run( + Stage::Fragment, + "uniform sampler2D gtexture; +varying vec2 uv; +void main() { + /* DRAWBUFFERS:02 */ + gl_FragData[0] = texture2D(gtexture, uv); + gl_FragData[1] = vec4(1.0); +} +", + &mut link, + ) + .unwrap(); + assert!( + fs.glsl.contains("if (!(iris_FragData0.a > 0.1)) discard;"), + "{}", + fs.glsl + ); + assert!(fs.glsl.contains("set = 2, binding = "), "{}", fs.glsl); + reparse(&fs.wgsl).unwrap(); +} + /// A fragment output narrower than its four-channel target (Steadfast's /// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: /// GL fills the missing channels, wgpu refuses the pipeline. diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3b3a47189..3d32e37f6 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -22,7 +22,8 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs | | Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) | | Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) | -| Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | +| Java shader packs: `gbuffers_terrain`, `gbuffers_water` (`gfx/java_terrain.rs`: Horizon's terrain fed to the pack's programs) | first slice: MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water (below) | +| Java shader packs: other `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | ## How the renderer draws a frame today @@ -347,6 +348,25 @@ Picking one translates every planned pass of each dimension folder (`java_pack.r 4. `final` draws into a target that replaces the world's picture, where Horizon packs' `composite` output goes: the hand, menus and HUD are drawn over it. +When the pack has a `gbuffers_terrain` (or `textured_lit`, `textured`, `basic`, the program Iris falls back to), the +pack draws the terrain itself (`gfx/java_terrain.rs`): Horizon's world pass skips its own solid and translucent +terrain, then + +- at step 2, after Horizon's sky, entities and the rest enter `colortex0` and depth, the pack's terrain program draws + every visible section into its `RENDERTARGETS` (the side the next pass reads), tested against that depth; the + depth is then copied into `depthtex0` and `depthtex1`; +- before the first `composite`, as Iris does, `gbuffers_water` (or the terrain program) draws the translucent + layer with the pack's `blend.*` or vanilla's blending; the depth goes into `depthtex0` only. + +The pack's vertex program reads Horizon's own terrain vertices (the arena pages, instanced or flat draws): a glue +function written before `main` decodes them into Iris's attributes (`vaPosition`/`gl_Vertex` relative to the camera, +`gl_Color` with vanilla's face shading undone, `gl_MultiTexCoord0/1`, the normal and `at_tangent` from the quad's +four corners, `mc_midTexCoord`, `at_midBlock`), and `mc_Entity.x` is the block's id from the pack's +`block.properties`, matched to the sprite's block by name. `gtexture`/`texture` is a 2D atlas built from Horizon's +sprite arrays (animated sprites copied in each frame), `lightmap` is Horizon's lightmap with Iris's texture matrix, +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). + 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 @@ -377,10 +397,13 @@ What makes Horizon look like OpenGL to the pack: Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3 grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its -`deferred` reads the albedo `gbuffers_*` write to `colortex4`. Without `gbuffers_*` and `shadow`, no pack has its -shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and +`deferred` reads the albedo `gbuffers_*` write to `colortex4` (not checked again since the terrain programs run). +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. +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 +come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, and only the +overworld has been checked. ### Compatibility @@ -388,18 +411,19 @@ Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default op the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked (`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game -and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet. +and screenshotted. Full-screen passes, `gbuffers_terrain` and `gbuffers_water` run (above); no pack has its own +shadows, entities or sky yet. | Pack | Version | Result | First thing that stops it | | --- | --- | --- | --- | -| BSL | v10.1.8 | drawn: 26 passes | | +| BSL | v10.1.8 | drawn: 26 passes and its terrain and water programs | | | Complementary Reimagined | r5.9.3 | drawn: 27 passes | | | Complementary Unbound | r5.8 | loads: 27 passes | | | Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | | | Steadfast | 0.8.0 | drawn: 3 passes | | -| Chocapic13' | V9 High | drawn: 16 passes, its grade and fog over Horizon's world | | -| MakeUp Ultra Fast | 9.6 | drawn: 6 passes; its fog covers everything without its `gbuffers_*` | | -| Photon | v1.4 | loads: 27 passes; draws black: it lights the scene from the G-buffer its `gbuffers_*` write | | +| Chocapic13' | V9 High | drawn: 16 passes and its terrain and water programs | | +| MakeUp Ultra Fast | 9.6 | drawn: 6 passes and its terrain and water programs | | +| Photon | v1.4 | loads: 27 passes and its terrain and water programs; draws black | its sky and light come from a compute pass and `.dat` look-up tables, not loaded yet | | Bliss | 2.1.2 | fails | `world0/composite1.fsh`: a vector component passed to an `inout` parameter (WGSL can't point at one) | | Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses | | Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) | @@ -440,9 +464,9 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer 3. **Full-screen programs**: `deferred*`, `composite*`, `final` with `colortex0..15` (formats from the pack), `depthtex0..2`, `noisetex` and the uniforms (most are already computed for the world shaders). This alone runs Sildur's and BSL post-processing over Horizon's own world. -4. **`gbuffers_terrain`, `gbuffers_water`, `gbuffers_sky*`**: Horizon's terrain vertices extended with Iris's - attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second set of - terrain pipelines writing the pack's render targets. +4. **`gbuffers_terrain`, `gbuffers_water`** (done, above), **`gbuffers_sky*`**: Horizon's terrain vertices decoded + into Iris's attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second + set of terrain pipelines writing the pack's render targets. 5. **Entities, block entities, hand, weather, clouds, particles** `gbuffers_*`. 6. **Shadow pass**: terrain and entities from the sun into `shadowtex0/1` and `shadowcolor0/1`, culled from the light's view, with the pack's distortion.