diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f43593360..180d38ab0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6784,11 +6784,12 @@ impl Game<'_> { self.fangs_geometry(camera, alpha, &mut out); let mut see_through = std::mem::take(&mut self.see_through_vertices); see_through.clear(); - self.mark_entity(out.len(), "minecraft:name_tag"); + // Name tags and shadows blend: Horizon keeps drawing them until the pack's entity + // programs draw translucent parts (`minecraft:name_tag`, `minecraft:entity_shadow`). + self.mark_stage(out.len(), "NONE"); self.name_tag_geometry(camera, alpha, &mut out, &mut see_through); self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). - self.mark_entity(out.len(), "minecraft:entity_shadow"); if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); @@ -7016,7 +7017,8 @@ impl Game<'_> { self.boat_geometry(camera, alpha, &mut out); self.mark_entity(out.len(), "minecraft:minecart"); self.cart_geometry(camera, alpha, &mut out); - self.mark_stage(out.len(), "BLOCK_ENTITIES"); + // Beams: `gbuffers_beaconbeam`, not a block entity's program (5.4 has no stage for them). + self.mark_stage(out.len(), "NONE"); self.beacon_geometry(camera, alpha, &mut out); self.mark_entity(out.len(), "minecraft:fishing_bobber"); self.fishing_geometry(camera, alpha, &mut out); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 4351fd85d..d354b9bba 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -70,6 +70,7 @@ mod lod; mod occlusion; mod pack_atlas; pub mod pack_draw; +mod pack_entities; mod pack_post; mod pack_sky; mod pack_timing; @@ -487,6 +488,8 @@ pub struct Renderer { world_post: world_post::Post, /// The shader pack's post-processing, and the dimension (legacy id) it was loaded for. pack_post: Option<(i32, Option)>, + /// The entity vertices Horizon draws itself while a shader pack draws the others. + pack_entity_rest: Vec, /// The block sprites as one atlas, while a shader pack is loaded. pack_atlas: Option, /// The pack's terrain program reads flat draws' vertices (`pack_terrain_inputs`). @@ -2346,6 +2349,7 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, pack_post: None, + pack_entity_rest: Vec::new(), pack_atlas: None, pack_terrain_flat: false, hud, @@ -2832,6 +2836,7 @@ impl Renderer { terrain: self.pack_terrain_inputs(), sky: Some(pack_sky::inputs()), celestial: Some(pack_sky::celestial_inputs()), + entities: Some(pack_entities::inputs()), } } @@ -3509,18 +3514,31 @@ impl Renderer { self.uploads .buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines)); } + // While a shader pack draws entities, the runs of `entity_spans` its programs draw are + // left out of Horizon's own entity draw. + let mut entities = frame.entities; + if !frame.title + && let Some((_, Some(post))) = &mut self.pack_post + && post.has_entities() + { + post.prepare_entities( + &self.device, + &self.queue, + frame.entities, + frame.entity_spans, + &mut self.pack_entity_rest, + ); + entities = &self.pack_entity_rest; + } let [ entity_quads, crumbling_quads, translucent_crumbling_quads, water_mask_quads, shadow_quads, - ] = self.entity_batch.update( - frame.entities, - frame.additive, - frame.hand, - frame.see_through, - ); + ] = self + .entity_batch + .update(entities, frame.additive, frame.hand, frame.see_through); let weather_quads = frame.weather.len() as u32 / 4; let world_quads = entity_quads + crumbling_quads diff --git a/crates/horizon-client/src/gfx/pack_entities.rs b/crates/horizon-client/src/gfx/pack_entities.rs new file mode 100644 index 000000000..b30aa4fdb --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_entities.rs @@ -0,0 +1,400 @@ +//! Entities and block entities drawn by a shader pack's `gbuffers_entities` and `gbuffers_block` +//! (spec 2.3, 5.3, 5.4): the runs of `Frame::entities` the game marked (`EntitySpan`), each its +//! own draw with its `entityId` or `blockEntityId` and `entityColor` in a per-draw slot of +//! `HzDraw` (set 2). Horizon draws whatever the pack does not. + +use std::ops::Range; + +use horizon_shaders::render_stage; + +use super::Vertex; +use super::pack_draw::EntitySpan; + +/// `HzDraw`'s size (pack_draw.rs). +const SLOT: u64 = 32; + +const ATTRIBUTES: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![ + 0 => Float32x3, 1 => Float32x2, 2 => Uint32, 3 => Unorm8x4, 4 => Uint8x4, 5 => Snorm8x4 +]; + +/// The entity vertex: Horizon's own (`Vertex`). +pub fn buffers() -> [Option>; 1] { + [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &ATTRIBUTES, + })] +} + +/// What `gbuffers_entities` and `gbuffers_block` read from an entity vertex: camera-relative +/// position, the shared atlas's UV, colour, light (block, sky in 16ths) and the world-oriented +/// normal. The quad's corners, read from the same vertices at set 1, give the face normal where +/// the vertex has none (block entities) and `at_tangent` along the texture's u, as for terrain. +pub fn inputs() -> horizon_shaders::GbuffersInputs { + let declarations = "layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\ + layout(location = 2) in uint hz_v_overlay;\nlayout(location = 3) in vec4 hz_v_color;\n\ + layout(location = 4) in uvec4 hz_v_light;\nlayout(location = 5) in vec4 hz_v_normal;\n\ + layout(set = 1, binding = 0) readonly buffer HzEntityVertices { uint hz_entity_vertices[]; };\n\ + vec4 hz_tangent; vec2 hz_mid;\n" + .to_owned(); + let words = std::mem::size_of::() / 4; + let corner = |k: usize, field: &str| { + let at = |o: usize| format!("hz_entity_vertices[hz_q + {}u]", k * words + o); + match field { + "pos" => format!("uintBitsToFloat(uvec3({}, {}, {}))", at(0), at(1), at(2)), + _ => format!("uintBitsToFloat(uvec2({}, {}))", at(3), at(4)), + } + }; + let body = format!( + " uint hz_q = (uint(gl_VertexIndex) & ~3u) * {words}u;\n \ + vec3 hz_e1 = {p1} - {p0};\n \ + vec3 hz_e2 = {p2} - {p0};\n \ + vec2 hz_t0 = {t0};\n \ + vec2 hz_d1 = {t1} - hz_t0;\n \ + vec2 hz_d2 = {t2} - hz_t0;\n \ + hz_mid = (hz_t0 + {t2}) * 0.5;\n \ + vec3 hz_n = cross(hz_e1, hz_e2);\n \ + hz_Normal = dot(hz_v_normal.xyz, hz_v_normal.xyz) > 0.01 ? normalize(hz_v_normal.xyz)\n \ + : dot(hz_n, hz_n) > 1e-12 ? normalize(hz_n) : vec3(0.0, 1.0, 0.0);\n \ + hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n \ + float hz_r = hz_d1.x * hz_d2.y - hz_d2.x * hz_d1.y;\n \ + vec3 hz_t = (hz_e1 * hz_d2.y - hz_e2 * hz_d1.y) * sign(hz_r);\n \ + vec3 hz_b = (hz_e2 * hz_d1.x - hz_e1 * hz_d2.x) * sign(hz_r);\n \ + hz_t -= hz_Normal * dot(hz_Normal, hz_t);\n \ + if (dot(hz_t, hz_t) > 1e-12) {{\n \ + hz_t = normalize(hz_t);\n \ + hz_tangent = vec4(hz_t, dot(cross(hz_t, hz_Normal), hz_b) < 0.0 ? -1.0 : 1.0);\n \ + }}\n \ + hz_Vertex = vec4(hz_v_pos, 1.0);\n \ + hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \ + hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \ + hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \ + hz_Color = hz_v_color;\n", + p0 = corner(0, "pos"), + p1 = corner(1, "pos"), + p2 = corner(2, "pos"), + t0 = corner(0, "uv"), + t1 = corner(1, "uv"), + t2 = corner(2, "uv"), + ); + let attributes = [ + ("at_tangent", "hz_tangent"), + ("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"), + ("vaPosition", "hz_Vertex.xyz"), + ("vaUV0", "hz_v_uv"), + ("vaUV1", "ivec2(0, 10)"), + ("vaUV2", "ivec2(hz_MultiTexCoord1.xy)"), + ("vaColor", "hz_Color"), + ("vaNormal", "hz_Normal"), + ]; + horizon_shaders::GbuffersInputs { + declarations, + body, + attributes: attributes + .iter() + .map(|&(n, v)| (n.to_owned(), v.to_owned())) + .collect(), + after: String::new(), + // Cutout, as vanilla's entity types mostly are (OQ-23): the loader's test at 0.1. + alpha_test: Some(horizon_shaders::AlphaTest { + op: ">", + reference: 0.1, + }), + } +} + +/// `entityColor` for a run whose first quad carries overlay code `overlay`: the hurt red or a +/// white flash, its alpha how much of that colour shows over the entity (vanilla mixes the +/// overlay texel's colour in by one minus the texel's alpha). +pub fn entity_color(overlay: u32) -> [f32; 4] { + let [r, g, b, a] = crate::overlay::HURT_TEXEL.map(|v| f32::from(v) / 255.0); + let white = |u: u32| { + let a = f32::from(crate::overlay::white_alpha(u)) / 255.0; + [1.0, 1.0, 1.0, 1.0 - a] + }; + match overlay { + 1 | 8 => [r, g, b, 1.0 - a], + 5 => white(15), + 16..32 => white(overlay - crate::overlay::WHITE), + _ => [0.0; 4], + } +} + +/// One draw: its quads in `PackEntities`' buffer, its program and its slot of `HzDraw`. +pub(super) struct Draw { + /// The first vertex. + pub base: u32, + pub quads: u32, + /// `gbuffers_block` (or its fallback) draws it, not `gbuffers_entities`. + pub block: bool, + pub slot: u32, +} + +/// The vertices and per-draw uniforms of the runs a pack draws, rebuilt each frame. +pub(super) struct PackEntities { + vertices: wgpu::Buffer, + /// Set 1: the vertices again, for the quads' corners. + pub table: wgpu::BindGroupLayout, + pub table_group: wgpu::BindGroup, + slots: wgpu::Buffer, + pub group: wgpu::BindGroup, + stride: u64, + /// Two triangles per quad, for `quads` quads. + pub indices: wgpu::Buffer, + quads: u32, + scratch: Vec, + uniforms: Vec, + pub draws: Vec, +} + +impl PackEntities { + pub fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout) -> Self { + let stride = SLOT.max(u64::from( + device.limits().min_uniform_buffer_offset_alignment, + )); + let table = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Shader pack entity vertices"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + 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, + }], + }); + let (vertices, table_group) = Self::vertex_buffer(device, &table, 4096); + let (slots, group) = Self::slot_buffer(device, layout, 64, stride); + Self { + vertices, + table, + table_group, + slots, + group, + stride, + indices: quad_indices(device, 1024), + quads: 1024, + scratch: Vec::new(), + uniforms: Vec::new(), + draws: Vec::new(), + } + } + + fn vertex_buffer( + device: &wgpu::Device, + table: &wgpu::BindGroupLayout, + vertices: u64, + ) -> (wgpu::Buffer, wgpu::BindGroup) { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack entity vertices"), + size: vertices * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack entity vertices"), + layout: table, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + }); + (buffer, group) + } + + fn slot_buffer( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + slots: u64, + stride: u64, + ) -> (wgpu::Buffer, wgpu::BindGroup) { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack entity draws"), + size: slots * stride, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack entity draws"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &buffer, + offset: 0, + size: wgpu::BufferSize::new(SLOT), + }), + }], + }); + (buffer, group) + } + + pub fn vertices(&self) -> wgpu::BufferSlice<'_> { + self.vertices.slice(..) + } + + /// The dynamic offset of draw slot `slot`. + pub fn offset(&self, slot: u32) -> u32 { + (u64::from(slot) * self.stride) as u32 + } + + /// Splits `entities` between the pack, which draws the runs of `spans` its programs cover + /// (`drawn`: whether it has `gbuffers_entities`, `gbuffers_block` or their fallbacks), and + /// Horizon, which draws the rest (`rest`). Uploads the pack's part. + #[allow(clippy::too_many_arguments)] + pub fn prepare( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + layout: &wgpu::BindGroupLayout, + entities: &[Vertex], + spans: &[EntitySpan], + drawn: [bool; 2], + rest: &mut Vec, + ) { + self.draws.clear(); + self.scratch.clear(); + self.uniforms.clear(); + rest.clear(); + let first = spans.first().map_or(entities.len(), |s| s.start as usize); + rest.extend_from_slice(&entities[..first.min(entities.len())]); + for (span, range) in runs(entities.len(), spans) { + let run = &entities[range]; + let Some(block) = drawn_by_pack(span.stage, drawn).filter(|_| plain(run)) else { + rest.extend_from_slice(run); + continue; + }; + if run.is_empty() { + continue; + } + let start = self.scratch.len() as u32; + self.scratch.extend_from_slice(run); + let (entity_id, block_id) = if block { (0, span.id) } else { (span.id, 0) }; + let mut bytes = [0u8; SLOT as usize]; + bytes[0..4].copy_from_slice(&(span.stage as i32).to_le_bytes()); + bytes[4..8].copy_from_slice(&entity_id.to_le_bytes()); + bytes[8..12].copy_from_slice(&block_id.to_le_bytes()); + for (i, c) in entity_color(run[0].layer).iter().enumerate() { + bytes[16 + 4 * i..20 + 4 * i].copy_from_slice(&c.to_le_bytes()); + } + self.uniforms.extend_from_slice(&bytes); + self.uniforms + .resize(self.uniforms.len() + (self.stride - SLOT) as usize, 0); + self.draws.push(Draw { + base: start, + quads: run.len() as u32 / 4, + block, + slot: self.draws.len() as u32, + }); + } + if self.draws.is_empty() { + return; + } + let vertex_size = std::mem::size_of::() as u64; + let (need_vertices, need_slots) = (self.scratch.len() as u64, self.draws.len() as u64); + let have_vertices = self.vertices.size() / vertex_size; + let have_slots = self.slots.size() / self.stride; + if need_vertices > have_vertices { + (self.vertices, self.table_group) = + Self::vertex_buffer(device, &self.table, need_vertices.next_power_of_two()); + } + if need_slots > have_slots { + (self.slots, self.group) = + Self::slot_buffer(device, layout, need_slots.next_power_of_two(), self.stride); + } + let quads = self.draws.iter().map(|d| d.quads).max().unwrap_or(0); + if quads > self.quads { + self.quads = quads.next_power_of_two(); + self.indices = quad_indices(device, self.quads); + } + queue.write_buffer(&self.vertices, 0, bytemuck::cast_slice(&self.scratch)); + queue.write_buffer(&self.slots, 0, &self.uniforms); + } +} + +/// Two triangles for each of `quads` quads, from vertex 0. +fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { + let indices: Vec = (0..quads) + .flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q * 4 + i)) + .collect(); + wgpu::util::DeviceExt::create_buffer_init( + device, + &wgpu::util::BufferInitDescriptor { + label: Some("Shader pack entity indices"), + contents: bytemuck::cast_slice(&indices), + usage: wgpu::BufferUsages::INDEX, + }, + ) +} + +/// Whether a run holds only geometry a gbuffers program can draw from the shared atlas: no +/// celestial body, cloud, beam, End portal or crack (overlay codes Horizon's entity shader +/// draws in its own way; entity.wgsl). +fn plain(run: &[Vertex]) -> bool { + run.iter() + .step_by(4) + .all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12)) +} + +/// Whether the pack draws a run of render stage `stage` (`Some(true)` with `gbuffers_block`), +/// given which of `gbuffers_entities` and `gbuffers_block` (or their fallbacks) it has. +pub fn drawn_by_pack(stage: u32, drawn: [bool; 2]) -> Option { + if stage == render_stage("ENTITIES") && drawn[0] { + Some(false) + } else if stage == render_stage("BLOCK_ENTITIES") && drawn[1] { + Some(true) + } else { + None + } +} + +/// Each span with its vertex range: from its start to the next span's (or the end). +pub fn runs( + len: usize, + spans: &[EntitySpan], +) -> impl Iterator)> + '_ { + spans.iter().enumerate().map(move |(i, s)| { + let end = spans.get(i + 1).map_or(len, |n| n.start as usize); + let start = (s.start as usize).min(len); + (*s, start..end.clamp(start, len)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn runs_split_the_list_between_pack_and_horizon() { + let v = |layer| Vertex { + layer, + ..bytemuck::Zeroable::zeroed() + }; + let span = |start, stage: &str, id| EntitySpan { + start, + stage: render_stage(stage), + id, + }; + let spans = [ + span(2, "ENTITIES", 7), + span(5, "PARTICLES", 0), + span(6, "BLOCK_ENTITIES", 9), + ]; + let ranges: Vec<_> = runs(10, &spans).map(|(_, r)| r).collect(); + assert_eq!(ranges, [2..5, 5..6, 6..10]); + assert_eq!(drawn_by_pack(spans[0].stage, [true, false]), Some(false)); + assert_eq!(drawn_by_pack(spans[1].stage, [true, true]), None); + assert_eq!(drawn_by_pack(spans[2].stage, [true, false]), None); + assert_eq!(drawn_by_pack(spans[2].stage, [false, true]), Some(true)); + // A beacon beam's quads stay Horizon's. + assert!(plain(&[v(0), v(0), v(0), v(0), v(1)])); + assert!(!plain(&[v(0), v(0), v(0), v(0), v(6)])); + assert_eq!(entity_color(1)[0], 1.0); + assert!((entity_color(1)[3] - (1.0 - 178.0 / 255.0)).abs() < 1e-6); + assert_eq!(entity_color(0), [0.0; 4]); + } +} diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index c3a67f22e..8d6d12d94 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; use horizon_shaders::{Format, Group, Kind, Post, Val}; use super::pack_draw::DrawUniforms; +use super::pack_entities::PackEntities; use super::pack_sky::PackSky; use super::pack_uniforms::{self, FrameUniforms, PackInputs}; @@ -130,6 +131,14 @@ struct Sky { textured: Option, } +/// Entities and block entities a pack draws (`gbuffers_entities`, `gbuffers_block` or their +/// fallbacks), after terrain; Horizon draws the others. +struct Entities { + geometry: PackEntities, + entity: Option, + block: Option, +} + struct Pass { name: String, group: Group, @@ -203,6 +212,8 @@ pub struct PackPost { water: Option, /// What draws the sky (`gbuffers_skybasic` or its fallback), before terrain, and its vertices. sky: Option, + /// What draws entities and block entities, after terrain, and their vertices. + entities: Option, /// A program after translucent terrain reads `depthtex1`: it is copied before water. depth1: bool, /// Buffers with mipmaps (filterable ones a program asks them for). @@ -901,6 +912,28 @@ impl PackPost { } }); let sky = sky.filter(|s| s.basic.is_some() || s.textured.is_some()); + let entity_vertices = (post.entities.is_some() || post.block.is_some()) + .then(|| PackEntities::new(device, &draws.layout)); + let entity_buffers = super::pack_entities::buffers(); + let entity_geometry = entity_vertices.as_ref().map(|e| Geometry { + buffers: &entity_buffers, + table: Some(&e.table), + depth_write: true, + atlas: world.celestial.clone(), + ids: None, + cull: false, + }); + let entity = post.entities.zip(entity_geometry.as_ref()); + let entity = entity.and_then(|(p, g)| build(p, Some(g))); + let block = post.block.zip(entity_geometry.as_ref()); + let block = block.and_then(|(p, g)| build(p, Some(g))); + let entities = entity_vertices + .filter(|_| entity.is_some() || block.is_some()) + .map(|geometry| Entities { + geometry, + entity, + block, + }); // Developers' aid: `HORIZON_SHADER_PACK_SKIP=composite,final` leaves programs out. let skip = std::env::var("HORIZON_SHADER_PACK_SKIP").unwrap_or_default(); let passes: Vec = post @@ -923,6 +956,14 @@ impl PackPost { notes.push(format!("the {part} draw with {}", p.name)); } } + for (part, pass) in entities + .iter() + .flat_map(|e| [("entities", &e.entity), ("block entities", &e.block)]) + { + if let Some(p) = pass { + notes.push(format!("{part} draw with {}", p.name)); + } + } let depth1 = water.is_some() && passes .iter() @@ -940,6 +981,11 @@ impl PackPost { .iter() .flat_map(|s| s.basic.iter().chain(&s.textured)) .chain(&terrain) + .chain( + entities + .iter() + .flat_map(|e| e.entity.iter().chain(&e.block)), + ) .chain(&water) .find(touched) .map(|_| true) @@ -955,6 +1001,7 @@ impl PackPost { let blit_depth = terrain.is_some() || water.is_some() || sky.is_some() + || entities.is_some() || passes.iter().any(|p| { p.samplers .iter() @@ -1050,6 +1097,7 @@ impl PackPost { terrain, water, sky, + entities, depth1, mipped, mips_valid: 0, @@ -1372,7 +1420,82 @@ impl PackPost { self.sky = Some(sky); } - /// The sky, when it shows, then terrain. + /// Entities and block entities with the pack's programs: each run `prepare_entities` kept + /// is one draw with its own `entityId` or `blockEntityId` and `entityColor`. + fn draw_entities( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + size: [u32; 2], + ) { + let Some(mut entities) = self.entities.take() else { + return; + }; + let geometry = &entities.geometry; + for (block, pass) in [(false, &mut entities.entity), (true, &mut entities.block)] { + let Some(pass) = pass else { continue }; + let mut draws = geometry + .draws + .iter() + .filter(|d| d.block == block) + .peekable(); + if draws.peek().is_none() { + continue; + } + let group = self.bind(device, queue, pass, size); + { + let mut rp = self.begin(encoder, pass); + rp.set_pipeline(&pass.pipeline); + rp.set_bind_group(0, &group, &[]); + rp.set_bind_group(1, &geometry.table_group, &[]); + rp.set_vertex_buffer(0, geometry.vertices()); + rp.set_index_buffer(geometry.indices.slice(..), wgpu::IndexFormat::Uint32); + for d in draws { + if pass.draw { + rp.set_bind_group(2, &geometry.group, &[geometry.offset(d.slot)]); + } + rp.draw_indexed(0..d.quads * 6, d.base as i32, 0..1); + } + } + self.mips_valid &= !pass.written; + } + self.entities = Some(entities); + } + + /// Splits `entities` (`Frame::entities`) between the pack and Horizon by its runs + /// (`spans`): the pack's part is uploaded for this frame's draw, Horizon's goes to `rest`. + pub fn prepare_entities( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + entities: &[super::Vertex], + spans: &[super::pack_draw::EntitySpan], + rest: &mut Vec, + ) { + let Some(e) = &mut self.entities else { + rest.clear(); + rest.extend_from_slice(entities); + return; + }; + let drawn = [e.entity.is_some(), e.block.is_some()]; + e.geometry.prepare( + device, + queue, + &self.draws.layout, + entities, + spans, + drawn, + rest, + ); + } + + /// Whether the pack draws entities or block entities itself. + pub fn has_entities(&self) -> bool { + self.entities.is_some() + } + + /// The sky, when it shows, then terrain, entities and block entities. fn draw_opaque( &mut self, device: &wgpu::Device, @@ -1386,6 +1509,7 @@ impl PackPost { self.draw_sky(device, queue, encoder, size, frame); } self.draw_terrain(device, queue, encoder, size, false, terrain); + self.draw_entities(device, queue, encoder, size); } /// Regenerates the mip chain of buffer `b`'s side that programs read. @@ -1692,7 +1816,8 @@ impl PackPost { let mut passes = std::mem::take(&mut self.passes); let mut seen = (false, false); let mut shown = false; - let mut terrain_drawn = self.terrain.is_none() && self.sky.is_none(); + let mut terrain_drawn = + self.terrain.is_none() && self.sky.is_none() && self.entities.is_none(); let mut water_drawn = self.water.is_none(); for pass in &mut passes { if !terrain_drawn && pass.group != Group::Prepare { diff --git a/crates/horizon-client/src/gfx/pack_timing.rs b/crates/horizon-client/src/gfx/pack_timing.rs index 61ab721e5..acfdb698f 100644 --- a/crates/horizon-client/src/gfx/pack_timing.rs +++ b/crates/horizon-client/src/gfx/pack_timing.rs @@ -132,7 +132,8 @@ impl PassTiming { fn report(&mut self) { let mut total = 0.0; let mut parts = Vec::new(); - for (name, v) in &mut self.samples { + // A pass that did not run in this window (no entities, the sky out of sight) is left out. + for (name, v) in self.samples.iter_mut().filter(|s| !s.1.is_empty()) { v.sort_by(f32::total_cmp); let median = v[v.len() / 2]; total += median; diff --git a/crates/horizon-shaders/src/post.rs b/crates/horizon-shaders/src/post.rs index 7b83b98b5..71c055c2b 100644 --- a/crates/horizon-shaders/src/post.rs +++ b/crates/horizon-shaders/src/post.rs @@ -103,6 +103,23 @@ const SKY_TEXTURED: [&str; 3] = [ "gbuffers_basic", ]; +/// `gbuffers_entities` and its fallbacks (2.3). +const ENTITIES: [&str; 4] = [ + "gbuffers_entities", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + +/// `gbuffers_block` and its fallbacks (2.3). +const BLOCK: [&str; 5] = [ + "gbuffers_block", + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + /// The sun and moon's default blend: added to the sky, as vanilla draws them. pub const CELESTIAL_BLEND: Blend = [ Factor::SrcAlpha, @@ -149,6 +166,10 @@ pub struct Post { pub sky: Option, /// What draws the sun and moon, between the sunset and the stars. pub sky_textured: Option, + /// What draws entities, after terrain. + pub entities: Option, + /// What draws block entities, after terrain. + pub block: Option, /// The custom uniforms of `shaders.properties` (3.4). pub custom: Custom, pub config: Config, @@ -174,6 +195,8 @@ pub struct GameInputs { pub terrain: Option, pub sky: Option, pub celestial: Option, + /// Entities and block entities (one vertex format). + pub entities: Option, } /// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the @@ -194,6 +217,8 @@ pub fn load_post( water: None, sky: None, sky_textured: None, + entities: None, + block: None, custom: Custom::parse(properties), config: Config::default(), notes: Vec::new(), @@ -253,6 +278,21 @@ pub fn load_post( p.blend = blend(properties, &p.name).unwrap_or(Some(CELESTIAL_BLEND)); p }); + // Entities and block entities draw without blending, as terrain does and as vanilla's + // cutout entity types do, unless `blend.*` says otherwise (OQ-23). + let entity_blend = |p: Option| { + p.map(|mut p| { + p.blend = blend(properties, &p.name).flatten(); + p + }) + }; + let (entities, block) = match &inputs.entities { + Some(i) => ( + entity_blend(gbuffers(&ENTITIES, Group::Gbuffers, i)), + entity_blend(gbuffers(&BLOCK, Group::Gbuffers, i)), + ), + None => (None, None), + }; if let Some(inputs) = &inputs.terrain { let terrain = gbuffers(&TERRAIN, Group::Gbuffers, inputs); // gbuffers_water falls back to gbuffers_terrain's chain (2.3). @@ -268,6 +308,8 @@ pub fn load_post( } loader.post.sky = sky; loader.post.sky_textured = sky_textured; + loader.post.entities = entities; + loader.post.block = block; post.config = std::mem::take(&mut post.config).finish(); post } @@ -530,8 +572,8 @@ mod tests { assert!(post.programs.iter().any(|p| p.name == "composite3")); } - /// Water falls back to the terrain chain and blends by default, as the sky does; `blend.*` - /// overrides. + /// Water falls back to the terrain chain and blends by default, as the sky does; entities + /// and block entities fall back along theirs; `blend.*` overrides. #[test] fn water_falls_back_to_terrain_and_blends() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/packs/terrain-test"); @@ -545,7 +587,8 @@ mod tests { let inputs = GameInputs { terrain: Some(inputs.clone()), sky: Some(inputs.clone()), - celestial: Some(inputs), + celestial: Some(inputs.clone()), + entities: Some(inputs), }; let post = load_post(&pack, "", &Properties::default(), ¯os, &inputs); let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap()); @@ -570,6 +613,17 @@ mod tests { (water.group, water.blend), (Group::Translucent, Some(TRANSLUCENT_BLEND)) ); + // Entities fall back to gbuffers_textured, block entities to gbuffers_terrain; both + // draw without blending. + let (entities, block) = (post.entities.unwrap(), post.block.unwrap()); + assert_eq!( + (entities.name.as_str(), entities.blend), + ("gbuffers_textured", None) + ); + assert_eq!( + (block.name.as_str(), block.blend), + ("gbuffers_terrain", None) + ); let properties = Properties::parse( "blend.gbuffers_terrain = ONE ONE ZERO ONE\nblend.gbuffers_water = off\n", ¯os, diff --git a/crates/horizon-shaders/tests/real_packs.rs b/crates/horizon-shaders/tests/real_packs.rs index 5ed954898..b77b3b158 100644 --- a/crates/horizon-shaders/tests/real_packs.rs +++ b/crates/horizon-shaders/tests/real_packs.rs @@ -172,16 +172,19 @@ fn real_packs_read() { let inputs = horizon_shaders::GameInputs { terrain: Some(terrain.clone()), sky: Some(terrain.clone()), - celestial: Some(terrain), + celestial: Some(terrain.clone()), + entities: Some(terrain), }; let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs); println!( - " dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?} {:?}, {} notes, {:.0} ms", + " dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?} {:?}, entities {:?} {:?}, {} notes, {:.0} ms", post.programs.len(), post.terrain.as_ref().map(|t| &t.name), post.water.as_ref().map(|t| &t.name), post.sky.as_ref().map(|t| &t.name), post.sky_textured.as_ref().map(|t| &t.name), + post.entities.as_ref().map(|t| &t.name), + post.block.as_ref().map(|t| &t.name), post.notes.len() + post.config.notes.len(), start.elapsed().as_secs_f64() * 1000.0 );