Compare block entity rendering with vanilla renderers
Add a differential harness (test_block_entity_render_parity) whose Java oracle runs each vanilla BlockEntityRenderer on a real block entity and captures the submitted model vertices, textures, light and text calls. Horizon now animates shulker lids, bell shakes, active conduits (cage, wind and the camera-facing eye), skull jaws and ears, pot wobble and sherd sides; signs wrap lines like StringSplitter and measure spaces with the font; books use the Mth sine table and player heads the slim default skin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
//! Headless transport for the block-entity render parity gate: replays each
|
||||
//! case (block state, light, partial tick and ticked block-entity fields)
|
||||
//! through `BlockEntityRenderer` at the block origin and writes the quads
|
||||
//! (texture, sprite-local UVs, baked colour, light) and sign text calls.
|
||||
#![forbid(unsafe_code)]
|
||||
use glam::{DVec3, Mat4, Quat};
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
banner::{self, Banners},
|
||||
block_entity_render::{BlockAnim, BlockEntityRenderer, Scene, TextCall},
|
||||
chunk::{Chunk, Light},
|
||||
hud::{HudAtlas, Rect},
|
||||
signs::{DYE_TEXT, SignData, SignText},
|
||||
world::World,
|
||||
};
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
fs,
|
||||
io::{BufWriter, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
/// Every texture the vanilla oracle used gets its own unit square on a small
|
||||
/// grid (offsets stay small so f32 UVs keep their precision), so a vertex's
|
||||
/// texture and sprite-local UV can be recovered.
|
||||
fn fake_sprites(list: &Path) -> Result<(HashMap<String, Rect>, Vec<String>, usize)> {
|
||||
let names: Vec<String> = fs::read_to_string(list)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let grid = (names.len() as f64).sqrt().ceil().max(1.0) as usize;
|
||||
let map = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, n)| {
|
||||
let (u0, v0) = ((i % grid) as f32 * 2.0, (i / grid) as f32 * 2.0);
|
||||
(
|
||||
n.clone(),
|
||||
Rect {
|
||||
u0,
|
||||
v0,
|
||||
u1: u0 + 1.0,
|
||||
v1: v0 + 1.0,
|
||||
w: 16,
|
||||
h: 16,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Ok((map, names, grid))
|
||||
}
|
||||
|
||||
fn find_state(registry: &BlockRegistry, spec: &str) -> Option<u32> {
|
||||
let (name, props) = match spec.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (spec, ""),
|
||||
};
|
||||
let wanted: Vec<(&str, &str)> = props
|
||||
.split(',')
|
||||
.filter(|p| !p.is_empty())
|
||||
.filter_map(|p| p.split_once('='))
|
||||
.collect();
|
||||
let default = registry.state(registry.default_state(name)?)?.clone();
|
||||
(0..registry.len() as u32).find(|&id| {
|
||||
registry.state(BlockStateId(id)).is_some_and(|s| {
|
||||
s.name == name
|
||||
&& s.properties.iter().all(|(k, v)| {
|
||||
wanted
|
||||
.iter()
|
||||
.find(|(wk, _)| wk == k)
|
||||
.map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn sign_side(v: &Value) -> SignText {
|
||||
let mut side = SignText::default();
|
||||
for (line, text) in side
|
||||
.lines
|
||||
.iter_mut()
|
||||
.zip(v["lines"].as_array().into_iter().flatten())
|
||||
{
|
||||
*line = text.as_str().unwrap_or_default().to_owned();
|
||||
}
|
||||
let color = v["color"].as_str().unwrap_or("black");
|
||||
side.color = DYE_TEXT.iter().position(|(n, _)| *n == color).unwrap_or(15) as u8;
|
||||
side.glowing = v["glowing"].as_bool().unwrap_or(false);
|
||||
side
|
||||
}
|
||||
|
||||
fn intern(s: &str) -> &'static str {
|
||||
match s {
|
||||
"north" => "north",
|
||||
"south" => "south",
|
||||
"west" => "west",
|
||||
"east" => "east",
|
||||
"up" => "up",
|
||||
_ => "down",
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
let [root, inputs, textures, output] = args.as_slice() else {
|
||||
return Err("usage: block_entity_render_fixture RESOURCES INPUTS TEXTURES OUTPUT".into());
|
||||
};
|
||||
let assets = Assets::load(root)?;
|
||||
let registry = assets.registry;
|
||||
let mut renderer = BlockEntityRenderer::load(root, registry)?;
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let banners = Banners::load(root);
|
||||
let (sprites, names, grid) = fake_sprites(textures)?;
|
||||
let air = registry.default_state("minecraft:air").ok_or("no air")?;
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let block = case["block"].as_str().unwrap_or_default();
|
||||
let Some(state) = find_state(registry, block) else {
|
||||
writeln!(out, "{}", json!({"skip": "unknown block state"}))?;
|
||||
continue;
|
||||
};
|
||||
if !renderer.renders(state) {
|
||||
writeln!(out, "{}", json!({"skip": "no renderer"}))?;
|
||||
continue;
|
||||
}
|
||||
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
|
||||
let float = |v: &Value| v.as_f64().unwrap_or(0.0) as f32;
|
||||
let pos = [
|
||||
int(&case["pos"][0]),
|
||||
int(&case["pos"][1]),
|
||||
int(&case["pos"][2]),
|
||||
];
|
||||
let packed = (int(&case["light"][0]) << 4 | int(&case["light"][1])) as u8;
|
||||
let mut world = World::new(air, 0);
|
||||
for dx in -1..=1 {
|
||||
for dz in -1..=1 {
|
||||
let (cx, cz) = ((pos[0] >> 4) + dx, (pos[2] >> 4) + dz);
|
||||
let mut chunk = Chunk::empty(cx, cz);
|
||||
for section in &mut chunk.sections {
|
||||
Arc::make_mut(section).light = Light::Uniform(packed);
|
||||
}
|
||||
world.chunks.insert((cx, cz), Arc::new(chunk));
|
||||
}
|
||||
}
|
||||
if let Some(book) = case.get("book") {
|
||||
renderer.set_book(
|
||||
pos,
|
||||
int(&book["time"]),
|
||||
["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])),
|
||||
);
|
||||
}
|
||||
let sign = case.get("sign").map(|s| {
|
||||
let mut data = SignData {
|
||||
hanging: block.contains("hanging"),
|
||||
..SignData::default()
|
||||
};
|
||||
data.front = sign_side(&s["front"]);
|
||||
data.back = sign_side(&s["back"]);
|
||||
data
|
||||
});
|
||||
let layers: Vec<(String, u32)> = case["patterns"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|p| {
|
||||
(
|
||||
banners.banner_texture(p[0].as_str().unwrap_or_default()),
|
||||
banner::dye_rgb(p[1].as_str().unwrap_or_default()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let anim = BlockAnim {
|
||||
shulker: (float(&case["progress"]), float(&case["progressOld"])),
|
||||
bell_ticks: int(&case["bellTicks"]),
|
||||
bell_shake: case["shake"].as_str().map(intern),
|
||||
conduit: (
|
||||
int(&case["conduit"]["tickCount"]),
|
||||
case["conduit"]["active"].as_bool().unwrap_or(false),
|
||||
case["conduit"]["hunting"].as_bool().unwrap_or(false),
|
||||
float(&case["conduit"]["activeRotation"]),
|
||||
),
|
||||
skull: (
|
||||
case["skullAnimation"][0].as_bool().unwrap_or(false),
|
||||
int(&case["skullAnimation"][1]),
|
||||
),
|
||||
sherds: [0, 1, 2, 3].map(|i| {
|
||||
case["sherds"][i]
|
||||
.as_str()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
}),
|
||||
wobble: case["wobble"]
|
||||
.as_array()
|
||||
.map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))),
|
||||
};
|
||||
let open = float(&case["open"]);
|
||||
let near = case["sign"]["near"].as_bool().unwrap_or(false);
|
||||
let camera = DVec3::new(
|
||||
case["camera"][0].as_f64().unwrap_or(0.0),
|
||||
case["camera"][1].as_f64().unwrap_or(0.0),
|
||||
case["camera"][2].as_f64().unwrap_or(0.0),
|
||||
);
|
||||
// Signs pick the outline from the camera distance: put the camera where the case says.
|
||||
let camera = if case.get("sign").is_some() {
|
||||
let centre = DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + 0.5;
|
||||
centre
|
||||
+ if near {
|
||||
DVec3::ZERO
|
||||
} else {
|
||||
DVec3::new(20.0, 0.0, 0.0)
|
||||
}
|
||||
} else {
|
||||
camera
|
||||
};
|
||||
let (yaw, pitch) = (float(&case["yaw"]), float(&case["pitch"]));
|
||||
let texts = RefCell::new(Vec::<TextCall>::new());
|
||||
let scene = Scene {
|
||||
camera,
|
||||
orientation: Quat::from_euler(
|
||||
glam::EulerRot::YXZ,
|
||||
std::f32::consts::PI - yaw * (std::f32::consts::PI / 180.0),
|
||||
-pitch * (std::f32::consts::PI / 180.0),
|
||||
0.0,
|
||||
),
|
||||
anim: &|_| anim.clone(),
|
||||
texts: Some(&texts),
|
||||
partial: float(&case["partial"]),
|
||||
game_time: 0,
|
||||
world: &world,
|
||||
sprites: &sprites,
|
||||
nether: false,
|
||||
lid: &|_| open,
|
||||
sign: &|_| sign.as_ref(),
|
||||
banner: &|_| layers.clone(),
|
||||
glyph: &|c| atlas.glyph_cell(c),
|
||||
};
|
||||
let mut verts = Vec::new();
|
||||
renderer.render_block(&scene, pos, state, Mat4::IDENTITY, packed, &mut verts);
|
||||
let quads: Vec<Value> = verts
|
||||
.chunks(4)
|
||||
.map(|q| {
|
||||
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)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let v: Vec<Value> = q
|
||||
.iter()
|
||||
.map(|v| {
|
||||
json!([
|
||||
v.pos[0],
|
||||
v.pos[1],
|
||||
v.pos[2],
|
||||
v.uv[0] - cu * 2.0,
|
||||
v.uv[1] - cv * 2.0
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
json!({"texture": texture, "v": v, "color": q[0].color, "light": q[0].light})
|
||||
})
|
||||
.collect();
|
||||
let texts: Vec<Value> = texts
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter(|t| !t.text.is_empty())
|
||||
.map(|t| {
|
||||
json!({"matrix": t.matrix.to_cols_array(), "x": t.x, "y": t.y, "text": t.text,
|
||||
"color": t.color, "outline": t.outline,
|
||||
"light": ((t.light & 0xFF) << 16 | (t.light >> 8 & 0xFF))})
|
||||
})
|
||||
.collect();
|
||||
writeln!(out, "{}", json!({"quads": quads, "texts": texts}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,7 +7,10 @@
|
||||
//! 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::random::{LegacyRandom, RandomSource};
|
||||
use horizon_core::{
|
||||
geometry::trig::Mth,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, f32::consts::PI, path::Path};
|
||||
@@ -582,19 +585,19 @@ fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32;
|
||||
"right_lid" => p[4] = -openness,
|
||||
"left_pages" => {
|
||||
p[4] = openness;
|
||||
p[0] = openness.sin();
|
||||
p[0] = openness.msin();
|
||||
}
|
||||
"right_pages" => {
|
||||
p[4] = -openness;
|
||||
p[0] = openness.sin();
|
||||
p[0] = openness.msin();
|
||||
}
|
||||
"flip_page1" => {
|
||||
p[4] = openness - openness * 2.0 * flip1;
|
||||
p[0] = openness.sin();
|
||||
p[0] = openness.msin();
|
||||
}
|
||||
"flip_page2" => {
|
||||
p[4] = openness - openness * 2.0 * flip2;
|
||||
p[0] = openness.sin();
|
||||
p[0] = openness.msin();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -603,94 +606,163 @@ fn frac(x: f32) -> f32 {
|
||||
x - x.floor()
|
||||
}
|
||||
|
||||
/// `StringSplitter.splitLines(...).get(0)` for plain text: the first line,
|
||||
/// wrapped at the last space that fits or mid-word when none does.
|
||||
fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let mut width = 0.0;
|
||||
let mut last_space = None;
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if c == '\n' {
|
||||
return chars[..i].iter().collect();
|
||||
}
|
||||
if c == ' ' {
|
||||
last_space = Some(i);
|
||||
}
|
||||
width += advance(c);
|
||||
if width > max_width {
|
||||
let end = match last_space {
|
||||
Some(s) if s > 0 => s,
|
||||
_ => i.max(1),
|
||||
};
|
||||
return chars[..end].iter().collect();
|
||||
}
|
||||
}
|
||||
line.to_owned()
|
||||
}
|
||||
|
||||
/// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text
|
||||
/// full-bright with an 8x outline in the dark colour.
|
||||
fn sign_text(
|
||||
fn sign_text_calls(
|
||||
scene: &Scene,
|
||||
data: &crate::signs::SignData,
|
||||
text: &crate::signs::SignText,
|
||||
m: Mat4,
|
||||
packed: u8,
|
||||
near: bool,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
) -> Vec<TextCall> {
|
||||
let line_height = data.line_height();
|
||||
let midpoint = (4.0 * line_height / 2.0).floor();
|
||||
let dark = text.dark_color();
|
||||
let dark = 0xFF00_0000 | text.dark_color();
|
||||
let (color, outline, light) = if text.glowing {
|
||||
let c = text.text_color();
|
||||
(c, (c == 0 || near).then_some(dark), 240 | 240 << 8)
|
||||
(
|
||||
0xFF00_0000 | c,
|
||||
if c == 0 || near { dark } else { 0 },
|
||||
240 | 240 << 8,
|
||||
)
|
||||
} else {
|
||||
(dark, None, vertex_light(packed))
|
||||
(dark, 0, vertex_light(packed))
|
||||
};
|
||||
let width = |s: &str| {
|
||||
s.chars()
|
||||
.map(|c| (scene.glyph)(c).map_or(6.0, |g| g.1))
|
||||
.sum::<f32>()
|
||||
};
|
||||
for (i, line) in text.lines.iter().enumerate() {
|
||||
// Font.split(line, maxWidth).get(0): keep what fits.
|
||||
let mut shown = String::new();
|
||||
for ch in line.chars() {
|
||||
shown.push(ch);
|
||||
if width(&shown) > data.max_line_width() {
|
||||
shown.pop();
|
||||
break;
|
||||
let advance = |c: char| (scene.glyph)(c).1;
|
||||
let width = |s: &str| s.chars().map(advance).sum::<f32>().ceil();
|
||||
text.lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, line)| {
|
||||
let shown = first_line(line, data.max_line_width(), &advance);
|
||||
TextCall {
|
||||
matrix: m,
|
||||
x: -((width(&shown) as i32) / 2) as f32,
|
||||
y: i as f32 * line_height - midpoint,
|
||||
text: shown,
|
||||
color,
|
||||
outline,
|
||||
light,
|
||||
}
|
||||
}
|
||||
let x0 = -(width(&shown) as i32 / 2) as f32;
|
||||
let y0 = i as f32 * line_height - midpoint;
|
||||
let mut emit = |dx: f32, dy: f32, rgb: u32| {
|
||||
let mut x = x0 + dx;
|
||||
for ch in shown.chars() {
|
||||
let Some((r, advance)) = (scene.glyph)(ch) else {
|
||||
x += 6.0;
|
||||
continue;
|
||||
};
|
||||
if ch != ' ' {
|
||||
let corners = [
|
||||
(x, y0 + dy + 8.0),
|
||||
(x + 8.0, y0 + dy + 8.0),
|
||||
(x + 8.0, y0 + dy),
|
||||
(x, y0 + dy),
|
||||
];
|
||||
let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]];
|
||||
let c =
|
||||
0xFF00_0000 | (rgb & 255) << 16 | (rgb >> 8 & 255) << 8 | (rgb >> 16 & 255);
|
||||
for ((cx, cy), uv) in corners.into_iter().zip(uvs) {
|
||||
out.push(Vertex {
|
||||
pos: m.transform_point3(Vec3::new(cx, cy, 0.0)).to_array(),
|
||||
uv,
|
||||
layer: 0,
|
||||
color: c,
|
||||
light,
|
||||
});
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Draws a text call with the font atlas: 8x8 glyph cells, the outline as
|
||||
/// eight one-pixel offsets under the text.
|
||||
fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec<Vertex>) {
|
||||
let mut emit = |dx: f32, dy: f32, argb: u32| {
|
||||
let mut x = call.x + dx;
|
||||
let y0 = call.y + dy;
|
||||
for ch in call.text.chars() {
|
||||
let (cell, advance) = (scene.glyph)(ch);
|
||||
if let Some(r) = cell {
|
||||
let corners = [(x, y0 + 8.0), (x + 8.0, y0 + 8.0), (x + 8.0, y0), (x, y0)];
|
||||
let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]];
|
||||
let c =
|
||||
0xFF00_0000 | (argb & 255) << 16 | (argb >> 8 & 255) << 8 | (argb >> 16 & 255);
|
||||
for ((cx, cy), uv) in corners.into_iter().zip(uvs) {
|
||||
out.push(Vertex {
|
||||
pos: call
|
||||
.matrix
|
||||
.transform_point3(Vec3::new(cx, cy, 0.0))
|
||||
.to_array(),
|
||||
uv,
|
||||
layer: 0,
|
||||
color: c,
|
||||
light: call.light,
|
||||
});
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
};
|
||||
if let Some(o) = outline {
|
||||
for (dx, dy) in [
|
||||
(-1.0, -1.0),
|
||||
(0.0, -1.0),
|
||||
(1.0, -1.0),
|
||||
(-1.0, 0.0),
|
||||
(1.0, 0.0),
|
||||
(-1.0, 1.0),
|
||||
(0.0, 1.0),
|
||||
(1.0, 1.0),
|
||||
] {
|
||||
emit(dx, dy, o);
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
};
|
||||
if call.outline != 0 {
|
||||
for (dx, dy) in [
|
||||
(-1.0, -1.0),
|
||||
(0.0, -1.0),
|
||||
(1.0, -1.0),
|
||||
(-1.0, 0.0),
|
||||
(1.0, 0.0),
|
||||
(-1.0, 1.0),
|
||||
(0.0, 1.0),
|
||||
(1.0, 1.0),
|
||||
] {
|
||||
emit(dx, dy, call.outline);
|
||||
}
|
||||
emit(0.0, 0.0, color);
|
||||
}
|
||||
emit(0.0, 0.0, call.color);
|
||||
}
|
||||
|
||||
/// Block-entity fields the level ticks, at one position (vanilla's own field
|
||||
/// values; extraction to render state happens here as in each renderer).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct BlockAnim {
|
||||
/// `ShulkerBoxBlockEntity` progress and progressOld.
|
||||
pub shulker: (f32, f32),
|
||||
/// `BellBlockEntity.ticks` and the click direction while `shaking`.
|
||||
pub bell_ticks: i32,
|
||||
pub bell_shake: Option<&'static str>,
|
||||
/// `ConduitBlockEntity` tickCount, isActive, isHunting and activeRotation.
|
||||
pub conduit: (i32, bool, bool, f32),
|
||||
/// `SkullBlockEntity` isAnimating and animationTickCount.
|
||||
pub skull: (bool, i32),
|
||||
/// `DecoratedPotBlockEntity` decorations as item ids: back, left, right, front.
|
||||
pub sherds: [Option<String>; 4],
|
||||
/// `DecoratedPotRenderState` wobble style (positive) and progress.
|
||||
pub wobble: Option<(bool, f32)>,
|
||||
}
|
||||
|
||||
/// One `submitText` call (`AbstractSignRenderer.submitSignText`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextCall {
|
||||
pub matrix: Mat4,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub text: String,
|
||||
/// ARGB.
|
||||
pub color: u32,
|
||||
/// ARGB outline colour, 0 for none.
|
||||
pub outline: u32,
|
||||
/// Horizon packed light (sky*16 | block*16 << 8).
|
||||
pub light: u32,
|
||||
}
|
||||
|
||||
/// Inputs from the game for one frame of block-entity rendering.
|
||||
pub struct Scene<'a> {
|
||||
pub camera: DVec3,
|
||||
/// `Camera.rotation` (conduit eyes face the camera).
|
||||
pub orientation: Quat,
|
||||
/// Ticked block-entity state at a position.
|
||||
pub anim: &'a dyn Fn([i32; 3]) -> BlockAnim,
|
||||
/// When set, sign text is recorded here as text calls instead of drawn.
|
||||
pub texts: Option<&'a std::cell::RefCell<Vec<TextCall>>>,
|
||||
pub partial: f32,
|
||||
pub game_time: i64,
|
||||
pub world: &'a World,
|
||||
@@ -702,8 +774,8 @@ pub struct Scene<'a> {
|
||||
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
|
||||
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
|
||||
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
|
||||
/// Font glyph cell and advance.
|
||||
pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>,
|
||||
/// Font glyph cell (none for blank glyphs such as the space) and advance.
|
||||
pub glyph: &'a dyn Fn(char) -> (Option<Rect>, f32),
|
||||
}
|
||||
|
||||
pub struct BlockEntityRenderer {
|
||||
@@ -711,8 +783,10 @@ pub struct BlockEntityRenderer {
|
||||
kinds: Vec<Kind>,
|
||||
books: HashMap<[i32; 3], Book>,
|
||||
random: LegacyRandom,
|
||||
/// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`).
|
||||
pot_patterns: HashMap<String, String>,
|
||||
}
|
||||
const MODELS: [(&str, &str); 24] = [
|
||||
const MODELS: [(&str, &str); 27] = [
|
||||
("chest", "minecraft:chest#main"),
|
||||
("double_chest_left", "minecraft:double_chest_left#main"),
|
||||
("double_chest_right", "minecraft:double_chest_right#main"),
|
||||
@@ -734,6 +808,9 @@ const MODELS: [(&str, &str); 24] = [
|
||||
("bell", "minecraft:bell#main"),
|
||||
("book", "minecraft:book#main"),
|
||||
("conduit_shell", "minecraft:conduit#shell"),
|
||||
("conduit_cage", "minecraft:conduit#cage"),
|
||||
("conduit_wind", "minecraft:conduit#wind"),
|
||||
("conduit_eye", "minecraft:conduit#eye"),
|
||||
("decorated_pot_base", "minecraft:decorated_pot_base#main"),
|
||||
("decorated_pot_sides", "minecraft:decorated_pot_sides#main"),
|
||||
("copper_golem", "minecraft:copper_golem#main"),
|
||||
@@ -757,7 +834,30 @@ impl BlockEntityRenderer {
|
||||
.iter()
|
||||
.filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v))))
|
||||
.collect();
|
||||
Ok(Self::new(models, registry))
|
||||
let mut renderer = Self::new(models, 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)?;
|
||||
for (item, components) in items.as_object().into_iter().flatten() {
|
||||
let Some(pattern) = components["minecraft:provides_pottery_pattern"].as_str()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let name = pattern.strip_prefix("minecraft:").unwrap_or(pattern);
|
||||
let file = root.join(format!("data/minecraft/decorated_pot_pattern/{name}.json"));
|
||||
let Ok(def) = std::fs::read(file) else {
|
||||
continue;
|
||||
};
|
||||
let def: Value = serde_json::from_slice(&def)?;
|
||||
if let Some(asset) = def["asset_id"].as_str() {
|
||||
let asset = asset.strip_prefix("minecraft:").unwrap_or(asset);
|
||||
renderer
|
||||
.pot_patterns
|
||||
.insert(item.clone(), format!("entity/decorated_pot/{asset}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(renderer)
|
||||
}
|
||||
fn new(models: HashMap<&'static str, ModelPart>, registry: &BlockRegistry) -> Self {
|
||||
let kinds = (0..registry.len() as u32)
|
||||
@@ -773,6 +873,7 @@ impl BlockEntityRenderer {
|
||||
kinds,
|
||||
books: HashMap::new(),
|
||||
random: LegacyRandom::new(0x5EED_B00C),
|
||||
pot_patterns: HashMap::new(),
|
||||
}
|
||||
}
|
||||
/// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`).
|
||||
@@ -831,6 +932,41 @@ impl BlockEntityRenderer {
|
||||
self.render_one(scene, *pos, kind, base, packed, lights, out);
|
||||
}
|
||||
}
|
||||
/// One block entity at `pos` drawn under `base` with the given packed light
|
||||
/// (the parity fixture's entry point).
|
||||
pub fn render_block(
|
||||
&self,
|
||||
scene: &Scene,
|
||||
pos: [i32; 3],
|
||||
state: u32,
|
||||
base: Mat4,
|
||||
packed: u8,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let kind = self.kind(state);
|
||||
let lights = diffuse_lights(scene.nether);
|
||||
self.render_one(scene, pos, kind, base, packed, lights, out);
|
||||
}
|
||||
/// Whether this block state has a block-entity renderer here.
|
||||
pub fn renders(&self, state: u32) -> bool {
|
||||
!matches!(self.kind(state), Kind::None)
|
||||
}
|
||||
/// Sets an enchanting table's book fields (`EnchantingTableBlockEntity`):
|
||||
/// time, flip, oFlip, open, oOpen, rot, oRot.
|
||||
pub fn set_book(&mut self, pos: [i32; 3], time: i32, fields: [f32; 6]) {
|
||||
let [flip, o_flip, open, o_open, rot, o_rot] = fields;
|
||||
let book = self.books.entry(pos).or_default();
|
||||
*book = Book {
|
||||
time,
|
||||
flip,
|
||||
o_flip,
|
||||
open,
|
||||
o_open,
|
||||
rot,
|
||||
o_rot,
|
||||
..*book
|
||||
};
|
||||
}
|
||||
/// One block entity of `state` drawn under `base` (minecart contents).
|
||||
pub fn render_state(
|
||||
&self,
|
||||
@@ -913,7 +1049,11 @@ impl BlockEntityRenderer {
|
||||
)
|
||||
.distance_squared(scene.camera)
|
||||
< 256.0;
|
||||
sign_text(scene, data, text, m, packed, near, out);
|
||||
let calls = sign_text_calls(scene, data, text, m, packed, near);
|
||||
match scene.texts {
|
||||
Some(sink) => sink.borrow_mut().extend(calls),
|
||||
None => calls.iter().for_each(|c| draw_text(scene, c, out)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Chest {
|
||||
@@ -968,8 +1108,18 @@ impl BlockEntityRenderer {
|
||||
* Mat4::from_quat(direction_rotation(facing))
|
||||
* Mat4::from_scale(Vec3::new(1.0, -1.0, -1.0))
|
||||
* Mat4::from_translation(Vec3::new(0.0, -1.0, 0.0));
|
||||
// ShulkerBoxModel.setupAnim(progress = 0): closed lid.
|
||||
draw_part(model, "root", m, &none, paint, out);
|
||||
// ShulkerBoxModel.setupAnim(getProgress(partial)): the lid rises and turns.
|
||||
let (progress, old) = (scene.anim)(pos).shulker;
|
||||
let progress = old + scene.partial * (progress - old);
|
||||
let lid = move |name: &str, p: &mut [f32; 9]| {
|
||||
if name == "lid" {
|
||||
p[0] = 0.0;
|
||||
p[1] = 24.0 - progress * 0.5 * 16.0;
|
||||
p[2] = 0.0;
|
||||
p[4] = 270.0 * progress * (PI / 180.0);
|
||||
}
|
||||
};
|
||||
draw_part(model, "root", m, &lid, paint, out);
|
||||
}
|
||||
Kind::Banner { color, wall, angle } => {
|
||||
let (main, flag) = if *wall {
|
||||
@@ -995,7 +1145,7 @@ impl BlockEntityRenderer {
|
||||
/ 100.0;
|
||||
let wave = move |name: &str, p: &mut [f32; 9]| {
|
||||
if name == "flag" {
|
||||
p[3] = (-0.0125 + 0.01 * (2.0 * PI * phase).cos()) * PI;
|
||||
p[3] = (-0.0125 + 0.01 * (2.0 * PI * phase).mcos()) * PI;
|
||||
}
|
||||
};
|
||||
if let Some(paint) = paint("entity/banner/banner_base", 0xFFFFFF, packed) {
|
||||
@@ -1027,7 +1177,7 @@ impl BlockEntityRenderer {
|
||||
SkullType::Creeper => ("creeper_head", "entity/creeper/creeper"),
|
||||
SkullType::Dragon => ("dragon_skull", "entity/enderdragon/dragon"),
|
||||
SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"),
|
||||
SkullType::Player => ("player_head", "entity/player/wide/steve"),
|
||||
SkullType::Player => ("player_head", "entity/player/slim/steve"),
|
||||
};
|
||||
let (Some(model), Some(paint)) =
|
||||
(self.models.get(model), paint(texture, 0xFFFFFF, packed))
|
||||
@@ -1050,11 +1200,16 @@ impl BlockEntityRenderer {
|
||||
* Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0))
|
||||
}
|
||||
};
|
||||
// SkullModelBase.State with animationPos 0 (unpowered).
|
||||
let anim = |name: &str, p: &mut [f32; 9]| match name {
|
||||
"jaw" => p[3] = (0.0f32.sin() + 1.0) * 0.2,
|
||||
"left_ear" => p[5] = -(1.0 + 2.5) * 0.2,
|
||||
"right_ear" => p[5] = (1.0 + 2.5) * 0.2,
|
||||
// SkullBlockEntity.getAnimation: the dragon jaw and piglin ears
|
||||
// (DragonHeadModel / PiglinHeadModel use double-precision Math).
|
||||
let (animating, count) = (scene.anim)(pos).skull;
|
||||
let t = count as f32 + if animating { scene.partial } else { 0.0 };
|
||||
let anim = move |name: &str, p: &mut [f32; 9]| match name {
|
||||
"jaw" => p[3] = (f64::from(t * PI * 0.2).sin() + 1.0) as f32 * 0.2,
|
||||
"left_ear" => {
|
||||
p[5] = -((f64::from(t * PI * 0.2 * 1.2).cos() + 2.5) as f32) * 0.2;
|
||||
}
|
||||
"right_ear" => p[5] = (f64::from(t * PI * 0.2).cos() + 2.5) as f32 * 0.2,
|
||||
_ => {}
|
||||
};
|
||||
draw_part(model, "root", m, &anim, paint, out);
|
||||
@@ -1066,7 +1221,27 @@ impl BlockEntityRenderer {
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
draw_part(model, "root", base, &none, paint, out);
|
||||
// BellModel.setupAnim(State(ticks + partial, shakeDirection)).
|
||||
let a = (scene.anim)(pos);
|
||||
let ticks = a.bell_ticks as f32 + scene.partial;
|
||||
let (mut x_rot, mut z_rot) = (0.0, 0.0);
|
||||
if let Some(dir) = a.bell_shake {
|
||||
let base_rot = (ticks / PI).msin() / (4.0 + ticks / 3.0);
|
||||
match dir {
|
||||
"north" => x_rot = -base_rot,
|
||||
"south" => x_rot = base_rot,
|
||||
"east" => z_rot = -base_rot,
|
||||
"west" => z_rot = base_rot,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let shake = move |name: &str, p: &mut [f32; 9]| {
|
||||
if name == "bell_body" {
|
||||
p[3] = x_rot;
|
||||
p[5] = z_rot;
|
||||
}
|
||||
};
|
||||
draw_part(model, "root", base, &shake, paint, out);
|
||||
}
|
||||
Kind::DecoratedPot { y_rot } => {
|
||||
let (Some(base_model), Some(sides)) = (
|
||||
@@ -1075,38 +1250,111 @@ impl BlockEntityRenderer {
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let m = base
|
||||
let a = (scene.anim)(pos);
|
||||
let mut m = base
|
||||
* around(
|
||||
Mat4::from_rotation_y((180.0 - y_rot).to_radians()),
|
||||
Vec3::splat(0.5),
|
||||
);
|
||||
// DecoratedPotRenderer.submit: the wobble tilts around the base centre.
|
||||
let pivot = Vec3::new(0.5, 0.0, 0.5);
|
||||
if let Some((positive, progress)) = a.wobble
|
||||
&& (0.0..=1.0).contains(&progress)
|
||||
{
|
||||
if positive {
|
||||
let delta = progress * (PI * 2.0);
|
||||
let tilt_x = -1.5 * (delta.mcos() + 0.5) * (delta / 2.0).msin();
|
||||
m *= around(Mat4::from_rotation_x(tilt_x * 0.015_625), pivot);
|
||||
let tilt_z = delta.msin();
|
||||
m *= around(Mat4::from_rotation_z(tilt_z * 0.015_625), pivot);
|
||||
} else {
|
||||
let turn = (-progress * 3.0 * PI).msin() * 0.125;
|
||||
let decay = 1.0 - progress;
|
||||
m *= around(Mat4::from_rotation_y(turn * decay), pivot);
|
||||
}
|
||||
}
|
||||
if let Some(paint) =
|
||||
paint("entity/decorated_pot/decorated_pot_base", 0xFFFFFF, packed)
|
||||
{
|
||||
draw_part(base_model, "root", m, &none, paint, out);
|
||||
}
|
||||
if let Some(paint) =
|
||||
paint("entity/decorated_pot/decorated_pot_side", 0xFFFFFF, packed)
|
||||
{
|
||||
draw_part(sides, "root", m, &none, paint, out);
|
||||
// PotDecorations (back, left, right, front); items without a pattern use the blank side.
|
||||
for (side, item) in ["back", "left", "right", "front"].iter().zip(&a.sherds) {
|
||||
let texture = item
|
||||
.as_ref()
|
||||
.and_then(|i| self.pot_patterns.get(i))
|
||||
.map_or("entity/decorated_pot/decorated_pot_side", String::as_str);
|
||||
if let (Some(part), Some(paint)) =
|
||||
(sides.child(side), paint(texture, 0xFFFFFF, packed))
|
||||
{
|
||||
draw_part(part, side, m, &none, paint, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Conduit => {
|
||||
// Inactive conduit (no frame scan yet): the shell at activeRotation 0.
|
||||
let (Some(model), Some(paint)) = (
|
||||
self.models.get("conduit_shell"),
|
||||
paint("entity/conduit/base", 0xFFFFFF, packed),
|
||||
) else {
|
||||
let (ticks, active, hunting, raw_rotation) = (scene.anim)(pos).conduit;
|
||||
// ConduitRenderer.extractRenderState.
|
||||
let rotation = (raw_rotation + if active { scene.partial } else { 0.0 }) * -0.0375;
|
||||
let tex = |name: &str| paint(name, 0xFFFFFF, packed);
|
||||
if !active {
|
||||
let (Some(model), Some(paint)) =
|
||||
(self.models.get("conduit_shell"), tex("entity/conduit/base"))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let m = base
|
||||
* Mat4::from_translation(Vec3::splat(0.5))
|
||||
* Mat4::from_rotation_y(rotation.to_radians());
|
||||
draw_part(model, "root", m, &none, paint, out);
|
||||
return;
|
||||
}
|
||||
let anim_time = ticks as f32 + scene.partial;
|
||||
let phase = ticks / 66 % 3;
|
||||
let degrees = rotation * (180.0 / PI);
|
||||
let hh = (anim_time * 0.1).msin() / 2.0 + 0.5;
|
||||
let hh = hh * hh + hh;
|
||||
let lift = Vec3::new(0.5, 0.3 + hh * 0.2, 0.5);
|
||||
if let (Some(model), Some(paint)) =
|
||||
(self.models.get("conduit_cage"), tex("entity/conduit/cage"))
|
||||
{
|
||||
let axis = Vec3::new(0.5, 1.0, 0.5).normalize();
|
||||
let m = base
|
||||
* Mat4::from_translation(lift)
|
||||
* Mat4::from_quat(Quat::from_axis_angle(axis, degrees * (PI / 180.0)));
|
||||
draw_part(model, "root", m, &none, paint, out);
|
||||
}
|
||||
let wind = if phase == 1 {
|
||||
"entity/conduit/wind_vertical"
|
||||
} else {
|
||||
"entity/conduit/wind"
|
||||
};
|
||||
draw_part(
|
||||
model,
|
||||
"root",
|
||||
base * Mat4::from_translation(Vec3::splat(0.5)),
|
||||
&none,
|
||||
paint,
|
||||
out,
|
||||
);
|
||||
if let (Some(model), Some(paint)) = (self.models.get("conduit_wind"), tex(wind)) {
|
||||
let turn = match phase {
|
||||
1 => Mat4::from_rotation_x(PI / 2.0),
|
||||
2 => Mat4::from_rotation_z(PI / 2.0),
|
||||
_ => Mat4::IDENTITY,
|
||||
};
|
||||
let center = base * Mat4::from_translation(Vec3::splat(0.5));
|
||||
draw_part(model, "root", center * turn, &none, paint, out);
|
||||
let inner = center
|
||||
* Mat4::from_scale(Vec3::splat(0.875))
|
||||
* Mat4::from_quat(Quat::from_euler(glam::EulerRot::XYZ, PI, 0.0, PI));
|
||||
draw_part(model, "root", inner, &none, paint, out);
|
||||
}
|
||||
let eye = if hunting {
|
||||
"entity/conduit/open_eye"
|
||||
} else {
|
||||
"entity/conduit/closed_eye"
|
||||
};
|
||||
if let (Some(model), Some(paint)) = (self.models.get("conduit_eye"), tex(eye)) {
|
||||
let m = base
|
||||
* Mat4::from_translation(lift)
|
||||
* Mat4::from_scale(Vec3::splat(0.5))
|
||||
* Mat4::from_quat(scene.orientation)
|
||||
* Mat4::from_quat(Quat::from_rotation_z(PI) * Quat::from_rotation_y(PI))
|
||||
* Mat4::from_scale(Vec3::splat(1.333_333_4));
|
||||
draw_part(model, "root", m, &none, paint, out);
|
||||
}
|
||||
}
|
||||
Kind::EnchantingTable => {
|
||||
let (Some(model), Some(paint)) = (
|
||||
@@ -1123,12 +1371,13 @@ impl BlockEntityRenderer {
|
||||
let y_rot = b.o_rot + wrap(b.rot - b.o_rot) * a;
|
||||
let m = base
|
||||
* Mat4::from_translation(Vec3::new(0.5, 0.75, 0.5))
|
||||
* Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).sin() * 0.01, 0.0))
|
||||
* Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).msin() * 0.01, 0.0))
|
||||
* Mat4::from_rotation_y(-y_rot)
|
||||
* Mat4::from_rotation_z(80f32.to_radians());
|
||||
let ff1 = (frac(flip + 0.25) * 1.6 - 0.3).clamp(0.0, 1.0);
|
||||
let ff2 = (frac(flip + 0.75) * 1.6 - 0.3).clamp(0.0, 1.0);
|
||||
let openness = ((time * 0.02).sin() * 0.1 + 1.25) * open;
|
||||
// BookModel.State.forAnimation.
|
||||
let openness = ((time * 0.02).msin() * 0.1 + 1.25) * open;
|
||||
draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out);
|
||||
}
|
||||
Kind::Lectern { y_rot } => {
|
||||
|
||||
@@ -4483,8 +4483,22 @@ impl Game<'_> {
|
||||
.unwrap_or((0.0, 0.0));
|
||||
prev + (cur - prev) * alpha as f32
|
||||
};
|
||||
let (view_yaw, view_pitch) = if self.camera_type == perspective::CameraType::ThirdPersonFront {
|
||||
(self.yaw + 180.0, -self.pitch)
|
||||
} else {
|
||||
(self.yaw, self.pitch)
|
||||
};
|
||||
let scene = horizon_client::block_entity_render::Scene {
|
||||
camera,
|
||||
// Camera.setRotation.
|
||||
orientation: glam::Quat::from_euler(
|
||||
glam::EulerRot::YXZ,
|
||||
std::f32::consts::PI - view_yaw.to_radians(),
|
||||
-view_pitch.to_radians(),
|
||||
0.0,
|
||||
),
|
||||
anim: &|_| horizon_client::block_entity_render::BlockAnim::default(),
|
||||
texts: None,
|
||||
partial: alpha as f32,
|
||||
game_time: self.world.game_time,
|
||||
world: &self.world,
|
||||
@@ -4496,7 +4510,7 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
},
|
||||
banner: &|p| self.banner_layers_at(p),
|
||||
glyph: &|c| self.res.atlas.glyph(c),
|
||||
glyph: &|c| self.res.atlas.glyph_cell(c),
|
||||
};
|
||||
self.res
|
||||
.block_entity_render
|
||||
|
||||
@@ -1231,6 +1231,9 @@ impl Game<'_> {
|
||||
let lid = |_: [i32; 3]| 0.0;
|
||||
let scene = horizon_client::block_entity_render::Scene {
|
||||
camera: glam::DVec3::ZERO,
|
||||
orientation: glam::Quat::IDENTITY,
|
||||
anim: &|_| horizon_client::block_entity_render::BlockAnim::default(),
|
||||
texts: None,
|
||||
partial: 0.0,
|
||||
game_time: self.world.game_time,
|
||||
world: &self.world,
|
||||
@@ -1239,7 +1242,7 @@ impl Game<'_> {
|
||||
lid: &lid,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
glyph: &|c| self.res.atlas.glyph(c),
|
||||
glyph: &|c| self.res.atlas.glyph_cell(c),
|
||||
};
|
||||
self.res
|
||||
.block_entity_render
|
||||
|
||||
@@ -68,6 +68,11 @@ impl HudAtlas {
|
||||
let g = self.font.glyph(ch);
|
||||
g.rect.map(|rect| (rect, g.advance))
|
||||
}
|
||||
/// A font glyph's atlas cell (none for blank glyphs such as the space) and advance.
|
||||
pub fn glyph_cell(&self, ch: char) -> (Option<Rect>, f32) {
|
||||
let g = self.font.glyph(ch);
|
||||
(g.rect, g.advance)
|
||||
}
|
||||
pub fn build(root: &Path) -> Result<Self> {
|
||||
let textures = root.join("assets/minecraft/textures");
|
||||
let mut files = Vec::new();
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.blaze3d.font.GlyphInfo;
|
||||
import com.mojang.blaze3d.font.GlyphProvider;
|
||||
import com.mojang.blaze3d.font.UnbakedGlyph;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GlyphSource;
|
||||
import net.minecraft.client.gui.font.glyphs.BakedGlyph;
|
||||
import net.minecraft.client.gui.font.providers.GlyphProviderDefinition;
|
||||
import net.minecraft.client.gui.font.TextRenderable;
|
||||
import net.minecraft.network.chat.FontDescription;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.util.RandomSource;
|
||||
|
||||
/**
|
||||
* The vanilla default font's glyph metrics without a GPU: the `space` and
|
||||
* `include/default` providers of the client jar loaded by vanilla's own
|
||||
* provider definitions (BitmapProvider scans ascii.png etc. for advances).
|
||||
* Glyphs carry metrics only; nothing is stitched.
|
||||
*/
|
||||
public final class ParityFont {
|
||||
public static ResourceManager resources() throws Exception {
|
||||
var method = net.minecraft.client.resources.ClientPackSource.class.getDeclaredMethod("createVanillaPackSource", Path.class);
|
||||
method.setAccessible(true);
|
||||
var pack = (net.minecraft.server.packs.VanillaPackResources) method.invoke(null, Path.of("/nonexistent-horizon-assets"));
|
||||
return pack.asResourceManager();
|
||||
}
|
||||
|
||||
public static Font create(ResourceManager resources) throws Exception {
|
||||
List<GlyphProvider> providers = new ArrayList<>();
|
||||
for (String include : new String[] {"space", "default"}) {
|
||||
var id = Identifier.withDefaultNamespace("font/include/" + include + ".json");
|
||||
try (var reader = new InputStreamReader(resources.open(id), StandardCharsets.UTF_8)) {
|
||||
var json = JsonParser.parseReader(reader).getAsJsonObject();
|
||||
for (var element : json.getAsJsonArray("providers")) {
|
||||
var conditional = GlyphProviderDefinition.Conditional.CODEC.parse(JsonOps.INSTANCE, element).getOrThrow();
|
||||
var loader = conditional.definition().unpack().left().orElseThrow();
|
||||
providers.add(loader.load(resources));
|
||||
}
|
||||
}
|
||||
}
|
||||
GlyphSource source = new GlyphSource() {
|
||||
@Override
|
||||
public BakedGlyph getGlyph(int codepoint) {
|
||||
for (GlyphProvider provider : providers) {
|
||||
UnbakedGlyph glyph = provider.getGlyph(codepoint);
|
||||
if (glyph != null) return baked(glyph.info());
|
||||
}
|
||||
return baked(GlyphInfo.simple(6.0F));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedGlyph getRandomGlyph(RandomSource random, int width) {
|
||||
return getGlyph('?');
|
||||
}
|
||||
};
|
||||
return new Font(new Font.Provider() {
|
||||
@Override
|
||||
public GlyphSource glyphs(FontDescription font) {
|
||||
return source;
|
||||
}
|
||||
|
||||
@Override
|
||||
public net.minecraft.client.gui.font.glyphs.EffectGlyph effect() {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static BakedGlyph baked(GlyphInfo info) {
|
||||
return new BakedGlyph() {
|
||||
@Override
|
||||
public GlyphInfo info() {
|
||||
return info;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextRenderable.Styled createGlyph(float x, float y, int color, int shadowColor, Style style, float boldOffset, float shadowOffset) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.model.Model;
|
||||
import net.minecraft.client.model.geom.EntityModelSet;
|
||||
import net.minecraft.client.model.geom.LayerDefinitions;
|
||||
import net.minecraft.client.renderer.SubmitNodeCollector;
|
||||
import net.minecraft.client.renderer.blockentity.*;
|
||||
import net.minecraft.client.renderer.blockentity.state.*;
|
||||
import net.minecraft.client.renderer.rendertype.RenderType;
|
||||
import net.minecraft.client.renderer.state.level.CameraRenderState;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.texture.UvMapping;
|
||||
import net.minecraft.client.resources.model.sprite.SpriteGetter;
|
||||
import net.minecraft.client.resources.model.sprite.SpriteId;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.minecraft.world.item.DyeColor;
|
||||
import net.minecraft.world.item.ItemStackTemplate;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.entity.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.ChestType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
/**
|
||||
* Original oracle for block-entity rendering: each case builds a vanilla block
|
||||
* entity for a block state, sets its animation fields, runs the real
|
||||
* renderer's extractRenderState and submit, and captures every submitted
|
||||
* model (vertices after setupAnim and the pose stack, sprite-local UVs, tint,
|
||||
* light), text call and item. Level-backed inputs (light, chest lid
|
||||
* openness, pot wobble) come from the case because the entity has no level.
|
||||
*
|
||||
* Input lines: case JSON. Output lines: {case, submits:[...]} or {case, error}.
|
||||
*/
|
||||
public final class VanillaBlockEntityRenderOracle {
|
||||
private static final Map<TextureAtlasSprite, SpriteId> SPRITES = new IdentityHashMap<>();
|
||||
private static Object unsafe;
|
||||
private static Method allocate;
|
||||
|
||||
static String textureName(Identifier id) {
|
||||
String path = id.getPath();
|
||||
if (path.startsWith("textures/")) path = path.substring(9);
|
||||
if (path.endsWith(".png")) path = path.substring(0, path.length() - 4);
|
||||
return id.getNamespace().equals("minecraft") ? path : id.getNamespace() + ":" + path;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Identifier renderTypeTexture(RenderType type) throws Exception {
|
||||
Field state = RenderType.class.getDeclaredField("state");
|
||||
state.setAccessible(true);
|
||||
Object setup = state.get(type);
|
||||
Field textures = setup.getClass().getDeclaredField("textures");
|
||||
textures.setAccessible(true);
|
||||
var map = (Map<String, Object>) textures.get(setup);
|
||||
Object binding = map.get("Sampler0");
|
||||
if (binding == null) return null;
|
||||
Method location = binding.getClass().getDeclaredMethod("location");
|
||||
location.setAccessible(true);
|
||||
return (Identifier) location.invoke(binding);
|
||||
}
|
||||
|
||||
static JsonArray matrix(Matrix4f m) {
|
||||
var a = new JsonArray();
|
||||
float[] f = new float[16];
|
||||
m.get(f);
|
||||
for (float x : f) a.add(x);
|
||||
return a;
|
||||
}
|
||||
|
||||
/** A vertex consumer recording [x,y,z,color,u,v,overlay,light,nx,ny,nz]. */
|
||||
static VertexConsumer recorder(List<float[]> out) {
|
||||
InvocationHandler handler = new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args);
|
||||
float[] v = out.isEmpty() ? null : out.get(out.size() - 1);
|
||||
switch (method.getName()) {
|
||||
case "addVertex" -> out.add(new float[] {(float) args[0], (float) args[1], (float) args[2], 0, 0, 0, 0, 0, 0, 0, 0});
|
||||
case "setColor" -> v[3] = Float.intBitsToFloat(args.length == 1 ? (int) args[0]
|
||||
: ((int) args[3] << 24) | ((int) args[0] << 16) | ((int) args[1] << 8) | (int) args[2]);
|
||||
case "setUv" -> { v[4] = (float) args[0]; v[5] = (float) args[1]; }
|
||||
case "setUv1" -> v[6] = Float.intBitsToFloat(((int) args[0]) | ((int) args[1] << 16));
|
||||
case "setUv2" -> v[7] = Float.intBitsToFloat(((int) args[0]) | ((int) args[1] << 16));
|
||||
case "setNormal" -> { v[8] = (float) args[0]; v[9] = (float) args[1]; v[10] = (float) args[2]; }
|
||||
default -> { }
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
};
|
||||
return (VertexConsumer) Proxy.newProxyInstance(VertexConsumer.class.getClassLoader(), new Class<?>[] {VertexConsumer.class}, handler);
|
||||
}
|
||||
|
||||
static JsonArray vertices(List<float[]> verts) {
|
||||
var out = new JsonArray();
|
||||
for (float[] v : verts) {
|
||||
var a = new JsonArray();
|
||||
a.add(v[0]); a.add(v[1]); a.add(v[2]);
|
||||
a.add(Float.floatToRawIntBits(v[3]));
|
||||
a.add(v[4]); a.add(v[5]);
|
||||
a.add(Float.floatToRawIntBits(v[6])); a.add(Float.floatToRawIntBits(v[7]));
|
||||
a.add(v[8]); a.add(v[9]); a.add(v[10]);
|
||||
out.add(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static String text(FormattedCharSequence sequence) {
|
||||
var sb = new StringBuilder();
|
||||
sequence.accept((index, style, codepoint) -> {
|
||||
sb.appendCodePoint(codepoint);
|
||||
return true;
|
||||
});
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static SubmitNodeCollector collector(JsonArray submits) {
|
||||
InvocationHandler handler = new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
String name = method.getName();
|
||||
if (name.equals("order")) return proxy;
|
||||
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args);
|
||||
var submit = new JsonObject();
|
||||
submit.addProperty("type", name);
|
||||
switch (name) {
|
||||
case "submitModel" -> {
|
||||
var model = (Model) args[0];
|
||||
var pose = (PoseStack) args[2];
|
||||
var renderType = (RenderType) args[3];
|
||||
var uv = (UvMapping) args[7];
|
||||
String texture;
|
||||
if (uv instanceof TextureAtlasSprite sprite && SPRITES.containsKey(sprite))
|
||||
texture = textureName(SPRITES.get(sprite).texture());
|
||||
else {
|
||||
Identifier t = renderTypeTexture(renderType);
|
||||
texture = t == null ? "?" : textureName(t);
|
||||
}
|
||||
submit.addProperty("texture", texture);
|
||||
submit.addProperty("renderType", renderType.toString().split("\\[")[0]);
|
||||
submit.addProperty("light", (int) args[4]);
|
||||
submit.addProperty("overlay", (int) args[5]);
|
||||
submit.addProperty("tint", (int) args[6]);
|
||||
model.setupAnim(args[1]);
|
||||
List<float[]> verts = new ArrayList<>();
|
||||
model.renderToBuffer(pose, recorder(verts), (int) args[4], (int) args[5], (int) args[6]);
|
||||
submit.add("vertices", vertices(verts));
|
||||
}
|
||||
case "submitText" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
submit.add("matrix", matrix(pose.last().pose()));
|
||||
submit.addProperty("x", (float) args[1]);
|
||||
submit.addProperty("y", (float) args[2]);
|
||||
submit.addProperty("text", text((FormattedCharSequence) args[3]));
|
||||
submit.addProperty("shadow", (boolean) args[4]);
|
||||
submit.addProperty("mode", args[5].toString());
|
||||
submit.addProperty("light", (int) args[6]);
|
||||
submit.addProperty("color", (int) args[7]);
|
||||
submit.addProperty("background", (int) args[8]);
|
||||
submit.addProperty("outline", (int) args[9]);
|
||||
}
|
||||
case "submitCustomGeometry" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
var renderType = (RenderType) args[1];
|
||||
Identifier t = renderTypeTexture(renderType);
|
||||
submit.addProperty("texture", t == null ? "?" : textureName(t));
|
||||
submit.addProperty("renderType", renderType.toString().split("\\[")[0]);
|
||||
List<float[]> verts = new ArrayList<>();
|
||||
((SubmitNodeCollector.CustomGeometryRenderer) args[2]).render(pose.last(), recorder(verts));
|
||||
submit.add("vertices", vertices(verts));
|
||||
}
|
||||
case "submitItem" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
submit.add("matrix", matrix(pose.last().pose()));
|
||||
submit.addProperty("context", args[1].toString());
|
||||
submit.addProperty("light", (int) args[2]);
|
||||
}
|
||||
case "submitMovingBlock", "submitBlockModel" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
submit.add("matrix", matrix(pose.last().pose()));
|
||||
}
|
||||
case "submitCrumblingOverlay" -> { return null; }
|
||||
default -> { }
|
||||
}
|
||||
submits.add(submit);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return (SubmitNodeCollector) Proxy.newProxyInstance(SubmitNodeCollector.class.getClassLoader(), new Class<?>[] {SubmitNodeCollector.class}, handler);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws NoSuchFieldException {
|
||||
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
|
||||
try {
|
||||
Field f = c.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
} catch (NoSuchFieldException e) {
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name + " on " + type);
|
||||
}
|
||||
|
||||
static DyeColor dye(String name) {
|
||||
return DyeColor.byName(name, DyeColor.BLACK);
|
||||
}
|
||||
|
||||
static SignText signText(JsonObject side) {
|
||||
var lines = side.getAsJsonArray("lines");
|
||||
var messages = new ArrayList<Component>();
|
||||
for (int i = 0; i < 4; i++) messages.add(Component.literal(i < lines.size() ? lines.get(i).getAsString() : ""));
|
||||
return new SignText(messages, messages, dye(side.get("color").getAsString()), side.get("glowing").getAsBoolean());
|
||||
}
|
||||
|
||||
/** Block-entity fields that vanilla ticks; set from the case before extraction. */
|
||||
static void apply(BlockEntity be, JsonObject c) throws Exception {
|
||||
if (be instanceof BellBlockEntity bell) {
|
||||
bell.ticks = c.has("bellTicks") ? c.get("bellTicks").getAsInt() : 0;
|
||||
bell.shaking = c.has("shake");
|
||||
if (bell.shaking) bell.clickDirection = Direction.byName(c.get("shake").getAsString());
|
||||
} else if (be instanceof ShulkerBoxBlockEntity) {
|
||||
field(ShulkerBoxBlockEntity.class, "progressOld").setFloat(be, c.has("progressOld") ? c.get("progressOld").getAsFloat() : 0.0F);
|
||||
field(ShulkerBoxBlockEntity.class, "progress").setFloat(be, c.has("progress") ? c.get("progress").getAsFloat() : 0.0F);
|
||||
} else if (be instanceof ConduitBlockEntity conduit && c.has("conduit")) {
|
||||
var k = c.getAsJsonObject("conduit");
|
||||
conduit.tickCount = k.get("tickCount").getAsInt();
|
||||
field(ConduitBlockEntity.class, "isActive").setBoolean(be, k.get("active").getAsBoolean());
|
||||
field(ConduitBlockEntity.class, "isHunting").setBoolean(be, k.get("hunting").getAsBoolean());
|
||||
field(ConduitBlockEntity.class, "activeRotation").setFloat(be, k.get("activeRotation").getAsFloat());
|
||||
} else if (be instanceof EnchantingTableBlockEntity table && c.has("book")) {
|
||||
var b = c.getAsJsonObject("book");
|
||||
table.time = b.get("time").getAsInt();
|
||||
table.flip = b.get("flip").getAsFloat(); table.oFlip = b.get("oFlip").getAsFloat();
|
||||
table.open = b.get("open").getAsFloat(); table.oOpen = b.get("oOpen").getAsFloat();
|
||||
table.rot = b.get("rot").getAsFloat(); table.oRot = b.get("oRot").getAsFloat();
|
||||
} else if (be instanceof SkullBlockEntity && c.has("skullAnimation")) {
|
||||
var a = c.getAsJsonArray("skullAnimation");
|
||||
field(SkullBlockEntity.class, "isAnimating").setBoolean(be, a.get(0).getAsBoolean());
|
||||
field(SkullBlockEntity.class, "animationTickCount").setInt(be, a.get(1).getAsInt());
|
||||
} else if (be instanceof DecoratedPotBlockEntity && c.has("sherds")) {
|
||||
var s = c.getAsJsonArray("sherds");
|
||||
var items = new ArrayList<Optional<ItemStackTemplate>>();
|
||||
for (var e : s) {
|
||||
var id = e.getAsString();
|
||||
items.add(id.isEmpty() ? Optional.empty()
|
||||
: Optional.of(new ItemStackTemplate(BuiltInRegistries.ITEM.getValue(Identifier.parse(id)))));
|
||||
}
|
||||
field(DecoratedPotBlockEntity.class, "decorations").set(be, new PotDecorations(items.get(0), items.get(1), items.get(2), items.get(3)));
|
||||
} else if (be instanceof BannerBlockEntity && c.has("patterns")) {
|
||||
var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder();
|
||||
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
|
||||
for (var e : c.getAsJsonArray("patterns")) {
|
||||
var p = e.getAsJsonArray();
|
||||
var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString())));
|
||||
builder.add(holder, dye(p.get(1).getAsString()));
|
||||
}
|
||||
field(BannerBlockEntity.class, "patterns").set(be, builder.build());
|
||||
}
|
||||
}
|
||||
|
||||
/** Render-state values vanilla reads from the level (absent here). */
|
||||
static void patch(BlockEntityRenderState rs, BlockState state, JsonObject c) {
|
||||
if (rs instanceof ChestRenderState chest) {
|
||||
chest.type = state.hasProperty(net.minecraft.world.level.block.ChestBlock.TYPE)
|
||||
? state.getValue(net.minecraft.world.level.block.ChestBlock.TYPE) : ChestType.SINGLE;
|
||||
chest.facing = state.getValue(net.minecraft.world.level.block.ChestBlock.FACING);
|
||||
chest.open = c.has("open") ? c.get("open").getAsFloat() : 0.0F;
|
||||
} else if (rs instanceof DecoratedPotRenderState pot && c.has("wobble")) {
|
||||
var w = c.getAsJsonArray("wobble");
|
||||
pot.wobbleStyle = DecoratedPotBlockEntity.WobbleStyle.valueOf(w.get(0).getAsString());
|
||||
pot.wobbleProgress = w.get(1).getAsFloat();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
Font font = ParityFont.create(ParityFont.resources());
|
||||
var models = new EntityModelSet(LayerDefinitions.createRoots());
|
||||
SpriteGetter sprites = id -> {
|
||||
try {
|
||||
var sprite = (TextureAtlasSprite) allocate.invoke(unsafe, TextureAtlasSprite.class);
|
||||
SPRITES.put(sprite, id);
|
||||
return sprite;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
};
|
||||
var context = new BlockEntityRendererProvider.Context(null, null, null, null, models, font, sprites, null);
|
||||
Map<Object, BlockEntityRenderer> renderers = (Map) BlockEntityRenderers.createEntityRenderers(context);
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
if (line.isBlank()) continue;
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
var result = new JsonObject();
|
||||
result.add("case", c);
|
||||
try {
|
||||
BlockState state = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, c.get("block").getAsString(), false).blockState();
|
||||
var p = c.getAsJsonArray("pos");
|
||||
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
|
||||
var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
|
||||
if (be == null) throw new IllegalStateException("no block entity");
|
||||
apply(be, c);
|
||||
var renderer = renderers.get(be.getType());
|
||||
if (renderer == null) throw new IllegalStateException("no renderer");
|
||||
float partial = c.get("partial").getAsFloat();
|
||||
var cam = c.getAsJsonArray("camera");
|
||||
var cameraPos = new Vec3(cam.get(0).getAsDouble(), cam.get(1).getAsDouble(), cam.get(2).getAsDouble());
|
||||
var rs = (BlockEntityRenderState) renderer.createRenderState();
|
||||
if (rs instanceof SignRenderState sign) {
|
||||
// AbstractSignRenderer.extractRenderState reads Minecraft.getInstance(); its level-free part:
|
||||
var signBe = (SignBlockEntity) be;
|
||||
BlockEntityRenderState.extractBase(be, rs, null);
|
||||
sign.maxTextLineWidth = signBe.getMaxTextLineWidth();
|
||||
sign.textLineHeight = signBe.getTextLineHeight();
|
||||
var s = c.getAsJsonObject("sign");
|
||||
sign.frontText = signText(s.getAsJsonObject("front"));
|
||||
sign.backText = signText(s.getAsJsonObject("back"));
|
||||
sign.drawOutline = s.get("near").getAsBoolean();
|
||||
if (rs instanceof StandingSignRenderState standing) {
|
||||
standing.attachmentType = net.minecraft.world.level.block.PlainSignBlock.getAttachmentPoint(state);
|
||||
sign.transformations = state.getBlock() instanceof net.minecraft.world.level.block.WallSignBlock
|
||||
? StandingSignRenderer.TRANSFORMATIONS.wallTransformation(state.getValue(net.minecraft.world.level.block.WallSignBlock.FACING))
|
||||
: StandingSignRenderer.TRANSFORMATIONS.freeTransformations(state.getValue(net.minecraft.world.level.block.StandingSignBlock.ROTATION));
|
||||
} else {
|
||||
((HangingSignRenderState) rs).attachmentType = net.minecraft.world.level.block.HangingSignBlock.getAttachmentPoint(state);
|
||||
sign.transformations = state.getBlock() instanceof net.minecraft.world.level.block.WallHangingSignBlock
|
||||
? HangingSignRenderer.TRANSFORMATIONS.wallTransformation(state.getValue(net.minecraft.world.level.block.WallHangingSignBlock.FACING))
|
||||
: HangingSignRenderer.TRANSFORMATIONS.freeTransformations(state.getValue(net.minecraft.world.level.block.CeilingHangingSignBlock.ROTATION));
|
||||
}
|
||||
} else {
|
||||
renderer.extractRenderState(be, rs, partial, cameraPos, null);
|
||||
}
|
||||
var light = c.getAsJsonArray("light");
|
||||
rs.lightCoords = light.get(1).getAsInt() << 4 | light.get(0).getAsInt() << 20;
|
||||
patch(rs, state, c);
|
||||
var camera = new CameraRenderState();
|
||||
camera.pos = cameraPos;
|
||||
float yaw = c.has("yaw") ? c.get("yaw").getAsFloat() : 0.0F, pitch = c.has("pitch") ? c.get("pitch").getAsFloat() : 0.0F;
|
||||
// Camera.setRotation.
|
||||
camera.orientation = new Quaternionf().rotationYXZ((float) Math.PI - yaw * (float) (Math.PI / 180.0), -pitch * (float) (Math.PI / 180.0), 0.0F);
|
||||
var submits = new JsonArray();
|
||||
renderer.submit(rs, new PoseStack(), collector(submits), camera);
|
||||
result.add("submits", submits);
|
||||
} catch (Throwable error) {
|
||||
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
|
||||
var sw = new java.io.StringWriter();
|
||||
cause.printStackTrace(new java.io.PrintWriter(sw));
|
||||
result.addProperty("error", sw.toString().lines().limit(6).reduce("", (a, b) -> a + b + " | "));
|
||||
}
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare block-entity rendering with the vanilla 26.3 client renderers.
|
||||
|
||||
The Java oracle (VanillaBlockEntityRenderOracle) builds each case's vanilla
|
||||
block entity, sets its animation fields, runs the real BlockEntityRenderer's
|
||||
extractRenderState and submit, and captures what it submits: model vertices
|
||||
after setupAnim and the pose stack (sprite-local UVs, tint, normal, light),
|
||||
text calls and items. `examples/block_entity_render_fixture` replays the case
|
||||
through Horizon's BlockEntityRenderer. Quads are matched by texture and
|
||||
position; colours compare vanilla's tint times the entity shader's
|
||||
`minecraft_mix_light` for the vanilla normal with Horizon's baked colour.
|
||||
|
||||
test_block_entity_render_parity.py [--filter SUBSTRING] [--detail N] [--tolerance EPS]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
|
||||
'blue', 'brown', 'green', 'red', 'black']
|
||||
HORIZONTAL = ['north', 'south', 'west', 'east']
|
||||
ALL = HORIZONTAL + ['up', 'down']
|
||||
NO_OVERLAY = 10 << 16
|
||||
|
||||
|
||||
def cases():
|
||||
rng = random.Random(0x42454e44)
|
||||
out = []
|
||||
|
||||
def add(block, **extra):
|
||||
case = {'block': block, 'pos': [rng.randint(-40, 40), rng.randint(-20, 90), rng.randint(-40, 40)],
|
||||
'light': [rng.randint(0, 15), rng.randint(0, 15)], 'partial': round(rng.random(), 4),
|
||||
'camera': [0.5, 70.0, 0.5]}
|
||||
case.update(extra)
|
||||
out.append(case)
|
||||
|
||||
for block in ['chest', 'trapped_chest', 'copper_chest', 'exposed_copper_chest', 'weathered_copper_chest',
|
||||
'oxidized_copper_chest', 'waxed_copper_chest', 'waxed_oxidized_copper_chest']:
|
||||
for facing in HORIZONTAL:
|
||||
for kind in ['single', 'left', 'right']:
|
||||
add(f'minecraft:{block}[facing={facing},type={kind}]', open=rng.choice([0.0, 0.25, 0.7, 1.0]))
|
||||
for facing in HORIZONTAL:
|
||||
add(f'minecraft:ender_chest[facing={facing}]', open=rng.choice([0.0, 0.5, 1.0]))
|
||||
texts = [['Hello', '', 'World', ''], ['A much longer line that cannot fit', 'mid', 'iii', 'WWWWWWWWWWWWWWW'],
|
||||
['', '', '', ''], ['x', 'Sign text', '#1 (test)', '!']]
|
||||
for wood in ['oak', 'spruce', 'cherry', 'crimson', 'bamboo', 'pale_oak']:
|
||||
signs = [f'minecraft:{wood}_sign[rotation={r}]' for r in (0, 3, 8, 13)] + \
|
||||
[f'minecraft:{wood}_wall_sign[facing={f}]' for f in HORIZONTAL] + \
|
||||
[f'minecraft:{wood}_hanging_sign[rotation={r},attached={a}]' for r, a in ((0, 'false'), (6, 'true'), (11, 'false'))] + \
|
||||
[f'minecraft:{wood}_wall_hanging_sign[facing={f}]' for f in HORIZONTAL]
|
||||
for block in signs:
|
||||
side = lambda: {'lines': rng.choice(texts), 'color': rng.choice(DYES), 'glowing': rng.random() < 0.4}
|
||||
add(block, sign={'front': side(), 'back': side(), 'near': rng.random() < 0.5})
|
||||
patterns = ['minecraft:stripe_bottom', 'minecraft:creeper', 'minecraft:gradient', 'minecraft:flower',
|
||||
'minecraft:border', 'minecraft:skull', 'minecraft:globe', 'minecraft:piglin']
|
||||
for color in ['white', 'red', 'light_gray', 'black']:
|
||||
for r in (0, 5, 12):
|
||||
add(f'minecraft:{color}_banner[rotation={r}]',
|
||||
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 3))])
|
||||
for f in HORIZONTAL:
|
||||
add(f'minecraft:{color}_wall_banner[facing={f}]',
|
||||
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))])
|
||||
add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)])
|
||||
for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head',
|
||||
'piglin_head', 'player_head']:
|
||||
wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head')
|
||||
for r in (0, 4, 9):
|
||||
add(f'minecraft:{skull}[rotation={r}]', skullAnimation=[rng.random() < 0.5, rng.randint(0, 80)])
|
||||
for f in HORIZONTAL:
|
||||
add(f'minecraft:{wall}[facing={f}]', skullAnimation=[rng.random() < 0.5, rng.randint(0, 80)])
|
||||
for color in [None, 'white', 'light_gray', 'purple', 'black']:
|
||||
name = 'shulker_box' if color is None else f'{color}_shulker_box'
|
||||
for f in ALL:
|
||||
p = rng.choice([0.0, 0.0, 0.3, 1.0])
|
||||
add(f'minecraft:{name}[facing={f}]', progress=p, progressOld=max(0.0, p - 0.1))
|
||||
for attach in ['floor', 'ceiling', 'single_wall', 'double_wall']:
|
||||
for f in HORIZONTAL:
|
||||
shake = rng.choice([None] + HORIZONTAL)
|
||||
extra = {'bellTicks': rng.randint(0, 50)}
|
||||
if shake:
|
||||
extra['shake'] = shake
|
||||
add(f'minecraft:bell[attachment={attach},facing={f}]', **extra)
|
||||
sherds = ['', 'minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:skull_pottery_sherd',
|
||||
'minecraft:heart_pottery_sherd', 'minecraft:flow_pottery_sherd']
|
||||
for f in HORIZONTAL:
|
||||
for wobble in [None, ['POSITIVE', 0.3], ['NEGATIVE', 0.6], ['POSITIVE', 1.2]]:
|
||||
extra = {'sherds': [rng.choice(sherds) for _ in range(4)]}
|
||||
if wobble:
|
||||
extra['wobble'] = wobble
|
||||
add(f'minecraft:decorated_pot[facing={f}]', **extra)
|
||||
for active in (False, True):
|
||||
for _ in range(4):
|
||||
add('minecraft:conduit', conduit={'tickCount': rng.randint(0, 400), 'active': active,
|
||||
'hunting': rng.random() < 0.5, 'activeRotation': rng.uniform(0, 300)},
|
||||
yaw=round(rng.uniform(-180, 180), 2), pitch=round(rng.uniform(-90, 90), 2))
|
||||
for _ in range(6):
|
||||
o = rng.random()
|
||||
add('minecraft:enchanting_table', book={'time': rng.randint(0, 2000), 'flip': rng.uniform(-3, 3),
|
||||
'oFlip': rng.uniform(-3, 3), 'open': o, 'oOpen': max(0.0, o - 0.1),
|
||||
'rot': rng.uniform(-3.1, 3.1), 'oRot': rng.uniform(-3.1, 3.1)})
|
||||
for f in HORIZONTAL:
|
||||
add(f'minecraft:lectern[facing={f},has_book=true]')
|
||||
add(f'minecraft:lectern[facing={f},has_book=false]')
|
||||
for prefix in ['', 'exposed_', 'weathered_', 'oxidized_', 'waxed_']:
|
||||
for pose in ['standing', 'running', 'sitting', 'star']:
|
||||
add(f'minecraft:{prefix}copper_golem_statue[facing={rng.choice(HORIZONTAL)},copper_golem_pose={pose}]')
|
||||
for block in ['end_portal', 'end_gateway', 'beacon', 'campfire[facing=north]', 'spawner',
|
||||
'trial_spawner', 'vault', 'suspicious_sand', 'oak_shelf[facing=east]']:
|
||||
add('minecraft:' + block)
|
||||
return out
|
||||
|
||||
|
||||
def light_coords(light):
|
||||
"""Horizon light (sky*16 low byte, block*16 next) as vanilla light coords."""
|
||||
return ((light & 0xFF) << 16) | ((light >> 8) & 0xFF)
|
||||
|
||||
|
||||
def lights():
|
||||
def norm(v):
|
||||
n = math.sqrt(sum(x * x for x in v))
|
||||
return [x / n for x in v]
|
||||
return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7])
|
||||
|
||||
|
||||
L0, L1 = lights()
|
||||
|
||||
|
||||
def mix(normal):
|
||||
d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal)))
|
||||
return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4)
|
||||
|
||||
|
||||
def vanilla_quads(submits):
|
||||
quads, other = [], []
|
||||
for s in submits:
|
||||
if s['type'] != 'submitModel':
|
||||
other.append(s)
|
||||
continue
|
||||
verts = s['vertices']
|
||||
for i in range(0, len(verts), 4):
|
||||
q = verts[i:i + 4]
|
||||
tint = q[0][3] & 0xFFFFFFFF
|
||||
b = mix(q[0][8:11])
|
||||
ch = lambda shift: int(((tint >> shift) & 255) * b)
|
||||
quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q],
|
||||
'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7],
|
||||
'overlay': q[0][6], 'type': s['renderType']})
|
||||
return quads, other
|
||||
|
||||
|
||||
def area(q):
|
||||
import itertools
|
||||
p = [v[:3] for v in q]
|
||||
a = [p[1][i] - p[0][i] for i in range(3)]
|
||||
b = [p[2][i] - p[0][i] for i in range(3)]
|
||||
c = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
a2 = [p[3][i] - p[0][i] for i in range(3)]
|
||||
d = [b[1] * a2[2] - b[2] * a2[1], b[2] * a2[0] - b[0] * a2[2], b[0] * a2[1] - b[1] * a2[0]]
|
||||
return math.sqrt(sum(x * x for x in c)) + math.sqrt(sum(x * x for x in d))
|
||||
|
||||
|
||||
def pair(vq, rq):
|
||||
"""Matches quads of the same texture globally by ascending vertex distance."""
|
||||
candidates = []
|
||||
for i, a in enumerate(vq):
|
||||
for j, b in enumerate(rq):
|
||||
if a['texture'] == b['texture']:
|
||||
d = sum((a['v'][k][c] - b['v'][k][c]) ** 2 for k in range(4) for c in range(5))
|
||||
candidates.append((d, i, j))
|
||||
candidates.sort()
|
||||
match, used = {}, set()
|
||||
for d, i, j in candidates:
|
||||
if i not in match and j not in used:
|
||||
match[i] = j
|
||||
used.add(j)
|
||||
return [(a, rq[match[i]] if i in match else None) for i, a in enumerate(vq)], \
|
||||
[b for j, b in enumerate(rq) if j not in used]
|
||||
|
||||
|
||||
def compare_case(v, r, tol):
|
||||
problems = []
|
||||
vq, other = vanilla_quads(v['submits'])
|
||||
for s in other:
|
||||
if s['type'] == 'submitText':
|
||||
continue
|
||||
problems.append(f'unsupported vanilla submit {s["type"]}')
|
||||
rq = r.get('quads', [])
|
||||
if len(vq) != len(rq):
|
||||
tex = lambda qs: sorted({q['texture'] for q in qs})
|
||||
problems.append(f'{len(vq)} vanilla quads {tex(vq)} vs {len(rq)} Horizon quads {tex(rq)}')
|
||||
pairs, extra = pair(vq, rq)
|
||||
for b in extra[:1]:
|
||||
problems.append(f'extra Horizon quad {b["texture"]} {b["v"]}')
|
||||
for a, b in pairs:
|
||||
if b is None:
|
||||
problems.append(f'missing {a["texture"]} quad {a["v"]}')
|
||||
break
|
||||
bad = [(i, j) for i in range(4) for j in range(5) if abs(a['v'][i][j] - b['v'][i][j]) > tol * (1 + abs(a['v'][i][j]))]
|
||||
if bad:
|
||||
problems.append(f'{a["texture"]} vertices {a["v"]} != {b["v"]}')
|
||||
break
|
||||
if a['overlay'] != NO_OVERLAY:
|
||||
problems.append(f'overlay {a["overlay"]}')
|
||||
got = b['color']
|
||||
rgb = [got & 255, (got >> 8) & 255, (got >> 16) & 255]
|
||||
# A zero-area quad shows nothing: vanilla shades it by its face normal, Horizon cannot derive one.
|
||||
if area(a['v']) > 1e-9 and (any(abs(x - y) > 1 for x, y in zip(a['rgb'], rgb)) or (got >> 24) != a['alpha']):
|
||||
problems.append(f'{a["texture"]} colour {a["rgb"]}/{a["alpha"]} != {rgb}/{got >> 24} at {a["v"]}')
|
||||
break
|
||||
if a['light'] != light_coords(b['light']):
|
||||
problems.append(f'{a["texture"]} light {a["light"]:#x} != {light_coords(b["light"]):#x}')
|
||||
break
|
||||
vt = [s for s in v['submits'] if s['type'] == 'submitText' and s['text']]
|
||||
rt = r.get('texts', [])
|
||||
if len(vt) != len(rt):
|
||||
problems.append(f'{len(vt)} vanilla texts {[t["text"] for t in vt]} vs {len(rt)} Horizon texts {[t["text"] for t in rt]}')
|
||||
for a, b in zip(vt, rt):
|
||||
for k in ('text', 'x', 'y', 'color', 'outline', 'light'):
|
||||
av, bv = a[k], b[k]
|
||||
if k in ('color', 'outline'):
|
||||
av &= 0xFFFFFFFF
|
||||
if (abs(av - bv) > 1e-4) if isinstance(av, float) else av != bv:
|
||||
problems.append(f'text {a["text"]!r} {k} {av!r} != {bv!r}')
|
||||
if any(abs(x - y) > tol * (1 + abs(x)) for x, y in zip(a['matrix'], b['matrix'])):
|
||||
problems.append(f'text {a["text"]!r} matrix {a["matrix"]} != {b["matrix"]}')
|
||||
return problems
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--filter', default='')
|
||||
parser.add_argument('--detail', type=int, default=2)
|
||||
parser.add_argument('--tolerance', type=float, default=2e-5)
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = lab.LOCAL / 'rust-block-entity-render-parity'; build.mkdir(parents=True, exist_ok=True)
|
||||
resources = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
chosen = [c for c in cases() if args.filter in c['block']]
|
||||
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
|
||||
classes = build / 'classes'; classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
|
||||
if result.returncode:
|
||||
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
|
||||
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaBlockEntityRenderOracle'))], 'compile-java')
|
||||
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityRenderOracle',
|
||||
inputs, build / 'vanilla.jsonl'], 'vanilla')
|
||||
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
|
||||
textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s})
|
||||
(build / 'textures.txt').write_text(''.join(t + '\n' for t in textures))
|
||||
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_render_fixture', '--',
|
||||
resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust')
|
||||
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
|
||||
assert len(vanilla) == len(rust), (len(vanilla), len(rust))
|
||||
groups, errors, skipped, passed = {}, {}, {}, 0
|
||||
for v, r in zip(vanilla, rust):
|
||||
block = v['case']['block'].split('[')[0]
|
||||
if 'error' in v:
|
||||
errors.setdefault(block, v['error']); continue
|
||||
if 'skip' in r:
|
||||
if not v['submits']:
|
||||
passed += 1 # vanilla submits nothing either (e.g. a lectern without a book)
|
||||
else:
|
||||
skipped.setdefault(r['skip'], set()).add(block)
|
||||
continue
|
||||
problems = compare_case(v, r, args.tolerance)
|
||||
if problems:
|
||||
groups.setdefault(block, []).append((v['case'], problems))
|
||||
else:
|
||||
passed += 1
|
||||
for reason, blocks in sorted(skipped.items()):
|
||||
print(f'NOT RENDERED by Horizon ({reason}): {", ".join(sorted(blocks))}')
|
||||
for block, error in sorted(errors.items()):
|
||||
print(f'ORACLE ERROR {block}: {error}')
|
||||
for block, items in sorted(groups.items()):
|
||||
print(f'MISMATCH {block}: {len(items)} cases')
|
||||
for case, problems in items[:args.detail]:
|
||||
print(' ', json.dumps(case))
|
||||
for p in problems[:4]:
|
||||
print(' ', p[:600])
|
||||
total = len(vanilla)
|
||||
print(f'{passed}/{total} cases match; {sum(len(b) for b in skipped.values())} not rendered; {len(errors)} oracle errors')
|
||||
if groups or errors or skipped:
|
||||
sys.exit(1)
|
||||
print('block entity render parity ok')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user