From 613702c0a769baa0a175219ceac027f3137376c2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:05:36 +0200 Subject: [PATCH] Render End portals and End gateways as vanilla's block-entity renderers TheEndPortalRenderer and TheEndGatewayRenderer: the position-only portal cube in FaceInfo order (only the vertical faces for portals, the faces Block.shouldRenderFace leaves for gateways) and the gateway beam through a shared submitBeaconBeam. The beacon beam now goes through the same function. The client does not track gateway ages and cooldowns yet, so gateways in game render settled. Co-Authored-By: Claude Opus 5.5 --- .../examples/block_entity_render_fixture.rs | 55 +++- .../horizon-client/src/block_entity_render.rs | 292 ++++++++++++++---- crates/horizon-client/src/game.rs | 15 +- crates/horizon-client/src/game/minecarts.rs | 1 + 4 files changed, 299 insertions(+), 64 deletions(-) diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index f29cebc0c..1770c0c89 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -7,7 +7,9 @@ use glam::{DVec3, Mat4, Quat, Vec3}; use horizon_client::{ assets::Assets, banner::{self, Banners}, - block_entity_render::{BlockAnim, BlockEntityRenderer, Scene, TextCall}, + block_entity_render::{ + BlockAnim, BlockEntityRenderer, END_GATEWAY_LAYER, END_PORTAL_LAYER, Scene, TextCall, + }, chunk::{Chunk, Light}, hud::{HudAtlas, Rect}, signs::{DYE_TEXT, SignData, SignText}, @@ -196,6 +198,25 @@ fn main() -> Result<()> { world.chunks.insert((cx, cz), Arc::new(chunk)); } } + // Neighbour blocks the case sets (End gateway faces). + for (direction, spec) in case["neighbours"].as_object().into_iter().flatten() { + let d = match direction.as_str() { + "down" => [0, -1, 0], + "up" => [0, 1, 0], + "north" => [0, 0, -1], + "south" => [0, 0, 1], + "west" => [-1, 0, 0], + _ => [1, 0, 0], + }; + let neighbour = find_state(registry, spec.as_str().unwrap_or_default()) + .ok_or("unknown neighbour state")?; + world.set( + pos[0] + d[0], + pos[1] + d[1], + pos[2] + d[2], + BlockStateId(neighbour), + )?; + } if let Some(book) = case.get("book") { renderer.set_book( pos, @@ -246,6 +267,15 @@ fn main() -> Result<()> { wobble: case["wobble"] .as_array() .map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))), + gateway: ( + case["gateway"]["age"].as_i64().unwrap_or(0), + int(&case["gateway"]["cooldown"]), + ), + }; + // The case's level height (minimum y, height): the End's by default. + let max_y = match case["level"].as_array() { + Some(l) => int(&l[0]) + int(&l[1]) - 1, + None => 255, }; let open = float(&case["open"]); let near = case["sign"]["near"].as_bool().unwrap_or(false); @@ -279,7 +309,8 @@ fn main() -> Result<()> { anim: &|_| anim.clone(), texts: Some(&texts), partial: float(&case["partial"]), - game_time: 0, + game_time: case["gameTime"].as_i64().unwrap_or(0), + max_y, world: &world, sprites: &sprites, nether: false, @@ -293,6 +324,26 @@ fn main() -> Result<()> { let quads: Vec = verts .chunks(4) .map(|q| { + // Custom geometry: the End portal shader's position-only cube (its + // render type samples end_sky first) and End gateway beams. + if q[0].layer == END_PORTAL_LAYER || q[0].layer == END_GATEWAY_LAYER { + let v: Vec = q + .iter() + .map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]])) + .collect(); + return json!({"texture": "environment/end_sky", "v": v, "color": q[0].color, + "light": q[0].light, "custom": true}); + } + if q[0].layer == 6 { + let texture = "entity/end_portal/end_gateway_beam"; + let u0 = sprites.get(texture).map_or(0.0, |r| r.u0); + let v: Vec = q + .iter() + .map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0] - u0, v.uv[1]])) + .collect(); + return json!({"texture": texture, "v": v, "color": q[0].color, + "light": q[0].light, "custom": true}); + } let (cu, cv) = ((q[0].uv[0] / 2.0).floor(), (q[0].uv[1] / 2.0).floor()); let texture = names .get(cu as usize + cv as usize * grid) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index f3638865b..1619ccba5 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -1,19 +1,23 @@ //! Block-entity renderers (`BlockEntityRenderers`): chests (single, double, //! trapped, ender, copper), shulker boxes, banners, skulls and heads, bells, //! decorated pots, conduits, enchanting-table and lectern books and copper -//! golem statues. Models are vanilla's baked `LayerDefinitions` layers +//! golem statues, End portals and End gateways. Models are vanilla's baked `LayerDefinitions` layers //! (`entity-models.json`); transforms, animation and textures follow each //! vanilla renderer. Faces are lit like the `entity` shader: the lightmap at //! the block plus `minecraft_mix_light` with the level's two diffuse lights. use crate::{hud::Rect, mesher::Vertex, world::World}; use glam::{DVec3, Mat4, Quat, Vec3}; +use horizon_core::geometry::Direction; use horizon_core::{ - geometry::trig::Mth, + geometry::trig::{self, Mth}, random::{LegacyRandom, RandomSource}, }; -use horizon_world::registry::{BlockRegistry, BlockStateId}; +use horizon_world::{ + block_render::FaceVisibility, + registry::{BlockRegistry, BlockStateId}, +}; use serde_json::Value; -use std::{collections::HashMap, f32::consts::PI, path::Path}; +use std::{collections::HashMap, f32::consts::PI, path::Path, sync::Mutex}; /// One baked `ModelPart`: initial pose, textured polygons (pixel units, /// normalized UVs) and named children. @@ -289,6 +293,12 @@ enum Kind { pose: &'static str, facing: &'static str, }, + /// `TheEndPortalRenderer`: the top and bottom faces of a 6/16-tall slab. + EndPortal, + /// `TheEndGatewayRenderer`: the visible faces of the cube and the beam. + EndGateway { + state: u32, + }, /// Sign text (`StandingSignRenderer` / `HangingSignRenderer`); the boards are block models. Sign { hanging: bool, @@ -413,6 +423,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { }; } "conduit" => return Kind::Conduit, + "end_portal" => return Kind::EndPortal, + "end_gateway" => return Kind::EndGateway { state: 0 }, "enchanting_table" => return Kind::EnchantingTable, "lectern" => { return if prop("has_book").as_deref() == Some("true") { @@ -737,6 +749,8 @@ pub struct BlockAnim { pub sherds: [Option; 4], /// `DecoratedPotRenderState` wobble style (positive) and progress. pub wobble: Option<(bool, f32)>, + /// `TheEndGatewayBlockEntity` age and teleportCooldown. + pub gateway: (i64, i32), } /// One `submitText` call (`AbstractSignRenderer.submitSignText`). @@ -765,6 +779,8 @@ pub struct Scene<'a> { pub texts: Option<&'a std::cell::RefCell>>, pub partial: f32, pub game_time: i64, + /// `Level.getMaxY` (End gateway beams while spawning). + pub max_y: i32, pub world: &'a World, pub sprites: &'a HashMap, pub nether: bool, @@ -785,6 +801,8 @@ pub struct BlockEntityRenderer { random: LegacyRandom, /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). pot_patterns: HashMap, + /// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock). + visibility: Option>, } const MODELS: [(&str, &str); 27] = [ ("chest", "minecraft:chest#main"), @@ -835,6 +853,7 @@ impl BlockEntityRenderer { .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) .collect(); let mut renderer = Self::new(models, registry); + renderer.visibility = Some(Mutex::new(crate::models::load_visibility(root, registry)?)); // Sherd items: provides_pottery_pattern -> decorated_pot_pattern asset id. if let Ok(bytes) = std::fs::read(root.join("items.json")) { let items: Value = serde_json::from_slice(&bytes)?; @@ -864,7 +883,10 @@ impl BlockEntityRenderer { .map(|id| { registry.state(BlockStateId(id)).map_or(Kind::None, |s| { let prop = |k: &str| s.properties.get(k).cloned(); - classify(&s.name, &prop) + match classify(&s.name, &prop) { + Kind::EndGateway { .. } => Kind::EndGateway { state: id }, + kind => kind, + } }) }) .collect(); @@ -874,6 +896,7 @@ impl BlockEntityRenderer { books: HashMap::new(), random: LegacyRandom::new(0x5EED_B00C), pot_patterns: HashMap::new(), + visibility: None, } } /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). @@ -921,7 +944,13 @@ impl BlockEntityRenderer { f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5, ); - if center.distance_squared(scene.camera) > VIEW_DISTANCE * VIEW_DISTANCE { + // BlockEntityRenderer.getViewDistance: 256 for End gateways. + let distance = if matches!(kind, Kind::EndGateway { .. }) { + 256.0 + } else { + VIEW_DISTANCE + }; + if center.distance_squared(scene.camera) > distance * distance { continue; } let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) @@ -1291,6 +1320,73 @@ impl BlockEntityRenderer { } } } + Kind::EndPortal => { + // TheEndPortalRenderer.TRANSFORMATION: y from 6/16 to 12/16; only the + // vertical faces (TheEndPortalBlockEntity.shouldRenderFace). + let m = base + * Mat4::from_translation(Vec3::new(0.0, 0.375, 0.0)) + * Mat4::from_scale(Vec3::new(1.0, 0.375, 1.0)); + portal_cube(m, &[Direction::Down, Direction::Up], END_PORTAL_LAYER, out); + } + Kind::EndGateway { state } => { + let anim = (scene.anim)(pos); + let (age, cooldown) = anim.gateway; + // TheEndGatewayRenderer.extractRenderState. + let spawning = age < 200; + if spawning || cooldown > 0 { + let a = scene.partial; + let percent = if spawning { + ((age as f32 + a) / 200.0).clamp(0.0, 1.0) + } else { + 1.0 - ((cooldown as f32 - a) / 40.0).clamp(0.0, 1.0) + }; + let distance = if spawning { + f64::from(scene.max_y) + } else { + 50.0 + }; + let scale = trig::sin(f64::from(percent * PI)); + let height = (f64::from(scale) * distance).floor() as i32; + // DyeColor.MAGENTA / PURPLE getTextureDiffuseColor. + let color = if spawning { 0xC7_4EBD } else { 0x89_32B8 }; + let time = scene.game_time.rem_euclid(40) as f32 + a; + if height > 0 + && let Some(s) = sprite("entity/end_portal/end_gateway_beam") + { + beam( + base, + BeamShape { + scale, + time, + start: -height, + height: height * 2, + color, + solid_radius: 0.15, + glow_radius: 0.175, + }, + s, + out, + ); + } + } + // AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace. + let faces: Vec = Direction::ALL + .into_iter() + .filter(|&d| { + let [dx, dy, dz] = d.normal(); + let neighbor = scene.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz); + self.visibility.as_ref().is_none_or(|v| { + v.lock() + .map(|mut v| { + v.should_render_face(BlockStateId(*state), neighbor, d, true) + .unwrap_or(true) + }) + .unwrap_or(true) + }) + }) + .collect(); + portal_cube(base, &faces, END_GATEWAY_LAYER, out); + } Kind::Conduit => { let (ticks, active, hunting, raw_rotation) = (scene.anim)(pos).conduit; // ConduitRenderer.extractRenderState. @@ -1438,8 +1534,7 @@ impl BlockEntityRenderer { /// rotating solid beam and its translucent glow, the last section 2048 /// blocks tall. `origin` is the beacon block's corner relative to the camera, /// `time` the animation time (game time mod 40 plus partial tick) and `scale` -/// the radius scale. The sprite's v range rides in the light bytes (the -/// entity shader wraps v for layer 6). +/// the radius scale. pub fn beacon_beam( origin: Vec3, sections: &[(u32, i32)], @@ -1448,9 +1543,7 @@ pub fn beacon_beam( s: Rect, out: &mut Vec, ) { - let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; - let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; - let o = origin + Vec3::new(0.5, 0.0, 0.5); + let base = Mat4::from_translation(origin); let mut start = 0i32; for (i, &(color, height)) in sections.iter().enumerate() { let height = if i == sections.len() - 1 { @@ -1458,63 +1551,140 @@ pub fn beacon_beam( } else { height }; - let end = start + height; - let scroll = if height < 0 { time } else { -time }; - let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); - let abgr = - |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); - // Solid beam: radius 0.2 * scale, rotated with time. - let r = 0.2 * scale; - let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); - let corners = [ - rot * Vec3::new(0.0, 0.0, r), - rot * Vec3::new(r, 0.0, 0.0), - rot * Vec3::new(-r, 0.0, 0.0), - rot * Vec3::new(0.0, 0.0, -r), - ]; - let v2 = -1.0 + v_off; - let v1 = height as f32 * (0.5 / r) + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); - // Glow: radius 0.25 * scale, translucent. - let g = 0.25 * scale; - let corners = [ - Vec3::new(-g, 0.0, -g), - Vec3::new(g, 0.0, -g), - Vec3::new(-g, 0.0, g), - Vec3::new(g, 0.0, g), - ]; - let v1 = height as f32 + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); - start = end; + let shape = BeamShape { + scale: 1.0, + time, + start, + height, + color, + solid_radius: 0.2 * scale, + glow_radius: 0.25 * scale, + }; + beam(base, shape, s, out); + start += height; } } -/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). -#[allow(clippy::too_many_arguments)] -fn beam_part( - out: &mut Vec, - o: Vec3, +/// The arguments of `BeaconRenderer.submitBeaconBeam`. +pub struct BeamShape { + /// Scales the v range (End gateways shrink and grow their beam with it). + pub scale: f32, + /// Animation time: game time mod 40 plus the partial tick. + pub time: f32, + pub start: i32, + pub height: i32, + /// RGB. + pub color: u32, + pub solid_radius: f32, + pub glow_radius: f32, +} +/// `BeaconRenderer.submitBeaconBeam` under `base` (the block's corner): the +/// rotating solid beam and its translucent glow. The sprite's v range rides +/// in the light bytes (the entity shader wraps v for layer 6). +pub fn beam(base: Mat4, b: BeamShape, s: Rect, out: &mut Vec) { + let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; + let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; + let color = b.color; + let end = b.start + b.height; + let scroll = if b.height < 0 { b.time } else { -b.time }; + let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); + let abgr = + |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); + // Solid beam, rotated with time. + let r = b.solid_radius; + let rot = glam::Mat3::from_rotation_y((b.time * 2.25 - 45.0).to_radians()); + let corners = [ + rot * Vec3::new(0.0, 0.0, r), + rot * Vec3::new(r, 0.0, 0.0), + rot * Vec3::new(-r, 0.0, 0.0), + rot * Vec3::new(0.0, 0.0, -r), + ]; + let v2 = -1.0 + v_off; + let v1 = b.height as f32 * b.scale * (0.5 / r) + v2; + let part = BeamPart { + base, + start: b.start, + end, + s, + wrap, + }; + part.emit(out, corners, [v1, v2], abgr(255)); + // Glow, translucent. + let g = b.glow_radius; + let corners = [ + Vec3::new(-g, 0.0, -g), + Vec3::new(g, 0.0, -g), + Vec3::new(-g, 0.0, g), + Vec3::new(g, 0.0, g), + ]; + let v1 = b.height as f32 * b.scale + v2; + part.emit(out, corners, [v1, v2], abgr(32)); +} +struct BeamPart { + base: Mat4, start: i32, end: i32, - [wn, en, ws, es]: [Vec3; 4], - [v1, v2]: [f32; 2], - color: u32, s: Rect, wrap: u32, -) { - for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { - let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); - for (p, uv) in [ - (at(a, end), [s.u1, v1]), - (at(a, start), [s.u1, v2]), - (at(b, start), [s.u0, v2]), - (at(b, end), [s.u0, v1]), - ] { +} +impl BeamPart { + /// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). + fn emit( + &self, + out: &mut Vec, + [wn, en, ws, es]: [Vec3; 4], + [v1, v2]: [f32; 2], + color: u32, + ) { + let s = self.s; + for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { + let at = |c: Vec3, y: i32| { + self.base + .transform_point3(Vec3::new(0.5, 0.0, 0.5) + c + Vec3::new(0.0, y as f32, 0.0)) + }; + for (p, uv) in [ + (at(a, self.end), [s.u1, v1]), + (at(a, self.start), [s.u1, v2]), + (at(b, self.start), [s.u0, v2]), + (at(b, self.end), [s.u0, v1]), + ] { + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 6, + color, + light: self.wrap, + }); + } + } + } +} + +/// Entity-shader layers for `rendertype_end_portal`: end portals draw 15 +/// layers of `end_portal.png` over `end_sky.png`, End gateways 16. +pub const END_PORTAL_LAYER: u32 = 9; +pub const END_GATEWAY_LAYER: u32 = 10; +/// `AbstractEndPortalRenderer.FACES`: the unit cube's corners for each face +/// (`Direction` order) in `FaceInfo` vertex order. +#[rustfmt::skip] +const PORTAL_FACES: [[[f32; 3]; 4]; 6] = [ + [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0]], + [[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0]], + [[1.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + [[0.0, 1.0, 1.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]], + [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0]], + [[1.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]], +]; +/// `AbstractEndPortalRenderer.submitCube`: position-only quads (the portal +/// shader projects its textures from the screen; uv, colour and light are unused). +fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec) { + for &d in faces { + for c in PORTAL_FACES[d as usize] { out.push(Vertex { - pos: p.to_array(), - uv, - layer: 6, - color, - light: wrap, + pos: m.transform_point3(Vec3::from(c)).to_array(), + uv: [0.0; 2], + layer, + color: 0, + light: 0, }); } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 667e7d911..697cccc36 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -780,6 +780,13 @@ impl Dim { _ => Self::Overworld, } } + /// `Level.getMaxY`: the dimension type's minimum y plus height, less one. + fn max_y(self) -> i32 { + match self { + Self::Overworld => MIN_Y + HEIGHT - 1, + Self::Nether | Self::End => 255, + } + } } fn facing_offset(facing: &str) -> [i32; 3] { match facing { @@ -4126,10 +4133,16 @@ impl Game<'_> { -view_pitch.to_radians(), 0.0, ), - anim: &|_| horizon_client::block_entity_render::BlockAnim::default(), + // The client does not track End gateway ages and cooldowns yet: + // gateways render as settled (no beam). + anim: &|_| horizon_client::block_entity_render::BlockAnim { + gateway: (i64::MAX, 0), + ..Default::default() + }, texts: None, partial: alpha as f32, game_time: self.world.game_time, + max_y: self.dim.max_y(), world: &self.world, sprites: &self.res.atlas.sprites, nether: self.dim == Dim::Nether, diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 967bef7e4..439097c6c 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1236,6 +1236,7 @@ impl Game<'_> { texts: None, partial: 0.0, game_time: self.world.game_time, + max_y: self.dim.max_y(), world: &self.world, sprites: &self.res.atlas.sprites, nether: self.dim == super::Dim::Nether,