Merge main into agent branch
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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(®ion);
|
||||
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(®ion);
|
||||
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,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;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
+1233
-189
File diff suppressed because it is too large
Load Diff
@@ -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());
|
||||
}
|
||||
@@ -571,8 +565,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 +590,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")))
|
||||
|
||||
+749
-161
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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) = §ion.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;
|
||||
|
||||
@@ -79,6 +79,7 @@ impl Game<'_> {
|
||||
let ally = matches!(
|
||||
m.species(),
|
||||
Species::Evoker
|
||||
| Species::Illusioner
|
||||
| Species::Vex
|
||||
| Species::Pillager
|
||||
| Species::Vindicator
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 §ion.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,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -919,16 +919,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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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\"");
|
||||
}
|
||||
}
|
||||
@@ -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"),
|
||||
];
|
||||
@@ -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",
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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 §ion.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 {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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)),
|
||||
});
|
||||
|
||||
@@ -27,6 +27,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 +453,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 +492,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 +893,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 +1230,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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ fn raider(s: Species) -> bool {
|
||||
| Species::Vindicator
|
||||
| Species::Witch
|
||||
| Species::Evoker
|
||||
| Species::Illusioner
|
||||
| Species::Ravager
|
||||
)
|
||||
}
|
||||
@@ -30,6 +31,7 @@ fn targets(m: &mut Mob, villagers_seen: bool) {
|
||||
Species::Vindicator,
|
||||
Species::Witch,
|
||||
Species::Evoker,
|
||||
Species::Illusioner,
|
||||
Species::Vex,
|
||||
Species::Ravager,
|
||||
];
|
||||
@@ -95,7 +97,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 {
|
||||
@@ -542,6 +544,7 @@ enum ArmPose {
|
||||
Attacking,
|
||||
CrossbowHold,
|
||||
CrossbowCharge,
|
||||
Bow,
|
||||
}
|
||||
/// `Pillager` / `Vindicator.getArmPose`.
|
||||
fn arm_pose(m: &Mob) -> ArmPose {
|
||||
@@ -557,6 +560,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,7 +582,11 @@ 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) {
|
||||
@@ -600,6 +610,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
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);
|
||||
// IllagerModel hides the hat; the illusioner's renderer shows it.
|
||||
if m.species() != Species::Illusioner {
|
||||
hide(p, "hat");
|
||||
}
|
||||
let pose = arm_pose(m);
|
||||
match pose {
|
||||
ArmPose::Attacking => {
|
||||
@@ -638,6 +652,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -57,6 +57,7 @@ pub fn is_raider(s: Species) -> bool {
|
||||
Species::Pillager
|
||||
| Species::Vindicator
|
||||
| Species::Evoker
|
||||
| Species::Illusioner
|
||||
| Species::Witch
|
||||
| Species::Ravager
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@ pub fn register(m: &mut Mob) {
|
||||
Species::Pillager,
|
||||
Species::Vindicator,
|
||||
Species::Evoker,
|
||||
Species::Illusioner,
|
||||
Species::Witch,
|
||||
Species::Ravager,
|
||||
];
|
||||
@@ -180,7 +181,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 {
|
||||
|
||||
@@ -822,10 +822,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)));
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
@@ -1435,6 +1450,7 @@ impl Def {
|
||||
| S::ElderGuardian
|
||||
| S::Shulker
|
||||
| S::Evoker
|
||||
| S::Illusioner
|
||||
| S::Vex
|
||||
| S::Ravager
|
||||
| S::Wither
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -32,6 +32,7 @@ pub fn register(m: &mut Mob) {
|
||||
Species::Pillager,
|
||||
Species::Vindicator,
|
||||
Species::Evoker,
|
||||
Species::Illusioner,
|
||||
Species::Witch,
|
||||
Species::Vex,
|
||||
];
|
||||
|
||||
@@ -63,6 +63,7 @@ pub fn register(m: &mut Mob) {
|
||||
Species::Pillager,
|
||||
Species::Vindicator,
|
||||
Species::Evoker,
|
||||
Species::Illusioner,
|
||||
Species::Ravager,
|
||||
Species::Zoglin,
|
||||
];
|
||||
@@ -1217,7 +1218,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,
|
||||
|
||||
@@ -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))));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
(
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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,18 +559,21 @@ 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 {
|
||||
@@ -558,7 +585,7 @@ impl Settings {
|
||||
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 +699,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;
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -670,33 +648,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 §ion.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 +675,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 +729,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 +880,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 +922,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 +945,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 +970,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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(®ion), &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(®ion), 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)
|
||||
|
||||
@@ -59,12 +59,13 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
|
||||
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
|
||||
}
|
||||
@fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4<f32> {
|
||||
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color;
|
||||
if color.a < 0.5 { discard; }
|
||||
// Bit 31 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
|
||||
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color;
|
||||
if color.a < 0.5 && (in.layer & 0x80000000u) == 0u { discard; }
|
||||
return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
|
||||
}
|
||||
@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4<f32> {
|
||||
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color;
|
||||
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color;
|
||||
if color.a < 0.01 { discard; }
|
||||
return apply_fog(color, in.spherical, in.cylindrical);
|
||||
}
|
||||
|
||||
@@ -76,7 +76,12 @@ impl ChunkGenerator for TestTerrain {
|
||||
impl TestTerrain {
|
||||
fn generate(&self, _: &mut (), cx: i32, cz: i32) -> Chunk {
|
||||
let mut chunk = Chunk::empty(cx, cz);
|
||||
chunk.biomes = std::sync::Arc::new(vec![self.plains; chunk.biomes.len()]);
|
||||
for s in &mut chunk.sections {
|
||||
std::sync::Arc::make_mut(s).biomes = horizon_core::paletted::PalettedContainer::new(
|
||||
crate::chunk::BIOME_STRATEGY,
|
||||
u32::from(self.plains),
|
||||
);
|
||||
}
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//! aquifers, surface rules, carvers and placed features) to chunk streaming.
|
||||
use crate::{
|
||||
biome::Biomes,
|
||||
chunk::{Chunk, HEIGHT, MIN_Y},
|
||||
chunk::{BIOME_STRATEGY, Chunk, HEIGHT, MIN_Y, SECTIONS, Section},
|
||||
streaming::{ChunkGenerator, Proto},
|
||||
};
|
||||
use horizon_core::position::ChunkPos;
|
||||
use horizon_core::{paletted::PalettedContainer, position::ChunkPos};
|
||||
use horizon_world::{
|
||||
registry::BlockRegistry,
|
||||
worldgen::generator::{GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk},
|
||||
@@ -177,15 +177,27 @@ impl ChunkGenerator for VanillaTerrain {
|
||||
chunk.terrain.min_y().max(MIN_Y),
|
||||
(chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT),
|
||||
);
|
||||
for y in lo..hi {
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let id = chunk.block(bx + x, y, bz + z).0 as u16;
|
||||
if id != 0 {
|
||||
out.set(x, y, z, id);
|
||||
let mut values = Box::new([0u16; 4096]);
|
||||
for si in 0..SECTIONS as i32 {
|
||||
let base = MIN_Y + si * 16;
|
||||
if base + 16 <= lo || base >= hi {
|
||||
continue;
|
||||
}
|
||||
values.fill(0);
|
||||
let mut any = false;
|
||||
for y in base.max(lo)..(base + 16).min(hi) {
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let id = chunk.block(bx + x, y, bz + z).0 as u16;
|
||||
values[((y & 15) << 8 | z << 4 | x) as usize] = id;
|
||||
any |= id != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if any {
|
||||
Arc::make_mut(&mut out.sections[si as usize]).blocks =
|
||||
Section::from_blocks(&values);
|
||||
}
|
||||
}
|
||||
let base_section = chunk.terrain.min_y() >> 4;
|
||||
for (i, marks) in chunk.terrain.postprocessing().iter().enumerate() {
|
||||
@@ -199,19 +211,17 @@ impl ChunkGenerator for VanillaTerrain {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut biomes = vec![0u16; 16 * (HEIGHT as usize / 4)];
|
||||
for qy in 0..HEIGHT / 4 {
|
||||
for qz in 0..4 {
|
||||
for qx in 0..4 {
|
||||
let y = (MIN_Y + qy * 4).clamp(lo, hi - 1);
|
||||
let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4);
|
||||
let index = id.0 as usize;
|
||||
biomes[(qy * 16 + qz * 4 + qx) as usize] =
|
||||
self.biome_map.get(index).copied().unwrap_or(0);
|
||||
}
|
||||
for si in 0..SECTIONS as i32 {
|
||||
let mut cells = [0u32; 64];
|
||||
for (j, cell) in cells.iter_mut().enumerate() {
|
||||
let (qx, qz, qy) = (j as i32 & 3, (j as i32 >> 2) & 3, si * 4 + (j as i32 >> 4));
|
||||
let y = (MIN_Y + qy * 4).clamp(lo, hi - 1);
|
||||
let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4);
|
||||
*cell = u32::from(self.biome_map.get(id.0 as usize).copied().unwrap_or(0));
|
||||
}
|
||||
Arc::make_mut(&mut out.sections[si as usize]).biomes =
|
||||
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
|
||||
}
|
||||
out.biomes = Arc::new(biomes);
|
||||
out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref());
|
||||
out.structure_refs = chunk
|
||||
.structures()
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Window sizing and frame pacing of 26.3: `Window.calculateScale` and
|
||||
//! `setGuiScale`, `MouseHandler`'s scaled positions, `FramerateLimitTracker`,
|
||||
//! `FramerateLimiter` and the vsync present-mode choice.
|
||||
|
||||
/// `Window.calculateScale`: the largest scale that leaves at least 320x240
|
||||
/// GUI pixels, capped by `max_scale` (0 = automatic); an odd result is bumped
|
||||
/// to even when unicode is enforced.
|
||||
pub fn calculate_scale(framebuffer: [i32; 2], max_scale: i32, enforce_unicode: bool) -> i32 {
|
||||
let [width, height] = framebuffer;
|
||||
let mut scale = 1;
|
||||
while scale != max_scale
|
||||
&& scale < width
|
||||
&& scale < height
|
||||
&& width / (scale + 1) >= 320
|
||||
&& height / (scale + 1) >= 240
|
||||
{
|
||||
scale += 1;
|
||||
}
|
||||
if enforce_unicode && scale % 2 != 0 {
|
||||
scale += 1;
|
||||
}
|
||||
scale
|
||||
}
|
||||
|
||||
/// `Window.setGuiScale`: the GUI-scaled size of a framebuffer.
|
||||
pub fn gui_scaled_size(framebuffer: [i32; 2], gui_scale: i32) -> [i32; 2] {
|
||||
let scaled = |v: i32| (f64::from(v) / f64::from(gui_scale)).ceil() as i32;
|
||||
[scaled(framebuffer[0]), scaled(framebuffer[1])]
|
||||
}
|
||||
|
||||
/// `MouseHandler.getScaledXPos`/`getScaledYPos`.
|
||||
pub fn scaled_pos(pos: f64, gui_scaled: i32, screen: i32) -> f64 {
|
||||
pos * f64::from(gui_scaled) / f64::from(screen)
|
||||
}
|
||||
|
||||
/// `InactivityFpsLimit`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum InactivityFpsLimit {
|
||||
Minimized,
|
||||
Afk,
|
||||
}
|
||||
|
||||
/// `FramerateLimitTracker.FramerateThrottleReason`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ThrottleReason {
|
||||
None,
|
||||
WindowIconified,
|
||||
LongAfk,
|
||||
ShortAfk,
|
||||
OutOfLevelMenu,
|
||||
}
|
||||
|
||||
/// What `FramerateLimitTracker` looks at.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FrameContext {
|
||||
pub inactivity: InactivityFpsLimit,
|
||||
pub iconified: bool,
|
||||
pub focused: bool,
|
||||
pub exclusive_fullscreen: bool,
|
||||
pub now_ms: i64,
|
||||
pub latest_input_ms: i64,
|
||||
pub has_level: bool,
|
||||
pub has_screen: bool,
|
||||
pub has_overlay: bool,
|
||||
}
|
||||
|
||||
/// `getThrottleReason`.
|
||||
pub fn throttle_reason(c: FrameContext) -> ThrottleReason {
|
||||
if !c.iconified && (c.focused || !c.exclusive_fullscreen) {
|
||||
if c.inactivity == InactivityFpsLimit::Afk {
|
||||
let afk = c.now_ms - c.latest_input_ms;
|
||||
if afk > 600_000 {
|
||||
return ThrottleReason::LongAfk;
|
||||
}
|
||||
if afk > 60_000 {
|
||||
return ThrottleReason::ShortAfk;
|
||||
}
|
||||
}
|
||||
if c.has_level || (!c.has_screen && !c.has_overlay) {
|
||||
ThrottleReason::None
|
||||
} else {
|
||||
ThrottleReason::OutOfLevelMenu
|
||||
}
|
||||
} else {
|
||||
ThrottleReason::WindowIconified
|
||||
}
|
||||
}
|
||||
|
||||
/// `getFramerateLimit`.
|
||||
pub fn framerate_limit(option_limit: i32, c: FrameContext) -> i32 {
|
||||
match throttle_reason(c) {
|
||||
ThrottleReason::None => option_limit,
|
||||
ThrottleReason::WindowIconified | ThrottleReason::LongAfk => 10,
|
||||
ThrottleReason::ShortAfk => option_limit.min(30),
|
||||
ThrottleReason::OutOfLevelMenu => 60,
|
||||
}
|
||||
}
|
||||
|
||||
/// `isHeavilyThrottled`.
|
||||
pub fn heavily_throttled(reason: ThrottleReason) -> bool {
|
||||
matches!(
|
||||
reason,
|
||||
ThrottleReason::WindowIconified | ThrottleReason::LongAfk
|
||||
)
|
||||
}
|
||||
|
||||
/// Present modes the renderer can choose between.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PresentMode {
|
||||
Fifo,
|
||||
Mailbox,
|
||||
Immediate,
|
||||
}
|
||||
|
||||
/// `GpuSurface.PresentMode.getSupportedVsyncMode`: vsync means Fifo only,
|
||||
/// otherwise the first of Immediate, Mailbox, Fifo that is supported.
|
||||
pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option<PresentMode> {
|
||||
let preferred: &[PresentMode] = if vsync {
|
||||
&[PresentMode::Fifo]
|
||||
} else {
|
||||
&[
|
||||
PresentMode::Immediate,
|
||||
PresentMode::Mailbox,
|
||||
PresentMode::Fifo,
|
||||
]
|
||||
};
|
||||
preferred.iter().copied().find(|m| supported.contains(m))
|
||||
}
|
||||
|
||||
/// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep
|
||||
/// and spin decisions are testable.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FramerateLimiter {
|
||||
last_frame_time: i64,
|
||||
average_overshoot_ns: i64,
|
||||
last_framerate_limit: i32,
|
||||
}
|
||||
|
||||
/// Time source of the limiter.
|
||||
pub trait LimiterClock {
|
||||
fn nanos(&mut self) -> i64;
|
||||
/// `LockSupport.parkNanos`.
|
||||
fn park(&mut self, nanos: i64);
|
||||
/// `Thread.onSpinWait`.
|
||||
fn spin(&mut self);
|
||||
}
|
||||
|
||||
impl FramerateLimiter {
|
||||
pub fn new(now_ns: i64) -> Self {
|
||||
Self {
|
||||
last_frame_time: now_ns,
|
||||
average_overshoot_ns: 0,
|
||||
last_framerate_limit: 0,
|
||||
}
|
||||
}
|
||||
pub fn limit_display_fps(&mut self, framerate_limit: i32, clock: &mut impl LimiterClock) {
|
||||
let target_time_per_frame = 1_000_000_000 / i64::from(framerate_limit);
|
||||
let target_time_ns = self.last_frame_time + target_time_per_frame;
|
||||
if framerate_limit != self.last_framerate_limit {
|
||||
self.average_overshoot_ns = 0;
|
||||
self.last_framerate_limit = framerate_limit;
|
||||
}
|
||||
loop {
|
||||
let remaining = target_time_ns - clock.nanos();
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
}
|
||||
if remaining > self.average_overshoot_ns + 500_000 {
|
||||
let sleep_start = clock.nanos();
|
||||
let expected = remaining - self.average_overshoot_ns - 500_000;
|
||||
clock.park(expected);
|
||||
let duration = clock.nanos() - sleep_start;
|
||||
let overshoot = duration - expected;
|
||||
if overshoot > 0 && overshoot < 25_000_000 {
|
||||
self.average_overshoot_ns =
|
||||
(0.1 * overshoot as f64 + 0.9 * self.average_overshoot_ns as f64) as i64;
|
||||
self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000);
|
||||
}
|
||||
} else {
|
||||
clock.spin();
|
||||
}
|
||||
}
|
||||
self.last_frame_time = clock.nanos();
|
||||
}
|
||||
pub fn last_frame_time(&self) -> i64 {
|
||||
self.last_frame_time
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Virtual {
|
||||
now: i64,
|
||||
oversleep: i64,
|
||||
}
|
||||
impl LimiterClock for Virtual {
|
||||
fn nanos(&mut self) -> i64 {
|
||||
self.now
|
||||
}
|
||||
fn park(&mut self, nanos: i64) {
|
||||
self.now += nanos + self.oversleep;
|
||||
}
|
||||
fn spin(&mut self) {
|
||||
self.now += 1000;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_matches_the_320_by_240_rule() {
|
||||
assert_eq!(calculate_scale([854, 480], 0, false), 2);
|
||||
assert_eq!(calculate_scale([1920, 1080], 0, false), 4);
|
||||
assert_eq!(calculate_scale([1920, 1080], 3, false), 3);
|
||||
assert_eq!(calculate_scale([1920, 1080], 3, true), 4);
|
||||
assert_eq!(gui_scaled_size([1921, 1081], 4), [481, 271]);
|
||||
}
|
||||
#[test]
|
||||
fn limiter_paces_frames_at_the_target() {
|
||||
let mut limiter = FramerateLimiter::new(0);
|
||||
let mut clock = Virtual {
|
||||
now: 1_000_000,
|
||||
oversleep: 200_000,
|
||||
};
|
||||
limiter.limit_display_fps(100, &mut clock);
|
||||
assert!(clock.now >= 10_000_000);
|
||||
assert!(clock.now < 10_000_000 + 1_000_000);
|
||||
}
|
||||
#[test]
|
||||
fn vsync_only_uses_fifo() {
|
||||
let all = [
|
||||
PresentMode::Mailbox,
|
||||
PresentMode::Fifo,
|
||||
PresentMode::Immediate,
|
||||
];
|
||||
assert_eq!(vsync_present_mode(&all, true), Some(PresentMode::Fifo));
|
||||
assert_eq!(
|
||||
vsync_present_mode(&all, false),
|
||||
Some(PresentMode::Immediate)
|
||||
);
|
||||
assert_eq!(
|
||||
vsync_present_mode(&[PresentMode::Fifo], false),
|
||||
Some(PresentMode::Fifo)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ pub struct World {
|
||||
/// Chunks changed since the last save.
|
||||
pub modified: HashSet<(i32, i32)>,
|
||||
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
|
||||
/// `BaseContainerBlockEntity.name`: custom names of container block entities.
|
||||
pub block_names: HashMap<(i32, i32, i32), String>,
|
||||
/// States (by id) whose writes are recorded in `watched_writes` (sculk
|
||||
/// blocks, which need a block entity).
|
||||
pub watched: Vec<bool>,
|
||||
@@ -114,6 +116,7 @@ impl World {
|
||||
loaded_entities: Vec::new(),
|
||||
modified: HashSet::new(),
|
||||
block_entities: HashMap::new(),
|
||||
block_names: HashMap::new(),
|
||||
watched: Vec::new(),
|
||||
watched_writes: Vec::new(),
|
||||
inhabited: HashMap::new(),
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Text transport for the PalettedContainer comparison: replays scripted edits
|
||||
//! and prints the same hashes as `VanillaPalettedContainerOracle`.
|
||||
use horizon_core::paletted::{PalettedContainer, Strategy};
|
||||
use std::{
|
||||
fs,
|
||||
io::{self, Write},
|
||||
};
|
||||
const BASIS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
fn fnv(h: u64, b: u8) -> u64 {
|
||||
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
|
||||
}
|
||||
fn hash_bytes(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(BASIS, |h, &b| fnv(h, b))
|
||||
}
|
||||
fn varint(out: &mut Vec<u8>, mut v: u32) {
|
||||
while v >= 0x80 {
|
||||
out.push((v & 0x7F) as u8 | 0x80);
|
||||
v >>= 7;
|
||||
}
|
||||
out.push(v as u8);
|
||||
}
|
||||
/// `PalettedContainer.write`.
|
||||
fn write(c: &PalettedContainer) -> Vec<u8> {
|
||||
let (bits, palette, words) = c.to_wire();
|
||||
let mut out = vec![bits];
|
||||
if bits == 0 {
|
||||
varint(&mut out, palette[0]);
|
||||
} else if !palette.is_empty() {
|
||||
varint(&mut out, palette.len() as u32);
|
||||
for p in palette {
|
||||
varint(&mut out, p);
|
||||
}
|
||||
}
|
||||
for w in words {
|
||||
out.extend(w.to_be_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `PalettedContainer.read` for the leading byte, palette and longs.
|
||||
fn read(strategy: Strategy, bytes: &[u8]) -> PalettedContainer {
|
||||
let mut at = 1;
|
||||
let mut varint = || {
|
||||
let (mut v, mut shift) = (0u32, 0);
|
||||
loop {
|
||||
let b = bytes[at];
|
||||
at += 1;
|
||||
v |= u32::from(b & 0x7F) << shift;
|
||||
if b & 0x80 == 0 {
|
||||
return v;
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
};
|
||||
let bits = bytes[0];
|
||||
let palette = if bits == 0 {
|
||||
vec![varint()]
|
||||
} else if strategy.wire_has_palette(bits) {
|
||||
let n = varint();
|
||||
(0..n).map(|_| varint()).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let words = bytes[at..]
|
||||
.chunks_exact(8)
|
||||
.map(|c| u64::from_be_bytes(c.try_into().unwrap()))
|
||||
.collect();
|
||||
PalettedContainer::from_wire(strategy, bits, palette, words).unwrap()
|
||||
}
|
||||
fn wire(c: &PalettedContainer) -> String {
|
||||
let bytes = write(c);
|
||||
format!("{}:{}", bytes.len(), hash_bytes(&bytes) as i64)
|
||||
}
|
||||
fn values(c: &PalettedContainer) -> i64 {
|
||||
let mut h = BASIS;
|
||||
for i in 0..c.strategy().entries() {
|
||||
for b in c.get(i).to_le_bytes() {
|
||||
h = fnv(h, b);
|
||||
}
|
||||
}
|
||||
h as i64
|
||||
}
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut out = io::BufWriter::new(fs::File::create(&args[2])?);
|
||||
for line in fs::read_to_string(&args[1])?.lines() {
|
||||
let t: Vec<&str> = line.split_whitespace().collect();
|
||||
let strategy = if t[1] == "blocks" {
|
||||
Strategy::blocks(16)
|
||||
} else {
|
||||
Strategy::biomes(7)
|
||||
};
|
||||
let mut c = PalettedContainer::new(strategy, t[2].parse()?);
|
||||
let every: usize = t[3].parse()?;
|
||||
let (mut olds, mut n) = (BASIS, 0usize);
|
||||
let mut checkpoints = Vec::new();
|
||||
for pair in t[4..].chunks(2) {
|
||||
let old = c.set(pair[0].parse()?, pair[1].parse()?);
|
||||
for b in old.to_le_bytes() {
|
||||
olds = fnv(olds, b);
|
||||
}
|
||||
n += 1;
|
||||
if n % every == 0 {
|
||||
checkpoints.push(wire(&c));
|
||||
}
|
||||
}
|
||||
let reread = read(strategy, &write(&c));
|
||||
let packed = c.pack();
|
||||
let storage = packed.data.as_ref().map_or(BASIS, |data| {
|
||||
data.iter().flat_map(|w| w.to_le_bytes()).fold(BASIS, fnv)
|
||||
});
|
||||
let palette: Vec<String> = packed.palette.iter().map(u32::to_string).collect();
|
||||
let loaded = PalettedContainer::from_packed(
|
||||
strategy,
|
||||
packed.palette.clone(),
|
||||
packed.data.as_deref(),
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
"{} {} cp={} bits={} final={} values={} read={}/{} packed={}/{}/{} loaded={}/{}",
|
||||
t[0],
|
||||
olds as i64,
|
||||
checkpoints.join(","),
|
||||
c.bits(),
|
||||
wire(&c),
|
||||
values(&c),
|
||||
values(&reread),
|
||||
wire(&reread),
|
||||
packed.bits,
|
||||
storage as i64,
|
||||
palette.join(","),
|
||||
values(&loaded),
|
||||
wire(&loaded),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod carving;
|
||||
pub mod density;
|
||||
pub mod geometry;
|
||||
pub mod noise;
|
||||
pub mod paletted;
|
||||
pub mod position;
|
||||
pub mod random;
|
||||
pub mod storage;
|
||||
|
||||
@@ -0,0 +1,744 @@
|
||||
//! Resident `PalettedContainer` of Java Edition 26.3: single-value, linear and
|
||||
//! hash-map palettes with vanilla's bit-width thresholds, and the global
|
||||
//! palette beyond them, over `SimpleBitStorage` words (values never span
|
||||
//! longs). One container type serves blocks (16^3 entries) and biomes (4^3).
|
||||
//!
|
||||
//! Growth follows `PalettedContainer.onResize`: a full palette asks for one
|
||||
//! more bit, the new configuration is built by re-adding the distinct values
|
||||
//! in index order, and the value that did not fit is added last. Palettes
|
||||
//! never shrink while resident; `pack` writes the canonical saved form.
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// `Strategy.createForBlockStates`: 4096 entries, linear palettes up to 4
|
||||
/// bits and hash-map palettes from 5 to 8.
|
||||
Blocks,
|
||||
/// `Strategy.createForBiomes`: 64 entries, linear palettes up to 3 bits.
|
||||
Biomes,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Strategy {
|
||||
pub kind: Kind,
|
||||
/// `ceillog2` of the registry size: the width of the global palette.
|
||||
pub global_bits: u8,
|
||||
}
|
||||
/// `getConfigurationForBitCount`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Config {
|
||||
Single,
|
||||
/// Palette of up to `1 << bits` entries, stored in `bits` bits.
|
||||
List(u8),
|
||||
Global,
|
||||
}
|
||||
impl Strategy {
|
||||
pub const fn blocks(global_bits: u8) -> Self {
|
||||
Self {
|
||||
kind: Kind::Blocks,
|
||||
global_bits,
|
||||
}
|
||||
}
|
||||
pub const fn biomes(global_bits: u8) -> Self {
|
||||
Self {
|
||||
kind: Kind::Biomes,
|
||||
global_bits,
|
||||
}
|
||||
}
|
||||
pub const fn entries(self) -> usize {
|
||||
match self.kind {
|
||||
Kind::Blocks => 4096,
|
||||
Kind::Biomes => 64,
|
||||
}
|
||||
}
|
||||
fn config(self, bits: u8) -> Config {
|
||||
match (self.kind, bits) {
|
||||
(_, 0) => Config::Single,
|
||||
(Kind::Blocks, 1..=4) => Config::List(4),
|
||||
(Kind::Blocks, 5..=8) => Config::List(bits),
|
||||
(Kind::Biomes, 1..=3) => Config::List(bits),
|
||||
_ => Config::Global,
|
||||
}
|
||||
}
|
||||
/// Whether a container written with leading byte `bits` lists its palette
|
||||
/// (all but the global one).
|
||||
pub fn wire_has_palette(self, bits: u8) -> bool {
|
||||
self.config(bits) != Config::Global
|
||||
}
|
||||
/// Bits of the storage a configuration keeps in memory.
|
||||
fn storage_bits(self, config: Config) -> u8 {
|
||||
match config {
|
||||
Config::Single => 0,
|
||||
Config::List(bits) => bits,
|
||||
Config::Global => self.global_bits,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Mth.ceillog2`.
|
||||
pub fn ceil_log2(n: usize) -> u8 {
|
||||
if n <= 1 {
|
||||
0
|
||||
} else {
|
||||
(usize::BITS - (n - 1).leading_zeros()) as u8
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PaletteError {
|
||||
/// A palette bigger than its configuration allows, or empty.
|
||||
BadPalette { len: usize },
|
||||
/// Storage with the wrong number of longs.
|
||||
BadStorage { expected: usize, actual: usize },
|
||||
/// A stored index past the palette.
|
||||
BadIndex { index: u32, palette: usize },
|
||||
/// The declared bit count does not match the palette.
|
||||
BadBits { declared: u8, expected: u8 },
|
||||
}
|
||||
impl std::fmt::Display for PaletteError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for PaletteError {}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Palette {
|
||||
Single(u32),
|
||||
/// Linear and hash-map palettes alike: ids in insertion order.
|
||||
List(Vec<u32>),
|
||||
Global,
|
||||
}
|
||||
/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits] = ceil(2^20 /
|
||||
/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`.
|
||||
const MAGIC: [u32; 33] = {
|
||||
let mut table = [0; 33];
|
||||
let mut bits = 1;
|
||||
while bits <= 32 {
|
||||
let per = 64 / bits as u32;
|
||||
table[bits] = (1u32 << 20).div_ceil(per);
|
||||
bits += 1;
|
||||
}
|
||||
table
|
||||
};
|
||||
/// Words of `bits`-wide values: `entries.div_ceil(64 / bits)`.
|
||||
pub fn storage_len(bits: u8, entries: usize) -> usize {
|
||||
if bits == 0 {
|
||||
0
|
||||
} else {
|
||||
entries.div_ceil(64 / usize::from(bits))
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn locate(bits: u8, i: usize) -> (usize, u32) {
|
||||
if bits.is_power_of_two() {
|
||||
// 64 / bits is a power of two: shifts instead of the multiplication.
|
||||
let log = bits.trailing_zeros();
|
||||
let word = i >> (6 - log);
|
||||
(word, ((i & ((64 >> log) - 1)) as u32) << log)
|
||||
} else {
|
||||
let per = 64 / u32::from(bits);
|
||||
let word = (i as u32 * MAGIC[usize::from(bits)]) >> 20;
|
||||
(word as usize, (i as u32 - word * per) * u32::from(bits))
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn mask(bits: u8) -> u64 {
|
||||
(1u64 << bits) - 1
|
||||
}
|
||||
fn read(words: &[u64], bits: u8, i: usize) -> u32 {
|
||||
let (word, shift) = locate(bits, i);
|
||||
((words[word] >> shift) & mask(bits)) as u32
|
||||
}
|
||||
fn write(words: &mut [u64], bits: u8, i: usize, value: u32) {
|
||||
let (word, shift) = locate(bits, i);
|
||||
words[word] = (words[word] & !(mask(bits) << shift)) | (u64::from(value) << shift);
|
||||
}
|
||||
/// Words holding `ids` in `bits`-wide slots.
|
||||
fn pack_words(bits: u8, entries: usize, ids: impl Iterator<Item = u32>) -> Vec<u64> {
|
||||
let mut words = vec![0u64; storage_len(bits, entries)];
|
||||
for (i, id) in ids.enumerate() {
|
||||
write(&mut words, bits, i, id);
|
||||
}
|
||||
words
|
||||
}
|
||||
/// The saved form: distinct values in index order, and the packed indices
|
||||
/// when there is more than one value.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Packed {
|
||||
pub palette: Vec<u32>,
|
||||
/// Bits per index in `data` (0 when `data` is absent).
|
||||
pub bits: u8,
|
||||
pub data: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PalettedContainer {
|
||||
strategy: Strategy,
|
||||
bits: u8,
|
||||
palette: Palette,
|
||||
words: Vec<u64>,
|
||||
}
|
||||
impl PalettedContainer {
|
||||
/// `new PalettedContainer(initialValue, strategy)`.
|
||||
pub fn new(strategy: Strategy, value: u32) -> Self {
|
||||
Self {
|
||||
strategy,
|
||||
bits: 0,
|
||||
palette: Palette::Single(value),
|
||||
words: Vec::new(),
|
||||
}
|
||||
}
|
||||
pub fn strategy(&self) -> Strategy {
|
||||
self.strategy
|
||||
}
|
||||
/// Bits per stored index (`BitStorage.getBits`).
|
||||
pub fn bits(&self) -> u8 {
|
||||
self.bits
|
||||
}
|
||||
/// Entries in the palette (the global palette reports its bit capacity).
|
||||
pub fn palette_len(&self) -> usize {
|
||||
match &self.palette {
|
||||
Palette::Single(_) => 1,
|
||||
Palette::List(list) => list.len(),
|
||||
Palette::Global => 1 << self.bits.min(31),
|
||||
}
|
||||
}
|
||||
pub fn is_global(&self) -> bool {
|
||||
matches!(self.palette, Palette::Global)
|
||||
}
|
||||
#[inline]
|
||||
fn raw(&self, i: usize) -> usize {
|
||||
let (word, shift) = locate(self.bits, i);
|
||||
((self.words[word] >> shift) & mask(self.bits)) as usize
|
||||
}
|
||||
#[inline]
|
||||
pub fn get(&self, i: usize) -> u32 {
|
||||
match &self.palette {
|
||||
Palette::Single(value) => *value,
|
||||
Palette::List(list) => list[self.raw(i)],
|
||||
Palette::Global => self.raw(i) as u32,
|
||||
}
|
||||
}
|
||||
/// The value when every entry is equal, without the palette having to be
|
||||
/// minimal.
|
||||
pub fn uniform(&self) -> Option<u32> {
|
||||
match &self.palette {
|
||||
Palette::Single(value) => Some(*value),
|
||||
Palette::List(list) if list.len() == 1 => Some(list[0]),
|
||||
Palette::Global => self.all_equal(self.get(0)).then(|| self.get(0)),
|
||||
Palette::List(list) => {
|
||||
let first = list[self.raw(0)];
|
||||
self.all_equal(first).then_some(first)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Whether all entries equal `value`.
|
||||
pub fn is_uniform(&self, value: u32) -> bool {
|
||||
match &self.palette {
|
||||
Palette::Single(v) => *v == value,
|
||||
Palette::List(list) => match list.iter().position(|&v| v == value) {
|
||||
None => false,
|
||||
Some(_) if list.len() == 1 => true,
|
||||
Some(_) => self.all_equal(value),
|
||||
},
|
||||
Palette::Global => self.all_equal(value),
|
||||
}
|
||||
}
|
||||
fn all_equal(&self, value: u32) -> bool {
|
||||
let id = match &self.palette {
|
||||
Palette::Single(v) => return *v == value,
|
||||
Palette::List(list) => match list.iter().position(|&v| v == value) {
|
||||
Some(id) => id as u64,
|
||||
None => return false,
|
||||
},
|
||||
Palette::Global => u64::from(value),
|
||||
};
|
||||
let bits = usize::from(self.bits);
|
||||
let per = 64 / bits;
|
||||
let pattern = (0..per).fold(0u64, |word, slot| word | id << (slot * bits));
|
||||
let entries = self.strategy.entries();
|
||||
let full = entries / per;
|
||||
if self.words[..full].iter().any(|&w| w != pattern) {
|
||||
return false;
|
||||
}
|
||||
let tail = entries - full * per;
|
||||
tail == 0 || {
|
||||
let used = (1u64 << (tail * bits)) - 1;
|
||||
self.words[full] & used == pattern & used
|
||||
}
|
||||
}
|
||||
/// `getAndSet`: stores `value` and returns the previous one.
|
||||
pub fn set(&mut self, i: usize, value: u32) -> u32 {
|
||||
let id = self.id_for(value);
|
||||
match &self.palette {
|
||||
Palette::Single(old) => *old,
|
||||
Palette::List(list) => {
|
||||
let old = read(&self.words, self.bits, i) as usize;
|
||||
write(&mut self.words, self.bits, i, id as u32);
|
||||
list[old]
|
||||
}
|
||||
Palette::Global => {
|
||||
let old = read(&self.words, self.bits, i);
|
||||
write(&mut self.words, self.bits, i, id as u32);
|
||||
old
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Palette.idFor`, growing the container when the palette is full.
|
||||
fn id_for(&mut self, value: u32) -> usize {
|
||||
match &mut self.palette {
|
||||
Palette::Single(v) if *v == value => 0,
|
||||
Palette::Single(_) => self.resize(1, value),
|
||||
Palette::List(list) => {
|
||||
if let Some(id) = list.iter().position(|&v| v == value) {
|
||||
id
|
||||
} else if list.len() < 1 << self.bits {
|
||||
list.push(value);
|
||||
list.len() - 1
|
||||
} else {
|
||||
self.resize(self.bits + 1, value)
|
||||
}
|
||||
}
|
||||
Palette::Global => value as usize,
|
||||
}
|
||||
}
|
||||
/// `PalettedContainer.onResize`: rebuild with the configuration for
|
||||
/// `bits`, then add `last` and return its id.
|
||||
fn resize(&mut self, bits: u8, last: u32) -> usize {
|
||||
let strategy = self.strategy;
|
||||
let config = strategy.config(bits);
|
||||
let storage_bits = strategy.storage_bits(config);
|
||||
let entries = strategy.entries();
|
||||
let mut palette = match config {
|
||||
Config::Single => Palette::Single(last),
|
||||
Config::List(_) => Palette::List(Vec::new()),
|
||||
Config::Global => Palette::Global,
|
||||
};
|
||||
let mut words = vec![0u64; storage_len(storage_bits, entries)];
|
||||
let id_in = |palette: &mut Palette, value: u32| -> u32 {
|
||||
match palette {
|
||||
Palette::Single(_) => 0,
|
||||
Palette::List(list) => match list.iter().position(|&v| v == value) {
|
||||
Some(id) => id as u32,
|
||||
None => {
|
||||
list.push(value);
|
||||
list.len() as u32 - 1
|
||||
}
|
||||
},
|
||||
Palette::Global => value,
|
||||
}
|
||||
};
|
||||
if let Palette::Single(only) = self.palette {
|
||||
let id = id_in(&mut palette, only);
|
||||
if storage_bits > 0 && id != 0 {
|
||||
for i in 0..entries {
|
||||
write(&mut words, storage_bits, i, id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let (mut last_old, mut new_id) = (u32::MAX, 0);
|
||||
for i in 0..entries {
|
||||
let old = read(&self.words, self.bits, i);
|
||||
if old != last_old {
|
||||
last_old = old;
|
||||
let value = match &self.palette {
|
||||
Palette::List(list) => list[old as usize],
|
||||
_ => old,
|
||||
};
|
||||
new_id = id_in(&mut palette, value);
|
||||
}
|
||||
if storage_bits > 0 {
|
||||
write(&mut words, storage_bits, i, new_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let id = id_in(&mut palette, last);
|
||||
self.palette = palette;
|
||||
self.bits = storage_bits;
|
||||
self.words = words;
|
||||
id as usize
|
||||
}
|
||||
/// All values in index order.
|
||||
pub fn unpack(&self, out: &mut [u32]) {
|
||||
assert_eq!(out.len(), self.strategy.entries());
|
||||
match &self.palette {
|
||||
Palette::Single(value) => out.fill(*value),
|
||||
palette => {
|
||||
let bits = usize::from(self.bits);
|
||||
let per = 64 / bits;
|
||||
let m = mask(self.bits);
|
||||
for (chunk, &word) in out.chunks_mut(per).zip(&self.words) {
|
||||
for (slot, cell) in chunk.iter_mut().enumerate() {
|
||||
let id = ((word >> (slot * bits)) & m) as u32;
|
||||
*cell = match palette {
|
||||
Palette::List(list) => list[id as usize],
|
||||
_ => id,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Block ids as 16-bit values (callers whose registry fits in 16 bits).
|
||||
pub fn unpack_u16(&self, out: &mut [u16; 4096]) {
|
||||
debug_assert_eq!(self.strategy.entries(), 4096);
|
||||
match &self.palette {
|
||||
Palette::Single(value) => out.fill(*value as u16),
|
||||
palette => {
|
||||
let bits = usize::from(self.bits);
|
||||
let per = 64 / bits;
|
||||
let m = mask(self.bits);
|
||||
for (chunk, &word) in out.chunks_mut(per).zip(&self.words) {
|
||||
for (slot, cell) in chunk.iter_mut().enumerate() {
|
||||
let id = ((word >> (slot * bits)) & m) as usize;
|
||||
*cell = match palette {
|
||||
Palette::List(list) => list[id] as u16,
|
||||
_ => id as u16,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A container holding `values` in the smallest configuration for their
|
||||
/// distinct count, with palette ids in first-occurrence order, like a
|
||||
/// container unpacked from disk.
|
||||
pub fn from_values(strategy: Strategy, values: &[u32]) -> Self {
|
||||
assert_eq!(values.len(), strategy.entries());
|
||||
let mut palette: Vec<u32> = Vec::new();
|
||||
let mut small = true;
|
||||
let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
|
||||
let mut ids = Vec::with_capacity(values.len());
|
||||
for &value in values {
|
||||
let id = if small {
|
||||
match palette.iter().position(|&v| v == value) {
|
||||
Some(id) => id as u32,
|
||||
None => {
|
||||
palette.push(value);
|
||||
if palette.len() > 16 {
|
||||
small = false;
|
||||
lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32)));
|
||||
}
|
||||
palette.len() as u32 - 1
|
||||
}
|
||||
}
|
||||
} else {
|
||||
*lookup.entry(value).or_insert_with(|| {
|
||||
palette.push(value);
|
||||
palette.len() as u32 - 1
|
||||
})
|
||||
};
|
||||
ids.push(id);
|
||||
}
|
||||
Self::build(strategy, palette, &ids)
|
||||
}
|
||||
/// A container over a distinct-value `palette` and an id per entry.
|
||||
fn build(strategy: Strategy, palette: Vec<u32>, ids: &[u32]) -> Self {
|
||||
let config = strategy.config(ceil_log2(palette.len()));
|
||||
match config {
|
||||
Config::Single => Self::new(strategy, palette[0]),
|
||||
Config::List(bits) => Self {
|
||||
strategy,
|
||||
bits,
|
||||
words: pack_words(bits, ids.len(), ids.iter().copied()),
|
||||
palette: Palette::List(palette),
|
||||
},
|
||||
Config::Global => {
|
||||
let bits = strategy.global_bits;
|
||||
Self {
|
||||
strategy,
|
||||
bits,
|
||||
words: pack_words(bits, ids.len(), ids.iter().map(|&id| palette[id as usize])),
|
||||
palette: Palette::Global,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `PalettedContainer.read`: the container as sent on the wire. `bits` is
|
||||
/// the leading byte, `palette` the VarInt entries (a single one for
|
||||
/// `bits == 0`, none for the global palette) and `words` the longs.
|
||||
pub fn from_wire(
|
||||
strategy: Strategy,
|
||||
bits: u8,
|
||||
palette: Vec<u32>,
|
||||
words: Vec<u64>,
|
||||
) -> Result<Self, PaletteError> {
|
||||
let config = strategy.config(bits);
|
||||
let storage_bits = strategy.storage_bits(config);
|
||||
let expected = storage_len(storage_bits, strategy.entries());
|
||||
if words.len() != expected {
|
||||
return Err(PaletteError::BadStorage {
|
||||
expected,
|
||||
actual: words.len(),
|
||||
});
|
||||
}
|
||||
match config {
|
||||
Config::Single => {
|
||||
if palette.len() != 1 {
|
||||
return Err(PaletteError::BadPalette { len: palette.len() });
|
||||
}
|
||||
Ok(Self::new(strategy, palette[0]))
|
||||
}
|
||||
Config::List(bits) => {
|
||||
if palette.is_empty() || palette.len() > 1 << bits {
|
||||
return Err(PaletteError::BadPalette { len: palette.len() });
|
||||
}
|
||||
let container = Self {
|
||||
strategy,
|
||||
bits,
|
||||
palette: Palette::List(palette),
|
||||
words,
|
||||
};
|
||||
container.check_indices()?;
|
||||
Ok(container)
|
||||
}
|
||||
Config::Global => Ok(Self {
|
||||
strategy,
|
||||
bits: storage_bits,
|
||||
palette: Palette::Global,
|
||||
words,
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn check_indices(&self) -> Result<(), PaletteError> {
|
||||
let Palette::List(list) = &self.palette else {
|
||||
return Ok(());
|
||||
};
|
||||
if list.len() == 1 << self.bits {
|
||||
return Ok(());
|
||||
}
|
||||
for i in 0..self.strategy.entries() {
|
||||
let index = read(&self.words, self.bits, i);
|
||||
if index as usize >= list.len() {
|
||||
return Err(PaletteError::BadIndex {
|
||||
index,
|
||||
palette: list.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `PalettedContainer.write`: the leading bits byte, the palette entries
|
||||
/// (none for the global palette) and the raw longs, exactly as resident.
|
||||
pub fn to_wire(&self) -> (u8, Vec<u32>, &[u64]) {
|
||||
let palette = match &self.palette {
|
||||
Palette::Single(value) => vec![*value],
|
||||
Palette::List(list) => list.clone(),
|
||||
Palette::Global => Vec::new(),
|
||||
};
|
||||
(self.bits, palette, &self.words)
|
||||
}
|
||||
/// `PalettedContainer.pack`: distinct values in index order, indices
|
||||
/// re-encoded for the saved bit width.
|
||||
pub fn pack(&self) -> Packed {
|
||||
let entries = self.strategy.entries();
|
||||
let mut palette: Vec<u32> = Vec::new();
|
||||
let mut ids = Vec::with_capacity(entries);
|
||||
let mut values = vec![0u32; entries];
|
||||
self.unpack(&mut values);
|
||||
let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
|
||||
for &value in &values {
|
||||
let id = *lookup.entry(value).or_insert_with(|| {
|
||||
palette.push(value);
|
||||
palette.len() as u32 - 1
|
||||
});
|
||||
ids.push(id);
|
||||
}
|
||||
let bits = match self.strategy.config(ceil_log2(palette.len())) {
|
||||
Config::Single => 0,
|
||||
Config::List(bits) => bits,
|
||||
Config::Global => ceil_log2(palette.len()),
|
||||
};
|
||||
let data = (bits != 0).then(|| pack_words(bits, entries, ids.iter().copied()));
|
||||
Packed {
|
||||
palette,
|
||||
bits,
|
||||
data,
|
||||
}
|
||||
}
|
||||
/// `PalettedContainer.unpack`: a container from the saved form.
|
||||
pub fn from_packed(
|
||||
strategy: Strategy,
|
||||
palette: Vec<u32>,
|
||||
data: Option<&[u64]>,
|
||||
) -> Result<Self, PaletteError> {
|
||||
if palette.is_empty() {
|
||||
return Err(PaletteError::BadPalette { len: 0 });
|
||||
}
|
||||
let config = strategy.config(ceil_log2(palette.len()));
|
||||
let entries = strategy.entries();
|
||||
let disc_bits = match config {
|
||||
Config::Single => return Ok(Self::new(strategy, palette[0])),
|
||||
Config::List(bits) => bits,
|
||||
Config::Global => ceil_log2(palette.len()),
|
||||
};
|
||||
let data = data.ok_or(PaletteError::BadStorage {
|
||||
expected: storage_len(disc_bits, entries),
|
||||
actual: 0,
|
||||
})?;
|
||||
let expected = storage_len(disc_bits, entries);
|
||||
if data.len() != expected {
|
||||
return Err(PaletteError::BadStorage {
|
||||
expected,
|
||||
actual: data.len(),
|
||||
});
|
||||
}
|
||||
let mut ids = Vec::with_capacity(entries);
|
||||
for i in 0..entries {
|
||||
let index = read(data, disc_bits, i);
|
||||
if index as usize >= palette.len() {
|
||||
return Err(PaletteError::BadIndex {
|
||||
index,
|
||||
palette: palette.len(),
|
||||
});
|
||||
}
|
||||
ids.push(index);
|
||||
}
|
||||
Ok(match config {
|
||||
Config::List(bits) => Self {
|
||||
strategy,
|
||||
bits,
|
||||
words: data.to_vec(),
|
||||
palette: Palette::List(palette),
|
||||
},
|
||||
_ => Self::build(strategy, palette, &ids),
|
||||
})
|
||||
}
|
||||
/// Whether any palette entry satisfies `predicate` (`maybeHas`): entries
|
||||
/// no longer used by any position still count.
|
||||
pub fn maybe_has(&self, mut predicate: impl FnMut(u32) -> bool) -> bool {
|
||||
match &self.palette {
|
||||
Palette::Single(value) => predicate(*value),
|
||||
Palette::List(list) => list.iter().any(|&v| predicate(v)),
|
||||
Palette::Global => (0..1u32 << self.bits.min(31)).any(predicate),
|
||||
}
|
||||
}
|
||||
/// Heap bytes held by the palette and the storage.
|
||||
pub fn heap_bytes(&self) -> usize {
|
||||
self.words.capacity() * 8
|
||||
+ match &self.palette {
|
||||
Palette::List(list) => list.capacity() * 4,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PartialEq for PalettedContainer {
|
||||
/// Equal when every entry is.
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let entries = self.strategy.entries();
|
||||
entries == other.strategy.entries() && (0..entries).all(|i| self.get(i) == other.get(i))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const BLOCKS: Strategy = Strategy::blocks(16);
|
||||
const BIOMES: Strategy = Strategy::biomes(7);
|
||||
fn rng(state: &mut u64) -> u64 {
|
||||
*state ^= *state << 13;
|
||||
*state ^= *state >> 7;
|
||||
*state ^= *state << 17;
|
||||
*state
|
||||
}
|
||||
#[test]
|
||||
fn grows_through_vanilla_widths() {
|
||||
let mut c = PalettedContainer::new(BLOCKS, 0);
|
||||
assert_eq!((c.bits(), c.palette_len()), (0, 1));
|
||||
let mut expected = Vec::new();
|
||||
for n in 1..=300u32 {
|
||||
c.set(n as usize, n);
|
||||
expected.push(match n + 1 {
|
||||
2..=16 => 4,
|
||||
17..=32 => 5,
|
||||
33..=64 => 6,
|
||||
65..=128 => 7,
|
||||
129..=256 => 8,
|
||||
_ => 16,
|
||||
});
|
||||
assert_eq!(c.bits(), *expected.last().unwrap(), "after {n} values");
|
||||
}
|
||||
assert!(c.is_global());
|
||||
for n in 1..=300u32 {
|
||||
assert_eq!(c.get(n as usize), n);
|
||||
}
|
||||
let mut b = PalettedContainer::new(BIOMES, 3);
|
||||
for n in 1..=9u32 {
|
||||
b.set(n as usize, n + 3);
|
||||
let want = match n + 1 {
|
||||
2 => 1,
|
||||
3..=4 => 2,
|
||||
5..=8 => 3,
|
||||
_ => 7,
|
||||
};
|
||||
assert_eq!(b.bits(), want, "after {n} biomes");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn matches_a_plain_array_under_random_edits() {
|
||||
for (strategy, distinct) in [(BLOCKS, 700u64), (BLOCKS, 12), (BIOMES, 9), (BIOMES, 3)] {
|
||||
let entries = strategy.entries();
|
||||
let mut state = 0x1234_5678_9ABC_DEF1u64;
|
||||
let mut c = PalettedContainer::new(strategy, 5);
|
||||
let mut plain = vec![5u32; entries];
|
||||
for _ in 0..20_000 {
|
||||
let r = rng(&mut state);
|
||||
let i = (r % entries as u64) as usize;
|
||||
let v = ((r >> 20) % distinct) as u32 * 7;
|
||||
assert_eq!(c.set(i, v), plain[i]);
|
||||
plain[i] = v;
|
||||
}
|
||||
let mut out = vec![0; entries];
|
||||
c.unpack(&mut out);
|
||||
assert_eq!(out, plain);
|
||||
for (i, &v) in plain.iter().enumerate() {
|
||||
assert_eq!(c.get(i), v);
|
||||
}
|
||||
let packed = c.pack();
|
||||
let loaded = PalettedContainer::from_packed(
|
||||
strategy,
|
||||
packed.palette.clone(),
|
||||
packed.data.as_deref(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(loaded, c);
|
||||
assert_eq!(loaded.pack(), packed);
|
||||
let again = PalettedContainer::from_values(strategy, &plain);
|
||||
assert_eq!(again, c);
|
||||
assert_eq!(again.pack(), packed);
|
||||
let (bits, palette, words) = c.to_wire();
|
||||
let wire =
|
||||
PalettedContainer::from_wire(strategy, bits, palette, words.to_vec()).unwrap();
|
||||
assert_eq!(wire, c);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn uniform_detection_ignores_stale_palette_entries() {
|
||||
let mut c = PalettedContainer::new(BLOCKS, 0);
|
||||
c.set(10, 3);
|
||||
assert!(!c.is_uniform(0));
|
||||
c.set(10, 0);
|
||||
assert!(c.palette_len() == 2 && c.is_uniform(0) && c.uniform() == Some(0));
|
||||
assert!(!c.is_uniform(3));
|
||||
for i in 0..4096 {
|
||||
c.set(i, 3);
|
||||
}
|
||||
assert_eq!(c.uniform(), Some(3));
|
||||
}
|
||||
#[test]
|
||||
fn rejects_malformed_wire_data() {
|
||||
assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![1, 2], vec![0; 255]).is_err());
|
||||
assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![1, 2], vec![0x3333; 256]).is_err());
|
||||
assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![], vec![0; 256]).is_err());
|
||||
assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![1, 2], vec![]).is_err());
|
||||
assert!(PalettedContainer::from_wire(BIOMES, 2, vec![1, 2, 3, 4, 5], vec![0; 4]).is_err());
|
||||
assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![9], vec![]).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn division_magic_is_exact() {
|
||||
for bits in 1..=32u8 {
|
||||
let per = 64 / usize::from(bits);
|
||||
for i in 0..4096usize {
|
||||
assert_eq!(locate(bits, i).0, i / per, "bits {bits} index {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
-8
@@ -24,7 +24,8 @@ emit for the same scenes.
|
||||
loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`,
|
||||
`load_visibility`, `MeshTables`), builds the same blocks and light in real
|
||||
client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the
|
||||
scene constants and runs `Mesher::mesh`.
|
||||
scene constants (or, for the biome-blend scenes, keeps the real biome
|
||||
definitions and fills the chunks' quart biome arrays) and runs `Mesher::mesh`.
|
||||
- **Comparison**: quads are matched as multisets per scene, keyed by sprite,
|
||||
render-layer class (translucent vs. solid/cutout) and geometry rounded to
|
||||
1/1000 after binary32 normalisation, with a winding-preserving rotation.
|
||||
@@ -37,7 +38,7 @@ emit for the same scenes.
|
||||
overlay classes (`HalfTransparentBlock`/`LeavesBlock`), tint source counts
|
||||
and `getOffset` at five columns.
|
||||
|
||||
The corpus (94 sections, ~842k quads, ~206k of them fluid quads) has full
|
||||
The corpus (112 sections, ~1.0M quads, ~206k of them fluid quads) has full
|
||||
cubes in open air, corners, cavities and overhangs; slabs, stairs, walls,
|
||||
fences, panes, bars, torches, flowers and grasses with XZ/XYZ offsets, tall
|
||||
plants, tinted blocks (grass, leaves, stems, redstone, lily pad, petals, leaf
|
||||
@@ -50,6 +51,27 @@ sculk sensor, glow lichen); Nether shading; every block's default state; every
|
||||
`RenderShape.MODEL` state of the registry on a sparse grid; and dense random
|
||||
scenes mixing all model states with fluids under propagated or random light.
|
||||
|
||||
Biome tint blending is compared against the client's real
|
||||
`ClientLevel.calculateBlockTint`: the oracle builds a `BiomeManager` (the
|
||||
eight-corner zoom with a random hashed seed) over a fixed noise-biome map of
|
||||
real `Biome` objects from the registry bootstrap (colormap sampling, colour
|
||||
overrides, the dark-forest and swamp grass modifiers), initialises
|
||||
`GrassColor`/`FoliageColor`/`DryFoliageColor` from the jar's colormaps, and
|
||||
averages the resolver over the blend radius at each block's own height. The
|
||||
`biome_blend_r*` scenes (radius 0, 1, 2, 3, 5, 7) put tinted blocks (grass,
|
||||
leaves, water, leaf litter, cane, ferns, vines) at four heights on every
|
||||
column of a Voronoi patchwork of 16 common biomes that shifts with height;
|
||||
the `biome_each_*` scenes cover all 67 biomes. Option scenes (`options_*`)
|
||||
cover flat lighting (`ao` off), opaque leaves (`cutoutLeaves` off, which
|
||||
`SectionCompiler` draws in the solid layer and `LeavesBlock.skipRendering`
|
||||
joins) and both together.
|
||||
|
||||
With `biomeBlendRadius` 0 the client takes the resolver's colour as is. Biome
|
||||
colours given as plain RGB (all water colours, most grass/foliage overrides)
|
||||
have alpha 0 there, so the client's tinted vertices come out fully
|
||||
transparent, which the terrain shader would discard. Horizon keeps them
|
||||
opaque and the gate compares RGB for radius-0 scenes.
|
||||
|
||||
## Running
|
||||
|
||||
```sh
|
||||
@@ -112,15 +134,14 @@ gate.
|
||||
|
||||
## What remains different or untested
|
||||
|
||||
- Biome tint blending: vanilla blends `BiomeManager`'s zoomed biome at each
|
||||
block's own height; Horizon blends its quart biome cells at the section's
|
||||
mid-height. The gate uses one constant colour per resolver, so this is not
|
||||
compared.
|
||||
- Changing `biomeBlendRadius`, `ao` or `cutoutLeaves` in the options does not
|
||||
remesh resident sections; new and edited sections use the new values.
|
||||
- Model variant seeds: `DoublePlantBlock`, `DoorBlock` and `AbstractBedBlock`
|
||||
override `getSeed`; Horizon seeds every block from its own position. No
|
||||
vanilla block among those has weighted variants, so output is unaffected.
|
||||
- Settings: only smooth lighting on and cutout ("fancy") leaves are covered;
|
||||
Horizon has no flat-lighting or opaque-leaves modes.
|
||||
- Opaque leaves: the vertex layer carries a flag (`OPAQUE_LAYER`) that makes
|
||||
the terrain shader ignore the texture's alpha; the shader side is not
|
||||
compared (GPU pixels).
|
||||
- Layers: vanilla's solid and cutout layers are compared as one class because
|
||||
Horizon draws both in its opaque pass.
|
||||
- Not compared: block entities and their renderers, animated sprite frames,
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.nbt.*;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.ReloadableServerRegistries;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
/**
|
||||
* Shared set-up for the interaction/inventory parity oracles: the vanilla data
|
||||
* pack loaded into registries (as the server does), an NBT registry ops, a
|
||||
* stand-in ServerLevel that only answers registryAccess, and canonical text
|
||||
* for item stacks and NBT so both sides print comparable lines.
|
||||
*/
|
||||
public final class ParityData {
|
||||
public static HolderLookup.Provider lookup;
|
||||
public static RegistryAccess access;
|
||||
public static RegistryOps<Tag> ops;
|
||||
public static ServerLevel level;
|
||||
|
||||
public static void init() throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
|
||||
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
|
||||
lookup = loaded.lookupWithUpdatedTags();
|
||||
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
|
||||
access = loaded.layers().compositeAccess();
|
||||
ops = RegistryOps.create(NbtOps.INSTANCE, lookup);
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
Object unsafe = unsafeField.get(null);
|
||||
level = (ServerLevel) unsafe.getClass().getMethod("allocateInstance", Class.class).invoke(unsafe, ServerLevel.class);
|
||||
Field registryAccess = Level.class.getDeclaredField("registryAccess");
|
||||
registryAccess.setAccessible(true);
|
||||
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, registryAccess);
|
||||
unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, level, offset, access);
|
||||
}
|
||||
|
||||
/** "-" is the empty stack; otherwise ItemStack.CODEC over SNBT. */
|
||||
public static ItemStack stack(String snbt) throws Exception {
|
||||
if (snbt.equals("-")) return ItemStack.EMPTY;
|
||||
Tag tag = TagParser.parseCompoundFully(snbt);
|
||||
return ItemStack.CODEC.parse(ops, tag).getOrThrow();
|
||||
}
|
||||
|
||||
public static String canon(ItemStack stack) {
|
||||
if (stack == null || stack.isEmpty()) return "-";
|
||||
Tag tag = ItemStack.CODEC.encodeStart(ops, stack).getOrThrow();
|
||||
return canon(tag);
|
||||
}
|
||||
|
||||
/** Sorted-key, type-annotated text of an NBT tag. */
|
||||
public static String canon(Tag tag) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
canon(tag, out);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static void canon(Tag tag, StringBuilder out) {
|
||||
switch (tag) {
|
||||
case ByteTag t -> out.append(t.value()).append('b');
|
||||
case ShortTag t -> out.append(t.value()).append('s');
|
||||
case IntTag t -> out.append(t.value());
|
||||
case LongTag t -> out.append(t.value()).append('L');
|
||||
case FloatTag t -> out.append(t.value()).append('f');
|
||||
case DoubleTag t -> out.append(t.value()).append('d');
|
||||
case StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"');
|
||||
case ByteArrayTag t -> {
|
||||
out.append("[B;");
|
||||
byte[] a = t.getAsByteArray();
|
||||
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
|
||||
out.append(']');
|
||||
}
|
||||
case IntArrayTag t -> {
|
||||
out.append("[I;");
|
||||
int[] a = t.getAsIntArray();
|
||||
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
|
||||
out.append(']');
|
||||
}
|
||||
case LongArrayTag t -> {
|
||||
out.append("[L;");
|
||||
long[] a = t.getAsLongArray();
|
||||
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
|
||||
out.append(']');
|
||||
}
|
||||
case ListTag t -> {
|
||||
out.append('[');
|
||||
for (int i = 0; i < t.size(); i++) {
|
||||
if (i > 0) out.append(',');
|
||||
canon(t.get(i), out);
|
||||
}
|
||||
out.append(']');
|
||||
}
|
||||
case CompoundTag t -> {
|
||||
out.append('{');
|
||||
boolean first = true;
|
||||
for (String key : new TreeSet<>(t.keySet())) {
|
||||
if (!first) out.append(',');
|
||||
first = false;
|
||||
out.append(key).append(':');
|
||||
canon(t.get(key), out);
|
||||
}
|
||||
out.append('}');
|
||||
}
|
||||
default -> throw new IllegalStateException(tag.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.level.LevelAccessor;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.core.component.BlockTransformer;
|
||||
|
||||
/**
|
||||
* Original oracle: the data-driven axe/hoe/shovel BlockTransformer entries.
|
||||
* "dump" lists every block state; a case line "transformer TAB face TAB
|
||||
* clicked TAB above" (states as "name|prop=value,...") prints the first
|
||||
* transform that yields a state and its settings, as BlockTransformer.transformBlock
|
||||
* would pick it.
|
||||
*/
|
||||
public final class VanillaBlockTransformerOracle {
|
||||
static String describe(BlockState state) {
|
||||
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
|
||||
List<Property<?>> props = new ArrayList<>(state.getProperties());
|
||||
props.sort(Comparator.comparing(Property::getName));
|
||||
boolean first = true;
|
||||
for (Property<?> p : props) {
|
||||
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
|
||||
first = false;
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static String name(BlockState state, Property p) {
|
||||
return p.getName(state.getValue(p));
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static BlockState parse(String text) {
|
||||
String[] parts = text.split("\\|", -1);
|
||||
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
|
||||
BlockState state = block.defaultBlockState();
|
||||
if (!parts[1].isEmpty()) {
|
||||
for (String kv : parts[1].split(",")) {
|
||||
String[] pair = kv.split("=");
|
||||
Property p = block.getStateDefinition().getProperty(pair[0]);
|
||||
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
static LevelAccessor level(BlockState clicked, BlockState above) {
|
||||
return (LevelAccessor) Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(), new Class<?>[]{LevelAccessor.class}, (proxy, method, args) -> {
|
||||
if (method.getName().equals("getBlockState")) {
|
||||
BlockPos pos = (BlockPos) args[0];
|
||||
return pos.getY() == 0 ? clicked : pos.getY() == 1 && pos.getX() == 0 && pos.getZ() == 0 ? above : net.minecraft.world.level.block.Blocks.STONE.defaultBlockState();
|
||||
}
|
||||
throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
if (args[0].equals("dump")) {
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (Block block : BuiltInRegistries.BLOCK) {
|
||||
for (BlockState state : block.getStateDefinition().getPossibleStates()) out.println(describe(state));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
var registry = ParityData.access.lookupOrThrow(Registries.BLOCK_TRANSFORMER);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
String[] f = line.split("\t", -1);
|
||||
try {
|
||||
if (f[0].equals("honeycomb")) {
|
||||
out.println(net.minecraft.world.item.HoneycombItem.getWaxed(parse(f[2])).map(VanillaBlockTransformerOracle::describe).orElse("none"));
|
||||
continue;
|
||||
}
|
||||
var transformer = registry.getOrThrow(ResourceKey.create(Registries.BLOCK_TRANSFORMER, Identifier.parse(f[0]))).value();
|
||||
Direction face = Direction.byName(f[1]);
|
||||
BlockState clicked = parse(f[2]);
|
||||
LevelAccessor level = level(clicked, parse(f[3]));
|
||||
String result = "none";
|
||||
int index = 0;
|
||||
for (var data : transformer.transforms()) {
|
||||
if (!data.disallowedFaces().contains(face)) {
|
||||
BlockState state = data.blockStateProvider().value().getOptionalState(level, RandomSource.create(0L), BlockPos.ZERO);
|
||||
if (state != null) {
|
||||
result = index + "\t" + describe(state) + "\t" + BuiltInRegistries.SOUND_EVENT.getKey(data.sound().value())
|
||||
+ "\t" + data.particle().name().toLowerCase() + "\t"
|
||||
+ data.loot().map(k -> k.identifier().toString()).orElse("-") + "\t" + data.dropStrategy().name().toLowerCase()
|
||||
+ "\t" + data.updateFromNeighbors() + "\t" + data.transformType().name().toLowerCase() + "\t" + data.consumeOnUse()
|
||||
+ "\t" + data.itemDamagePerUse();
|
||||
break;
|
||||
}
|
||||
}
|
||||
index++;
|
||||
}
|
||||
out.println(result);
|
||||
} catch (Throwable e) {
|
||||
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.EntityEquipment;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.AbstractCauldronBlock;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
|
||||
/**
|
||||
* Original oracle: a cauldron's useItemOn (CauldronInteractions) with a
|
||||
* recording stand-in level and player. Each case line is JSON: cauldron state
|
||||
* ("name|prop=value"), the held stack, creative, whether water is above. The
|
||||
* output line lists the result, block writes, sounds, the final inventory and
|
||||
* drops.
|
||||
*/
|
||||
public final class VanillaCauldronOracle {
|
||||
static Object unsafe;
|
||||
static java.lang.reflect.Method allocate;
|
||||
static final List<String> events = new ArrayList<>();
|
||||
static boolean underWater;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) {
|
||||
try {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
f.set(target, value);
|
||||
}
|
||||
|
||||
static String describe(BlockState state) {
|
||||
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
|
||||
List<Property<?>> props = new ArrayList<>(state.getProperties());
|
||||
props.sort(Comparator.comparing(Property::getName));
|
||||
boolean first = true;
|
||||
for (Property<?> p : props) {
|
||||
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
|
||||
first = false;
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static String name(BlockState state, Property p) {
|
||||
return p.getName(state.getValue(p));
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static BlockState parse(String text) {
|
||||
String[] parts = text.split("\\|", -1);
|
||||
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
|
||||
BlockState state = block.defaultBlockState();
|
||||
if (!parts[1].isEmpty()) {
|
||||
for (String kv : parts[1].split(",")) {
|
||||
String[] pair = kv.split("=");
|
||||
Property p = block.getStateDefinition().getProperty(pair[0]);
|
||||
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
static final class World extends ServerLevel {
|
||||
World() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
@Override public boolean isClientSide() { return false; }
|
||||
@Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int limit) { events.add("set " + describe(state)); return true; }
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return underWater ? Fluids.WATER.defaultFluidState() : Fluids.EMPTY.defaultFluidState(); }
|
||||
@Override public void playSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) {
|
||||
events.add("sound " + BuiltInRegistries.SOUND_EVENT.getKey(s));
|
||||
}
|
||||
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, net.minecraft.world.phys.Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
|
||||
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
|
||||
}
|
||||
|
||||
static final class FakePlayer extends ServerPlayer {
|
||||
boolean creative;
|
||||
Inventory inv;
|
||||
FakePlayer() {
|
||||
super(null, null, null, null);
|
||||
}
|
||||
@Override public Inventory getInventory() { return inv; }
|
||||
@Override public boolean hasInfiniteMaterials() { return creative; }
|
||||
@Override public boolean isCreative() { return creative; }
|
||||
@Override public void setItemInHand(InteractionHand hand, ItemStack stack) { inv.setItem(0, stack); }
|
||||
@Override public ItemStack getItemInHand(InteractionHand hand) { return inv.getItem(0); }
|
||||
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
|
||||
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
|
||||
if (!stack.isEmpty()) events.add("drop " + ParityData.canon(stack));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
unsafe = field.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
var f = JsonParser.parseString(line).getAsJsonObject();
|
||||
try {
|
||||
events.clear();
|
||||
underWater = f.get("under_water").getAsBoolean();
|
||||
var world = make(World.class);
|
||||
var player = make(FakePlayer.class);
|
||||
player.creative = f.get("creative").getAsBoolean();
|
||||
player.inv = new Inventory(player, new EntityEquipment());
|
||||
for (var other : f.getAsJsonArray("inventory")) {
|
||||
var pair = other.getAsJsonArray();
|
||||
player.inv.setItem(pair.get(0).getAsInt(), ParityData.stack(pair.get(1).getAsString()));
|
||||
}
|
||||
ItemStack held = ParityData.stack(f.get("held").getAsString());
|
||||
player.inv.setItem(0, held);
|
||||
BlockState state = parse(f.get("state").getAsString());
|
||||
var cauldron = (AbstractCauldronBlock) state.getBlock();
|
||||
var use = net.minecraft.world.level.block.state.BlockBehaviour.class.getDeclaredMethod("useItemOn", ItemStack.class, BlockState.class,
|
||||
net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, net.minecraft.world.phys.BlockHitResult.class);
|
||||
use.setAccessible(true);
|
||||
InteractionResult result = (InteractionResult) use.invoke(cauldron, held, state, world, BlockPos.ZERO, player, InteractionHand.MAIN_HAND, null);
|
||||
String kind = result == InteractionResult.SUCCESS ? "success" : result == InteractionResult.CONSUME ? "consume"
|
||||
: result == InteractionResult.TRY_WITH_EMPTY_HAND ? "pass" : result.toString();
|
||||
StringBuilder inventory = new StringBuilder();
|
||||
for (int i = 0; i < 41; i++) {
|
||||
ItemStack s = player.inv.getItem(i);
|
||||
if (!s.isEmpty()) inventory.append(i).append('=').append(ParityData.canon(s)).append(' ');
|
||||
}
|
||||
out.println(kind + "\t" + String.join(";", events) + "\t" + inventory.toString().trim());
|
||||
} catch (Throwable e) {
|
||||
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
|
||||
if (System.getenv("CAULDRON_TRACE") != null) e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.platform.FramerateLimitTracker;
|
||||
import com.mojang.blaze3d.platform.InputConstants;
|
||||
import com.mojang.blaze3d.platform.Window;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.tutorial.Tutorial;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.ServerTickRateManager;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import net.minecraft.world.entity.player.Input;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
|
||||
/**
|
||||
* Drives the real DeltaTracker.Timer, ServerTickRateManager, Window.calculateScale,
|
||||
* FramerateLimitTracker, MouseHandler (move, scroll, turnPlayer), Entity.turn and
|
||||
* ToggleKeyMapping with the input sequences in a JSON-lines file and prints
|
||||
* every observable bit-exactly. Hosts are uninitialised shells (Unsafe) that
|
||||
* carry only the fields the exercised code reads.
|
||||
*/
|
||||
public final class VanillaGameLoopOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
Field f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static float f(JsonElement v) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static double d(JsonElement v) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static String fb(float v) {
|
||||
return String.format("%08x", Float.floatToRawIntBits(v) == 0x7fc00000 || Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
static String db(double v) {
|
||||
return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v));
|
||||
}
|
||||
|
||||
// ---- stubs for the server tick manager -------------------------------------------------
|
||||
static final List<String> reports = new ArrayList<>();
|
||||
|
||||
static final class StubStack extends CommandSourceStack {
|
||||
StubStack() {
|
||||
super(null, null, null, null, null, (Component) null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSuccess(Supplier<Component> message, boolean broadcast) {
|
||||
var contents = (TranslatableContents) message.get().getContents();
|
||||
reports.add(contents.getArgs()[0] + " " + contents.getArgs()[1]);
|
||||
}
|
||||
}
|
||||
|
||||
static final class StubPlayers extends PlayerList {
|
||||
StubPlayers() {
|
||||
super(null, null, null, (net.minecraft.server.notifications.NotificationService) null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void broadcastAll(net.minecraft.network.protocol.Packet<?> packet) {
|
||||
}
|
||||
}
|
||||
|
||||
static StubStack stubStack;
|
||||
static StubPlayers stubPlayers;
|
||||
|
||||
static final class StubServer extends MinecraftServer {
|
||||
StubServer() {
|
||||
super(null, null, null, null, null, null, null, null, null, false, null);
|
||||
}
|
||||
|
||||
@Override public PlayerList getPlayerList() { return stubPlayers; }
|
||||
@Override public CommandSourceStack createCommandSourceStack() { return stubStack; }
|
||||
@Override public void onTickRateChanged() { }
|
||||
@Override protected boolean initServer() { return false; }
|
||||
@Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; }
|
||||
@Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; }
|
||||
@Override public boolean shouldRconBroadcast() { return false; }
|
||||
@Override protected net.minecraft.util.debugchart.SampleLogger getTickTimeLogger() { return null; }
|
||||
@Override public boolean isTickTimeLoggingEnabled() { return false; }
|
||||
@Override public net.minecraft.SystemReport fillServerSystemReport(net.minecraft.SystemReport r) { return r; }
|
||||
@Override public boolean isDedicatedServer() { return false; }
|
||||
@Override public int getRateLimitPacketsPerSecond() { return 0; }
|
||||
@Override public int getCommandSpamThresholdSeconds() { return 0; }
|
||||
@Override public int getChatSpamThresholdSeconds() { return 0; }
|
||||
@Override public boolean useNativeTransport() { return false; }
|
||||
@Override public boolean isPublished() { return false; }
|
||||
@Override public int getMaxPlayers() { return 0; }
|
||||
@Override public boolean shouldInformAdmins() { return false; }
|
||||
@Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; }
|
||||
}
|
||||
|
||||
static final class StubPlayer extends LocalPlayer {
|
||||
boolean scoping;
|
||||
|
||||
StubPlayer() {
|
||||
super(null, null, null, null, null, Input.EMPTY, false, null, null);
|
||||
}
|
||||
|
||||
@Override public boolean isScoping() { return scoping; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
}
|
||||
|
||||
static Minecraft shell;
|
||||
static Options options;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
shell = make(Minecraft.class);
|
||||
field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer());
|
||||
field(Minecraft.class, "instance").set(null, shell);
|
||||
options = new Options(shell, Files.createTempDirectory("opts").toFile());
|
||||
stubStack = make(StubStack.class);
|
||||
stubPlayers = make(StubPlayers.class);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
switch (c.get("t").getAsString()) {
|
||||
case "timer" -> timer(c, out);
|
||||
case "rate" -> rate(c, out);
|
||||
case "scale" -> scale(c, out);
|
||||
case "limit" -> limit(c, out);
|
||||
case "mouse" -> mouse(c, out);
|
||||
case "scroll" -> scroll(c, out);
|
||||
case "key" -> key(c, out);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static void timer(JsonObject c, PrintWriter out) {
|
||||
float[] mspt = {0};
|
||||
var timer = new DeltaTracker.Timer(f(c.get("tps")), c.get("start").getAsLong(),
|
||||
d -> mspt[0] == 0 ? d : Math.max(d, mspt[0]));
|
||||
out.println("timer");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String name = op.get(0).getAsString();
|
||||
String result = "";
|
||||
switch (name) {
|
||||
case "adv" -> {
|
||||
mspt[0] = op.get(2).isJsonNull() ? 0 : f(op.get(2));
|
||||
result = " " + timer.advanceGameTime(op.get(1).getAsLong());
|
||||
}
|
||||
case "real" -> timer.advanceRealTime(op.get(1).getAsLong());
|
||||
case "pause" -> timer.updatePauseState(op.get(1).getAsBoolean());
|
||||
case "frozen" -> timer.updateFrozenState(op.get(1).getAsBoolean());
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
}
|
||||
out.println(name + result + " " + fb(timer.getGameTimeDeltaTicks()) + " " + fb(timer.getGameTimeDeltaPartialTick(false))
|
||||
+ " " + fb(timer.getGameTimeDeltaPartialTick(true)) + " " + fb(timer.getRealtimeDeltaTicks()));
|
||||
}
|
||||
}
|
||||
|
||||
static void rate(JsonObject c, PrintWriter out) throws Exception {
|
||||
var m = make(ServerTickRateManager.class);
|
||||
field(ServerTickRateManager.class, "server").set(m, make(StubServer.class));
|
||||
// Field initialisers do not run on a shell.
|
||||
field(net.minecraft.world.TickRateManager.class, "tickrate").setFloat(m, 20.0F);
|
||||
field(net.minecraft.world.TickRateManager.class, "nanosecondsPerTick").setLong(m, 50_000_000L);
|
||||
field(net.minecraft.world.TickRateManager.class, "runGameElements").setBoolean(m, true);
|
||||
var startTime = field(ServerTickRateManager.class, "sprintTickStartTime");
|
||||
var spend = field(ServerTickRateManager.class, "sprintTimeSpend");
|
||||
out.println("rate");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String name = op.get(0).getAsString();
|
||||
reports.clear();
|
||||
String result = "";
|
||||
switch (name) {
|
||||
case "rate" -> m.setTickRate(f(op.get(1)));
|
||||
case "freeze" -> m.setFrozen(op.get(1).getAsBoolean());
|
||||
case "step" -> result = " " + m.stepGameIfPaused(op.get(1).getAsInt());
|
||||
case "stopstep" -> result = " " + m.stopStepping();
|
||||
case "sprint" -> result = " " + m.requestGameToSprint(op.get(1).getAsInt());
|
||||
case "check" -> {
|
||||
result = " " + m.checkShouldSprintThisTick();
|
||||
if (m.runsNormally() && result.equals(" true")) {
|
||||
startTime.setLong(m, op.get(1).getAsLong());
|
||||
} else if (m.runsNormally() && reports.isEmpty()) {
|
||||
// unreachable: the else branch always reports
|
||||
}
|
||||
}
|
||||
case "end" -> {
|
||||
long before = spend.getLong(m);
|
||||
m.endTickWork();
|
||||
spend.setLong(m, before + (op.get(1).getAsLong() - startTime.getLong(m)));
|
||||
}
|
||||
case "stopsprint" -> result = " " + m.stopSprinting();
|
||||
case "tick" -> m.tick();
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
}
|
||||
out.println(name + result + " | " + fb(m.tickrate()) + " " + m.nanosecondsPerTick() + " " + fb(m.millisecondsPerTick())
|
||||
+ " " + m.runsNormally() + " " + m.isSteppingForward() + " " + m.frozenTicksToRun() + " " + m.isFrozen()
|
||||
+ " " + m.isSprinting() + (reports.isEmpty() ? "" : " report " + reports.get(0)));
|
||||
}
|
||||
}
|
||||
|
||||
static Window window(int w, int h, int sw, int sh) throws Exception {
|
||||
Window window = make(Window.class);
|
||||
field(Window.class, "framebufferWidth").setInt(window, w);
|
||||
field(Window.class, "framebufferHeight").setInt(window, h);
|
||||
field(Window.class, "width").setInt(window, sw);
|
||||
field(Window.class, "height").setInt(window, sh);
|
||||
return window;
|
||||
}
|
||||
|
||||
static void scale(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(c.get("w").getAsInt(), c.get("h").getAsInt(), c.get("sw").getAsInt(), c.get("sh").getAsInt());
|
||||
int scale = window.calculateScale(c.get("max").getAsInt(), c.get("uni").getAsBoolean());
|
||||
window.setGuiScale(scale);
|
||||
out.println("scale " + scale + " " + window.getGuiScaledWidth() + " " + window.getGuiScaledHeight() + " "
|
||||
+ db(MouseHandler.getScaledXPos(window, d(c.get("x")))) + " " + db(MouseHandler.getScaledYPos(window, d(c.get("y")))));
|
||||
}
|
||||
|
||||
static void limit(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(1, 1, 1, 1);
|
||||
field(Window.class, "iconified").setBoolean(window, c.get("iconified").getAsBoolean());
|
||||
field(Window.class, "focused").setBoolean(window, c.get("focused").getAsBoolean());
|
||||
Minecraft mc = make(Minecraft.class);
|
||||
field(Minecraft.class, "window").set(mc, window);
|
||||
Gui gui = make(Gui.class);
|
||||
field(Gui.class, "screen").set(gui, c.get("screen").getAsBoolean() ? make(net.minecraft.client.gui.screens.PauseScreen.class) : null);
|
||||
field(Gui.class, "overlay").set(gui, c.get("overlay").getAsBoolean() ? make(net.minecraft.client.gui.screens.LoadingOverlay.class) : null);
|
||||
field(Minecraft.class, "gui").set(mc, gui);
|
||||
field(Minecraft.class, "level").set(mc, c.get("level").getAsBoolean() ? make(net.minecraft.client.multiplayer.ClientLevel.class) : null);
|
||||
options.framerateLimit().set(c.get("opt").getAsInt());
|
||||
options.inactivityFpsLimit().set(c.get("afk").getAsBoolean() ? InactivityFpsLimit.AFK : InactivityFpsLimit.MINIMIZED);
|
||||
var tracker = new FramerateLimitTracker(options, mc);
|
||||
field(FramerateLimitTracker.class, "latestInputTime").setLong(tracker, net.minecraft.util.Util.getMillis() - c.get("ago").getAsLong());
|
||||
out.println("limit " + tracker.getThrottleReason() + " " + tracker.getFramerateLimit() + " " + tracker.isHeavilyThrottled());
|
||||
}
|
||||
|
||||
static MouseHandler handler(Minecraft mc) throws Exception {
|
||||
MouseHandler h = new MouseHandler(mc);
|
||||
return h;
|
||||
}
|
||||
|
||||
static void mouse(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(1, 1, 1, 1);
|
||||
field(Window.class, "handle").setLong(window, 1L);
|
||||
field(Window.class, "focused").setBoolean(window, c.get("active").getAsBoolean());
|
||||
Minecraft mc = make(Minecraft.class);
|
||||
field(Minecraft.class, "window").set(mc, window);
|
||||
field(Minecraft.class, "options").set(mc, options);
|
||||
field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class));
|
||||
field(Minecraft.class, "tutorial").set(mc, make(Tutorial.class));
|
||||
StubPlayer player = make(StubPlayer.class);
|
||||
player.scoping = c.get("scoping").getAsBoolean();
|
||||
mc.player = player;
|
||||
options.sensitivity().set(d(c.get("sens")));
|
||||
options.smoothCamera = c.get("smooth").getAsBoolean();
|
||||
options.invertMouseX().set(c.get("ix").getAsBoolean());
|
||||
options.invertMouseY().set(c.get("iy").getAsBoolean());
|
||||
MouseHandler h = handler(mc);
|
||||
field(MouseHandler.class, "mouseGrabbed").setBoolean(h, c.get("grabbed").getAsBoolean());
|
||||
var turn = MouseHandler.class.getDeclaredMethod("turnPlayer", double.class);
|
||||
turn.setAccessible(true);
|
||||
var dx = field(MouseHandler.class, "accumulatedDX");
|
||||
var dy = field(MouseHandler.class, "accumulatedDY");
|
||||
double last = Double.MIN_VALUE;
|
||||
out.println("mouse");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "move" -> h.onMove(1L, d(op.get(1)), d(op.get(2)), d(op.get(3)), d(op.get(4)));
|
||||
case "ignore" -> h.setIgnoreFirstMove();
|
||||
case "frame" -> {
|
||||
double time = d(op.get(1));
|
||||
double mousea = time - last;
|
||||
last = time;
|
||||
// MouseHandler.handleAccumulatedMovement without the SDL clock and screens.
|
||||
if (mc.isWindowActive() && h.isMouseGrabbed() && mc.player != null) {
|
||||
turn.invoke(h, mousea);
|
||||
}
|
||||
dx.setDouble(h, 0.0);
|
||||
dy.setDouble(h, 0.0);
|
||||
out.println("frame " + fb(player.getXRot()) + " " + fb(player.getYRot()) + " "
|
||||
+ fb(player.xRotO) + " " + fb(player.yRotO));
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void scroll(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(1, 1, 1, 1);
|
||||
field(Window.class, "handle").setLong(window, 1L);
|
||||
Minecraft mc = make(Minecraft.class);
|
||||
field(Minecraft.class, "window").set(mc, window);
|
||||
field(Minecraft.class, "options").set(mc, options);
|
||||
field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class));
|
||||
field(Minecraft.class, "gui").set(mc, make(Gui.class));
|
||||
StubPlayer player = make(StubPlayer.class);
|
||||
Inventory inventory = make(Inventory.class);
|
||||
inventory.setSelectedSlot(c.get("slot").getAsInt());
|
||||
field(net.minecraft.world.entity.player.Player.class, "inventory").set(player, inventory);
|
||||
mc.player = player;
|
||||
options.discreteMouseScroll().set(c.get("discrete").getAsBoolean());
|
||||
options.mouseWheelSensitivity().set(d(c.get("sens")));
|
||||
MouseHandler h = handler(mc);
|
||||
out.println("scroll");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
h.onScroll(1L, d(op.get(0)), d(op.get(1)));
|
||||
out.println(inventory.getSelectedSlot());
|
||||
}
|
||||
}
|
||||
|
||||
static int keys = 0;
|
||||
|
||||
static void key(JsonObject c, PrintWriter out) throws Exception {
|
||||
AtomicBoolean option = new AtomicBoolean();
|
||||
int value = 10000 + keys++;
|
||||
KeyMapping mapping = c.get("toggle").getAsBoolean()
|
||||
? new ToggleKeyMapping("key.test" + value, c.get("keyboard").getAsBoolean() ? InputConstants.Type.KEYBOARD : InputConstants.Type.MOUSE,
|
||||
value, KeyMapping.Category.MISC, option::get, c.get("restore").getAsBoolean())
|
||||
: new KeyMapping("key.test" + value, InputConstants.Type.KEYBOARD, value, KeyMapping.Category.MISC);
|
||||
var release = KeyMapping.class.getDeclaredMethod("release");
|
||||
release.setAccessible(true);
|
||||
var key = c.get("toggle").getAsBoolean() && !c.get("keyboard").getAsBoolean()
|
||||
? InputConstants.Type.MOUSE.getOrCreate(value) : InputConstants.Type.KEYBOARD.getOrCreate(value);
|
||||
out.println("key");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String result = "";
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "option" -> option.set(op.get(1).getAsBoolean());
|
||||
case "down" -> mapping.setDown(op.get(1).getAsBoolean());
|
||||
case "release" -> release.invoke(mapping);
|
||||
case "restore" -> result = mapping instanceof ToggleKeyMapping t ? " " + t.shouldRestoreStateOnScreenClosed() : " false";
|
||||
case "click" -> KeyMapping.click(key);
|
||||
case "consume" -> result = " " + mapping.consumeClick();
|
||||
case "ingame" -> {
|
||||
var m = KeyMapping.class.getDeclaredMethod("shouldSetOnIngameFocus");
|
||||
m.setAccessible(true);
|
||||
result = " " + m.invoke(mapping);
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
out.println(op.get(0).getAsString() + result + " " + mapping.isDown());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.SimpleContainer;
|
||||
import net.minecraft.world.entity.EntityEquipment;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.inventory.*;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
|
||||
/**
|
||||
* Original oracle: AbstractContainerMenu.clicked over vanilla's real menu
|
||||
* classes. A stand-in player (inventory, drops recorded) and a stand-in server
|
||||
* level (real RecipeManager, no networking) run each case's clicks; after
|
||||
* every click the slots, carried stack, data slots, drops and player state
|
||||
* are printed as canonical NBT.
|
||||
*/
|
||||
public final class VanillaMenuOracle {
|
||||
static Object unsafe;
|
||||
static java.lang.reflect.Method allocate;
|
||||
static RecipeManager recipes;
|
||||
static final List<String> drops = new ArrayList<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) {
|
||||
try {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
f.set(target, value);
|
||||
}
|
||||
|
||||
static final class Server extends net.minecraft.server.dedicated.DedicatedServer {
|
||||
Server() {
|
||||
super(null, null, null, null, null, null, null, null, null, null);
|
||||
}
|
||||
@Override public RecipeManager getRecipeManager() { return recipes; }
|
||||
}
|
||||
|
||||
static final class Connection extends ServerGamePacketListenerImpl {
|
||||
Connection() {
|
||||
super(null, null, null, null);
|
||||
}
|
||||
@Override public void send(net.minecraft.network.protocol.Packet<?> packet) { }
|
||||
}
|
||||
|
||||
static final class World extends ServerLevel {
|
||||
Server server;
|
||||
World() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
|
||||
@Override public RecipeManager recipeAccess() { return recipes; }
|
||||
@Override public boolean isClientSide() { return false; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
|
||||
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
|
||||
@Override public net.minecraft.world.level.gamerules.GameRules getGameRules() { return new net.minecraft.world.level.gamerules.GameRules(FeatureFlags.DEFAULT_FLAGS); }
|
||||
@Override public void levelEvent(net.minecraft.world.entity.Entity p, int type, BlockPos pos, int data) { }
|
||||
@Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { }
|
||||
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; }
|
||||
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
|
||||
}
|
||||
|
||||
static final class FakePlayer extends ServerPlayer {
|
||||
World world;
|
||||
boolean creative;
|
||||
Inventory inv;
|
||||
FakePlayer() {
|
||||
super(null, null, null, null);
|
||||
}
|
||||
@Override public Inventory getInventory() { return inv; }
|
||||
@Override public ServerLevel level() { return world; }
|
||||
@Override public boolean hasInfiniteMaterials() { return creative; }
|
||||
@Override public boolean isCreative() { return creative; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
@Override public EntityType<?> getType() { return net.minecraft.world.entity.EntityTypes.PLAYER; }
|
||||
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); }
|
||||
@Override public boolean canUseSlot(EquipmentSlot slot) { return true; }
|
||||
@Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { }
|
||||
@Override public boolean hasDisconnected() { return false; }
|
||||
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
|
||||
if (!stack.isEmpty()) drops.add(ParityData.canon(stack));
|
||||
return null;
|
||||
}
|
||||
@Override public void triggerRecipeCrafted(net.minecraft.world.item.crafting.RecipeHolder<?> recipe, java.util.List<ItemStack> items) { }
|
||||
@Override public int awardRecipes(java.util.Collection<net.minecraft.world.item.crafting.RecipeHolder<?>> recipes) { return 0; }
|
||||
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
|
||||
@Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); }
|
||||
@Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); }
|
||||
}
|
||||
|
||||
static AbstractContainerMenu menu(String kind, FakePlayer player, Inventory inv) {
|
||||
var access = ContainerLevelAccess.create(player.world, BlockPos.ZERO);
|
||||
if (kind.startsWith("chest")) {
|
||||
int rows = Integer.parseInt(kind.substring(5));
|
||||
MenuType<?> type = new MenuType[]{MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6}[rows - 1];
|
||||
return new ChestMenu(type, 0, inv, new SimpleContainer(9 * rows), rows);
|
||||
}
|
||||
return switch (kind) {
|
||||
case "inventory" -> new InventoryMenu(inv, true, player);
|
||||
case "crafting" -> new CraftingMenu(0, inv, access);
|
||||
case "hopper" -> new HopperMenu(0, inv);
|
||||
case "dispenser" -> new DispenserMenu(0, inv);
|
||||
case "shulker" -> new ShulkerBoxMenu(0, inv);
|
||||
case "furnace" -> new FurnaceMenu(0, inv);
|
||||
case "blast_furnace" -> new BlastFurnaceMenu(0, inv);
|
||||
case "smoker" -> new SmokerMenu(0, inv);
|
||||
case "brewing" -> new BrewingStandMenu(0, inv);
|
||||
case "crafter" -> new CrafterMenu(0, inv);
|
||||
default -> throw new IllegalArgumentException(kind);
|
||||
};
|
||||
}
|
||||
|
||||
static String state(AbstractContainerMenu menu, Inventory inv) throws Exception {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < menu.slots.size(); i++) {
|
||||
out.append(i > 0 ? " " : "").append(ParityData.canon(menu.getSlot(i).getItem()));
|
||||
}
|
||||
out.append(" | ").append(ParityData.canon(menu.getCarried()));
|
||||
Field dataSlots = AbstractContainerMenu.class.getDeclaredField("dataSlots");
|
||||
dataSlots.setAccessible(true);
|
||||
List<DataSlot> data = (List<DataSlot>) dataSlots.get(menu);
|
||||
out.append(" |");
|
||||
for (DataSlot d : data) out.append(' ').append(d.get());
|
||||
out.append(" | ").append(String.join(";", drops));
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
unsafe = field.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
recipes = new RecipeManager(ParityData.lookup);
|
||||
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
var f = JsonParser.parseString(line).getAsJsonObject();
|
||||
try {
|
||||
drops.clear();
|
||||
var world = make(World.class);
|
||||
world.server = make(Server.class);
|
||||
var player = make(FakePlayer.class);
|
||||
player.world = world;
|
||||
player.creative = f.get("creative").getAsBoolean();
|
||||
set(player, ServerPlayer.class, "connection", make(Connection.class));
|
||||
var inv = new Inventory(player, new EntityEquipment());
|
||||
player.inv = inv;
|
||||
AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv);
|
||||
set(player, Player.class, "containerMenu", menu);
|
||||
if (menu instanceof InventoryMenu im) set(player, Player.class, "inventoryMenu", im);
|
||||
var slotsJson = f.getAsJsonArray("slots");
|
||||
for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString()));
|
||||
menu.setCarried(ParityData.stack(f.get("carried").getAsString()));
|
||||
var dataJson = f.getAsJsonArray("data");
|
||||
for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt());
|
||||
drops.clear();
|
||||
out.println("init " + state(menu, inv));
|
||||
for (var opJson : f.getAsJsonArray("ops")) {
|
||||
var op = opJson.getAsJsonArray();
|
||||
int slot = op.get(0).getAsInt();
|
||||
int button = op.get(1).getAsInt();
|
||||
var input = ContainerInput.valueOf(op.get(2).getAsString());
|
||||
try {
|
||||
menu.clicked(slot, button, input, player);
|
||||
} catch (RuntimeException e) {
|
||||
Throwable cause = e.getCause() != null ? e.getCause() : e;
|
||||
out.println("error " + cause.getClass().getSimpleName());
|
||||
if (System.getenv("MENU_TRACE") != null) cause.printStackTrace();
|
||||
continue;
|
||||
}
|
||||
out.println(state(menu, inv));
|
||||
}
|
||||
out.println("end");
|
||||
} catch (Throwable e) {
|
||||
out.println("error-case " + e.getClass().getSimpleName());
|
||||
if (System.getenv("MENU_TRACE") != null) e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
|
||||
/**
|
||||
* Loads each options.txt case through the real Options.load and writes it back
|
||||
* with Options.save, then dumps the key mapping table (order, defaults,
|
||||
* categories). The Minecraft instance is an uninitialised shell that only
|
||||
* supplies the data fixer.
|
||||
*/
|
||||
public final class VanillaOptionsOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe");
|
||||
uf.setAccessible(true);
|
||||
Object unsafe = uf.get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class);
|
||||
Field fixer = Minecraft.class.getDeclaredField("fixerUpper");
|
||||
fixer.setAccessible(true);
|
||||
fixer.set(shell, DataFixers.getDataFixer());
|
||||
Field instance = Minecraft.class.getDeclaredField("instance");
|
||||
instance.setAccessible(true);
|
||||
instance.set(null, shell);
|
||||
Path cases = Path.of(args[0]);
|
||||
Path work = Files.createTempDirectory("opts");
|
||||
List<Path> files = new ArrayList<>();
|
||||
try (var s = Files.list(cases)) {
|
||||
s.sorted().forEach(files::add);
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
boolean first = true;
|
||||
for (Path file : files) {
|
||||
Path target = work.resolve("options.txt");
|
||||
Files.deleteIfExists(target);
|
||||
if (!file.getFileName().toString().equals("absent.txt")) {
|
||||
Files.copy(file, target);
|
||||
}
|
||||
Options options = new Options(shell, work.toFile());
|
||||
options.save();
|
||||
out.print("== " + file.getFileName() + "\n");
|
||||
out.print(Files.readString(target, StandardCharsets.UTF_8));
|
||||
if (first) {
|
||||
first = false;
|
||||
out.print("== keys\n");
|
||||
for (KeyMapping k : options.keyMappings) {
|
||||
out.print(k.getName() + " " + k.getDefaultKey().getName() + " " + k.getCategory().id().getPath() + " "
|
||||
+ (k instanceof ToggleKeyMapping) + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
|
||||
/**
|
||||
* Dumps Options.processOptions as a table: key, kind and default in processing
|
||||
* order. Used to (re)generate the Rust options table; the differential harness
|
||||
* then proves the Rust port agrees on loading and saving.
|
||||
*/
|
||||
public final class VanillaOptionsTableExporter {
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe");
|
||||
uf.setAccessible(true);
|
||||
Object unsafe = uf.get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class);
|
||||
Field instance = Minecraft.class.getDeclaredField("instance");
|
||||
instance.setAccessible(true);
|
||||
instance.set(null, shell);
|
||||
Path work = Files.createTempDirectory("opts");
|
||||
Options options = new Options(shell, work.toFile());
|
||||
Method process = Options.class.getDeclaredMethod("processOptions", Class.forName("net.minecraft.client.Options$FieldAccess"));
|
||||
process.setAccessible(true);
|
||||
Field valuesField = OptionInstance.class.getDeclaredField("values");
|
||||
valuesField.setAccessible(true);
|
||||
Gson gson = new Gson();
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) {
|
||||
Class<?> fa = Class.forName("net.minecraft.client.Options$FieldAccess");
|
||||
Object access = Proxy.newProxyInstance(fa.getClassLoader(), new Class<?>[]{fa}, (proxy, method, a) -> {
|
||||
String name = (String) a[0];
|
||||
Class<?> rt = method.getReturnType();
|
||||
if (a.length == 2 && a[1] instanceof OptionInstance<?> oi) {
|
||||
Object vs = valuesField.get(oi);
|
||||
var encoded = ((OptionInstance<Object>) oi).codec().encodeStart(JsonOps.INSTANCE, oi.get()).result().orElse(null);
|
||||
if (vs instanceof OptionInstance.Enum<?> en) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object v : en.values()) {
|
||||
sb.append(gson.toJson(((com.mojang.serialization.Codec<Object>) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(',');
|
||||
}
|
||||
out.println("enum " + name + " " + sb);
|
||||
}
|
||||
if (vs instanceof OptionInstance.SliderableEnum<?> en) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object v : en.values()) {
|
||||
sb.append(gson.toJson(((com.mojang.serialization.Codec<Object>) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(',');
|
||||
}
|
||||
out.println("enum " + name + " " + sb);
|
||||
}
|
||||
out.println("option " + name + " " + vs.getClass().getSimpleName() + " " + describe(vs) + " => " + gson.toJson(encoded));
|
||||
return null;
|
||||
}
|
||||
if (a.length == 2) {
|
||||
out.println("plain " + name + " " + rt.getSimpleName() + " => " + a[1]);
|
||||
return a[1];
|
||||
}
|
||||
if (a.length == 4) {
|
||||
Object conv = ((Function<Object, String>) a[3]).apply(a[1]);
|
||||
out.println("custom " + name + " => " + conv);
|
||||
return a[1];
|
||||
}
|
||||
return null;
|
||||
});
|
||||
process.invoke(options, access);
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
Field map = com.mojang.blaze3d.platform.InputConstants.Type.class.getDeclaredField("map");
|
||||
map.setAccessible(true);
|
||||
for (var type : com.mojang.blaze3d.platform.InputConstants.Type.values()) {
|
||||
var m = (it.unimi.dsi.fastutil.ints.Int2ObjectMap<com.mojang.blaze3d.platform.InputConstants.Key>) map.get(type);
|
||||
var entries = new TreeMap<Integer, String>();
|
||||
for (var e : m.int2ObjectEntrySet()) {
|
||||
entries.put(e.getIntKey(), e.getValue().getName());
|
||||
}
|
||||
for (var e : entries.entrySet()) {
|
||||
out.println(type.name().toLowerCase() + " " + e.getKey() + " " + e.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static String describe(Object vs) throws Exception {
|
||||
if (vs instanceof Record r) {
|
||||
StringBuilder sb = new StringBuilder("{");
|
||||
for (var c : r.getClass().getRecordComponents()) {
|
||||
Object v = c.getAccessor().invoke(r);
|
||||
String s = String.valueOf(v);
|
||||
if (v instanceof List<?> l) {
|
||||
s = l.toString();
|
||||
} else if (v != null && s.contains("$$Lambda")) {
|
||||
s = "<fn>";
|
||||
}
|
||||
if (c.getName().equals("codec") || c.getName().equals("valueSetter") || c.getName().equals("altCondition")
|
||||
|| c.getName().equals("validateValue") || c.getName().equals("maxSupplier") || c.getName().equals("values") && !(v instanceof List)) {
|
||||
if (c.getName().equals("maxSupplier")) {
|
||||
s = "<supplier " + ((java.util.function.IntSupplier) v).getAsInt() + ">";
|
||||
} else if (!c.getName().equals("values")) {
|
||||
s = "<fn>";
|
||||
}
|
||||
}
|
||||
sb.append(c.getName()).append('=').append(s).append(' ');
|
||||
}
|
||||
return sb.append('}').toString();
|
||||
}
|
||||
return vs.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.stream.LongStream;
|
||||
import net.minecraft.core.IdMap;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.world.level.chunk.PalettedContainer;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerRO;
|
||||
import net.minecraft.world.level.chunk.Strategy;
|
||||
|
||||
/** Runs the real PalettedContainer (single-value, linear, hash-map and global palettes, resize,
|
||||
* network write/read, pack/unpack) over scripted edits and records hashes of everything
|
||||
* observable: set results, the serialized container after every few edits, the saved form and
|
||||
* the containers read back from both. */
|
||||
public final class VanillaPalettedContainerOracle {
|
||||
private static final Gson JSON = new GsonBuilder().serializeNulls().create();
|
||||
/** The palettes compare entries by identity, as registry objects allow: intern the boxes. */
|
||||
private static final Map<Integer, Integer> INTERNED = new HashMap<>();
|
||||
private static Integer intern(int value) { return INTERNED.computeIfAbsent(value, v -> new Integer(v)); }
|
||||
private static final class Ids implements IdMap<Integer> {
|
||||
final int size;
|
||||
Ids(int size) { this.size = size; }
|
||||
public int getId(Integer value) { return value < size ? value : -1; }
|
||||
public Integer byId(int id) { return id >= 0 && id < size ? intern(id) : null; }
|
||||
public int size() { return size; }
|
||||
public Iterator<Integer> iterator() { return java.util.stream.IntStream.range(0, size).boxed().iterator(); }
|
||||
}
|
||||
private static long fnv(long h, int b) { return (h ^ (b & 0xFF)) * 0x100000001b3L; }
|
||||
private static final long BASIS = 0xcbf29ce484222325L;
|
||||
private static long hashBytes(byte[] bytes) {
|
||||
long h = BASIS;
|
||||
for (byte b : bytes) h = fnv(h, b);
|
||||
return h;
|
||||
}
|
||||
private static long hashValues(PalettedContainer<Integer> c, int bits) {
|
||||
long h = BASIS;
|
||||
int n = 1 << (3 * bits);
|
||||
for (int i = 0; i < n; i++) {
|
||||
int v = c.get(i & (n - 1) & ((1 << bits) - 1), i >> (2 * bits), (i >> bits) & ((1 << bits) - 1));
|
||||
for (int k = 0; k < 4; k++) h = fnv(h, v >> (8 * k));
|
||||
}
|
||||
return h;
|
||||
}
|
||||
private static byte[] write(PalettedContainer<Integer> c) {
|
||||
var buffer = new FriendlyByteBuf(Unpooled.buffer());
|
||||
c.write(buffer);
|
||||
byte[] bytes = new byte[buffer.readableBytes()];
|
||||
buffer.readBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
private static String wire(PalettedContainer<Integer> c) {
|
||||
byte[] bytes = write(c);
|
||||
return bytes.length + ":" + hashBytes(bytes);
|
||||
}
|
||||
/** Input line: name kind initial every i v i v ...; output: one line of fields. */
|
||||
private static String scenario(String line) {
|
||||
var t = line.trim().split(" ");
|
||||
boolean blocks = t[1].equals("blocks");
|
||||
int bits = blocks ? 4 : 2;
|
||||
Strategy<Integer> strategy = blocks ? Strategy.createForBlockStates(new Ids(35723)) : Strategy.createForBiomes(new Ids(67));
|
||||
var c = new PalettedContainer<>(intern(Integer.parseInt(t[2])), strategy);
|
||||
int every = Integer.parseInt(t[3]);
|
||||
var checkpoints = new StringJoiner(",");
|
||||
long oldsHash = BASIS;
|
||||
int n = 0, mask = (1 << bits) - 1;
|
||||
for (int k = 4; k + 1 < t.length; k += 2) {
|
||||
int i = Integer.parseInt(t[k]);
|
||||
int old = c.getAndSetUnchecked(i & mask, i >> (2 * bits), (i >> bits) & mask, intern(Integer.parseInt(t[k + 1])));
|
||||
for (int j = 0; j < 4; j++) oldsHash = fnv(oldsHash, old >> (8 * j));
|
||||
if (++n % every == 0) checkpoints.add(wire(c));
|
||||
}
|
||||
var out = new StringJoiner(" ");
|
||||
out.add(t[0]).add(Long.toString(oldsHash)).add("cp=" + checkpoints).add("bits=" + c.bitsPerEntry());
|
||||
out.add("final=" + wire(c)).add("values=" + hashValues(c, bits));
|
||||
var read = new PalettedContainer<>(intern(0), strategy);
|
||||
read.read(new FriendlyByteBuf(Unpooled.wrappedBuffer(write(c))));
|
||||
out.add("read=" + hashValues(read, bits) + "/" + wire(read));
|
||||
var packed = c.pack(strategy);
|
||||
long[] storage = packed.storage().map(LongStream::toArray).orElse(null);
|
||||
long storageHash = BASIS;
|
||||
if (storage != null) for (long word : storage) for (int j = 0; j < 8; j++) storageHash = fnv(storageHash, (int) (word >> (8 * j)));
|
||||
var palette = new StringJoiner(",");
|
||||
for (int v : packed.paletteEntries()) palette.add(Integer.toString(v));
|
||||
out.add("packed=" + packed.bitsPerEntry() + "/" + storageHash + "/" + palette);
|
||||
var loaded = PalettedContainer.unpack(strategy, new PalettedContainerRO.PackedData<>(packed.paletteEntries(),
|
||||
Optional.ofNullable(storage).map(LongStream::of), -1)).getOrThrow();
|
||||
out.add("loaded=" + hashValues(loaded, bits) + "/" + wire(loaded));
|
||||
return out.toString();
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
try (var input = Files.newBufferedReader(Path.of(args[0])); var output = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
for (String line; (line = input.readLine()) != null; ) {
|
||||
output.write(scenario(line));
|
||||
output.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.*;
|
||||
|
||||
/**
|
||||
* Original oracle: vanilla's RecipeManager over the data pack's recipes.
|
||||
* Tab-separated commands (stacks are SNBT of ItemStack.CODEC, "-" is empty):
|
||||
* craft N cells..., cook TYPE stack, stonecut stack, smith template base addition.
|
||||
* "dump" prints every crafting recipe's ingredient item lists for the generator.
|
||||
*/
|
||||
public final class VanillaRecipeOracle {
|
||||
static RecipeManager recipes;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
recipes = new RecipeManager(ParityData.lookup);
|
||||
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
|
||||
if (args[0].equals("dump")) {
|
||||
dump(Path.of(args[1]));
|
||||
return;
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
String result;
|
||||
try {
|
||||
result = run(line.split("\t", -1));
|
||||
} catch (Exception e) {
|
||||
result = "error";
|
||||
}
|
||||
out.println(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String run(String[] f) throws Exception {
|
||||
switch (f[0]) {
|
||||
case "craft": {
|
||||
int n = Integer.parseInt(f[1]);
|
||||
List<ItemStack> items = new ArrayList<>();
|
||||
for (int i = 0; i < n * n; i++) items.add(ParityData.stack(f[2 + i]));
|
||||
var positioned = CraftingInput.ofPositioned(n, n, items);
|
||||
var input = positioned.input();
|
||||
if (input.isEmpty()) return "none";
|
||||
var found = recipes.getRecipeFor(RecipeType.CRAFTING, input, null);
|
||||
if (found.isEmpty()) return "none";
|
||||
var recipe = found.get().value();
|
||||
var result = recipe.assemble(input);
|
||||
var rest = recipe.getRemainingItems(input);
|
||||
StringJoiner joiner = new StringJoiner(";");
|
||||
for (int i = 0; i < rest.size(); i++) {
|
||||
if (rest.get(i).isEmpty()) continue;
|
||||
int at = (positioned.top() + i / input.width()) * n + positioned.left() + i % input.width();
|
||||
joiner.add(at + "=" + ParityData.canon(rest.get(i)));
|
||||
}
|
||||
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(result) + "\t" + joiner;
|
||||
}
|
||||
case "cook": {
|
||||
RecipeType<? extends AbstractCookingRecipe> type = switch (f[1]) {
|
||||
case "smelting" -> RecipeType.SMELTING;
|
||||
case "blasting" -> RecipeType.BLASTING;
|
||||
case "smoking" -> RecipeType.SMOKING;
|
||||
default -> RecipeType.CAMPFIRE_COOKING;
|
||||
};
|
||||
return cook(type, ParityData.stack(f[2]));
|
||||
}
|
||||
case "stonecut": {
|
||||
var stack = ParityData.stack(f[1]);
|
||||
StringJoiner joiner = new StringJoiner(";");
|
||||
for (var entry : recipes.getSynchronizedStonecutterRecipes().selectByInput(stack).entries()) {
|
||||
var holder = entry.recipe().recipe().get();
|
||||
joiner.add(holder.id().identifier().getPath() + "=" + ParityData.canon(holder.value().assemble(new SingleRecipeInput(stack))));
|
||||
}
|
||||
return joiner.toString();
|
||||
}
|
||||
case "smith": {
|
||||
var input = new SmithingRecipeInput(ParityData.stack(f[1]), ParityData.stack(f[2]), ParityData.stack(f[3]));
|
||||
var found = recipes.getRecipeFor(RecipeType.SMITHING, input, null);
|
||||
if (found.isEmpty()) return "none";
|
||||
return ParityData.canon(found.get().value().assemble(input));
|
||||
}
|
||||
default:
|
||||
throw new IllegalArgumentException(f[0]);
|
||||
}
|
||||
}
|
||||
|
||||
static <T extends AbstractCookingRecipe> String cook(RecipeType<T> type, ItemStack stack) {
|
||||
if (stack.isEmpty()) return "none";
|
||||
var input = new SingleRecipeInput(stack);
|
||||
var found = recipes.getRecipeFor(type, input, null);
|
||||
if (found.isEmpty()) return "none";
|
||||
var recipe = found.get().value();
|
||||
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(recipe.assemble(input)) + "\t" + recipe.experience() + "\t" + recipe.cookingTime();
|
||||
}
|
||||
|
||||
static String items(Ingredient ingredient) {
|
||||
if (ingredient == null) return "[]";
|
||||
StringBuilder row = new StringBuilder("[");
|
||||
var items = ingredient.items().toList();
|
||||
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
|
||||
return row.append(']').toString();
|
||||
}
|
||||
|
||||
static void dump(Path path) throws Exception {
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) {
|
||||
for (var holder : recipes.getRecipes()) {
|
||||
var recipe = holder.value();
|
||||
if (recipe instanceof SmithingRecipe smithing) {
|
||||
out.println("{\"id\":\"" + holder.id().identifier().getPath() + "\",\"kind\":\"" + recipe.getClass().getSimpleName()
|
||||
+ "\",\"template\":" + items(smithing.templateIngredient().orElse(null)) + ",\"base\":" + items(smithing.baseIngredient())
|
||||
+ ",\"addition\":" + items(smithing.additionIngredient().orElse(null)) + "}");
|
||||
continue;
|
||||
}
|
||||
if (recipe.getType() != RecipeType.CRAFTING) continue;
|
||||
var info = recipe.placementInfo();
|
||||
StringBuilder row = new StringBuilder();
|
||||
row.append("{\"id\":\"").append(holder.id().identifier().getPath()).append("\",\"kind\":\"").append(recipe.getClass().getSimpleName()).append("\",\"slots\":[");
|
||||
for (int i = 0; i < info.slotsToIngredientIndex().size(); i++) row.append(i > 0 ? "," : "").append(info.slotsToIngredientIndex().getInt(i));
|
||||
row.append("],\"ingredients\":[");
|
||||
boolean firstIngredient = true;
|
||||
for (var ingredient : info.ingredients()) {
|
||||
row.append(firstIngredient ? "" : ",").append('[');
|
||||
firstIngredient = false;
|
||||
var items = ingredient.items().toList();
|
||||
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
|
||||
row.append(']');
|
||||
}
|
||||
row.append("]}");
|
||||
out.println(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import net.minecraft.client.color.block.BlockColors;
|
||||
import net.minecraft.client.renderer.BiomeColors;
|
||||
import net.minecraft.client.renderer.block.*;
|
||||
@@ -29,6 +30,14 @@ import net.minecraft.world.level.CardinalLighting;
|
||||
import net.minecraft.world.level.ColorResolver;
|
||||
import net.minecraft.world.level.EmptyBlockGetter;
|
||||
import net.minecraft.world.level.LightLayer;
|
||||
import net.minecraft.world.level.DryFoliageColor;
|
||||
import net.minecraft.world.level.FoliageColor;
|
||||
import net.minecraft.world.level.GrassColor;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.util.ARGB;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
@@ -100,6 +109,12 @@ public final class VanillaSectionMeshOracle {
|
||||
return (T) value;
|
||||
}
|
||||
}
|
||||
private static int[] colormap(String name) throws IOException {
|
||||
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream("/assets/minecraft/textures/colormap/" + name + ".png");
|
||||
var image = NativeImage.read(input)) {
|
||||
return image.makePixelArray();
|
||||
}
|
||||
}
|
||||
private static String resource(String path) throws IOException {
|
||||
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) {
|
||||
return input == null ? null : new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
@@ -139,12 +154,47 @@ public final class VanillaSectionMeshOracle {
|
||||
return baked.computeIfAbsent(state, s -> Objects.requireNonNull(roots.get(s), () -> "no model for " + s).bake(s, baker));
|
||||
}
|
||||
}
|
||||
/** ClientLevel.calculateBlockTint over a BiomeManager with a fixed noise-biome map:
|
||||
* quart cells listed in the scene, a default elsewhere in the 3x3 chunk region and
|
||||
* plains outside it (chunks that are not loaded). */
|
||||
private static final class TintBiomes {
|
||||
final BiomeManager manager; final int radius;
|
||||
final Map<Long, Holder<Biome>> cells = new HashMap<>();
|
||||
final Holder<Biome> dflt, plains;
|
||||
TintBiomes(JsonObject o, HolderLookup.RegistryLookup<Biome> lookup) {
|
||||
radius = o.get("radius").getAsInt();
|
||||
Function<String, Holder<Biome>> named = name -> lookup.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(name)));
|
||||
plains = named.apply("minecraft:plains");
|
||||
dflt = named.apply(o.get("default").getAsString());
|
||||
for (var item : o.getAsJsonArray("cells")) {
|
||||
var c = item.getAsJsonArray();
|
||||
cells.put(BlockPos.asLong(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), named.apply(c.get(3).getAsString()));
|
||||
}
|
||||
manager = new BiomeManager((qx, qy, qz) -> {
|
||||
if (qx < -4 || qx >= 8 || qz < -4 || qz >= 8) return plains;
|
||||
return cells.getOrDefault(BlockPos.asLong(qx, Math.max(-16, Math.min(79, qy)), qz), dflt);
|
||||
}, o.get("seed").getAsLong());
|
||||
}
|
||||
int tint(BlockPos pos, ColorResolver resolver) {
|
||||
if (radius == 0) return resolver.getColor(manager.getBiome(pos).value(), pos.getX(), pos.getZ());
|
||||
int count = (radius * 2 + 1) * (radius * 2 + 1);
|
||||
int red = 0, green = 0, blue = 0;
|
||||
var cursor = new Cursor3D(pos.getX() - radius, pos.getY(), pos.getZ() - radius, pos.getX() + radius, pos.getY(), pos.getZ() + radius);
|
||||
var next = new BlockPos.MutableBlockPos();
|
||||
while (cursor.advance()) {
|
||||
next.set(cursor.nextX(), cursor.nextY(), cursor.nextZ());
|
||||
int color = resolver.getColor(manager.getBiome(next).value(), next.getX(), next.getZ());
|
||||
red += ARGB.red(color); green += ARGB.green(color); blue += ARGB.blue(color);
|
||||
}
|
||||
return ARGB.color(red / count, green / count, blue / count);
|
||||
}
|
||||
}
|
||||
private static long key(int x, int y, int z) { return BlockPos.asLong(x, y, z); }
|
||||
/** A fixed region: listed blocks over air, listed light over a default. */
|
||||
private static final class Scene implements BlockAndTintGetter {
|
||||
final Map<Long, BlockState> blocks = new HashMap<>();
|
||||
final Map<Long, int[]> light = new HashMap<>();
|
||||
int[] defaultLight; boolean nether; int grass, foliage, dry, water;
|
||||
int[] defaultLight; boolean nether; int grass, foliage, dry, water; TintBiomes biomes;
|
||||
public CardinalLighting cardinalLighting() { return nether ? CardinalLighting.NETHER : CardinalLighting.DEFAULT; }
|
||||
public LevelLightEngine getLightEngine() { return LevelLightEngine.EMPTY; }
|
||||
public int getBrightness(LightLayer layer, BlockPos pos) {
|
||||
@@ -152,6 +202,7 @@ public final class VanillaSectionMeshOracle {
|
||||
return layer == LightLayer.SKY ? value[0] : value[1];
|
||||
}
|
||||
public int getBlockTint(BlockPos pos, ColorResolver resolver) {
|
||||
if (biomes != null) return biomes.tint(pos, resolver);
|
||||
int rgb = resolver == BiomeColors.GRASS_COLOR_RESOLVER ? grass : resolver == BiomeColors.FOLIAGE_COLOR_RESOLVER ? foliage
|
||||
: resolver == BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER ? dry : resolver == BiomeColors.WATER_COLOR_RESOLVER ? water : -1;
|
||||
if (rgb == -1) throw new AssertionError("unexpected colour resolver");
|
||||
@@ -165,7 +216,7 @@ public final class VanillaSectionMeshOracle {
|
||||
}
|
||||
private static final class Recorder {
|
||||
final List<Object> quads = new ArrayList<>();
|
||||
List<Object> pending; BlockPos block; String kind, layer, sprite;
|
||||
List<Object> pending; boolean forceSolid; BlockPos block; String kind, layer, sprite;
|
||||
void vertex(float x, float y, float z, int color, float u, float v, int light) {
|
||||
if (pending == null) pending = new ArrayList<>();
|
||||
pending.add(new Object[]{x, y, z, u, v, color, light});
|
||||
@@ -176,7 +227,7 @@ public final class VanillaSectionMeshOracle {
|
||||
}
|
||||
}
|
||||
private static String layer(ChunkSectionLayer layer) { return layer.name().toLowerCase(Locale.ROOT); }
|
||||
private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids) {
|
||||
private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids, HolderLookup.RegistryLookup<Biome> biomeLookup) {
|
||||
var scene = new Scene();
|
||||
var light = row.getAsJsonArray("light");
|
||||
scene.defaultLight = new int[]{light.get(0).getAsInt(), light.get(1).getAsInt()};
|
||||
@@ -184,6 +235,7 @@ public final class VanillaSectionMeshOracle {
|
||||
var colors = row.getAsJsonObject("colors");
|
||||
scene.grass = colors.get("grass").getAsInt(); scene.foliage = colors.get("foliage").getAsInt();
|
||||
scene.dry = colors.get("dry_foliage").getAsInt(); scene.water = colors.get("water").getAsInt();
|
||||
if (row.has("biomes")) scene.biomes = new TintBiomes(row.getAsJsonObject("biomes"), biomeLookup);
|
||||
for (var item : row.getAsJsonArray("blocks")) {
|
||||
var b = item.getAsJsonArray();
|
||||
scene.blocks.put(key(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt()), Block.stateById(b.get(3).getAsInt()));
|
||||
@@ -194,10 +246,13 @@ public final class VanillaSectionMeshOracle {
|
||||
}
|
||||
var recorder = new Recorder();
|
||||
BlockModelLighter.enableCaching();
|
||||
var renderer = new ModelBlockRenderer(true, true, BlockColors.createDefault());
|
||||
boolean smooth = !row.has("smooth") || row.get("smooth").getAsBoolean();
|
||||
boolean cutoutLeaves = !row.has("cutout_leaves") || row.get("cutout_leaves").getAsBoolean();
|
||||
LeavesBlock.setCutoutLeaves(cutoutLeaves);
|
||||
var renderer = new ModelBlockRenderer(smooth, true, BlockColors.createDefault());
|
||||
var fluidRenderer = new FluidRenderer(fluids);
|
||||
BlockQuadOutput output = (x, y, z, quad, instance) -> {
|
||||
recorder.kind = "model"; recorder.layer = layer(quad.materialInfo().layer());
|
||||
recorder.kind = "model"; recorder.layer = recorder.forceSolid ? "solid" : layer(quad.materialInfo().layer());
|
||||
recorder.sprite = quad.materialInfo().sprite().contents().name().toString();
|
||||
int emission = quad.materialInfo().lightEmission();
|
||||
int slot = Arrays.asList(FLUID_SPRITES).indexOf(recorder.sprite);
|
||||
@@ -233,9 +288,8 @@ public final class VanillaSectionMeshOracle {
|
||||
}, state, fluid);
|
||||
}
|
||||
if (state.getRenderShape() == RenderShape.MODEL) {
|
||||
renderer.tesselateBlock(ModelBlockRenderer.forceOpaque(true, state) ? (x, y, z, quad, instance) -> {
|
||||
throw new AssertionError("cutout leaves are enabled");
|
||||
} : output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()),
|
||||
recorder.forceSolid = ModelBlockRenderer.forceOpaque(cutoutLeaves, state);
|
||||
renderer.tesselateBlock(output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()),
|
||||
scene, pos, state, models.get(state), state.getSeed(pos));
|
||||
}
|
||||
}
|
||||
@@ -244,6 +298,7 @@ public final class VanillaSectionMeshOracle {
|
||||
return map("name", row.get("name").getAsString(), "quads", recorder.quads);
|
||||
}
|
||||
private static BlockColors COLORS;
|
||||
private static HolderLookup.RegistryLookup<Biome> biomeLookup;
|
||||
/** Per-state facts the Rust mesher derives from prepared resources. */
|
||||
private static Object facts(BlockState state, int id) {
|
||||
var level = EmptyBlockGetter.INSTANCE;
|
||||
@@ -266,6 +321,7 @@ public final class VanillaSectionMeshOracle {
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject());
|
||||
LeavesBlock.setCutoutLeaves(true);
|
||||
GrassColor.init(colormap("grass")); FoliageColor.init(colormap("foliage")); DryFoliageColor.init(colormap("dry_foliage"));
|
||||
COLORS = BlockColors.createDefault();
|
||||
if (args[0].equals("facts")) {
|
||||
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
@@ -288,10 +344,11 @@ public final class VanillaSectionMeshOracle {
|
||||
var atlas = new SpriteLoader.Preparations(16, 16, 0, missing, Map.of(), CompletableFuture.completedFuture(null));
|
||||
var materials = new Materials(atlas);
|
||||
var models = new Models(blocks, materials);
|
||||
biomeLookup = net.minecraft.data.registries.VanillaRegistries.createWorldLookup().lookupOrThrow(Registries.BIOME);
|
||||
var fluidModels = FluidStateModelSet.bake(materials);
|
||||
var fluids = new FluidStateModelSet(fluidModels, fluidModels.values().iterator().next());
|
||||
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids))); output.newLine(); }
|
||||
for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids, biomeLookup))); output.newLine(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Shared plumbing for the interaction/inventory differential harnesses
|
||||
(test_recipe_parity, test_menu_click_parity, test_block_interaction_parity):
|
||||
compile and run a vanilla Java oracle headlessly, run the matching Rust
|
||||
example, and report differing lines grouped by a key."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
|
||||
|
||||
def work_dir(name):
|
||||
path = lab.LOCAL / name
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
class Vanilla:
|
||||
"""Compiles oracles against the pinned server jar and runs them."""
|
||||
|
||||
def __init__(self, work):
|
||||
self.lock, self.jars, self.libraries = base.verify_artifacts()
|
||||
self.work = work
|
||||
self.classes = work / 'classes'
|
||||
self.classes.mkdir(exist_ok=True)
|
||||
self.deps = os.pathsep.join(map(str, [self.jars['server'], *self.libraries]))
|
||||
|
||||
def compile(self, *oracles):
|
||||
sources = [PARITY / (name + '.java') for name in oracles]
|
||||
done = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none',
|
||||
'-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', '-Xmaxerrs', '30',
|
||||
'-cp', self.deps, '-d', str(self.classes), *map(str, sources)], capture_output=True, text=True)
|
||||
if done.returncode:
|
||||
print(done.stderr.replace(str(lab.ROOT) + '/', ''))
|
||||
raise SystemExit('javac failed')
|
||||
|
||||
def run(self, oracle, *args, heap='2G'):
|
||||
subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps,
|
||||
'dev.horizonlab.parity.' + oracle, *map(str, args)], check=True)
|
||||
|
||||
|
||||
def cargo_example(package, example, *args, profile=None):
|
||||
command = ['cargo', 'run', '-q', '-j3']
|
||||
if profile:
|
||||
command += ['--profile', profile]
|
||||
command += ['-p', package, '--example', example, '--', *map(str, args)]
|
||||
subprocess.run(command, check=True, cwd=lab.ROOT)
|
||||
|
||||
|
||||
def compare(cases, native_path, rust_path, key, describe=None, limit=3):
|
||||
"""Print differing cases grouped by key(case, native_line); returns the count."""
|
||||
native = Path(native_path).read_text().split('\n')
|
||||
rust = Path(rust_path).read_text().split('\n')
|
||||
if len(native) != len(rust):
|
||||
print(f'line counts differ: native {len(native)} rust {len(rust)}')
|
||||
groups = {}
|
||||
for case, a, b in zip(cases, native, rust):
|
||||
if a != b:
|
||||
groups.setdefault(key(case, a), []).append((case, a, b))
|
||||
describe = describe or (lambda case: case if isinstance(case, str) else json.dumps(case))
|
||||
total = sum(len(v) for v in groups.values())
|
||||
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
|
||||
print(f'{name}: {len(entries)} differing')
|
||||
for case, a, b in entries[:limit]:
|
||||
print(f' case {describe(case)}\n native {a}\n rust {b}')
|
||||
print(f'{len(cases) - total}/{len(cases)} cases match')
|
||||
return total
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Shared plumbing for single-oracle differential harnesses.
|
||||
|
||||
A harness supplies a Java oracle (compiled against the pinned client jar and its
|
||||
libraries), a Rust example probe, and a text input; both programs write one
|
||||
result line per input line and the outputs must be byte-identical."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
|
||||
def run_logged(command, build, name, timeout=900, **kwargs):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
subprocess.run([str(c) for c in command], cwd=lab.ROOT, check=True, timeout=timeout,
|
||||
stdout=log, stderr=subprocess.STDOUT, **kwargs)
|
||||
|
||||
|
||||
def compile_oracle(build, oracle_name, jars, libraries, java_major):
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle_name + '.java')
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
run_logged(['javac', '--release', java_major, '-proc:none', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
build, 'compile-java-' + oracle_name)
|
||||
return classes, dependencies, oracle
|
||||
|
||||
|
||||
def build_probe(build, example):
|
||||
run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example],
|
||||
build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3'))
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
|
||||
return Path(metadata['target_directory']) / 'debug/examples' / example
|
||||
|
||||
|
||||
def java_run(build, classes, dependencies, main_class, args, name, jvm=()):
|
||||
run_logged(['java', '-Xmx2g', '-Djava.awt.headless=true', *jvm, '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.' + main_class, *args], build, name)
|
||||
|
||||
|
||||
def compare(client_out, rust_out, expected_lines):
|
||||
matched = base.compare(client_out, rust_out)
|
||||
if matched != expected_lines:
|
||||
raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines')
|
||||
return matched
|
||||
|
||||
|
||||
def differential(name, oracle, probe, make_input, scope, sources=(), expected_lines=None):
|
||||
"""Compile the oracle and probe, run both on one input and require identical output."""
|
||||
import platform
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = lab.LOCAL / name
|
||||
build.mkdir(exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle_path = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle + '.java')
|
||||
all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py',
|
||||
lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock',
|
||||
lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs',
|
||||
lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)]
|
||||
tested = base.source_hashes(all_sources)
|
||||
input_path, units = make_input(build)
|
||||
input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None
|
||||
classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major'])
|
||||
binary = build_probe(build, probe)
|
||||
run_logged([binary, input_path, build / 'rust.txt'], build, 'rust')
|
||||
java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client')
|
||||
try:
|
||||
matched = base.compare(build / 'client.txt', build / 'rust.txt')
|
||||
except AssertionError as error:
|
||||
raise AssertionError(str(error) + explain(build, str(error))) from None
|
||||
if expected_lines is not None and matched != expected_lines:
|
||||
raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines')
|
||||
base.ensure_sources_unchanged(all_sources, tested)
|
||||
if input_hash is not None and input_hash != lab.digest(input_path, 'sha256'):
|
||||
raise AssertionError('Input fixtures changed')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'],
|
||||
platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], units=units,
|
||||
sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'),
|
||||
matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope))
|
||||
print(f'{units:,} {name} cases match the pinned client ({matched:,} output lines): {report}', flush=True)
|
||||
return matched
|
||||
|
||||
|
||||
def explain(build, message):
|
||||
"""Summarise differing sections ("== name" blocks) of multi-case outputs."""
|
||||
def sections(path):
|
||||
out, name = {}, None
|
||||
for line in path.read_text(encoding='utf-8', errors='replace').splitlines():
|
||||
if line.startswith('== '):
|
||||
name = line[3:]
|
||||
out[name] = []
|
||||
elif name is not None:
|
||||
out[name].append(line)
|
||||
return out
|
||||
left, right = sections(build / 'client.txt'), sections(build / 'rust.txt')
|
||||
report, count = '', 0
|
||||
for name in left:
|
||||
if left[name] != right.get(name):
|
||||
count += 1
|
||||
if count <= 25:
|
||||
case = build / 'cases' / name
|
||||
text = case.read_text(encoding='utf-8', errors='replace') if case.is_file() else ''
|
||||
a, b = left[name], right.get(name, [])
|
||||
diffs = [(x, y) for x, y in zip(a, b) if x != y][:4]
|
||||
if len(a) != len(b):
|
||||
diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>'))
|
||||
report += f"\n case {name}: {text[:300]!r}\n differences (vanilla, rust): {diffs}"
|
||||
return f'\n{count} differing cases.' + report
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the data-driven axe/hoe/shovel block transformers with vanilla.
|
||||
|
||||
The Java oracle (VanillaBlockTransformerOracle) evaluates the registry's
|
||||
BlockStateProviders on a stand-in level; the Rust example
|
||||
(block_transform_fixture) evaluates horizon_client::block_transform. Cases are
|
||||
every block state any transformer mentions (plus a random sample of all states)
|
||||
under each transformer, with a few blocks above and three clicked faces.
|
||||
"""
|
||||
import argparse
|
||||
import random
|
||||
try:
|
||||
from . import interaction_lab as lib, lab
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import lab
|
||||
|
||||
ABOVE = ['minecraft:air|', 'minecraft:cave_air|', 'minecraft:stone|', 'minecraft:water|level=0', 'minecraft:oak_slab|type=bottom,waterlogged=false']
|
||||
FACES = ['up', 'down', 'north']
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=7)
|
||||
parser.add_argument('--sample', type=int, default=3000)
|
||||
parser.add_argument('--limit', type=int, default=4)
|
||||
args = parser.parse_args()
|
||||
work = lib.work_dir('block-transformer-parity')
|
||||
vanilla = lib.Vanilla(work)
|
||||
vanilla.compile('ParityData', 'VanillaBlockTransformerOracle')
|
||||
vanilla.run('VanillaBlockTransformerOracle', 'dump', work / 'states.txt')
|
||||
states = (work / 'states.txt').read_text().splitlines()
|
||||
mentioned = set()
|
||||
for path in (lib.RESOURCES / 'data/minecraft/block_transformer').glob('*.json'):
|
||||
text = path.read_text()
|
||||
for name in set(__import__('re').findall(r'"minecraft:([a-z_0-9]+)"', text)):
|
||||
mentioned.add('minecraft:' + name)
|
||||
tags = set()
|
||||
for tag in ['turns_into_farmland', 'turns_into_dirt_path', 'air']:
|
||||
for name in __import__('json').loads((lib.RESOURCES / 'data/minecraft/tags/block' / (tag + '.json')).read_text())['values']:
|
||||
if not name.startswith('#'):
|
||||
tags.add(name)
|
||||
rng = random.Random(args.seed)
|
||||
chosen = [s for s in states if s.split('|')[0] in mentioned or s.split('|')[0] in tags or 'copper' in s or 'lightning_rod' in s]
|
||||
chosen += rng.sample(states, args.sample)
|
||||
cases = []
|
||||
for transformer in ['axe', 'hoe', 'shovel', 'honeycomb']:
|
||||
for state in chosen:
|
||||
for face in FACES:
|
||||
cases.append('\t'.join([transformer, face, state, rng.choice(ABOVE)]))
|
||||
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
|
||||
vanilla.run('VanillaBlockTransformerOracle', work / 'cases.txt', work / 'native.txt')
|
||||
lib.cargo_example('horizon-client', 'block_transform_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
|
||||
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
|
||||
lambda case, line: case.split('\t')[0] + ' ' + line.split('\t')[0][:12], None, args.limit)
|
||||
raise SystemExit(1 if total else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare cauldron item interactions with vanilla's CauldronInteractions.
|
||||
|
||||
The Java oracle (VanillaCauldronOracle) calls the cauldron block's useItemOn
|
||||
with a recording level and player; the Rust example (cauldron_fixture) runs
|
||||
horizon_client::cauldron. Every item is used on every cauldron state (empty,
|
||||
water, lava and powder snow at each level), with water potions, dyed armour,
|
||||
patterned banners and shulker boxes, in survival and creative, under water or
|
||||
not, and with a crowded inventory. The result, block writes, sounds, drops and
|
||||
the final inventory are compared.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
try:
|
||||
from . import interaction_lab as lib, lab
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import lab
|
||||
|
||||
STATES = ['minecraft:cauldron|', 'minecraft:water_cauldron|level=1', 'minecraft:water_cauldron|level=2',
|
||||
'minecraft:water_cauldron|level=3', 'minecraft:lava_cauldron|', 'minecraft:powder_snow_cauldron|level=1',
|
||||
'minecraft:powder_snow_cauldron|level=3']
|
||||
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
|
||||
'blue', 'brown', 'green', 'red', 'black']
|
||||
|
||||
|
||||
def snbt(item, count=1, **components):
|
||||
body = ','.join('"minecraft:%s":%s' % (k, v) for k, v in sorted(components.items()))
|
||||
return '{id:"%s",count:%d%s}' % (item, count, ',components:{%s}' % body if body else '')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=7)
|
||||
parser.add_argument('--limit', type=int, default=4)
|
||||
args = parser.parse_args()
|
||||
work = lib.work_dir('cauldron-parity')
|
||||
vanilla = lib.Vanilla(work)
|
||||
vanilla.compile('ParityData', 'VanillaCauldronOracle')
|
||||
items = json.loads((lib.RESOURCES / 'items.json').read_text())
|
||||
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
|
||||
rng = random.Random(args.seed)
|
||||
held = []
|
||||
for name, info in items.items():
|
||||
if name == 'minecraft:air':
|
||||
continue
|
||||
top = info.get('minecraft:max_stack_size', 64)
|
||||
held.append(snbt(name, 1))
|
||||
held.append(snbt(name, rng.randrange(1, top + 1)))
|
||||
for color in DYES:
|
||||
for layers in range(0, 4):
|
||||
body = '[%s]' % ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(patterns), rng.choice(DYES)) for _ in range(layers))
|
||||
held.append(snbt('minecraft:%s_banner' % color, rng.choice([1, 3]), banner_patterns=body))
|
||||
held.append(snbt('minecraft:%s_shulker_box' % color, rng.choice([1, 2])))
|
||||
for item in ['leather_helmet', 'leather_chestplate', 'leather_leggings', 'leather_boots', 'leather_horse_armor', 'wolf_armor']:
|
||||
held.append(snbt('minecraft:' + item, 1, dyed_color=rng.randrange(1 << 24)))
|
||||
for potion in ['minecraft:water', 'minecraft:healing', 'minecraft:awkward']:
|
||||
for item in ['potion', 'splash_potion', 'lingering_potion']:
|
||||
held.append(snbt('minecraft:' + item, rng.choice([1, 2]), potion_contents='{potion:"%s"}' % potion))
|
||||
cases = []
|
||||
filler = [snbt(i, 64) for i in ['minecraft:stone', 'minecraft:dirt', 'minecraft:cobblestone']]
|
||||
for state in STATES:
|
||||
for stack in held:
|
||||
crowded = rng.random() < 0.25
|
||||
inventory = [[i, rng.choice(filler)] for i in range(1, 36)] if crowded else []
|
||||
if not crowded and rng.random() < 0.3:
|
||||
inventory = [[rng.randrange(1, 36), snbt('minecraft:bucket', rng.randrange(1, 16))]]
|
||||
cases.append({'state': state, 'held': stack, 'creative': rng.random() < 0.3, 'under_water': rng.random() < 0.3,
|
||||
'inventory': inventory})
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
|
||||
vanilla.run('VanillaCauldronOracle', work / 'cases.jsonl', work / 'native.txt')
|
||||
lib.cargo_example('horizon-client', 'cauldron_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
|
||||
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
|
||||
lambda case, line: case['state'].split('|')[0] + ' ' + line.split('\t')[0],
|
||||
lambda case: json.dumps(case)[:700], args.limit)
|
||||
raise SystemExit(1 if total else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the game loop and input handling with the pinned client: the
|
||||
DeltaTracker.Timer, ServerTickRateManager (freeze, step, sprint), Window
|
||||
scale computation, FramerateLimitTracker decisions, MouseHandler (relative
|
||||
and absolute motion, sensitivity curve, cinematic smoothing, inversion,
|
||||
scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping,
|
||||
all driven with identical synthetic input and time sequences."""
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def fbits(v):
|
||||
return struct.pack('>f', v).hex()
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
|
||||
|
||||
def timer_cases(rng):
|
||||
for n in range(700):
|
||||
tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0])
|
||||
start = rng.choice([0, 0, 1234, 10**9])
|
||||
now = start
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
kind = rng.choice(['adv', 'adv', 'adv', 'real', 'pause', 'frozen'])
|
||||
if kind in ('adv', 'real'):
|
||||
now += rng.choice([0, 1, 2, 7, 16, 17, 33, 49, 50, 51, 99, 100, 101, 250, 999, 5000, 70000])
|
||||
if rng.random() < 0.03:
|
||||
now -= rng.randrange(0, 30)
|
||||
if kind == 'adv':
|
||||
mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1])
|
||||
ops.append(['adv', now, None if mspt is None else fbits(mspt)])
|
||||
elif kind == 'real':
|
||||
ops.append(['real', now])
|
||||
else:
|
||||
ops.append([kind, rng.random() < 0.5])
|
||||
yield dict(t='timer', tps=fbits(tps), start=start, ops=ops)
|
||||
|
||||
|
||||
def rate_cases(rng):
|
||||
rates = [20.0, 1.0, 0.5, 0.0, -3.0, 100.0, 10000.0, 3.3, 1e-3, 33.333, 7.0, float('nan'), float('inf'), 59.99]
|
||||
for n in range(500):
|
||||
ops = []
|
||||
clock = 0
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint',
|
||||
'tick', 'tick', 'tick'])
|
||||
if kind == 'rate':
|
||||
ops.append(['rate', fbits(rng.choice(rates))])
|
||||
elif kind == 'freeze':
|
||||
ops.append(['freeze', rng.random() < 0.5])
|
||||
elif kind == 'step':
|
||||
ops.append(['step', rng.choice([1, 2, 5, 20, 0, -1])])
|
||||
elif kind == 'sprint':
|
||||
ops.append(['sprint', rng.choice([1, 2, 3, 10, 100, 0])])
|
||||
elif kind in ('check', 'end'):
|
||||
clock += rng.choice([0, 1, 1000, 50_000_000, 123_456_789, 3_000_000_000])
|
||||
ops.append([kind, clock])
|
||||
else:
|
||||
ops.append([kind])
|
||||
yield dict(t='rate', ops=ops)
|
||||
|
||||
|
||||
def scale_cases(rng):
|
||||
sizes = [(1, 1), (2, 2), (319, 239), (320, 240), (321, 241), (640, 480), (854, 480), (1280, 720), (1920, 1080),
|
||||
(2560, 1440), (3840, 2160), (7680, 4320), (0, 0), (1000, 100), (100, 1000), (641, 481), (333, 777)]
|
||||
for w, h in sizes:
|
||||
for maxs in [0, 1, 2, 3, 4, 5, 6, 8, 100, -1, 7]:
|
||||
for uni in (False, True):
|
||||
sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)])
|
||||
yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh,
|
||||
x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h)))
|
||||
|
||||
|
||||
def limit_cases(rng):
|
||||
for iconified, focused in [(True, False), (True, True), (False, True)]:
|
||||
for opt in (10, 30, 60, 120, 140, 260):
|
||||
for afk in (False, True):
|
||||
for ago in (0, 1000, 59000, 61000, 599000, 601000, 5_000_000):
|
||||
for level in (False, True):
|
||||
for screen in (False, True):
|
||||
for overlay in (False, True):
|
||||
yield dict(t='limit', iconified=iconified, focused=focused, opt=opt, afk=afk, ago=ago,
|
||||
level=level, screen=screen, overlay=overlay)
|
||||
|
||||
|
||||
def mouse_cases(rng):
|
||||
for n in range(900):
|
||||
sens = rng.choice([0.0, 0.5, 1.0, 0.25, 0.1, 0.75, 0.3333, rng.random()])
|
||||
time = rng.choice([0.0, 10.0, 12345.678])
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
kind = rng.choice(['move', 'move', 'move', 'frame', 'frame', 'ignore'])
|
||||
if kind == 'move':
|
||||
x, y = rng.uniform(0, 1920), rng.uniform(0, 1080)
|
||||
big = rng.choice([1, 1, 1, 50, 5000])
|
||||
ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)])
|
||||
elif kind == 'frame':
|
||||
time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0])
|
||||
ops.append(['frame', dbits(time)])
|
||||
else:
|
||||
ops.append(['ignore'])
|
||||
yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3,
|
||||
ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops)
|
||||
|
||||
|
||||
def scroll_cases(rng):
|
||||
for n in range(700):
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)])
|
||||
y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)])
|
||||
ops.append([dbits(x), dbits(y)])
|
||||
yield dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])),
|
||||
slot=rng.randrange(9), ops=ops)
|
||||
|
||||
|
||||
def key_cases(rng):
|
||||
for n in range(900):
|
||||
toggle = rng.random() < 0.8
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 50)):
|
||||
ops.append(rng.choice([['option', rng.random() < 0.5], ['down', True], ['down', False], ['down', True], ['release'],
|
||||
['restore'], ['click'], ['consume'], ['consume'], ['ingame']]))
|
||||
yield dict(t='key', toggle=toggle, keyboard=rng.random() < 0.7, restore=rng.random() < 0.6, ops=ops)
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
rng = random.Random(0x4c4f4f50)
|
||||
path = build / 'cases.jsonl'
|
||||
count = 0
|
||||
with path.open('w') as out:
|
||||
for generator in (timer_cases, rate_cases, scale_cases, limit_cases, mouse_cases, scroll_cases, key_cases):
|
||||
for case in generator(rng):
|
||||
out.write(json.dumps(case, separators=(',', ':')) + '\n')
|
||||
count += 1
|
||||
return path, count
|
||||
|
||||
|
||||
def main():
|
||||
scope = ('Real DeltaTracker.Timer (float partial ticks from integer milliseconds, pause residual, frozen partial tick, '
|
||||
'real-time delta cap), ServerTickRateManager (set rate, freeze, step, sprint including the sprint report text), '
|
||||
'Window.calculateScale/setGuiScale and MouseHandler scaled positions, FramerateLimitTracker throttle reasons and '
|
||||
'limits (not the focus-lost exclusive-fullscreen branch, which reads SDL), MouseHandler.onMove/turnPlayer with '
|
||||
'sensitivity, cinematic smoothing, scoping and inversion, Entity.turn clamps, onScroll with ScrollWheelHandler '
|
||||
'accumulation, discrete scrolling and hotbar selection, and ToggleKeyMapping/KeyMapping down, click and '
|
||||
'screen-release state. The frame clock source (Blaze3D.getTime, System.nanoTime) is injected, so sleeping in '
|
||||
'FramerateLimiter and vsync present-mode selection are covered by Rust unit tests only.')
|
||||
harness.differential(
|
||||
'rust-game-loop-parity', 'VanillaGameLoopOracle', 'game_loop_probe', make_cases, scope,
|
||||
sources=[lab.ROOT / f'crates/horizon-client/src/{name}.rs' for name in ('clock', 'mouse', 'window', 'keymapping')])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare AbstractContainerMenu.clicked with vanilla's menu classes.
|
||||
|
||||
The Java oracle (VanillaMenuOracle) runs each case's clicks on the real menu
|
||||
class with a stand-in player and level; the Rust example (menu_fixture) runs
|
||||
horizon_client::menu. Cases are randomized slot contents with random click
|
||||
sequences covering every ContainerInput (pickup, quick move, swap, clone,
|
||||
throw, the three quick craft drags, pickup all) over the player inventory,
|
||||
crafting table, chests, hopper, dispenser, shulker box and the furnaces. After
|
||||
every click the slots, carried stack, data slots and drops are compared.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
try:
|
||||
from . import interaction_lab as lib, lab
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import lab
|
||||
|
||||
MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81,
|
||||
'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46}
|
||||
DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10}
|
||||
COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread',
|
||||
'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool',
|
||||
'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin',
|
||||
'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box',
|
||||
'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling',
|
||||
'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder',
|
||||
'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath']
|
||||
|
||||
|
||||
def quote(text):
|
||||
return '"' + text + '"'
|
||||
|
||||
|
||||
def snbt(item, count, damage=0, curse=False, potion=None):
|
||||
comps = []
|
||||
if potion:
|
||||
comps.append('"minecraft:potion_contents":{potion:"%s"}' % potion)
|
||||
if damage:
|
||||
comps.append('"minecraft:damage":%d' % damage)
|
||||
if curse:
|
||||
comps.append('"minecraft:enchantments":{"minecraft:binding_curse":1}')
|
||||
body = ',components:{%s}' % ','.join(comps) if comps else ''
|
||||
return '{id:%s,count:%d%s}' % (quote(item), count, body)
|
||||
|
||||
|
||||
class Gen:
|
||||
def __init__(self, rng, items):
|
||||
self.rng = rng
|
||||
self.items = items
|
||||
self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items]
|
||||
self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k
|
||||
and not k.endswith('_spawn_egg')]
|
||||
|
||||
def stack(self):
|
||||
rng = self.rng
|
||||
item = rng.choice(self.pool if rng.random() < 0.85 else self.all)
|
||||
info = self.items[item]
|
||||
top = info.get('minecraft:max_stack_size', 64)
|
||||
damage = 0
|
||||
if info.get('minecraft:max_damage') and rng.random() < 0.3:
|
||||
damage = rng.randrange(1, info['minecraft:max_damage'])
|
||||
count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)])
|
||||
potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None
|
||||
return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion)
|
||||
|
||||
def slots(self, size, density):
|
||||
return [self.stack() if self.rng.random() < density else '-' for _ in range(size)]
|
||||
|
||||
def recipe(self, slots, width):
|
||||
"""Fills the crafting grid (slots 1..) with a small known recipe."""
|
||||
rng = self.rng
|
||||
amount = lambda: rng.choice([1, 1, 2, 5, 64])
|
||||
choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')],
|
||||
[('iron_ingot',) * 3] * 3, [('milk_bucket',) * 3, ('sugar', 'egg', 'sugar'), ('wheat',) * 3],
|
||||
[('wheat',) * 3], [('white_wool',) * 2, ('white_wool',) * 2], [('coal',), ('stick',)]]
|
||||
pattern = rng.choice(choices)
|
||||
if len(pattern) > width or any(len(row) > width for row in pattern):
|
||||
pattern = [('oak_planks',), ('oak_planks',)]
|
||||
for y, row in enumerate(pattern):
|
||||
for x, name in enumerate(row):
|
||||
slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1)
|
||||
|
||||
def ops(self, size):
|
||||
rng = self.rng
|
||||
out = []
|
||||
for _ in range(rng.randrange(1, 9)):
|
||||
kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'],
|
||||
[30, 20, 8, 3, 6, 14, 6, 2])[0]
|
||||
slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size)
|
||||
if kind == 'PICKUP':
|
||||
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
|
||||
elif kind == 'QUICK_MOVE':
|
||||
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
|
||||
elif kind == 'SWAP':
|
||||
out.append([slot, rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 40, 9, -1]), kind])
|
||||
elif kind in ('CLONE', 'THROW', 'PICKUP_ALL'):
|
||||
out.append([slot, rng.randrange(0, 2), kind])
|
||||
elif kind == 'DRAG':
|
||||
ty = rng.randrange(0, 4)
|
||||
out.append([-999, 0 | ty << 2, 'QUICK_CRAFT'])
|
||||
for _ in range(rng.randrange(0, 6)):
|
||||
out.append([rng.randrange(size), 1 | ty << 2, 'QUICK_CRAFT'])
|
||||
out.append([-999, 2 | ty << 2, 'QUICK_CRAFT'])
|
||||
else:
|
||||
out.append([rng.choice([slot, 999, -5]), rng.randrange(-1, 5), rng.choice(
|
||||
['PICKUP', 'QUICK_MOVE', 'QUICK_CRAFT', 'SWAP', 'THROW', 'PICKUP_ALL'])])
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=7)
|
||||
parser.add_argument('--cases', type=int, default=6000)
|
||||
parser.add_argument('--limit', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
work = lib.work_dir('menu-click-parity')
|
||||
vanilla = lib.Vanilla(work)
|
||||
vanilla.compile('ParityData', 'VanillaMenuOracle')
|
||||
items = json.loads((lib.RESOURCES / 'items.json').read_text())
|
||||
rng = random.Random(args.seed)
|
||||
g = Gen(rng, items)
|
||||
cases = []
|
||||
for n in range(args.cases):
|
||||
menu = list(MENUS)[n % len(MENUS)]
|
||||
size = MENUS[menu]
|
||||
slots = g.slots(size, rng.choice([0.1, 0.4, 0.8]))
|
||||
if menu in ('inventory', 'crafting'):
|
||||
slots[0] = '-'
|
||||
if menu in ('inventory', 'crafting') and rng.random() < 0.6:
|
||||
g.recipe(slots, 2 if menu == 'inventory' else 3)
|
||||
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,
|
||||
'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))],
|
||||
'ops': g.ops(size)})
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
|
||||
vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt')
|
||||
lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
|
||||
native = (work / 'native.txt').read_text().split('\n')
|
||||
rust = (work / 'rust.txt').read_text().split('\n')
|
||||
|
||||
def by_case(lines):
|
||||
out, cur = [], []
|
||||
for line in lines:
|
||||
cur.append(line)
|
||||
if line == 'end' or line.startswith('error-case'):
|
||||
out.append(cur)
|
||||
cur = []
|
||||
return out
|
||||
native, rust = by_case(native), by_case(rust)
|
||||
bad = {}
|
||||
for case, a, b in zip(cases, native, rust):
|
||||
if a != b:
|
||||
step = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else 0
|
||||
op = case['ops'][step - 1] if 0 < step <= len(case['ops']) else None
|
||||
bad.setdefault((case['menu'], op[2] if op else 'init'), []).append((case, step, a, b))
|
||||
total = sum(len(v) for v in bad.values())
|
||||
for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])):
|
||||
print(f'{key}: {len(entries)} differing')
|
||||
for case, step, a, b in entries[:args.limit]:
|
||||
print(f' ops {case["ops"][:step]}\n start {a[0]}\n native {a[step]}\n rust {b[step]}')
|
||||
print(f'{len(cases) - total}/{len(cases)} cases match')
|
||||
raise SystemExit(1 if total else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare options.txt loading and saving, and the key mapping table, with the
|
||||
pinned client: every file is loaded through the real Options.load and written
|
||||
back with Options.save, and the Rust port must produce identical text."""
|
||||
from pathlib import Path
|
||||
import random
|
||||
import shutil
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
VERSION = 5023
|
||||
|
||||
# Raw JSON-ish value texts: valid, boundary, wrong-typed, lenient-parser and
|
||||
# syntax-error forms. Syntax errors abort the rest of a load, as in vanilla.
|
||||
TOKENS = [
|
||||
'true', 'false', 'TRUE', 'False', '"true"', '0', '1', '2', '3', '4', '5', '-1', '-3', '7', '10', '11', '12', '13',
|
||||
'16', '27', '29', '30', '31', '32', '33', '60', '65', '69', '70', '71', '100', '109', '110', '111', '120', '128',
|
||||
'129', '130', '255', '256', '260', '261', '1000', '2147483646', '2147483647', '2147483648', '-2147483648',
|
||||
'0.0', '0.1', '0.25', '0.3', '0.5', '0.75', '0.77', '0.99', '1.0', '1.5', '2.0', '2.5', '5.0', '5.5', '6.0',
|
||||
'10.0', '10.5', '-0.5', '-0.0', '1e0', '1e1', '1E-2', '1e2', '2.5e-1', '0.0001', '1e30', '12.7', '4.99',
|
||||
'"fast"', '"fancy"', '"fabulous"', '"custom"', '"afk"', '"minimized"', '"left"', '"right"', '"default"',
|
||||
'"opengl"', '"all"', '"none"', '"limited"', '"never"', '"pause"', '"pause_and_toast"', '"DEFAULT"', '"FREQUENT"',
|
||||
'"CONSTANT"', '"false"', '"movement"', '"Fast"', "'fast'", 'fast', 'afk', 'left', 'abc', '', ' ', '""', 'null',
|
||||
'[]', '[1,2]', '["vanilla"]', '["vanilla","file/x.zip"]', '{}', '[vanilla,a]', '["a<b>&=\'"]', '0.5f', '.5',
|
||||
'007', '+1', 'NaN', 'Infinity', '-Infinity', '0x10', '1 2', '"unterminated', '{', ']', '1,2', '0.5 # note',
|
||||
'0.5 // note', '/* c */ 0.5', '0.5;', ')]}\'\n0.5', 'tRuE', 'nul', 'true false',
|
||||
]
|
||||
KEY_TOKENS = [
|
||||
'key.keyboard.w', 'key.keyboard.unknown', 'key.mouse.left', 'key.mouse.9', 'key.mouse.99', 'key.keyboard.200',
|
||||
'key.keyboard.007', 'key.keyboard.-5', 'key.keyboard.+4', 'key.keyboard.', 'key.keyboard', 'key.mouse', 'key.mousefoo',
|
||||
'key.keyboardX5', 'key.keyboard.abc', 'key.keyboard.f13', 'key.keyboard.keypad.0', 'key.keyboard.right.shift',
|
||||
'', 'w', 'key.w', 'scancode.17', 'key.keyboard.4294967296', 'key.keyboard.2147483647', 'key.keyboard.2147483648',
|
||||
'KEY.KEYBOARD.W', 'key.keyboard.menu', 'key.keyboard.f24',
|
||||
]
|
||||
PLAIN_TOKENS = ['true', 'false', 'True', '1', '0', 'yes', '', ' true', 'abc', '5', '-1', '2147483648', '+3', '007', '1.0']
|
||||
STRING_TOKENS = ['en_us', 'FR_fr', '', ' a:b ', 'a:b:c', 'Ünïcode', '"quoted"', 'x' * 300]
|
||||
TAIL = 'musicFrequency:"FREQUENT"\nmodelPart_hat:false\n' # shows whether a load was aborted
|
||||
|
||||
|
||||
def option_keys():
|
||||
"""Option-instance keys, read from the Rust table through the probe-independent
|
||||
list below (generated from VanillaOptionsTableExporter output)."""
|
||||
return ALL_KEYS
|
||||
|
||||
|
||||
# Every key the 26.3 Options writes, in processing order (verified by the
|
||||
# defaults case: a mismatch in either name or order fails the comparison).
|
||||
ALL_KEYS = [
|
||||
'ao', 'biomeBlendRadius', 'chunkSectionFadeInTime', 'cutoutLeaves', 'enableVsync', 'entityDistanceScaling',
|
||||
'entityShadows', 'forceUnicodeFont', 'japaneseGlyphVariants', 'fov', 'fovEffectScale', 'darknessEffectScale',
|
||||
'glintSpeed', 'glintStrength', 'preferredGraphicsBackend', 'graphicsPreset', 'prioritizeChunkUpdates',
|
||||
'fullscreen', 'exclusiveFullscreen', 'macFullscreenMenuVisibility', 'gamma', 'guiScale', 'debugGuiScale',
|
||||
'maxAnisotropyBit', 'textureFiltering', 'maxFps', 'improvedTransparency', 'inactivityFpsLimit', 'mipmapLevels',
|
||||
'narrator', 'particles', 'reducedDebugInfo', 'renderClouds', 'cloudRange', 'renderDistance',
|
||||
'simulationDistance', 'screenEffectScale', 'soundDevice', 'vignette', 'weatherRadius', 'autoJump',
|
||||
'rotateWithMinecart', 'operatorItemsTab', 'autoSuggestions', 'chatColors', 'chatLinks', 'chatLinksPrompt',
|
||||
'discrete_mouse_scroll', 'invertXMouse', 'invertYMouse', 'realmsNotifications', 'showSubtitles',
|
||||
'directionalAudio', 'bobView', 'toggleCrouch', 'toggleSprint', 'toggleAttack', 'toggleUse', 'sprintWindow',
|
||||
'darkMojangStudiosBackground', 'hideLightningFlashes', 'hideSplashTexts', 'mouseSensitivity',
|
||||
'damageTiltStrength', 'highContrast', 'highContrastBlockOutline', 'narratorHotkey', 'resourcePacks',
|
||||
'incompatibleResourcePacks', 'lastServer', 'lang', 'chatVisibility', 'chatOpacity', 'chatLineSpacing',
|
||||
'textBackgroundOpacity', 'backgroundForChatOnly', 'hideServerAddress', 'advancedItemTooltips',
|
||||
'pauseOnLostFocus', 'overrideWidth', 'overrideHeight', 'chatHeightFocused', 'chatDelay', 'chatHeightUnfocused',
|
||||
'chatScale', 'chatWidth', 'notificationDisplayTime', 'useNativeTransport', 'mainHand', 'attackIndicator',
|
||||
'tutorialStep', 'mouseWheelSensitivity', 'allowCursorChanges', 'quitShortcuts', 'ctrlClickEmulatesRightClick',
|
||||
'glDebugVerbosity', 'skipMultiplayerWarning', 'hideMatchedNames', 'joinedFirstServer', 'syncChunkWrites',
|
||||
'showAutosaveIndicator', 'allowServerListing', 'inGameNotification', 'sharePresence', 'onlyShowSecureChat',
|
||||
'saveChatDrafts', 'panoramaScrollSpeed', 'telemetryOptInExtra', 'onboardAccessibility',
|
||||
'menuBackgroundBlurriness', 'startedCleanly', 'musicToast', 'musicFrequency',
|
||||
]
|
||||
PLAIN = {'lastServer', 'lang', 'hideServerAddress', 'advancedItemTooltips', 'pauseOnLostFocus', 'overrideWidth',
|
||||
'overrideHeight', 'useNativeTransport', 'glDebugVerbosity', 'skipMultiplayerWarning', 'joinedFirstServer',
|
||||
'syncChunkWrites', 'onboardAccessibility', 'startedCleanly'}
|
||||
PLAIN_STRINGS = {'lastServer', 'lang'}
|
||||
MAPPINGS = None
|
||||
SOUNDS = ['master', 'music', 'record', 'weather', 'block', 'hostile', 'neutral', 'player', 'ambient', 'voice', 'ui']
|
||||
PARTS = ['cape', 'jacket', 'left_sleeve', 'right_sleeve', 'left_pants_leg', 'right_pants_leg', 'hat']
|
||||
|
||||
|
||||
def write(directory, index, text, newline='\n'):
|
||||
(directory / f'{index:05d}.txt').write_bytes(text.replace('\n', newline).encode('utf-8'))
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
directory = build / 'cases'
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir()
|
||||
rng = random.Random(0x4f5054)
|
||||
n = 0
|
||||
# The no-file case is named absent.txt so the oracle skips the copy.
|
||||
(directory / 'absent.txt').write_text('')
|
||||
n += 1
|
||||
header = f'version:{VERSION}\n'
|
||||
# One option per file with each token: isolates every codec path.
|
||||
for key in ALL_KEYS:
|
||||
tokens = PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else (
|
||||
STRING_TOKENS if key in PLAIN_STRINGS else TOKENS)
|
||||
for token in tokens:
|
||||
write(directory, n, f'{header}{key}:{token}\n{TAIL}')
|
||||
n += 1
|
||||
# Round trips of values the game itself would save.
|
||||
for key in ALL_KEYS:
|
||||
write(directory, n, f'{header}{key}:{rng.choice(TOKENS)}\n{key}:{rng.choice(TOKENS)}\n')
|
||||
n += 1
|
||||
# Key mappings, sound volumes and model parts.
|
||||
keys = ['key.attack', 'key.use', 'key.forward', 'key.sneak', 'key.sprint', 'key.hotbar.1', 'key.swapOffhand',
|
||||
'key.debug.modifier', 'key.debug.profilingChart', 'key.spectatorHotbar', 'key.nonexistent']
|
||||
for key in keys:
|
||||
for token in KEY_TOKENS:
|
||||
write(directory, n, f'{header}key_{key}:{token}\n{TAIL}')
|
||||
n += 1
|
||||
for source in SOUNDS + ['nonexistent']:
|
||||
for token in TOKENS[:60]:
|
||||
write(directory, n, f'{header}soundCategory_{source}:{token}\n{TAIL}')
|
||||
n += 1
|
||||
for part in PARTS + ['nonexistent']:
|
||||
for token in PLAIN_TOKENS:
|
||||
write(directory, n, f'{header}modelPart_{part}:{token}\n')
|
||||
n += 1
|
||||
# Random multi-option files, some with CRLF/CR line ends, noise and duplicates.
|
||||
syntax_errors = {'1 2', '"unterminated', '{', ']', '1,2', 'true false', '0.5 // note'}
|
||||
safe = [t for t in TOKENS if t not in syntax_errors]
|
||||
for _ in range(1500):
|
||||
lines = [] if rng.random() < 0.1 else [f'version:{VERSION}']
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
key = rng.choice(ALL_KEYS)
|
||||
pool = safe if rng.random() < 0.9 else TOKENS
|
||||
lines.append(f'{key}:{rng.choice(PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else pool)}')
|
||||
if rng.random() < 0.05:
|
||||
lines.append(rng.choice(['', 'garbage', ':', 'novalue:', ':novalue', 'a:b:c', 'fullscreenResolution:1920x1080@60:24']))
|
||||
newline = rng.choice(['\n', '\n', '\r\n', '\r'])
|
||||
write(directory, n, '\n'.join(lines) + rng.choice(['', '\n']), newline)
|
||||
n += 1
|
||||
# Older files exercise the data fixers; each version boundary of the OPTIONS fixers.
|
||||
legacy = [
|
||||
'fancyGraphics:true\nao:2\nlang:EN_US\nchatOpacity:0.4\nmenuBackgroundBlurriness:0.5\nkey_key.forward:17\n'
|
||||
'key_key.attack:-100\nkey_key.use:-99\nkey_key.pickItem:-98\nkey_key.jump:-95\nresourcePacks:["programer_art"]\n'
|
||||
'showNowPlayingToast:true\n',
|
||||
'fancyGraphics:false\nao:0\nkey_key.forward:key.w\nkey_key.swapHands:key.f\nmouseSensitivity:0.5\n',
|
||||
'graphicsMode:2\nao:1\nmenuBackgroundBlurriness:abc\nchatOpacity:abc\nshowNowPlayingToast:false\n',
|
||||
'graphicsMode:0\nmenuBackgroundBlurriness:0.35\nchatOpacity:1e-3\n',
|
||||
'graphicsMode:1\nlang:Fr_Ca\nresourcePacks:["a","programer_art"]\nincompatibleResourcePacks:["programer_art"]\n',
|
||||
'key_key.forward:abc\n', 'key_key.forward:\n', 'key_key.attack:k\n', 'chatOpacity:Infinity\n',
|
||||
'chatOpacity: 0.5d\n', 'menuBackgroundBlurriness:0.25\n', 'menuBackgroundBlurriness:1.04999\n',
|
||||
]
|
||||
versions = [-1, 0, 100, 504, 505, 815, 816, 1343, 1344, 1445, 1446, 1935, 1936, 2555, 2556, 2557, 2558, 3200, 3201,
|
||||
3213, 3214, 3318, 3319, 3942, 3943, 4650, 4651, 4660, 4661, 4891, 4892, 5022, 5023, 5024, 9999]
|
||||
for version in versions:
|
||||
for body in legacy:
|
||||
write(directory, n, f'version:{version}\n{body}')
|
||||
n += 1
|
||||
for body in legacy:
|
||||
write(directory, n, body)
|
||||
n += 1
|
||||
write(directory, n, f'version:abc\n{body}')
|
||||
n += 1
|
||||
write(directory, n, f'version: 5023\n{body}')
|
||||
n += 1
|
||||
for text in ['fullscreenResolution:1920x1080@60:24\n', 'fullscreenResolution:\n', 'fov:abc\nfullscreenResolution:x\n',
|
||||
'fov:1 2\nfullscreenResolution:x\n', 'version:5023\nfov:0.5\n', 'FOV:0.5\n', ' fov:0.5\n', 'fov :0.5\n']:
|
||||
write(directory, n, f'version:{VERSION}\n{text}')
|
||||
n += 1
|
||||
return directory, n
|
||||
|
||||
|
||||
def main():
|
||||
scope = ('Real Options.load and Options.save (26.3) on generated options.txt files: the full option table in '
|
||||
'processing order with defaults, every codec/validator path (int ranges, quantised doubles, unit doubles with '
|
||||
'boolean alternative, string and id enums with wrapping, clouds, fov, frame limit, scroll sensitivity), plain '
|
||||
'fields, lenient Gson parsing and syntax-error aborts, key mappings (names, scancode-number forms, unbinding), '
|
||||
'sound volumes, model parts, line endings, the OPTIONS data fixers across version boundaries, and the '
|
||||
'KeyMapping table (order, defaults, categories, toggle mappings). Does not cover option screens or '
|
||||
'runtime side effects of setting an option.')
|
||||
harness.differential(
|
||||
'rust-options-parity', 'VanillaOptionsOracle', 'options_probe', make_cases, scope,
|
||||
sources=[lab.ROOT / 'crates/horizon-client/src/options_file.rs', lab.ROOT / 'crates/horizon-client/src/options_fixes.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/java_text.rs', lab.ROOT / 'crates/horizon-client/src/key_names.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/keybinds.rs'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Horizon's resident PalettedContainer with the client's own.
|
||||
|
||||
Scripted edits run through vanilla's PalettedContainer (block-state and biome
|
||||
strategies: single-value, linear, hash-map and global palettes, resizing, network
|
||||
write and read, pack and unpack) and through horizon_core::paletted. Both sides
|
||||
print the set results, the serialized container after every few edits, the
|
||||
container read back from the wire, the saved form (palette, bit width, storage)
|
||||
and the container loaded from it, as hashes.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
BUILD = lab.ROOT / 'target/paletted-container-parity'
|
||||
LIMITS = {'blocks': (4096, 35723), 'biomes': (64, 67)}
|
||||
|
||||
|
||||
def corpus():
|
||||
rng = random.Random(0x50414C45545445)
|
||||
counts = [1, 2, 3, 4, 5, 8, 9, 15, 16, 17, 31, 32, 33, 64, 100, 128, 129, 200, 256, 257, 300, 700, 2000]
|
||||
for kind, (entries, ids) in LIMITS.items():
|
||||
for count in counts:
|
||||
if kind == 'biomes' and count > 70:
|
||||
continue
|
||||
for trial in range(6):
|
||||
pool = rng.sample(range(ids), min(count, ids))
|
||||
initial = rng.choice(pool) if trial % 2 else rng.randrange(ids)
|
||||
ops = []
|
||||
for _ in range(rng.choice([entries // 4, entries, entries * 3])):
|
||||
ops.append((rng.randrange(entries), rng.choice(pool)))
|
||||
if trial == 5:
|
||||
# Every position written once, in order, then half of them reset.
|
||||
ops = [(i, pool[i % len(pool)]) for i in range(entries)] + [(i, initial) for i in range(0, entries, 2)]
|
||||
yield f'{kind}_{count}_{trial}', kind, initial, rng.choice([1, 7, 37, 211]), ops
|
||||
# A few edits at a time: the palette grows one value at a time from a single value.
|
||||
for trial in range(20):
|
||||
ops = [(rng.randrange(entries), rng.randrange(ids)) for _ in range(rng.randrange(1, 40))]
|
||||
yield f'{kind}_sparse_{trial}', kind, rng.randrange(ids), 1, ops
|
||||
# Overwriting with the value already there, and filling a section with one value.
|
||||
yield f'{kind}_fill', kind, 3, 500, [(i, 9) for i in range(entries)] + [(i, 3) for i in range(entries)]
|
||||
yield f'{kind}_same', kind, 3, 1, [(i, 3) for i in range(0, entries, 5)]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.parse_args()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
BUILD.mkdir(parents=True, exist_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java'
|
||||
sources = [Path(__file__), oracle, lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock',
|
||||
lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-core/examples/paletted_fixture.rs',
|
||||
*sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs'))]
|
||||
tested = base.source_hashes(sources)
|
||||
scenarios = list(corpus())
|
||||
inputs = BUILD / 'inputs.txt'
|
||||
inputs.write_text(''.join(f'{name} {kind} {initial} {every} ' + ' '.join(f'{i} {v}' for i, v in ops) + '\n'
|
||||
for name, kind, initial, every, ops in scenarios))
|
||||
|
||||
def run(command, name):
|
||||
with (BUILD / (name + '.log')).open('w') as log:
|
||||
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
|
||||
classes = BUILD / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java')
|
||||
run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', os.environ.get('CARGO_BUILD_JOBS', '3'), '-p', 'horizon-core', '--example', 'paletted_fixture'], 'compile-rust')
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
|
||||
binary = Path(metadata['target_directory']) / 'fast/examples/paletted_fixture'
|
||||
run([binary, inputs, BUILD / 'rust.txt'], 'rust')
|
||||
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPalettedContainerOracle', inputs, BUILD / 'client.txt'], 'client')
|
||||
client = (BUILD / 'client.txt').read_text().splitlines()
|
||||
rust = (BUILD / 'rust.txt').read_text().splitlines()
|
||||
assert len(client) == len(rust) == len(scenarios), (len(client), len(rust), len(scenarios))
|
||||
bad = [(a, b) for a, b in zip(client, rust) if a != b]
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
for a, b in bad[:5]:
|
||||
print('client', a[:600])
|
||||
print('rust ', b[:600])
|
||||
if bad:
|
||||
raise SystemExit(f'{len(bad)} of {len(scenarios)} scenarios differ')
|
||||
edits = sum(len(s[4]) for s in scenarios)
|
||||
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenarios': len(scenarios), 'edits': edits,
|
||||
'sources_sha256': tested}
|
||||
lab.write_json(BUILD / 'report.json', report)
|
||||
print(f'PalettedContainer parity: {len(scenarios)} scenarios, {edits:,} edits, all hashes identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,303 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare crafting, cooking, stonecutting and smithing with vanilla's RecipeManager.
|
||||
|
||||
The Java oracle (VanillaRecipeOracle) loads the data pack's recipe registry and
|
||||
answers craft/cook/stonecut/smith commands; the Rust example (recipe_fixture)
|
||||
answers the same commands from horizon_client::crafting and ::stations.
|
||||
Crafting cases are built from every recipe's own ingredients (placed at random
|
||||
offsets, mirrored, perturbed) plus focused generators for the special recipes
|
||||
(banners, books, fireworks, dyeing, repair, pots, tipped arrows, maps) and
|
||||
random grids. Results are compared as canonical ItemStack NBT, with the
|
||||
matched recipe id and the crafting remainders.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
try:
|
||||
from . import interaction_lab as lib, lab
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import lab
|
||||
|
||||
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
|
||||
'blue', 'brown', 'green', 'red', 'black']
|
||||
POTIONS = ['minecraft:healing', 'minecraft:swiftness', 'minecraft:water', 'minecraft:night_vision']
|
||||
SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst']
|
||||
|
||||
|
||||
def quote(text):
|
||||
return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
def stack(item, count=1, **components):
|
||||
"""SNBT of an ItemStack.CODEC compound; component values are SNBT text."""
|
||||
body = ','.join(f'{quote("minecraft:" + key)}:{value}' for key, value in sorted(components.items()))
|
||||
comp = f',components:{{{body}}}' if body else ''
|
||||
return f'{{id:{quote(item)},count:{count}{comp}}}'
|
||||
|
||||
|
||||
def colors(rng, n=None):
|
||||
n = rng.randrange(0, 4) if n is None else n
|
||||
return '[I;' + ','.join(str(rng.randrange(1 << 24)) for _ in range(n)) + ']'
|
||||
|
||||
|
||||
def explosion(rng):
|
||||
return ('{shape:%s,colors:%s,fade_colors:%s,has_trail:%db,has_twinkle:%db}'
|
||||
% (quote(rng.choice(SHAPES)), colors(rng), colors(rng), rng.randrange(2), rng.randrange(2)))
|
||||
|
||||
|
||||
class Gen:
|
||||
def __init__(self, rng, items, recipes, patterns):
|
||||
self.rng = rng
|
||||
self.items = items
|
||||
self.recipes = recipes
|
||||
self.patterns = patterns
|
||||
self.durable = [k for k, v in items.items() if v.get('minecraft:max_damage')]
|
||||
|
||||
def layers(self, n=None):
|
||||
n = self.rng.choice([0, 0, 1, 2, 6, 7]) if n is None else n
|
||||
return '[' + ','.join('{pattern:%s,color:%s}' % (quote(self.rng.choice(self.patterns)), quote(self.rng.choice(DYES))) for _ in range(n)) + ']'
|
||||
|
||||
def book(self, generation=None):
|
||||
g = self.rng.randrange(4) if generation is None else generation
|
||||
return stack('minecraft:written_book', written_book_content='{title:{raw:"T"},author:"A",generation:%d,pages:[{raw:"p1"},{raw:"p2"}]}' % g)
|
||||
|
||||
def stack(self, item, count=None, rich=0.5):
|
||||
"""A stack of the item, with the components that apply to it."""
|
||||
rng = self.rng
|
||||
info = self.items.get(item, {})
|
||||
count = rng.choice([1, 1, 1, 2, 3]) if count is None else count
|
||||
c = {}
|
||||
if rng.random() < rich:
|
||||
if info.get('minecraft:max_damage') and rng.random() < 0.7:
|
||||
c['damage'] = str(rng.randrange(0, info['minecraft:max_damage'] + 1))
|
||||
if info.get('minecraft:max_damage') and rng.random() < 0.3:
|
||||
c['enchantments'] = '{%s:1}' % quote(rng.choice(['minecraft:binding_curse', 'minecraft:vanishing_curse', 'minecraft:mending', 'minecraft:unbreaking']))
|
||||
if item.endswith('_banner'):
|
||||
c['banner_patterns'] = self.layers()
|
||||
if item == 'minecraft:shield':
|
||||
if rng.random() < 0.3:
|
||||
c['banner_patterns'] = self.layers(rng.randrange(1, 3))
|
||||
c['base_color'] = quote(rng.choice(DYES))
|
||||
if item == 'minecraft:written_book':
|
||||
return self.book()
|
||||
if item == 'minecraft:firework_star':
|
||||
c['firework_explosion'] = explosion(rng)
|
||||
if item == 'minecraft:firework_rocket':
|
||||
c['fireworks'] = '{flight_duration:%db,explosions:[%s]}' % (rng.randrange(1, 4), explosion(rng))
|
||||
if item in ('minecraft:lingering_potion', 'minecraft:potion', 'minecraft:splash_potion'):
|
||||
c['potion_contents'] = '{potion:%s}' % quote(rng.choice(POTIONS))
|
||||
if item.startswith('minecraft:leather_') or item in ('minecraft:wolf_armor',):
|
||||
if rng.random() < 0.6:
|
||||
c['dyed_color'] = str(rng.randrange(1 << 24))
|
||||
if item.endswith('shulker_box'):
|
||||
c['container'] = '[{slot:0,item:{id:"minecraft:stone",count:%d}}]' % rng.randrange(1, 64)
|
||||
if item.endswith('_bundle') or item == 'minecraft:bundle':
|
||||
c['bundle_contents'] = '[{id:"minecraft:stone",count:%d}]' % rng.randrange(1, 64)
|
||||
if item == 'minecraft:filled_map':
|
||||
c['map_id'] = str(rng.randrange(1, 5))
|
||||
return stack(item, count, **c)
|
||||
|
||||
def plain(self, item):
|
||||
return self.stack(item, rich=0.3)
|
||||
|
||||
|
||||
def place(rng, cells, size):
|
||||
"""Cells (stack list) at random free positions of a size x size grid."""
|
||||
grid = ['-'] * (size * size)
|
||||
spots = rng.sample(range(size * size), len(cells))
|
||||
for spot, cell in zip(spots, cells):
|
||||
grid[spot] = cell
|
||||
return grid
|
||||
|
||||
|
||||
def place_box(rng, width, height, cells, size):
|
||||
"""A width x height pattern at a random offset of the grid."""
|
||||
x0 = rng.randrange(size - width + 1)
|
||||
y0 = rng.randrange(size - height + 1)
|
||||
grid = ['-'] * (size * size)
|
||||
for i, cell in enumerate(cells):
|
||||
grid[(y0 + i // width) * size + x0 + i % width] = cell
|
||||
return grid
|
||||
|
||||
|
||||
def craft_case(grid, size):
|
||||
return 'craft\t%d\t%s' % (size, '\t'.join(grid))
|
||||
|
||||
|
||||
def recipe_cases(g, count_per):
|
||||
rng = g.rng
|
||||
for recipe in g.recipes:
|
||||
if 'slots' not in recipe or not recipe['ingredients']:
|
||||
continue
|
||||
ingredients = recipe['ingredients']
|
||||
slots = recipe['slots']
|
||||
shaped = recipe['kind'] == 'ShapedRecipe'
|
||||
if shaped:
|
||||
width = recipe['width']
|
||||
height = len(slots) // width
|
||||
for variant in range(count_per):
|
||||
pick = [g.plain(rng.choice(i)) if i else '-' for i in ingredients]
|
||||
if shaped:
|
||||
cells = ['-' if s < 0 else pick[s] for s in slots]
|
||||
if variant % 3 == 1: # mirrored
|
||||
cells = [cells[y * width + width - 1 - x] for y in range(height) for x in range(width)]
|
||||
size = rng.choice([s for s in (2, 3) if s >= max(width, height)])
|
||||
grid = place_box(rng, width, height, cells, size)
|
||||
else:
|
||||
size = 3 if len(pick) > 4 else rng.choice([2, 3])
|
||||
grid = place(rng, pick, size)
|
||||
yield craft_case(grid, size)
|
||||
# Perturbations: drop one, swap one for a stranger, add one, shift a count.
|
||||
if variant < 2:
|
||||
filled = [i for i, c in enumerate(grid) if c != '-']
|
||||
broken = list(grid)
|
||||
broken[rng.choice(filled)] = '-'
|
||||
yield craft_case(broken, size)
|
||||
broken = list(grid)
|
||||
broken[rng.choice(filled)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
|
||||
yield craft_case(broken, size)
|
||||
free = [i for i, c in enumerate(grid) if c == '-']
|
||||
if free:
|
||||
broken = list(grid)
|
||||
broken[rng.choice(free)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
|
||||
yield craft_case(broken, size)
|
||||
|
||||
|
||||
def special_cases(g, n):
|
||||
rng = g.rng
|
||||
items = g.items
|
||||
banners = [f'minecraft:{d}_banner' for d in DYES]
|
||||
dyes = [f'minecraft:{d}_dye' for d in DYES]
|
||||
armor = [k for k in items if k.startswith('minecraft:leather_') and k.count('_') == 2] + ['minecraft:wolf_armor']
|
||||
boxes = [k for k in items if k.endswith('shulker_box')]
|
||||
bundles = [k for k in items if k.endswith('bundle')]
|
||||
skulls = [k for k in items if k.endswith('_head') or k.endswith('_skull')]
|
||||
for _ in range(n):
|
||||
size = rng.choice([2, 3])
|
||||
# banner duplicate / shield decoration
|
||||
a, b = rng.choice(banners), rng.choice(banners)
|
||||
yield craft_case(place(rng, [g.stack(a, 1, 1.0), g.stack(b if rng.random() < 0.3 else a, 1, 0.5)], size), size)
|
||||
yield craft_case(place(rng, [g.stack(rng.choice(banners), 1, 1.0), g.stack('minecraft:shield', 1, 0.5)], size), size)
|
||||
# book cloning
|
||||
books = [g.book(rng.choice([0, 0, 1, 2, 3]))] + [stack('minecraft:writable_book') for _ in range(rng.randrange(0, 4))]
|
||||
if rng.random() < 0.2:
|
||||
books.append(g.book())
|
||||
yield craft_case(place(rng, books, 3), 3)
|
||||
# fireworks
|
||||
star = [stack(rng.choice(['minecraft:gunpowder'] + dyes[:2] + ['minecraft:gold_nugget', 'minecraft:feather', 'minecraft:fire_charge',
|
||||
'minecraft:diamond', 'minecraft:glowstone_dust', rng.choice(skulls)]))
|
||||
for _ in range(rng.randrange(1, 7))]
|
||||
star += [stack('minecraft:gunpowder'), stack(rng.choice(dyes))]
|
||||
yield craft_case(place(rng, star[:9], 3), 3)
|
||||
fade = [g.stack('minecraft:firework_star', 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
|
||||
yield craft_case(place(rng, fade, 3), 3)
|
||||
rocket = [stack('minecraft:paper')] + [stack('minecraft:gunpowder') for _ in range(rng.randrange(0, 5))] + \
|
||||
[g.stack('minecraft:firework_star', 1, 1.0) for _ in range(rng.randrange(0, 4))]
|
||||
yield craft_case(place(rng, rocket[:9], 3), 3)
|
||||
# armour dyeing, with leftovers
|
||||
dye_cells = [g.stack(rng.choice(armor), 1, 0.7)] + [stack(rng.choice(dyes + ['minecraft:stick'] if rng.random() < 0.1 else dyes)) for _ in range(rng.randrange(1, 5))]
|
||||
yield craft_case(place(rng, dye_cells[:9], 3), 3)
|
||||
# repair
|
||||
tool = rng.choice(g.durable)
|
||||
pair = [g.stack(tool, 1, 1.0), g.stack(tool if rng.random() < 0.85 else rng.choice(g.durable), 1, 1.0)]
|
||||
yield craft_case(place(rng, pair, size), size)
|
||||
# shulker boxes and bundles
|
||||
yield craft_case(place(rng, [g.stack(rng.choice(boxes + bundles), 1, 1.0), stack(rng.choice(dyes))], size), size)
|
||||
multi = [g.stack(rng.choice(boxes + bundles), 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
|
||||
yield craft_case(place(rng, multi, 3), 3)
|
||||
# decorated pots
|
||||
sherds = ['minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:archer_pottery_sherd', 'minecraft:stick', 'minecraft:blade_pottery_sherd']
|
||||
pot = ['-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-']
|
||||
if rng.random() < 0.2:
|
||||
pot[rng.choice([0, 2, 6, 8, 4])] = stack('minecraft:brick')
|
||||
yield craft_case(pot, 3)
|
||||
yield craft_case([stack('minecraft:brick') if i in (1, 3, 5, 7) else '-' for i in range(9)], 3)
|
||||
# tipped arrows
|
||||
ring = [stack('minecraft:arrow', rng.choice([1, 2]))] * 9
|
||||
ring[4] = g.stack('minecraft:lingering_potion', 1, 1.0 if rng.random() < 0.8 else 0.0)
|
||||
yield craft_case(ring, 3)
|
||||
# map cloning
|
||||
maps = [g.stack('minecraft:filled_map', 1, 1.0)] + [stack('minecraft:map') for _ in range(rng.randrange(1, 9))]
|
||||
yield craft_case(place(rng, maps, 3), 3)
|
||||
# mixed junk of the interesting items
|
||||
pool = banners + dyes + armor + boxes + bundles + ['minecraft:written_book', 'minecraft:writable_book', 'minecraft:firework_star',
|
||||
'minecraft:paper', 'minecraft:gunpowder', 'minecraft:shield', 'minecraft:glass_bottle',
|
||||
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:bowl', 'minecraft:stick']
|
||||
junk = [g.stack(rng.choice(pool), None, 0.7) for _ in range(rng.randrange(1, 6))]
|
||||
yield craft_case(place(rng, junk, 3), 3)
|
||||
|
||||
|
||||
def smithing_cases(g):
|
||||
rng = g.rng
|
||||
for recipe in g.recipes:
|
||||
if recipe['kind'].startswith('Smithing'):
|
||||
for _ in range(24):
|
||||
pick = lambda key: g.plain(rng.choice(recipe[key])) if recipe[key] else '-'
|
||||
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), pick('addition'))
|
||||
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])))
|
||||
# Armour with a trim already on it.
|
||||
trims = ['{material:"minecraft:iron",pattern:"minecraft:coast"}', '{material:"minecraft:gold",pattern:"minecraft:sentry"}']
|
||||
for recipe in g.recipes:
|
||||
if recipe['kind'] == 'SmithingTrimRecipe':
|
||||
for trim in trims:
|
||||
base = rng.choice(recipe['base'])
|
||||
yield 'smith\t%s\t%s\t%s' % (stack(rng.choice(recipe['template'])), stack(base, 1, trim=trim), stack(rng.choice(recipe['addition'])))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=7)
|
||||
parser.add_argument('--variants', type=int, default=6)
|
||||
parser.add_argument('--specials', type=int, default=1500)
|
||||
parser.add_argument('--random', type=int, default=4000)
|
||||
parser.add_argument('--limit', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
work = lib.work_dir('recipe-parity')
|
||||
vanilla = lib.Vanilla(work)
|
||||
vanilla.compile('ParityData', 'VanillaRecipeOracle')
|
||||
vanilla.run('VanillaRecipeOracle', 'dump', work / 'recipes.jsonl')
|
||||
recipes = [json.loads(line) for line in (work / 'recipes.jsonl').read_text().splitlines()]
|
||||
# Shaped recipes: widths come from the data pack.
|
||||
for recipe in recipes:
|
||||
path = lib.RESOURCES / 'data/minecraft/recipe' / (recipe['id'] + '.json')
|
||||
data = json.loads(path.read_text())
|
||||
if recipe['kind'] == 'ShapedRecipe':
|
||||
rows = [row.rstrip() for row in data['pattern']]
|
||||
left = min(len(row) - len(row.lstrip()) for row in rows if row)
|
||||
recipe['width'] = max(len(row) for row in rows) - left
|
||||
items = json.loads((lib.RESOURCES / 'items.json').read_text())
|
||||
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
|
||||
rng = random.Random(args.seed)
|
||||
g = Gen(rng, items, recipes, patterns)
|
||||
cases = list(recipe_cases(g, args.variants))
|
||||
cases += list(special_cases(g, args.specials))
|
||||
pool = [k for k in items if not k.endswith('_spawn_egg') and k != 'minecraft:air']
|
||||
interesting = [f'minecraft:{d}_dye' for d in DYES] + ['minecraft:paper', 'minecraft:gunpowder', 'minecraft:bowl', 'minecraft:stick',
|
||||
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:water_bucket']
|
||||
for _ in range(args.random):
|
||||
size = rng.choice([2, 3])
|
||||
cells = [g.stack(rng.choice(interesting if rng.random() < 0.6 else pool), None, 0.5) for _ in range(rng.randrange(1, size * size + 1))]
|
||||
cases.append(craft_case(place(rng, cells, size), size))
|
||||
for kind in ['smelting', 'blasting', 'smoking', 'campfire_cooking']:
|
||||
for item in [i for i in items if i != 'minecraft:air']:
|
||||
cases.append('cook\t%s\t%s' % (kind, stack(item)))
|
||||
for item in [i for i in items if i != 'minecraft:air']:
|
||||
cases.append('stonecut\t' + stack(item))
|
||||
cases += list(smithing_cases(g))
|
||||
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
|
||||
vanilla.run('VanillaRecipeOracle', work / 'cases.txt', work / 'native.txt')
|
||||
lib.cargo_example('horizon-client', 'recipe_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
|
||||
|
||||
def key(case, native_line):
|
||||
kind = case.split('\t')[0]
|
||||
return kind if kind != 'craft' else 'craft ' + native_line.split('\t')[0]
|
||||
|
||||
def describe(case):
|
||||
return case if len(case) < 1200 else case[:1200] + '...'
|
||||
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', key, describe, args.limit)
|
||||
raise SystemExit(1 if total else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -29,6 +29,7 @@ except ImportError:
|
||||
import test_model_baking_parity as baking
|
||||
|
||||
BUILD = lab.ROOT / 'target/section-mesh-parity'
|
||||
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
SECTION_Y = 0
|
||||
COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4}
|
||||
POSITION_TOLERANCE = 1e-4
|
||||
@@ -71,6 +72,8 @@ class Scene:
|
||||
self.blocks = {}
|
||||
self.light_override = {}
|
||||
self.noise = None
|
||||
self.biomes = None
|
||||
self.options = {}
|
||||
|
||||
def put(self, x, y, z, name, **properties):
|
||||
self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties)
|
||||
@@ -130,8 +133,38 @@ class Scene:
|
||||
return result
|
||||
|
||||
def row(self):
|
||||
return {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
|
||||
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
|
||||
row = {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
|
||||
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
|
||||
if self.biomes is not None:
|
||||
row['biomes'] = self.biomes
|
||||
row.update(self.options)
|
||||
return row
|
||||
|
||||
def tinted_columns(self):
|
||||
"""Every tint source at several heights over the section's 16x16 footprint."""
|
||||
names = [('grass_block', {}), ('short_grass', {}), ('oak_leaves', {}), ('water', {}), ('leaf_litter', {'segment_amount': 2}),
|
||||
('sugar_cane', {}), ('fern', {}), ('vine', {'north': True}), ('mangrove_leaves', {}), ('jungle_leaves', {})]
|
||||
for x in range(16):
|
||||
for z in range(16):
|
||||
for layer, y in enumerate((1, 5, 9, 13)):
|
||||
name, properties = names[(x * 5 + z * 3 + layer) % len(names)]
|
||||
self.put(x, y, z, 'stone')
|
||||
self.put(x, y + 1, z, name, **properties)
|
||||
if name == 'water':
|
||||
self.put(x, y + 2, z, 'water')
|
||||
|
||||
def biome_field(self, seed, radius, names, default='plains'):
|
||||
"""Noise-biome quart cells: a Voronoi patchwork that shifts with height."""
|
||||
rng = random.Random(seed)
|
||||
sites = [[(rng.uniform(-4, 8), rng.uniform(-4, 8), rng.choice(names)) for _ in range(9)] for _ in range(10)]
|
||||
cells = []
|
||||
for qy in range(-3, 8):
|
||||
layer = sites[(qy + 3) // 2 % len(sites)]
|
||||
for qx in range(-4, 8):
|
||||
for qz in range(-4, 8):
|
||||
best = min(layer, key=lambda site: (site[0] - qx) ** 2 + (site[1] - qz) ** 2)
|
||||
cells.append([qx, qy, qz, 'minecraft:' + best[2]])
|
||||
self.biomes = {'seed': rng.randrange(-2 ** 63, 2 ** 63), 'radius': radius, 'default': 'minecraft:' + default, 'cells': cells}
|
||||
|
||||
|
||||
def corpus(states, full=True):
|
||||
@@ -306,6 +339,38 @@ def corpus(states, full=True):
|
||||
s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids))
|
||||
if seed % 2:
|
||||
s.noise = seed
|
||||
# Biome tint blending: BiomeManager's zoomed biome at each block's own height, averaged
|
||||
# over the blend radius, for real biome colours (colormaps, overrides, modifiers).
|
||||
biome_names = sorted(path.stem for path in (RESOURCES / 'data/minecraft/worldgen/biome').glob('*.json'))
|
||||
common = ['plains', 'swamp', 'dark_forest', 'desert', 'jungle', 'badlands', 'mangrove_swamp', 'warm_ocean', 'snowy_plains',
|
||||
'birch_forest', 'cherry_grove', 'pale_garden', 'savanna', 'taiga', 'old_growth_pine_taiga', 'lush_caves']
|
||||
for i, radius in enumerate((2, 0, 1, 3, 5, 7)):
|
||||
s = scene(f'biome_blend_r{radius}')
|
||||
s.floor(0)
|
||||
s.tinted_columns()
|
||||
s.biome_field(0x42494F4D + i, radius, common)
|
||||
for i in range(0, len(biome_names), 8):
|
||||
s = scene(f'biome_each_{i // 8}')
|
||||
s.tinted_columns()
|
||||
s.biome_field(0x45414348 + i, 2, biome_names[i:i + 8], biome_names[i])
|
||||
# Options: flat lighting (ao off) and opaque leaves (cutoutLeaves off) alone and together.
|
||||
leaves = ['oak_leaves', 'spruce_leaves', 'birch_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves',
|
||||
'azalea_leaves', 'flowering_azalea_leaves', 'mangrove_leaves', 'cherry_leaves', 'pale_oak_leaves']
|
||||
option_palette = ['stone', 'glass', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy', 'short_grass',
|
||||
'glowstone', 'oak_fence', 'ice', 'oak_log', 'tinted_glass', 'slime_block', 'honey_block'] + leaves * 2
|
||||
for i, options in enumerate(({'smooth': False}, {'cutout_leaves': False}, {'smooth': False, 'cutout_leaves': False})):
|
||||
rng = random.Random(0x4F505453 + i)
|
||||
s = scene(f'options_{i}', nether=i == 2)
|
||||
s.options = options
|
||||
s.floor(0)
|
||||
for x in range(-1, 17):
|
||||
for y in range(1, 17):
|
||||
for z in range(-1, 17):
|
||||
if rng.random() < 0.5:
|
||||
name = rng.choice(option_palette)
|
||||
s.put(x, y, z, rng.choice(states.by_name['minecraft:' + name]))
|
||||
if i:
|
||||
s.noise = i
|
||||
s = scene('cubes_nether', nether=True)
|
||||
s.floor(3, 'netherrack')
|
||||
s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks')
|
||||
@@ -337,6 +402,7 @@ def light(coords):
|
||||
|
||||
|
||||
def compare(scene, client, rust, states, report, limit):
|
||||
blend_zero = scene.get('biomes', {}).get('radius') == 0
|
||||
blocks = {tuple(b[:3]): b[3] for b in scene['blocks']}
|
||||
def describe(quad, rotation):
|
||||
v = quad['vertices']
|
||||
@@ -377,6 +443,11 @@ def compare(scene, client, rust, states, report, limit):
|
||||
if any(abs(p[i] - q[i]) > UV_TOLERANCE for i in (3, 4)):
|
||||
problems.add('uv')
|
||||
cp, cq = channels(p[5]), channels(q[5])
|
||||
if blend_zero and cp[3] == 0 and cq[3] == 255:
|
||||
# With biomeBlendRadius 0 the client uses the resolver's colour as is,
|
||||
# and biome colours given as plain RGB have alpha 0: tinted vertices come
|
||||
# out fully transparent. Horizon keeps them opaque; RGB is compared.
|
||||
cp[3] = 255
|
||||
if cp != cq:
|
||||
problems.add('color' if max(abs(x - y) for x, y in zip(cp, cq)) > 1 else 'color_rounding')
|
||||
if light(p[6]) != light(q[6]):
|
||||
|
||||
Reference in New Issue
Block a user