Merge branch 'main' into night-entities

This commit is contained in:
Ludovic Marie
2026-10-10 10:26:59 +02:00
155 changed files with 18644 additions and 1734 deletions
@@ -0,0 +1,97 @@
//! Block transformer lookups for tools/test_block_transformer_parity.py: reads
//! "transformer TAB face TAB clicked TAB above" lines (states as
//! "name|prop=value,...") and prints the oracle's result lines.
//!
//! usage: block_transform_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
assets::Assets,
block_transform::{Around, Transformers},
items::Items,
};
use horizon_world::chunk::BlockState;
use std::{fs, path::Path};
fn parse(text: &str) -> BlockState {
let (name, props) = text.split_once('|').unwrap_or((text, ""));
BlockState {
name: name.to_owned(),
properties: props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
}
}
fn describe(state: &BlockState) -> String {
let props: Vec<String> = state
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}|{}", state.name, props.join(","))
}
struct Column {
clicked: BlockState,
above: BlockState,
}
impl Around for Column {
fn state(&self, offset: [i32; 3]) -> BlockState {
match offset {
[0, 0, 0] => self.clicked.clone(),
[0, 1, 0] => self.above.clone(),
_ => BlockState {
name: "minecraft:stone".into(),
properties: Default::default(),
},
}
}
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let assets = Assets::load(root)?;
let transformers = Transformers::load(root, assets.registry)?;
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let around = Column {
clicked: parse(f[2]),
above: parse(f[3]),
};
if f[0] == "honeycomb" {
let waxed = transformers.waxed(assets.registry, &around.clicked);
out += &format!("{}\n", waxed.map_or("none".to_owned(), |s| describe(&s)));
continue;
}
let id = format!("minecraft:{}", f[0]);
match transformers.apply(&items, assets.registry, &id, f[1], &around) {
None => out += "none\n",
Some((index, t, state)) => {
out += &format!(
"{index}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
describe(&state),
t.sound,
t.particle,
t.loot.as_deref().unwrap_or("-"),
t.drop_strategy,
t.update_from_neighbors,
t.transform_type,
t.consume_on_use,
t.damage
);
}
}
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,145 @@
//! Cauldron interactions for tools/test_cauldron_parity.py: reads one JSON
//! case per line and prints "result TAB events TAB inventory".
//!
//! usage: cauldron_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
cauldron::{Outcome, Player, interact, removes_dye},
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::{ItemStack, Items},
menu::{Env, Kind, Menu},
};
use horizon_world::chunk::BlockState;
use serde_json::Value;
use std::{fs, path::Path};
struct Stand<'a> {
menu: Menu,
env: &'a Env<'a>,
events: Vec<String>,
hand: Option<ItemStack>,
}
impl Player for Stand<'_> {
fn creative(&self) -> bool {
self.menu.creative
}
fn hand(&mut self) -> &mut Option<ItemStack> {
&mut self.hand
}
fn add(&mut self, stack: &mut ItemStack) -> bool {
// The held stack lives in inventory slot 0 for Inventory.add.
self.menu.set_player_item(0, self.hand.take());
let added = self.menu.give(self.env, stack);
self.hand = self.menu.player_item(0).cloned();
self.menu.set_player_item(0, None);
added
}
fn contains(&self, stack: &ItemStack) -> bool {
self.menu.player_contains(stack)
|| self
.hand
.as_ref()
.is_some_and(|h| h.same_item_same_components(stack))
}
fn drop_stack(&mut self, stack: ItemStack) {
self.events
.push(format!("drop {}", canon_stack(Some(&stack))));
}
}
fn parse(text: &str) -> BlockState {
let (name, props) = text.split_once('|').unwrap_or((text, ""));
BlockState {
name: name.to_owned(),
properties: props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
}
}
fn describe(state: &BlockState) -> String {
let props: Vec<String> = state
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}|{}", state.name, props.join(","))
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
};
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
let mut menu = Menu::new(Kind::Inventory);
menu.creative = case["creative"].as_bool().unwrap_or(false);
for pair in case["inventory"].as_array().ok_or("inventory")? {
menu.set_player_item(
pair[0].as_u64().unwrap_or(0) as usize,
parse_stack(pair[1].as_str().unwrap_or("-"))?,
);
}
let held = parse_stack(case["held"].as_str().unwrap_or("-"))?;
let mut stand = Stand {
menu,
env: &env,
events: Vec::new(),
hand: held,
};
let cauldron = parse(case["state"].as_str().unwrap_or_default());
let dye = stand
.hand
.as_ref()
.is_some_and(|h| removes_dye(&items, &h.item));
let result = interact(
&cauldron,
case["under_water"].as_bool().unwrap_or(false),
dye,
&mut stand,
);
if let Some(block) = &result.block {
stand.events.push(format!("set {}", describe(block)));
}
if let Some(sound) = result.sound {
stand.events.push(format!("sound {sound}"));
}
let kind = match result.outcome {
Outcome::Success => "success",
Outcome::Consume => "consume",
Outcome::Pass => "pass",
};
stand.menu.set_player_item(0, stand.hand.take());
let inventory: Vec<String> = (0..41)
.filter_map(|i| {
stand
.menu
.player_item(i)
.map(|s| format!("{i}={}", canon_stack(Some(s))))
})
.collect();
out += &format!(
"{kind}\t{}\t{}\n",
stand.events.join(";"),
inventory.join(" ")
);
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,212 @@
//! Resident chunk storage benchmark: generates a block of vanilla terrain, then
//! reports the resident block/biome memory, the cost of lookups, meshing and
//! lighting on it.
//!
//! chunk_bench <client resource dir> [--seed S] [--size N]
#![forbid(unsafe_code)]
use horizon_client::{
assets::Assets,
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, SECTIONS},
light::{LightTables, light_chunk},
mesher::{MeshTables, Mesher},
models,
streaming::{ChunkGenerator, Proto},
vanillagen::VanillaTerrain,
};
use horizon_core::biome::BiomeZoom;
use std::{path::PathBuf, sync::Arc, time::Instant};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let root = PathBuf::from(args.first().ok_or("usage: chunk_bench RESOURCES")?);
let flag = |name: &str, default: i64| -> i64 {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1))
.and_then(|v| v.parse().ok())
.unwrap_or(default)
};
let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32);
let assets = Assets::load(&root)?;
let facts = BlockFacts::load(&root, assets.registry)?;
let biomes = Biomes::load(&root)?;
let tables = MeshTables::new(
&assets,
&facts,
models::load_visibility(&root, assets.registry)?,
)?;
let light = LightTables::load(&root, assets.registry, &facts)?;
let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?;
let mut worker = terrain.worker();
// Protos for size+4 columns, decorated for the inner size+2, finished as size+2.
let started = Instant::now();
let outer = size + 4;
let mut protos: Vec<Option<Proto>> = (0..outer * outer)
.map(|i| Some(terrain.proto(&mut worker, i % outer, i / outer)))
.collect();
eprintln!("proto: {:.2}s", started.elapsed().as_secs_f64());
let started = Instant::now();
let inner = size + 2;
for z in 1..=inner {
for x in 1..=inner {
let mut region: [Proto; 9] = std::array::from_fn(|k| {
let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1);
protos[((z + dz) * outer + x + dx) as usize]
.take()
.expect("proto")
});
terrain.decorate(&mut worker, &mut region);
for (k, p) in region.into_iter().enumerate() {
let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1);
protos[((z + dz) * outer + x + dx) as usize] = Some(p);
}
}
}
eprintln!("decorate: {:.2}s", started.elapsed().as_secs_f64());
let started = Instant::now();
let mut chunks: Vec<Chunk> = Vec::new();
for z in 1..=inner {
for x in 1..=inner {
let proto = protos[(z * outer + x) as usize].take().expect("proto");
let mut chunk = terrain.finish(proto);
chunk.x = x;
chunk.z = z;
chunks.push(chunk);
}
}
let finish = started.elapsed().as_secs_f64();
println!(
"finish (proto -> resident chunk): {:.1} ms per chunk",
finish * 1e3 / chunks.len() as f64
);
let chunks: Vec<Arc<Chunk>> = chunks.into_iter().map(Arc::new).collect();
let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone();
// Light all inner-inner columns.
let started = Instant::now();
let mut lit = Vec::new();
for z in 2..inner {
for x in 2..inner {
let region: [[Option<Arc<Chunk>>; 3]; 3] = std::array::from_fn(|dz| {
std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let borrowed = horizon_client::mesher::borrow(&region);
lit.push(((x, z), light_chunk(&borrowed, &light, true)));
}
}
println!(
"light: {:.2} ms per column",
started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64
);
let mut chunks: Vec<Chunk> = chunks.iter().map(|c| (**c).clone()).collect();
for ((x, z), sections) in lit {
chunks[((z - 1) * inner + x - 1) as usize].sections = sections;
}
let chunks: Vec<Arc<Chunk>> = chunks.into_iter().map(Arc::new).collect();
let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone();
// Memory.
let (mut bytes, mut sections, mut uniform) = (0usize, 0usize, 0usize);
for chunk in &chunks {
bytes += chunk.heap_bytes();
for s in &chunk.sections {
sections += 1;
uniform += usize::from(s.is_uniform(s.get(0)));
}
}
println!(
"resident: {} chunks, {} sections ({} uniform), {:.1} KiB per chunk ({:.2} MiB total)",
chunks.len(),
sections,
uniform,
bytes as f64 / 1024.0 / chunks.len() as f64,
bytes as f64 / 1048576.0
);
// Meshing.
let mut mesher = Mesher {
nether_shading: false,
assets: &assets,
tables: &tables,
biomes: &biomes,
visibility: tables.visibility.clone(),
zoom: BiomeZoom::new(7),
blend_radius: 2,
smooth_lighting: true,
cutout_leaves: true,
};
let mut best = f64::MAX;
let mut quads = 0usize;
for _ in 0..3 {
let started = Instant::now();
let mut jobs = 0;
quads = 0;
for z in 2..inner {
for x in 2..inner {
let region: [[Option<Arc<Chunk>>; 3]; 3] = std::array::from_fn(|dz| {
std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let borrowed = horizon_client::mesher::borrow(&region);
for sy in 0..SECTIONS as i32 {
let mesh = mesher.mesh(&borrowed, sy);
quads += (mesh.solid.len() + mesh.translucent.len()) / 4;
jobs += 1;
}
}
}
best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs));
}
println!(
"mesh: {:.1} us per section ({} quads total)",
best * 1e6,
quads
);
// Random lookups, as collision and entity queries do.
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let started = Instant::now();
let mut sum = 0u64;
let lookups = 20_000_000u64;
for _ in 0..lookups {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
let cx = 2 + (state % u64::from((inner - 2) as u32)) as i32;
let cz = 2 + ((state >> 8) % u64::from((inner - 2) as u32)) as i32;
let chunk = &chunks[((cz - 1) * inner + cx - 1) as usize];
let (x, y, z) = (
(state >> 16) as i32 & 15,
MIN_Y + ((state >> 24) % 384) as i32,
(state >> 40) as i32 & 15,
);
sum += u64::from(chunk.get(x, y, z));
}
println!(
"random get: {:.2} ns per lookup (checksum {sum})",
started.elapsed().as_secs_f64() * 1e9 / lookups as f64
);
// Coherent scan, as a column or area query does.
let started = Instant::now();
let mut sum = 0u64;
for _ in 0..4 {
for chunk in &chunks {
for y in MIN_Y..MIN_Y + 384 {
for z in 0..16 {
for x in 0..16 {
sum += u64::from(chunk.get(x, y, z));
}
}
}
}
}
println!(
"scan get: {:.2} ns per lookup (checksum {sum})",
started.elapsed().as_secs_f64() * 1e9 / (4.0 * chunks.len() as f64 * 98304.0)
);
Ok(())
}
@@ -0,0 +1,433 @@
//! Replays the render states of the vanilla entity-animation oracle through
//! Horizon's `mobs::anim::setup` and writes every part's pose.
//!
//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \
//! RESOURCES VANILLA.jsonl OUT.jsonl
use horizon_client::mobs::{
Mob, MobData, MobTypes, Part, Species, allay,
anim::{self, Poses, State},
aquatic, body_anim as b_anim, equine, guardian,
keyframes::AnimationState,
shulker, species, tame,
};
use horizon_core::geometry::Vec3;
use serde_json::{Value, json};
use std::{collections::BTreeMap, fs, path::PathBuf, sync::Arc};
fn walk(part: &Part, path: &str, poses: &Poses, out: &mut BTreeMap<String, Value>) {
let p = poses.pose(part);
let mut polys = 0;
let mut sum = 0.0f64;
for polygon in &part.polygons {
polys += 1;
for v in polygon.vertices {
sum += f64::from(v[0])
+ 2.0 * f64::from(v[1])
+ 3.0 * f64::from(v[2])
+ 5.0 * f64::from(v[3])
+ 7.0 * f64::from(v[4]);
}
}
let visible = !poses.is_hidden(part) && !poses.skips(part);
let mut row: Vec<Value> = p.iter().map(|&x| json!(x)).collect();
row.push(json!(u8::from(visible)));
row.push(json!(polys));
row.push(json!(sum));
out.insert(path.to_owned(), Value::Array(row));
for c in &part.children {
let child = if path.is_empty() {
c.name.clone()
} else {
format!("{path}/{}", c.name)
};
walk(c, &child, poses, out);
}
}
/// The entity-side values behind the render-state fields the case sets, for
/// the species whose Horizon animation reads them from the `Mob`.
fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
match species {
Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32,
Species::Guardian | Species::ElderGuardian => {
mob.anim.v[guardian::TAIL] = num("tailAnimation");
mob.anim.vo[guardian::TAIL] = num("tailAnimation");
mob.anim.v[guardian::SPIKES] = num("spikesAnimation");
mob.anim.vo[guardian::SPIKES] = num("spikesAnimation");
}
Species::Shulker => {
mob.anim.v[shulker::PEEK] = num("peekAmount");
mob.anim.vo[shulker::PEEK] = num("peekAmount");
}
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin
| Species::Giant
| Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::WitherSkeleton
| Species::Parched => {
mob.ai.aggressive = flag("isAggressive");
mob.extra.crouching = flag("isCrouching");
mob.extra.passenger = flag("isPassenger");
if flag("isHoldingBow") {
mob.extra.main_hand = Some("minecraft:bow".into());
}
}
Species::IronGolem => {
mob.extra.anim_ticks = num("attackTicksRemaining") as i32;
mob.extra.counter = num("offerFlowerTick") as i32;
}
Species::Hoglin | Species::Zoglin => {
mob.extra.anim_ticks = num("attackAnimationRemainingTicks") as i32;
}
Species::Ravager => {
mob.extra.counter2 = num("stunnedTicksRemaining") as i32;
mob.extra.counter = num("attackTicksRemaining") as i32;
let roar = num("roarAnimation");
if roar > 0.0 {
mob.extra.anim_ticks = (20.0 - roar * 20.0) as i32;
}
}
Species::Vex => mob.extra.flag = flag("isCharging"),
Species::Squid | Species::GlowSquid => {
mob.anim.v[aquatic::TENTACLE_ANGLE] = num("tentacleAngle");
mob.anim.vo[aquatic::TENTACLE_ANGLE] = num("tentacleAngle");
}
Species::Dolphin => {
if flag("isMoving") {
mob.velocity.x = 0.1;
}
}
Species::Cod | Species::Salmon | Species::TropicalFish | Species::Tadpole => {
mob.fluids.in_water = flag("isInWater");
}
Species::Allay => {
mob.extra.flag = flag("isDancing");
mob.extra.ints[4] = if flag("isSpinning") { 10 } else { 20 };
mob.anim.v[allay::SPIN] = num("spinningProgress") * 15.0;
mob.anim.vo[allay::SPIN] = num("spinningProgress") * 15.0;
mob.anim.v[allay::HOLD] = num("holdingAnimationProgress") * 5.0;
mob.anim.vo[allay::HOLD] = num("holdingAnimationProgress") * 5.0;
}
Species::Horse
| Species::Donkey
| Species::Mule
| Species::ZombieHorse
| Species::SkeletonHorse => {
for (slot, key) in [
(equine::EAT, "eatAnimation"),
(equine::STAND, "standAnimation"),
(equine::MOUTH, "feedingAnimation"),
] {
mob.anim.v[slot] = num(key);
mob.anim.vo[slot] = num(key);
}
mob.fluids.in_water = flag("isInWater");
mob.extra.chested = flag("hasChest");
}
Species::Camel => {
for (i, k) in [
"sitAnimationState",
"sitPoseAnimationState",
"sitUpAnimationState",
"idleAnimationState",
"dashAnimationState",
]
.into_iter()
.enumerate()
{
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
}
mob.extra.anim_ticks = num("jumpCooldown") as i32;
}
Species::Chicken => {
mob.anim.flap = num("flap");
mob.anim.flap_o = num("flap");
mob.anim.flap_speed = num("flapSpeed");
mob.anim.flap_speed_o = num("flapSpeed");
}
Species::Wolf => {
mob.extra.sitting = flag("isSitting");
mob.extra.anger = if flag("isAngry") { 100 } else { 0 };
mob.anim.v[tame::SHAKE] = num("shakeAnim");
mob.anim.vo[tame::SHAKE] = num("shakeAnim");
mob.anim.v[tame::INTEREST] = num("interest");
mob.anim.vo[tame::INTEREST] = num("interest");
}
Species::Creaking => {
mob.extra.flag2 = !flag("canMove");
for (i, k) in [
"attackAnimationState",
"invulnerabilityAnimationState",
"deathAnimationState",
]
.into_iter()
.enumerate()
{
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
}
}
Species::Witch if flag("isHoldingItem") => {
mob.extra.main_hand = Some("minecraft:potion".into());
}
_ => {}
}
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let root = PathBuf::from(&args[0]);
let types = MobTypes::load(&root)?;
let animations = MobData::load_animations(&root);
let mut out = String::new();
for line in fs::read_to_string(&args[1])?.lines() {
let v: Value = serde_json::from_str(line)?;
let layer = v["layer"]
.as_str()
.unwrap_or_default()
.trim_start_matches("minecraft:");
let baby = layer.contains("_baby#");
let adult = layer.replace("_baby#", "#");
// Variant layers (sizes, hatless villagers, climate cows...) animate
// like their base model.
let mut base = adult.clone();
for cut in ["_no_hat", "_small", "_medium", "_large"] {
base = base.replace(cut, "");
}
let base = base.trim_start_matches("cold_").trim_start_matches("warm_");
let Some(def) = species::ALL.iter().find(|d| {
d.model == layer
|| (baby && d.model == adult)
|| d.model == base
|| d.model.trim_end_matches("#main") == base.trim_end_matches("#main")
}) else {
out.push_str(&format!("{}\n", json!({"skip": "no species"})));
continue;
};
let Some(kind) = types.types.get(&format!("minecraft:{}", def.name)) else {
out.push_str(&format!("{}\n", json!({"skip": "no type"})));
continue;
};
let kind = Arc::new(kind.clone());
let model = kind
.layer(layer)
.cloned()
.unwrap_or_else(|| kind.model.clone());
let mut mob = Mob::new(7, kind, Vec3::new(0.0, 64.0, 0.0), 0.0);
mob.extra.main_hand = None;
let case = &v["case"];
let f = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
if baby {
mob.extra.age = -24000;
}
mob.age = f("ageInTicks") as u32;
let state = State {
pos: f("walkAnimationPos"),
speed: f("walkAnimationSpeed"),
age: f("ageInTicks"),
y_rot: f("yRot"),
x_rot: f("xRot"),
swing: f("swingAnimation"),
baby,
partial: 0.0,
};
let mut poses = Poses::new(&model);
entity_state(&mut mob, def.species, case);
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
let started = |k: &str| AnimationState {
started: case[k].as_f64().map(|v| v as f32),
};
let (p, s) = (&mut poses, &state);
match def.species {
Species::Goat => b_anim::goat(
p,
s,
&b_anim::Goat {
left_horn: flag("hasLeftHorn"),
right_horn: flag("hasRightHorn"),
ramming_x_head_rot: num("rammingXHeadRot"),
},
),
Species::PolarBear => b_anim::polar_bear(p, s, num("standScale")),
Species::Panda => b_anim::panda(
p,
s,
&b_anim::Panda {
unhappy: flag("isUnhappy"),
sneezing: flag("isSneezing"),
sneeze_time: num("sneezeTime") as i32,
eating: flag("isEating"),
scared: flag("isScared"),
sit_amount: num("sitAmount"),
lie_on_back_amount: num("lieOnBackAmount"),
roll_amount: num("rollAmount"),
},
),
Species::Llama | Species::TraderLlama => b_anim::llama(p, s, flag("hasChest")),
Species::Turtle => b_anim::turtle(
p,
s,
&b_anim::Turtle {
on_land: flag("isOnLand"),
laying_egg: flag("isLayingEgg"),
has_egg: flag("hasEgg"),
},
),
Species::Strider => b_anim::strider(p, s, flag("isRidden")),
Species::SnowGolem => b_anim::snow_golem(p, s),
Species::Silverfish => b_anim::silverfish(p, s),
Species::Endermite => b_anim::endermite(p, s),
Species::Parrot => b_anim::parrot(
p,
s,
match case["pose"].as_str() {
Some("FLYING") => b_anim::ParrotPose::Flying,
Some("ON_SHOULDER") => b_anim::ParrotPose::OnShoulder,
Some("SITTING") => b_anim::ParrotPose::Sitting,
Some("PARTY") => b_anim::ParrotPose::Party,
_ => b_anim::ParrotPose::Standing,
},
num("flapAngle"),
),
Species::Bee => b_anim::bee(
p,
s,
&b_anim::Bee {
has_stinger: flag("hasStinger"),
on_ground: flag("isOnGround"),
angry: flag("isAngry"),
roll_amount: num("rollAmount"),
},
),
Species::Bat => b_anim::bat(
p,
s,
flag("isResting"),
&started("flyAnimationState"),
&started("restAnimationState"),
&animations,
),
Species::Armadillo => b_anim::armadillo(
p,
s,
&b_anim::Armadillo {
hiding_in_shell: flag("isHidingInShell"),
roll_out: started("rollOutAnimationState"),
roll_up: started("rollUpAnimationState"),
peek: started("peekAnimationState"),
},
&animations,
),
Species::Axolotl => b_anim::axolotl(
p,
s,
&b_anim::Axolotl {
playing_dead: num("playingDeadFactor"),
in_water: num("inWaterFactor"),
on_ground: num("onGroundFactor"),
moving: num("movingFactor"),
swim: started("swimAnimation"),
walk: started("walkAnimationState"),
idle_on_ground: started("idleOnGroundAnimationState"),
idle_underwater_on_ground: started("idleUnderWaterOnGroundAnimationState"),
idle_underwater: started("idleUnderWaterAnimationState"),
play_dead: started("playDeadAnimationState"),
},
&animations,
),
Species::Frog => b_anim::frog(
p,
s,
&b_anim::Frog {
swimming: flag("isSwimming"),
jump: started("jumpAnimationState"),
croak: started("croakAnimationState"),
tongue: started("tongueAnimationState"),
swim_idle: started("swimIdleAnimationState"),
},
&animations,
),
Species::Rabbit => b_anim::rabbit(
p,
s,
&started("hopAnimationState"),
&started("idleHeadTiltAnimationState"),
&animations,
),
Species::Fox => b_anim::fox(
p,
s,
&b_anim::Fox {
crouching: flag("isCrouching"),
sleeping: flag("isSleeping"),
sitting: flag("isSitting"),
pouncing: flag("isPouncing"),
faceplanted: flag("isFaceplanted"),
head_roll_angle: num("headRollAngle"),
crouch_amount: num("crouchAmount"),
leg_motion_pos: 0.67,
},
&animations,
),
Species::Cat | Species::Ocelot => horizon_client::mobs::tame::feline(
p,
s,
&horizon_client::mobs::tame::Feline {
crouching: flag("isCrouching"),
sprinting: flag("isSprinting"),
sitting: flag("isSitting"),
lie_down: num("lieDownAmount"),
lie_down_tail: num("lieDownAmountTail"),
relax_one: num("relaxStateOneAmount"),
},
),
Species::Piglin | Species::PiglinBrute => {
use horizon_client::mobs::piglin::{PiglinPose, piglin_pose};
let pose = match case["armPose"].as_str() {
Some("DANCING") => PiglinPose::Dancing,
Some("ATTACKING_WITH_MELEE_WEAPON") => PiglinPose::MeleeWeapon,
Some("CROSSBOW_HOLD") => PiglinPose::CrossbowHold,
Some("CROSSBOW_CHARGE") => PiglinPose::CrossbowCharge,
Some("ADMIRING_ITEM") => PiglinPose::AdmiringItem,
_ => PiglinPose::Default,
};
piglin_pose(
p,
s,
pose,
num("maxCrossbowChageDuration"),
num("ticksUsingItem"),
);
}
Species::Evoker | Species::Pillager | Species::Vindicator => {
use horizon_client::mobs::illager::{ArmPose, anim_pose};
let pose = match case["armPose"].as_str() {
Some("CROSSED") => ArmPose::Crossed,
Some("ATTACKING") => ArmPose::Attacking,
Some("SPELLCASTING") => ArmPose::Spellcasting,
Some("BOW_AND_ARROW") => ArmPose::BowAndArrow,
Some("CROSSBOW_HOLD") => ArmPose::CrossbowHold,
Some("CROSSBOW_CHARGE") => ArmPose::CrossbowCharge,
Some("CELEBRATING") => ArmPose::Celebrating,
_ => ArmPose::Neutral,
};
mob.extra.passenger = flag("isRiding");
mob.extra.using_item = num("ticksUsingItem") as i32;
anim_pose(&mob, s, p, pose);
}
_ => anim::setup(&mob, s, p, &animations),
}
let mut parts = BTreeMap::new();
walk(&model, "", &poses, &mut parts);
out.push_str(&format!("{}\n", json!({"parts": parts})));
}
fs::write(&args[2], out)?;
Ok(())
}
@@ -0,0 +1,72 @@
//! Environment attributes for differential tests against vanilla
//! (tools/test_environment_render_parity.py): reads "dimension ticks rain
//! thunder biome" lines and prints the sampled sky state as JSON lines.
//!
//! usage: environment_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
biome::Biomes,
environment::{Environment, apply_weather},
};
use std::{collections::HashMap, fmt::Write as _, fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: environment_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let biomes = Biomes::load(root)?;
let mut environments: HashMap<String, Environment> = HashMap::new();
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split(' ').collect();
let dimension = f[0];
let environment =
match environments.entry(dimension.to_owned()) {
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
std::collections::hash_map::Entry::Vacant(e) => e.insert(
Environment::load_dimension(root, dimension, dimension == "overworld")?,
),
};
let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4])));
let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog);
if dimension == "overworld" {
apply_weather(&mut sky, f[2].parse()?, f[3].parse()?);
}
let v3 = |c: [f32; 3]| format!("[{:?},{:?},{:?}]", c[0], c[1], c[2]);
let v4 = |c: [f32; 4]| format!("[{:?},{:?},{:?},{:?}]", c[0], c[1], c[2], c[3]);
let mut row = format!("{{\"case\":\"{line}\"");
let mut put = |name: &str, value: String| {
let _ = write!(row, ",\"minecraft:{name}\":{value}");
};
put("visual/sky_color", v3(sky.sky_color));
put("visual/fog_color", v3(sky.fog_color));
put("visual/cloud_color", v4(sky.cloud_color));
put("visual/sunrise_sunset_color", v4(sky.sunrise_color));
put(
"visual/sky_light_factor",
format!("{:?}", sky.sky_light_factor),
);
put("visual/sky_light_color", v3(sky.sky_light_color));
put("visual/block_light_tint", v3(sky.block_light_tint));
put("visual/ambient_light_color", v3(sky.ambient_light_color));
put("visual/sun_angle", format!("{:?}", sky.sun_angle));
put("visual/moon_angle", format!("{:?}", sky.moon_angle));
put("visual/star_angle", format!("{:?}", sky.star_angle));
put(
"visual/star_brightness",
format!("{:?}", sky.star_brightness),
);
put(
"gameplay/sky_light_level",
format!("{:?}", sky.sky_light_level * 15.0),
);
put("visual/fog_start_distance", format!("{:?}", sky.fog_start));
put("visual/fog_end_distance", format!("{:?}", sky.fog_end));
out.push_str(&row);
out.push_str("}\n");
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,301 @@
#![forbid(unsafe_code)]
//! Runs the JSON-lines scenarios of tools/test_game_loop_parity.py through the
//! Rust timer, tick-rate manager, window, mouse and key-mapping code.
use horizon_client::{
Result,
clock::{ServerTickRateManager, Timer},
keymapping::KeyState,
mouse::{LookOptions, MouseLook, Rotation},
options_file::{OptionsFile, V},
window::{self, FrameContext, InactivityFpsLimit},
};
use serde_json::Value;
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
fn fl(v: &Value) -> f32 {
f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn db(v: &Value) -> f64 {
f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn fb(v: f32) -> String {
format!("{:08x}", if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() })
}
fn dbs(v: f64) -> String {
format!(
"{:016x}",
if v.is_nan() {
0x7ff8_0000_0000_0000
} else {
v.to_bits()
}
)
}
fn b(v: &Value) -> bool {
v.as_bool().unwrap()
}
fn timer(c: &Value, out: &mut impl Write) -> Result<()> {
let mut timer = Timer::new(fl(&c["tps"]), c["start"].as_i64().unwrap());
writeln!(out, "timer")?;
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
let mut result = String::new();
match name {
"adv" => {
let mspt = if op[2].is_null() { 0.0 } else { fl(&op[2]) };
let ticks = timer.advance_game_time(op[1].as_i64().unwrap(), |d| {
if mspt == 0.0 { d } else { java_max(d, mspt) }
});
result = format!(" {ticks}");
}
"real" => timer.advance_real_time(op[1].as_i64().unwrap()),
"pause" => timer.update_pause_state(b(&op[1])),
"frozen" => timer.update_frozen_state(b(&op[1])),
_ => panic!("{name}"),
}
writeln!(
out,
"{name}{result} {} {} {} {}",
fb(timer.game_time_delta_ticks()),
fb(timer.game_time_delta_partial_tick(false)),
fb(timer.game_time_delta_partial_tick(true)),
fb(timer.realtime_delta_ticks())
)?;
}
Ok(())
}
/// Math.max(float, float).
fn java_max(a: f32, b: f32) -> f32 {
if a.is_nan() || b.is_nan() {
f32::NAN
} else if a == 0.0 && b == 0.0 {
f32::from_bits(a.to_bits() & b.to_bits())
} else if a >= b {
a
} else {
b
}
}
fn rate(c: &Value, out: &mut impl Write) -> Result<()> {
let mut m = ServerTickRateManager::default();
writeln!(out, "rate")?;
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
let mut result = String::new();
let mut report = None;
match name {
"rate" => m.set_tick_rate(fl(&op[1])),
"freeze" => m.base.set_frozen(b(&op[1])),
"step" => {
result = format!(" {}", m.step_game_if_paused(op[1].as_i64().unwrap() as i32))
}
"stopstep" => result = format!(" {}", m.stop_stepping()),
"sprint" => {
result = format!(
" {}",
m.request_game_to_sprint(op[1].as_i64().unwrap() as i32)
)
}
"check" => {
let (run, r) = m.check_should_sprint_this_tick(op[1].as_i64().unwrap());
result = format!(" {run}");
report = r;
}
"end" => m.end_tick_work(op[1].as_i64().unwrap()),
"stopsprint" => {
report = m.stop_sprinting();
result = format!(" {}", report.is_some());
}
"tick" => m.base.tick(),
_ => panic!("{name}"),
}
let tail = report.map_or(String::new(), |r| {
format!(" report {} {}", r.ticks_per_second, r.milliseconds_per_tick)
});
writeln!(
out,
"{name}{result} | {} {} {} {} {} {} {} {}{tail}",
fb(m.base.tickrate()),
m.base.nanoseconds_per_tick(),
fb(m.base.milliseconds_per_tick()),
m.base.runs_normally(),
m.base.is_stepping_forward(),
m.base.frozen_ticks_to_run(),
m.base.is_frozen(),
m.is_sprinting()
)?;
}
Ok(())
}
fn scale(c: &Value, out: &mut impl Write) -> Result<()> {
let i = |k: &str| c[k].as_i64().unwrap() as i32;
let fbsize = [i("w"), i("h")];
let scale = window::calculate_scale(fbsize, i("max"), b(&c["uni"]));
let [gw, gh] = window::gui_scaled_size(fbsize, scale);
writeln!(
out,
"scale {scale} {gw} {gh} {} {}",
dbs(window::scaled_pos(db(&c["x"]), gw, i("sw"))),
dbs(window::scaled_pos(db(&c["y"]), gh, i("sh")))
)?;
Ok(())
}
fn limit(c: &Value, out: &mut impl Write) -> Result<()> {
let ctx = FrameContext {
inactivity: if b(&c["afk"]) {
InactivityFpsLimit::Afk
} else {
InactivityFpsLimit::Minimized
},
iconified: b(&c["iconified"]),
focused: b(&c["focused"]),
exclusive_fullscreen: false,
now_ms: c["ago"].as_i64().unwrap(),
latest_input_ms: 0,
has_level: b(&c["level"]),
has_screen: b(&c["screen"]),
has_overlay: b(&c["overlay"]),
};
let reason = window::throttle_reason(ctx);
let name = match reason {
window::ThrottleReason::None => "NONE",
window::ThrottleReason::WindowIconified => "WINDOW_ICONIFIED",
window::ThrottleReason::LongAfk => "LONG_AFK",
window::ThrottleReason::ShortAfk => "SHORT_AFK",
window::ThrottleReason::OutOfLevelMenu => "OUT_OF_LEVEL_MENU",
};
writeln!(
out,
"limit {name} {} {}",
window::framerate_limit(c["opt"].as_i64().unwrap() as i32, ctx),
window::heavily_throttled(reason)
)?;
Ok(())
}
fn mouse(c: &Value, out: &mut impl Write) -> Result<()> {
let look = LookOptions {
sensitivity: db(&c["sens"]),
smooth_camera: b(&c["smooth"]),
scoping: b(&c["scoping"]),
invert_x: b(&c["ix"]),
invert_y: b(&c["iy"]),
};
let (active, grabbed) = (b(&c["active"]), b(&c["grabbed"]));
let mut handler = MouseLook::default();
let mut rotation = Rotation {
x_rot: 0.0,
y_rot: 0.0,
x_rot_o: 0.0,
y_rot_o: 0.0,
};
writeln!(out, "mouse")?;
for op in c["ops"].as_array().unwrap() {
match op[0].as_str().unwrap() {
"move" => handler.on_move(
db(&op[1]),
db(&op[2]),
db(&op[3]),
db(&op[4]),
active,
grabbed,
),
"ignore" => handler.set_ignore_first_move(),
"frame" => {
if let Some((xo, yo)) =
handler.handle_accumulated_movement(db(&op[1]), active, grabbed, look)
{
rotation.turn(xo, yo);
}
writeln!(
out,
"frame {} {} {} {}",
fb(rotation.x_rot),
fb(rotation.y_rot),
fb(rotation.x_rot_o),
fb(rotation.y_rot_o)
)?;
}
other => panic!("{other}"),
}
}
Ok(())
}
fn scroll(c: &Value, out: &mut impl Write) -> Result<()> {
let mut handler = MouseLook::default();
let mut slot = c["slot"].as_i64().unwrap() as i32;
// OptionInstance.set quantises the wheel sensitivity.
let mut file = OptionsFile::default();
file.set("mouseWheelSensitivity", V::Double(db(&c["sens"])));
let sensitivity = file.double("mouseWheelSensitivity");
writeln!(out, "scroll")?;
for op in c["ops"].as_array().unwrap() {
if let Some((wheel, _)) =
handler.on_scroll(db(&op[0]), db(&op[1]), b(&c["discrete"]), sensitivity)
{
slot = horizon_client::mouse::ScrollWheelHandler::next_selection(
f64::from(wheel),
slot,
9,
);
}
writeln!(out, "{slot}")?;
}
Ok(())
}
fn key(c: &Value, out: &mut impl Write) -> Result<()> {
let mut state = if b(&c["toggle"]) {
KeyState::toggle(b(&c["restore"]), b(&c["keyboard"]))
} else {
KeyState::plain()
};
let mut option = false;
writeln!(out, "key")?;
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
let mut result = String::new();
match name {
"option" => option = b(&op[1]),
"down" => state.set_down(b(&op[1]), option),
"release" => state.release(option),
"restore" => {
result = format!(" {}", state.should_restore_state_on_screen_closed(option))
}
"click" => state.click(),
"consume" => result = format!(" {}", state.consume_click()),
"ingame" => result = format!(" {}", state.should_set_on_ingame_focus(option)),
_ => panic!("{name}"),
}
writeln!(out, "{name}{result} {}", state.is_down)?;
}
Ok(())
}
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
let mut out = BufWriter::new(File::create(&args[1])?);
for line in BufReader::new(File::open(&args[0])?).lines() {
let c: Value = serde_json::from_str(&line?)?;
match c["t"].as_str().unwrap() {
"timer" => timer(&c, &mut out)?,
"rate" => rate(&c, &mut out)?,
"scale" => scale(&c, &mut out)?,
"limit" => limit(&c, &mut out)?,
"mouse" => mouse(&c, &mut out)?,
"scroll" => scroll(&c, &mut out)?,
"key" => key(&c, &mut out)?,
other => panic!("{other}"),
}
}
Ok(())
}
@@ -0,0 +1,71 @@
//! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per
//! line (menu, creative, slots, carried, data, ops) and prints the oracle's
//! state lines after every click.
//!
//! usage: menu_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::Items,
menu::{Env, Input, Kind, Menu},
};
use serde_json::Value;
use std::{fs, path::Path};
fn state(menu: &Menu) -> String {
let slots: Vec<String> = (0..menu.slot_count())
.map(|i| canon_stack(menu.slot(i)))
.collect();
let data: String = menu.data.iter().map(|d| format!(" {d}")).collect();
format!(
"{} | {} |{data} | {}",
slots.join(" "),
canon_stack(menu.carried.as_ref()),
menu.drops.join(";")
)
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
};
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?;
let mut menu = Menu::new(kind);
menu.creative = case["creative"].as_bool().unwrap_or(false);
for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() {
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
}
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
}
menu.drops.clear();
out += &format!("init {}\n", state(&menu));
for op in case["ops"].as_array().ok_or("ops")? {
let slot = op[0].as_i64().unwrap_or(0) as i32;
let button = op[1].as_i64().unwrap_or(0) as i32;
let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?;
match menu.click(&env, slot, button, kind) {
Ok(()) => out += &format!("{}\n", state(&menu)),
Err(name) => out += &format!("error {name}\n"),
}
}
out += "end\n";
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,32 @@
#![forbid(unsafe_code)]
//! Loads and saves option files like `Options.load`/`save`, for the
//! differential harness (tools/test_options_parity.py).
use horizon_client::{Result, keybinds, options_file::OptionsFile};
use std::{fs, io::Write};
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
let mut names: Vec<_> = fs::read_dir(&args[0])?
.map(|e| e.map(|e| e.path()))
.collect::<std::io::Result<_>>()?;
names.sort();
let mut out = fs::File::create(&args[1])?;
let mut first = true;
for path in names {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let file = if name == "absent.txt" {
OptionsFile::default()
} else {
OptionsFile::parse(&String::from_utf8_lossy(&fs::read(&path)?))
};
write!(out, "== {name}\n{}", file.serialize())?;
if first {
first = false;
writeln!(out, "== keys")?;
for (name, key, category) in keybinds::MAPPINGS {
writeln!(out, "{name} {key} {category} {}", keybinds::is_toggle(name))?;
}
}
}
Ok(())
}
@@ -0,0 +1,91 @@
//! Recipe lookups for tools/test_recipe_parity.py: reads the oracle's
//! tab-separated commands (craft, cook, stonecut, smith) and prints one line
//! per command in the oracle's format.
//!
//! usage: recipe_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
enchant::Enchantments,
item_data::{canon_stack, parse_stack},
items::Items,
stations::StationRecipes,
};
use std::{fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let stations = StationRecipes::load(root, &items);
let enchantments = Enchantments::load(root);
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let stack = |i: usize| parse_stack(f[i]);
let text = match f[0] {
"craft" => {
let n: usize = f[1].parse()?;
let mut grid = Vec::new();
for i in 0..n * n {
grid.push(stack(2 + i)?);
}
match recipes.find(&grid, n) {
None => "none".to_owned(),
Some((id, result)) => {
let rest = recipes.remainders(id, &grid, n);
let rest: Vec<String> = rest
.iter()
.enumerate()
.filter_map(|(i, s)| {
Some(format!("{i}={}", canon_stack(Some(s.as_ref()?))))
})
.collect();
format!("{id}\t{}\t{}", canon_stack(Some(&result)), rest.join(";"))
}
}
}
"cook" => match stack(2)?.and_then(|s| {
recipes
.cook(&format!("minecraft:{}", f[1]), &s)
.map(|c| (c.id.clone(), c.result.clone(), c.experience, c.time))
}) {
None => "none".to_owned(),
Some((id, result, xp, time)) => {
format!("{id}\t{}\t{xp:?}\t{time}", canon_stack(Some(&result)))
}
},
"stonecut" => match stack(1)? {
None => String::new(),
Some(s) => stations
.stonecutter(&s)
.iter()
.map(|r| {
format!(
"{}={}",
r.id.trim_start_matches("minecraft:"),
canon_stack(Some(&r.result))
)
})
.collect::<Vec<_>>()
.join(";"),
},
"smith" => {
let (t, b, a) = (stack(1)?, stack(2)?, stack(3)?);
match stations.smithing_result(&enchantments, t.as_ref(), b.as_ref(), a.as_ref()) {
None => "none".to_owned(),
Some(r) => canon_stack(Some(&r)),
}
}
other => return Err(format!("unknown command {other}").into()),
};
out.push_str(&text);
out.push('\n');
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -4,12 +4,13 @@
#![forbid(unsafe_code)]
use horizon_client::{
assets::Assets,
biome::{Biomes, GrassModifier},
biome::{BiomeInfo, Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
mesher::{MeshTables, Mesher, Vertex},
mesher::{MeshTables, Mesher, OPAQUE_LAYER, Vertex},
models,
};
use horizon_core::biome::BiomeZoom;
use horizon_world::registry::BlockStateId;
use serde_json::{Value, json};
use std::{
@@ -48,17 +49,23 @@ fn scene(
assets: &Assets,
tables: &MeshTables,
biomes: &mut Biomes,
pristine: &[BiomeInfo],
names: &BTreeMap<u32, &str>,
elapsed: &mut Duration,
) -> Result<Value> {
let colors = &row["colors"];
let color = |k: &str| -> Result<u32> { 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")?;
// Scenes without a biome field give every biome the same constant colours;
// the others use the real biome definitions.
biomes.list = pristine.to_vec();
if row.get("biomes").is_none() {
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;
@@ -89,6 +96,31 @@ fn scene(
values[index(x, y, z)] = packed(int(&cell[3])?, int(&cell[4])?);
}
}
let (mut zoom, mut blend_radius) = (BiomeZoom::new(0), 2);
let smooth_lighting = row["smooth"].as_bool().unwrap_or(true);
let cutout_leaves = row["cutout_leaves"].as_bool().unwrap_or(true);
if let Some(field) = row.get("biomes") {
zoom = BiomeZoom::new(field["seed"].as_i64().ok_or("missing biome seed")?);
blend_radius = int(&field["radius"])?;
let default = biomes.id(field["default"].as_str().ok_or("missing default biome")?);
for chunk in &mut chunks {
for qy in 0..96 {
for cell in 0..16 {
chunk.set_biome_cell(cell & 3, qy, cell >> 2, default);
}
}
}
for cell in field["cells"].as_array().ok_or("missing biome cells")? {
let (qx, qy, qz) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?);
let i = chunk_index(qx * 4, qz * 4)?;
chunks[i].set_biome_cell(
qx,
qy - MIN_Y / 4,
qz,
biomes.id(cell[3].as_str().ok_or("biome name")?),
);
}
}
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 {
@@ -97,6 +129,10 @@ fn scene(
tables,
biomes: &*biomes,
visibility: tables.visibility.clone(),
zoom,
blend_radius,
smooth_lighting,
cutout_leaves,
};
let section_y = int(&row["section_y"])?;
let started = Instant::now();
@@ -109,7 +145,9 @@ fn scene(
return Err("partial quad".into());
}
for quad in vertices {
let sprite = names.get(&quad[0].layer).ok_or("unknown sprite layer")?;
let sprite = names
.get(&(quad[0].layer & !OPAQUE_LAYER))
.ok_or("unknown sprite layer")?;
if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) {
return Err("quad mixes sprite layers".into());
}
@@ -150,6 +188,7 @@ fn main() -> Result<()> {
.iter()
.map(|(name, layer)| (*layer, name.as_str()))
.collect();
let pristine = biomes.list.clone();
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.
@@ -175,7 +214,15 @@ fn main() -> Result<()> {
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)?;
let result = scene(
&row,
&assets,
&tables,
&mut biomes,
&pristine,
&names,
&mut elapsed,
)?;
serde_json::to_writer(&mut output, &result)?;
output.write_all(b"\n")?;
sections += 1;
+2 -2
View File
@@ -147,7 +147,7 @@ fn launch(socket: &Path, args: &[String]) -> Result<bool, String> {
.stderr(file)
.spawn()
.map_err(|e| format!("{}: {e}", game.display()))?;
let deadline = Instant::now() + Duration::from_secs(60);
let deadline = Instant::now() + Duration::from_secs(300);
while Instant::now() < deadline {
if UnixStream::connect(socket).is_ok() {
println!(
@@ -160,7 +160,7 @@ fn launch(socket: &Path, args: &[String]) -> Result<bool, String> {
}
println!(
"{}",
serde_json::json!({ "error": "control socket did not open within 60 seconds", "log": log })
serde_json::json!({ "error": "control socket did not open within 300 seconds", "log": log })
);
Ok(false)
}
+5 -11
View File
@@ -32,8 +32,9 @@ pub struct BiomeInfo {
pub foliage: u32,
pub dry_foliage: u32,
pub water: u32,
pub sky: u32,
pub fog: u32,
pub sky: Option<u32>,
/// The biome's own fog colour attribute; otherwise the dimension's applies.
pub fog: Option<u32>,
pub water_fog: u32,
}
pub struct Biomes {
@@ -77,13 +78,6 @@ impl Biomes {
let grass = colormap(root, "grass")?;
let foliage = colormap(root, "foliage")?;
let dry = colormap(root, "dry_foliage")?;
let dimension: Value = serde_json::from_slice(&fs::read(
root.join("data/minecraft/dimension_type/overworld.json"),
)?)?;
let default_fog =
color(&dimension["attributes"]["minecraft:visual/fog_color"]).unwrap_or(0xC0D8FF);
let default_sky =
color(&dimension["attributes"]["minecraft:visual/sky_color"]).unwrap_or(0x78A7FF);
let mut list = Vec::new();
let mut names: Vec<_> = fs::read_dir(root.join("data/minecraft/worldgen/biome"))?
.filter_map(|e| e.ok())
@@ -151,8 +145,8 @@ impl Biomes {
dry_foliage: color(&effects["dry_foliage_color"])
.unwrap_or_else(|| sample(&dry, temperature, downfall, 0x5D4930)),
water: color(&effects["water_color"]).unwrap_or(0x3F76E4),
sky: color(&attributes["minecraft:visual/sky_color"]).unwrap_or(default_sky),
fog: color(&attributes["minecraft:visual/fog_color"]).unwrap_or(default_fog),
sky: color(&attributes["minecraft:visual/sky_color"]),
fog: color(&attributes["minecraft:visual/fog_color"]),
water_fog: color(&attributes["minecraft:visual/water_fog_color"])
.unwrap_or(0x050533),
name,
@@ -0,0 +1,269 @@
//! The `minecraft:block_transformer` registry (axe, hoe, shovel) that
//! `BlockTransformer.transformBlock` reads: each transform's rule based state
//! provider is evaluated against the clicked block and the block above.
//! `tools/test_block_transformer_parity.py` compares every block state with
//! vanilla.
use crate::{Result, items::Items};
use horizon_world::{chunk::BlockState, registry::BlockRegistry};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
enum Predicate {
Blocks(Vec<String>),
Tag { tag: String, offset: [i32; 3] },
AllOf(Vec<Predicate>),
AnyOf(Vec<Predicate>),
}
enum Provider {
Rules(Vec<(Predicate, Provider)>),
State(BlockState),
/// `CopyPropertiesProvider`: the source with the clicked block's properties.
Copy(Box<Provider>),
}
/// One `BlockTransformData`.
pub struct Transform {
provider: Provider,
pub disallowed_faces: Vec<String>,
pub sound: String,
pub particle: String,
pub loot: Option<String>,
pub drop_strategy: String,
pub update_from_neighbors: bool,
pub transform_type: String,
pub consume_on_use: bool,
pub damage: u32,
}
pub struct Transformers {
transformers: HashMap<String, Vec<Transform>>,
}
/// What the transformer reads of the world: the block state at an offset from
/// the clicked position.
pub trait Around {
fn state(&self, offset: [i32; 3]) -> BlockState;
}
fn state_of(value: &Value, registry: &BlockRegistry) -> Option<BlockState> {
let name = value["id"].as_str().or_else(|| value["Name"].as_str())?;
let default = registry.default_state(name)?;
let mut state = registry.state(default)?.clone();
for (k, v) in value["properties"].as_object().into_iter().flatten() {
state.properties.insert(k.clone(), v.as_str()?.to_owned());
}
Some(state)
}
fn predicate(value: &Value) -> Option<Predicate> {
Some(match value["type"].as_str()? {
"minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] {
Value::String(s) => vec![s.clone()],
Value::Array(a) => a
.iter()
.filter_map(|b| b.as_str().map(str::to_owned))
.collect(),
_ => return None,
}),
"minecraft:matching_block_tag" => {
let o = value["offset"].as_array();
let at = |i: usize| {
o.and_then(|o| o.get(i))
.and_then(Value::as_i64)
.unwrap_or(0) as i32
};
Predicate::Tag {
tag: value["tag"].as_str()?.to_owned(),
offset: [at(0), at(1), at(2)],
}
}
"minecraft:all_of" => Predicate::AllOf(
value["predicates"]
.as_array()?
.iter()
.map(predicate)
.collect::<Option<_>>()?,
),
"minecraft:any_of" => Predicate::AnyOf(
value["predicates"]
.as_array()?
.iter()
.map(predicate)
.collect::<Option<_>>()?,
),
_ => return None,
})
}
fn provider(value: &Value, registry: &BlockRegistry) -> Option<Provider> {
match value["type"].as_str() {
Some("minecraft:rule_based") => {
let mut rules = Vec::new();
for rule in value["rules"].as_array()? {
rules.push((
predicate(&rule["if_true"])?,
provider(&rule["then"], registry)?,
));
}
Some(Provider::Rules(rules))
}
Some("minecraft:copy_properties") => Some(Provider::Copy(Box::new(provider(
&value["source"],
registry,
)?))),
_ => state_of(value, registry).map(Provider::State),
}
}
/// `BlockState.withPropertiesOf`: the properties both blocks have.
fn with_properties_of(
registry: &BlockRegistry,
mut state: BlockState,
old: &BlockState,
) -> Option<BlockState> {
let defaults = registry
.default_state(&state.name)
.and_then(|id| registry.state(id))?;
for (k, v) in &old.properties {
if defaults.properties.contains_key(k) {
let mut candidate = state.clone();
candidate.properties.insert(k.clone(), v.clone());
if registry.resolve(&candidate).is_ok() {
state = candidate;
}
}
}
Some(state)
}
impl Predicate {
fn test(&self, items: &Items, around: &dyn Around) -> bool {
match self {
Self::Blocks(names) => {
let state = around.state([0, 0, 0]);
names.contains(&state.name)
}
Self::Tag { tag, offset } => {
let state = around.state(*offset);
items
.block_tags
.get(tag)
.is_some_and(|members| members.contains(&state.name))
}
Self::AllOf(all) => all.iter().all(|p| p.test(items, around)),
Self::AnyOf(any) => any.iter().any(|p| p.test(items, around)),
}
}
}
impl Provider {
fn state(
&self,
items: &Items,
registry: &BlockRegistry,
around: &dyn Around,
) -> Option<BlockState> {
match self {
Self::Rules(rules) => rules
.iter()
.find(|(p, _)| p.test(items, around))
.and_then(|(_, then)| then.state(items, registry, around)),
Self::State(state) => Some(state.clone()),
Self::Copy(source) => {
let state = source.state(items, registry, around)?;
with_properties_of(registry, state, &around.state([0, 0, 0]))
}
}
}
}
impl Transformers {
/// Reads `data/minecraft/block_transformer/*.json`.
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let mut transformers = HashMap::new();
let dir = root.join("data/minecraft/block_transformer");
if dir.exists() {
for entry in fs::read_dir(&dir)?.flatten() {
let path = entry.path();
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let list: Value = serde_json::from_slice(&fs::read(&path)?)?;
let mut transforms = Vec::new();
for t in list.as_array().into_iter().flatten() {
let text = |k: &str, d: &str| t[k].as_str().unwrap_or(d).to_owned();
let Some(provider) = provider(&t["block_state_provider"], registry) else {
continue;
};
transforms.push(Transform {
provider,
disallowed_faces: t["disallowed_faces"]
.as_array()
.into_iter()
.flatten()
.filter_map(|f| f.as_str().map(str::to_owned))
.collect(),
sound: text("sound", "minecraft:empty"),
particle: text("particle", "none"),
loot: t["loot"].as_str().map(str::to_owned),
drop_strategy: text("drop_strategy", "from_middle"),
update_from_neighbors: t["update_from_neighbors"].as_bool().unwrap_or(true),
transform_type: text("transform_type", "single_block"),
consume_on_use: t["consume_on_use"].as_bool().unwrap_or(true),
damage: t["item_damage_per_use"].as_u64().unwrap_or(0) as u32,
});
}
transformers.insert(format!("minecraft:{stem}"), transforms);
}
}
Ok(Self { transformers })
}
/// `BlockTransformer.transformBlock` without the world writes: the first
/// transform that allows the clicked face and provides a state, with its
/// index.
pub fn apply<'a>(
&'a self,
items: &Items,
registry: &BlockRegistry,
id: &str,
face: &str,
around: &dyn Around,
) -> Option<(usize, &'a Transform, BlockState)> {
self.transformers
.get(id)?
.iter()
.enumerate()
.filter(|(_, t)| !t.disallowed_faces.iter().any(|f| f == face))
.find_map(|(i, t)| Some((i, t, t.provider.state(items, registry, around)?)))
}
/// `HoneycombItem.getWaxed`: the waxed twin of a copper block, found from
/// the axe's wax-off transforms (`WAX_OFF_BY_BLOCK` is the inverse of
/// `WAXABLES`).
pub fn waxed(&self, registry: &BlockRegistry, old: &BlockState) -> Option<BlockState> {
for transform in self.transformers.get("minecraft:axe")? {
if transform.particle != "wax_off" {
continue;
}
let Provider::Rules(rules) = &transform.provider else {
continue;
};
for (predicate, then) in rules {
if let (Predicate::Blocks(names), Provider::Copy(source)) = (predicate, then)
&& let Provider::State(unwaxed) = &**source
&& unwaxed.name == old.name
&& let Some(waxed) = names.first()
{
let target = registry
.default_state(waxed)
.and_then(|id| registry.state(id))?
.clone();
return with_properties_of(registry, target, old);
}
}
}
None
}
}
+298
View File
@@ -0,0 +1,298 @@
//! `CauldronInteractions`: what an item does to an empty, water, lava or
//! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item
//! with vanilla's `useItemOn`.
use crate::items::{ItemStack, Items};
/// `ItemTags.CAULDRON_CAN_REMOVE_DYE` membership.
pub fn removes_dye(items: &Items, item: &str) -> bool {
items
.item_tags
.get("minecraft:cauldron_can_remove_dye")
.is_some_and(|members| members.contains(item))
}
use horizon_world::chunk::BlockState;
/// The player side of an interaction.
pub trait Player {
fn creative(&self) -> bool;
/// The stack in the interacting hand.
fn hand(&mut self) -> &mut Option<ItemStack>;
/// `Inventory.add`; the leftover stays in `stack`.
fn add(&mut self, stack: &mut ItemStack) -> bool;
/// `Inventory.contains`.
fn contains(&self, stack: &ItemStack) -> bool;
fn drop_stack(&mut self, stack: ItemStack);
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outcome {
/// `InteractionResult.SUCCESS`
Success,
/// `InteractionResult.CONSUME`
Consume,
/// `TRY_WITH_EMPTY_HAND`
Pass,
}
#[derive(Debug)]
pub struct Interaction {
pub outcome: Outcome,
/// The cauldron's new state.
pub block: Option<BlockState>,
pub sound: Option<&'static str>,
}
fn state(name: &str, level: Option<u8>) -> BlockState {
BlockState {
name: name.to_owned(),
properties: level
.map(|l| ("level".to_owned(), l.to_string()))
.into_iter()
.collect(),
}
}
fn pass() -> Interaction {
Interaction {
outcome: Outcome::Pass,
block: None,
sound: None,
}
}
/// `ItemUtils.createFilledResult`.
fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
let creative = player.creative();
if limit_creative && creative {
if !player.contains(&new) {
let mut new = new;
player.add(&mut new);
}
return;
}
let hand = player.hand();
if !creative && let Some(held) = hand.as_mut() {
held.count -= 1;
if held.count == 0 {
*hand = None;
}
}
if hand.is_none() {
*hand = Some(new);
return;
}
let mut new = new;
if !player.add(&mut new) {
player.drop_stack(new);
}
}
/// `LayeredCauldronBlock.lowerFillLevel`.
fn lowered(cauldron: &BlockState) -> BlockState {
let level: u8 = cauldron
.properties
.get("level")
.and_then(|l| l.parse().ok())
.unwrap_or(1);
if level <= 1 {
state("minecraft:cauldron", None)
} else {
let mut next = cauldron.clone();
next.properties
.insert("level".into(), (level - 1).to_string());
next
}
}
fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction {
Interaction {
outcome: Outcome::Success,
block: Some(block),
sound,
}
}
const COLORS: [&str; 16] = [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black",
];
/// The cauldron interaction of the held item (`useItemOn`); the hand stack is
/// changed through `player`. `removes_dye` is whether the held item is in the
/// `cauldron_can_remove_dye` tag.
pub fn interact(
cauldron: &BlockState,
under_water: bool,
removes_dye: bool,
player: &mut dyn Player,
) -> Interaction {
let Some(held) = player.hand().clone() else {
return pass();
};
let kind = match cauldron.name.as_str() {
"minecraft:cauldron" => "empty",
"minecraft:water_cauldron" => "water",
"minecraft:lava_cauldron" => "lava",
"minecraft:powder_snow_cauldron" => "powder_snow",
_ => return pass(),
};
let level: u8 = cauldron
.properties
.get("level")
.and_then(|l| l.parse().ok())
.unwrap_or(0);
let item = &*held.item;
let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water");
// Dispatcher.get: tags first, then the item map.
if kind == "water" && removes_dye {
if held.data().and_then(|d| d.dyed_color).is_none() {
return pass();
}
if let Some(stack) = player.hand().as_mut() {
stack.data_mut().dyed_color = None;
stack.tidy();
}
return changed(lowered(cauldron), None);
}
let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| {
if !can_fill {
return pass();
}
filled(player, ItemStack::new(new, 1), true);
changed(state("minecraft:cauldron", None), Some(sound))
};
let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| {
filled(player, ItemStack::new("minecraft:bucket", 1), true);
changed(block, Some(sound))
};
match item {
"minecraft:lava_bucket" => {
return if under_water {
Interaction {
outcome: Outcome::Consume,
block: None,
sound: None,
}
} else {
empty_bucket(
player,
state("minecraft:lava_cauldron", None),
"minecraft:item.bucket.empty_lava",
)
};
}
"minecraft:water_bucket" => {
return empty_bucket(
player,
state("minecraft:water_cauldron", Some(3)),
"minecraft:item.bucket.empty",
);
}
"minecraft:powder_snow_bucket" => {
return if under_water {
Interaction {
outcome: Outcome::Consume,
block: None,
sound: None,
}
} else {
empty_bucket(
player,
state("minecraft:powder_snow_cauldron", Some(3)),
"minecraft:item.bucket.empty_powder_snow",
)
};
}
_ => {}
}
match (kind, item) {
("empty", "minecraft:potion") => {
if !water_potion {
return pass();
}
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
changed(
state("minecraft:water_cauldron", Some(1)),
Some("minecraft:item.bottle.empty"),
)
}
("water", "minecraft:bucket") => fill_bucket(
player,
"minecraft:water_bucket",
level == 3,
"minecraft:item.bucket.fill",
),
("water", "minecraft:glass_bottle") => {
filled(
player,
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"),
true,
);
changed(lowered(cauldron), Some("minecraft:item.bottle.fill"))
}
("water", "minecraft:potion") => {
if level == 3 || !water_potion {
return pass();
}
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
let mut next = cauldron.clone();
// BlockState.cycle on a 1..=3 property
next.properties
.insert("level".into(), (level % 3 + 1).to_string());
changed(next, Some("minecraft:item.bottle.empty"))
}
("water", name)
if name
.strip_prefix("minecraft:")
.and_then(|n| n.strip_suffix("_banner"))
.is_some_and(|c| COLORS.contains(&c)) =>
{
let layers = held.data().map_or(0, |d| d.banner_patterns.len());
if layers == 0 {
return pass();
}
let mut cleaned = held.clone();
cleaned.count = 1;
cleaned.data_mut().banner_patterns.pop();
cleaned.tidy();
filled(player, cleaned, false);
changed(lowered(cauldron), None)
}
("water", name)
if name
.strip_prefix("minecraft:")
.and_then(|n| n.strip_suffix("_shulker_box"))
.is_some_and(|c| COLORS.contains(&c)) =>
{
filled(player, held.transmute("minecraft:shulker_box", 1), false);
changed(lowered(cauldron), None)
}
("lava", "minecraft:bucket") => fill_bucket(
player,
"minecraft:lava_bucket",
true,
"minecraft:item.bucket.fill_lava",
),
("powder_snow", "minecraft:bucket") => fill_bucket(
player,
"minecraft:powder_snow_bucket",
level == 3,
"minecraft:item.bucket.fill_powder_snow",
),
_ => pass(),
}
}
+60 -35
View File
@@ -1,6 +1,7 @@
//! Resident client chunk storage. Sections are reference-counted so worker
//! threads can mesh and light immutable snapshots while the game thread edits
//! (copy-on-write through `Arc::make_mut`).
use horizon_core::paletted::{PalettedContainer, Strategy};
use horizon_world::registry::BlockStateId;
use std::sync::Arc;
@@ -8,11 +9,11 @@ pub const MIN_Y: i32 = -64;
pub const HEIGHT: i32 = 384;
pub const SECTIONS: usize = (HEIGHT / 16) as usize;
#[derive(Clone)]
pub enum Blocks {
Uniform(u16),
Full(Box<[u16; 4096]>),
}
/// Block states are `PalettedContainer`s over the pinned registry (35,723
/// states: a 16-bit global palette); biomes are 4x4x4 containers over the
/// biome table (67 entries: a 7-bit global palette).
pub const BLOCK_STRATEGY: Strategy = Strategy::blocks(16);
pub const BIOME_STRATEGY: Strategy = Strategy::biomes(7);
/// Packed light per block: sky light in the high nibble, block light in the low one.
#[derive(Clone)]
pub enum Light {
@@ -25,13 +26,16 @@ pub fn index(x: i32, y: i32, z: i32) -> usize {
}
#[derive(Clone)]
pub struct Section {
pub blocks: Blocks,
pub blocks: PalettedContainer,
/// Biome table index per 4x4x4 cell, `(y << 2 | z) << 2 | x`.
pub biomes: PalettedContainer,
pub light: Light,
}
impl Default for Section {
fn default() -> Self {
Self {
blocks: Blocks::Uniform(0),
blocks: PalettedContainer::new(BLOCK_STRATEGY, 0),
biomes: PalettedContainer::new(BIOME_STRATEGY, 0),
light: Light::Uniform(0xF0),
}
}
@@ -39,23 +43,19 @@ impl Default for Section {
impl Section {
#[inline]
pub fn get(&self, i: usize) -> u16 {
match &self.blocks {
Blocks::Uniform(v) => *v,
Blocks::Full(a) => a[i],
}
self.blocks.get(i) as u16
}
pub fn set(&mut self, i: usize, v: u16) -> u16 {
match &mut self.blocks {
Blocks::Uniform(u) if *u == v => v,
Blocks::Uniform(u) => {
let old = *u;
let mut a = Box::new([old; 4096]);
a[i] = v;
self.blocks = Blocks::Full(a);
old
}
Blocks::Full(a) => std::mem::replace(&mut a[i], v),
}
self.blocks.set(i, u32::from(v)) as u16
}
/// All 4,096 block states in index order.
pub fn unpack(&self, out: &mut [u16; 4096]) {
self.blocks.unpack_u16(out);
}
/// The block states of a whole section at once.
pub fn from_blocks(values: &[u16; 4096]) -> PalettedContainer {
let wide: Vec<u32> = values.iter().map(|&v| u32::from(v)).collect();
PalettedContainer::from_values(BLOCK_STRATEGY, &wide)
}
#[inline]
pub fn light(&self, i: usize) -> u8 {
@@ -65,17 +65,26 @@ impl Section {
}
}
pub fn is_uniform(&self, v: u16) -> bool {
match &self.blocks {
Blocks::Uniform(u) => *u == v,
Blocks::Full(a) => a.iter().all(|&b| b == v),
}
self.blocks.is_uniform(u32::from(v))
}
/// Collapse storage that became uniform.
/// Heap bytes held by the block, biome and light storage (benchmark accounting).
pub fn heap_bytes(&self) -> usize {
self.blocks.heap_bytes()
+ self.biomes.heap_bytes()
+ match &self.light {
Light::Uniform(_) => 0,
Light::Full(_) => 4096,
}
}
/// Collapse storage that became uniform, and drop palette entries no
/// block uses any more.
pub fn compact(&mut self) {
if let Blocks::Full(a) = &self.blocks
&& a.iter().all(|&b| b == a[0])
{
self.blocks = Blocks::Uniform(a[0]);
for container in [&mut self.blocks, &mut self.biomes] {
if container.bits() != 0
&& let Some(v) = container.uniform()
{
*container = PalettedContainer::new(container.strategy(), v);
}
}
if let Light::Full(a) = &self.light
&& a.iter().all(|&b| b == a[0])
@@ -89,8 +98,6 @@ pub struct Chunk {
pub x: i32,
pub z: i32,
pub sections: Vec<Arc<Section>>,
/// Biome index per 4x4x4 cell (x,z in 0..4, y in 0..96) into `Biomes`.
pub biomes: Arc<Vec<u16>>,
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
pub heights: Arc<[i16; 256]>,
pub lit: bool,
@@ -100,6 +107,8 @@ pub struct Chunk {
pub fresh: bool,
/// Block entities read from a save, moved into the world on arrival.
pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>,
/// `CustomName` of the container block entities (shown as the screen title).
pub block_names: Vec<((i32, i32, i32), String)>,
/// Generation postprocessing marks (ProtoChunk.postProcessing) as world
/// positions, applied once by LevelChunk.postProcessGeneration.
pub postprocess: Vec<[i32; 3]>,
@@ -119,12 +128,12 @@ impl Chunk {
sections: (0..SECTIONS)
.map(|_| Arc::new(Section::default()))
.collect(),
biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]),
heights: Arc::new([MIN_Y as i16; 256]),
lit: false,
light_loaded: false,
fresh: false,
block_entities: Vec::new(),
block_names: Vec::new(),
structure_refs: Vec::new(),
postprocess: Vec::new(),
saved: None,
@@ -161,9 +170,25 @@ impl Chunk {
}
self.sections[s as usize].light(index(x, y, z))
}
/// Heap bytes held by the sections (benchmark accounting).
pub fn heap_bytes(&self) -> usize {
self.sections.iter().map(|s| s.heap_bytes()).sum::<usize>()
}
/// Biome table index at a block position (`ChunkAccess.getNoiseBiome` with
/// the quart y clamped to the column).
#[inline]
pub fn biome(&self, x: i32, y: i32, z: i32) -> u16 {
let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1);
self.biomes[(qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize]
self.sections[(qy >> 2) as usize]
.biomes
.get(((qy & 3) << 4 | ((z & 15) >> 2) << 2 | (x & 15) >> 2) as usize) as u16
}
/// Sets the biome of one quart cell (`qy` counts from the column's bottom).
pub fn set_biome_cell(&mut self, qx: i32, qy: i32, qz: i32, biome: u16) {
let section = Arc::make_mut(&mut self.sections[(qy >> 2) as usize]);
section.biomes.set(
((qy & 3) << 4 | (qz & 3) << 2 | (qx & 3)) as usize,
u32::from(biome),
);
}
}
+422 -145
View File
@@ -1,134 +1,445 @@
//! Fixed-rate development simulation driver. Rendering consumes elapsed time;
//! a per-frame work cap retains its backlog instead of dropping simulation time.
//! The rate, freezing, stepping and sprinting are what `/tick` controls
//! (`ServerTickRateManager`).
use std::time::Duration;
//! `DeltaTracker.Timer` and the tick-rate managers of 26.3: how real
//! milliseconds turn into game ticks, partial ticks and real-time deltas, and
//! the `/tick` freeze, step and sprint state.
pub const TICK: Duration = Duration::from_millis(50);
/// Ticks one sprint frame may run.
const SPRINT_PER_FRAME: u32 = 40;
/// `DeltaTracker.Timer`: float arithmetic on integer milliseconds, exactly as
/// the client does it.
#[derive(Clone, Debug)]
pub struct Timer {
delta_ticks: f32,
delta_tick_residual: f32,
realtime_delta_ticks: f32,
paused_delta_tick_residual: f32,
last_ms: i64,
last_ui_ms: i64,
ms_per_tick: f32,
paused: bool,
frozen: bool,
}
impl Timer {
pub fn new(ticks_per_second: f32, current_ms: i64) -> Self {
Self {
delta_ticks: 0.0,
delta_tick_residual: 0.0,
realtime_delta_ticks: 0.0,
paused_delta_tick_residual: 0.0,
last_ms: current_ms,
last_ui_ms: current_ms,
ms_per_tick: 1000.0 / ticks_per_second,
paused: false,
frozen: false,
}
}
/// `advanceGameTime`: the whole ticks to run now. `target_mspt` maps the
/// default milliseconds per tick to the target in force (the tick-rate
/// manager's, when the level runs normally). The caller runs at most ten.
pub fn advance_game_time(
&mut self,
current_ms: i64,
target_mspt: impl FnOnce(f32) -> f32,
) -> i32 {
self.delta_ticks = (current_ms - self.last_ms) as f32 / target_mspt(self.ms_per_tick);
self.last_ms = current_ms;
self.delta_tick_residual += self.delta_ticks;
let ticks = self.delta_tick_residual as i32;
self.delta_tick_residual -= ticks as f32;
ticks
}
/// `advanceRealTime`.
pub fn advance_real_time(&mut self, current_ms: i64) {
self.realtime_delta_ticks = (current_ms - self.last_ui_ms) as f32 / self.ms_per_tick;
self.last_ui_ms = current_ms;
}
/// `updatePauseState`.
pub fn update_pause_state(&mut self, pause: bool) {
if pause {
if !self.paused {
self.paused_delta_tick_residual = self.delta_tick_residual;
}
self.paused = true;
} else {
if self.paused {
self.delta_tick_residual = self.paused_delta_tick_residual;
}
self.paused = false;
}
}
/// `updateFrozenState`.
pub fn update_frozen_state(&mut self, frozen: bool) {
self.frozen = frozen;
}
pub fn game_time_delta_ticks(&self) -> f32 {
self.delta_ticks
}
/// `getGameTimeDeltaPartialTick`.
pub fn game_time_delta_partial_tick(&self, ignore_frozen_game: bool) -> f32 {
if !ignore_frozen_game && self.frozen {
1.0
} else if self.paused {
self.paused_delta_tick_residual
} else {
self.delta_tick_residual
}
}
/// `getRealtimeDeltaTicks`.
pub fn realtime_delta_ticks(&self) -> f32 {
if self.realtime_delta_ticks > 7.0 {
0.5
} else {
self.realtime_delta_ticks
}
}
}
const NANOSECONDS_PER_SECOND: i64 = 1_000_000_000;
const NANOSECONDS_PER_MILLISECOND: i64 = 1_000_000;
/// `TickRateManager`.
#[derive(Clone, Debug)]
pub struct TickRateManager {
tickrate: f32,
nanoseconds_per_tick: i64,
frozen_ticks_to_run: i32,
run_game_elements: bool,
is_frozen: bool,
}
impl Default for TickRateManager {
fn default() -> Self {
Self {
tickrate: 20.0,
nanoseconds_per_tick: NANOSECONDS_PER_SECOND / 20,
frozen_ticks_to_run: 0,
run_game_elements: true,
is_frozen: false,
}
}
}
impl TickRateManager {
/// `setTickRate` (`Math.max(rate, 1.0F)`, NaN propagates).
pub fn set_tick_rate(&mut self, rate: f32) {
self.tickrate = if rate.is_nan() || rate > 1.0 {
rate
} else {
1.0
};
self.nanoseconds_per_tick =
(NANOSECONDS_PER_SECOND as f64 / f64::from(self.tickrate)) as i64;
}
pub fn tickrate(&self) -> f32 {
self.tickrate
}
pub fn milliseconds_per_tick(&self) -> f32 {
self.nanoseconds_per_tick as f32 / NANOSECONDS_PER_MILLISECOND as f32
}
pub fn nanoseconds_per_tick(&self) -> i64 {
self.nanoseconds_per_tick
}
pub fn runs_normally(&self) -> bool {
self.run_game_elements
}
pub fn is_stepping_forward(&self) -> bool {
self.frozen_ticks_to_run > 0
}
pub fn set_frozen_ticks_to_run(&mut self, ticks: i32) {
self.frozen_ticks_to_run = ticks;
}
pub fn frozen_ticks_to_run(&self) -> i32 {
self.frozen_ticks_to_run
}
pub fn set_frozen(&mut self, frozen: bool) {
self.is_frozen = frozen;
}
pub fn is_frozen(&self) -> bool {
self.is_frozen
}
/// `tick`: decides whether game elements run this tick.
pub fn tick(&mut self) {
self.run_game_elements = !self.is_frozen || self.frozen_ticks_to_run > 0;
if self.frozen_ticks_to_run > 0 {
self.frozen_ticks_to_run -= 1;
}
}
/// `isEntityFrozen` for an entity that is not (and does not carry) a player.
pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool {
!self.runs_normally() && !is_player_or_carries_player
}
}
/// What `/tick sprint` reports when it ends.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SprintReport {
pub ticks_per_second: i32,
pub milliseconds_per_tick: String,
}
/// `ServerTickRateManager`: the freeze, step and sprint state kept by the
/// server (the broadcasts to clients are the caller's concern).
#[derive(Clone, Debug, Default)]
pub struct ServerTickRateManager {
pub base: TickRateManager,
remaining_sprint_ticks: i64,
sprint_tick_start_time: i64,
sprint_time_spend: i64,
scheduled_current_sprint_ticks: i64,
previous_is_frozen: bool,
}
impl ServerTickRateManager {
pub fn is_sprinting(&self) -> bool {
self.scheduled_current_sprint_ticks > 0
}
pub fn remaining_sprint_ticks(&self) -> i64 {
self.remaining_sprint_ticks
}
/// `stepGameIfPaused`.
pub fn step_game_if_paused(&mut self, ticks: i32) -> bool {
if !self.base.is_frozen() {
return false;
}
self.base.set_frozen_ticks_to_run(ticks);
true
}
/// `stopStepping`.
pub fn stop_stepping(&mut self) -> bool {
if self.base.frozen_ticks_to_run() > 0 {
self.base.set_frozen_ticks_to_run(0);
true
} else {
false
}
}
/// `stopSprinting`.
pub fn stop_sprinting(&mut self) -> Option<SprintReport> {
if self.remaining_sprint_ticks > 0 {
Some(self.finish_tick_sprint())
} else {
None
}
}
/// `requestGameToSprint`: true when an earlier sprint was interrupted.
pub fn request_game_to_sprint(&mut self, time: i32) -> bool {
let interrupted = self.remaining_sprint_ticks > 0;
self.sprint_time_spend = 0;
self.scheduled_current_sprint_ticks = i64::from(time);
self.remaining_sprint_ticks = i64::from(time);
self.previous_is_frozen = self.base.is_frozen();
self.base.set_frozen(false);
interrupted
}
fn finish_tick_sprint(&mut self) -> SprintReport {
let completed_ticks = self.scheduled_current_sprint_ticks - self.remaining_sprint_ticks;
let milliseconds_to_complete =
(self.sprint_time_spend.max(1)) as f64 / NANOSECONDS_PER_MILLISECOND as f64;
let ticks_per_second = (1000.0 * completed_ticks as f64 / milliseconds_to_complete) as i32;
let per_tick = if completed_ticks == 0 {
f64::from(self.base.milliseconds_per_tick())
} else {
milliseconds_to_complete / completed_ticks as f64
};
self.scheduled_current_sprint_ticks = 0;
self.sprint_time_spend = 0;
self.remaining_sprint_ticks = 0;
self.base.set_frozen(self.previous_is_frozen);
SprintReport {
ticks_per_second,
milliseconds_per_tick: crate::java_text::format_fixed2(per_tick),
}
}
/// `checkShouldSprintThisTick`: whether to run this tick without waiting,
/// plus the report when the sprint just finished.
pub fn check_should_sprint_this_tick(&mut self, now_ns: i64) -> (bool, Option<SprintReport>) {
if !self.base.run_game_elements {
(false, None)
} else if self.remaining_sprint_ticks > 0 {
self.sprint_tick_start_time = now_ns;
self.remaining_sprint_ticks -= 1;
(true, None)
} else {
(false, Some(self.finish_tick_sprint()))
}
}
/// `endTickWork`.
pub fn end_tick_work(&mut self, now_ns: i64) {
self.sprint_time_spend += now_ns - self.sprint_tick_start_time;
}
/// `setTickRate`.
pub fn set_tick_rate(&mut self, rate: f32) {
self.base.set_tick_rate(rate);
}
}
/// Ticks one sprint frame may run (rendering carries on between frames).
const SPRINT_PER_FRAME: i64 = 40;
const SAMPLES: usize = 100;
/// The game's clock: `DeltaTracker.Timer` pacing driven by the
/// `ServerTickRateManager` the `/tick` command controls, over a virtual
/// millisecond clock built from the frame times it is fed. The integrated
/// simulation is one loop, so the tick rate paces it directly (the vanilla
/// client timer only ever slows down, because its server ticks separately).
#[derive(Clone, Debug)]
pub struct FixedStep {
pending: Duration,
/// Ticks per second (`tickrate`).
rate: f32,
frozen: bool,
/// Ticks the frozen world still runs (`/tick step`).
step: u32,
/// Ticks left in a sprint.
sprint: u32,
/// How long recent ticks took (nanoseconds), newest last.
samples: Vec<u64>,
timer: Timer,
manager: ServerTickRateManager,
now: std::time::Duration,
pause: bool,
sprint_checked: bool,
sprint_report: Option<SprintReport>,
tick_times: [i64; SAMPLES],
aggregated: i64,
tick_count: i64,
}
impl Default for FixedStep {
fn default() -> Self {
Self {
pending: Duration::ZERO,
rate: 20.0,
frozen: false,
step: 0,
sprint: 0,
samples: Vec::new(),
timer: Timer::new(20.0, 0),
manager: ServerTickRateManager::default(),
now: std::time::Duration::ZERO,
pause: false,
sprint_checked: false,
sprint_report: None,
tick_times: [0; SAMPLES],
aggregated: 0,
tick_count: 0,
}
}
}
impl FixedStep {
fn now_ms(&self) -> i64 {
self.now.as_millis() as i64
}
fn now_ns(&self) -> i64 {
self.now.as_nanos() as i64
}
/// The length of one tick at the current rate.
pub fn tick_duration(&self) -> Duration {
Duration::from_secs_f64(1.0 / f64::from(self.rate.max(0.01)))
pub fn tick_duration(&self) -> std::time::Duration {
std::time::Duration::from_nanos(self.manager.base.nanoseconds_per_tick().max(1) as u64)
}
pub fn advance(&mut self, elapsed: Duration) -> u32 {
if self.sprint > 0 {
let n = self.sprint.min(SPRINT_PER_FRAME);
self.sprint -= n;
self.pending = Duration::ZERO;
return n;
/// Feed one frame's elapsed time; returns the ticks to run (at most ten,
/// or a sprint frame's worth).
pub fn advance(&mut self, elapsed: std::time::Duration) -> u32 {
self.now += elapsed;
let now_ms = self.now_ms();
if self.manager.is_sprinting() {
// Keep the timer current so leaving the sprint does not replay it.
self.timer.advance_game_time(now_ms, |d| d);
let remaining = self.manager.remaining_sprint_ticks();
// One extra pass lets the sprint finish and report.
return (remaining + 1).min(SPRINT_PER_FRAME) as u32;
}
self.pending += elapsed;
let tick = self.tick_duration();
let steps = (self.pending.as_nanos() / tick.as_nanos().max(1)).min(10) as u32;
self.pending -= tick * steps;
steps
let runs = self.manager.base.runs_normally();
let mspt = self.manager.base.milliseconds_per_tick();
let ticks = self
.timer
.advance_game_time(now_ms, |default| if runs { mspt } else { default });
ticks.clamp(0, 10) as u32
}
/// Restart pacing from now (after loading, so no backlog replays).
pub fn reset(&mut self) {
self.pending = Duration::ZERO;
self.timer = Timer::new(20.0, self.now_ms());
self.timer.update_pause_state(self.pause);
}
/// The partial tick for interpolation (`getGameTimeDeltaPartialTick(false)`).
pub fn fraction(&self) -> f64 {
(self.pending.as_secs_f64() / self.tick_duration().as_secs_f64()).min(1.0)
f64::from(self.timer.game_time_delta_partial_tick(false))
}
/// Whether the world ticks this time (`ServerTickRateManager.runsNormally`
/// or a pending step); called once per tick.
/// After a frame: whether the game is paused by a screen (the residual
/// stops accumulating) and whether the level is frozen.
pub fn end_frame(&mut self, pause: bool) {
self.pause = pause;
self.timer.update_pause_state(pause);
self.timer
.update_frozen_state(!self.manager.base.runs_normally());
}
pub fn paused(&self) -> bool {
self.pause
}
/// `TickRateManager.tick` for one tick, then whether the world runs
/// (`runsNormally`). Also the sprint check that opens a sprint tick.
pub fn world_runs(&mut self) -> bool {
if !self.frozen {
return true;
self.manager.base.tick();
self.sprint_checked = false;
if self.manager.is_sprinting() {
let (_, report) = self.manager.check_should_sprint_this_tick(self.now_ns());
self.sprint_checked = report.is_none();
if report.is_some() {
self.sprint_report = report;
}
}
if self.step > 0 {
self.step -= 1;
return true;
}
false
self.manager.base.runs_normally()
}
/// The report of a sprint that just finished, once.
pub fn take_sprint_report(&mut self) -> Option<SprintReport> {
self.sprint_report.take()
}
pub fn rate(&self) -> f32 {
self.rate
self.manager.base.tickrate()
}
pub fn set_rate(&mut self, rate: f32) {
self.rate = rate.clamp(1.0, 10000.0);
self.manager.set_tick_rate(rate);
}
pub fn frozen(&self) -> bool {
self.frozen
self.manager.base.is_frozen()
}
pub fn set_frozen(&mut self, frozen: bool) {
self.frozen = frozen;
if !frozen {
self.step = 0;
}
self.manager.base.set_frozen(frozen);
}
pub fn sprinting(&self) -> bool {
self.sprint > 0
self.manager.is_sprinting()
}
/// `requestGameToSprint`: true when a sprint was already running.
pub fn start_sprint(&mut self, ticks: u32) -> bool {
let was = self.sprint > 0;
self.sprint = ticks;
was
self.manager
.request_game_to_sprint(ticks.min(i32::MAX as u32) as i32)
}
pub fn stop_sprint(&mut self) -> bool {
let was = self.sprint > 0;
self.sprint = 0;
was
/// `stopSprinting`: the report when a sprint was running.
pub fn stop_sprint(&mut self) -> Option<SprintReport> {
self.manager.stop_sprinting()
}
pub fn stepping(&self) -> bool {
self.step > 0
self.manager.base.is_stepping_forward()
}
/// `stepGameIfPaused`: only works while frozen.
pub fn start_step(&mut self, ticks: u32) -> bool {
if !self.frozen {
return false;
}
self.step = ticks;
true
self.manager
.step_game_if_paused(ticks.min(i32::MAX as u32) as i32)
}
pub fn stop_step(&mut self) -> bool {
let was = self.step > 0;
self.step = 0;
was
self.manager.stop_stepping()
}
pub fn record(&mut self, took: Duration) {
if self.samples.len() == SAMPLES {
self.samples.remove(0);
/// Record how long a tick took (`MinecraftServer.tickServer` bookkeeping
/// and `endTickWork`).
pub fn record(&mut self, took: std::time::Duration) {
let took = took.as_nanos() as i64;
let index = (self.tick_count % SAMPLES as i64) as usize;
self.aggregated -= self.tick_times[index];
self.aggregated += took;
self.tick_times[index] = took;
self.tick_count += 1;
if self.sprint_checked {
let end = self.now_ns() + took;
self.manager.end_tick_work(end);
}
self.samples.push(took.as_nanos() as u64);
}
/// `getAverageTickTimeNanos`.
pub fn average_nanos(&self) -> u64 {
if self.samples.is_empty() {
return 0;
}
self.samples.iter().sum::<u64>() / self.samples.len() as u64
(self.aggregated / SAMPLES.min(self.tick_count.max(1) as usize) as i64).max(0) as u64
}
/// The sorted tick times (p50, p95, p99 inputs) and their count.
/// The sorted `getTickTimesNanos` array (always 100 entries).
pub fn sorted_samples(&self) -> Vec<u64> {
let mut v = self.samples.clone();
let mut v: Vec<u64> = self.tick_times.iter().map(|&t| t.max(0) as u64).collect();
v.sort_unstable();
v
}
@@ -137,70 +448,36 @@ impl FixedStep {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_schedules_preserve_ticks_and_stall_backlog() {
for schedule in [&[7, 13, 18, 12][..], &[50][..], &[1, 999, 2700, 300][..]] {
let mut clock = FixedStep::default();
let mut elapsed = Duration::ZERO;
let mut ticks = 0;
for _ in 0..100 {
for &ms in schedule {
let frame = Duration::from_millis(ms);
elapsed += frame;
let count = clock.advance(frame);
assert!(count <= 10);
ticks += count;
}
}
loop {
let count = clock.advance(Duration::ZERO);
ticks += count;
if count == 0 {
break;
}
}
assert_eq!(u128::from(ticks), elapsed.as_nanos() / TICK.as_nanos());
fn timer_carries_fractions_and_caps_nothing_itself() {
let mut t = Timer::new(20.0, 0);
assert_eq!(t.advance_game_time(49, |d| d), 0);
assert_eq!(t.advance_game_time(50, |d| d), 1);
assert_eq!(t.advance_game_time(1050, |d| d), 20);
}
#[test]
fn pause_restores_the_residual() {
let mut t = Timer::new(20.0, 0);
t.advance_game_time(25, |d| d);
t.update_pause_state(true);
t.advance_game_time(1000, |d| d);
assert_eq!(t.game_time_delta_partial_tick(false), 0.5);
t.update_pause_state(false);
assert_eq!(t.game_time_delta_partial_tick(false), 0.5);
}
#[test]
fn frozen_step_runs_exactly_the_requested_ticks() {
let mut m = ServerTickRateManager::default();
m.base.set_frozen(true);
m.base.tick();
assert!(!m.base.runs_normally());
assert!(m.step_game_if_paused(2));
for _ in 0..2 {
m.base.tick();
assert!(m.base.runs_normally());
}
}
#[test]
fn pause_discards_only_explicitly_reset_time() {
let mut clock = FixedStep::default();
assert_eq!(clock.advance(Duration::from_millis(49)), 0);
assert_eq!(clock.advance(Duration::from_millis(1)), 1);
assert_eq!(clock.advance(Duration::from_millis(24)), 0);
clock.reset();
assert_eq!(clock.advance(Duration::from_millis(26)), 0);
assert_eq!(clock.advance(Duration::from_millis(24)), 1);
}
#[test]
fn rate_changes_the_tick_length() {
let mut clock = FixedStep::default();
clock.set_rate(40.0);
assert_eq!(clock.advance(Duration::from_millis(100)), 4);
clock.set_rate(5.0);
assert_eq!(clock.advance(Duration::from_millis(400)), 2);
clock.set_rate(1.0e9);
assert_eq!(clock.rate(), 10000.0);
}
#[test]
fn freeze_step_and_sprint() {
let mut clock = FixedStep::default();
assert!(clock.world_runs());
assert!(!clock.start_step(3), "stepping needs a frozen game");
clock.set_frozen(true);
assert!(!clock.world_runs());
assert!(clock.start_step(2));
assert!(clock.world_runs() && clock.world_runs() && !clock.world_runs());
assert!(clock.start_step(5) && clock.stop_step() && !clock.stop_step());
clock.set_frozen(false);
assert!(!clock.start_sprint(100));
assert!(clock.sprinting());
assert_eq!(clock.advance(Duration::ZERO), SPRINT_PER_FRAME);
assert!(clock.stop_sprint() && !clock.sprinting());
for ns in [3, 1, 2] {
clock.record(Duration::from_nanos(ns));
}
assert_eq!(clock.average_nanos(), 2);
assert_eq!(clock.sorted_samples(), vec![1, 2, 3]);
m.base.tick();
assert!(!m.base.runs_normally());
}
}
@@ -40,6 +40,7 @@ pub struct Registries {
/// Boss bar ids and datapack predicate ids.
pub bossbars: Vec<String>,
pub predicates: Vec<String>,
pub item_modifiers: Vec<String>,
pub schedules: Vec<String>,
pub stopwatches: Vec<String>,
pub recipes: Vec<String>,
@@ -1936,6 +1937,7 @@ impl ArgType {
"templates" => reg.templates.clone(),
"random_sequences" => reg.random_sequences.clone(),
"predicates" => reg.predicates.clone(),
"item_modifiers" => reg.item_modifiers.clone(),
"time_markers" => reg.time_markers.clone(),
"advancements" => reg.advancements.clone(),
_ => Vec::new(),
@@ -222,6 +222,14 @@ fn data_and_tag_commands_parse() {
assert_eq!(id, "data.get");
assert_eq!(args, ["target", "path", "scale"]);
assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get");
assert_eq!(
run("item modify entity @s weapon.mainhand a:b").unwrap().0,
"item.modify"
);
assert_eq!(
run("item modify block 1 2 3 container.0 a:b").unwrap().0,
"item.modify"
);
assert_eq!(run("data get storage my:store").unwrap().0, "data.get");
assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge");
assert_eq!(
@@ -151,6 +151,18 @@ pub fn register(d: &mut Dispatcher, root: usize) {
fn item(d: &mut Dispatcher, root: usize) {
let item = d.literal(root, "item");
d.requires(item, GAMEMASTERS);
let modify = d.literal(item, "modify");
for provider in ["entity", "block"] {
let p = d.literal(modify, provider);
let target = if provider == "entity" {
d.argument(p, "target", ENTITIES)
} else {
d.argument(p, "targetPos", ArgType::BlockPos)
};
let slot = d.argument(target, "slot", ArgType::Slot);
let modifier = d.argument(slot, "modifier", ArgType::Id("item_modifiers"));
d.executes(modifier, "item.modify");
}
for mode in ["replace", "fill", "override"] {
let m = d.literal(item, mode);
for provider in ["entity", "block"] {
File diff suppressed because it is too large Load Diff
+7
View File
@@ -280,6 +280,8 @@ pub struct DataStore {
/// Function tag id -> entries (`ns:f`, `#ns:tag`), with `required` flags.
pub function_tags: BTreeMap<String, Vec<(String, bool)>>,
pub predicates: BTreeMap<String, serde_json::Value>,
/// `item_modifier` files, for `/item modify`.
pub item_modifiers: BTreeMap<String, serde_json::Value>,
/// Functions that failed to parse (id, message), for logging.
pub errors: Vec<(String, String)>,
}
@@ -322,6 +324,11 @@ impl DataStore {
&& let Ok(v) = serde_json::from_slice(&bytes)
{
s.predicates.insert(id, v);
} else if let Some(id) = resource_id(&f, "item_modifier", ".json")
&& let Some(bytes) = pack.read(&f)
&& let Ok(v) = serde_json::from_slice(&bytes)
{
s.item_modifiers.insert(id, v);
}
}
}
+22 -17
View File
@@ -239,11 +239,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&"Items".into());
}
let mut equipment = Vec::new();
if m.extra.saddled {
equipment.push((
"saddle",
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
));
if let Some(saddle) = m.saddle_item() {
equipment.push(("saddle", crate::save::item_to_nbt(&saddle)));
}
if let Some(armor) = &m.extra.head {
equipment.push((
@@ -273,11 +270,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
if m.extra.saddled {
equipment.insert(
"saddle".into(),
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
);
if let Some(saddle) = m.saddle_item() {
equipment.insert("saddle".into(), crate::save::item_to_nbt(&saddle));
} else {
equipment.remove(&"saddle".into());
}
@@ -354,10 +348,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:warden" => {
if let Some(st) = &m.extra.warden {
map.insert("listener".into(), st.vibration.to_nbt());
map.insert(
"anger".into(),
Tag::compound([("suspects", Tag::List(Vec::new()))]),
);
map.insert("anger".into(), Tag::compound(Vec::<(&str, Tag)>::new()));
}
}
"minecraft:ravager" => {
@@ -541,6 +532,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
crate::mobs::gear::set(&mut m, index, stack.enchantments().to_vec());
}
}
} else {
// Registration hands out default weapons (finalizeSpawn does in
// vanilla); a loaded mob holds only what its file lists.
m.extra.main_hand = None;
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent = flag(tag, "PersistenceRequired");
@@ -571,8 +566,15 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.species(),
crate::mobs::Species::Pig | crate::mobs::Species::Strider
) {
m.extra.saddled =
tag.get("equipment").and_then(|e| e.get("saddle")).is_some() || flag(tag, "Saddle");
let saddle = tag
.get("equipment")
.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt);
if saddle.is_some() || flag(tag, "Saddle") {
m.set_saddle(Some(saddle.unwrap_or_else(|| {
crate::items::ItemStack::new("minecraft:saddle", 1)
})));
}
}
if crate::mobs::equine::is_equine(m.species()) {
m.extra.tame = flag(tag, "Tame");
@@ -589,7 +591,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
}
let eq = tag.get("equipment");
m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some();
m.set_saddle(
eq.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt),
);
m.extra.head = eq
.and_then(|e| e.get("body"))
.and_then(|b| text(b.get("id")))
+21 -10
View File
@@ -229,7 +229,7 @@ impl Environment {
self.base.get(name).copied().unwrap_or([0.0, 0.0, 0.0, 1.0])
}
/// Sky state for a time of day, with the biome's sky and fog colours as base values.
pub fn sample(&self, ticks: i64, biome_sky: u32, biome_fog: u32) -> Sky {
pub fn sample(&self, ticks: i64, biome_sky: Option<u32>, biome_fog: Option<u32>) -> Sky {
let rgb = |c: u32| {
[
(c >> 16 & 255) as f32 / 255.0,
@@ -260,8 +260,14 @@ impl Environment {
.map_or(0.0, |t| t.sample(ticks, self.period)[0])
};
Sky {
sky_color: three(v("minecraft:visual/sky_color", rgb(biome_sky))),
fog_color: three(v("minecraft:visual/fog_color", rgb(biome_fog))),
sky_color: three(v(
"minecraft:visual/sky_color",
biome_sky.map_or_else(|| self.base("minecraft:visual/sky_color"), rgb),
)),
fog_color: three(v(
"minecraft:visual/fog_color",
biome_fog.map_or_else(|| self.base("minecraft:visual/fog_color"), rgb),
)),
sky_light_factor: scalar("minecraft:visual/sky_light_factor"),
sky_light_color: three(v(
"minecraft:visual/sky_light_color",
@@ -279,7 +285,10 @@ impl Environment {
.map_or([0.0; 4], |t| t.sample(ticks, self.period)),
cloud_color: v(
"minecraft:visual/cloud_color",
self.base("minecraft:visual/cloud_color"),
self.base
.get("minecraft:visual/cloud_color")
.copied()
.unwrap_or([0.0; 4]),
),
sky_light_level: scalar("minecraft:gameplay/sky_light_level") / 15.0,
fog_start: self
@@ -304,24 +313,26 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) {
std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t)
};
let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t;
let night = [0.48, 0.48, 1.0];
// Vanilla stores these colours as 8-bit ARGB (`ARGB.colorFromFloat` floors).
let q = |v: f32| (v * 255.0).floor() / 255.0;
let night = [q(0.48), q(0.48), 1.0];
// (level, sky gray (brightness, factor), fog multiplier, cloud gray, alpha, sunrise multiplier)
let layers = [
(
rain - thunder,
(0.6, 0.75),
[0.5, 0.5, 0.6],
[q(0.5), q(0.5), q(0.6)],
(0.24, 0.5),
0.3125,
[0.5, 0.5, 0.6],
[q(0.5), q(0.5), q(0.6)],
),
(
thunder,
(0.24, 0.94),
[0.25, 0.25, 0.3],
[q(0.25), q(0.25), q(0.3)],
(0.095, 0.94),
0.527_343_75,
[0.25, 0.25, 0.3],
[q(0.25), q(0.25), q(0.3)],
),
];
for (level, (sb, sf), fog, (cb, cf), alpha, sunrise) in layers {
@@ -347,7 +358,7 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) {
sky.sky_light_color = lerp3(
level,
sky.sky_light_color,
lerp3(alpha, sky.sky_light_color, night),
lerp3(q(alpha), sky.sky_light_color, night),
);
sky.sky_light_factor = lerp(
level,
+22
View File
@@ -68,8 +68,30 @@ pub struct FogState {
pub water_vision_time: i32,
/// `AtmosphericFogEnvironment.rainFogMultiplier`.
pub rain_fog_multiplier: f32,
/// `LightmapRenderStateExtractor.blockLightFlicker`.
pub block_light_flicker: f32,
flicker_seed: u64,
}
impl FogState {
fn next_float(&mut self) -> f32 {
// splitmix64: the vanilla source is unseeded `RandomSource.create()`.
self.flicker_seed = self.flicker_seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.flicker_seed;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
((z ^ (z >> 31)) >> 40) as f32 / (1u32 << 24) as f32
}
/// `LightmapRenderStateExtractor.tick`: the torch light flickers.
pub fn tick_flicker(&mut self) {
let (a, b, c, d) = (
self.next_float(),
self.next_float(),
self.next_float(),
self.next_float(),
);
self.block_light_flicker += (a - b) * c * d * 0.1;
self.block_light_flicker *= 0.9;
}
/// `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 {
File diff suppressed because it is too large Load Diff
@@ -536,6 +536,7 @@ impl Game<'_> {
"setworldspawn" => self.cmd_setworldspawn(ctx),
"clear" => self.cmd_clear(ctx),
"item" => self.cmd_item(ctx),
"item.modify" => self.cmd_item_modify(ctx),
"place" => self.cmd_place(ctx),
"recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx),
"damage" => self.cmd_damage(ctx),
@@ -312,6 +312,240 @@ impl Game<'_> {
extra,
}))
}
/// One item modifier (a typed object, a list or a datapack reference)
/// applied to a stack; `None` when the stack ends up empty.
fn apply_item_modifier(
&self,
m: &serde_json::Value,
stack: Option<ItemStack>,
rng: &mut horizon_core::random::LegacyRandom,
this: Option<&horizon_client::advancements::EntityView>,
origin: [f64; 3],
depth: u32,
) -> Option<ItemStack> {
use horizon_core::random::RandomSource;
use serde_json::Value;
if depth > 16 {
return stack;
}
let int = |v: &Value, rng: &mut horizon_core::random::LegacyRandom| -> i32 {
if let Some(n) = v.as_f64() {
return n as i32;
}
let min = v["min"].as_f64().unwrap_or(0.) as i32;
let max = v["max"].as_f64().unwrap_or(0.) as i32;
match v["type"].as_str().unwrap_or("minecraft:constant") {
"minecraft:uniform" | "uniform" => rng
.next_int_between_inclusive(min, max.max(min))
.unwrap_or(min),
_ => v["value"].as_f64().unwrap_or(0.) as i32,
}
};
match m {
Value::Array(list) => list.iter().fold(stack, |s, f| {
self.apply_item_modifier(f, s, rng, this, origin, depth + 1)
}),
Value::String(id) => match self.fns.store.item_modifiers.get(id) {
Some(f) => self.apply_item_modifier(f, stack, rng, this, origin, depth + 1),
None => stack,
},
Value::Object(_) => {
let mut stack = stack?;
if !m["conditions"].is_null()
&& !self.conditions_hold(&m["conditions"], this, origin)
{
return Some(stack);
}
match m["function"].as_str().unwrap_or("") {
"minecraft:sequence" => {
#[allow(clippy::manual_try_fold)]
return m["functions"]
.as_array()
.into_iter()
.flatten()
.fold(Some(stack), |s, f| {
self.apply_item_modifier(f, s, rng, this, origin, depth + 1)
});
}
"minecraft:set_count" => {
let n = int(&m["count"], rng);
let base = if m["add"].as_bool() == Some(true) {
stack.count as i32
} else {
0
};
let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack);
stack.count = (base + n).clamp(0, max as i32) as u32;
}
"minecraft:limit_count" => {
let min = m["limit"]["min"].as_i64().or(m["limit"].as_i64());
let max = m["limit"]["max"].as_i64().or(m["limit"].as_i64());
if let Some(min) = min {
stack.count = stack.count.max(min as u32);
}
if let Some(max) = max {
stack.count = stack.count.min(max as u32);
}
}
"minecraft:set_damage" => {
let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
if max > 0 {
let f = match m["damage"].as_f64() {
Some(f) => f as f32,
None => {
let lo = m["damage"]["min"].as_f64().unwrap_or(0.) as f32;
let hi = m["damage"]["max"].as_f64().unwrap_or(0.) as f32;
lo + rng.next_float() * (hi - lo)
}
};
let base = if m["add"].as_bool() == Some(true) {
1. - stack.damage as f32 / max as f32
} else {
0.
};
let frac = (base + f).clamp(0., 1.);
stack.damage = ((1. - frac) * max as f32).floor() as u32;
}
}
"minecraft:set_name" => {
let t = horizon_client::packs::component(&m["name"]);
stack.extra.get_or_insert_with(Default::default).custom_name =
Some(t.plain());
}
"minecraft:set_enchantments" => {
let add = m["add"].as_bool() == Some(true);
let d = stack.extra.get_or_insert_with(Default::default);
let target = if &*stack.item == "minecraft:enchanted_book" {
&mut d.stored_enchantments
} else {
&mut d.enchantments
};
for (id, level) in m["enchantments"].as_object().into_iter().flatten() {
let n = int(level, rng).clamp(0, 255) as u32;
let id: std::sync::Arc<str> = if id.contains(':') {
id.as_str().into()
} else {
format!("minecraft:{id}").into()
};
match target.iter_mut().find(|(e, _)| *e == id) {
Some(e) => e.1 = if add { e.1 + n } else { n },
None => target.push((id, n)),
}
target.retain(|(_, l)| *l > 0);
}
}
"minecraft:set_potion" => {
if let Some(p) = m["id"].as_str() {
stack.extra.get_or_insert_with(Default::default).potion =
Some(p.into());
}
}
_ => {}
}
(stack.count > 0).then_some(stack)
}
_ => stack,
}
}
/// `/item modify (entity|block) <target> <slot> <modifier>`.
pub(super) fn cmd_item_modify(&mut self, ctx: &Context) -> R<i32> {
self.ensure_datapacks();
let targets = self.owner_of(ctx, "target", true)?;
let Some(Arg::Str(slot_name)) = ctx.get("slot").cloned() else {
return Ok(0);
};
let Some(Arg::Str(id)) = ctx.get("modifier").cloned() else {
return Ok(0);
};
let id = if id.contains(':') {
id
} else {
format!("minecraft:{id}")
};
let Some(modifier) = self.fns.store.item_modifiers.get(&id).cloned() else {
return Err(err("argument.item_modifier.unknown", &[&id]));
};
let source = self.command_source.unwrap_or_else(|| self.player_source());
let view = source.entity.map(|t| self.entity_view_of(t));
let seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as i64);
let mut rng = horizon_core::random::LegacyRandom::new(seed);
let mut tracker = Tracker::default();
let mut selected = 0;
for o in &targets {
let slots = self.slots_named(o, &slot_name);
if slots.is_empty() {
if let Owner::Block(p) = o
&& !self.world.block_entities.contains_key(&(p[0], p[1], p[2]))
{
return Err(err(
"commands.item.target.not_a_container",
&[&p[0], &p[1], &p[2]],
));
}
continue;
}
let mut changed = 0;
for slot in &slots {
// SlotSelector.NON_EMPTY_SLOTS
let Some(current) = self.slot_get(slot) else {
continue;
};
selected += 1;
let new = self.apply_item_modifier(
&modifier,
Some(current.clone()),
&mut rng,
view.as_ref(),
source.pos,
0,
);
if new.as_ref() != Some(&current) && self.slot_set(slot, new) {
changed += 1;
}
}
let h = self.owner_holder(o);
tracker.track(&h, changed);
}
if selected == 0 {
return Err(err("commands.item.target.no_such_slot", &[&slot_name]));
}
let pos = match targets.first() {
Some(Owner::Block(p)) => Some(*p),
_ => None,
};
let (message, total) = tracker.message(
false,
Some(err("commands.item.target.failed", &[])),
|h, count| {
let n = Text::literal(count.to_string());
match pos {
Some(p) => Text::translate(
"commands.item.block.modify.success",
&[
n,
Text::literal(p[0].to_string()),
Text::literal(p[1].to_string()),
Text::literal(p[2].to_string()),
],
),
None => Text::translate(
"commands.item.entity.modify.success.single",
&[n, h.text.clone()],
),
}
},
|c, _| {
Text::translate(
"commands.item.entity.modify.success.multiple",
&[Text::literal(c.to_string())],
)
},
)?;
self.feedback(message);
Ok(total)
}
/// `/item replace|fill|override <target> <slots> (with <item> [count] | from <source> <slots>)`.
pub(super) fn cmd_item(&mut self, ctx: &Context) -> R<i32> {
let mode = ctx
@@ -1,11 +1,15 @@
//! `/random` (RandomCommand) and `/teammsg` (TeamMsgCommand).
use super::{Arg, Context, Game, R, Target, err};
use crate::game::chat::PLAYER_NAME;
use horizon_client::text::{self, Text};
use horizon_client::{
clock::SprintReport,
java_text::format_fixed,
text::{self, Text},
};
use horizon_core::random::RandomSource;
fn millis(nanos: u64) -> String {
format!("{:.1}", nanos as f32 / 1_000_000.0)
format_fixed(f64::from(nanos as f32 / 1_000_000.0), 1)
}
impl Game<'_> {
@@ -79,14 +83,14 @@ impl Game<'_> {
self.clock.set_rate(rate);
self.feedback(t(
"commands.tick.rate.success",
&[lit(format!("{rate:.1}"))],
&[lit(format_fixed(f64::from(rate), 1))],
));
Ok(rate as i32)
}
"tick.query" => {
let rate = self.clock.rate();
let busy = millis(self.clock.average_nanos());
let rate_text = format!("{rate:.1}");
let rate_text = format_fixed(f64::from(rate), 1);
if self.clock.sprinting() {
self.feedback(t("commands.tick.status.sprinting", &[]));
self.feedback(t(
@@ -137,16 +141,19 @@ impl Game<'_> {
Ok(1)
}
"tick.sprint.stop" => {
if !self.clock.stop_sprint() {
let Some(report) = self.clock.stop_sprint() else {
return Err(err("commands.tick.sprint.stop.fail", &[]));
}
};
self.sprint_report(&report);
self.feedback(t("commands.tick.sprint.stop.success", &[]));
Ok(1)
}
"tick.freeze" | "tick.unfreeze" => {
let freeze = id == "tick.freeze";
if freeze {
self.clock.stop_sprint();
if let Some(report) = self.clock.stop_sprint() {
self.sprint_report(&report);
}
self.clock.stop_step();
}
self.clock.set_frozen(freeze);
@@ -176,6 +183,16 @@ impl Game<'_> {
}
}
}
/// The report `/tick sprint` prints when a sprint ends.
pub(in crate::game) fn sprint_report(&mut self, report: &SprintReport) {
self.feedback(Text::translate(
"commands.tick.sprint.report",
&[
Text::literal(report.ticks_per_second.to_string()),
Text::literal(report.milliseconds_per_tick.clone()),
],
));
}
pub(super) fn cmd_random(&mut self, id: &str, ctx: &Context) -> R<i32> {
let seed = self.level.seed;
if id == "random.reset" {
@@ -214,10 +214,9 @@ impl Game<'_> {
continue;
}
let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1);
let index = (qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize;
if let Some(chunk) = self.world.chunks.get_mut(&key) {
let chunk = std::sync::Arc::make_mut(chunk);
std::sync::Arc::make_mut(&mut chunk.biomes)[index] = target as u16;
chunk.set_biome_cell((x & 15) >> 2, qy, (z & 15) >> 2, target as u16);
}
touched.insert(key);
changed += 1;
+7 -2
View File
@@ -466,6 +466,11 @@ impl Game<'_> {
block_tags: &self.res.items.block_tags,
biomes: &self.res.biomes,
mob_griefing: self.ui.rules.bool("mob_griefing"),
difficulty: self.local_difficulty(
self.player
.as_ref()
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]),
),
}
}
/// `ServerLevel.getCurrentDifficultyAt`.
@@ -777,8 +782,8 @@ impl Game<'_> {
}
// Saddles, horse armour and chests always drop.
let mut gear: Vec<&str> = Vec::new();
if m.extra.saddled {
gear.push("minecraft:saddle");
if let Some(saddle) = m.saddle_item() {
self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10);
}
// WitherBoss.dropCustomDeathLoot.
if m.species() == Species::Wither {
+2 -1
View File
@@ -578,7 +578,7 @@ impl Game<'_> {
(_, Some(1)) => m.extra.chest = Some(item.clone()),
(_, Some(2)) => m.extra.legs = Some(item.clone()),
(_, Some(3)) => m.extra.feet = Some(item.clone()),
("saddle", _) => m.extra.saddled = true,
("saddle", _) => m.set_saddle(Some(one.clone())),
_ => m.extra.head = Some(item.clone()),
}
// setGuaranteedDrop / setPersistenceRequired.
@@ -1155,6 +1155,7 @@ impl Game<'_> {
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(target, entity);
self.fill_placed_box([target.0, target.1, target.2], &stack);
self.name_placed_container([target.0, target.1, target.2], &stack);
}
let sounds = self.res.facts.get(state).sounds.clone();
self.audio.play(
+7 -2
View File
@@ -933,9 +933,14 @@ impl Game<'_> {
};
let mut found = Vec::new();
for (s, section) in chunk.sections.iter().enumerate() {
let horizon_client::chunk::Blocks::Full(blocks) = &section.blocks else {
if !section
.blocks
.maybe_has(|v| v == u32::from(portal) || v == u32::from(gateway))
{
continue;
};
}
let mut blocks = Box::new([0u16; 4096]);
section.unpack(&mut blocks);
for (i, &b) in blocks.iter().enumerate() {
if b == portal || b == gateway {
let y = horizon_client::chunk::MIN_Y + s as i32 * 16 + (i >> 8) as i32;
+1
View File
@@ -79,6 +79,7 @@ impl Game<'_> {
let ally = matches!(
m.species(),
Species::Evoker
| Species::Illusioner
| Species::Vex
| Species::Pillager
| Species::Vindicator
@@ -123,6 +123,7 @@ impl Game<'_> {
reg.functions = self.fns.store.functions.keys().cloned().collect();
reg.function_tags = self.fns.store.function_tags.keys().cloned().collect();
reg.predicates = self.fns.store.predicates.keys().cloned().collect();
reg.item_modifiers = self.fns.store.item_modifiers.keys().cloned().collect();
reg.schedules = self.fns.schedule.iter().map(|s| s.id.clone()).collect();
reg.datapacks_enabled = std::iter::once("vanilla".to_owned())
.chain(self.fns.enabled.iter().cloned())
@@ -0,0 +1,226 @@
//! `Hud.extractPlayerHealth`: armour, hearts, food. The layout is computed as
//! a list of sprites so it can be tested without drawing.
use std::time::Instant;
/// `java.util.Random`, for the HUD's per-tick jitter.
pub(super) struct JavaRandom(i64);
impl JavaRandom {
pub fn new(seed: i64) -> Self {
Self((seed ^ 0x5_DEEC_E66D) & ((1 << 48) - 1))
}
fn next(&mut self, bits: u32) -> i32 {
self.0 = (self.0.wrapping_mul(0x5_DEEC_E66D).wrapping_add(0xB)) & ((1 << 48) - 1);
(self.0 >> (48 - bits)) as i32
}
pub fn next_int(&mut self, bound: i32) -> i32 {
let mut r = self.next(31);
let m = bound - 1;
if bound & m == 0 {
return ((i64::from(bound) * i64::from(r)) >> 31) as i32;
}
let mut u = r;
loop {
r = u % bound;
if u.wrapping_sub(r).wrapping_add(m) >= 0 {
return r;
}
u = self.next(31);
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum HeartKind {
Normal,
Poisoned,
Withered,
Absorbing,
}
impl HeartKind {
fn prefix(self) -> &'static str {
match self {
Self::Normal => "",
Self::Poisoned => "poisoned_",
Self::Withered => "withered_",
Self::Absorbing => "absorbing_",
}
}
}
/// State kept between frames (`Hud.lastHealth`, `displayHealth`, ...).
pub(super) struct HealthHud {
last_health: i32,
display_health: i32,
last_health_time: Instant,
health_blink_time: i64,
}
impl Default for HealthHud {
fn default() -> Self {
Self {
last_health: 0,
display_health: 0,
last_health_time: Instant::now(),
health_blink_time: 0,
}
}
}
pub(super) struct HealthInputs {
pub tick: u64,
pub health: f32,
pub max_health: f32,
pub absorption: f32,
pub armor: i32,
pub food: i32,
pub saturation: f32,
pub kind: HeartKind,
pub regeneration: bool,
pub hunger: bool,
pub hardcore: bool,
/// `damageCooldownTime > 0`.
pub damage_cooldown: bool,
/// A mount with its own hearts replaces the food bar.
pub show_food: bool,
}
fn heart_sprite(kind: HeartKind, hardcore: bool, half: bool, blink: bool) -> String {
let (hc, h) = (
if hardcore { "hardcore_" } else { "" },
if half { "half" } else { "full" },
);
let b = if blink { "_blinking" } else { "" };
format!("gui/sprites/hud/heart/{}{hc}{h}{b}", kind.prefix())
}
impl HealthHud {
/// Sprites (name, x, y) in draw order for a screen of `w` x `h` GUI pixels.
pub fn layout(
&mut self,
i: &HealthInputs,
w: i32,
h: i32,
now: Instant,
) -> Vec<(String, i32, i32)> {
let mut out = Vec::new();
let tick = i64::try_from(i.tick).unwrap_or(i64::MAX);
let current = i.health.ceil() as i32;
let blink = self.health_blink_time > tick && (self.health_blink_time - tick) / 3 % 2 == 1;
if current < self.last_health && i.damage_cooldown {
self.last_health_time = now;
self.health_blink_time = tick + 20;
} else if current > self.last_health && i.damage_cooldown {
self.last_health_time = now;
self.health_blink_time = tick + 10;
}
if now.duration_since(self.last_health_time).as_millis() > 1000 {
self.display_health = current;
self.last_health_time = now;
}
self.last_health = current;
let old = self.display_health;
let mut random = JavaRandom::new(i64::from((i.tick as i32).wrapping_mul(312_871)));
let (x_left, x_right, y_base) = (w / 2 - 91, w / 2 + 91, h - 39);
let max_health = i.max_health.max(old.max(current) as f32);
let absorption = i.absorption.ceil() as i32;
let rows = ((max_health + absorption as f32) / 2.0 / 10.0).ceil() as i32;
let row_height = (10 - (rows - 2)).max(3);
let offset_index = if i.regeneration {
(i.tick as i32).rem_euclid((max_health + 5.0).ceil() as i32)
} else {
-1
};
if i.armor > 0 {
let y = y_base - (rows - 1) * row_height - 10;
for n in 0..10 {
let name = match (n * 2 + 1).cmp(&i.armor) {
std::cmp::Ordering::Less => "armor_full",
std::cmp::Ordering::Equal => "armor_half",
std::cmp::Ordering::Greater => "armor_empty",
};
out.push((format!("gui/sprites/hud/{name}"), x_left + n * 8, y));
}
}
let containers = (max_health / 2.0).ceil() as i32;
let absorb_containers = (absorption as f32 / 2.0).ceil() as i32;
let container = |hardcore: bool, blink: bool| {
format!(
"gui/sprites/hud/heart/container{}{}",
if hardcore { "_hardcore" } else { "" },
if blink { "_blinking" } else { "" }
)
};
for c in (0..containers + absorb_containers).rev() {
let (row, column) = (c / 10, c % 10);
let x = x_left + column * 8;
let mut y = y_base - row * row_height;
if current + absorption <= 4 {
y += random.next_int(2);
}
if c < containers && c == offset_index {
y -= 2;
}
out.push((container(i.hardcore, blink), x, y));
let halves = c * 2;
if c >= containers {
let ah = halves - containers * 2;
if ah < absorption {
let kind = if i.kind == HeartKind::Withered {
i.kind
} else {
HeartKind::Absorbing
};
out.push((
heart_sprite(kind, i.hardcore, ah + 1 == absorption, false),
x,
y,
));
}
}
if blink && halves < old {
out.push((
heart_sprite(i.kind, i.hardcore, halves + 1 == old, true),
x,
y,
));
}
if halves < current {
out.push((
heart_sprite(i.kind, i.hardcore, halves + 1 == current, false),
x,
y,
));
}
}
if i.show_food {
let suffix = if i.hunger { "_hunger" } else { "" };
for n in 0..10 {
let mut y = y_base;
if i.saturation <= 0.0 && (i.tick as i32).rem_euclid(i.food * 3 + 1) == 0 {
y += random.next_int(3) - 1;
}
let x = x_right - n * 8 - 9;
out.push((format!("gui/sprites/hud/food_empty{suffix}"), x, y));
if n * 2 + 1 < i.food {
out.push((format!("gui/sprites/hud/food_full{suffix}"), x, y));
}
if n * 2 + 1 == i.food {
out.push((format!("gui/sprites/hud/food_half{suffix}"), x, y));
}
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn java_random_matches_reference() {
// new Random(42).nextInt(10) sequence: 0, 3, 8, 4, 0.
let mut r = JavaRandom::new(42);
let v: Vec<i32> = (0..5).map(|_| r.next_int(10)).collect();
assert_eq!(v, [0, 3, 8, 4, 0]);
}
}
@@ -746,6 +746,7 @@ impl Game<'_> {
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
}
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
let title = &self.container_title(title.to_owned());
let title_x = if screen == Screen::Hopper {
8.0
} else {
@@ -125,7 +125,7 @@ impl Game<'_> {
true,
horizon_world::level::flags::UPDATE_CLIENTS,
);
let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result);
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
self.crafter_eject(key, facing, result, &recipe);
for rest in remainders.into_iter().flatten() {
self.crafter_eject(key, facing, rest, &recipe);
@@ -270,7 +270,7 @@ impl Game<'_> {
256.0,
);
let grey = rgba(64, 64, 64, 255);
let title = self.translate("container.crafter", "Crafter");
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+4 -7
View File
@@ -67,10 +67,7 @@ impl Game<'_> {
mob: m.id,
species,
columns,
saddle: m
.extra
.saddled
.then(|| ItemStack::new("minecraft:saddle", 1)),
saddle: m.saddle_item(),
armor: m
.extra
.head
@@ -137,18 +134,18 @@ impl Game<'_> {
let Some(index) = self.mount_mob_index(open.mob) else {
return;
};
let (saddle, armor) = (open.saddle.is_some(), open.armor.clone());
let (saddle, armor) = (open.saddle.clone(), open.armor.clone());
let items = open.items.clone();
let m = &mut self.mobs[index];
let at = m.center();
let sound = if saddle && !m.extra.saddled {
let sound = if saddle.is_some() && !m.extra.saddled {
Some("minecraft:entity.horse.saddle")
} else if armor.is_some() && m.extra.head.is_none() {
Some("minecraft:entity.horse.armor")
} else {
None
};
m.extra.saddled = saddle;
m.set_saddle(saddle);
if open.show_armor {
m.extra.head = armor.map(|a| a.item);
}
+4 -2
View File
@@ -45,13 +45,14 @@ impl Game<'_> {
}
/// `Pig` / `Strider.mobInteract`: saddle an adult, or ride a saddled one.
fn interact_steerable(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &mut self.mobs[index];
if m.is_baby() || !m.alive() || Some(m.id) == self.riding {
return false;
}
let at = m.center();
if item == "minecraft:saddle" && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
let sound = if m.species() == Species::Strider {
"minecraft:entity.strider.saddle"
} else {
@@ -98,6 +99,7 @@ impl Game<'_> {
}
/// `AbstractHorse.mobInteract`. Returns whether the click was used.
pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &self.mobs[index];
let species = m.species();
if matches!(species, Species::Pig | Species::Strider) {
@@ -131,7 +133,7 @@ impl Game<'_> {
let at = m.center();
let tamed = m.extra.tame;
let sound = if item == "minecraft:saddle" && tamed && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
Some("minecraft:entity.horse.saddle")
} else if item.ends_with("_horse_armor")
&& species == Species::Horse
+25 -7
View File
@@ -6,6 +6,7 @@ use horizon_client::{
hud::HudBatch,
lang,
options_ui::{Event, Page},
window::{FrameContext, InactivityFpsLimit, framerate_limit},
};
use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen};
@@ -177,16 +178,33 @@ impl Game<'_> {
}
/// Frame limiter for the Max Framerate option: when the next frame is due.
pub(super) fn next_frame_due(&self) -> Option<std::time::Instant> {
let fps = self.settings.max_fps;
if fps >= 260 || self.options.frames.is_some() {
if self.options.frames.is_some() {
return None;
}
// Menus without a world run at 60 fps like vanilla's title screen.
let fps = if self.title.is_some() {
fps.min(60)
} else {
fps
// FramerateLimitTracker.getFramerateLimit: the option, throttled when
// minimised, idle, or in a menu without a world.
let context = FrameContext {
inactivity: if self.settings.inactivity_fps_limit == "minimized" {
InactivityFpsLimit::Minimized
} else {
InactivityFpsLimit::Afk
},
iconified: self
.window
.as_ref()
.is_some_and(|w| w.is_minimized().unwrap_or(false)),
focused: self.focused,
exclusive_fullscreen: false,
now_ms: self.started.elapsed().as_millis() as i64,
latest_input_ms: self.last_input.duration_since(self.started).as_millis() as i64,
has_level: self.title.is_none(),
has_screen: self.title.is_some() || self.screen != super::Screen::Playing,
has_overlay: false,
};
let fps = framerate_limit(self.settings.max_fps as i32, context);
if fps >= 260 {
return None;
}
let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps));
(due > std::time::Instant::now()).then_some(due)
}
+98 -10
View File
@@ -68,6 +68,9 @@ pub(super) struct RecipeUi {
overlay: Option<Overlay>,
view: View,
view_key: u64,
/// Squeeze animations of new recipes: ticks left per button index and tab.
button_anim: Vec<(usize, f32)>,
tab_anim: Vec<(Tab, f32)>,
}
impl RecipeUi {
@@ -179,6 +182,11 @@ impl Game<'_> {
return;
}
self.ensure_book();
for id in recipes {
if !self.level.recipe_book.to_be_displayed.contains(id) {
self.level.recipe_book.to_be_displayed.push(id.clone());
}
}
let icon = self
.recipe_ui
.book
@@ -291,6 +299,71 @@ impl Game<'_> {
if self.recipe_ui.page >= pages.max(1) {
self.recipe_ui.page = 0;
}
self.start_new_recipe_animations(book_type);
}
/// `RecipeBookTabButton.startAnimation` and `RecipeButton.init`: tabs
/// holding a recipe still to be displayed squeeze, and the buttons of the
/// shown page squeeze once and clear their recipes' highlight.
fn start_new_recipe_animations(&mut self, book_type: BookType) {
if self.level.recipe_book.to_be_displayed.is_empty() {
return;
}
let Some(book) = self.recipe_ui.book.take() else {
return;
};
let unlocked = self.unlocked_recipes();
let filtering = self.book_filtering(book_type);
let (gw, gh) = self.book_grid();
let available = self.book_available(book_type);
let shown = |e: &Entry| {
(book_type != BookType::Crafting || e.fits(gw, gh))
&& (!filtering || available.can_craft(&e.requirements()))
};
let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id);
let mut tabs = Vec::new();
for tab in self.recipe_ui.view.tabs.clone() {
if tab == Tab::Search {
continue;
}
let hit = book
.collections(&unlocked, book_type, tab)
.iter()
.flat_map(|c| c.entries.iter())
.any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i]));
if hit {
tabs.push((tab, 15.0));
}
}
self.recipe_ui.tab_anim = tabs;
let first = self.recipe_ui.page * 20;
let mut buttons = Vec::new();
let mut cleared = Vec::new();
for (n, button) in self
.recipe_ui
.view
.buttons
.iter()
.skip(first)
.take(20)
.enumerate()
{
let ids: Vec<&String> = button
.entries
.iter()
.map(|e| &book.entries[e.0].id)
.filter(|id| self.level.recipe_book.to_be_displayed.contains(*id))
.collect();
if !ids.is_empty() {
buttons.push((first + n, 15.0));
cleared.extend(ids.into_iter().cloned());
}
}
self.level
.recipe_book
.to_be_displayed
.retain(|id| !cleared.contains(id));
self.recipe_ui.button_anim = buttons;
self.recipe_ui.book = Some(book);
}
fn build_view(&mut self, ui: &RecipeUi, book_type: BookType) -> View {
let Some(book) = ui.book.as_ref() else {
@@ -329,9 +402,8 @@ impl Game<'_> {
continue;
}
if !query.is_empty()
&& !c.entries.iter().any(|&i| {
let e = &book.entries[i];
book.matches_search(e, &query, &self.res.names.item(&e.result.item))
&& !book.collection_matches(&c.entries, &query, &|stack| {
self.stack_tooltip(stack).into_iter().map(|l| l.0).collect()
})
{
continue;
@@ -972,26 +1044,30 @@ impl Game<'_> {
.tab
.filter(|t| tabs.contains(t))
.unwrap_or(Tab::Search);
let mut tab_icons = Vec::new();
let frame = self.frame_ticks;
for (n, tab) in tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
let selected = *tab == current;
let name = if selected { "tab_selected" } else { "tab" };
let sx = if selected { x - 2.0 } else { x };
let start = batch.vertices.len();
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
let (a, b) = tab.icons();
let shift = if selected { -2.0 } else { 0.0 };
match b {
Some(b) => {
tab_icons.push((a, x + 3.0 + shift, y + 5.0));
tab_icons.push((b, x + 14.0 + shift, y + 5.0));
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
}
None => tab_icons.push((a, x + 9.0 + shift, y + 5.0)),
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
}
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
entry.1 -= frame;
}
}
for (item, x, y) in tab_icons {
self.draw_item(batch, &ItemStack::new(item, 1), x, y);
}
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
// Craftable filter.
let filtering = self.book_filtering(book_type);
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
@@ -1019,6 +1095,7 @@ impl Game<'_> {
break;
};
let (x, y) = Self::button_pos(xo, yo, n);
let anim_start = batch.vertices.len();
let many = button.entries.len() > 1;
let name = match (button.craftable(), many) {
(true, true) => "slot_many_craftable",
@@ -1048,6 +1125,16 @@ impl Game<'_> {
offset -= 1.0;
}
self.draw_item_plain(batch, &stack, x + offset, y + offset);
if let Some(entry) = self
.recipe_ui
.button_anim
.iter_mut()
.find(|e| e.0 == first + n)
{
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
entry.1 -= self.frame_ticks;
}
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
let mut lines = self.stack_tooltip(&stack);
if many {
@@ -1059,6 +1146,7 @@ impl Game<'_> {
tooltip = Some(lines);
}
}
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
// Page arrows and number.
if pages > 1 {
let page_text = self
+38 -35
View File
@@ -9,7 +9,7 @@
use super::{Dim, Game, Mining, Screen};
use horizon_client::{
Result,
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section},
chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section},
containers::{BlockEntity, Furnace, FurnaceKind},
entities::{Experience, ItemEntity},
hud::{HudBatch, rgba},
@@ -22,7 +22,7 @@ use horizon_client::{
streaming::{ChunkGenerator, Proto, Streaming},
world::World,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_core::{geometry::Vec3, paletted::PalettedContainer, random::RandomSource};
use horizon_protocol::{
entity_data::{ITEM_ENTITY_ITEM, Value},
item::{Hashed, Stack},
@@ -420,6 +420,8 @@ impl Game<'_> {
.is_none_or(|r| r.dimension.has_skylight);
self.streaming.sky_light = has_sky;
self.streaming.nether_shading = self.dim == Dim::Nether;
// The seed in SpawnInfo is already the hashed one the client's BiomeManager holds.
self.streaming.biome_zoom = horizon_core::biome::BiomeZoom::new(spawn.seed);
self.player = None;
self.apply_settings();
}
@@ -432,54 +434,55 @@ impl Game<'_> {
.sections(r.dimension.sections(), 16, r.biome_bits)
.map_err(|e| e.to_string())?;
let mut chunk = Chunk::empty(p.x, p.z);
let mut biomes = vec![0u16; chunk.biomes.len()];
let offset = (r.dimension.min_y - MIN_Y).div_euclid(16);
// Biome table index per quart cell of the dimension's own sections.
let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len());
for (i, s) in sections.iter().enumerate() {
let target = offset + i as i32;
let mut cells = [0u32; 64];
for (j, cell) in cells.iter_mut().enumerate() {
*cell = u32::from(
r.biome_map
.get(s.biomes.get(j) as usize)
.copied()
.unwrap_or(0),
);
}
biome_cells.push(cells);
if !(0..SECTIONS as i32).contains(&target) {
continue;
}
let blocks = if s.states.bits == 0 {
Blocks::Uniform(s.states.get(0) as u16)
} else {
let mut a = Box::new([0u16; 4096]);
for (j, v) in a.iter_mut().enumerate() {
*v = s.states.get(j) as u16;
}
Blocks::Full(a)
};
let strategy = BLOCK_STRATEGY;
let palette = s.states.palette.iter().map(|&p| p as u32).collect();
let words = s.states.data.iter().map(|&w| w as u64).collect();
let blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words)
.map_err(|e| e.to_string())?;
let mut section = Section {
blocks,
biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells),
light: Light::Uniform(0xF0),
};
section.compact();
chunk.sections[target as usize] = Arc::new(section);
for j in 0..64 {
let biome = r
.biome_map
.get(s.biomes.get(j) as usize)
.copied()
.unwrap_or(0);
if let Some(cell) = biomes.get_mut(target as usize * 64 + j) {
*cell = biome;
}
// Sections outside the dimension's range take its nearest biomes
// (the column's top or bottom cell layer repeated).
if !biome_cells.is_empty() {
let last = biome_cells.len() - 1;
for si in 0..SECTIONS as i32 {
let i = si - offset;
if (0..sections.len() as i32).contains(&i) {
continue;
}
let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) };
let mut cells = [0u32; 64];
for (j, cell) in cells.iter_mut().enumerate() {
*cell = biome_cells[edge][layer * 16 + j % 16];
}
Arc::make_mut(&mut chunk.sections[si as usize]).biomes =
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
}
}
// Columns outside the dimension's range take its nearest biome.
let (lo, hi) = (
offset.max(0) as usize * 64,
((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64,
);
if lo < hi {
for j in 0..biomes.len() {
if j < lo {
biomes[j] = biomes[lo + j % 16];
} else if j >= hi {
biomes[j] = biomes[hi - 16 + j % 16];
}
}
}
chunk.biomes = Arc::new(biomes);
Ok(chunk)
}
/// Keep the renderable block entities (chests, furnaces) in step with blocks.
@@ -172,6 +172,7 @@ impl Game<'_> {
lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw)
}
pub(super) fn tick_particles(&mut self) {
self.res.fog.state.tick_flicker();
let eye = self.eye_position();
if let Some(e) = eye {
let brightness = self.eye_brightness(e);
@@ -227,6 +227,24 @@ impl Game<'_> {
}
}
}
if ok && !s.predicates.is_empty() {
// EntityPredicates: the datapack predicate with the entity as
// `this` and the entity's position as origin.
self.ensure_datapacks();
let view = self.entity_view_of(t);
let origin = self.target_position(t).unwrap_or_default();
for (id, negated) in &s.predicates {
let matches = self
.fns
.store
.predicates
.get(id)
.is_some_and(|json| self.conditions_hold(json, Some(&view), origin));
if matches == *negated {
ok = false;
}
}
}
if ok && !s.advancements.is_empty() {
ok = t == Target::Player && self.advancements_match(&s.advancements);
}
+39 -18
View File
@@ -336,30 +336,28 @@ impl Game<'_> {
}
}
fn sculk_scan_chunk(&mut self, key: (i32, i32)) {
use horizon_client::chunk::{Blocks, MIN_Y};
use horizon_client::chunk::MIN_Y;
let Some(chunk) = self.world.chunks.get(&key).cloned() else {
return;
};
let mut found = Vec::new();
for (s, section) in chunk.sections.iter().enumerate() {
let y0 = MIN_Y + s as i32 * 16;
match &section.blocks {
Blocks::Uniform(v) => {
// A uniform section of sculk blocks does not exist.
let _ = v;
}
Blocks::Full(a) => {
for (i, v) in a.iter().enumerate() {
if self.kind_of_state(*v) != 0 {
let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8);
found.push((
key.0 * 16 + x as i32,
y0 + y as i32,
key.1 * 16 + z as i32,
*v,
));
}
}
if section.blocks.uniform().is_some() {
// A uniform section of sculk blocks does not exist.
continue;
}
let mut a = [0u16; 4096];
section.unpack(&mut a);
for (i, v) in a.iter().enumerate() {
if self.kind_of_state(*v) != 0 {
let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8);
found.push((
key.0 * 16 + x as i32,
y0 + y as i32,
key.1 * 16 + z as i32,
*v,
));
}
}
}
@@ -1096,6 +1094,29 @@ impl Game<'_> {
(modifier, pulse.max(0.0))
}
/// `LightmapRenderStateExtractor`: the night vision effect's intensity
/// (`GameRenderer.nightVisionScale`), or conduit power's water vision.
pub(super) fn night_vision_intensity(&self) -> f32 {
use horizon_client::fog::FogType;
if let Some(e) = self.potions.effects.get("night_vision") {
// MobEffectInstance.endsWithin(200); -1 is infinite.
return if e.duration < 0 || e.duration > 200 {
1.0
} else {
0.7 + (e.duration as f32 * std::f32::consts::PI * 0.2).sin() * 0.3
};
}
if self.potions.effects.get("conduit_power").is_some()
&& let Some(eye) = self.eye_position()
{
let in_water =
horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward())
== FogType::Water;
return self.res.fog.state.water_vision(in_water);
}
0.0
}
/// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`.
pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) {
if self.creative || self.spectator() {
+7 -1
View File
@@ -1305,7 +1305,13 @@ impl Game<'_> {
);
}
}
let title = self.translate("container.brewing", "Brewing Stand");
let default = self.translate("container.brewing", "Brewing Stand");
let title = self
.station
.as_ref()
.and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2])))
.cloned()
.unwrap_or(default);
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+44 -66
View File
@@ -11,6 +11,14 @@ impl Game<'_> {
/// Block-entity contents on removal: shulker boxes keep theirs for the
/// dropped box (`copy_components`), other containers spill them.
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
if let Some(name) = self
.world
.block_names
.remove(&(pos[0], pos[1], pos[2]))
.filter(|_| !matches!(entity, BlockEntity::Banner(_)))
{
self.pending_names.insert(pos, (block.to_owned(), name));
}
if let BlockEntity::Banner(banner) = entity {
self.pending_banner.insert(pos, banner);
return;
@@ -41,6 +49,38 @@ impl Game<'_> {
stack.data_mut().container = contents;
}
}
/// The custom name a broken container drops with (`copy_components`).
pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
if self
.pending_names
.get(&pos)
.is_some_and(|(item, _)| **item == *stack.item)
&& let Some((_, name)) = self.pending_names.remove(&pos)
{
stack.data_mut().custom_name = Some(name);
}
}
/// A placed container takes the item's custom name.
pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) {
let key = (pos[0], pos[1], pos[2]);
if let Some(name) = stack.custom_name()
&& !matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Banner(_) | BlockEntity::Sign(_))
)
{
self.world.block_names.insert(key, name.to_owned());
}
}
/// The custom name of the open container, or its default title
/// (a double chest is named by whichever half has a name).
pub(super) fn container_title(&self, default: String) -> String {
self.container_parts()
.iter()
.find_map(|(key, _)| self.world.block_names.get(key))
.cloned()
.unwrap_or(default)
}
/// A placed shulker box takes the item's contents.
pub(super) fn fill_placed_box(&mut self, pos: [i32; 3], stack: &ItemStack) {
let Some(data) = stack.data() else { return };
@@ -234,7 +274,7 @@ impl Game<'_> {
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
_ => ("container.chest", "Chest"),
};
self.translate(key, fallback)
self.container_title(self.translate(key, fallback))
}
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
/// container rows, the title and the inventory label.
@@ -302,72 +342,10 @@ impl Game<'_> {
impl Game<'_> {
/// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace
/// menu for a shift-click on `slot`; false when the menu has none.
/// menu for a shift-click on `slot`, run by the verified menu engine
/// (`horizon_client::menu`); false when the menu has none.
pub(super) fn container_quick_move(&mut self, slot: usize) -> bool {
let size = self.container_size();
let furnace = match self.container_kind() {
Some(BlockEntity::Chest(_)) => None,
Some(BlockEntity::Furnace(f)) => Some(f.kind),
_ => return false,
};
if slot >= 300 + size.max(3) {
return false;
}
let Some(mut stack) = self.slot_mut(slot).take() else {
return true;
};
let player: Vec<usize> = (9..36).chain(0..9).collect();
let hotbar_or_main = |slot: usize| -> Vec<usize> {
if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
}
};
match furnace {
None => {
if slot >= 300 {
self.move_to(&mut stack, &player, true);
} else {
let targets: Vec<usize> = (300..300 + size).collect();
self.move_to(&mut stack, &targets, false);
}
}
Some(kind) => {
// AbstractFurnaceMenu.quickMoveStack.
if slot >= 300 {
self.move_to(&mut stack, &player, slot == 302);
} else {
let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some();
let fuel = self
.res
.items
.get(&stack.item)
.is_some_and(|i| i.fuel.is_some());
let moved = if smeltable {
self.move_to(&mut stack, &[300], false)
} else if fuel {
self.move_to(&mut stack, &[301], false)
} else {
false
};
if !moved && !smeltable && !fuel {
let other = hotbar_or_main(slot);
self.move_to(&mut stack, &other, false);
}
if let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.cooking_timer = 0;
}
}
}
}
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
}
true
self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove)
}
}
+33 -13
View File
@@ -80,6 +80,10 @@ pub struct Frame<'a> {
/// The darkness effect on the lightmap: the brightness it takes off the
/// gamma option and the pulsing scale subtracted from the light.
pub darkness: (f32, f32),
/// Night vision (or conduit water vision) intensity on the lightmap.
pub night_vision: f32,
/// Torch flicker added to the block light factor of 1.4.
pub block_flicker: f32,
}
pub struct Renderer {
instance: wgpu::Instance,
@@ -919,16 +923,21 @@ impl Renderer {
}
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
pub fn set_vsync(&mut self, vsync: bool) {
let has = |m| self.present_modes.contains(&m);
let mode = match (
vsync,
has(wgpu::PresentMode::Mailbox),
has(wgpu::PresentMode::Immediate),
) {
(true, true, _) => wgpu::PresentMode::Mailbox,
(true, false, _) => wgpu::PresentMode::Fifo,
(false, _, true) => wgpu::PresentMode::Immediate,
(false, true, false) => wgpu::PresentMode::Mailbox,
use crate::window::{PresentMode, vsync_present_mode};
let supported: Vec<PresentMode> = self
.present_modes
.iter()
.filter_map(|m| match m {
wgpu::PresentMode::Fifo => Some(PresentMode::Fifo),
wgpu::PresentMode::Mailbox => Some(PresentMode::Mailbox),
wgpu::PresentMode::Immediate => Some(PresentMode::Immediate),
_ => None,
})
.collect();
// GpuSurface.PresentMode.getSupportedVsyncMode.
let mode = match vsync_present_mode(&supported, vsync) {
Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox,
Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate,
_ => wgpu::PresentMode::Fifo,
};
if self.config.present_mode != mode {
@@ -1077,7 +1086,14 @@ impl Renderer {
* bob
* Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y)
}
fn update_lightmap(&self, sky: &Sky, darkness: f32, gamma: f32) {
fn update_lightmap(
&self,
sky: &Sky,
darkness: f32,
gamma: f32,
night_vision: f32,
flicker: f32,
) {
// lightmap.fsh: per (block, sky) level.
let brightness = |level: f32| level / (4.0 - 3.0 * level);
let mut pixels = [0u8; 16 * 16 * 4];
@@ -1085,9 +1101,11 @@ impl Renderer {
for b in 0..16 {
let block_level = b as f32 / 15.0;
let sky_level = s as f32 / 15.0;
let block_brightness = brightness(block_level) * 1.4;
let block_brightness = brightness(block_level) * (1.4 + flicker);
let sky_brightness = brightness(sky_level) * sky.sky_light_factor;
let mut color = Vec3::from(sky.ambient_light_color);
// NightVisionColor defaults to 0x999999.
let mut color =
Vec3::from(sky.ambient_light_color).max(Vec3::splat(0.6 * night_vision));
color += Vec3::from(sky.sky_light_color) * sky_brightness;
let parabolic = (2.0 * block_level - 1.0).powi(2);
let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic);
@@ -1193,6 +1211,8 @@ impl Renderer {
&frame.sky,
frame.darkness.1,
(self.gamma - frame.darkness.0).max(0.0),
frame.night_vision,
frame.block_flicker,
);
let view_proj = self.view_projection(frame);
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
+8
View File
@@ -278,6 +278,14 @@ impl HudBatch {
/// Clip the quads drawn since `start` to `[x0, x1) x [y0, y1)` (the
/// GUI scissor): axis-aligned quads are cut with their UVs, others are
/// kept or dropped by their centre.
/// Scale the vertices pushed since `start` about `(cx, cy)` (a GUI pose
/// matrix of translate, scale, translate back).
pub fn scale_since(&mut self, start: usize, cx: f32, cy: f32, sx: f32, sy: f32) {
for v in &mut self.vertices[start..] {
v.pos[0] = cx + (v.pos[0] - cx) * sx;
v.pos[1] = cy + (v.pos[1] - cy) * sy;
}
}
pub fn clip_since(&mut self, start: usize, x0: f32, y0: f32, x1: f32, y1: f32) {
let quads: Vec<[HudVertex; 6]> = self.vertices[start..].as_chunks::<6>().0.to_vec();
self.vertices.truncate(start);
+279 -67
View File
@@ -44,6 +44,18 @@ pub struct StackData {
pub ominous_banner: bool,
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
pub ominous_amplifier: Option<u8>,
/// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB).
pub dyed_color: Option<i32>,
/// `minecraft:firework_explosion` (a firework star).
pub firework_explosion: Option<crate::particles::FireworkExplosion>,
/// `minecraft:pot_decorations`: back, left, right, front sherds.
pub pot_decorations: Option<Box<[Option<ItemStack>; 4]>>,
/// `minecraft:bundle_contents`.
pub bundle_contents: Vec<ItemStack>,
/// `minecraft:suspicious_stew_effects`: (effect id, duration).
pub stew_effects: Vec<(Arc<str>, i32)>,
/// `minecraft:map_post_processing`: 0 lock, 1 scale.
pub map_post_processing: Option<u8>,
}
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
@@ -243,6 +255,151 @@ fn read_text(t: &Tag) -> Option<String> {
}
}
/// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted).
fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag {
let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect());
let mut fields = vec![("shape", Tag::String(e.shape.name().into()))];
if !e.colors.is_empty() {
fields.push(("colors", colors(&e.colors)));
}
if !e.fade.is_empty() {
fields.push(("fade_colors", colors(&e.fade)));
}
if e.trail {
fields.push(("has_trail", Tag::Byte(1)));
}
if e.twinkle {
fields.push(("has_twinkle", Tag::Byte(1)));
}
Tag::compound(fields)
}
fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion {
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(),
_ => Vec::new(),
};
crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.map_or("small_ball", |s| s.strip_prefix("minecraft:").unwrap_or(s)),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
}
}
/// An `ItemStackTemplate`: `{id, count?, components?}`.
fn template_tag(stack: &ItemStack) -> Tag {
let mut entries = vec![("id", Tag::String((&*stack.item).into()))];
if stack.count != 1 {
entries.push(("count", Tag::Int(stack.count as i32)));
}
if let Some(components) = encode_components(stack) {
entries.push(("components", components));
}
Tag::compound(entries)
}
/// The pot prototype's decorations: a brick on every side.
pub fn all_bricks(sides: &[Option<ItemStack>; 4]) -> bool {
sides.iter().all(|s| {
s.as_ref()
.is_some_and(|s| &*s.item == "minecraft:brick" && s.count == 1 && s.extra.is_none())
})
}
fn template_from(tag: &Tag) -> Option<ItemStack> {
match tag {
Tag::String(id) => Some(ItemStack::new(&id.to_string_lossy(), 1)),
_ => {
let id = tag.get("id").and_then(string)?;
let (damage, extra) = decode_components(tag.get("components"));
Some(ItemStack {
item: Arc::from(id.as_str()),
count: tag.get("count").and_then(int).unwrap_or(1).max(1) as u32,
damage,
extra,
})
}
}
}
/// Sorted-key, type-annotated text of a tag (the differential harnesses
/// print the same form from the vanilla side).
pub fn canon_tag(tag: &Tag) -> String {
fn list(out: &mut String, prefix: &str, items: impl Iterator<Item = String>) {
out.push_str(prefix);
out.push_str(&items.collect::<Vec<_>>().join(","));
out.push(']');
}
fn go(tag: &Tag, out: &mut String) {
use std::fmt::Write as _;
match tag {
Tag::End => {}
Tag::Byte(v) => write!(out, "{v}b").unwrap(),
Tag::Short(v) => write!(out, "{v}s").unwrap(),
Tag::Int(v) => write!(out, "{v}").unwrap(),
Tag::Long(v) => write!(out, "{v}L").unwrap(),
Tag::Float(v) => write!(out, "{}f", f32::from_bits(*v)).unwrap(),
Tag::Double(v) => write!(out, "{}d", f64::from_bits(*v)).unwrap(),
Tag::String(s) => write!(
out,
"\"{}\"",
s.to_string_lossy()
.replace('\\', "\\\\")
.replace('"', "\\\"")
)
.unwrap(),
Tag::ByteArray(v) => list(out, "[B;", v.iter().map(|b| (*b as i8).to_string())),
Tag::IntArray(v) => list(out, "[I;", v.iter().map(i32::to_string)),
Tag::LongArray(v) => list(out, "[L;", v.iter().map(i64::to_string)),
Tag::List(items) => {
out.push('[');
for (i, t) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
go(t, out);
}
out.push(']');
}
Tag::Compound(map) => {
let mut keys: Vec<(String, &Tag)> =
map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
out.push('{');
for (i, (k, v)) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&k);
out.push(':');
go(v, out);
}
out.push('}');
}
}
}
let mut out = String::new();
go(tag, &mut out);
out
}
/// `canon_tag` of a stack as `ItemStack.CODEC` writes it; "-" for none.
pub fn canon_stack(stack: Option<&ItemStack>) -> String {
stack.map_or_else(
|| "-".to_owned(),
|s| canon_tag(&crate::save::item_to_nbt(s)),
)
}
/// The stack of an SNBT `ItemStack.CODEC` compound; None for "-".
pub fn parse_stack(snbt: &str) -> Result<Option<ItemStack>, String> {
if snbt == "-" {
return Ok(None);
}
let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?;
Ok(crate::save::item_from_nbt(&tag))
}
/// The `components` compound for a stack, or None when every component is default.
pub fn encode_components(stack: &ItemStack) -> Option<Tag> {
components_tag(stack.damage, stack.data())
@@ -317,40 +474,73 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.collect();
entries.push((
"minecraft:written_book_content",
Tag::compound([
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("generation", Tag::Int(i32::from(w.generation))),
("pages", Tag::List(pages)),
("resolved", Tag::Byte(1)),
]),
Tag::compound({
let mut fields = vec![
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("pages", Tag::List(pages)),
];
if w.generation != 0 {
fields.push(("generation", Tag::Int(i32::from(w.generation))));
}
fields
}),
));
}
if let Some((flight, explosions)) = &d.fireworks {
let list = explosions
.iter()
.map(|e| {
Tag::compound([
("shape", Tag::String(e.shape.name().into())),
(
"colors",
Tag::IntArray(e.colors.iter().map(|c| *c as i32).collect()),
),
(
"fade_colors",
Tag::IntArray(e.fade.iter().map(|c| *c as i32).collect()),
),
("has_trail", Tag::Byte(i8::from(e.trail))),
("has_twinkle", Tag::Byte(i8::from(e.twinkle))),
])
})
.collect();
let mut fields = Vec::new();
if *flight != 0 {
fields.push(("flight_duration", Tag::Byte(*flight as i8)));
}
if !explosions.is_empty() {
fields.push((
"explosions",
Tag::List(explosions.iter().map(explosion_tag).collect()),
));
}
entries.push(("minecraft:fireworks", Tag::compound(fields)));
}
if let Some(e) = &d.firework_explosion {
entries.push(("minecraft:firework_explosion", explosion_tag(e)));
}
if let Some(color) = d.dyed_color {
entries.push(("minecraft:dyed_color", Tag::Int(color)));
}
if let Some(sides) = &d.pot_decorations {
let mut sherds = Vec::new();
for (name, side) in ["back", "left", "right", "front"].iter().zip(sides.iter()) {
if let Some(stack) = side {
sherds.push((*name, template_tag(stack)));
}
}
entries.push(("minecraft:pot_decorations", Tag::compound(sherds)));
}
if !d.bundle_contents.is_empty() {
entries.push((
"minecraft:fireworks",
Tag::compound([
("flight_duration", Tag::Byte(*flight as i8)),
("explosions", Tag::List(list)),
]),
"minecraft:bundle_contents",
Tag::List(d.bundle_contents.iter().map(template_tag).collect()),
));
}
if !d.stew_effects.is_empty() {
entries.push((
"minecraft:suspicious_stew_effects",
Tag::List(
d.stew_effects
.iter()
.map(|(id, duration)| {
Tag::compound([
("id", Tag::String((&**id).into())),
("duration", Tag::Int(*duration)),
])
})
.collect(),
),
));
}
if let Some(mode) = d.map_post_processing {
entries.push((
"minecraft:map_post_processing",
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
));
}
if !d.charged.is_empty() {
@@ -399,7 +589,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.map(|(slot, stack)| {
Tag::compound([
("slot", Tag::Int(i32::from(*slot))),
("item", crate::save::item_to_nbt(stack)),
("item", template_tag(stack)),
])
})
.collect();
@@ -456,36 +646,54 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
_ => Vec::new(),
},
}),
fireworks: c.get("minecraft:fireworks").map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
_ => Vec::new(),
};
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list
.iter()
.map(|e| crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.unwrap_or("small_ball"),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
})
.collect(),
_ => Vec::new(),
};
(flight, explosions)
}),
fireworks: c
.get("minecraft:fireworks")
.map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list.iter().map(explosion_from).collect(),
_ => Vec::new(),
};
(flight, explosions)
})
.filter(|(flight, explosions)| !(*flight == 1 && explosions.is_empty())),
firework_explosion: c.get("minecraft:firework_explosion").map(explosion_from),
dyed_color: c
.get("minecraft:dyed_color")
.and_then(int)
.map(|v| v as i32),
pot_decorations: c
.get("minecraft:pot_decorations")
.map(|p| {
let side = |name: &str| p.get(name).and_then(template_from);
Box::new([side("back"), side("left"), side("right"), side("front")])
})
.filter(|sides| !all_bricks(sides)),
bundle_contents: match c.get("minecraft:bundle_contents") {
Some(Tag::List(list)) => list.iter().filter_map(template_from).collect(),
_ => Vec::new(),
},
stew_effects: match c.get("minecraft:suspicious_stew_effects") {
Some(Tag::List(list)) => list
.iter()
.filter_map(|e| {
Some((
Arc::from(e.get("id").and_then(string)?.as_str()),
e.get("duration").and_then(int).unwrap_or(160) as i32,
))
})
.collect(),
_ => Vec::new(),
},
map_post_processing: match c.get("minecraft:map_post_processing") {
Some(Tag::String(s)) => Some(u8::from(s.to_string_lossy() != "lock")),
Some(t) => int(t).map(|v| v.clamp(0, 1) as u8),
None => None,
},
charged: match c.get("minecraft:charged_projectiles") {
Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(),
_ => Vec::new(),
@@ -496,17 +704,21 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
.filter_map(|e| {
Some((
e.get("slot").and_then(int)?.clamp(0, 255) as u8,
crate::save::item_from_nbt(e.get("item")?)?,
template_from(e.get("item")?)?,
))
})
.collect(),
_ => Vec::new(),
},
ominous_banner: matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
),
ominous_banner: c
.get("minecraft:item_name")
.and_then(|n| n.get("translate"))
.and_then(string)
.as_deref()
== Some("block.minecraft.ominous_banner")
&& matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.len() == OMINOUS_LAYERS.len()),
ominous_amplifier: c
.get("minecraft:ominous_bottle_amplifier")
.and_then(int)
+31 -2
View File
@@ -60,7 +60,22 @@ pub struct ItemInfo {
pub equip_sound: Option<String>,
/// `jukebox_playable`: the jukebox song it plays.
pub jukebox_song: Option<String>,
/// `crafting_remainder`: what stays in the grid when the item is used in a recipe.
pub crafting_remainder: Option<String>,
/// `dye`: the dye colour name (dyes, and anything else with the component).
pub dye: Option<String>,
/// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks.
pub block_transformer: Option<String>,
}
/// `Item.Properties.craftRemainder` (not a data component, so not in the
/// default-component report): what an item leaves in the grid when crafted with.
pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [
("minecraft:water_bucket", "minecraft:bucket"),
("minecraft:lava_bucket", "minecraft:bucket"),
("minecraft:milk_bucket", "minecraft:bucket"),
("minecraft:dragon_breath", "minecraft:glass_bottle"),
("minecraft:honey_bottle", "minecraft:glass_bottle"),
];
/// A reduction of `blocks_attacks.damage_reductions`.
#[derive(Clone, Debug)]
pub struct BlockReduction {
@@ -264,8 +279,6 @@ fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<S
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
let default = registry.default_state(&s.name);
@@ -275,6 +288,16 @@ impl Items {
.or_insert(BlockStateId(i as u32));
}
}
Self::load_with(root, &block_for_item)
}
/// Every item's default components and the tags, without the block <->
/// item mapping (for headless tools that never place blocks).
pub fn catalog(root: &Path) -> Result<Self> {
Self::load_with(root, &HashMap::new())
}
fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let entity_tags = load_tags(root, "entity_type")?;
let mut items = HashMap::new();
let mut order = Vec::new();
@@ -352,6 +375,12 @@ impl Items {
.as_str()
.map(str::to_owned),
jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned),
dye: c["minecraft:dye"].as_str().map(str::to_owned),
block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned),
crafting_remainder: CRAFT_REMAINDERS
.iter()
.find(|(item, _)| *item == name)
.map(|(_, rest)| (*rest).to_owned()),
use_speed: c["minecraft:use_effects"]["speed_multiplier"]
.as_f64()
.unwrap_or(0.2) as f32,
+613
View File
@@ -0,0 +1,613 @@
//! Java text conventions the vanilla option files depend on: shortest-digit
//! `Double.toString`/`Float.toString`, Gson's HTML-safe string escaping and a
//! reader for Gson's lenient JSON (`JsonParser.parseString`).
/// Digits and decimal exponent of the shortest round-trip form.
fn shortest(text: &str) -> (String, i32) {
// `{:e}` yields "d.ddde-5" or "de5".
let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0"));
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
(digits, exponent.parse().unwrap_or(0))
}
fn render(negative: bool, digits: &str, exponent: i32) -> String {
let mut out = String::new();
if negative {
out.push('-');
}
let digits = if digits.is_empty() { "0" } else { digits };
if (-3..7).contains(&exponent) {
if exponent >= 0 {
let int_len = exponent as usize + 1;
if digits.len() <= int_len {
out.push_str(digits);
out.extend(std::iter::repeat_n('0', int_len - digits.len()));
out.push_str(".0");
} else {
out.push_str(&digits[..int_len]);
out.push('.');
out.push_str(&digits[int_len..]);
}
} else {
out.push_str("0.");
out.extend(std::iter::repeat_n('0', (-exponent - 1) as usize));
out.push_str(digits);
}
} else {
out.push_str(&digits[..1]);
out.push('.');
if digits.len() > 1 {
out.push_str(&digits[1..]);
} else {
out.push('0');
}
out.push('E');
out.push_str(&exponent.to_string());
}
out
}
/// `Double.toString`.
pub fn double_to_string(value: f64) -> String {
if value.is_nan() {
return "NaN".into();
}
if value.is_infinite() {
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
}
if value == 0.0 {
return if value.is_sign_negative() {
"-0.0"
} else {
"0.0"
}
.into();
}
let (digits, exponent) = shortest(&format!("{:e}", value.abs()));
render(value < 0.0, &digits, exponent)
}
/// `Float.toString`.
pub fn float_to_string(value: f32) -> String {
if value.is_nan() {
return "NaN".into();
}
if value.is_infinite() {
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
}
if value == 0.0 {
return if value.is_sign_negative() {
"-0.0"
} else {
"0.0"
}
.into();
}
let (digits, exponent) = shortest(&format!("{:e}", value.abs()));
render(value < 0.0, &digits, exponent)
}
/// Gson's default (HTML-safe) JSON string literal.
pub fn gson_string(value: &str) -> String {
let mut out = String::from("\"");
for c in value.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' => {
out.push_str(&format!("\\u{:04x}", c as u32));
}
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// A parsed JSON element as Gson models it.
#[derive(Clone, Debug, PartialEq)]
pub enum Json {
Null,
Bool(bool),
/// The number's source text (`LazilyParsedNumber`).
Number(String),
String(String),
Array(Vec<Json>),
Object,
}
impl Json {
/// `Number.intValue()` of a `LazilyParsedNumber`: `Integer.parseInt`, else
/// `BigDecimal.intValue()` (truncate, keep the low 32 bits).
pub fn int_value(text: &str) -> i32 {
let (negative, body) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text),
};
let (mantissa, exponent) = match body.split_once(['e', 'E']) {
Some((m, e)) => (
m,
e.strip_prefix('+').unwrap_or(e).parse::<i64>().unwrap_or(0),
),
None => (body, 0),
};
let (int_part, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let digits: Vec<u32> = int_part
.chars()
.chain(fraction.chars())
.filter_map(|c| c.to_digit(10))
.collect();
// value = digits * 10^scale; truncating drops digits below the point.
let scale = exponent - fraction.len() as i64;
let keep = if scale >= 0 {
digits.len()
} else {
digits
.len()
.saturating_sub(scale.unsigned_abs().min(usize::MAX as u64) as usize)
};
let mut v: u32 = 0;
for d in &digits[..keep] {
v = v.wrapping_mul(10).wrapping_add(*d);
}
if scale > 0 {
// v * 10^scale modulo 2^32 by repeated squaring.
let (mut base, mut power, mut e) = (10u32, 1u32, scale as u64);
while e > 0 {
if e & 1 == 1 {
power = power.wrapping_mul(base);
}
base = base.wrapping_mul(base);
e >>= 1;
}
v = v.wrapping_mul(power);
}
let v = v as i32;
if negative { v.wrapping_neg() } else { v }
}
/// `Number.doubleValue()`.
pub fn double_value(text: &str) -> f64 {
text.parse::<f64>().unwrap_or(0.0)
}
}
/// A syntax error aborts the whole options load, as in vanilla.
#[derive(Debug)]
pub struct SyntaxError;
struct Reader {
chars: Vec<char>,
pos: usize,
}
fn is_literal(c: char) -> bool {
!matches!(
c,
'/' | '\\'
| ';'
| '#'
| '='
| '{'
| '}'
| '['
| ']'
| ':'
| ','
| ' '
| '\t'
| '\u{c}'
| '\r'
| '\n'
)
}
impl Reader {
fn peek_char(&self) -> Option<char> {
self.chars.get(self.pos).copied()
}
/// `nextNonWhitespace` with lenient comments; `None` at the end.
fn skip(&mut self) -> Result<Option<char>, SyntaxError> {
loop {
match self.peek_char() {
None => return Ok(None),
Some(' ' | '\t' | '\r' | '\n') => self.pos += 1,
Some('#') => self.line_comment(),
Some('/') => match self.chars.get(self.pos + 1) {
Some('/') => self.line_comment(),
Some('*') => {
self.pos += 2;
loop {
match (self.peek_char(), self.chars.get(self.pos + 1)) {
(Some('*'), Some('/')) => {
self.pos += 2;
break;
}
(Some(_), _) => self.pos += 1,
(None, _) => return Err(SyntaxError),
}
}
}
_ => return Ok(Some('/')),
},
Some(c) => return Ok(Some(c)),
}
}
}
fn line_comment(&mut self) {
while let Some(c) = self.peek_char() {
self.pos += 1;
if c == '\n' || c == '\r' {
break;
}
}
}
fn quoted(&mut self, quote: char) -> Result<String, SyntaxError> {
self.pos += 1;
let mut out = String::new();
loop {
let c = self.peek_char().ok_or(SyntaxError)?;
self.pos += 1;
if c == quote {
return Ok(out);
}
if c != '\\' {
out.push(c);
continue;
}
let e = self.peek_char().ok_or(SyntaxError)?;
self.pos += 1;
match e {
'u' => {
let mut v = 0u32;
for _ in 0..4 {
let d = self.peek_char().ok_or(SyntaxError)?;
self.pos += 1;
v = v * 16 + d.to_digit(16).ok_or(SyntaxError)?;
}
// Lone surrogates cannot be represented; keep the replacement.
out.push(char::from_u32(v).unwrap_or('\u{fffd}'));
}
't' => out.push('\t'),
'b' => out.push('\u{8}'),
'n' => out.push('\n'),
'r' => out.push('\r'),
'f' => out.push('\u{c}'),
'\n' | '\'' | '"' | '\\' | '/' => out.push(e),
_ => return Err(SyntaxError),
}
}
}
fn literal(&mut self) -> String {
let start = self.pos;
while self.peek_char().is_some_and(is_literal) {
self.pos += 1;
}
self.chars[start..self.pos].iter().collect()
}
/// JSON number grammar with Gson's leading-zero rule.
fn is_number(text: &str) -> bool {
let b: Vec<char> = text.chars().collect();
let mut i = 0;
if b.first() == Some(&'-') {
i += 1;
}
match b.get(i) {
Some('0') => {
i += 1;
}
Some(c) if c.is_ascii_digit() => {
while b.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
_ => return false,
}
if b.get(i) == Some(&'.') {
i += 1;
if !b.get(i).is_some_and(char::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
if matches!(b.get(i), Some('e' | 'E')) {
i += 1;
if matches!(b.get(i), Some('+' | '-')) {
i += 1;
}
if !b.get(i).is_some_and(char::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
i == b.len()
}
fn keyword(text: &str, word: &str) -> bool {
text.len() == word.len() && text.eq_ignore_ascii_case(word)
}
fn value(&mut self) -> Result<Json, SyntaxError> {
let c = self.skip()?.ok_or(SyntaxError)?;
match c {
'"' | '\'' => Ok(Json::String(self.quoted(c)?)),
'[' => {
self.pos += 1;
let mut items = Vec::new();
loop {
match self.skip()?.ok_or(SyntaxError)? {
']' => {
self.pos += 1;
// A trailing separator leaves an implicit null.
return Ok(Json::Array(items));
}
',' | ';' => {
self.pos += 1;
items.push(Json::Null);
continue;
}
_ => {}
}
items.push(self.value()?);
match self.skip()?.ok_or(SyntaxError)? {
']' => {
self.pos += 1;
return Ok(Json::Array(items));
}
',' | ';' => self.pos += 1,
_ => return Err(SyntaxError),
}
}
}
'{' => {
self.pos += 1;
loop {
match self.skip()?.ok_or(SyntaxError)? {
'}' => {
self.pos += 1;
return Ok(Json::Object);
}
'"' | '\'' => {
let q = self.skip()?.ok_or(SyntaxError)?;
self.quoted(q)?;
}
c if is_literal(c) => {
self.literal();
}
_ => return Err(SyntaxError),
}
match self.skip()?.ok_or(SyntaxError)? {
':' => self.pos += 1,
'=' => {
self.pos += 1;
if self.peek_char() == Some('>') {
self.pos += 1;
}
}
_ => return Err(SyntaxError),
}
self.value()?;
match self.skip()?.ok_or(SyntaxError)? {
'}' => {
self.pos += 1;
return Ok(Json::Object);
}
',' | ';' => self.pos += 1,
_ => return Err(SyntaxError),
}
}
}
']' | '}' | ',' | ';' | ':' | '=' | '\\' | '/' => Err(SyntaxError),
_ => {
let text = self.literal();
if text.is_empty() {
return Err(SyntaxError);
}
if Self::keyword(&text, "true") {
Ok(Json::Bool(true))
} else if Self::keyword(&text, "false") {
Ok(Json::Bool(false))
} else if Self::keyword(&text, "null") {
Ok(Json::Null)
} else if Self::is_number(&text) {
Ok(Json::Number(text))
} else {
Ok(Json::String(text))
}
}
}
}
}
/// `JsonParser.parseString`: one lenient value and nothing after it.
pub fn parse_lenient(text: &str) -> Result<Json, SyntaxError> {
let text = text.strip_prefix(")]}'\n").unwrap_or(text);
let mut reader = Reader {
chars: text.chars().collect(),
pos: 0,
};
if reader.skip()?.is_none() {
return Ok(Json::Null);
}
let value = reader.value()?;
// The trailing check runs after Gson restored its legacy-strict mode:
// only whitespace may follow the value.
if value != Json::Null
&& reader.chars[reader.pos..]
.iter()
.any(|c| !matches!(c, ' ' | '\t' | '\r' | '\n'))
{
return Err(SyntaxError);
}
Ok(value)
}
impl Reader {
/// Next non-whitespace char in strict mode (comments are errors).
fn strict_skip(&mut self) -> Option<char> {
while matches!(self.peek_char(), Some(' ' | '\t' | '\r' | '\n')) {
self.pos += 1;
}
self.peek_char()
}
}
/// `Gson.getAdapter(List<String>).read` on a strict `JsonReader`
/// (`GsonHelper.fromNullableJson`): `Ok(None)` for `null`, an error for
/// anything Gson rejects, including an empty document.
pub fn parse_strict_string_list(text: &str) -> Result<Option<Vec<String>>, SyntaxError> {
let mut r = Reader {
chars: text.chars().collect(),
pos: 0,
};
match r.strict_skip().ok_or(SyntaxError)? {
'n' => {
let word = r.literal();
if word == "null" {
Ok(None)
} else {
Err(SyntaxError)
}
}
'[' => {
r.pos += 1;
let mut items = Vec::new();
if r.strict_skip().ok_or(SyntaxError)? == ']' {
return Ok(Some(items));
}
loop {
let c = r.strict_skip().ok_or(SyntaxError)?;
match c {
'"' => items.push(r.quoted('"')?),
'-' | '0'..='9' => {
let word = r.literal();
if !Reader::is_number(&word) {
return Err(SyntaxError);
}
items.push(word);
}
't' | 'f' | 'n' => {
let word = r.literal();
match word.as_str() {
"true" | "false" => items.push(word),
"null" => {}
_ => return Err(SyntaxError),
}
}
_ => return Err(SyntaxError),
}
match r.strict_skip().ok_or(SyntaxError)? {
',' => r.pos += 1,
']' => return Ok(Some(items)),
_ => return Err(SyntaxError),
}
}
}
_ => Err(SyntaxError),
}
}
/// `String.format(Locale.ROOT, "%.<n>f", value)`: Java rounds the shortest
/// round-trip decimal expansion half-up (so 1.005 gives 1.01).
pub fn format_fixed(value: f64, decimals: usize) -> String {
if value.is_nan() {
return "NaN".into();
}
if value.is_infinite() {
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
}
let negative = value.is_sign_negative();
let (digits, exponent) = if value == 0.0 {
("0".to_owned(), 0)
} else {
shortest(&format!("{:e}", value.abs()))
};
let mut int_part: Vec<u8> = Vec::new();
let mut frac: Vec<u8> = Vec::new();
let d: Vec<u8> = digits.bytes().map(|b| b - b'0').collect();
let point = exponent + 1; // digits before the decimal point
if point <= 0 {
int_part.push(0);
frac.extend(std::iter::repeat_n(0, (-point) as usize));
frac.extend(&d);
} else {
let point = point as usize;
for i in 0..point {
int_part.push(d.get(i).copied().unwrap_or(0));
}
if d.len() > point {
frac.extend(&d[point..]);
}
}
let round_up = frac.get(decimals).is_some_and(|&x| x >= 5);
frac.truncate(decimals);
frac.resize(decimals, 0);
if round_up {
let mut carry = true;
for x in frac.iter_mut().rev().chain(int_part.iter_mut().rev()) {
if !carry {
break;
}
if *x == 9 {
*x = 0;
} else {
*x += 1;
carry = false;
}
}
if carry {
int_part.insert(0, 1);
}
}
let mut out = String::new();
if negative {
out.push('-');
}
out.extend(int_part.iter().map(|&x| (b'0' + x) as char));
if decimals > 0 {
out.push('.');
out.extend(frac.iter().map(|&x| (b'0' + x) as char));
}
out
}
/// `%.2f`.
pub fn format_fixed2(value: f64) -> String {
format_fixed(value, 2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn java_number_text() {
assert_eq!(double_to_string(1.0), "1.0");
assert_eq!(double_to_string(0.5), "0.5");
assert_eq!(double_to_string(0.0001), "1.0E-4");
assert_eq!(double_to_string(0.001), "0.001");
assert_eq!(double_to_string(1234567.0), "1234567.0");
assert_eq!(double_to_string(12345678.0), "1.2345678E7");
assert_eq!(double_to_string(100.0), "100.0");
assert_eq!(float_to_string(0.15), "0.15");
assert_eq!(float_to_string(1.0e10), "1.0E10");
assert_eq!(double_to_string(-2.5), "-2.5");
}
#[test]
fn lenient_json() {
assert_eq!(parse_lenient("0.5").unwrap(), Json::Number("0.5".into()));
assert_eq!(parse_lenient("fast").unwrap(), Json::String("fast".into()));
assert_eq!(parse_lenient("TRUE").unwrap(), Json::Bool(true));
assert_eq!(parse_lenient("007").unwrap(), Json::String("007".into()));
assert!(parse_lenient("1 2").is_err());
assert!(parse_lenient("\"abc").is_err());
assert_eq!(parse_lenient(" ").unwrap(), Json::Null);
assert_eq!(gson_string("a=b"), "\"a\\u003db\"");
}
}
+265
View File
@@ -0,0 +1,265 @@
//! InputConstants key tables of 26.3 (SDL scancodes), generated from the
//! pinned client by `VanillaOptionsTableExporter`.
/// Keyboard keys: (SDL scancode, key name).
pub const KEYBOARD: &[(i32, &str)] = &[
(0, "key.keyboard.unknown"),
(4, "key.keyboard.a"),
(5, "key.keyboard.b"),
(6, "key.keyboard.c"),
(7, "key.keyboard.d"),
(8, "key.keyboard.e"),
(9, "key.keyboard.f"),
(10, "key.keyboard.g"),
(11, "key.keyboard.h"),
(12, "key.keyboard.i"),
(13, "key.keyboard.j"),
(14, "key.keyboard.k"),
(15, "key.keyboard.l"),
(16, "key.keyboard.m"),
(17, "key.keyboard.n"),
(18, "key.keyboard.o"),
(19, "key.keyboard.p"),
(20, "key.keyboard.q"),
(21, "key.keyboard.r"),
(22, "key.keyboard.s"),
(23, "key.keyboard.t"),
(24, "key.keyboard.u"),
(25, "key.keyboard.v"),
(26, "key.keyboard.w"),
(27, "key.keyboard.x"),
(28, "key.keyboard.y"),
(29, "key.keyboard.z"),
(30, "key.keyboard.1"),
(31, "key.keyboard.2"),
(32, "key.keyboard.3"),
(33, "key.keyboard.4"),
(34, "key.keyboard.5"),
(35, "key.keyboard.6"),
(36, "key.keyboard.7"),
(37, "key.keyboard.8"),
(38, "key.keyboard.9"),
(39, "key.keyboard.0"),
(40, "key.keyboard.enter"),
(41, "key.keyboard.escape"),
(42, "key.keyboard.backspace"),
(43, "key.keyboard.tab"),
(44, "key.keyboard.space"),
(45, "key.keyboard.minus"),
(46, "key.keyboard.equal"),
(47, "key.keyboard.left.bracket"),
(48, "key.keyboard.right.bracket"),
(49, "key.keyboard.backslash"),
(50, "key.keyboard.world.2"),
(51, "key.keyboard.semicolon"),
(52, "key.keyboard.apostrophe"),
(53, "key.keyboard.grave.accent"),
(54, "key.keyboard.comma"),
(55, "key.keyboard.period"),
(56, "key.keyboard.slash"),
(57, "key.keyboard.caps.lock"),
(58, "key.keyboard.f1"),
(59, "key.keyboard.f2"),
(60, "key.keyboard.f3"),
(61, "key.keyboard.f4"),
(62, "key.keyboard.f5"),
(63, "key.keyboard.f6"),
(64, "key.keyboard.f7"),
(65, "key.keyboard.f8"),
(66, "key.keyboard.f9"),
(67, "key.keyboard.f10"),
(68, "key.keyboard.f11"),
(69, "key.keyboard.f12"),
(70, "key.keyboard.print.screen"),
(71, "key.keyboard.scroll.lock"),
(72, "key.keyboard.pause"),
(73, "key.keyboard.insert"),
(74, "key.keyboard.home"),
(75, "key.keyboard.page.up"),
(76, "key.keyboard.delete"),
(77, "key.keyboard.end"),
(78, "key.keyboard.page.down"),
(79, "key.keyboard.right"),
(80, "key.keyboard.left"),
(81, "key.keyboard.down"),
(82, "key.keyboard.up"),
(83, "key.keyboard.num.lock"),
(84, "key.keyboard.keypad.divide"),
(85, "key.keyboard.keypad.multiply"),
(86, "key.keyboard.keypad.subtract"),
(87, "key.keyboard.keypad.add"),
(88, "key.keyboard.keypad.enter"),
(89, "key.keyboard.keypad.1"),
(90, "key.keyboard.keypad.2"),
(91, "key.keyboard.keypad.3"),
(92, "key.keyboard.keypad.4"),
(93, "key.keyboard.keypad.5"),
(94, "key.keyboard.keypad.6"),
(95, "key.keyboard.keypad.7"),
(96, "key.keyboard.keypad.8"),
(97, "key.keyboard.keypad.9"),
(98, "key.keyboard.keypad.0"),
(99, "key.keyboard.keypad.period"),
(100, "key.keyboard.world.1"),
(101, "key.keyboard.application"),
(102, "key.keyboard.power"),
(103, "key.keyboard.keypad.equal"),
(104, "key.keyboard.f13"),
(105, "key.keyboard.f14"),
(106, "key.keyboard.f15"),
(107, "key.keyboard.f16"),
(108, "key.keyboard.f17"),
(109, "key.keyboard.f18"),
(110, "key.keyboard.f19"),
(111, "key.keyboard.f20"),
(112, "key.keyboard.f21"),
(113, "key.keyboard.f22"),
(114, "key.keyboard.f23"),
(115, "key.keyboard.f24"),
(116, "key.keyboard.execute"),
(117, "key.keyboard.help"),
(118, "key.keyboard.menu"),
(119, "key.keyboard.select"),
(120, "key.keyboard.stop"),
(121, "key.keyboard.again"),
(122, "key.keyboard.undo"),
(123, "key.keyboard.cut"),
(124, "key.keyboard.copy"),
(125, "key.keyboard.paste"),
(126, "key.keyboard.find"),
(127, "key.keyboard.mute"),
(128, "key.keyboard.volume.up"),
(129, "key.keyboard.volume.down"),
(133, "key.keyboard.keypad.comma"),
(134, "key.keyboard.keypad.equals.as400"),
(135, "key.keyboard.international1"),
(136, "key.keyboard.international2"),
(137, "key.keyboard.international3"),
(138, "key.keyboard.international4"),
(139, "key.keyboard.international5"),
(140, "key.keyboard.international6"),
(141, "key.keyboard.international7"),
(142, "key.keyboard.international8"),
(143, "key.keyboard.international9"),
(144, "key.keyboard.lang1"),
(145, "key.keyboard.lang2"),
(146, "key.keyboard.lang3"),
(147, "key.keyboard.lang4"),
(148, "key.keyboard.lang5"),
(149, "key.keyboard.lang6"),
(150, "key.keyboard.lang7"),
(151, "key.keyboard.lang8"),
(152, "key.keyboard.lang9"),
(153, "key.keyboard.alternate.erase"),
(154, "key.keyboard.sys.req"),
(155, "key.keyboard.cancel"),
(156, "key.keyboard.clear"),
(157, "key.keyboard.prior"),
(158, "key.keyboard.enter2"),
(159, "key.keyboard.separator"),
(160, "key.keyboard.out"),
(161, "key.keyboard.oper"),
(162, "key.keyboard.clear.again"),
(163, "key.keyboard.crsel"),
(164, "key.keyboard.exsel"),
(176, "key.keyboard.keypad.00"),
(177, "key.keyboard.keypad.000"),
(178, "key.keyboard.thousands.separator"),
(179, "key.keyboard.decimal.separator"),
(180, "key.keyboard.currency.unit"),
(181, "key.keyboard.currency.subunit"),
(182, "key.keyboard.keypad.left.parenthesis"),
(183, "key.keyboard.keypad.right.parenthesis"),
(184, "key.keyboard.keypad.left.brace"),
(185, "key.keyboard.keypad.right.brace"),
(186, "key.keyboard.keypad.tab"),
(187, "key.keyboard.keypad.backspace"),
(188, "key.keyboard.keypad.a"),
(189, "key.keyboard.keypad.b"),
(190, "key.keyboard.keypad.c"),
(191, "key.keyboard.keypad.d"),
(192, "key.keyboard.keypad.e"),
(193, "key.keyboard.keypad.f"),
(194, "key.keyboard.keypad.xor"),
(195, "key.keyboard.keypad.power"),
(196, "key.keyboard.keypad.percent"),
(197, "key.keyboard.keypad.less"),
(198, "key.keyboard.keypad.greater"),
(199, "key.keyboard.keypad.ampersand"),
(200, "key.keyboard.keypad.double.ampersand"),
(201, "key.keyboard.keypad.vertical.bar"),
(202, "key.keyboard.keypad.double.vertical.bar"),
(203, "key.keyboard.keypad.colon"),
(204, "key.keyboard.keypad.hash"),
(205, "key.keyboard.keypad.space"),
(206, "key.keyboard.keypad.at"),
(207, "key.keyboard.keypad.exclamation"),
(208, "key.keyboard.keypad.memory.store"),
(209, "key.keyboard.keypad.memory.recall"),
(210, "key.keyboard.keypad.memory.clear"),
(211, "key.keyboard.keypad.memory.add"),
(212, "key.keyboard.keypad.memory.subtract"),
(213, "key.keyboard.keypad.memory.multiply"),
(214, "key.keyboard.keypad.memory.divide"),
(215, "key.keyboard.keypad.plus.minus"),
(216, "key.keyboard.keypad.clear"),
(217, "key.keyboard.keypad.clear.entry"),
(218, "key.keyboard.keypad.binary"),
(219, "key.keyboard.keypad.octal"),
(220, "key.keyboard.keypad.decimal"),
(221, "key.keyboard.keypad.hexadecimal"),
(224, "key.keyboard.left.control"),
(225, "key.keyboard.left.shift"),
(226, "key.keyboard.left.alt"),
(227, "key.keyboard.left.win"),
(228, "key.keyboard.right.control"),
(229, "key.keyboard.right.shift"),
(230, "key.keyboard.right.alt"),
(231, "key.keyboard.right.win"),
(257, "key.keyboard.mode"),
(258, "key.keyboard.sleep"),
(259, "key.keyboard.wake"),
(260, "key.keyboard.channel.up"),
(261, "key.keyboard.channel.down"),
(262, "key.keyboard.media.play"),
(263, "key.keyboard.media.pause"),
(264, "key.keyboard.media.record"),
(265, "key.keyboard.media.fast.forward"),
(266, "key.keyboard.media.rewind"),
(267, "key.keyboard.media.next.track"),
(268, "key.keyboard.media.previous.track"),
(269, "key.keyboard.media.stop"),
(270, "key.keyboard.media.eject"),
(271, "key.keyboard.media.play.pause"),
(272, "key.keyboard.media.select"),
(273, "key.keyboard.ac.new"),
(274, "key.keyboard.ac.open"),
(275, "key.keyboard.ac.close"),
(276, "key.keyboard.ac.exit"),
(277, "key.keyboard.ac.save"),
(278, "key.keyboard.ac.print"),
(279, "key.keyboard.ac.properties"),
(280, "key.keyboard.ac.search"),
(281, "key.keyboard.ac.home"),
(282, "key.keyboard.ac.back"),
(283, "key.keyboard.ac.forward"),
(284, "key.keyboard.ac.stop"),
(285, "key.keyboard.ac.refresh"),
(286, "key.keyboard.ac.bookmarks"),
(287, "key.keyboard.soft.left"),
(288, "key.keyboard.soft.right"),
(289, "key.keyboard.call"),
(290, "key.keyboard.end.call"),
];
/// Mouse buttons: (button number, key name).
pub const MOUSE: &[(i32, &str)] = &[
(1, "key.mouse.left"),
(2, "key.mouse.middle"),
(3, "key.mouse.right"),
(4, "key.mouse.4"),
(5, "key.mouse.5"),
(6, "key.mouse.6"),
(7, "key.mouse.7"),
(8, "key.mouse.8"),
];
+26
View File
@@ -43,6 +43,7 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
("key.advancements", "key.keyboard.l", "misc"),
("key.quickActions", "key.keyboard.g", "misc"),
("key.debug.overlay", "key.keyboard.f3", "debug"),
("key.debug.modifier", "key.keyboard.f3", "debug"),
("key.hotbar.1", "key.keyboard.1", "inventory"),
("key.hotbar.2", "key.keyboard.2", "inventory"),
("key.hotbar.3", "key.keyboard.3", "inventory"),
@@ -52,7 +53,32 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
("key.hotbar.7", "key.keyboard.7", "inventory"),
("key.hotbar.8", "key.keyboard.8", "inventory"),
("key.hotbar.9", "key.keyboard.9", "inventory"),
("key.debug.reloadChunk", "key.keyboard.a", "debug"),
("key.debug.showHitboxes", "key.keyboard.b", "debug"),
("key.debug.clearChat", "key.keyboard.d", "debug"),
("key.debug.crash", "key.keyboard.c", "debug"),
("key.debug.showChunkBorders", "key.keyboard.g", "debug"),
("key.debug.showAdvancedTooltips", "key.keyboard.h", "debug"),
("key.debug.copyRecreateCommand", "key.keyboard.i", "debug"),
("key.debug.spectate", "key.keyboard.n", "debug"),
("key.debug.switchGameMode", "key.keyboard.f4", "debug"),
("key.debug.debugOptions", "key.keyboard.f6", "debug"),
("key.debug.focusPause", "key.keyboard.p", "debug"),
("key.debug.dumpDynamicTextures", "key.keyboard.s", "debug"),
("key.debug.reloadResourcePacks", "key.keyboard.t", "debug"),
("key.debug.profiling", "key.keyboard.l", "debug"),
("key.debug.copyLocation", "key.keyboard.c", "debug"),
("key.debug.dumpVersion", "key.keyboard.v", "debug"),
("key.debug.profilingChart", "key.keyboard.1", "debug"),
("key.debug.fpsCharts", "key.keyboard.2", "debug"),
("key.debug.networkCharts", "key.keyboard.3", "debug"),
("key.debug.lightmapTexture", "key.keyboard.4", "debug"),
("key.debug.improvedTransparency", "key.keyboard.x", "debug"),
];
/// Mappings Options builds as `ToggleKeyMapping` (hold or toggle by option).
pub fn is_toggle(name: &str) -> bool {
matches!(name, "key.sneak" | "key.sprint" | "key.use" | "key.attack")
}
/// KeyMapping.Category sort order.
pub const CATEGORIES: [&str; 8] = [
"movement",
+110
View File
@@ -0,0 +1,110 @@
//! The down/click state of `KeyMapping` and `ToggleKeyMapping` (sneak,
//! sprint, attack and use can be toggled instead of held).
/// One mapping's runtime state. `toggle` is `Some(restore)` for a
/// `ToggleKeyMapping` (with its `shouldRestore` flag), `None` for a plain one.
#[derive(Clone, Debug)]
pub struct KeyState {
pub is_down: bool,
click_count: i32,
released_by_screen_when_down: bool,
toggle: Option<bool>,
keyboard: bool,
}
impl KeyState {
pub fn plain() -> Self {
Self {
is_down: false,
click_count: 0,
released_by_screen_when_down: false,
toggle: None,
keyboard: true,
}
}
/// A `ToggleKeyMapping`; `keyboard` is whether the bound key is a keyboard key.
pub fn toggle(should_restore: bool, keyboard: bool) -> Self {
Self {
toggle: Some(should_restore),
keyboard,
..Self::plain()
}
}
/// `KeyMapping.click`: one more pending click.
pub fn click(&mut self) {
self.click_count += 1;
}
/// `consumeClick`.
pub fn consume_click(&mut self) -> bool {
if self.click_count == 0 {
false
} else {
self.click_count -= 1;
true
}
}
/// `setDown`; `needs_toggle` is the mapping's option value.
pub fn set_down(&mut self, down: bool, needs_toggle: bool) {
if self.toggle.is_some() && needs_toggle {
if down {
self.is_down = !self.is_down;
}
} else {
self.is_down = down;
}
}
/// `shouldSetOnIngameFocus` for a keyboard-bound, bound key.
pub fn should_set_on_ingame_focus(&self, needs_toggle: bool) -> bool {
self.keyboard && (self.toggle.is_none() || !needs_toggle)
}
/// `release` (a screen opened): drops pending clicks and the held state.
pub fn release(&mut self, needs_toggle: bool) {
if self.toggle.is_some() {
// ToggleKeyMapping.release does not clear pending clicks.
if needs_toggle && self.is_down || self.released_by_screen_when_down {
self.released_by_screen_when_down = true;
}
self.reset();
} else {
self.click_count = 0;
self.set_down(false, needs_toggle);
}
}
/// `ToggleKeyMapping.reset`.
pub fn reset(&mut self) {
self.is_down = false;
}
/// `shouldRestoreStateOnScreenClosed` (clears the remembered release).
pub fn should_restore_state_on_screen_closed(&mut self, needs_toggle: bool) -> bool {
let Some(restore) = self.toggle else {
return false;
};
let result = restore && needs_toggle && self.keyboard && self.released_by_screen_when_down;
self.released_by_screen_when_down = false;
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggle_flips_on_press_and_ignores_release() {
let mut k = KeyState::toggle(true, true);
k.set_down(true, true);
assert!(k.is_down);
k.set_down(false, true);
assert!(k.is_down);
k.set_down(true, true);
assert!(!k.is_down);
}
#[test]
fn screen_release_restores_toggled_state() {
let mut k = KeyState::toggle(true, true);
k.set_down(true, true);
k.release(true);
assert!(!k.is_down);
assert!(k.should_restore_state_on_screen_closed(true));
assert!(!k.should_restore_state_on_screen_closed(true));
}
}
+9 -20
View File
@@ -2,7 +2,7 @@
//! (sections with their paletted containers, block entities and the sky and
//! block DataLayers) and the section block-change batches.
use crate::{
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section},
chunk::{Chunk, Light, MIN_Y, SECTIONS, Section},
containers::BlockEntity,
};
use horizon_protocol::{
@@ -154,12 +154,7 @@ impl ChunkEncoder {
.is_none_or(|f| f & NON_AIR == 0)
}
fn section(
&self,
section: &Section,
chunk: &Chunk,
index: usize,
) -> (horizon_protocol::chunk::Section, bool) {
fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, bool) {
let mut values = Vec::with_capacity(BLOCKS);
let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false);
let mut count = |state: u16, n: i16| {
@@ -172,21 +167,15 @@ impl ChunkEncoder {
}
f & ENTITY != 0
};
match &section.blocks {
Blocks::Uniform(v) => {
entities |= count(*v, BLOCKS as i16);
values.resize(BLOCKS, i32::from(*v));
}
Blocks::Full(a) => {
for &v in a.iter() {
entities |= count(v, 1);
values.push(i32::from(v));
}
}
let mut unpacked = [0u16; BLOCKS];
section.unpack(&mut unpacked);
for &v in &unpacked {
entities |= count(v, 1);
values.push(i32::from(v));
}
let biome_values: Vec<i32> = (0..BIOMES)
.map(|j| {
let internal = chunk.biomes.get(index * BIOMES + j).copied().unwrap_or(0);
let internal = section.biomes.get(j) as u16;
self.biome_ids
.get(usize::from(internal))
.copied()
@@ -213,7 +202,7 @@ impl ChunkEncoder {
let mut sections = Vec::with_capacity(SECTIONS);
let mut entity_infos = Vec::new();
for (i, s) in chunk.sections.iter().enumerate() {
let (encoded, has_entities) = self.section(s, chunk, i);
let (encoded, has_entities) = self.section(s);
if has_entities {
for y in 0..16 {
for z in 0..16 {
+169
View File
@@ -0,0 +1,169 @@
//! LAN game discovery: LanServerPinger announces a hosted world on the
//! multicast group 224.0.2.60:4445 every 1.5 seconds as
//! `[MOTD]text[/MOTD][AD]port[/AD]`, and LanServerDetection collects those
//! announcements for the multiplayer screen.
use std::{
io,
net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket},
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
thread::JoinHandle,
time::{Duration, Instant},
};
pub const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 2, 60);
pub const PORT: u16 = 4445;
/// LanServerPinger sleeps 1500 ms between announcements.
const INTERVAL: Duration = Duration::from_millis(1500);
/// LanServerDetection.LanServerList drops entries not refreshed for 5 s.
const EXPIRY: Duration = Duration::from_secs(5);
/// LanServerPinger.createPingString.
pub fn ping_string(motd: &str, port: u16) -> String {
format!("[MOTD]{motd}[/MOTD][AD]{port}[/AD]")
}
fn between<'a>(s: &'a str, open: &str, close: &str) -> Option<&'a str> {
let start = s.find(open)? + open.len();
let end = s[start..].find(close)? + start;
Some(&s[start..end])
}
/// LanServerPinger.parseMotd; vanilla shows "missing no" when absent.
pub fn parse_motd(s: &str) -> String {
between(s, "[MOTD]", "[/MOTD]")
.unwrap_or("missing no")
.to_owned()
}
/// LanServerPinger.parseAddress: the announced port, if present and valid.
pub fn parse_port(s: &str) -> Option<u16> {
between(s, "[AD]", "[/AD]")?.parse().ok().filter(|p| *p > 0)
}
/// Announces one hosted world until dropped.
pub struct Pinger {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl Pinger {
pub fn start(motd: String, port: u16) -> io::Result<Self> {
let socket = UdpSocket::bind(("0.0.0.0", 0))?;
let _ = socket.set_multicast_ttl_v4(4);
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let message = ping_string(&motd, port);
let thread = std::thread::Builder::new()
.name("horizon-lan-ping".into())
.spawn(move || {
let target = SocketAddr::V4(SocketAddrV4::new(GROUP, PORT));
while !flag.load(Ordering::Relaxed) {
let _ = socket.send_to(message.as_bytes(), target);
let mut slept = Duration::ZERO;
while slept < INTERVAL && !flag.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(50));
slept += Duration::from_millis(50);
}
}
})?;
Ok(Self {
stop,
thread: Some(thread),
})
}
}
impl Drop for Pinger {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
/// A world announced on the local network.
#[derive(Clone, Debug, PartialEq)]
pub struct LanGame {
pub motd: String,
pub address: String,
}
type Games = Arc<Mutex<Vec<(LanGame, Instant)>>>;
/// Listens for announcements until the last clone is dropped.
#[derive(Clone, Debug)]
pub struct Scanner {
inner: Arc<ScanInner>,
}
#[derive(Debug)]
struct ScanInner {
games: Games,
stop: Arc<AtomicBool>,
}
impl Drop for ScanInner {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
}
}
impl Scanner {
/// Bind the discovery port; without it the list simply stays empty.
pub fn start() -> Self {
let games: Games = Arc::default();
let stop = Arc::new(AtomicBool::new(false));
if let Ok(socket) = bind_listener() {
let (games, stop) = (games.clone(), stop.clone());
let _ = std::thread::Builder::new()
.name("horizon-lan-scan".into())
.spawn(move || listen(socket, games, stop));
}
Self {
inner: Arc::new(ScanInner { games, stop }),
}
}
/// The live announcements, oldest first.
pub fn games(&self) -> Vec<LanGame> {
let mut games = self.inner.games.lock().unwrap();
games.retain(|(_, seen)| seen.elapsed() < EXPIRY);
games.iter().map(|(g, _)| g.clone()).collect()
}
}
fn bind_listener() -> io::Result<UdpSocket> {
let socket = UdpSocket::bind(("0.0.0.0", PORT))?;
socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?;
socket.set_read_timeout(Some(Duration::from_millis(250)))?;
Ok(socket)
}
fn listen(socket: UdpSocket, games: Games, stop: Arc<AtomicBool>) {
let mut buf = [0u8; 1024];
while !stop.load(Ordering::Relaxed) {
let Ok((n, from)) = socket.recv_from(&mut buf) else {
continue;
};
let text = String::from_utf8_lossy(&buf[..n]);
let Some(port) = parse_port(&text) else {
continue;
};
let game = LanGame {
motd: parse_motd(&text),
address: format!("{}:{port}", from.ip()),
};
let mut games = games.lock().unwrap();
match games.iter_mut().find(|(g, _)| g.address == game.address) {
Some(entry) => *entry = (game, Instant::now()),
None => games.push((game, Instant::now())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ping_string_round_trips() {
let s = ping_string("Steve - World", 25565);
assert_eq!(s, "[MOTD]Steve - World[/MOTD][AD]25565[/AD]");
assert_eq!(parse_motd(&s), "Steve - World");
assert_eq!(parse_port(&s), Some(25565));
assert_eq!(parse_port("[AD]0[/AD]"), None);
assert_eq!(parse_motd("junk"), "missing no");
}
}
+6
View File
@@ -8,6 +8,7 @@ pub mod chunks;
pub mod conn;
pub mod containers;
pub mod data;
pub mod discovery;
pub mod entity;
pub mod guest;
pub mod hub;
@@ -111,6 +112,8 @@ pub struct Lan {
events: Receiver<NetEvent>,
pub port: u16,
listener: Option<JoinHandle<()>>,
/// The multicast announcement (LanServerPinger); absent when the socket failed.
_pinger: Option<discovery::Pinger>,
}
impl Lan {
/// Listen on `port` (0 picks a free one).
@@ -123,6 +126,7 @@ impl Lan {
let listener = TcpListener::bind(("0.0.0.0", port))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let _pinger = discovery::Pinger::start(motd.clone(), port).ok();
let (tx, events) = channel();
let shared = Arc::new(Shared {
sync,
@@ -142,6 +146,7 @@ impl Lan {
events,
port,
listener: Some(listener),
_pinger,
})
}
/// Everything the connection threads reported since the last call.
@@ -160,6 +165,7 @@ impl Lan {
if let Some(t) = self.listener.take() {
let _ = t.join();
}
self._pinger = None;
}
}
impl Drop for Lan {
+10
View File
@@ -11,9 +11,11 @@ pub mod banner;
pub mod biome;
pub mod block_entity_nbt;
pub mod block_entity_render;
pub mod block_transform;
pub mod blocks;
pub mod bossbar;
pub mod brewing;
pub mod cauldron;
pub mod chat;
pub mod chunk;
pub mod clock;
@@ -43,20 +45,27 @@ pub mod hunger;
pub mod input;
pub mod item_data;
pub mod items;
pub mod java_text;
pub mod key_names;
pub mod keybinds;
pub mod keymapping;
pub mod lan;
pub mod landing;
pub mod lang;
pub mod light;
pub mod menu;
pub mod merchant;
pub mod mesher;
pub mod mobs;
pub mod models;
pub mod motion;
pub mod mouse;
pub mod multiplayer;
pub mod music;
pub mod nbt_path;
pub mod net;
pub mod options_file;
pub mod options_fixes;
pub mod options_ui;
pub mod packs;
pub mod particles;
@@ -86,6 +95,7 @@ pub mod text;
pub mod title;
pub mod ui;
pub mod vanillagen;
pub mod window;
pub mod world;
pub mod worldborder;
pub mod zip;
+3 -2
View File
@@ -216,6 +216,7 @@ pub fn light_chunk(
let mut block = vec![0u8; W * W * h];
let mut queue = VecDeque::new();
let mut sky_queue = VecDeque::new();
let mut ids = Box::new([0u16; 4096]);
for (dz, row) in region.iter().enumerate() {
for (dx, chunk) in row.iter().enumerate() {
let Some(chunk) = chunk else { continue };
@@ -223,8 +224,8 @@ pub fn light_chunk(
if section.is_uniform(0) {
continue;
}
for i in 0..4096 {
let id = section.get(i);
section.unpack(&mut ids);
for (i, &id) in ids.iter().enumerate() {
let (lx, lz, ly) = (i & 15, (i >> 4) & 15, i >> 8);
let p = at(dx * 16 + lx, si * 16 + ly, dz * 16 + lz);
states[p] = id;
File diff suppressed because it is too large Load Diff
+168 -63
View File
@@ -12,7 +12,9 @@ use crate::{
chunk::{Chunk, MIN_Y},
models::catalog::BakedFace,
};
use horizon_core::{geometry::Direction, position::BlockPos, random::position_seed};
use horizon_core::{
biome::BiomeZoom, geometry::Direction, position::BlockPos, random::position_seed,
};
use horizon_world::{
block_render::FaceVisibility,
fluid::{FluidKind, FluidState},
@@ -161,6 +163,8 @@ struct Info {
legacy_solid: bool,
/// `HalfTransparentBlock`/`LeavesBlock`: water sides show the overlay sprite.
overlay: bool,
/// `LeavesBlock`: with opaque leaves the faces between two leaf blocks are skipped.
leaves: bool,
blocks_flow: bool,
ice: bool,
sturdy: u8,
@@ -313,6 +317,7 @@ impl MeshTables {
offset,
legacy_solid: s.legacy_solid,
overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"),
leaves: s.has_class("LeavesBlock"),
blocks_flow: assets.blocks_fluid_flow.contains(&*s.name),
ice: s.has_class("IceBlock"),
sturdy: s.sturdy_full,
@@ -378,6 +383,13 @@ 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;
// The section itself is unpacked in one pass; the border cells of the
// neighbouring sections are read one by one.
let mut own = Box::new([0u16; 4096]);
let center = region[1][1].map(|c| &c.sections[sy as usize]);
if let Some(section) = center {
section.unpack(&mut own);
}
for y in -B..16 + B {
let wy = base_y + y;
for z in -B..16 + B {
@@ -385,7 +397,13 @@ impl Padded {
let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize];
let i = pi(x, y, z);
if let Some(c) = chunk {
blocks[i] = c.get(x & 15, wy, z & 15);
blocks[i] =
if (0..16).contains(&x) && (0..16).contains(&y) && (0..16).contains(&z)
{
own[(y << 8 | z << 4 | x) as usize]
} else {
c.get(x & 15, wy, z & 15)
};
light[i] = c.light(x & 15, wy, z & 15);
} else {
light[i] = 0xF0;
@@ -396,57 +414,113 @@ impl Padded {
Self { blocks, light }
}
}
/// Set on a vertex's sprite layer when its texture alpha must be ignored.
pub const OPAQUE_LAYER: u32 = 1 << 31;
const UNSET: u32 = u32::MAX;
const NO_BIOME: u16 = u16::MAX;
/// The `ColorResolver`s `ClientLevel` caches block tints for.
#[derive(Clone, Copy)]
struct Colors {
grass: [u32; 256],
tall_upper: [u32; 256],
foliage: [u32; 256],
dry: [u32; 256],
water: [u32; 256],
enum Resolver {
Grass,
Foliage,
Dry,
Water,
}
fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y: i32) -> Colors {
// Vanilla blends over a (2r+1)^2 area; r = 2 is the default option.
const R: i32 = 2;
let biome_at = |x: i32, z: i32| -> u16 {
region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]
.map_or(0, |c| c.biome(x & 15, y, z & 15))
};
let mut colors = Colors {
grass: [0; 256],
tall_upper: [0; 256],
foliage: [0; 256],
dry: [0; 256],
water: [0; 256],
};
let avg = |f: &dyn Fn(u16, i32, i32) -> u32, x: i32, z: i32| -> u32 {
let (mut r, mut g, mut b) = (0, 0, 0);
for dz in -R..=R {
for dx in -R..=R {
let c = f(biome_at(x + dx, z + dz), x + dx, z + dz);
r += c >> 16 & 255;
g += c >> 8 & 255;
b += c & 255;
}
}
let n = ((2 * R + 1) * (2 * R + 1)) as u32;
(r / n) << 16 | (g / n) << 8 | (b / n)
};
for z in 0..16 {
for x in 0..16 {
let i = (z * 16 + x) as usize;
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
colors.grass[i] = avg(
&|b, dx, dz| biomes.grass(b, f64::from(wx + dx - x), f64::from(wz + dz - z)),
x,
z,
);
colors.tall_upper[i] = colors.grass[i];
colors.foliage[i] = avg(&|b, _, _| biomes.get(b).foliage, x, z);
colors.dry[i] = avg(&|b, _, _| biomes.get(b).dry_foliage, x, z);
colors.water[i] = avg(&|b, _, _| biomes.get(b).water, x, z);
/// Biome tints of one block layer: the zoomed biome of every block of the
/// layer plus the blend radius around it, and the blended colours per column.
struct Layer {
zoomed: Vec<u16>,
colors: [[u32; 256]; 4],
}
/// `ClientLevel.calculateBlockTint` behind a per-layer `BlockTintCache`: each
/// block averages the colours of the biomes `BiomeManager.getBiome` picks (the
/// eight-corner zoom) over a `(2r+1)^2` square at the block's own height.
/// Layers and columns are only computed when a tinted block asks for them.
struct Tints<'a> {
region: &'a [[Option<&'a Chunk>; 3]; 3],
biomes: &'a Biomes,
zoom: BiomeZoom,
radius: i32,
plains: u16,
/// Chunk x, chunk z and the section's lowest block y.
origin: [i32; 3],
layers: [Option<Box<Layer>>; 16],
}
impl<'a> Tints<'a> {
fn new(
region: &'a [[Option<&'a Chunk>; 3]; 3],
biomes: &'a Biomes,
zoom: BiomeZoom,
radius: i32,
origin: [i32; 3],
) -> Self {
Self {
region,
biomes,
zoom,
radius: radius.clamp(0, 7),
plains: biomes.id("minecraft:plains"),
origin,
layers: Default::default(),
}
}
colors
/// The blended tint of block `(x, y, z)` (section-local x/z, y in 0..16).
fn get(&mut self, resolver: Resolver, x: i32, y: i32, z: i32) -> u32 {
let r = self.radius;
let dim = (16 + 2 * r) as usize;
let layer = self.layers[y as usize].get_or_insert_with(|| {
Box::new(Layer {
zoomed: vec![NO_BIOME; dim * dim],
colors: [[UNSET; 256]; 4],
})
});
let slot = (z * 16 + x) as usize;
let cached = layer.colors[resolver as usize][slot];
if cached != UNSET {
return cached;
}
let [cx, cz, base_y] = self.origin;
let (bx, by, bz) = (cx * 16, base_y + y, cz * 16);
let (mut red, mut green, mut blue) = (0, 0, 0);
for dz in -r..=r {
for dx in -r..=r {
let cell = ((z + dz + r) as usize) * dim + (x + dx + r) as usize;
let mut biome = layer.zoomed[cell];
if biome == NO_BIOME {
// BiomeManager.getBiome over the loaded chunks (plains
// where there is none).
let q = self
.zoom
.quart_at_block(BlockPos::new(bx + x + dx, by, bz + z + dz));
let (rx, rz) = ((q[0] >> 2) - cx + 1, (q[2] >> 2) - cz + 1);
biome = if (0..3).contains(&rx) && (0..3).contains(&rz) {
self.region[rz as usize][rx as usize].map_or(self.plains, |c| {
c.biome((q[0] & 3) * 4, q[1] * 4, (q[2] & 3) * 4)
})
} else {
self.plains
};
layer.zoomed[cell] = biome;
}
let c = match resolver {
Resolver::Grass => {
self.biomes
.grass(biome, f64::from(bx + x + dx), f64::from(bz + z + dz))
}
Resolver::Foliage => self.biomes.get(biome).foliage,
Resolver::Dry => self.biomes.get(biome).dry_foliage,
Resolver::Water => self.biomes.get(biome).water,
};
red += c >> 16 & 255;
green += c >> 8 & 255;
blue += c & 255;
}
}
let n = ((2 * r + 1) * (2 * r + 1)) as u32;
let color = (red / n) << 16 | (green / n) << 8 | (blue / n);
layer.colors[resolver as usize][slot] = color;
color
}
}
/// Packs 8-bit RGB into the vertex's RGBA8 (red in the low byte), opaque.
fn pack_rgb([r, g, b]: [u32; 3]) -> u32 {
@@ -464,6 +538,14 @@ pub struct Mesher<'a> {
pub tables: &'a MeshTables,
pub biomes: &'a Biomes,
pub visibility: FaceVisibility,
/// The client's biome zoom (the hashed world seed `BiomeManager` holds).
pub zoom: BiomeZoom,
/// The `biomeBlendRadius` option, 0 to 7.
pub blend_radius: i32,
/// The `ao` option: smooth lighting for models that allow it.
pub smooth_lighting: bool,
/// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque.
pub cutout_leaves: bool,
}
impl Mesher<'_> {
/// `region[dz][dx]` are the chunks around the meshed column (centre 1,1).
@@ -477,7 +559,13 @@ impl Mesher<'_> {
let pad = Padded::new(region, sy);
out.visibility = visibility(&pad, &self.tables.info);
let base_y = MIN_Y + sy * 16;
let colors = blend(region, self.biomes, center.x, center.z, base_y + 8);
let mut tints = Tints::new(
region,
self.biomes,
self.zoom,
self.blend_radius,
[center.x, center.z, base_y],
);
let info = &self.tables.info;
for y in 0..16 {
for z in 0..16 {
@@ -502,7 +590,7 @@ impl Mesher<'_> {
continue;
}
if state.fluid.kind() != FluidKind::Empty {
let water = colors.water[(z * 16 + x) as usize];
let water = tints.get(Resolver::Water, x, y, z);
let nether = self.nether_shading;
fluid::tesselate(self.tables, nether, &pad, water, &mut out, [x, y, z]);
}
@@ -522,7 +610,7 @@ impl Mesher<'_> {
let Some((_, first)) = models.first() else {
continue;
};
let ao = state.emission == 0 && first.ambient_occlusion;
let ao = self.smooth_lighting && state.emission == 0 && first.ambient_occlusion;
let origin = match offset(state, world.x, world.z) {
Some(o) => [
x as f32 + o[0] as f32,
@@ -544,13 +632,26 @@ impl Mesher<'_> {
true,
)
.unwrap_or(true);
// LeavesBlock.skipRendering with opaque leaves.
if !self.cutout_leaves && state.leaves && info[neighbor as usize].leaves {
visible[d as usize] = false;
}
}
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], origin, face, ao, state);
self.face(
&pad,
&mut tints,
&mut out,
[x, y, z],
origin,
face,
ao,
state,
);
}
}
}
@@ -559,18 +660,17 @@ impl Mesher<'_> {
out
}
/// `BlockColors` tint source `index`, or `None` for an untinted (-1) layer.
fn tint(state: &Info, index: i32, colors: &Colors, x: i32, z: i32) -> Option<u32> {
fn tint(state: &Info, index: i32, tints: &mut Tints, [x, y, z]: [i32; 3]) -> Option<u32> {
if index < 0 || index >= i32::from(state.tint_count) {
return None;
}
let column = (z * 16 + x) as usize;
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],
Tint::DryFoliage => colors.dry[column],
Tint::Water => colors.water[column],
Tint::Grass => tints.get(Resolver::Grass, x, y, z),
Tint::TallGrassUpper => tints.get(Resolver::Grass, x, y, z),
Tint::Foliage => tints.get(Resolver::Foliage, x, y, z),
Tint::DryFoliage => tints.get(Resolver::Dry, x, y, z),
Tint::Water => tints.get(Resolver::Water, x, y, z),
Tint::Constant(c) => c,
Tint::Redstone(p) => redstone_color(p),
Tint::Stem(age) => {
@@ -583,7 +683,7 @@ impl Mesher<'_> {
fn face(
&self,
pad: &Padded,
colors: &Colors,
tints: &mut Tints,
out: &mut SectionMesh,
pos: [i32; 3],
origin: [f32; 3],
@@ -608,7 +708,7 @@ impl Mesher<'_> {
};
([lighting::gray(directional); 4], [coords; 4])
};
let tint = Self::tint(state, q.tint_index, colors, pos[0], pos[2]);
let tint = Self::tint(state, q.tint_index, tints, pos);
let target = if face.translucent {
&mut out.translucent
} else {
@@ -624,7 +724,12 @@ impl Mesher<'_> {
target.push(Vertex {
pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]],
uv: q.uv[i],
layer: face.layer,
// Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout.
layer: if !self.cutout_leaves && state.leaves {
face.layer | OPAQUE_LAYER
} else {
face.layer
},
color: pack_rgb(rgb),
light: pack_coords(lighting::with_emission(coords[i], q.light_emission)),
});
+28
View File
@@ -9,6 +9,7 @@ pub mod ai;
pub mod allay;
pub mod anim;
pub mod aquatic;
pub mod body_anim;
pub mod brain;
pub mod breeze;
pub mod camel;
@@ -27,6 +28,7 @@ pub mod guardian;
pub mod happy_ghast;
pub mod hostile;
pub mod illager;
pub mod illusioner;
pub mod keyframes;
pub mod leash;
pub mod living;
@@ -452,6 +454,9 @@ pub struct Extra {
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
pub pick_up_loot: bool,
pub saddled: bool,
/// The saddle's components (name, enchantments...) when it is not a bare
/// one; `saddled` stays the gameplay flag.
pub saddle_stack: Option<crate::items::ItemStack>,
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
@@ -488,6 +493,8 @@ pub struct Extra {
pub vector: [f64; 3],
/// Active status effects: (effect id, ticks left, amplifier).
pub effects: Vec<(&'static str, i32, i32)>,
/// An invisible illusioner's mirror images.
pub illusions: Option<illusioner::Illusions>,
/// A villager's claimed bed head and meeting bell.
pub bed: Option<[i32; 3]>,
pub meeting: Option<[i32; 3]>,
@@ -887,6 +894,8 @@ pub struct MobWorld<'a> {
pub biomes: &'a crate::biome::Biomes,
/// The `mob_griefing` game rule.
pub mob_griefing: bool,
/// `getCurrentDifficultyAt` near the player.
pub difficulty: spawning::LocalDifficulty,
}
impl Mob {
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
@@ -1222,3 +1231,22 @@ pub fn render_model(
}
}
}
impl Mob {
/// The saddle worn, with its components.
pub fn saddle_item(&self) -> Option<crate::items::ItemStack> {
self.extra.saddled.then(|| {
self.extra
.saddle_stack
.clone()
.unwrap_or_else(|| crate::items::ItemStack::new("minecraft:saddle", 1))
})
}
/// Wear (or take off) a saddle stack, keeping its components.
pub fn set_saddle(&mut self, saddle: Option<crate::items::ItemStack>) {
self.extra.saddled = saddle.is_some();
self.extra.saddle_stack = saddle
.map(|s| crate::items::ItemStack { count: 1, ..s })
.filter(|s| s.damage != 0 || s.extra.is_some());
}
}
+5 -1
View File
@@ -122,7 +122,7 @@ pub fn family(s: Species) -> Family {
S::Wolf | S::Cat => Family::Tame,
S::Blaze | S::Ghast => Family::Nether,
S::IronGolem | S::SnowGolem => Family::Golem,
S::Pillager | S::Vindicator | S::Evoker => Family::Illager,
S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => Family::Illager,
S::Vex => Family::Vex,
S::Ravager => Family::Ravager,
S::Wither => Family::Wither,
@@ -168,6 +168,7 @@ pub fn register(m: &mut Mob) {
Family::Golem => super::golem::register_snow(m),
Family::Illager if m.species() == Species::Pillager => super::illager::register_pillager(m),
Family::Illager if m.species() == Species::Evoker => super::illager::register_evoker(m),
Family::Illager if m.species() == Species::Illusioner => super::illusioner::register(m),
Family::Illager => super::illager::register_vindicator(m),
Family::Equine => super::equine::register(m),
Family::Phantom => super::phantom::register(m),
@@ -383,6 +384,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
}
tick_effects(m);
if m.species() == Species::Illusioner {
super::illusioner::tick(m, events);
}
if m.hurt_time > 0 {
m.hurt_time -= 1;
}
+10 -8
View File
@@ -8,6 +8,7 @@ use super::{
goals::{Cx, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone},
nav::NavKind,
};
use horizon_core::geometry::trig::Mth;
// Allay state: `main_hand` the held item, `ints[1]` how many it carries,
// `tame` a liked player, `point` the wanted item (set by the game),
@@ -15,8 +16,8 @@ use super::{
// pickup cooldown, `flag` dancing with `ints[4]` the dance clock,
// `egg_time` the duplication cooldown. AnimState slots: holding (0),
// spinning (1).
const HOLD: usize = 0;
const SPIN: usize = 1;
pub const HOLD: usize = 0;
pub const SPIN: usize = 1;
pub fn register(m: &mut Mob) {
m.ai.mov.kind = MoveKind::Flying {
@@ -151,22 +152,22 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
use std::f32::consts::PI;
let (speed, pos) = (s.speed, s.pos);
let flap_speed = (s.age * 20.0).to_radians() + pos;
let flap = flap_speed.cos() * PI * 0.15 + speed;
let flap = flap_speed.mcos() * PI * 0.15 + speed;
let idle_bob = (s.age * 9.0).to_radians();
let flying = (speed / 0.3).min(1.0);
let idle = 1.0 - flying;
let hold = m.anim.lerp(HOLD, s.partial) / 5.0;
if m.extra.flag {
let dance = (s.age * 8.0).to_radians() + speed;
let freq = dance.cos() * 16f32.to_radians();
let freq = dance.mcos() * 16f32.to_radians();
let spin = m.anim.lerp(SPIN, s.partial) / 15.0;
let spinning = (m.extra.ints[4] as f32 % 55.0) < 15.0;
if spinning {
p.yrot("root", PI * 4.0 * spin);
}
p.zrot("root", freq * (1.0 - spin));
p.yrot("head", dance.cos() * 30f32.to_radians() * (1.0 - spin));
p.zrot("head", dance.cos() * 14f32.to_radians() * (1.0 - spin));
p.yrot("head", dance.mcos() * 30f32.to_radians() * (1.0 - spin));
p.zrot("head", dance.mcos() * 14f32.to_radians() * (1.0 - spin));
} else {
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
@@ -177,11 +178,12 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("left_wing", PI / 4.0 - flap);
p.xrot("body", flying * PI / 4.0);
let arm_x = hold * (-PI / 3.0 + (-1.134_464 + PI / 3.0) * flying);
p.get("root")[1] += idle_bob.cos() * 0.25 * idle;
// `(float) Math.cos`: the exact function, not `Mth.cos`.
p.get("root")[1] += (f64::from(idle_bob).cos() as f32) * 0.25 * idle;
p.xrot("right_arm", arm_x);
p.xrot("left_arm", arm_x);
let arm_bob = idle * (1.0 - hold);
let amount = 0.436_332_32 - (idle_bob + PI * 1.5).cos() * PI * 0.075 * arm_bob;
let amount = 0.436_332_32 - (idle_bob + PI * 1.5).mcos() * PI * 0.075 * arm_bob;
p.zrot("left_arm", -amount);
p.zrot("right_arm", amount);
p.yrot("right_arm", 0.279_252_68 * hold);
+231 -145
View File
@@ -2,6 +2,7 @@
//! (quadrupeds, humanoids, creepers, spiders, chickens...) applied to a map of
//! part poses before the model is drawn.
use super::{Mob, Part, keyframes::AnimationState, living::wrap};
use horizon_core::geometry::trig::Mth;
use std::collections::HashMap;
use std::f32::consts::PI;
@@ -102,6 +103,10 @@ impl AnimState {
pub struct Poses {
map: HashMap<String, [f32; 9]>,
dummy: [f32; 9],
/// Parts with `skipDraw` set: their own cubes are not drawn, children are.
skipped: std::collections::HashSet<String>,
/// Parts with `visible` cleared: neither they nor their children draw.
hidden: std::collections::HashSet<String>,
}
impl Poses {
pub fn new(model: &Part) -> Self {
@@ -116,6 +121,8 @@ impl Poses {
Self {
map,
dummy: [0.0; 9],
skipped: Default::default(),
hidden: Default::default(),
}
}
pub fn get(&mut self, name: &str) -> &mut [f32; 9] {
@@ -127,6 +134,12 @@ impl Poses {
pub fn pose(&self, part: &Part) -> [f32; 9] {
self.map.get(&part.name).copied().unwrap_or(part.pose)
}
pub fn skip_draw(&mut self, name: &str) {
self.skipped.insert(name.to_owned());
}
pub fn skips(&self, part: &Part) -> bool {
self.skipped.contains(&part.name)
}
pub fn has(&self, name: &str) -> bool {
self.map.contains_key(name)
}
@@ -139,14 +152,17 @@ impl Poses {
pub fn zrot(&mut self, n: &str, v: f32) {
self.get(n)[5] = v;
}
/// `ModelPart.visible = v`; a hidden part and its children do not draw.
pub fn visible(&mut self, n: &str, v: bool) {
if !v {
let p = self.get(n);
p[6] = 0.0;
p[7] = 0.0;
p[8] = 0.0;
if v {
self.hidden.remove(n);
} else if self.map.contains_key(n) {
self.hidden.insert(n.to_owned());
}
}
pub fn is_hidden(&self, part: &Part) -> bool {
self.hidden.contains(&part.name)
}
}
/// The LivingEntityRenderState values setupAnim reads.
#[derive(Clone, Copy, Debug)]
@@ -198,18 +214,18 @@ fn head(p: &mut Poses, s: &State) {
pub(super) fn quadruped(p: &mut Poses, s: &State) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * sp);
p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * sp);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp);
p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * sp);
}
/// AnimationUtils.bobModelPart
fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) {
let q = p.get(n);
q[5] += scale * ((age * 0.09).cos() * 0.05 + 0.05);
q[3] += scale * ((age * 0.067).sin() * 0.05);
q[5] += scale * ((age * 0.09).mcos() * 0.05 + 0.05);
q[3] += scale * ((age * 0.067).msin() * 0.05);
}
#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ArmPose {
Empty,
Item,
@@ -217,118 +233,196 @@ pub enum ArmPose {
CrossbowHold,
CrossbowCharge,
}
/// HumanoidModel.setupAnim holding an item or not (piglins).
pub fn humanoid_item(p: &mut Poses, s: &State, holding: bool) {
let right = if holding {
ArmPose::Item
} else {
ArmPose::Empty
};
humanoid(p, s, right, ArmPose::Empty, None, holding);
/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself.
pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) {
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// HumanoidModel.setupAnim with empty hands (endermen).
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
humanoid(p, s, ArmPose::Empty, ArmPose::Empty, None, false);
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// HumanoidModel.setupAnim up to (and including) the attack animation hook.
fn humanoid(
p: &mut Poses,
s: &State,
right: ArmPose,
left: ArmPose,
zombie: Option<bool>,
holding: bool,
) {
/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm.
pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) {
let attack2 = (swing * PI).msin();
let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15);
p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5);
p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4;
p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4;
bob(p, "right_arm", age, 1.0);
bob(p, "left_arm", age, -1.0);
}
/// What `HumanoidModel.setupAnim` reads besides the walk and head inputs.
#[derive(Clone, Copy, Debug)]
pub struct Hum {
pub right: ArmPose,
pub left: ArmPose,
pub crouching: bool,
pub passenger: bool,
/// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`.
pub zombie: Option<bool>,
/// The main hand holds something (`getMainHandItemStack() != EMPTY`).
pub holding: bool,
/// `maxCrossbowChargeDuration`, `ticksUsingItem`.
pub charge: (f32, f32),
/// `PiglinModel.setupAttackAnimation`: swing a held weapon down.
pub weapon_swing: bool,
}
impl Hum {
pub fn new(right: ArmPose, left: ArmPose) -> Self {
Self {
right,
left,
crouching: false,
passenger: false,
zombie: None,
holding: false,
charge: (0.0, 0.0),
weapon_swing: false,
}
}
}
impl ArmPose {
fn two_handed(self) -> bool {
matches!(self, Self::Bow | Self::CrossbowHold | Self::CrossbowCharge)
}
fn affects_offhand(self) -> bool {
self.two_handed()
}
}
/// `AnimationUtils.animateCrossbowHold`.
fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
let (hold, shoot) = if in_right {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if in_right { -0.3 } else { 0.3 } + hy);
p.yrot(shoot, if in_right { 0.6 } else { -0.6 } + hy);
p.xrot(hold, -PI / 2.0 + hx + 0.1);
p.xrot(shoot, -1.5 + hx);
}
/// `AnimationUtils.animateCrossbowCharge`.
fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) {
let (hold, pull) = if in_right {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if in_right { -0.8 } else { 0.8 });
p.xrot(hold, -0.970_796_35);
p.xrot(pull, -0.970_796_35);
let use_ticks = ticks.clamp(0.0, max);
let alpha = use_ticks / max;
let lerp = |a: f32, p0: f32, p1: f32| p0 + a * (p1 - p0);
p.yrot(
pull,
lerp(alpha, 0.4, 0.85) * if in_right { 1.0 } else { -1.0 },
);
let x = lerp(alpha, p.get(pull)[3], -PI / 2.0);
p.xrot(pull, x);
}
/// `HumanoidModel.poseRightArm` / `poseLeftArm`.
fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
let arm = if right { "right_arm" } else { "left_arm" };
let (hx, hy) = (p.get("head")[3], p.get("head")[4]);
match pose {
ArmPose::Empty => p.yrot(arm, 0.0),
ArmPose::Item => {
let x = p.get(arm)[3];
p.xrot(arm, x * 0.5 - PI / 10.0);
p.yrot(arm, 0.0);
}
ArmPose::Bow => {
p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 });
p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 });
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -PI / 2.0 + hx);
}
ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right),
ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right),
}
}
/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`).
pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5);
p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5);
p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp);
p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5);
p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5);
p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp);
p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp);
p.yrot("right_leg", 0.005);
p.yrot("left_leg", -0.005);
p.zrot("right_leg", 0.005);
p.zrot("left_leg", -0.005);
let (hx, hy) = (p.get("head")[3], p.get("head")[4]);
for (arm, pose) in [("right_arm", right), ("left_arm", left)] {
match pose {
ArmPose::Empty => p.yrot(arm, 0.0),
ArmPose::Item => {
let x = p.get(arm)[3];
p.xrot(arm, x * 0.5 - PI / 10.0);
p.yrot(arm, 0.0);
}
ArmPose::Bow => {
let right_main = arm == "right_arm";
p.yrot("right_arm", -0.1 + hy - if right_main { 0.0 } else { 0.4 });
p.yrot("left_arm", 0.1 + hy + if right_main { 0.4 } else { 0.0 });
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -PI / 2.0 + hx);
}
ArmPose::CrossbowHold => {
let r = arm == "right_arm";
let (hold, shoot) = if r {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if r { -0.3 } else { 0.3 } + hy);
p.yrot(shoot, if r { 0.6 } else { -0.6 } + hy);
p.xrot(hold, -PI / 2.0 + hx + 0.1);
p.xrot(shoot, -1.5 + hx);
}
ArmPose::CrossbowCharge => {
let r = arm == "right_arm";
let (hold, pull) = if r {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if r { -0.8 } else { 0.8 });
p.xrot(hold, -0.970_796_35);
p.xrot(pull, -0.970_796_35);
p.yrot(pull, 0.6 * if r { 1.0 } else { -1.0 });
p.xrot(pull, -PI / 2.0);
}
if h.passenger {
p.get("right_arm")[3] += -PI / 5.0;
p.get("left_arm")[3] += -PI / 5.0;
p.xrot("right_leg", -1.413_716_7);
p.yrot("right_leg", PI / 10.0);
p.zrot("right_leg", 0.078_539_82);
p.xrot("left_leg", -1.413_716_7);
p.yrot("left_leg", -PI / 10.0);
p.zrot("left_leg", -0.078_539_82);
}
// The main arm is the right one: the off-hand pose goes first unless it
// needs both hands.
if h.left.two_handed() {
pose_arm(p, h.right, true, h);
if !h.right.affects_offhand() {
pose_arm(p, h.left, false, h);
}
} else {
pose_arm(p, h.left, false, h);
if !h.left.affects_offhand() {
pose_arm(p, h.right, true, h);
}
}
// setupAttackAnimation (WHACK swing with the right arm).
let hx = p.get("head")[3];
let swing = s.swing;
if swing > 0.0 {
let body_y = (swing.sqrt() * PI * 2.0).sin() * 0.2;
if swing > 0.0 && h.weapon_swing {
swing_weapon_down(p, swing, s.age);
} else if swing > 0.0 {
let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2;
p.yrot("body", body_y);
let age_scale = if s.baby { 0.5 } else { 1.0 };
{
let r = p.get("right_arm");
r[2] = body_y.sin() * 5.0 * age_scale;
r[0] = -body_y.cos() * 5.0 * age_scale;
r[2] = body_y.msin() * 5.0 * age_scale;
r[0] = -body_y.mcos() * 5.0 * age_scale;
}
{
let l = p.get("left_arm");
l[2] = -body_y.sin() * 5.0 * age_scale;
l[0] = body_y.cos() * 5.0 * age_scale;
l[2] = -body_y.msin() * 5.0 * age_scale;
l[0] = body_y.mcos() * 5.0 * age_scale;
}
p.get("right_arm")[4] += body_y;
p.get("left_arm")[4] += body_y;
p.get("left_arm")[3] += body_y;
// Ease.outQuart
let eased = 1.0 - (1.0 - swing).powi(4);
let aa = (eased * PI).sin();
let bb = (swing * PI).sin() * -(hx - 0.7) * 0.75;
let aa = (eased * PI).msin();
let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75;
let r = p.get("right_arm");
r[3] -= aa * 1.2 + bb;
r[4] += body_y * 2.0;
r[5] += (swing * PI).sin() * -0.4;
r[5] += (swing * PI).msin() * -0.4;
}
if let Some(aggressive) = zombie {
if let Some(aggressive) = h.zombie {
// AnimationUtils.animateZombieArms
let raise = !s.baby || !holding;
let raise = !s.baby || !h.holding;
let drop = if raise {
-PI / if aggressive { 1.5 } else { 2.25 }
} else {
0.0
};
let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).sin();
let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).msin();
let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
let x = drop + ym * 1.2 - xm * 0.4;
let y = 0.1 - ym * 0.6;
p.xrot("right_arm", x);
@@ -338,6 +432,17 @@ fn humanoid(
p.yrot("left_arm", if raise { y } else { -y });
p.zrot("left_arm", 0.0);
}
if h.crouching {
p.xrot("body", 0.5);
p.get("right_arm")[3] += 0.4;
p.get("left_arm")[3] += 0.4;
p.get("right_leg")[2] += 4.0;
p.get("left_leg")[2] += 4.0;
p.get("head")[1] += 4.2;
p.get("body")[1] += 3.2;
p.get("left_arm")[1] += 3.2;
p.get("right_arm")[1] += 3.2;
}
bob(p, "right_arm", s.age, 1.0);
bob(p, "left_arm", s.age, -1.0);
}
@@ -348,6 +453,9 @@ pub fn setup(
p: &mut Poses,
w_anims: &HashMap<String, super::keyframes::Animation>,
) {
if super::body_anim::anim(m, s, p, w_anims) {
return;
}
match m.kind.anim {
Anim::Camel => super::camel::anim(m, s, p, w_anims),
Anim::Breeze => super::breeze::anim(m, s, p, w_anims),
@@ -377,7 +485,7 @@ pub fn setup(
};
let angle = if t > 4 && t <= 36 {
let f = ((t - 4) as f32 - partial) / 32.0;
PI / 5.0 + 0.219_911_49 * (f * 28.7).sin()
PI / 5.0 + 0.219_911_49 * (f * 28.7).msin()
} else if t > 0 {
PI / 5.0
} else {
@@ -391,9 +499,9 @@ pub fn setup(
let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial;
let flap_speed =
m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial;
let angle = (flap.sin() + 1.0) * flap_speed;
p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
p.xrot("left_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed);
let angle = (flap.msin() + 1.0) * flap_speed;
p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed);
p.xrot("left_leg", (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed);
p.zrot("right_wing", angle);
p.zrot("left_wing", -angle);
if !s.baby {
@@ -405,57 +513,35 @@ pub fn setup(
| Anim::ZombieVillager
| Anim::ZombifiedPiglin
| Anim::Humanoid { zombie_arms: true } => {
let holding = m.extra.main_hand.is_some();
let right = if holding {
ArmPose::Item
} else {
ArmPose::Empty
};
humanoid(p, s, right, ArmPose::Empty, Some(m.ai.aggressive), holding);
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.zombie = Some(m.ai.aggressive);
h.holding = m.extra.main_hand.is_some();
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
humanoid(p, s, &h);
if m.kind.anim == Anim::ZombifiedPiglin {
super::piglin::ears(p, s);
}
}
Anim::Skeleton | Anim::Humanoid { zombie_arms: false } => {
let bow = m.extra.main_hand.as_deref() == Some("minecraft:bow");
let player = matches!(m.kind.anim, Anim::Humanoid { .. });
let right = if bow && m.ai.aggressive {
ArmPose::Bow
} else if m.extra.main_hand.is_some() {
} else if player && m.extra.main_hand.is_some() {
ArmPose::Item
} else {
ArmPose::Empty
};
humanoid(
p,
s,
right,
ArmPose::Empty,
None,
m.extra.main_hand.is_some(),
);
if m.extra.passenger {
// HumanoidModel.setupAnim: riding.
p.get("right_arm")[3] -= PI / 5.0;
p.get("left_arm")[3] -= PI / 5.0;
for (leg, side) in [("right_leg", 1.0), ("left_leg", -1.0)] {
p.xrot(leg, -1.413_716_7);
p.yrot(leg, side * PI / 10.0);
p.zrot(leg, side * 0.078_539_82);
}
}
if m.extra.crouching {
p.xrot("body", 0.5);
p.get("right_arm")[3] += 0.4;
p.get("left_arm")[3] += 0.4;
p.get("right_leg")[2] += 4.0;
p.get("left_leg")[2] += 4.0;
p.get("head")[1] += 4.2;
p.get("body")[1] += 3.2;
p.get("left_arm")[1] += 3.2;
p.get("right_arm")[1] += 3.2;
}
let mut h = Hum::new(right, ArmPose::Empty);
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
humanoid(p, s, &h);
if m.ai.aggressive && !bow {
// SkeletonModel melee pose.
let sw = s.swing;
let s2 = (sw * PI).sin();
let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).sin();
let s2 = (sw * PI).msin();
let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", -(0.1 - s2 * 0.6));
@@ -483,37 +569,37 @@ pub fn setup(
// DonkeyModel: the chests show once fitted.
if !m.extra.chested {
for part in ["left_chest", "right_chest"] {
if p.has(part) {
let v = p.get(part);
v[6] = 0.0;
v[7] = 0.0;
v[8] = 0.0;
}
p.visible(part, false);
}
}
}
Anim::Hoglin => super::piglin::hoglin_anim(m, s, p),
Anim::Blaze => super::nether::blaze_anim(s, p),
Anim::Ghast => super::nether::ghast_anim(s, p),
Anim::Feline if m.species() == super::Species::Cat => super::tame::cat_anim(m, s, p),
Anim::Feline => super::tame::cat_anim(m, s, p),
Anim::Enderman => super::enderman::anim(m, s, p),
Anim::Slime | Anim::MagmaCube => super::cube::anim(m, s, p),
Anim::Creeper => {
head(p, s);
p.xrot("right_hind_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
p.xrot("left_hind_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed);
// CreeperModel binds its fields to the opposite-side parts, so the
// left formulas drive the right parts and the reverse.
p.xrot("left_hind_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed);
p.xrot(
"right_front_leg",
(s.pos * 0.6662 + PI).cos() * 1.4 * s.speed,
"right_hind_leg",
(s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed,
);
p.xrot("left_front_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
p.xrot(
"left_front_leg",
(s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed,
);
p.xrot("right_front_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed);
}
Anim::Spider => {
head(p, s);
let pos = s.pos * 0.6662;
let sp = s.speed;
let swing = |o: f32| -((pos * 2.0 + o).cos() * 0.4) * sp;
let step = |o: f32| ((pos + o).sin() * 0.4).abs() * sp;
let swing = |o: f32| -((pos * 2.0 + o).mcos() * 0.4) * sp;
let step = |o: f32| ((pos + o).msin() * 0.4).abs() * sp;
let legs = [
("hind", 0.0f32, 0.0f32),
("middle_hind", PI, PI),
+16 -15
View File
@@ -12,12 +12,13 @@ use super::{
nav::NavKind,
};
use crate::blocks::Fluid;
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
// Squid animation slots in AnimState.v.
const TENTACLE_MOVEMENT: usize = 0;
const TENTACLE_ANGLE: usize = 1;
pub const TENTACLE_ANGLE: usize = 1;
const X_BODY_ROT: usize = 2;
const Z_BODY_ROT: usize = 3;
const TENTACLE_SPEED: usize = 4;
@@ -229,7 +230,7 @@ fn squid_ai_step(m: &mut Mob) {
if m.fluids.in_water {
if v[TENTACLE_MOVEMENT] < PI {
let scale = v[TENTACLE_MOVEMENT] / PI;
v[TENTACLE_ANGLE] = (scale * scale * PI).sin() * PI * 0.25;
v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25;
if scale > 0.75 {
let mv = m.extra.vector;
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
@@ -250,7 +251,7 @@ fn squid_ai_step(m: &mut Mob) {
v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5;
v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1;
} else {
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].sin().abs() * PI * 0.25;
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25;
let yd = m.velocity.y - m.kind.gravity;
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
let v = &mut m.anim.v;
@@ -339,9 +340,9 @@ impl Goal for SquidRandomMovement {
let angle = m.random.next_float() * PI * 2.0;
let y = -0.1 + m.random.next_float() * 0.2;
m.extra.vector = [
f64::from(angle.cos() * 0.2),
f64::from(angle.mcos() * 0.2),
f64::from(y),
f64::from(angle.sin() * 0.2),
f64::from(angle.msin() * 0.2),
];
}
}
@@ -496,23 +497,23 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot(&format!("tentacle{i}"), angle);
}
}
S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()),
S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).msin()),
// TadpoleModel: a stronger tail swing out of water.
S::Tadpole => {
let a = if m.fluids.in_water { 1.0 } else { 1.5 };
p.yrot("tail", -a * 0.25 * (0.3 * s.age).sin())
p.yrot("tail", -a * 0.25 * (0.3 * s.age).msin())
}
S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()),
S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).msin()),
S::Salmon => {
let (a, k) = if m.fluids.in_water {
(1.0, 1.0)
} else {
(1.3, 1.7)
};
p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).sin());
p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).msin());
}
S::Pufferfish => {
let fin = 0.2 - 0.4 * (s.age * 0.2).sin();
let fin = 0.2 - 0.4 * (s.age * 0.2).msin();
if p.has("right_blue_fin") {
p.zrot("right_blue_fin", -fin);
p.zrot("left_blue_fin", fin);
@@ -526,9 +527,9 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("body", s.y_rot.to_radians());
let moving = m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z > 1.0e-7;
if moving {
p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).cos();
p.xrot("tail", -0.1 * (s.age * 0.3).cos());
p.xrot("tail_fin", -0.2 * (s.age * 0.3).cos());
p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).mcos();
p.xrot("tail", -0.1 * (s.age * 0.3).mcos());
p.xrot("tail_fin", -0.2 * (s.age * 0.3).mcos());
}
}
_ => {}
@@ -565,7 +566,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option<glam::Mat4> {
(1.0, 1.0)
};
let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians())
* glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians());
* glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).msin()).to_radians());
if !m.fluids.in_water {
let off = if m.species() == S::Cod {
glam::Vec3::new(0.1, 0.1, -0.1)
@@ -577,7 +578,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option<glam::Mat4> {
Some(t)
}
S::Pufferfish => Some(
glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0))
glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).mcos() * 0.08, 0.0))
* glam::Mat4::from_rotation_y((180.0 - body).to_radians()),
),
_ => None,
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -8,6 +8,7 @@ use super::{
Tempt, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::collections::HashMap;
@@ -179,7 +180,7 @@ pub fn dash(m: &mut Mob, amount: f32, events: &mut Vec<MobEvent>) {
return;
}
let yaw = m.yaw.to_radians();
let (dx, dz) = (f64::from(-yaw.sin()), f64::from(yaw.cos()));
let (dx, dz) = (f64::from(-yaw.msin()), f64::from(yaw.mcos()));
let speed = m.movement_speed();
let a = f64::from(amount);
m.velocity.x += dx * 22.2222 * a * speed;
+8
View File
@@ -68,6 +68,14 @@ impl MobData {
data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default();
data
}
/// Only the keyframe animation definitions of `mob-data.json`.
pub fn load_animations(root: &Path) -> HashMap<String, Animation> {
fs::read(root.join("mob-data.json"))
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
.map(|v| Self::from_json(&v).animations)
.unwrap_or_default()
}
pub fn entity_has(&self, tag: &str, entity: &str) -> bool {
self.entity_tags
.get(tag)
+24 -11
View File
@@ -9,6 +9,7 @@ use super::{
Tempt, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -24,9 +25,9 @@ pub const COLORS: [&str; 7] = [
pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackdots"];
// AnimState slots.
const EAT: usize = 0;
const STAND: usize = 1;
const MOUTH: usize = 2;
pub const EAT: usize = 0;
pub const STAND: usize = 1;
pub const MOUTH: usize = 2;
/// What a rider asks of its mount this tick.
#[derive(Clone, Copy, Debug, Default)]
@@ -180,7 +181,7 @@ fn boost_factor(m: &mut Mob) -> f32 {
m.extra.counter2 = 0;
return 1.0;
}
1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).sin()
1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).msin()
}
/// `AbstractHorse.MountPanicGoal`: only without a rider.
#[derive(Clone, Debug)]
@@ -381,7 +382,7 @@ pub fn ridden_step(m: &mut Mob) {
let impulse = m.extra.vector[0] as f32 * r.jump;
m.velocity.y = f64::from(impulse);
if forward > 0.0 {
let (s, c) = (m.yaw.to_radians().sin(), m.yaw.to_radians().cos());
let (s, c) = (m.yaw.to_radians().msin(), m.yaw.to_radians().mcos());
m.velocity.x += f64::from(-0.4 * s * r.jump);
m.velocity.z += f64::from(0.4 * c * r.jump);
}
@@ -506,19 +507,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let mut head_x = s.x_rot.to_radians();
let (speed, pos) = (s.speed, s.pos);
if speed > 0.2 {
head_x += (pos * 0.8).cos() * 0.15 * speed;
head_x += (pos * 0.8).mcos() * 0.15 * speed;
}
let eating = m.anim.lerp(EAT, s.partial);
let standing = m.anim.lerp(STAND, s.partial);
let istand = 1.0 - standing;
let feeding = m.anim.lerp(MOUTH, s.partial);
let in_water = if m.fluids.in_water { 0.2 } else { 1.0 };
let leg1 = (in_water * pos * 0.6662 + PI).cos();
let leg1 = (in_water * pos * 0.6662 + PI).mcos();
let leg_x = leg1 * 0.8 * speed;
let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.sin() * 0.05);
let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05);
p.xrot(
"head_parts",
standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.sin() * 0.05) + base,
standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.msin() * 0.05) + base,
);
p.yrot(
"head_parts",
@@ -551,7 +552,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
rf[2] = z;
}
let stand = stand_angle * standing;
let bob = (s.age * 0.6 + PI).cos();
let bob = (s.age * 0.6 + PI).mcos();
let rleg = (stand_x_off + bob) * standing + leg_x * istand;
let lleg = (stand_x_off - bob) * standing - leg_x * istand;
p.xrot("left_hind_leg", stand - leg1 * 0.5 * speed * istand);
@@ -560,9 +561,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("right_front_leg", lleg);
if baby && donkey {
let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t;
// BabyDonkeyModel lerps the right leg from the left leg's new height.
let y = lerp(standing, p.get("left_hind_leg")[1], -0.3);
p.get("left_hind_leg")[1] = y;
p.get("right_hind_leg")[1] = y;
p.get("right_hind_leg")[1] = lerp(standing, y, -0.3);
}
let age = if baby { 0.5 } else { 1.0 };
p.xrot("tail", tail_off + PI / 6.0 + speed * 0.75);
@@ -572,4 +574,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
t[2] += speed * 2.0 * age;
}
p.yrot("tail", 0.0);
if baby && donkey {
// BabyDonkeyModel overrides the state's pitch with -30 degrees and
// sets the head parts again.
let head_x = -30.0f32 * horizon_core::geometry::trig::DEG_TO_RAD;
let base =
(1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05);
p.xrot(
"head_parts",
standing * (PI / 12.0 + head_x) + eating * (PI / 2.0 + s.age.msin() * 0.05) + base,
);
}
}
+11 -10
View File
@@ -12,15 +12,16 @@ use super::{
nav::NavKind,
path::PathType,
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
// Guardian state: `flag` an active beam target (DATA_ID_ATTACK_TARGET),
// `flag2` moving (DATA_ID_MOVING), `counter2` the client attack time.
// AnimState slots: tail animation, its speed, spikes animation.
const TAIL: usize = 0;
pub const TAIL: usize = 0;
const TAIL_SPEED: usize = 1;
const SPIKES: usize = 2;
pub const SPIKES: usize = 2;
const EYE_X: usize = 3;
const EYE_Y: usize = 4;
@@ -166,8 +167,8 @@ pub fn move_control(m: &mut Mob) {
let t = f64::from(m.age as i32 + m.id as i32);
let push = (t * 0.5).sin() * 0.05;
let (cos, sin) = (
f64::from(m.yaw.to_radians().cos()),
f64::from(m.yaw.to_radians().sin()),
f64::from(m.yaw.to_radians().mcos()),
f64::from(m.yaw.to_radians().msin()),
);
let y_push = (t * 0.75).sin() * 0.05;
m.velocity = m.velocity.add_vector(Vec3::new(
@@ -277,7 +278,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 };
let yaw = m.head_yaw.to_radians();
let pitch = m.head_pitch.to_radians();
let view = [-yaw.sin() * pitch.cos(), yaw.cos() * pitch.cos()];
let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()];
let d = [m.position.x - look[0], m.position.z - look[2]];
let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9);
let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32);
@@ -365,7 +366,7 @@ pub fn beam_geometry(
128u32.saturating_sub((cs * 64.0) as u32),
);
let color = 0xFF00_0000 | (b.min(255) << 16) | (g.min(255) << 8) | r.min(255);
let at = |a: f32, radius: f32| (a.cos() * radius, a.sin() * radius);
let at = |a: f32, radius: f32| (a.mcos() * radius, a.msin() * radius);
let quarter = std::f32::consts::FRAC_PI_4;
let (wx, wz) = at(rot + PI, 0.2);
let (ex, ez) = at(rot, 0.2);
@@ -432,7 +433,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
8.0, -8.0, 0.0, 0.0, -8.0, -8.0, 8.0, 8.0, 8.0, -8.0, 0.0, 0.0,
];
for i in 0..12 {
let offset = 1.0 + (s.age * 1.5 + i as f32).cos() * 0.01 - withdrawal;
let offset = 1.0 + (s.age * 1.5 + i as f32).mcos() * 0.01 - withdrawal;
let part = p.get(&format!("spike{i}"));
part[0] = X[i] * offset;
part[1] = 16.0 + Y[i] * offset;
@@ -442,7 +443,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
e[0] = m.anim.v[EYE_X];
e[1] = m.anim.v[EYE_Y];
let tail = m.anim.lerp(TAIL, s.partial);
p.yrot("tail0", tail.sin() * PI * 0.05);
p.yrot("tail1", tail.sin() * PI * 0.1);
p.yrot("tail2", tail.sin() * PI * 0.15);
p.yrot("tail0", tail.msin() * PI * 0.05);
p.yrot("tail1", tail.msin() * PI * 0.1);
p.yrot("tail2", tail.msin() * PI * 0.15);
}
+84 -35
View File
@@ -9,6 +9,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
@@ -20,6 +21,7 @@ fn raider(s: Species) -> bool {
| Species::Vindicator
| Species::Witch
| Species::Evoker
| Species::Illusioner
| Species::Ravager
)
}
@@ -30,6 +32,7 @@ fn targets(m: &mut Mob, villagers_seen: bool) {
Species::Vindicator,
Species::Witch,
Species::Evoker,
Species::Illusioner,
Species::Vex,
Species::Ravager,
];
@@ -95,7 +98,7 @@ enum Spell {
/// `SpellcasterCastingSpellGoal`: stand still facing the target while a
/// spell is cast.
#[derive(Clone, Debug)]
struct CastingSpell;
pub(super) struct CastingSpell;
impl Goal for CastingSpell {
goal_clone!();
fn flags(&self) -> u8 {
@@ -304,8 +307,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) {
for i in 0..5 {
let a = angle + i as f32 * PI * 0.4;
place(
x + f64::from(a.cos()) * 1.5,
z + f64::from(a.sin()) * 1.5,
x + f64::from(a.mcos()) * 1.5,
z + f64::from(a.msin()) * 1.5,
a,
0,
);
@@ -313,8 +316,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) {
for i in 0..8 {
let a = angle + i as f32 * PI * 2.0 / 8.0 + PI * 2.0 / 5.0;
place(
x + f64::from(a.cos()) * 2.5,
z + f64::from(a.sin()) * 2.5,
x + f64::from(a.mcos()) * 2.5,
z + f64::from(a.msin()) * 2.5,
a,
3,
);
@@ -323,8 +326,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) {
for i in 0..16 {
let reach = 1.25 * f64::from(i + 1);
place(
x + f64::from(angle.cos()) * reach,
z + f64::from(angle.sin()) * reach,
x + f64::from(angle.mcos()) * reach,
z + f64::from(angle.msin()) * reach,
angle,
i,
);
@@ -533,8 +536,9 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
pitch,
));
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ArmPose {
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ArmPose {
BowAndArrow,
Spellcasting,
Crossed,
Celebrating,
@@ -542,6 +546,7 @@ enum ArmPose {
Attacking,
CrossbowHold,
CrossbowCharge,
Bow,
}
/// `Pillager` / `Vindicator.getArmPose`.
fn arm_pose(m: &Mob) -> ArmPose {
@@ -557,6 +562,9 @@ fn arm_pose(m: &Mob) -> ArmPose {
ArmPose::Neutral
}
}
Species::Illusioner if m.extra.variant2 != 0 => ArmPose::Spellcasting,
Species::Illusioner if m.ai.aggressive => ArmPose::Bow,
Species::Illusioner => ArmPose::Crossed,
Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting,
Species::Evoker if celebrating(m) => ArmPose::Celebrating,
Species::Evoker => ArmPose::Crossed,
@@ -576,38 +584,62 @@ fn celebrating(m: &Mob) -> bool {
}
/// Whether the held item shows (vindicators only draw their axe when angry).
pub fn shows_item(m: &Mob) -> bool {
m.species() != Species::Vindicator || m.ai.aggressive
match m.species() {
Species::Vindicator => m.ai.aggressive,
Species::Illusioner => m.extra.variant2 != 0 || m.ai.aggressive,
_ => true,
}
}
fn hide(p: &mut Poses, part: &str) {
if p.has(part) {
let v = p.get(part);
v[6] = 0.0;
v[7] = 0.0;
v[8] = 0.0;
}
p.visible(part, false);
}
/// `IllagerModel.setupAnim`.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
anim_pose(m, s, p, arm_pose(m));
}
/// `IllagerModel.setupAnim` for a given arm pose.
pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) {
// IllagerModel hides the hat; the illusioner's renderer shows it.
if m.species() != Species::Illusioner {
hide(p, "hat");
}
let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians());
p.yrot("head", hy);
p.xrot("head", hx);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5);
p.yrot("right_arm", 0.0);
p.zrot("right_arm", 0.0);
p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5);
p.yrot("left_arm", 0.0);
p.zrot("left_arm", 0.0);
p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp * 0.5);
p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp * 0.5);
let pose = arm_pose(m);
if m.extra.passenger {
for arm in ["right_arm", "left_arm"] {
p.xrot(arm, -PI / 5.0);
p.yrot(arm, 0.0);
p.zrot(arm, 0.0);
}
p.xrot("right_leg", -1.413_716_7);
p.yrot("right_leg", PI / 10.0);
p.zrot("right_leg", 0.078_539_82);
p.xrot("left_leg", -1.413_716_7);
p.yrot("left_leg", -PI / 10.0);
p.zrot("left_leg", -0.078_539_82);
} else {
p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5);
p.yrot("right_arm", 0.0);
p.zrot("right_arm", 0.0);
p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5);
p.yrot("left_arm", 0.0);
p.zrot("left_arm", 0.0);
p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp * 0.5);
p.yrot("right_leg", 0.0);
p.zrot("right_leg", 0.0);
p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp * 0.5);
p.yrot("left_leg", 0.0);
p.zrot("left_leg", 0.0);
}
match pose {
ArmPose::Attacking => {
if m.extra.main_hand.is_none() {
// animateZombieArms + bobArms
let swing = s.swing;
let a = (swing * PI).sin();
let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
let a = (swing * PI).msin();
let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", -(0.1 - a * 0.6));
@@ -618,26 +650,36 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
} else {
// swingWeaponDown (right-handed).
let swing = s.swing;
let a2 = (swing * PI).sin();
let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
let a2 = (swing * PI).msin();
let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot(
"right_arm",
-1.884_955_8 + (s.age * 0.09).cos() * 0.15 + (a2 * 2.2 - a * 0.4),
-1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4),
);
p.xrot(
"left_arm",
-0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4),
);
p.xrot("left_arm", (s.age * 0.19).cos() * 0.5);
}
let bob = |p: &mut Poses, part: &str, sign: f32| {
let v = p.get(part);
v[5] += sign * ((s.age * 0.09).cos() * 0.05 + 0.05);
v[3] += sign * (s.age * 0.067).sin() * 0.05;
v[5] += sign * ((s.age * 0.09).mcos() * 0.05 + 0.05);
v[3] += sign * (s.age * 0.067).msin() * 0.05;
};
bob(p, "right_arm", 1.0);
bob(p, "left_arm", -1.0);
}
ArmPose::Bow => {
p.yrot("right_arm", -0.1 + hy);
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -0.942_477_9 + hx);
p.yrot("left_arm", hy - 0.4);
p.zrot("left_arm", PI / 2.0);
}
ArmPose::CrossbowHold => {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
@@ -660,7 +702,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let v = p.get(arm);
v[2] = 0.0;
v[0] = x;
v[3] = (s.age * 0.6662).cos() * 0.25;
v[3] = (s.age * 0.6662).mcos() * 0.25;
v[4] = 0.0;
v[5] = z_rot;
}
@@ -673,11 +715,18 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let v = p.get(arm);
v[2] = 0.0;
v[0] = x;
v[3] = (s.age * 0.6662).cos() * 0.05;
v[3] = (s.age * 0.6662).mcos() * 0.05;
v[4] = 0.0;
v[5] = z_rot;
}
}
ArmPose::BowAndArrow => {
p.yrot("right_arm", -0.1 + hy);
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -0.942_477_9 + hx);
p.yrot("left_arm", hy - 0.4);
p.zrot("left_arm", PI / 2.0);
}
ArmPose::Crossed | ArmPose::Neutral => {}
}
if pose == ArmPose::Crossed {
@@ -0,0 +1,235 @@
//! The illusioner (`Illusioner`): a bow-wielding spellcaster that turns
//! invisible behind four mirror images and blinds its target.
use super::{
Mob, MobEvent, Species, Who,
goals::{
Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Stroll,
goal_clone, reduced,
},
illager::CastingSpell,
undead::BowAttack,
};
use horizon_core::random::RandomSource;
const INVISIBILITY: &str = "minecraft:invisibility";
const BLINDNESS: &str = "minecraft:blindness";
/// `Illusioner.NUM_ILLUSIONS`.
pub const COPIES: usize = 4;
/// `Illusioner.clientSideIllusionTicks` and the two offset sets.
#[derive(Clone, Debug, Default)]
pub struct Illusions {
pub ticks: i32,
pub offsets: [[[f64; 3]; COPIES]; 2],
}
pub const MIRROR: u8 = 5;
pub const BLINDNESS_SPELL: u8 = 4;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, CastingSpell);
g.add(
3,
AvoidEntity::new(Avoid::Species(vec![Species::Creaking]), 8.0, 1.0, 1.2),
);
g.add(4, Spell::new(MIRROR));
g.add(5, Spell::new(BLINDNESS_SPELL));
g.add(6, BowAttack::new(0.5, 20, 15.0));
g.add(8, Stroll::new(0.6));
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
g.add(10, LookAtPlayer::new(8.0));
let mut hurt = HurtByTarget::new().alert();
hurt.ignore = vec![
Species::Pillager,
Species::Vindicator,
Species::Witch,
Species::Evoker,
Species::Illusioner,
Species::Vex,
Species::Ravager,
];
m.ai.targets.add(1, hurt);
m.ai.targets.add(2, NearestTarget::player(true));
m.ai.targets.add(
3,
NearestTarget::species(&[Species::Villager, Species::WanderingTrader], false),
);
m.ai.targets
.add(3, NearestTarget::species(&[Species::IronGolem], false));
}
/// `Illusioner.finalizeSpawn`: a bow in the main hand.
pub fn finalize(m: &mut Mob) {
m.extra.main_hand = Some("minecraft:bow".into());
}
/// `IllusionerMirrorSpellGoal` and `IllusionerBlindnessSpellGoal`.
#[derive(Clone, Debug)]
struct Spell {
spell: u8,
warmup: i32,
next: i64,
last_target: Option<Who>,
}
impl Spell {
fn new(spell: u8) -> Self {
Self {
spell,
warmup: 0,
next: 0,
last_target: None,
}
}
/// (casting time, interval, prepare sound).
fn timing(&self) -> (i32, i64, &'static str) {
if self.spell == MIRROR {
(20, 340, "entity.illusioner.prepare_mirror")
} else {
(20, 180, "entity.illusioner.prepare_blindness")
}
}
}
impl Goal for Spell {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !m.target_info(cx.w).is_some_and(|t| t.alive)
|| m.extra.counter > 0
|| i64::from(m.age) < self.next
{
return false;
}
if self.spell == MIRROR {
!m.has_effect(INVISIBILITY)
} else {
m.ai.target != self.last_target && cx.w.difficulty.effective > 2.0
}
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.target_info(cx.w).is_some_and(|t| t.alive) && self.warmup > 0
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
let (casting, interval, sound) = self.timing();
self.warmup = reduced(20);
m.extra.counter = casting;
self.next = i64::from(m.age) + interval;
cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0));
m.extra.variant2 = self.spell;
if self.spell == BLINDNESS_SPELL {
self.last_target = m.ai.target;
}
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.warmup -= 1;
if self.warmup != 0 {
return;
}
if self.spell == MIRROR {
m.add_effect(INVISIBILITY, 1200, 0);
} else if m.ai.target == Some(Who::Player) {
cx.events.push(MobEvent::EffectPlayer {
effect: BLINDNESS,
ticks: 400,
amplifier: 0,
});
}
cx.events.push(MobEvent::Sound(
"entity.illusioner.cast_spell",
m.center(),
1.0,
1.0,
));
}
}
/// The client-side half of `Illusioner.aiStep`: new image offsets when
/// hurt and once a minute, with a puff of cloud and a sound.
pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
if !m.has_effect(INVISIBILITY) {
return;
}
let hurt = m.hurt_time;
let age = m.age;
let mut il = m.extra.illusions.take().unwrap_or_default();
il.ticks = (il.ticks - 1).max(0);
if hurt == 1 || age.is_multiple_of(1200) {
il.ticks = 3;
for i in 0..COPIES {
il.offsets[0][i] = il.offsets[1][i];
let r = &mut m.random;
let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64;
let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
il.offsets[1][i] = [x, y, z];
}
events.push(MobEvent::Particles {
kind: "minecraft:cloud",
at: [m.position.x, m.position.y + 0.9, m.position.z],
count: 16,
});
events.push(MobEvent::Sound(
"entity.illusioner.mirror_move",
m.center(),
1.0,
1.0,
));
} else if hurt == 9 {
il.ticks = 3;
for i in 0..COPIES {
il.offsets[0][i] = il.offsets[1][i];
il.offsets[1][i] = [0.0; 3];
}
}
m.extra.illusions = Some(il);
}
/// `Illusioner.getIllusionOffsets`.
pub fn offsets(m: &Mob, partial: f32) -> [[f64; 3]; COPIES] {
let Some(il) = &m.extra.illusions else {
return [[0.0; 3]; COPIES];
};
if il.ticks <= 0 {
return il.offsets[1];
}
let scale = (f64::from(il.ticks as f32 - partial) / 3.0).powf(0.25);
let mut out = [[0.0; 3]; COPIES];
for (i, o) in out.iter_mut().enumerate() {
for k in 0..3 {
o[k] = il.offsets[1][i][k] * (1.0 - scale) + il.offsets[0][i][k] * scale;
}
}
out
}
/// The wobble `IllusionerRenderer.submit` adds to each image.
pub fn wobble(i: usize, age: f32) -> [f64; 3] {
let i = i as f32;
[
f64::from((i + age * 0.5).cos()) * 0.025,
f64::from((i + age * 0.75).cos()) * 0.0125,
f64::from((i + age * 0.7).cos()) * 0.025,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn settled_offsets_are_the_new_set() {
let il = Illusions {
ticks: 0,
offsets: [[[1.0; 3]; COPIES], [[2.0; 3]; COPIES]],
};
let mut v = [[0.0; 3]; COPIES];
v.copy_from_slice(&il.offsets[1]);
assert_eq!(v[0], [2.0; 3]);
}
#[test]
fn wobble_is_small() {
assert!(wobble(1, 10.0).iter().all(|c| c.abs() <= 0.025));
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn is_zombie(s: &Seen) -> bool {
pub fn is_illager(s: &Seen) -> bool {
matches!(
s.species,
Species::Pillager | Species::Vindicator | Species::Evoker
Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner
)
}
pub fn register(m: &mut Mob) {
+12 -11
View File
@@ -10,6 +10,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
@@ -181,25 +182,25 @@ pub fn blaze_anim(s: &State, p: &mut Poses) {
let mut angle = age * PI * -0.1;
for i in 0..4 {
let part = p.get(&format!("part{i}"));
part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).cos();
part[0] = angle.cos() * 9.0;
part[2] = angle.sin() * 9.0;
part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).mcos();
part[0] = angle.mcos() * 9.0;
part[2] = angle.msin() * 9.0;
angle += PI / 2.0;
}
angle = PI / 4.0 + age * PI * 0.03;
for i in 4..8 {
let part = p.get(&format!("part{i}"));
part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).cos();
part[0] = angle.cos() * 7.0;
part[2] = angle.sin() * 7.0;
part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).mcos();
part[0] = angle.mcos() * 7.0;
part[2] = angle.msin() * 7.0;
angle += PI / 2.0;
}
angle = 0.471_238_94 + age * PI * -0.05;
for i in 8..12 {
let part = p.get(&format!("part{i}"));
part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).cos();
part[0] = angle.cos() * 5.0;
part[2] = angle.sin() * 5.0;
part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).mcos();
part[0] = angle.mcos() * 5.0;
part[2] = angle.msin() * 5.0;
angle += PI / 2.0;
}
p.yrot("head", s.y_rot.to_radians());
@@ -365,7 +366,7 @@ impl Goal for GhastShoot {
}
if self.charge == 20 {
let yaw = m.yaw.to_radians();
let view = [-f64::from(yaw.sin()), f64::from(yaw.cos())];
let view = [-f64::from(yaw.msin()), f64::from(yaw.mcos())];
let half = f64::from(m.height()) * 0.5;
let ty = (t.bounds.min_position().y + t.bounds.max_position().y) * 0.5;
let dir = [
@@ -404,7 +405,7 @@ pub fn ghast_anim(s: &State, p: &mut Poses) {
for i in 0..9 {
let name = format!("tentacle{i}");
if p.has(&name) {
p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).sin() + 0.4);
p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).msin() + 0.4);
}
}
}
+10 -9
View File
@@ -5,6 +5,7 @@ use super::{
control::MoveKind,
goals::{Cx, Goal, MOVE, TARGET, goal_clone, reduced},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
/// Phantom state in `Extra`: `flag` swooping, `home` the anchor,
@@ -151,9 +152,9 @@ impl CircleAroundAnchor {
]);
self.angle += self.clockwise * 15.0f32.to_radians();
m.extra.vector = [
f64::from(a[0]) + f64::from(self.distance * self.angle.cos()),
f64::from(a[0]) + f64::from(self.distance * self.angle.mcos()),
f64::from(a[1]) + f64::from(-4.0 + self.height),
f64::from(a[2]) + f64::from(self.distance * self.angle.sin()),
f64::from(a[2]) + f64::from(self.distance * self.angle.msin()),
];
}
}
@@ -319,9 +320,9 @@ pub fn move_control(m: &mut Mob) {
let x_rot = -((-dy).atan2(sd) as f32).to_degrees();
m.head_pitch = x_rot;
let move_angle = (m.yaw + 90.0).to_radians();
let tx = f64::from(speed * move_angle.cos()) * (dx / sd2).abs();
let tz = f64::from(speed * move_angle.sin()) * (dz / sd2).abs();
let ty = f64::from(speed * x_rot.to_radians().sin()) * (dy / sd2).abs();
let tx = f64::from(speed * move_angle.mcos()) * (dx / sd2).abs();
let tz = f64::from(speed * move_angle.msin()) * (dz / sd2).abs();
let ty = f64::from(speed * x_rot.to_radians().msin()) * (dy / sd2).abs();
let v = m.velocity;
m.velocity = Vec3::new(
v.x + (tx - v.x) * 0.2,
@@ -336,20 +337,20 @@ pub fn move_control(m: &mut Mob) {
/// `PhantomModel.setupAnim` (flap time offset by the id).
pub fn anim(m: &Mob, s: &super::anim::State, p: &mut super::anim::Poses) {
let flap = (m.id as f32 * 3.0 + s.age) * 7.448_451_f32.to_radians();
let wing = flap.cos() * 16.0f32.to_radians();
let wing = flap.mcos() * 16.0f32.to_radians();
p.zrot("left_wing_base", wing);
p.zrot("left_wing_tip", wing);
p.zrot("right_wing_base", -wing);
p.zrot("right_wing_tip", -wing);
let tail = -(5.0 + (flap * 2.0).cos() * 5.0f32).to_radians();
let tail = -(5.0 + (flap * 2.0).mcos() * 5.0f32).to_radians();
p.xrot("tail_base", tail);
p.xrot("tail_tip", tail);
}
/// The flap sound when a wingbeat begins (`Phantom.isFlapping`).
pub fn flap_sound(m: &Mob, events: &mut Vec<MobEvent>) {
let t = m.id as f32 * 3.0 + m.age as f32;
let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos();
let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos();
let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos();
let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos();
if a > 0.0 && b <= 0.0 {
events.push(MobEvent::Sound(
"entity.phantom.flap",
+95 -30
View File
@@ -9,6 +9,7 @@ use super::{
NearestTarget, Prey, RandomLookAround, Stroll, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -251,48 +252,112 @@ pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
};
cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0));
}
/// `AbstractPiglinModel.setupAnim`: the ears flap around their default angle
/// (30 degrees for adults, 5 for babies).
pub fn ears(p: &mut Poses, s: &State) {
use horizon_core::geometry::trig::DEG_TO_RAD;
let default = if s.baby { 5.0 } else { 30.0 } * DEG_TO_RAD;
let freq = s.age * 0.1 + s.pos * 0.5;
let amp = 0.08 + s.speed * 0.4;
p.zrot("left_ear", -default - (freq * 1.2).mcos() * amp);
p.zrot("right_ear", default + freq.mcos() * amp);
}
/// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the
/// arm pose (`PiglinModel`).
pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) {
super::anim::humanoid_item(p, s, m.extra.main_hand.is_some());
let default = PI / 6.0;
let freq = s.age * 0.1 + s.pos * 0.5;
let amp = 0.08 + s.speed * 0.4;
p.zrot("left_ear", -default - (freq * 1.2).cos() * amp);
p.zrot("right_ear", default + freq.cos() * amp);
let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians());
if m.extra.using_item > 0 {
// ADMIRING_ITEM: head down at the left hand.
p.xrot("head", 0.5);
p.yrot("head", 0.0);
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
let pose = if m.extra.using_item > 0 {
PiglinPose::AdmiringItem
} else if m.extra.flag {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
let a = (m.extra.using_item as f32).clamp(0.0, 25.0) / 25.0;
p.yrot("left_arm", 0.4 + 0.45 * a);
p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a);
PiglinPose::CrossbowCharge
} else if m.extra.main_hand.as_deref() == Some("minecraft:crossbow") && m.ai.aggressive {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
p.xrot("right_arm", -PI / 2.0 + hx + 0.1);
p.xrot("left_arm", -1.5 + hx);
} else if m.ai.aggressive && m.extra.main_hand.is_some() && s.swing == 0.0 {
p.xrot("right_arm", -1.8);
PiglinPose::CrossbowHold
} else if m.ai.aggressive && m.extra.main_hand.is_some() {
PiglinPose::MeleeWeapon
} else {
PiglinPose::Default
};
piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32);
}
/// `PiglinArmPose`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PiglinPose {
Default,
Dancing,
MeleeWeapon,
CrossbowHold,
CrossbowCharge,
AdmiringItem,
}
/// `PiglinModel.setupAnim` for a piglin facing right-handed.
pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) {
use super::anim::{ArmPose, Hum, humanoid};
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.weapon_swing = pose == PiglinPose::MeleeWeapon;
h.charge = (max_charge, ticks);
humanoid(p, s, &h);
ears(p, s);
let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians());
let rad = |v: f64| v as f32;
let deg = horizon_core::geometry::trig::DEG_TO_RAD;
match pose {
PiglinPose::Dancing => {
let dance = s.age / 60.0;
p.zrot(
"right_ear",
rad(std::f64::consts::PI / 6.0) + deg * (dance * 30.0).msin() * 10.0,
);
p.zrot(
"left_ear",
rad(-std::f64::consts::PI / 6.0) - deg * (dance * 30.0).mcos() * 10.0,
);
p.get("head")[0] += (dance * 10.0).msin();
p.get("head")[1] += (dance * 40.0).msin() + 0.4;
let z = deg * (70.0 + (dance * 40.0).mcos() * 10.0);
p.zrot("right_arm", z);
p.zrot("left_arm", -z);
p.get("right_arm")[1] += (dance * 40.0).msin() * 0.5 - 0.5;
p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5;
p.get("body")[1] += (dance * 40.0).msin() * 0.35;
}
PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8),
PiglinPose::CrossbowHold => {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
p.xrot("right_arm", -PI / 2.0 + hx + 0.1);
p.xrot("left_arm", -1.5 + hx);
}
PiglinPose::CrossbowCharge => {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
p.xrot("left_arm", -0.970_796_35);
let alpha = ticks.clamp(0.0, max_charge) / max_charge;
p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4));
let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35);
p.xrot("left_arm", x);
}
PiglinPose::AdmiringItem => {
p.xrot("head", 0.5);
p.yrot("head", 0.0);
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
}
_ => {}
}
}
/// `HoglinModel.setupAnim`.
pub fn hoglin_anim(m: &Mob, s: &State, p: &mut Poses) {
let (pos, sp) = (s.pos, s.speed);
p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.sin());
p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.sin());
p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.msin());
p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.msin());
p.yrot("head", s.y_rot.to_radians());
let remaining = m.extra.anim_ticks as f32;
let f = 1.0 - (10.0 - 2.0 * remaining).abs() / 10.0;
p.xrot("head", 0.872_664_63 + (-PI / 9.0 - 0.872_664_63) * f);
p.xrot("right_front_leg", pos.cos() * 1.2 * sp);
p.xrot("left_front_leg", (pos + PI).cos() * 1.2 * sp);
p.xrot("right_hind_leg", (pos + PI).cos() * 1.2 * sp);
p.xrot("left_hind_leg", pos.cos() * 1.2 * sp);
if s.baby {
p.get("head")[1] += f * 2.5;
}
p.xrot("right_front_leg", pos.mcos() * 1.2 * sp);
p.xrot("left_front_leg", (pos + PI).mcos() * 1.2 * sp);
p.xrot("right_hind_leg", (pos + PI).mcos() * 1.2 * sp);
p.xrot("left_hind_leg", pos.mcos() * 1.2 * sp);
}
+1
View File
@@ -57,6 +57,7 @@ pub fn is_raider(s: Species) -> bool {
Species::Pillager
| Species::Vindicator
| Species::Evoker
| Species::Illusioner
| Species::Witch
| Species::Ravager
)
+16 -13
View File
@@ -7,6 +7,7 @@ use super::{
goals::{Float, HurtByTarget, LookAtPlayer, MeleeAttack, NearestTarget, Stroll},
path::PathType,
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -25,6 +26,7 @@ pub fn register(m: &mut Mob) {
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Illusioner,
Species::Witch,
Species::Ravager,
];
@@ -134,9 +136,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
events.push(MobEvent::Particles {
kind: "entity_effect",
at: [
m.position.x - width * f64::from(yaw.sin()),
m.position.x - width * f64::from(yaw.msin()),
m.position.y + f64::from(m.height()) - 0.3,
m.position.z + width * f64::from(yaw.cos()),
m.position.z + width * f64::from(yaw.mcos()),
],
count: 0,
});
@@ -180,7 +182,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
let illager = matches!(
s.species,
Species::Pillager | Species::Vindicator | Species::Evoker
Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner
);
if !illager {
events.push(MobEvent::AttackMob {
@@ -225,34 +227,35 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let neck_x_rot = p.get("neck")[3];
let neck = p.get("neck");
neck[2] = -6.5 + head;
neck[1] = -7.0 - head * neck_x_rot.sin();
neck[1] = -7.0 - head * neck_x_rot.msin();
let mouth = if attack > 5.0 {
((-4.0 + attack) / 4.0).sin() * PI * 0.4
((-4.0 + attack) / 4.0).msin() * PI * 0.4
} else {
PI / 20.0 * (PI * attack / 10.0).sin()
PI / 20.0 * (PI * attack / 10.0).msin()
};
p.xrot("mouth", mouth);
} else {
let is_stunned = stunned > 0.0;
let x_rot: f32 = if is_stunned { 0.219_911_49 } else { 0.0 };
let neck = p.get("neck");
let y_offset = -neck[3].msin();
neck[0] = 0.0;
neck[1] = -7.0 + x_rot.sin();
neck[1] = -7.0 - y_offset;
neck[2] = 5.5;
neck[3] = x_rot;
p.xrot("mouth", PI * if is_stunned { 0.05 } else { 0.01 });
if is_stunned {
p.get("neck")[0] = ((stunned / 40.0) * 10.0).sin() * 3.0;
p.get("neck")[0] = ((f64::from(stunned) / 40.0) * 10.0).sin() as f32 * 3.0;
} else if m.extra.anim_ticks > 0 {
let roar = (20.0 - m.extra.anim_ticks as f32 + s.partial) / 20.0;
p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).sin());
p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).msin());
}
}
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
let (pos, leg) = (s.pos, 0.4 * s.speed);
p.xrot("right_hind_leg", (pos * 0.6662).cos() * leg);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * leg);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * leg);
p.xrot("left_front_leg", (pos * 0.6662).cos() * leg);
p.xrot("right_hind_leg", (pos * 0.6662).mcos() * leg);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * leg);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * leg);
p.xrot("left_front_leg", (pos * 0.6662).mcos() * leg);
}
+28 -4
View File
@@ -8,6 +8,7 @@ use super::{
living::wrap,
};
use crate::mesher::Vertex;
use horizon_core::geometry::trig::Mth;
use std::f32::consts::PI;
/// A texture lookup into the shared atlas (name without namespace -> uv rect).
@@ -743,7 +744,7 @@ fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 {
let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha)
/ 28.0)
.clamp(0.0, 1.0);
let wobble = 1.0 + (s * 100.0).sin() * s * 0.01;
let wobble = 1.0 + (s * 100.0).msin() * s * 0.01;
let s4 = s * s * s * s;
let xz = (1.0 + s4 * 0.4) * wobble;
let y = (1.0 + s4 * 0.1) / wobble;
@@ -775,10 +776,10 @@ pub fn draw(
p[3],
))
* glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8]));
if p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 {
if poses.is_hidden(part) || p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 {
return;
}
for poly in &part.polygons {
for poly in part.polygons.iter().filter(|_| !poses.skips(part)) {
for v in poly.vertices {
let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0);
out.push(Vertex {
@@ -822,10 +823,33 @@ pub fn render_with(
extra: &[(&Part, [f32; 4], u32)],
out: &mut Vec<Vertex>,
) {
// The invisibility effect hides the model (a drinking wandering trader).
// The invisibility effect hides the model (a drinking wandering trader);
// an illusioner shows its four mirror images instead.
if super::trader::is_invisible(m) {
if m.species() == Species::Illusioner {
let age = m.age as f32 + alpha;
for (i, off) in super::illusioner::offsets(m, alpha).iter().enumerate() {
let w = super::illusioner::wobble(i, age);
let shifted =
camera - glam::DVec3::new(off[0] + w[0], off[1] + w[1], off[2] + w[2]);
render_visible(m, alpha, shifted, atlas, light, data, extra, out);
}
}
return;
}
render_visible(m, alpha, camera, atlas, light, data, extra, out);
}
#[allow(clippy::too_many_arguments)]
fn render_visible(
m: &Mob,
alpha: f32,
camera: glam::DVec3,
atlas: Atlas,
light: u32,
data: &MobData,
extra: &[(&Part, [f32; 4], u32)],
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn vehicle_attachment(r: &Mob) -> f64 {
| S::Bogged
| S::Parched
| S::WitherSkeleton => 0.7,
S::Pillager | S::Vindicator | S::Evoker => 0.6,
S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => 0.6,
_ => 0.0,
}
}
+5 -4
View File
@@ -11,6 +11,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileWorld, STEPS};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
@@ -20,7 +21,7 @@ use std::f32::consts::PI;
// Shulker state: `variant3` the attach face (3D data value), `counter` the
// raw peek (0..100), `color` the shell colour (16 none). AnimState slot 0
// the current peek amount.
const PEEK: usize = 0;
pub const PEEK: usize = 0;
pub const NO_COLOR: u8 = 16;
pub fn register(m: &mut Mob) {
@@ -335,14 +336,14 @@ pub fn rotations(m: &Mob) -> glam::Mat4 {
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let peek = m.anim.lerp(PEEK, s.partial);
let bs = (0.5 + peek) * PI;
let q = -1.0 + bs.sin();
let q = -1.0 + bs.msin();
let extra = if bs > PI {
(s.age * 0.1).sin() * 0.7
(s.age * 0.1).msin() * 0.7
} else {
0.0
};
let lid = p.get("lid");
lid[1] = 16.0 + bs.sin() * 8.0 + extra;
lid[1] = 16.0 + bs.msin() * 8.0 + extra;
lid[4] = if peek > 0.3 {
q * q * q * q * PI * 0.125
} else {
@@ -397,6 +397,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
m.extra.main_hand = Some("minecraft:golden_axe".into());
m.extra.pick_up_loot = true;
}
S::Illusioner => super::illusioner::finalize(m),
S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()),
S::Villager => {
m.extra.variant = villager_type(biome);
+19
View File
@@ -78,6 +78,7 @@ pub enum Species {
ElderGuardian,
Shulker,
Evoker,
Illusioner,
Vex,
Ravager,
Wither,
@@ -905,6 +906,20 @@ pub const ALL: &[Def] = &[
None,
Baby::None
),
def!(
Illusioner,
"illusioner",
"illusioner#main",
"entity/illager/illusioner",
A::Illager,
[
"entity.illusioner.ambient",
"entity.illusioner.hurt",
"entity.illusioner.death"
],
None,
Baby::None
),
def!(
Allay,
"allay",
@@ -1287,6 +1302,9 @@ impl Def {
Species::Hoglin => &["hoglin_baby"],
Species::Zoglin => &["zoglin_baby"],
Species::Strider => &["strider_baby"],
Species::Camel => &["camel_baby"],
Species::ZombieHorse => &["zombie_horse_baby"],
Species::SkeletonHorse => &["skeleton_horse_baby"],
_ => &[],
};
v.extend_from_slice(extra);
@@ -1435,6 +1453,7 @@ impl Def {
| S::ElderGuardian
| S::Shulker
| S::Evoker
| S::Illusioner
| S::Vex
| S::Ravager
| S::Wither
+73 -37
View File
@@ -10,6 +10,7 @@ use super::{
reduced,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
@@ -54,8 +55,8 @@ pub fn wolf_variant_for(biome: &str, has_tag: &dyn Fn(&str) -> bool) -> u8 {
pub const RED: u8 = 14;
// AnimState slots: begging interest and the shake animation.
const INTEREST: usize = 0;
const SHAKE: usize = 1;
pub const INTEREST: usize = 0;
pub const SHAKE: usize = 1;
pub fn register(m: &mut Mob) {
m.extra.color = RED;
@@ -537,7 +538,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.anim.vo[SHAKE] = 0.0;
}
if m.anim.v[SHAKE] > 0.4 {
let count = (((m.anim.v[SHAKE] - 0.4) * PI).sin() * 7.0) as u32;
let count = (((m.anim.v[SHAKE] - 0.4) * PI).msin() * 7.0) as u32;
if count > 0 {
events.push(MobEvent::Particles {
kind: "splash",
@@ -576,7 +577,7 @@ fn tail_angle(m: &Mob) -> f32 {
/// `WolfRenderState.getBodyRollAngle`.
fn body_roll(shake: f32, offset: f32) -> f32 {
let p = ((shake + offset) / 1.8).clamp(0.0, 1.0);
(p * PI).sin() * (p * PI * 11.0).sin() * 0.15 * PI
(p * PI).msin() * (p * PI * 11.0).msin() * 0.15 * PI
}
/// `WolfModel.setupAnim` with the adult and baby overrides.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
@@ -585,7 +586,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
if angry(m) {
p.yrot("tail", 0.0);
} else {
p.yrot("tail", (pos * 0.6662).cos() * 1.4 * speed);
p.yrot("tail", (pos * 0.6662).mcos() * 1.4 * speed);
}
if m.extra.sitting {
let age = if baby { 0.5 } else { 1.0 };
@@ -615,10 +616,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("upper_body", 0.0);
}
} else {
p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * speed);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed);
p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * speed);
p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * speed);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed);
p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * speed);
}
// shakeOffWater
let shake = m.anim.lerp(SHAKE, s.partial);
@@ -946,26 +947,39 @@ pub fn cat_rotations(m: &Mob, partial: f32) -> glam::Mat4 {
glam::Mat4::from_translation(glam::Vec3::new(0.4 * lie, 0.15 * lie, 0.1 * lie))
* glam::Mat4::from_rotation_z((90.0 * lie).to_radians())
}
/// `Mth.rotLerp`: degrees-wrapping, applied by the feline models to radians.
fn rot_lerp(t: f32, from: f32, to: f32) -> f32 {
let mut d = (to - from) % (PI * 2.0);
if d < -PI {
d += PI * 2.0;
}
if d >= PI {
d -= PI * 2.0;
}
from + t * d
from + t * super::living::wrap(to - from)
}
/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats.
/// `FelineRenderState` values the feline models read.
#[derive(Clone, Copy, Debug, Default)]
pub struct Feline {
pub crouching: bool,
pub sprinting: bool,
pub sitting: bool,
pub lie_down: f32,
pub lie_down_tail: f32,
pub relax_one: f32,
}
/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats and ocelots.
pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
let baby = m.is_baby();
let age = if baby { 0.5 } else { 1.0 };
let wanted = m.ai.mov.has_wanted();
let speed_mod = m.ai.mov.speed_modifier;
// Cat.customServerAiStep: crouch while stalking, sprint while dashing.
let crouching = wanted && (speed_mod - 0.6).abs() < 1e-6;
let sprinting = wanted && (speed_mod - 1.33).abs() < 1e-6;
let sitting = cat_sitting(m);
let st = Feline {
crouching: wanted && (speed_mod - 0.6).abs() < 1e-6,
sprinting: wanted && (speed_mod - 1.33).abs() < 1e-6,
sitting: cat_sitting(m),
lie_down: m.anim.lerp(LIE, s.partial),
lie_down_tail: m.anim.lerp(LIE_TAIL, s.partial),
relax_one: m.anim.lerp(RELAX, s.partial),
};
feline(p, s, &st);
}
pub fn feline(p: &mut Poses, s: &State, st: &Feline) {
let baby = s.baby;
let age = if baby { 0.5 } else { 1.0 };
let (crouching, sprinting, sitting) = (st.crouching, st.sprinting, st.sitting);
let add = |p: &mut Poses, part: &str, x: f32, y: f32, z: f32| {
let v = p.get(part);
v[0] += x;
@@ -994,18 +1008,18 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("body", PI / 2.0);
}
if sprinting {
p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).cos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).cos() * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * sp);
p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.cos() * sp);
p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).mcos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).mcos() * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * sp);
p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.mcos() * sp);
} else {
p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + PI).cos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI).cos() * sp);
p.xrot("right_front_leg", (pos * 0.6662).cos() * sp);
p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + PI).mcos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI).mcos() * sp);
p.xrot("right_front_leg", (pos * 0.6662).mcos() * sp);
let swing = if crouching { 0.471_238_94 } else { PI / 4.0 };
p.xrot("tail2", 1.727_876_1 + swing * pos.cos() * sp);
p.xrot("tail2", 1.727_876_1 + swing * pos.mcos() * sp);
}
} else if baby {
let x = p.get("body")[3] - 0.436_332_32;
@@ -1034,9 +1048,31 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("right_hind_leg", -PI / 2.0);
add(p, "right_hind_leg", 0.0, 3.0 * age, -4.0 * age);
}
let lie = m.anim.lerp(LIE, s.partial);
let lie_tail = m.anim.lerp(LIE_TAIL, s.partial);
if lie > 0.0 && !baby {
let lie = st.lie_down;
let lie_tail = st.lie_down_tail;
if lie > 0.0 && baby {
add(p, "body", 1.0, 0.0, 0.0);
let hx = p.get("head")[3];
p.xrot("head", rot_lerp(lie, hx, PI / 18.0));
let hz = p.get("head")[5];
p.zrot("head", rot_lerp(lie, hz, -PI * 5.0 / 12.0));
add(p, "head", 1.5, 0.75, -0.5);
p.xrot("right_front_leg", -PI / 4.0);
add(p, "right_front_leg", 3.5, -0.5, 0.0);
p.xrot("left_front_leg", -PI / 2.0);
add(p, "left_front_leg", 1.5, -1.0, -2.0);
p.xrot("right_hind_leg", PI * 2.0 / 9.0);
p.yrot("right_hind_leg", PI / 9.0);
p.zrot("right_hind_leg", -PI / 9.0);
add(p, "right_hind_leg", 2.5, -0.25, 0.5);
add(p, "left_hind_leg", 1.5, 0.0, -1.0);
let t = p.get("tail1");
let (tx, ty, tz) = (t[3], t[4], t[5]);
p.xrot("tail1", tx + rot_lerp(lie_tail, tx, -PI / 6.0));
p.yrot("tail1", ty + rot_lerp(lie_tail, ty, 0.0));
p.zrot("tail1", tz + rot_lerp(lie_tail, tz, -PI / 18.0));
add(p, "tail1", 1.0, 0.5, -0.25);
} else if lie > 0.0 {
let (hz, hy) = (p.get("head")[5], p.get("head")[4]);
p.zrot("head", rot_lerp(lie, hz, -1.270_796_3));
p.yrot("head", rot_lerp(lie, hy, 1.270_796_3));
@@ -1052,7 +1088,7 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("tail1", rot_lerp(lie_tail, t1, 0.8));
p.xrot("tail2", rot_lerp(lie_tail, t2, -0.4));
}
let relax = m.anim.lerp(RELAX, s.partial);
let relax = st.relax_one;
if relax > 0.0 {
let hx = p.get("head")[3];
p.xrot("head", rot_lerp(relax, hx, -0.581_776_44));
+1
View File
@@ -44,6 +44,7 @@ pub fn register(m: &mut Mob) {
for (species, distance) in [
(Species::Zombie, 8.0),
(Species::Evoker, 12.0),
(Species::Illusioner, 12.0),
(Species::Vindicator, 8.0),
(Species::Vex, 8.0),
(Species::Pillager, 15.0),
+27 -6
View File
@@ -9,6 +9,7 @@ use super::{
Cx, Float, Goal, HurtByTarget, LookAtPlayer, MOVE, NearestTarget, goal_clone, reduced,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
@@ -32,6 +33,7 @@ pub fn register(m: &mut Mob) {
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Illusioner,
Species::Witch,
Species::Vex,
];
@@ -224,19 +226,38 @@ pub fn ai_step(m: &mut Mob, w: &super::MobWorld) {
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", s.y_rot.to_radians());
p.xrot("head", s.x_rot.to_radians());
let bob = (s.age * 5.5).to_radians().cos() * 0.1;
let bob = (s.age * 5.5 * horizon_core::geometry::trig::DEG_TO_RAD).mcos() * 0.1;
p.zrot("right_arm", PI / 5.0 + bob);
p.zrot("left_arm", -(PI / 5.0 + bob));
if m.extra.flag {
p.xrot("body", 0.0);
// Holding the sword in the right hand.
p.xrot("right_arm", PI * 7.0 / 6.0);
p.yrot("right_arm", PI / 12.0);
p.zrot("right_arm", -0.471_238_88 - bob);
// setArmsCharging
let (right, left) = (m.extra.main_hand.is_some(), m.extra.off_hand.is_some());
if !right && !left {
p.xrot("right_arm", -1.221_730_5);
p.yrot("right_arm", PI / 12.0);
p.zrot("right_arm", -0.471_238_88 - bob);
p.xrot("left_arm", -1.221_730_5);
p.yrot("left_arm", -PI / 12.0);
p.zrot("left_arm", 0.471_238_88 + bob);
} else {
let sword = (std::f64::consts::PI * 7.0 / 6.0) as f32;
if right {
p.xrot("right_arm", sword);
p.yrot("right_arm", PI / 12.0);
p.zrot("right_arm", -0.471_238_88 - bob);
}
if left {
p.xrot("left_arm", sword);
p.yrot("left_arm", -PI / 12.0);
p.zrot("left_arm", 0.471_238_88 + bob);
}
}
} else {
p.xrot("body", PI / 20.0);
}
let wing = 1.099_557_4 + (s.age * 45.836_624).to_radians().cos() * 16.2_f32.to_radians();
let deg = horizon_core::geometry::trig::DEG_TO_RAD;
let wing = 1.099_557_4 + (s.age * 45.836_624 * deg).mcos() * deg * 16.2;
p.yrot("left_wing", wing);
p.yrot("right_wing", -wing);
p.xrot("left_wing", 0.471_238_88);
+6 -4
View File
@@ -13,6 +13,7 @@ use super::{
},
};
use crate::items::ItemStack;
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::{collections::HashMap, f32::consts::PI};
@@ -63,6 +64,7 @@ pub fn register(m: &mut Mob) {
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Illusioner,
Species::Ravager,
Species::Zoglin,
];
@@ -603,16 +605,16 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", if awake { s.y_rot.to_radians() } else { 0.0 });
p.xrot("head", if awake { s.x_rot.to_radians() } else { 0.0 });
if m.extra.ints[0] > 0 {
p.zrot("head", 0.3 * (0.45 * s.age).sin());
p.zrot("head", 0.3 * (0.45 * s.age).msin());
p.xrot("head", 0.4);
} else {
p.zrot("head", 0.0);
}
let leg = (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5;
let leg = (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5;
p.xrot("right_leg", leg);
p.xrot(
"left_leg",
(s.pos * 0.6662 + PI).cos() * 1.4 * s.speed * 0.5,
(s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed * 0.5,
);
p.yrot("right_leg", 0.0);
p.yrot("left_leg", 0.0);
@@ -1217,7 +1219,7 @@ fn hostile_range(s: Species) -> f64 {
| Species::Vex
| Species::Zombie
| Species::ZombieVillager => 8.0,
Species::Evoker | Species::Ravager => 12.0,
Species::Evoker | Species::Illusioner | Species::Ravager => 12.0,
Species::Pillager => 15.0,
Species::Vindicator | Species::Zoglin => 10.0,
_ => 0.0,
+6 -10
View File
@@ -9,6 +9,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
pub fn register(m: &mut Mob) {
@@ -258,20 +259,15 @@ pub fn ai_step(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", s.y_rot.to_radians());
p.xrot("head", s.x_rot.to_radians());
p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5);
p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5);
p.xrot(
"left_leg",
(s.pos * 0.6662 + std::f32::consts::PI).cos() * 1.4 * s.speed * 0.5,
(s.pos * 0.6662 + std::f32::consts::PI).mcos() * 1.4 * s.speed * 0.5,
);
let speed = 0.01 * (m.id % 10) as f32;
p.xrot(
"nose",
(s.age * speed).sin() * 4.5 * std::f32::consts::PI / 180.0,
);
p.zrot(
"nose",
(s.age * speed).cos() * 2.5 * std::f32::consts::PI / 180.0,
);
let deg = horizon_core::geometry::trig::DEG_TO_RAD;
p.xrot("nose", (s.age * speed).msin() * 4.5 * deg);
p.zrot("nose", (s.age * speed).mcos() * 2.5 * deg);
if m.extra.main_hand.is_some() {
let n = p.get("nose");
n[0] = 0.0;
+6 -5
View File
@@ -13,6 +13,7 @@ use super::{
nav::NavKind,
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
// Wither state: `counter` the invulnerable ticks, `counter2` the block
@@ -102,9 +103,9 @@ fn head_pos(m: &Mob, i: usize) -> [f64; 3] {
}
let a = (m.body_yaw + 180.0 * (i as f32 - 1.0)).to_radians();
[
m.position.x + f64::from(a.cos()) * 1.3,
m.position.x + f64::from(a.mcos()) * 1.3,
m.position.y + 2.2,
m.position.z + f64::from(a.sin()) * 1.3,
m.position.z + f64::from(a.msin()) * 1.3,
]
}
/// `performRangedAttack`: a skull from a head toward a point.
@@ -348,13 +349,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot(head, (y - body).to_radians());
p.xrot(head, x.to_radians());
}
let anim = (s.age * 0.1).cos();
let anim = (s.age * 0.1).mcos();
let rib = (0.065 + 0.05 * anim) * std::f32::consts::PI;
p.xrot("ribcage", rib);
let tail = p.get("tail");
tail[0] = -2.0;
tail[1] = 6.9 + rib.cos() * 10.0;
tail[2] = -0.5 + rib.sin() * 10.0;
tail[1] = 6.9 + rib.mcos() * 10.0;
tail[2] = -0.5 + rib.msin() * 10.0;
p.xrot("tail", (0.265 + 0.1 * anim) * std::f32::consts::PI);
p.yrot("center_head", s.y_rot.to_radians());
p.xrot("center_head", s.x_rot.to_radians());
+314
View File
@@ -0,0 +1,314 @@
//! Mouse look and scrolling of 26.3: `MouseHandler` (accumulated movement,
//! sensitivity curve, cinematic smoothing, inversion), `SmoothDouble`,
//! `ScrollWheelHandler` and `Entity.turn`.
/// `SmoothDouble`.
#[derive(Clone, Debug, Default)]
pub struct SmoothDouble {
target_value: f64,
remaining_value: f64,
last_amount: f64,
}
impl SmoothDouble {
pub fn get_new_delta_value(&mut self, target_delta: f64, time: f64) -> f64 {
self.target_value += target_delta;
let mut delta = self.target_value - self.remaining_value;
let new_last_amount = self.last_amount + 0.5 * (delta - self.last_amount);
let delta_sign = java_signum(delta);
if delta_sign * delta > delta_sign * self.last_amount {
delta = new_last_amount;
}
self.last_amount = new_last_amount;
self.remaining_value += delta * time;
delta * time
}
pub fn reset(&mut self) {
*self = Self::default();
}
}
/// `Math.signum(double)`.
pub fn java_signum(v: f64) -> f64 {
if v == 0.0 || v.is_nan() {
v
} else {
v.signum()
}
}
/// `ScrollWheelHandler`.
#[derive(Clone, Debug, Default)]
pub struct ScrollWheelHandler {
accumulated_x: f64,
accumulated_y: f64,
}
impl ScrollWheelHandler {
/// `onMouseScroll`: whole wheel steps `(x, y)` once enough has accumulated.
pub fn on_mouse_scroll(&mut self, x: f64, y: f64) -> (i32, i32) {
if self.accumulated_x != 0.0 && java_signum(x) != java_signum(self.accumulated_x) {
self.accumulated_x = 0.0;
}
if self.accumulated_y != 0.0 && java_signum(y) != java_signum(self.accumulated_y) {
self.accumulated_y = 0.0;
}
self.accumulated_x += x;
self.accumulated_y += y;
// Java's double-to-int cast saturates and maps NaN to zero, like Rust's.
let wheel_x = self.accumulated_x as i32;
let wheel_y = self.accumulated_y as i32;
if wheel_x == 0 && wheel_y == 0 {
return (0, 0);
}
self.accumulated_x -= f64::from(wheel_x);
self.accumulated_y -= f64::from(wheel_y);
(wheel_x, wheel_y)
}
/// `getNextScrollWheelSelection`.
pub fn next_selection(wheel: f64, current_selected: i32, limit: i32) -> i32 {
let step = java_signum(wheel) as i32;
let mut current = (current_selected - step).max(-1);
while current < 0 {
current += limit;
}
while current >= limit {
current -= limit;
}
current
}
}
/// Entity rotation as `Entity.turn` keeps it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rotation {
pub x_rot: f32,
pub y_rot: f32,
pub x_rot_o: f32,
pub y_rot_o: f32,
}
impl Rotation {
fn set_x_rot(&mut self, x_rot: f32) {
if x_rot.is_finite() {
self.x_rot = (x_rot % 360.0).clamp(-90.0, 90.0);
}
}
fn set_y_rot(&mut self, y_rot: f32) {
if y_rot.is_finite() {
self.y_rot = y_rot;
}
}
/// `Entity.turn(xo, yo)`: mouse deltas in, 0.15 degrees per unit, pitch clamped.
pub fn turn(&mut self, xo: f64, yo: f64) {
let x_delta = (yo as f32) * 0.15;
let y_delta = (xo as f32) * 0.15;
self.set_x_rot(self.x_rot + x_delta);
self.set_y_rot(self.y_rot + y_delta);
self.set_x_rot(mth_clamp(self.x_rot, -90.0, 90.0));
self.x_rot_o += x_delta;
self.y_rot_o += y_delta;
self.x_rot_o = mth_clamp(self.x_rot_o, -90.0, 90.0);
}
}
/// `Mth.clamp(float, float, float)`.
pub fn mth_clamp(value: f32, min: f32, max: f32) -> f32 {
if value < min {
min
} else if value.is_nan() || max.is_nan() {
f32::NAN
} else {
value.min(max)
}
}
/// The options `turnPlayer` reads.
#[derive(Clone, Copy, Debug)]
pub struct LookOptions {
pub sensitivity: f64,
pub smooth_camera: bool,
/// First-person camera and the player is scoping (spyglass).
pub scoping: bool,
pub invert_x: bool,
pub invert_y: bool,
}
/// The input state of `MouseHandler` that drives the camera and the hotbar.
#[derive(Clone, Debug)]
pub struct MouseLook {
xpos: f64,
ypos: f64,
ignore_first_move: bool,
smooth_turn_x: SmoothDouble,
smooth_turn_y: SmoothDouble,
accumulated_dx: f64,
accumulated_dy: f64,
pub scroll: ScrollWheelHandler,
last_handle_movement_time: f64,
}
impl Default for MouseLook {
fn default() -> Self {
Self {
xpos: 0.0,
ypos: 0.0,
ignore_first_move: true,
smooth_turn_x: SmoothDouble::default(),
smooth_turn_y: SmoothDouble::default(),
accumulated_dx: 0.0,
accumulated_dy: 0.0,
scroll: ScrollWheelHandler::default(),
// Double.MIN_VALUE
last_handle_movement_time: 4.9e-324,
}
}
}
impl MouseLook {
/// `setIgnoreFirstMove`.
pub fn set_ignore_first_move(&mut self) {
self.ignore_first_move = true;
}
/// `onMove`: relative motion counts while the pointer is grabbed, absolute
/// motion otherwise.
pub fn on_move(
&mut self,
xpos: f64,
ypos: f64,
xrel: f64,
yrel: f64,
window_active: bool,
grabbed: bool,
) {
if self.ignore_first_move {
self.xpos = xpos;
self.ypos = ypos;
self.ignore_first_move = false;
} else {
if window_active {
if grabbed {
self.accumulated_dx += xrel;
self.accumulated_dy += yrel;
} else {
self.accumulated_dx += xpos - self.xpos;
self.accumulated_dy += ypos - self.ypos;
}
}
self.xpos = xpos;
self.ypos = ypos;
}
}
/// Movement accumulated since the last frame (for screens' mouse-moved events).
pub fn accumulated(&self) -> (f64, f64) {
(self.accumulated_dx, self.accumulated_dy)
}
/// `handleAccumulatedMovement` for a frame at `time` seconds: the
/// `(xo, yo)` passed to `Entity.turn` when the pointer is grabbed and the
/// window is active. The accumulators are cleared either way.
pub fn handle_accumulated_movement(
&mut self,
time: f64,
window_active: bool,
grabbed_with_player: bool,
look: LookOptions,
) -> Option<(f64, f64)> {
let mousea = time - self.last_handle_movement_time;
self.last_handle_movement_time = time;
let turn = (window_active && grabbed_with_player).then(|| self.turn_player(mousea, look));
self.accumulated_dx = 0.0;
self.accumulated_dy = 0.0;
turn
}
fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) {
let ss = look.sensitivity * f64::from(0.6f32) + f64::from(0.2f32);
let sensitivity_mod = ss * ss * ss;
let sens = sensitivity_mod * 8.0;
let (xo, yo) = if look.smooth_camera {
(
self.smooth_turn_x
.get_new_delta_value(self.accumulated_dx * sens, mousea * sens),
self.smooth_turn_y
.get_new_delta_value(self.accumulated_dy * sens, mousea * sens),
)
} else if look.scoping {
self.smooth_turn_x.reset();
self.smooth_turn_y.reset();
(
self.accumulated_dx * sensitivity_mod,
self.accumulated_dy * sensitivity_mod,
)
} else {
self.smooth_turn_x.reset();
self.smooth_turn_y.reset();
(self.accumulated_dx * sens, self.accumulated_dy * sens)
};
(
if look.invert_x { -xo } else { xo },
if look.invert_y { -yo } else { yo },
)
}
/// `onScroll` for the in-game case (no screen, player present): the wheel
/// value `wheel` the hotbar or spectator speed reacts to, and the raw
/// wheel steps. `None` when no whole step has accumulated.
pub fn on_scroll(
&mut self,
xoffset: f64,
yoffset: f64,
discrete: bool,
wheel_sensitivity: f64,
) -> Option<(i32, (i32, i32))> {
let scale = |v: f64| (if discrete { java_signum(v) } else { v }) * wheel_sensitivity;
let (x, y) = self.scroll.on_mouse_scroll(scale(xoffset), scale(yoffset));
if x == 0 && y == 0 {
return None;
}
let wheel = if y == 0 { -x } else { y };
Some((wheel, (x, y)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_sensitivity_turns_point_fifteen_degrees_per_count_at_one() {
let mut look = MouseLook::default();
look.on_move(0.0, 0.0, 0.0, 0.0, true, true);
look.on_move(1.0, 0.0, 1.0, 0.0, true, true);
let (xo, _) = look
.handle_accumulated_movement(
1.0,
true,
true,
LookOptions {
sensitivity: 0.5,
smooth_camera: false,
scoping: false,
invert_x: false,
invert_y: false,
},
)
.unwrap();
let mut rot = Rotation {
x_rot: 0.0,
y_rot: 0.0,
x_rot_o: 0.0,
y_rot_o: 0.0,
};
rot.turn(xo, 0.0);
assert!((rot.y_rot - 0.15 * 1.0).abs() < 1e-6, "{}", rot.y_rot);
}
#[test]
fn scroll_accumulates_fractions() {
let mut look = MouseLook::default();
assert_eq!(look.on_scroll(0.0, 0.4, false, 1.0), None);
assert_eq!(look.on_scroll(0.0, 0.7, false, 1.0), Some((1, (0, 1))));
}
}
+69 -12
View File
@@ -3,6 +3,7 @@
//! Disconnected screen. Entries are pinged in the background like
//! ServerStatusPinger to show the MOTD, player count and latency.
use crate::hud::{HudAtlas, HudBatch, rgba};
use crate::lan::discovery::Scanner;
use horizon_protocol::servers::{self, ServerEntry};
use std::{
collections::HashMap,
@@ -31,6 +32,8 @@ pub enum Screen {
servers: Vec<ServerEntry>,
selected: Option<usize>,
pings: Pings,
/// Worlds announced on the local network, listed after the servers.
lan: Scanner,
},
/// Add (index None) or edit a server entry.
Edit {
@@ -92,6 +95,18 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) {
}
}
/// The address of list row `index`: the saved servers, then the LAN games.
fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option<String> {
match servers.get(index) {
Some(s) => Some(s.ip.clone()),
None => lan
.games()
.into_iter()
.nth(index - servers.len())
.map(|g| g.address),
}
}
impl Screen {
pub fn list(saves: &Path) -> Self {
let servers = servers::load(&servers_file(saves));
@@ -101,6 +116,7 @@ impl Screen {
servers,
selected: None,
pings,
lan: Scanner::start(),
}
}
pub fn buttons(&self, w: f32, h: f32) -> Vec<ButtonSpec> {
@@ -256,6 +272,7 @@ impl Screen {
servers,
selected,
pings,
lan,
} => {
centered(batch, "Play Multiplayer", 8.0, u32::MAX);
batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100));
@@ -319,6 +336,42 @@ impl Screen {
);
}
}
for (k, game) in lan.games().iter().enumerate() {
let i = servers.len() + k;
let y = 36.0 + i as f32 * 36.0;
if y + 36.0 > h - 64.0 {
break;
}
let x = w / 2.0 - 152.0;
if *selected == Some(i) {
batch.fill(
atlas,
x - 2.0,
y - 2.0,
306.0,
36.0,
rgba(128, 128, 128, 255),
);
batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255));
}
batch.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false);
batch.text(
atlas,
&game.motd,
x + 35.0,
y + 12.0,
rgba(128, 128, 128, 255),
false,
);
batch.text(
atlas,
&game.address,
x + 35.0,
y + 22.0,
rgba(96, 96, 96, 255),
false,
);
}
if servers.is_empty() {
centered(
batch,
@@ -392,12 +445,15 @@ impl Screen {
match (&mut *self, id) {
(
Self::List {
servers, selected, ..
servers,
selected,
lan,
..
},
Some(40),
) => {
if let Some(s) = selected.and_then(|i| servers.get(i)) {
return Outcome::Connect(s.ip.clone());
if let Some(address) = selected.and_then(|i| entry_address(servers, lan, i)) {
return Outcome::Connect(address);
}
}
(Self::List { .. }, Some(41)) => {
@@ -446,21 +502,22 @@ impl Screen {
(Self::List { .. }, Some(46)) => return Outcome::Back,
(
Self::List {
servers, selected, ..
servers,
selected,
lan,
..
},
None,
) => {
let index = ((y - 36.0) / 36.0).floor();
if y >= 36.0
&& y < h - 64.0
&& (x - w / 2.0).abs() < 154.0
&& (index as usize) < servers.len()
{
if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 {
let index = index as usize;
if *selected == Some(index) {
return Outcome::Connect(servers[index].ip.clone());
if let Some(address) = entry_address(servers, lan, index) {
if *selected == Some(index) {
return Outcome::Connect(address);
}
*selected = Some(index);
}
*selected = Some(index);
}
}
(
+719
View File
@@ -0,0 +1,719 @@
//! `options.txt` exactly as `Options.load`/`Options.save` handle it in 26.3:
//! the processing order, per-option codecs and validation (`OptionInstance`),
//! plain fields, key mappings, sound volumes and model parts. Typed access for
//! the game lives in `settings`.
use crate::{
java_text::{self, Json},
key_names,
};
use std::sync::LazyLock;
/// A stored option value.
#[derive(Clone, Debug, PartialEq)]
pub enum V {
Bool(bool),
Int(i32),
Double(f64),
Str(String),
List(Vec<String>),
}
/// How an `OptionInstance` decodes, validates and encodes its value.
#[derive(Clone, Copy, Debug)]
pub enum Spec {
/// `Codec.BOOL`.
Bool,
/// `IntRange(min, max)`: codec `intRange(min, max + 1)`, validated to `max`.
Int(i32, i32),
/// `ClampingLazyMaxIntRange(min, ..)` while the game is not running.
LazyInt(i32),
/// `IntRange(imin, imax).xmap(i / k, (int)(v * k))` with `doubleRange(lo, hi)`.
Scaled(i32, i32, f64, f64, f64),
/// The frame rate limit: `IntRange(1, 26).xmap(i * 10, v / 10)`, codec 10..=260.
FrameLimit,
/// Field of view degrees stored as `(fov - 70) / 40`.
Fov,
/// `IntRange(-200, 100).xmap(10^(i/100), floor(log10(v) * 100))`.
WheelSensitivity,
/// `UnitDouble`.
Unit,
/// `UnitDouble.xmap(square, sqrt)` with an explicit `doubleRange(0, 1)` codec.
UnitSquare,
/// `UnitDouble.xmap(square, sqrt)` using the value set's own codec.
UnitSquareImplicit,
/// String-represented enum.
Named(&'static [&'static str]),
/// Enum stored as its id, wrapping out-of-range ids.
Id(i32),
/// `CloudStatus` with the boolean alternative.
Clouds,
/// Any string (`LazyEnum` while the game is not running).
AnyStr,
}
#[derive(Clone, Copy, Debug)]
enum Kind {
Option(Spec),
PlainBool,
PlainInt,
PlainStr,
List,
Tutorial,
Key,
}
struct Def {
key: String,
kind: Kind,
default: V,
}
const TUTORIAL_STEPS: [&str; 6] = [
"movement",
"find_tree",
"punch_tree",
"open_inventory",
"craft_planks",
"none",
];
const MODEL_PARTS: [&str; 7] = [
"cape",
"jacket",
"left_sleeve",
"right_sleeve",
"left_pants_leg",
"right_pants_leg",
"hat",
];
const GRAPHICS_BACKEND: &[&str] = &["default", "opengl", "vulkan"];
const GRAPHICS_PRESET: &[&str] = &["fast", "fancy", "fabulous", "custom"];
const INACTIVITY: &[&str] = &["minimized", "afk"];
const CLOUDS: &[&str] = &["false", "fast", "true"];
const MAIN_HAND: &[&str] = &["left", "right"];
const PRESENCE: &[&str] = &["none", "limited", "all"];
const MUSIC_TOAST: &[&str] = &["never", "pause", "pause_and_toast"];
const MUSIC_FREQUENCY: &[&str] = &["DEFAULT", "FREQUENT", "CONSTANT"];
fn def(key: &str, kind: Kind, default: V) -> Def {
Def {
key: key.to_owned(),
kind,
default,
}
}
/// The processing order of `Options.processOptions`.
static TABLE: LazyLock<Vec<Def>> = LazyLock::new(|| {
use Kind::{List, Option as O, PlainBool as PB, PlainInt as PI, PlainStr as PS, Tutorial};
use Spec::{
AnyStr, Bool, Clouds, Fov, FrameLimit, Id, Int, LazyInt, Named, Scaled, Unit, UnitSquare,
UnitSquareImplicit, WheelSensitivity,
};
let b = |key: &str, d: bool| def(key, O(Bool), V::Bool(d));
let i = |key: &str, lo, hi, d: i32| def(key, O(Int(lo, hi)), V::Int(d));
let u = |key: &str, d: f64| def(key, O(Unit), V::Double(d));
let n =
|key: &str, names: &'static [&'static str], d: i32| def(key, O(Named(names)), V::Int(d));
let id = |key: &str, count: i32, d: i32| def(key, O(Id(count)), V::Int(d));
let pb = |key: &str, d: bool| def(key, PB, V::Bool(d));
let mut t = vec![
b("ao", true),
i("biomeBlendRadius", 0, 7, 2),
def(
"chunkSectionFadeInTime",
O(Scaled(0, 40, 20.0, 0.0, 2.0)),
V::Double(0.75),
),
b("cutoutLeaves", true),
b("enableVsync", true),
def(
"entityDistanceScaling",
O(Scaled(2, 20, 4.0, 0.5, 5.0)),
V::Double(1.0),
),
b("entityShadows", true),
b("forceUnicodeFont", false),
b("japaneseGlyphVariants", false),
def("fov", O(Fov), V::Int(70)),
def("fovEffectScale", O(UnitSquare), V::Double(1.0)),
def("darknessEffectScale", O(UnitSquareImplicit), V::Double(1.0)),
u("glintSpeed", 0.5),
u("glintStrength", 0.75),
n("preferredGraphicsBackend", GRAPHICS_BACKEND, 0),
n("graphicsPreset", GRAPHICS_PRESET, 1),
id("prioritizeChunkUpdates", 3, 0),
b("fullscreen", false),
b("exclusiveFullscreen", false),
b("macFullscreenMenuVisibility", false),
u("gamma", 0.5),
def("guiScale", O(LazyInt(0)), V::Int(0)),
def("debugGuiScale", O(LazyInt(-1)), V::Int(0)),
i("maxAnisotropyBit", 1, 3, 2),
id("textureFiltering", 3, 0),
def("maxFps", O(FrameLimit), V::Int(120)),
b("improvedTransparency", false),
n("inactivityFpsLimit", INACTIVITY, 1),
i("mipmapLevels", 0, 4, 4),
id("narrator", 4, 0),
id("particles", 3, 0),
b("reducedDebugInfo", false),
def("renderClouds", O(Clouds), V::Int(2)),
i("cloudRange", 2, 128, 128),
i("renderDistance", 2, 32, 12),
i("simulationDistance", 5, 32, 12),
u("screenEffectScale", 1.0),
def("soundDevice", O(AnyStr), V::Str(String::new())),
b("vignette", true),
i("weatherRadius", 3, 10, 10),
b("autoJump", false),
b("rotateWithMinecart", false),
b("operatorItemsTab", false),
b("autoSuggestions", true),
b("chatColors", true),
b("chatLinks", true),
b("chatLinksPrompt", true),
b("discrete_mouse_scroll", false),
b("invertXMouse", false),
b("invertYMouse", false),
b("realmsNotifications", true),
b("showSubtitles", false),
b("directionalAudio", false),
b("bobView", true),
b("toggleCrouch", false),
b("toggleSprint", false),
b("toggleAttack", false),
b("toggleUse", false),
i("sprintWindow", 0, 10, 7),
b("darkMojangStudiosBackground", false),
b("hideLightningFlashes", false),
b("hideSplashTexts", false),
u("mouseSensitivity", 0.5),
u("damageTiltStrength", 1.0),
b("highContrast", false),
b("highContrastBlockOutline", false),
b("narratorHotkey", true),
def("resourcePacks", List, V::List(Vec::new())),
def("incompatibleResourcePacks", List, V::List(Vec::new())),
def("lastServer", PS, V::Str(String::new())),
def("lang", PS, V::Str("en_us".into())),
id("chatVisibility", 3, 0),
u("chatOpacity", 1.0),
u("chatLineSpacing", 0.0),
u("textBackgroundOpacity", 0.5),
b("backgroundForChatOnly", true),
pb("hideServerAddress", false),
pb("advancedItemTooltips", false),
pb("pauseOnLostFocus", true),
def("overrideWidth", PI, V::Int(0)),
def("overrideHeight", PI, V::Int(0)),
u("chatHeightFocused", 1.0),
def(
"chatDelay",
O(Scaled(0, 60, 10.0, 0.0, 6.0)),
V::Double(0.0),
),
u("chatHeightUnfocused", 0.4375),
u("chatScale", 1.0),
u("chatWidth", 1.0),
def(
"notificationDisplayTime",
O(Scaled(5, 100, 10.0, 0.5, 10.0)),
V::Double(1.0),
),
pb("useNativeTransport", true),
n("mainHand", MAIN_HAND, 1),
id("attackIndicator", 3, 1),
def("tutorialStep", Tutorial, V::Int(0)),
def("mouseWheelSensitivity", O(WheelSensitivity), V::Double(1.0)),
b("allowCursorChanges", true),
b("quitShortcuts", true),
b("ctrlClickEmulatesRightClick", false),
def("glDebugVerbosity", PI, V::Int(1)),
pb("skipMultiplayerWarning", false),
b("hideMatchedNames", true),
pb("joinedFirstServer", false),
pb("syncChunkWrites", false),
b("showAutosaveIndicator", true),
b("allowServerListing", true),
b("inGameNotification", false),
n("sharePresence", PRESENCE, 2),
b("onlyShowSecureChat", false),
b("saveChatDrafts", false),
u("panoramaScrollSpeed", 1.0),
b("telemetryOptInExtra", false),
pb("onboardAccessibility", true),
i("menuBackgroundBlurriness", 0, 10, 5),
pb("startedCleanly", true),
n("musicToast", MUSIC_TOAST, 0),
n("musicFrequency", MUSIC_FREQUENCY, 0),
];
for (name, key, _) in crate::keybinds::MAPPINGS {
t.push(def(
&format!("key_{name}"),
Kind::Key,
V::Str((*key).to_owned()),
));
}
for source in crate::settings::SOUND_SOURCES {
t.push(u(&format!("soundCategory_{source}"), 1.0));
}
for part in MODEL_PARTS {
t.push(pb(&format!("modelPart_{part}"), true));
}
t
});
/// Mth.floor for doubles.
fn floor_int(v: f64) -> i32 {
let i = v as i32;
if v < f64::from(i) { i - 1 } else { i }
}
fn number(json: &Json) -> Option<&str> {
match json {
Json::Number(n) => Some(n),
_ => None,
}
}
fn codec_int(json: &Json) -> Option<i32> {
number(json).map(Json::int_value)
}
fn codec_double(json: &Json) -> Option<f64> {
number(json).map(Json::double_value)
}
fn codec_bool(json: &Json) -> Option<bool> {
match json {
Json::Bool(b) => Some(*b),
_ => None,
}
}
fn codec_string(json: &Json) -> Option<&str> {
match json {
Json::String(s) => Some(s),
_ => None,
}
}
fn double_range(v: f64, lo: f64, hi: f64) -> Option<f64> {
// Double.compareTo: -0.0 sorts below 0.0 and NaN above everything.
(v.total_cmp(&lo).is_ge() && v.total_cmp(&hi).is_le() && !v.is_nan()).then_some(v)
}
fn log_mouse(value: i32) -> f64 {
10f64.powf(f64::from(value) / 100.0)
}
fn unit_alt(json: &Json) -> Option<f64> {
codec_double(json)
.and_then(|v| double_range(v, 0.0, 1.0))
.or_else(|| codec_bool(json).map(|b| if b { 1.0 } else { 0.0 }))
}
impl Spec {
/// `codec.parse(JsonOps.INSTANCE, element)`.
fn decode(self, json: &Json) -> Option<V> {
match self {
Spec::Bool => codec_bool(json).map(V::Bool),
Spec::Int(lo, hi) => {
let v = codec_int(json)?;
(v >= lo && i64::from(v) <= i64::from(hi) + 1).then_some(V::Int(v))
}
Spec::LazyInt(lo) => {
let v = codec_int(json)?;
(v >= lo).then_some(V::Int(v))
}
Spec::Scaled(.., lo, hi) => double_range(codec_double(json)?, lo, hi).map(V::Double),
Spec::FrameLimit => {
let v = codec_int(json)?;
(10..=260).contains(&v).then_some(V::Int(v))
}
Spec::Fov => Some(V::Int((codec_double(json)? * 40.0 + 70.0) as i32)),
Spec::WheelSensitivity => {
double_range(codec_double(json)?, log_mouse(-200), log_mouse(100)).map(V::Double)
}
Spec::Unit => unit_alt(json).map(V::Double),
Spec::UnitSquare => double_range(codec_double(json)?, 0.0, 1.0).map(V::Double),
Spec::UnitSquareImplicit => unit_alt(json).map(|v| V::Double(v * v)),
Spec::Named(names) => {
let s = codec_string(json)?;
names.iter().position(|n| *n == s).map(|i| V::Int(i as i32))
}
Spec::Id(count) => codec_int(json).map(|v| V::Int(v.rem_euclid(count))),
Spec::Clouds => {
if let Some(s) = codec_string(json) {
return CLOUDS
.iter()
.position(|n| *n == s)
.map(|i| V::Int(i as i32));
}
codec_bool(json).map(|b| V::Int(if b { 2 } else { 0 }))
}
Spec::AnyStr => codec_string(json).map(|s| V::Str(s.to_owned())),
}
}
/// `ValueSet.validateValue`; `None` makes `OptionInstance.set` fall back
/// to the option's initial value.
fn validate(self, v: &V) -> Option<V> {
match (self, v) {
(Spec::Bool, V::Bool(_)) => Some(v.clone()),
(Spec::Int(lo, hi), V::Int(x)) => (*x >= lo && *x <= hi).then(|| v.clone()),
(Spec::LazyInt(lo), V::Int(x)) => Some(V::Int((*x).clamp(lo, 2_147_483_646))),
(Spec::Scaled(imin, imax, k, ..), V::Double(x)) => {
let i = (x * k) as i32;
(i >= imin && i <= imax).then(|| V::Double(f64::from(i) / k))
}
(Spec::FrameLimit, V::Int(x)) => {
let i = x / 10;
(1..=26).contains(&i).then(|| V::Int(i * 10))
}
(Spec::Fov, V::Int(x)) => (30..=110).contains(x).then(|| v.clone()),
(Spec::WheelSensitivity, V::Double(x)) => {
let i = floor_int(x.log10() * 100.0);
(-200..=100).contains(&i).then(|| V::Double(log_mouse(i)))
}
(Spec::Unit, V::Double(x)) => (*x >= 0.0 && *x <= 1.0).then(|| v.clone()),
(Spec::UnitSquare | Spec::UnitSquareImplicit, V::Double(x)) => {
let root = x.sqrt();
(0.0..=1.0)
.contains(&root)
.then_some(V::Double(root * root))
}
(Spec::Named(names), V::Int(x)) => {
(*x >= 0 && (*x as usize) < names.len()).then(|| v.clone())
}
(Spec::Id(count), V::Int(x)) => (*x >= 0 && *x < count).then(|| v.clone()),
(Spec::Clouds, V::Int(x)) => (0..3).contains(x).then(|| v.clone()),
(Spec::AnyStr, V::Str(_)) => Some(v.clone()),
_ => None,
}
}
/// `codec.encodeStart(JsonOps.INSTANCE, value)` rendered by Gson.
fn encode(self, v: &V) -> Option<String> {
let double = |x: f64| java_text::double_to_string(x);
Some(match (self, v) {
(Spec::Bool, V::Bool(b)) => b.to_string(),
(Spec::Int(lo, hi), V::Int(x)) => {
if *x < lo || i64::from(*x) > i64::from(hi) + 1 {
return None;
}
x.to_string()
}
(Spec::LazyInt(lo), V::Int(x)) => {
if *x < lo {
return None;
}
x.to_string()
}
(Spec::Scaled(.., lo, hi), V::Double(x)) => {
double_range(*x, lo, hi)?;
double(*x)
}
(Spec::FrameLimit, V::Int(x)) => {
if !(10..=260).contains(x) {
return None;
}
x.to_string()
}
(Spec::Fov, V::Int(x)) => double((f64::from(*x) - 70.0) / 40.0),
(Spec::WheelSensitivity, V::Double(x)) => {
double_range(*x, log_mouse(-200), log_mouse(100))?;
double(*x)
}
(Spec::Unit, V::Double(x)) => {
double_range(*x, 0.0, 1.0)?;
double(*x)
}
(Spec::UnitSquare, V::Double(x)) => {
double_range(*x, 0.0, 1.0)?;
double(*x)
}
(Spec::UnitSquareImplicit, V::Double(x)) => {
let root = x.sqrt();
double_range(root, 0.0, 1.0)?;
double(root)
}
(Spec::Named(names), V::Int(x)) => {
java_text::gson_string(names.get(usize::try_from(*x).ok()?)?)
}
(Spec::Id(_), V::Int(x)) => x.to_string(),
(Spec::Clouds, V::Int(x)) => {
java_text::gson_string(CLOUDS.get(usize::try_from(*x).ok()?)?)
}
(Spec::AnyStr, V::Str(s)) => java_text::gson_string(s),
_ => return None,
})
}
}
/// `InputConstants.getKey(name)`: the canonical name of a key, or the
/// unbound key when `name` is invalid.
pub fn canonical_key(name: &str) -> Result<String, java_text::SyntaxError> {
for (_, n) in key_names::KEYBOARD.iter().chain(key_names::MOUSE) {
if *n == name {
return Ok(name.to_owned());
}
}
for (prefix, table) in [
("key.keyboard", key_names::KEYBOARD),
("key.mouse", key_names::MOUSE),
] {
if let Some(rest) = name.strip_prefix(prefix) {
// substring(prefix.length() + 1): the separator is skipped blindly.
let mut chars = rest.chars();
if chars.next().is_none() {
// StringIndexOutOfBoundsException is not an IllegalArgumentException.
return Err(java_text::SyntaxError);
}
let Some(value) = crate::options_fixes::java_parse_int(chars.as_str()) else {
return Ok("key.keyboard.unknown".into());
};
return Ok(table
.iter()
.find(|(v, _)| *v == value)
.map_or_else(|| format!("{prefix}.{value}"), |(_, n)| (*n).to_owned()));
}
}
Ok("key.keyboard.unknown".into())
}
fn read_list(text: &str) -> Result<Vec<String>, java_text::SyntaxError> {
// GsonHelper.fromNullableJson with a List<String> type token.
Ok(java_text::parse_strict_string_list(text)?.unwrap_or_default())
}
/// All option values in `processOptions` order.
#[derive(Clone, Debug, PartialEq)]
pub struct OptionsFile {
values: Vec<V>,
/// `fullscreenResolution`, kept verbatim.
pub fullscreen_resolution: Option<String>,
}
impl Default for OptionsFile {
fn default() -> Self {
Self {
values: TABLE.iter().map(|d| d.default.clone()).collect(),
fullscreen_resolution: None,
}
}
}
impl OptionsFile {
fn index(key: &str) -> Option<usize> {
TABLE.iter().position(|d| d.key == key)
}
pub fn get(&self, key: &str) -> Option<&V> {
Self::index(key).map(|i| &self.values[i])
}
pub fn bool(&self, key: &str) -> bool {
matches!(self.get(key), Some(V::Bool(true)))
}
pub fn int(&self, key: &str) -> i32 {
match self.get(key) {
Some(V::Int(i)) => *i,
_ => 0,
}
}
pub fn double(&self, key: &str) -> f64 {
match self.get(key) {
Some(V::Double(d)) => *d,
_ => 0.0,
}
}
pub fn string(&self, key: &str) -> String {
match self.get(key) {
Some(V::Str(s)) => s.clone(),
_ => String::new(),
}
}
pub fn list(&self, key: &str) -> Vec<String> {
match self.get(key) {
Some(V::List(l)) => l.clone(),
_ => Vec::new(),
}
}
/// The serialized name of an enum-valued option.
pub fn name(&self, key: &str) -> String {
let Some(i) = Self::index(key) else {
return String::new();
};
match (TABLE[i].kind, &self.values[i]) {
(Kind::Option(Spec::Named(names)), V::Int(x)) => {
names.get(*x as usize).copied().unwrap_or("").to_owned()
}
(Kind::Option(Spec::Clouds), V::Int(x)) => {
CLOUDS.get(*x as usize).copied().unwrap_or("").to_owned()
}
_ => String::new(),
}
}
/// `OptionInstance.set` with a candidate value (invalid values revert to
/// the initial value).
pub fn set(&mut self, key: &str, value: V) {
let Some(i) = Self::index(key) else { return };
let Kind::Option(spec) = TABLE[i].kind else {
self.values[i] = value;
return;
};
self.values[i] = spec
.validate(&value)
.unwrap_or_else(|| TABLE[i].default.clone());
}
/// Select an enum option by serialized name.
pub fn set_name(&mut self, key: &str, name: &str) {
let Some(i) = Self::index(key) else { return };
let names: &[&str] = match TABLE[i].kind {
Kind::Option(Spec::Named(names)) => names,
Kind::Option(Spec::Clouds) => CLOUDS,
_ => return,
};
if let Some(p) = names.iter().position(|n| *n == name) {
self.values[i] = V::Int(p as i32);
}
}
/// Key mapping value by mapping name.
pub fn key_binding(&self, name: &str) -> String {
self.string(&format!("key_{name}"))
}
/// `Options.load` on the text of an options file.
pub fn parse(text: &str) -> Self {
let mut file = Self::default();
let mut raw: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for line in split_lines(text) {
if let Some((k, v)) = line.split_once(':') {
raw.insert(k.to_owned(), v.to_owned());
}
}
let version = raw
.get("version")
.and_then(|v| crate::options_fixes::java_parse_int(v))
.unwrap_or(0);
// A fixer failure abandons the whole file, leaving the defaults.
if crate::options_fixes::update(&mut raw, version).is_ok() {
file.apply(&raw);
}
file
}
fn apply(&mut self, raw: &std::collections::HashMap<String, String>) {
// A syntax error aborts the rest of the load, fullscreenResolution included.
if self.try_apply(raw).is_ok()
&& let Some(r) = raw.get("fullscreenResolution")
{
self.fullscreen_resolution = Some(r.clone());
}
}
fn try_apply(
&mut self,
raw: &std::collections::HashMap<String, String>,
) -> Result<(), java_text::SyntaxError> {
for (i, d) in TABLE.iter().enumerate() {
let Some(text) = raw.get(&d.key) else {
continue;
};
match d.kind {
Kind::Option(spec) => {
let json =
java_text::parse_lenient(if text.is_empty() { "\"\"" } else { text })?;
if let Some(decoded) = spec.decode(&json) {
self.values[i] =
spec.validate(&decoded).unwrap_or_else(|| d.default.clone());
}
}
Kind::PlainBool => self.values[i] = V::Bool(text == "true"),
Kind::PlainInt => {
if let Some(v) = crate::options_fixes::java_parse_int(text) {
self.values[i] = V::Int(v);
}
}
Kind::PlainStr => self.values[i] = V::Str(text.clone()),
Kind::List => self.values[i] = V::List(read_list(text)?),
Kind::Tutorial => {
let step = TUTORIAL_STEPS.iter().position(|n| n == text).unwrap_or(5);
self.values[i] = V::Int(step as i32);
}
Kind::Key => {
let V::Str(current) = &self.values[i] else {
continue;
};
if current != text {
self.values[i] = V::Str(canonical_key(text)?);
}
}
}
}
Ok(())
}
/// `Options.save`.
pub fn serialize(&self) -> String {
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
for (d, v) in TABLE.iter().zip(&self.values) {
let rendered = match (d.kind, v) {
(Kind::Option(spec), v) => match spec.encode(v) {
Some(s) => s,
None => continue,
},
(Kind::PlainBool, V::Bool(b)) => b.to_string(),
(Kind::PlainInt, V::Int(x)) => x.to_string(),
(Kind::PlainStr | Kind::Key, V::Str(s)) => s.clone(),
(Kind::List, V::List(items)) => {
let parts: Vec<String> =
items.iter().map(|s| java_text::gson_string(s)).collect();
format!("[{}]", parts.join(","))
}
(Kind::Tutorial, V::Int(x)) => TUTORIAL_STEPS
.get(*x as usize)
.copied()
.unwrap_or("none")
.to_owned(),
_ => continue,
};
out.push_str(&d.key);
out.push(':');
out.push_str(&rendered);
out.push('\n');
}
if let Some(r) = &self.fullscreen_resolution {
out.push_str("fullscreenResolution:");
out.push_str(r);
out.push('\n');
}
out
}
}
/// `BufferedReader.lines()`: \n, \r\n and \r terminate lines.
fn split_lines(text: &str) -> Vec<&str> {
let mut lines = Vec::new();
let bytes = text.as_bytes();
let mut start = 0;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\n' => {
lines.push(&text[start..i]);
start = i + 1;
}
b'\r' => {
lines.push(&text[start..i]);
if bytes.get(i + 1) == Some(&b'\n') {
i += 1;
}
start = i + 1;
}
_ => {}
}
i += 1;
}
if start < bytes.len() {
lines.push(&text[start..]);
}
lines
}
/// Option names in processing order (for tests and tooling).
pub fn keys() -> Vec<&'static str> {
TABLE.iter().map(|d| d.key.as_str()).collect()
}
+324
View File
@@ -0,0 +1,324 @@
//! The `OPTIONS` data fixers of 26.3 (`DataFixTypes.OPTIONS`), applied to the
//! raw key/value strings of an `options.txt` older than the current version.
use std::collections::HashMap;
/// A fixer threw an exception; vanilla abandons loading the file.
#[derive(Debug)]
pub struct FixFailed;
pub type Raw = HashMap<String, String>;
/// OptionsKeyLwjgl3Fix.MAP: GLFW 2 key codes to key names.
const LWJGL3: &[(i32, &str)] = &[
(0, "key.unknown"),
(11, "key.0"),
(2, "key.1"),
(3, "key.2"),
(4, "key.3"),
(5, "key.4"),
(6, "key.5"),
(7, "key.6"),
(8, "key.7"),
(9, "key.8"),
(10, "key.9"),
(30, "key.a"),
(40, "key.apostrophe"),
(48, "key.b"),
(43, "key.backslash"),
(14, "key.backspace"),
(46, "key.c"),
(58, "key.caps.lock"),
(51, "key.comma"),
(32, "key.d"),
(211, "key.delete"),
(208, "key.down"),
(18, "key.e"),
(207, "key.end"),
(28, "key.enter"),
(13, "key.equal"),
(1, "key.escape"),
(33, "key.f"),
(59, "key.f1"),
(68, "key.f10"),
(87, "key.f11"),
(88, "key.f12"),
(100, "key.f13"),
(101, "key.f14"),
(102, "key.f15"),
(103, "key.f16"),
(104, "key.f17"),
(105, "key.f18"),
(113, "key.f19"),
(60, "key.f2"),
(61, "key.f3"),
(62, "key.f4"),
(63, "key.f5"),
(64, "key.f6"),
(65, "key.f7"),
(66, "key.f8"),
(67, "key.f9"),
(34, "key.g"),
(41, "key.grave.accent"),
(35, "key.h"),
(199, "key.home"),
(23, "key.i"),
(210, "key.insert"),
(36, "key.j"),
(37, "key.k"),
(82, "key.keypad.0"),
(79, "key.keypad.1"),
(80, "key.keypad.2"),
(81, "key.keypad.3"),
(75, "key.keypad.4"),
(76, "key.keypad.5"),
(77, "key.keypad.6"),
(71, "key.keypad.7"),
(72, "key.keypad.8"),
(73, "key.keypad.9"),
(78, "key.keypad.add"),
(83, "key.keypad.decimal"),
(181, "key.keypad.divide"),
(156, "key.keypad.enter"),
(141, "key.keypad.equal"),
(55, "key.keypad.multiply"),
(74, "key.keypad.subtract"),
(38, "key.l"),
(203, "key.left"),
(56, "key.left.alt"),
(26, "key.left.bracket"),
(29, "key.left.control"),
(42, "key.left.shift"),
(219, "key.left.win"),
(50, "key.m"),
(12, "key.minus"),
(49, "key.n"),
(69, "key.num.lock"),
(24, "key.o"),
(25, "key.p"),
(209, "key.page.down"),
(201, "key.page.up"),
(197, "key.pause"),
(52, "key.period"),
(183, "key.print.screen"),
(16, "key.q"),
(19, "key.r"),
(205, "key.right"),
(184, "key.right.alt"),
(27, "key.right.bracket"),
(157, "key.right.control"),
(54, "key.right.shift"),
(220, "key.right.win"),
(31, "key.s"),
(70, "key.scroll.lock"),
(39, "key.semicolon"),
(53, "key.slash"),
(57, "key.space"),
(20, "key.t"),
(15, "key.tab"),
(22, "key.u"),
(200, "key.up"),
(47, "key.v"),
(17, "key.w"),
(45, "key.x"),
(21, "key.y"),
(44, "key.z"),
];
/// `Integer.parseInt(String)`.
pub fn java_parse_int(text: &str) -> Option<i32> {
let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
}
text.parse::<i32>().ok()
}
enum Number<'a> {
Special(f64),
Decimal(bool, &'a str),
}
fn java_number(text: &str) -> Option<Number<'_>> {
let t = text.trim_matches(|c: char| c <= ' ');
let (negative, body) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
match body {
"NaN" => return Some(Number::Special(f64::NAN)),
"Infinity" => {
return Some(Number::Special(if negative {
f64::NEG_INFINITY
} else {
f64::INFINITY
}));
}
_ => {}
}
let body = body.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(body);
if body.is_empty()
|| !body
.chars()
.all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-'))
|| !body.chars().any(|c| c.is_ascii_digit())
{
return None;
}
Some(Number::Decimal(negative, body))
}
/// `Double.parseDouble(String)` for decimal and special forms.
pub fn java_parse_double(text: &str) -> Option<f64> {
match java_number(text)? {
Number::Special(v) => Some(v),
Number::Decimal(negative, body) => body
.parse::<f64>()
.ok()
.map(|v| if negative { -v } else { v }),
}
}
/// `Float.parseFloat(String)`.
pub fn java_parse_float(text: &str) -> Option<f32> {
match java_number(text)? {
Number::Special(v) => Some(v as f32),
Number::Decimal(negative, body) => body
.parse::<f32>()
.ok()
.map(|v| if negative { -v } else { v }),
}
}
fn rename(raw: &mut Raw, from: &str, to: &str, fix: impl FnOnce(&str) -> String) {
if let Some(old) = raw.remove(from) {
let value = fix(&old);
raw.insert(to.to_owned(), value);
}
}
/// `OPTIONS` fixers from `version` up to the current data version.
pub fn update(raw: &mut Raw, version: i32) -> Result<(), FixFailed> {
if version < 816
&& let Some(lang) = raw.get_mut("lang")
{
*lang = lang.to_lowercase();
}
if version < 1344 {
let keys: Vec<String> = raw
.keys()
.filter(|k| k.starts_with("key_"))
.cloned()
.collect();
for key in keys {
let old = java_parse_int(&raw[&key]).ok_or(FixFailed)?;
let name = if old < 0 {
match old + 100 {
0 => "key.mouse.left".to_owned(),
1 => "key.mouse.right".to_owned(),
2 => "key.mouse.middle".to_owned(),
button => format!("key.mouse.{}", button + 1),
}
} else {
LWJGL3
.iter()
.find(|(v, _)| *v == old)
.map_or("key.unknown", |(_, n)| n)
.to_owned()
};
raw.insert(key, name);
}
}
if version < 1446 {
let keys: Vec<String> = raw
.keys()
.filter(|k| k.starts_with("key_"))
.cloned()
.collect();
for key in keys {
let old = raw[&key].clone();
if !old.starts_with("key.mouse") && !old.starts_with("scancode.") {
// substring(4) on a shorter value throws.
let rest: String = old.chars().skip(4).collect();
if old.chars().count() < 4 {
return Err(FixFailed);
}
raw.insert(key, format!("key.keyboard.{rest}"));
}
}
}
if version < 1936
&& let Some(opacity) = raw.get("chatOpacity")
{
let background = java_parse_double(opacity).map_or(0.5, |v| (0.9 * v + 0.1) / 2.0);
raw.insert(
"textBackgroundOpacity".into(),
crate::java_text::double_to_string(background),
);
}
if version < 2556 {
rename(raw, "fancyGraphics", "graphicsMode", |v| {
if v == "true" { "1" } else { "0" }.to_owned()
});
}
if version < 2558
&& let Some(v) = raw.remove("key_key.swapHands")
{
raw.insert("key_key.swapOffhand".into(), v);
}
if version < 3201 {
for key in ["resourcePacks", "incompatibleResourcePacks"] {
if let Some(v) = raw.get_mut(key) {
*v = v.replace("\"programer_art\"", "\"programmer_art\"");
}
}
}
if version < 3214
&& let Some(ao) = raw.get_mut("ao")
{
match ao.as_str() {
"0" => *ao = "false".into(),
"1" | "2" => *ao = "true".into(),
_ => {}
}
}
if version < 3319 {
raw.insert("onboardAccessibility".into(), "false".into());
}
if version < 3943
&& let Some(v) = raw.get_mut("menuBackgroundBlurriness")
{
let value = java_parse_float(v).map_or(5, |d| ((d * 10.0) + 0.5).floor() as i32);
*v = value.to_string();
}
if version < 4651 {
let mode = raw.get("graphicsMode").cloned();
for (name, fast, fancy, fabulous) in [
("cutoutLeaves", "false", "true", "true"),
("weatherRadius", "5", "10", "10"),
("vignette", "false", "true", "true"),
("improvedTransparency", "false", "false", "true"),
] {
let value = match mode.as_deref() {
Some("2") => fabulous,
Some("0") => fast,
_ => fancy,
};
raw.insert(name.into(), value.into());
}
raw.insert("graphicsPreset".into(), "custom".into());
}
if version < 4661 {
rename(raw, "showNowPlayingToast", "musicToast", |v| {
if v == "false" {
"never"
} else {
"pause_and_toast"
}
.to_owned()
});
}
if version < 4892 {
raw.insert("preferredGraphicsBackend".into(), "default".into());
}
Ok(())
}
+78 -27
View File
@@ -280,14 +280,27 @@ impl Book {
ingredients,
result,
} => (Display::Shapeless(ingredients.clone()), result),
Recipe::Special(_) => continue,
// Custom recipes are never learnable; the others show one
// display per material count (TransmuteRecipe.display).
Recipe::Special(special) => {
for (display, result) in special.book_displays() {
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result,
});
}
continue;
}
};
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result: result.clone(),
result: result.create(),
});
}
for c in &recipes.cooking {
@@ -376,24 +389,33 @@ impl Book {
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
items
}
/// `RecipeCollection` search: the result's name or registry path, or
/// `@namespace`.
pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool {
/// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a
/// `FullTextSearchTree`): without a colon the text must occur in a
/// tooltip line of a result item of the collection; `namespace:path`
/// needs the namespace in a result id and the path in an id or a line.
pub fn collection_matches(
&self,
entries: &[usize],
query: &str,
tooltip: &dyn Fn(&ItemStack) -> Vec<String>,
) -> bool {
let query = query.to_lowercase();
if let Some(ns) = query.strip_prefix('@') {
return entry
.result
.item
.split(':')
.next()
.is_some_and(|n| n.starts_with(ns));
}
name.to_lowercase().contains(&query)
|| entry
.result
.item
.trim_start_matches("minecraft:")
.contains(&query)
let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect();
let in_lines = |text: &str| {
results
.iter()
.any(|r| tooltip(r).iter().any(|l| l.to_lowercase().contains(text)))
};
let Some((namespace, path)) = query.split_once(':') else {
return in_lines(&query);
};
let (namespace, path) = (namespace.trim(), path.trim());
let id = |r: &&ItemStack| {
let (ns, p) = r.item.split_once(':').unwrap_or(("minecraft", &r.item));
(ns.to_lowercase(), p.to_lowercase())
};
results.iter().any(|r| id(r).0.contains(namespace))
&& (results.iter().any(|r| id(r).1.contains(path)) || in_lines(path))
}
}
@@ -524,6 +546,8 @@ pub struct Settings {
pub filtering: [bool; 4],
/// Unlocked recipe ids (`recipes`).
pub recipes: Vec<String>,
/// Recipes not yet shown in the book (`toBeDisplayed`): they animate once.
pub to_be_displayed: Vec<String>,
}
impl Settings {
pub fn read(tag: Option<&Tag>) -> Self {
@@ -535,30 +559,38 @@ impl Settings {
s.open[b.index()] = flag(open);
s.filtering[b.index()] = flag(filter);
}
if let Some(Tag::List(list)) = tag.get("recipes") {
s.recipes = list
let ids = |key: &str| match tag.get(key) {
Some(Tag::List(list)) => list
.iter()
.filter_map(|t| match t {
Tag::String(id) => Some(id.to_string_lossy()),
_ => None,
})
.collect();
}
.collect(),
_ => Vec::new(),
};
s.recipes = ids("recipes");
s.to_be_displayed = ids("toBeDisplayed");
s
}
/// The compound written to the player file; `toBeDisplayed` stays empty.
/// The compound written to the player file.
pub fn write(&self) -> Tag {
let mut entries: Vec<(&str, Tag)> = Vec::new();
for b in BookType::ALL {
let (open, filter) = b.keys();
entries.push((open, Tag::Byte(i8::from(self.open[b.index()]))));
entries.push((filter, Tag::Byte(i8::from(self.filtering[b.index()]))));
// The codec omits settings at their default (false).
if self.open[b.index()] {
entries.push((open, Tag::Byte(1)));
}
if self.filtering[b.index()] {
entries.push((filter, Tag::Byte(1)));
}
}
let list = |ids: &[String]| {
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
};
entries.push(("recipes", list(&self.recipes)));
entries.push(("toBeDisplayed", Tag::List(Vec::new())));
entries.push(("toBeDisplayed", list(&self.to_be_displayed)));
Tag::compound(entries)
}
}
@@ -672,6 +704,25 @@ mod tests {
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
}
#[test]
fn search_reads_tooltip_lines_and_ids() {
let book = Book {
entries: vec![Entry {
id: "minecraft:stick".into(),
category: Category::CraftingMisc,
group: None,
display: Display::Shapeless(Vec::new()),
result: ItemStack::new("minecraft:stick", 4),
}],
order: HashMap::new(),
};
let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()];
assert!(book.collection_matches(&[0], "STI", &lines));
// Plain text searches tooltips only, not the registry path.
assert!(!book.collection_matches(&[0], "stick:", &lines));
assert!(book.collection_matches(&[0], "minecraft:stic", &lines));
assert!(!book.collection_matches(&[0], "other:stick", &lines));
}
#[test]
fn settings_round_trip() {
let mut s = Settings::default();
s.open[BookType::Furnace.index()] = true;
+81 -78
View File
@@ -16,10 +16,11 @@
use crate::{
Result,
biome::Biomes,
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS},
chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS},
streaming::ChunkGenerator,
};
use horizon_core::{
paletted::PalettedContainer,
position::{BlockPos, ChunkPos},
ticks::{SavedTick, TickPriority, TickTypeId},
};
@@ -42,29 +43,6 @@ use std::{
pub const VERSION_NAME: &str = "26.3";
fn pack(indices: &[u16], bits: u32) -> Vec<i64> {
let per_long = (64 / bits) as usize;
let mut longs = vec![0i64; indices.len().div_ceil(per_long)];
for (i, &v) in indices.iter().enumerate() {
longs[i / per_long] |=
(i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits);
}
longs
}
fn unpack(longs: &[i64], bits: u32, count: usize) -> Vec<u16> {
let per_long = (64 / bits) as usize;
let mask = (1u64 << bits) - 1;
(0..count)
.map(|i| {
longs.get(i / per_long).map_or(0, |&l| {
((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16
})
})
.collect()
}
fn bits_for(len: usize, min: u32) -> u32 {
(usize::BITS - (len.max(1) - 1).leading_zeros()).max(min)
}
fn string(s: &str) -> Tag {
Tag::String(s.into())
}
@@ -133,6 +111,27 @@ impl SessionLock {
Ok(Self(file))
}
}
/// Refuse a world last saved by an older game version: chunks are only read
/// at the current DataVersion, and the DataFixerUpper chain is not ported.
/// `tools/upgrade_world.py` runs vanilla's own upgrader (`--forceUpgrade`).
pub fn check_data_version(world: &Path) -> Result<()> {
let Some(root) = read_dat(&world.join("level.dat")) else {
return Ok(());
};
let version = root
.get("Data")
.and_then(|d| number(d.get("DataVersion")))
.unwrap_or(i64::from(DATA_VERSION));
if version < i64::from(DATA_VERSION) {
return Err(format!(
"{} was saved with DataVersion {version} (this game is {DATA_VERSION}); \
upgrade it first with tools/upgrade_world.py",
world.display()
)
.into());
}
Ok(())
}
/// Move a world saved by an older Horizon build (pre-26.3 layout with a
/// DataVersion that keeps vanilla from upgrading it) into the 26.3 layout.
pub fn migrate_legacy(world: &Path) -> Result<()> {
@@ -670,33 +669,22 @@ pub fn encode_with(
});
for (si, section) in chunk.sections.iter().enumerate() {
let y = (MIN_Y >> 4) + si as i32;
let ids: Vec<u16> = match &section.blocks {
Blocks::Uniform(v) => vec![*v],
Blocks::Full(a) => a.to_vec(),
};
let mut palette: Vec<u16> = Vec::new();
let mut lookup: HashMap<u16, u16> = HashMap::new();
let indices: Vec<u16> = ids
.iter()
.map(|id| {
*lookup.entry(*id).or_insert_with(|| {
palette.push(*id);
(palette.len() - 1) as u16
})
})
.collect();
// PalettedContainer.pack: distinct states in index order, indices at
// the saved width.
let packed = section.blocks.pack();
let mut states = vec![(
"palette",
Tag::List(
palette
packed
.palette
.iter()
.map(|id| {
let state = registry.state(BlockStateId(u32::from(*id)));
.map(|&id| {
let state = registry.state(BlockStateId(id));
match state {
// BlockState.CODEC: the block name for default states.
Some(s)
if tables.is_some_and(|t| {
t.default_state.get(*id as usize) == Some(&true)
t.default_state.get(id as usize) == Some(&true)
}) =>
{
string(&s.name)
@@ -708,37 +696,27 @@ pub fn encode_with(
.collect(),
),
)];
if palette.len() > 1 {
if let Some(data) = &packed.data {
states.push((
"data",
Tag::LongArray(pack(&indices, bits_for(palette.len(), 4))),
Tag::LongArray(data.iter().map(|&w| w as i64).collect()),
));
}
let quart: Vec<u16> = (0..64).map(|i| chunk.biomes[si * 64 + i]).collect();
let mut biome_palette: Vec<u16> = Vec::new();
let biome_indices: Vec<u16> = quart
.iter()
.map(|b| match biome_palette.iter().position(|p| p == b) {
Some(i) => i as u16,
None => {
biome_palette.push(*b);
(biome_palette.len() - 1) as u16
}
})
.collect();
let biome_packed = section.biomes.pack();
let mut biome_tag = vec![(
"palette",
Tag::List(
biome_palette
biome_packed
.palette
.iter()
.map(|b| string(&biomes.get(*b).name))
.map(|&b| string(&biomes.get(b as u16).name))
.collect(),
),
)];
if biome_palette.len() > 1 {
if let Some(data) = &biome_packed.data {
biome_tag.push((
"data",
Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0))),
Tag::LongArray(data.iter().map(|&w| w as i64).collect()),
));
}
let mut entries = vec![
@@ -772,7 +750,12 @@ pub fn encode_with(
.iter()
.map(|(p, e)| {
let block = block_name(p);
let current = encode_block_entity(*p, e, &block);
let mut current = encode_block_entity(*p, e, &block);
if let Some((_, name)) = chunk.block_names.iter().find(|(q, _)| q == p)
&& let Tag::Compound(map) = &mut current
{
map.insert("CustomName".into(), string(name));
}
let source = extras
.and_then(|x| x.block_entity_sources.iter().find(|(q, _)| q == p))
.map(|(_, tag)| tag)
@@ -918,7 +901,6 @@ pub fn decode_with(
}
let air = registry.default_state("minecraft:air")?.0 as u16;
let mut cache: HashMap<String, u16> = HashMap::new();
let mut biome_data = (*chunk.biomes).clone();
let Some(Tag::List(sections)) = tag.get("sections") else {
return Some(chunk);
};
@@ -961,15 +943,17 @@ pub fn decode_with(
})
.collect();
let target = Arc::make_mut(&mut chunk.sections[si as usize]);
if ids.len() <= 1 {
target.blocks = Blocks::Uniform(ids.first().copied().unwrap_or(air));
} else if let Some(Tag::LongArray(data)) = states.get("data") {
let indices = unpack(data, bits_for(ids.len(), 4), 4096);
let mut full = Box::new([air; 4096]);
for (i, idx) in indices.iter().enumerate() {
full[i] = ids.get(*idx as usize).copied().unwrap_or(air);
let data = match states.get("data") {
Some(Tag::LongArray(data)) => {
Some(data.iter().map(|&w| w as u64).collect::<Vec<_>>())
}
target.blocks = Blocks::Full(full);
_ => None,
};
let palette: Vec<u32> = ids.iter().map(|&id| u32::from(id)).collect();
if let Ok(blocks) =
PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref())
{
target.blocks = blocks;
}
}
if let Some(b) = section.get("biomes")
@@ -982,18 +966,23 @@ pub fn decode_with(
_ => 0,
})
.collect();
let indices = match b.get("data") {
Some(Tag::LongArray(data)) if ids.len() > 1 => {
unpack(data, bits_for(ids.len(), 0), 64)
let data = match b.get("data") {
Some(Tag::LongArray(data)) => {
Some(data.iter().map(|&w| w as u64).collect::<Vec<_>>())
}
_ => vec![0; 64],
_ => None,
};
for (i, idx) in indices.iter().enumerate() {
biome_data[si as usize * 64 + i] = ids.get(*idx as usize).copied().unwrap_or(0);
let palette: Vec<u32> = ids.iter().map(|&id| u32::from(id)).collect();
let target = Arc::make_mut(&mut chunk.sections[si as usize]);
if let Ok(container) =
PalettedContainer::from_packed(BIOME_STRATEGY, palette.clone(), data.as_deref())
{
target.biomes = container;
} else if let Some(&first) = palette.first() {
target.biomes = PalettedContainer::new(BIOME_STRATEGY, first);
}
}
}
chunk.biomes = Arc::new(biome_data);
let mut extras = ChunkExtras {
last_update: number(tag.get("LastUpdate")).unwrap_or(0),
..ChunkExtras::default()
@@ -1002,6 +991,9 @@ pub fn decode_with(
for e in entities {
match decode_block_entity(e) {
Some(be) => {
if let Some(name) = text(e.get("CustomName")) {
chunk.block_names.push((be.0, name));
}
extras.block_entity_sources.push((be.0, e.clone()));
chunk.block_entities.push(be);
}
@@ -2187,6 +2179,17 @@ impl<G: ChunkGenerator> ChunkGenerator for Persistent<G> {
#[cfg(test)]
mod tests {
#[test]
fn old_data_version_is_refused() {
let dir = std::env::temp_dir().join(format!("horizon-dv-{}", std::process::id()));
let level =
|v: i32| Tag::compound([("Data", Tag::compound([("DataVersion", Tag::Int(v))]))]);
super::write_dat(&dir.join("level.dat"), level(3955)).unwrap();
assert!(super::check_data_version(&dir).is_err());
super::write_dat(&dir.join("level.dat"), level(super::DATA_VERSION)).unwrap();
assert!(super::check_data_version(&dir).is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn session_lock_is_exclusive() {
let dir = std::env::temp_dir().join(format!("horizon-lock-{}", std::process::id()));
+17 -8
View File
@@ -780,7 +780,7 @@ impl Scoreboard {
// saved data
pub fn pack(&self) -> Tag {
let objectives = self
let objectives: Vec<Tag> = self
.objectives
.iter()
.map(|o| {
@@ -824,7 +824,7 @@ impl Scoreboard {
.iter()
.map(|(k, v)| (k.as_str(), Tag::String(v.as_str().into())))
.collect::<Vec<_>>();
let teams = self
let teams: Vec<Tag> = self
.teams
.iter()
.map(|t| {
@@ -866,12 +866,21 @@ impl Scoreboard {
Tag::compound(c)
})
.collect();
Tag::compound([
("Objectives", Tag::List(objectives)),
("PlayerScores", Tag::List(scores)),
("DisplaySlots", Tag::compound(slots)),
("Teams", Tag::List(teams)),
])
// The codec leaves out empty parts.
let mut entries: Vec<(&str, Tag)> = Vec::new();
if !objectives.is_empty() {
entries.push(("Objectives", Tag::List(objectives)));
}
if !scores.is_empty() {
entries.push(("PlayerScores", Tag::List(scores)));
}
if !slots.is_empty() {
entries.push(("DisplaySlots", Tag::compound(slots)));
}
if !teams.is_empty() {
entries.push(("Teams", Tag::List(teams)));
}
Tag::compound(entries)
}
pub fn unpack(data: &Tag) -> Self {
let mut sb = Scoreboard::default();
+214 -245
View File
@@ -2,7 +2,8 @@
//! encodings (Options.processOptions); lines Horizon does not know are kept.
//! The option screens live in `options_ui`.
use crate::keybinds::KeyBinds;
use std::{collections::BTreeMap, fs, path::Path};
use crate::options_file::{OptionsFile, V};
use std::{fs, path::Path};
/// SoundSource names in vanilla order.
pub const SOUND_SOURCES: [&str; 11] = [
@@ -20,7 +21,7 @@ pub fn set_source_volumes(volumes: [f32; 11]) {
pub fn sound_source(event: &str) -> usize {
let e = event.trim_start_matches("minecraft:");
let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0);
const HOSTILE: [&str; 24] = [
const HOSTILE: [&str; 25] = [
"zombie",
"skeleton",
"creeper",
@@ -39,6 +40,7 @@ pub fn sound_source(event: &str) -> usize {
"pillager",
"vindicator",
"evoker",
"illusioner",
"ravager",
"guardian",
"elder_guardian",
@@ -166,8 +168,13 @@ pub struct Settings {
/// Enabled resource packs, bottom first (resourcePacks).
pub resource_packs: Vec<String>,
pub keys: KeyBinds,
/// Lines Horizon does not interpret, kept verbatim.
pub extra: BTreeMap<String, String>,
/// Every option in its stored form (the typed fields above mirror it).
pub file: OptionsFile,
pub invert_x: bool,
pub toggle_attack: bool,
pub toggle_use: bool,
/// Taps of the sprint key counted as double taps (sprintWindow).
pub sprint_window: i32,
}
impl Default for Settings {
fn default() -> Self {
@@ -229,267 +236,228 @@ impl Default for Settings {
show_subtitles: false,
notification_display_time: 1.0,
main_hand_left: false,
resource_packs: vec!["vanilla".into()],
resource_packs: Vec::new(),
keys: KeyBinds::default(),
extra: BTreeMap::new(),
file: OptionsFile::default(),
invert_x: false,
toggle_attack: false,
toggle_use: false,
sprint_window: 7,
}
}
}
fn unquote(v: &str) -> &str {
v.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.unwrap_or(v)
fn put_f(f: &mut OptionsFile, key: &str, v: f32) {
if v != f.double(key) as f32 {
f.set(key, V::Double(f64::from(v)));
}
}
fn parse_list(v: &str) -> Vec<String> {
serde_json::from_str::<Vec<String>>(v).unwrap_or_default()
fn put_i(f: &mut OptionsFile, key: &str, v: i32) {
if v != f.int(key) {
f.set(key, V::Int(v));
}
}
fn put_b(f: &mut OptionsFile, key: &str, v: bool) {
if v != f.bool(key) {
f.set(key, V::Bool(v));
}
}
fn put_name(f: &mut OptionsFile, key: &str, v: &str) {
if v != f.name(key) {
f.set_name(key, v);
}
}
fn put_s(f: &mut OptionsFile, key: &str, v: &str) {
if v != f.string(key) {
f.set(key, V::Str(v.to_owned()));
}
}
impl Settings {
pub fn load(path: &Path) -> Self {
let Ok(text) = fs::read_to_string(path) else {
let Ok(bytes) = fs::read(path) else {
return Self::default();
};
Self::parse(&text)
Self::parse(&String::from_utf8_lossy(&bytes))
}
pub fn parse(text: &str) -> Self {
let mut s = Self::default();
for line in text.lines() {
let Some((k, v)) = line.split_once(':') else {
continue;
};
let f = |d: f32| v.parse::<f32>().unwrap_or(d);
let b = |d: bool| match v {
"true" => true,
"false" => false,
_ => d,
};
let i = |d: i32| v.parse::<i32>().unwrap_or(d);
match k {
"version" => {}
"fov" => {
s.fov = v
.parse::<f32>()
.map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0))
}
"renderDistance" => s.render_distance = i(12).clamp(2, 32),
"simulationDistance" => s.simulation_distance = i(12).clamp(5, 32),
"mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0),
"guiScale" => s.gui_scale = v.parse().unwrap_or(0),
"bobView" => s.view_bobbing = b(true),
"gamma" => s.gamma = f(0.5).clamp(0.0, 1.0),
"maxFps" => s.max_fps = v.parse::<u32>().unwrap_or(260).clamp(10, 260),
"enableVsync" => s.vsync = b(true),
"fullscreen" => s.fullscreen = b(false),
"ao" => s.smooth_lighting = b(true),
"renderClouds" => s.clouds = unquote(v).to_owned(),
"cloudRange" => s.cloud_range = i(128).clamp(2, 128),
"particles" => s.particles = v.parse::<u8>().unwrap_or(0).min(2),
"entityDistanceScaling" => s.entity_distance = f(1.0).clamp(0.5, 5.0),
"entityShadows" => s.entity_shadows = b(true),
"biomeBlendRadius" => s.biome_blend = i(2).clamp(0, 7),
"graphicsPreset" => s.graphics_preset = unquote(v).to_owned(),
"mipmapLevels" => s.mipmap_levels = i(4).clamp(0, 4),
"weatherRadius" => s.weather_radius = i(10).clamp(3, 10),
"chunkSectionFadeInTime" => s.chunk_fade = f(0.75).clamp(0.0, 2.0),
"vignette" => s.vignette = b(true),
"showAutosaveIndicator" => s.autosave_indicator = b(true),
"cutoutLeaves" => s.cutout_leaves = b(true),
"improvedTransparency" => s.improved_transparency = b(false),
"attackIndicator" => s.attack_indicator = v.parse::<u8>().unwrap_or(1).min(2),
"inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(),
"prioritizeChunkUpdates" => {
s.prioritize_chunk_updates = v.parse::<u8>().unwrap_or(0).min(2)
}
"menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10),
"invertYMouse" => s.invert_y = b(false),
"mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0),
"discrete_mouse_scroll" => s.discrete_scroll = b(false),
"toggleCrouch" => s.toggle_crouch = b(false),
"toggleSprint" => s.toggle_sprint = b(false),
"autoJump" => s.auto_jump = b(false),
"lang" => s.language = v.to_owned(),
"forceUnicodeFont" => s.force_unicode = b(false),
"japaneseGlyphVariants" => s.japanese_glyphs = b(false),
"chatVisibility" => s.chat_visibility = v.parse::<u8>().unwrap_or(0).min(2),
"chatColors" => s.chat_colors = b(true),
"chatLinks" => s.chat_links = b(true),
"chatOpacity" => s.chat_opacity = f(1.0).clamp(0.0, 1.0),
"textBackgroundOpacity" => s.text_background_opacity = f(0.5).clamp(0.0, 1.0),
"chatScale" => s.chat_scale = f(1.0).clamp(0.0, 1.0),
"chatWidth" => s.chat_width = f(1.0).clamp(0.0, 1.0),
"chatHeightFocused" => s.chat_height_focused = f(1.0).clamp(0.0, 1.0),
"chatHeightUnfocused" => s.chat_height_unfocused = f(0.4375).clamp(0.0, 1.0),
"chatLineSpacing" => s.chat_line_spacing = f(0.0).clamp(0.0, 1.0),
"autoSuggestions" => s.auto_suggestions = b(true),
"reducedDebugInfo" => s.reduced_debug_info = b(false),
"highContrast" => s.high_contrast = b(false),
"showSubtitles" => s.show_subtitles = b(false),
"notificationDisplayTime" => {
s.notification_display_time = f(1.0).clamp(0.5, 10.0);
}
"mainHand" => s.main_hand_left = unquote(v) == "left",
"resourcePacks" => s.resource_packs = parse_list(v),
_ if k.starts_with("key_") => {
if !s.keys.set_saved(&k[4..], v) {
s.extra.insert(k.to_owned(), v.to_owned());
}
}
_ if k.starts_with("soundCategory_") => {
let name = &k["soundCategory_".len()..];
match SOUND_SOURCES.iter().position(|n| *n == name) {
Some(0) => s.master_volume = f(1.0).clamp(0.0, 1.0),
Some(i) => s.volumes[i] = f(1.0).clamp(0.0, 1.0),
None => {
s.extra.insert(k.to_owned(), v.to_owned());
}
}
}
_ => {
s.extra.insert(k.to_owned(), v.to_owned());
}
}
}
s
Self::from_file(OptionsFile::parse(text))
}
/// The `options.txt` text (Options.save: `version` first, then key:value).
pub fn serialize(&self) -> String {
let mut lines: Vec<(String, String)> = vec![
("ao".into(), self.smooth_lighting.to_string()),
("biomeBlendRadius".into(), self.biome_blend.to_string()),
("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()),
("cutoutLeaves".into(), self.cutout_leaves.to_string()),
("enableVsync".into(), self.vsync.to_string()),
(
"entityDistanceScaling".into(),
self.entity_distance.to_string(),
),
("entityShadows".into(), self.entity_shadows.to_string()),
("forceUnicodeFont".into(), self.force_unicode.to_string()),
(
"japaneseGlyphVariants".into(),
self.japanese_glyphs.to_string(),
),
("fov".into(), ((self.fov - 70.0) / 40.0).to_string()),
(
"graphicsPreset".into(),
format!("\"{}\"", self.graphics_preset),
),
(
"prioritizeChunkUpdates".into(),
self.prioritize_chunk_updates.to_string(),
),
("fullscreen".into(), self.fullscreen.to_string()),
("gamma".into(), self.gamma.to_string()),
("guiScale".into(), self.gui_scale.to_string()),
("maxFps".into(), self.max_fps.to_string()),
(
"improvedTransparency".into(),
self.improved_transparency.to_string(),
),
(
"inactivityFpsLimit".into(),
format!("\"{}\"", self.inactivity_fps_limit),
),
("mipmapLevels".into(), self.mipmap_levels.to_string()),
("particles".into(), self.particles.to_string()),
(
"reducedDebugInfo".into(),
self.reduced_debug_info.to_string(),
),
("renderClouds".into(), format!("\"{}\"", self.clouds)),
("cloudRange".into(), self.cloud_range.to_string()),
("renderDistance".into(), self.render_distance.to_string()),
(
"simulationDistance".into(),
self.simulation_distance.to_string(),
),
("vignette".into(), self.vignette.to_string()),
("weatherRadius".into(), self.weather_radius.to_string()),
("autoJump".into(), self.auto_jump.to_string()),
("autoSuggestions".into(), self.auto_suggestions.to_string()),
("chatColors".into(), self.chat_colors.to_string()),
("chatLinks".into(), self.chat_links.to_string()),
(
"discrete_mouse_scroll".into(),
self.discrete_scroll.to_string(),
),
("invertYMouse".into(), self.invert_y.to_string()),
("bobView".into(), self.view_bobbing.to_string()),
("toggleCrouch".into(), self.toggle_crouch.to_string()),
("toggleSprint".into(), self.toggle_sprint.to_string()),
("mouseSensitivity".into(), self.sensitivity.to_string()),
("highContrast".into(), self.high_contrast.to_string()),
("showSubtitles".into(), self.show_subtitles.to_string()),
(
"notificationDisplayTime".into(),
self.notification_display_time.to_string(),
),
(
"resourcePacks".into(),
serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into()),
),
("lang".into(), self.language.clone()),
("chatVisibility".into(), self.chat_visibility.to_string()),
("chatOpacity".into(), self.chat_opacity.to_string()),
("chatLineSpacing".into(), self.chat_line_spacing.to_string()),
(
"textBackgroundOpacity".into(),
self.text_background_opacity.to_string(),
),
(
"chatHeightFocused".into(),
self.chat_height_focused.to_string(),
),
(
"chatHeightUnfocused".into(),
self.chat_height_unfocused.to_string(),
),
("chatScale".into(), self.chat_scale.to_string()),
("chatWidth".into(), self.chat_width.to_string()),
(
"mainHand".into(),
if self.main_hand_left {
"\"left\"".into()
} else {
"\"right\"".into()
},
),
("attackIndicator".into(), self.attack_indicator.to_string()),
(
"mouseWheelSensitivity".into(),
self.mouse_wheel_sensitivity.to_string(),
),
(
"showAutosaveIndicator".into(),
self.autosave_indicator.to_string(),
),
(
"menuBackgroundBlurriness".into(),
self.menu_blur.to_string(),
),
];
for (name, key) in self.keys.saved() {
lines.push((format!("key_{name}"), key));
/// Typed view of an options file.
pub fn from_file(f: OptionsFile) -> Self {
let mut keys = KeyBinds::default();
for (name, _, _) in crate::keybinds::MAPPINGS {
keys.set(name, &f.key_binding(name));
}
let mut volumes = [1.0; 11];
for (i, source) in SOUND_SOURCES.iter().enumerate() {
volumes[i] = f.double(&format!("soundCategory_{source}")) as f32;
}
Self {
fov: f.int("fov") as f32,
render_distance: f.int("renderDistance"),
simulation_distance: f.int("simulationDistance"),
sensitivity: f.double("mouseSensitivity") as f32,
master_volume: volumes[0],
volumes,
gui_scale: f.int("guiScale").max(0) as u32,
view_bobbing: f.bool("bobView"),
gamma: f.double("gamma") as f32,
max_fps: f.int("maxFps") as u32,
vsync: f.bool("enableVsync"),
fullscreen: f.bool("fullscreen"),
smooth_lighting: f.bool("ao"),
clouds: f.name("renderClouds"),
cloud_range: f.int("cloudRange"),
particles: f.int("particles") as u8,
entity_distance: f.double("entityDistanceScaling") as f32,
entity_shadows: f.bool("entityShadows"),
biome_blend: f.int("biomeBlendRadius"),
graphics_preset: f.name("graphicsPreset"),
mipmap_levels: f.int("mipmapLevels"),
weather_radius: f.int("weatherRadius"),
chunk_fade: f.double("chunkSectionFadeInTime") as f32,
vignette: f.bool("vignette"),
autosave_indicator: f.bool("showAutosaveIndicator"),
cutout_leaves: f.bool("cutoutLeaves"),
improved_transparency: f.bool("improvedTransparency"),
attack_indicator: f.int("attackIndicator") as u8,
inactivity_fps_limit: f.name("inactivityFpsLimit"),
prioritize_chunk_updates: f.int("prioritizeChunkUpdates") as u8,
menu_blur: f.int("menuBackgroundBlurriness"),
invert_x: f.bool("invertXMouse"),
invert_y: f.bool("invertYMouse"),
mouse_wheel_sensitivity: f.double("mouseWheelSensitivity") as f32,
discrete_scroll: f.bool("discrete_mouse_scroll"),
toggle_crouch: f.bool("toggleCrouch"),
toggle_sprint: f.bool("toggleSprint"),
toggle_attack: f.bool("toggleAttack"),
toggle_use: f.bool("toggleUse"),
sprint_window: f.int("sprintWindow"),
auto_jump: f.bool("autoJump"),
language: f.string("lang"),
force_unicode: f.bool("forceUnicodeFont"),
japanese_glyphs: f.bool("japaneseGlyphVariants"),
chat_visibility: f.int("chatVisibility") as u8,
chat_colors: f.bool("chatColors"),
chat_links: f.bool("chatLinks"),
chat_opacity: f.double("chatOpacity") as f32,
text_background_opacity: f.double("textBackgroundOpacity") as f32,
chat_scale: f.double("chatScale") as f32,
chat_width: f.double("chatWidth") as f32,
chat_height_focused: f.double("chatHeightFocused") as f32,
chat_height_unfocused: f.double("chatHeightUnfocused") as f32,
chat_line_spacing: f.double("chatLineSpacing") as f32,
auto_suggestions: f.bool("autoSuggestions"),
reduced_debug_info: f.bool("reducedDebugInfo"),
high_contrast: f.bool("highContrast"),
show_subtitles: f.bool("showSubtitles"),
notification_display_time: f.double("notificationDisplayTime") as f32,
main_hand_left: f.name("mainHand") == "left",
resource_packs: f.list("resourcePacks"),
keys,
file: f,
}
}
/// The options file reflecting the typed fields; values the game did not
/// change keep their stored form.
pub fn to_file(&self) -> OptionsFile {
let mut f = self.file.clone();
put_i(&mut f, "fov", self.fov as i32);
put_i(&mut f, "renderDistance", self.render_distance);
put_i(&mut f, "simulationDistance", self.simulation_distance);
put_f(&mut f, "mouseSensitivity", self.sensitivity);
for (i, source) in SOUND_SOURCES.iter().enumerate() {
let v = if i == 0 {
self.master_volume
} else {
self.volumes[i]
};
lines.push((format!("soundCategory_{source}"), v.to_string()));
put_f(&mut f, &format!("soundCategory_{source}"), v);
}
let known: std::collections::BTreeSet<String> =
lines.iter().map(|(k, _)| k.clone()).collect();
for (k, v) in &self.extra {
if !known.contains(k) {
lines.push((k.clone(), v.clone()));
}
put_i(&mut f, "guiScale", self.gui_scale as i32);
put_b(&mut f, "bobView", self.view_bobbing);
put_f(&mut f, "gamma", self.gamma);
put_i(&mut f, "maxFps", self.max_fps as i32);
put_b(&mut f, "enableVsync", self.vsync);
put_b(&mut f, "fullscreen", self.fullscreen);
put_b(&mut f, "ao", self.smooth_lighting);
put_name(&mut f, "renderClouds", &self.clouds);
put_i(&mut f, "cloudRange", self.cloud_range);
put_i(&mut f, "particles", i32::from(self.particles));
put_f(&mut f, "entityDistanceScaling", self.entity_distance);
put_b(&mut f, "entityShadows", self.entity_shadows);
put_i(&mut f, "biomeBlendRadius", self.biome_blend);
put_name(&mut f, "graphicsPreset", &self.graphics_preset);
put_i(&mut f, "mipmapLevels", self.mipmap_levels);
put_i(&mut f, "weatherRadius", self.weather_radius);
put_f(&mut f, "chunkSectionFadeInTime", self.chunk_fade);
put_b(&mut f, "vignette", self.vignette);
put_b(&mut f, "showAutosaveIndicator", self.autosave_indicator);
put_b(&mut f, "cutoutLeaves", self.cutout_leaves);
put_b(&mut f, "improvedTransparency", self.improved_transparency);
put_i(&mut f, "attackIndicator", i32::from(self.attack_indicator));
put_name(&mut f, "inactivityFpsLimit", &self.inactivity_fps_limit);
put_i(
&mut f,
"prioritizeChunkUpdates",
i32::from(self.prioritize_chunk_updates),
);
put_i(&mut f, "menuBackgroundBlurriness", self.menu_blur);
put_b(&mut f, "invertXMouse", self.invert_x);
put_b(&mut f, "invertYMouse", self.invert_y);
put_f(
&mut f,
"mouseWheelSensitivity",
self.mouse_wheel_sensitivity,
);
put_b(&mut f, "discrete_mouse_scroll", self.discrete_scroll);
put_b(&mut f, "toggleCrouch", self.toggle_crouch);
put_b(&mut f, "toggleSprint", self.toggle_sprint);
put_b(&mut f, "toggleAttack", self.toggle_attack);
put_b(&mut f, "toggleUse", self.toggle_use);
put_i(&mut f, "sprintWindow", self.sprint_window);
put_b(&mut f, "autoJump", self.auto_jump);
put_s(&mut f, "lang", &self.language);
put_b(&mut f, "forceUnicodeFont", self.force_unicode);
put_b(&mut f, "japaneseGlyphVariants", self.japanese_glyphs);
put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility));
put_b(&mut f, "chatColors", self.chat_colors);
put_b(&mut f, "chatLinks", self.chat_links);
put_f(&mut f, "chatOpacity", self.chat_opacity);
put_f(
&mut f,
"textBackgroundOpacity",
self.text_background_opacity,
);
put_f(&mut f, "chatScale", self.chat_scale);
put_f(&mut f, "chatWidth", self.chat_width);
put_f(&mut f, "chatHeightFocused", self.chat_height_focused);
put_f(&mut f, "chatHeightUnfocused", self.chat_height_unfocused);
put_f(&mut f, "chatLineSpacing", self.chat_line_spacing);
put_b(&mut f, "autoSuggestions", self.auto_suggestions);
put_b(&mut f, "reducedDebugInfo", self.reduced_debug_info);
put_b(&mut f, "highContrast", self.high_contrast);
put_b(&mut f, "showSubtitles", self.show_subtitles);
put_f(
&mut f,
"notificationDisplayTime",
self.notification_display_time,
);
put_name(
&mut f,
"mainHand",
if self.main_hand_left { "left" } else { "right" },
);
if self.resource_packs != f.list("resourcePacks") {
f.set("resourcePacks", V::List(self.resource_packs.clone()));
}
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
for (k, v) in lines {
out.push_str(&format!("{k}:{v}\n"));
for (name, key) in self.keys.saved() {
put_s(&mut f, &format!("key_{name}"), &key);
}
out
f
}
/// The `options.txt` text (Options.save).
pub fn serialize(&self) -> String {
self.to_file().serialize()
}
pub fn save(&self, path: &Path) {
let _ = fs::write(path, self.serialize());
@@ -538,7 +506,8 @@ mod tests {
let out = s.serialize();
assert!(out.starts_with("version:"));
assert!(out.contains("\nkey_key.jump:key.keyboard.j\n"));
assert!(out.contains("\nsomeFutureOption:42\n"));
// Options.save writes only the options it knows.
assert!(!out.contains("someFutureOption"));
assert!(out.contains("\nrenderClouds:\"fast\"\n"));
let again = Settings::parse(&out);
assert_eq!(again.fov, 90.0);
@@ -555,10 +524,10 @@ mod tests {
let d = Settings::parse("");
assert!(!d.show_subtitles);
assert_eq!(d.notification_display_time, 1.0);
// The multiplier stays within the slider's range.
// Codec.doubleRange(0.5, 10.0) rejects other values; the default stays.
assert_eq!(
Settings::parse("notificationDisplayTime:50\n").notification_display_time,
10.0
1.0
);
}
}
+48 -4
View File
@@ -8,6 +8,7 @@ use crate::{
mesher::{MeshTables, Mesher, Region, SectionMesh, borrow},
world::World,
};
use horizon_core::biome::BiomeZoom;
use std::{
collections::{BinaryHeap, HashMap, HashSet},
sync::{
@@ -40,12 +41,21 @@ pub trait ChunkGenerator: Send + Sync + 'static {
fn decorate(&self, _worker: &mut Self::Worker, _region: &mut [Proto; 9]) {}
fn finish(&self, proto: Proto) -> Chunk;
}
/// Per-job mesher inputs that change with the dimension or the options.
#[derive(Clone, Copy)]
struct MeshSettings {
nether: bool,
zoom: BiomeZoom,
blend_radius: i32,
smooth_lighting: bool,
cutout_leaves: bool,
}
enum Job {
Generate(i32, i32),
Decorate(i32, i32, Box<[Proto; 9]>),
Finish(Proto),
Light(i32, i32, Box<Region>, u64, bool),
Mesh(i32, i32, i32, Box<Region>, u64, bool),
Mesh(i32, i32, i32, Box<Region>, u64, MeshSettings),
}
pub enum Done {
Generated(Chunk),
@@ -111,6 +121,12 @@ pub struct Streaming {
/// Dimension flags: sky light, Nether face shading.
pub sky_light: bool,
pub nether_shading: bool,
/// `BiomeManager`'s zoom seed (the hashed world seed) and `biomeBlendRadius`.
pub biome_zoom: BiomeZoom,
pub biome_blend: i32,
/// The `ao` and `cutoutLeaves` options.
pub smooth_lighting: bool,
pub cutout_leaves: bool,
/// Incremental relighting of block edits on lit chunks (see `light::relight`).
light_tables: Arc<LightTables>,
/// Applied edits by sequence, replayed onto light jobs snapshotted before them.
@@ -158,6 +174,10 @@ impl Streaming {
let mut worker = generator.worker();
let mut mesher = Mesher {
nether_shading: false,
zoom: BiomeZoom::new(0),
blend_radius: 2,
smooth_lighting: true,
cutout_leaves: true,
assets: &context.assets,
tables: &context.tables,
biomes: &context.biomes,
@@ -192,8 +212,12 @@ impl Streaming {
light_chunk(&borrow(&region), &context.light, sky),
seq,
),
Job::Mesh(x, sy, z, region, seq, nether) => {
mesher.nether_shading = nether;
Job::Mesh(x, sy, z, region, seq, settings) => {
mesher.nether_shading = settings.nether;
mesher.zoom = settings.zoom;
mesher.blend_radius = settings.blend_radius;
mesher.smooth_lighting = settings.smooth_lighting;
mesher.cutout_leaves = settings.cutout_leaves;
Done::Meshed(x, sy, z, mesher.mesh(&borrow(&region), sy), seq)
}
};
@@ -227,6 +251,10 @@ impl Streaming {
paused: false,
sky_light: true,
nether_shading: false,
biome_zoom: BiomeZoom::new(0),
biome_blend: 2,
smooth_lighting: true,
cutout_leaves: true,
light_tables,
light_log: Vec::new(),
light_edit_sequence: 0,
@@ -333,6 +361,9 @@ impl Streaming {
world
.block_entities
.extend(std::mem::take(&mut chunk.block_entities));
world
.block_names
.extend(std::mem::take(&mut chunk.block_names));
let entities = std::mem::take(&mut chunk.entities);
if !entities.is_empty() {
world.loaded_entities.push(((chunk.x, chunk.z), entities));
@@ -599,7 +630,20 @@ impl Streaming {
self.meshing.insert((x, sy, z), self.sequence);
self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 },
Job::Mesh(x, sy, z, region, self.sequence, self.nether_shading),
Job::Mesh(
x,
sy,
z,
region,
self.sequence,
MeshSettings {
nether: self.nether_shading,
zoom: self.biome_zoom,
blend_radius: self.biome_blend,
smooth_lighting: self.smooth_lighting,
cutout_leaves: self.cutout_leaves,
},
),
);
}
(uploads, removed)

Some files were not shown because too many files have changed in this diff Show More