diff --git a/crates/horizon-assets/src/bake.rs b/crates/horizon-assets/src/bake.rs index e2afe55df..1b48ad7dd 100644 --- a/crates/horizon-assets/src/bake.rs +++ b/crates/horizon-assets/src/bake.rs @@ -168,6 +168,22 @@ pub fn bake_model(model: &ResolvedCuboidModel) -> Result> { pub fn bake_model_transformed( model: &ResolvedCuboidModel, transform: BlockModelTransform, +) -> Result> { + bake_elements(model, transform, false) +} +/// Block-model baking as `UnbakedCuboidGeometry.bake` does it: an element with +/// zero extent along an axis draws no faces across that extent (a flat X +/// element keeps only its X faces, and so on). +pub fn bake_block_model( + model: &ResolvedCuboidModel, + transform: BlockModelTransform, +) -> Result> { + bake_elements(model, transform, true) +} +fn bake_elements( + model: &ResolvedCuboidModel, + transform: BlockModelTransform, + skip_flat: bool, ) -> Result> { let mut output = Vec::new(); for element in model.elements() { @@ -175,7 +191,16 @@ pub fn bake_model_transformed( .as_ref() .ok_or_else(|| error("null model element"))?; let matrix = element.rotation.as_ref().map(ElementMatrix::from_rotation); + let flat = |axis: usize| skip_flat && element.from[axis] == element.to[axis]; for (direction, face) in &element.faces { + let drawn = match direction { + Direction::West | Direction::East => !flat(1) && !flat(2), + Direction::Down | Direction::Up => !flat(0) && !flat(2), + Direction::North | Direction::South => !flat(0) && !flat(1), + }; + if !drawn { + continue; + } let face = face.as_ref().ok_or_else(|| error("null model face"))?; let material = model.material(&face.texture)?.cloned().unwrap_or(Material { sprite: "minecraft:missingno".to_owned(), diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs new file mode 100644 index 000000000..1ac0e094d --- /dev/null +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -0,0 +1,190 @@ +//! Headless transport for the section-mesh parity gate: builds the requested +//! scenes in real client chunks and writes the vertices `Mesher::mesh` emits in +//! the oracle's canonical form (vanilla ARGB colours and packed light coords). +#![forbid(unsafe_code)] +use horizon_client::{ + assets::Assets, + biome::{Biomes, GrassModifier}, + blocks::BlockFacts, + chunk::{Chunk, Light, MIN_Y, index}, + mesher::{MeshTables, Mesher, Vertex}, + models, +}; +use horizon_world::registry::BlockStateId; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + fs, + io::{BufRead, BufReader, BufWriter, Write}, + path::PathBuf, + sync::Arc, + time::{Duration, Instant}, +}; +type Result = std::result::Result>; + +fn int(value: &Value) -> Result { + Ok(i32::try_from(value.as_i64().ok_or("expected integer")?)?) +} +/// Horizon packs RGBA little endian (red in the low byte); vanilla uses ARGB. +fn argb(color: u32) -> i32 { + let [r, g, b, a] = color.to_le_bytes(); + i32::from_be_bytes([a, r, g, b]) +} +/// Horizon keeps sky*16 in the low byte and block*16 above it; vanilla's light +/// coords keep block in the low half-word and sky in the high one. +fn light_coords(light: u32) -> i32 { + ((light & 0xFF) << 16 | (light >> 8 & 0xFF)) as i32 +} +/// Scenes cover the 3x3 chunk region around chunk (0, 0). +fn chunk_index(x: i32, z: i32) -> Result { + let (cx, cz) = (x.div_euclid(16), z.div_euclid(16)); + if !(-1..=1).contains(&cx) || !(-1..=1).contains(&cz) { + return Err("scene block outside the 3x3 chunk region".into()); + } + Ok(((cz + 1) * 3 + cx + 1) as usize) +} +fn scene( + row: &Value, + assets: &Assets, + tables: &MeshTables, + biomes: &mut Biomes, + names: &BTreeMap, + elapsed: &mut Duration, +) -> Result { + let colors = &row["colors"]; + let color = |k: &str| -> Result { Ok(int(&colors[k])? as u32 & 0xFF_FFFF) }; + for biome in &mut biomes.list { + biome.grass = color("grass")?; + biome.modifier = GrassModifier::None; + biome.foliage = color("foliage")?; + biome.dry_foliage = color("dry_foliage")?; + biome.water = color("water")?; + } + let default = row["light"].as_array().ok_or("missing default light")?; + let packed = |sky: i32, block: i32| (sky << 4 | block) as u8; + let default = packed(int(&default[0])?, int(&default[1])?); + let mut chunks: Vec = (0..9) + .map(|i| { + let mut chunk = Chunk::empty(i % 3 - 1, i / 3 - 1); + for section in &mut chunk.sections { + Arc::make_mut(section).light = Light::Uniform(default); + } + chunk + }) + .collect(); + for block in row["blocks"].as_array().ok_or("missing blocks")? { + let (x, y, z) = (int(&block[0])?, int(&block[1])?, int(&block[2])?); + let i = chunk_index(x, z)?; + chunks[i].set(x & 15, y, z & 15, u16::try_from(int(&block[3])?)?); + } + for cell in row["lights"].as_array().ok_or("missing lights")? { + let (x, y, z) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?); + let i = chunk_index(x, z)?; + let s = ((y - MIN_Y) >> 4) as usize; + let section = Arc::make_mut(&mut chunks[i].sections[s]); + if let Light::Uniform(v) = section.light { + section.light = Light::Full(Box::new([v; 4096])); + } + if let Light::Full(values) = &mut section.light { + values[index(x, y, z)] = packed(int(&cell[3])?, int(&cell[4])?); + } + } + let region: [[Option<&Chunk>; 3]; 3] = + std::array::from_fn(|z| std::array::from_fn(|x| Some(&chunks[z * 3 + x]))); + let mut mesher = Mesher { + nether_shading: row["nether"].as_bool().unwrap_or(false), + assets, + tables, + biomes: &*biomes, + visibility: tables.visibility.clone(), + }; + let section_y = int(&row["section_y"])?; + let started = Instant::now(); + let mesh = mesher.mesh(®ion, (section_y * 16 - MIN_Y) / 16); + *elapsed += started.elapsed(); + let mut quads = Vec::new(); + for (layer, vertices) in [("opaque", &mesh.solid), ("translucent", &mesh.translucent)] { + let (vertices, rest) = vertices.as_chunks::<4>(); + if !rest.is_empty() { + return Err("partial quad".into()); + } + for quad in vertices { + let sprite = names.get(&quad[0].layer).ok_or("unknown sprite layer")?; + if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) { + return Err("quad mixes sprite layers".into()); + } + let vertices: Vec = quad + .iter() + .map(|v| { + json!([ + v.pos[0], + v.pos[1], + v.pos[2], + v.uv[0], + v.uv[1], + argb(v.color), + light_coords(v.light) + ]) + }) + .collect(); + quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices})); + } + } + Ok(json!({"name": row["name"], "quads": quads})) +} +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + if args.len() != 3 { + return Err( + "usage: section_mesh_fixture RESOURCES (INPUT.jsonl | facts) OUTPUT.jsonl".into(), + ); + } + let root = PathBuf::from(&args[0]); + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let mut biomes = Biomes::load(&root)?; + let visibility = models::load_visibility(&root, assets.registry)?; + let tables = MeshTables::new(&assets, &facts, visibility)?; + let names: BTreeMap = assets + .sprite_layers + .iter() + .map(|(name, layer)| (*layer, name.as_str())) + .collect(); + let mut output = BufWriter::new(fs::File::create(&args[2])?); + if args[1] == "facts" { + // The per-state facts the mesher derives, in the oracle's order and positions. + let positions = [(0, 0), (5, -3), (-17, 31), (123, -456), (9, 2)]; + for id in 0..assets.registry.len() as u32 { + let state = BlockStateId(id); + let f = tables.facts(state).ok_or("missing mesh facts")?; + let offsets: Vec<_> = positions + .iter() + .filter_map(|&(x, z)| tables.offset(state, x, z)) + .collect(); + let row = json!({"id": id, "shade": f.shade, "emissive": f.emissive, + "legacy_solid": f.legacy_solid, "light_permeable": f.light_permeable, + "solid_render": f.solid_render, "full_collision": f.full_collision, + "emission": f.emission, "overlay": f.overlay, "tint_sources": f.tint_sources, + "offsets": offsets}); + serde_json::to_writer(&mut output, &row)?; + output.write_all(b"\n")?; + } + output.flush()?; + return Ok(()); + } + let (mut elapsed, mut sections) = (Duration::ZERO, 0u32); + for line in BufReader::new(fs::File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let result = scene(&row, &assets, &tables, &mut biomes, &names, &mut elapsed)?; + serde_json::to_writer(&mut output, &result)?; + output.write_all(b"\n")?; + sections += 1; + } + output.flush()?; + eprintln!( + "meshed {sections} sections in {:.1} ms ({:.0} us per section)", + elapsed.as_secs_f64() * 1e3, + elapsed.as_secs_f64() * 1e6 / f64::from(sections.max(1)) + ); + Ok(()) +} diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs new file mode 100644 index 000000000..bf156e425 --- /dev/null +++ b/crates/horizon-client/src/animate_tick.rs @@ -0,0 +1,1084 @@ +//! Client-side ambient block effects: `ClientLevel.animateTick` (667 random +//! blocks within 16 and 32 blocks per tick calling `Block.animateTick` and +//! `FluidState.animateTick`, fluid drips and biome ambient particles) and the +//! campfire block-entity particle tick. Particle positions, odds and sounds +//! follow the vanilla block classes. +use crate::{ + biome::Biomes, + blocks::{BlockFacts, Fluid}, + particles::{ParticleEngine, ParticleOptions, ParticleType as T}, + world::World, +}; +use horizon_core::{ + geometry::Axis, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::{ + block_collision::BlockCollisionRegistry, + registry::{BlockRegistry, BlockStateId}, + worldgen::tags::TagDefinitions, +}; +use std::{collections::BTreeMap, path::Path}; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Animate { + None, + Torch(T), + WallTorch(T, [i32; 3]), + RedstoneTorch, + RedstoneWallTorch([i32; 3]), + Furnace([i32; 3]), + BlastFurnace([i32; 3]), + Smoker, + Campfire { + spawn_particles: bool, + }, + /// Leaves: optional falling-leaf particle and chance, tinted by foliage. + Leaves(Option<(T, f32)>), + NetherPortal, + EnchantingTable, + EndRod([i32; 3]), + SporeBlossom, + CryingObsidian, + Mycelium, + Candles(u8), + CandleCake, + BrewingStand, + EnderChest, + /// FallingBlock with its dust colour. + Falling(u32), + RedstoneOre, + RedstoneWire { + power: u8, + sides: [u8; 4], + }, + RespawnAnchor, + BubbleColumn { + drag: bool, + }, + Fire, +} +fn step(facing: &str) -> [i32; 3] { + match facing { + "north" => [0, 0, -1], + "south" => [0, 0, 1], + "west" => [-1, 0, 0], + "east" => [1, 0, 0], + "up" => [0, 1, 0], + _ => [0, -1, 0], + } +} +fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + let lit = prop("lit").as_deref() == Some("true"); + let facing = || step(&prop("facing").unwrap_or_default()); + match name { + "torch" => Animate::Torch(T::Flame), + "soul_torch" => Animate::Torch(T::SoulFireFlame), + "copper_torch" => Animate::Torch(T::CopperFireFlame), + "wall_torch" => Animate::WallTorch(T::Flame, facing()), + "soul_wall_torch" => Animate::WallTorch(T::SoulFireFlame, facing()), + "copper_wall_torch" => Animate::WallTorch(T::CopperFireFlame, facing()), + "redstone_torch" if lit => Animate::RedstoneTorch, + "redstone_wall_torch" if lit => Animate::RedstoneWallTorch(facing()), + "furnace" if lit => Animate::Furnace(facing()), + "blast_furnace" if lit => Animate::BlastFurnace(facing()), + "smoker" if lit => Animate::Smoker, + "campfire" if lit => Animate::Campfire { + spawn_particles: true, + }, + "soul_campfire" if lit => Animate::Campfire { + spawn_particles: false, + }, + "oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" + | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))), + "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))), + "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))), + "spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None), + "nether_portal" => Animate::NetherPortal, + "enchanting_table" => Animate::EnchantingTable, + "end_rod" => Animate::EndRod(facing()), + "spore_blossom" => Animate::SporeBlossom, + "crying_obsidian" => Animate::CryingObsidian, + "mycelium" => Animate::Mycelium, + "brewing_stand" => Animate::BrewingStand, + "ender_chest" => Animate::EnderChest, + "sand" => Animate::Falling(0xDBD3A0), + "red_sand" => Animate::Falling(0xA95821), + "gravel" => Animate::Falling(0x807C7B), + "redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre, + "redstone_wire" => { + let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0); + let side = |d: &str| match prop(d).as_deref() { + Some("up") => 2, + Some("side") => 1, + _ => 0, + }; + if power == 0 { + Animate::None + } else { + Animate::RedstoneWire { + power, + sides: [side("north"), side("east"), side("south"), side("west")], + } + } + } + "respawn_anchor" if prop("charges").is_some_and(|c| c != "0") => Animate::RespawnAnchor, + "bubble_column" => Animate::BubbleColumn { + drag: prop("drag").as_deref() == Some("true"), + }, + "fire" | "soul_fire" => Animate::Fire, + _ if name.ends_with("candle_cake") && lit => Animate::CandleCake, + _ if (name == "candle" || name.ends_with("_candle")) && lit => { + Animate::Candles(prop("candles").and_then(|c| c.parse().ok()).unwrap_or(1)) + } + _ => Animate::None, + } +} +/// `RedstoneWireBlock.COLORS`. +fn redstone_color(power: u8) -> [f32; 3] { + let f = f32::from(power) / 15.0; + let r = f * 0.6 + if f > 0.0 { 0.4 } else { 0.3 }; + let g = (f * f * 0.7 - 0.5).clamp(0.0, 1.0); + let b = (f * f * 0.6 - 0.7).clamp(0.0, 1.0); + // DustParticleOptions stores the packed int colour. + let q = |c: f32| ((c * 255.0) as u8) as f32 / 255.0; + [q(r), q(g), q(b)] +} +/// `CandleBlock.PARTICLE_OFFSETS` by candle count (pixels). +fn candle_offsets(count: u8) -> &'static [[f64; 3]] { + match count { + 1 => &[[8.0, 8.0, 8.0]], + 2 => &[[6.0, 7.0, 8.0], [10.0, 8.0, 7.0]], + 3 => &[[8.0, 5.0, 10.0], [6.0, 7.0, 8.0], [9.0, 8.0, 7.0]], + _ => &[ + [7.0, 5.0, 9.0], + [10.0, 7.0, 9.0], + [6.0, 7.0, 6.0], + [9.0, 8.0, 6.0], + ], + } +} + +/// Per-state animate behaviour and the block tags it needs. +pub struct AnimateTables { + kinds: Vec, + impermeable: Vec, + power_provider: Vec, + power_transmitter: Vec, + /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). + ambient: Vec>, +} +impl AnimateTables { + pub fn load(root: &Path, registry: &BlockRegistry, biomes: &Biomes) -> crate::Result { + let kinds = (0..registry.len() as u32) + .map(|id| { + registry.state(BlockStateId(id)).map_or(Animate::None, |s| { + classify(&s.name, &|k| s.properties.get(k).cloned()) + }) + }) + .collect(); + let bundle: BTreeMap = + serde_json::from_slice(&std::fs::read(root.join("block-tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle { + definitions.apply_json(&name, "vanilla", &text)?; + } + let built = + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + let by_state = |tag: &str| -> Vec { + let names = built.tags.get(tag); + (0..registry.len() as u32) + .map(|id| { + registry + .state(BlockStateId(id)) + .is_some_and(|s| names.is_some_and(|n| n.iter().any(|t| *t == s.name))) + }) + .collect() + }; + let mut ambient = vec![Vec::new(); biomes.list.len()]; + for (name, &id) in &biomes.index { + let path = root.join(format!( + "data/minecraft/worldgen/biome/{}.json", + name.trim_start_matches("minecraft:") + )); + let Ok(bytes) = std::fs::read(path) else { + continue; + }; + let Ok(json) = serde_json::from_slice::(&bytes) else { + continue; + }; + let list = &json["attributes"]["minecraft:visual/ambient_particles"]; + let entries = list["argument"].as_array().or_else(|| list.as_array()); + for entry in entries.into_iter().flatten() { + let ty = entry["particle"]["type"].as_str().and_then(T::from_name); + let probability = entry["probability"].as_f64().unwrap_or(0.0) as f32; + if let (Some(ty), Some(slot)) = (ty, ambient.get_mut(id as usize)) { + slot.push((ty, probability)); + } + } + } + Ok(Self { + kinds, + impermeable: by_state("minecraft:impermeable"), + power_provider: by_state("minecraft:enchantment_power_provider"), + power_transmitter: by_state("minecraft:enchantment_power_transmitter"), + ambient, + }) + } + fn kind(&self, state: BlockStateId) -> Animate { + self.kinds + .get(state.0 as usize) + .copied() + .unwrap_or(Animate::None) + } + /// Whether a state ticks campfire particles (`CampfireBlockEntity.particleTick`). + pub fn is_lit_campfire(&self, state: u32) -> bool { + matches!(self.kind(BlockStateId(state)), Animate::Campfire { .. }) + } +} + +/// World access for ambient effects. +pub struct AnimateContext<'a> { + pub world: &'a World, + pub facts: &'a BlockFacts, + pub collision: &'a BlockCollisionRegistry<'a>, + pub biomes: &'a Biomes, + pub registry: &'a BlockRegistry, + /// `Level.isRainingAt`. + pub raining_at: &'a dyn Fn([i32; 3]) -> bool, +} +impl AnimateContext<'_> { + fn state(&self, p: [i32; 3]) -> BlockStateId { + self.world.block(p[0], p[1], p[2]) + } + fn is_air(&self, p: [i32; 3]) -> bool { + self.facts.is_air(self.state(p)) + } + /// `isFaceSturdy` approximated by a full collision cube. + fn sturdy(&self, p: [i32; 3]) -> bool { + self.facts.get(self.state(p)).full_collision + } + fn shape_y(&self, p: [i32; 3]) -> Option<(f64, f64, [f64; 4])> { + let shape = self + .collision + .cached_shapes() + .cached_shape(self.state(p)) + .ok()??; + if shape.is_empty() { + return Some((0.0, 0.0, [0.0; 4])); + } + Some(( + shape.min(Axis::Y), + shape.max(Axis::Y), + [ + shape.min(Axis::X), + shape.max(Axis::X), + shape.min(Axis::Z), + shape.max(Axis::Z), + ], + )) + } + fn foliage(&self, p: [i32; 3]) -> u32 { + let biome = self + .world + .chunks + .get(&(p[0] >> 4, p[2] >> 4)) + .map_or(0, |c| c.biome(p[0], p[1], p[2])); + self.biomes.get(biome).foliage + } +} + +fn add(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { + engine.add(&ParticleOptions::simple(ty), p, v); +} +fn sound(engine: &mut ParticleEngine, name: &'static str, p: [f64; 3], volume: f32, pitch: f32) { + engine.sounds.push((name, p, volume, pitch)); +} +fn redstone(engine: &mut ParticleEngine, p: [f64; 3]) { + engine.add(&ParticleOptions::dust([1.0, 0.0, 0.0], 1.0), p, [0.0; 3]); +} + +/// `ClientLevel.animateTick` around the player's block position. +pub fn animate_tick( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + player: [i32; 3], +) { + for _ in 0..667 { + do_animate_tick(tables, engine, ctx, player, 16); + do_animate_tick(tables, engine, ctx, player, 32); + } +} +fn next_int(r: &mut LegacyRandom, bound: i32) -> i32 { + r.next_int_bound(bound).unwrap_or(0) +} +fn do_animate_tick( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + center: [i32; 3], + r: i32, +) { + let random = engine.random(); + let x = center[0] + next_int(random, r) - next_int(random, r); + let y = center[1] + next_int(random, r) - next_int(random, r); + let z = center[2] + next_int(random, r) - next_int(random, r); + let pos = [x, y, z]; + if !ctx.world.loaded(x, z) { + return; + } + let state = ctx.state(pos); + block_animate_tick(tables, engine, ctx, state, pos); + let facts = ctx.facts.get(state); + if facts.fluid != Fluid::None { + fluid_animate_tick( + engine, + ctx, + pos, + facts.fluid, + facts.fluid_level, + facts.fluid_falling, + ); + if next_int(engine.random(), 10) == 0 { + let drip = if facts.fluid == Fluid::Water { + T::DrippingWater + } else { + T::DrippingLava + }; + let top_solid = ctx.sturdy(pos); + try_spawn_drip(tables, engine, ctx, [x, y - 1, z], drip, top_solid); + } + } + if !facts.full_collision { + let biome = ctx + .world + .chunks + .get(&(x >> 4, z >> 4)) + .map_or(0, |c| c.biome(x, y, z)); + for &(ty, probability) in tables.ambient.get(biome as usize).into_iter().flatten() { + // AmbientParticle.canSpawn: random.nextFloat() <= probability. + let random = engine.random(); + if random.next_float() <= probability { + let p = [ + f64::from(x) + random.next_double(), + f64::from(y) + random.next_double(), + f64::from(z) + random.next_double(), + ]; + add(engine, ty, p, [0.0; 3]); + } + } + } +} +/// `ClientLevel.trySpawnDripParticles`. +fn try_spawn_drip( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + pos: [i32; 3], + drip: T, + top_solid: bool, +) { + let state = ctx.state(pos); + if ctx.facts.get(state).fluid != Fluid::None { + return; + } + let Some((bottom, top, bounds)) = ctx.shape_y(pos) else { + return; + }; + let spawn = |engine: &mut ParticleEngine, x1: f64, x2: f64, z1: f64, z2: f64, y: f64| { + let r = engine.random(); + let (a, b) = (r.next_double(), r.next_double()); + add( + engine, + drip, + [x1 + (x2 - x1) * a, y, z1 + (z2 - z1) * b], + [0.0; 3], + ); + }; + let (fx, fy, fz) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); + if top < 1.0 { + if top_solid { + spawn(engine, fx, fx + 1.0, fz, fz + 1.0, fy + 1.0 - 0.05); + } + } else if !tables + .impermeable + .get(state.0 as usize) + .copied() + .unwrap_or(false) + { + if bottom > 0.0 { + spawn( + engine, + fx + bounds[0], + fx + bounds[1], + fz + bounds[2], + fz + bounds[3], + fy + bottom - 0.05, + ); + } else { + let below = [pos[0], pos[1] - 1, pos[2]]; + let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1); + if below_top < 1.0 && ctx.facts.get(ctx.state(below)).fluid == Fluid::None { + spawn( + engine, + fx + bounds[0], + fx + bounds[1], + fz + bounds[2], + fz + bounds[3], + fy - 0.05, + ); + } + } + } +} +/// `WaterFluid.animateTick` / `LavaFluid.animateTick`. +fn fluid_animate_tick( + engine: &mut ParticleEngine, + ctx: &AnimateContext, + pos: [i32; 3], + fluid: Fluid, + level: u8, + falling: bool, +) { + let (fx, fy, fz) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); + if fluid == Fluid::Water { + let source = level >= 8 && !falling; + let random = engine.random(); + if !source && !falling { + if next_int(random, 64) == 0 { + let volume = random.next_float() * 0.25 + 0.75; + let pitch = random.next_float() + 0.5; + sound( + engine, + "minecraft:block.water.ambient", + [fx + 0.5, fy + 0.5, fz + 0.5], + volume, + pitch, + ); + } + } else if next_int(random, 10) == 0 { + let p = [ + fx + random.next_double(), + fy + random.next_double(), + fz + random.next_double(), + ]; + add(engine, T::Underwater, p, [0.0; 3]); + } + return; + } + let above = [pos[0], pos[1] + 1, pos[2]]; + if ctx.is_air(above) { + let random = engine.random(); + if next_int(random, 100) == 0 { + let p = [ + fx + random.next_double(), + fy + 1.0, + fz + random.next_double(), + ]; + add(engine, T::Lava, p, [0.0; 3]); + let random = engine.random(); + let (volume, pitch) = ( + 0.2 + random.next_float() * 0.2, + 0.9 + random.next_float() * 0.15, + ); + sound(engine, "minecraft:block.lava.pop", p, volume, pitch); + } + let random = engine.random(); + if next_int(random, 200) == 0 { + let (volume, pitch) = ( + 0.2 + random.next_float() * 0.2, + 0.9 + random.next_float() * 0.15, + ); + sound( + engine, + "minecraft:block.lava.ambient", + [fx, fy, fz], + volume, + pitch, + ); + } + } +} +#[allow(clippy::too_many_lines)] +fn block_animate_tick( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + let (fx, fy, fz) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); + match tables.kind(state) { + Animate::None => {} + Animate::Torch(flame) => { + let p = [fx + 0.5, fy + 0.7, fz + 0.5]; + add(engine, T::Smoke, p, [0.0; 3]); + add(engine, flame, p, [0.0; 3]); + } + Animate::WallTorch(flame, facing) => { + let p = [ + fx + 0.5 - 0.27 * f64::from(facing[0]), + fy + 0.7 + 0.22, + fz + 0.5 - 0.27 * f64::from(facing[2]), + ]; + add(engine, T::Smoke, p, [0.0; 3]); + add(engine, flame, p, [0.0; 3]); + } + Animate::RedstoneTorch => { + let r = engine.random(); + let p = [ + fx + 0.5 + (r.next_double() - 0.5) * 0.2, + fy + 0.7 + (r.next_double() - 0.5) * 0.2, + fz + 0.5 + (r.next_double() - 0.5) * 0.2, + ]; + redstone(engine, p); + } + Animate::RedstoneWallTorch(facing) => { + let r = engine.random(); + let p = [ + fx + 0.5 + (r.next_double() - 0.5) * 0.2 - 0.27 * f64::from(facing[0]), + fy + 0.7 + (r.next_double() - 0.5) * 0.2 + 0.22, + fz + 0.5 + (r.next_double() - 0.5) * 0.2 - 0.27 * f64::from(facing[2]), + ]; + redstone(engine, p); + } + Animate::Furnace(facing) | Animate::BlastFurnace(facing) => { + let blast = matches!(tables.kind(state), Animate::BlastFurnace(_)); + let (x, y, z) = (fx + 0.5, fy, fz + 0.5); + let r = engine.random(); + if r.next_double() < 0.1 { + let name = if blast { + "minecraft:block.blastfurnace.fire_crackle" + } else { + "minecraft:block.furnace.fire_crackle" + }; + sound(engine, name, [x, y, z], 1.0, 1.0); + } + let r = engine.random(); + let ss = r.next_double() * 0.6 - 0.3; + let dx = if facing[0] != 0 { + f64::from(facing[0]) * 0.52 + } else { + ss + }; + let dy = r.next_double() * if blast { 9.0 } else { 6.0 } / 16.0; + let dz = if facing[2] != 0 { + f64::from(facing[2]) * 0.52 + } else { + ss + }; + let p = [x + dx, y + dy, z + dz]; + add(engine, T::Smoke, p, [0.0; 3]); + if !blast { + add(engine, T::Flame, p, [0.0; 3]); + } + } + Animate::Smoker => { + let r = engine.random(); + if r.next_double() < 0.1 { + sound( + engine, + "minecraft:block.smoker.smoke", + [fx + 0.5, fy, fz + 0.5], + 1.0, + 1.0, + ); + } + add(engine, T::Smoke, [fx + 0.5, fy + 1.1, fz + 0.5], [0.0; 3]); + } + Animate::Campfire { spawn_particles } => { + let r = engine.random(); + if next_int(r, 10) == 0 { + let (volume, pitch) = (0.5 + r.next_float(), r.next_float() * 0.7 + 0.6); + sound( + engine, + "minecraft:block.campfire.crackle", + [fx + 0.5, fy + 0.5, fz + 0.5], + volume, + pitch, + ); + } + let r = engine.random(); + if spawn_particles && next_int(r, 5) == 0 { + let count = next_int(r, 1) + 1; + for _ in 0..count { + let r = engine.random(); + let v = [ + f64::from(r.next_float() / 2.0), + 5.0e-5, + f64::from(r.next_float() / 2.0), + ]; + add(engine, T::Lava, [fx + 0.5, fy + 0.5, fz + 0.5], v); + } + } + } + Animate::Leaves(falling) => { + let below = [pos[0], pos[1] - 1, pos[2]]; + // LeavesBlock.makeDrippingWaterParticles. + if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1 + { + let below_facts = ctx.facts.get(ctx.state(below)); + if !below_facts.can_occlude || !ctx.sturdy(below) { + let r = engine.random(); + let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()]; + add(engine, T::DrippingWater, p, [0.0; 3]); + } + } + // FallingParticlesLeavesBlock.makeFallingLeavesParticles. + if let Some((ty, chance)) = falling + && engine.random().next_float() < chance + && !ctx.sturdy(below) + { + let r = engine.random(); + let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()]; + let options = if ty == T::TintedLeaves { + let c = ctx.foliage(pos); + let f = |s: u32| ((c >> s) & 255) as f32 / 255.0; + ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0]) + } else { + ParticleOptions::simple(ty) + }; + engine.add(&options, p, [0.0; 3]); + } + } + Animate::NetherPortal => { + let r = engine.random(); + if next_int(r, 100) == 0 { + let pitch = r.next_float() * 0.4 + 0.8; + sound( + engine, + "minecraft:block.portal.ambient", + [fx + 0.5, fy + 0.5, fz + 0.5], + 0.5, + pitch, + ); + } + let along_z = ctx.state([pos[0] - 1, pos[1], pos[2]]) == state + || ctx.state([pos[0] + 1, pos[1], pos[2]]) == state; + for _ in 0..4 { + let r = engine.random(); + let mut p = [ + fx + r.next_double(), + fy + r.next_double(), + fz + r.next_double(), + ]; + let mut v = [ + f64::from(r.next_float() - 0.5) * 0.5, + f64::from(r.next_float() - 0.5) * 0.5, + f64::from(r.next_float() - 0.5) * 0.5, + ]; + let flip = f64::from(next_int(r, 2) * 2 - 1); + if along_z { + p[2] = fz + 0.5 + 0.25 * flip; + v[2] = f64::from(r.next_float() * 2.0) * flip; + } else { + p[0] = fx + 0.5 + 0.25 * flip; + v[0] = f64::from(r.next_float() * 2.0) * flip; + } + add(engine, T::Portal, p, v); + } + } + Animate::EnchantingTable => { + for ox in -2i32..=2 { + for oy in 0..=1 { + for oz in -2i32..=2 { + if ox.abs() != 2 && oz.abs() != 2 { + continue; + } + if next_int(engine.random(), 16) != 0 { + continue; + } + let provider = ctx.state([pos[0] + ox, pos[1] + oy, pos[2] + oz]); + let between = ctx.state([pos[0] + ox / 2, pos[1] + oy, pos[2] + oz / 2]); + if tables + .power_provider + .get(provider.0 as usize) + .copied() + .unwrap_or(false) + && tables + .power_transmitter + .get(between.0 as usize) + .copied() + .unwrap_or(false) + { + let r = engine.random(); + let v = [ + f64::from(ox as f32 + r.next_float() - 0.5), + f64::from(oy as f32 - r.next_float() - 1.0), + f64::from(oz as f32 + r.next_float() - 0.5), + ]; + add(engine, T::Enchant, [fx + 0.5, fy + 2.0, fz + 0.5], v); + } + } + } + } + } + Animate::EndRod(facing) => { + let r = engine.random(); + let x = fx + 0.55 - f64::from(r.next_float() * 0.1); + let y = fy + 0.55 - f64::from(r.next_float() * 0.1); + let z = fz + 0.55 - f64::from(r.next_float() * 0.1); + let d = f64::from(0.4 - (r.next_float() + r.next_float()) * 0.4); + if next_int(r, 5) == 0 { + let v = [ + r.next_gaussian() * 0.005, + r.next_gaussian() * 0.005, + r.next_gaussian() * 0.005, + ]; + let p = [ + x + f64::from(facing[0]) * d, + y + f64::from(facing[1]) * d, + z + f64::from(facing[2]) * d, + ]; + add(engine, T::EndRod, p, v); + } + } + Animate::SporeBlossom => { + let r = engine.random(); + let p = [fx + r.next_double(), fy + 0.7, fz + r.next_double()]; + add(engine, T::FallingSporeBlossom, p, [0.0; 3]); + for _ in 0..14 { + let r = engine.random(); + let a = [ + pos[0] + next_int(r, 21) - 10, + pos[1] - next_int(r, 10), + pos[2] + next_int(r, 21) - 10, + ]; + if !ctx.facts.get(ctx.state(a)).full_collision { + let r = engine.random(); + let p = [ + f64::from(a[0]) + r.next_double(), + f64::from(a[1]) + r.next_double(), + f64::from(a[2]) + r.next_double(), + ]; + add(engine, T::SporeBlossomAir, p, [0.0; 3]); + } + } + } + Animate::CryingObsidian => { + let r = engine.random(); + if next_int(r, 5) == 0 { + // Direction.getRandom: down, up, north, south, west, east. + let d = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ][next_int(r, 6) as usize]; + if d != [0, 1, 0] { + let relative = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + if !ctx.sturdy(relative) { + let r = engine.random(); + let off = |s: i32, r: &mut LegacyRandom| { + if s == 0 { + r.next_double() + } else { + 0.5 + f64::from(s) * 0.6 + } + }; + let p = [fx + off(d[0], r), fy + off(d[1], r), fz + off(d[2], r)]; + add(engine, T::DrippingObsidianTear, p, [0.0; 3]); + } + } + } + } + Animate::Mycelium => { + let r = engine.random(); + if next_int(r, 10) == 0 { + let p = [fx + r.next_double(), fy + 1.1, fz + r.next_double()]; + add(engine, T::Mycelium, p, [0.0; 3]); + } + } + Animate::Candles(count) => { + for o in candle_offsets(count) { + candle( + engine, + [fx + o[0] / 16.0, fy + o[1] / 16.0, fz + o[2] / 16.0], + ); + } + } + Animate::CandleCake => candle(engine, [fx + 0.5, fy + 1.0, fz + 0.5]), + Animate::BrewingStand => { + let r = engine.random(); + let p = [ + fx + 0.4 + f64::from(r.next_float() * 0.2), + fy + 0.7 + f64::from(r.next_float() * 0.3), + fz + 0.4 + f64::from(r.next_float() * 0.2), + ]; + add(engine, T::Smoke, p, [0.0; 3]); + } + Animate::EnderChest => { + for _ in 0..3 { + let r = engine.random(); + let flip_x = f64::from(next_int(r, 2) * 2 - 1); + let flip_z = f64::from(next_int(r, 2) * 2 - 1); + let p = [ + fx + 0.5 + 0.25 * flip_x, + fy + f64::from(r.next_float()), + fz + 0.5 + 0.25 * flip_z, + ]; + let v = [ + f64::from(r.next_float()) * flip_x, + f64::from(r.next_float() - 0.5) * 0.125, + f64::from(r.next_float()) * flip_z, + ]; + add(engine, T::Portal, p, v); + } + } + Animate::Falling(color) => { + if next_int(engine.random(), 16) == 0 { + let below = ctx.facts.get(ctx.state([pos[0], pos[1] - 1, pos[2]])); + // FallingBlock.isFree: air, fire, liquids or replaceable. + if below.replaceable + || below.fluid != Fluid::None + || ctx.is_air([pos[0], pos[1] - 1, pos[2]]) + { + let r = engine.random(); + let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()]; + engine.add( + &ParticleOptions::block(T::FallingDust, String::new(), color), + p, + [0.0; 3], + ); + } + } + } + Animate::RedstoneOre => { + for d in [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ] { + let relative = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + if ctx.facts.get(ctx.state(relative)).solid_render { + continue; + } + let r = engine.random(); + let mut c = |s: i32| { + if s != 0 { + 0.5 + 0.5625 * f64::from(s) + } else { + f64::from(r.next_float()) + } + }; + let p = [fx + c(d[0]), fy + c(d[1]), fz + c(d[2])]; + redstone(engine, p); + } + } + Animate::RedstoneWire { power, sides } => { + let color = redstone_color(power); + let horizontals = [[0, 0, -1], [1, 0, 0], [0, 0, 1], [-1, 0, 0]]; + let line = |engine: &mut ParticleEngine, + side: [i32; 3], + along: [i32; 3], + from: f32, + to: f32| { + let span = to - from; + let r = engine.random(); + if r.next_float() < 0.2 * span { + let on = from + span * r.next_float(); + let c = |i: usize| { + 0.5 + 0.4375 * f64::from(side[i]) + f64::from(on) * f64::from(along[i]) + }; + engine.add( + &ParticleOptions::dust(color, 1.0), + [fx + c(0), fy + c(1), fz + c(2)], + [0.0; 3], + ); + } + }; + for (i, h) in horizontals.into_iter().enumerate() { + match sides[i] { + 2 => { + line(engine, h, [0, 1, 0], -0.5, 0.5); + line(engine, [0, -1, 0], h, 0.0, 0.5); + } + 1 => line(engine, [0, -1, 0], h, 0.0, 0.5), + _ => line(engine, [0, -1, 0], h, 0.0, 0.3), + } + } + } + Animate::RespawnAnchor => { + let r = engine.random(); + if next_int(r, 100) == 0 { + sound( + engine, + "minecraft:block.respawn_anchor.ambient", + [fx + 0.5, fy + 0.5, fz + 0.5], + 1.0, + 1.0, + ); + } + let r = engine.random(); + let p = [ + fx + 0.5 + (0.5 - r.next_double()), + fy + 1.0, + fz + 0.5 + (0.5 - r.next_double()), + ]; + let ya = f64::from(r.next_float() * 0.04); + add(engine, T::ReversePortal, p, [0.0, ya, 0.0]); + } + Animate::BubbleColumn { drag } => { + if drag { + add(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); + let r = engine.random(); + if next_int(r, 200) == 0 { + let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); + sound( + engine, + "minecraft:block.bubble_column.whirlpool_ambient", + [fx, fy, fz], + volume, + pitch, + ); + } + } else { + add( + engine, + T::BubbleColumnUp, + [fx + 0.5, fy, fz + 0.5], + [0.0, 0.04, 0.0], + ); + let r = engine.random(); + let p = [ + fx + f64::from(r.next_float()), + fy + f64::from(r.next_float()), + fz + f64::from(r.next_float()), + ]; + add(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); + let r = engine.random(); + if next_int(r, 200) == 0 { + let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); + sound( + engine, + "minecraft:block.bubble_column.upwards_ambient", + [fx, fy, fz], + volume, + pitch, + ); + } + } + } + Animate::Fire => { + let r = engine.random(); + if next_int(r, 24) == 0 { + let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3); + sound( + engine, + "minecraft:block.fire.ambient", + [fx + 0.5, fy + 0.5, fz + 0.5], + volume, + pitch, + ); + } + } + } +} +/// `AbstractCandleBlock.addParticlesAndSound`. +fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { + let r = engine.random(); + let chance = r.next_float(); + if chance < 0.3 { + add(engine, T::Smoke, p, [0.0; 3]); + if chance < 0.17 { + let r = engine.random(); + let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3); + sound( + engine, + "minecraft:block.candle.ambient", + [p[0] + 0.5, p[1] + 0.5, p[2] + 0.5], + volume, + pitch, + ); + } + } + add(engine, T::SmallFlame, p, [0.0; 3]); +} +/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items). +pub fn campfire_particles<'a>( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + blocks: impl Iterator, +) { + for &(pos, state) in blocks { + if !tables.is_lit_campfire(state) { + continue; + } + let signal = ctx + .registry + .state(BlockStateId(state)) + .is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true")); + let r = engine.random(); + if r.next_float() < 0.11 { + let count = next_int(r, 2) + 2; + for _ in 0..count { + make_campfire_smoke(engine, pos, signal); + } + } + } +} +/// `CampfireBlock.makeParticles` (always visible, overriding the limiter). +pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) { + let r = engine.random(); + let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 }; + let dx = r.next_double() / 3.0; + let x = f64::from(pos[0]) + 0.5 + dx * sign(r); + let y = f64::from(pos[1]) + r.next_double() + r.next_double(); + let dz = r.next_double() / 3.0; + let z = f64::from(pos[2]) + 0.5 + dz * sign(r); + let ty = if signal { + T::CampfireSignalSmoke + } else { + T::CampfireCosySmoke + }; + engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn classifies_animated_blocks() { + let none = |_: &str| None; + assert_eq!(classify("minecraft:torch", &none), Animate::Torch(T::Flame)); + let lit = |k: &str| (k == "lit").then(|| "true".to_owned()); + assert_eq!( + classify("minecraft:furnace", &lit), + Animate::Furnace([0, -1, 0]) + ); + assert_eq!(classify("minecraft:furnace", &none), Animate::None); + let wall = |k: &str| (k == "facing").then(|| "north".to_owned()); + assert_eq!( + classify("minecraft:soul_wall_torch", &wall), + Animate::WallTorch(T::SoulFireFlame, [0, 0, -1]) + ); + let candles = |k: &str| match k { + "lit" => Some("true".to_owned()), + "candles" => Some("3".to_owned()), + _ => None, + }; + assert_eq!( + classify("minecraft:red_candle", &candles), + Animate::Candles(3) + ); + assert_eq!( + classify("minecraft:red_candle_cake", &lit), + Animate::CandleCake + ); + } + #[test] + fn redstone_colours_match_wire_table() { + // RedstoneWireBlock.COLORS[15] = (1.0, 0.2, 0.1) before int packing. + let c = redstone_color(15); + assert!((c[0] - 1.0).abs() < 1e-6); + assert!((c[1] - (51.0 / 255.0)).abs() < 0.01); + } +} diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index cafdd7b2d..8e22f7736 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -63,6 +63,8 @@ pub struct Assets { pub animations: Vec, pub sprite_layers: std::collections::BTreeMap, pub translucent_layers: Vec, + /// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors). + pub blocks_fluid_flow: BTreeSet, } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) @@ -144,6 +146,13 @@ impl Assets { .iter() .map(String::as_str) .collect(); + let blocks_fluid_flow = built + .tags + .get("minecraft:blocks_fluid_flow") + .ok_or_else(|| invalid("missing fluid flow tag"))? + .iter() + .cloned() + .collect(); let properties = Properties(Arc::new( states .iter() @@ -202,6 +211,7 @@ impl Assets { animations: sprites.animations, sprite_layers: sprites.layers, translucent_layers: sprites.translucent, + blocks_fluid_flow, }) } } diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs new file mode 100644 index 000000000..70670e167 --- /dev/null +++ b/crates/horizon-client/src/block_entity_render.rs @@ -0,0 +1,1228 @@ +//! 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 +//! (`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::random::{LegacyRandom, RandomSource}; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::Value; +use std::{collections::HashMap, f32::consts::PI, path::Path}; + +/// One baked `ModelPart`: initial pose, textured polygons (pixel units, +/// normalized UVs) and named children. +#[derive(Clone, Debug, Default)] +pub struct ModelPart { + /// x, y, z, xRot, yRot, zRot, xScale, yScale, zScale. + pub pose: [f32; 9], + pub polygons: Vec<[[f32; 5]; 4]>, + pub children: Vec<(String, ModelPart)>, +} +impl ModelPart { + pub fn parse(v: &Value) -> Self { + let mut pose = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + if let Some(a) = v["pose"].as_array() { + for (p, x) in pose.iter_mut().zip(a) { + *p = x.as_f64().unwrap_or(0.0) as f32; + } + } + let polygons = v["polygons"] + .as_array() + .map(|polys| { + polys + .iter() + .filter_map(|poly| { + let verts = poly.as_array()?; + if verts.len() != 4 { + return None; + } + let mut out = [[0f32; 5]; 4]; + for (o, vert) in out.iter_mut().zip(verts) { + for (c, x) in o.iter_mut().zip(vert.as_array()?) { + *c = x.as_f64().unwrap_or(0.0) as f32; + } + } + Some(out) + }) + .collect() + }) + .unwrap_or_default(); + let children = v["children"] + .as_object() + .map(|m| m.iter().map(|(k, c)| (k.clone(), Self::parse(c))).collect()) + .unwrap_or_default(); + Self { + pose, + polygons, + children, + } + } + pub fn child(&self, name: &str) -> Option<&ModelPart> { + self.children + .iter() + .find(|(n, _)| n == name) + .map(|(_, c)| c) + } +} + +/// `Lighting` level light directions (overworld/end and nether). +pub fn diffuse_lights(nether: bool) -> (Vec3, Vec3) { + let l0 = Vec3::new(0.2, 1.0, -0.7).normalize(); + let l1 = if nether { + Vec3::new(-0.2, -1.0, 0.7) + } else { + Vec3::new(-0.2, 1.0, 0.7) + } + .normalize(); + (l0, l1) +} +/// `minecraft_mix_light`: 0.6 power, 0.4 ambient. +pub fn diffuse(normal: Vec3, lights: (Vec3, Vec3)) -> f32 { + ((lights.0.dot(normal).max(0.0) + lights.1.dot(normal).max(0.0)) * 0.6 + 0.4).min(1.0) +} +/// Packed vertex light from the level's packed `sky << 4 | block` byte. +pub fn vertex_light(packed: u8) -> u32 { + u32::from(packed >> 4) * 16 | (u32::from(packed & 15) * 16) << 8 +} +fn pack_color(rgb: u32, alpha: u32, brightness: f32) -> u32 { + let c = |shift: u32| (((rgb >> shift) & 255) as f32 * brightness) as u32; + alpha << 24 | c(0) << 16 | c(8) << 8 | c(16) +} + +/// Everything a draw call needs besides the geometry. +#[derive(Clone, Copy)] +pub struct Paint { + pub sprite: Rect, + /// 0xRRGGBB multiplied with the texture (`-1` = white in vanilla). + pub tint: u32, + pub light: u32, + pub lights: (Vec3, Vec3), +} +/// `ModelPart.render`: translate by pose/16, rotate ZYX, scale; children inherit. +/// `adjust` may change a part's pose by name (`setupAnim`); `skip` hides parts. +pub fn draw_part( + part: &ModelPart, + name: &str, + parent: Mat4, + adjust: &dyn Fn(&str, &mut [f32; 9]), + paint: Paint, + out: &mut Vec, +) { + let mut p = part.pose; + adjust(name, &mut p); + let m = parent + * Mat4::from_translation(Vec3::new(p[0], p[1], p[2]) / 16.0) + * Mat4::from_quat(Quat::from_euler(glam::EulerRot::ZYX, p[5], p[4], p[3])) + * Mat4::from_scale(Vec3::new(p[6], p[7], p[8])); + let Paint { + sprite: r, + tint, + light, + lights, + } = paint; + for poly in &part.polygons { + let pos = poly.map(|v| m.transform_point3(Vec3::new(v[0], v[1], v[2]) / 16.0)); + let normal = (pos[1] - pos[0]).cross(pos[2] - pos[0]).normalize_or_zero(); + let normal = if normal == Vec3::ZERO { + // Degenerate polygon: use the other diagonal. + (pos[2] - pos[1]) + .cross(pos[3] - pos[1]) + .normalize_or(Vec3::Y) + } else { + normal + }; + let color = pack_color(tint, 255, diffuse(normal, lights)); + for (v, position) in poly.iter().zip(pos) { + out.push(Vertex { + pos: position.to_array(), + uv: [r.u0 + (r.u1 - r.u0) * v[3], r.v0 + (r.v1 - r.v0) * v[4]], + layer: 0, + color, + light, + }); + } + } + for (child_name, child) in &part.children { + draw_part(child, child_name, m, adjust, paint, out); + } +} + +/// `Direction.toYRot` for horizontal facings (south 0, west 90, north 180, east 270). +fn y_rot(facing: &str) -> f32 { + match facing { + "west" => 90.0, + "north" => 180.0, + "east" => 270.0, + _ => 0.0, + } +} +fn opposite(facing: &str) -> &'static str { + match facing { + "north" => "south", + "south" => "north", + "west" => "east", + "east" => "west", + "up" => "down", + _ => "up", + } +} +fn clockwise(facing: &str) -> &'static str { + match facing { + "north" => "east", + "east" => "south", + "south" => "west", + _ => "north", + } +} +fn step(facing: &str) -> [i32; 3] { + match facing { + "north" => [0, 0, -1], + "south" => [0, 0, 1], + "west" => [-1, 0, 0], + "east" => [1, 0, 0], + "up" => [0, 1, 0], + _ => [0, -1, 0], + } +} +/// `Direction.getRotation`. +fn direction_rotation(facing: &str) -> Quat { + let xyz = |x: f32, y: f32, z: f32| Quat::from_euler(glam::EulerRot::XYZ, x, y, z); + match facing { + "down" => Quat::from_rotation_x(PI), + "north" => xyz(PI / 2.0, 0.0, PI), + "south" => Quat::from_rotation_x(PI / 2.0), + "west" => xyz(PI / 2.0, 0.0, PI / 2.0), + "east" => xyz(PI / 2.0, 0.0, -PI / 2.0), + _ => Quat::IDENTITY, + } +} +fn around(rotation: Mat4, pivot: Vec3) -> Mat4 { + Mat4::from_translation(pivot) * rotation * Mat4::from_translation(-pivot) +} + +/// `DyeColor` names and texture diffuse colours, by id. +pub const DYES: [(&str, u32); 16] = [ + ("white", 0xF9FFFE), + ("orange", 0xF9801D), + ("magenta", 0xC74EBD), + ("light_blue", 0x3AB3DA), + ("yellow", 0xFED83D), + ("lime", 0x80C71F), + ("pink", 0xF38BAA), + ("gray", 0x474F52), + ("light_gray", 0x9D9D97), + ("cyan", 0x169C9C), + ("purple", 0x8932B8), + ("blue", 0x3C44AA), + ("brown", 0x835432), + ("green", 0x5E7C16), + ("red", 0xB02E26), + ("black", 0x1D1D21), +]; +fn dye_prefix(name: &str) -> Option<(usize, &str)> { + // Longest names first so "light_gray" wins over "gray". + let mut order: Vec = (0..16).collect(); + order.sort_by_key(|&i| std::cmp::Reverse(DYES[i].0.len())); + order.into_iter().find_map(|i| { + name.strip_prefix(DYES[i].0) + .and_then(|rest| rest.strip_prefix('_')) + .map(|rest| (i, rest)) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChestPart { + Single, + Left, + Right, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SkullType { + Skeleton, + WitherSkeleton, + Zombie, + Creeper, + Dragon, + Piglin, + Player, +} +#[derive(Clone, Debug)] +enum Kind { + None, + Chest { + texture: &'static str, + part: ChestPart, + y_rot: f32, + double_with: Option<[i32; 3]>, + }, + Shulker { + texture: String, + facing: &'static str, + }, + Banner { + color: u32, + wall: bool, + angle: f32, + }, + Skull { + kind: SkullType, + wall: Option<&'static str>, + segment: u8, + }, + Bell, + DecoratedPot { + y_rot: f32, + }, + Conduit, + EnchantingTable, + Lectern { + y_rot: f32, + }, + CopperGolem { + texture: &'static str, + pose: &'static str, + facing: &'static str, + }, + /// Sign text (`StandingSignRenderer` / `HangingSignRenderer`); the boards are block models. + Sign { + hanging: bool, + wall: bool, + angle: f32, + }, +} +fn intern(facing: &str) -> &'static str { + match facing { + "north" => "north", + "south" => "south", + "west" => "west", + "east" => "east", + "up" => "up", + _ => "down", + } +} +fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + let facing = || intern(&prop("facing").unwrap_or_default()); + let chest = |texture: &'static str, left: &'static str, right: &'static str| { + let facing = facing(); + let part = match prop("type").as_deref() { + Some("left") => ChestPart::Left, + Some("right") => ChestPart::Right, + _ => ChestPart::Single, + }; + // ChestBlock.getConnectedDirection: left connects clockwise, right counter-clockwise. + let other = match part { + ChestPart::Single => None, + ChestPart::Left => Some(step(clockwise(facing))), + ChestPart::Right => Some(step(opposite(clockwise(facing)))), + }; + Kind::Chest { + texture: match part { + ChestPart::Single => texture, + ChestPart::Left => left, + ChestPart::Right => right, + }, + part, + y_rot: y_rot(facing), + double_with: other, + } + }; + if let Some(hanging) = crate::signs::sign_kind(name) { + let wall = name.contains("_wall_"); + let angle = if wall { + y_rot(facing()) + } else { + prop("rotation").and_then(|r| r.parse::().ok()).unwrap_or(0.0) * 22.5 + }; + return Kind::Sign { hanging, wall, angle }; + } + let unwaxed = name.strip_prefix("waxed_").unwrap_or(name); + match unwaxed { + "chest" => { + return chest( + "entity/chest/normal", + "entity/chest/normal_left", + "entity/chest/normal_right", + ); + } + "trapped_chest" => { + return chest( + "entity/chest/trapped", + "entity/chest/trapped_left", + "entity/chest/trapped_right", + ); + } + "ender_chest" => { + return chest( + "entity/chest/ender", + "entity/chest/ender", + "entity/chest/ender", + ); + } + "copper_chest" => { + return chest( + "entity/chest/copper", + "entity/chest/copper_left", + "entity/chest/copper_right", + ); + } + "exposed_copper_chest" => { + return chest( + "entity/chest/copper_exposed", + "entity/chest/copper_exposed_left", + "entity/chest/copper_exposed_right", + ); + } + "weathered_copper_chest" => { + return chest( + "entity/chest/copper_weathered", + "entity/chest/copper_weathered_left", + "entity/chest/copper_weathered_right", + ); + } + "oxidized_copper_chest" => { + return chest( + "entity/chest/copper_oxidized", + "entity/chest/copper_oxidized_left", + "entity/chest/copper_oxidized_right", + ); + } + "shulker_box" => { + return Kind::Shulker { + texture: "entity/shulker/shulker".into(), + facing: facing(), + }; + } + "bell" => return Kind::Bell, + "decorated_pot" => { + return Kind::DecoratedPot { + y_rot: y_rot(facing()), + }; + } + "conduit" => return Kind::Conduit, + "enchanting_table" => return Kind::EnchantingTable, + "lectern" => { + return if prop("has_book").as_deref() == Some("true") { + Kind::Lectern { + y_rot: y_rot(clockwise(facing())), + } + } else { + Kind::None + }; + } + _ => {} + } + for (prefix, texture) in [ + ("copper_golem_statue", "entity/copper_golem/copper_golem"), + ( + "exposed_copper_golem_statue", + "entity/copper_golem/copper_golem_exposed", + ), + ( + "weathered_copper_golem_statue", + "entity/copper_golem/copper_golem_weathered", + ), + ( + "oxidized_copper_golem_statue", + "entity/copper_golem/copper_golem_oxidized", + ), + ] { + if unwaxed == prefix { + let pose = match prop("copper_golem_pose").as_deref() { + Some("running") => "running", + Some("sitting") => "sitting", + Some("star") => "star", + _ => "standing", + }; + return Kind::CopperGolem { + texture, + pose, + facing: facing(), + }; + } + } + let skull = |base: &str| -> Option { + Some(match base { + "skeleton_skull" => SkullType::Skeleton, + "wither_skeleton_skull" => SkullType::WitherSkeleton, + "zombie_head" => SkullType::Zombie, + "creeper_head" => SkullType::Creeper, + "dragon_head" => SkullType::Dragon, + "piglin_head" => SkullType::Piglin, + "player_head" => SkullType::Player, + _ => return None, + }) + }; + if let Some(kind) = skull(name) { + let segment = prop("rotation").and_then(|r| r.parse().ok()).unwrap_or(0); + return Kind::Skull { + kind, + wall: None, + segment, + }; + } + if name.contains("_wall_") + && let Some(kind) = skull(&name.replace("_wall_", "_")) + { + return Kind::Skull { + kind, + wall: Some(facing()), + segment: 0, + }; + } + if let Some((dye, rest)) = dye_prefix(name) { + match rest { + "shulker_box" => { + return Kind::Shulker { + texture: format!("entity/shulker/shulker_{}", DYES[dye].0), + facing: facing(), + }; + } + "banner" => { + let segment: f32 = prop("rotation").and_then(|r| r.parse().ok()).unwrap_or(0.0); + return Kind::Banner { + color: DYES[dye].1, + wall: false, + angle: segment * 22.5, + }; + } + "wall_banner" => { + return Kind::Banner { + color: DYES[dye].1, + wall: true, + angle: y_rot(facing()), + }; + } + _ => {} + } + } + Kind::None +} + +/// `EnchantingTableBlockEntity` book animation state. +#[derive(Clone, Copy, Default)] +struct Book { + time: i32, + flip: f32, + o_flip: f32, + flip_t: f32, + flip_a: f32, + open: f32, + o_open: f32, + rot: f32, + o_rot: f32, + t_rot: f32, +} +fn wrap(mut a: f32) -> f32 { + while a >= PI { + a -= 2.0 * PI; + } + while a < -PI { + a += 2.0 * PI; + } + a +} +impl Book { + /// `EnchantingTableBlockEntity.bookAnimationTick`. + fn tick(&mut self, pos: [i32; 3], player: Option<[f64; 3]>, random: &mut LegacyRandom) { + self.o_open = self.open; + self.o_rot = self.rot; + let c = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + let near = player.filter(|p| { + (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) < 9.0 + }); + if let Some(p) = near { + self.t_rot = (p[2] - c[2]).atan2(p[0] - c[0]) as f32; + self.open += 0.1; + if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { + let old = self.flip_t; + loop { + let a = random.next_int_bound(4).unwrap_or(0); + let b = random.next_int_bound(4).unwrap_or(0); + self.flip_t += (a - b) as f32; + if old != self.flip_t { + break; + } + } + } + } else { + self.t_rot += 0.02; + self.open -= 0.1; + } + self.rot = wrap(self.rot); + self.t_rot = wrap(self.t_rot); + let dir = wrap(self.t_rot - self.rot); + self.rot += dir * 0.4; + self.open = self.open.clamp(0.0, 1.0); + self.time += 1; + self.o_flip = self.flip; + let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); + self.flip_a += (diff - self.flip_a) * 0.9; + self.flip += self.flip_a; + } +} +/// `BookModel.setupAnim` for `BookModel.State(openness, pageFlip1, pageFlip2)`. +fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) { + move |name, p| match name { + "left_lid" => p[4] = PI + openness, + "right_lid" => p[4] = -openness, + "left_pages" => { + p[4] = openness; + p[0] = openness.sin(); + } + "right_pages" => { + p[4] = -openness; + p[0] = openness.sin(); + } + "flip_page1" => { + p[4] = openness - openness * 2.0 * flip1; + p[0] = openness.sin(); + } + "flip_page2" => { + p[4] = openness - openness * 2.0 * flip2; + p[0] = openness.sin(); + } + _ => {} + } +} +fn frac(x: f32) -> f32 { + x - x.floor() +} + +/// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text +/// full-bright with an 8x outline in the dark colour. +fn sign_text(scene: &Scene, data: &crate::signs::SignData, text: &crate::signs::SignText, m: Mat4, packed: u8, near: bool, out: &mut Vec) { + let line_height = data.line_height(); + let midpoint = (4.0 * line_height / 2.0).floor(); + let dark = 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) + } else { + (dark, None, vertex_light(packed)) + }; + let width = |s: &str| s.chars().map(|c| (scene.glyph)(c).map_or(6.0, |g| g.1)).sum::(); + 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 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 }); + } + } + 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); + } + } + emit(0.0, 0.0, color); + } +} + +/// Inputs from the game for one frame of block-entity rendering. +pub struct Scene<'a> { + pub camera: DVec3, + pub partial: f32, + pub game_time: i64, + pub world: &'a World, + pub sprites: &'a HashMap, + pub nether: bool, + /// Chest lid openness (`ChestLidController.getOpenNess`) at a position. + pub lid: &'a dyn Fn([i32; 3]) -> f32, + /// Sign block-entity data at a position. + pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, + /// Font glyph cell and advance. + pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, +} + +pub struct BlockEntityRenderer { + models: HashMap<&'static str, ModelPart>, + kinds: Vec, + books: HashMap<[i32; 3], Book>, + random: LegacyRandom, +} +const MODELS: [(&str, &str); 24] = [ + ("chest", "minecraft:chest#main"), + ("double_chest_left", "minecraft:double_chest_left#main"), + ("double_chest_right", "minecraft:double_chest_right#main"), + ("shulker_box", "minecraft:shulker_box#main"), + ("standing_banner", "minecraft:standing_banner#main"), + ("standing_banner_flag", "minecraft:standing_banner#flag"), + ("wall_banner", "minecraft:wall_banner#main"), + ("wall_banner_flag", "minecraft:wall_banner#flag"), + ("skeleton_skull", "minecraft:skeleton_skull#main"), + ( + "wither_skeleton_skull", + "minecraft:wither_skeleton_skull#main", + ), + ("zombie_head", "minecraft:zombie_head#main"), + ("creeper_head", "minecraft:creeper_head#main"), + ("dragon_skull", "minecraft:dragon_skull#main"), + ("piglin_head", "minecraft:piglin_head#main"), + ("player_head", "minecraft:player_head#main"), + ("bell", "minecraft:bell#main"), + ("book", "minecraft:book#main"), + ("conduit_shell", "minecraft:conduit#shell"), + ("decorated_pot_base", "minecraft:decorated_pot_base#main"), + ("decorated_pot_sides", "minecraft:decorated_pot_sides#main"), + ("copper_golem", "minecraft:copper_golem#main"), + ( + "copper_golem_running", + "minecraft:copper_golem_running#main", + ), + ( + "copper_golem_sitting", + "minecraft:copper_golem_sitting#main", + ), + ("copper_golem_star", "minecraft:copper_golem_star#main"), +]; +/// `BlockEntityRenderer.getViewDistance` default. +const VIEW_DISTANCE: f64 = 64.0; + +impl BlockEntityRenderer { + pub fn load(root: &Path, registry: &BlockRegistry) -> crate::Result { + let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?; + let models = MODELS + .iter() + .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) + .collect(); + Ok(Self::new(models, registry)) + } + fn new(models: HashMap<&'static str, ModelPart>, registry: &BlockRegistry) -> Self { + let kinds = (0..registry.len() as u32) + .map(|id| { + registry.state(BlockStateId(id)).map_or(Kind::None, |s| { + let prop = |k: &str| s.properties.get(k).cloned(); + classify(&s.name, &prop) + }) + }) + .collect(); + Self { + models, + kinds, + books: HashMap::new(), + random: LegacyRandom::new(0x5EED_B00C), + } + } + fn kind(&self, state: u32) -> &Kind { + self.kinds.get(state as usize).unwrap_or(&Kind::None) + } + /// Client-side block-entity ticks (enchanting-table books). + pub fn tick<'a>( + &mut self, + blocks: impl Iterator, + player: Option<[f64; 3]>, + ) { + let mut seen = Vec::new(); + for (pos, state) in blocks { + if matches!(self.kind(*state), Kind::EnchantingTable) { + seen.push(*pos); + } + } + self.books.retain(|p, _| seen.contains(p)); + for pos in seen { + let book = self.books.entry(pos).or_default(); + book.tick(pos, player, &mut self.random); + } + } + pub fn render<'a>( + &self, + scene: &Scene, + blocks: impl Iterator, + out: &mut Vec, + ) { + let lights = diffuse_lights(scene.nether); + for (pos, state) in blocks { + let kind = self.kind(*state); + if matches!(kind, Kind::None) { + continue; + } + let center = DVec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ); + if center.distance_squared(scene.camera) > VIEW_DISTANCE * VIEW_DISTANCE { + continue; + } + let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + - scene.camera) + .as_vec3(); + let base = Mat4::from_translation(origin); + let packed = scene.world.light(pos[0], pos[1], pos[2]); + self.render_one(scene, *pos, kind, base, packed, lights, out); + } + } + #[allow(clippy::too_many_arguments)] + fn render_one( + &self, + scene: &Scene, + pos: [i32; 3], + kind: &Kind, + base: Mat4, + packed: u8, + lights: (Vec3, Vec3), + out: &mut Vec, + ) { + let sprite = |name: &str| scene.sprites.get(name).copied(); + let paint = |name: &str, tint: u32, packed: u8| { + sprite(name).map(|s| Paint { + sprite: s, + tint, + light: vertex_light(packed), + lights, + }) + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + match kind { + Kind::None => {} + Kind::Sign { hanging, wall, angle } => { + let Some(data) = (scene.sign)(pos) else { return }; + let s = Vec3::new(1.0, -1.0, 1.0); + for (front, text) in [(true, &data.front), (false, &data.back)] { + if text.is_empty() { + continue; + } + let mut m = base; + if *hanging { + // HangingSignRenderer.textTransformation. + m *= Mat4::from_translation(Vec3::new(0.5, 0.9375, 0.5)) + * Mat4::from_rotation_y((-angle).to_radians()) + * Mat4::from_translation(Vec3::new(0.0, -0.3125, 0.0)); + if !front { + m *= Mat4::from_rotation_y(PI); + } + m *= Mat4::from_translation(Vec3::new(0.0, -0.32, 0.073)) * Mat4::from_scale(s * 0.014_062_5); + } else { + // StandingSignRenderer.textTransformation. + m *= Mat4::from_translation(Vec3::splat(0.5)) * Mat4::from_rotation_y((-angle).to_radians()); + if *wall { + m *= Mat4::from_translation(Vec3::new(0.0, -0.3125, -0.4375)); + } + if !front { + m *= Mat4::from_rotation_y(PI); + } + m *= Mat4::from_translation(Vec3::new(0.0, 1.0 / 3.0, 0.046_666_667)) * Mat4::from_scale(s * 0.010_416_667); + } + let near = DVec3::new(f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5).distance_squared(scene.camera) < 256.0; + sign_text(scene, data, text, m, packed, near, out); + } + } + Kind::Chest { + texture, + part, + y_rot, + double_with, + } => { + let model = match part { + ChestPart::Single => "chest", + ChestPart::Left => "double_chest_left", + ChestPart::Right => "double_chest_right", + }; + let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { + return; + }; + // ChestBlock.opennessCombiner / BrightnessCombiner: both halves. + let mut open = (scene.lid)(pos); + let mut packed = packed; + if let Some(d) = double_with { + let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + open = open.max((scene.lid)(other)); + let l = scene.world.light(other[0], other[1], other[2]); + packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15); + } + let open = 1.0 - (1.0 - open).powi(3); + let m = base + * around( + Mat4::from_rotation_y((-y_rot).to_radians()), + Vec3::new(0.5, 0.0, 0.5), + ); + let lid = -(open * PI / 2.0); + let adjust = move |name: &str, p: &mut [f32; 9]| { + if name == "lid" || name == "lock" { + p[3] = lid; + } + }; + if let Some(paint) = paint(texture, 0xFFFFFF, packed) { + draw_part(model, "root", m, &adjust, paint, out); + } + } + Kind::Shulker { texture, facing } => { + let (Some(model), Some(paint)) = ( + self.models.get("shulker_box"), + paint(texture, 0xFFFFFF, packed), + ) else { + return; + }; + let m = base + * Mat4::from_translation(Vec3::splat(0.5)) + * Mat4::from_scale(Vec3::splat(0.9995)) + * 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); + } + Kind::Banner { color, wall, angle } => { + let (main, flag) = if *wall { + ("wall_banner", "wall_banner_flag") + } else { + ("standing_banner", "standing_banner_flag") + }; + let (Some(main), Some(flag)) = (self.models.get(main), self.models.get(flag)) + else { + return; + }; + let m = base + * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) + * Mat4::from_rotation_y((-angle).to_radians()) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let time = scene.game_time; + let phase = ((i64::from(pos[0]) * 7 + + i64::from(pos[1]) * 9 + + i64::from(pos[2]) * 13 + + time) + .rem_euclid(100) as f32 + + scene.partial) + / 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; + } + }; + if let Some(paint) = paint("entity/banner/banner_base", 0xFFFFFF, packed) { + draw_part(main, "root", m, &none, paint, out); + draw_part(flag, "root", m, &wave, paint, out); + } + // BannerRenderer.submitPatterns: the base pattern layer in the dye colour. + if let Some(paint) = paint("entity/banner/base", *color, packed) { + draw_part(flag, "root", m, &wave, paint, out); + } + } + Kind::Skull { + kind, + wall, + segment, + } => { + let (model, texture) = match kind { + SkullType::Skeleton => ("skeleton_skull", "entity/skeleton/skeleton"), + SkullType::WitherSkeleton => { + ("wither_skeleton_skull", "entity/skeleton/wither_skeleton") + } + SkullType::Zombie => ("zombie_head", "entity/zombie/zombie"), + 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"), + }; + let (Some(model), Some(paint)) = + (self.models.get(model), paint(texture, 0xFFFFFF, packed)) + else { + return; + }; + let m = match wall { + Some(facing) => { + let s = step(facing); + base * Mat4::from_translation(Vec3::new( + 0.5 - s[0] as f32 * 0.25, + 0.25, + 0.5 - s[2] as f32 * 0.25, + )) * Mat4::from_rotation_y((-y_rot(opposite(facing))).to_radians()) + * Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0)) + } + None => { + base * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) + * Mat4::from_rotation_y((-(f32::from(*segment) * 22.5)).to_radians()) + * 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, + _ => {} + }; + draw_part(model, "root", m, &anim, paint, out); + } + Kind::Bell => { + let (Some(model), Some(paint)) = ( + self.models.get("bell"), + paint("entity/bell/bell_body", 0xFFFFFF, packed), + ) else { + return; + }; + draw_part(model, "root", base, &none, paint, out); + } + Kind::DecoratedPot { y_rot } => { + let (Some(base_model), Some(sides)) = ( + self.models.get("decorated_pot_base"), + self.models.get("decorated_pot_sides"), + ) else { + return; + }; + let m = base + * around( + Mat4::from_rotation_y((180.0 - y_rot).to_radians()), + Vec3::splat(0.5), + ); + 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); + } + } + 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 { + return; + }; + draw_part( + model, + "root", + base * Mat4::from_translation(Vec3::splat(0.5)), + &none, + paint, + out, + ); + } + Kind::EnchantingTable => { + let (Some(model), Some(paint)) = ( + self.models.get("book"), + paint("entity/enchantment/enchanting_table_book", 0xFFFFFF, packed), + ) else { + return; + }; + let b = self.books.get(&pos).copied().unwrap_or_default(); + let a = scene.partial; + let flip = b.o_flip + (b.flip - b.o_flip) * a; + let open = b.o_open + (b.open - b.o_open) * a; + let time = b.time as f32 + a; + 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_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; + draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out); + } + Kind::Lectern { y_rot } => { + let (Some(model), Some(paint)) = ( + self.models.get("book"), + paint("entity/enchantment/enchanting_table_book", 0xFFFFFF, packed), + ) else { + return; + }; + let m = base + * Mat4::from_translation(Vec3::new(0.5, 1.0625, 0.5)) + * Mat4::from_rotation_y((-y_rot).to_radians()) + * Mat4::from_rotation_z(67.5f32.to_radians()) + * Mat4::from_translation(Vec3::new(0.0, -0.125, 0.0)); + // LecternRenderer.BOOK_STATE = forAnimation(0, 0.1, 0.9, 1.2). + draw_part( + model, + "root", + m, + &book_pose(1.25 * 1.2, 0.1, 0.9), + paint, + out, + ); + } + Kind::CopperGolem { + texture, + pose, + facing, + } => { + let key = match *pose { + "running" => "copper_golem_running", + "sitting" => "copper_golem_sitting", + "star" => "copper_golem_star", + _ => "copper_golem", + }; + let (Some(model), Some(paint)) = + (self.models.get(key), paint(texture, 0xFFFFFF, packed)) + else { + return; + }; + let m = base + * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) + * Mat4::from_rotation_y((-y_rot(opposite(facing))).to_radians()); + // CopperGolemStatueModel.setupAnim: root.y = 0, root.zRot = PI. + let statue = |name: &str, p: &mut [f32; 9]| { + if name == "root" { + p[1] = 0.0; + p[5] = PI; + } + }; + draw_part(model, "root", m, &statue, paint, out); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn classifies_vanilla_block_names() { + let props = |pairs: &'static [(&'static str, &'static str)]| { + move |k: &str| { + pairs + .iter() + .find(|(a, _)| *a == k) + .map(|(_, v)| (*v).to_owned()) + } + }; + let k = classify( + "minecraft:light_gray_shulker_box", + &props(&[("facing", "up")]), + ); + assert!( + matches!(k, Kind::Shulker { ref texture, .. } if texture == "entity/shulker/shulker_light_gray") + ); + let k = classify("minecraft:gray_wall_banner", &props(&[("facing", "west")])); + assert!(matches!(k, Kind::Banner { color: 0x474F52, wall: true, angle } if angle == 90.0)); + let k = classify( + "minecraft:wither_skeleton_wall_skull", + &props(&[("facing", "north")]), + ); + assert!(matches!( + k, + Kind::Skull { + kind: SkullType::WitherSkeleton, + wall: Some("north"), + .. + } + )); + let k = classify("minecraft:piglin_head", &props(&[("rotation", "4")])); + assert!(matches!( + k, + Kind::Skull { + kind: SkullType::Piglin, + wall: None, + segment: 4 + } + )); + let k = classify( + "minecraft:chest", + &props(&[("facing", "north"), ("type", "left")]), + ); + // A north-facing left half connects to the east (clockwise). + assert!(matches!( + k, + Kind::Chest { + part: ChestPart::Left, + double_with: Some([1, 0, 0]), + texture: "entity/chest/normal_left", + .. + } + )); + let k = classify( + "minecraft:waxed_oxidized_copper_chest", + &props(&[("facing", "south"), ("type", "single")]), + ); + assert!(matches!( + k, + Kind::Chest { + texture: "entity/chest/copper_oxidized", + .. + } + )); + assert!(matches!( + classify("minecraft:lectern", &props(&[("has_book", "false")])), + Kind::None + )); + assert!(matches!( + classify("minecraft:furnace", &props(&[])), + Kind::None + )); + } + #[test] + fn mix_light_matches_shader() { + let lights = diffuse_lights(false); + // Straight up: both lights contribute. + let up = diffuse(Vec3::Y, lights); + let expected = ((lights.0.y + lights.1.y) * 0.6 + 0.4).min(1.0); + assert!((up - expected).abs() < 1e-6); + // Straight down: ambient only. + assert!((diffuse(-Vec3::Y, lights) - 0.4).abs() < 1e-6); + } + #[test] + fn part_poses_compose_like_model_part() { + let part = ModelPart { + pose: [16.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], + polygons: vec![[ + [0.0, 0.0, 0.0, 0.0, 0.0], + [16.0, 0.0, 0.0, 1.0, 0.0], + [16.0, 0.0, 16.0, 1.0, 1.0], + [0.0, 0.0, 16.0, 0.0, 1.0], + ]], + children: vec![], + }; + let mut out = Vec::new(); + let rect = Rect { + u0: 0.0, + v0: 0.0, + u1: 0.5, + v1: 0.5, + w: 1, + h: 1, + }; + draw_part( + &part, + "root", + Mat4::IDENTITY, + &|_, _| {}, + Paint { + sprite: rect, + tint: 0xFFFFFF, + light: 0, + lights: diffuse_lights(false), + }, + &mut out, + ); + assert_eq!(out.len(), 4); + assert_eq!(out[1].pos, [2.0, 0.0, 0.0]); + assert_eq!(out[2].uv, [0.5, 0.5]); + } +} diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index b67529ece..fe7547e65 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -52,6 +52,19 @@ pub struct StateFacts { pub fluid_level: u8, pub fluid_falling: bool, pub waterlogged: bool, + /// `hasOffsetFunction`: the model is jittered per column. + pub random_offset: bool, + /// `BlockState.isSolid()` (legacy solidity; fluid surfaces read it). + pub legacy_solid: bool, + /// `isFaceSturdy(.., SupportType.FULL)` by Direction ordinal. + pub sturdy_full: u8, + /// The block's class chain (`TransparentBlock`, `LeavesBlock`, ...), most specific first. + pub classes: Arc<[Arc]>, +} +impl StateFacts { + pub fn has_class(&self, name: &str) -> bool { + self.classes.iter().any(|c| &**c == name) + } } pub struct BlockFacts { pub states: Vec, @@ -67,6 +80,33 @@ impl BlockFacts { if entries.len() != registry.len() { return Err("gameplay facts do not match the block registry".into()); } + // Class chains and per-state behaviour flags exported from the actual block objects. + let behaviours: Value = serde_json::from_reader(BufReader::new(File::open( + root.join("block-behaviours.json"), + )?))?; + let behaviour_states = behaviours["states"] + .as_array() + .filter(|s| s.len() == registry.len()) + .ok_or("block behaviour facts do not match the block registry")?; + let mut class_names: HashMap> = HashMap::new(); + let classes: HashMap<&str, Arc<[Arc]>> = behaviours["blocks"] + .as_array() + .ok_or("missing block behaviour classes")? + .iter() + .filter_map(|b| { + let chain = b["class"] + .as_array()? + .iter() + .filter_map(Value::as_str) + .map(|c| { + class_names + .entry(c.to_owned()) + .or_insert_with(|| Arc::from(c)) + .clone() + }); + Some((b["name"].as_str()?, chain.collect())) + }) + .collect(); let mut names: HashMap> = HashMap::new(); let mut intern = |s: &str| -> Arc { names @@ -143,6 +183,13 @@ impl BlockFacts { fluid_level, fluid_falling, waterlogged: prop("waterlogged") == Some("true"), + random_offset: flag("offset"), + legacy_solid: behaviour_states[index][1].as_u64().unwrap_or(0) & 1 != 0, + sturdy_full: (behaviour_states[index][0].as_u64().unwrap_or(0) & 63) as u8, + classes: classes + .get(state.name.as_str()) + .cloned() + .ok_or("missing block behaviour class chain")?, }); } Ok(Self { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 4267e3ef2..f12dc9a67 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -50,9 +50,14 @@ pub enum BlockEntity { Chest(Vec>), Furnace(Furnace), Brewing(Box), + /// Signs and hanging signs (`SignBlockEntity`). + Sign(crate::signs::SignData), } impl BlockEntity { pub fn for_block(name: &str) -> Option { + if let Some(hanging) = crate::signs::sign_kind(name) { + return Some(Self::Sign(crate::signs::SignData { hanging, ..Default::default() })); + } if let Some(kind) = FurnaceKind::from_block(name) { return Some(Self::Furnace(Furnace { kind, @@ -112,6 +117,7 @@ impl BlockEntity { FurnaceKind::BlastFurnace => "minecraft:blast_furnace", FurnaceKind::Smoker => "minecraft:smoker", }, + Self::Sign(s) => s.id(), } } pub fn contents(&self) -> Vec { @@ -125,6 +131,7 @@ impl BlockEntity { match self { Self::Chest(items) => items, Self::Furnace(f) => &f.items, + Self::Sign(_) => Vec::new(), } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -132,6 +139,7 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, + Self::Sign(_) => &mut [], } } } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index ed2f00277..490270251 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -9,6 +9,8 @@ struct Globals { inverse_view: mat4x4, sunrise: vec4, sun: vec4, + // x: sky fog end, y: cloud fog end + fog_ends: vec4, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var atlas: texture_2d; @@ -22,6 +24,7 @@ struct Out { @location(2) spherical: f32, @location(3) cylindrical: f32, @location(4) flash: f32, + @location(4) @interpolate(flat) overlay: u32, } @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4) -> Out { @@ -31,8 +34,8 @@ struct Out { let l = vec2(f32(light.y), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); - // overlay 2: celestial bodies use their vertex colour unlit. - var c = select(color * lm, color, overlay == 2u); + // overlay 2: celestial bodies, 4: clouds; both use their vertex colour unlit. + var c = select(color * lm, color, overlay == 2u || overlay == 4u); // Hurt overlay (OverlayTexture red tint). if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); } out.color = c; @@ -41,6 +44,8 @@ struct Out { // Sky geometry (clouds, celestial bodies) is exempt from render-distance fog. out.spherical = select(length(position), 0.0, overlay >= 2u); out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u); + out.overlay = overlay; + if overlay == 4u { out.spherical = length(position); } return out; } fn linear_fog(d: f32, start: f32, end: f32) -> f32 { @@ -50,6 +55,11 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { } @fragment fn fs_entity(in: Out) -> @location(0) vec4 { var color = textureSample(atlas, atlas_sampler, in.uv) * in.color; + let color = textureSample(atlas, atlas_sampler, in.uv) * in.color; + if in.overlay == 4u { + // clouds.fsh: alpha fades out towards the cloud fog end. + return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y))); + } if color.a < 0.1 { discard; } color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a); let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs new file mode 100644 index 000000000..90d2e109f --- /dev/null +++ b/crates/horizon-client/src/fog.rs @@ -0,0 +1,399 @@ +//! `FogRenderer` and its fog environments (atmospheric with rain fog, water +//! with water vision, lava, powder snow, blindness), the camera fog type +//! (`Camera.getFluidInCamera`) and the fog colour (`computeFogColor`: sunrise +//! tint, sky-colour mix, void darkness, water-vision brightening). +use crate::{ + biome::Biomes, + blocks::{BlockFacts, Fluid}, + environment::Sky, + world::World, +}; +use std::path::Path; + +/// `FogType` of the camera position. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FogType { + Atmospheric, + Water, + Lava, + PowderSnow, +} + +/// The fog uniform (`FogData`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FogData { + pub color: [f32; 4], + pub environmental_start: f32, + pub environmental_end: f32, + pub render_distance_start: f32, + pub render_distance_end: f32, + pub sky_end: f32, + pub cloud_end: f32, +} + +/// Per-biome water fog end multipliers (`visual/water_fog_end_distance`). +pub struct FogTables { + water_fog_end: Vec, +} +impl FogTables { + pub fn load(root: &Path, biomes: &Biomes) -> Self { + let mut water_fog_end = vec![1.0; biomes.list.len()]; + for (name, &id) in &biomes.index { + let path = root.join(format!( + "data/minecraft/worldgen/biome/{}.json", + name.trim_start_matches("minecraft:") + )); + let Ok(bytes) = std::fs::read(path) else { + continue; + }; + let Ok(json) = serde_json::from_slice::(&bytes) else { + continue; + }; + let v = &json["attributes"]["minecraft:visual/water_fog_end_distance"]; + if v["modifier"].as_str() == Some("multiply") + && let (Some(f), Some(slot)) = + (v["argument"].as_f64(), water_fog_end.get_mut(id as usize)) + { + *slot = f as f32; + } + } + Self { water_fog_end } + } +} + +/// Fog state that evolves over time. +#[derive(Clone, Copy, Debug, Default)] +pub struct FogState { + /// `LocalPlayer.waterVisionTime` (0..600). + pub water_vision_time: i32, + /// `AtmosphericFogEnvironment.rainFogMultiplier`. + pub rain_fog_multiplier: f32, +} +impl FogState { + /// `LocalPlayer.aiStep`: water vision ramps up while the eye is in water. + pub fn tick(&mut self, eye_in_water: bool) { + self.water_vision_time = if eye_in_water { + (self.water_vision_time + 1).min(600) + } else { + (self.water_vision_time - 10).max(0) + }; + } + /// `LocalPlayer.getWaterVision`. + pub fn water_vision(&self, eye_in_water: bool) -> f32 { + if !eye_in_water { + return 0.0; + } + let t = self.water_vision_time as f32; + if t >= 600.0 { + return 1.0; + } + let a = (t / 100.0).clamp(0.0, 1.0); + let b = if t < 100.0 { + 0.0 + } else { + ((t - 100.0) / 500.0).clamp(0.0, 1.0) + }; + a * 0.6 + b * 0.399_999_98 + } +} + +/// The fog tables and evolving state kept by the game. +pub struct FogRenderer { + pub tables: FogTables, + pub state: FogState, +} +impl FogRenderer { + pub fn load(root: &Path, biomes: &Biomes) -> Self { + Self { + tables: FogTables::load(root, biomes), + state: FogState::default(), + } + } + pub fn setup(&self, input: &FogInputs) -> FogData { + setup_fog(&self.tables, &self.state, input) + } +} +/// `FluidState.getHeightForCamera`. +fn camera_fluid_height(world: &World, facts: &BlockFacts, b: [i32; 3]) -> Option<(Fluid, f64)> { + let s = facts.get(world.block(b[0], b[1], b[2])); + if s.fluid == Fluid::None { + return None; + } + let above = facts.get(world.block(b[0], b[1] + 1, b[2])); + let source = s.fluid_level >= 8 && !s.fluid_falling; + let height = if source && above.full_collision { + 1.0 + } else if above.fluid == s.fluid { + 1.0 + } else { + f64::from(s.fluid_level) / 9.0 + }; + Some((s.fluid, height)) +} +/// `Camera.getFluidInCamera` (near-plane points reduced to the camera and +/// the point just in front of it). +pub fn fog_type(world: &World, facts: &BlockFacts, camera: [f64; 3], forward: [f64; 3]) -> FogType { + let block = |p: [f64; 3]| { + [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ] + }; + let b = block(camera); + if let Some((Fluid::Water, h)) = camera_fluid_height(world, facts, b) + && camera[1] < f64::from(b[1]) + h + { + return FogType::Water; + } + for p in [ + [ + camera[0] + forward[0] * 0.05, + camera[1] + forward[1] * 0.05, + camera[2] + forward[2] * 0.05, + ], + camera, + ] { + let b = block(p); + match camera_fluid_height(world, facts, b) { + Some((Fluid::Lava, h)) if p[1] <= f64::from(b[1]) + h => return FogType::Lava, + Some((Fluid::Lava, _)) => {} + _ => { + if &*facts.get(world.block(b[0], b[1], b[2])).name == "minecraft:powder_snow" { + return FogType::PowderSnow; + } + } + } + } + FogType::Atmospheric +} + +/// Everything `FogRenderer.setupFog` reads for one frame. +pub struct FogInputs<'a> { + pub fog_type: FogType, + pub sky: &'a Sky, + /// Biome water fog colour (`visual/water_fog_color`). + pub water_fog_color: [f32; 3], + pub biome: u16, + pub render_distance_chunks: i32, + pub camera_y: f64, + pub min_y: i32, + /// Flat worlds use a 1-block void darkness range. + pub flat: bool, + pub forward: [f32; 3], + pub rain: f32, + pub thunder: f32, + /// Dimensions with a sky disc (overworld): sunrise tint and sky mix apply. + pub skybox: bool, + /// Blindness: (remaining duration ticks, infinite). + pub blindness: Option<(i32, bool)>, +} + +/// `FogRenderer.setupFog` + `computeFogColor`. +pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> FogData { + let rd = input.render_distance_chunks as f32 * 16.0; + let sky = input.sky; + let eye_in_water = input.fog_type == FogType::Water; + let water_vision = state.water_vision(eye_in_water); + // Base colour of the applicable environment. + let mut color = match input.fog_type { + FogType::Lava => rgb(0x99_1A00), + FogType::PowderSnow => rgb(0x9F_BACC), + FogType::Water => input.water_fog_color, + FogType::Atmospheric => { + let mut fog = sky.fog_color; + if input.skybox && input.render_distance_chunks >= 4 { + let sun_x = if sky.sun_angle.to_radians().sin() > 0.0 { + -1.0 + } else { + 1.0 + }; + let looking = input.forward[0] * sun_x; + let alpha = sky.sunrise_color[3]; + if looking > 0.0 && alpha > 0.0 { + let t = looking * alpha; + fog = std::array::from_fn(|i| fog[i] + (sky.sunrise_color[i] - fog[i]) * t); + } + } + let mut sky_color = sky.sky_color; + if input.rain > 0.0 { + let m = 1.0 - input.rain * 0.5; + let mb = 1.0 - input.rain * 0.4; + sky_color = [sky_color[0] * m, sky_color[1] * m, sky_color[2] * mb]; + } + if input.thunder > 0.0 { + let m = 1.0 - input.thunder * 0.5; + sky_color = sky_color.map(|c| c * m); + } + let sky_fog_end = (512.0f32 / 16.0).min(input.render_distance_chunks as f32); + let mix = (sky_fog_end / 32.0).clamp(0.0, 1.0).mul_add(0.75, 0.25); + let mix = 1.0 - mix.powf(0.25); + std::array::from_fn(|i| fog[i] + (sky_color[i] - fog[i]) * mix) + } + }; + // Void darkness and blindness. + let range = if input.flat { 1.0 } else { 32.0 }; + let mut darkness = + ((range + input.min_y as f32 - input.camera_y as f32) / range).clamp(0.0, 1.0); + if let Some((duration, infinite)) = input.blindness { + darkness = if !infinite && duration < 20 { + darkness.max(duration as f32 / 20.0) + } else { + 1.0 + }; + } + if darkness > 0.0 && !matches!(input.fog_type, FogType::Lava | FogType::PowderSnow) { + let brightness = (1.0 - darkness) * (1.0 - darkness); + color = color.map(|c| c * brightness); + } + let brighten = if eye_in_water { water_vision } else { 0.0 }; + if color.iter().all(|&c| c != 0.0) { + let scale = 1.0 / color[0].max(color[1]).max(color[2]); + color = color.map(|c| c + (c * scale - c) * brighten); + } + let mut fog = FogData { + color: [color[0], color[1], color[2], 1.0], + environmental_start: 0.0, + environmental_end: 1024.0, + render_distance_start: 0.0, + render_distance_end: rd, + sky_end: rd.min(512.0), + cloud_end: 2048.0, + }; + match input.fog_type { + FogType::Lava => { + fog.environmental_start = 0.25; + fog.environmental_end = 1.0; + fog.sky_end = 1.0; + fog.cloud_end = 1.0; + } + FogType::PowderSnow => { + fog.environmental_start = 0.0; + fog.environmental_end = 2.0; + fog.sky_end = 2.0; + fog.cloud_end = 2.0; + } + _ if input.blindness.is_some() => { + let (duration, infinite) = input.blindness.unwrap_or((0, true)); + let distance = if infinite { + 5.0 + } else { + rd + (5.0 - rd) * (duration as f32 / 20.0).min(1.0) + }; + fog.environmental_start = distance * 0.25; + fog.environmental_end = distance; + fog.sky_end = distance * 0.8; + fog.cloud_end = distance * 0.8; + } + FogType::Water => { + fog.environmental_start = -8.0; + let factor = tables + .water_fog_end + .get(input.biome as usize) + .copied() + .unwrap_or(1.0); + fog.environmental_end = 96.0 * factor * water_vision.max(0.25); + fog.sky_end = fog.environmental_end; + fog.cloud_end = fog.environmental_end; + } + FogType::Atmospheric => { + fog.environmental_start = sky.fog_start + -160.0 * state.rain_fog_multiplier; + let min_end = sky.fog_end.min(96.0); + fog.environmental_end = min_end.max(sky.fog_end + -256.0 * state.rain_fog_multiplier); + fog.sky_end = rd.min(512.0); + fog.cloud_end = 2048.0f32.min(128.0 * 16.0); + } + } + let span = (rd / 10.0).clamp(4.0, 64.0); + fog.render_distance_start = rd - span; + fog.render_distance_end = rd; + fog +} +/// `AtmosphericFogEnvironment.updateRainFogState`. +pub fn update_rain_fog( + state: &mut FogState, + rain: f32, + sky_light: u8, + biome_rains: bool, + delta_ticks: f32, +) { + let sky = ((f32::from(sky_light) - 8.0) / 7.0).clamp(0.0, 1.0); + let target = rain * sky * if biome_rains { 1.0 } else { 0.5 }; + state.rain_fog_multiplier += (target - state.rain_fog_multiplier) * delta_ticks * 0.2; +} +fn rgb(c: u32) -> [f32; 3] { + [ + (c >> 16 & 255) as f32 / 255.0, + (c >> 8 & 255) as f32 / 255.0, + (c & 255) as f32 / 255.0, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + fn inputs(sky: &Sky) -> FogInputs<'_> { + FogInputs { + fog_type: FogType::Atmospheric, + sky, + water_fog_color: [0.0, 0.0, 0.2], + biome: 0, + render_distance_chunks: 12, + camera_y: 70.0, + min_y: -64, + flat: false, + forward: [0.0, 0.0, 1.0], + rain: 0.0, + thunder: 0.0, + skybox: true, + blindness: None, + } + } + #[test] + fn render_distance_fog_span() { + let sky = Sky { + fog_end: 1024.0, + fog_color: [0.5; 3], + sky_color: [0.5; 3], + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.0], + }; + let fog = setup_fog(&tables, &FogState::default(), &inputs(&sky)); + // 12 chunks = 192 blocks, span clamp(19.2, 4, 64). + assert!((fog.render_distance_start - (192.0 - 19.2)).abs() < 1e-4); + assert_eq!(fog.render_distance_end, 192.0); + assert_eq!(fog.sky_end, 192.0); + } + #[test] + fn water_vision_ramps() { + let mut s = FogState::default(); + for _ in 0..100 { + s.tick(true); + } + assert!((s.water_vision(true) - 0.6).abs() < 1e-6); + for _ in 0..500 { + s.tick(true); + } + assert_eq!(s.water_vision(true), 1.0); + assert_eq!(s.water_vision(false), 0.0); + } + #[test] + fn rain_fog_pulls_fog_in() { + let sky = Sky { + fog_end: 1024.0, + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.0], + }; + let state = FogState { + rain_fog_multiplier: 1.0, + ..FogState::default() + }; + let fog = setup_fog(&tables, &state, &inputs(&sky)); + assert_eq!(fog.environmental_start, -160.0); + assert_eq!(fog.environmental_end, 768.0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 126d371b1..618ae56f0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -22,6 +22,9 @@ mod options; mod packs; mod screens; mod creatures; +mod render_control; +mod render_tick; +mod sign_edit; use horizon_client::{ Result, assets::Assets, @@ -337,7 +340,10 @@ pub struct Resources { mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, providers: Providers, - chest_model: Option, + block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer, + animate: horizon_client::animate_tick::AnimateTables, + fog: horizon_client::fog::FogRenderer, + screen_fx: horizon_client::screen_effects::ScreenEffects, nether_environment: Environment, end_environment: Environment, behaviours: Behaviours, @@ -407,7 +413,9 @@ struct Game<'a> { audio: Audio, dropped: Vec, next_entity: u32, - particles: Vec, + particles: horizon_client::particles::ParticleEngine, + /// Sign text being edited (`SignEditScreen`). + sign_edit: Option, spawn_search: u32, mobs: Vec, arrows: Vec, @@ -1132,7 +1140,11 @@ impl Game<'_> { }; let target = [pos.x, pos.y, pos.z]; if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + let sign = matches!(entity, BlockEntity::Sign(_)); self.world.block_entities.insert((target[0], target[1], target[2]), entity); + if sign { + self.open_sign_editor((target[0], target[1], target[2]), true); + } } self.swing_arm(); let sounds = self.res.facts.get(state).sounds.clone(); @@ -1543,7 +1555,11 @@ impl Game<'_> { if self.particles.len() > 4000 { let excess = self.particles.len() - 4000; self.particles.drain(..excess); + if let Some(r) = &self.renderer { + let eye = self.player.as_ref().map(|p| [p.position.x, p.position.y + f64::from(self.eye), p.position.z]); + self.res.block_entity_render.tick(r.block_entities(), eye); } + self.tick_particles(); if self.right && self.use_delay == 0 && self.screen == Screen::Playing { self.use_item()?; self.use_delay = 4; @@ -1847,6 +1863,7 @@ impl Game<'_> { Screen::Playing | Screen::Options => {} } self.remote_hud(&mut batch); + self.draw_sign_editor(&mut batch); batch } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { @@ -1866,6 +1883,7 @@ impl Game<'_> { Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)), Some(BlockEntity::Furnace(_)) => v.extend(300..303), Some(BlockEntity::Brewing(_)) => v.extend(300..305), + Some(BlockEntity::Sign(_)) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); v.push(200); @@ -1989,6 +2007,7 @@ impl Game<'_> { } } Some(BlockEntity::Brewing(_)) => {} + Some(BlockEntity::Sign(_)) => {} None => { let texture = if self.craft_size == 3 { "gui/container/crafting_table" } else { "gui/container/inventory" }; part(batch, texture, 0.0, 0.0, 176.0, 166.0, ox, oy); @@ -2258,50 +2277,42 @@ impl Game<'_> { } } } - // Chests (ChestRenderer): rotate by facing around the block centre, lift the lid. - if let Some(model) = &self.res.chest_model { - for (pos, entity) in &self.world.block_entities { - if !matches!(entity, BlockEntity::Chest(_)) { - continue; - } - let state = self.world.block(pos.0, pos.1, pos.2); - let name = &self.res.facts.get(state).name; - let texture = match &**name { - "minecraft:chest" => "entity/chest/normal", - "minecraft:trapped_chest" => "entity/chest/trapped", - _ => continue, - }; - let origin = glam::DVec3::new(f64::from(pos.0), f64::from(pos.1), f64::from(pos.2)) - camera; - if origin.length_squared() > 64.0 * 64.0 { - continue; - } - let Some(r) = self.res.atlas.sprites.get(texture).copied() else { continue }; - let facing = self.res.assets.registry.state(state).and_then(|s| s.properties.get("facing").cloned()).unwrap_or_default(); - let yrot: f32 = match facing.as_str() { - "west" => 90.0, - "north" => 180.0, - "east" => 270.0, - _ => 0.0, - }; - let (prev, cur) = self.chest_open.get(pos).copied().unwrap_or((0.0, 0.0)); - let o = prev + (cur - prev) * alpha as f32; - let open = 1.0 - (1.0 - o).powi(3); - let base = glam::Mat4::from_translation(origin.as_vec3()) - * glam::Mat4::from_translation(glam::Vec3::new(0.5, 0.0, 0.5)) - * glam::Mat4::from_rotation_y((-yrot).to_radians()) - * glam::Mat4::from_translation(glam::Vec3::new(-0.5, 0.0, -0.5)); - let light = self.world.light(pos.0, pos.1, pos.2); - let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; - let pose = |part: &horizon_client::mobs::Part| { - let mut p = part.pose; - if part.name == "lid" || part.name == "lock" { - p[3] = -(open * std::f32::consts::FRAC_PI_2); - } - p - }; - horizon_client::mobs::render_model(model, base, &pose, [r.u0, r.v0, r.u1, r.v1], packed, 0, &mut out); + // Entity shadows (EntityRenderer.extractShadow). + if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() { + let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; + let darken = self.sky_darken(); + let a = alpha; + let lerp = |p: Vec3, q: Vec3| glam::DVec3::new(p.x + (q.x - p.x) * a, p.y + (q.y - p.y) * a, p.z + (q.z - p.z) * a); + let mut casters: Vec<(glam::DVec3, &str)> = self.mobs.iter().map(|m| (lerp(m.previous, m.position), m.kind.id.as_str())).collect(); + casters.extend(self.dropped.iter().map(|i| (lerp(i.previous, i.position), "minecraft:item"))); + casters.extend(self.orbs.iter().map(|o| (lerp(o.previous, o.position), "minecraft:experience_orb"))); + for (pos, id) in casters { + let (radius, strength) = horizon_client::shadows::shadow_params(id); + horizon_client::shadows::shadow(&self.world, &self.res.facts, sprite, camera, pos, radius, strength, ambient, darken, &mut out); } } + // Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls... + if let Some(r) = &self.renderer { + let lid = |p: [i32; 3]| { + let (prev, cur) = self.chest_open.get(&(p[0], p[1], p[2])).copied().unwrap_or((0.0, 0.0)); + prev + (cur - prev) * alpha as f32 + }; + let scene = horizon_client::block_entity_render::Scene { + camera, + partial: alpha as f32, + game_time: self.world.game_time, + world: &self.world, + sprites: &self.res.atlas.sprites, + nether: self.dim == Dim::Nether, + lid: &lid, + sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { + Some(BlockEntity::Sign(sign)) => Some(sign), + _ => None, + }, + glyph: &|c| self.res.atlas.glyph(c), + }; + self.res.block_entity_render.render(&scene, r.block_entities(), &mut out); + } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self.res.atlas.sprites.get("entity/experience_orb").copied() { let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); @@ -2366,29 +2377,10 @@ impl Game<'_> { let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); + // Particles (ParticleEngine.extract): camera-facing quads. + let world = &self.world; + self.particles.render(camera, self.yaw, self.pitch, alpha as f32, &|b| world.light(b[0], b[1], b[2]), &mut out); let atlas = &self.res.atlas; - for p in &self.particles { - let Some(r) = atlas.sprites.get(&p.sprite).copied() else { continue }; - let a = alpha; - let pos = glam::DVec3::new( - p.previous[0] + (p.position[0] - p.previous[0]) * a, - p.previous[1] + (p.position[1] - p.previous[1]) * a, - p.previous[2] + (p.position[2] - p.previous[2]) * a, - ) - camera; - let c = pos.as_vec3(); - let light = self.world.light(p.position[0].floor() as i32, p.position[1].floor() as i32, p.position[2].floor() as i32); - let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; - // TerrainParticle colour: 0.6 base brightness times the block tint. - let ch = |sft: u32| (((p.tint >> sft) & 255) as f32 * 0.6) as u32; - let color = 0xFF00_0000 | ch(0) << 16 | ch(8) << 8 | ch(16); - let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); - let (u0, v0, u1, v1) = (r.u0 + du * p.uv[0], r.v0 + dv * p.uv[1], r.u0 + du * p.uv[2], r.v0 + dv * p.uv[3]); - let s = p.size; - for (k, uv) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].iter().zip([[u0, v1], [u1, v1], [u1, v0], [u0, v0]]) { - let v = c + right * (k.0 * s) + up * (k.1 * s); - out.push(Vertex { pos: v.to_array(), uv, layer: 0, color, light: packed }); - } - } // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 @@ -2502,6 +2494,15 @@ impl Game<'_> { let mob = &mut self.mobs[index]; let center = [mob.position.x, mob.position.y + mob.kind.height / 2.0, mob.position.z]; if mob.hurt(amount, from, &mut self.world.random) { + // Player.attack: crit emitter and damage indicator hearts. + let (feet, width, height) = ([mob.position.x, mob.position.y, mob.position.z], mob.kind.width, mob.kind.height); + if crit { + self.particles.tracking_emitter(horizon_client::particles::ParticleOptions::simple(horizon_client::particles::ParticleType::Crit), feet, width, height); + } + if amount > 2.0 { + let indicator = horizon_client::particles::ParticleOptions::simple(horizon_client::particles::ParticleType::DamageIndicator); + self.particles.send_particles(&indicator, [feet[0], feet[1] + height * 0.5, feet[2]], [0.1, 0.0, 0.1], 0.2, (amount * 0.5) as u32); + } self.last_hurt_by_player.insert(mob.id); let kind = mob.kind.clone(); let dead = !mob.alive(); @@ -2559,6 +2560,7 @@ impl Game<'_> { } } } + let destroyed_count = destroyed.len(); for b in destroyed { let state = self.world.block(b[0], b[1], b[2]); if self.res.facts.is_air(state) { @@ -2573,6 +2575,8 @@ impl Game<'_> { } self.world.set(b[0], b[1], b[2], self.world.air)?; } + let (world, facts) = (&self.world, &self.res.facts); + self.particles.explosion(center, radius, destroyed_count, &|b| facts.is_air(world.block(b[0], b[1], b[2]))); self.audio.play("minecraft:entity.generic.explode", Some(center), 4.0, (1.0 + (self.world.random.next_float() - self.world.random.next_float()) * 0.2) * 0.7); // Entity damage by distance (exposure approximated as unobstructed). let diameter = f64::from(radius) * 2.0; @@ -2901,7 +2905,8 @@ impl Game<'_> { let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0); let mut quad = |p: [[f32; 3]; 4], shade: f32| { for v in p { - out.push(Vertex { pos: v, uv, layer: 2, color: color(shade), light }); + // Overlay 4: clouds (unlit, faded by the cloud fog end). + out.push(Vertex { pos: v, uv, layer: 4, color: color(shade), light }); } }; quad([[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], 1.0); @@ -4282,6 +4287,7 @@ impl Game<'_> { Vec::new() }; let hand = if title || self.screen == Screen::Inventory { Vec::new() } else { self.hand_geometry(alpha) }; + let screen = if title { Vec::new() } else { self.screen_quads(alpha as f32, size) }; let mut entities = entities; if !title { self.end_geometry(camera, &mut entities); @@ -4315,11 +4321,14 @@ impl Game<'_> { // The camera inside an opaque block sees nothing through it: disable. cave_culling: !self.res.facts.get(self.world.block(block[0], block[1], block[2])).solid_render, water_fog, + fog: Some(self.frame_fog(camera, &sky, biome)), + dark_disc: self.dark_disc(camera), outline, hud: &hud, entities: &entities, celestial: &celestial, hand: &hand, + screen: &screen, game_time: self.world.game_time as f32, ticks: self.ticks, }; @@ -4587,6 +4596,12 @@ impl ApplicationHandler for Game<'_> { } } WindowEvent::MouseInput { .. } if self.title.is_some() => {} + WindowEvent::MouseInput { state, button, .. } if self.sign_edit.is_some() => { + if state == ElementState::Pressed && button == MouseButton::Left { + let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); + self.sign_edit_click(size); + } + } WindowEvent::MouseInput { state, button, .. } => { let pressed = state == ElementState::Pressed; match self.screen { @@ -4658,6 +4673,7 @@ impl ApplicationHandler for Game<'_> { } } } + WindowEvent::KeyboardInput { event, .. } if self.sign_edit.is_some() => self.sign_edit_key(&event), WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Creative && self.creative_screen.tab().search && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => @@ -4882,6 +4898,8 @@ pub fn run() -> Result<()> { let world = World::new(facts.air, 0); let creative = options.creative; let stations = horizon_client::stations::StationData::load(&root, &items); + let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; + let fog = horizon_client::fog::FogRenderer::load(&root, &biomes); let mut resources = Resources { stations, assets, @@ -4894,7 +4912,10 @@ pub fn run() -> Result<()> { icons: HashMap::new(), layer_names, providers: Providers::load(&root), - chest_model: horizon_client::mobs::load_model(&root, "minecraft:chest#main"), + block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load(&root, ®istry_owner.registry)?, + animate, + fog, + screen_fx: Default::default(), nether_environment: Environment::load_dimension(&root, "the_nether", false)?, end_environment: Environment::load_dimension(&root, "the_end", false)?, behaviours: Behaviours::load(registry_owner.registry, &root)?, @@ -4918,6 +4939,7 @@ pub fn run() -> Result<()> { settings.render_distance = d; } let look = options.look; + let particles = horizon_client::particles::ParticleEngine::new(&root, &resources.atlas.sprites); let mut game = Game { res: &mut resources, collision: &collision, @@ -4970,7 +4992,8 @@ pub fn run() -> Result<()> { audio, dropped: Vec::new(), next_entity: 0, - particles: Vec::new(), + particles, + sign_edit: None, spawn_search: 0, mobs: Vec::new(), arrows: Vec::new(), diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 8c2df7b63..93439e2ec 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -81,6 +81,8 @@ impl Game<'_> { match words[0] { "help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::station_control::HELP).collect::>() }))), "help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::blockctl::HELP).collect::>() }))), + "help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::render_control::HELP).collect::>() }))), + "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), "status" => Ok(Some(self.control_status())), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs new file mode 100644 index 000000000..c5a70aea6 --- /dev/null +++ b/crates/horizon-client/src/game/render_control.rs @@ -0,0 +1,119 @@ +//! Control-socket commands for inspecting rendering: place blocks without +//! updates (`setblock`, `fill`) to build test scenes. +use super::Game; +use horizon_client::Result; +use horizon_core::random::RandomSource; +use horizon_world::registry::BlockStateId; +use serde_json::{Value, json}; + +pub const HELP: &[&str] = &[ + "setblock X Y Z STATE set a block state (name[prop=value,...]) without updates", + "fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates", + "particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)", + "signedit X Y Z [front|back] open the sign editor for the sign at X Y Z", +]; + +impl Game<'_> { + /// Parse `name[k=v,...]` into a registry state (defaults for missing properties). + fn parse_state(&self, text: &str) -> Result { + let (name, props) = match text.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let registry = &self.res.assets.registry; + let default = registry + .default_state(&name) + .ok_or_else(|| format!("unknown block {name}"))?; + let mut state = registry + .state(default) + .ok_or("missing default state")? + .clone(); + for pair in props.split(',').filter(|p| !p.is_empty()) { + let (k, v) = pair + .split_once('=') + .ok_or_else(|| format!("bad property {pair}"))?; + if !state.properties.contains_key(k) { + return Err(format!("{name} has no property {k}").into()); + } + state.properties.insert(k.to_owned(), v.to_owned()); + } + Ok(registry.resolve(&state)?) + } + pub(super) fn render_command(&mut self, words: &[&str]) -> Result> { + let int = |i: usize| -> Result { + Ok(words + .get(i) + .ok_or_else(|| format!("missing argument {i}"))? + .parse::()?) + }; + match words[0] { + "setblock" => { + let state = self.parse_state(words.get(4).ok_or("missing state")?)?; + self.world.set(int(1)?, int(2)?, int(3)?, state)?; + Ok(Some(json!({ "ok": true, "state": state.0 }))) + } + "fill" => { + let state = self.parse_state(words.get(7).ok_or("missing state")?)?; + let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]); + let mut count = 0; + for x in a[0].min(b[0])..=a[0].max(b[0]) { + for y in a[1].min(b[1])..=a[1].max(b[1]) { + for z in a[2].min(b[2])..=a[2].max(b[2]) { + self.world.set(x, y, z, state)?; + count += 1; + } + } + } + Ok(Some(json!({ "ok": true, "blocks": count }))) + } + "particle" => { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let ty = ParticleType::from_name(words.get(1).ok_or("missing particle")?) + .ok_or("unknown particle type")?; + let num = |i: usize, default: f64| -> Result { + Ok(words.get(i).map_or(Ok(default), |w| w.parse::())?) + }; + let at = [num(2, 0.0)?, num(3, 0.0)?, num(4, 0.0)?]; + let delta = [num(5, 0.0)?, num(6, 0.0)?, num(7, 0.0)?]; + let count = num(8, 1.0)? as u32; + let options = match ty { + ParticleType::Dust => ParticleOptions::dust([1.0, 0.0, 0.0], 1.0), + ParticleType::Block | ParticleType::FallingDust | ParticleType::DustPillar => { + ParticleOptions::block(ty, "block/stone".into(), 0x808080) + } + _ => ParticleOptions::simple(ty), + }; + // ServerLevel.sendParticles: count 0 uses the delta as velocity. + if count == 0 { + self.particles.create(&options, at, delta); + } + for _ in 0..count { + let r = self.particles.random(); + let p = [ + at[0] + r.next_gaussian() * delta[0], + at[1] + r.next_gaussian() * delta[1], + at[2] + r.next_gaussian() * delta[2], + ]; + self.particles.create(&options, p, [0.0; 3]); + } + Ok(Some(json!({ "ok": true, "live": self.particles.len() }))) + } + "signedit" => { + let key = (int(1)?, int(2)?, int(3)?); + let name = self.res.facts.get(self.world.block(key.0, key.1, key.2)).name.clone(); + let entity = horizon_client::containers::BlockEntity::for_block(&name) + .filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_))) + .ok_or("no sign there")?; + self.world.block_entities.entry(key).or_insert(entity); + self.open_sign_editor(key, words.get(4) != Some(&"back")); + Ok(Some(json!({ "ok": true }))) + } + other => Err(format!("unknown render command {other}").into()), + } + } +} diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs new file mode 100644 index 000000000..f3d2d26f2 --- /dev/null +++ b/crates/horizon-client/src/game/render_tick.rs @@ -0,0 +1,309 @@ +//! Per-tick client visuals: the particle engine, `ClientLevel.animateTick`, +//! campfire smoke and rain splashes (`ClientLevel.tickWeatherEffects`). +use super::{Dim, Game}; +use horizon_client::fog::{FogData, FogInputs, FogType, fog_type, update_rain_fog}; +use horizon_client::screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness}; +use horizon_client::{ + animate_tick::{AnimateContext, animate_tick, campfire_particles}, + biome::Biomes, + blocks::{BlockFacts, Fluid}, + chunk::{HEIGHT, MIN_Y}, + particles::{ParticleLevel, ParticleOptions, ParticleType}, + world::World, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; + +/// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one. +fn motion_blocking(world: &World, facts: &BlockFacts, x: i32, z: i32, from: i32) -> i32 { + let mut y = from.min(MIN_Y + HEIGHT - 1); + while y > MIN_Y { + let f = facts.get(world.block(x, y, z)); + if f.full_collision || f.fluid != Fluid::None || f.name.contains("leaves") { + return y + 1; + } + y -= 1; + } + MIN_Y +} +/// `Biome.getPrecipitationAt` is rain (not snow) at this position. +fn rains_at(world: &World, biomes: &Biomes, x: i32, y: i32, z: i32) -> bool { + let Some(chunk) = world.chunks.get(&(x >> 4, z >> 4)) else { + return false; + }; + let b = biomes.get(chunk.biome(x, y, z)); + if !b.precipitation { + return false; + } + let t = if y > 80 { + b.temperature - (y - 80) as f32 * 0.05 / 40.0 + } else { + b.temperature + }; + t >= 0.15 +} + +impl Game<'_> { + fn forward(&self) -> [f64; 3] { + let (yaw, pitch) = ( + f64::from(self.yaw).to_radians(), + f64::from(self.pitch).to_radians(), + ); + [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ] + } + /// `FogRenderer.setupFog` for the frame's camera. + pub(super) fn frame_fog( + &self, + camera: glam::DVec3, + sky: &horizon_client::environment::Sky, + biome: u16, + ) -> FogData { + let forward = self.forward(); + let at = [camera.x, camera.y, camera.z]; + let fog_type = fog_type(&self.world, &self.res.facts, at, forward); + let water = self.res.biomes.get(biome).water_fog; + let (rain, thunder) = if self.dim == Dim::Overworld { + self.world.weather.levels(self.clock.fraction() as f32) + } else { + (0.0, 0.0) + }; + self.res.fog.setup(&FogInputs { + fog_type, + sky, + water_fog_color: [ + (water >> 16 & 255) as f32 / 255.0, + (water >> 8 & 255) as f32 / 255.0, + (water & 255) as f32 / 255.0, + ], + biome, + render_distance_chunks: self.streaming.radius, + camera_y: camera.y, + min_y: MIN_Y, + flat: false, + forward: forward.map(|c| c as f32), + rain, + thunder, + skybox: self.dim == Dim::Overworld, + blindness: None, + }) + } + /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. + pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool { + camera.y < 63.0 + && fog_type( + &self.world, + &self.res.facts, + [camera.x, camera.y, camera.z], + self.forward(), + ) != FogType::Water + } + /// `ScreenEffectRenderer` + `Hud` camera overlays for this frame. + pub(super) fn screen_quads(&self, partial: f32, size: [u32; 2]) -> Vec { + let Some(p) = self.player.as_ref() else { + return Vec::new(); + }; + let eye = [ + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ]; + // LevelExtractor.getViewBlockingState: 8 points around the eye. + let mut block_overlay = None; + let w = f64::from(p.dimensions.width) * 0.8; + for i in 0..8 { + let t = [ + p.position.x + (f64::from(i & 1) - 0.5) * w, + eye[1] + (f64::from((i >> 1) & 1) - 0.5) * 0.1, + p.position.z + (f64::from((i >> 2) & 1) - 0.5) * w, + ]; + let state = self.world.block( + t[0].floor() as i32, + t[1].floor() as i32, + t[2].floor() as i32, + ); + let f = self.res.facts.get(state); + if f.render_shape != horizon_client::blocks::RenderShape::Invisible + && f.solid_render + && f.full_collision + { + block_overlay = self.particle_sprite(state).map(|(name, _)| name); + break; + } + } + let in_water = + fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water; + let water = in_water.then(|| (self.eye_brightness(eye), self.yaw, self.pitch)); + let camera_overlays = match &self.armor[0] { + Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => { + vec!["misc/pumpkinblur".to_owned()] + } + _ => Vec::new(), + }; + self.res.screen_fx.build(&ScreenInputs { + sprites: &self.res.atlas.sprites, + aspect: size[0] as f32 / size[1].max(1) as f32, + partial, + block_overlay, + water, + on_fire: false, + camera_overlays, + frozen: 0.0, + vignette: true, + border_warning: None, + }) + } + /// `Lightmap.getBrightness(getMaxLocalRawBrightness(eye))`. + fn eye_brightness(&self, eye: [f64; 3]) -> f32 { + let b = [ + eye[0].floor() as i32, + eye[1].floor() as i32, + eye[2].floor() as i32, + ]; + let packed = self.world.light(b[0], b[1], b[2]); + let sky = i32::from(packed >> 4) - self.sky_darken(); + let raw = sky.max(i32::from(packed & 15)).clamp(0, 15) as u8; + lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw) + } + pub(super) fn tick_particles(&mut self) { + let eye = self.eye_position(); + if let Some(e) = eye { + let brightness = self.eye_brightness(e); + let inside_portal = self.portal_ticks > 0; + self.res.screen_fx.tick(brightness, inside_portal); + // LocalPlayer water vision and AtmosphericFogEnvironment rain fog. + let in_water = + fog_type(&self.world, &self.res.facts, e, self.forward()) == FogType::Water; + self.res.fog.state.tick(in_water); + let b = [ + e[0].floor() as i32, + e[1].floor() as i32, + e[2].floor() as i32, + ]; + let rain = if self.dim == Dim::Overworld { + self.world.weather.levels(1.0).0 + } else { + 0.0 + }; + let biome = self + .world + .chunks + .get(&(b[0] >> 4, b[2] >> 4)) + .map_or(0, |c| c.biome(b[0], b[1], b[2])); + let rains = self.res.biomes.get(biome).precipitation; + update_rain_fog( + &mut self.res.fog.state, + rain, + self.world.light(b[0], b[1], b[2]) >> 4, + rains, + 1.0, + ); + } + if let Some(e) = eye { + self.particles.camera = e; + } + let (rain, _) = if self.dim == Dim::Overworld { + self.world.weather.levels(1.0) + } else { + (0.0, 0.0) + }; + let world = &self.world; + let facts = &self.res.facts; + let biomes = &self.res.biomes; + let raining = rain > 0.2; + let raining_at = |p: [i32; 3]| { + raining + && motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1] + && rains_at(world, biomes, p[0], p[1], p[2]) + }; + let ctx = AnimateContext { + world, + facts, + collision: self.collision, + biomes, + registry: self.res.assets.registry, + raining_at: &raining_at, + }; + if let Some(e) = eye { + let block = [ + e[0].floor() as i32, + e[1].floor() as i32, + e[2].floor() as i32, + ]; + animate_tick(&self.res.animate, &mut self.particles, &ctx, block); + if rain > 0.0 { + // ClientLevel.tickWeatherEffects: rain splashes (weather radius 10). + let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); + let radius = 10; + let diameter = 2 * radius + 1; + let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32; + for _ in 0..count { + let x = block[0] + random.next_int_bound(diameter).unwrap_or(0) - radius; + let z = block[2] + random.next_int_bound(diameter).unwrap_or(0) - radius; + let top = motion_blocking(world, facts, x, z, block[1] + 64); + if top <= MIN_Y + || top > block[1] + 10 + || top < block[1] - 10 + || !rains_at(world, biomes, x, top, z) + { + continue; + } + let below = top - 1; + let (bx, bz) = (random.next_double(), random.next_double()); + let state = world.block(x, below, z); + let f = facts.get(state); + let block_top = match self.collision.cached_shapes().cached_shape(state) { + Ok(Some(shape)) if !shape.is_empty() => { + shape.max_at(horizon_core::geometry::Axis::Y, bx, bz) + } + _ => 0.0, + }; + let fluid_top = if f.fluid == Fluid::None { + 0.0 + } else { + f64::from(f.fluid_level) / 9.0 + }; + let smoke = f.fluid == Fluid::Lava + || &*f.name == "minecraft:magma_block" + || (f.name.ends_with("campfire") + && self.res.animate.is_lit_campfire(state.0)); + let ty = if smoke { + ParticleType::Smoke + } else { + ParticleType::Rain + }; + let p = [ + f64::from(x) + bx, + f64::from(below) + block_top.max(fluid_top), + f64::from(z) + bz, + ]; + self.particles + .add(&ParticleOptions::simple(ty), p, [0.0; 3]); + } + } + } + if let Some(r) = &self.renderer { + campfire_particles( + &self.res.animate, + &mut self.particles, + &ctx, + r.block_entities(), + ); + } + let level = ParticleLevel { + world, + facts, + collision: self.collision, + player: self + .player + .as_ref() + .map(|p| ([p.position.x, p.position.y, p.position.z], p.velocity.y)), + }; + self.particles.tick(&level); + for (name, at, volume, pitch) in std::mem::take(&mut self.particles.sounds) { + self.audio.play(name, Some(at), volume, pitch); + } + } +} diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs new file mode 100644 index 000000000..795b29457 --- /dev/null +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -0,0 +1,140 @@ +//! The sign editing screen (`SignEditScreen` / `HangingSignEditScreen`): +//! opened when a sign is placed, four lines limited to the sign's line +//! width, Up/Down/Enter move between lines, Escape or Done closes. +use super::Game; +use horizon_client::{ + containers::BlockEntity, + hud::{HudBatch, rgba}, + signs::{SignData, wood_type}, +}; +use std::time::Instant; +use winit::{ + event::{ElementState, KeyEvent}, + keyboard::{KeyCode, PhysicalKey}, +}; + +pub(super) struct SignEditor { + pub pos: (i32, i32, i32), + pub front: bool, + pub line: usize, + pub opened: Instant, +} + +impl Game<'_> { + fn edited_sign(&mut self) -> Option<&mut SignData> { + let key = self.sign_edit.as_ref()?.pos; + match self.world.block_entities.get_mut(&key) { + Some(BlockEntity::Sign(sign)) => Some(sign), + _ => None, + } + } + /// `SignBlock.openTextEdit` for the front side after placement. + pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { + self.sign_edit = Some(SignEditor { pos, front, line: 0, opened: Instant::now() }); + self.keys.clear(); + self.right = false; + self.capture(false); + } + fn close_sign_editor(&mut self) { + if let Some(edit) = self.sign_edit.take() { + self.world.modified.insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); + } + self.capture(true); + } + pub(super) fn sign_edit_key(&mut self, event: &KeyEvent) { + if event.state != ElementState::Pressed { + return; + } + let Some(edit) = self.sign_edit.as_mut() else { return }; + let front = edit.front; + match event.physical_key { + PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(), + PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3, + PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => edit.line = (edit.line + 1) & 3, + PhysicalKey::Code(KeyCode::Backspace) => { + let line = edit.line; + if let Some(sign) = self.edited_sign() { + let text = if front { &mut sign.front } else { &mut sign.back }; + text.lines[line].pop(); + } + } + _ => { + let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else { return }; + let line = edit.line; + let atlas = &self.res.atlas; + let width = |s: &str| HudBatch::text_width(atlas, s); + let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return }; + if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) { + let max = sign.max_line_width(); + let text = if front { &mut sign.front } else { &mut sign.back }; + for ch in typed.chars().filter(|c| !c.is_control()) { + let mut next = text.lines[line].clone(); + next.push(ch); + // TextFieldHelper filter: font.width(s) <= maxTextLineWidth. + if width(&next) <= max { + text.lines[line] = next; + } + } + } + } + } + } + /// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20). + pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) { + let b = HudBatch::new(size); + let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0); + let (mx, my) = self.cursor; + if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 { + self.close_sign_editor(); + } + } + pub(super) fn draw_sign_editor(&self, batch: &mut HudBatch) { + let Some(edit) = &self.sign_edit else { return }; + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return }; + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); + let title = if sign.hanging { "Edit Hanging Sign Message" } else { "Edit Sign Message" }; + let tw = HudBatch::text_width(atlas, title); + batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); + let name = self.res.facts.get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)).name.clone(); + let wood = wood_type(&name); + let cx = w / 2.0; + let y = if sign.hanging { + // HangingSignEditScreen: 16x16 texture scaled 4.5 at (0, -13). + let s = 4.5; + batch.sprite_scaled(atlas, &format!("gui/hanging_signs/{wood}"), cx - 8.0 * s, 125.0 - 13.0 - 8.0 * s, 16.0 * s, 16.0 * s, u32::MAX); + 125.0 + } else { + // SignEditScreen: 24x26 texture scaled 3.9 at (0, 27); wall signs show 12 rows. + let s = 3.9; + let wall = name.contains("_wall_"); + let rows = if wall { 12.0 } else { 26.0 }; + if let Some(mut r) = atlas.sprites.get(&format!("gui/signs/{wood}")).copied() { + r.v1 = r.v0 + (r.v1 - r.v0) * rows / 26.0; + batch.rect_uv(cx - 12.0 * s, 90.0 + 27.0 - 13.0 * s, 24.0 * s, rows * s, r, u32::MAX); + } + 90.0 + }; + let text = if edit.front { &sign.front } else { &sign.back }; + let color = if text.glowing { text.text_color() } else { text.dark_color() }; + let color = rgba((color >> 16) as u8, (color >> 8) as u8, color as u8, 255); + let line_height = sign.line_height(); + let midpoint = (4.0 * line_height / 2.0).floor(); + let blink = (edit.opened.elapsed().as_millis() / 300) % 2 == 0; + for (i, line) in text.lines.iter().enumerate() { + let lw = HudBatch::text_width(atlas, line); + let x = cx - (lw as i32 / 2) as f32; + let ly = y + i as f32 * line_height - midpoint; + batch.text(atlas, line, x, ly, color, false); + if i == edit.line && blink { + // TextCursorUtils.extractAppendCursor: an underscore after the text. + batch.text(atlas, "_", x + lw, ly, color, false); + } + } + let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0); + batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX); + let tw = HudBatch::text_width(atlas, "Done"); + batch.text(atlas, "Done", bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 685ed4302..89ef75859 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -24,6 +24,8 @@ struct Globals { inverse_view: [[f32; 4]; 4], sunrise: [f32; 4], sun: [f32; 4], + /// x: sky fog end, y: cloud fog end, z: dark disc (camera below the horizon), w: unused. + fog_ends: [f32; 4], } pub type SectionKey = (i32, i32, i32); struct SectionGpu { @@ -54,6 +56,10 @@ pub struct Frame<'a> { /// Environmental fog start/end (Nether 10..96), if any. pub environment_fog: Option<(f32, f32)>, pub water_fog: [f32; 3], + /// `FogRenderer.setupFog` result; replaces the underwater/environment fields when set. + pub fog: Option, + /// Camera eye below the horizon height and not under water (`shouldRenderDarkDisc`). + pub dark_disc: bool, pub outline: Option<[f64; 6]>, pub hud: &'a HudBatch, /// Camera-relative entity geometry textured from the shared atlas. @@ -62,6 +68,8 @@ pub struct Frame<'a> { pub celestial: &'a [Vertex], /// First-person hand and held item, drawn after clearing depth. pub hand: &'a [Vertex], + /// Full-screen camera effects drawn over the world and hand, under the HUD. + pub screen: &'a [crate::screen_effects::ScreenQuad], pub game_time: f32, pub ticks: u64, } @@ -75,10 +83,15 @@ pub struct Renderer { solid: wgpu::RenderPipeline, translucent: wgpu::RenderPipeline, sky: wgpu::RenderPipeline, + dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, entity_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + /// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines. + screen_pipelines: [wgpu::RenderPipeline; 2], + screen_buffer: wgpu::Buffer, + screen_capacity: u64, entity_group: wgpu::BindGroup, entity_buffer: wgpu::Buffer, entity_capacity: u64, @@ -95,6 +108,8 @@ pub struct Renderer { outline: wgpu::Buffer, depth: wgpu::TextureView, sections: HashMap, + /// Block-entity blocks per meshed section (world position, state id). + block_entities: HashMap>, /// VisGraph face connectivity per meshed section (cave culling). visibility: HashMap, reachable: std::collections::HashSet, @@ -360,6 +375,7 @@ impl Renderer { Some(alpha_blend), ); let sky = pipeline("Sky", "vs_sky", "fs_sky", &[], tri, None, false, false, None); + let dark_disc = pipeline("Dark disc", "vs_sky", "fs_dark_disc", &[], tri, None, false, false, Some(alpha_blend)); let lines = pipeline( "Block outline", "vs_line", @@ -650,6 +666,62 @@ impl Renderer { multiview_mask: None, cache: None, }); + let screen_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon screen effects"), + source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), + }); + let screen_attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; + let screen_vertex = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &screen_attributes, + })]; + let vignette_blend = wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrc, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }; + let screen_pipelines = [("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Screen effects"), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &screen_shader, + entry_point: Some("vs_screen"), + compilation_options: Default::default(), + buffers: &screen_vertex, + }, + primitive: wgpu::PrimitiveState { cull_mode: None, ..Default::default() }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &screen_shader, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }); + let screen_capacity = 64; + let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Screen effect vertices"), + size: screen_capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); let celestial_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Celestial vertices"), size: 2048 * 4 * std::mem::size_of::() as u64, @@ -673,10 +745,14 @@ impl Renderer { solid, translucent, sky, + dark_disc, lines, entity_pipeline, celestial_pipeline, celestial_buffer, + screen_pipelines, + screen_buffer, + screen_capacity, entity_group, entity_buffer, entity_capacity, @@ -693,6 +769,7 @@ impl Renderer { outline, depth, sections: HashMap::new(), + block_entities: HashMap::new(), visibility: HashMap::new(), reachable: std::collections::HashSet::new(), reachable_from: None, @@ -772,6 +849,11 @@ impl Renderer { if self.visibility.insert(key, mesh.visibility) != Some(mesh.visibility) { self.visibility_dirty = true; } + if mesh.block_entities.is_empty() { + self.block_entities.remove(&key); + } else { + self.block_entities.insert(key, mesh.block_entities.clone()); + } let solid = (mesh.solid.len() / 4) as u32; let translucent = (mesh.translucent.len() / 4) as u32; if solid + translucent == 0 { @@ -804,7 +886,12 @@ impl Renderer { }, ); } + /// Block-entity blocks of every meshed section (see `SectionMesh::block_entities`). + pub fn block_entities(&self) -> impl Iterator { + self.block_entities.values().flatten() + } pub fn clear_sections(&mut self) { + self.block_entities.clear(); self.sections.clear(); self.visibility.clear(); self.visibility_dirty = true; @@ -844,6 +931,7 @@ impl Renderer { self.visibility_dirty = false; } pub fn remove(&mut self, key: SectionKey) { + self.block_entities.remove(&key); self.visibility.remove(&key); self.visibility_dirty = true; self.sections.remove(&key); @@ -985,7 +1073,9 @@ impl Renderer { let sun_angle = frame.sky.sun_angle.to_radians(); // Celestial bodies rotate around the X axis; angle 0 = noon. let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin()); - let (fog_color, fog) = if frame.underwater { + let (fog_color, fog) = if let Some(f) = frame.fog { + (f.color, [f.environmental_start, f.environmental_end, f.render_distance_start, f.render_distance_end]) + } else if frame.underwater { ( [frame.water_fog[0], frame.water_fog[1], frame.water_fog[2], 1.0], [-8.0, 96.0, -8.0, 96.0], @@ -1015,6 +1105,12 @@ impl Renderer { inverse_view: view.inverse().to_cols_array_2d(), sunrise: frame.sky.sunrise_color, sun: [sun.x, sun.y, sun.z, frame.sky.star_brightness], + fog_ends: [ + frame.fog.map_or(frame.distance.min(512.0), |f| f.sky_end), + frame.fog.map_or(2048.0, |f| f.cloud_end), + if frame.dark_disc { 1.0 } else { 0.0 }, + 0.0, + ], }; self.queue .write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals)); @@ -1187,6 +1283,13 @@ impl Renderer { pass.set_bind_group(0, &self.group, &[]); if !frame.underwater && (frame.skybox || frame.end_sky) { if !frame.title && frame.skybox { + // LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks). + let sky_visible = match frame.fog { + Some(f) => f.sky_end > 2.0, + None => !frame.underwater, + }; + if sky_visible && frame.skybox { + if !frame.title { pass.set_pipeline(&self.sky); pass.draw(0..3, 0..1); } @@ -1198,6 +1301,10 @@ impl Renderer { pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1); pass.set_bind_group(0, &self.group, &[]); } + if !frame.title && frame.dark_disc { + pass.set_pipeline(&self.dark_disc); + pass.draw(0..3, 0..1); + } } if frame.title { visible.clear(); @@ -1269,6 +1376,41 @@ impl Renderer { pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); pass.draw_indexed(0..hand_quads * 6, (entity_quads * 4) as i32, 0..1); } + if !frame.screen.is_empty() { + let vertices: Vec = frame.screen.iter().flat_map(|q| q.vertices).collect(); + if vertices.len() as u64 > self.screen_capacity { + self.screen_capacity = (vertices.len() as u64).next_power_of_two(); + self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Screen effect vertices"), + size: self.screen_capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + self.queue.write_buffer(&self.screen_buffer, 0, bytemuck::cast_slice(&vertices)); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: &view_target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Screen effects"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(0, self.screen_buffer.slice(..)); + for (i, quad) in frame.screen.iter().enumerate() { + let pipeline = match quad.blend { + crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0], + crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1], + }; + pass.set_pipeline(pipeline); + pass.draw_indexed(0..6, (i * 4) as i32, 0..1); + } + } self.hud.draw( &self.device, &self.queue, diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index d4d0db42c..ef8d0e012 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -59,6 +59,10 @@ fn walk(dir: &Path, out: &mut Vec) { } } impl HudAtlas { + /// A font glyph's atlas cell (8x8 GUI pixels) and advance. + pub fn glyph(&self, ch: char) -> Option<(Rect, f32)> { + self.glyphs.get(&ch).map(|g| (g.rect, g.advance)) + } pub fn build(root: &Path) -> Result { let textures = root.join("assets/minecraft/textures"); let mut files = Vec::new(); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ee0ca5821..3fd072579 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -1,10 +1,12 @@ //! Horizon native client: resources, world streaming, rendering and the //! bindings between the validated simulation pieces and the game loop. #![forbid(unsafe_code)] +pub mod animate_tick; pub mod assets; pub mod attribute_updates; pub mod audio; pub mod biome; +pub mod block_entity_render; pub mod blocks; pub mod brewing; pub mod chunk; @@ -23,6 +25,7 @@ pub mod entity_nbt; pub mod environment; pub mod font; pub mod gamerules; +pub mod fog; pub mod gfx; pub mod health; pub mod hud; @@ -47,7 +50,10 @@ pub mod particles; pub mod pose; pub mod projectiles; pub mod save; +pub mod screen_effects; pub mod settings; +pub mod shadows; +pub mod signs; pub mod sprint; pub mod sprites; pub mod stations; diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 28750057a..4480f246e 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -1,17 +1,23 @@ //! Section meshing on worker threads. Faces follow the baked blockstate models -//! with vanilla's neighbour culling; vertex lighting follows -//! `ModelBlockRenderer`'s smooth-lighting blend (four samples per corner, zero -//! samples replaced by the centre) and ambient-occlusion shade brightness. -//! Fluids follow `FluidRenderer` (corner heights, still/flowing sprites). +//! with vanilla's neighbour culling; vertex light and colour follow +//! `ModelBlockRenderer`/`BlockModelLighter` (smooth light, ambient occlusion, +//! cardinal shading, tint sources, block offsets; see `lighting`). Fluids +//! follow `FluidRenderer` (see `fluid`). +mod fluid; +mod lighting; use crate::{ assets::Assets, biome::Biomes, - blocks::{BlockFacts, Fluid, RenderShape}, + blocks::{BlockFacts, RenderShape}, chunk::{Chunk, MIN_Y}, models::catalog::BakedFace, }; -use horizon_core::{geometry::Direction, position::BlockPos}; -use horizon_world::{block_render::FaceVisibility, registry::BlockStateId}; +use horizon_core::{geometry::Direction, position::BlockPos, random::position_seed}; +use horizon_world::{ + block_render::FaceVisibility, + fluid::{FluidKind, FluidState}, + registry::BlockStateId, +}; use std::sync::Arc; #[repr(C)] @@ -32,10 +38,14 @@ pub struct SectionMesh { /// VisGraph: bit `a * 6 + b` is set when faces `a` and `b` (Direction /// order) are connected through non-opaque blocks. pub visibility: u64, + /// Blocks with a block-entity renderer (world position, state id), drawn + /// each frame by `block_entity_render` like vanilla's per-section + /// `SectionCompiler.Results.blockEntities`. + pub block_entities: Vec<([i32; 3], u32)>, } impl Default for SectionMesh { fn default() -> Self { - Self { solid: Vec::new(), translucent: Vec::new(), visibility: ALL_VISIBLE } + Self { solid: Vec::new(), translucent: Vec::new(), visibility: ALL_VISIBLE, block_entities: Vec::new() } } } pub const ALL_VISIBLE: u64 = (1 << 36) - 1; @@ -100,22 +110,57 @@ enum Tint { /// Per-state data the mesher needs on every block, flattened for speed. #[derive(Clone, Copy)] struct Info { + /// `isSolidRender`. solid: bool, - /// `isCollisionShapeFullBlock` drives the 0.2 AO shade brightness. + /// `isCollisionShapeFullBlock`: AO faces flush with a full block sample outside it. full: bool, - /// Side blocks that are transparent let the AO corner sample through. - translucent: bool, + /// `isLightPermeable`: diagonal AO samples are taken through such side blocks. + permeable: bool, + /// `getShadeBrightness` (ambient occlusion contribution). + shade: f32, emission: u8, - fluid: Fluid, - level: u8, + /// `emissiveRendering`: drawn and sampled at full brightness. + emissive: bool, + fluid: FluidState, model: bool, + /// The state has a block entity (candidates for block-entity renderers). + block_entity: bool, tints: [Tint; 2], + tint_count: u8, + /// `OffsetType` as (max horizontal, max vertical): vertical 0 for XZ. + offset: Option<(f32, f32)>, + /// `isSolid()` (legacy), for fluid corner heights. + legacy_solid: bool, + /// `HalfTransparentBlock`/`LeavesBlock`: water sides show the overlay sprite. + overlay: bool, + blocks_flow: bool, + ice: bool, + sturdy: u8, + /// Occlusion face per direction: 0 empty, 1 the full-block singleton, 2 partial. + face: [u8; 6], + /// Height from the bottom over which face `d`, flush with the `d` side, covers + /// the full width (vertical faces: 1 when the whole square is covered). + cover: [f32; 6], +} +/// Derived per-state facts, exposed for the section-mesh parity gate. +#[derive(Clone, Copy, Debug)] +pub struct MeshFacts { + pub shade: f32, + pub emissive: bool, + pub legacy_solid: bool, + pub light_permeable: bool, + pub solid_render: bool, + pub full_collision: bool, + pub emission: u8, + pub overlay: bool, + pub tint_sources: u8, } pub struct MeshTables { info: Vec, pub visibility: FaceVisibility, water_still: u32, water_flow: u32, + water_overlay: u32, lava_still: u32, lava_flow: u32, } @@ -140,75 +185,162 @@ impl MeshTables { .copied() .ok_or_else(|| format!("missing fluid sprite {name}").into()) }; - let info = facts - .states - .iter() - .enumerate() - .map(|(id, s)| { - let props = assets - .registry - .state(BlockStateId(id as u32)) - .map(|s| &s.properties); - let prop = |k: &str| -> u8 { - props - .and_then(|p| p.get(k)) - .and_then(|v| v.parse().ok()) - .unwrap_or(0) - }; - let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name); - let tints = match name { - "large_fern" | "tall_grass" => { - if props.and_then(|p| p.get("half")).map(String::as_str) == Some("upper") { - [Tint::TallGrassUpper; 2] - } else { - [Tint::Grass; 2] - } + let mut covers = std::collections::HashMap::new(); + let mut info = Vec::with_capacity(facts.states.len()); + for (id, s) in facts.states.iter().enumerate() { + let state = assets + .registry + .state(BlockStateId(id as u32)) + .ok_or("missing registry state")?; + let props = &state.properties; + let prop = |k: &str| -> u8 { props.get(k).and_then(|v| v.parse().ok()).unwrap_or(0) }; + let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name); + // BlockColors.createDefault: tint sources by block. + let (tints, tint_count) = match name { + "large_fern" | "tall_grass" => { + if props.get("half").map(String::as_str) == Some("upper") { + ([Tint::TallGrassUpper; 2], 1) + } else { + ([Tint::Grass; 2], 1) } - "fern" | "short_grass" | "potted_fern" | "bush" | "grass_block" - | "sugar_cane" => [Tint::Grass; 2], - "pink_petals" | "wildflowers" => [Tint::None, Tint::Grass], - "spruce_leaves" => [Tint::Constant(0x61_9961); 2], - "birch_leaves" => [Tint::Constant(0x80_A755); 2], - "oak_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" - | "vine" | "mangrove_leaves" => [Tint::Foliage; 2], - "leaf_litter" => [Tint::DryFoliage; 2], - "water_cauldron" | "water" | "bubble_column" => [Tint::Water; 2], - "redstone_wire" => [Tint::Redstone(prop("power")); 2], - "attached_melon_stem" | "attached_pumpkin_stem" => { - [Tint::Constant(0xE0_C71C); 2] - } - "melon_stem" | "pumpkin_stem" => [Tint::Stem(prop("age")); 2], - "lily_pad" => [Tint::Constant(0x20_8030); 2], - _ => [Tint::None; 2], - }; - Info { - solid: s.solid_render, - full: s.full_collision, - translucent: !s.solid_render || s.dampening == 0, - emission: s.emission, - fluid: s.fluid, - level: s.fluid_level, - model: s.render_shape == RenderShape::Model, - tints, } - }) - .collect(); + "fern" | "short_grass" | "potted_fern" | "bush" | "grass_block" | "sugar_cane" => { + ([Tint::Grass; 2], 1) + } + "pink_petals" | "wildflowers" => ([Tint::None, Tint::Grass], 2), + "spruce_leaves" => ([Tint::Constant(0x61_9961); 2], 1), + "birch_leaves" => ([Tint::Constant(0x80_A755); 2], 1), + "oak_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" | "vine" + | "mangrove_leaves" => ([Tint::Foliage; 2], 1), + "leaf_litter" => ([Tint::DryFoliage; 2], 1), + "water_cauldron" => ([Tint::Water; 2], 1), + // Their in-world colour is the particle-only source's -1. + "water" | "bubble_column" => ([Tint::None; 2], 1), + "redstone_wire" => ([Tint::Redstone(prop("power")); 2], 1), + "attached_melon_stem" | "attached_pumpkin_stem" => { + ([Tint::Constant(0xE0_C71C); 2], 1) + } + "melon_stem" | "pumpkin_stem" => ([Tint::Stem(prop("age")); 2], 1), + "lily_pad" => ([Tint::Constant(0x20_8030); 2], 1), + _ => ([Tint::None; 2], 0), + }; + // getShadeBrightness overrides; the default is 0.2 for full collision shapes. + let overrides = [ + "TransparentBlock", + "BarrierBlock", + "LightBlock", + "StructureVoidBlock", + ]; + let shade = if overrides.iter().any(|c| s.has_class(c)) { + 1.0 + } else if s.has_class("SoulSandBlock") || s.has_class("MudBlock") { + 0.2 + } else if s.has_class("SnowLayerBlock") { + if prop("layers") == 8 { 0.2 } else { 1.0 } + } else if s.full_collision { + 0.2 + } else { + 1.0 + }; + let emissive = name == "magma_block" + || (matches!(name, "sculk_sensor" | "calibrated_sculk_sensor") + && props.get("sculk_sensor_phase").map(String::as_str) == Some("active")); + // OffsetType.XZ/XYZ with getMaxHorizontalOffset/getMaxVerticalOffset. + let offset = s.random_offset.then(|| { + let horizontal = if s.has_class("SpeleothemBlock") { + 0.125 + } else { + 0.25 + }; + let vertical = match name { + "small_dripleaf" => 0.1, + "short_grass" | "fern" | "short_dry_grass" | "tall_dry_grass" => 0.2, + _ => 0.0, + }; + (horizontal, vertical) + }); + let mut face = [0u8; 6]; + let mut cover = [0f32; 6]; + for d in Direction::ALL { + let (face_id, shape) = visibility + .occlusion_face(BlockStateId(id as u32), d) + .ok_or("missing occlusion face")?; + face[d as usize] = face_id.min(2) as u8; + cover[d as usize] = *covers + .entry((face_id, d as u8)) + .or_insert_with(|| fluid::coverage(shape, d)); + } + info.push(Info { + solid: s.solid_render, + full: s.full_collision, + permeable: !s.solid_render || s.dampening == 0, + shade, + emission: s.emission, + emissive, + fluid: FluidState::from_block(state)?, + model: s.render_shape == RenderShape::Model, + block_entity: s.block_entity, + tints, + tint_count, + offset, + legacy_solid: s.legacy_solid, + overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"), + blocks_flow: assets.blocks_fluid_flow.contains(&*s.name), + ice: s.has_class("IceBlock"), + sturdy: s.sturdy_full, + face, + cover, + }); + } Ok(Self { info, visibility, water_still: layer("minecraft:block/water_still")?, water_flow: layer("minecraft:block/water_flow")?, + water_overlay: layer("minecraft:block/water_overlay")?, lava_still: layer("minecraft:block/lava_still")?, lava_flow: layer("minecraft:block/lava_flow")?, }) } + pub fn facts(&self, state: BlockStateId) -> Option { + let i = self.info.get(state.0 as usize)?; + Some(MeshFacts { + shade: i.shade, + emissive: i.emissive, + legacy_solid: i.legacy_solid, + light_permeable: i.permeable, + solid_render: i.solid, + full_collision: i.full, + emission: i.emission, + overlay: i.overlay, + tint_sources: i.tint_count, + }) + } + /// `BlockState.getOffset` for blocks with a random model offset. + pub fn offset(&self, state: BlockStateId, x: i32, z: i32) -> Option<[f64; 3]> { + offset(self.info.get(state.0 as usize)?, x, z) + } } -const P: usize = 18; +/// `OffsetType.XZ`/`XYZ`: a per-column jitter from `Mth.getSeed(x, 0, z)`. +fn offset(info: &Info, x: i32, z: i32) -> Option<[f64; 3]> { + let (horizontal, vertical) = info.offset?; + let seed = position_seed(BlockPos::new(x, 0, z)); + let nibble = |shift: u32| ((seed >> shift) & 15) as f32 / 15.0; + let h = f64::from(horizontal); + Some([ + ((f64::from(nibble(0)) - 0.5) * 0.5).clamp(-h, h), + (f64::from(nibble(4)) - 1.0) * f64::from(vertical), + ((f64::from(nibble(8)) - 0.5) * 0.5).clamp(-h, h), + ]) +} +/// Border width: smooth lighting samples up to two blocks out along a face normal. +const B: i32 = 2; +const P: usize = 16 + 2 * B as usize; #[inline] fn pi(x: i32, y: i32, z: i32) -> usize { - ((y + 1) as usize * P + (z + 1) as usize) * P + (x + 1) as usize + ((y + B) as usize * P + (z + B) as usize) * P + (x + B) as usize } -/// Blocks and light of one section plus a one-block border. +/// Blocks and light of one section plus a `B`-block border. struct Padded { blocks: Vec, light: Vec, @@ -218,10 +350,10 @@ impl Padded { let mut blocks = vec![0u16; P * P * P]; let mut light = vec![0u8; P * P * P]; let base_y = MIN_Y + sy * 16; - for y in -1..17 { + for y in -B..16 + B { let wy = base_y + y; - for z in -1..17i32 { - for x in -1..17i32 { + for z in -B..16 + B { + for x in -B..16 + B { let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]; let i = pi(x, y, z); if let Some(c) = chunk { @@ -269,7 +401,7 @@ fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y } } let n = ((2 * R + 1) * (2 * R + 1)) as u32; - (r / n) << 16 | (g / n) << 8 | b / n + (r / n) << 16 | (g / n) << 8 | (b / n) }; for z in 0..16 { for x in 0..16 { @@ -288,23 +420,14 @@ fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y } colors } -fn shade(direction: horizon_assets::model::Direction) -> f32 { - use horizon_assets::model::Direction as D; - match direction { - D::Down => 0.5, - D::Up => 1.0, - D::North | D::South => 0.8, - D::West | D::East => 0.6, - } -} -fn pack_color(rgb: u32, brightness: f32) -> u32 { - let r = ((rgb >> 16 & 255) as f32 * brightness) as u32; - let g = ((rgb >> 8 & 255) as f32 * brightness) as u32; - let b = ((rgb & 255) as f32 * brightness) as u32; +/// Packs 8-bit RGB into the vertex's RGBA8 (red in the low byte), opaque. +fn pack_rgb([r, g, b]: [u32; 3]) -> u32 { 0xFF00_0000 | b << 16 | g << 8 | r } -fn pack_light(sky: f32, block: f32) -> u32 { - (sky * 16.0).clamp(0.0, 255.0) as u32 | ((block * 16.0).clamp(0.0, 255.0) as u32) << 8 +/// Vanilla light coords (block*16 in the low half, sky*16 in the high half) to +/// the vertex layout (sky*16 in bits 0..8, block*16 in bits 8..16). +fn pack_coords(coords: u32) -> u32 { + (coords >> 16 & 0xFF) | (coords & 0xFF) << 8 } pub struct Mesher<'a> { /// CardinalLighting.NETHER: brighter up/down faces. @@ -335,7 +458,10 @@ impl Mesher<'_> { if id == 0 { continue; } - let state = info[id as usize]; + let state = &info[id as usize]; + if state.block_entity { + out.block_entities.push(([center.x * 16 + x, base_y + y, center.z * 16 + z], u32::from(id))); + } if state.solid && Direction::ALL.iter().all(|d| { let [dx, dy, dz] = d.normal(); @@ -344,8 +470,10 @@ impl Mesher<'_> { { continue; } - if state.fluid != Fluid::None { - self.fluid(&pad, &colors, &mut out, x, y, z, id); + if state.fluid.kind() != FluidKind::Empty { + let water = colors.water[(z * 16 + x) as usize]; + let nether = self.nether_shading; + fluid::tesselate(self.tables, nether, &pad, water, &mut out, [x, y, z]); } if !state.model { continue; @@ -355,6 +483,20 @@ impl Mesher<'_> { else { continue; }; + // ModelBlockRenderer: the first part decides smooth lighting + // for all; light-emitting blocks are always lit flat. + let Some((_, first)) = models.first() else { + continue; + }; + let ao = state.emission == 0 && first.ambient_occlusion; + let origin = match offset(state, world.x, world.z) { + Some(o) => [ + x as f32 + o[0] as f32, + y as f32 + o[1] as f32, + z as f32 + o[2] as f32, + ], + None => [x as f32, y as f32, z as f32], + }; let mut visible = [false; 6]; for d in Direction::ALL { let [dx, dy, dz] = d.normal(); @@ -369,20 +511,12 @@ impl Mesher<'_> { ) .unwrap_or(true); } - for (_, model) in models { + for (_, model) in &models { for face in &model.faces { if face.quad.cull.is_some_and(|d| !visible[d as usize]) { continue; } - self.face( - &pad, - &colors, - &mut out, - [x, y, z], - face, - model.ambient_occlusion, - state, - ); + self.face(&pad, &colors, &mut out, [x, y, z], origin, face, ao, state); } } } @@ -390,13 +524,14 @@ impl Mesher<'_> { } out } - fn tint(state: Info, index: i32, colors: &Colors, x: i32, z: i32) -> u32 { - if index < 0 { - return 0xFF_FFFF; + /// `BlockColors` tint source `index`, or `None` for an untinted (-1) layer. + fn tint(state: &Info, index: i32, colors: &Colors, x: i32, z: i32) -> Option { + if index < 0 || index >= i32::from(state.tint_count) { + return None; } let column = (z * 16 + x) as usize; - match state.tints[(index as usize).min(1)] { - Tint::None => 0xFF_FFFF, + Some(match state.tints[(index as usize).min(1)] { + Tint::None => return None, Tint::Grass => colors.grass[column], Tint::TallGrassUpper => colors.tall_upper[column], Tint::Foliage => colors.foliage[column], @@ -406,9 +541,9 @@ impl Mesher<'_> { Tint::Redstone(p) => redstone_color(p), Tint::Stem(age) => { let a = u32::from(age); - (a * 32) << 16 | (255 - a * 8) << 8 | a * 4 + (a * 32) << 16 | (255 - a * 8) << 8 | (a * 4) } - } + }) } #[allow(clippy::too_many_arguments)] fn face( @@ -416,313 +551,51 @@ impl Mesher<'_> { pad: &Padded, colors: &Colors, out: &mut SectionMesh, - [x, y, z]: [i32; 3], + pos: [i32; 3], + origin: [f32; 3], face: &BakedFace, ao: bool, - state: Info, + state: &Info, ) { let q = &face.quad; - let facing = q.facing; - let normal = Direction::ALL[facing as usize].normal(); - let axis = normal.iter().position(|&n| n != 0).unwrap_or(1); - let positive = normal[axis] > 0; - let on_boundary = q.positions.iter().all(|p| { - if positive { - p[axis] >= 1.0 - 1e-4 - } else { - p[axis] <= 1e-4 - } - }); - let base = if on_boundary { - [x + normal[0], y + normal[1], z + normal[2]] + let shade_face = q.shade_direction_override.unwrap_or(q.facing); + let directional = lighting::cardinal(self.nether_shading, shade_face); + // Grey level per vertex before tinting, and vanilla light coords. + let (gray, coords) = if ao { + let info = &self.tables.info; + let (brightness, coords) = + lighting::ambient_occlusion(pad, info, state, pos, &q.positions, q.facing); + let gray = brightness.map(|b| lighting::scale(lighting::gray(b), directional)); + (gray, coords) } else { - [x, y, z] - }; - let tint = Self::tint(state, q.tint_index, colors, x, z); - let mut directional = match q.shade_direction_override { - Some(d) => shade(d), - None => shade(facing), - }; - if self.nether_shading && matches!(q.shade_direction_override.unwrap_or(facing), horizon_assets::model::Direction::Up | horizon_assets::model::Direction::Down) { - directional = 0.9; - } - let info = &self.tables.info; - let light_at = |p: [i32; 3]| -> u32 { - let i = pi(p[0], p[1], p[2]); - let packed = pad.light[i]; - let s = info[pad.blocks[i] as usize]; - let block = (packed & 15).max(s.emission); - u32::from(packed >> 4) << 16 | u32::from(block) - }; - let shade_at = |p: [i32; 3]| -> f32 { - if info[pad.blocks[pi(p[0], p[1], p[2])] as usize].full { - 0.2 - } else { - 1.0 - } - }; - let open_at = |p: [i32; 3]| -> bool { info[pad.blocks[pi(p[0], p[1], p[2])] as usize].translucent }; - // Tangent axes of the face plane. - let (ua, va) = match axis { - 0 => (2, 1), - 1 => (0, 2), - _ => (0, 1), - }; - let center_light = light_at(base); - let center_shade = shade_at(base); - // Corner values for (su, sv) in {0,1}^2 -> (sky, block, ao). - let mut corners = [[0f32; 3]; 4]; - for (ci, corner) in corners.iter_mut().enumerate() { - let su = if ci & 1 == 0 { -1 } else { 1 }; - let sv = if ci & 2 == 0 { -1 } else { 1 }; - let mut p1 = base; - p1[ua] += su; - let mut p2 = base; - p2[va] += sv; - let mut pc = base; - pc[ua] += su; - pc[va] += sv; - let (l1, l2) = (light_at(p1), light_at(p2)); - let (lc, ac) = if open_at(p1) || open_at(p2) { - (light_at(pc), shade_at(pc)) - } else { - (l1, shade_at(p1)) + let coords = match q.cull { + Some(d) => lighting::coords(pad, state, lighting::step(pos, d)), + None => lighting::flat(pad, state, pos, &q.positions, q.facing), }; - // ModelBlockRenderer.blend: zero samples take the centre value. - let fix = |v: u32| if v == 0 { center_light } else { v }; - let sum = fix(l1) + fix(l2) + fix(lc) + center_light; - corner[0] = (sum >> 16) as f32 / 4.0; - corner[1] = (sum & 0xFFFF) as f32 / 4.0; - corner[2] = (shade_at(p1) + shade_at(p2) + ac + center_shade) / 4.0; - } - let flat_sky = (center_light >> 16) as f32; - let flat_block = (center_light & 0xFFFF) as f32; + ([lighting::gray(directional); 4], [coords; 4]) + }; + let tint = Self::tint(state, q.tint_index, colors, pos[0], pos[2]); let target = if face.translucent { &mut out.translucent } else { &mut out.solid }; - for (p, uv) in q.positions.iter().zip(q.uv) { - let (sky, block, occlusion) = if ao { - let u = p[ua].clamp(0.0, 1.0); - let v = p[va].clamp(0.0, 1.0); - let lerp = |k: usize| { - let a = corners[0][k] * (1.0 - u) + corners[1][k] * u; - let b = corners[2][k] * (1.0 - u) + corners[3][k] * u; - a * (1.0 - v) + b * v - }; - (lerp(0), lerp(1), lerp(2)) - } else { - (flat_sky, flat_block, 1.0) + for i in 0..4 { + let g = gray[i] as u32; + let rgb = match tint { + Some(t) => [16, 8, 0].map(|shift| g * (t >> shift & 255) / 255), + None => [g; 3], }; + let p = q.positions[i]; target.push(Vertex { - pos: [p[0] + x as f32, p[1] + y as f32, p[2] + z as f32], - uv, + pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], + uv: q.uv[i], layer: face.layer, - color: pack_color(tint, directional * occlusion), - light: pack_light(sky, block), + color: pack_rgb(rgb), + light: pack_coords(lighting::with_emission(coords[i], q.light_emission)), }); } } - #[allow(clippy::too_many_arguments)] - fn fluid(&self, pad: &Padded, colors: &Colors, out: &mut SectionMesh, x: i32, y: i32, z: i32, id: u16) { - let info = &self.tables.info; - let me = info[id as usize]; - let water = me.fluid == Fluid::Water; - let same = |p: [i32; 3]| info[pad.blocks[pi(p[0], p[1], p[2])] as usize].fluid == me.fluid; - let solid = |p: [i32; 3]| { - let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize]; - s.solid || s.full - }; - let height = |p: [i32; 3]| -> f32 { - let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize]; - if s.fluid == me.fluid { - if same([p[0], p[1] + 1, p[2]]) { - 1.0 - } else { - f32::from(s.level) / 9.0 - } - } else if !(s.solid || s.full) { - 0.0 - } else { - -1.0 - } - }; - let own = height([x, y, z]); - let corner = |a: f32, b: f32, c: [i32; 3]| -> f32 { - if a >= 1.0 || b >= 1.0 { - return 1.0; - } - let mut sum = [0.0f32; 2]; - let mut add = |h: f32| { - if h >= 0.8 { - sum[0] += h * 10.0; - sum[1] += 10.0; - } else if h >= 0.0 { - sum[0] += h; - sum[1] += 1.0; - } - }; - if a > 0.0 || b > 0.0 { - let hc = height(c); - if hc >= 1.0 { - return 1.0; - } - add(hc); - } - add(own); - add(a); - add(b); - sum[0] / sum[1] - }; - let (nw, sw, se, ne) = if own >= 1.0 { - (1.0, 1.0, 1.0, 1.0) - } else { - let n = height([x, y, z - 1]); - let s = height([x, y, z + 1]); - let e = height([x + 1, y, z]); - let w = height([x - 1, y, z]); - ( - corner(n, w, [x - 1, y, z - 1]), - corner(s, w, [x - 1, y, z + 1]), - corner(s, e, [x + 1, y, z + 1]), - corner(n, e, [x + 1, y, z - 1]), - ) - }; - let tint = if water { - colors.water[(z * 16 + x) as usize] - } else { - 0xFF_FFFF - }; - let (still, flow) = if water { - (self.tables.water_still, self.tables.water_flow) - } else { - (self.tables.lava_still, self.tables.lava_flow) - }; - let light = |p: [i32; 3]| { - let packed = pad.light[pi(p[0], p[1], p[2])]; - let emission = if water { 0 } else { 15 }; - pack_light(f32::from(packed >> 4), f32::from((packed & 15).max(emission))) - }; - let target = if water { - &mut out.translucent - } else { - &mut out.solid - }; - let (fx, fy, fz) = (x as f32, y as f32, z as f32); - let quad = |target: &mut Vec, v: [([f32; 3], [f32; 2]); 4], layer: u32, b: f32, l: u32, back: bool| { - for (p, uv) in v { - target.push(Vertex { - pos: p, - uv, - layer, - color: pack_color(tint, b), - light: l, - }); - } - if back { - for i in [0, 3, 2, 1] { - let (p, uv) = v[i]; - target.push(Vertex { - pos: p, - uv, - layer, - color: pack_color(tint, b), - light: l, - }); - } - } - }; - let above_same = same([x, y + 1, z]); - if !above_same && !solid([x, y + 1, z]) || !above_same && own < 1.0 { - let o = 0.001; - let (h0, h1, h2, h3) = (nw - o, sw - o, se - o, ne - o); - // Flow direction from neighbour height differences. - let mut fxv = 0.0f32; - let mut fzv = 0.0f32; - if own < 1.0 && me.level < 8 || own < 0.88 { - for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { - let h = height([x + dx, y, z + dz]); - if h >= 0.0 { - let d = own - h.max(0.0); - fxv += dx as f32 * d; - fzv += dz as f32 * d; - } - } - } - let (layer, uvs) = if fxv.abs() < 1e-4 && fzv.abs() < 1e-4 { - (still, [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]) - } else { - let angle = fzv.atan2(fxv) - std::f32::consts::FRAC_PI_2; - let (s, c) = (angle.sin() * 0.25, angle.cos() * 0.25); - // Flowing sprites are sampled over their top-left quarter-scaled region (getU(0.5+..) of 16 units). - ( - flow, - [ - [0.5 + (-c - s), 0.5 + (-c + s)], - [0.5 + (-c + s), 0.5 + (c + s)], - [0.5 + (c + s), 0.5 + (c - s)], - [0.5 + (c - s), 0.5 + (-c - s)], - ], - ) - }; - quad( - target, - [ - ([fx, fy + h0, fz], uvs[0]), - ([fx, fy + h1, fz + 1.0], uvs[1]), - ([fx + 1.0, fy + h2, fz + 1.0], uvs[2]), - ([fx + 1.0, fy + h3, fz], uvs[3]), - ], - layer, - 1.0, - light([x, y, z]), - water && !solid([x, y + 1, z]), - ); - } - if !same([x, y - 1, z]) && !solid([x, y - 1, z]) { - quad( - target, - [ - ([fx, fy + 0.001, fz], [0.0, 0.0]), - ([fx + 1.0, fy + 0.001, fz], [1.0, 0.0]), - ([fx + 1.0, fy + 0.001, fz + 1.0], [1.0, 1.0]), - ([fx, fy + 0.001, fz + 1.0], [0.0, 1.0]), - ], - still, - 0.5, - light([x, y - 1, z]), - false, - ); - } - let o = 0.001; - for (dx, dz, h0, h1, p0, p1, sh) in [ - (0, -1, nw, ne, [fx, fz + o], [fx + 1.0, fz + o], 0.8), - (0, 1, se, sw, [fx + 1.0, fz + 1.0 - o], [fx, fz + 1.0 - o], 0.8), - (-1, 0, sw, nw, [fx + o, fz + 1.0], [fx + o, fz], 0.6), - (1, 0, ne, se, [fx + 1.0 - o, fz], [fx + 1.0 - o, fz + 1.0], 0.6), - ] { - let n = [x + dx, y, z + dz]; - if same(n) || solid(n) { - continue; - } - let v0 = (1.0 - h0) * 0.5; - let v1 = (1.0 - h1) * 0.5; - quad( - target, - [ - ([p0[0], fy + h0, p0[1]], [0.0, v0]), - ([p1[0], fy + h1, p1[1]], [0.5, v1]), - ([p1[0], fy, p1[1]], [0.5, 0.5]), - ([p0[0], fy, p0[1]], [0.0, 0.5]), - ], - flow, - sh, - light([x, y, z]), - water, - ); - } - } } /// Snapshot of the 3x3 chunk neighbourhood used by a worker job. pub type Region = [[Option>; 3]; 3]; diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs new file mode 100644 index 000000000..e555e12ca --- /dev/null +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -0,0 +1,469 @@ +//! Fluid surfaces following `FluidRenderer.tesselate`: corner heights, face +//! occlusion against neighbour shapes, flow-rotated top UVs, the water overlay +//! beside glass and leaves, back faces, cardinal shading and max(self, above) +//! light. +use super::{Info, MeshTables, Padded, SectionMesh, Vertex, lighting, pack_coords, pack_rgb, pi}; +use horizon_core::{ + geometry::{Axis, Direction, VoxelShape, trig}, + position::BlockPos, +}; +use horizon_world::{ + fluid::{FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, +}; +use std::{convert::Infallible, sync::OnceLock}; + +/// `FluidRenderer.MAX_FLUID_HEIGHT`. +const MAX_HEIGHT: f32 = 0.888_888_9; +const EPSILON: f32 = 0.001; + +/// For the occlusion face toward `direction`: the height from the bottom over +/// which its slice flush with the `direction` side covers the whole width +/// (vertical faces: 1 when the whole square is covered, else 0). This is what +/// `Shapes.blockOccludes` decides for a fluid box of a given height. +pub(super) fn coverage(shape: &VoxelShape, direction: Direction) -> f32 { + let (axis, u, v) = match direction { + Direction::Down | Direction::Up => (Axis::Y, Axis::X, Axis::Z), + Direction::North | Direction::South => (Axis::Z, Axis::X, Axis::Y), + Direction::West | Direction::East => (Axis::X, Axis::Z, Axis::Y), + }; + let positive = matches!( + direction, + Direction::Up | Direction::South | Direction::East + ); + let rects: Vec<[f64; 4]> = shape + .boxes() + .iter() + .filter(|b| { + if positive { + b.max(axis) >= 1.0 - 1e-7 + } else { + b.min(axis) <= 1e-7 + } + }) + .map(|b| [b.min(u), b.max(u), b.min(v), b.max(v)]) + .collect(); + let mut cuts: Vec = rects + .iter() + .flat_map(|r| [r[2], r[3]]) + .filter(|c| (0.0..=1.0).contains(c)) + .chain([0.0, 1.0]) + .collect(); + cuts.sort_by(f64::total_cmp); + cuts.dedup(); + let mut covered = 0.0; + for w in cuts.windows(2) { + let middle = (w[0] + w[1]) / 2.0; + let mut spans: Vec<(f64, f64)> = rects + .iter() + .filter(|r| r[2] <= middle && middle <= r[3]) + .map(|r| (r[0], r[1])) + .collect(); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut reach = 0.0f64; + for (lo, hi) in spans { + if lo > reach + 1e-7 { + break; + } + reach = reach.max(hi); + } + if reach < 1.0 - 1e-7 { + break; + } + covered = w[1]; + } + if matches!(direction, Direction::Down | Direction::Up) && covered < 1.0 { + return 0.0; + } + covered as f32 +} +/// `isFaceOccludedByState` for a fluid box `height` tall against `state`'s +/// face opposite `direction`. +fn occluded_by(direction: Direction, height: f32, state: &Info) -> bool { + let opposite = direction.opposite() as usize; + match state.face[opposite] { + 0 => false, + 1 => direction != Direction::Up || height == 1.0, + _ => match direction { + Direction::Up => { + f64::from(height) >= 1.0 - 1e-7 && state.cover[Direction::Down as usize] >= 1.0 + } + Direction::Down => state.cover[Direction::Up as usize] >= 1.0, + _ => f64::from(height) <= f64::from(state.cover[opposite]) + 1e-7, + }, + } +} +/// `isFaceOccludedBySelf`: the cell's own occlusion face toward `direction`. +fn occluded_by_self(state: &Info, direction: Direction) -> bool { + match state.face[direction as usize] { + 0 => false, + 1 => true, + _ => state.cover[direction as usize] >= 1.0, + } +} +/// `Mth.atan2`: the client's table-driven arctangent. +fn atan2(mut y: f64, mut x: f64) -> f64 { + static TABLES: OnceLock<(Vec, Vec)> = OnceLock::new(); + let (asin, cos) = TABLES.get_or_init(|| { + (0..257) + .map(|i| { + let a = (f64::from(i) / 256.0).asin(); + (a, a.cos()) + }) + .unzip() + }); + let frac_bias = f64::from_bits(4_805_340_802_404_319_232); + let d2 = x * x + y * y; + if d2.is_nan() { + return f64::NAN; + } + let negative_y = y < 0.0; + if negative_y { + y = -y; + } + let negative_x = x < 0.0; + if negative_x { + x = -x; + } + let steep = y > x; + if steep { + std::mem::swap(&mut x, &mut y); + } + // Mth.fastInvSqrt + let half = 0.5 * d2; + let mut r = f64::from_bits((6_910_469_410_427_058_090i64 - (d2.to_bits() as i64 >> 1)) as u64); + r *= 1.5 - half * r * r; + x *= r; + y *= r; + let yp = frac_bias + y; + let index = yp.to_bits() as i32 as usize; + let s_phi = yp - frac_bias; + let sd = y * cos[index] - x * s_phi; + let mut theta = asin[index] + (6.0 + sd * sd) * sd * 0.166_666_666_666_666_66; + if steep { + theta = std::f64::consts::FRAC_PI_2 - theta; + } + if negative_x { + theta = std::f64::consts::PI - theta; + } + if negative_y { + theta = -theta; + } + theta +} +/// The padded section as `FlowingFluid.getFlow` sees it (section-relative positions). +struct FlowView<'a> { + pad: &'a Padded, + info: &'a [Info], +} +impl FlowView<'_> { + fn id(&self, p: BlockPos) -> u16 { + self.pad.blocks[pi(p.x, p.y, p.z)] + } +} +impl FluidFlowWorld for FlowView<'_> { + type Error = Infallible; + type Block = u16; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.info[self.id(p) as usize].fluid) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(self.id(p)) + } + fn blocks_fluid_flow(&self, state: u16) -> bool { + self.info[state as usize].blocks_flow + } + fn is_ice_class(&self, state: u16) -> bool { + self.info[state as usize].ice + } + fn is_face_sturdy( + &mut self, + state: u16, + _: BlockPos, + d: Direction, + ) -> Result { + Ok(self.info[state as usize].sturdy & 1 << d as u8 != 0) + } +} +/// Emits one fluid cell at section-relative `[x, y, z]`. +pub(super) fn tesselate( + tables: &MeshTables, + nether: bool, + pad: &Padded, + water_color: u32, + out: &mut SectionMesh, + [x, y, z]: [i32; 3], +) { + use horizon_assets::model::Direction as D; + let info = &tables.info; + let at = |p: [i32; 3]| &info[pad.blocks[pi(p[0], p[1], p[2])] as usize]; + let me = at([x, y, z]); + let kind = me.fluid.kind(); + let same = |s: &Info| s.fluid.kind().same_family(kind); + let neighbor = |d: Direction| { + let [dx, dy, dz] = d.normal(); + at([x + dx, y + dy, z + dz]) + }; + let (down, up) = (neighbor(Direction::Down), neighbor(Direction::Up)); + let should_render = |d: Direction| !same(neighbor(d)) && !occluded_by_self(me, d); + let render_up = !same(up); + let render_down = + should_render(Direction::Down) && !occluded_by(Direction::Down, MAX_HEIGHT, down); + let sides = [ + Direction::North, + Direction::South, + Direction::West, + Direction::East, + ] + .map(should_render); + if !render_up && !render_down && !sides.iter().any(|&s| s) { + return; + } + let water = matches!(kind, FluidKind::Water | FluidKind::FlowingWater); + let tint = if water { + water_color & 0xFF_FFFF + } else { + 0xFF_FFFF + }; + let color = |by: f32| { + pack_rgb([16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32)) + }; + let height = |p: [i32; 3]| -> f32 { + let s = at(p); + if same(s) { + if same(at([p[0], p[1] + 1, p[2]])) { + 1.0 + } else { + s.fluid.own_height() + } + } else if !s.legacy_solid { + 0.0 + } else { + -1.0 + } + }; + let own = height([x, y, z]); + let (mut ne, mut nw, mut se, mut sw) = (1.0f32, 1.0f32, 1.0f32, 1.0f32); + if own < 1.0 { + let n = height([x, y, z - 1]); + let s = height([x, y, z + 1]); + let e = height([x + 1, y, z]); + let w = height([x - 1, y, z]); + // calculateAverageHeight(self, height2, height1, corner) + let average = |h2: f32, h1: f32, corner: [i32; 3]| -> f32 { + if h1 >= 1.0 || h2 >= 1.0 { + return 1.0; + } + let mut sum = [0f32; 2]; + let mut add = |h: f32| { + if h >= 0.8 { + sum[0] += h * 10.0; + sum[1] += 10.0; + } else if h >= 0.0 { + sum[0] += h; + sum[1] += 1.0; + } + }; + if h1 > 0.0 || h2 > 0.0 { + let hc = height(corner); + if hc >= 1.0 { + return 1.0; + } + add(hc); + } + add(own); + add(h1); + add(h2); + sum[0] / sum[1] + }; + ne = average(n, e, [x + 1, y, z - 1]); + nw = average(n, w, [x - 1, y, z - 1]); + se = average(s, e, [x + 1, y, z + 1]); + sw = average(s, w, [x - 1, y, z + 1]); + } + let light = |p: [i32; 3]| { + let above = [p[0], p[1] + 1, p[2]]; + pack_coords(lighting::max_coords( + lighting::coords(pad, at(p), p), + lighting::coords(pad, at(above), above), + )) + }; + let (still, flow, overlay) = if water { + ( + tables.water_still, + tables.water_flow, + Some(tables.water_overlay), + ) + } else { + (tables.lava_still, tables.lava_flow, None) + }; + let target = if water { + &mut out.translucent + } else { + &mut out.solid + }; + let mut quad = + |v: [([f32; 3], [f32; 2]); 4], layer: u32, color: u32, light: u32, back: bool| { + let vertex = |(pos, uv): ([f32; 3], [f32; 2])| Vertex { + pos, + uv, + layer, + color, + light, + }; + target.extend(v.map(vertex)); + if back { + target.extend([v[0], v[3], v[2], v[1]].map(vertex)); + } + }; + let (fx, fy, fz) = (x as f32, y as f32, z as f32); + let bottom = if render_down { EPSILON } else { 0.0 }; + if render_up && !occluded_by(Direction::Up, nw.min(sw).min(se.min(ne)), up) { + nw -= EPSILON; + sw -= EPSILON; + se -= EPSILON; + ne -= EPSILON; + let flow_vector = flow_at( + &mut FlowView { pad, info }, + me.fluid, + BlockPos::new(x, y, z), + ) + .unwrap_or_else(|e| match e {}); + let (layer, uv) = if flow_vector.x == 0.0 && flow_vector.z == 0.0 { + (still, [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]) + } else { + let angle = + atan2(flow_vector.z, flow_vector.x) as f32 - std::f64::consts::FRAC_PI_2 as f32; + let s = trig::sin(f64::from(angle)) * 0.25; + let c = trig::cos(f64::from(angle)) * 0.25; + ( + flow, + [ + [0.5 + (-c - s), 0.5 + (-c + s)], + [0.5 + (-c + s), 0.5 + (c + s)], + [0.5 + (c + s), 0.5 + (c - s)], + [0.5 + (c - s), 0.5 + (-c - s)], + ], + ) + }; + // FluidState.shouldRenderBackwardUpFace over the 3x3 cells above. + let backward = (-1..=1).any(|ox| { + (-1..=1).any(|oz| { + let s = at([x + ox, y + 1, z + oz]); + !same(s) && !s.solid + }) + }); + quad( + [ + ([fx, fy + nw, fz], uv[0]), + ([fx, fy + sw, fz + 1.0], uv[1]), + ([fx + 1.0, fy + se, fz + 1.0], uv[2]), + ([fx + 1.0, fy + ne, fz], uv[3]), + ], + layer, + color(lighting::cardinal(nether, D::Up)), + light([x, y, z]), + backward, + ); + } + if render_down { + let y0 = fy + bottom; + quad( + [ + ([fx, y0, fz], [0.0, 0.0]), + ([fx + 1.0, y0, fz], [1.0, 0.0]), + ([fx + 1.0, y0, fz + 1.0], [1.0, 1.0]), + ([fx, y0, fz + 1.0], [0.0, 1.0]), + ], + still, + color(lighting::cardinal(nether, D::Down)), + light([x, y - 1, z]), + false, + ); + } + let side_light = light([x, y, z]); + let up_shade = lighting::cardinal(nether, D::Up); + for (i, d) in [ + Direction::North, + Direction::South, + Direction::West, + Direction::East, + ] + .into_iter() + .enumerate() + { + let (h0, h1, [x0, z0], [x1, z1]) = match d { + Direction::North => (nw, ne, [fx, fz + EPSILON], [fx + 1.0, fz + EPSILON]), + Direction::South => ( + se, + sw, + [fx + 1.0, fz + 1.0 - EPSILON], + [fx, fz + 1.0 - EPSILON], + ), + Direction::West => (sw, nw, [fx + EPSILON, fz + 1.0], [fx + EPSILON, fz]), + _ => ( + ne, + se, + [fx + 1.0 - EPSILON, fz], + [fx + 1.0 - EPSILON, fz + 1.0], + ), + }; + let face_state = neighbor(d); + if !sides[i] || occluded_by(d, h0.max(h1), face_state) { + continue; + } + let (layer, is_overlay) = match overlay { + Some(layer) if face_state.overlay => (layer, true), + _ => (flow, false), + }; + let side = if matches!(d, Direction::North | Direction::South) { + lighting::cardinal(nether, D::North) + } else { + lighting::cardinal(nether, D::West) + }; + let (v0, v1) = ((1.0 - h0) * 0.5, (1.0 - h1) * 0.5); + quad( + [ + ([x0, fy + h0, z0], [0.0, v0]), + ([x1, fy + h1, z1], [0.5, v1]), + ([x1, fy + bottom, z1], [0.5, 0.5]), + ([x0, fy + bottom, z0], [0.0, 0.5]), + ], + layer, + color(up_shade * side), + side_light, + !is_overlay, + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn atan2_follows_the_table_approximation() { + for (y, x) in [ + (1.0, 0.0), + (0.0, 1.0), + (-0.5, 0.25), + (0.3, -0.9), + (-1.0, -1.0), + (0.1, 0.7), + ] { + let exact = f64::atan2(y, x); + assert!((atan2(y, x) - exact).abs() < 1e-6, "{y} {x}"); + } + assert!(atan2(f64::NAN, 1.0).is_nan()); + } + #[test] + fn coverage_of_full_and_partial_faces() { + assert_eq!(coverage(&VoxelShape::block(), Direction::North), 1.0); + assert_eq!(coverage(&VoxelShape::block(), Direction::Up), 1.0); + assert_eq!(coverage(&VoxelShape::empty(), Direction::East), 0.0); + // A bottom slab covers the lower half of each side and the whole floor. + let slab = VoxelShape::from_cube([1, 2, 1], &[true, false]).unwrap(); + assert_eq!(coverage(&slab, Direction::South), 0.5); + assert_eq!(coverage(&slab, Direction::Down), 1.0); + assert_eq!(coverage(&slab, Direction::Up), 0.0); + } +} diff --git a/crates/horizon-client/src/mesher/lighting.rs b/crates/horizon-client/src/mesher/lighting.rs new file mode 100644 index 000000000..38b79ce54 --- /dev/null +++ b/crates/horizon-client/src/mesher/lighting.rs @@ -0,0 +1,420 @@ +//! Vertex light and colour of model quads, following `BlockModelLighter` +//! (smooth light and ambient occlusion, including the partial-face weights) +//! and `ModelBlockRenderer`'s integer colour arithmetic (`ARGB.gray`, +//! `scaleRGB`, `multiply`). +use super::{Info, Padded, pi}; +use horizon_assets::model::Direction as D; + +/// `LightCoordsUtil.FULL_BRIGHT`. +pub(super) const FULL_BRIGHT: u32 = 0x00F0_00F0; + +/// `CardinalLighting.DEFAULT`/`NETHER` by face. +pub(super) fn cardinal(nether: bool, face: D) -> f32 { + match face { + D::Down if nether => 0.9, + D::Up if nether => 0.9, + D::Down => 0.5, + D::Up => 1.0, + D::North | D::South => 0.8, + D::West | D::East => 0.6, + } +} +fn normal(face: D) -> [i32; 3] { + match face { + D::Down => [0, -1, 0], + D::Up => [0, 1, 0], + D::North => [0, 0, -1], + D::South => [0, 0, 1], + D::West => [-1, 0, 0], + D::East => [1, 0, 0], + } +} +pub(super) fn step(p: [i32; 3], face: D) -> [i32; 3] { + let n = normal(face); + [p[0] + n[0], p[1] + n[1], p[2] + n[2]] +} +fn state<'a>(pad: &Padded, info: &'a [Info], p: [i32; 3]) -> &'a Info { + &info[pad.blocks[pi(p[0], p[1], p[2])] as usize] +} +/// `LightCoordsUtil.getLightCoords`: light at `p` as seen through `state` +/// (block level << 4 | sky level << 20). +pub(super) fn coords(pad: &Padded, state: &Info, p: [i32; 3]) -> u32 { + if state.emissive { + return FULL_BRIGHT; + } + let packed = pad.light[pi(p[0], p[1], p[2])]; + let block = u32::from((packed & 15).max(state.emission)); + block << 4 | u32::from(packed >> 4) << 20 +} +/// `LightCoordsUtil.max`. +pub(super) fn max_coords(a: u32, b: u32) -> u32 { + (a >> 4 & 15).max(b >> 4 & 15) << 4 | (a >> 20 & 15).max(b >> 20 & 15) << 20 +} +/// `LightCoordsUtil.lightCoordsWithEmission` (a quad's element light emission). +pub(super) fn with_emission(coords: u32, emission: u8) -> u32 { + if emission == 0 { + return coords; + } + let e = u32::from(emission); + (coords >> 4 & 15).max(e) << 4 | (coords >> 20 & 15).max(e) << 20 +} +/// `LightCoordsUtil.smoothBlend`: zero samples take the centre; samples without +/// sky light borrow the centre's sky. +pub(super) fn smooth_blend(mut a: u32, mut b: u32, mut c: u32, center: u32) -> u32 { + if center >> 20 & 15 > 2 || center >> 4 & 15 > 2 { + for n in [&mut a, &mut b, &mut c] { + if *n == 0 { + *n = center; + } else if *n >> 20 & 15 == 0 { + *n |= center & 0x00FF_0000; + } + } + } + (a + b + c + center) >> 2 & 0x00FF_00FF +} +/// `LightCoordsUtil.smoothWeightedBlend` (Java float sums and int narrowing). +fn weighted_blend(c: [u32; 4], w: [f32; 4]) -> u32 { + let channel = |shift: u32| { + let v = |i: usize| (c[i] >> shift & 0xFF) as f32 * w[i]; + (v(0) + v(1) + v(2) + v(3)) as i32 as u32 & 0xFF + }; + channel(0) | channel(16) << 16 +} +/// `ARGB.gray` channel: `Mth.floor(brightness * 255)`. +pub(super) fn gray(brightness: f32) -> i32 { + (brightness * 255.0).floor() as i32 +} +/// One channel of `ARGB.scaleRGB(color, float)`. +pub(super) fn scale(channel: i32, by: f32) -> i32 { + ((channel as f32 * by) as i32).clamp(0, 255) +} +// SizeInfo indices into the face shape. +const DOWN: u8 = 0; +const UP: u8 = 1; +const NORTH: u8 = 2; +const SOUTH: u8 = 3; +const WEST: u8 = 4; +const EAST: u8 = 5; +const FLIP_DOWN: u8 = 6; +const FLIP_UP: u8 = 7; +const FLIP_NORTH: u8 = 8; +const FLIP_SOUTH: u8 = 9; +const FLIP_WEST: u8 = 10; +const FLIP_EAST: u8 = 11; +struct Adjacency { + corners: [D; 4], + /// Face-shape factor pairs for each vertex's four corner weights. + weights: [[u8; 8]; 4], + /// Output vertex for each of the four computed corners. + remap: [usize; 4], +} +const fn adjacency(face: D) -> Adjacency { + use D::*; + match face { + Down => Adjacency { + corners: [West, East, North, South], + weights: [ + [ + FLIP_WEST, SOUTH, FLIP_WEST, FLIP_SOUTH, WEST, FLIP_SOUTH, WEST, SOUTH, + ], + [ + FLIP_WEST, NORTH, FLIP_WEST, FLIP_NORTH, WEST, FLIP_NORTH, WEST, NORTH, + ], + [ + FLIP_EAST, NORTH, FLIP_EAST, FLIP_NORTH, EAST, FLIP_NORTH, EAST, NORTH, + ], + [ + FLIP_EAST, SOUTH, FLIP_EAST, FLIP_SOUTH, EAST, FLIP_SOUTH, EAST, SOUTH, + ], + ], + remap: [0, 1, 2, 3], + }, + Up => Adjacency { + corners: [East, West, North, South], + weights: [ + [ + EAST, SOUTH, EAST, FLIP_SOUTH, FLIP_EAST, FLIP_SOUTH, FLIP_EAST, SOUTH, + ], + [ + EAST, NORTH, EAST, FLIP_NORTH, FLIP_EAST, FLIP_NORTH, FLIP_EAST, NORTH, + ], + [ + WEST, NORTH, WEST, FLIP_NORTH, FLIP_WEST, FLIP_NORTH, FLIP_WEST, NORTH, + ], + [ + WEST, SOUTH, WEST, FLIP_SOUTH, FLIP_WEST, FLIP_SOUTH, FLIP_WEST, SOUTH, + ], + ], + remap: [2, 3, 0, 1], + }, + North => Adjacency { + corners: [Up, Down, East, West], + weights: [ + [UP, FLIP_WEST, UP, WEST, FLIP_UP, WEST, FLIP_UP, FLIP_WEST], + [UP, FLIP_EAST, UP, EAST, FLIP_UP, EAST, FLIP_UP, FLIP_EAST], + [ + DOWN, FLIP_EAST, DOWN, EAST, FLIP_DOWN, EAST, FLIP_DOWN, FLIP_EAST, + ], + [ + DOWN, FLIP_WEST, DOWN, WEST, FLIP_DOWN, WEST, FLIP_DOWN, FLIP_WEST, + ], + ], + remap: [3, 0, 1, 2], + }, + South => Adjacency { + corners: [West, East, Down, Up], + weights: [ + [UP, FLIP_WEST, FLIP_UP, FLIP_WEST, FLIP_UP, WEST, UP, WEST], + [ + DOWN, FLIP_WEST, FLIP_DOWN, FLIP_WEST, FLIP_DOWN, WEST, DOWN, WEST, + ], + [ + DOWN, FLIP_EAST, FLIP_DOWN, FLIP_EAST, FLIP_DOWN, EAST, DOWN, EAST, + ], + [UP, FLIP_EAST, FLIP_UP, FLIP_EAST, FLIP_UP, EAST, UP, EAST], + ], + remap: [0, 1, 2, 3], + }, + West => Adjacency { + corners: [Up, Down, North, South], + weights: [ + [ + UP, SOUTH, UP, FLIP_SOUTH, FLIP_UP, FLIP_SOUTH, FLIP_UP, SOUTH, + ], + [ + UP, NORTH, UP, FLIP_NORTH, FLIP_UP, FLIP_NORTH, FLIP_UP, NORTH, + ], + [ + DOWN, NORTH, DOWN, FLIP_NORTH, FLIP_DOWN, FLIP_NORTH, FLIP_DOWN, NORTH, + ], + [ + DOWN, SOUTH, DOWN, FLIP_SOUTH, FLIP_DOWN, FLIP_SOUTH, FLIP_DOWN, SOUTH, + ], + ], + remap: [3, 0, 1, 2], + }, + East => Adjacency { + corners: [Down, Up, North, South], + weights: [ + [ + FLIP_DOWN, SOUTH, FLIP_DOWN, FLIP_SOUTH, DOWN, FLIP_SOUTH, DOWN, SOUTH, + ], + [ + FLIP_DOWN, NORTH, FLIP_DOWN, FLIP_NORTH, DOWN, FLIP_NORTH, DOWN, NORTH, + ], + [ + FLIP_UP, NORTH, FLIP_UP, FLIP_NORTH, UP, FLIP_NORTH, UP, NORTH, + ], + [ + FLIP_UP, SOUTH, FLIP_UP, FLIP_SOUTH, UP, FLIP_SOUTH, UP, SOUTH, + ], + ], + remap: [1, 2, 3, 0], + }, + } +} +const ADJACENCY: [Adjacency; 6] = [ + adjacency(D::Down), + adjacency(D::Up), + adjacency(D::North), + adjacency(D::South), + adjacency(D::West), + adjacency(D::East), +]; +/// `prepareQuadShape`: the quad's bounds, whether it is partial (smaller than +/// the block face) and whether it is cubic (flush with the block boundary, or +/// flat on a full collision shape). +struct Shape { + bounds: [f32; 12], + partial: bool, + cubic: bool, +} +fn shape(positions: &[[f32; 3]; 4], face: D, full: bool) -> Shape { + let (mut min, mut max) = ([32f32; 3], [-32f32; 3]); + for p in positions { + for i in 0..3 { + min[i] = min[i].min(p[i]); + max[i] = max[i].max(p[i]); + } + } + let mut bounds = [0f32; 12]; + for (index, value) in [ + (WEST, min[0]), + (EAST, max[0]), + (DOWN, min[1]), + (UP, max[1]), + (NORTH, min[2]), + (SOUTH, max[2]), + ] { + bounds[index as usize] = value; + bounds[index as usize + 6] = 1.0 - value; + } + let (lo, hi) = (1.0e-4f32, 0.9999f32); + let partial = |a: usize, b: usize| min[a] >= lo || min[b] >= lo || max[a] <= hi || max[b] <= hi; + let (partial, cubic) = match face { + D::Down => (partial(0, 2), min[1] == max[1] && (min[1] < lo || full)), + D::Up => (partial(0, 2), min[1] == max[1] && (max[1] > hi || full)), + D::North => (partial(0, 1), min[2] == max[2] && (min[2] < lo || full)), + D::South => (partial(0, 1), min[2] == max[2] && (max[2] > hi || full)), + D::West => (partial(1, 2), min[0] == max[0] && (min[0] < lo || full)), + D::East => (partial(1, 2), min[0] == max[0] && (max[0] > hi || full)), + }; + Shape { + bounds, + partial, + cubic, + } +} +/// `prepareQuadFlat` for a quad without a cull face: light from the +/// neighbour when the quad is flush with the face, else from the block itself. +pub(super) fn flat( + pad: &Padded, + own: &Info, + pos: [i32; 3], + positions: &[[f32; 3]; 4], + face: D, +) -> u32 { + let cubic = shape(positions, face, own.full).cubic; + coords(pad, own, if cubic { step(pos, face) } else { pos }) +} +/// `prepareQuadAmbientOcclusion`: per-vertex AO brightness (before `ARGB.gray`) +/// and smooth light coords, by vertex index. +pub(super) fn ambient_occlusion( + pad: &Padded, + info: &[Info], + own: &Info, + pos: [i32; 3], + positions: &[[f32; 3]; 4], + face: D, +) -> ([f32; 4], [u32; 4]) { + let shape = shape(positions, face, own.full); + let base = if shape.cubic { step(pos, face) } else { pos }; + let adjacency = &ADJACENCY[face as usize]; + let corner = |i: usize| step(base, adjacency.corners[i]); + let sample = |p: [i32; 3]| { + let s = state(pad, info, p); + (coords(pad, s, p), s.shade) + }; + let (light0, shade0) = sample(corner(0)); + let (light1, shade1) = sample(corner(1)); + let (light2, shade2) = sample(corner(2)); + let (light3, shade3) = sample(corner(3)); + let permeable = |i: usize| state(pad, info, step(corner(i), face)).permeable; + let (p0, p1, p2, p3) = (permeable(0), permeable(1), permeable(2), permeable(3)); + let diagonal = |a: usize, b: usize, open: bool| { + if open { + sample(step(corner(a), adjacency.corners[b])) + } else { + (light0, shade0) + } + }; + let (light02, shade02) = diagonal(0, 2, p2 || p0); + let (light03, shade03) = diagonal(0, 3, p3 || p0); + let (light12, shade12) = diagonal(1, 2, p2 || p1); + let (light13, shade13) = diagonal(1, 3, p3 || p1); + let next = step(pos, face); + let next_state = state(pad, info, next); + let light_center = if shape.cubic || !next_state.solid { + coords(pad, next_state, next) + } else { + coords(pad, own, pos) + }; + let shade_center = if shape.cubic { + state(pad, info, base).shade + } else { + own.shade + }; + let ao = [ + (shade3 + shade0 + shade03 + shade_center) * 0.25, + (shade2 + shade0 + shade02 + shade_center) * 0.25, + (shade2 + shade1 + shade12 + shade_center) * 0.25, + (shade3 + shade1 + shade13 + shade_center) * 0.25, + ]; + let blended = [ + smooth_blend(light3, light0, light03, light_center), + smooth_blend(light2, light0, light02, light_center), + smooth_blend(light2, light1, light12, light_center), + smooth_blend(light3, light1, light13, light_center), + ]; + let mut brightness = [0f32; 4]; + let mut light = [0u32; 4]; + for (k, &vertex) in adjacency.remap.iter().enumerate() { + if shape.partial { + let f = |i: usize| shape.bounds[adjacency.weights[k][i] as usize]; + let w = [f(0) * f(1), f(2) * f(3), f(4) * f(5), f(6) * f(7)]; + brightness[vertex] = + (ao[0] * w[0] + ao[1] * w[1] + ao[2] * w[2] + ao[3] * w[3]).clamp(0.0, 1.0); + light[vertex] = weighted_blend(blended, w); + } else { + brightness[vertex] = ao[k]; + light[vertex] = blended[k]; + } + } + (brightness, light) +} + +#[cfg(test)] +mod tests { + use super::*; + const fn packed(block: u32, sky: u32) -> u32 { + block << 4 | sky << 20 + } + #[test] + fn smooth_blend_replaces_dark_samples_with_the_centre() { + let center = packed(2, 15); + // A zero sample takes the centre; a sky-less sample borrows its sky. + let blended = smooth_blend(0, packed(8, 0), packed(4, 15), center); + assert_eq!(blended & 0xFF, (32 + 128 + 64 + 32) / 4); + assert_eq!(blended >> 16 & 0xFF, 240); + // A dark centre leaves samples untouched. + assert_eq!( + smooth_blend(0, 0, packed(15, 15), packed(1, 1)) & 0xFF, + (240 + 16) / 4 + ); + } + #[test] + fn weighted_blend_narrows_like_java_int_casts() { + let c = [packed(15, 15); 4]; + assert_eq!(weighted_blend(c, [0.25; 4]), packed(15, 15)); + // Negative weights (geometry past the block) wrap through the 0xFF mask. + assert_eq!( + weighted_blend([packed(1, 0); 4], [-0.25; 4]) & 0xFF, + (-16i32 as u32) & 0xFF + ); + } + #[test] + fn colour_arithmetic_matches_argb_helpers() { + assert_eq!(gray(1.0), 255); + assert_eq!(gray(0.8), 204); + assert_eq!(scale(255, 0.5), 127); + assert_eq!(scale(gray(0.6), 0.8), 122); + assert_eq!(cardinal(true, D::Down), 0.9); + assert_eq!(cardinal(false, D::Down), 0.5); + } + #[test] + fn emission_raises_both_channels_and_drops_fractions() { + assert_eq!(with_emission(0x0087_0013, 0), 0x0087_0013); + assert_eq!(with_emission(0x0087_0013, 3), packed(3, 8)); + assert_eq!(max_coords(packed(3, 9), packed(7, 2)), packed(7, 9)); + } + #[test] + fn quad_shape_classifies_partial_and_cubic_faces() { + let full_top = [ + [0.0, 1.0, 0.0], + [0.0, 1.0, 1.0], + [1.0, 1.0, 1.0], + [1.0, 1.0, 0.0], + ]; + let s = shape(&full_top, D::Up, false); + assert!(s.cubic && !s.partial); + let slab_top = full_top.map(|[x, _, z]| [x, 0.5, z]); + let s = shape(&slab_top, D::Up, false); + assert!(!s.cubic && !s.partial); + assert!(shape(&slab_top, D::Up, true).cubic); + let small = slab_top.map(|[x, y, z]| [x * 0.5, y, z]); + let s = shape(&small, D::Up, false); + assert!(s.partial); + assert_eq!(s.bounds[EAST as usize], 0.5); + assert_eq!(s.bounds[FLIP_EAST as usize], 0.5); + } +} diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index fa223905b..61db847a0 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -3,7 +3,7 @@ //! resource-pack reloads remain separate work. use crate::{Result, sprites::Sprites}; use horizon_assets::{ - bake::{BlockModelTransform, ModelQuad, bake_model_transformed}, + bake::{BlockModelTransform, ModelQuad, bake_block_model}, blockstate::{ BlockStateDefinition, Variant, VariantSet, bind::{Properties, PropertySchema, PropertyValues, SelectedModels}, @@ -176,7 +176,7 @@ impl StateModels { for (name, turns, lock) in variants { let model = library.resolve(&name)?; let faces: Vec = - bake_model_transformed(&model, BlockModelTransform::new(turns, lock))? + bake_block_model(&model, BlockModelTransform::new(turns, lock))? .into_iter() .map(|quad| { let layer = sprites.insert(root, &quad.material.sprite)?; diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index aaac918f3..34b2fcf3b 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1,87 +1,2243 @@ -//! Block particles (`TerrainParticle`): destroy bursts and mining crumbs that -//! sample a random quarter of the block's texture, fall with gravity and -//! expire after a randomized lifetime. -use crate::world::World; -use horizon_core::random::{LegacyRandom, RandomSource}; +//! Client particle engine (`ParticleEngine`, `Particle`, `SingleQuadParticle`) +//! and the vanilla particle types players see most: block crumbs, smoke, +//! flames, lava pops, drips, splashes and rain, bubbles, portal and enchant +//! glyphs, crits, hearts, villager particles, explosions, campfire smoke, +//! notes, redstone dust, totem, end rod, biome ash and spores, falling leaves, +//! spells and dragon breath. Constructors, ticks, sizes, colours and light +//! follow the vanilla classes; sprite sets come from `particles/*.json`. +use crate::{ + blocks::{BlockFacts, Fluid}, + collisions::SceneCollisions, + hud::Rect, + mesher::Vertex, + world::World, +}; +use glam::{DVec3, Quat, Vec3 as FVec3}; +use horizon_core::{ + geometry::{Aabb, Axis, Vec3}, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::block_collision::BlockCollisionRegistry; +use std::{collections::HashMap, path::Path}; + +macro_rules! particle_types { + ($($variant:ident = $name:literal),* $(,)?) => { + /// Vanilla particle types with a client implementation here. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum ParticleType { $($variant),* } + impl ParticleType { + pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; + /// Registry path (`minecraft:`), also the sprite-set file name. + pub fn name(self) -> &'static str { + match self { $(ParticleType::$variant => $name),* } + } + pub fn from_name(name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + match name { $($name => Some(ParticleType::$variant),)* _ => None } + } + } + }; +} +particle_types! { + Block = "block", + BlockCrumble = "block_crumble", + DustPillar = "dust_pillar", + FallingDust = "falling_dust", + Smoke = "smoke", + LargeSmoke = "large_smoke", + WhiteSmoke = "white_smoke", + Flame = "flame", + SoulFireFlame = "soul_fire_flame", + CopperFireFlame = "copper_fire_flame", + SmallFlame = "small_flame", + Lava = "lava", + DrippingWater = "dripping_water", + FallingWater = "falling_water", + DrippingLava = "dripping_lava", + FallingLava = "falling_lava", + LandingLava = "landing_lava", + DrippingHoney = "dripping_honey", + FallingHoney = "falling_honey", + LandingHoney = "landing_honey", + FallingNectar = "falling_nectar", + FallingSporeBlossom = "falling_spore_blossom", + SporeBlossomAir = "spore_blossom_air", + DrippingObsidianTear = "dripping_obsidian_tear", + FallingObsidianTear = "falling_obsidian_tear", + LandingObsidianTear = "landing_obsidian_tear", + DrippingDripstoneWater = "dripping_dripstone_water", + FallingDripstoneWater = "falling_dripstone_water", + DrippingDripstoneLava = "dripping_dripstone_lava", + FallingDripstoneLava = "falling_dripstone_lava", + Splash = "splash", + Rain = "rain", + Bubble = "bubble", + BubblePop = "bubble_pop", + BubbleColumnUp = "bubble_column_up", + CurrentDown = "current_down", + Underwater = "underwater", + Portal = "portal", + ReversePortal = "reverse_portal", + Enchant = "enchant", + Nautilus = "nautilus", + VaultConnection = "vault_connection", + Crit = "crit", + EnchantedHit = "enchanted_hit", + DamageIndicator = "damage_indicator", + Heart = "heart", + AngryVillager = "angry_villager", + HappyVillager = "happy_villager", + Composter = "composter", + Mycelium = "mycelium", + Dolphin = "dolphin", + EggCrack = "egg_crack", + Poof = "poof", + Explosion = "explosion", + ExplosionEmitter = "explosion_emitter", + CampfireCosySmoke = "campfire_cosy_smoke", + CampfireSignalSmoke = "campfire_signal_smoke", + Note = "note", + Dust = "dust", + TotemOfUndying = "totem_of_undying", + EndRod = "end_rod", + Ash = "ash", + WhiteAsh = "white_ash", + CrimsonSpore = "crimson_spore", + WarpedSpore = "warped_spore", + CherryLeaves = "cherry_leaves", + PaleOakLeaves = "pale_oak_leaves", + TintedLeaves = "tinted_leaves", + Effect = "effect", + InstantEffect = "instant_effect", + EntityEffect = "entity_effect", + Witch = "witch", + Infested = "infested", + Cloud = "cloud", + Sneeze = "sneeze", + Snowflake = "snowflake", + Soul = "soul", + SculkSoul = "sculk_soul", + DragonBreath = "dragon_breath", +} +impl ParticleType { + /// `ParticleType.getOverrideLimiter`: spawned regardless of distance. + pub fn override_limiter(self) -> bool { + matches!( + self, + Self::DamageIndicator | Self::ExplosionEmitter | Self::Explosion | Self::Poof + ) + } +} + +/// `ParticleOptions` with the parameters of the option classes used here. +#[derive(Clone, Debug)] +pub struct ParticleOptions { + pub ty: ParticleType, + /// `BlockParticleOption`: the block's particle sprite and terrain tint. + pub block: Option<(String, u32)>, + /// RGB(A) for dust, spells, entity effects and tinted leaves. + pub color: [f32; 4], + /// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`. + pub scale: f32, +} +impl ParticleOptions { + pub fn simple(ty: ParticleType) -> Self { + Self { + ty, + block: None, + color: [1.0; 4], + scale: 1.0, + } + } + pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self { + Self { + block: Some((sprite, tint)), + ..Self::simple(ty) + } + } + /// `DustParticleOptions(color, scale)`. + pub fn dust(rgb: [f32; 3], scale: f32) -> Self { + Self { + color: [rgb[0], rgb[1], rgb[2], 1.0], + scale: scale.clamp(0.01, 4.0), + ..Self::simple(ParticleType::Dust) + } + } + pub fn colored(ty: ParticleType, rgba: [f32; 4]) -> Self { + Self { + color: rgba, + ..Self::simple(ty) + } + } +} +#[derive(Clone, Debug)] +enum Sprite { + /// Index into the engine's sprite table. + Index(u32), + /// An atlas sprite by name (block textures for terrain particles). + Named(String), +} +#[derive(Clone, Copy, Debug, PartialEq)] +enum Size { + Fixed, + /// `quadSize * clamp((age + a) / lifetime * 32, 0, 1)`. + GrowIn, + Flame, + Lava, + Portal, + ReversePortal, +} +#[derive(Clone, Copy, Debug, PartialEq)] +enum Light { + World, + FullBright, + /// `LightCoordsUtil.withBlock(light, 15)`. + Block15, + /// `addSmoothBlockEmission` with the age fraction. + AgeEmission, + /// `addSmoothBlockEmission` with the age fraction to the fourth power. + AgeEmission4, +} +#[derive(Clone, Copy, Debug, PartialEq)] +enum Behaviour { + Base, + /// BaseAshSmokeParticle / Explode / Dust / Snowflake / EmissiveRising: base tick, sprite from age. + Animated, + Lava, + Drip { + fluid: Fluid, + stage: DripStage, + next: Option, + sound: Option<&'static str>, + }, + WaterDrop, + Bubble, + BubblePop, + BubbleColumnUp, + CurrentDown { + angle: f32, + }, + SuspendedTown, + Portal { + start: [f64; 3], + }, + ReversePortal, + FlyTowards { + start: [f64; 3], + alpha: [f32; 4], + }, + Crit, + HugeExplosion, + ExplosionSeed, + Campfire, + SimpleAnimated { + fade: Option<[f32; 3]>, + }, + Spell { + original_alpha: f32, + }, + Cloud, + Snowflake, + Leaves { + rot_speed: f32, + spin: f32, + wind: f32, + swirl: bool, + flow: bool, + flow_scale: [f64; 2], + swirl_period: f64, + }, + FallingDust { + rot_speed: f32, + }, + DragonBreath { + hit_ground: bool, + }, +} +#[derive(Clone, Copy, Debug, PartialEq)] +enum DripStage { + Hang, + CoolingHang, + Fall, + FallAndLand, + Land, +} + +/// One live particle (`Particle` + `SingleQuadParticle` state). #[derive(Clone, Debug)] pub struct Particle { + pub ty: ParticleType, pub position: [f64; 3], pub previous: [f64; 3], pub velocity: [f64; 3], - pub age: u32, - pub lifetime: u32, - pub size: f32, - pub sprite: String, - /// Sub-rectangle of the sprite in 0..1 (u0, v0, u1, v1). - pub uv: [f32; 4], - pub tint: u32, - pub gravity: f64, + bb: Aabb, + bb_width: f32, + bb_height: f32, pub on_ground: bool, + has_physics: bool, + /// Particles that move without collision (`move` overridden). + free_move: bool, + stopped_by_collision: bool, + removed: bool, + pub age: i32, + pub lifetime: i32, + gravity: f32, + friction: f32, + speed_up_when_y_blocked: bool, + /// `quadSize`. + pub size: f32, + pub rgba: [f32; 4], + roll: f32, + o_roll: f32, + sprite: Sprite, + /// Age-driven sprite set (`setSpriteFromAge`). + set: Option, + /// Sub-rectangle of the sprite (u0, v0, u1, v1) in 0..1. + pub uv: [f32; 4], + size_curve: Size, + light: Light, + behaviour: Behaviour, + no_render: bool, + /// Ticked once when created (`CritParticle` constructor). + pre_tick: bool, +} +fn aabb_at(p: [f64; 3], w: f32, h: f32) -> Aabb { + let w = f64::from(w) / 2.0; + Aabb::new( + Vec3::new(p[0] - w, p[1], p[2] - w), + Vec3::new(p[0] + w, p[1] + f64::from(h), p[2] + w), + ) } impl Particle { - /// TerrainParticle(level, x, y, z, xa, ya, za, state) - pub fn terrain(random: &mut LegacyRandom, position: [f64; 3], velocity: [f64; 3], sprite: String, tint: u32) -> Self { - // Particle constructor: random jitter of velocity, normalized speed. - let mut v = [ - velocity[0] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4, - velocity[1] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4, - velocity[2] + f64::from(random.next_float() * 2.0 - 1.0) * 0.4, - ]; - let speed = f64::from(random.next_float() + random.next_float() + 1.0) * 0.15; - let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-9); - for (i, c) in v.iter_mut().enumerate() { - *c = *c / length * speed * 0.4; - if i == 1 { - *c += 0.1; - } - } - let u = random.next_float() * 3.0 / 4.0; - let w = random.next_float() * 3.0 / 4.0; - // SingleQuadParticle quadSize: 0.1 * (rand*0.5+0.5) * 2, halved for terrain. - let size = 0.1 * (random.next_float() * 0.5 + 0.5); - let lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as u32; + /// `Particle(level, x, y, z)` + `SingleQuadParticle` (no initial velocity). + fn at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self { + let mut particle = Self::blank(ty, p); + particle.lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as i32; + particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0; + particle + } + fn blank(ty: ParticleType, p: [f64; 3]) -> Self { Self { - position, - previous: position, - velocity: v, - age: 0, - lifetime, - size, - sprite, - uv: [u, w, u + 0.25, w + 0.25], - tint, - gravity: 1.0, + ty, + position: p, + previous: p, + velocity: [0.0; 3], + bb: aabb_at(p, 0.2, 0.2), + bb_width: 0.2, + bb_height: 0.2, on_ground: false, + has_physics: true, + free_move: false, + stopped_by_collision: false, + removed: false, + age: 0, + lifetime: 0, + gravity: 0.0, + friction: 0.98, + speed_up_when_y_blocked: false, + size: 0.0, + rgba: [1.0; 4], + roll: 0.0, + o_roll: 0.0, + sprite: Sprite::Index(u32::MAX), + set: None, + uv: [0.0, 0.0, 1.0, 1.0], + size_curve: Size::Fixed, + light: Light::World, + behaviour: Behaviour::Base, + no_render: false, + pre_tick: false, } } - pub fn tick(&mut self, world: &World, solid: impl Fn(u16) -> bool) -> bool { - self.previous = self.position; - self.age += 1; - if self.age >= self.lifetime { - return false; - } - self.velocity[1] -= 0.04 * self.gravity; - for axis in 0..3 { - let mut next = self.position; - next[axis] += self.velocity[axis]; - let block = world.block(next[0].floor() as i32, next[1].floor() as i32, next[2].floor() as i32); - if solid(block.0 as u16) { - if axis == 1 && self.velocity[1] < 0.0 { - self.on_ground = true; - } - self.velocity[axis] = 0.0; - } else { - self.position = next; + /// `Particle(level, x, y, z, xa, ya, za)`: jittered, normalized initial velocity. + fn moving(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3], v: [f64; 3]) -> Self { + let lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as i32; + let mut d = [ + v[0] + f64::from((random.next_float() * 2.0 - 1.0) * 0.4), + v[1] + f64::from((random.next_float() * 2.0 - 1.0) * 0.4), + v[2] + f64::from((random.next_float() * 2.0 - 1.0) * 0.4), + ]; + let speed = f64::from((random.next_float() + random.next_float() + 1.0) * 0.15); + let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + for (i, c) in d.iter_mut().enumerate() { + *c = *c / length * speed * f64::from(0.4f32); + if i == 1 { + *c += f64::from(0.1f32); } } + let mut particle = Self::blank(ty, p); + particle.lifetime = lifetime; + particle.velocity = d; + particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0; + particle + } + /// `TerrainParticle(level, x, y, z, xa, ya, za, state)`: a crumb from a + /// random quarter of the block's particle sprite, tinted like the block. + pub fn terrain( + random: &mut LegacyRandom, + position: [f64; 3], + velocity: [f64; 3], + sprite: String, + tint: u32, + ) -> Self { + let mut p = Self::moving(random, ParticleType::Block, position, velocity); + p.sprite = Sprite::Named(sprite); + p.gravity = 1.0; + let c = |shift: u32| 0.6 * ((tint >> shift) & 255) as f32 / 255.0; + p.rgba = [c(16), c(8), c(0), 1.0]; + p.size /= 2.0; + let uo = random.next_float() * 3.0; + let vo = random.next_float() * 3.0; + // getU0 = (uo + 1) / 4, getU1 = uo / 4: the crumb is mirrored horizontally. + p.uv = [(uo + 1.0) / 4.0, vo / 4.0, uo / 4.0, (vo + 1.0) / 4.0]; + p + } + /// `Particle.setPower`. + pub fn set_power(&mut self, power: f32) { + let power = f64::from(power); + self.velocity[0] *= power; + self.velocity[1] = (self.velocity[1] - f64::from(0.1f32)) * power + f64::from(0.1f32); + self.velocity[2] *= power; + } + /// `SingleQuadParticle.scale` (quad and collision box). + pub fn scale(&mut self, scale: f32) { + self.size *= scale; + self.set_size(0.2 * scale, 0.2 * scale); + } + fn set_size(&mut self, w: f32, h: f32) { + if w != self.bb_width || h != self.bb_height { + self.bb_width = w; + self.bb_height = h; + let min = self.bb.min_position(); + let max = self.bb.max_position(); + let nx = (min.x + max.x - f64::from(w)) / 2.0; + let nz = (min.z + max.z - f64::from(w)) / 2.0; + self.bb = Aabb::new( + Vec3::new(nx, min.y, nz), + Vec3::new(nx + f64::from(w), min.y + f64::from(h), nz + f64::from(w)), + ); + } + } + fn set_pos(&mut self, p: [f64; 3]) { + self.position = p; + self.bb = aabb_at(p, self.bb_width, self.bb_height); + } + fn set_location_from_bb(&mut self) { + let (min, max) = (self.bb.min_position(), self.bb.max_position()); + self.position = [(min.x + max.x) / 2.0, min.y, (min.z + max.z) / 2.0]; + } + fn set_color(&mut self, r: f32, g: f32, b: f32) { + self.rgba[0] = r; + self.rgba[1] = g; + self.rgba[2] = b; + } + pub fn is_alive(&self) -> bool { + !self.removed + } + /// `Particle.move` with `Entity.collideBoundingBox` against block collision shapes. + fn move_by(&mut self, level: &ParticleLevel, d: [f64; 3]) { + if self.free_move { + self.bb = self.bb.move_by(Vec3::new(d[0], d[1], d[2])); + self.set_location_from_bb(); + return; + } + if self.stopped_by_collision { + return; + } + let original = d; + let mut moved = d; + let length2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if self.has_physics && length2 != 0.0 && length2 < 100.0 * 100.0 { + moved = level.collide(self.bb, d); + } + if moved != [0.0; 3] { + self.bb = self.bb.move_by(Vec3::new(moved[0], moved[1], moved[2])); + self.set_location_from_bb(); + } + if original[1].abs() >= f64::from(1.0e-5f32) && moved[1].abs() < f64::from(1.0e-5f32) { + self.stopped_by_collision = true; + } + self.on_ground = original[1] != moved[1] && original[1] < 0.0; + if original[0] != moved[0] { + self.velocity[0] = 0.0; + } + if original[2] != moved[2] { + self.velocity[2] = 0.0; + } + } + /// `Particle.tick`. + fn base_tick(&mut self, level: &ParticleLevel) { + self.previous = self.position; + let age = self.age; + self.age += 1; + if age >= self.lifetime { + self.removed = true; + return; + } + self.velocity[1] -= 0.04 * f64::from(self.gravity); + self.move_by(level, self.velocity); + if self.speed_up_when_y_blocked && self.position[1] == self.previous[1] { + self.velocity[0] *= 1.1; + self.velocity[2] *= 1.1; + } + let f = f64::from(self.friction); for c in &mut self.velocity { - *c *= 0.98; + *c *= f; } if self.on_ground { - self.velocity[0] *= 0.7; - self.velocity[2] *= 0.7; + self.velocity[0] *= f64::from(0.7f32); + self.velocity[2] *= f64::from(0.7f32); + } + } + fn quad_size(&self, a: f32) -> f32 { + let t = (self.age as f32 + a) / self.lifetime as f32; + match self.size_curve { + Size::Fixed => self.size, + Size::GrowIn => self.size * (t * 32.0).clamp(0.0, 1.0), + Size::Flame => self.size * (1.0 - t * t * 0.5), + Size::Lava => self.size * (1.0 - t * t), + Size::Portal => { + let s = 1.0 - t; + self.size * (1.0 - s * s) + } + Size::ReversePortal => { + self.size * (1.0 - (self.age as f32 + a) / (self.lifetime as f32 * 1.5)) + } } - true + } +} + +/// World access for particle physics. +pub struct ParticleLevel<'a> { + pub world: &'a World, + pub facts: &'a BlockFacts, + pub collision: &'a BlockCollisionRegistry<'a>, + /// Local player feet position and vertical velocity (`PlayerCloudParticle`). + pub player: Option<([f64; 3], f64)>, +} +impl ParticleLevel<'_> { + fn collide(&self, bb: Aabb, d: [f64; 3]) -> [f64; 3] { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + match scene.resolve(bb, Vec3::new(d[0], d[1], d[2]), 0.0, false) { + Ok(v) => [v.x, v.y, v.z], + Err(_) => d, + } + } + fn block_at(p: [f64; 3]) -> [i32; 3] { + [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ] + } + /// The fluid at a block and `FluidState.getHeight`. + fn fluid(&self, b: [i32; 3]) -> (Fluid, f64) { + let s = self.facts.get(self.world.block(b[0], b[1], b[2])); + if s.fluid == Fluid::None { + return (Fluid::None, 0.0); + } + let above = self.facts.get(self.world.block(b[0], b[1] + 1, b[2])); + let height = if above.fluid == s.fluid { + 1.0 + } else { + f64::from(s.fluid_level) / 9.0 + }; + (s.fluid, height) + } + /// `getCollisionShape(...).max(Y, x, z)` for cached shapes. + fn collision_top(&self, b: [i32; 3], fx: f64, fz: f64) -> f64 { + let state = self.world.block(b[0], b[1], b[2]); + match self.collision.cached_shapes().cached_shape(state) { + Ok(Some(shape)) if !shape.is_empty() => shape.max_at(Axis::Y, fx, fz), + Ok(Some(_)) => 0.0, + _ => { + if self.facts.get(state).full_collision { + 1.0 + } else { + 0.0 + } + } + } + } +} + +/// `ParticleEngine` plus the sprite sets of `ParticleResources`. +pub struct ParticleEngine { + particles: Vec, + pending: Vec, + random: LegacyRandom, + names: Vec, + rects: Vec>, + atlas: HashMap, + sets: HashMap, + set_sprites: Vec>, + /// `TrackingEmitter`s: particle type, entity feet position, width, height, ticks left. + emitters: Vec<(ParticleOptions, [f64; 3], f64, f64, u32)>, + /// Camera position for the 32-block spawn limiter. + pub camera: [f64; 3], + /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). + pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>, +} +/// `ParticleGroup.MAX_PARTICLES` (per render group; one group here). +const MAX_PARTICLES: usize = 16384; +impl ParticleEngine { + pub fn new(root: &Path, atlas: &HashMap) -> Self { + let mut engine = Self { + particles: Vec::new(), + pending: Vec::new(), + random: LegacyRandom::new(0x7061_7274), + names: Vec::new(), + rects: Vec::new(), + atlas: atlas.clone(), + sets: HashMap::new(), + set_sprites: Vec::new(), + emitters: Vec::new(), + camera: [0.0; 3], + sounds: Vec::new(), + }; + let dir = root.join("assets/minecraft/particles"); + for &ty in ParticleType::ALL { + let Ok(bytes) = std::fs::read(dir.join(format!("{}.json", ty.name()))) else { + continue; + }; + let Ok(json) = serde_json::from_slice::(&bytes) else { + continue; + }; + let sprites: Vec = json["textures"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|t| t.as_str()) + .map(|t| { + engine + .intern(&format!("particle/{}", t.trim_start_matches("minecraft:"))) + }) + .collect() + }) + .unwrap_or_default(); + if !sprites.is_empty() { + engine.sets.insert(ty, engine.set_sprites.len() as u32); + engine.set_sprites.push(sprites); + } + } + engine + } + fn intern(&mut self, name: &str) -> u32 { + if let Some(i) = self.names.iter().position(|n| n == name) { + return i as u32; + } + self.names.push(name.to_owned()); + self.rects.push(self.atlas.get(name).copied()); + (self.names.len() - 1) as u32 + } + pub fn len(&self) -> usize { + self.particles.len() + } + pub fn is_empty(&self) -> bool { + self.particles.is_empty() + } + pub fn clear(&mut self) { + self.emitters.clear(); + self.particles.clear(); + self.pending.clear(); + } + /// `ParticleEngine.add` (via `particlesToAdd`, applied on the next tick). + pub fn push(&mut self, particle: Particle) { + self.pending.push(particle); + } + /// Random generator shared by particle constructors and spawners. + pub fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + /// `ClientLevel.addParticle`: dropped beyond 32 blocks of the camera unless + /// the type overrides the limiter. + pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { + let c = self.camera; + let d2 = (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2); + if !options.ty.override_limiter() && d2 > 1024.0 { + return; + } + self.create(options, p, v); + } + /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the + /// explosion particle (emitter for radius >= 2) and up to 512 poof/smoke + /// particles thrown from air inside the radius. + pub fn explosion( + &mut self, + center: [f64; 3], + radius: f32, + block_count: usize, + is_air: &dyn Fn([i32; 3]) -> bool, + ) { + let ty = if radius < 2.0 { + ParticleType::Explosion + } else { + ParticleType::ExplosionEmitter + }; + self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + for _ in 0..block_count.min(512) { + let r = &mut self.random; + let d = Vec3::new( + f64::from(r.next_float() * 2.0 - 1.0), + f64::from(r.next_float() * 2.0 - 1.0), + f64::from(r.next_float() * 2.0 - 1.0), + ) + .normalize(); + let distance = r.next_float().cbrt() * radius; + let local = [ + d.x * f64::from(distance), + d.y * f64::from(distance), + d.z * f64::from(distance), + ]; + let at = [ + center[0] + local[0], + center[1] + local[1], + center[2] + local[2], + ]; + if !is_air(ParticleLevel::block_at(at)) { + continue; + } + let speed = 0.5 / (distance / radius + 0.1) * r.next_float() * r.next_float() + 0.3; + // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES: poof (scaling 0.5) or smoke, equally weighted. + let (ty, scaling) = if r.next_int_bound(2).unwrap_or(0) == 0 { + (ParticleType::Poof, 0.5) + } else { + (ParticleType::Smoke, 1.0) + }; + let p = [ + center[0] + local[0] * scaling, + center[1] + local[1] * scaling, + center[2] + local[2] * scaling, + ]; + let v = [ + d.x * f64::from(speed), + d.y * f64::from(speed), + d.z * f64::from(speed), + ]; + self.add(&ParticleOptions::simple(ty), p, v); + } + } + /// `ParticleEngine.createTrackingEmitter` (crits): 16 tries per tick for + /// three ticks inside a quarter of the entity's box, ticked once at creation. + pub fn tracking_emitter( + &mut self, + options: ParticleOptions, + feet: [f64; 3], + width: f64, + height: f64, + ) { + self.emit(&options, feet, width, height); + self.emitters.push((options, feet, width, height, 2)); + } + fn emit(&mut self, options: &ParticleOptions, feet: [f64; 3], width: f64, height: f64) { + for _ in 0..16 { + let r = &mut self.random; + let xa = f64::from(r.next_float() * 2.0 - 1.0); + let ya = f64::from(r.next_float() * 2.0 - 1.0); + let za = f64::from(r.next_float() * 2.0 - 1.0); + if xa * xa + ya * ya + za * za <= 1.0 { + let p = [ + feet[0] + width * xa / 4.0, + feet[1] + height * (0.5 + ya / 4.0), + feet[2] + width * za / 4.0, + ]; + self.add(options, p, [xa, ya + 0.2, za]); + } + } + } + /// `ClientPacketListener.handleParticleEvent` for `ServerLevel.sendParticles`. + pub fn send_particles( + &mut self, + options: &ParticleOptions, + at: [f64; 3], + spread: [f64; 3], + speed: f64, + count: u32, + ) { + if count == 0 { + let v = [speed * spread[0], speed * spread[1], speed * spread[2]]; + self.add(options, at, v); + return; + } + for _ in 0..count { + let r = &mut self.random; + let p = [ + at[0] + r.next_gaussian() * spread[0], + at[1] + r.next_gaussian() * spread[1], + at[2] + r.next_gaussian() * spread[2], + ]; + let v = [ + r.next_gaussian() * speed, + r.next_gaussian() * speed, + r.next_gaussian() * speed, + ]; + self.add(options, p, v); + } + } + /// `ParticleEngine.createParticle`: always spawned. + pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { + if let Some(particle) = self.make(options, p, v) { + self.pending.push(particle); + } + } + /// `SpriteSet.get(random)`. + fn sprite_from_set(&mut self, ty: ParticleType) -> Sprite { + match self.sets.get(&ty) { + Some(&set) => { + let sprites = &self.set_sprites[set as usize]; + Sprite::Index( + sprites[self + .random + .next_int_bound(sprites.len() as i32) + .unwrap_or(0) as usize], + ) + } + None => Sprite::Index(u32::MAX), + } + } + fn set_of(&self, ty: ParticleType) -> Option { + self.sets.get(&ty).copied() + } + fn first(&self, ty: ParticleType) -> Sprite { + self.set_of(ty).map_or(Sprite::Index(u32::MAX), |s| { + Sprite::Index(self.set_sprites[s as usize][0]) + }) + } + /// `SingleQuadParticle.setSpriteFromAge`. + fn sprite_from_age(&self, p: &mut Particle) { + if p.removed { + return; + } + if let Some(set) = p.set { + let sprites = &self.set_sprites[set as usize]; + let lifetime = p.lifetime.max(1); + let index = (p.age.max(0) as i64 * (sprites.len() as i64 - 1) / i64::from(lifetime)) + .clamp(0, sprites.len() as i64 - 1); + p.sprite = Sprite::Index(sprites[index as usize]); + } + } + #[allow(clippy::too_many_lines)] + fn make(&mut self, o: &ParticleOptions, p: [f64; 3], v: [f64; 3]) -> Option { + use ParticleType as T; + let ty = o.ty; + let set = self.set_of(ty); + let r = &mut self.random; + let mut particle = match ty { + T::Block | T::BlockCrumble | T::DustPillar => { + let (sprite, tint) = o.block.clone()?; + let mut q = Particle::terrain(r, p, v, sprite, tint); + q.ty = ty; + if ty == T::BlockCrumble { + q.velocity = [0.0; 3]; + q.lifetime = r.next_int_bound(10).unwrap_or(0) + 1; + } else if ty == T::DustPillar { + q.velocity = [ + r.next_gaussian() / 30.0, + v[1] + r.next_gaussian() / 2.0, + r.next_gaussian() / 30.0, + ]; + q.lifetime = r.next_int_bound(20).unwrap_or(0) + 20; + } + return Some(q); + } + T::FallingDust => { + let (_, tint) = o.block.clone()?; + let mut q = Particle::at(r, ty, p); + q.set_color( + ((tint >> 16) & 255) as f32 / 255.0, + ((tint >> 8) & 255) as f32 / 255.0, + (tint & 255) as f32 / 255.0, + ); + q.size *= 0.674_999_95; + let base = (32.0 / (r.next_float() * 0.8 + 0.2)) as i32; + q.lifetime = ((base as f32 * 0.9) as i32).max(1); + let rot_speed = (r.next_float() - 0.5) * 0.1; + q.roll = r.next_float() * std::f32::consts::TAU; + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::FallingDust { rot_speed }; + q.set = set; + q + } + T::Smoke | T::LargeSmoke | T::WhiteSmoke | T::Ash | T::WhiteAsh => { + // BaseAshSmokeParticle(dir, xa, scale, colorRandom, maxLifetime, gravity, hasPhysics). + let (dir, scale, color_random, max_lifetime, gravity, physics, vel) = match ty { + T::Smoke | T::WhiteSmoke => ([0.1, 0.1, 0.1], 1.0, 0.3, 8, -0.1, true, v), + T::LargeSmoke => ([0.1, 0.1, 0.1], 2.5, 0.3, 8, -0.1, true, v), + T::Ash => ([0.1, -0.1, 0.1], 1.0, 0.5, 20, 0.1, false, [0.0; 3]), + _ => { + let xa = f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1; + let ya = f64::from(r.next_float()) + * -0.5 + * f64::from(r.next_float()) + * 0.1 + * 5.0; + let za = f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1; + ([0.1, -0.1, 0.1], 1.0, 0.0, 20, 0.0125, false, [xa, ya, za]) + } + }; + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.friction = 0.96; + q.gravity = gravity; + q.speed_up_when_y_blocked = true; + for i in 0..3 { + q.velocity[i] = q.velocity[i] * f64::from(dir[i] as f32) + vel[i]; + } + let col = r.next_float() * color_random; + q.set_color(col, col, col); + q.size *= 0.75 * scale; + q.lifetime = ((f64::from(max_lifetime) / (f64::from(r.next_float()) * 0.8 + 0.2) + * f64::from(scale)) as i32) + .max(1); + q.has_physics = physics; + if ty == T::WhiteSmoke { + q.set_color(0.729_411_8, 0.694_117_67, 0.760_784_3); + } else if ty == T::WhiteAsh { + q.set_color(186.0 / 255.0, 177.0 / 255.0, 194.0 / 255.0); + } + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::Animated; + q.set = set; + q + } + T::Flame + | T::SoulFireFlame + | T::CopperFireFlame + | T::SmallFlame + | T::Soul + | T::SculkSoul => { + // RisingParticle. + let mut q = Particle::moving(r, ty, p, v); + q.friction = 0.96; + for i in 0..3 { + q.velocity[i] = q.velocity[i] * f64::from(0.01f32) + v[i]; + } + for i in 0..3 { + q.position[i] += f64::from((r.next_float() - r.next_float()) * 0.05); + } + // RisingParticle moves x/y/z but not the bounding box. + q.previous = p; + q.lifetime = (8.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + 4; + if matches!(ty, T::Soul | T::SculkSoul) { + q.scale(1.5); + q.behaviour = Behaviour::Animated; + q.set = set; + if ty == T::SculkSoul { + q.light = Light::Block15; + } + } else { + q.free_move = true; + q.size_curve = Size::Flame; + q.light = Light::AgeEmission; + if ty == T::SmallFlame { + q.scale(0.5); + } + } + q + } + T::Lava => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.gravity = 0.75; + q.friction = 0.999; + q.velocity[0] *= f64::from(0.8f32); + q.velocity[1] *= f64::from(0.8f32); + q.velocity[2] *= f64::from(0.8f32); + q.velocity[1] = f64::from(r.next_float() * 0.4 + 0.05); + q.size *= r.next_float() * 2.0 + 0.2; + q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.size_curve = Size::Lava; + q.light = Light::Block15; + q.behaviour = Behaviour::Lava; + q + } + T::DrippingWater + | T::FallingWater + | T::DrippingLava + | T::FallingLava + | T::LandingLava + | T::DrippingHoney + | T::FallingHoney + | T::LandingHoney + | T::FallingNectar + | T::FallingSporeBlossom + | T::DrippingObsidianTear + | T::FallingObsidianTear + | T::LandingObsidianTear + | T::DrippingDripstoneWater + | T::FallingDripstoneWater + | T::DrippingDripstoneLava + | T::FallingDripstoneLava => { + let mut q = Particle::at(r, ty, p); + q.set_size(0.01, 0.01); + q.gravity = 0.06; + let water = [0.2, 0.3, 1.0]; + let lava = [1.0, 0.285_714_3, 0.083_333_336]; + let tear = [0.511_718_75, 0.031_25, 0.890_625]; + let (fluid, stage, next, color, sound) = match ty { + T::DrippingWater => ( + Fluid::Water, + DripStage::Hang, + Some(T::FallingWater), + Some(water), + None, + ), + T::FallingWater => ( + Fluid::Water, + DripStage::FallAndLand, + Some(T::Splash), + Some(water), + None, + ), + T::DrippingLava => ( + Fluid::Lava, + DripStage::CoolingHang, + Some(T::FallingLava), + None, + None, + ), + T::FallingLava => ( + Fluid::Lava, + DripStage::FallAndLand, + Some(T::LandingLava), + Some(lava), + None, + ), + T::LandingLava => (Fluid::Lava, DripStage::Land, None, Some(lava), None), + T::DrippingHoney => ( + Fluid::None, + DripStage::Hang, + Some(T::FallingHoney), + Some([0.622, 0.508, 0.082]), + None, + ), + T::FallingHoney => ( + Fluid::None, + DripStage::FallAndLand, + Some(T::LandingHoney), + Some([0.582, 0.448, 0.082]), + Some("minecraft:block.beehive.drip"), + ), + T::LandingHoney => ( + Fluid::None, + DripStage::Land, + None, + Some([0.522, 0.408, 0.082]), + None, + ), + T::FallingNectar => ( + Fluid::None, + DripStage::Fall, + None, + Some([0.92, 0.782, 0.72]), + None, + ), + T::FallingSporeBlossom => ( + Fluid::None, + DripStage::Fall, + None, + Some([0.32, 0.5, 0.22]), + None, + ), + T::DrippingObsidianTear => ( + Fluid::None, + DripStage::Hang, + Some(T::FallingObsidianTear), + Some(tear), + None, + ), + T::FallingObsidianTear => ( + Fluid::None, + DripStage::FallAndLand, + Some(T::LandingObsidianTear), + Some(tear), + None, + ), + T::LandingObsidianTear => { + (Fluid::None, DripStage::Land, None, Some(tear), None) + } + T::DrippingDripstoneWater => ( + Fluid::Water, + DripStage::Hang, + Some(T::FallingDripstoneWater), + Some(water), + None, + ), + T::FallingDripstoneWater => ( + Fluid::Water, + DripStage::FallAndLand, + Some(T::Splash), + Some(water), + Some("minecraft:block.pointed_dripstone.drip_water"), + ), + T::DrippingDripstoneLava => ( + Fluid::Lava, + DripStage::CoolingHang, + Some(T::FallingDripstoneLava), + None, + None, + ), + _ => ( + Fluid::Lava, + DripStage::FallAndLand, + Some(T::LandingLava), + Some(lava), + Some("minecraft:block.pointed_dripstone.drip_lava"), + ), + }; + match stage { + DripStage::Hang | DripStage::CoolingHang => { + q.gravity *= 0.02; + q.lifetime = 40; + } + DripStage::FallAndLand => { + q.lifetime = (64.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + } + DripStage::Land => { + q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + } + DripStage::Fall => {} + } + match ty { + T::FallingHoney | T::FallingObsidianTear => q.gravity = 0.01, + T::DrippingHoney | T::DrippingObsidianTear => { + q.gravity *= 0.01; + q.lifetime = 100; + } + T::LandingHoney => { + q.lifetime = (128.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + } + T::LandingObsidianTear => { + q.lifetime = (28.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + } + T::FallingNectar => { + q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.gravity = 0.007; + } + T::FallingSporeBlossom => { + q.lifetime = (64.0 / (r.next_float() * (0.9 - 0.1) + 0.1)) as i32; + q.gravity = 0.005; + } + _ => {} + } + if matches!( + ty, + T::DrippingObsidianTear | T::FallingObsidianTear | T::LandingObsidianTear + ) { + q.light = Light::Block15; + } + if let Some(c) = color { + q.set_color(c[0], c[1], c[2]); + } + q.behaviour = Behaviour::Drip { + fluid, + stage, + next, + sound, + }; + q + } + T::Rain | T::Splash => { + // WaterDropParticle. + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.velocity[0] *= f64::from(0.3f32); + q.velocity[1] = f64::from(r.next_float() * 0.2 + 0.1); + q.velocity[2] *= f64::from(0.3f32); + q.set_size(0.01, 0.01); + q.gravity = 0.06; + q.lifetime = (8.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + if ty == T::Splash { + q.gravity = 0.04; + if v[1] == 0.0 && (v[0] != 0.0 || v[2] != 0.0) { + q.velocity = [v[0], 0.1, v[2]]; + } + } + q.behaviour = Behaviour::WaterDrop; + q + } + T::Bubble | T::BubbleColumnUp => { + let mut q = Particle::at(r, ty, p); + q.set_size(0.02, 0.02); + q.size *= r.next_float() * 0.6 + 0.2; + for i in 0..3 { + q.velocity[i] = + v[i] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + } + if ty == T::Bubble { + q.lifetime = (8.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.behaviour = Behaviour::Bubble; + } else { + q.gravity = -0.125; + q.friction = 0.85; + q.lifetime = (40.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.behaviour = Behaviour::BubbleColumnUp; + } + q + } + T::BubblePop => { + let mut q = Particle::at(r, ty, p); + q.lifetime = 4; + q.gravity = 0.008; + q.velocity = v; + q.behaviour = Behaviour::BubblePop; + q.set = set; + q + } + T::CurrentDown => { + let mut q = Particle::at(r, ty, p); + q.lifetime = (r.next_float() * 60.0) as i32 + 30; + q.has_physics = false; + q.velocity = [0.0, -0.05, 0.0]; + q.set_size(0.02, 0.02); + q.size *= r.next_float() * 0.6 + 0.2; + q.gravity = 0.002; + q.behaviour = Behaviour::CurrentDown { angle: 0.0 }; + q + } + T::Underwater | T::CrimsonSpore | T::WarpedSpore | T::SporeBlossomAir => { + let below = [p[0], p[1] - 0.125, p[2]]; + let mut q = if ty == T::Underwater { + let mut q = Particle::at(r, ty, below); + q.set_size(0.01, 0.01); + q.size *= r.next_float() * 0.6 + 0.2; + q + } else { + let vel = match ty { + T::CrimsonSpore => [ + r.next_gaussian() * 1.0e-6, + r.next_gaussian() * 1.0e-4, + r.next_gaussian() * 1.0e-6, + ], + T::WarpedSpore => [ + 0.0, + f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1, + 0.0, + ], + _ => [0.0, f64::from(-0.8f32), 0.0], + }; + let mut q = Particle::moving(r, ty, below, vel); + q.set_size(0.01, 0.01); + q.size *= r.next_float() * 0.6 + 0.6; + q + }; + q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.has_physics = false; + q.friction = 1.0; + q.gravity = 0.0; + match ty { + T::Underwater => q.set_color(0.4, 0.4, 0.7), + T::CrimsonSpore => q.set_color(0.9, 0.4, 0.5), + T::WarpedSpore => { + q.set_color(0.1, 0.1, 0.3); + q.set_size(0.001, 0.001); + } + _ => { + q.lifetime = r.next_int_bound(501).unwrap_or(0) + 500; + q.gravity = 0.01; + q.set_color(0.32, 0.5, 0.22); + } + } + q + } + T::Portal | T::ReversePortal => { + let mut q = Particle::at(r, ty, p); + q.velocity = v; + q.size = 0.1 * (r.next_float() * 0.2 + 0.5); + let br = r.next_float() * 0.6 + 0.4; + q.set_color(br * 0.9, br * 0.3, br); + q.lifetime = (r.next_float() * 10.0) as i32 + 40; + q.free_move = true; + q.light = Light::AgeEmission4; + if ty == T::Portal { + q.size_curve = Size::Portal; + q.behaviour = Behaviour::Portal { start: p }; + } else { + q.size *= 1.5; + q.lifetime = (r.next_float() * 2.0) as i32 + 60; + q.size_curve = Size::ReversePortal; + q.behaviour = Behaviour::ReversePortal; + } + q + } + T::Enchant | T::Nautilus | T::VaultConnection => { + let mut q = Particle::at(r, ty, p); + let alpha = if ty == T::VaultConnection { + [0.0, 0.6, 0.25, 1.0] + } else { + [1.0, 1.0, 0.0, 1.0] + }; + q.rgba[3] = alpha[0]; + q.velocity = v; + let start = [p[0] + v[0], p[1] + v[1], p[2] + v[2]]; + q.previous = start; + q.set_pos(start); + q.position = start; + q.size = 0.1 * (r.next_float() * 0.5 + 0.2); + let br = r.next_float() * 0.6 + 0.4; + q.set_color(0.9 * br, 0.9 * br, br); + q.has_physics = false; + q.lifetime = (r.next_float() * 10.0) as i32 + 30; + q.free_move = true; + q.light = if ty == T::VaultConnection { + Light::Block15 + } else { + Light::AgeEmission4 + }; + q.behaviour = Behaviour::FlyTowards { start: p, alpha }; + if ty == T::VaultConnection { + q.scale(1.5); + } + q + } + T::Crit | T::EnchantedHit | T::DamageIndicator => { + let vel = if ty == T::DamageIndicator { + [v[0], v[1] + 1.0, v[2]] + } else { + v + }; + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.friction = 0.7; + q.gravity = 0.5; + for i in 0..3 { + q.velocity[i] = q.velocity[i] * f64::from(0.1f32) + vel[i] * 0.4; + } + let col = r.next_float() * 0.3 + 0.6; + q.set_color(col, col, col); + q.size *= 0.75; + q.lifetime = ((6.0 / (f64::from(r.next_float()) * 0.8 + 0.6)) as i32).max(1); + q.has_physics = false; + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::Crit; + q.pre_tick = true; + q + } + T::Heart | T::AngryVillager => { + let at = if ty == T::AngryVillager { + [p[0], p[1] + 0.5, p[2]] + } else { + p + }; + let mut q = Particle::moving(r, ty, at, [0.0; 3]); + q.speed_up_when_y_blocked = true; + q.friction = 0.86; + for c in &mut q.velocity { + *c *= f64::from(0.01f32); + } + q.velocity[1] += 0.1; + q.size *= 1.5; + q.lifetime = 16; + q.has_physics = false; + q.size_curve = Size::GrowIn; + q + } + T::HappyVillager | T::Composter | T::Mycelium | T::Dolphin | T::EggCrack => { + let mut q = Particle::moving(r, ty, p, v); + let br = r.next_float() * 0.1 + 0.2; + q.set_color(br, br, br); + q.set_size(0.02, 0.02); + q.size *= r.next_float() * 0.6 + 0.5; + for c in &mut q.velocity { + *c *= f64::from(0.02f32); + } + q.lifetime = (20.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.free_move = true; + q.behaviour = Behaviour::SuspendedTown; + match ty { + T::HappyVillager | T::EggCrack => q.set_color(1.0, 1.0, 1.0), + T::Composter => { + q.set_color(1.0, 1.0, 1.0); + q.lifetime = 3 + r.next_int_bound(5).unwrap_or(0); + } + T::Dolphin => { + q.set_color(0.3, 0.5, 1.0); + q.rgba[3] = 1.0 - r.next_float() * 0.7; + q.lifetime /= 2; + } + _ => {} + } + q + } + T::Poof | T::Snowflake => { + let mut q = Particle::at(r, ty, p); + if ty == T::Poof { + q.gravity = -0.1; + q.friction = 0.9; + } else { + q.gravity = 0.225; + q.friction = 1.0; + } + for i in 0..3 { + q.velocity[i] = v[i] + f64::from((r.next_float() * 2.0 - 1.0) * 0.05); + } + if ty == T::Poof { + let col = r.next_float() * 0.3 + 0.7; + q.set_color(col, col, col); + q.size = 0.1 * (r.next_float() * r.next_float() * 6.0 + 1.0); + } else { + q.size = 0.1 * (r.next_float() * r.next_float() + 1.0); + } + q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + 2; + q.behaviour = if ty == T::Poof { + Behaviour::Animated + } else { + Behaviour::Snowflake + }; + if ty == T::Snowflake { + q.set_color(0.923, 0.964, 0.999); + } + q.set = set; + q + } + T::Explosion => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.lifetime = 6 + r.next_int_bound(4).unwrap_or(0); + let col = r.next_float() * 0.6 + 0.4; + q.set_color(col, col, col); + q.size = 2.0 * (1.0 - v[0] as f32 * 0.5); + q.light = Light::FullBright; + q.behaviour = Behaviour::HugeExplosion; + q.set = set; + q + } + T::ExplosionEmitter => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.lifetime = 8; + q.no_render = true; + q.behaviour = Behaviour::ExplosionSeed; + q + } + T::CampfireCosySmoke | T::CampfireSignalSmoke => { + let mut q = Particle::at(r, ty, p); + q.scale(3.0); + q.set_size(0.25, 0.25); + q.lifetime = r.next_int_bound(50).unwrap_or(0) + + if ty == T::CampfireSignalSmoke { + 280 + } else { + 80 + }; + q.gravity = 3.0e-6; + q.velocity = [v[0], v[1] + f64::from(r.next_float() / 500.0), v[2]]; + q.rgba[3] = if ty == T::CampfireSignalSmoke { + 0.95 + } else { + 0.9 + }; + q.behaviour = Behaviour::Campfire; + q + } + T::Note => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.friction = 0.66; + q.speed_up_when_y_blocked = true; + for c in &mut q.velocity { + *c *= f64::from(0.01f32); + } + q.velocity[1] += 0.2; + let color = v[0] as f32; + let channel = |offset: f32| { + ((color + offset) * std::f32::consts::TAU) + .sin() + .mul_add(0.65, 0.35) + .max(0.0) + }; + q.set_color(channel(0.0), channel(1.0 / 3.0), channel(2.0 / 3.0)); + q.size *= 1.5; + q.lifetime = 6; + q.size_curve = Size::GrowIn; + q + } + T::Dust => { + let mut q = Particle::moving(r, ty, p, v); + q.friction = 0.96; + q.speed_up_when_y_blocked = true; + for c in &mut q.velocity { + *c *= f64::from(0.1f32); + } + q.size *= 0.75 * o.scale; + let base = (8.0 / (r.next_double() * 0.8 + 0.2)) as i32; + q.lifetime = ((base as f32 * o.scale).max(1.0)) as i32; + let factor = r.next_float() * 0.4 + 0.6; + let mut randomize = |c: f32| (r.next_float() * 0.2 + 0.8) * c * factor; + let rgb = [ + randomize(o.color[0]), + randomize(o.color[1]), + randomize(o.color[2]), + ]; + q.set_color(rgb[0], rgb[1], rgb[2]); + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::Animated; + q.set = set; + q + } + T::TotemOfUndying | T::EndRod => { + let mut q = Particle::at(r, ty, p); + q.friction = 0.91; + q.gravity = if ty == T::TotemOfUndying { + 1.25 + } else { + 0.0125 + }; + q.velocity = v; + q.size *= 0.75; + q.lifetime = 60 + r.next_int_bound(12).unwrap_or(0); + let mut fade = None; + if ty == T::TotemOfUndying { + q.friction = 0.6; + if r.next_int_bound(4).unwrap_or(1) == 0 { + q.set_color( + 0.6 + r.next_float() * 0.2, + 0.6 + r.next_float() * 0.3, + r.next_float() * 0.2, + ); + } else { + q.set_color( + 0.1 + r.next_float() * 0.2, + 0.4 + r.next_float() * 0.3, + r.next_float() * 0.2, + ); + } + } else { + fade = Some([ + 0xF2 as f32 / 255.0, + 0xDE as f32 / 255.0, + 0xC9 as f32 / 255.0, + ]); + q.free_move = true; + } + q.light = Light::FullBright; + q.behaviour = Behaviour::SimpleAnimated { fade }; + q.set = set; + q + } + T::CherryLeaves | T::PaleOakLeaves | T::TintedLeaves => { + let (fall, side, swirl, flow, scale, start) = if ty == T::CherryLeaves { + (0.25f32, 2.0f32, false, true, 1.0f32, 0.0f32) + } else { + (0.07, 10.0, true, false, 2.0, 0.021) + }; + let mut q = Particle::at(r, ty, p); + let rot_speed = (if r.next_boolean() { -30.0f32 } else { 30.0 }).to_radians(); + let spin = (if r.next_boolean() { -5.0f32 } else { 5.0 }).to_radians(); + q.lifetime = 300; + q.gravity = fall * 1.2 * 0.0025; + let s = scale * if r.next_boolean() { 0.05 } else { 0.075 }; + q.size = s; + q.set_size(s, s); + q.friction = 1.0; + q.velocity[1] = -f64::from(start); + let pr = r.next_float(); + let flow_scale = [ + f64::from(pr * 60.0).to_radians().cos() * f64::from(side), + f64::from(pr * 60.0).to_radians().sin() * f64::from(side), + ]; + let swirl_period = f64::from(1000.0 + pr * 3000.0).to_radians(); + if ty == T::TintedLeaves { + q.set_color(o.color[0], o.color[1], o.color[2]); + } + q.behaviour = Behaviour::Leaves { + rot_speed, + spin, + wind: side, + swirl, + flow, + flow_scale, + swirl_period, + }; + q + } + T::Effect | T::InstantEffect | T::EntityEffect | T::Witch | T::Infested => { + // SpellParticle: x/z velocity from a shared random, y from the option. + let xa = 0.5 - r.next_double(); + let za = 0.5 - r.next_double(); + let mut q = Particle::moving(r, ty, p, [xa, v[1], za]); + q.friction = 0.96; + q.gravity = -0.1; + q.speed_up_when_y_blocked = true; + q.velocity[1] *= f64::from(0.2f32); + if v[0] == 0.0 && v[2] == 0.0 { + q.velocity[0] *= f64::from(0.1f32); + q.velocity[2] *= f64::from(0.1f32); + } + q.size *= 0.75; + q.lifetime = (8.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.has_physics = false; + match ty { + T::Witch => { + let b = r.next_float() * 0.5 + 0.35; + q.set_color(b, 0.0, b); + } + T::EntityEffect => { + q.set_color(o.color[0], o.color[1], o.color[2]); + q.rgba[3] = o.color[3]; + } + T::Effect | T::InstantEffect => { + q.set_color(o.color[0], o.color[1], o.color[2]); + q.set_power(o.scale); + } + _ => {} + } + q.behaviour = Behaviour::Spell { + original_alpha: q.rgba[3], + }; + q.set = set; + q + } + T::Cloud | T::Sneeze => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.friction = 0.96; + for i in 0..3 { + q.velocity[i] = q.velocity[i] * f64::from(0.1f32) + v[i]; + } + let col = 1.0 - r.next_float() * 0.3; + q.set_color(col, col, col); + q.size *= 1.875; + let base = (8.0 / (f64::from(r.next_float()) * 0.8 + 0.3)) as i32; + q.lifetime = ((base as f32 * 2.5).max(1.0)) as i32; + q.has_physics = false; + if ty == T::Sneeze { + q.set_color(0.22, 1.0, 0.53); + q.rgba[3] = 0.4; + } + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::Cloud; + q.set = set; + q + } + T::DragonBreath => { + let mut q = Particle::at(r, ty, p); + q.friction = 0.96; + q.velocity = v; + q.set_color( + r.next_float() * (0.874_509_8 - 0.717_647_1) + 0.717_647_1, + 0.0, + r.next_float() * (0.976_470_6 - 0.823_529_4) + 0.823_529_4, + ); + q.size *= 0.75; + q.lifetime = (20.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.has_physics = false; + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::DragonBreath { hit_ground: false }; + q.set = set; + q.set_power(o.scale); + q + } + }; + if particle.set.is_some() { + particle.sprite = self.first(ty); + self.sprite_from_age(&mut particle); + } else if matches!(particle.sprite, Sprite::Index(u32::MAX)) { + particle.sprite = self.sprite_from_set(ty); + } + Some(particle) + } + + /// `ParticleEngine.tick`: tick live particles, then admit queued ones. + pub fn tick(&mut self, level: &ParticleLevel) { + for (options, feet, width, height, life) in std::mem::take(&mut self.emitters) { + self.emit(&options, feet, width, height); + if life > 1 { + self.emitters.push((options, feet, width, height, life - 1)); + } + } + let mut particles = std::mem::take(&mut self.particles); + for p in &mut particles { + self.tick_particle(p, level); + } + particles.retain(|p| !p.removed); + self.particles = particles; + let pending = std::mem::take(&mut self.pending); + for mut p in pending { + if p.pre_tick { + p.pre_tick = false; + self.tick_particle(&mut p, level); + } + // ParticleGroup.add: the last quarter fills with decreasing probability. + let size = self.particles.len(); + if size >= MAX_PARTICLES { + continue; + } + if size >= 12288 { + let free = (MAX_PARTICLES - size) as f32 / 4096.0; + if self.random.next_float() >= free * free { + continue; + } + } + self.particles.push(p); + } + } + #[allow(clippy::too_many_lines)] + fn tick_particle(&mut self, p: &mut Particle, level: &ParticleLevel) { + match p.behaviour { + Behaviour::Base => p.base_tick(level), + Behaviour::Animated => { + p.base_tick(level); + self.sprite_from_age(p); + } + Behaviour::Snowflake => { + p.base_tick(level); + self.sprite_from_age(p); + p.velocity[0] *= f64::from(0.95f32); + p.velocity[1] *= f64::from(0.9f32); + p.velocity[2] *= f64::from(0.95f32); + } + Behaviour::Lava => { + p.base_tick(level); + if !p.removed { + let odds = p.age as f32 / p.lifetime as f32; + if self.random.next_float() > odds { + self.add( + &ParticleOptions::simple(ParticleType::Smoke), + p.position, + p.velocity, + ); + } + } + } + Behaviour::Crit => { + p.base_tick(level); + p.rgba[1] *= 0.96; + p.rgba[2] *= 0.9; + } + Behaviour::Drip { + fluid, + stage, + next, + sound, + } => { + p.previous = p.position; + // preMoveUpdate + if stage == DripStage::CoolingHang { + p.rgba[0] = 1.0; + p.rgba[1] = 16.0 / (40 - p.lifetime + 16) as f32; + p.rgba[2] = 4.0 / (40 - p.lifetime + 8) as f32; + } + let lifetime = p.lifetime; + p.lifetime -= 1; + if lifetime <= 0 { + p.removed = true; + if matches!(stage, DripStage::Hang | DripStage::CoolingHang) + && let Some(next) = next + { + self.add(&ParticleOptions::simple(next), p.position, p.velocity); + } + } + if p.removed { + return; + } + p.velocity[1] -= f64::from(p.gravity); + p.move_by(level, p.velocity); + // postMoveUpdate + match stage { + DripStage::Hang | DripStage::CoolingHang => { + for c in &mut p.velocity { + *c *= 0.02; + } + } + DripStage::Fall if p.on_ground => p.removed = true, + DripStage::FallAndLand if p.on_ground => { + p.removed = true; + if let Some(next) = next { + self.add(&ParticleOptions::simple(next), p.position, [0.0; 3]); + } + if let Some(sound) = sound { + let volume = self.random.next_float() * 0.7 + 0.3; + self.sounds.push((sound, p.position, volume, 1.0)); + } + } + _ => {} + } + if p.removed { + return; + } + for c in &mut p.velocity { + *c *= f64::from(0.98f32); + } + if fluid != Fluid::None { + let b = ParticleLevel::block_at(p.position); + let (f, height) = level.fluid(b); + if f == fluid && p.position[1] < f64::from(b[1]) + height { + p.removed = true; + } + } + } + Behaviour::WaterDrop => { + p.previous = p.position; + let lifetime = p.lifetime; + p.lifetime -= 1; + if lifetime <= 0 { + p.removed = true; + return; + } + p.velocity[1] -= f64::from(p.gravity); + p.move_by(level, p.velocity); + for c in &mut p.velocity { + *c *= f64::from(0.98f32); + } + if p.on_ground { + if self.random.next_float() < 0.5 { + p.removed = true; + } + p.velocity[0] *= f64::from(0.7f32); + p.velocity[2] *= f64::from(0.7f32); + } + let b = ParticleLevel::block_at(p.position); + let top = level.collision_top( + b, + p.position[0] - f64::from(b[0]), + p.position[2] - f64::from(b[2]), + ); + let offset = top.max(level.fluid(b).1); + if offset > 0.0 && p.position[1] < f64::from(b[1]) + offset { + p.removed = true; + } + } + Behaviour::Bubble => { + p.previous = p.position; + let lifetime = p.lifetime; + p.lifetime -= 1; + if lifetime <= 0 { + p.removed = true; + return; + } + p.velocity[1] += 0.002; + p.move_by(level, p.velocity); + for c in &mut p.velocity { + *c *= f64::from(0.85f32); + } + if level.fluid(ParticleLevel::block_at(p.position)).0 != Fluid::Water { + p.removed = true; + } + } + Behaviour::BubbleColumnUp => { + p.base_tick(level); + if !p.removed && level.fluid(ParticleLevel::block_at(p.position)).0 != Fluid::Water + { + p.removed = true; + } + } + Behaviour::BubblePop => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + p.velocity[1] -= f64::from(p.gravity); + p.move_by(level, p.velocity); + self.sprite_from_age(p); + } + Behaviour::CurrentDown { angle } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + p.velocity[0] += f64::from(0.6 * angle.cos()); + p.velocity[2] += f64::from(0.6 * angle.sin()); + p.velocity[0] *= 0.07; + p.velocity[2] *= 0.07; + p.move_by(level, p.velocity); + if level.fluid(ParticleLevel::block_at(p.position)).0 != Fluid::Water || p.on_ground + { + p.removed = true; + } + p.behaviour = Behaviour::CurrentDown { + angle: angle + 0.08, + }; + } + Behaviour::SuspendedTown => { + p.previous = p.position; + let lifetime = p.lifetime; + p.lifetime -= 1; + if lifetime <= 0 { + p.removed = true; + return; + } + p.move_by(level, p.velocity); + for c in &mut p.velocity { + *c *= 0.99; + } + } + Behaviour::Portal { start } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let a = p.age as f32 / p.lifetime as f32; + let pos = 1.0 - (-a + a * a * 2.0); + p.position = [ + start[0] + p.velocity[0] * f64::from(pos), + start[1] + p.velocity[1] * f64::from(pos) + f64::from(1.0 - a), + start[2] + p.velocity[2] * f64::from(pos), + ]; + } + Behaviour::ReversePortal => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let m = f64::from(p.age as f32 / p.lifetime as f32); + for i in 0..3 { + p.position[i] += p.velocity[i] * m; + } + } + Behaviour::FlyTowards { start, .. } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let pos = 1.0 - p.age as f32 / p.lifetime as f32; + let mut pp = 1.0 - pos; + pp *= pp; + pp *= pp; + p.position = [ + start[0] + p.velocity[0] * f64::from(pos), + start[1] + p.velocity[1] * f64::from(pos) - f64::from(pp * 1.2), + start[2] + p.velocity[2] * f64::from(pos), + ]; + } + Behaviour::HugeExplosion => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + self.sprite_from_age(p); + } + Behaviour::ExplosionSeed => { + for _ in 0..6 { + let r = &mut self.random; + let at = [ + p.position[0] + (r.next_double() - r.next_double()) * 4.0, + p.position[1] + (r.next_double() - r.next_double()) * 4.0, + p.position[2] + (r.next_double() - r.next_double()) * 4.0, + ]; + let f = f64::from(p.age as f32 / p.lifetime as f32); + self.add( + &ParticleOptions::simple(ParticleType::Explosion), + at, + [f, 0.0, 0.0], + ); + } + p.age += 1; + if p.age == p.lifetime { + p.removed = true; + } + } + Behaviour::Campfire => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age < p.lifetime && p.rgba[3] > 0.0 { + let r = &mut self.random; + let dx = r.next_float() / 5000.0 * if r.next_boolean() { 1.0 } else { -1.0 }; + p.velocity[0] += f64::from(dx); + let dz = r.next_float() / 5000.0 * if r.next_boolean() { 1.0 } else { -1.0 }; + p.velocity[2] += f64::from(dz); + p.velocity[1] -= f64::from(p.gravity); + p.move_by(level, p.velocity); + if p.age >= p.lifetime - 60 && p.rgba[3] > 0.01 { + p.rgba[3] -= 0.015; + } + } else { + p.removed = true; + } + } + Behaviour::SimpleAnimated { fade } => { + p.base_tick(level); + self.sprite_from_age(p); + if p.age > p.lifetime / 2 { + p.rgba[3] = 1.0 - (p.age as f32 - (p.lifetime / 2) as f32) / p.lifetime as f32; + if let Some(f) = fade { + for i in 0..3 { + p.rgba[i] += (f[i] - p.rgba[i]) * 0.2; + } + } + } + } + Behaviour::Spell { original_alpha } => { + p.base_tick(level); + self.sprite_from_age(p); + p.rgba[3] += (original_alpha - p.rgba[3]) * 0.05; + } + Behaviour::Cloud => { + p.base_tick(level); + if !p.removed { + self.sprite_from_age(p); + if let Some((player, vy)) = level.player { + let d2 = (player[0] - p.position[0]).powi(2) + + (player[1] - p.position[1]).powi(2) + + (player[2] - p.position[2]).powi(2); + if d2 < 4.0 && p.position[1] > player[1] { + let y = p.position[1] + (player[1] - p.position[1]) * 0.2; + p.velocity[1] += (vy - p.velocity[1]) * 0.2; + p.set_pos([p.position[0], y, p.position[2]]); + } + } + } + } + Behaviour::Leaves { + mut rot_speed, + spin, + wind, + swirl, + flow, + flow_scale, + swirl_period, + } => { + p.previous = p.position; + let lifetime = p.lifetime; + p.lifetime -= 1; + if lifetime <= 0 { + p.removed = true; + } + if !p.removed { + let alive = (300 - p.lifetime) as f32; + let relative = (alive / 300.0).min(1.0); + let (mut xa, mut za) = (0.0f64, 0.0f64); + if flow { + xa += flow_scale[0] * f64::from(relative).powf(1.25); + za += flow_scale[1] * f64::from(relative).powf(1.25); + } + if swirl { + let rel = f64::from(relative); + xa += rel * (rel * swirl_period).cos() * f64::from(wind); + za += rel * (rel * swirl_period).sin() * f64::from(wind); + } + p.velocity[0] += xa * f64::from(0.0025f32); + p.velocity[2] += za * f64::from(0.0025f32); + p.velocity[1] -= f64::from(p.gravity); + rot_speed += spin / 20.0; + p.o_roll = p.roll; + p.roll += rot_speed / 20.0; + p.move_by(level, p.velocity); + if p.on_ground + || p.lifetime < 299 && (p.velocity[0] == 0.0 || p.velocity[2] == 0.0) + { + p.removed = true; + } + if !p.removed { + let f = f64::from(p.friction); + for c in &mut p.velocity { + *c *= f; + } + } + } + p.behaviour = Behaviour::Leaves { + rot_speed, + spin, + wind, + swirl, + flow, + flow_scale, + swirl_period, + }; + } + Behaviour::FallingDust { rot_speed } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + self.sprite_from_age(p); + p.o_roll = p.roll; + p.roll += std::f32::consts::PI * rot_speed * 2.0; + if p.on_ground { + p.o_roll = 0.0; + p.roll = 0.0; + } + p.move_by(level, p.velocity); + p.velocity[1] -= f64::from(0.003f32); + p.velocity[1] = p.velocity[1].max(f64::from(-0.14f32)); + } + Behaviour::DragonBreath { mut hit_ground } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + self.sprite_from_age(p); + if p.on_ground { + p.velocity[1] = 0.0; + hit_ground = true; + } + if hit_ground { + p.velocity[1] += 0.002; + } + p.move_by(level, p.velocity); + if p.position[1] == p.previous[1] { + p.velocity[0] *= 1.1; + p.velocity[2] *= 1.1; + } + let f = f64::from(p.friction); + p.velocity[0] *= f; + p.velocity[2] *= f; + if hit_ground { + p.velocity[1] *= f; + } + p.behaviour = Behaviour::DragonBreath { hit_ground }; + } + } + } + + /// Camera-facing quads (`QuadParticleRenderState.renderRotatedQuad`). + pub fn render( + &self, + camera: DVec3, + yaw: f32, + pitch: f32, + partial: f32, + light_at: &dyn Fn([i32; 3]) -> u8, + out: &mut Vec, + ) { + // Camera.setRotation: rotationYXZ(PI - yRot, -xRot, 0). + let base = Quat::from_rotation_y(std::f32::consts::PI - yaw.to_radians()) + * Quat::from_rotation_x(-pitch.to_radians()); + for p in &self.particles { + if p.no_render { + continue; + } + let rect = match &p.sprite { + Sprite::Index(i) => self.rects.get(*i as usize).copied().flatten(), + Sprite::Named(name) => self.atlas.get(name).copied(), + }; + let Some(r) = rect else { continue }; + let a = f64::from(partial); + let pos = DVec3::new( + p.previous[0] + (p.position[0] - p.previous[0]) * a, + p.previous[1] + (p.position[1] - p.previous[1]) * a, + p.previous[2] + (p.position[2] - p.previous[2]) * a, + ) - camera; + let center = pos.as_vec3(); + let rotation = if p.roll != 0.0 { + base * Quat::from_rotation_z(p.o_roll + (p.roll - p.o_roll) * partial) + } else { + base + }; + let size = p.quad_size(partial); + let mut alpha = p.rgba[3]; + if let Behaviour::FlyTowards { alpha: la, .. } = p.behaviour { + alpha = lifetime_alpha(la, p.age, p.lifetime, partial); + } + let block = ParticleLevel::block_at(p.position); + let packed = light_at(block); + let (sky, mut block_light) = (u32::from(packed >> 4) * 16, u32::from(packed & 15) * 16); + let mut sky_light = sky; + let t = ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0); + match p.light { + Light::World => {} + Light::FullBright => { + block_light = 240; + sky_light = 240; + } + Light::Block15 => block_light = 240, + Light::AgeEmission => block_light = (block_light + (t * 240.0) as u32).min(240), + Light::AgeEmission4 => { + let b = p.age as f32 / p.lifetime as f32; + let b = (b * b) * (b * b); + block_light = (block_light + (b.clamp(0.0, 1.0) * 240.0) as u32).min(240); + } + } + let light = sky_light | block_light << 8; + let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0) as u32; + let color = c(alpha) << 24 | c(p.rgba[2]) << 16 | c(p.rgba[1]) << 8 | c(p.rgba[0]); + let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); + let (u0, v0, u1, v1) = ( + r.u0 + du * p.uv[0], + r.v0 + dv * p.uv[1], + r.u0 + du * p.uv[2], + r.v0 + dv * p.uv[3], + ); + for (n, uv) in [ + ((1.0, -1.0), [u1, v1]), + ((1.0, 1.0), [u1, v0]), + ((-1.0, 1.0), [u0, v0]), + ((-1.0, -1.0), [u0, v1]), + ] { + let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size; + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color, + light, + }); + } + } + } +} +/// `Particle.LifetimeAlpha.currentAlphaForAge`. +fn lifetime_alpha(a: [f32; 4], age: i32, lifetime: i32, partial: f32) -> f32 { + if (a[0] - a[1]).abs() < 1.0e-5 { + return a[0]; + } + let t = ((age as f32 + partial) / lifetime as f32 - a[2]) / (a[3] - a[2]); + a[0] + (a[1] - a[0]) * t.clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn particle_names_round_trip() { + for &ty in ParticleType::ALL { + assert_eq!( + ParticleType::from_name(&format!("minecraft:{}", ty.name())), + Some(ty) + ); + } + assert_eq!(ParticleType::from_name("minecraft:not_a_particle"), None); + } + #[test] + fn terrain_crumb_samples_a_mirrored_quarter() { + let mut r = LegacyRandom::new(1); + let p = Particle::terrain(&mut r, [0.5; 3], [0.0; 3], "block/stone".into(), 0xFFFFFF); + assert!((p.uv[0] - p.uv[2] - 0.25).abs() < 1e-6); + assert!((p.uv[3] - p.uv[1] - 0.25).abs() < 1e-6); + assert!((p.rgba[0] - 0.6).abs() < 1e-6); + // The initial speed is normalized to 0.15..0.45 * 0.4 plus 0.1 upwards. + let s = + (p.velocity[0].powi(2) + (p.velocity[1] - 0.1).powi(2) + p.velocity[2].powi(2)).sqrt(); + assert!((0.15 * 0.4 - 1e-6..=0.45 * 0.4 + 1e-6).contains(&s)); + } + #[test] + fn sizes_follow_vanilla_curves() { + let mut r = LegacyRandom::new(2); + let mut p = Particle::at(&mut r, ParticleType::Flame, [0.0; 3]); + p.size = 1.0; + p.lifetime = 10; + p.age = 5; + p.size_curve = Size::Flame; + assert!((p.quad_size(0.0) - (1.0 - 0.25 * 0.5)).abs() < 1e-6); + p.size_curve = Size::GrowIn; + p.age = 0; + assert!((p.quad_size(0.1) - (0.1f32 / 10.0 * 32.0)).abs() < 1e-6); + } + #[test] + fn lifetime_alpha_interpolates() { + let a = [0.0, 0.6, 0.25, 1.0]; + assert_eq!(lifetime_alpha(a, 0, 40, 0.0), 0.0); + assert!((lifetime_alpha(a, 40, 40, 0.0) - 0.6).abs() < 1e-6); } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 74cbba45b..6d55fc588 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -350,6 +350,7 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b entries.push(("total_fuel", Tag::Int(b.total_fuel))); entries.push(("speed_multiplier", Tag::Float(b.speed.to_bits()))); } + BlockEntity::Sign(sign) => entries.extend(sign.encode()), } Tag::compound(entries) } @@ -387,6 +388,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: _ => 1.0, }; } + BlockEntity::Sign(sign) => sign.decode(tag), } Some((pos, entity)) } diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl new file mode 100644 index 000000000..62cb2ee6c --- /dev/null +++ b/crates/horizon-client/src/screen.wgsl @@ -0,0 +1,34 @@ +// Full-screen camera effects (screen_effects.rs): clip-space quads sampling +// the shared 2D atlas with repeat inside each sprite rectangle. +@group(0) @binding(1) var atlas: texture_2d; +@group(0) @binding(2) var atlas_sampler: sampler; +struct Out { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) rect: vec4, + @location(2) color: vec4, +} +@vertex fn vs_screen(@location(0) pos: vec2, @location(1) uv: vec2, + @location(2) rect: vec4, @location(3) color: vec4) -> Out { + var out: Out; + out.clip = vec4(pos, 0.0, 1.0); + out.uv = uv; + out.rect = rect; + out.color = color; + return out; +} +fn sample(in: Out) -> vec4 { + let f = fract(in.uv); + let uv = in.rect.xy + f * (in.rect.zw - in.rect.xy); + return textureSampleLevel(atlas, atlas_sampler, uv, 0.0) * in.color; +} +@fragment fn fs_screen(in: Out) -> @location(0) vec4 { + let c = sample(in); + if c.a <= 0.0 { discard; } + return c; +} +// RenderPipelines.VIGNETTE blends ZERO, ONE_MINUS_SRC_COLOR: output the +// texture colour; the blend state darkens the frame by it. +@fragment fn fs_vignette(in: Out) -> @location(0) vec4 { + return vec4(sample(in).rgb, 1.0); +} diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs new file mode 100644 index 000000000..ca728779c --- /dev/null +++ b/crates/horizon-client/src/screen_effects.rs @@ -0,0 +1,266 @@ +//! Full-screen camera effects drawn between the world and the HUD: +//! `ScreenEffectRenderer` (in-wall block texture, underwater overlay, fire) +//! and the `Hud` camera overlays (vignette, pumpkin blur, powder-snow +//! outline, nether portal swirl). Positions are clip-space quads; textures +//! come from the shared 2D atlas and may repeat. +use crate::hud::Rect; +use std::collections::HashMap; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Blend { + /// `GUI_TEXTURED` / screen effects: alpha blending. + Alpha, + /// `RenderPipelines.VIGNETTE`: `dst * (1 - src)`. + Vignette, +} +/// One clip-space vertex of a screen quad. +#[repr(C)] +#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] +pub struct ScreenVertex { + pub pos: [f32; 2], + /// Texture coordinates in sprite units (repeat outside 0..1). + pub uv: [f32; 2], + /// Atlas rectangle (u0, v0, u1, v1) of the sprite. + pub rect: [f32; 4], + pub color: [f32; 4], +} +#[derive(Clone, Debug)] +pub struct ScreenQuad { + pub vertices: [ScreenVertex; 4], + pub blend: Blend, +} + +/// What the camera sees this frame. +pub struct ScreenInputs<'a> { + pub sprites: &'a HashMap, + pub aspect: f32, + pub partial: f32, + /// Particle sprite of the view-blocking block around the eye. + pub block_overlay: Option, + /// Eye in water: (lightmap brightness at the eye, yaw, pitch). + pub water: Option<(f32, f32, f32)>, + pub on_fire: bool, + /// Equipment camera overlays (`Equippable.cameraOverlay`, e.g. `misc/pumpkinblur`). + pub camera_overlays: Vec, + /// `Player.getPercentFrozen`. + pub frozen: f32, + /// `Options.vignette`. + pub vignette: bool, + /// Distance to the world border and its warning distance, when close. + pub border_warning: Option, +} + +/// Effect state advanced every tick. +#[derive(Clone, Copy, Debug)] +pub struct ScreenEffects { + /// `Hud.vignetteBrightness`. + pub vignette_brightness: f32, + pub portal: f32, + pub o_portal: f32, +} +impl Default for ScreenEffects { + fn default() -> Self { + Self { + vignette_brightness: 1.0, + portal: 0.0, + o_portal: 0.0, + } + } +} +/// `Lightmap.getBrightness`. +pub fn lightmap_brightness(ambient_light: f32, level: u8) -> f32 { + let v = f32::from(level) / 15.0; + let curved = v / (4.0 - 3.0 * v); + curved + (1.0 - curved) * ambient_light +} +/// Clip-space scale of the hand projection (fov 70) at view depth 0.5. +fn hand_scale(aspect: f32) -> [f32; 2] { + let half = 0.5 * (35.0f32).to_radians().tan(); + [1.0 / (half * aspect), 1.0 / half] +} +impl ScreenEffects { + /// `Hud.updateVignetteBrightness` and `LocalPlayer.handlePortalTransitionEffect`. + pub fn tick(&mut self, eye_brightness: f32, inside_portal: bool) { + let target = (1.0 - eye_brightness).clamp(0.0, 1.0); + self.vignette_brightness += (target - self.vignette_brightness) * 0.01; + self.o_portal = self.portal; + let step = if inside_portal { + 0.0125 + } else if self.portal > 0.0 { + -0.05 + } else { + 0.0 + }; + self.portal = (self.portal + step).clamp(0.0, 1.0); + } + pub fn build(&self, input: &ScreenInputs) -> Vec { + let mut out = Vec::new(); + let sprite = |name: &str| input.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + let scale = hand_scale(input.aspect); + // Screen-effect quads live at view depth 0.5 in the hand projection. + let hand_quad = |corners: [[f32; 2]; 4], + uv: [[f32; 2]; 4], + rect: [f32; 4], + color: [f32; 4]| ScreenQuad { + vertices: std::array::from_fn(|i| ScreenVertex { + pos: [corners[i][0] * scale[0], corners[i][1] * scale[1]], + uv: uv[i], + rect, + color, + }), + blend: Blend::Alpha, + }; + let full = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]]; + // ScreenEffectRenderer.submitBlockSprite: u1/v1 at (-1, -1), colour 0xFF191919. + if let Some(name) = &input.block_overlay + && let Some(rect) = sprite(name) + { + let c = 0x19 as f32 / 255.0; + out.push(hand_quad( + full, + [[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]], + rect, + [c, c, c, 1.0], + )); + } + if let Some((brightness, yaw, pitch)) = input.water + && let Some(rect) = sprite("misc/underwater") + { + let (u, v) = (-yaw / 64.0, pitch / 64.0); + let uv = [[u + 4.0, v + 4.0], [u, v + 4.0], [u, v], [u + 4.0, v]]; + out.push(hand_quad( + full, + uv, + rect, + [brightness, brightness, brightness, 0.1], + )); + } + if input.on_fire + && let Some(rect) = sprite("block/fire_1") + { + for (dx, angle) in [(0.24f32, -10.0f32), (-0.24, 10.0)] { + let (s, c) = angle.to_radians().sin_cos(); + // rotateY about the quad then translate; z = -0.5 feeds into x. + let corner = |x: f32, y: f32| [x * c + -0.5 * s + dx, y - 0.3]; + let corners = [ + corner(-0.5, -0.5), + corner(0.5, -0.5), + corner(0.5, 0.5), + corner(-0.5, 0.5), + ]; + let alpha = 0xE5 as f32 / 255.0; + out.push(hand_quad( + corners, + [[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]], + rect, + [1.0, 1.0, 1.0, alpha], + )); + } + } + // Hud camera overlays: GUI-space full-screen blits (v grows downwards). + let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend| ScreenQuad { + vertices: std::array::from_fn(|i| { + let p = [[-1.0f32, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]][i]; + ScreenVertex { + pos: p, + uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i], + rect, + color, + } + }), + blend, + }; + if input.vignette + && let Some(rect) = sprite("misc/vignette") + { + let b = self.vignette_brightness.clamp(0.0, 1.0); + let color = match input.border_warning { + Some(w) if w > 0.0 => { + let w = w.clamp(0.0, 1.0); + let red = b * (1.0 - w); + let gb = b + (1.0 - b) * w; + [red, gb, gb, 1.0] + } + _ => [b, b, b, 1.0], + }; + out.push(gui(rect, color, Blend::Vignette)); + } + for overlay in &input.camera_overlays { + if let Some(rect) = sprite(overlay) { + out.push(gui(rect, [1.0; 4], Blend::Alpha)); + } + } + if input.frozen > 0.0 + && let Some(rect) = sprite("misc/powder_snow_outline") + { + out.push(gui(rect, [1.0, 1.0, 1.0, input.frozen], Blend::Alpha)); + } + let portal = self.o_portal + (self.portal - self.o_portal) * input.partial; + if portal > 0.0 + && let Some(rect) = sprite("block/nether_portal") + { + let mut a = portal; + if a < 1.0 { + a *= a; + a *= a; + a = a * 0.8 + 0.2; + } + out.push(gui(rect, [1.0, 1.0, 1.0, a], Blend::Alpha)); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn lightmap_brightness_curve() { + assert_eq!(lightmap_brightness(0.0, 15), 1.0); + assert_eq!(lightmap_brightness(0.0, 0), 0.0); + assert!((lightmap_brightness(0.1, 0) - 0.1).abs() < 1e-6); + } + #[test] + fn portal_intensity_ramps() { + let mut e = ScreenEffects::default(); + for _ in 0..80 { + e.tick(1.0, true); + } + assert!((e.portal - 1.0).abs() < 1e-5); + e.tick(1.0, false); + assert!((e.portal - 0.95).abs() < 1e-5); + // Vignette fades towards 1 - brightness at 1% per tick. + assert!(e.vignette_brightness < 1.0); + } + #[test] + fn overlays_need_their_sprites() { + let mut sprites = HashMap::new(); + sprites.insert( + "misc/vignette".to_owned(), + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 256, + h: 256, + }, + ); + let e = ScreenEffects::default(); + let input = ScreenInputs { + sprites: &sprites, + aspect: 1.6, + partial: 0.0, + block_overlay: None, + water: Some((1.0, 0.0, 0.0)), + on_fire: false, + camera_overlays: vec![], + frozen: 0.0, + vignette: true, + border_warning: None, + }; + let quads = e.build(&input); + assert_eq!(quads.len(), 1); + assert_eq!(quads[0].blend, Blend::Vignette); + } +} diff --git a/crates/horizon-client/src/shadows.rs b/crates/horizon-client/src/shadows.rs new file mode 100644 index 000000000..e971687da --- /dev/null +++ b/crates/horizon-client/src/shadows.rs @@ -0,0 +1,116 @@ +//! Entity shadows (`EntityRenderer.extractShadow` + `ShadowFeatureRenderer`): +//! `misc/shadow.png` projected onto the tops of full-collision blocks under +//! an entity, faded by camera distance, depth below the entity and the light +//! at each block. +use crate::{blocks::BlockFacts, hud::Rect, mesher::Vertex, world::World}; +use glam::DVec3; + +/// Vanilla renderer shadow radius and strength for an entity type id. +pub fn shadow_params(entity: &str) -> (f32, f32) { + let id = entity.strip_prefix("minecraft:").unwrap_or(entity); + let radius = match id { + "item" | "experience_orb" | "tropical_fish" => 0.15, + "tadpole" => 0.14, + "pufferfish" => 0.2, + "slime" | "magma_cube" | "bat" => 0.25, + "chicken" | "cod" | "parrot" | "rabbit" | "frog" | "silverfish" | "endermite" | "vex" => 0.3, + "cat" | "ocelot" | "fox" | "bee" | "allay" | "salmon" => 0.4, + "zombie" | "husk" | "drowned" | "zombie_villager" | "zombified_piglin" | "skeleton" | "stray" | "wither_skeleton" | "bogged" + | "creeper" | "enderman" | "villager" | "wandering_trader" | "witch" | "pillager" | "vindicator" | "evoker" | "illusioner" + | "blaze" | "breeze" | "snow_golem" | "copper_golem" | "strider" | "wolf" | "axolotl" | "tnt" | "falling_block" | "end_crystal" => { + 0.5 + } + "cave_spider" => 0.56, + "creaking" => 0.6, + "pig" | "cow" | "mooshroom" | "sheep" | "goat" | "llama" | "trader_llama" | "iron_golem" | "camel" | "camel_husk" | "squid" + | "glow_squid" | "dolphin" | "turtle" | "hoglin" | "zoglin" | "nautilus" | "zombie_nautilus" | "minecart" => 0.7, + "horse" | "donkey" | "mule" | "skeleton_horse" | "zombie_horse" | "phantom" => 0.75, + "spider" | "boat" => 0.8, + "polar_bear" | "panda" | "warden" => 0.9, + "wither" => 1.0, + "sniffer" | "ravager" => 1.1, + "ghast" => 1.5, + _ => 0.5, + }; + let strength = if matches!(id, "item" | "experience_orb") { 0.75 } else { 1.0 }; + (radius, strength) +} + +/// Shadow quads for an entity at `pos` (interpolated feet position). +#[allow(clippy::too_many_arguments)] +pub fn shadow( + world: &World, + facts: &BlockFacts, + sprite: Rect, + camera: DVec3, + pos: DVec3, + radius: f32, + strength: f32, + ambient_light: f32, + sky_darken: i32, + out: &mut Vec, +) { + let radius = radius.min(32.0); + if radius <= 0.0 { + return; + } + let dist_sq = pos.distance_squared(camera); + let pow = ((1.0 - dist_sq / 256.0) * f64::from(strength)) as f32; + if pow <= 0.0 { + return; + } + let r = f64::from(radius); + let (x0, x1) = ((pos.x - r).floor() as i32, (pos.x + r).floor() as i32); + let (z0, z1) = ((pos.z - r).floor() as i32, (pos.z + r).floor() as i32); + let depth = (pow / 0.5 - 1.0).min(radius); + let (y0, y1) = ((pos.y - f64::from(depth)).floor() as i32, pos.y.floor() as i32); + for z in z0..=z1 { + for x in x0..=x1 { + for y in y0..=y1 { + let below = facts.get(world.block(x, y - 1, z)); + if below.render_shape == crate::blocks::RenderShape::Invisible || !below.full_collision { + continue; + } + let packed = world.light(x, y, z); + let raw = (i32::from(packed >> 4) - sky_darken).max(i32::from(packed & 15)); + if raw <= 3 { + continue; + } + let power_at_depth = pow - (pos.y - f64::from(y)) as f32 * 0.5; + let alpha = (power_at_depth * 0.5 * crate::screen_effects::lightmap_brightness(ambient_light, raw as u8)).clamp(0.0, 1.0); + // The block top, clipped to the shadow square so the UVs stay inside the sprite. + let (bx0, bx1) = (f64::from(x).max(pos.x - r), f64::from(x + 1).min(pos.x + r)); + let (bz0, bz1) = (f64::from(z).max(pos.z - r), f64::from(z + 1).min(pos.z + r)); + if bx1 <= bx0 || bz1 <= bz0 { + continue; + } + let u = |wx: f64| (-((wx - pos.x) as f32) / 2.0 / radius + 0.5).clamp(0.0, 1.0); + let v = |wz: f64| (-((wz - pos.z) as f32) / 2.0 / radius + 0.5).clamp(0.0, 1.0); + let a = (alpha * 255.0) as u32; + let color = a << 24 | 0x00FF_FFFF; + let top = f64::from(y) + 0.001; + for (wx, wz) in [(bx0, bz0), (bx0, bz1), (bx1, bz1), (bx1, bz0)] { + let p = DVec3::new(wx, top, wz) - camera; + out.push(Vertex { + pos: p.as_vec3().to_array(), + uv: [sprite.u0 + (sprite.u1 - sprite.u0) * u(wx), sprite.v0 + (sprite.v1 - sprite.v0) * v(wz)], + layer: 0, + color, + light: 240 | 240 << 8, + }); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn vanilla_radii() { + assert_eq!(shadow_params("minecraft:zombie"), (0.5, 1.0)); + assert_eq!(shadow_params("minecraft:item"), (0.15, 0.75)); + assert_eq!(shadow_params("minecraft:spider"), (0.8, 1.0)); + } +} diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs new file mode 100644 index 000000000..2d40391f9 --- /dev/null +++ b/crates/horizon-client/src/signs.rs @@ -0,0 +1,179 @@ +//! Sign block entities (`SignBlockEntity`, `SignText`): two four-line text +//! sides with a dye colour and glow, saved in vanilla's `front_text` / +//! `back_text` NBT layout. +use horizon_world::nbt::Tag; + +/// `DyeColor` names and `getTextColor` values by id. +pub const DYE_TEXT: [(&str, u32); 16] = [ + ("white", 0xFFFFFF), + ("orange", 0xFF681F), + ("magenta", 0xFF00FF), + ("light_blue", 0x9AC0CD), + ("yellow", 0xFFFF00), + ("lime", 0xBFFF00), + ("pink", 0xFF69B4), + ("gray", 0x808080), + ("light_gray", 0xD3D3D3), + ("cyan", 0x00FFFF), + ("purple", 0xA020F0), + ("blue", 0x0000FF), + ("brown", 0x8B4513), + ("green", 0x00FF00), + ("red", 0xFF0000), + ("black", 0x000000), +]; +const BLACK: u8 = 15; + +/// One sign side (`SignText`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SignText { + pub lines: [String; 4], + /// `DyeColor` id. + pub color: u8, + pub glowing: bool, +} +impl Default for SignText { + fn default() -> Self { + Self { lines: Default::default(), color: BLACK, glowing: false } + } +} +impl SignText { + pub fn is_empty(&self) -> bool { + self.lines.iter().all(String::is_empty) + } + /// `DyeColor.getTextColor` of this side. + pub fn text_color(&self) -> u32 { + DYE_TEXT[usize::from(self.color.min(15))].1 + } + /// `AbstractSignRenderer.getDarkColor`. + pub fn dark_color(&self) -> u32 { + let c = self.text_color(); + if c == 0 && self.glowing { + 0xF0EBCC + } else { + let s = |shift: u32| ((((c >> shift) & 255) as f32 * 0.4) as u32) << shift; + s(16) | s(8) | s(0) + } + } +} + +/// `SignBlockEntity` / `HangingSignBlockEntity` data. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SignData { + pub hanging: bool, + pub front: SignText, + pub back: SignText, + pub waxed: bool, +} +impl SignData { + pub fn id(&self) -> &'static str { + if self.hanging { "minecraft:hanging_sign" } else { "minecraft:sign" } + } + /// `SignBlockEntity.getMaxTextLineWidth`. + pub fn max_line_width(&self) -> f32 { + if self.hanging { 60.0 } else { 90.0 } + } + /// `SignBlockEntity.getTextLineHeight`. + pub fn line_height(&self) -> f32 { + if self.hanging { 9.0 } else { 10.0 } + } + /// NBT entries after the common block-entity header. + pub fn encode(&self) -> Vec<(&'static str, Tag)> { + let side = |t: &SignText| { + Tag::compound([ + ("messages", Tag::List(t.lines.iter().map(|l| Tag::String(l.as_str().into())).collect())), + ("color", Tag::String(DYE_TEXT[usize::from(t.color.min(15))].0.into())), + ("has_glowing_text", Tag::Byte(i8::from(t.glowing))), + ]) + }; + vec![("front_text", side(&self.front)), ("back_text", side(&self.back)), ("is_waxed", Tag::Byte(i8::from(self.waxed)))] + } + pub fn decode(&mut self, tag: &Tag) { + let side = |t: Option<&Tag>| -> SignText { + let mut out = SignText::default(); + let Some(t) = t else { return out }; + if let Some(Tag::List(messages)) = t.get("messages") { + for (line, m) in out.lines.iter_mut().zip(messages) { + *line = component_text(m); + } + } + if let Some(Tag::String(c)) = t.get("color") { + let name = c.to_string_lossy(); + if let Some(i) = DYE_TEXT.iter().position(|(n, _)| *n == name) { + out.color = i as u8; + } + } + out.glowing = matches!(t.get("has_glowing_text"), Some(Tag::Byte(b)) if *b != 0); + out + }; + self.front = side(tag.get("front_text")); + self.back = side(tag.get("back_text")); + self.waxed = matches!(tag.get("is_waxed"), Some(Tag::Byte(b)) if *b != 0); + } +} +/// Plain text of a stored text component (string, `{text: ...}` or JSON string). +fn component_text(tag: &Tag) -> String { + match tag { + Tag::String(s) => { + let s = s.to_string_lossy(); + match serde_json::from_str::(&s) { + Ok(serde_json::Value::String(text)) => text, + Ok(v) if v.get("text").is_some() => v["text"].as_str().unwrap_or_default().to_owned(), + _ => s, + } + } + Tag::Compound(_) => match tag.get("text") { + Some(Tag::String(t)) => t.to_string_lossy(), + _ => String::new(), + }, + _ => String::new(), + } +} +/// Whether a block name is a sign (standing, wall, hanging or wall hanging). +pub fn sign_kind(name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + if name == "hanging_sign" || name.ends_with("_hanging_sign") { + Some(true) + } else if name == "sign" || name.ends_with("_sign") { + Some(false) + } else { + None + } +} +/// Wood type of a sign block (`SignBlock.getWoodType`), for the editor texture. +pub fn wood_type(name: &str) -> &str { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + for suffix in ["_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign"] { + if let Some(wood) = name.strip_suffix(suffix) { + return wood; + } + } + "oak" +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn round_trips_nbt() { + let mut data = SignData { hanging: false, ..SignData::default() }; + data.front.lines[0] = "Hello".into(); + data.front.color = 14; + data.back.glowing = true; + let tag = Tag::compound(data.encode()); + let mut decoded = SignData::default(); + decoded.decode(&tag); + assert_eq!(decoded, data); + } + #[test] + fn names_and_colors() { + assert_eq!(sign_kind("minecraft:oak_wall_hanging_sign"), Some(true)); + assert_eq!(sign_kind("minecraft:sign"), Some(false)); + assert_eq!(sign_kind("minecraft:spruce_wall_sign"), Some(false)); + assert_eq!(sign_kind("minecraft:stone"), None); + assert_eq!(wood_type("minecraft:dark_oak_wall_sign"), "dark_oak"); + assert_eq!(SignText::default().dark_color(), 0); + let red = SignText { color: 14, ..SignText::default() }; + assert_eq!(red.dark_color(), 0x660000); + } +} diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 406e718fc..02c79db05 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -12,6 +12,8 @@ struct Globals { sunrise: vec4, // xyz: sun direction, w: star brightness sun: vec4, + // x: sky fog end, y: cloud fog end, z: dark disc flag + fog_ends: vec4, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var sprites: texture_2d_array; @@ -67,8 +69,12 @@ fn apply_fog(color: vec4, spherical: f32, cylindrical: f32) -> vec4 { return apply_fog(color, in.spherical, in.cylindrical); } -// Sky: vanilla draws a sky disc in the sky colour and blends towards the fog -// colour at the horizon; sunrise/sunset tints the horizon facing the sun. +// Sky (SkyRenderer): the 10-vertex sky disc fan at y = 16 (radius 512) in +// the sky colour with sky fog (sky.fsh: fog 0..FogSkyEnd on the spherical +// distance, a step at FogSkyEnd on the cylindrical one), evaluated per pixel +// along the view ray with the fan's interpolated vertex distances; the +// clear colour (fog colour) elsewhere; the sunrise/sunset fan blended over +// it; the dark disc (y = -4) below the horizon when the camera is low. struct SkyOut { @builtin(position) clip: vec4, @location(0) ndc: vec2, @@ -80,22 +86,87 @@ struct SkyOut { out.ndc = p; return out; } +fn view_ray(ndc: vec2) -> vec3 { + return normalize((globals.inverse_view * vec4(ndc.x * globals.misc.z * globals.misc.w, + ndc.y * globals.misc.w, -1.0, 0.0)).xyz); +} +const PI: f32 = 3.14159265; +// Interpolated (spherical, cylindrical) distance where the ray meets a disc +// fan at height y, or negative when it misses. +fn disc_distance(d: vec3, y: f32) -> vec2 { + if d.y * y <= 0.0 { return vec2(-1.0); } + let p = d * (y / d.y); + let h = length(p.xz); + let phi = atan2(p.z, p.x); + let sector = PI / 4.0; + let delta = phi - (floor(phi / sector) * sector + sector * 0.5); + let edge = 512.0 * cos(sector * 0.5) / cos(delta); + if h > edge { return vec2(-1.0); } + let s = h / edge; + let ay = abs(y); + let rim = sqrt(512.0 * 512.0 + y * y); + return vec2(ay + s * (rim - ay), ay + s * (512.0 - ay)); +} +fn sky_fog(color: vec3, dist: vec2) -> vec3 { + let end = globals.fog_ends.x; + let f = max(linear_fog(dist.x, 0.0, end), linear_fog(dist.y, end, end)); + return mix(color, globals.fog_color.rgb, f * globals.fog_color.a); +} +fn rotate_x90(v: vec3) -> vec3 { return vec3(v.x, -v.z, v.y); } +// Weight of the fan centre where the ray crosses the sunrise fan (0 when missed). +fn sunrise_weight(d: vec3) -> f32 { + let alpha = globals.sunrise.a; + if alpha <= 0.001 { return 0.0; } + // sin(sunAngle) < 0 flips the fan to the other horizon; sun.z = -sin(sunAngle). + let flip = select(0.0, 180.0, -globals.sun.z < 0.0); + let theta = radians(flip + 90.0); + let c = cos(theta); + let s = sin(theta); + var best = 0.0; + let apex = rotate_x90(vec3(-100.0 * s, 100.0 * c, 0.0)); + for (var i = 0; i < 16; i++) { + let a0 = f32(i) * 2.0 * PI / 16.0; + let a1 = f32(i + 1) * 2.0 * PI / 16.0; + let l0 = vec3(sin(a0) * 120.0, cos(a0) * 120.0, -cos(a0) * 40.0 * alpha); + let l1 = vec3(sin(a1) * 120.0, cos(a1) * 120.0, -cos(a1) * 40.0 * alpha); + let r0 = rotate_x90(vec3(l0.x * c - l0.y * s, l0.x * s + l0.y * c, l0.z)); + let r1 = rotate_x90(vec3(l1.x * c - l1.y * s, l1.x * s + l1.y * c, l1.z)); + // Moller-Trumbore from the origin along d. + let e1 = r0 - apex; + let e2 = r1 - apex; + let pv = cross(d, e2); + let det = dot(e1, pv); + if abs(det) < 1e-6 { continue; } + let tv = -apex; + let u = dot(tv, pv) / det; + let qv = cross(tv, e1); + let v = dot(d, qv) / det; + let t = dot(e2, qv) / det; + if u >= 0.0 && v >= 0.0 && u + v <= 1.0 && t > 0.0 { + best = max(best, 1.0 - u - v); + } + } + return best; +} @fragment fn fs_sky(in: SkyOut) -> @location(0) vec4 { - let view = normalize((globals.inverse_view * vec4(in.ndc.x * globals.misc.z * globals.misc.w, - in.ndc.y * globals.misc.w, -1.0, 0.0)).xyz); - let up = clamp(view.y, -1.0, 1.0); - // Fog band towards the horizon (vanilla sky end distance blending). - let horizon = 1.0 - smoothstep(0.0, 0.35, up); - var color = mix(globals.sky_color.rgb, globals.fog_color.rgb, horizon); - let toward_sun = max(dot(normalize(vec3(view.x, 0.0, view.z) + vec3(0.0001)), normalize(vec3(globals.sun.x, 0.0, globals.sun.z) + vec3(0.0001))), 0.0); - let band = (1.0 - smoothstep(-0.1, 0.4, abs(up))) * pow(toward_sun, 3.0); - color = mix(color, globals.sunrise.rgb, band * globals.sunrise.a); - if up < 0.0 { - // Void below the horizon. - color = mix(color, globals.sky_color.rgb * 0.2, smoothstep(0.0, -0.3, up) * (1.0 - globals.misc.x)); + let d = view_ray(in.ndc); + var color = globals.fog_color.rgb; + let dist = disc_distance(d, 16.0); + if dist.x >= 0.0 { + color = sky_fog(globals.sky_color.rgb, dist); + } + let w = sunrise_weight(d); + if w > 0.0 { + color = mix(color, globals.sunrise.rgb, w * globals.sunrise.a); } return vec4(color, 1.0); } +@fragment fn fs_dark_disc(in: SkyOut) -> @location(0) vec4 { + let d = view_ray(in.ndc); + let dist = disc_distance(d, -4.0); + if dist.x < 0.0 { discard; } + return vec4(sky_fog(vec3(0.0), dist), 1.0); +} struct LineOut { @builtin(position) clip: vec4 } @vertex fn vs_line(@location(0) position: vec3) -> LineOut { diff --git a/crates/horizon-world/src/block_render.rs b/crates/horizon-world/src/block_render.rs index 2d3932c81..1ed9c51af 100644 --- a/crates/horizon-world/src/block_render.rs +++ b/crates/horizon-world/src/block_render.rs @@ -163,6 +163,16 @@ impl FaceVisibility { .get(state.0 as usize) .is_some_and(|s| s.faces[direction as usize] == 1) } + /// The state's occlusion face toward `direction` (`getFaceOcclusionShape`) and + /// its shared ID: 0 is the empty singleton, 1 the full-block singleton. + pub fn occlusion_face( + &self, + state: BlockStateId, + direction: Direction, + ) -> Option<(u32, &VoxelShape)> { + let id = self.states.get(state.0 as usize)?.faces[direction as usize]; + Some((id, &self.faces[id as usize])) + } /// Whether the state's occlusion face toward `direction` is empty. pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool { self.states diff --git a/docs/parity/meshing.md b/docs/parity/meshing.md new file mode 100644 index 000000000..841ca30a3 --- /dev/null +++ b/docs/parity/meshing.md @@ -0,0 +1,128 @@ +# Section meshing parity + +`tools/test_section_mesh_parity.py` compares the vertices Horizon's section +mesher (`crates/horizon-client/src/mesher.rs`, with `mesher/lighting.rs` and +`mesher/fluid.rs`) emits with the vertices the pinned client's own renderers +emit for the same scenes. + +## What is compared + +- **Vanilla side**: `VanillaSectionMeshOracle` bootstraps the game, binds the + prepared block tags, parses the jar's blockstate definitions and block + models, and bakes `BlockStateModel`s through the real `ModelDiscovery`, + `UnbakedRoot.bake` and `FaceBakery` path. Every texture becomes a real sprite + (its PNG from the jar) alone in a unit atlas, so UVs stay in sprite-local + [0,1] space; the five fluid sprites share one strip with gaps so the fluid + vertex stream still identifies them. A fixed `BlockAndTintGetter` serves the + scene's block states, per-cell sky/block light, constant biome colours per + `ColorResolver` and the overworld or Nether `CardinalLighting`. Blocks of one + section are visited like `SectionCompiler.compile`: fluids through + `FluidRenderer.tesselate`, then `RenderShape.MODEL` blocks through + `ModelBlockRenderer.tesselateBlock` with smooth lighting on, culling on, + cutout leaves, `BlockColors.createDefault()` and `state.getSeed(pos)`. +- **Horizon side**: `crates/horizon-client/examples/section_mesh_fixture.rs` + loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`, + `load_visibility`, `MeshTables`), builds the same blocks and light in real + client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the + scene constants and runs `Mesher::mesh`. +- **Comparison**: quads are matched as multisets per scene, keyed by sprite, + render-layer class (translucent vs. solid/cutout) and geometry rounded to + 1/1000 after binary32 normalisation, with a winding-preserving rotation. + Matched quads compare per vertex: positions and UVs within 1e-4, ARGB colour + and light coordinates (sky and block, 1/16 steps) exactly. +- **Per-state facts**: a second gate compares, for all 35,723 states, the facts + the Rust tables derive from prepared resources with the client's accessors: + `getShadeBrightness`, `emissiveRendering`, `isSolid`, `isLightPermeable`, + `isSolidRender`, `isCollisionShapeFullBlock`, light emission, the water + overlay classes (`HalfTransparentBlock`/`LeavesBlock`), tint source counts + and `getOffset` at five columns. + +The corpus (94 sections, ~842k quads, ~206k of them fluid quads) has full +cubes in open air, corners, cavities and overhangs; slabs, stairs, walls, +fences, panes, bars, torches, flowers and grasses with XZ/XYZ offsets, tall +plants, tinted blocks (grass, leaves, stems, redstone, lily pad, petals, leaf +litter, cauldrons), snow layers, carpets, farmland, paths, hoppers, anvils, +chains, lanterns, dripleaf, dripstone; water and lava sources, flowing levels, +falling columns, waterlogged blocks, water against glass/leaves/slabs/ice; +section edges with neighbours in other chunks and sections; a cave with +emissive and light-emitting blocks (magma, glowstone, sea lantern, active +sculk sensor, glow lichen); Nether shading; every block's default state; every +`RenderShape.MODEL` state of the registry on a sparse grid; and dense random +scenes mixing all model states with fluids under propagated or random light. + +## Running + +```sh +python3 tools/test_section_mesh_parity.py # full corpus +python3 tools/test_section_mesh_parity.py --quick # skip the all-states catalogue +python3 tools/test_section_mesh_parity.py --strict # exit 1 on any difference +python3 tools/test_section_mesh_parity.py --only fluids +``` + +It needs the pinned jars (`tools/lab.py prepare`) and prepared client resources +(`tools/prepare_native_client.py --prepare`). Outputs, logs and +`report.json` go to `target/section-mesh-parity/`; nothing is written under +`.local/`. The fixture is built with `--profile fast` and reports its +meshing time. + +## Results + +Before the port (commit `2940b5a`, first 18 scenes): 25,391 of 55,017 vanilla +quads identical (46%); 7,685 fluid quads missing, 9,231 extra quads, and +light/colour differences on most of the rest. + +After: all 841,775 quads of the 94 scenes match and are identical, and all +per-state facts match. Meshing cost is unchanged within noise: the fixture +meshes the 94 (dense) corpus sections in about 3 ms each with both the old and +the ported mesher (`--profile fast`, loaded 24-thread desktop). + +What was ported to get there: + +- `BlockModelLighter`: quad shape (`faceCubic`/`facePartial`), the corner, + diagonal and centre samples (diagonals only through light-permeable blocks, + the centre from the neighbour unless it is solid-render), shade brightness + overrides, emissive full-bright samples, `smoothBlend` (zero samples take the + centre, sky-less samples borrow its sky, only when the centre is above 2), + the partial-face weights with `smoothWeightedBlend`'s int narrowing, and the + vertex remap. The padded section border grew to two blocks because cubic + faces sample two blocks out along their normal. +- `ModelBlockRenderer`: flat lighting for light-emitting blocks or when the + first model part disables AO (culled quads read light from the cull + neighbour, others from the neighbour only when flush), `ARGB.gray`/ + `scaleRGB`/`multiply` integer arithmetic, cardinal shading including + `NETHER`, shade-direction overrides, per-element light emission, tint source + counts (layer indices past the list are untinted; water and bubble columns + are untinted in the world) and `getOffset` for XZ/XYZ blocks. +- `FluidRenderer`: face culling against the neighbour's occlusion face shape + for the fluid box height, self occlusion, `isSolid` corner heights, the + weighted corner averages in vanilla order, the 0.001 insets (also feeding the + side faces), `FlowingFluid.getFlow` with `Mth.atan2` and the sine table, the + water overlay beside half-transparent and leaf blocks, back faces, + `max(self, above)` light, bottom light from below, and cardinal shading. +- `UnbakedCuboidGeometry.bake`: elements flat along an axis draw no faces + across it (`bake_block_model` in horizon-assets; the raw + `bake_model_transformed` used by the model-baking gate is unchanged). + +Exported facts used: `block-behaviours.json` (class chains, `isSolid`, full +face sturdiness), `gameplay-facts.json` (`offset` flag, emission, shapes), +the `#minecraft:blocks_fluid_flow` tag and the occlusion faces already loaded +for face visibility. Offset types and maximum offsets, shade-brightness and +emissive overrides are keyed by class or block name and checked by the facts +gate. + +## What remains different or untested + +- Biome tint blending: vanilla blends `BiomeManager`'s zoomed biome at each + block's own height; Horizon blends its quart biome cells at the section's + mid-height. The gate uses one constant colour per resolver, so this is not + compared. +- Model variant seeds: `DoublePlantBlock`, `DoorBlock` and `AbstractBedBlock` + override `getSeed`; Horizon seeds every block from its own position. No + vanilla block among those has weighted variants, so output is unaffected. +- Settings: only smooth lighting on and cutout ("fancy") leaves are covered; + Horizon has no flat-lighting or opaque-leaves modes. +- Layers: vanilla's solid and cutout layers are compared as one class because + Horizon draws both in its opaque pass. +- Not compared: block entities and their renderers, animated sprite frames, + translucent sorting, chunk-border light outside loaded chunks and GPU + pixels. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java new file mode 100644 index 000000000..548275cbe --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java @@ -0,0 +1,297 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.vertex.QuadInstance; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import net.minecraft.client.color.block.BlockColors; +import net.minecraft.client.renderer.BiomeColors; +import net.minecraft.client.renderer.block.*; +import net.minecraft.client.renderer.block.dispatch.*; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.client.renderer.texture.*; +import net.minecraft.client.resources.metadata.animation.FrameSize; +import net.minecraft.client.resources.model.*; +import net.minecraft.client.resources.model.cuboid.*; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.sprite.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.util.StrictJsonParser; +import net.minecraft.world.level.CardinalLighting; +import net.minecraft.world.level.ColorResolver; +import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.lighting.LevelLightEngine; +import net.minecraft.world.level.material.FluidState; +import org.joml.Vector3fc; +import static dev.horizonlab.parity.VanillaCuboidModelOracle.map; + +/** Runs the client's own ModelBlockRenderer (smooth lighting on) and FluidRenderer + * over small fixed scenes, the way SectionCompiler visits one section, and + * records every emitted vertex. Block models are baked from the jar's own + * blockstate and model resources; every texture becomes a real sprite alone in + * a unit atlas so UVs stay in sprite-local [0,1] space. Fluid sprites share one + * strip with gaps so their vertex stream still identifies the sprite. */ +public final class VanillaSectionMeshOracle { + private static final Gson JSON = new GsonBuilder().serializeNulls().create(); + private static final String[] FLUID_SPRITES = {"minecraft:block/water_still", "minecraft:block/water_flow", + "minecraft:block/water_overlay", "minecraft:block/lava_still", "minecraft:block/lava_flow"}; + private static final int STRIP = 2 * FLUID_SPRITES.length; + + private static final class Sprite extends TextureAtlasSprite { + Sprite(SpriteContents contents, int slots, int slot) { + super(TextureAtlas.LOCATION_BLOCKS, contents, contents.width() * slots, contents.height(), contents.width() * slot, 0, 0); + } + } + private static final Map SPRITES = new HashMap<>(); + private static SpriteContents contents(Identifier id) throws IOException { + var path = "/assets/" + id.getNamespace() + "/textures/" + id.getPath() + ".png"; + try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) { + NativeImage image = input == null ? new NativeImage(16, 16, true) : NativeImage.read(input); + int size = Math.min(image.getWidth(), image.getHeight()); + return new SpriteContents(id, new FrameSize(image.getWidth(), size), image); + } + } + private static TextureAtlasSprite sprite(Identifier id) { + return SPRITES.computeIfAbsent(id, key -> { + try { + int slot = Arrays.asList(FLUID_SPRITES).indexOf(key.toString()); + return slot < 0 ? new Sprite(contents(key), 1, 0) : new Sprite(contents(key), STRIP, 2 * slot); + } catch (IOException error) { throw new UncheckedIOException(error); } + }); + } + /** Hands out the unit-atlas sprite named by each material. */ + private static final class Materials extends MaterialBaker { + Materials(SpriteLoader.Preparations atlas) { super(atlas, atlas); } + @Override public Material.Baked get(Material material, ModelDebugName name) { + return new Material.Baked(sprite(material.sprite()), material.forceTranslucent()); + } + } + private static final class Baker implements ModelBaker { + final Map resolved; final ResolvedModel missing; final MaterialBaker materials; + final Map, Object> cache = new HashMap<>(); + Baker(Map resolved, ResolvedModel missing, MaterialBaker materials) { + this.resolved = resolved; this.missing = missing; this.materials = materials; + } + public ResolvedModel getModel(Identifier id) { return resolved.getOrDefault(id, missing); } + public BlockStateModelPart missingBlockModelPart() { throw new AssertionError("missing block model part"); } + public MaterialBaker materials() { return materials; } + public ModelBaker.Interner interner() { + return new ModelBaker.Interner() { + public Vector3fc vector(Vector3fc vector) { return vector; } + public BakedQuad.MaterialInfo materialInfo(BakedQuad.MaterialInfo value) { return value; } + }; + } + @SuppressWarnings("unchecked") + public T compute(SharedOperationKey key) { + var value = cache.get(key); + if (value == null) { value = key.compute(this); cache.put(key, value); } + return (T) value; + } + } + private static String resource(String path) throws IOException { + try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) { + return input == null ? null : new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + } + /** Real blockstate definitions and models for the requested blocks. */ + private static final class Models { + final Map roots = new HashMap<>(); + final Map baked = new HashMap<>(); + final Baker baker; + Models(Set blocks, MaterialBaker materials) throws IOException { + var unbaked = new HashMap(); + for (var block : blocks) { + var id = BuiltInRegistries.BLOCK.getKey(block); + var raw = resource("/assets/" + id.getNamespace() + "/blockstates/" + id.getPath() + ".json"); + if (raw == null) continue; + var definition = BlockStateModelDispatcher.CODEC.parse(JsonOps.INSTANCE, StrictJsonParser.parse(raw)).getOrThrow(); + roots.putAll(definition.instantiate(block.getStateDefinition(), id::toString)); + } + var pending = new ArrayList(); + for (var root : new HashSet<>(roots.values())) root.resolveDependencies(pending::add); + for (int i = 0; i < pending.size(); i++) { + var id = pending.get(i); + if (unbaked.containsKey(id)) continue; + var raw = resource("/assets/" + id.getNamespace() + "/models/" + id.getPath() + ".json"); + if (raw == null) continue; + var model = CuboidModel.fromStream(new StringReader(raw)); + unbaked.put(id, model); + if (model.parent() != null) pending.add(model.parent()); + } + var discovery = new ModelDiscovery(unbaked, MissingCuboidModel.missingModel()); + discovery.addRoot(resolver -> { for (var id : unbaked.keySet()) resolver.markDependency(id); }); + var resolved = discovery.resolve(); + baker = new Baker(resolved, discovery.missingModel(), materials); + } + BlockStateModel get(BlockState state) { + return baked.computeIfAbsent(state, s -> Objects.requireNonNull(roots.get(s), () -> "no model for " + s).bake(s, baker)); + } + } + private static long key(int x, int y, int z) { return BlockPos.asLong(x, y, z); } + /** A fixed region: listed blocks over air, listed light over a default. */ + private static final class Scene implements BlockAndTintGetter { + final Map blocks = new HashMap<>(); + final Map light = new HashMap<>(); + int[] defaultLight; boolean nether; int grass, foliage, dry, water; + public CardinalLighting cardinalLighting() { return nether ? CardinalLighting.NETHER : CardinalLighting.DEFAULT; } + public LevelLightEngine getLightEngine() { return LevelLightEngine.EMPTY; } + public int getBrightness(LightLayer layer, BlockPos pos) { + var value = light.getOrDefault(pos.asLong(), defaultLight); + return layer == LightLayer.SKY ? value[0] : value[1]; + } + public int getBlockTint(BlockPos pos, ColorResolver resolver) { + int rgb = resolver == BiomeColors.GRASS_COLOR_RESOLVER ? grass : resolver == BiomeColors.FOLIAGE_COLOR_RESOLVER ? foliage + : resolver == BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER ? dry : resolver == BiomeColors.WATER_COLOR_RESOLVER ? water : -1; + if (rgb == -1) throw new AssertionError("unexpected colour resolver"); + return 0xFF000000 | rgb; + } + public BlockEntity getBlockEntity(BlockPos pos) { return null; } + public BlockState getBlockState(BlockPos pos) { return blocks.getOrDefault(pos.asLong(), Blocks.AIR.defaultBlockState()); } + public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } + public int getHeight() { return 384; } + public int getMinY() { return -64; } + } + private static final class Recorder { + final List quads = new ArrayList<>(); + List pending; BlockPos block; String kind, layer, sprite; + void vertex(float x, float y, float z, int color, float u, float v, int light) { + if (pending == null) pending = new ArrayList<>(); + pending.add(new Object[]{x, y, z, u, v, color, light}); + if (pending.size() == 4) { + quads.add(map("block", new int[]{block.getX(), block.getY(), block.getZ()}, "kind", kind, "layer", layer, "sprite", sprite, "vertices", pending)); + pending = null; + } + } + } + private static String layer(ChunkSectionLayer layer) { return layer.name().toLowerCase(Locale.ROOT); } + private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids) { + var scene = new Scene(); + var light = row.getAsJsonArray("light"); + scene.defaultLight = new int[]{light.get(0).getAsInt(), light.get(1).getAsInt()}; + scene.nether = row.get("nether").getAsBoolean(); + var colors = row.getAsJsonObject("colors"); + scene.grass = colors.get("grass").getAsInt(); scene.foliage = colors.get("foliage").getAsInt(); + scene.dry = colors.get("dry_foliage").getAsInt(); scene.water = colors.get("water").getAsInt(); + for (var item : row.getAsJsonArray("blocks")) { + var b = item.getAsJsonArray(); + scene.blocks.put(key(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt()), Block.stateById(b.get(3).getAsInt())); + } + for (var item : row.getAsJsonArray("lights")) { + var l = item.getAsJsonArray(); + scene.light.put(key(l.get(0).getAsInt(), l.get(1).getAsInt(), l.get(2).getAsInt()), new int[]{l.get(3).getAsInt(), l.get(4).getAsInt()}); + } + var recorder = new Recorder(); + BlockModelLighter.enableCaching(); + var renderer = new ModelBlockRenderer(true, true, BlockColors.createDefault()); + var fluidRenderer = new FluidRenderer(fluids); + BlockQuadOutput output = (x, y, z, quad, instance) -> { + recorder.kind = "model"; recorder.layer = layer(quad.materialInfo().layer()); + recorder.sprite = quad.materialInfo().sprite().contents().name().toString(); + int emission = quad.materialInfo().lightEmission(); + int slot = Arrays.asList(FLUID_SPRITES).indexOf(recorder.sprite); + for (int i = 0; i < 4; i++) { + var p = quad.position(i); long uv = quad.packedUV(i); + float u = Float.intBitsToFloat((int) (uv >>> 32)); + recorder.vertex(p.x() + x, p.y() + y, p.z() + z, instance.getColor(i), + slot < 0 ? u : u * STRIP - 2 * slot, Float.intBitsToFloat((int) uv), instance.getLightCoordsWithEmission(i, emission)); + } + }; + int baseY = row.get("section_y").getAsInt() * 16; + for (var pos : BlockPos.betweenClosed(0, baseY, 0, 15, baseY + 15, 15)) { + var state = scene.getBlockState(pos); + if (state.isAir()) continue; + recorder.block = pos.immutable(); + var fluid = state.getFluidState(); + if (!fluid.isEmpty()) { + fluidRenderer.tesselate(scene, pos, sectionLayer -> new VertexConsumer() { + public void addVertex(float x, float y, float z, int color, float u, float v, int overlay, int light, float nx, float ny, float nz) { + int slot = (int) Math.floor(u * STRIP / 2.0f); + recorder.kind = "fluid"; recorder.layer = layer(sectionLayer); recorder.sprite = FLUID_SPRITES[slot]; + recorder.vertex(x, y, z, color, u * STRIP - 2 * slot, v, light); + } + public VertexConsumer addVertex(float x, float y, float z) { throw new AssertionError(); } + public VertexConsumer setColor(int r, int g, int b, int a) { throw new AssertionError(); } + public VertexConsumer setColor(int color) { throw new AssertionError(); } + public VertexConsumer setUv(float u, float v) { throw new AssertionError(); } + public VertexConsumer setUv1(int u, int v) { throw new AssertionError(); } + public VertexConsumer setUv2(int u, int v) { throw new AssertionError(); } + public VertexConsumer setUv3(float u, float v) { throw new AssertionError(); } + public VertexConsumer setNormal(float x, float y, float z) { throw new AssertionError(); } + public VertexConsumer setLineWidth(float width) { throw new AssertionError(); } + }, state, fluid); + } + if (state.getRenderShape() == RenderShape.MODEL) { + renderer.tesselateBlock(ModelBlockRenderer.forceOpaque(true, state) ? (x, y, z, quad, instance) -> { + throw new AssertionError("cutout leaves are enabled"); + } : output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()), + scene, pos, state, models.get(state), state.getSeed(pos)); + } + } + BlockModelLighter.clearCache(); + if (recorder.pending != null) throw new AssertionError("partial quad"); + return map("name", row.get("name").getAsString(), "quads", recorder.quads); + } + private static BlockColors COLORS; + /** Per-state facts the Rust mesher derives from prepared resources. */ + private static Object facts(BlockState state, int id) { + var level = EmptyBlockGetter.INSTANCE; + var offsets = new ArrayList(); + if (state.hasOffsetFunction()) { + for (var p : new BlockPos[]{new BlockPos(0, 0, 0), new BlockPos(5, 7, -3), new BlockPos(-17, 70, 31), new BlockPos(123, -40, -456), new BlockPos(9, 1, 2)}) { + var o = state.getOffset(p); + offsets.add(new double[]{o.x, o.y, o.z}); + } + } + var block = state.getBlock(); + return map("id", id, "shade", state.getShadeBrightness(level, BlockPos.ZERO), "emissive", state.emissiveRendering(), + "legacy_solid", state.isSolid(), "light_permeable", state.isLightPermeable(), "solid_render", state.isSolidRender(), + "full_collision", state.isCollisionShapeFullBlock(level, BlockPos.ZERO), "emission", state.getLightEmission(), + "overlay", block instanceof HalfTransparentBlock || block instanceof LeavesBlock, + "tint_sources", COLORS.getTintSources(state).size(), "offsets", offsets); + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject()); + LeavesBlock.setCutoutLeaves(true); + COLORS = BlockColors.createDefault(); + if (args[0].equals("facts")) { + try (var output = Files.newBufferedWriter(Path.of(args[1]))) { + int id = 0; + for (var state : Block.BLOCK_STATE_REGISTRY) { + if (Block.getId(state) != id) throw new AssertionError("state registry order"); + output.write(JSON.toJson(facts(state, id++))); output.newLine(); + } + } + return; + } + var rows = new ArrayList(); + try (var input = Files.newBufferedReader(Path.of(args[0]))) { + for (String line; (line = input.readLine()) != null; ) rows.add(JsonParser.parseString(line).getAsJsonObject()); + } + var blocks = new HashSet(); + for (var row : rows) for (var item : row.getAsJsonArray("blocks")) blocks.add(Block.stateById(item.getAsJsonArray().get(3).getAsInt()).getBlock()); + var missingContents = new SpriteContents(Identifier.parse("minecraft:missingno"), new FrameSize(16, 16), new NativeImage(16, 16, true)); + var missing = new Sprite(missingContents, 1, 0); + var atlas = new SpriteLoader.Preparations(16, 16, 0, missing, Map.of(), CompletableFuture.completedFuture(null)); + var materials = new Materials(atlas); + var models = new Models(blocks, materials); + var fluidModels = FluidStateModelSet.bake(materials); + var fluids = new FluidStateModelSet(fluidModels, fluidModels.values().iterator().next()); + try (var output = Files.newBufferedWriter(Path.of(args[1]))) { + for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids))); output.newLine(); } + } + } +} diff --git a/tools/test_section_mesh_parity.py b/tools/test_section_mesh_parity.py new file mode 100644 index 000000000..629696cd5 --- /dev/null +++ b/tools/test_section_mesh_parity.py @@ -0,0 +1,488 @@ +#!/usr/bin/env python3 +"""Compare Horizon's section mesher with the client's own ModelBlockRenderer and FluidRenderer. + +Both sides mesh the same scenes (block states by registry ID, per-cell sky/block +light, constant biome colours, overworld or Nether cardinal lighting). The Java +oracle runs vanilla smooth lighting (AO on, cutout leaves) block by block the way +SectionCompiler visits a section; the Rust fixture runs ``Mesher::mesh`` on real +client chunks. Quads are compared as multisets keyed by sprite, render layer class +and rounded geometry; matched quads then compare UVs, ARGB colours and light +coordinates per vertex. A second gate compares the per-state facts the Rust mesher +derives (shade brightness, emissive rendering, legacy solidity, offsets, ...) +with the client's own state accessors for every registry state. +""" +import argparse +from collections import Counter, defaultdict +import json +import math +import os +from pathlib import Path +import platform +import random +import struct +import subprocess +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab + import test_rust_parity as base + import test_model_baking_parity as baking + +BUILD = lab.ROOT / 'target/section-mesh-parity' +SECTION_Y = 0 +COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4} +POSITION_TOLERANCE = 1e-4 +UV_TOLERANCE = 1e-4 + + +class States: + """Registry state IDs by name and properties, from the prepared registry facts.""" + def __init__(self, resources): + facts = json.loads((resources / 'facts.json').read_text()) + self.defaults = facts['defaults'] + self.properties = [entry[4].get('properties', {}) for entry in facts['states']] + self.names = [entry[0] for entry in facts['states']] + self.by_name = defaultdict(list) + for index, name in enumerate(self.names): + self.by_name[name].append(index) + gameplay = json.loads((resources / 'gameplay-facts.json').read_text())['states'] + self.dampening = [s['dampening'] for s in gameplay] + self.emission = [s['emission'] for s in gameplay] + self.opaque = [s['solid_render'] for s in gameplay] + self.render_shape = [s['render_shape'] for s in gameplay] + + def __call__(self, name, **properties): + name = name if ':' in name else 'minecraft:' + name + wanted = dict(self.properties[self.defaults[name]]) + for key, value in properties.items(): + key = key.rstrip('_') + if key not in wanted: + raise KeyError(f'{name} has no property {key}') + wanted[key] = str(value).lower() + for index in self.by_name[name]: + if self.properties[index] == wanted: + return index + raise KeyError(f'no state {name} {wanted}') + + +class Scene: + def __init__(self, states, name, nether=False): + self.states, self.name, self.nether = states, name, nether + self.blocks = {} + self.light_override = {} + self.noise = None + + def put(self, x, y, z, name, **properties): + self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties) + + def fill(self, x0, y0, z0, x1, y1, z1, name, **properties): + state = self.states(name, **properties) + for x in range(x0, x1 + 1): + for y in range(y0, y1 + 1): + for z in range(z0, z1 + 1): + self.blocks[(x, y, z)] = state + + def floor(self, y=3, name='stone'): + self.fill(-1, y, -1, 16, y, 16, name) + + def lights(self): + """Simple deterministic propagation: straight-down skylight, -1 per step + sideways, dampening per cell; emitters spread block light the same way.""" + lo, hi = -2, 17 + base = SECTION_Y * 16 + cells = [(x, y, z) for x in range(lo, hi + 1) for y in range(base + lo, base + hi + 1) for z in range(lo, hi + 1)] + damp = {c: self.states.dampening[self.blocks.get(c, 0)] for c in cells} + opaque = {c: self.states.opaque[self.blocks.get(c, 0)] and damp[c] > 0 for c in cells} + def spread(seeds, straight_down): + level = {c: 0 for c in cells} + queue = [] + for c, v in seeds: + if v > level[c]: + level[c] = v + queue.append(c) + while queue: + nxt = [] + for c in queue: + v = level[c] + for d in [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]: + n = (c[0] + d[0], c[1] + d[1], c[2] + d[2]) + if n not in level or opaque[n]: + continue + loss = 0 if straight_down and d == (0, -1, 0) and v == 15 and damp[n] == 0 else 1 + w = v - loss - damp[n] + if w > level[n]: + level[n] = w + nxt.append(n) + queue = nxt + return level + top = base + hi + sky = spread([((x, top, z), 15) for x in range(lo, hi + 1) for z in range(lo, hi + 1) if not opaque[(x, top, z)]], True) + block = spread([(c, self.states.emission[self.blocks.get(c, 0)]) for c in cells], False) + rng = random.Random(self.noise) if self.noise is not None else None + result = [] + for c in cells: + s, b = sky[c], block[c] + if rng is not None: + s, b = rng.randrange(16), rng.randrange(16) + s, b = self.light_override.get(c, (s, b)) + if (s, b) != (15, 0): + result.append([*c, s, b]) + return result + + def row(self): + return {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0], + 'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()} + + +def corpus(states, full=True): + scenes = [] + def scene(name, **kwargs): + s = Scene(states, name, **kwargs) + scenes.append(s) + return s + # Full cubes: open air, corners, cavities, overhangs and steps for AO. + s = scene('cubes_open') + s.put(8, 8, 8, 'stone') + s.put(3, 3, 3, 'grass_block') + s = scene('cubes_corners') + s.floor(3) + s.fill(0, 4, 0, 15, 7, 0, 'stone') + s.fill(0, 4, 0, 0, 7, 15, 'cobblestone') + s.fill(4, 4, 4, 6, 4, 6, 'oak_planks') + s.put(5, 5, 5, 'stone') + s.fill(9, 4, 9, 12, 6, 12, 'stone') + s.put(10, 6, 10, 'air') + s.put(11, 5, 10, 'air') + s.put(10, 5, 10, 'air') + s.fill(2, 8, 2, 6, 8, 6, 'stone') + s.put(13, 4, 2, 'glass') + s.put(13, 4, 3, 'stone') + s.put(14, 4, 2, 'oak_leaves') + s.put(14, 5, 2, 'grass_block') + s.put(12, 4, 14, 'soul_sand') + s.put(13, 4, 14, 'mud') + s.put(14, 4, 14, 'barrier') + s.put(12, 5, 14, 'grass_block') + s.put(13, 5, 14, 'grass_block') + s.put(14, 5, 14, 'snow', layers=8) + s.put(15, 5, 14, 'snow', layers=4) + s = scene('cave') + s.fill(-1, 0, -1, 16, 15, 16, 'stone') + s.fill(2, 3, 2, 13, 9, 13, 'air') + s.fill(5, 3, 5, 9, 3, 9, 'water') + s.put(4, 4, 4, 'torch') + s.put(12, 3, 12, 'glowstone') + s.put(3, 3, 12, 'magma_block') + s.put(12, 3, 3, 'sea_lantern') + s.put(7, 9, 7, 'shroomlight') + s.put(10, 4, 4, 'lantern') + s.put(2, 5, 7, 'wall_torch', facing='east') + s.put(6, 4, 11, 'redstone_wire', power=15) + s.put(7, 4, 11, 'redstone_wire', power=7) + s.put(8, 4, 11, 'redstone_wire', power=0) + s.put(6, 3, 11, 'stone') + s.put(9, 4, 12, 'sculk_sensor', sculk_sensor_phase='active') + s.put(10, 4, 12, 'sculk_sensor') + s.put(11, 4, 12, 'glow_lichen', down=True) + # Shapes on a floor, against walls and in the open. + s = scene('shapes') + s.floor(3) + s.fill(-1, 4, 15, 16, 7, 16, 'stone') + x = 0 + for name, props in [('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}), + ('oak_stairs', {}), ('oak_stairs', {'facing': 'east', 'half': 'top'}), ('oak_stairs', {'shape': 'inner_left'}), + ('oak_stairs', {'facing': 'south', 'shape': 'outer_right'}), ('cobblestone_wall', {'north': 'low', 'up': True}), + ('oak_fence', {'north': True, 'east': True}), ('glass_pane', {'north': True, 'south': True}), + ('iron_bars', {'east': True, 'west': True}), ('torch', {}), ('poppy', {}), ('dandelion', {}), + ('short_grass', {}), ('fern', {})]: + s.put(x, 4, 7, name, **props) + s.put(x, 4, 14, name, **props) + x += 1 + x = 0 + for name, props in [('tall_grass', {'half': 'lower'}), ('large_fern', {'half': 'lower'}), ('sunflower', {'half': 'lower'}), + ('grass_block', {}), ('oak_leaves', {}), ('spruce_leaves', {}), ('birch_leaves', {}), ('snow', {'layers': 1}), + ('snow', {'layers': 7}), ('white_carpet', {}), ('farmland', {}), ('dirt_path', {}), ('cauldron', {}), + ('water_cauldron', {'level': 3}), ('hopper', {}), ('anvil', {})]: + s.put(x, 4, 4, name, **props) + if name in ('tall_grass', 'large_fern', 'sunflower'): + s.put(x, 5, 4, name, half='upper') + x += 1 + x = 0 + for name, props in [('iron_chain', {}), ('iron_chain', {'axis': 'x'}), ('lantern', {}), ('lantern', {'hanging': True}), + ('soul_lantern', {}), ('lily_pad', {}), ('vine', {'north': True}), ('sugar_cane', {}), ('pink_petals', {'flower_amount': 4}), + ('melon_stem', {'age': 5}), ('attached_pumpkin_stem', {}), ('leaf_litter', {'segment_amount': 3}), + ('small_dripleaf', {}), ('pointed_dripstone', {}), ('bamboo', {}), ('brewing_stand', {})]: + s.put(x, 4, 10, name, **props) + x += 1 + s.put(15, 8, 10, 'stone') + s.put(3, 7, 10, 'stone') + s.put(2, 5, 10, 'stone') + s.put(15, 4, 1, 'scaffolding') + # Fluids: sources, flowing levels, falling columns, mixed neighbours, waterlogging. + s = scene('fluids') + s.floor(2) + s.fill(0, 3, 0, 4, 3, 4, 'water') + for i, level in enumerate([1, 2, 3, 4, 5, 6, 7]): + s.put(5 + i, 3, 2, 'water', level=level) + s.put(5 + i, 3, 3, 'water', level=8 - level) + s.put(5 + i, 3, 6, 'lava', level=level) + s.put(2, 4, 2, 'water', level=8) + s.put(2, 5, 2, 'water', level=8) + s.put(13, 3, 3, 'glass') + s.put(12, 4, 3, 'oak_leaves') + s.put(4, 4, 4, 'stone_slab', type='bottom', waterlogged=True) + s.put(4, 4, 3, 'oak_stairs', waterlogged=True) + s.put(3, 4, 4, 'oak_fence', waterlogged=True) + s.put(1, 4, 1, 'ice') + s.fill(0, 3, 8, 3, 3, 11, 'lava') + s.put(1, 4, 9, 'lava', level=8) + s.put(2, 4, 10, 'stone') + s.fill(8, 3, 9, 12, 5, 13, 'water') + s.put(10, 6, 11, 'water', level=3) + s.put(9, 6, 11, 'oak_slab', type='top') + s.put(11, 6, 11, 'glass') + s.put(10, 6, 12, 'stone') + s.put(13, 4, 11, 'kelp') + s.put(14, 3, 11, 'seagrass') + s.put(15, 3, 13, 'water', level=2) + s.put(15, 4, 14, 'water', level=9) + s.put(15, 3, 15, 'stone_slab', type='top') + # Section edges with neighbours in other chunks and sections. + s = scene('edges') + for x in [0, 15]: + for y in [0, 15]: + for z in [0, 15]: + s.put(x, y, z, 'stone') + s.put(x + (-1 if x == 0 else 1), y, z, 'stone') + s.put(x, y + (-1 if y == 0 else 1), z, 'dirt') + s.put(7, 15, 7, 'water') + s.put(7, 16, 7, 'water') + s.put(8, 0, 8, 'water', level=3) + s.put(8, -1, 8, 'stone') + s.put(-1, 7, 7, 'water') + s.put(0, 7, 7, 'water', level=2) + s.put(16, 7, 7, 'oak_leaves') + s.put(15, 7, 7, 'oak_leaves') + # Every block with a model, default state, on a sparse grid. + model_blocks = sorted(name for name, default in states.defaults.items() if states.render_shape[default] == 'MODEL' + and name not in ('minecraft:air', 'minecraft:cave_air', 'minecraft:void_air')) + per_scene = 8 * 8 * 8 + for chunk in range(0, len(model_blocks), per_scene): + s = scene(f'catalog_{chunk // per_scene}') + for i, name in enumerate(model_blocks[chunk:chunk + per_scene]): + s.put(i % 8 * 2, i // 64 * 2, i // 8 % 8 * 2, states.defaults[name]) + # Every model state (rotations, multipart, UV lock, waterlogging) on a sparse grid. + air = {'minecraft:air', 'minecraft:cave_air', 'minecraft:void_air'} + model_states = [i for i, name in enumerate(states.names) if states.render_shape[i] == 'MODEL' and name not in air] + if full: + for chunk in range(0, len(model_states), per_scene): + s = scene(f'states_{chunk // per_scene}') + for i, state in enumerate(model_states[chunk:chunk + per_scene]): + s.put(i % 8 * 2, i // 64 * 2, i // 8 % 8 * 2, state) + # Dense random states from the whole registry packed against each other and fluids. + fluids = [states('water'), states('lava'), states('water', level=3), states('water', level=9), states('lava', level=4)] + for seed in range(6 if full else 2): + rng = random.Random(0x44454E53 + seed) + s = scene(f'dense_{seed}', nether=seed == 5) + for x in range(-1, 17): + for y in range(-1, 17): + for z in range(-1, 17): + roll = rng.random() + if roll < 0.45: + s.put(x, y, z, rng.choice(model_states)) + elif roll < 0.6: + s.put(x, y, z, rng.choice(fluids)) + if seed % 2: + s.noise = seed + # Random dense scenes over a palette, with structured and noisy light. + palette = ['stone', 'glass', 'oak_leaves', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy', + 'short_grass', 'glowstone', 'oak_fence', 'snow', 'white_carpet', 'magma_block', 'soul_sand', 'ice', 'farmland', 'dirt_path'] + for seed in range(8): + rng = random.Random(0x4D455348 + seed) + s = scene(f'random_{seed}', nether=seed % 4 == 3) + for _ in range(900): + name = rng.choice(palette) + ids = states.by_name['minecraft:' + name] + s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids)) + if seed % 2: + s.noise = seed + s = scene('cubes_nether', nether=True) + s.floor(3, 'netherrack') + s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks') + s.fill(8, 4, 8, 10, 4, 10, 'lava') + s.put(12, 4, 12, 'glowstone') + return scenes + + +def f32(value): + """Both sides emit binary32 values; Java prints them shortest-form, so parse back to the same float.""" + return struct.unpack('> 16 & 255, color >> 8 & 255, color & 255, color >> 24] + + +def light(coords): + return [coords >> 16 & 0xFFFF, coords & 0xFFFF] + + +def compare(scene, client, rust, states, report, limit): + blocks = {tuple(b[:3]): b[3] for b in scene['blocks']} + def describe(quad, rotation): + v = quad['vertices'] + centre = [sum(p[i] for p in v) / 4 for i in range(3)] + block = quad.get('block') or [math.floor(c + 1e-4 if i != 1 else c - 1e-3) for i, c in enumerate(centre)] + state = blocks.get(tuple(block), 0) + return {'block': block, 'state': f"{states.names[state]}{states.properties[state] or ''}", + 'sprite': quad['sprite'], 'kind': quad.get('kind', 'rust'), + 'vertices': [list(x) for x in (v[rotation:] + v[:rotation])]} + groups = defaultdict(lambda: ([], [])) + for side, quads in [(0, client), (1, rust)]: + for quad in quads: + key, rotation = quad_key(quad) + groups[key][side].append((quad, rotation)) + counts = Counter() + def add(category, *examples): + counts[category] += 1 + report['categories'][category] = report['categories'].get(category, 0) + 1 + bucket = report['examples'].setdefault(category, []) + if len(bucket) < limit: + bucket.append({'scene': scene['name'], 'quads': list(examples)}) + def attributes(entry): + quad, rotation = entry + v = quad['vertices'] + return str([(round(x[3], 3), round(x[4], 3), channels(x[5]), light(x[6])) for x in v[rotation:] + v[:rotation]]) + for key, (left, right) in groups.items(): + # Coincident quads (back faces, overlapping elements) pair up by their attributes. + left.sort(key=attributes) + right.sort(key=attributes) + for a, b in zip(left, right): + report['matched_quads'] += 1 + ca = a[0]['vertices'][a[1]:] + a[0]['vertices'][:a[1]] + cb = b[0]['vertices'][b[1]:] + b[0]['vertices'][:b[1]] + problems = set() + for p, q in zip(ca, cb): + if any(abs(p[i] - q[i]) > POSITION_TOLERANCE for i in range(3)): + problems.add('position') + if any(abs(p[i] - q[i]) > UV_TOLERANCE for i in (3, 4)): + problems.add('uv') + cp, cq = channels(p[5]), channels(q[5]) + if cp != cq: + problems.add('color' if max(abs(x - y) for x, y in zip(cp, cq)) > 1 else 'color_rounding') + if light(p[6]) != light(q[6]): + lp, lq = light(p[6]), light(q[6]) + problems.add('light_sky' if lp[0] != lq[0] else 'light_block') + if not problems: + report['identical_quads'] += 1 + for problem in sorted(problems): + add(f"{problem}:{a[0].get('kind', 'model')}", describe(*a), describe(*b)) + for entry in left[len(right):]: + add(f"missing:{entry[0]['kind']}", describe(*entry)) + for entry in right[len(left):]: + add('extra', describe(*entry)) + report['client_quads'] += len(client) + report['rust_quads'] += len(rust) + return counts + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('--strict', action='store_true', help='fail when any quad or fact differs') + parser.add_argument('--examples', type=int, default=12, help='examples kept per mismatch category') + parser.add_argument('--only', help='only scenes whose name contains this text') + parser.add_argument('--quick', action='store_true', help='skip the all-states catalogue and most dense scenes') + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + BUILD.mkdir(parents=True, exist_ok=True) + report_path = BUILD / 'report.json' + report_path.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java' + helpers = [oracle.with_name(n + '.java') for n in ['VanillaCuboidModelOracle', 'VanillaHeightmapOracle']] + sources = [Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', oracle, *helpers, + lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/section_mesh_fixture.rs'] + for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: + sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] + tested = base.source_hashes(sources) + states = States(resources) + scenes = [s for s in corpus(states, not args.quick) if not args.only or args.only in s.name] + rows = [s.row() for s in scenes] + inputs = BUILD / 'inputs.jsonl' + inputs.write_text(''.join(json.dumps(row) + '\n' for row in rows)) + def run(command, name): + path = BUILD / (name + '.log') + with path.open('w') as log: + code = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT).returncode + if code: + tail = [line for line in path.read_text(errors='replace').splitlines() if not line.startswith('WARNING')][-15:] + raise SystemExit(f'{name} failed ({code}); see {path}\n' + '\n'.join(tail)) + classes = BUILD / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle, *helpers], 'compile-java') + env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3') + run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'section_mesh_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) + binary = Path(metadata['target_directory']) / 'fast/examples' / ('section_mesh_fixture.exe' if os.name == 'nt' else 'section_mesh_fixture') + java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle'] + run([binary, resources, inputs, BUILD / 'rust.jsonl'], 'rust') + run([*java, inputs, BUILD / 'client.jsonl', resources], 'client') + run([*java, 'facts', BUILD / 'client-facts.jsonl', resources], 'client-facts') + run([binary, resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') + report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), + 'scenes': len(rows), 'client_quads': 0, 'rust_quads': 0, 'matched_quads': 0, 'identical_quads': 0, + 'categories': {}, 'examples': {}, 'per_scene': {}, 'facts': {}} + client = [json.loads(line) for line in (BUILD / 'client.jsonl').read_text().splitlines()] + rust = [json.loads(line) for line in (BUILD / 'rust.jsonl').read_text().splitlines()] + for row, a, b in zip(rows, client, rust): + assert row['name'] == a['name'] == b['name'] + counts = compare(row, a['quads'], b['quads'], states, report, args.examples) + report['per_scene'][row['name']] = {'client': len(a['quads']), 'rust': len(b['quads']), **counts} + client_facts = [json.loads(line) for line in (BUILD / 'client-facts.jsonl').read_text().splitlines()] + rust_facts = [json.loads(line) for line in (BUILD / 'rust-facts.jsonl').read_text().splitlines()] + fact_mismatches = Counter() + for a, b in zip(client_facts, rust_facts): + for key in a: + if key == 'offsets': + same = len(a[key]) == len(b.get(key, [])) and all(abs(x - y) < 1e-6 for p, q in zip(a[key], b[key]) for x, y in zip(p, q)) + elif isinstance(a[key], float): + same = isinstance(b.get(key), (int, float)) and abs(f32(a[key]) - f32(b[key])) == 0 + else: + same = a[key] == b.get(key) + if not same: + fact_mismatches[key] += 1 + examples = report['facts'].setdefault(key, []) + if len(examples) < args.examples: + examples.append({'state': f"{states.names[a['id']]}{states.properties[a['id']]}", 'client': a[key], 'rust': b.get(key)}) + timing = [line for line in (BUILD / 'rust.log').read_text().splitlines() if line.startswith('meshed ')] + report['rust_mesh_timing'] = timing[-1] if timing else None + report['fact_mismatches'] = dict(fact_mismatches) + report['fact_states'] = len(client_facts) + base.ensure_sources_unchanged(sources, tested) + report['sources_sha256'] = tested + lab.write_json(report_path, report) + total = report['client_quads'] + print(f"Section mesh parity: {len(rows)} scenes, client {total:,} quads, Rust {report['rust_quads']:,} quads, " + f"{report['matched_quads']:,} geometry matches, {report['identical_quads']:,} identical " + f"({100.0 * report['identical_quads'] / max(total, 1):.2f}% of client quads)") + for category, count in sorted(report['categories'].items(), key=lambda kv: -kv[1]): + print(f' {category:<28} {count:,}') + print(f"Mesh facts: {len(client_facts):,} states, mismatches: {dict(fact_mismatches) or 'none'}") + print(f"Rust fixture (fast profile): {report['rust_mesh_timing']}") + print(f'Report: {report_path}') + if args.strict and (report['categories'] or fact_mismatches): + raise SystemExit(1) + + +if __name__ == '__main__': + main()