Merge main into feat/fishing-rod-visuals: keep the off-hand renderer, add the cast-rod flag
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -131,6 +131,7 @@ fn main() {
|
||||
let tick = TickContext {
|
||||
player_underwater: ambience.was_underwater(),
|
||||
player_removed: removed,
|
||||
..TickContext::default()
|
||||
};
|
||||
engine.tick(false, &tick, &mut backend);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
use horizon_client::{
|
||||
Result,
|
||||
arrows::{
|
||||
self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, Pickup, Touch,
|
||||
self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, EntityHit, Pickup,
|
||||
Touch,
|
||||
},
|
||||
assets::Assets,
|
||||
blocks::BlockFacts,
|
||||
@@ -12,11 +13,11 @@ use horizon_client::{
|
||||
items::ItemStack,
|
||||
mobs::Who,
|
||||
motion::{LAVA, MotionResources, WATER},
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
projectiles::{Hit, Projectile, ProjectileKind},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
geometry::{Aabb, Vec3},
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use serde_json::Value;
|
||||
@@ -89,11 +90,16 @@ fn main() -> Result<()> {
|
||||
&ItemStack::new("minecraft:arrow", 1),
|
||||
f["intangible"].as_bool().unwrap(),
|
||||
));
|
||||
// The entity in the way: its box and whether it takes the damage.
|
||||
let mut target: Option<(Aabb, bool)> = None;
|
||||
for op in f["ops"].as_array().unwrap() {
|
||||
let mut events = Vec::new();
|
||||
let mut touched = "-".to_string();
|
||||
match op["mode"].as_str().unwrap() {
|
||||
"tick" => {
|
||||
// The game's part of an entity hit: the damage it deals
|
||||
// (recorded after the tick's own events).
|
||||
let mut hurt = None;
|
||||
if !arrow.arrow.as_ref().unwrap().removed {
|
||||
let no_rain = |_| false;
|
||||
let view = ArrowScene {
|
||||
@@ -106,9 +112,35 @@ fn main() -> Result<()> {
|
||||
mob_griefing: true,
|
||||
tnt_explodes: true,
|
||||
};
|
||||
arrows::tick(&mut arrow, &view, &[]);
|
||||
let targets: Vec<_> = target.iter().map(|t| (Who::Mob(2), t.0)).collect();
|
||||
let (_, hit) = arrows::tick(&mut arrow, &view, &targets);
|
||||
if let (Hit::Entity { .. }, Some((_, takes))) = (hit, target) {
|
||||
let mut st = arrow.arrow.take().unwrap();
|
||||
let damage = arrow.arrow_damage(&mut st.random);
|
||||
hurt = Some((st.events.len(), damage));
|
||||
arrow.arrow = Some(st);
|
||||
let outcome = if takes {
|
||||
EntityHit::Hurt
|
||||
} else {
|
||||
EntityHit::Refused
|
||||
};
|
||||
arrows::finish_entity_hit(&mut arrow, &view, outcome);
|
||||
}
|
||||
}
|
||||
for event in arrow.arrow.as_mut().unwrap().events.drain(..) {
|
||||
let a = arrow.arrow.as_mut().unwrap();
|
||||
let (drop_at, dropped) = (arrow.position, a.pickup_item.count);
|
||||
let raised = std::mem::take(&mut a.events);
|
||||
let count = raised.len();
|
||||
for (i, event) in raised.into_iter().map(Some).chain([None]).enumerate() {
|
||||
if let Some((at, damage)) = hurt
|
||||
&& at == i
|
||||
{
|
||||
events.push(format!("hurt {:08x}", damage.to_bits()));
|
||||
}
|
||||
let Some(event) = event else {
|
||||
debug_assert_eq!(i, count);
|
||||
break;
|
||||
};
|
||||
match event {
|
||||
ArrowEvent::Particle {
|
||||
kind,
|
||||
@@ -191,9 +223,28 @@ fn main() -> Result<()> {
|
||||
},
|
||||
ArrowEvent::SplashEvent => events.push("splash-event".into()),
|
||||
ArrowEvent::ShootEvent => events.push("shoot-event".into()),
|
||||
ArrowEvent::Drop => events.push(format!(
|
||||
"drop {} {dropped}",
|
||||
bits(Vec3::new(
|
||||
drop_at.x,
|
||||
drop_at.y + f64::from(0.1f32),
|
||||
drop_at.z
|
||||
))
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
"target" => {
|
||||
// EntityDimensions.scalable(0.6, 1.8).makeBoundingBox.
|
||||
let at = vector(&op["position"]);
|
||||
let w = f64::from(0.6f32) / 2.0;
|
||||
let h = f64::from(1.8f32);
|
||||
let b = Aabb::new(
|
||||
Vec3::new(at.x - w, at.y, at.z - w),
|
||||
Vec3::new(at.x + w, at.y + h, at.z + w),
|
||||
);
|
||||
target = Some((b, op["takes"].as_bool().unwrap()));
|
||||
}
|
||||
"block" => {
|
||||
let p = &op["position"];
|
||||
let mut state = assets
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
//! `mobs::spawner::Spawner` loaded from the case's SNBT on the same world and
|
||||
//! print its events tick by tick.
|
||||
//!
|
||||
//! Trial spawner cases (`mode=trial`, tools/test_trial_spawner_parity.py) tick
|
||||
//! a `mobs::trial_spawner::TrialSpawner` with the game time advancing and
|
||||
//! print its states, events, spawns and ejected items.
|
||||
//!
|
||||
//! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
@@ -31,6 +35,7 @@ use horizon_client::{
|
||||
},
|
||||
spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn},
|
||||
species::{self, Baby},
|
||||
trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState},
|
||||
},
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -38,11 +43,11 @@ use horizon_core::{
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::BlockCollisionRegistry, chunk::BlockState, registry::BlockStateId,
|
||||
block_collision::BlockCollisionRegistry, chunk::BlockState, nbt::Tag, registry::BlockStateId,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
cell::{Cell, RefCell},
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
fmt::Write as _,
|
||||
fs,
|
||||
@@ -106,6 +111,12 @@ struct World<'a> {
|
||||
spawners_work: bool,
|
||||
/// Types and boxes of living entities (case entities, then spawned mobs).
|
||||
entities: RefCell<Vec<(String, Aabb)>>,
|
||||
/// Blocks set since the case started (a trial spawner's states).
|
||||
placed: RefCell<Vec<([i32; 3], BlockStateId)>>,
|
||||
/// The game time (trial cases advance it).
|
||||
time: Cell<i64>,
|
||||
/// The mobs a trial spawner added: UUID, position and box.
|
||||
trial_mobs: RefCell<Vec<([i32; 4], [f64; 3], Aabb)>>,
|
||||
}
|
||||
impl World<'_> {
|
||||
fn biome_at(&self, x: i32, y: i32, z: i32) -> &str {
|
||||
@@ -129,6 +140,15 @@ impl World<'_> {
|
||||
}
|
||||
impl SpawnLevel for World<'_> {
|
||||
fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId {
|
||||
if let Some((_, s)) = self
|
||||
.placed
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(p, _)| *p == [x, y, z])
|
||||
{
|
||||
return *s;
|
||||
}
|
||||
self.blocks
|
||||
.iter()
|
||||
.rev()
|
||||
@@ -341,6 +361,50 @@ impl SpawnerLevel for World<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl TrialSpawnerLevel for World<'_> {
|
||||
fn game_time(&self) -> i64 {
|
||||
self.time.get()
|
||||
}
|
||||
fn mob_spawning(&self) -> bool {
|
||||
self.spawn_mobs
|
||||
}
|
||||
fn players(&self) -> Vec<TrialPlayer> {
|
||||
self.players
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (p, mode))| TrialPlayer {
|
||||
uuid: [0, 0, 0, i as i32 + 1],
|
||||
block: p.map(|v| v.floor() as i32),
|
||||
eye: [p[0], p[1] + f64::from(1.62f32), p[2]],
|
||||
creative: mode == "creative",
|
||||
spectator: mode == "spectator",
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> {
|
||||
let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z);
|
||||
let mut scene = LookupCollisions {
|
||||
block: &lookup,
|
||||
binding: self.s.collision,
|
||||
};
|
||||
let v = |p: [f64; 3]| horizon_core::geometry::Vec3::new(p[0], p[1], p[2]);
|
||||
horizon_client::mobs::visual_clip(
|
||||
self.s.facts,
|
||||
self.s.collision,
|
||||
&mut scene,
|
||||
&lookup,
|
||||
v(from),
|
||||
v(to),
|
||||
)
|
||||
.flatten()
|
||||
}
|
||||
fn entity_block(&self, uuid: [i32; 4]) -> Option<[i32; 3]> {
|
||||
let mobs = self.trial_mobs.borrow();
|
||||
let (_, p, _) = mobs.iter().find(|(u, ..)| *u == uuid)?;
|
||||
Some(p.map(|v| v.floor() as i32))
|
||||
}
|
||||
}
|
||||
|
||||
/// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random.
|
||||
fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb {
|
||||
let t = &l.s.types.types[r.entity];
|
||||
@@ -407,6 +471,13 @@ fn main() -> horizon_client::Result<()> {
|
||||
let facts = BlockFacts::load(root, registry)?;
|
||||
let data = MobData::load(root, &facts);
|
||||
let items = Items::tags_only(root)?;
|
||||
// Trial spawner rewards: the loot tables and the configs.
|
||||
let loot = if input.contains("mode=trial") {
|
||||
horizon_client::mobs::trial_spawner::load_registry(root);
|
||||
horizon_client::structure_blocks::loot_data(root)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let types = MobTypes::load(root)?;
|
||||
let biomes = Biomes::load(root)?;
|
||||
let structures = StructureSpawns::load(root);
|
||||
@@ -593,6 +664,9 @@ fn main() -> horizon_client::Result<()> {
|
||||
unloaded,
|
||||
spawn_mobs: get("rules", "1") != "0",
|
||||
spawners_work: get("spawners", "1") != "0",
|
||||
placed: RefCell::new(Vec::new()),
|
||||
time: Cell::new(0),
|
||||
trial_mobs: RefCell::new(Vec::new()),
|
||||
entities: RefCell::new(
|
||||
case_entities
|
||||
.iter()
|
||||
@@ -629,6 +703,9 @@ fn main() -> horizon_client::Result<()> {
|
||||
let mode = get("mode", "chunk");
|
||||
if mode == "spawner" {
|
||||
spawner_case(&world, &get, &mut random, &mut log)?;
|
||||
} else if mode == "trial" {
|
||||
let loot = loot.as_ref().ok_or("no loot tables")?;
|
||||
trial_case(&world, registry, loot, &get, &mut random, &mut log)?;
|
||||
} else if mode == "gen" {
|
||||
let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?);
|
||||
// The level random of the spawn predicates: no creature's predicate
|
||||
@@ -831,3 +908,196 @@ fn spawner_case(
|
||||
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `TrialSpawner.tickServer` `ticks` times from game time `t0` at `spos` on a
|
||||
/// trial spawner block in state `state` (ominous with `ominous=1`) loaded from
|
||||
/// `snbt` (base64 SNBT), as the oracle logs it. Every `kill` ticks the mobs it
|
||||
/// spawned die.
|
||||
fn trial_case(
|
||||
world: &World,
|
||||
registry: &horizon_world::registry::BlockRegistry,
|
||||
loot: &horizon_world::loot::LootData,
|
||||
get: &dyn Fn(&str, &'static str) -> String,
|
||||
random: &mut LegacyRandom,
|
||||
log: &mut Vec<String>,
|
||||
) -> horizon_client::Result<()> {
|
||||
let v: Vec<i32> = get("spos", "0,0,0")
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap_or(0))
|
||||
.collect();
|
||||
let pos = [v[0], v[1], v[2]];
|
||||
let block_state = |state: TrialState, ominous: bool| {
|
||||
parse_state(&format!(
|
||||
"minecraft:trial_spawner[trial_spawner_state={},ominous={ominous}]",
|
||||
state.name()
|
||||
))
|
||||
};
|
||||
let mut state =
|
||||
TrialState::from_name(&get("state", "waiting_for_players")).ok_or("bad state")?;
|
||||
let mut ominous = get("ominous", "0") == "1";
|
||||
world
|
||||
.placed
|
||||
.borrow_mut()
|
||||
.push((pos, registry.resolve(&block_state(state, ominous))?));
|
||||
let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?;
|
||||
let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0;
|
||||
let mut spawner = TrialSpawner::load(&tag);
|
||||
let ticks: i64 = get("ticks", "1").parse()?;
|
||||
let t0: i64 = get("t0", "0").parse()?;
|
||||
let kill: i64 = get("kill", "0").parse()?;
|
||||
let seed = world.seed;
|
||||
let mut sequences = horizon_client::random_sequences::RandomSequences::default();
|
||||
let center = pos.map(|v| f64::from(v) + 0.5);
|
||||
for tick in 0..ticks {
|
||||
world.time.set(t0 + tick);
|
||||
let mut events = Vec::new();
|
||||
let mut spawned = std::collections::VecDeque::new();
|
||||
let mut items = Vec::new();
|
||||
let mut spawn = |l: &World, r: &SpawnerSpawn| {
|
||||
let t = l.s.types.types.get(r.id)?;
|
||||
// Slime.readAdditionalSaveData: size Size + 1, clamped to 1..=127.
|
||||
let size = match r.entity.get(&horizon_world::nbt::JavaString::from("Size")) {
|
||||
Some(Tag::Byte(v)) => i32::from(*v),
|
||||
Some(Tag::Short(v)) => i32::from(*v),
|
||||
Some(Tag::Int(v)) => *v,
|
||||
Some(Tag::Long(v)) => *v as i32,
|
||||
_ => 0,
|
||||
};
|
||||
let size = if matches!(r.id, "minecraft:slime" | "minecraft:magma_cube") {
|
||||
size.saturating_add(1).clamp(1, 127)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let [x, y, z] = r.position;
|
||||
let scale = size as f32;
|
||||
let bounds = spawn_box(x, y, z, t.width as f32 * scale, t.height as f32 * scale);
|
||||
l.entities.borrow_mut().push((r.id.to_owned(), bounds));
|
||||
let uuid = [1, 0, 0, l.trial_mobs.borrow().len() as i32];
|
||||
l.trial_mobs.borrow_mut().push((uuid, r.position, bounds));
|
||||
spawned.push_back(format!(
|
||||
"{tick} spawn {} {} {} {} {}",
|
||||
r.id,
|
||||
bits(x),
|
||||
bits(y),
|
||||
bits(z),
|
||||
if size == 1 {
|
||||
yaw_text(r.id, r.yaw)
|
||||
} else {
|
||||
"head".to_owned()
|
||||
}
|
||||
));
|
||||
Some(uuid)
|
||||
};
|
||||
let mut eject = |table: &str, random: &mut LegacyRandom| {
|
||||
let drops = match loot.random_sequence(table) {
|
||||
Some(s) => loot.roll_split(table, sequences.get(s, seed)),
|
||||
None => loot.roll_split(table, random),
|
||||
};
|
||||
for stack in &drops {
|
||||
random.next_double();
|
||||
let spread = 0.017_227_5 * 2.0;
|
||||
let v = [
|
||||
random.triangle(0.0, spread),
|
||||
random.triangle(0.2, spread),
|
||||
random.triangle(0.0, spread),
|
||||
];
|
||||
items.push(format!(
|
||||
"{tick} item {} {} {} {} {} {} {} {}",
|
||||
stack.item,
|
||||
stack.count,
|
||||
bits(center[0]),
|
||||
bits(center[1] + 0.7 - 0.125),
|
||||
bits(center[2]),
|
||||
bits(v[0]),
|
||||
bits(v[1]),
|
||||
bits(v[2])
|
||||
));
|
||||
}
|
||||
!drops.is_empty()
|
||||
};
|
||||
let next = spawner.server_tick(
|
||||
world,
|
||||
random,
|
||||
pos,
|
||||
state,
|
||||
ominous,
|
||||
&mut spawn,
|
||||
&mut eject,
|
||||
&mut events,
|
||||
);
|
||||
for e in events {
|
||||
match e {
|
||||
TrialEvent::BlockUpdated => log.push(format!("{tick} update")),
|
||||
TrialEvent::LevelEvent(id, _, data) => {
|
||||
// A spawn's events follow its tryAddFreshEntityWithPassengers,
|
||||
// a reward's its items.
|
||||
match id {
|
||||
3011 => log.extend(spawned.pop_front()),
|
||||
3014 => log.append(&mut items),
|
||||
_ => {}
|
||||
}
|
||||
log.push(format!("{tick} levent {id} {data}"));
|
||||
}
|
||||
TrialEvent::Sound(name) => log.push(format!(
|
||||
"{tick} sound minecraft:{name} {} {} {} 1.0 1.0",
|
||||
bits(center[0]),
|
||||
bits(center[1]),
|
||||
bits(center[2])
|
||||
)),
|
||||
TrialEvent::EntityPlace(_, p) => log.push(format!(
|
||||
"{tick} gevent minecraft:entity_place {} {} {}",
|
||||
p[0], p[1], p[2]
|
||||
)),
|
||||
TrialEvent::OminousSet(set) => {
|
||||
ominous = set;
|
||||
world
|
||||
.placed
|
||||
.borrow_mut()
|
||||
.push((pos, registry.resolve(&block_state(state, ominous))?));
|
||||
log.push(format!("{tick} state {} {ominous}", state.name()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if next != state || spawner.is_ominous != ominous {
|
||||
state = next;
|
||||
ominous = spawner.is_ominous;
|
||||
world
|
||||
.placed
|
||||
.borrow_mut()
|
||||
.push((pos, registry.resolve(&block_state(state, ominous))?));
|
||||
log.push(format!("{tick} state {} {ominous}", state.name()));
|
||||
}
|
||||
if kill > 0 && tick % kill == kill - 1 {
|
||||
let dead: Vec<Aabb> = world
|
||||
.trial_mobs
|
||||
.borrow_mut()
|
||||
.drain(..)
|
||||
.map(|(.., b)| b)
|
||||
.collect();
|
||||
world
|
||||
.entities
|
||||
.borrow_mut()
|
||||
.retain(|(_, b)| !dead.iter().any(|d| d == b));
|
||||
if !dead.is_empty() {
|
||||
log.push(format!("{tick} kill {}", dead.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
log.push(format!(
|
||||
"end state={} players={} mobs={} cooldown={} next_spawn={} total={} data={} eject={}",
|
||||
state.name(),
|
||||
spawner.detected_players.len(),
|
||||
spawner.current_mobs.len(),
|
||||
spawner.cooldown_ends_at,
|
||||
spawner.next_mob_spawns_at,
|
||||
spawner.total_mobs_spawned,
|
||||
spawner
|
||||
.next_spawn_data
|
||||
.as_ref()
|
||||
.and_then(|d| d.id())
|
||||
.unwrap_or_else(|| "-".into()),
|
||||
spawner.ejecting_loot_table.as_deref().unwrap_or("-")
|
||||
));
|
||||
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
mod common;
|
||||
use common::{Fake, d, describe, f, flush, result_name};
|
||||
use horizon_client::sound_engine::{
|
||||
Attenuation, Backend, InstanceId, SoundEngine, SoundInstance, TickContext,
|
||||
Attenuation, Backend, CartSound, InstanceId, SoundEngine, SoundInstance, TickContext,
|
||||
};
|
||||
use horizon_client::sound_events::SoundRegistry;
|
||||
use horizon_core::random::LegacyRandom;
|
||||
@@ -19,6 +19,9 @@ fn main() {
|
||||
let mut backend = Fake::default();
|
||||
let mut ctx = TickContext::default();
|
||||
let mut instances: BTreeMap<String, InstanceId> = BTreeMap::new();
|
||||
// Script cart names to entity ids (a removed cart leaves the level).
|
||||
let mut cart_ids: BTreeMap<String, u32> = BTreeMap::new();
|
||||
let mut removed: BTreeMap<u32, CartSound> = BTreeMap::new();
|
||||
let input = std::fs::read_to_string(&args[2]).expect("input");
|
||||
let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output"));
|
||||
for line in input.lines() {
|
||||
@@ -49,6 +52,21 @@ fn main() {
|
||||
"loop" => SoundInstance::biome_loop(&event, random),
|
||||
"uloop" => SoundInstance::under_liquid_loop(&event, random),
|
||||
"usub" => SoundInstance::under_liquid_sub(&event, random),
|
||||
"cart" | "rcart" | "rcartu" => {
|
||||
let id = cart_ids[a[3]];
|
||||
let cart = ctx
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.or_else(|| removed.get(&id))
|
||||
.copied()
|
||||
.expect("cart");
|
||||
if a[2] == "cart" {
|
||||
SoundInstance::minecart(&cart, random)
|
||||
} else {
|
||||
SoundInstance::riding_minecart(&cart, a[2] == "rcartu", random)
|
||||
}
|
||||
}
|
||||
_ => panic!("{line}"),
|
||||
};
|
||||
if let Some(old) = instances.remove(a[1]) {
|
||||
@@ -92,6 +110,26 @@ fn main() {
|
||||
ctx.player_underwater = a[1] == "1";
|
||||
ctx.player_removed = a[2] == "1";
|
||||
}
|
||||
"cart" => {
|
||||
let next = cart_ids.len() as u32 + 1;
|
||||
let id = *cart_ids.entry(a[1].to_owned()).or_insert(next);
|
||||
ctx.carts.retain(|c| c.id != id);
|
||||
let cart = CartSound {
|
||||
id,
|
||||
position: [d(a[2]), d(a[3]), d(a[4])],
|
||||
// Vec3.horizontalDistance.
|
||||
speed: (d(a[5]) * d(a[5]) + d(a[7]) * d(a[7])).sqrt(),
|
||||
};
|
||||
if a[8] == "1" {
|
||||
// Out of the level, still there for a later play.
|
||||
removed.insert(id, cart);
|
||||
} else {
|
||||
removed.remove(&id);
|
||||
ctx.carts.push(cart);
|
||||
}
|
||||
}
|
||||
"ride" => ctx.vehicle = cart_ids.get(a[1]).copied(),
|
||||
"freeze" => ctx.frozen = a[1] == "1",
|
||||
"tick" => engine.tick(a[1] == "1", &ctx, &mut backend),
|
||||
"forget" => {
|
||||
if let Some(id) = instances.remove(a[1]) {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! `AbstractArrow.tick` for arrows, tipped and spectral arrows: the flight with
|
||||
//! its water inertia and bubbles, the base tick's fluids (currents, splash),
|
||||
//! bubble columns and water along the path, sticking in blocks, falling out
|
||||
//! when the block goes, and despawning. Entity hits and their effects stay
|
||||
//! with the game (`projectile_hit`).
|
||||
//! when the block goes, and despawning. The tick stops at an entity it hits:
|
||||
//! the game hurts the entity (`projectile_hit`), then `finish_entity_hit`
|
||||
//! spends the arrow or turns it back and ends the tick.
|
||||
use crate::{
|
||||
blocks::BlockFacts,
|
||||
collisions::SceneCollisions,
|
||||
@@ -113,6 +114,9 @@ pub enum ArrowEvent {
|
||||
/// The SPLASH and PROJECTILE_SHOOT game events.
|
||||
SplashEvent,
|
||||
ShootEvent,
|
||||
/// `spawnAtLocation(pickupItem, 0.1)`: a turned-back arrow too slow to fly
|
||||
/// on drops what picking it up gives.
|
||||
Drop,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArrowParticle {
|
||||
@@ -124,7 +128,7 @@ pub enum ArrowParticle {
|
||||
pub enum ArrowSound {
|
||||
/// `entity.generic.splash` (an arrow's splash and high-speed splash).
|
||||
Splash,
|
||||
/// The arrow's hit-ground sound (`entity.arrow.hit`).
|
||||
/// The arrow's `soundEvent` (`entity.arrow.hit`), for blocks and entities.
|
||||
HitGround,
|
||||
/// `entity.generic.extinguish_fire`.
|
||||
Extinguish,
|
||||
@@ -382,14 +386,17 @@ fn signum(v: f64) -> f64 {
|
||||
v
|
||||
}
|
||||
}
|
||||
/// One arrow tick: whether to keep it and what it hit.
|
||||
/// One arrow tick: whether to keep it and what it hit. An arrow that hit an
|
||||
/// entity stops there and is not kept: the game hands it to
|
||||
/// `finish_entity_hit` once it has hurt the entity.
|
||||
pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> (bool, Hit) {
|
||||
let Some(mut st) = p.arrow.take() else {
|
||||
return (false, Hit::None);
|
||||
};
|
||||
// Entity.setOldPosAndRot: the renderer interpolates from here, in flight
|
||||
// and stuck alike.
|
||||
// and stuck alike; ServerLevel.tickNonPassenger counts the tick.
|
||||
p.previous = p.position;
|
||||
p.age += 1;
|
||||
let hit = Ticker {
|
||||
p,
|
||||
st: &mut st,
|
||||
@@ -397,10 +404,44 @@ pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) ->
|
||||
}
|
||||
.tick(targets);
|
||||
p.stuck = st.in_ground;
|
||||
let keep = !st.removed;
|
||||
let keep = !st.removed && !matches!(hit, Hit::Entity { .. });
|
||||
p.arrow = Some(st);
|
||||
(keep, hit)
|
||||
}
|
||||
/// What became of the entity an arrow hit (`AbstractArrow.onHitEntity`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EntityHit {
|
||||
/// `hurtOrSimulate` succeeded: the arrow is spent, with its hit sound.
|
||||
Hurt,
|
||||
/// It failed (a raised shield, invulnerability): the arrow turns back.
|
||||
Refused,
|
||||
/// The entity turned it first (`Entity.deflection`: breezes).
|
||||
Deflected,
|
||||
}
|
||||
/// The rest of the tick of an arrow that hit an entity: whether to keep it.
|
||||
pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: EntityHit) -> bool {
|
||||
let Some(mut st) = p.arrow.take() else {
|
||||
return false;
|
||||
};
|
||||
let mut ticker = Ticker {
|
||||
p,
|
||||
st: &mut st,
|
||||
scene,
|
||||
};
|
||||
match outcome {
|
||||
EntityHit::Hurt => {
|
||||
ticker.hit_sound();
|
||||
ticker.st.removed = true;
|
||||
}
|
||||
EntityHit::Refused => ticker.turn_back(),
|
||||
EntityHit::Deflected => {}
|
||||
}
|
||||
ticker.finish();
|
||||
p.stuck = st.in_ground;
|
||||
let keep = !st.removed;
|
||||
p.arrow = Some(st);
|
||||
keep
|
||||
}
|
||||
struct Ticker<'p, 's, 'a, 'r> {
|
||||
p: &'p mut Projectile,
|
||||
st: &'s mut ArrowState,
|
||||
@@ -517,10 +558,20 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
);
|
||||
if physics {
|
||||
hit = self.step_move_and_hit(original, end, targets);
|
||||
if matches!(hit, Hit::Entity { .. }) {
|
||||
return hit;
|
||||
}
|
||||
} else {
|
||||
self.p.position = end;
|
||||
self.apply_effects_from_blocks(original, end);
|
||||
}
|
||||
self.finish();
|
||||
hit
|
||||
}
|
||||
/// The end of a tick in flight: drag and gravity, then `Projectile.tick`
|
||||
/// and `Entity.baseTick`'s fluid and fire phases.
|
||||
fn finish(&mut self) {
|
||||
let physics = !self.st.no_physics;
|
||||
if !self.st.was_touching_water {
|
||||
self.p.velocity = self.p.velocity.scale(f64::from(0.99f32));
|
||||
}
|
||||
@@ -547,7 +598,6 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.st.removed = true;
|
||||
}
|
||||
self.st.first_tick = false;
|
||||
hit
|
||||
}
|
||||
/// `getDeltaMovement().add(0, y, 0)`: the zeros added to x and z also
|
||||
/// turn a negative zero positive.
|
||||
@@ -589,16 +639,23 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.st.life = 0;
|
||||
}
|
||||
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
|
||||
/// block (not piercing: the game removes an arrow that hits an entity).
|
||||
/// block (piercing is not modelled).
|
||||
fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit {
|
||||
let block = self.scene.clip(from, to);
|
||||
let end = block.map_or(to, |b| b.0);
|
||||
// findHitEntities: ProjectileUtil.computeMargin and the search box.
|
||||
let margin = f64::from(((self.p.age as i32 - 2) as f32 / 20.0).clamp(0.0, 0.3));
|
||||
let area = bounds(from)
|
||||
.expand_towards(self.p.velocity)
|
||||
.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||
let mut best: Option<(Who, Vec3, f64)> = None;
|
||||
for (who, b) in targets {
|
||||
if Some(*who) == self.p.owner && !self.p.left_owner {
|
||||
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
|
||||
continue;
|
||||
}
|
||||
if let Some(at) = b.inflate(Vec3::new(0.3, 0.3, 0.3)).clip(from, end) {
|
||||
if let Some(at) = self.entity_hit(b, from, end, margin) {
|
||||
// Sorted by the distance to the entity's position (the
|
||||
// stable sort keeps the first of equals).
|
||||
let c = b.center();
|
||||
let d = from.distance_squared(Vec3::new(c.x, b.min_position().y, c.z));
|
||||
if best.is_none_or(|bb| d < bb.2) {
|
||||
@@ -610,8 +667,6 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.p.position = next;
|
||||
self.apply_effects_from_blocks(from, next);
|
||||
if let Some((who, at, _)) = best {
|
||||
// The game hurts it; the arrow is spent (piercing is not modelled).
|
||||
self.st.removed = true;
|
||||
return Hit::Entity { who, at };
|
||||
}
|
||||
let Some((at, pos, face)) = block else {
|
||||
@@ -631,6 +686,49 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
face,
|
||||
}
|
||||
}
|
||||
/// `ProjectileUtil.getManyEntityHitResult` for one entity box: where the
|
||||
/// path enters it, else where it enters the box grown by `margin`, if a
|
||||
/// line from there towards the centre (stopped by blocks) reaches the box.
|
||||
fn entity_hit(&self, b: &Aabb, from: Vec3, to: Vec3, margin: f64) -> Option<Vec3> {
|
||||
if let Some(at) = b.clip(from, to) {
|
||||
return Some(at);
|
||||
}
|
||||
if margin <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let outside = b
|
||||
.inflate(Vec3::new(margin, margin, margin))
|
||||
.clip(from, to)?;
|
||||
let centre = b.center();
|
||||
let towards = self.scene.clip(outside, centre).map_or(centre, |h| h.0);
|
||||
b.clip(outside, towards).map(|_| outside)
|
||||
}
|
||||
/// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`.
|
||||
fn hit_sound(&mut self) {
|
||||
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::HitGround,
|
||||
volume: 1.0,
|
||||
pitch,
|
||||
});
|
||||
}
|
||||
/// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`,
|
||||
/// a half turn give or take ten degrees at a tenth of the speed; one
|
||||
/// left almost still drops its pickup (ALLOWED) and is discarded.
|
||||
fn turn_back(&mut self) {
|
||||
let power = 0.2;
|
||||
let rotation = 170.0 + self.st.random.next_float() * 20.0;
|
||||
let v = self.p.velocity;
|
||||
let k = -power * 0.5;
|
||||
self.p.velocity = Vec3::new(v.x * k, v.y * k, v.z * k);
|
||||
self.p.yaw += rotation;
|
||||
if self.p.velocity.length_squared() < 1.0e-7 {
|
||||
if self.st.pickup == Pickup::Allowed {
|
||||
self.st.events.push(ArrowEvent::Drop);
|
||||
}
|
||||
self.st.removed = true;
|
||||
}
|
||||
}
|
||||
/// `AbstractArrow.onHitBlock`: back off the face by 0.05 along each axis
|
||||
/// it moved on, stop, and stick.
|
||||
fn on_hit_block(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
@@ -649,12 +747,7 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.p.position.z - signum(v.z) * offset,
|
||||
);
|
||||
self.p.velocity = Vec3::ZERO;
|
||||
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::HitGround,
|
||||
volume: 1.0,
|
||||
pitch,
|
||||
});
|
||||
self.hit_sound();
|
||||
self.st.in_ground = true;
|
||||
self.st.shake = 7;
|
||||
self.p.set_critical(false);
|
||||
|
||||
@@ -393,6 +393,10 @@ impl FixedStep {
|
||||
pub fn frozen(&self) -> bool {
|
||||
self.manager.base.is_frozen()
|
||||
}
|
||||
/// `runsNormally` as of the last `world_runs`.
|
||||
pub fn runs_normally(&self) -> bool {
|
||||
self.manager.base.runs_normally()
|
||||
}
|
||||
pub fn set_frozen(&mut self, frozen: bool) {
|
||||
self.manager.base.set_frozen(frozen);
|
||||
}
|
||||
|
||||
@@ -68,6 +68,8 @@ pub enum BlockEntity {
|
||||
Crafter(Crafter),
|
||||
/// `SpawnerBlockEntity` (`crate::mobs::spawner`).
|
||||
Spawner(Box<crate::mobs::spawner::Spawner>),
|
||||
/// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`).
|
||||
TrialSpawner(Box<crate::mobs::trial_spawner::TrialSpawner>),
|
||||
/// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`).
|
||||
Beehive(Box<crate::beehive::Beehive>),
|
||||
}
|
||||
@@ -187,6 +189,9 @@ impl BlockEntity {
|
||||
if name == "minecraft:spawner" {
|
||||
return Some(Self::Spawner(Box::default()));
|
||||
}
|
||||
if name == "minecraft:trial_spawner" {
|
||||
return Some(Self::TrialSpawner(Box::default()));
|
||||
}
|
||||
if name == "minecraft:beehive" || name == "minecraft:bee_nest" {
|
||||
return Some(Self::Beehive(Box::default()));
|
||||
}
|
||||
@@ -266,6 +271,7 @@ impl BlockEntity {
|
||||
Self::Crafter(_) => "minecraft:crafter",
|
||||
Self::CreakingHeart(_) => "minecraft:creaking_heart",
|
||||
Self::Spawner(_) => "minecraft:mob_spawner",
|
||||
Self::TrialSpawner(_) => "minecraft:trial_spawner",
|
||||
Self::Beehive(_) => "minecraft:beehive",
|
||||
}
|
||||
}
|
||||
@@ -276,9 +282,11 @@ impl BlockEntity {
|
||||
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
|
||||
Self::Sign(_) => Vec::new(),
|
||||
Self::Jukebox(j) => j.record.iter().cloned().collect(),
|
||||
Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => {
|
||||
Vec::new()
|
||||
}
|
||||
Self::Beacon(_)
|
||||
| Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Beehive(_) => Vec::new(),
|
||||
Self::Lectern(l) => l.book.iter().cloned().collect(),
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
@@ -297,7 +305,10 @@ impl BlockEntity {
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &[],
|
||||
Self::Crafter(c) => &c.items,
|
||||
Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &[],
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Beehive(_) => &[],
|
||||
}
|
||||
}
|
||||
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
|
||||
@@ -312,7 +323,10 @@ impl BlockEntity {
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &mut [],
|
||||
Self::Crafter(c) => &mut c.items,
|
||||
Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &mut [],
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Beehive(_) => &mut [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,579 @@
|
||||
//! The debug charts (26.3 `debugchart`): F3+2 shows the frame times and, in
|
||||
//! single player, the integrated server's tick times; F3+3 the ping and, on a
|
||||
//! remote server, the bandwidth. Each chart keeps the last 240 samples
|
||||
//! (`LocalSampleLogger`) and draws one bar per sample over a 60 pixel high
|
||||
//! box (`AbstractDebugChart`).
|
||||
use crate::{
|
||||
font::Font,
|
||||
hud_layout::{GuiDraw, argb, fill},
|
||||
text::Text,
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// `LocalSampleLogger.CAPACITY`.
|
||||
pub const CAPACITY: usize = 240;
|
||||
/// `AbstractDebugChart.CHART_HEIGHT`.
|
||||
pub const CHART_HEIGHT: i32 = 60;
|
||||
/// `TpsDebugDimensions`: a tick sample's values.
|
||||
pub const FULL_TICK: usize = 0;
|
||||
pub const TICK_SERVER_METHOD: usize = 1;
|
||||
pub const SCHEDULED_TASKS: usize = 2;
|
||||
pub const IDLE: usize = 3;
|
||||
|
||||
/// `LocalSampleLogger`: the last [`CAPACITY`] samples, oldest first; a
|
||||
/// sample has up to four values (`TpsDebugDimensions`), the first the main.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SampleLogger {
|
||||
samples: VecDeque<[i64; 4]>,
|
||||
}
|
||||
impl SampleLogger {
|
||||
/// `logSample`.
|
||||
pub fn log(&mut self, value: i64) {
|
||||
self.log_full([value, 0, 0, 0]);
|
||||
}
|
||||
/// `logFullSample`.
|
||||
pub fn log_full(&mut self, sample: [i64; 4]) {
|
||||
if self.samples.len() == CAPACITY {
|
||||
self.samples.pop_front();
|
||||
}
|
||||
self.samples.push_back(sample);
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.samples.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.samples.is_empty()
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.samples.clear();
|
||||
}
|
||||
fn get(&self, index: usize, dimension: usize) -> i64 {
|
||||
self.samples[index][dimension]
|
||||
}
|
||||
}
|
||||
|
||||
/// `DebugScreenOverlay`'s chart switches and the samples behind them.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DebugCharts {
|
||||
/// `renderFpsCharts` (F3+2).
|
||||
pub fps: bool,
|
||||
/// `renderNetworkCharts` (F3+3).
|
||||
pub network: bool,
|
||||
/// `renderLightmapTexture` (F3+4).
|
||||
pub lightmap: bool,
|
||||
/// `frameTimeLogger`: nanoseconds between frames.
|
||||
pub frame_times: SampleLogger,
|
||||
/// `tickTimeLogger`: the integrated server's ticks.
|
||||
pub tick_times: SampleLogger,
|
||||
/// `pingLogger`: milliseconds.
|
||||
pub ping: SampleLogger,
|
||||
/// `bandwidthLogger`: bytes received per tick.
|
||||
pub bandwidth: SampleLogger,
|
||||
previous_tick: Option<Instant>,
|
||||
bytes_seen: Option<i64>,
|
||||
}
|
||||
impl DebugCharts {
|
||||
/// `toggleFpsCharts`; `overlay` is the debug overlay's visibility.
|
||||
pub fn toggle_fps(&mut self, overlay: &mut bool) {
|
||||
self.fps = !*overlay || !self.fps;
|
||||
if self.fps {
|
||||
*overlay = true;
|
||||
self.network = false;
|
||||
self.lightmap = false;
|
||||
}
|
||||
}
|
||||
/// `toggleNetworkCharts`.
|
||||
pub fn toggle_network(&mut self, overlay: &mut bool) {
|
||||
self.network = !*overlay || !self.network;
|
||||
if self.network {
|
||||
*overlay = true;
|
||||
self.fps = false;
|
||||
self.lightmap = false;
|
||||
}
|
||||
}
|
||||
/// `toggleLightmapTexture`.
|
||||
pub fn toggle_lightmap(&mut self, overlay: &mut bool) {
|
||||
self.lightmap = !*overlay || !self.lightmap;
|
||||
if self.lightmap {
|
||||
*overlay = true;
|
||||
self.fps = false;
|
||||
self.network = false;
|
||||
}
|
||||
}
|
||||
/// `reset`: leaving a world.
|
||||
pub fn reset(&mut self) {
|
||||
self.tick_times.reset();
|
||||
self.ping.reset();
|
||||
self.bandwidth.reset();
|
||||
self.previous_tick = None;
|
||||
self.bytes_seen = None;
|
||||
}
|
||||
/// One integrated server tick that started at `started` and ran its
|
||||
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
|
||||
/// `logTickMethodTime`): the full tick runs from one start to the next,
|
||||
/// and what the tick method leaves of it is idle.
|
||||
pub fn log_tick(&mut self, started: Instant, method: Duration) {
|
||||
let method = method.as_nanos() as i64;
|
||||
let full = self
|
||||
.previous_tick
|
||||
.map_or(method, |p| (started - p).as_nanos() as i64)
|
||||
.max(method);
|
||||
self.previous_tick = Some(started);
|
||||
self.tick_times.log_full([full, method, 0, full - method]);
|
||||
}
|
||||
/// `BandwidthDebugMonitor.tick`: the bytes received since the last
|
||||
/// tick, from the connection's running total.
|
||||
pub fn log_bandwidth(&mut self, total: i64) {
|
||||
if let Some(seen) = self.bytes_seen {
|
||||
self.bandwidth.log(total - seen);
|
||||
}
|
||||
self.bytes_seen = Some(total);
|
||||
}
|
||||
/// The charts along the bottom of the screen (`extractRenderState`):
|
||||
/// frame times left and tick times right, or bandwidth left (remote
|
||||
/// servers only) and ping right. `mspt` is the level's milliseconds
|
||||
/// per tick.
|
||||
pub fn draw(
|
||||
&self,
|
||||
font: &Font,
|
||||
width: i32,
|
||||
height: i32,
|
||||
framerate_limit: u32,
|
||||
mspt: f32,
|
||||
remote: bool,
|
||||
) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
let max_width = width / 2;
|
||||
let chart_width = Chart::width(max_width);
|
||||
if self.fps {
|
||||
let fps = Chart::Fps { framerate_limit };
|
||||
out.extend(fps.draw(font, &self.frame_times, 0, chart_width, height));
|
||||
if !self.tick_times.is_empty() {
|
||||
let tps = Chart::Tps { mspt };
|
||||
out.extend(tps.draw(
|
||||
font,
|
||||
&self.tick_times,
|
||||
width - chart_width,
|
||||
chart_width,
|
||||
height,
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.network {
|
||||
if remote {
|
||||
out.extend(Chart::Bandwidth.draw(font, &self.bandwidth, 0, chart_width, height));
|
||||
}
|
||||
out.extend(Chart::Ping.draw(
|
||||
font,
|
||||
&self.ping,
|
||||
width - chart_width,
|
||||
chart_width,
|
||||
height,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The lightmap view (`showLightmapTexture`): the 16 by 16 texture at 64
|
||||
/// by 64 in the bottom right corner on a black border, sky light up and
|
||||
/// block light right (the blit flips the texture's rows). `pixels` are RGBA
|
||||
/// rows of sky level by block level.
|
||||
pub fn lightmap(pixels: &[u8; 16 * 16 * 4], width: i32, height: i32) -> Vec<GuiDraw> {
|
||||
let (x, y) = (width - 64 - 2, height - 64 - 2);
|
||||
let mut out = vec![fill(x - 1, y - 1, x + 64 + 1, y + 64 + 1, 0xFF00_0000)];
|
||||
for (i, p) in pixels.as_chunks::<4>().0.iter().enumerate() {
|
||||
let (sky, block) = ((i / 16) as i32, (i % 16) as i32);
|
||||
let color = argb(255, u32::from(p[0]), u32::from(p[1]), u32::from(p[2]));
|
||||
let (cx, cy) = (x + block * 4, y + (15 - sky) * 4);
|
||||
out.push(fill(cx, cy, cx + 4, cy + 4, color));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The four charts and what each needs to scale its bars.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Chart {
|
||||
/// `FpsDebugChart`: frame durations in nanoseconds; the frame rate limit
|
||||
/// option (`maxFps`).
|
||||
Fps { framerate_limit: u32 },
|
||||
/// `TpsDebugChart`: tick samples in nanoseconds; the level's
|
||||
/// milliseconds per tick.
|
||||
Tps { mspt: f32 },
|
||||
/// `PingDebugChart`: round trips in milliseconds.
|
||||
Ping,
|
||||
/// `BandwidthDebugChart`: bytes received per tick.
|
||||
Bandwidth,
|
||||
}
|
||||
|
||||
/// The labels' colour and the backdrop of the box and shaded labels.
|
||||
const LABEL: u32 = 0xFFE0_E0E0;
|
||||
const BACKDROP: u32 = 0x9050_5050;
|
||||
const WHITE: u32 = 0xFFFF_FFFF;
|
||||
const GREEN: u32 = 0xFF00_FF00;
|
||||
const YELLOW: u32 = 0xFFFF_FF00;
|
||||
const RED: u32 = 0xFFFF_0000;
|
||||
const CYAN: u32 = 0xFF00_FFFF;
|
||||
/// `BandwidthDebugChart.MID_COLOR`.
|
||||
const LAVENDER: u32 = 0xFFA0_A0FF;
|
||||
/// `TpsDebugChart`'s bar parts.
|
||||
const TICK_METHOD_COLOR: u32 = 0xFF99_1111;
|
||||
const TASK_COLOR: u32 = 0xFFBA_995F;
|
||||
const OTHER_COLOR: u32 = 0xFF5F_0E8C;
|
||||
const MEGABYTE: f64 = 1_048_576.0;
|
||||
|
||||
impl Chart {
|
||||
/// `AbstractDebugChart.getWidth`.
|
||||
pub fn width(max_width: i32) -> i32 {
|
||||
(CAPACITY as i32 + 2).min(max_width)
|
||||
}
|
||||
/// `getFullHeight`: the box and the min/avg/max line above it.
|
||||
pub fn full_height() -> i32 {
|
||||
CHART_HEIGHT + 9
|
||||
}
|
||||
/// `AbstractDebugChart.extractRenderState`.
|
||||
pub fn draw(
|
||||
self,
|
||||
font: &Font,
|
||||
samples: &SampleLogger,
|
||||
left: i32,
|
||||
width: i32,
|
||||
bottom: i32,
|
||||
) -> Vec<GuiDraw> {
|
||||
let mut out = vec![fill(
|
||||
left,
|
||||
bottom - CHART_HEIGHT,
|
||||
left + width,
|
||||
bottom,
|
||||
BACKDROP,
|
||||
)];
|
||||
let (mut sum, mut min, mut max) = (0i64, i64::from(i32::MAX), i64::from(i32::MIN));
|
||||
let start = CAPACITY.saturating_sub((width - 2).max(0) as usize);
|
||||
let count = samples.len().saturating_sub(start);
|
||||
for i in 0..count {
|
||||
let x = left + i as i32 + 1;
|
||||
let index = start + i;
|
||||
let value = self.aggregated(samples, index);
|
||||
min = min.min(value);
|
||||
max = max.max(value);
|
||||
sum += value;
|
||||
self.bars(&mut out, samples, bottom, x, index);
|
||||
}
|
||||
horizontal_line(
|
||||
&mut out,
|
||||
left,
|
||||
left + width - 1,
|
||||
bottom - CHART_HEIGHT,
|
||||
WHITE,
|
||||
);
|
||||
horizontal_line(&mut out, left, left + width - 1, bottom - 1, WHITE);
|
||||
vertical_line(&mut out, left, bottom - CHART_HEIGHT, bottom, WHITE);
|
||||
vertical_line(
|
||||
&mut out,
|
||||
left + width - 1,
|
||||
bottom - CHART_HEIGHT,
|
||||
bottom,
|
||||
WHITE,
|
||||
);
|
||||
if count > 0 {
|
||||
let y = bottom - CHART_HEIGHT - 9;
|
||||
let min_text = format!("{} min", self.display(min as f64));
|
||||
let avg_text = format!("{} avg", self.display(sum as f64 / count as f64));
|
||||
let max_text = format!("{} max", self.display(max as f64));
|
||||
text(&mut out, min_text, left + 2, y, LABEL, true);
|
||||
let avg_x = left + width / 2 - font.width(&avg_text) as i32 / 2;
|
||||
text(&mut out, avg_text, avg_x, y, LABEL, true);
|
||||
let max_x = left + width - font.width(&max_text) as i32 - 2;
|
||||
text(&mut out, max_text, max_x, y, LABEL, true);
|
||||
}
|
||||
self.lines_and_labels(&mut out, font, left, width, bottom);
|
||||
out
|
||||
}
|
||||
fn bars(
|
||||
self,
|
||||
out: &mut Vec<GuiDraw>,
|
||||
samples: &SampleLogger,
|
||||
bottom: i32,
|
||||
x: i32,
|
||||
index: usize,
|
||||
) {
|
||||
let value = samples.get(index, 0);
|
||||
let height = self.height(value as f64);
|
||||
out.push(fill(x, bottom - height, x + 1, bottom, self.color(value)));
|
||||
if let Chart::Tps { .. } = self {
|
||||
let method = samples.get(index, TICK_SERVER_METHOD);
|
||||
let method_h = self.height(method as f64);
|
||||
out.push(fill(x, bottom - method_h, x + 1, bottom, TICK_METHOD_COLOR));
|
||||
let tasks = samples.get(index, SCHEDULED_TASKS);
|
||||
let tasks_h = self.height(tasks as f64);
|
||||
out.push(fill(
|
||||
x,
|
||||
bottom - method_h - tasks_h,
|
||||
x + 1,
|
||||
bottom - method_h,
|
||||
TASK_COLOR,
|
||||
));
|
||||
let other = value - samples.get(index, IDLE) - method - tasks;
|
||||
let other_h = self.height(other as f64);
|
||||
out.push(fill(
|
||||
x,
|
||||
bottom - other_h - tasks_h - method_h,
|
||||
x + 1,
|
||||
bottom - tasks_h - method_h,
|
||||
OTHER_COLOR,
|
||||
));
|
||||
}
|
||||
}
|
||||
/// `getValueForAggregation`: a tick's time without its idle part.
|
||||
fn aggregated(self, samples: &SampleLogger, index: usize) -> i64 {
|
||||
match self {
|
||||
Chart::Tps { .. } => samples.get(index, 0) - samples.get(index, IDLE),
|
||||
_ => samples.get(index, 0),
|
||||
}
|
||||
}
|
||||
/// `extractAdditionalLinesAndLabels`.
|
||||
fn lines_and_labels(
|
||||
self,
|
||||
out: &mut Vec<GuiDraw>,
|
||||
font: &Font,
|
||||
left: i32,
|
||||
width: i32,
|
||||
bottom: i32,
|
||||
) {
|
||||
match self {
|
||||
Chart::Fps { framerate_limit } => {
|
||||
shaded(out, font, "30 fps", left + 1, bottom - CHART_HEIGHT + 1);
|
||||
shaded(out, font, "60 fps", left + 1, bottom - 30 + 1);
|
||||
horizontal_line(out, left, left + width - 1, bottom - 30, WHITE);
|
||||
if framerate_limit > 0 && framerate_limit <= 250 {
|
||||
let y = bottom - self.height(1.0e9 / f64::from(framerate_limit)) - 1;
|
||||
horizontal_line(out, left, left + width - 1, y, CYAN);
|
||||
}
|
||||
}
|
||||
Chart::Tps { mspt } => {
|
||||
let tps = 1000.0 / mspt;
|
||||
shaded(
|
||||
out,
|
||||
font,
|
||||
&format!("{tps:.1} tps"),
|
||||
left + 1,
|
||||
bottom - CHART_HEIGHT + 1,
|
||||
);
|
||||
}
|
||||
Chart::Ping => shaded(out, font, "500 ms", left + 1, bottom - CHART_HEIGHT + 1),
|
||||
Chart::Bandwidth => {
|
||||
for bytes in [64.0, 1024.0, 16384.0] {
|
||||
let y = bottom - bandwidth_height(bytes);
|
||||
shaded(out, font, &bandwidth_display(bytes), left + 1, y + 1);
|
||||
horizontal_line(out, left, left + width - 1, y, WHITE);
|
||||
}
|
||||
let y = bottom - bandwidth_height(MEGABYTE) + 1;
|
||||
shaded(out, font, &bandwidth_display(MEGABYTE), left + 1, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `toDisplayString`.
|
||||
fn display(self, sample: f64) -> String {
|
||||
match self {
|
||||
Chart::Fps { .. } | Chart::Tps { .. } => format!("{} ms", java_round(sample / 1.0e6)),
|
||||
Chart::Ping => format!("{} ms", java_round(sample)),
|
||||
Chart::Bandwidth => bandwidth_display(sample * 20.0),
|
||||
}
|
||||
}
|
||||
/// `getSampleHeight`.
|
||||
fn height(self, sample: f64) -> i32 {
|
||||
match self {
|
||||
Chart::Fps { .. } => java_round(sample / 1.0e6 * 60.0 / 33.333333333333336) as i32,
|
||||
Chart::Tps { mspt } => java_round(sample / 1.0e6 * 60.0 / f64::from(mspt)) as i32,
|
||||
Chart::Ping => java_round(sample * 60.0 / 500.0) as i32,
|
||||
Chart::Bandwidth => bandwidth_height(sample * 20.0),
|
||||
}
|
||||
}
|
||||
/// `getSampleColor`.
|
||||
fn color(self, sample: i64) -> u32 {
|
||||
let s = sample as f64;
|
||||
match self {
|
||||
Chart::Fps { .. } => gradient(s / 1.0e6, 0.0, GREEN, 28.0, YELLOW, 56.0, RED),
|
||||
Chart::Tps { mspt } => {
|
||||
let m = f64::from(mspt);
|
||||
gradient(s / 1.0e6, m, GREEN, m * 1.125, YELLOW, m * 1.25, RED)
|
||||
}
|
||||
Chart::Ping => gradient(s, 0.0, GREEN, 250.0, YELLOW, 500.0, RED),
|
||||
Chart::Bandwidth => gradient(s * 20.0, 0.0, CYAN, 8192.0, LAVENDER, 1.048576e7, RED),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `BandwidthDebugChart.toDisplayStringInternal`.
|
||||
fn bandwidth_display(bytes_per_second: f64) -> String {
|
||||
if bytes_per_second >= MEGABYTE {
|
||||
format!("{:.1} MiB/s", bytes_per_second / MEGABYTE)
|
||||
} else if bytes_per_second >= 1024.0 {
|
||||
format!("{:.1} KiB/s", bytes_per_second / 1024.0)
|
||||
} else {
|
||||
format!("{} B/s", bytes_per_second.floor() as i64)
|
||||
}
|
||||
}
|
||||
/// `BandwidthDebugChart.getSampleHeightInternal`: logarithmic, 1 MiB/s at
|
||||
/// the top.
|
||||
fn bandwidth_height(bytes_per_second: f64) -> i32 {
|
||||
java_round((bytes_per_second + 1.0).ln() * 60.0 / MEGABYTE.ln()) as i32
|
||||
}
|
||||
/// `Math.round(double)`: halves round up.
|
||||
fn java_round(v: f64) -> i64 {
|
||||
(v + 0.5).floor() as i64
|
||||
}
|
||||
/// `AbstractDebugChart.getSampleColor(sample, min, minColor, mid, ...)`.
|
||||
fn gradient(
|
||||
sample: f64,
|
||||
min: f64,
|
||||
min_color: u32,
|
||||
mid: f64,
|
||||
mid_color: u32,
|
||||
max: f64,
|
||||
max_color: u32,
|
||||
) -> u32 {
|
||||
let sample = sample.clamp(min, max);
|
||||
if sample < mid {
|
||||
srgb_lerp(((sample - min) / (mid - min)) as f32, min_color, mid_color)
|
||||
} else {
|
||||
srgb_lerp(((sample - mid) / (max - mid)) as f32, mid_color, max_color)
|
||||
}
|
||||
}
|
||||
/// `ARGB.srgbLerp`: each channel by `Mth.lerpInt`.
|
||||
fn srgb_lerp(alpha: f32, p0: u32, p1: u32) -> u32 {
|
||||
let channel = |shift: u32| {
|
||||
let (a, b) = (((p0 >> shift) & 255) as i32, ((p1 >> shift) & 255) as i32);
|
||||
(a + (alpha * (b - a) as f32).floor() as i32) as u32
|
||||
};
|
||||
argb(channel(24), channel(16), channel(8), channel(0))
|
||||
}
|
||||
/// `GuiGraphicsExtractor.horizontalLine`.
|
||||
fn horizontal_line(out: &mut Vec<GuiDraw>, x0: i32, x1: i32, y: i32, color: u32) {
|
||||
out.push(fill(x0.min(x1), y, x0.max(x1) + 1, y + 1, color));
|
||||
}
|
||||
/// `GuiGraphicsExtractor.verticalLine`.
|
||||
fn vertical_line(out: &mut Vec<GuiDraw>, x: i32, y0: i32, y1: i32, color: u32) {
|
||||
out.push(fill(x, y0.min(y1) + 1, x + 1, y0.max(y1), color));
|
||||
}
|
||||
fn text(out: &mut Vec<GuiDraw>, s: String, x: i32, y: i32, color: u32, shadow: bool) {
|
||||
out.push(GuiDraw::Text {
|
||||
text: Text::literal(s),
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
});
|
||||
}
|
||||
/// `extractStringWithShade`: a label on a dark backdrop, without shadow.
|
||||
fn shaded(out: &mut Vec<GuiDraw>, font: &Font, s: &str, x: i32, y: i32) {
|
||||
out.push(fill(x, y, x + font.width(s) as i32 + 1, y + 9, BACKDROP));
|
||||
text(out, s.to_owned(), x + 1, y + 1, LABEL, false);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_logger_keeps_the_last_240_samples() {
|
||||
let mut l = SampleLogger::default();
|
||||
for i in 0..300 {
|
||||
l.log(i);
|
||||
}
|
||||
assert_eq!(l.len(), CAPACITY);
|
||||
assert_eq!(l.get(0, 0), 60);
|
||||
assert_eq!(l.get(CAPACITY - 1, 0), 299);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_toggles_show_the_overlay_and_exclude_each_other() {
|
||||
let mut c = DebugCharts::default();
|
||||
let mut overlay = false;
|
||||
c.toggle_fps(&mut overlay);
|
||||
assert!(overlay && c.fps);
|
||||
c.toggle_network(&mut overlay);
|
||||
assert!(c.network && !c.fps);
|
||||
c.toggle_network(&mut overlay);
|
||||
assert!(!c.network && overlay);
|
||||
c.toggle_lightmap(&mut overlay);
|
||||
c.toggle_fps(&mut overlay);
|
||||
assert!(c.fps && !c.lightmap);
|
||||
// With the overlay hidden, the key shows it again with the chart on.
|
||||
c.toggle_fps(&mut overlay);
|
||||
overlay = false;
|
||||
c.toggle_fps(&mut overlay);
|
||||
assert!(overlay && c.fps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lightmap_puts_full_sky_light_at_the_top_left() {
|
||||
let mut pixels = [0u8; 16 * 16 * 4];
|
||||
// Sky 15, block 0: the last row's first texel.
|
||||
pixels[15 * 64..15 * 64 + 4].copy_from_slice(&[10, 20, 30, 255]);
|
||||
let draws = lightmap(&pixels, 427, 240);
|
||||
assert_eq!(draws[0], fill(360, 173, 426, 239, 0xFF00_0000));
|
||||
assert_eq!(draws.len(), 257);
|
||||
assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticks_and_bandwidth_log_their_differences() {
|
||||
let mut c = DebugCharts::default();
|
||||
let t0 = Instant::now();
|
||||
c.log_tick(t0, Duration::from_millis(5));
|
||||
c.log_tick(t0 + Duration::from_millis(50), Duration::from_millis(7));
|
||||
assert_eq!(
|
||||
c.tick_times.samples[1],
|
||||
[50_000_000, 7_000_000, 0, 43_000_000]
|
||||
);
|
||||
c.log_bandwidth(1000);
|
||||
c.log_bandwidth(1600);
|
||||
assert_eq!(c.bandwidth.len(), 1);
|
||||
assert_eq!(c.bandwidth.get(0, 0), 600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heights_match_vanilla_scales() {
|
||||
let fps = Chart::Fps {
|
||||
framerate_limit: 260,
|
||||
};
|
||||
// 33.3 ms (30 fps) fills the chart; 16.7 ms half of it.
|
||||
assert_eq!(fps.height(33_333_333.0), 60);
|
||||
assert_eq!(fps.height(16_666_667.0), 30);
|
||||
let tps = Chart::Tps { mspt: 50.0 };
|
||||
assert_eq!(tps.height(25e6), 30);
|
||||
assert_eq!(Chart::Ping.height(250.0), 30);
|
||||
// 1 MiB/s at the top; 52 bytes per tick is 1 KiB/s.
|
||||
assert_eq!(bandwidth_height(MEGABYTE), 60);
|
||||
assert_eq!(Chart::Bandwidth.height(51.2), 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_match_vanilla_formats() {
|
||||
assert_eq!(
|
||||
Chart::Fps { framerate_limit: 0 }.display(16_500_000.0),
|
||||
"17 ms"
|
||||
);
|
||||
assert_eq!(Chart::Ping.display(12.4), "12 ms");
|
||||
assert_eq!(Chart::Bandwidth.display(3.0), "60 B/s");
|
||||
assert_eq!(Chart::Bandwidth.display(100.0), "2.0 KiB/s");
|
||||
assert_eq!(bandwidth_display(MEGABYTE), "1.0 MiB/s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_go_green_yellow_red() {
|
||||
let fps = Chart::Fps { framerate_limit: 0 };
|
||||
assert_eq!(fps.color(0), GREEN);
|
||||
assert_eq!(fps.color(28_000_000), YELLOW);
|
||||
assert_eq!(fps.color(100_000_000), RED);
|
||||
// Halfway between green and yellow: Mth.lerpInt floors.
|
||||
assert_eq!(fps.color(14_000_000), 0xFF7F_FF00);
|
||||
let tps = Chart::Tps { mspt: 50.0 };
|
||||
assert_eq!(tps.color(10_000_000), GREEN);
|
||||
assert_eq!(Chart::Bandwidth.color(0), CYAN);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,9 @@ pub enum ItemPose {
|
||||
},
|
||||
}
|
||||
|
||||
/// `submitArmWithItem`: the main-hand item pose, before the model transform.
|
||||
/// `submitArmWithItem`: the pose of an item in the hand on the `left` or
|
||||
/// right arm, before the model transform. Only the main hand's charged
|
||||
/// crossbow is turned aside.
|
||||
pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -> glam::Mat4 {
|
||||
use glam::{Mat4, Vec3};
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
@@ -127,6 +129,25 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
|
||||
m
|
||||
}
|
||||
|
||||
/// `FirstPersonHandsAndItems.evaluateWhichHandsToRender`: whether the main
|
||||
/// and the off hand show, from what each holds (item and whether it is a
|
||||
/// charged crossbow) and the item in use with its hand. A bow or crossbow
|
||||
/// being drawn hides the other hand, and a charged crossbow in the main hand
|
||||
/// hides the off hand unless the off hand is the one in use.
|
||||
pub fn hands_to_render(held: [Option<(&str, bool)>; 2], using: Option<(Hand, &str)>) -> [bool; 2] {
|
||||
let bow_like = |id: &str| matches!(id, "minecraft:bow" | "minecraft:crossbow");
|
||||
let charged_crossbow =
|
||||
|h: Option<(&str, bool)>| h.is_some_and(|(id, c)| c && id == "minecraft:crossbow");
|
||||
if !held.iter().flatten().any(|&(id, _)| bow_like(id)) {
|
||||
return [true, true];
|
||||
}
|
||||
match using {
|
||||
None => [true, !charged_crossbow(held[0])],
|
||||
Some((hand, id)) if bow_like(id) => [hand == Hand::Main, hand == Hand::Off],
|
||||
Some((hand, _)) => [true, !(hand == Hand::Main && charged_crossbow(held[1]))],
|
||||
}
|
||||
}
|
||||
|
||||
/// `InteractionHand`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Hand {
|
||||
@@ -719,6 +740,36 @@ impl Clicks {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn drawing_a_bow_or_holding_a_charged_crossbow_hides_a_hand() {
|
||||
let (bow, apple) = (
|
||||
Some(("minecraft:bow", false)),
|
||||
Some(("minecraft:apple", false)),
|
||||
);
|
||||
let charged = Some(("minecraft:crossbow", true));
|
||||
assert_eq!(hands_to_render([apple, apple], None), [true, true]);
|
||||
assert_eq!(hands_to_render([bow, apple], None), [true, true]);
|
||||
assert_eq!(hands_to_render([charged, apple], None), [true, false]);
|
||||
assert_eq!(hands_to_render([apple, charged], None), [true, true]);
|
||||
let drawing = |hand| Some((hand, "minecraft:bow"));
|
||||
assert_eq!(
|
||||
hands_to_render([bow, apple], drawing(Hand::Main)),
|
||||
[true, false]
|
||||
);
|
||||
assert_eq!(
|
||||
hands_to_render([apple, bow], drawing(Hand::Off)),
|
||||
[false, true]
|
||||
);
|
||||
let eating = |hand| Some((hand, "minecraft:apple"));
|
||||
assert_eq!(
|
||||
hands_to_render([apple, charged], eating(Hand::Main)),
|
||||
[true, false]
|
||||
);
|
||||
assert_eq!(
|
||||
hands_to_render([charged, apple], eating(Hand::Off)),
|
||||
[true, true]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn a_swing_lasts_its_duration_and_restarts_after_half() {
|
||||
let mut s = SwingState::default();
|
||||
assert!(s.start_if_able(Hand::Main, SwingAnimation::DEFAULT, 6));
|
||||
|
||||
@@ -154,6 +154,7 @@ impl Title {
|
||||
seed,
|
||||
creative,
|
||||
focus,
|
||||
..
|
||||
} => {
|
||||
let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
|
||||
create_page(ui, x, w, name, seed, *creative, *focus, caret);
|
||||
@@ -379,14 +380,7 @@ impl Title {
|
||||
};
|
||||
}
|
||||
}
|
||||
CREATE => {
|
||||
self.mode = Mode::Create {
|
||||
name: "New World".into(),
|
||||
seed: String::new(),
|
||||
creative: false,
|
||||
focus: 0,
|
||||
}
|
||||
}
|
||||
CREATE => self.mode = Title::new_world(),
|
||||
DELETE_WORLD => {
|
||||
if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() {
|
||||
self.mode = Mode::Delete { world };
|
||||
@@ -814,6 +808,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
|
||||
selected,
|
||||
pings,
|
||||
lan,
|
||||
..
|
||||
} => {
|
||||
let games = lan.games();
|
||||
let sub = match servers.len() {
|
||||
|
||||
+392
-208
File diff suppressed because it is too large
Load Diff
@@ -19,27 +19,99 @@ pub(super) struct Toast {
|
||||
icon: String,
|
||||
frame: Frame,
|
||||
title: Text,
|
||||
shown: Option<Instant>,
|
||||
/// A `RecipeToast`: the icon is a recipe result.
|
||||
recipe: bool,
|
||||
slide: Slide,
|
||||
/// A `RecipeToast`: the crafting station and result of each display
|
||||
/// unlocked while it lasts (`recipeItems`); empty for an advancement.
|
||||
recipes: Vec<(String, ItemStack)>,
|
||||
/// `RecipeToast.changed` and `lastChanged`.
|
||||
changed: bool,
|
||||
last_changed: i64,
|
||||
}
|
||||
impl Toast {
|
||||
pub(super) fn is_recipe(&self) -> bool {
|
||||
self.recipe
|
||||
}
|
||||
pub(super) fn was_shown(&self) -> bool {
|
||||
self.shown.is_some()
|
||||
}
|
||||
/// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result.
|
||||
pub(super) fn recipe(icon: &str) -> Self {
|
||||
/// `RecipeToast.addOrUpdate` on a new toast.
|
||||
pub(super) fn recipe(items: Vec<(String, ItemStack)>) -> Self {
|
||||
Self {
|
||||
icon: icon.to_owned(),
|
||||
icon: String::new(),
|
||||
frame: Frame::Task,
|
||||
title: Text::literal(""),
|
||||
shown: None,
|
||||
recipe: true,
|
||||
slide: Slide::default(),
|
||||
recipes: items,
|
||||
changed: true,
|
||||
last_changed: 0,
|
||||
}
|
||||
}
|
||||
pub(super) fn is_recipe(&self) -> bool {
|
||||
!self.recipes.is_empty()
|
||||
}
|
||||
/// `RecipeToast.addItem`: more displays on a toast still queued or shown.
|
||||
pub(super) fn add_recipes(&mut self, items: Vec<(String, ItemStack)>) {
|
||||
self.recipes.extend(items);
|
||||
self.changed = true;
|
||||
}
|
||||
/// `Toast.update` with `fullyVisibleForMs`: whether it wants to be shown.
|
||||
fn wants_show(&mut self, fully_for: i64, multiplier: f64) -> bool {
|
||||
let time = 5000.0 * multiplier;
|
||||
if self.recipes.is_empty() {
|
||||
// AdvancementToast.
|
||||
return (fully_for as f64) < time;
|
||||
}
|
||||
if self.changed {
|
||||
self.last_changed = fully_for;
|
||||
self.changed = false;
|
||||
}
|
||||
((fully_for - self.last_changed) as f64) < time
|
||||
}
|
||||
/// `RecipeToast.displayedRecipeIndex`: the displays take turns over the
|
||||
/// toast's display time.
|
||||
fn displayed_recipe(&self, fully_for: i64, multiplier: f64) -> usize {
|
||||
let n = self.recipes.len() as f64;
|
||||
(fully_for as f64 / (5000.0 * multiplier / n).max(1.0) % n) as usize
|
||||
}
|
||||
}
|
||||
/// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms,
|
||||
/// eased by the square, and counts how long it has been fully shown.
|
||||
#[derive(Default)]
|
||||
struct Slide {
|
||||
/// When it first updated; the times below are milliseconds since.
|
||||
origin: Option<Instant>,
|
||||
begun: bool,
|
||||
/// `animationStartTime`.
|
||||
start: i64,
|
||||
/// `becameFullyVisibleAt`.
|
||||
fully_at: i64,
|
||||
show: bool,
|
||||
/// `visiblePortion`: 0 off screen, 1 fully in.
|
||||
portion: f32,
|
||||
/// `fullyVisibleFor`.
|
||||
fully_for: i64,
|
||||
}
|
||||
impl Slide {
|
||||
const MS: i64 = 600;
|
||||
/// `ToastInstance.update` at `now`; `wants_show` is the toast's own
|
||||
/// update. The visibility it switched to (the sound to play), and whether
|
||||
/// it has finished sliding out.
|
||||
fn update(&mut self, now: i64, wants_show: impl FnOnce(i64) -> bool) -> (Option<bool>, bool) {
|
||||
let was = self.show;
|
||||
if !self.begun {
|
||||
self.begun = true;
|
||||
self.start = now;
|
||||
self.show = true;
|
||||
}
|
||||
if self.show && now - self.start <= Self::MS {
|
||||
self.fully_at = now;
|
||||
}
|
||||
self.fully_for = now - self.fully_at;
|
||||
let progress = ((now - self.start) as f32 / Self::MS as f32).clamp(0.0, 1.0);
|
||||
let progress = progress * progress;
|
||||
self.portion = if self.show { progress } else { 1.0 - progress };
|
||||
let wanted = wants_show(self.fully_for);
|
||||
if wanted != self.show {
|
||||
self.start = now - ((1.0 - self.portion) * Self::MS as f32) as i64;
|
||||
self.show = wanted;
|
||||
}
|
||||
let finished = !self.show && now - self.start > Self::MS;
|
||||
((self.show != was).then_some(self.show), finished)
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct AdvState {
|
||||
@@ -430,8 +502,10 @@ impl Game<'_> {
|
||||
icon: d.icon.clone(),
|
||||
frame: d.frame,
|
||||
title: text_of(&d.title),
|
||||
shown: None,
|
||||
recipe: false,
|
||||
slide: Slide::default(),
|
||||
recipes: Vec::new(),
|
||||
changed: false,
|
||||
last_changed: 0,
|
||||
});
|
||||
}
|
||||
if d.announce && self.ui.rules.bool("show_advancement_messages") {
|
||||
@@ -679,45 +753,57 @@ impl Game<'_> {
|
||||
c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to)
|
||||
});
|
||||
}
|
||||
/// `ToastManager` with the `AdvancementToast`.
|
||||
/// `ToastManager` with the `AdvancementToast` and the `RecipeToast`,
|
||||
/// one at a time.
|
||||
pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) {
|
||||
let multiplier = f64::from(self.settings.notification_display_time);
|
||||
let Some(t) = self.adv.toasts.front_mut() else {
|
||||
return;
|
||||
};
|
||||
let shown = *t.shown.get_or_insert_with(Instant::now);
|
||||
let ms = shown.elapsed().as_millis() as f32;
|
||||
// AdvancementToast.DISPLAY_TIME: 5 s, sliding 600 ms in and out.
|
||||
if ms > 5600.0 {
|
||||
let first = t.slide.origin.is_none();
|
||||
let origin = *t.slide.origin.get_or_insert_with(Instant::now);
|
||||
let now = origin.elapsed().as_millis() as i64;
|
||||
let mut slide = std::mem::take(&mut t.slide);
|
||||
let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier));
|
||||
t.slide = slide;
|
||||
if finished {
|
||||
self.adv.toasts.pop_front();
|
||||
return;
|
||||
}
|
||||
let slide = if ms < 600.0 {
|
||||
ms / 600.0
|
||||
} else if ms > 5000.0 {
|
||||
1.0 - (ms - 5000.0) / 600.0
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe);
|
||||
if recipe {
|
||||
// RecipeToast: black description under a purple title.
|
||||
let x = batch.width - 160.0 * t.slide.portion;
|
||||
let fully_for = t.slide.fully_for;
|
||||
let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone());
|
||||
let recipe = t
|
||||
.is_recipe()
|
||||
.then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone());
|
||||
// ToastManager.update: the sound of the new visibility, and a
|
||||
// challenge's own sound as it leaves the queue.
|
||||
if let Some(show) = sound {
|
||||
let event = if show { "ui.toast.in" } else { "ui.toast.out" };
|
||||
self.audio
|
||||
.play(&format!("minecraft:{event}"), None, 1.0, 1.0);
|
||||
}
|
||||
if first && recipe.is_none() && frame == Frame::Challenge {
|
||||
self.audio
|
||||
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
|
||||
}
|
||||
if let Some((station, item)) = recipe {
|
||||
// RecipeToast: black description under a purple title, the
|
||||
// station at 0.6 scale in the corner over the cycling result.
|
||||
let atlas = &self.res.atlas;
|
||||
let x = batch.width - 160.0 * slide;
|
||||
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
|
||||
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
|
||||
let description = self.translate("recipe.toast.description", "Check your recipe book");
|
||||
let atlas = &self.res.atlas;
|
||||
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
|
||||
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
|
||||
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0);
|
||||
let start = batch.vertices.len();
|
||||
self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0);
|
||||
batch.scale_since(start, x, 0.0, 0.6, 0.6);
|
||||
self.draw_item_model(batch, &item, x + 8.0, 8.0);
|
||||
return;
|
||||
}
|
||||
if frame == Frame::Challenge && ms < 50.0 {
|
||||
self.audio
|
||||
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
|
||||
}
|
||||
let atlas = &self.res.atlas;
|
||||
let x = batch.width - 160.0 * slide;
|
||||
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
|
||||
let (key, color) = match frame {
|
||||
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
|
||||
@@ -813,3 +899,94 @@ pub(super) fn text_of(v: &Value) -> Text {
|
||||
Text::empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn recipes(n: usize) -> Toast {
|
||||
Toast::recipe(
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let item = ItemStack::new(&format!("minecraft:item_{i}"), 1);
|
||||
("minecraft:crafting_table".to_owned(), item)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
/// Drives a toast frame by frame (every `step` ms) and returns the slide
|
||||
/// portions at the given times and when it finished.
|
||||
fn run(toast: &mut Toast, step: i64, until: i64, at: &[i64]) -> (Vec<f32>, Option<i64>) {
|
||||
let mut slide = Slide::default();
|
||||
let mut seen = Vec::new();
|
||||
for now in (0..=until).step_by(step as usize) {
|
||||
let (_, finished) = slide.update(now, |f| toast.wants_show(f, 1.0));
|
||||
if finished {
|
||||
return (seen, Some(now));
|
||||
}
|
||||
if at.contains(&now) {
|
||||
seen.push(slide.portion);
|
||||
}
|
||||
}
|
||||
(seen, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toasts_slide_in_squared_and_out_after_five_seconds() {
|
||||
let mut toast = recipes(1);
|
||||
let (portions, finished) = run(&mut toast, 10, 10_000, &[0, 300, 600, 3000]);
|
||||
// (300 / 600)² = 0.25: ToastInstance.calculateVisiblePortion.
|
||||
assert_eq!(portions, [0.0, 0.25, 1.0, 1.0]);
|
||||
// Fully in at 600, shown 5000 ms, out over 600 more.
|
||||
assert!(
|
||||
finished.is_some_and(|t| (6200..=6220).contains(&t)),
|
||||
"{finished:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_update_plays_the_show_sound_and_the_hide_sound_follows() {
|
||||
let mut toast = recipes(1);
|
||||
let mut slide = Slide::default();
|
||||
assert_eq!(slide.update(0, |f| toast.wants_show(f, 1.0)).0, Some(true));
|
||||
assert_eq!(slide.update(100, |f| toast.wants_show(f, 1.0)).0, None);
|
||||
assert_eq!(
|
||||
slide.update(5600, |f| toast.wants_show(f, 1.0)).0,
|
||||
Some(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipe_toasts_cycle_through_their_displays_over_the_display_time() {
|
||||
let toast = recipes(4);
|
||||
let shown: Vec<usize> = [0, 1249, 1250, 2500, 3750, 4999, 5000]
|
||||
.iter()
|
||||
.map(|&t| toast.displayed_recipe(t, 1.0))
|
||||
.collect();
|
||||
assert_eq!(shown, [0, 0, 1, 2, 3, 3, 0]);
|
||||
// notificationDisplayTime doubles each turn.
|
||||
assert_eq!(toast.displayed_recipe(2500, 2.0), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocking_more_recipes_keeps_the_toast_up_five_more_seconds() {
|
||||
let mut toast = recipes(1);
|
||||
let mut slide = Slide::default();
|
||||
let mut finished = None;
|
||||
for now in (0..=20_000).step_by(10) {
|
||||
if now == 4000 {
|
||||
toast.add_recipes(recipes(1).recipes);
|
||||
}
|
||||
if slide.update(now, |f| toast.wants_show(f, 1.0)).1 {
|
||||
finished = Some(now);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(toast.recipes.len(), 2);
|
||||
// lastChanged moved to 3400 ms fully shown: hidden at 8400 + 600.
|
||||
assert!(
|
||||
finished.is_some_and(|t| (9600..=9620).contains(&t)),
|
||||
"{finished:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,11 +485,19 @@ impl Game<'_> {
|
||||
seed,
|
||||
creative,
|
||||
focus,
|
||||
options,
|
||||
} => json!({
|
||||
"mode": "create-world",
|
||||
"tab": (["game", "world", "more"][options.tab.min(2)]),
|
||||
"fields": { "name": name, "seed": seed },
|
||||
"focus": match focus { 0 => "name", 1 => "seed", _ => "none" },
|
||||
"creative": creative,
|
||||
"hardcore": options.hardcore,
|
||||
"difficulty": horizon_client::title::DIFFICULTIES[options.difficulty()],
|
||||
"allow_commands": options.commands(*creative),
|
||||
"superflat": options.flat,
|
||||
"generate_structures": options.structures,
|
||||
"bonus_chest": options.bonus_chest(),
|
||||
}),
|
||||
Mode::Edit {
|
||||
world,
|
||||
@@ -1322,10 +1330,17 @@ impl Game<'_> {
|
||||
let title = self.title.as_mut().ok_or("no title screen")?;
|
||||
if let Some(field) = &field {
|
||||
match &mut title.mode {
|
||||
horizon_client::title::Mode::Create { focus, .. } => {
|
||||
horizon_client::title::Mode::Create { focus, options, .. } => {
|
||||
// Each box is on its own tab.
|
||||
*focus = match field.as_str() {
|
||||
"name" => 0,
|
||||
"seed" => 1,
|
||||
"name" => {
|
||||
options.tab = 0;
|
||||
0
|
||||
}
|
||||
"seed" => {
|
||||
options.tab = 1;
|
||||
1
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"the create-world fields are name and seed, not {other}"
|
||||
|
||||
@@ -565,9 +565,9 @@ impl Game<'_> {
|
||||
held.count -= 1;
|
||||
if held.count == 0 {
|
||||
// The worn piece comes back to the hand.
|
||||
self.inventory[self.selected] = current;
|
||||
*self.held_mut() = current;
|
||||
} else {
|
||||
self.inventory[self.selected] = Some(held);
|
||||
*self.held_mut() = Some(held);
|
||||
if let Some(old) = current
|
||||
&& let Some(rest) = self.give(old)
|
||||
&& let Some(eye) = self.eye_position()
|
||||
|
||||
@@ -666,6 +666,7 @@ impl Game<'_> {
|
||||
if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
|
||||
return false;
|
||||
}
|
||||
self.vehicle_attack_sounds();
|
||||
let b = &mut self.boats[i];
|
||||
b.hurt_dir = -b.hurt_dir;
|
||||
b.hurt_time = 10;
|
||||
|
||||
@@ -59,7 +59,7 @@ impl Game<'_> {
|
||||
pages.push(String::new());
|
||||
}
|
||||
BookScreen::Edit {
|
||||
slot: self.selected,
|
||||
slot: self.held_slot(),
|
||||
pages,
|
||||
page: 0,
|
||||
signing: false,
|
||||
@@ -104,7 +104,7 @@ impl Game<'_> {
|
||||
while pages.len() > 1 && pages.last().is_some_and(String::is_empty) {
|
||||
pages.pop();
|
||||
}
|
||||
if let Some(stack) = self.inventory.get_mut(slot).and_then(Option::as_mut)
|
||||
if let Some(stack) = self.stack_in_mut(slot).as_mut()
|
||||
&& &*stack.item == "minecraft:writable_book"
|
||||
{
|
||||
if sign {
|
||||
|
||||
@@ -488,7 +488,7 @@ impl Game<'_> {
|
||||
let folder = arg(1)?;
|
||||
let seed = words.get(2).map(|s| s.parse::<i64>()).transpose()?;
|
||||
let creative = words.get(3) == Some(&"creative");
|
||||
self.open_world(folder, Some(folder), seed, creative)?;
|
||||
self.open_world(folder, Some(folder), seed, creative, None)?;
|
||||
ok()
|
||||
}
|
||||
"connect" => {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use super::{Dim, Game, view_vector};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
arrows::EntityHit,
|
||||
blocks::Fluid,
|
||||
collisions::SceneCollisions,
|
||||
items::ItemStack,
|
||||
@@ -25,14 +26,16 @@ use horizon_core::{
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The world impact sound after successful arrow damage, including self-shots.
|
||||
fn arrow_impact_sound(
|
||||
random: &mut impl RandomSource,
|
||||
hurt: bool,
|
||||
) -> Option<(&'static str, f32, f32)> {
|
||||
hurt.then(|| {
|
||||
let pitch = 1.2 / (random.next_float() * 0.2 + 0.9);
|
||||
("minecraft:entity.arrow.hit", 1.0, pitch)
|
||||
})
|
||||
/// `AbstractArrow.onHitEntity`'s damage: the crit bonus comes from the
|
||||
/// arrow's own random.
|
||||
fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32 {
|
||||
let mut state = arrow.arrow.take();
|
||||
let damage = match state.as_mut() {
|
||||
Some(a) => arrow.arrow_damage(&mut a.random),
|
||||
None => arrow.arrow_damage(fallback),
|
||||
};
|
||||
arrow.arrow = state;
|
||||
damage
|
||||
}
|
||||
|
||||
/// Mob-system state owned by the game.
|
||||
@@ -1528,20 +1531,8 @@ impl Game<'_> {
|
||||
self.world.random.next_float()
|
||||
};
|
||||
let w = self.mob_world_base(&[]);
|
||||
// Level.isRainingAt: raining, open to the sky (the biome's
|
||||
// precipitation is not checked here).
|
||||
let (raining, world) = (w.raining, w.world);
|
||||
let rain = move |p: BlockPos| raining && world.light(p.x, p.y, p.z) >> 4 == 15;
|
||||
let scene = horizon_client::arrows::ArrowScene {
|
||||
world: w.world,
|
||||
registry: w.registry,
|
||||
facts: w.facts,
|
||||
collision: w.collision,
|
||||
fluids: &self.motion.fluids,
|
||||
raining: &rain,
|
||||
mob_griefing: self.ui.rules.bool("mob_griefing"),
|
||||
tnt_explodes: self.ui.rules.bool("tnt_explodes"),
|
||||
};
|
||||
let rain = self.arrow_rain();
|
||||
let scene = self.arrow_scene(&rain);
|
||||
// Arrows also hit minecarts (VehicleEntity is pickable).
|
||||
let mut arrow_targets = targets.clone();
|
||||
arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds())));
|
||||
@@ -1568,8 +1559,10 @@ impl Game<'_> {
|
||||
&& breezes.contains(&id)
|
||||
{
|
||||
super::wind::reverse(p, jitter);
|
||||
if let Some(a) = p.arrow.as_mut() {
|
||||
a.removed = false;
|
||||
if p.arrow.is_some() {
|
||||
horizon_client::arrows::finish_entity_hit(p, &scene, EntityHit::Deflected);
|
||||
let a = p.arrow.as_mut().expect("an arrow");
|
||||
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
|
||||
}
|
||||
deflections.push([at.x, at.y, at.z]);
|
||||
return true;
|
||||
@@ -1680,7 +1673,53 @@ impl Game<'_> {
|
||||
ArrowEvent::SplashEvent => {
|
||||
self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]);
|
||||
}
|
||||
ArrowEvent::ShootEvent => {}
|
||||
// finish_arrow_hit drops the pickup, which it holds.
|
||||
ArrowEvent::ShootEvent | ArrowEvent::Drop => {}
|
||||
}
|
||||
}
|
||||
/// `Level.isRainingAt` for arrows: raining, open to the sky (the biome's
|
||||
/// precipitation is not checked here).
|
||||
fn arrow_rain(&self) -> impl Fn(BlockPos) -> bool + '_ {
|
||||
let raining = self.world.weather.levels(1.0).0 > 0.2;
|
||||
move |p: BlockPos| raining && self.world.light(p.x, p.y, p.z) >> 4 == 15
|
||||
}
|
||||
/// The level as arrows see it.
|
||||
fn arrow_scene<'s>(
|
||||
&'s self,
|
||||
rain: &'s dyn Fn(BlockPos) -> bool,
|
||||
) -> horizon_client::arrows::ArrowScene<'s, 's> {
|
||||
horizon_client::arrows::ArrowScene {
|
||||
world: &self.world,
|
||||
registry: self.res.assets.registry,
|
||||
facts: &self.res.facts,
|
||||
collision: self.collision,
|
||||
fluids: &self.motion.fluids,
|
||||
raining: rain,
|
||||
mob_griefing: self.ui.rules.bool("mob_griefing"),
|
||||
tnt_explodes: self.ui.rules.bool("tnt_explodes"),
|
||||
}
|
||||
}
|
||||
/// The rest of the tick of an arrow that hit an entity
|
||||
/// (`arrows::finish_entity_hit`): its sounds and drop, and back among the
|
||||
/// projectiles if it flies on.
|
||||
fn finish_arrow_hit(&mut self, mut arrow: Projectile, outcome: EntityHit) {
|
||||
let keep = {
|
||||
let rain = self.arrow_rain();
|
||||
horizon_client::arrows::finish_entity_hit(&mut arrow, &self.arrow_scene(&rain), outcome)
|
||||
};
|
||||
let Some(a) = arrow.arrow.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let (events, item) = (std::mem::take(&mut a.events), a.pickup_item.clone());
|
||||
for event in events {
|
||||
if event == horizon_client::arrows::ArrowEvent::Drop {
|
||||
self.spawn_at_location(arrow.position, f64::from(0.1f32), item.clone());
|
||||
} else {
|
||||
self.arrow_event(arrow.position, event);
|
||||
}
|
||||
}
|
||||
if keep {
|
||||
self.creatures.projectiles.push(arrow);
|
||||
}
|
||||
}
|
||||
fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
|
||||
@@ -1720,14 +1759,12 @@ impl Game<'_> {
|
||||
&& let Some(i) = self.carts.iter().position(|c| c.id == id)
|
||||
{
|
||||
// AbstractArrow.onHitEntity on a minecart.
|
||||
let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage;
|
||||
let mut arrow = p.clone();
|
||||
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
|
||||
let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire());
|
||||
let creative = p.owner == Some(Who::Player) && self.creative;
|
||||
self.arrow_hits_cart(i, amount, p.velocity, burning, creative);
|
||||
if let Some((sound, volume, pitch)) = arrow_impact_sound(&mut self.world.random, true) {
|
||||
self.audio
|
||||
.play(sound, Some([at.x, at.y, at.z]), volume, pitch);
|
||||
}
|
||||
self.finish_arrow_hit(arrow, EntityHit::Hurt);
|
||||
return Ok(());
|
||||
}
|
||||
let atp = [at.x, at.y, at.z];
|
||||
@@ -1747,16 +1784,9 @@ impl Game<'_> {
|
||||
};
|
||||
match (&p.kind, hit) {
|
||||
(ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => {
|
||||
let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage;
|
||||
// Punch pushes along the flight, Flame burns for five seconds.
|
||||
let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt();
|
||||
if p.bonus.punch > 0 && flight > 1e-6 {
|
||||
let k = f64::from(p.bonus.punch) * 0.6 / flight;
|
||||
self.handle_mob_events(vec![MobEvent::Push {
|
||||
target: who,
|
||||
velocity: [p.velocity.x * k, 0.1, p.velocity.z * k],
|
||||
}])?;
|
||||
}
|
||||
let mut arrow = p.clone();
|
||||
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
|
||||
let player_fire = self.player.as_ref().map(|pl| pl.fire_ticks);
|
||||
// AbstractArrow.onHitEntity: a burning arrow sets its target alight.
|
||||
if p.arrow.as_ref().is_some_and(|a| a.on_fire()) {
|
||||
self.handle_mob_events(vec![MobEvent::Ignite {
|
||||
@@ -1788,10 +1818,27 @@ impl Game<'_> {
|
||||
hurt
|
||||
}
|
||||
};
|
||||
if let Some((sound, volume, pitch)) =
|
||||
arrow_impact_sound(&mut self.world.random, hurt)
|
||||
{
|
||||
self.audio.play(sound, Some(atp), volume, pitch);
|
||||
// doKnockback: Punch pushes along the flight.
|
||||
let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt();
|
||||
if hurt && p.bonus.punch > 0 && flight > 1e-6 {
|
||||
let k = f64::from(p.bonus.punch) * 0.6 / flight;
|
||||
self.handle_mob_events(vec![MobEvent::Push {
|
||||
target: who,
|
||||
velocity: [p.velocity.x * k, 0.1, p.velocity.z * k],
|
||||
}])?;
|
||||
}
|
||||
match (hurt, who) {
|
||||
(true, _) => self.finish_arrow_hit(arrow, EntityHit::Hurt),
|
||||
// What the player took no damage from (a raised shield)
|
||||
// keeps its fire as it was and turns the arrow back.
|
||||
(false, Who::Player) => {
|
||||
if let (Some(pl), Some(ticks)) = (self.player.as_mut(), player_fire) {
|
||||
pl.set_remaining_fire_ticks(ticks);
|
||||
}
|
||||
self.finish_arrow_hit(arrow, EntityHit::Refused);
|
||||
}
|
||||
// Mobs' refusals don't follow hurtServer yet: the arrow is gone.
|
||||
(false, Who::Mob(_)) => {}
|
||||
}
|
||||
}
|
||||
// AbstractArrow.onHitBlock plays its sound itself (ArrowEvent).
|
||||
@@ -2569,11 +2616,11 @@ impl Game<'_> {
|
||||
self.audio.play(sound, Some(eye), 0.5, pitch);
|
||||
self.swing_arm();
|
||||
if !self.creative
|
||||
&& let Some(s) = self.inventory[self.selected].as_mut()
|
||||
&& let Some(s) = self.held_mut().as_mut()
|
||||
{
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.inventory[self.selected] = None;
|
||||
*self.held_mut() = None;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
@@ -2615,11 +2662,11 @@ impl Game<'_> {
|
||||
}
|
||||
self.swing_arm();
|
||||
if !self.creative
|
||||
&& let Some(s) = self.inventory[self.selected].as_mut()
|
||||
&& let Some(s) = self.held_mut().as_mut()
|
||||
{
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.inventory[self.selected] = None;
|
||||
*self.held_mut() = None;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
@@ -2945,32 +2992,3 @@ impl Game<'_> {
|
||||
let _ = self.spawn_mob("minecraft:zombified_piglin", at, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::LegacyRandom;
|
||||
|
||||
#[test]
|
||||
fn arrow_impact_uses_world_sound_volume_and_seeded_pitch() {
|
||||
let mut random = LegacyRandom::new(0);
|
||||
assert_eq!(
|
||||
arrow_impact_sound(&mut random, true),
|
||||
Some((
|
||||
"minecraft:entity.arrow.hit",
|
||||
1.0,
|
||||
f32::from_bits(0x3f92d167)
|
||||
))
|
||||
);
|
||||
let mut expected = LegacyRandom::new(0);
|
||||
expected.next_float();
|
||||
assert_eq!(random.next_float(), expected.next_float());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_arrow_damage_is_silent_without_drawing_pitch() {
|
||||
let mut random = LegacyRandom::new(0);
|
||||
assert_eq!(arrow_impact_sound(&mut random, false), None);
|
||||
assert_eq!(random.next_float(), LegacyRandom::new(0).next_float());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Crossbows (`CrossbowItem`): charging with the start/middle/end sounds
|
||||
//! (Quick Charge), loading arrows into `charged_projectiles` (Multishot
|
||||
//! loads three), and shooting critical arrows at power 3.15 with the fanned
|
||||
//! Multishot angles and their shot pitches.
|
||||
use super::{Game, view_vector};
|
||||
//! (Quick Charge), loading arrows or a held firework rocket into
|
||||
//! `charged_projectiles` (Multishot loads three), and shooting critical
|
||||
//! arrows at power 3.15, or rockets at 1.6 for three durability, with the
|
||||
//! fanned Multishot angles and their shot pitches. `Player.getProjectile`
|
||||
//! finds the ammo for bows and crossbows.
|
||||
use super::{Game, shield::OFFHAND_SLOT, view_vector};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
mobs::Who,
|
||||
@@ -11,6 +13,31 @@ use horizon_client::{
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
const CROSSBOW: &str = "minecraft:crossbow";
|
||||
const FIREWORK_ROCKET: &str = "minecraft:firework_rocket";
|
||||
|
||||
/// `ProjectileWeaponItem.ARROW_ONLY`, for the arrows Horizon shoots.
|
||||
fn is_arrow(stack: &ItemStack) -> bool {
|
||||
&*stack.item == "minecraft:arrow"
|
||||
}
|
||||
|
||||
/// `Player.getProjectile`: what `weapon` supports in the off hand, then in
|
||||
/// the main hand (`getHeldProjectile`; crossbows also take firework rockets
|
||||
/// there), else the first arrows in the inventory. The slot of the stack.
|
||||
fn projectile_slot(
|
||||
weapon: &str,
|
||||
hands: [(usize, Option<&ItemStack>); 2],
|
||||
inventory: &[Option<ItemStack>],
|
||||
) -> Option<usize> {
|
||||
let held = |s: &ItemStack| is_arrow(s) || weapon == CROSSBOW && &*s.item == FIREWORK_ROCKET;
|
||||
hands
|
||||
.into_iter()
|
||||
.find_map(|(slot, s)| s.is_some_and(held).then_some(slot))
|
||||
.or_else(|| {
|
||||
inventory
|
||||
.iter()
|
||||
.position(|s| s.as_ref().is_some_and(is_arrow))
|
||||
})
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn charge_ticks(stack: &ItemStack) -> u32 {
|
||||
@@ -42,10 +69,10 @@ impl Game<'_> {
|
||||
],
|
||||
}
|
||||
}
|
||||
pub(super) fn arrow_slot(&self) -> Option<usize> {
|
||||
self.inventory
|
||||
.iter()
|
||||
.position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow"))
|
||||
/// `Player.getProjectile` for `weapon` (`projectile_slot`).
|
||||
pub(super) fn projectile_slot(&self, weapon: &str) -> Option<usize> {
|
||||
let hands = [OFFHAND_SLOT, self.selected].map(|slot| (slot, self.stack_in(slot)));
|
||||
projectile_slot(weapon, hands, &self.inventory)
|
||||
}
|
||||
/// `CrossbowItem.use`: shoot when charged, else start charging.
|
||||
pub(super) fn use_crossbow(&mut self, stack: &ItemStack) -> bool {
|
||||
@@ -58,8 +85,10 @@ impl Game<'_> {
|
||||
}
|
||||
if stack.data().is_some_and(|d| !d.charged.is_empty()) {
|
||||
self.shoot_crossbow();
|
||||
} else if (self.arrow_slot().is_some() || self.creative) && self.using.is_none() {
|
||||
self.using = Some((self.selected, 0));
|
||||
} else if (self.projectile_slot(CROSSBOW).is_some() || self.creative)
|
||||
&& self.using.is_none()
|
||||
{
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -88,16 +117,17 @@ impl Game<'_> {
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let slot_ammo = self.arrow_slot();
|
||||
let slot_ammo = self.projectile_slot(CROSSBOW);
|
||||
let ammo = slot_ammo
|
||||
.and_then(|i| self.inventory[i].clone())
|
||||
.and_then(|i| self.stack_in(i).cloned())
|
||||
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
|
||||
if !self.creative {
|
||||
let Some(i) = slot_ammo else { return };
|
||||
if let Some(s) = self.inventory[i].as_mut() {
|
||||
let cell = self.stack_in_mut(i);
|
||||
if let Some(s) = cell.as_mut() {
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.inventory[i] = None;
|
||||
*cell = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,7 +135,7 @@ impl Game<'_> {
|
||||
let drawn = (0..shots)
|
||||
.map(|i| horizon_client::arrows::drawn_ammo(&ammo, self.creative || i > 0))
|
||||
.collect();
|
||||
if let Some(bow) = self.inventory[slot].as_mut() {
|
||||
if let Some(bow) = self.stack_in_mut(slot).as_mut() {
|
||||
bow.data_mut().charged = drawn;
|
||||
}
|
||||
let pitch = 1.0 / (self.world.random.next_float() * 0.5 + 1.0) + 0.2;
|
||||
@@ -117,12 +147,18 @@ impl Game<'_> {
|
||||
let Some(eye) = self.eye_position() else {
|
||||
return;
|
||||
};
|
||||
let Some(bow) = self.inventory[self.selected].as_mut() else {
|
||||
let Some(bow) = self.held_mut().as_mut() else {
|
||||
return;
|
||||
};
|
||||
let charged = std::mem::take(&mut bow.data_mut().charged);
|
||||
bow.tidy();
|
||||
let count = charged.len();
|
||||
// getShootingPower: a rocket among them slows every shot.
|
||||
let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) {
|
||||
1.6
|
||||
} else {
|
||||
3.15
|
||||
};
|
||||
// ProjectileWeaponItem.shoot: angles fanned 10 degrees apart.
|
||||
let spread = if count > 1 { 10.0 } else { 0.0 };
|
||||
let view = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
|
||||
@@ -140,22 +176,38 @@ impl Game<'_> {
|
||||
};
|
||||
let dir =
|
||||
glam::DQuat::from_axis_angle(up.normalize_or_zero(), angle.to_radians()) * view;
|
||||
let kind = ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: true,
|
||||
effect: None,
|
||||
};
|
||||
let mut arrow = Projectile::new(
|
||||
kind,
|
||||
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
|
||||
Some(Who::Player),
|
||||
);
|
||||
if let Some(a) = arrow.arrow.as_mut() {
|
||||
a.set_item(ammo);
|
||||
a.set_owner(Some(Who::Player));
|
||||
// createProjectile: a rocket shot at an angle from 0.15 under the
|
||||
// eyes, spread by its own random; three durability.
|
||||
let rocket = &*ammo.item == FIREWORK_ROCKET;
|
||||
if rocket {
|
||||
let at = Vec3::new(eye[0], eye[1] - f64::from(0.15f32), eye[2]);
|
||||
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
|
||||
shot.shoot(
|
||||
&mut super::dispenser::entity_random(),
|
||||
dir.to_array(),
|
||||
power,
|
||||
1.0,
|
||||
);
|
||||
self.launch_angled_rocket(at, shot.velocity, ammo);
|
||||
}
|
||||
if !rocket {
|
||||
let kind = ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: true,
|
||||
effect: None,
|
||||
};
|
||||
let mut arrow = Projectile::new(
|
||||
kind,
|
||||
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
|
||||
Some(Who::Player),
|
||||
);
|
||||
if let Some(a) = arrow.arrow.as_mut() {
|
||||
a.set_item(ammo);
|
||||
a.set_owner(Some(Who::Player));
|
||||
}
|
||||
arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
}
|
||||
arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
self.player_projectile_shot();
|
||||
let pitch = if index == 0 {
|
||||
1.0
|
||||
@@ -165,7 +217,43 @@ impl Game<'_> {
|
||||
};
|
||||
self.audio
|
||||
.play("minecraft:item.crossbow.shoot", Some(eye), 1.0, pitch);
|
||||
self.damage_held(1);
|
||||
self.damage_held(if rocket { 3 } else { 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_projectiles_come_before_the_inventory() {
|
||||
let stack = |item: &str| Some(ItemStack::new(item, 1));
|
||||
let (crossbow, rocket, arrow) = (
|
||||
stack(CROSSBOW),
|
||||
stack(FIREWORK_ROCKET),
|
||||
stack("minecraft:arrow"),
|
||||
);
|
||||
let mut inventory = vec![None; 36];
|
||||
inventory[5] = arrow.clone();
|
||||
// The weapon in hotbar slot 0, `off` in the off hand.
|
||||
let slot = |weapon, off: &Option<ItemStack>, inventory: &[Option<ItemStack>]| {
|
||||
let hands = [(OFFHAND_SLOT, off.as_ref()), (0, crossbow.as_ref())];
|
||||
projectile_slot(weapon, hands, inventory)
|
||||
};
|
||||
// The off hand's rocket loads a crossbow; a bow only takes arrows.
|
||||
assert_eq!(slot(CROSSBOW, &rocket, &inventory), Some(OFFHAND_SLOT));
|
||||
assert_eq!(slot("minecraft:bow", &rocket, &inventory), Some(5));
|
||||
assert_eq!(
|
||||
slot("minecraft:bow", &arrow, &inventory),
|
||||
Some(OFFHAND_SLOT)
|
||||
);
|
||||
assert_eq!(slot(CROSSBOW, &None, &inventory), Some(5));
|
||||
// A rocket in the inventory is not ammo.
|
||||
inventory[5] = rocket.clone();
|
||||
assert_eq!(slot(CROSSBOW, &None, &inventory), None);
|
||||
// The main hand's rocket, with the crossbow in the off hand.
|
||||
let hands = [(OFFHAND_SLOT, crossbow.as_ref()), (3, rocket.as_ref())];
|
||||
assert_eq!(projectile_slot(CROSSBOW, hands, &inventory), Some(3));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `Util.getMillis` (positive: KeyboardHandler treats 0 as unset).
|
||||
fn debug_millis(&self) -> i64 {
|
||||
pub(super) fn debug_millis(&self) -> i64 {
|
||||
self.started.elapsed().as_millis() as i64 + 1_000_000
|
||||
}
|
||||
/// `KeyboardHandler.tick`: the debug crash countdown.
|
||||
@@ -180,6 +180,79 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The network charts' samples each tick: `PingDebugMonitor.tick` while
|
||||
/// they show, `BandwidthDebugMonitor.tick` always.
|
||||
pub(super) fn tick_debug_charts(&mut self) {
|
||||
let shown = self.debug && self.debug_charts.network;
|
||||
let Some(r) = &self.remote else {
|
||||
// The integrated server answers within the tick.
|
||||
if shown {
|
||||
self.debug_charts.ping.log(0);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let received = r
|
||||
.session
|
||||
.counters
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed));
|
||||
if let Some(total) = received {
|
||||
self.debug_charts.log_bandwidth(total);
|
||||
}
|
||||
if shown {
|
||||
use horizon_protocol::packets::{play::Serverbound, status::Ping};
|
||||
let time = self.debug_millis();
|
||||
self.send(Serverbound::PingRequest(Ping { time }));
|
||||
}
|
||||
}
|
||||
/// The overlay's chart lines (`DebugScreenOverlay`'s "Debug charts").
|
||||
pub(super) fn debug_chart_lines(&self) -> [String; 3] {
|
||||
let keys = &self.settings.keys;
|
||||
let modifier = keys.get("key.debug.modifier");
|
||||
let key = |mapping: &str| {
|
||||
let prefix = if modifier == "key.keyboard.unknown" {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{}+", keybinds::display_name(modifier).plain())
|
||||
};
|
||||
format!(
|
||||
"[{prefix}{}]",
|
||||
keybinds::display_name(keys.get(mapping)).plain()
|
||||
)
|
||||
};
|
||||
let chart = |mapping: &str, name: &str, on: bool| {
|
||||
format!(
|
||||
"{} {name} {}",
|
||||
key(mapping),
|
||||
if on { "visible" } else { "hidden" }
|
||||
)
|
||||
};
|
||||
let remote = self.remote.is_some();
|
||||
let c = &self.debug_charts;
|
||||
[
|
||||
format!(
|
||||
"Debug charts: {}; {};",
|
||||
chart("key.debug.profilingChart", "Profiler", false),
|
||||
chart(
|
||||
"key.debug.fpsCharts",
|
||||
if remote { "fps" } else { "fps + tps" },
|
||||
c.fps
|
||||
),
|
||||
),
|
||||
format!(
|
||||
"{}; {}",
|
||||
chart(
|
||||
"key.debug.networkCharts",
|
||||
if remote { "Bandwidth + Ping" } else { "Ping" },
|
||||
c.network
|
||||
),
|
||||
chart("key.debug.lightmapTexture", "Lightmap", c.lightmap),
|
||||
),
|
||||
format!("To edit: press {}", key("key.debug.debugOptions")),
|
||||
]
|
||||
}
|
||||
/// `KeyMapping.getTranslatedKeyMessage`.
|
||||
fn key_text(&self, mapping: &str) -> Text {
|
||||
keybinds::display_name(self.settings.keys.get(mapping))
|
||||
@@ -339,16 +412,25 @@ impl Game<'_> {
|
||||
});
|
||||
true
|
||||
}
|
||||
DebugAction::FpsCharts => {
|
||||
self.debug_charts.toggle_fps(&mut self.debug);
|
||||
true
|
||||
}
|
||||
DebugAction::NetworkCharts => {
|
||||
self.debug_charts.toggle_network(&mut self.debug);
|
||||
true
|
||||
}
|
||||
DebugAction::LightmapTexture => {
|
||||
self.debug_charts.toggle_lightmap(&mut self.debug);
|
||||
true
|
||||
}
|
||||
// Screens and overlays Horizon does not draw yet (the debug
|
||||
// options screen, the profiler and its charts, the lightmap, the
|
||||
// texture dump): the keys are used up as in vanilla.
|
||||
// options screen, the profiler and its chart, the texture dump):
|
||||
// the keys are used up as in vanilla.
|
||||
DebugAction::DebugOptions
|
||||
| DebugAction::DumpDynamicTextures
|
||||
| DebugAction::Profiling
|
||||
| DebugAction::ProfilingChart
|
||||
| DebugAction::FpsCharts
|
||||
| DebugAction::NetworkCharts
|
||||
| DebugAction::LightmapTexture => true,
|
||||
| DebugAction::ProfilingChart => true,
|
||||
DebugAction::ShowHitboxes
|
||||
| DebugAction::ShowChunkBorders
|
||||
| DebugAction::SwitchGameMode
|
||||
|
||||
@@ -372,7 +372,13 @@ impl Game<'_> {
|
||||
let world_dir = std::env::current_dir()?.join(&universe).join(&level_name);
|
||||
let folder = world_dir.to_string_lossy().into_owned();
|
||||
let new_world = !world_dir.join("level.dat").exists();
|
||||
self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?;
|
||||
self.open_world(
|
||||
&folder,
|
||||
Some(&level_name),
|
||||
Some(props.seed),
|
||||
game_mode == 1,
|
||||
None,
|
||||
)?;
|
||||
if new_world {
|
||||
self.level.hardcore = props.hardcore;
|
||||
}
|
||||
|
||||
@@ -514,9 +514,15 @@ impl Game<'_> {
|
||||
}
|
||||
self.using = None;
|
||||
self.inventory[self.selected] = stack.clone();
|
||||
let used_before = stack
|
||||
.as_ref()
|
||||
.map_or(0, |s| self.stats.get("used", &s.item));
|
||||
self.offhand = parse_stack(op["offhand"].as_str().unwrap_or("-"))?;
|
||||
// The used statistic of each item held, once.
|
||||
let mut items: Vec<_> = [stack.as_ref(), self.offhand.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|s| s.item.clone())
|
||||
.collect();
|
||||
items.dedup();
|
||||
let used_before: Vec<_> = items.iter().map(|i| self.stats.get("used", i)).collect();
|
||||
self.forced_hit = Some(super::Hit {
|
||||
pos: [pos.x, pos.y, pos.z],
|
||||
face: [0, 1, 0],
|
||||
@@ -542,10 +548,10 @@ impl Game<'_> {
|
||||
out.push(format!("msg {key}"));
|
||||
}
|
||||
}
|
||||
if let Some(s) = &stack {
|
||||
let used = self.stats.get("used", &s.item) - used_before;
|
||||
for (item, before) in items.iter().zip(used_before) {
|
||||
let used = self.stats.get("used", item) - before;
|
||||
if used != 0 {
|
||||
out.push(format!("stat {} minecraft:used {used}", s.item));
|
||||
out.push(format!("stat {item} minecraft:used {used}"));
|
||||
}
|
||||
}
|
||||
let using = self
|
||||
@@ -553,8 +559,9 @@ impl Game<'_> {
|
||||
.and_then(|(slot, _)| self.stack_in(slot))
|
||||
.map_or("-".to_owned(), |s| s.item.to_string());
|
||||
out.push(format!(
|
||||
"held {} using {using}",
|
||||
canon_stack(self.inventory[self.selected].as_ref())
|
||||
"held {} offhand {} using {using}",
|
||||
canon_stack(self.inventory[self.selected].as_ref()),
|
||||
canon_stack(self.offhand.as_ref())
|
||||
));
|
||||
out.push(match self.respawn_config {
|
||||
Some(c) => format!(
|
||||
@@ -568,6 +575,7 @@ impl Game<'_> {
|
||||
});
|
||||
self.player = None;
|
||||
self.using = None;
|
||||
self.offhand = None;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -950,7 +950,7 @@ impl Game<'_> {
|
||||
"minecraft:firework_rocket" => {
|
||||
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
|
||||
shot.shoot(&mut own, dir, power, uncertainty);
|
||||
self.launch_dispensed_rocket(at, shot.velocity, &one);
|
||||
self.launch_angled_rocket(at, shot.velocity, &one);
|
||||
}
|
||||
_ => {
|
||||
let kind = match item.as_str() {
|
||||
|
||||
@@ -85,8 +85,9 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// `FireworkRocketItem.asProjectile` shot out of a dispenser.
|
||||
pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) {
|
||||
/// A rocket shot at an angle (`DATA_SHOT_AT_ANGLE`): out of a dispenser
|
||||
/// (`FireworkRocketItem.asProjectile`) or a crossbow.
|
||||
pub(super) fn launch_angled_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) {
|
||||
let mut rocket = self.new_rocket(at, stack, false);
|
||||
rocket.velocity = velocity;
|
||||
rocket.angled = true;
|
||||
|
||||
@@ -146,7 +146,7 @@ impl Game<'_> {
|
||||
/// `SpyglassItem.use`: start scoping.
|
||||
pub(super) fn use_spyglass(&mut self) {
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.selected, 0));
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
let at = self.eye_position();
|
||||
self.audio.play("minecraft:item.spyglass.use", at, 1.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -42,9 +42,9 @@ impl Game<'_> {
|
||||
self.swings_started += 1;
|
||||
}
|
||||
}
|
||||
/// `swing(InteractionHand.MAIN_HAND)` with the default animation.
|
||||
/// `swing(hand)` for the hand that acts, with the default animation.
|
||||
pub(super) fn swing_arm(&mut self) {
|
||||
self.swing_hand(Hand::Main, SwingAnimation::DEFAULT);
|
||||
self.swing_hand(self.hand, SwingAnimation::DEFAULT);
|
||||
}
|
||||
/// `Player.resetAttackStrengthTicker`.
|
||||
pub(super) fn reset_attack_strength(&mut self) {
|
||||
@@ -166,18 +166,23 @@ impl Game<'_> {
|
||||
if self.clicks.destroying.active || self.hands_busy() {
|
||||
return Ok(());
|
||||
}
|
||||
let before = self.held().cloned();
|
||||
let before = [self.stack_in(self.selected).cloned(), self.offhand.clone()];
|
||||
let swings = self.swings_started;
|
||||
let using = self.using.is_some();
|
||||
self.use_item()?;
|
||||
let Some(hand) = self.use_item()? else {
|
||||
return Ok(());
|
||||
};
|
||||
let (before, after) = match hand {
|
||||
Hand::Main => (&before[0], self.stack_in(self.selected).cloned()),
|
||||
Hand::Off => (&before[1], self.offhand.clone()),
|
||||
};
|
||||
let swung = self.swings_started != swings;
|
||||
let after = self.held().cloned();
|
||||
let spent = match (&before, &after) {
|
||||
let spent = match (before, &after) {
|
||||
(Some(a), Some(b)) => a.count != b.count || a.item != b.item || self.creative,
|
||||
_ => false,
|
||||
};
|
||||
if (swung && spent) || (!using && self.using.is_some() && after.is_some()) {
|
||||
self.heights.item_used(Hand::Main);
|
||||
self.heights.item_used(hand);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -272,6 +277,22 @@ impl Game<'_> {
|
||||
.and_then(|h| self.res.items.get(&h.item))
|
||||
.map_or(0.0, |i| f64::from(i.attack_speed))
|
||||
}
|
||||
/// `evaluateWhichHandsToRender`: which of the main and off hand show.
|
||||
pub(super) fn hands_to_render(&self) -> [bool; 2] {
|
||||
let held = |slot| {
|
||||
self.stack_in(slot)
|
||||
.map(|s: &ItemStack| (&*s.item, s.data().is_some_and(|d| !d.charged.is_empty())))
|
||||
};
|
||||
let using = self.used_hand().zip(
|
||||
self.using
|
||||
.and_then(|(slot, _)| self.stack_in(slot))
|
||||
.map(|s| &*s.item),
|
||||
);
|
||||
horizon_client::first_person::hands_to_render(
|
||||
[held(self.selected), held(super::shield::OFFHAND_SLOT)],
|
||||
using,
|
||||
)
|
||||
}
|
||||
/// The visible main- and off-hand items.
|
||||
pub(super) fn visible_hand_items(&self) -> [Option<ItemStack>; 2] {
|
||||
[
|
||||
|
||||
@@ -482,7 +482,7 @@ impl Game<'_> {
|
||||
if self.creative {
|
||||
self.give_or_drop_stack(filled);
|
||||
} else if stack.count == 1 {
|
||||
self.inventory[self.selected] = Some(filled);
|
||||
*self.held_mut() = Some(filled);
|
||||
} else {
|
||||
self.consume_held();
|
||||
self.give_or_drop_stack(filled);
|
||||
|
||||
@@ -13,6 +13,7 @@ use horizon_client::{
|
||||
mesher::Vertex,
|
||||
mobs::{Part, anim::Poses},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
sound_engine::{CartSound, SoundEngine, SoundInstance, Sounds},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
@@ -786,6 +787,42 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ClientPacketListener.postAddEntitySoundInstance` for the carts that
|
||||
/// joined the level since the last tick, and `LocalPlayer.startRiding`'s
|
||||
/// two inside sounds when the player got in one; then what the sound
|
||||
/// instances read this tick (the ridden cart and every cart).
|
||||
pub(super) fn start_cart_sounds(&mut self) -> (Option<u32>, Vec<CartSound>) {
|
||||
let carts: Vec<CartSound> = self
|
||||
.carts
|
||||
.iter()
|
||||
.map(|c| CartSound {
|
||||
id: c.id,
|
||||
position: [c.position.x, c.position.y, c.position.z],
|
||||
// Vec3.horizontalDistance.
|
||||
speed: (c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z).sqrt(),
|
||||
})
|
||||
.collect();
|
||||
self.cart_sounds
|
||||
.retain(|id| carts.iter().any(|c| c.id == *id));
|
||||
for cart in &carts {
|
||||
if self.cart_sounds.insert(cart.id) {
|
||||
let instance = SoundInstance::minecart(cart, SoundEngine::unseeded());
|
||||
self.audio.play_instance(instance, false);
|
||||
}
|
||||
}
|
||||
let vehicle = self.riding.filter(|id| carts.iter().any(|c| c.id == *id));
|
||||
if vehicle != self.riding_cart_sounds
|
||||
&& let Some(cart) = carts.iter().find(|c| Some(c.id) == vehicle)
|
||||
{
|
||||
for underwater in [true, false] {
|
||||
let instance =
|
||||
SoundInstance::riding_minecart(cart, underwater, SoundEngine::unseeded());
|
||||
self.audio.play_instance(instance, false);
|
||||
}
|
||||
}
|
||||
self.riding_cart_sounds = vehicle;
|
||||
(vehicle, carts)
|
||||
}
|
||||
/// The rider's tick: the cart moves with the rider's input as its push.
|
||||
pub(super) fn tick_cart_riding(&mut self, keys: Keys) -> bool {
|
||||
let Some(i) = self.carts.iter().position(|c| Some(c.id) == self.riding) else {
|
||||
@@ -1044,6 +1081,7 @@ impl Game<'_> {
|
||||
let burning = self
|
||||
.held()
|
||||
.is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0);
|
||||
self.vehicle_attack_sounds();
|
||||
self.hurt_cart(i, damage, self.creative, burning);
|
||||
self.swing_arm();
|
||||
true
|
||||
|
||||
@@ -28,9 +28,13 @@ impl Game<'_> {
|
||||
}
|
||||
self.sound_paused = self.pause;
|
||||
}
|
||||
let (vehicle, carts) = self.start_cart_sounds();
|
||||
let ctx = TickContext {
|
||||
player_underwater: self.ambience.was_underwater(),
|
||||
player_removed: self.player.is_none(),
|
||||
vehicle,
|
||||
carts,
|
||||
frozen: !self.clock.runs_normally(),
|
||||
};
|
||||
self.audio.tick(self.pause, &ctx);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ use std::collections::HashMap;
|
||||
/// The game level as natural spawning reads it.
|
||||
pub(super) struct GameLevel<'g, 'a> {
|
||||
pub(super) game: &'g Game<'a>,
|
||||
w: MobWorld<'g>,
|
||||
pub(super) w: MobWorld<'g>,
|
||||
/// Boxes of the mobs this pass created, not yet in the game's list.
|
||||
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
|
||||
/// The types and boxes of what a spawner created this tick.
|
||||
|
||||
@@ -89,7 +89,7 @@ impl Game<'_> {
|
||||
match &*stack.item {
|
||||
"minecraft:potion" | "minecraft:ominous_bottle" => {
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.selected, 0));
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
@@ -177,8 +177,8 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.consume_held();
|
||||
if self.inventory[self.selected].is_none() {
|
||||
self.inventory[self.selected] = Some(filled);
|
||||
if self.held().is_none() {
|
||||
*self.held_mut() = Some(filled);
|
||||
} else if let Some(rest) = self.give(filled)
|
||||
&& let Some(eye) = self.eye_position()
|
||||
{
|
||||
@@ -218,15 +218,15 @@ impl Game<'_> {
|
||||
self.apply_effect_action(a);
|
||||
}
|
||||
if !self.creative {
|
||||
if let Some(s) = self.inventory[slot].as_mut() {
|
||||
if let Some(s) = self.stack_in_mut(slot).as_mut() {
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.inventory[slot] = None;
|
||||
*self.stack_in_mut(slot) = None;
|
||||
}
|
||||
}
|
||||
let bottle = ItemStack::new("minecraft:glass_bottle", 1);
|
||||
if self.inventory[slot].is_none() {
|
||||
self.inventory[slot] = Some(bottle);
|
||||
if self.stack_in(slot).is_none() {
|
||||
*self.stack_in_mut(slot) = Some(bottle);
|
||||
} else if let Some(rest) = self.give(bottle) {
|
||||
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let held = &mut self.inventory[self.selected];
|
||||
let held = self.held_mut();
|
||||
let last = held.as_ref().is_none_or(|s| s.count <= 1);
|
||||
if last {
|
||||
*held = Some(filled);
|
||||
|
||||
@@ -1224,11 +1224,11 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:item.ominous_bottle.dispose", Some(eye), 1.0, 1.0);
|
||||
if !self.creative
|
||||
&& let Some(s) = self.inventory[slot].as_mut()
|
||||
&& let Some(s) = self.stack_in_mut(slot).as_mut()
|
||||
{
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.inventory[slot] = None;
|
||||
*self.stack_in_mut(slot) = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,28 +197,59 @@ impl Game<'_> {
|
||||
search.reset_blink();
|
||||
}
|
||||
|
||||
/// The toast for newly unlocked recipes: one for a burst of unlocks.
|
||||
/// `RecipeToast.addOrUpdate` for each display of the recipes just
|
||||
/// unlocked: its crafting station and result join the toast still
|
||||
/// queued or shown, or a new one.
|
||||
pub(super) fn recipe_toast(&mut self, recipes: &[String]) {
|
||||
if recipes.is_empty() || self.adv.quiet {
|
||||
return;
|
||||
}
|
||||
self.ensure_book();
|
||||
let icon = self
|
||||
.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.and_then(|b| recipes.iter().find_map(|id| b.entry(id)))
|
||||
.map(|e| e.result.item.to_string());
|
||||
let Some(icon) = icon else { return };
|
||||
let fresh = self
|
||||
.adv
|
||||
.toasts
|
||||
.back()
|
||||
.is_some_and(|t| t.is_recipe() && !t.was_shown());
|
||||
if !fresh {
|
||||
self.adv
|
||||
let index = &self.res.stations.recipe_index;
|
||||
let book = self.recipe_ui.book.as_ref();
|
||||
// SmithingTrimDemoSlotDisplay draws from a random of its own.
|
||||
let mut random = super::dispenser::entity_random();
|
||||
let mut items = Vec::new();
|
||||
for id in recipes {
|
||||
let Some(station) = index.toast_station(id) else {
|
||||
continue;
|
||||
};
|
||||
for display in index.display_ids(id) {
|
||||
// The book's displays carry their resolved results; the
|
||||
// other recipe types name theirs, and trims are demos.
|
||||
let result = book
|
||||
.and_then(|b| {
|
||||
b.entry_of_display(display)
|
||||
.map(|i| b.entries[i].result.clone())
|
||||
})
|
||||
.or_else(|| index.result(id).map(|r| ItemStack::new(r, 1)))
|
||||
.or_else(|| {
|
||||
self.res.stations.recipes.trim_demo(
|
||||
&self.res.stations.enchantments,
|
||||
id,
|
||||
&mut |n| {
|
||||
horizon_core::random::RandomSource::next_int_bound(
|
||||
&mut random,
|
||||
n as i32,
|
||||
)
|
||||
.unwrap_or(0) as usize
|
||||
},
|
||||
)
|
||||
});
|
||||
if let Some(result) = result {
|
||||
items.push((station.to_owned(), result));
|
||||
}
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
return;
|
||||
}
|
||||
match self.adv.toasts.iter_mut().find(|t| t.is_recipe()) {
|
||||
Some(toast) => toast.add_recipes(items),
|
||||
None => self
|
||||
.adv
|
||||
.toasts
|
||||
.push_back(super::advancements::Toast::recipe(&icon));
|
||||
.push_back(super::advancements::Toast::recipe(items)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -272,6 +272,7 @@ impl Game<'_> {
|
||||
r.session.disconnect();
|
||||
}
|
||||
horizon_client::crash::clear_detail("Server");
|
||||
self.debug_charts.reset();
|
||||
self.tab_list.reset();
|
||||
self.score.board = Default::default();
|
||||
self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1);
|
||||
@@ -736,6 +737,11 @@ impl Game<'_> {
|
||||
|
||||
fn handle_packet(&mut self, packet: C) -> Result<()> {
|
||||
match packet {
|
||||
// PingDebugMonitor.onPongReceived.
|
||||
C::PongResponse(p) => {
|
||||
let delay = self.debug_millis() - p.time;
|
||||
self.debug_charts.ping.log(delay);
|
||||
}
|
||||
C::Login(p) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.online_mode = p.online_mode;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`),
|
||||
//! using a charge.
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::first_person::Hand;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
blocks::Fluid,
|
||||
@@ -104,7 +105,7 @@ impl Game<'_> {
|
||||
.play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0);
|
||||
Ok(())
|
||||
}
|
||||
/// `RespawnAnchorBlock.useItemOn` with `held` in the main hand.
|
||||
/// `RespawnAnchorBlock.useItemOn` with `held` in the hand that acts.
|
||||
pub(super) fn use_respawn_anchor(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
@@ -126,37 +127,11 @@ impl Game<'_> {
|
||||
}
|
||||
return Ok(AnchorUse::Charged);
|
||||
}
|
||||
if fuel(self.offhand.as_ref()) && chargeable {
|
||||
if self.hand == Hand::Main && fuel(self.offhand.as_ref()) && chargeable {
|
||||
return Ok(AnchorUse::Pass);
|
||||
}
|
||||
Ok(AnchorUse::Other)
|
||||
}
|
||||
/// The off hand's glowstone on an anchor the main hand passed on.
|
||||
pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result<bool> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let fuel = self
|
||||
.offhand
|
||||
.as_ref()
|
||||
.is_some_and(|s| &*s.item == "minecraft:glowstone");
|
||||
if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 {
|
||||
return Ok(false);
|
||||
}
|
||||
let used = self.offhand.clone();
|
||||
self.charge_anchor(pos, state, Some(Who::Player))?;
|
||||
if !self.creative
|
||||
&& let Some(s) = self.offhand.as_mut()
|
||||
{
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.offhand = None;
|
||||
}
|
||||
}
|
||||
if let Some(stack) = used {
|
||||
self.trigger_block("minecraft:item_used_on_block", pos, &stack);
|
||||
}
|
||||
self.swing_arm();
|
||||
Ok(true)
|
||||
}
|
||||
/// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the
|
||||
/// Nether it explodes; inside, it becomes the respawn point.
|
||||
pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> {
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Game<'_> {
|
||||
self.inventory.get(slot)?.as_ref()
|
||||
}
|
||||
}
|
||||
fn stack_in_mut(&mut self, slot: usize) -> &mut Option<ItemStack> {
|
||||
pub(super) fn stack_in_mut(&mut self, slot: usize) -> &mut Option<ItemStack> {
|
||||
if slot == OFFHAND_SLOT {
|
||||
&mut self.offhand
|
||||
} else {
|
||||
@@ -47,10 +47,6 @@ impl Game<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Main-hand use fell through: try the off hand (Minecraft.startUseItem).
|
||||
pub(super) fn use_offhand(&mut self) -> bool {
|
||||
self.raise_shield(OFFHAND_SLOT)
|
||||
}
|
||||
/// `LivingEntity.getItemBlockingWith` and the inputs of `applyItemBlocking`
|
||||
/// for an attack from `from` (`DamageSource.getSourcePosition`).
|
||||
pub(super) fn player_blocking(
|
||||
|
||||
@@ -20,7 +20,7 @@ use std::collections::{HashMap, HashSet};
|
||||
type Pos = (i32, i32, i32);
|
||||
|
||||
/// What a spawner tick decided to add, created once the level is free.
|
||||
enum Planned {
|
||||
pub(super) enum Planned {
|
||||
/// `finalizeSpawn` ran on a fresh mob.
|
||||
Finalized(Mob),
|
||||
/// A mob loaded from the spawn data (with its passengers).
|
||||
@@ -113,7 +113,12 @@ impl Game<'_> {
|
||||
spawner.server_tick(&level, &mut random, pos, &mut spawn, &mut events);
|
||||
}
|
||||
self.world.random = random;
|
||||
// Provisional ids (counting down from u32::MAX) become the mobs' ids.
|
||||
let ids = self.add_planned(planned);
|
||||
self.apply_spawner_events(key, events, &ids)
|
||||
}
|
||||
/// Creates the mobs a spawner tick planned; their provisional ids
|
||||
/// (counting down from u32::MAX) map to the mobs' ids.
|
||||
pub(super) fn add_planned(&mut self, planned: Vec<Planned>) -> HashMap<u32, u32> {
|
||||
let mut ids = HashMap::new();
|
||||
for (i, plan) in planned.into_iter().enumerate() {
|
||||
let provisional = u32::MAX - i as u32;
|
||||
@@ -133,11 +138,11 @@ impl Game<'_> {
|
||||
ids.insert(provisional, id);
|
||||
}
|
||||
}
|
||||
self.apply_spawner_events(key, events, &ids)
|
||||
ids
|
||||
}
|
||||
/// The spawner's `loadEntityRecursive` and `tryAddFreshEntityWithPassengers`:
|
||||
/// the mob it will add (created after the tick) and its box.
|
||||
fn plan_spawner_mob(
|
||||
pub(super) fn plan_spawner_mob(
|
||||
&self,
|
||||
l: &super::natural_spawning::GameLevel,
|
||||
r: &SpawnerSpawn,
|
||||
@@ -151,6 +156,8 @@ impl Game<'_> {
|
||||
let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32);
|
||||
let difficulty = self.local_difficulty(r.position);
|
||||
spawning::finalize(&mut mob, &facts, &difficulty);
|
||||
// TrialSpawner.spawnMob: setPersistenceRequired.
|
||||
mob.persistent = r.trial;
|
||||
horizon_client::mobs::raider::finalize(
|
||||
&mut mob,
|
||||
horizon_client::mobs::raider::Reason::Other,
|
||||
@@ -187,6 +194,9 @@ impl Game<'_> {
|
||||
Tag::Float(0f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
if r.trial {
|
||||
tag.insert("PersistenceRequired".into(), Tag::Byte(1));
|
||||
}
|
||||
let tag = Tag::Compound(tag);
|
||||
let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?;
|
||||
let bounds = mob.bounds();
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Trial spawners in the game: `TrialSpawner.tickServer` for every trial
|
||||
//! spawner (`mobs::trial_spawner`), the block's state as it changes, the mobs
|
||||
//! it adds and the rewards it ejects.
|
||||
use super::{Game, natural_spawning::GameLevel, spawner::Planned};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
containers::BlockEntity,
|
||||
items::ItemStack,
|
||||
mobs::{
|
||||
Who,
|
||||
spawner::SpawnerSpawn,
|
||||
trial_spawner::{
|
||||
TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState, Uuid,
|
||||
},
|
||||
},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::HashMap;
|
||||
|
||||
type Pos = (i32, i32, i32);
|
||||
|
||||
impl TrialSpawnerLevel for GameLevel<'_, '_> {
|
||||
fn game_time(&self) -> i64 {
|
||||
self.game.world.game_time
|
||||
}
|
||||
fn mob_spawning(&self) -> bool {
|
||||
self.game.ui.rules.bool("spawn_mobs")
|
||||
}
|
||||
fn players(&self) -> Vec<TrialPlayer> {
|
||||
let (Some(p), Some(view)) = (self.game.player.as_ref(), self.game.player_view()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
vec![TrialPlayer {
|
||||
uuid: self.game.level.player_uuid.unwrap_or_default(),
|
||||
block: [p.position.x, p.position.y, p.position.z].map(|v| v.floor() as i32),
|
||||
eye: view.eye,
|
||||
creative: self.game.creative,
|
||||
spectator: self.game.spectator(),
|
||||
}]
|
||||
}
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> {
|
||||
let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);
|
||||
self.w.visual_hit(v(from), v(to))
|
||||
}
|
||||
fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]> {
|
||||
let (id, _) = self.game.persist.uuids.iter().find(|(_, u)| **u == uuid)?;
|
||||
let m = self.game.mobs.iter().find(|m| m.id == *id)?;
|
||||
(!m.removed && m.alive())
|
||||
.then(|| [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i32))
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Every trial spawner's server tick.
|
||||
pub(super) fn tick_trial_spawners(&mut self) -> Result<()> {
|
||||
let keys: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
let Some(block) = self.res.assets.registry.state(state).cloned() else {
|
||||
continue;
|
||||
};
|
||||
if block.name != "minecraft:trial_spawner" {
|
||||
continue;
|
||||
}
|
||||
let Some(BlockEntity::TrialSpawner(mut spawner)) =
|
||||
self.world.block_entities.remove(&key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let current = block
|
||||
.properties
|
||||
.get("trial_spawner_state")
|
||||
.and_then(|s| TrialState::from_name(s))
|
||||
.unwrap_or_default();
|
||||
let ominous = block.properties.get("ominous").is_some_and(|v| v == "true");
|
||||
let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous);
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::TrialSpawner(spawner));
|
||||
result?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn server_tick_trial_spawner(
|
||||
&mut self,
|
||||
key: Pos,
|
||||
spawner: &mut TrialSpawner,
|
||||
current: TrialState,
|
||||
ominous: bool,
|
||||
) -> Result<()> {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0));
|
||||
let mut sequences = std::mem::take(&mut self.rand_sequences);
|
||||
let mut events = Vec::new();
|
||||
let mut planned: Vec<Planned> = Vec::new();
|
||||
let mut uuids: Vec<(u32, Uuid)> = Vec::new();
|
||||
let mut ejected: Vec<(ItemStack, [f64; 3])> = Vec::new();
|
||||
let next = {
|
||||
let level = self.natural_level();
|
||||
let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
|
||||
let seed = self.level.seed;
|
||||
let mut spawn = |l: &GameLevel, r: &SpawnerSpawn| {
|
||||
let added = l.game.plan_spawner_mob(l, r, &mut planned)?;
|
||||
let uuid = match planned.last_mut() {
|
||||
Some(Planned::Loaded(Tag::Compound(tag))) => {
|
||||
let tag_uuid =
|
||||
horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone()));
|
||||
tag_uuid.unwrap_or_else(|| {
|
||||
let uuid = horizon_client::save::random_uuid();
|
||||
tag.insert("UUID".into(), Tag::IntArray(uuid.to_vec()));
|
||||
uuid
|
||||
})
|
||||
}
|
||||
_ => horizon_client::save::random_uuid(),
|
||||
};
|
||||
uuids.push((added.id, uuid));
|
||||
Some(uuid)
|
||||
};
|
||||
// TrialSpawner.ejectReward: the table's items, each thrown up out
|
||||
// of the spawner (DefaultDispenseItemBehavior.spawnItem, accuracy 2).
|
||||
let mut eject = |table: &str, random: &mut LegacyRandom| {
|
||||
let Some(loot) = &loot else {
|
||||
return false;
|
||||
};
|
||||
let drops = match loot.random_sequence(table) {
|
||||
Some(s) => loot.roll_split(table, sequences.get(s, seed)),
|
||||
None => loot.roll_split(table, random),
|
||||
};
|
||||
for stack in &drops {
|
||||
// The power, which only scales the direction's x and z (0 going up).
|
||||
random.next_double();
|
||||
let spread = 0.017_227_5 * 2.0;
|
||||
let v = [
|
||||
random.triangle(0.0, spread),
|
||||
random.triangle(0.2, spread),
|
||||
random.triangle(0.0, spread),
|
||||
];
|
||||
ejected.push((
|
||||
horizon_client::structure_blocks::loot_item_with_components(stack),
|
||||
v,
|
||||
));
|
||||
}
|
||||
!drops.is_empty()
|
||||
};
|
||||
spawner.server_tick(
|
||||
&level,
|
||||
&mut random,
|
||||
pos,
|
||||
current,
|
||||
ominous,
|
||||
&mut spawn,
|
||||
&mut eject,
|
||||
&mut events,
|
||||
)
|
||||
};
|
||||
self.world.random = random;
|
||||
self.rand_sequences = sequences;
|
||||
let ids = self.add_planned(planned);
|
||||
let mut by_uuid = HashMap::new();
|
||||
for (provisional, uuid) in uuids {
|
||||
if let Some(id) = ids.get(&provisional) {
|
||||
self.persist.uuids.insert(*id, uuid);
|
||||
by_uuid.insert(uuid, *id);
|
||||
}
|
||||
}
|
||||
let center = pos.map(|v| f64::from(v) + 0.5);
|
||||
// Vec3.atBottomCenterOf(pos).relative(UP, 1.2), lowered by spawnItem.
|
||||
let above = [center[0], center[1] + 0.7 - 0.125, center[2]];
|
||||
for (stack, v) in ejected {
|
||||
self.spawn_item(stack, above, v, 0);
|
||||
}
|
||||
if next != current || ominous != spawner.is_ominous {
|
||||
self.set_trial_spawner_state(key, next, spawner.is_ominous)?;
|
||||
}
|
||||
for event in events {
|
||||
match event {
|
||||
TrialEvent::BlockUpdated => self.trial_spawner_updated(key),
|
||||
TrialEvent::LevelEvent(id, at, data) => self.level_event_at(id, at, data),
|
||||
TrialEvent::Sound(name) => {
|
||||
self.audio
|
||||
.play(&format!("minecraft:{name}"), Some(center), 1.0, 1.0)
|
||||
}
|
||||
// Written with the state above.
|
||||
TrialEvent::OminousSet(_) => {}
|
||||
TrialEvent::EntityPlace(uuid, at) => {
|
||||
let who = by_uuid.get(&uuid).map(|id| Who::Mob(*id));
|
||||
self.post_block_game_event("minecraft:entity_place", at, who, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `setState` (and `removeOminous`): the block's state and ominous flag.
|
||||
fn set_trial_spawner_state(
|
||||
&mut self,
|
||||
key: Pos,
|
||||
state: TrialState,
|
||||
ominous: bool,
|
||||
) -> Result<()> {
|
||||
let current = self.world.block(key.0, key.1, key.2);
|
||||
let Some(mut block) = self.res.assets.registry.state(current).cloned() else {
|
||||
return Ok(());
|
||||
};
|
||||
block
|
||||
.properties
|
||||
.insert("trial_spawner_state".into(), state.name().into());
|
||||
block
|
||||
.properties
|
||||
.insert("ominous".into(), ominous.to_string());
|
||||
let id = self.res.assets.registry.resolve(&block)?;
|
||||
self.level_set([key.0, key.1, key.2], id)
|
||||
}
|
||||
/// `markUpdated`: the clients load the new update tag.
|
||||
fn trial_spawner_updated(&mut self, key: Pos) {
|
||||
if let Some(log) = self.world.block_log.as_mut() {
|
||||
log.push(key);
|
||||
}
|
||||
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ impl Game<'_> {
|
||||
return true;
|
||||
}
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.selected, 0));
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -99,7 +99,7 @@ impl Game<'_> {
|
||||
if ticks < 10 {
|
||||
return;
|
||||
}
|
||||
let Some(stack) = self.inventory[self.selected].clone() else {
|
||||
let Some(stack) = self.held().cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(eye) = self.eye_position() else {
|
||||
@@ -134,13 +134,13 @@ impl Game<'_> {
|
||||
}
|
||||
// hurtWithoutBreaking, then the thrown copy.
|
||||
if !self.creative
|
||||
&& let Some(s) = self.inventory[self.selected].as_mut()
|
||||
&& let Some(s) = self.held_mut().as_mut()
|
||||
{
|
||||
s.damage += 1;
|
||||
}
|
||||
let thrown = self.inventory[self.selected].clone().unwrap_or(stack);
|
||||
let thrown = self.held().cloned().unwrap_or(stack);
|
||||
if !self.creative {
|
||||
self.inventory[self.selected] = None;
|
||||
*self.held_mut() = None;
|
||||
}
|
||||
let start = Vec3::new(eye[0], eye[1] - 0.1, eye[2]);
|
||||
let mut projectile = horizon_client::projectiles::Projectile::new(
|
||||
|
||||
@@ -71,11 +71,11 @@ impl Game<'_> {
|
||||
self.stats.add("used", "minecraft:wind_charge", 1);
|
||||
self.swing_arm();
|
||||
if !self.creative
|
||||
&& let Some(s) = self.inventory[self.selected].as_mut()
|
||||
&& let Some(s) = self.held_mut().as_mut()
|
||||
{
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
self.inventory[self.selected] = None;
|
||||
*self.held_mut() = None;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
|
||||
@@ -170,6 +170,9 @@ pub struct Frame<'a> {
|
||||
pub block_flicker: f32,
|
||||
/// Blur and grade the frame under a Horizon-style menu (`post`).
|
||||
pub post: Option<crate::post::PostGrade>,
|
||||
/// `Screen.extractBlurredBackground`: blur the frame by this radius
|
||||
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
|
||||
pub menu_blur: Option<f32>,
|
||||
}
|
||||
/// One frame of the world border wall (`WorldBorderRenderer.render`).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -198,6 +201,9 @@ pub struct Renderer {
|
||||
gpu_timer: Option<timing::GpuTimer>,
|
||||
/// GPU frame times (ms) read back since the caller last drained them.
|
||||
pub gpu_times: Vec<f32>,
|
||||
/// The last lightmap written, RGBA rows of sky level by block level
|
||||
/// (F3+4 shows it).
|
||||
pub lightmap_pixels: [u8; 16 * 16 * 4],
|
||||
/// Time the last `render` spent blocked on the GPU or the display
|
||||
/// (acquiring, presenting, offscreen pacing), excluded from CPU time.
|
||||
pub last_wait: std::time::Duration,
|
||||
@@ -288,6 +294,8 @@ pub struct Renderer {
|
||||
pub hud: HudRenderer,
|
||||
/// The menus' backdrop blur, made on first use.
|
||||
post: Option<crate::post::Post>,
|
||||
/// Vanilla's menu background blur, made on first use.
|
||||
menu_blur: Option<crate::menu_blur::MenuBlur>,
|
||||
pub info: wgpu::AdapterInfo,
|
||||
pub suspended: bool,
|
||||
pub drawn_sections: usize,
|
||||
@@ -1364,6 +1372,7 @@ impl Renderer {
|
||||
in_flight: std::collections::VecDeque::new(),
|
||||
gpu_timer,
|
||||
gpu_times: Vec::new(),
|
||||
lightmap_pixels: [0; 16 * 16 * 4],
|
||||
last_wait: std::time::Duration::ZERO,
|
||||
last_encode: std::time::Duration::ZERO,
|
||||
window,
|
||||
@@ -1433,6 +1442,7 @@ impl Renderer {
|
||||
world_post,
|
||||
hud,
|
||||
post: None,
|
||||
menu_blur: None,
|
||||
info,
|
||||
suspended: size.width == 0 || size.height == 0,
|
||||
drawn_sections: 0,
|
||||
@@ -1729,7 +1739,7 @@ impl Renderer {
|
||||
world_projection(fov_degrees, aspect, far) * bob * crate::camera::view_matrix(yaw, pitch)
|
||||
}
|
||||
fn update_lightmap(
|
||||
&self,
|
||||
&mut self,
|
||||
sky: &Sky,
|
||||
darkness: f32,
|
||||
gamma: f32,
|
||||
@@ -1785,6 +1795,7 @@ impl Renderer {
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
self.lightmap_pixels = pixels;
|
||||
}
|
||||
fn animate(&mut self, tick: u64) {
|
||||
animate_sprites(
|
||||
@@ -2396,6 +2407,23 @@ impl Renderer {
|
||||
pass.draw_indexed(0..6, (i * 4) as i32, 0..1);
|
||||
}
|
||||
}
|
||||
if let Some(radius) = frame.menu_blur
|
||||
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
|
||||
{
|
||||
let format = self.config.format;
|
||||
let device = &self.device;
|
||||
self.menu_blur
|
||||
.get_or_insert_with(|| crate::menu_blur::MenuBlur::new(device, format))
|
||||
.apply(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
&target_texture,
|
||||
&view_target,
|
||||
[self.config.width, self.config.height],
|
||||
radius,
|
||||
);
|
||||
}
|
||||
if let Some(grade) = &frame.post
|
||||
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
|
||||
{
|
||||
|
||||
@@ -583,6 +583,10 @@ impl HurtWorld for Environment<'_> {
|
||||
self.event(HealthEvent::DamageBroadcast {
|
||||
source: self.source.type_id(),
|
||||
});
|
||||
// The player hears its own hurt sound from handleDamageEvent; a
|
||||
// blocked hit sends the block sound (onBlocked) instead.
|
||||
let sound = hurt_sound(&self.source.definition().effects);
|
||||
self.events.push(MotionEvent::HurtSound(sound));
|
||||
Ok(())
|
||||
}
|
||||
fn mark_hurt(&mut self, _: &mut State) -> io::Result<()> {
|
||||
@@ -619,11 +623,9 @@ impl HurtWorld for Environment<'_> {
|
||||
*self.dead = true;
|
||||
self.phase("death-request")
|
||||
}
|
||||
/// `Player.playSound` leaves the player itself out: others hear this one.
|
||||
fn hurt_sound(&mut self, _: &mut State) -> io::Result<()> {
|
||||
self.phase("hurt-sound")?;
|
||||
let sound = hurt_sound(&self.source.definition().effects);
|
||||
self.events.push(MotionEvent::HurtSound(sound));
|
||||
Ok(())
|
||||
self.phase("hurt-sound")
|
||||
}
|
||||
fn game_time(&mut self, _: &mut State) -> io::Result<i64> {
|
||||
Ok(self.game_time)
|
||||
|
||||
@@ -45,6 +45,7 @@ pub mod crash;
|
||||
pub mod creative;
|
||||
pub mod data_cmd;
|
||||
pub mod datapack;
|
||||
pub mod debug_chart;
|
||||
pub mod debug_keys;
|
||||
pub mod effects;
|
||||
pub mod enchant;
|
||||
@@ -93,6 +94,7 @@ pub mod lang;
|
||||
pub mod light;
|
||||
pub mod logging;
|
||||
pub mod menu;
|
||||
pub mod menu_blur;
|
||||
pub mod merchant;
|
||||
pub mod mesher;
|
||||
pub mod minimap;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Vanilla's menu background blur (`GameRenderer.processBlurEffect`, the
|
||||
//! `minecraft:blur` post chain): three rounds of a horizontal then a vertical
|
||||
//! `post/box_blur` pass over the frame drawn so far, `menuBackgroundBlurriness`
|
||||
//! framebuffer pixels wide, before the screen is drawn over it. Works in the
|
||||
//! frame's own (gamma) values, as vanilla's main target does, and needs a
|
||||
//! swapchain that can be copied from.
|
||||
|
||||
/// `blur.json`: the passes' directions, ping-ponging between the copied
|
||||
/// frame and a swap texture; the last one writes the frame.
|
||||
const PASSES: [[f32; 2]; 6] = [
|
||||
[1.0, 0.0],
|
||||
[0.0, 1.0],
|
||||
[1.0, 0.0],
|
||||
[0.0, 1.0],
|
||||
[1.0, 0.0],
|
||||
[0.0, 1.0],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Uniform {
|
||||
size_dir: [f32; 4],
|
||||
radius: [f32; 4],
|
||||
}
|
||||
|
||||
pub struct MenuBlur {
|
||||
layout: wgpu::BindGroupLayout,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
sampler: wgpu::Sampler,
|
||||
uniforms: Vec<wgpu::Buffer>,
|
||||
/// The copied frame (`minecraft:main`) and `swap`.
|
||||
targets: Vec<(wgpu::Texture, wgpu::TextureView)>,
|
||||
size: [u32; 2],
|
||||
format: wgpu::TextureFormat,
|
||||
}
|
||||
impl MenuBlur {
|
||||
/// `format` is the swapchain's; the blur works in its non-sRGB view.
|
||||
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
|
||||
let format = format.remove_srgb_suffix();
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Menu blur"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("menu_blur.wgsl").into()),
|
||||
});
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Menu blur bindings"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Menu blur"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Menu blur pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
// The post chain's "bilinear": true inputs, clamped like render targets.
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Menu blur"),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
..Default::default()
|
||||
});
|
||||
let uniforms = PASSES
|
||||
.iter()
|
||||
.map(|_| {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Menu blur pass"),
|
||||
size: std::mem::size_of::<Uniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
layout,
|
||||
pipeline,
|
||||
sampler,
|
||||
uniforms,
|
||||
targets: Vec::new(),
|
||||
size: [0, 0],
|
||||
format,
|
||||
}
|
||||
}
|
||||
fn ensure(&mut self, device: &wgpu::Device, size: [u32; 2]) {
|
||||
if self.size == size && !self.targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.size = size;
|
||||
self.targets = (0..2)
|
||||
.map(|_| {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Menu blur target"),
|
||||
size: wgpu::Extent3d {
|
||||
width: size[0],
|
||||
height: size[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: self.format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&Default::default());
|
||||
(texture, view)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
/// Blur `frame` (the swapchain texture) in place through `target`, its
|
||||
/// non-sRGB view, by `radius` pixels (`menuBackgroundBlurriness`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn apply(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
frame: &wgpu::Texture,
|
||||
target: &wgpu::TextureView,
|
||||
size: [u32; 2],
|
||||
radius: f32,
|
||||
) {
|
||||
self.ensure(device, size);
|
||||
encoder.copy_texture_to_texture(
|
||||
frame.as_image_copy(),
|
||||
self.targets[0].0.as_image_copy(),
|
||||
wgpu::Extent3d {
|
||||
width: size[0],
|
||||
height: size[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
for (i, dir) in PASSES.iter().enumerate() {
|
||||
let data = Uniform {
|
||||
size_dir: [size[0] as f32, size[1] as f32, dir[0], dir[1]],
|
||||
radius: [radius, 0.0, 0.0, 0.0],
|
||||
};
|
||||
queue.write_buffer(&self.uniforms[i], 0, bytemuck::bytes_of(&data));
|
||||
let source = &self.targets[i % 2].1;
|
||||
let output = if i + 1 == PASSES.len() {
|
||||
target
|
||||
} else {
|
||||
&self.targets[(i + 1) % 2].1
|
||||
};
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Menu blur pass"),
|
||||
layout: &self.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(source),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.uniforms[i].as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: output,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Menu blur pass"),
|
||||
color_attachments: &attachments,
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn box_blur_shader_validates() {
|
||||
let module = naga::front::wgsl::parse_str(include_str!("menu_blur.wgsl")).unwrap();
|
||||
naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::all(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Vanilla's post/box_blur.fsh: one direction of a box blur of 2·Radius + 1
|
||||
// pixels, reading two pixels per linear sample.
|
||||
struct Blur {
|
||||
// InSize (pixels), BlurDir.
|
||||
size_dir: vec4<f32>,
|
||||
// Radius, unused, unused, unused.
|
||||
radius: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var src: texture_2d<f32>;
|
||||
@group(0) @binding(1) var samp: sampler;
|
||||
@group(0) @binding(2) var<uniform> blur: Blur;
|
||||
struct Out {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out {
|
||||
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
|
||||
var out: Out;
|
||||
out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
out.uv = vec2(p.x, 1.0 - p.y);
|
||||
return out;
|
||||
}
|
||||
@fragment fn fs_main(in: Out) -> @location(0) vec4<f32> {
|
||||
let step = blur.size_dir.zw / blur.size_dir.xy;
|
||||
let radius = round(blur.radius.x);
|
||||
var blurred = vec4(0.0);
|
||||
for (var a = -radius + 0.5; a <= radius; a += 2.0) {
|
||||
blurred += textureSampleLevel(src, samp, in.uv + step * a, 0.0);
|
||||
}
|
||||
blurred += textureSampleLevel(src, samp, in.uv + step * radius, 0.0) / 2.0;
|
||||
return blurred / (radius + 0.5);
|
||||
}
|
||||
@@ -65,6 +65,7 @@ pub mod sulfur_cube;
|
||||
pub mod tame;
|
||||
pub mod trader;
|
||||
pub mod transport_items;
|
||||
pub mod trial_spawner;
|
||||
pub mod undead;
|
||||
pub mod vex;
|
||||
pub mod villager;
|
||||
@@ -74,6 +75,7 @@ pub mod warden_brain;
|
||||
pub mod witch;
|
||||
pub mod wither;
|
||||
mod world;
|
||||
pub use world::visual_clip;
|
||||
pub mod zombie_villager;
|
||||
|
||||
use crate::{blocks::BlockFacts, mesher::Vertex, world::World};
|
||||
|
||||
@@ -107,11 +107,17 @@ impl SpawnData {
|
||||
}
|
||||
/// The entity compound is only its `id` (`hasNoConfiguration`): the
|
||||
/// spawned mob is finalized.
|
||||
fn unconfigured(&self) -> bool {
|
||||
pub(crate) fn unconfigured(&self) -> bool {
|
||||
self.entity.len() == 1 && self.id().is_some()
|
||||
}
|
||||
/// `CustomSpawnRules.isValidPosition`.
|
||||
fn valid_position<L: SpawnerLevel>(r: CustomSpawnRules, l: &L, x: i32, y: i32, z: i32) -> bool {
|
||||
pub(crate) fn valid_position<L: SpawnerLevel>(
|
||||
r: CustomSpawnRules,
|
||||
l: &L,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> bool {
|
||||
let block = l.block_light(x, y, z);
|
||||
let sky = (l.sky_light(x, y, z) - l.sky_darken()).max(0);
|
||||
(r.block.0..=r.block.1).contains(&block) && (r.sky.0..=r.sky.1).contains(&sky)
|
||||
@@ -135,8 +141,19 @@ pub fn normalize_id(s: &str) -> Option<String> {
|
||||
.then(|| format!("{ns}:{path}"))
|
||||
}
|
||||
|
||||
/// How much a slime's or magma cube's box is scaled by the size its data
|
||||
/// loads (`Slime.readAdditionalSaveData`: Size + 1, kept in 1..=127), which
|
||||
/// the obstruction test sees before `finalizeSpawn` picks one.
|
||||
pub(crate) fn cube_scale(id: &str, entity: &Compound) -> f32 {
|
||||
if !matches!(id, "minecraft:slime" | "minecraft:magma_cube") {
|
||||
return 1.0;
|
||||
}
|
||||
number(entity.get(&JavaString::from("Size")))
|
||||
.map_or(1, |size| (size as i32).saturating_add(1).clamp(1, 127)) as f32
|
||||
}
|
||||
|
||||
/// A whole number from any numeric tag (`NumericTag.intValue`: floats floor).
|
||||
fn number(tag: Option<&Tag>) -> Option<i64> {
|
||||
pub(crate) fn number(tag: Option<&Tag>) -> Option<i64> {
|
||||
Some(match tag? {
|
||||
Tag::Byte(v) => i64::from(*v),
|
||||
Tag::Short(v) => i64::from(*v),
|
||||
@@ -255,6 +272,9 @@ pub struct SpawnerSpawn<'a> {
|
||||
/// `finalizeSpawn(SPAWNER)` runs (the data is just an id).
|
||||
pub finalize: bool,
|
||||
pub equipment: Option<&'a Tag>,
|
||||
/// A trial spawner's mob (`EntitySpawnReason.TRIAL_SPAWNER`): it is
|
||||
/// always persistent.
|
||||
pub trial: bool,
|
||||
}
|
||||
/// An entity the level added: its id, box and whether it is a mob.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -370,25 +390,8 @@ impl Spawner {
|
||||
Next::Potential(i) => self.potentials.get_mut(*i).map(|(d, _)| d),
|
||||
}
|
||||
}
|
||||
/// `WeightedList.getRandom`: one draw over the total weight, none when
|
||||
/// the list weighs nothing.
|
||||
fn random_potential(&self, random: &mut impl RandomSource) -> Option<usize> {
|
||||
let total: i64 = self.potentials.iter().map(|(_, w)| i64::from(*w)).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut pick = i64::from(
|
||||
random
|
||||
.next_int_bound(total.min(i64::from(i32::MAX)) as i32)
|
||||
.unwrap_or(0),
|
||||
);
|
||||
for (i, (_, w)) in self.potentials.iter().enumerate() {
|
||||
pick -= i64::from(*w);
|
||||
if pick < 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
weighted_index(self.potentials.iter().map(|(_, w)| *w), random)
|
||||
}
|
||||
/// `getOrCreateNextSpawnData`: a potential at random, or empty data.
|
||||
fn next_or_create(&mut self, random: &mut impl RandomSource, events: &mut Vec<SpawnerEvent>) {
|
||||
@@ -555,7 +558,14 @@ impl Spawner {
|
||||
placed[1].floor() as i32,
|
||||
placed[2].floor() as i32,
|
||||
];
|
||||
let bounds = spawn_selection::spawn_box(placed[0], placed[1], placed[2], width, height);
|
||||
let scale = cube_scale(&id, &data.entity);
|
||||
let bounds = spawn_selection::spawn_box(
|
||||
placed[0],
|
||||
placed[1],
|
||||
placed[2],
|
||||
width * scale,
|
||||
height * scale,
|
||||
);
|
||||
let rules_ok = data.custom_spawn_rules.is_some()
|
||||
|| spawn_selection::mob_spawn_rules(s, l, own[0], own[1], own[2]);
|
||||
if !rules_ok
|
||||
@@ -570,6 +580,7 @@ impl Spawner {
|
||||
yaw,
|
||||
finalize: data.unconfigured(),
|
||||
equipment: data.equipment.as_ref(),
|
||||
trial: false,
|
||||
};
|
||||
let Some(result) = spawn(l, &request) else {
|
||||
self.delay(random, events);
|
||||
@@ -643,6 +654,30 @@ impl Spawner {
|
||||
}
|
||||
}
|
||||
|
||||
/// `WeightedList.getRandom`: one draw over the total weight, none when the
|
||||
/// list weighs nothing.
|
||||
pub fn weighted_index(
|
||||
weights: impl Iterator<Item = i32> + Clone,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Option<usize> {
|
||||
let total: i64 = weights.clone().map(i64::from).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut pick = i64::from(
|
||||
random
|
||||
.next_int_bound(total.min(i64::from(i32::MAX)) as i32)
|
||||
.unwrap_or(0),
|
||||
);
|
||||
for (i, w) in weights.enumerate() {
|
||||
pick -= i64::from(w);
|
||||
if pick < 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `Entity.setPos` of a fresh mob: a shulker sits at the centre of its block.
|
||||
pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] {
|
||||
if s == Species::Shulker {
|
||||
@@ -657,7 +692,7 @@ pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] {
|
||||
}
|
||||
|
||||
/// `Vec3.CODEC`: a list of three doubles.
|
||||
fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> {
|
||||
pub(crate) fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> {
|
||||
let Tag::List(v) = tag? else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,886 @@
|
||||
//! The trial spawner (`TrialSpawner` as `TrialSpawnerBlockEntity` runs it):
|
||||
//! its configs, saved state (`TrialSpawnerStateData`) and the server tick that
|
||||
//! walks `TrialSpawnerState`: waiting for players, spawning its waves while
|
||||
//! they fight, ejecting a reward per player, then cooling down.
|
||||
//!
|
||||
//! The state lives in the block (`trial_spawner_state`); the tick reads it and
|
||||
//! reports the next one. The level's random drives the tick in vanilla's draw
|
||||
//! order; what the spawner asks of the level goes through
|
||||
//! [`TrialSpawnerLevel`], so the game and a differential test world answer the
|
||||
//! same questions.
|
||||
use super::{
|
||||
spawn_rules::{self, Reason},
|
||||
spawn_selection,
|
||||
spawner::{self, SpawnData, SpawnerLevel, SpawnerSpawn},
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
use std::{collections::HashMap, path::Path, sync::OnceLock};
|
||||
|
||||
/// An entity's UUID as its four ints (`UUIDUtil.CODEC`).
|
||||
pub type Uuid = [i32; 4];
|
||||
|
||||
/// `MAX_MOB_TRACKING_DISTANCE`: a spawned mob further than this stops
|
||||
/// counting as one of the spawner's.
|
||||
const MAX_MOB_TRACKING_DISTANCE: i64 = 47;
|
||||
/// `DELAY_BEFORE_EJECT_AFTER_KILLING_LAST_MOB` and `TIME_BETWEEN_EACH_EJECTION`.
|
||||
const DELAY_BEFORE_EJECT: f32 = 40.0;
|
||||
const TIME_BETWEEN_EJECTIONS: f32 = 30.0;
|
||||
|
||||
/// `TrialSpawnerConfig`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TrialConfig {
|
||||
pub spawn_range: i32,
|
||||
pub total_mobs: f32,
|
||||
pub simultaneous_mobs: f32,
|
||||
pub total_mobs_added_per_player: f32,
|
||||
pub simultaneous_mobs_added_per_player: f32,
|
||||
pub ticks_between_spawn: i32,
|
||||
pub spawn_potentials: Vec<(SpawnData, i32)>,
|
||||
pub loot_tables_to_eject: Vec<(String, i32)>,
|
||||
pub items_to_drop_when_ominous: String,
|
||||
}
|
||||
impl Default for TrialConfig {
|
||||
/// `TrialSpawnerConfig.Builder`'s defaults.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
spawn_range: 4,
|
||||
total_mobs: 6.0,
|
||||
simultaneous_mobs: 2.0,
|
||||
total_mobs_added_per_player: 2.0,
|
||||
simultaneous_mobs_added_per_player: 1.0,
|
||||
ticks_between_spawn: 40,
|
||||
spawn_potentials: Vec::new(),
|
||||
loot_tables_to_eject: vec![
|
||||
("minecraft:spawners/trial_chamber/consumables".into(), 1),
|
||||
("minecraft:spawners/trial_chamber/key".into(), 1),
|
||||
],
|
||||
items_to_drop_when_ominous:
|
||||
"minecraft:spawners/trial_chamber/items_to_drop_when_ominous".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl TrialConfig {
|
||||
/// `TrialSpawnerConfig.DIRECT_CODEC`; None when the tag is not a
|
||||
/// compound. Read as `TagValueInput` does, keeping the partial result:
|
||||
/// a field that fails to decode takes its default, and the list entries
|
||||
/// that fail are dropped.
|
||||
pub fn decode(tag: &Tag) -> Option<Self> {
|
||||
let Tag::Compound(_) = tag else {
|
||||
return None;
|
||||
};
|
||||
let d = Self::default();
|
||||
let float = |k: &str, default: f32| {
|
||||
tag.get(k)
|
||||
.and_then(float)
|
||||
.filter(|v| *v >= 0.0)
|
||||
.unwrap_or(default)
|
||||
};
|
||||
let int = |k: &str, default: i32, lo: i32, hi: i32| {
|
||||
spawner::number(tag.get(k))
|
||||
.filter(|v| (i64::from(lo)..=i64::from(hi)).contains(v))
|
||||
.map_or(default, |v| v as i32)
|
||||
};
|
||||
let list = |k: &str| match tag.get(k) {
|
||||
Some(Tag::List(list)) => Some(list.iter()),
|
||||
_ => None,
|
||||
};
|
||||
let spawn_potentials = list("spawn_potentials").map_or_else(Vec::new, |l| {
|
||||
l.filter_map(|e| Some((SpawnData::decode(e.get("data")?)?, weight(e.get("weight"))?)))
|
||||
.collect()
|
||||
});
|
||||
let loot_tables_to_eject =
|
||||
list("loot_tables_to_eject").map_or(d.loot_tables_to_eject, |l| {
|
||||
l.filter_map(|e| Some((identifier(e.get("data"))?, weight(e.get("weight"))?)))
|
||||
.collect()
|
||||
});
|
||||
Some(Self {
|
||||
spawn_range: int("spawn_range", d.spawn_range, 1, 128),
|
||||
total_mobs: float("total_mobs", d.total_mobs),
|
||||
simultaneous_mobs: float("simultaneous_mobs", d.simultaneous_mobs),
|
||||
total_mobs_added_per_player: float(
|
||||
"total_mobs_added_per_player",
|
||||
d.total_mobs_added_per_player,
|
||||
),
|
||||
simultaneous_mobs_added_per_player: float(
|
||||
"simultaneous_mobs_added_per_player",
|
||||
d.simultaneous_mobs_added_per_player,
|
||||
),
|
||||
ticks_between_spawn: int("ticks_between_spawn", d.ticks_between_spawn, 0, i32::MAX),
|
||||
spawn_potentials,
|
||||
loot_tables_to_eject,
|
||||
items_to_drop_when_ominous: identifier(tag.get("items_to_drop_when_ominous"))
|
||||
.unwrap_or(d.items_to_drop_when_ominous),
|
||||
})
|
||||
}
|
||||
/// `calculateTargetTotalMobs`.
|
||||
pub fn target_total_mobs(&self, additional_players: i32) -> i32 {
|
||||
(self.total_mobs + self.total_mobs_added_per_player * additional_players as f32).floor()
|
||||
as i32
|
||||
}
|
||||
/// `calculateTargetSimultaneousMobs`.
|
||||
pub fn target_simultaneous_mobs(&self, additional_players: i32) -> i32 {
|
||||
(self.simultaneous_mobs
|
||||
+ self.simultaneous_mobs_added_per_player * additional_players as f32)
|
||||
.floor() as i32
|
||||
}
|
||||
}
|
||||
|
||||
static REGISTRY: OnceLock<HashMap<String, TrialConfig>> = OnceLock::new();
|
||||
|
||||
/// `Registries.TRIAL_SPAWNER_CONFIG`: the configs under the resources'
|
||||
/// `data/<namespace>/trial_spawner`, read once per process.
|
||||
pub fn load_registry(root: &Path) {
|
||||
REGISTRY.get_or_init(|| {
|
||||
let mut out = HashMap::new();
|
||||
let Ok(namespaces) = std::fs::read_dir(root.join("data")) else {
|
||||
return out;
|
||||
};
|
||||
for ns in namespaces.flatten() {
|
||||
let base = ns.path().join("trial_spawner");
|
||||
let mut stack = vec![base.clone()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
continue;
|
||||
}
|
||||
let (Ok(rel), Some(ns)) = (
|
||||
path.with_extension("")
|
||||
.strip_prefix(&base)
|
||||
.map(Path::to_path_buf),
|
||||
ns.file_name().to_str().map(str::to_owned),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let config = std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.and_then(|v| TrialConfig::decode(&crate::scoreboard::json_to_tag(&v)));
|
||||
match config {
|
||||
Some(c) => {
|
||||
let id = rel.to_string_lossy().replace('\\', "/");
|
||||
out.insert(format!("{ns}:{id}"), c);
|
||||
}
|
||||
None => log::warn!("Horizon: bad trial spawner config {}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
});
|
||||
}
|
||||
/// A config of the registry by id.
|
||||
pub fn registry_config(id: &str) -> Option<TrialConfig> {
|
||||
REGISTRY.get()?.get(id).cloned()
|
||||
}
|
||||
|
||||
fn float(t: &Tag) -> Option<f32> {
|
||||
Some(match t {
|
||||
Tag::Float(b) => f32::from_bits(*b),
|
||||
Tag::Double(b) => f64::from_bits(*b) as f32,
|
||||
t => spawner::number(Some(t))? as f32,
|
||||
})
|
||||
}
|
||||
/// `Weighted.CODEC`'s weight: a non-negative int.
|
||||
fn weight(t: Option<&Tag>) -> Option<i32> {
|
||||
spawner::number(t)
|
||||
.filter(|w| (0..=i64::from(i32::MAX)).contains(w))
|
||||
.map(|w| w as i32)
|
||||
}
|
||||
/// An `Identifier` (`minecraft` when the namespace is left out).
|
||||
fn identifier(t: Option<&Tag>) -> Option<String> {
|
||||
match t? {
|
||||
Tag::String(s) => spawner::normalize_id(&s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Holder<TrialSpawnerConfig>` as saved: a registry id
|
||||
/// (`minecraft:trial_chamber/breeze/normal`) or an inline config.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConfigSlot {
|
||||
/// The value as loaded, written back as is; None for the default.
|
||||
pub saved: Option<Tag>,
|
||||
pub config: TrialConfig,
|
||||
}
|
||||
|
||||
/// `TrialSpawnerState`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum TrialState {
|
||||
#[default]
|
||||
Inactive,
|
||||
WaitingForPlayers,
|
||||
Active,
|
||||
WaitingForRewardEjection,
|
||||
EjectingReward,
|
||||
Cooldown,
|
||||
}
|
||||
impl TrialState {
|
||||
pub const ALL: [Self; 6] = [
|
||||
Self::Inactive,
|
||||
Self::WaitingForPlayers,
|
||||
Self::Active,
|
||||
Self::WaitingForRewardEjection,
|
||||
Self::EjectingReward,
|
||||
Self::Cooldown,
|
||||
];
|
||||
/// The `trial_spawner_state` block property.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Inactive => "inactive",
|
||||
Self::WaitingForPlayers => "waiting_for_players",
|
||||
Self::Active => "active",
|
||||
Self::WaitingForRewardEjection => "waiting_for_reward_ejection",
|
||||
Self::EjectingReward => "ejecting_reward",
|
||||
Self::Cooldown => "cooldown",
|
||||
}
|
||||
}
|
||||
pub fn from_name(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
/// The spin speed of the mob shown inside, None when it shows none.
|
||||
pub fn spinning_mob_speed(self) -> Option<f64> {
|
||||
match self {
|
||||
Self::WaitingForPlayers => Some(200.0),
|
||||
Self::Active => Some(1000.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn capable_of_spawning(self) -> bool {
|
||||
matches!(self, Self::WaitingForPlayers | Self::Active)
|
||||
}
|
||||
}
|
||||
|
||||
/// A player the spawner can detect (`PlayerDetector.NO_CREATIVE_PLAYERS`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TrialPlayer {
|
||||
pub uuid: Uuid,
|
||||
pub block: [i32; 3],
|
||||
pub eye: [f64; 3],
|
||||
pub creative: bool,
|
||||
pub spectator: bool,
|
||||
}
|
||||
|
||||
/// What a trial spawner did that the level shows or sends.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TrialEvent {
|
||||
/// `markUpdated`: `sendBlockUpdated` with the new update tag.
|
||||
BlockUpdated,
|
||||
/// `levelEvent(id, pos, data)`.
|
||||
LevelEvent(i32, [i32; 3], i32),
|
||||
/// `playSound(null, spawner, sound, BLOCKS)` at volume and pitch 1.
|
||||
Sound(&'static str),
|
||||
/// `gameEvent(entity, ENTITY_PLACE, block)` for the mob just added.
|
||||
EntityPlace(Uuid, [i32; 3]),
|
||||
/// `setBlockAndUpdate` of the `ominous` property alone, even when it
|
||||
/// does not change (`removeOminous`).
|
||||
OminousSet(bool),
|
||||
}
|
||||
|
||||
/// What a trial spawner reads from the level besides the spawn rules.
|
||||
pub trait TrialSpawnerLevel: SpawnerLevel {
|
||||
fn game_time(&self) -> i64;
|
||||
/// `canSpawnInLevel`'s `spawn_mobs` game rule.
|
||||
fn mob_spawning(&self) -> bool;
|
||||
/// `level.getPlayers()`, in the server's order.
|
||||
fn players(&self) -> Vec<TrialPlayer>;
|
||||
/// The block a VISUAL clip from `from` to `to` (no fluids) first hits.
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]>;
|
||||
/// The block position of a living entity of this dimension, if any.
|
||||
fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]>;
|
||||
}
|
||||
|
||||
/// `TrialSpawner` with its `TrialSpawnerStateData`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TrialSpawner {
|
||||
pub normal: ConfigSlot,
|
||||
pub ominous: ConfigSlot,
|
||||
pub target_cooldown_length: i32,
|
||||
pub required_player_range: i32,
|
||||
pub detected_players: Vec<Uuid>,
|
||||
pub current_mobs: Vec<Uuid>,
|
||||
pub cooldown_ends_at: i64,
|
||||
pub next_mob_spawns_at: i64,
|
||||
pub total_mobs_spawned: i32,
|
||||
pub next_spawn_data: Option<SpawnData>,
|
||||
pub ejecting_loot_table: Option<String>,
|
||||
/// `isOminous`, set from the block on every server tick.
|
||||
pub is_ominous: bool,
|
||||
/// The server's display entity exists (`getOrCreateDisplayEntity`): it is
|
||||
/// made once per loaded block entity and kept.
|
||||
pub has_display: bool,
|
||||
pub spin: f64,
|
||||
pub o_spin: f64,
|
||||
}
|
||||
impl Default for TrialSpawner {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
normal: ConfigSlot::default(),
|
||||
ominous: ConfigSlot::default(),
|
||||
target_cooldown_length: 36000,
|
||||
required_player_range: 14,
|
||||
detected_players: Vec::new(),
|
||||
current_mobs: Vec::new(),
|
||||
cooldown_ends_at: 0,
|
||||
next_mob_spawns_at: 0,
|
||||
total_mobs_spawned: 0,
|
||||
next_spawn_data: None,
|
||||
ejecting_loot_table: None,
|
||||
is_ominous: false,
|
||||
has_display: false,
|
||||
spin: 0.0,
|
||||
o_spin: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn uuids(tag: Option<&Tag>) -> Vec<Uuid> {
|
||||
let Some(Tag::List(list)) = tag else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out: Vec<Uuid> = Vec::new();
|
||||
for t in list {
|
||||
if let Tag::IntArray(v) = t
|
||||
&& let Ok(u) = <Uuid>::try_from(v.as_slice())
|
||||
&& !out.contains(&u)
|
||||
{
|
||||
out.push(u);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn encode_uuids(list: &[Uuid]) -> Tag {
|
||||
Tag::List(list.iter().map(|u| Tag::IntArray(u.to_vec())).collect())
|
||||
}
|
||||
|
||||
impl TrialSpawner {
|
||||
/// `TrialSpawner.load`, with the configs of [`load_registry`].
|
||||
pub fn load(tag: &Tag) -> Self {
|
||||
Self::load_with(tag, ®istry_config)
|
||||
}
|
||||
/// `TrialSpawner.load`. `registry` resolves a config id.
|
||||
pub fn load_with(tag: &Tag, registry: &dyn Fn(&str) -> Option<TrialConfig>) -> Self {
|
||||
let long = |k: &str| match tag.get(k) {
|
||||
Some(Tag::Long(v)) => *v,
|
||||
t => spawner::number(t).unwrap_or(0),
|
||||
};
|
||||
let mut s = Self {
|
||||
detected_players: uuids(tag.get("registered_players")),
|
||||
current_mobs: uuids(tag.get("current_mobs")),
|
||||
cooldown_ends_at: long("cooldown_ends_at"),
|
||||
next_mob_spawns_at: long("next_mob_spawns_at"),
|
||||
total_mobs_spawned: spawner::number(tag.get("total_mobs_spawned"))
|
||||
.filter(|v| (0..=i64::from(i32::MAX)).contains(v))
|
||||
.map_or(0, |v| v as i32),
|
||||
next_spawn_data: tag.get("spawn_data").and_then(SpawnData::decode),
|
||||
ejecting_loot_table: identifier(tag.get("ejecting_loot_table")),
|
||||
..Self::default()
|
||||
};
|
||||
// FullConfig.MAP_CODEC, partial result kept: a field that fails to
|
||||
// decode takes its default.
|
||||
let slot = |k: &str| -> ConfigSlot {
|
||||
let config = match tag.get(k) {
|
||||
Some(Tag::String(id)) => {
|
||||
spawner::normalize_id(&id.to_string_lossy()).and_then(|id| registry(&id))
|
||||
}
|
||||
Some(t) => TrialConfig::decode(t),
|
||||
None => None,
|
||||
};
|
||||
config.map_or_else(ConfigSlot::default, |config| ConfigSlot {
|
||||
saved: tag.get(k).cloned(),
|
||||
config,
|
||||
})
|
||||
};
|
||||
let int = |k: &str, default: i32, lo: i32, hi: i32| {
|
||||
spawner::number(tag.get(k))
|
||||
.filter(|v| (i64::from(lo)..=i64::from(hi)).contains(v))
|
||||
.map_or(default, |v| v as i32)
|
||||
};
|
||||
s.normal = slot("normal_config");
|
||||
s.ominous = slot("ominous_config");
|
||||
s.target_cooldown_length = int("target_cooldown_length", 36000, 0, i32::MAX);
|
||||
s.required_player_range = int("required_player_range", 14, 1, 128);
|
||||
s
|
||||
}
|
||||
/// `TrialSpawner.store`: the state data's fields that differ from their
|
||||
/// defaults, then the configs.
|
||||
pub fn save(&self) -> Vec<(&'static str, Tag)> {
|
||||
let mut out = Vec::new();
|
||||
if !self.detected_players.is_empty() {
|
||||
out.push(("registered_players", encode_uuids(&self.detected_players)));
|
||||
}
|
||||
if !self.current_mobs.is_empty() {
|
||||
out.push(("current_mobs", encode_uuids(&self.current_mobs)));
|
||||
}
|
||||
if self.cooldown_ends_at != 0 {
|
||||
out.push(("cooldown_ends_at", Tag::Long(self.cooldown_ends_at)));
|
||||
}
|
||||
if self.next_mob_spawns_at != 0 {
|
||||
out.push(("next_mob_spawns_at", Tag::Long(self.next_mob_spawns_at)));
|
||||
}
|
||||
if self.total_mobs_spawned != 0 {
|
||||
out.push(("total_mobs_spawned", Tag::Int(self.total_mobs_spawned)));
|
||||
}
|
||||
if let Some(d) = &self.next_spawn_data {
|
||||
out.push(("spawn_data", d.encode()));
|
||||
}
|
||||
if let Some(t) = &self.ejecting_loot_table {
|
||||
out.push(("ejecting_loot_table", Tag::String(t.as_str().into())));
|
||||
}
|
||||
for (key, slot) in [
|
||||
("normal_config", &self.normal),
|
||||
("ominous_config", &self.ominous),
|
||||
] {
|
||||
if let Some(t) = &slot.saved {
|
||||
out.push((key, t.clone()));
|
||||
}
|
||||
}
|
||||
if self.target_cooldown_length != 36000 {
|
||||
out.push((
|
||||
"target_cooldown_length",
|
||||
Tag::Int(self.target_cooldown_length),
|
||||
));
|
||||
}
|
||||
if self.required_player_range != 14 {
|
||||
out.push((
|
||||
"required_player_range",
|
||||
Tag::Int(self.required_player_range),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `TrialSpawnerStateData.getUpdateTag`.
|
||||
pub fn update_tag(&self, state: TrialState) -> Tag {
|
||||
let mut out = Compound::new();
|
||||
if state == TrialState::Active {
|
||||
out.insert(
|
||||
"next_mob_spawns_at".into(),
|
||||
Tag::Long(self.next_mob_spawns_at),
|
||||
);
|
||||
}
|
||||
if let Some(d) = &self.next_spawn_data {
|
||||
out.insert("spawn_data".into(), d.encode());
|
||||
}
|
||||
Tag::Compound(out)
|
||||
}
|
||||
/// `activeConfig`.
|
||||
pub fn active_config(&self) -> &TrialConfig {
|
||||
if self.is_ominous {
|
||||
&self.ominous.config
|
||||
} else {
|
||||
&self.normal.config
|
||||
}
|
||||
}
|
||||
/// `resetStatistics`.
|
||||
fn reset_statistics(&mut self) {
|
||||
self.detected_players.clear();
|
||||
self.total_mobs_spawned = 0;
|
||||
self.next_mob_spawns_at = 0;
|
||||
self.cooldown_ends_at = 0;
|
||||
}
|
||||
/// `reset`.
|
||||
fn reset(&mut self) {
|
||||
self.current_mobs.clear();
|
||||
self.next_spawn_data = None;
|
||||
self.reset_statistics();
|
||||
}
|
||||
/// `getOrCreateNextSpawnData`: a potential at random, else empty data.
|
||||
fn next_or_create(
|
||||
&mut self,
|
||||
random: &mut impl RandomSource,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> &SpawnData {
|
||||
if self.next_spawn_data.is_none() {
|
||||
let potentials = &self.active_config().spawn_potentials;
|
||||
let picked = spawner::weighted_index(potentials.iter().map(|(_, w)| *w), random)
|
||||
.map(|i| potentials[i].0.clone());
|
||||
self.next_spawn_data = Some(picked.unwrap_or_default());
|
||||
events.push(TrialEvent::BlockUpdated);
|
||||
}
|
||||
self.next_spawn_data.get_or_insert_default()
|
||||
}
|
||||
/// `hasMobToSpawn`.
|
||||
fn has_mob_to_spawn(
|
||||
&mut self,
|
||||
random: &mut impl RandomSource,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> bool {
|
||||
self.next_or_create(random, events).id().is_some()
|
||||
// WeightedList.isEmpty: a total weight of 0.
|
||||
|| self.active_config().spawn_potentials.iter().any(|(_, w)| *w > 0)
|
||||
}
|
||||
/// `canSpawnInLevel`.
|
||||
fn can_spawn_in_level<L: TrialSpawnerLevel>(l: &L) -> bool {
|
||||
l.spawner_blocks_work() && !l.peaceful() && l.mob_spawning()
|
||||
}
|
||||
/// `PlayerDetector.NO_CREATIVE_PLAYERS.detect`.
|
||||
fn detect<L: TrialSpawnerLevel>(&self, l: &L, pos: [i32; 3], line_of_sight: bool) -> Vec<Uuid> {
|
||||
let range = f64::from(self.required_player_range);
|
||||
l.players()
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
let d = [0, 1, 2].map(|i| f64::from(p.block[i] - pos[i]));
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
|
||||
&& !p.creative
|
||||
&& !p.spectator
|
||||
})
|
||||
.filter(|p| !line_of_sight || in_line_of_sight(l, center(pos), p.eye))
|
||||
.map(|p| p.uuid)
|
||||
.collect()
|
||||
}
|
||||
/// `tryDetectPlayers`, every 20 ticks.
|
||||
fn try_detect_players<L: TrialSpawnerLevel>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
pos: [i32; 3],
|
||||
state: TrialState,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) {
|
||||
let packed = BlockPos::new(pos[0], pos[1], pos[2]).pack();
|
||||
if packed.wrapping_add(l.game_time()) % 20 != 0 {
|
||||
return;
|
||||
}
|
||||
if state == TrialState::Cooldown {
|
||||
return;
|
||||
}
|
||||
let in_sight = self.detect(l, pos, true);
|
||||
let found = if self.detected_players.is_empty() {
|
||||
in_sight
|
||||
} else {
|
||||
self.detect(l, pos, false)
|
||||
};
|
||||
let mut added = false;
|
||||
for uuid in found {
|
||||
if !self.detected_players.contains(&uuid) {
|
||||
self.detected_players.push(uuid);
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
if added {
|
||||
self.next_mob_spawns_at = (l.game_time() + 40).max(self.next_mob_spawns_at);
|
||||
let id = if self.is_ominous { 3019 } else { 3013 };
|
||||
events.push(TrialEvent::LevelEvent(
|
||||
id,
|
||||
pos,
|
||||
self.detected_players.len() as i32,
|
||||
));
|
||||
}
|
||||
}
|
||||
/// `TrialSpawner.tickServer`: the next state of the block.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn server_tick<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
state: TrialState,
|
||||
ominous: bool,
|
||||
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<Uuid>,
|
||||
eject: &mut dyn FnMut(&str, &mut R) -> bool,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> TrialState {
|
||||
self.is_ominous = ominous;
|
||||
let before = self.current_mobs.len();
|
||||
let max = MAX_MOB_TRACKING_DISTANCE * MAX_MOB_TRACKING_DISTANCE;
|
||||
self.current_mobs.retain(|id| {
|
||||
l.entity_block(*id).is_some_and(|b| {
|
||||
let d = [0, 1, 2].map(|i| i64::from(b[i] - pos[i]));
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= max
|
||||
})
|
||||
});
|
||||
if self.current_mobs.len() != before {
|
||||
self.next_mob_spawns_at =
|
||||
l.game_time() + i64::from(self.active_config().ticks_between_spawn);
|
||||
}
|
||||
self.tick_and_get_next(l, random, pos, state, spawn, eject, events)
|
||||
}
|
||||
/// `TrialSpawnerState.tickAndGetNext`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn tick_and_get_next<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
state: TrialState,
|
||||
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<Uuid>,
|
||||
eject: &mut dyn FnMut(&str, &mut R) -> bool,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> TrialState {
|
||||
use TrialState as S;
|
||||
let now = l.game_time();
|
||||
match state {
|
||||
S::Inactive => {
|
||||
// getOrCreateDisplayEntity: made once, from the next data's id.
|
||||
if !self.has_display {
|
||||
let id = self.next_or_create(random, events).id();
|
||||
self.has_display = id.is_some_and(|id| l.entity_exists(&id));
|
||||
}
|
||||
if self.has_display {
|
||||
S::WaitingForPlayers
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
S::WaitingForPlayers => {
|
||||
if !Self::can_spawn_in_level(l) {
|
||||
self.reset_statistics();
|
||||
state
|
||||
} else if !self.has_mob_to_spawn(random, events) {
|
||||
S::Inactive
|
||||
} else {
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if self.detected_players.is_empty() {
|
||||
state
|
||||
} else {
|
||||
S::Active
|
||||
}
|
||||
}
|
||||
}
|
||||
S::Active => {
|
||||
if !Self::can_spawn_in_level(l) {
|
||||
self.reset_statistics();
|
||||
return S::WaitingForPlayers;
|
||||
}
|
||||
if !self.has_mob_to_spawn(random, events) {
|
||||
return S::Inactive;
|
||||
}
|
||||
let config = self.active_config().clone();
|
||||
let additional = (self.detected_players.len() as i32 - 1).max(0);
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if self.total_mobs_spawned >= config.target_total_mobs(additional) {
|
||||
if self.current_mobs.is_empty() {
|
||||
self.cooldown_ends_at = now + i64::from(self.target_cooldown_length);
|
||||
self.total_mobs_spawned = 0;
|
||||
self.next_mob_spawns_at = 0;
|
||||
return S::WaitingForRewardEjection;
|
||||
}
|
||||
} else if now >= self.next_mob_spawns_at
|
||||
&& (self.current_mobs.len() as i32)
|
||||
< config.target_simultaneous_mobs(additional)
|
||||
&& let Some(uuid) = self.spawn_mob(l, random, pos, spawn, events)
|
||||
{
|
||||
self.current_mobs.push(uuid);
|
||||
self.total_mobs_spawned += 1;
|
||||
self.next_mob_spawns_at = now + i64::from(config.ticks_between_spawn);
|
||||
let potentials = &config.spawn_potentials;
|
||||
if let Some(i) =
|
||||
spawner::weighted_index(potentials.iter().map(|(_, w)| *w), random)
|
||||
{
|
||||
self.next_spawn_data = Some(potentials[i].0.clone());
|
||||
events.push(TrialEvent::BlockUpdated);
|
||||
}
|
||||
}
|
||||
state
|
||||
}
|
||||
S::WaitingForRewardEjection => {
|
||||
let started = self.cooldown_ends_at - i64::from(self.target_cooldown_length);
|
||||
if now as f32 >= started as f32 + DELAY_BEFORE_EJECT {
|
||||
events.push(TrialEvent::Sound("block.trial_spawner.open_shutter"));
|
||||
S::EjectingReward
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
S::EjectingReward => {
|
||||
let started = self.cooldown_ends_at - i64::from(self.target_cooldown_length);
|
||||
if (now - started) as f32 % TIME_BETWEEN_EJECTIONS != 0.0 {
|
||||
return state;
|
||||
}
|
||||
if self.detected_players.is_empty() {
|
||||
events.push(TrialEvent::Sound("block.trial_spawner.close_shutter"));
|
||||
self.ejecting_loot_table = None;
|
||||
return S::Cooldown;
|
||||
}
|
||||
if self.ejecting_loot_table.is_none() {
|
||||
let tables = &self.active_config().loot_tables_to_eject;
|
||||
self.ejecting_loot_table =
|
||||
spawner::weighted_index(tables.iter().map(|(_, w)| *w), random)
|
||||
.map(|i| tables[i].0.clone());
|
||||
}
|
||||
if let Some(table) = self.ejecting_loot_table.clone()
|
||||
&& eject(&table, random)
|
||||
{
|
||||
events.push(TrialEvent::LevelEvent(3014, pos, 0));
|
||||
}
|
||||
self.detected_players.remove(0);
|
||||
state
|
||||
}
|
||||
S::Cooldown => {
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if !self.detected_players.is_empty() {
|
||||
self.total_mobs_spawned = 0;
|
||||
self.next_mob_spawns_at = 0;
|
||||
S::Active
|
||||
} else if now >= self.cooldown_ends_at {
|
||||
self.is_ominous = false;
|
||||
events.push(TrialEvent::OminousSet(false));
|
||||
self.reset();
|
||||
S::WaitingForPlayers
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `TrialSpawner.spawnMob`: the UUID of the mob added, if one was.
|
||||
fn spawn_mob<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<Uuid>,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> Option<Uuid> {
|
||||
let data = self.next_or_create(random, events).clone();
|
||||
// EntityType.by: an unknown type spawns nothing.
|
||||
let id = data.id().filter(|id| l.entity_exists(id))?;
|
||||
let at = match spawner::read_pos(data.entity.get(&JavaString::from("Pos"))) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
let range = f64::from(self.active_config().spawn_range);
|
||||
let x =
|
||||
f64::from(pos[0]) + (random.next_double() - random.next_double()) * range + 0.5;
|
||||
let y = f64::from(pos[1] + random.next_int_bound(3).unwrap_or(0) - 1);
|
||||
let z =
|
||||
f64::from(pos[2]) + (random.next_double() - random.next_double()) * range + 0.5;
|
||||
[x, y, z]
|
||||
}
|
||||
};
|
||||
// Entity types Horizon cannot create spawn nothing.
|
||||
let (species, width, height, _) = l.mob_type(&id)?;
|
||||
let spawn_box = spawn_selection::spawn_aabb(species, at[0], at[1], at[2], width, height);
|
||||
if !l.no_collision(spawn_box) || !in_line_of_sight(l, center(pos), at) {
|
||||
return None;
|
||||
}
|
||||
let block = at.map(|v| v.floor() as i32);
|
||||
if !spawn_rules::check_spawn_rules(
|
||||
species,
|
||||
l,
|
||||
Reason::TrialSpawner,
|
||||
random,
|
||||
block[0],
|
||||
block[1],
|
||||
block[2],
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
if let Some(rules) = data.custom_spawn_rules
|
||||
&& !SpawnData::valid_position(rules, l, block[0], block[1], block[2])
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let yaw = random.next_float() * 360.0;
|
||||
let placed = spawner::entity_position(species, at);
|
||||
let own = placed.map(|v| v.floor() as i32);
|
||||
let scale = spawner::cube_scale(&id, &data.entity);
|
||||
let bounds = spawn_selection::spawn_box(
|
||||
placed[0],
|
||||
placed[1],
|
||||
placed[2],
|
||||
width * scale,
|
||||
height * scale,
|
||||
);
|
||||
if !spawn_selection::spawn_obstruction(species, l, bounds, &[], own[0], own[1], own[2]) {
|
||||
return None;
|
||||
}
|
||||
let request = SpawnerSpawn {
|
||||
entity: &data.entity,
|
||||
id: &id,
|
||||
position: placed,
|
||||
yaw,
|
||||
finalize: data.unconfigured(),
|
||||
equipment: data.equipment.as_ref(),
|
||||
trial: true,
|
||||
};
|
||||
let uuid = spawn(l, &request)?;
|
||||
let flame = i32::from(self.is_ominous);
|
||||
events.push(TrialEvent::LevelEvent(3011, pos, flame));
|
||||
events.push(TrialEvent::LevelEvent(3012, block, flame));
|
||||
events.push(TrialEvent::EntityPlace(uuid, block));
|
||||
Some(uuid)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Vec3.atCenterOf`.
|
||||
fn center(pos: [i32; 3]) -> [f64; 3] {
|
||||
pos.map(|v| f64::from(v) + 0.5)
|
||||
}
|
||||
/// `TrialSpawner.inLineOfSight`: a VISUAL clip from `to` back to the spawner
|
||||
/// hits nothing, or the spawner's own block.
|
||||
fn in_line_of_sight<L: TrialSpawnerLevel>(l: &L, origin: [f64; 3], to: [f64; 3]) -> bool {
|
||||
match l.visual_hit(to, origin) {
|
||||
None => true,
|
||||
Some(b) => b == origin.map(|v| v.floor() as i32),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tag(snbt: &str) -> Tag {
|
||||
horizon_world::nbt::parse_snbt(snbt).expect("snbt").0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_load_and_save_to_nothing() {
|
||||
let s = TrialSpawner::load_with(&tag("{}"), &|_| None);
|
||||
assert_eq!(s, TrialSpawner::default());
|
||||
assert!(s.save().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_configs_resolve_and_are_saved_by_id() {
|
||||
let breeze = TrialConfig {
|
||||
total_mobs: 2.0,
|
||||
..TrialConfig::default()
|
||||
};
|
||||
let registry =
|
||||
|id: &str| (id == "minecraft:trial_chamber/breeze/normal").then(|| breeze.clone());
|
||||
let s = TrialSpawner::load_with(
|
||||
&tag(
|
||||
r#"{normal_config:"minecraft:trial_chamber/breeze/normal",required_player_range:10}"#,
|
||||
),
|
||||
®istry,
|
||||
);
|
||||
assert_eq!(s.normal.config.total_mobs, 2.0);
|
||||
assert_eq!(s.required_player_range, 10);
|
||||
let saved: Vec<_> = s.save().into_iter().map(|(k, _)| k).collect();
|
||||
assert_eq!(saved, ["normal_config", "required_player_range"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_field_takes_its_default_alone() {
|
||||
let s = TrialSpawner::load_with(
|
||||
&tag(
|
||||
r#"{normal_config:"minecraft:nope",required_player_range:200,target_cooldown_length:5}"#,
|
||||
),
|
||||
&|_| None,
|
||||
);
|
||||
assert_eq!(s.normal, ConfigSlot::default());
|
||||
assert_eq!(s.required_player_range, 14);
|
||||
assert_eq!(s.target_cooldown_length, 5);
|
||||
let c = TrialConfig::decode(&tag(
|
||||
r#"{spawn_range:0,total_mobs:3.0f,spawn_potentials:[{data:{entity:{id:"minecraft:zombie"}},weight:-1},{data:{entity:{id:"minecraft:husk"}},weight:2}]}"#,
|
||||
))
|
||||
.expect("config");
|
||||
assert_eq!(c.spawn_range, 4);
|
||||
assert_eq!(c.total_mobs, 3.0);
|
||||
assert_eq!(c.spawn_potentials.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_floor_the_per_player_additions() {
|
||||
let c = TrialConfig {
|
||||
simultaneous_mobs: 1.0,
|
||||
simultaneous_mobs_added_per_player: 0.5,
|
||||
..TrialConfig::default()
|
||||
};
|
||||
assert_eq!(c.target_simultaneous_mobs(0), 1);
|
||||
assert_eq!(c.target_simultaneous_mobs(1), 1);
|
||||
assert_eq!(c.target_simultaneous_mobs(2), 2);
|
||||
assert_eq!(c.target_total_mobs(3), 12);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,18 @@
|
||||
//! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent
|
||||
//! values and the positions of other entities.
|
||||
use super::{MobWorld, Seen, Species, Who, data};
|
||||
use crate::{blocks::Fluid, collisions::SceneCollisions};
|
||||
use crate::{
|
||||
blocks::{BlockFacts, Fluid},
|
||||
collisions::SceneCollisions,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
position::BlockPos,
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::{BlockCollisionRegistry, DynamicCollisionWorld},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
|
||||
/// Where a target entity is this tick.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -81,38 +88,23 @@ impl MobWorld<'_> {
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
}
|
||||
/// Level.clip with VISUAL shapes and no fluids: true on a miss. Glass
|
||||
/// (`TransparentBlock`) and bars and panes (`IronBarsBlock`) have no
|
||||
/// visual shape; mud, soul sand and powder snow look like full blocks.
|
||||
/// Level.clip with VISUAL shapes and no fluids: true on a miss.
|
||||
pub fn visual_clear_between(&self, from: Vec3, to: Vec3) -> bool {
|
||||
self.visual_clip(from, to) == Some(None)
|
||||
}
|
||||
/// Level.clip with VISUAL shapes and no fluids: the block the segment
|
||||
/// first hits, if it does.
|
||||
pub fn visual_hit(&self, from: Vec3, to: Vec3) -> Option<[i32; 3]> {
|
||||
self.visual_clip(from, to).flatten()
|
||||
}
|
||||
fn visual_clip(&self, from: Vec3, to: Vec3) -> Option<Option<[i32; 3]>> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
let full = horizon_core::geometry::Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if self.facts.is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let name = self.facts.get(state).name.trim_start_matches("minecraft:");
|
||||
if name.ends_with("glass") || name.ends_with("glass_pane") || name.ends_with("_bars") {
|
||||
return None;
|
||||
}
|
||||
if matches!(name, "mud" | "soul_sand" | "powder_snow") {
|
||||
return full
|
||||
.move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))
|
||||
.clip(from, to)
|
||||
.map(|_| ());
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|_| ())
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
let state = |x, y, z| self.world.block(x, y, z);
|
||||
visual_clip(self.facts, self.collision, &mut scene, &state, from, to)
|
||||
}
|
||||
/// Level.clip with COLLIDER shapes and no fluids: where the segment
|
||||
/// first hits a block, if it does.
|
||||
@@ -260,3 +252,42 @@ impl MobWorld<'_> {
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Level.clip with VISUAL shapes and no fluids: the block the segment first
|
||||
/// hits, None inside when it hits nothing and outside when the segment is
|
||||
/// too long to walk. Glass and copper grates (`TransparentBlock`) and bars and panes
|
||||
/// (`IronBarsBlock`) have no visual shape; mud, soul sand and powder snow
|
||||
/// look like full blocks.
|
||||
pub fn visual_clip<W: DynamicCollisionWorld>(
|
||||
facts: &BlockFacts,
|
||||
collision: &BlockCollisionRegistry,
|
||||
scene: &mut W,
|
||||
state: &dyn Fn(i32, i32, i32) -> BlockStateId,
|
||||
from: Vec3,
|
||||
to: Vec3,
|
||||
) -> Option<Option<[i32; 3]>> {
|
||||
let full = Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let id = state(p.x, p.y, p.z);
|
||||
if facts.is_air(id) {
|
||||
return None;
|
||||
}
|
||||
let name = facts.get(id).name.trim_start_matches("minecraft:");
|
||||
if name.ends_with("glass")
|
||||
|| name.ends_with("glass_pane")
|
||||
|| name.ends_with("_bars")
|
||||
|| name.ends_with("copper_grate")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(name, "mud" | "soul_sand" | "powder_snow") {
|
||||
return full
|
||||
.move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))
|
||||
.clip(from, to)
|
||||
.map(|_| [p.x, p.y, p.z]);
|
||||
}
|
||||
let shape = collision.collision_shape(scene, id, [p.x, p.y, p.z]).ok()?;
|
||||
shape.clip(from, to, p).map(|_| [p.x, p.y, p.z])
|
||||
});
|
||||
result.ok()
|
||||
}
|
||||
|
||||
@@ -113,6 +113,7 @@ pub enum MotionEvent {
|
||||
enabled: bool,
|
||||
},
|
||||
Health(crate::health::HealthEvent),
|
||||
/// `LivingEntity.handleDamageEvent`: the hurt sound the player hears.
|
||||
HurtSound(&'static str),
|
||||
Fall(crate::landing::FallEvent),
|
||||
Recorded {
|
||||
@@ -2109,6 +2110,47 @@ mod tests {
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
// A shield that takes the whole arrow: onBlocked's sound, no damage
|
||||
// event, so the player hears no hurt sound.
|
||||
use horizon_world::blocking_rules::{BlockingRules, DamageReduction, ItemDamageFunction};
|
||||
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
|
||||
let source = resources.health.damage.id("minecraft:arrow").unwrap();
|
||||
let shield = crate::health::Blocking {
|
||||
rules: BlockingRules {
|
||||
delay_seconds: 0.25,
|
||||
disable_scale: 1.0,
|
||||
reductions: vec![DamageReduction {
|
||||
horizontal_angle: 90.0,
|
||||
types: None,
|
||||
base: 0.0,
|
||||
factor: 1.0,
|
||||
}],
|
||||
item_damage: ItemDamageFunction {
|
||||
threshold: 3.0,
|
||||
base: 1.0,
|
||||
factor: 1.0,
|
||||
},
|
||||
},
|
||||
bypassed: false,
|
||||
pierce: false,
|
||||
angle: 0.0,
|
||||
};
|
||||
let outcome = player
|
||||
.hurt_blocking(
|
||||
&resources.health,
|
||||
Default::default(),
|
||||
source,
|
||||
4.0,
|
||||
Some(shield),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!outcome.hurt && outcome.sound && outcome.blocked == 4.0);
|
||||
assert!(
|
||||
!player
|
||||
.events
|
||||
.iter()
|
||||
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
|
||||
);
|
||||
}
|
||||
|
||||
/// Footsteps on the prepared vanilla resources, when they are present:
|
||||
|
||||
@@ -34,6 +34,7 @@ pub enum Screen {
|
||||
pings: Pings,
|
||||
/// Worlds announced on the local network, listed after the servers.
|
||||
lan: Scanner,
|
||||
scroll: crate::ui::Scroll,
|
||||
},
|
||||
/// Add (index None) or edit a server entry.
|
||||
Edit {
|
||||
@@ -117,6 +118,60 @@ fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// JoinMultiplayerScreen's `HeaderAndFooterLayout(33, 60)`.
|
||||
const HEADER: f32 = 33.0;
|
||||
const FOOTER: f32 = 60.0;
|
||||
/// ServerSelectionList: rows 305 wide and 36 high.
|
||||
const ROW_WIDTH: f32 = 305.0;
|
||||
const ROW_HEIGHT: f32 = 36.0;
|
||||
/// One row of the list: the saved servers, the LAN header, the LAN games.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Row {
|
||||
Server(usize),
|
||||
LanHeader,
|
||||
Lan(usize),
|
||||
}
|
||||
/// The list's top and bottom and its rows' left edge (`getRowLeft`).
|
||||
fn list_area(w: f32, h: f32) -> (f32, f32, f32) {
|
||||
(
|
||||
HEADER,
|
||||
h - FOOTER,
|
||||
(w / 2.0).floor() - (ROW_WIDTH / 2.0).floor(),
|
||||
)
|
||||
}
|
||||
fn rows(servers: usize, lan: usize) -> impl Iterator<Item = Row> {
|
||||
(0..servers)
|
||||
.map(Row::Server)
|
||||
.chain(std::iter::once(Row::LanHeader))
|
||||
.chain((0..lan).map(Row::Lan))
|
||||
}
|
||||
/// `contentHeight`: the rows and 4 pixels of padding.
|
||||
fn content_height(servers: usize, lan: usize) -> f32 {
|
||||
(servers + 1 + lan) as f32 * ROW_HEIGHT + 4.0
|
||||
}
|
||||
/// The row under `(x, y)` (`getEntryAtPosition`), scrolled by `scroll`.
|
||||
fn row_at(
|
||||
servers: usize,
|
||||
lan: usize,
|
||||
(x, y): (f32, f32),
|
||||
size: (f32, f32),
|
||||
scroll: f32,
|
||||
) -> Option<Row> {
|
||||
let (top, bottom, left) = list_area(size.0, size.1);
|
||||
if y < top || y >= bottom || x < left || x >= left + ROW_WIDTH {
|
||||
return None;
|
||||
}
|
||||
let index = ((y - top - 2.0 + scroll.trunc()) / ROW_HEIGHT).floor();
|
||||
if index < 0.0 {
|
||||
return None;
|
||||
}
|
||||
rows(servers, lan).nth(index as usize)
|
||||
}
|
||||
/// `LoadingDotsText.get`.
|
||||
fn loading_dots(millis: u128) -> &'static str {
|
||||
["O o o", "o O o", "o o O", "o O o"][(millis / 300 % 4) as usize]
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
/// The address of list row `row` (saved servers, then LAN games).
|
||||
pub fn address_of(&self, row: usize) -> Option<String> {
|
||||
@@ -134,6 +189,7 @@ impl Screen {
|
||||
selected: None,
|
||||
pings,
|
||||
lan: Scanner::start(),
|
||||
scroll: crate::ui::Scroll::default(),
|
||||
}
|
||||
}
|
||||
pub fn buttons(&self, w: f32, h: f32) -> Vec<ButtonSpec> {
|
||||
@@ -141,44 +197,75 @@ impl Screen {
|
||||
(x, y, bw, label.to_owned(), enabled, id)
|
||||
};
|
||||
match self {
|
||||
// JoinMultiplayerScreen's two button rows.
|
||||
Self::List { selected, .. } => vec![
|
||||
b(
|
||||
w / 2.0 - 154.0,
|
||||
h - 52.0,
|
||||
100.0,
|
||||
"Join Server",
|
||||
selected.is_some(),
|
||||
40,
|
||||
),
|
||||
b(
|
||||
w / 2.0 - 50.0,
|
||||
h - 52.0,
|
||||
100.0,
|
||||
"Direct Connection",
|
||||
true,
|
||||
41,
|
||||
),
|
||||
b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42),
|
||||
b(
|
||||
w / 2.0 - 154.0,
|
||||
h - 28.0,
|
||||
74.0,
|
||||
"Edit",
|
||||
selected.is_some(),
|
||||
43,
|
||||
),
|
||||
b(
|
||||
w / 2.0 - 76.0,
|
||||
h - 28.0,
|
||||
74.0,
|
||||
"Delete",
|
||||
selected.is_some(),
|
||||
44,
|
||||
),
|
||||
b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45),
|
||||
b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46),
|
||||
],
|
||||
// JoinMultiplayerScreen's footer: two rows of buttons, 4 apart,
|
||||
// centred in the 60-pixel footer. Join needs a server or LAN game
|
||||
// selected (onSelectedChange), Edit and Delete a saved server.
|
||||
Self::List {
|
||||
servers, selected, ..
|
||||
} => {
|
||||
let (w, h) = (w.ceil(), h.ceil());
|
||||
let x = ((w - 308.0) / 2.0).floor();
|
||||
let saved = selected.is_some_and(|i| i < servers.len());
|
||||
let label = |key: &str, fallback: &str| crate::lang::get_or(key, fallback);
|
||||
vec![
|
||||
b(
|
||||
x,
|
||||
h - 52.0,
|
||||
100.0,
|
||||
&label("selectServer.select", "Join Server"),
|
||||
selected.is_some(),
|
||||
40,
|
||||
),
|
||||
b(
|
||||
x + 104.0,
|
||||
h - 52.0,
|
||||
100.0,
|
||||
&label("selectServer.direct", "Direct Connection"),
|
||||
true,
|
||||
41,
|
||||
),
|
||||
b(
|
||||
x + 208.0,
|
||||
h - 52.0,
|
||||
100.0,
|
||||
&label("selectServer.add", "Add Server"),
|
||||
true,
|
||||
42,
|
||||
),
|
||||
b(
|
||||
x,
|
||||
h - 28.0,
|
||||
74.0,
|
||||
&label("selectServer.edit", "Edit"),
|
||||
saved,
|
||||
43,
|
||||
),
|
||||
b(
|
||||
x + 78.0,
|
||||
h - 28.0,
|
||||
74.0,
|
||||
&label("selectServer.delete", "Delete"),
|
||||
saved,
|
||||
44,
|
||||
),
|
||||
b(
|
||||
x + 156.0,
|
||||
h - 28.0,
|
||||
74.0,
|
||||
&label("selectServer.refresh", "Refresh"),
|
||||
true,
|
||||
45,
|
||||
),
|
||||
b(
|
||||
x + 234.0,
|
||||
h - 28.0,
|
||||
74.0,
|
||||
&label("gui.back", "Back"),
|
||||
true,
|
||||
46,
|
||||
),
|
||||
]
|
||||
}
|
||||
Self::Edit { address, .. } => vec![
|
||||
b(
|
||||
w / 2.0 - 100.0,
|
||||
@@ -314,7 +401,7 @@ impl Screen {
|
||||
}
|
||||
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) {
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| {
|
||||
let tw = HudBatch::text_width(atlas, text);
|
||||
batch.text(atlas, text, (w - tw) / 2.0, y, color, true);
|
||||
@@ -325,121 +412,205 @@ impl Screen {
|
||||
selected,
|
||||
pings,
|
||||
lan,
|
||||
scroll,
|
||||
} => {
|
||||
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));
|
||||
let (w, h) = (w.ceil(), h.ceil());
|
||||
let title = crate::lang::get_or("multiplayer.title", "Play Multiplayer");
|
||||
// The header's StringWidget, centred in its 33 pixels.
|
||||
let tw = HudBatch::text_width(atlas, &title);
|
||||
let tx = ((w - tw.ceil()) / 2.0).floor();
|
||||
batch.text(
|
||||
atlas,
|
||||
&title,
|
||||
tx,
|
||||
((HEADER - 9.0) / 2.0).floor(),
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
let games = lan.games();
|
||||
let (top, bottom, left) = list_area(w, h);
|
||||
let content = content_height(servers.len(), games.len());
|
||||
let mut scroll = *scroll;
|
||||
scroll.clamp(top, bottom, content);
|
||||
// AbstractSelectionList.extractWidgetRenderState: background,
|
||||
// the rows clipped to the list, separators, scrollbar.
|
||||
crate::ui::list_background(batch, atlas, top, bottom, false);
|
||||
let first = batch.vertices.len();
|
||||
let pings = pings.lock().unwrap();
|
||||
for (i, server) in servers.iter().enumerate() {
|
||||
let y = 36.0 + i as f32 * 36.0;
|
||||
if y + 36.0 > h - 64.0 {
|
||||
break;
|
||||
let millis = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis());
|
||||
let gray = rgba(128, 128, 128, 255);
|
||||
for (i, row) in rows(servers.len(), games.len()).enumerate() {
|
||||
let y = top + 2.0 - scroll.amount.trunc() + i as f32 * ROW_HEIGHT;
|
||||
if y + ROW_HEIGHT < top || y > bottom {
|
||||
continue;
|
||||
}
|
||||
let x = w / 2.0 - 152.0;
|
||||
crate::widgets::target_as(
|
||||
[x - 2.0, y - 2.0, 306.0, 36.0],
|
||||
crate::widgets::Kind::Row,
|
||||
);
|
||||
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.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX);
|
||||
batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false);
|
||||
let (line, right, color) = match pings.get(&server.ip) {
|
||||
Some(Ping::Ok {
|
||||
motd, players, ms, ..
|
||||
}) => (
|
||||
motd.lines().next().unwrap_or("").to_owned(),
|
||||
format!("{players} {ms} ms"),
|
||||
rgba(128, 128, 128, 255),
|
||||
),
|
||||
Some(Ping::Failed(_)) => (
|
||||
"Can't connect to server".to_owned(),
|
||||
String::new(),
|
||||
rgba(170, 0, 0, 255),
|
||||
),
|
||||
_ => (
|
||||
"Pinging...".to_owned(),
|
||||
String::new(),
|
||||
rgba(128, 128, 128, 255),
|
||||
),
|
||||
let index = match row {
|
||||
Row::Server(k) => Some(k),
|
||||
Row::Lan(k) => Some(servers.len() + k),
|
||||
Row::LanHeader => None,
|
||||
};
|
||||
batch.text(atlas, &line, x + 35.0, y + 12.0, color, false);
|
||||
batch.text(
|
||||
atlas,
|
||||
&server.ip,
|
||||
x + 35.0,
|
||||
y + 22.0,
|
||||
rgba(96, 96, 96, 255),
|
||||
false,
|
||||
);
|
||||
if !right.is_empty() {
|
||||
let tw = HudBatch::text_width(atlas, &right);
|
||||
batch.text(
|
||||
atlas,
|
||||
&right,
|
||||
x + 300.0 - tw,
|
||||
y + 1.0,
|
||||
rgba(128, 128, 128, 255),
|
||||
false,
|
||||
if index.is_some()
|
||||
&& y + ROW_HEIGHT / 2.0 > top
|
||||
&& y + ROW_HEIGHT / 2.0 < bottom
|
||||
{
|
||||
crate::widgets::target_as(
|
||||
[left, y, ROW_WIDTH, ROW_HEIGHT],
|
||||
crate::widgets::Kind::Row,
|
||||
);
|
||||
}
|
||||
}
|
||||
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;
|
||||
crate::widgets::target_as(
|
||||
[x - 2.0, y - 2.0, 306.0, 36.0],
|
||||
crate::widgets::Kind::Row,
|
||||
);
|
||||
if *selected == Some(i) {
|
||||
// extractSelection: a white outline round black (the list
|
||||
// has focus once a row is clicked).
|
||||
if index.is_some() && *selected == index {
|
||||
batch.fill(atlas, left, y, ROW_WIDTH, ROW_HEIGHT, u32::MAX);
|
||||
batch.fill(
|
||||
atlas,
|
||||
x - 2.0,
|
||||
y - 2.0,
|
||||
306.0,
|
||||
36.0,
|
||||
rgba(128, 128, 128, 255),
|
||||
left + 1.0,
|
||||
y + 1.0,
|
||||
ROW_WIDTH - 2.0,
|
||||
ROW_HEIGHT - 2.0,
|
||||
rgba(0, 0, 0, 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,
|
||||
"No servers yet: add one or use Direct Connection",
|
||||
h / 2.0 - 20.0,
|
||||
rgba(160, 160, 160, 255),
|
||||
);
|
||||
// Entry content: 2 pixels in from the row.
|
||||
let (cx, cy) = (left + 2.0, y + 2.0);
|
||||
match row {
|
||||
Row::Server(k) => {
|
||||
let server = &servers[k];
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
"misc/unknown_server",
|
||||
cx,
|
||||
cy,
|
||||
32.0,
|
||||
32.0,
|
||||
u32::MAX,
|
||||
);
|
||||
batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, false);
|
||||
// OnlineServerEntry: up to two lines of MOTD, the
|
||||
// player count left of the status icon.
|
||||
let (motd, status, motd_color, icon) = match pings.get(&server.ip) {
|
||||
Some(Ping::Ok {
|
||||
motd, players, ms, ..
|
||||
}) => (
|
||||
motd.clone(),
|
||||
players.clone(),
|
||||
gray,
|
||||
format!(
|
||||
"server_list/ping_{}",
|
||||
match ms {
|
||||
0..150 => 5,
|
||||
150..300 => 4,
|
||||
300..600 => 3,
|
||||
600..1000 => 2,
|
||||
_ => 1,
|
||||
}
|
||||
),
|
||||
),
|
||||
Some(Ping::Failed(_)) => (
|
||||
crate::lang::get_or(
|
||||
"multiplayer.status.cannot_connect",
|
||||
"Can't connect to server",
|
||||
),
|
||||
String::new(),
|
||||
rgba(255, 0, 0, 255),
|
||||
"server_list/unreachable".to_owned(),
|
||||
),
|
||||
_ => {
|
||||
// The pinging bars bounce, offset by the row.
|
||||
let frame = (millis / 100 + i as u128 * 2) & 7;
|
||||
let frame = if frame > 4 { 8 - frame } else { frame };
|
||||
(
|
||||
crate::lang::get_or(
|
||||
"multiplayer.status.pinging",
|
||||
"Pinging...",
|
||||
),
|
||||
String::new(),
|
||||
gray,
|
||||
format!("server_list/pinging_{}", frame + 1),
|
||||
)
|
||||
}
|
||||
};
|
||||
for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas)
|
||||
.iter()
|
||||
.take(2)
|
||||
.enumerate()
|
||||
{
|
||||
batch.text(
|
||||
atlas,
|
||||
line,
|
||||
cx + 35.0,
|
||||
cy + 12.0 + 9.0 * n as f32,
|
||||
motd_color,
|
||||
false,
|
||||
);
|
||||
}
|
||||
let icon_x = cx + ROW_WIDTH - 4.0 - 15.0;
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
&format!("gui/sprites/{icon}"),
|
||||
icon_x,
|
||||
cy,
|
||||
10.0,
|
||||
8.0,
|
||||
u32::MAX,
|
||||
);
|
||||
if !status.is_empty() {
|
||||
let sw = HudBatch::text_width(atlas, &status).ceil();
|
||||
batch.text(
|
||||
atlas,
|
||||
&status,
|
||||
icon_x - sw - 5.0,
|
||||
cy + 1.0,
|
||||
gray,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
Row::LanHeader => {
|
||||
// LANHeader's LoadingDotsWidget: the label, then
|
||||
// the dots on its last line, both centred.
|
||||
let label = crate::lang::get_or(
|
||||
"lanServer.scanning",
|
||||
"Scanning for games on your local network",
|
||||
);
|
||||
let middle = cx + ((ROW_WIDTH - 4.0) / 2.0).floor();
|
||||
let lw = HudBatch::text_width(atlas, &label).ceil();
|
||||
let lx = middle - (lw / 2.0).floor();
|
||||
let centre = lx + (lw / 2.0).floor();
|
||||
batch.text(atlas, &label, lx, cy + 2.0, u32::MAX, false);
|
||||
let dots = loading_dots(millis);
|
||||
let dw = HudBatch::text_width(atlas, dots).ceil();
|
||||
batch.text(
|
||||
atlas,
|
||||
dots,
|
||||
centre - (dw / 2.0).floor(),
|
||||
cy + 28.0 - 9.0 - 2.0,
|
||||
gray,
|
||||
false,
|
||||
);
|
||||
}
|
||||
Row::Lan(k) => {
|
||||
let game = &games[k];
|
||||
let header = crate::lang::get_or("lanServer.title", "LAN World");
|
||||
batch.text(atlas, &header, cx + 35.0, cy + 1.0, u32::MAX, false);
|
||||
batch.text(atlas, &game.motd, cx + 35.0, cy + 12.0, gray, false);
|
||||
batch.text(atlas, &game.address, cx + 35.0, cy + 23.0, gray, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
batch.clip_since(first, 0.0, top, w, bottom);
|
||||
crate::ui::separators(batch, atlas, top, bottom, false);
|
||||
crate::ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
left + ROW_WIDTH + 8.0,
|
||||
top,
|
||||
bottom,
|
||||
content,
|
||||
scroll.amount,
|
||||
);
|
||||
}
|
||||
Self::Edit {
|
||||
index,
|
||||
@@ -583,19 +754,36 @@ impl Screen {
|
||||
servers,
|
||||
selected,
|
||||
lan,
|
||||
scroll,
|
||||
..
|
||||
},
|
||||
None,
|
||||
) => {
|
||||
let index = ((y - 36.0) / 36.0).floor();
|
||||
if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 {
|
||||
let index = index as usize;
|
||||
if let Some(address) = entry_address(servers, lan, index) {
|
||||
if *selected == Some(index) {
|
||||
return Outcome::Connect(address);
|
||||
}
|
||||
*selected = Some(index);
|
||||
let (w, h) = (w.ceil(), h.ceil());
|
||||
let games = lan.games().len();
|
||||
let (top, bottom, left) = list_area(w, h);
|
||||
let content = content_height(servers.len(), games);
|
||||
if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) {
|
||||
return Outcome::None;
|
||||
}
|
||||
// Clicking a selected row again joins it; the LAN header
|
||||
// takes the click without anything to join.
|
||||
let index = match row_at(servers.len(), games, (x, y), (w, h), scroll.amount) {
|
||||
Some(Row::Server(k)) => Some(k),
|
||||
Some(Row::Lan(k)) => Some(servers.len() + k),
|
||||
Some(Row::LanHeader) => {
|
||||
*selected = None;
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(index) = index
|
||||
&& let Some(address) = entry_address(servers, lan, index)
|
||||
{
|
||||
if *selected == Some(index) {
|
||||
return Outcome::Connect(address);
|
||||
}
|
||||
*selected = Some(index);
|
||||
}
|
||||
}
|
||||
(
|
||||
@@ -648,6 +836,45 @@ impl Screen {
|
||||
}
|
||||
Outcome::None
|
||||
}
|
||||
/// The mouse wheel over the server list (`scrollRate`: half a row).
|
||||
pub fn wheel(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) {
|
||||
if let Self::List {
|
||||
servers,
|
||||
lan,
|
||||
scroll,
|
||||
..
|
||||
} = self
|
||||
{
|
||||
let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil());
|
||||
if cursor.1 >= top && cursor.1 < bottom {
|
||||
let content = content_height(servers.len(), lan.games().len());
|
||||
scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The pointer moved: a held scrollbar follows it.
|
||||
pub fn drag(&mut self, y: f32, size: (f32, f32)) {
|
||||
if let Self::List {
|
||||
servers,
|
||||
lan,
|
||||
scroll,
|
||||
..
|
||||
} = self
|
||||
{
|
||||
let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil());
|
||||
scroll.drag(
|
||||
y,
|
||||
top,
|
||||
bottom,
|
||||
content_height(servers.len(), lan.games().len()),
|
||||
);
|
||||
}
|
||||
}
|
||||
pub fn release(&mut self) {
|
||||
if let Self::List { scroll, .. } = self {
|
||||
scroll.release();
|
||||
}
|
||||
}
|
||||
fn focused_field(&mut self) -> Option<&mut String> {
|
||||
match self {
|
||||
Self::Edit {
|
||||
@@ -756,3 +983,49 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec<String> {
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_lan_header_follows_the_saved_servers() {
|
||||
let all: Vec<Row> = rows(2, 1).collect();
|
||||
assert_eq!(
|
||||
all,
|
||||
[Row::Server(0), Row::Server(1), Row::LanHeader, Row::Lan(0)]
|
||||
);
|
||||
// No saved servers: the list is the scanning header alone.
|
||||
assert_eq!(rows(0, 0).collect::<Vec<_>>(), [Row::LanHeader]);
|
||||
assert_eq!(content_height(0, 0), 40.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_sit_two_pixels_under_the_header_and_scroll_with_the_list() {
|
||||
// 427x240 GUI: the list spans 33..180, rows 305 wide from x 61.
|
||||
let size = (427.0, 240.0);
|
||||
assert_eq!(list_area(size.0, size.1), (33.0, 180.0, 61.0));
|
||||
assert_eq!(row_at(3, 0, (100.0, 35.0), size, 0.0), Some(Row::Server(0)));
|
||||
assert_eq!(row_at(3, 0, (100.0, 70.9), size, 0.0), Some(Row::Server(0)));
|
||||
assert_eq!(row_at(3, 0, (100.0, 71.0), size, 0.0), Some(Row::Server(1)));
|
||||
assert_eq!(
|
||||
row_at(3, 0, (100.0, 35.0), size, 36.0),
|
||||
Some(Row::Server(1))
|
||||
);
|
||||
assert_eq!(
|
||||
row_at(3, 0, (100.0, 143.0), size, 0.0),
|
||||
Some(Row::LanHeader)
|
||||
);
|
||||
assert_eq!(row_at(3, 0, (60.0, 40.0), size, 0.0), None);
|
||||
assert_eq!(row_at(3, 0, (100.0, 32.0), size, 0.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_dots_step_every_300_ms() {
|
||||
let frames: Vec<&str> = [0, 299, 300, 600, 900, 1200].map(loading_dots).to_vec();
|
||||
assert_eq!(
|
||||
frames,
|
||||
["O o o", "O o o", "o O o", "o o O", "o O o", "O o o"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1699,7 +1699,11 @@ impl OptionsUi {
|
||||
}
|
||||
if self.page() == Page::Packs {
|
||||
let mut events = Vec::new();
|
||||
if drag || right {
|
||||
if drag {
|
||||
self.packs(atlas, size).drag(y as f64);
|
||||
return events;
|
||||
}
|
||||
if right {
|
||||
return events;
|
||||
}
|
||||
let m = crate::screen_draw::Measure(&atlas.font);
|
||||
@@ -1862,6 +1866,9 @@ impl OptionsUi {
|
||||
}
|
||||
pub fn release(&mut self) -> Vec<Event> {
|
||||
self.scrollbar_drag_y = None;
|
||||
if let Some(p) = &mut self.pack_screen {
|
||||
p.release();
|
||||
}
|
||||
// AbstractSliderButton suppresses the press sound and plays once on
|
||||
// release, even if the pointer has left the widget or its value stayed.
|
||||
let slider = self.dragging.take().is_some();
|
||||
|
||||
@@ -136,6 +136,8 @@ struct List {
|
||||
selected: Option<usize>,
|
||||
/// The list has a focused child (possibly an entry it no longer holds).
|
||||
focused: bool,
|
||||
/// The pointer's last y while the scrollbar is held (`scrolling`).
|
||||
held: Option<f64>,
|
||||
}
|
||||
impl List {
|
||||
fn new(selected_side: bool, height: i32) -> Self {
|
||||
@@ -149,6 +151,7 @@ impl List {
|
||||
entries: Vec::new(),
|
||||
selected: None,
|
||||
focused: false,
|
||||
held: None,
|
||||
}
|
||||
}
|
||||
fn bottom(&self) -> i32 {
|
||||
@@ -244,6 +247,21 @@ impl List {
|
||||
fn scroller_height(&self) -> i32 {
|
||||
((self.height * self.height) as f32 / self.content_height() as f32) as i32
|
||||
}
|
||||
/// `AbstractScrollArea.mouseDragged` while the scrollbar is held.
|
||||
fn drag(&mut self, y: f64) {
|
||||
let Some(last) = self.held else { return };
|
||||
if y < self.y as f64 {
|
||||
self.set_scroll(0.0);
|
||||
} else if y > self.bottom() as f64 {
|
||||
self.set_scroll(self.max_scroll() as f64);
|
||||
} else {
|
||||
let max = self.max_scroll().max(1) as f64;
|
||||
let bar = self.scroller_height().clamp(32, self.height - 8);
|
||||
let scale = (max / (self.height - bar) as f64).max(1.0);
|
||||
self.set_scroll(self.scroll + (y - last) * scale);
|
||||
}
|
||||
self.held = Some(y);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -490,6 +508,13 @@ impl PackScreen {
|
||||
&& x <= (l.scroll_bar_x() + 6) as f64
|
||||
&& y >= l.y as f64
|
||||
&& y < l.bottom() as f64;
|
||||
// updateScrolling: a press on the scroller holds it.
|
||||
if scrolling {
|
||||
self.lists[side].held = Some(y);
|
||||
self.set_focus(Focus::List(side));
|
||||
return Action::None;
|
||||
}
|
||||
let l = &self.lists[side];
|
||||
let hit = l.entry_at(x as i32, y as i32);
|
||||
let mut took = false;
|
||||
if let Some(i) = hit {
|
||||
@@ -516,7 +541,7 @@ impl PackScreen {
|
||||
}
|
||||
}
|
||||
}
|
||||
if took || scrolling {
|
||||
if took {
|
||||
self.set_focus(Focus::List(side));
|
||||
}
|
||||
return Action::None;
|
||||
@@ -669,6 +694,18 @@ impl PackScreen {
|
||||
false
|
||||
}
|
||||
/// The mouse wheel (`AbstractScrollArea.mouseScrolled`).
|
||||
/// The pointer moved with the button held: a held scrollbar follows it.
|
||||
pub fn drag(&mut self, y: f64) {
|
||||
for l in &mut self.lists {
|
||||
l.drag(y);
|
||||
}
|
||||
}
|
||||
/// `onRelease`.
|
||||
pub fn release(&mut self) {
|
||||
for l in &mut self.lists {
|
||||
l.held = None;
|
||||
}
|
||||
}
|
||||
pub fn scroll(&mut self, x: f64, y: f64, amount: f64) {
|
||||
if self.confirm.is_some() || self.search.contains(x, y) {
|
||||
return;
|
||||
|
||||
@@ -646,8 +646,31 @@ impl ClientBook {
|
||||
/// displays it has (`RecipeManager.listDisplaysForRecipe`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RecipeIndex {
|
||||
/// Recipe id -> (special, display count, first display id).
|
||||
recipes: std::collections::BTreeMap<String, (bool, usize, i32)>,
|
||||
recipes: std::collections::BTreeMap<String, Known>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct Known {
|
||||
special: bool,
|
||||
displays: usize,
|
||||
first_display: i32,
|
||||
/// `RecipeDisplay.craftingStation`: the workstation item of its displays.
|
||||
station: &'static str,
|
||||
/// `Recipe.showNotification`: unlocking it shows the `RecipeToast`.
|
||||
notify: bool,
|
||||
/// `result.id`, for the recipes the book doesn't list.
|
||||
result: Option<String>,
|
||||
}
|
||||
/// `RecipeDisplay.craftingStation` of a recipe type.
|
||||
fn crafting_station(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"minecraft:smelting" => "minecraft:furnace",
|
||||
"minecraft:blasting" => "minecraft:blast_furnace",
|
||||
"minecraft:smoking" => "minecraft:smoker",
|
||||
"minecraft:campfire_cooking" => "minecraft:campfire",
|
||||
"minecraft:stonecutting" => "minecraft:stonecutter",
|
||||
"minecraft:smithing_transform" | "minecraft:smithing_trim" => "minecraft:smithing_table",
|
||||
_ => "minecraft:crafting_table",
|
||||
}
|
||||
}
|
||||
impl RecipeIndex {
|
||||
/// Reads `data/minecraft/recipe/*.json` under `root`.
|
||||
@@ -685,13 +708,23 @@ impl RecipeIndex {
|
||||
} else {
|
||||
1
|
||||
};
|
||||
recipes.insert(format!("minecraft:{stem}"), (special, displays, 0));
|
||||
recipes.insert(
|
||||
format!("minecraft:{stem}"),
|
||||
Known {
|
||||
special,
|
||||
displays,
|
||||
first_display: 0,
|
||||
station: crafting_station(kind),
|
||||
notify: v["show_notification"].as_bool().unwrap_or(true),
|
||||
result: v["result"]["id"].as_str().map(str::to_owned),
|
||||
},
|
||||
);
|
||||
}
|
||||
// RecipeManager keeps its recipes sorted by id and numbers the displays in that order.
|
||||
let mut next = 0;
|
||||
for r in recipes.values_mut() {
|
||||
r.2 = next;
|
||||
next += r.1 as i32;
|
||||
r.first_display = next;
|
||||
next += r.displays as i32;
|
||||
}
|
||||
Self { recipes }
|
||||
}
|
||||
@@ -699,10 +732,19 @@ impl RecipeIndex {
|
||||
self.recipes.contains_key(id)
|
||||
}
|
||||
pub fn special(&self, id: &str) -> bool {
|
||||
self.recipes.get(id).is_some_and(|r| r.0)
|
||||
self.recipes.get(id).is_some_and(|r| r.special)
|
||||
}
|
||||
pub fn displays(&self, id: &str) -> usize {
|
||||
self.recipes.get(id).map_or(0, |r| r.1)
|
||||
self.recipes.get(id).map_or(0, |r| r.displays)
|
||||
}
|
||||
/// The crafting station shown on its displays' toast, when unlocking it
|
||||
/// shows one (`Recipe.showNotification`).
|
||||
pub fn toast_station(&self, id: &str) -> Option<&'static str> {
|
||||
self.recipes.get(id).filter(|r| r.notify).map(|r| r.station)
|
||||
}
|
||||
/// The result item id its file names (none for trims).
|
||||
pub fn result(&self, id: &str) -> Option<&str> {
|
||||
self.recipes.get(id).and_then(|r| r.result.as_deref())
|
||||
}
|
||||
/// Every recipe id, in id order.
|
||||
pub fn ids(&self) -> impl Iterator<Item = &String> {
|
||||
@@ -710,10 +752,15 @@ impl RecipeIndex {
|
||||
}
|
||||
/// The display ids of a recipe (none for a special one).
|
||||
pub fn display_ids(&self, id: &str) -> std::ops::Range<i32> {
|
||||
self.recipes.get(id).map_or(0..0, |r| r.2..r.2 + r.1 as i32)
|
||||
self.recipes.get(id).map_or(0..0, |r| {
|
||||
r.first_display..r.first_display + r.displays as i32
|
||||
})
|
||||
}
|
||||
pub fn first_display(&self, id: &str) -> Option<i32> {
|
||||
self.recipes.get(id).filter(|r| r.1 > 0).map(|r| r.2)
|
||||
self.recipes
|
||||
.get(id)
|
||||
.filter(|r| r.displays > 0)
|
||||
.map(|r| r.first_display)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -836,6 +883,57 @@ mod tests {
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
#[test]
|
||||
fn the_index_knows_each_recipes_toast_station_and_result() {
|
||||
let root = std::env::temp_dir().join(format!("horizon-toast-index-{}", std::process::id()));
|
||||
let dir = root.join("data/minecraft/recipe");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (name, json) in [
|
||||
(
|
||||
"stick",
|
||||
r#"{"type":"minecraft:crafting_shaped","result":{"id":"minecraft:stick"}}"#,
|
||||
),
|
||||
(
|
||||
"crafting_table",
|
||||
r#"{"type":"minecraft:crafting_shaped","show_notification":false,"result":{"id":"minecraft:crafting_table"}}"#,
|
||||
),
|
||||
(
|
||||
"cooked_beef_from_campfire_cooking",
|
||||
r#"{"type":"minecraft:campfire_cooking","result":{"id":"minecraft:cooked_beef"}}"#,
|
||||
),
|
||||
(
|
||||
"stone_slab_from_stonecutting",
|
||||
r#"{"type":"minecraft:stonecutting","result":{"id":"minecraft:stone_slab"}}"#,
|
||||
),
|
||||
(
|
||||
"coast_trim",
|
||||
r#"{"type":"minecraft:smithing_trim","pattern":"minecraft:coast"}"#,
|
||||
),
|
||||
] {
|
||||
std::fs::write(dir.join(format!("{name}.json")), json).unwrap();
|
||||
}
|
||||
let index = RecipeIndex::load(&root);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
let toast = |id: &str| (index.toast_station(id), index.result(id));
|
||||
assert_eq!(
|
||||
toast("minecraft:stick"),
|
||||
(Some("minecraft:crafting_table"), Some("minecraft:stick"))
|
||||
);
|
||||
// show_notification: false unlocks silently.
|
||||
assert_eq!(toast("minecraft:crafting_table").0, None);
|
||||
assert_eq!(
|
||||
toast("minecraft:cooked_beef_from_campfire_cooking"),
|
||||
(Some("minecraft:campfire"), Some("minecraft:cooked_beef"))
|
||||
);
|
||||
assert_eq!(
|
||||
toast("minecraft:stone_slab_from_stonecutting").0,
|
||||
Some("minecraft:stonecutter")
|
||||
);
|
||||
assert_eq!(
|
||||
toast("minecraft:coast_trim"),
|
||||
(Some("minecraft:smithing_table"), None)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn small_recipes_are_centred_in_the_grid() {
|
||||
// One ingredient in a 3x3 grid goes to the middle cell.
|
||||
assert_eq!(place_cells(3, 3, 1, 1, &['a']), vec![('a', 4)]);
|
||||
|
||||
@@ -527,6 +527,7 @@ pub fn encode_block_entity(
|
||||
}
|
||||
}
|
||||
BlockEntity::Spawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::TrialSpawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::Beehive(h) => entries.extend(h.to_nbt()),
|
||||
}
|
||||
Tag::compound(entries)
|
||||
@@ -656,6 +657,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
| BlockEntity::Banner(_)
|
||||
| BlockEntity::CreakingHeart(_) => {}
|
||||
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
|
||||
BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag),
|
||||
BlockEntity::Beehive(h) => **h = crate::beehive::Beehive::from_nbt(tag),
|
||||
}
|
||||
Some((pos, entity))
|
||||
@@ -1924,6 +1926,145 @@ const INT_RULES: [&str; 11] = [
|
||||
|
||||
/// World and player state stored in `level.dat`, the saved-data files and
|
||||
/// the player file.
|
||||
/// The world options CreateWorldScreen sets (`WorldOptions` and the world
|
||||
/// preset) that `world_gen_settings` keeps.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WorldGen {
|
||||
/// The `minecraft:flat` preset (Superflat) instead of `normal`.
|
||||
pub flat: bool,
|
||||
pub structures: bool,
|
||||
pub bonus_chest: bool,
|
||||
}
|
||||
impl WorldGen {
|
||||
/// A saved world's choices, from its `world_gen_settings`.
|
||||
pub fn read(world: &Path) -> Option<Self> {
|
||||
let settings = world_gen_settings(world)?;
|
||||
let flag = |key: &str, default: bool| number(settings.get(key)).map_or(default, |v| v != 0);
|
||||
let generator = settings
|
||||
.get("dimensions")
|
||||
.and_then(|d| d.get("minecraft:overworld"))
|
||||
.and_then(|o| o.get("generator"));
|
||||
Some(Self {
|
||||
flat: text(generator.and_then(|g| g.get("type")))
|
||||
.is_some_and(|t| t.trim_start_matches("minecraft:") == "flat"),
|
||||
structures: flag("generate_structures", true),
|
||||
bonus_chest: flag("bonus_chest", false),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Default for WorldGen {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
flat: false,
|
||||
structures: true,
|
||||
bonus_chest: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Writes a new world's `world_gen_settings` (seed, options and dimensions).
|
||||
pub fn write_world_gen_settings(dir: &Path, seed: i64, options: WorldGen) -> Result<()> {
|
||||
fs::create_dir_all(dir)?;
|
||||
// worldgen/world_preset/flat.json's overworld: the classic flat layers.
|
||||
let layer = |block: &str, height: i32| {
|
||||
Tag::compound([("block", string(block)), ("height", Tag::Int(height))])
|
||||
};
|
||||
let flat = Tag::compound([
|
||||
("type", string("minecraft:overworld")),
|
||||
(
|
||||
"generator",
|
||||
Tag::compound([
|
||||
("type", string("minecraft:flat")),
|
||||
(
|
||||
"settings",
|
||||
Tag::compound([
|
||||
("biome", string("minecraft:plains")),
|
||||
("features", Tag::Byte(0)),
|
||||
("lakes", Tag::Byte(0)),
|
||||
(
|
||||
"layers",
|
||||
Tag::List(vec![
|
||||
layer("minecraft:bedrock", 1),
|
||||
layer("minecraft:dirt", 2),
|
||||
layer("minecraft:grass_block", 1),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"structure_overrides",
|
||||
Tag::List(vec![
|
||||
string("minecraft:strongholds"),
|
||||
string("minecraft:villages"),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
let dimension = |kind: &str, settings: &str, source: Tag| {
|
||||
Tag::compound([
|
||||
("type", string(kind)),
|
||||
(
|
||||
"generator",
|
||||
Tag::compound([
|
||||
("type", string("minecraft:noise")),
|
||||
("settings", string(settings)),
|
||||
("biome_source", source),
|
||||
]),
|
||||
),
|
||||
])
|
||||
};
|
||||
let preset = |p: &str| {
|
||||
Tag::compound([
|
||||
("type", string("minecraft:multi_noise")),
|
||||
("preset", string(p)),
|
||||
])
|
||||
};
|
||||
write_saved_data(
|
||||
dir,
|
||||
"world_gen_settings",
|
||||
Tag::compound([
|
||||
("seed", Tag::Long(seed)),
|
||||
(
|
||||
"generate_structures",
|
||||
Tag::Byte(i8::from(options.structures)),
|
||||
),
|
||||
("bonus_chest", Tag::Byte(i8::from(options.bonus_chest))),
|
||||
(
|
||||
"dimensions",
|
||||
Tag::compound([
|
||||
(
|
||||
"minecraft:overworld",
|
||||
if options.flat {
|
||||
flat
|
||||
} else {
|
||||
dimension(
|
||||
"minecraft:overworld",
|
||||
"minecraft:overworld",
|
||||
preset("minecraft:overworld"),
|
||||
)
|
||||
},
|
||||
),
|
||||
(
|
||||
"minecraft:the_nether",
|
||||
dimension(
|
||||
"minecraft:the_nether",
|
||||
"minecraft:nether",
|
||||
preset("minecraft:nether"),
|
||||
),
|
||||
),
|
||||
(
|
||||
"minecraft:the_end",
|
||||
dimension(
|
||||
"minecraft:the_end",
|
||||
"minecraft:end",
|
||||
Tag::compound([("type", string("minecraft:the_end"))]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Level {
|
||||
pub name: String,
|
||||
@@ -1966,6 +2107,9 @@ pub struct Level {
|
||||
pub world_spawn: Option<[i32; 3]>,
|
||||
pub difficulty: String,
|
||||
pub hardcore: bool,
|
||||
/// `allowCommands` chosen on the Create New World screen; unset keeps
|
||||
/// the saved value (off for a new world).
|
||||
pub allow_commands: Option<bool>,
|
||||
/// Game rule values by name without namespace (`keep_inventory`, ...).
|
||||
pub game_rules: BTreeMap<String, i32>,
|
||||
pub player_uuid: Option<[i32; 4]>,
|
||||
@@ -2526,6 +2670,9 @@ impl Level {
|
||||
}
|
||||
if let Tag::Compound(map) = &mut data {
|
||||
map.entry("allowCommands".into()).or_insert(Tag::Byte(0));
|
||||
if let Some(allow) = self.allow_commands {
|
||||
map.insert("allowCommands".into(), Tag::Byte(i8::from(allow)));
|
||||
}
|
||||
map.entry("WasModded".into()).or_insert(Tag::Byte(0));
|
||||
map.entry("DataPacks".into()).or_insert_with(|| {
|
||||
Tag::compound([
|
||||
@@ -2569,63 +2716,7 @@ impl Level {
|
||||
}
|
||||
write_saved_data(dir, "world_clocks", clocks)?;
|
||||
if legacy || !saved_data_path(dir, "world_gen_settings").exists() {
|
||||
let dimension = |kind: &str, settings: &str, source: Tag| {
|
||||
Tag::compound([
|
||||
("type", string(kind)),
|
||||
(
|
||||
"generator",
|
||||
Tag::compound([
|
||||
("type", string("minecraft:noise")),
|
||||
("settings", string(settings)),
|
||||
("biome_source", source),
|
||||
]),
|
||||
),
|
||||
])
|
||||
};
|
||||
let preset = |p: &str| {
|
||||
Tag::compound([
|
||||
("type", string("minecraft:multi_noise")),
|
||||
("preset", string(p)),
|
||||
])
|
||||
};
|
||||
write_saved_data(
|
||||
dir,
|
||||
"world_gen_settings",
|
||||
Tag::compound([
|
||||
("seed", Tag::Long(self.seed)),
|
||||
("generate_structures", Tag::Byte(1)),
|
||||
("bonus_chest", Tag::Byte(0)),
|
||||
(
|
||||
"dimensions",
|
||||
Tag::compound([
|
||||
(
|
||||
"minecraft:overworld",
|
||||
dimension(
|
||||
"minecraft:overworld",
|
||||
"minecraft:overworld",
|
||||
preset("minecraft:overworld"),
|
||||
),
|
||||
),
|
||||
(
|
||||
"minecraft:the_nether",
|
||||
dimension(
|
||||
"minecraft:the_nether",
|
||||
"minecraft:nether",
|
||||
preset("minecraft:nether"),
|
||||
),
|
||||
),
|
||||
(
|
||||
"minecraft:the_end",
|
||||
dimension(
|
||||
"minecraft:the_end",
|
||||
"minecraft:end",
|
||||
Tag::compound([("type", string("minecraft:the_end"))]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)?;
|
||||
write_world_gen_settings(dir, self.seed, WorldGen::default())?;
|
||||
}
|
||||
if !saved_data_path(dir, "game_rules").exists() || !self.game_rules.is_empty() {
|
||||
// Only rules vanilla knows: an unknown key makes it reject the file.
|
||||
|
||||
@@ -17,6 +17,7 @@ use std::collections::HashMap;
|
||||
pub const MASTER: usize = 0;
|
||||
pub const MUSIC: usize = 1;
|
||||
pub const RECORDS: usize = 2;
|
||||
pub const NEUTRAL: usize = 6;
|
||||
pub const PLAYERS: usize = 7;
|
||||
pub const AMBIENT: usize = 8;
|
||||
pub const UI: usize = 10;
|
||||
@@ -48,12 +49,30 @@ pub enum Ticking {
|
||||
UnderLiquidLoop { fade: i32 },
|
||||
/// `UnderLiquidSubSound`.
|
||||
UnderLiquidSub,
|
||||
/// `MinecartSoundInstance` following a minecart.
|
||||
Minecart { cart: u32 },
|
||||
/// `RidingMinecartSoundInstance` for the player riding a minecart.
|
||||
RidingMinecart { cart: u32, underwater: bool },
|
||||
}
|
||||
/// What tickable instances read about the player.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
/// What a minecart's sound instances read about it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CartSound {
|
||||
pub id: u32,
|
||||
pub position: [f64; 3],
|
||||
/// `getDeltaMovement().horizontalDistance()`.
|
||||
pub speed: f64,
|
||||
}
|
||||
/// What tickable instances read about the player and the entities they follow.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TickContext {
|
||||
pub player_underwater: bool,
|
||||
pub player_removed: bool,
|
||||
/// The minecart the player rides.
|
||||
pub vehicle: Option<u32>,
|
||||
/// The minecarts in the level (a missing one has been removed).
|
||||
pub carts: Vec<CartSound>,
|
||||
/// `!tickRateManager().runsNormally()`.
|
||||
pub frozen: bool,
|
||||
}
|
||||
/// `AbstractSoundInstance` and its subclasses' fields.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -247,6 +266,55 @@ impl SoundInstance {
|
||||
pub fn under_liquid_sub(id: &str, random: LegacyRandom) -> Self {
|
||||
Self::ambient_loop(id, random, false, Ticking::UnderLiquidSub)
|
||||
}
|
||||
/// `new MinecartSoundInstance(minecart)`: silent until the cart rolls.
|
||||
pub fn minecart(cart: &CartSound, random: LegacyRandom) -> Self {
|
||||
let [x, y, z] = cart.position;
|
||||
let mut s = Self::new(
|
||||
"minecraft:entity.minecart.riding",
|
||||
NEUTRAL,
|
||||
0.0,
|
||||
1.0,
|
||||
random,
|
||||
true,
|
||||
0,
|
||||
Attenuation::Linear,
|
||||
[
|
||||
f64::from(x as f32),
|
||||
f64::from(y as f32),
|
||||
f64::from(z as f32),
|
||||
],
|
||||
false,
|
||||
);
|
||||
s.can_start_silent = true;
|
||||
s.ticking = Ticking::Minecart { cart: cart.id };
|
||||
s
|
||||
}
|
||||
/// `new RidingMinecartSoundInstance(player, minecart, underwater, event, 0, 0.75, 1)`.
|
||||
pub fn riding_minecart(cart: &CartSound, underwater: bool, random: LegacyRandom) -> Self {
|
||||
let id = if underwater {
|
||||
"minecraft:entity.minecart.inside.underwater"
|
||||
} else {
|
||||
"minecraft:entity.minecart.inside"
|
||||
};
|
||||
let mut s = Self::new(
|
||||
id,
|
||||
NEUTRAL,
|
||||
0.0,
|
||||
1.0,
|
||||
random,
|
||||
true,
|
||||
0,
|
||||
Attenuation::None,
|
||||
cart.position,
|
||||
false,
|
||||
);
|
||||
s.can_start_silent = true;
|
||||
s.ticking = Ticking::RidingMinecart {
|
||||
cart: cart.id,
|
||||
underwater,
|
||||
};
|
||||
s
|
||||
}
|
||||
pub fn tickable(&self) -> bool {
|
||||
self.ticking != Ticking::No
|
||||
}
|
||||
@@ -301,6 +369,46 @@ impl SoundInstance {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
Ticking::Minecart { cart } => {
|
||||
let id = *cart;
|
||||
let Some(cart) = ctx.carts.iter().find(|c| c.id == id) else {
|
||||
self.stop();
|
||||
return;
|
||||
};
|
||||
let [x, y, z] = cart.position;
|
||||
self.position = [
|
||||
f64::from(x as f32),
|
||||
f64::from(y as f32),
|
||||
f64::from(z as f32),
|
||||
];
|
||||
// Its own `pitch` field shadows the instance's, which stays 1.
|
||||
let speed = cart.speed as f32;
|
||||
self.volume = if speed >= 0.01 && !ctx.frozen {
|
||||
speed.clamp(0.0, 0.5) * 0.7
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
}
|
||||
Ticking::RidingMinecart { cart, underwater } => {
|
||||
let (id, underwater) = (*cart, *underwater);
|
||||
let found = ctx.carts.iter().find(|c| c.id == id);
|
||||
let Some(cart) = found.filter(|c| ctx.vehicle == Some(c.id)) else {
|
||||
self.stop();
|
||||
return;
|
||||
};
|
||||
if underwater != ctx.player_underwater {
|
||||
self.volume = 0.0;
|
||||
} else {
|
||||
// Mth.clampedLerp(speed, 0, 0.75), amplified by 1.
|
||||
let speed = cart.speed as f32;
|
||||
self.volume = if speed >= 0.01 {
|
||||
if speed > 1.0 { 0.75 } else { speed * 0.75 }
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
self.position = cart.position;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `LoopSoundInstance.fadeOut`.
|
||||
|
||||
@@ -437,6 +437,7 @@ pub enum Smithing {
|
||||
result: String,
|
||||
},
|
||||
Trim {
|
||||
id: String,
|
||||
template: Ingredient,
|
||||
base: Ingredient,
|
||||
addition: Ingredient,
|
||||
@@ -510,6 +511,7 @@ impl StationRecipes {
|
||||
.to_owned(),
|
||||
}),
|
||||
"minecraft:smithing_trim" => smithing.push(Smithing::Trim {
|
||||
id,
|
||||
template: ingredient(&v["template"], items),
|
||||
base: ingredient(&v["base"], items),
|
||||
addition: ingredient(&v["addition"], items),
|
||||
@@ -614,25 +616,64 @@ impl StationRecipes {
|
||||
base: b,
|
||||
addition: a,
|
||||
pattern,
|
||||
..
|
||||
} => {
|
||||
if t.test(template) && b.test(base) && a.test(addition) {
|
||||
let material = e.props(&addition.item)?.trim_material.clone()?;
|
||||
let trim = (Arc::from(material.as_str()), Arc::from(pattern.as_str()));
|
||||
if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) {
|
||||
return None;
|
||||
}
|
||||
let mut out = ItemStack {
|
||||
count: 1,
|
||||
..base.clone()
|
||||
};
|
||||
out.data_mut().trim = Some(trim);
|
||||
return Some(out);
|
||||
return apply_trim(e, base, addition, pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `SmithingTrimDemoSlotDisplay.resolveForFirstStack` of a trim recipe:
|
||||
/// a random base trimmed with a random material (`pick(n)` draws below n).
|
||||
pub fn trim_demo(
|
||||
&self,
|
||||
e: &Enchantments,
|
||||
id: &str,
|
||||
pick: &mut dyn FnMut(usize) -> usize,
|
||||
) -> Option<ItemStack> {
|
||||
let (base, addition, pattern) = self.smithing.iter().find_map(|r| match r {
|
||||
Smithing::Trim {
|
||||
id: i,
|
||||
base,
|
||||
addition,
|
||||
pattern,
|
||||
..
|
||||
} if i == id => Some((&base.1, &addition.1, pattern)),
|
||||
_ => None,
|
||||
})?;
|
||||
if base.is_empty() || addition.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// applyDemoTransformation: up to 256 draws, the first that isn't empty.
|
||||
(0..256).find_map(|_| {
|
||||
let base = ItemStack::new(&base[pick(base.len())], 1);
|
||||
let material = ItemStack::new(&addition[pick(addition.len())], 1);
|
||||
apply_trim(e, &base, &material, pattern)
|
||||
})
|
||||
}
|
||||
}
|
||||
/// `SmithingTrimRecipe.applyTrim`: none when the material provides no trim
|
||||
/// or the base already has this one.
|
||||
fn apply_trim(
|
||||
e: &Enchantments,
|
||||
base: &ItemStack,
|
||||
material: &ItemStack,
|
||||
pattern: &str,
|
||||
) -> Option<ItemStack> {
|
||||
let material = e.props(&material.item)?.trim_material.clone()?;
|
||||
let trim = (Arc::from(material.as_str()), Arc::from(pattern));
|
||||
if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) {
|
||||
return None;
|
||||
}
|
||||
let mut out = ItemStack {
|
||||
count: 1,
|
||||
..base.clone()
|
||||
};
|
||||
out.data_mut().trim = Some(trim);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -45,6 +45,27 @@ fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack {
|
||||
item
|
||||
}
|
||||
|
||||
/// A rolled stack as an item with its enchantments (stored ones on a
|
||||
/// book), potion and ominous bottle level.
|
||||
pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStack {
|
||||
let mut item = loot_item(s);
|
||||
for (id, level) in &s.enchantments {
|
||||
let level = (*level).max(0) as u32;
|
||||
if &*item.item == "minecraft:enchanted_book" {
|
||||
crate::item_data::set_level(&mut item.data_mut().stored_enchantments, id, level);
|
||||
} else {
|
||||
item.enchant(id, level);
|
||||
}
|
||||
}
|
||||
if let Some(potion) = &s.potion {
|
||||
item = item.with_potion(potion);
|
||||
}
|
||||
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
|
||||
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
/// The exploration map search an item still waits for, removed from it.
|
||||
pub fn take_pending_map(item: &mut ItemStack) -> Option<horizon_world::loot::ExplorationMap> {
|
||||
let data = item.extra.as_deref_mut()?;
|
||||
@@ -123,6 +144,9 @@ pub fn block_entities(
|
||||
if let BlockEntity::Spawner(s) = &mut entity {
|
||||
**s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
if let BlockEntity::TrialSpawner(s) = &mut entity {
|
||||
**s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
if let (BlockEntity::Chest(slots), Some(table), Some(loot)) =
|
||||
(&mut entity, text(nbt, "LootTable"), loot)
|
||||
{
|
||||
|
||||
+162
-175
@@ -12,12 +12,15 @@ use std::{
|
||||
sync::mpsc,
|
||||
};
|
||||
|
||||
mod create_world;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod world_management;
|
||||
pub use create_world::{DIFFICULTIES, WorldOptions};
|
||||
|
||||
const LIST_TOP: f32 = 48.0;
|
||||
const LIST_BOTTOM: f32 = 58.0;
|
||||
/// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`.
|
||||
const LIST_TOP: f32 = 49.0;
|
||||
const LIST_BOTTOM: f32 = 60.0;
|
||||
const ROW_HEIGHT: f32 = 36.0;
|
||||
const ROW_WIDTH: f32 = 270.0;
|
||||
|
||||
@@ -80,6 +83,7 @@ pub enum Mode {
|
||||
seed: String,
|
||||
creative: bool,
|
||||
focus: u8,
|
||||
options: WorldOptions,
|
||||
},
|
||||
Edit {
|
||||
world: WorldEntry,
|
||||
@@ -113,6 +117,7 @@ pub enum Action {
|
||||
name: String,
|
||||
seed: Option<i64>,
|
||||
creative: bool,
|
||||
options: WorldOptions,
|
||||
},
|
||||
Connect {
|
||||
address: String,
|
||||
@@ -124,7 +129,7 @@ pub struct Title {
|
||||
pub started: std::time::Instant,
|
||||
search: String,
|
||||
search_focused: bool,
|
||||
scroll: Cell<f32>,
|
||||
scroll: Cell<crate::ui::Scroll>,
|
||||
create_return_to_main: bool,
|
||||
message_lines: Cell<usize>,
|
||||
backup: Option<mpsc::Receiver<Result<u64, String>>>,
|
||||
@@ -139,7 +144,7 @@ pub struct Title {
|
||||
/// The saves listed for Home, re-read every couple of seconds.
|
||||
recent: std::cell::RefCell<Option<(std::time::Instant, Vec<WorldEntry>)>>,
|
||||
}
|
||||
struct Button {
|
||||
pub(crate) struct Button {
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
@@ -228,7 +233,7 @@ impl Title {
|
||||
started: now,
|
||||
search: String::new(),
|
||||
search_focused: false,
|
||||
scroll: Cell::new(0.0),
|
||||
scroll: Cell::default(),
|
||||
create_return_to_main: false,
|
||||
message_lines: Cell::new(1),
|
||||
backup: None,
|
||||
@@ -252,7 +257,7 @@ impl Title {
|
||||
pub fn enter_singleplayer(&mut self) {
|
||||
self.search.clear();
|
||||
self.search_focused = true;
|
||||
self.scroll.set(0.0);
|
||||
self.scroll.set(crate::ui::Scroll::default());
|
||||
let worlds = list_worlds(&self.saves);
|
||||
self.create_return_to_main = worlds.is_empty();
|
||||
self.mode = if worlds.is_empty() {
|
||||
@@ -264,12 +269,13 @@ impl Title {
|
||||
}
|
||||
};
|
||||
}
|
||||
fn new_world() -> Mode {
|
||||
pub(crate) fn new_world() -> Mode {
|
||||
Mode::Create {
|
||||
name: "New World".into(),
|
||||
seed: String::new(),
|
||||
creative: false,
|
||||
focus: 0,
|
||||
options: WorldOptions::default(),
|
||||
}
|
||||
}
|
||||
fn return_to_list(&mut self, folder: Option<&str>) {
|
||||
@@ -324,19 +330,48 @@ impl Title {
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
}
|
||||
/// Mouse wheel over the classic world list.
|
||||
/// The world list's top, bottom, rows' left edge and content height.
|
||||
fn world_list(&self, worlds: &[WorldEntry], (w, h): (f32, f32)) -> (f32, f32, f32, f32) {
|
||||
let (w, h) = (w.ceil(), h.ceil());
|
||||
let content = self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0;
|
||||
let left = (w / 2.0).floor() - ROW_WIDTH / 2.0;
|
||||
(LIST_TOP, h - LIST_BOTTOM, left, content)
|
||||
}
|
||||
/// The pointer moved with the button held (`mouseDragged`).
|
||||
pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode {
|
||||
return screen.drag(cursor.1, size);
|
||||
}
|
||||
if let Mode::Select { worlds, .. } = &self.mode {
|
||||
let (top, bottom, _, content) = self.world_list(worlds, size);
|
||||
let mut scroll = self.scroll.get();
|
||||
scroll.drag(cursor.1, top, bottom, content);
|
||||
self.scroll.set(scroll);
|
||||
}
|
||||
}
|
||||
/// The button was released (`onRelease`).
|
||||
pub fn release(&mut self) {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode {
|
||||
screen.release();
|
||||
}
|
||||
self.scroll.get_mut().release();
|
||||
}
|
||||
/// Mouse wheel over the classic world and server lists.
|
||||
pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode {
|
||||
screen.wheel(delta, cursor, size);
|
||||
return;
|
||||
}
|
||||
let Mode::Select { worlds, .. } = &self.mode else {
|
||||
return;
|
||||
};
|
||||
if cursor.1 < LIST_TOP || cursor.1 >= size.1 - LIST_BOTTOM {
|
||||
let (top, bottom, _, content) = self.world_list(worlds, size);
|
||||
if cursor.1 < top || cursor.1 >= bottom {
|
||||
return;
|
||||
}
|
||||
let max = (self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0
|
||||
- (size.1 - LIST_TOP - LIST_BOTTOM))
|
||||
.max(0.0);
|
||||
self.scroll
|
||||
.set((self.scroll.get() - delta * ROW_HEIGHT / 2.0).clamp(0.0, max));
|
||||
let mut scroll = self.scroll.get();
|
||||
scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content);
|
||||
self.scroll.set(scroll);
|
||||
}
|
||||
fn failed(&mut self, error: impl std::fmt::Display) {
|
||||
let return_to = Box::new(self.mode.clone());
|
||||
@@ -453,11 +488,22 @@ impl Title {
|
||||
name,
|
||||
seed,
|
||||
creative,
|
||||
options,
|
||||
..
|
||||
} = &self.mode
|
||||
else {
|
||||
return Action::None;
|
||||
};
|
||||
Action::Create {
|
||||
folder: self.target_folder(name),
|
||||
name: name.clone(),
|
||||
seed: parse_seed(seed),
|
||||
creative: *creative,
|
||||
options: options.clone(),
|
||||
}
|
||||
}
|
||||
/// The folder a new world named `name` gets (`findResultFolder`).
|
||||
fn target_folder(&self, name: &str) -> String {
|
||||
let base: String = name
|
||||
.chars()
|
||||
.map(|c| {
|
||||
@@ -480,12 +526,7 @@ impl Title {
|
||||
folder = format!("{base} ({n})");
|
||||
n += 1;
|
||||
}
|
||||
Action::Create {
|
||||
folder,
|
||||
name: name.clone(),
|
||||
seed: parse_seed(seed),
|
||||
creative: *creative,
|
||||
}
|
||||
folder
|
||||
}
|
||||
fn buttons(&self, w: f32, h: f32) -> Vec<Button> {
|
||||
let (w, h) = (w.ceil(), h.ceil());
|
||||
@@ -579,29 +620,9 @@ impl Title {
|
||||
),
|
||||
b((w / 2.0).floor() + 83.0, h - 28.0, 71.0, "Back", true, 12),
|
||||
],
|
||||
Mode::Create { creative, .. } => vec![
|
||||
b(
|
||||
(w / 2.0).floor() - 75.0,
|
||||
120.0,
|
||||
150.0,
|
||||
if *creative {
|
||||
"Game Mode: Creative"
|
||||
} else {
|
||||
"Game Mode: Survival"
|
||||
},
|
||||
true,
|
||||
20,
|
||||
),
|
||||
b(
|
||||
(w / 2.0).floor() - 155.0,
|
||||
h - 28.0,
|
||||
150.0,
|
||||
"Create New World",
|
||||
true,
|
||||
21,
|
||||
),
|
||||
b((w / 2.0).floor() + 5.0, h - 28.0, 150.0, "Cancel", true, 22),
|
||||
],
|
||||
Mode::Create {
|
||||
creative, options, ..
|
||||
} => create_world::buttons(w, h, *creative, options),
|
||||
Mode::Edit { world, name, .. } => {
|
||||
let x = (w / 2.0).floor() - 100.0;
|
||||
let top = edit_top(h);
|
||||
@@ -765,7 +786,7 @@ impl Title {
|
||||
batch.text(atlas, notice, w - tw - 2.0, h - 10.0, u32::MAX, true);
|
||||
}
|
||||
Mode::Select { worlds, selected } => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
centered(atlas, batch, "Select World", 8.0, u32::MAX);
|
||||
text_field(
|
||||
atlas,
|
||||
@@ -786,44 +807,33 @@ impl Title {
|
||||
true,
|
||||
);
|
||||
}
|
||||
let bottom = h - LIST_BOTTOM;
|
||||
batch.fill(
|
||||
atlas,
|
||||
0.0,
|
||||
LIST_TOP,
|
||||
w,
|
||||
bottom - LIST_TOP,
|
||||
rgba(0, 0, 0, 100),
|
||||
);
|
||||
batch.fill(atlas, 0.0, LIST_TOP - 1.0, w, 1.0, rgba(160, 160, 160, 255));
|
||||
batch.fill(atlas, 0.0, bottom, w, 1.0, rgba(160, 160, 160, 255));
|
||||
let count = self.visible_worlds(worlds).count();
|
||||
let max = (count as f32 * ROW_HEIGHT + 4.0 - (bottom - LIST_TOP)).max(0.0);
|
||||
self.scroll.set(self.scroll.get().clamp(0.0, max));
|
||||
let (top, bottom, left, content) = self.world_list(worlds, (w, h));
|
||||
let mut scroll = self.scroll.get();
|
||||
scroll.clamp(top, bottom, content);
|
||||
self.scroll.set(scroll);
|
||||
let offset = scroll.amount.trunc();
|
||||
// AbstractSelectionList: background, rows clipped to the
|
||||
// list, separators, scrollbar.
|
||||
crate::ui::list_background(batch, atlas, top, bottom, false);
|
||||
let first = batch.vertices.len();
|
||||
let x = ((w - ROW_WIDTH) / 2.0).floor() + 2.0;
|
||||
// Entry content sits 2 pixels inside its row.
|
||||
let x = left + 2.0;
|
||||
let mut slot = 0;
|
||||
for (row, (i, world)) in self.visible_worlds(worlds).enumerate() {
|
||||
let y = LIST_TOP + 5.0 + row as f32 * ROW_HEIGHT - self.scroll.get();
|
||||
if y + 32.0 <= LIST_TOP || y >= bottom {
|
||||
let y = top + 4.0 + row as f32 * ROW_HEIGHT - offset;
|
||||
if y + 32.0 <= top || y >= bottom {
|
||||
continue;
|
||||
}
|
||||
let mid = y - 2.0 + ROW_HEIGHT / 2.0;
|
||||
if mid > LIST_TOP && mid < bottom {
|
||||
if mid > top && mid < bottom {
|
||||
crate::widgets::target_as(
|
||||
[x - 2.0, y - 2.0, ROW_WIDTH, ROW_HEIGHT],
|
||||
crate::widgets::Kind::Row,
|
||||
);
|
||||
}
|
||||
// extractSelection: white once the list has focus.
|
||||
if *selected == Some(i) {
|
||||
batch.fill(
|
||||
atlas,
|
||||
x - 2.0,
|
||||
y - 2.0,
|
||||
ROW_WIDTH,
|
||||
ROW_HEIGHT,
|
||||
rgba(128, 128, 128, 255),
|
||||
);
|
||||
batch.fill(atlas, x - 2.0, y - 2.0, ROW_WIDTH, ROW_HEIGHT, u32::MAX);
|
||||
batch.fill(
|
||||
atlas,
|
||||
x - 1.0,
|
||||
@@ -872,8 +882,8 @@ impl Title {
|
||||
}
|
||||
// Clip list quads, including their UVs, to the content area.
|
||||
for quad in batch.vertices[first..].as_chunks_mut::<6>().0 {
|
||||
let top = quad.iter().map(|v| v.pos[1]).fold(f32::INFINITY, f32::min);
|
||||
let bot = quad
|
||||
let low = quad.iter().map(|v| v.pos[1]).fold(f32::INFINITY, f32::min);
|
||||
let high = quad
|
||||
.iter()
|
||||
.map(|v| v.pos[1])
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
@@ -883,96 +893,32 @@ impl Title {
|
||||
.map(|v| v.uv[1])
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
for v in quad {
|
||||
v.pos[1] = v.pos[1].clamp(LIST_TOP, bottom);
|
||||
if bot > top {
|
||||
v.uv[1] = uv_top + (uv_bot - uv_top) * (v.pos[1] - top) / (bot - top);
|
||||
v.pos[1] = v.pos[1].clamp(top, bottom);
|
||||
if high > low {
|
||||
v.uv[1] = uv_top + (uv_bot - uv_top) * (v.pos[1] - low) / (high - low);
|
||||
}
|
||||
}
|
||||
}
|
||||
if max > 0.0 {
|
||||
let track = bottom - LIST_TOP;
|
||||
let thumb =
|
||||
(track * track / (count as f32 * ROW_HEIGHT + 4.0)).clamp(32.0, track);
|
||||
let sx = (w / 2.0).floor() + ROW_WIDTH / 2.0 + 6.0;
|
||||
batch.fill(atlas, sx, LIST_TOP, 6.0, track, rgba(0, 0, 0, 255));
|
||||
batch.fill(
|
||||
atlas,
|
||||
sx,
|
||||
LIST_TOP + self.scroll.get() / max * (track - thumb),
|
||||
6.0,
|
||||
thumb,
|
||||
rgba(128, 128, 128, 255),
|
||||
);
|
||||
}
|
||||
crate::ui::separators(batch, atlas, top, bottom, false);
|
||||
crate::ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
left + ROW_WIDTH + 8.0,
|
||||
top,
|
||||
bottom,
|
||||
content,
|
||||
scroll.amount,
|
||||
);
|
||||
}
|
||||
Mode::Create {
|
||||
name, seed, focus, ..
|
||||
} => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
let title = "Create New World";
|
||||
let tw = HudBatch::text_width(atlas, title);
|
||||
batch.text(atlas, title, (w - tw) / 2.0, 8.0, u32::MAX, true);
|
||||
let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2);
|
||||
for (i, (label, value)) in [
|
||||
("World Name", name),
|
||||
(
|
||||
"Seed for the World Generator (leave blank for random)",
|
||||
seed,
|
||||
),
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let y = 40.0 + i as f32 * 40.0;
|
||||
crate::widgets::target_as(
|
||||
[(w / 2.0).floor() - 100.0, y + 11.0, 200.0, 20.0],
|
||||
crate::widgets::Kind::Field,
|
||||
);
|
||||
batch.text(
|
||||
atlas,
|
||||
label,
|
||||
(w / 2.0).floor() - 100.0,
|
||||
y,
|
||||
rgba(160, 160, 160, 255),
|
||||
true,
|
||||
);
|
||||
batch.fill(
|
||||
atlas,
|
||||
(w / 2.0).floor() - 100.0,
|
||||
y + 11.0,
|
||||
200.0,
|
||||
20.0,
|
||||
if *focus == i as u8 {
|
||||
u32::MAX
|
||||
} else {
|
||||
rgba(160, 160, 160, 255)
|
||||
},
|
||||
);
|
||||
batch.fill(
|
||||
atlas,
|
||||
(w / 2.0).floor() - 99.0,
|
||||
y + 12.0,
|
||||
198.0,
|
||||
18.0,
|
||||
rgba(0, 0, 0, 255),
|
||||
);
|
||||
let shown = if *focus == i as u8 && blink {
|
||||
format!("{value}_")
|
||||
} else {
|
||||
value.to_string()
|
||||
};
|
||||
batch.text(
|
||||
atlas,
|
||||
&shown,
|
||||
(w / 2.0).floor() - 96.0,
|
||||
y + 17.0,
|
||||
rgba(224, 224, 224, 255),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
name,
|
||||
seed,
|
||||
focus,
|
||||
options,
|
||||
..
|
||||
} => self.draw_create(atlas, batch, cursor, name, seed, *focus, options),
|
||||
Mode::Edit { name, focused, .. } => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
centered(
|
||||
atlas,
|
||||
batch,
|
||||
@@ -999,7 +945,7 @@ impl Title {
|
||||
);
|
||||
}
|
||||
Mode::Delete { world } => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
let message = translate(
|
||||
"selectWorld.deleteWarning",
|
||||
"'%s' will be lost forever! (A long time!)",
|
||||
@@ -1024,7 +970,7 @@ impl Title {
|
||||
}
|
||||
Mode::Backup { .. } => {
|
||||
self.backup_shown.set(true);
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
centered(
|
||||
atlas,
|
||||
batch,
|
||||
@@ -1050,7 +996,7 @@ impl Title {
|
||||
}
|
||||
}
|
||||
Mode::Error { message, .. } => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
let lines = wrapped(atlas, message, w - 50.0);
|
||||
self.message_lines.set(lines.len());
|
||||
let top = confirm_top(h, lines.len());
|
||||
@@ -1124,6 +1070,15 @@ impl Title {
|
||||
true,
|
||||
);
|
||||
}
|
||||
if let Mode::Create {
|
||||
name,
|
||||
creative,
|
||||
options,
|
||||
..
|
||||
} = &self.mode
|
||||
{
|
||||
self.create_tooltip(atlas, batch, cursor, name, *creative, options);
|
||||
}
|
||||
if let Some((at, toast)) = &self.toast
|
||||
&& at.elapsed().as_secs() < 5
|
||||
{
|
||||
@@ -1149,6 +1104,17 @@ impl Title {
|
||||
/// Navigation buttons can return `Action::None` while still sounding.
|
||||
pub fn click(&mut self, x: f32, y: f32, size: (f32, f32)) -> (Action, bool) {
|
||||
let (w, h) = (size.0.ceil(), size.1.ceil());
|
||||
// MenuTabBar: a new tab clears the focus and clicks.
|
||||
if let Mode::Create { focus, options, .. } = &mut self.mode
|
||||
&& let Some(tab) = create_world::tab_at(w, (x, y))
|
||||
{
|
||||
let changed = options.tab != tab;
|
||||
if changed {
|
||||
options.tab = tab;
|
||||
*focus = 2;
|
||||
}
|
||||
return (Action::None, changed);
|
||||
}
|
||||
let hit = self
|
||||
.buttons(w, h)
|
||||
.into_iter()
|
||||
@@ -1212,11 +1178,17 @@ impl Title {
|
||||
_ => {
|
||||
if let Some(level) = Level::read(&self.saves.join(&world.folder)) {
|
||||
self.create_return_to_main = false;
|
||||
let options = WorldOptions::of_world(
|
||||
&level,
|
||||
world.commands,
|
||||
&self.saves.join(&world.folder),
|
||||
);
|
||||
self.mode = Mode::Create {
|
||||
name: level.name,
|
||||
seed: level.seed.to_string(),
|
||||
creative: level.creative,
|
||||
focus: 0,
|
||||
options,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1230,11 +1202,20 @@ impl Title {
|
||||
(Mode::Select { .. }, None) => {
|
||||
self.search_focused =
|
||||
(21.0..41.0).contains(&y) && (x - (w / 2.0).floor()).abs() < 100.0;
|
||||
if y >= LIST_TOP
|
||||
&& y < h - LIST_BOTTOM
|
||||
&& (x - (w / 2.0).floor()).abs() < ROW_WIDTH / 2.0
|
||||
let Mode::Select { worlds, .. } = &self.mode else {
|
||||
unreachable!()
|
||||
};
|
||||
let (top, bottom, left, content) = self.world_list(worlds, (w, h));
|
||||
if self
|
||||
.scroll
|
||||
.get_mut()
|
||||
.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content)
|
||||
{
|
||||
let row = ((y - LIST_TOP - 5.0 + self.scroll.get()) / ROW_HEIGHT).floor();
|
||||
return Action::None;
|
||||
}
|
||||
if y >= top && y < bottom && x >= left && x < left + ROW_WIDTH {
|
||||
let offset = self.scroll.get().amount.trunc();
|
||||
let row = ((y - top - 2.0 + offset) / ROW_HEIGHT).floor();
|
||||
if row >= 0.0 {
|
||||
let Mode::Select { worlds, selected } = &self.mode else {
|
||||
unreachable!()
|
||||
@@ -1302,8 +1283,13 @@ impl Title {
|
||||
self.mode = *return_to.clone();
|
||||
Action::None
|
||||
}
|
||||
(Mode::Create { creative, .. }, Some(20)) => {
|
||||
*creative = !*creative;
|
||||
(
|
||||
Mode::Create {
|
||||
creative, options, ..
|
||||
},
|
||||
Some(id),
|
||||
) if id != 21 && id != 22 => {
|
||||
options.press(id, creative);
|
||||
Action::None
|
||||
}
|
||||
(Mode::Create { .. }, Some(21)) => self.create_action(),
|
||||
@@ -1311,13 +1297,8 @@ impl Title {
|
||||
self.cancel_create();
|
||||
Action::None
|
||||
}
|
||||
(Mode::Create { focus, .. }, None) => {
|
||||
for i in 0..2u8 {
|
||||
let fy = 40.0 + f32::from(i) * 40.0 + 11.0;
|
||||
if y >= fy && y < fy + 20.0 && (x - (w / 2.0).floor()).abs() < 100.0 {
|
||||
*focus = i;
|
||||
}
|
||||
}
|
||||
(Mode::Create { focus, options, .. }, None) => {
|
||||
*focus = create_world::field_at(w, h, options.tab, (x, y)).unwrap_or(2);
|
||||
Action::None
|
||||
}
|
||||
_ => Action::None,
|
||||
@@ -1367,7 +1348,7 @@ impl Title {
|
||||
&& let Mode::Select { selected, .. } = &mut self.mode
|
||||
{
|
||||
*selected = None;
|
||||
self.scroll.set(0.0);
|
||||
self.scroll.set(crate::ui::Scroll::default());
|
||||
}
|
||||
}
|
||||
pub fn confirm_edit(&mut self) {
|
||||
@@ -1398,8 +1379,14 @@ impl Title {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode {
|
||||
screen.tab();
|
||||
}
|
||||
if let Mode::Create { focus, .. } = &mut self.mode {
|
||||
*focus = (*focus + 1) % 2;
|
||||
// The open tab's one text box, then nothing.
|
||||
if let Mode::Create { focus, options, .. } = &mut self.mode {
|
||||
let field = if options.tab == 1 { 1 } else { 0 };
|
||||
*focus = if *focus == field || options.tab == 2 {
|
||||
2
|
||||
} else {
|
||||
field
|
||||
};
|
||||
}
|
||||
}
|
||||
/// The server auto-reconnect retries now, once its countdown is over.
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
//! CreateWorldScreen: the Game, World and More tabs under a MenuTabBar, with
|
||||
//! Create New World and Cancel in a 33-pixel footer.
|
||||
use super::{Button, Title};
|
||||
use crate::{
|
||||
hud::{HudAtlas, HudBatch},
|
||||
text::Text,
|
||||
ui,
|
||||
};
|
||||
|
||||
/// MenuTabBar.HEIGHT: the header above the tab area.
|
||||
const TAB_BAR: f32 = 24.0;
|
||||
/// HeaderAndFooterLayout's default footer height.
|
||||
const FOOTER: f32 = 33.0;
|
||||
const TABS: [&str; 3] = [
|
||||
"createWorld.tab.game.title",
|
||||
"createWorld.tab.world.title",
|
||||
"createWorld.tab.more.title",
|
||||
];
|
||||
/// Difficulty ids, in the cycle button's order.
|
||||
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
|
||||
|
||||
/// WorldCreationUiState beyond the name and seed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WorldOptions {
|
||||
/// The open tab: Game, World or More.
|
||||
pub tab: usize,
|
||||
/// Survival locked to Hard, one life (`SelectedGameMode.HARDCORE`).
|
||||
pub hardcore: bool,
|
||||
/// Index in `DIFFICULTIES`.
|
||||
pub difficulty: usize,
|
||||
/// Allow Cheats as toggled; unset follows the game mode.
|
||||
pub commands: Option<bool>,
|
||||
/// The Superflat world preset instead of Default.
|
||||
pub flat: bool,
|
||||
pub structures: bool,
|
||||
pub bonus_chest: bool,
|
||||
}
|
||||
impl Default for WorldOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tab: 0,
|
||||
hardcore: false,
|
||||
difficulty: 2,
|
||||
commands: None,
|
||||
flat: false,
|
||||
structures: true,
|
||||
bonus_chest: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl WorldOptions {
|
||||
/// Re-Create: the saved world's choices.
|
||||
pub(super) fn of_world(
|
||||
level: &crate::save::Level,
|
||||
commands: bool,
|
||||
dir: &std::path::Path,
|
||||
) -> Self {
|
||||
let generation = crate::save::WorldGen::read(dir).unwrap_or_default();
|
||||
Self {
|
||||
hardcore: level.hardcore,
|
||||
difficulty: DIFFICULTIES
|
||||
.iter()
|
||||
.position(|d| *d == level.difficulty)
|
||||
.unwrap_or(2),
|
||||
commands: Some(commands),
|
||||
flat: generation.flat,
|
||||
structures: generation.structures,
|
||||
bonus_chest: generation.bonus_chest,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
/// `getDifficulty`: Hardcore is always Hard.
|
||||
pub fn difficulty(&self) -> usize {
|
||||
if self.hardcore { 3 } else { self.difficulty }
|
||||
}
|
||||
/// `isAllowCommands`: never in Hardcore, else on for Creative until toggled.
|
||||
pub fn commands(&self, creative: bool) -> bool {
|
||||
!self.hardcore && self.commands.unwrap_or(creative)
|
||||
}
|
||||
/// `isBonusChest`: never in Hardcore.
|
||||
pub fn bonus_chest(&self) -> bool {
|
||||
!self.hardcore && self.bonus_chest
|
||||
}
|
||||
pub fn world_gen(&self) -> crate::save::WorldGen {
|
||||
crate::save::WorldGen {
|
||||
flat: self.flat,
|
||||
structures: self.structures,
|
||||
bonus_chest: self.bonus_chest(),
|
||||
}
|
||||
}
|
||||
/// A press on one of the open tab's cycle buttons or switches.
|
||||
pub(super) fn press(&mut self, id: u8, creative: &mut bool) {
|
||||
match id {
|
||||
// Survival, Hardcore, Creative.
|
||||
20 => {
|
||||
(*creative, self.hardcore) = match (*creative, self.hardcore) {
|
||||
(false, false) => (false, true),
|
||||
(false, true) => (true, false),
|
||||
_ => (false, false),
|
||||
}
|
||||
}
|
||||
23 => self.difficulty = (self.difficulty + 1) % DIFFICULTIES.len(),
|
||||
24 => self.commands = Some(!self.commands(*creative)),
|
||||
25 => self.flat = !self.flat,
|
||||
27 => self.structures = !self.structures,
|
||||
28 => self.bonus_chest = !self.bonus_chest,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Mth.roundToward`: up to a multiple of `step`.
|
||||
fn round_toward(value: f32, step: f32) -> f32 {
|
||||
(value / step).ceil() * step
|
||||
}
|
||||
/// MenuTabBar.arrangeElements: the first tab's x and every tab's width.
|
||||
fn tabs(w: f32) -> (f32, f32) {
|
||||
let width = w.min(400.0) - 28.0;
|
||||
(
|
||||
round_toward(((w - width) / 2.0).trunc(), 2.0),
|
||||
round_toward((width / TABS.len() as f32).trunc(), 2.0),
|
||||
)
|
||||
}
|
||||
/// The tab under the pointer.
|
||||
pub(super) fn tab_at(w: f32, (x, y): (f32, f32)) -> Option<usize> {
|
||||
let (x0, width) = tabs(w);
|
||||
((0.0..TAB_BAR).contains(&y) && x >= x0)
|
||||
.then(|| ((x - x0) / width) as usize)
|
||||
.filter(|i| *i < TABS.len())
|
||||
}
|
||||
/// GridLayoutTab.doLayout: the open tab's grid, aligned at (0.5, 1/6) in the
|
||||
/// area between the tab bar and the footer.
|
||||
fn grid(w: f32, h: f32, tab: usize) -> (f32, f32) {
|
||||
// Game: the labelled name box (9 + 4 + 20) and three buttons, 8 apart.
|
||||
// World: a button row, the labelled seed box and the SwitchGrid
|
||||
// (4 + 20 + 4 + 20 under its empty spacer row). More: three buttons.
|
||||
let (gw, gh) = match tab {
|
||||
0 => (210.0, 117.0),
|
||||
1 => (310.0, 117.0),
|
||||
_ => (210.0, 76.0),
|
||||
};
|
||||
let area = h - TAB_BAR - FOOTER;
|
||||
(
|
||||
((w - gw) * 0.5).trunc(),
|
||||
TAB_BAR + ((area - gh) * 0.166_666_67).trunc(),
|
||||
)
|
||||
}
|
||||
/// The text box under the pointer: 0 the name, 1 the seed.
|
||||
pub(super) fn field_at(w: f32, h: f32, tab: usize, (x, y): (f32, f32)) -> Option<u8> {
|
||||
let (gx, gy) = grid(w, h, tab);
|
||||
match tab {
|
||||
0 => ui::hovered((x, y), gx + 1.0, gy + 13.0, 208.0, 20.0).then_some(0),
|
||||
1 => ui::hovered((x, y), gx, gy + 41.0, 308.0, 20.0).then_some(1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tr(key: &str) -> String {
|
||||
Text::translate(key, &[]).plain()
|
||||
}
|
||||
/// `CycleButton`'s "Label: Value" (`options.generic_value`).
|
||||
fn labelled(key: &str, value: String) -> String {
|
||||
Text::translate(
|
||||
"options.generic_value",
|
||||
&[Text::translate(key, &[]), Text::literal(value)],
|
||||
)
|
||||
.plain()
|
||||
}
|
||||
fn on_off(on: bool) -> String {
|
||||
tr(if on { "options.on" } else { "options.off" })
|
||||
}
|
||||
fn game_mode(creative: bool, hardcore: bool) -> &'static str {
|
||||
match (creative, hardcore) {
|
||||
(true, _) => "selectWorld.gameMode.creative",
|
||||
(false, true) => "selectWorld.gameMode.hardcore",
|
||||
(false, false) => "selectWorld.gameMode.survival",
|
||||
}
|
||||
}
|
||||
|
||||
/// The open tab's buttons and the footer's.
|
||||
pub(super) fn buttons(w: f32, h: f32, creative: bool, o: &WorldOptions) -> Vec<Button> {
|
||||
let b = |x: f32, y: f32, w: f32, label: String, enabled: bool, id: u8| Button {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
label,
|
||||
enabled,
|
||||
id,
|
||||
icon: None,
|
||||
};
|
||||
let (gx, gy) = grid(w, h, o.tab);
|
||||
let mut buttons = match o.tab {
|
||||
0 => vec![
|
||||
b(
|
||||
gx,
|
||||
gy + 41.0,
|
||||
210.0,
|
||||
labelled("selectWorld.gameMode", tr(game_mode(creative, o.hardcore))),
|
||||
true,
|
||||
20,
|
||||
),
|
||||
b(
|
||||
gx,
|
||||
gy + 69.0,
|
||||
210.0,
|
||||
labelled(
|
||||
"options.difficulty",
|
||||
tr(&format!(
|
||||
"options.difficulty.{}",
|
||||
DIFFICULTIES[o.difficulty()]
|
||||
)),
|
||||
),
|
||||
!o.hardcore,
|
||||
23,
|
||||
),
|
||||
b(
|
||||
gx,
|
||||
gy + 97.0,
|
||||
210.0,
|
||||
labelled("selectWorld.allowCommands", on_off(o.commands(creative))),
|
||||
!o.hardcore,
|
||||
24,
|
||||
),
|
||||
],
|
||||
1 => vec![
|
||||
b(
|
||||
gx,
|
||||
gy,
|
||||
150.0,
|
||||
labelled(
|
||||
"selectWorld.mapType",
|
||||
tr(if o.flat {
|
||||
"generator.minecraft.flat"
|
||||
} else {
|
||||
"generator.minecraft.normal"
|
||||
}),
|
||||
),
|
||||
true,
|
||||
25,
|
||||
),
|
||||
// Horizon has no preset editor (CreateFlatWorldScreen) yet.
|
||||
b(
|
||||
gx + 160.0,
|
||||
gy,
|
||||
150.0,
|
||||
tr("selectWorld.customizeType"),
|
||||
false,
|
||||
26,
|
||||
),
|
||||
// SwitchGrid: 44-wide value-only buttons at the grid's right.
|
||||
b(gx + 266.0, gy + 73.0, 44.0, on_off(o.structures), true, 27),
|
||||
b(
|
||||
gx + 266.0,
|
||||
gy + 97.0,
|
||||
44.0,
|
||||
on_off(o.bonus_chest()),
|
||||
!o.hardcore,
|
||||
28,
|
||||
),
|
||||
],
|
||||
// Game rules, experiments and data packs have no screens yet.
|
||||
_ => [
|
||||
"selectWorld.gameRules",
|
||||
"selectWorld.experiments",
|
||||
"selectWorld.dataPacks",
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, key)| {
|
||||
b(
|
||||
gx,
|
||||
gy + 28.0 * i as f32,
|
||||
210.0,
|
||||
tr(key),
|
||||
false,
|
||||
29 + i as u8,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
// The footer: two 150-wide buttons 8 apart, centred in its 33 pixels.
|
||||
let x = ((w - 308.0) * 0.5).trunc();
|
||||
buttons.push(b(
|
||||
x,
|
||||
h - 27.0,
|
||||
150.0,
|
||||
crate::lang::get_or("selectWorld.create", "Create New World"),
|
||||
true,
|
||||
21,
|
||||
));
|
||||
buttons.push(b(
|
||||
x + 158.0,
|
||||
h - 27.0,
|
||||
150.0,
|
||||
crate::lang::get_or("gui.cancel", "Cancel"),
|
||||
true,
|
||||
22,
|
||||
));
|
||||
buttons
|
||||
}
|
||||
|
||||
impl Title {
|
||||
/// Everything but the buttons, which `draw` adds after.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn draw_create(
|
||||
&self,
|
||||
atlas: &HudAtlas,
|
||||
batch: &mut HudBatch,
|
||||
cursor: (f32, f32),
|
||||
name: &str,
|
||||
seed: &str,
|
||||
focus: u8,
|
||||
o: &WorldOptions,
|
||||
) {
|
||||
let (w, h) = (batch.width.ceil(), batch.height.ceil());
|
||||
// extractMenuBackground: the tab header strip, the menu background under it.
|
||||
ui::tiled(
|
||||
batch,
|
||||
atlas,
|
||||
"gui/tab_header_background",
|
||||
0.0,
|
||||
0.0,
|
||||
w,
|
||||
TAB_BAR,
|
||||
16.0,
|
||||
u32::MAX,
|
||||
);
|
||||
ui::menu_background(batch, atlas, 0.0, TAB_BAR, w, h - TAB_BAR, false);
|
||||
// MenuTabBar: header separators either side of the tabs.
|
||||
let (x0, tw) = tabs(w);
|
||||
let right = x0 + tw * TABS.len() as f32;
|
||||
for (x, width) in [(0.0, x0), (right, w - right)] {
|
||||
ui::tiled(
|
||||
batch,
|
||||
atlas,
|
||||
"gui/header_separator",
|
||||
x,
|
||||
TAB_BAR - 2.0,
|
||||
width,
|
||||
2.0,
|
||||
32.0,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
for (i, key) in TABS.iter().enumerate() {
|
||||
let x = x0 + tw * i as f32;
|
||||
let selected = o.tab == i;
|
||||
let label = Text::translate(key, &[]);
|
||||
crate::widgets::record(&label.plain(), [x, 0.0, tw, TAB_BAR], true);
|
||||
let sprite = match (selected, ui::hovered(cursor, x, 0.0, tw, TAB_BAR)) {
|
||||
(true, true) => "gui/sprites/widget/tab_selected_highlighted",
|
||||
(true, false) => "gui/sprites/widget/tab_selected",
|
||||
(false, true) => "gui/sprites/widget/tab_highlighted",
|
||||
(false, false) => "gui/sprites/widget/tab",
|
||||
};
|
||||
ui::nine_slice(batch, atlas, sprite, x, 0.0, tw, TAB_BAR, u32::MAX);
|
||||
let lw = atlas.font.width_text(&label).floor();
|
||||
if selected {
|
||||
ui::menu_background(batch, atlas, x + 2.0, 2.0, tw - 4.0, TAB_BAR - 2.0, false);
|
||||
// renderFocusUnderline.
|
||||
let uw = lw.min(tw - 4.0);
|
||||
batch.fill(
|
||||
atlas,
|
||||
x + ((tw - uw) / 2.0).floor(),
|
||||
TAB_BAR - 2.0,
|
||||
uw,
|
||||
1.0,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
// The label sits 3 pixels lower on unselected tabs.
|
||||
let top = if selected { 0.0 } else { 3.0 };
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&label,
|
||||
x + (tw / 2.0).floor() - (lw / 2.0).floor(),
|
||||
((top + TAB_BAR - 9.0) / 2.0).floor() + 1.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
let (gx, gy) = grid(w, h, o.tab);
|
||||
let label = |batch: &mut HudBatch, key: &str, x: f32, y: f32| {
|
||||
batch.text_styled(atlas, &Text::translate(key, &[]), x, y, u32::MAX, true);
|
||||
};
|
||||
match o.tab {
|
||||
0 => {
|
||||
// CommonLayouts.labeledElement, centred in the 210 column.
|
||||
label(batch, "selectWorld.enterName", gx + 1.0, gy);
|
||||
self.create_field(
|
||||
atlas,
|
||||
batch,
|
||||
name,
|
||||
[gx + 1.0, gy + 13.0, 208.0],
|
||||
focus == 0,
|
||||
None,
|
||||
);
|
||||
}
|
||||
1 => {
|
||||
label(batch, "selectWorld.enterSeed", gx, gy + 28.0);
|
||||
self.create_field(
|
||||
atlas,
|
||||
batch,
|
||||
seed,
|
||||
[gx, gy + 41.0, 308.0],
|
||||
focus == 1,
|
||||
Some("selectWorld.seedInfo"),
|
||||
);
|
||||
// SwitchGrid labels, centred on their switch rows.
|
||||
label(batch, "selectWorld.mapFeatures", gx, gy + 78.0);
|
||||
label(batch, "selectWorld.bonusItems", gx, gy + 102.0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// The footer separator, drawn over the screen.
|
||||
ui::tiled(
|
||||
batch,
|
||||
atlas,
|
||||
"gui/footer_separator",
|
||||
0.0,
|
||||
h - FOOTER - 2.0,
|
||||
w,
|
||||
2.0,
|
||||
32.0,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
/// An EditBox with its cursor at the end; `hint` shows while it is empty
|
||||
/// and unfocused.
|
||||
fn create_field(
|
||||
&self,
|
||||
atlas: &HudAtlas,
|
||||
batch: &mut HudBatch,
|
||||
value: &str,
|
||||
[x, y, width]: [f32; 3],
|
||||
focused: bool,
|
||||
hint: Option<&str>,
|
||||
) {
|
||||
let mut field = ui::EditBox::new(x, y, width, 20.0);
|
||||
field.value = value.to_owned();
|
||||
field.cursor = ui::char_len(value);
|
||||
field.highlight = field.cursor;
|
||||
field.focused = focused;
|
||||
field.focused_since(self.started);
|
||||
field.draw(batch, atlas, None);
|
||||
if let Some(hint) = hint
|
||||
&& value.is_empty()
|
||||
&& !focused
|
||||
{
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&Text::translate(hint, &[]).with_color(crate::text::DARK_GRAY),
|
||||
field.text_x(),
|
||||
field.text_y(),
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// The hovered widget's tooltip, wrapped to Tooltip's 170 pixels.
|
||||
pub(super) fn create_tooltip(
|
||||
&self,
|
||||
atlas: &HudAtlas,
|
||||
batch: &mut HudBatch,
|
||||
cursor: (f32, f32),
|
||||
name: &str,
|
||||
creative: bool,
|
||||
o: &WorldOptions,
|
||||
) {
|
||||
let (w, h) = (batch.width.ceil(), batch.height.ceil());
|
||||
let (gx, gy) = grid(w, h, o.tab);
|
||||
let over = |x: f32, y: f32, width: f32| ui::hovered(cursor, x, y, width, 20.0);
|
||||
let text = match o.tab {
|
||||
0 if over(gx + 1.0, gy + 13.0, 208.0) => Some(Text::translate(
|
||||
"selectWorld.targetFolder",
|
||||
&[Text::literal(self.target_folder(name)).italic()],
|
||||
)),
|
||||
0 if over(gx, gy + 41.0, 210.0) => Some(Text::translate(
|
||||
&format!("{}.info", game_mode(creative, o.hardcore)),
|
||||
&[],
|
||||
)),
|
||||
0 if over(gx, gy + 69.0, 210.0) => Some(Text::translate(
|
||||
&format!("options.difficulty.{}.info", DIFFICULTIES[o.difficulty()]),
|
||||
&[],
|
||||
)),
|
||||
0 if over(gx, gy + 97.0, 210.0) => {
|
||||
Some(Text::translate("selectWorld.allowCommands.info", &[]))
|
||||
}
|
||||
1 if over(gx + 266.0, gy + 73.0, 44.0) => {
|
||||
Some(Text::translate("selectWorld.mapFeatures.info", &[]))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(text) = text {
|
||||
ui::tooltip(batch, atlas, &atlas.font.split(&text, 170.0), cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -414,7 +414,7 @@ fn recreate_uses_existing_name_seed_and_mode_and_scroll_reaches_later_rows() {
|
||||
f.click("Cancel");
|
||||
f.title
|
||||
.scroll_worlds(-100.0, (240.0, 100.0), (480.0, 262.0));
|
||||
assert!(f.title.scroll.get() > 0.0);
|
||||
assert!(f.title.scroll.get().amount > 0.0);
|
||||
let Mode::Select { worlds, .. } = &f.title.mode else {
|
||||
panic!()
|
||||
};
|
||||
@@ -447,8 +447,15 @@ fn classic_navigation_buttons_sound_even_without_a_game_action() {
|
||||
f.title.click(240.0, 55.0, (480.0, 262.0)),
|
||||
(Action::None, false)
|
||||
);
|
||||
// The Game tab's game mode cycle button.
|
||||
let mode = f
|
||||
.title
|
||||
.buttons(480.0, 262.0)
|
||||
.into_iter()
|
||||
.find(|b| b.id == 20)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
f.click_with_sound("Game Mode: Survival"),
|
||||
f.title.click(mode.x + 1.0, mode.y + 1.0, (480.0, 262.0)),
|
||||
(Action::None, true)
|
||||
);
|
||||
assert_eq!(f.click_with_sound("Cancel"), (Action::None, true));
|
||||
@@ -561,3 +568,115 @@ fn delete_removes_links_without_following_them() {
|
||||
assert!(!f.title.saves.join("World").exists());
|
||||
assert!(outside.join("keep.txt").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrolled_world_list_draws_inside_the_list_and_drags_its_scroller() {
|
||||
let mut f = Fixture::new();
|
||||
for i in 0..10 {
|
||||
f.world(&format!("World{i}"), &format!("World {i}"));
|
||||
}
|
||||
f.select();
|
||||
let size = (480.0, 262.0);
|
||||
// SelectWorldScreen's list: 49 to h - 60, scroller at the row's right + 8.
|
||||
let bar = (480.0 / 2.0 - ROW_WIDTH / 2.0 + ROW_WIDTH + 8.0 + 3.0, 60.0);
|
||||
f.title.click(bar.0, bar.1, size);
|
||||
f.title.drag((bar.0, 120.0), size);
|
||||
let moved = f.title.scroll.get().amount;
|
||||
assert!(moved > 0.0);
|
||||
f.title.release();
|
||||
f.title.drag((bar.0, 60.0), size);
|
||||
assert_eq!(f.title.scroll.get().amount, moved);
|
||||
let atlas = crate::hud::HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap();
|
||||
let mut batch = HudBatch::new([480, 262]);
|
||||
f.title.draw(&atlas, &mut batch, (0.0, 0.0), true);
|
||||
assert!(!batch.vertices.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_world_tabs_follow_vanilla_and_their_choices_reach_the_action() {
|
||||
let mut f = Fixture::new();
|
||||
f.click("Singleplayer");
|
||||
let size = (480.0, 262.0);
|
||||
let labels = |f: &Fixture| -> Vec<(String, f32, f32, bool)> {
|
||||
f.title
|
||||
.buttons(size.0, size.1)
|
||||
.into_iter()
|
||||
.map(|b| (b.label, b.x, b.y, b.enabled))
|
||||
.collect()
|
||||
};
|
||||
// Game tab: the grid (210 × 117) at (0.5, 1/6) of 24..h-33, footer centred.
|
||||
let game = labels(&f);
|
||||
assert_eq!(game[0].1, 135.0);
|
||||
assert_eq!(game[0].2, 24.0 + 14.0 + 41.0);
|
||||
assert_eq!((game[3].1, game[3].2), (86.0, 235.0));
|
||||
assert_eq!((game[4].1, game[4].2), (244.0, 235.0));
|
||||
// Survival, Hardcore (Hard, no cheats, both locked), Creative (cheats on).
|
||||
f.title.click(240.0, game[0].2 + 10.0, size);
|
||||
let Mode::Create { options, .. } = &f.title.mode else {
|
||||
panic!()
|
||||
};
|
||||
assert!(options.hardcore && options.difficulty() == 3 && !options.commands(false));
|
||||
assert!(!labels(&f)[1].3 && !labels(&f)[2].3);
|
||||
f.title.click(240.0, game[0].2 + 10.0, size);
|
||||
let Mode::Create {
|
||||
creative, options, ..
|
||||
} = &f.title.mode
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(*creative && !options.hardcore && options.commands(true));
|
||||
// The World tab (second of three 124-wide tabs from x 54): its seed box
|
||||
// takes the focus, Superflat and the switches toggle.
|
||||
let (action, sound) = f.title.click(54.0 + 124.0 + 10.0, 10.0, size);
|
||||
assert!(sound && action == Action::None);
|
||||
let world = labels(&f);
|
||||
assert_eq!((world[0].1, world[0].2), (85.0, 38.0));
|
||||
assert_eq!((world[2].1, world[2].2), (85.0 + 266.0, 38.0 + 73.0));
|
||||
f.title.click(world[0].1 + 10.0, world[0].2 + 10.0, size);
|
||||
f.title.click(world[3].1 + 10.0, world[3].2 + 10.0, size);
|
||||
f.title.click(100.0, 38.0 + 41.0 + 10.0, size);
|
||||
let Mode::Create { focus, options, .. } = &f.title.mode else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(*focus, 1);
|
||||
assert!(options.flat && options.bonus_chest());
|
||||
let Action::Create { options, .. } = f.title.create_action() else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(
|
||||
options.world_gen(),
|
||||
crate::save::WorldGen {
|
||||
flat: true,
|
||||
structures: true,
|
||||
bonus_chest: true
|
||||
}
|
||||
);
|
||||
// The More tab's screens don't exist yet.
|
||||
f.title.click(54.0 + 248.0 + 10.0, 10.0, size);
|
||||
assert!(labels(&f)[..3].iter().all(|b| !b.3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_world_generation_settings_round_trip() {
|
||||
let f = Fixture::new();
|
||||
let dir = f.root.join("flat");
|
||||
let options = crate::save::WorldGen {
|
||||
flat: true,
|
||||
structures: false,
|
||||
bonus_chest: true,
|
||||
};
|
||||
crate::save::write_world_gen_settings(&dir, 42, options).unwrap();
|
||||
assert_eq!(crate::save::WorldGen::read(&dir), Some(options));
|
||||
let settings = crate::save::world_gen_settings(&dir).unwrap();
|
||||
assert_eq!(
|
||||
crate::save::text(
|
||||
settings
|
||||
.get("dimensions")
|
||||
.and_then(|d| d.get("minecraft:overworld"))
|
||||
.and_then(|o| o.get("generator"))
|
||||
.and_then(|g| g.get("type"))
|
||||
)
|
||||
.as_deref(),
|
||||
Some("minecraft:flat")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -430,6 +430,67 @@ pub(crate) fn scrollbar_thumb(
|
||||
Some((y, bar))
|
||||
}
|
||||
|
||||
/// `AbstractScrollArea`'s scrolling of a list `top..bottom` holding `content`
|
||||
/// pixels: the amount, the mouse wheel and the held scrollbar.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Scroll {
|
||||
pub amount: f32,
|
||||
/// The pointer's last y while the scrollbar is held (`scrolling`).
|
||||
held: Option<f32>,
|
||||
}
|
||||
impl Scroll {
|
||||
fn max(top: f32, bottom: f32, content: f32) -> f32 {
|
||||
(content - (bottom - top)).max(0.0)
|
||||
}
|
||||
/// `setScrollAmount`: kept within the content.
|
||||
pub fn clamp(&mut self, top: f32, bottom: f32, content: f32) {
|
||||
self.amount = self.amount.clamp(0.0, Self::max(top, bottom, content));
|
||||
}
|
||||
/// `mouseScrolled`: `rate` pixels per wheel step.
|
||||
pub fn wheel(&mut self, delta: f32, rate: f32, top: f32, bottom: f32, content: f32) {
|
||||
self.amount -= delta * rate;
|
||||
self.clamp(top, bottom, content);
|
||||
}
|
||||
/// `updateScrolling`: a press on the scrollbar column at `bar_x` (when
|
||||
/// there is something to scroll) holds it.
|
||||
pub fn press(
|
||||
&mut self,
|
||||
(x, y): (f32, f32),
|
||||
bar_x: f32,
|
||||
top: f32,
|
||||
bottom: f32,
|
||||
content: f32,
|
||||
) -> bool {
|
||||
let over = x >= bar_x && x <= bar_x + 6.0 && y >= top && y < bottom;
|
||||
self.held = (over && Self::max(top, bottom, content) > 0.0).then_some(y);
|
||||
self.held.is_some()
|
||||
}
|
||||
pub fn held(&self) -> bool {
|
||||
self.held.is_some()
|
||||
}
|
||||
/// `mouseDragged` while held: above or below the list jumps to an end,
|
||||
/// otherwise the thumb follows the pointer.
|
||||
pub fn drag(&mut self, y: f32, top: f32, bottom: f32, content: f32) {
|
||||
let Some(last) = self.held else { return };
|
||||
let max = Self::max(top, bottom, content);
|
||||
if y < top {
|
||||
self.amount = 0.0;
|
||||
} else if y > bottom {
|
||||
self.amount = max;
|
||||
} else {
|
||||
let height = bottom - top;
|
||||
let bar = ((height * height / content).trunc()).clamp(32.0, height - 8.0);
|
||||
self.amount += (y - last) * (max.max(1.0) / (height - bar)).max(1.0);
|
||||
}
|
||||
self.clamp(top, bottom, content);
|
||||
self.held = Some(y);
|
||||
}
|
||||
/// `onRelease`.
|
||||
pub fn release(&mut self) {
|
||||
self.held = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertical scroll bar (AbstractScrollArea): background and scroller sprites.
|
||||
pub fn scrollbar(
|
||||
batch: &mut HudBatch,
|
||||
@@ -576,6 +637,10 @@ impl EditBox {
|
||||
text_color: rgba(224, 224, 224, 255),
|
||||
}
|
||||
}
|
||||
/// When the field gained focus, for the cursor's blink.
|
||||
pub fn focused_since(&mut self, at: Instant) {
|
||||
self.focused_at = at;
|
||||
}
|
||||
pub fn inner_width(&self) -> f32 {
|
||||
if self.bordered {
|
||||
self.width - 8.0
|
||||
@@ -874,6 +939,28 @@ impl EditBox {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn held_scrollbars_follow_the_pointer_and_stop_at_the_ends() {
|
||||
// A 100-pixel list holding 400: the thumb is 25 -> 32 high, so a
|
||||
// pixel of drag scrolls 300 / 68 pixels (AbstractScrollArea.mouseDragged).
|
||||
let (top, bottom, content) = (0.0, 100.0, 400.0);
|
||||
let mut s = Scroll::default();
|
||||
assert!(!s.press((50.0, 10.0), 100.0, top, bottom, content));
|
||||
assert!(s.press((103.0, 10.0), 100.0, top, bottom, content));
|
||||
s.drag(20.0, top, bottom, content);
|
||||
assert!((s.amount - 10.0 * 300.0 / 68.0).abs() < 1e-3);
|
||||
s.drag(150.0, top, bottom, content);
|
||||
assert_eq!(s.amount, 300.0);
|
||||
s.drag(-5.0, top, bottom, content);
|
||||
assert_eq!(s.amount, 0.0);
|
||||
s.release();
|
||||
s.drag(50.0, top, bottom, content);
|
||||
assert_eq!(s.amount, 0.0);
|
||||
// Nothing to scroll: the column doesn't take the press.
|
||||
assert!(!s.press((103.0, 10.0), 100.0, top, bottom, 90.0));
|
||||
s.wheel(-2.0, 18.0, top, bottom, content);
|
||||
assert_eq!(s.amount, 36.0);
|
||||
}
|
||||
#[test]
|
||||
fn edit_box_editing() {
|
||||
let mut e = EditBox::new(0.0, 0.0, 100.0, 20.0);
|
||||
e.max_length = 10;
|
||||
|
||||
@@ -79,6 +79,9 @@ impl VanillaTerrain {
|
||||
}
|
||||
}
|
||||
let loot = dir.parent().and_then(crate::structure_blocks::loot_data);
|
||||
if let Some(root) = dir.parent() {
|
||||
crate::mobs::trial_spawner::load_registry(root);
|
||||
}
|
||||
let mut tick_blocks = Vec::with_capacity(registry.len());
|
||||
let mut tick_states = Vec::new();
|
||||
let mut last: Option<&str> = None;
|
||||
|
||||
@@ -1012,6 +1012,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
MerchantOffers(MerchantOffers) = MERCHANT_OFFERS,
|
||||
OpenScreen(OpenScreen) = OPEN_SCREEN,
|
||||
Ping(Ping) = PING,
|
||||
PongResponse(crate::packets::status::Ping) = PONG_RESPONSE,
|
||||
PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES,
|
||||
PlayerChat(PlayerChat) = PLAYER_CHAT,
|
||||
PlayerCombatKill(PlayerCombatKill) = PLAYER_COMBAT_KILL,
|
||||
@@ -1199,6 +1200,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
MovePlayerRot(MovePlayerRot) = MOVE_PLAYER_ROT,
|
||||
MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY,
|
||||
PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK,
|
||||
PingRequest(crate::packets::status::Ping) = PING_REQUEST,
|
||||
PlayerAction(PlayerAction) = PLAYER_ACTION,
|
||||
PlayerCommand(PlayerCommand) = PLAYER_COMMAND,
|
||||
PlayerInput(PlayerInput) = PLAYER_INPUT,
|
||||
@@ -1240,6 +1242,7 @@ mod tests {
|
||||
fn clientbound_round_trips() {
|
||||
let packets = vec![
|
||||
Clientbound::BundleDelimiter(Empty),
|
||||
Clientbound::PongResponse(crate::packets::status::Ping { time: 1_234_567 }),
|
||||
Clientbound::SetBorderCenter(SetBorderCenter { x: 1.5, z: -2.0 }),
|
||||
Clientbound::SetBorderLerpSize(SetBorderLerpSize {
|
||||
old_size: 10.0,
|
||||
@@ -1529,6 +1532,7 @@ mod tests {
|
||||
#[test]
|
||||
fn serverbound_round_trips() {
|
||||
let packets = vec![
|
||||
Serverbound::PingRequest(crate::packets::status::Ping { time: -7 }),
|
||||
Serverbound::AcceptTeleportation(AcceptTeleportation {
|
||||
id: 1,
|
||||
x: 0.5,
|
||||
|
||||
@@ -552,6 +552,31 @@ impl LootData {
|
||||
*random = c.random;
|
||||
items
|
||||
}
|
||||
/// LootTable.getRandomItems with an empty context (a trial spawner's
|
||||
/// reward): the stacks after the stack splitter. `random` is the table's
|
||||
/// random sequence (or the level random) and is advanced.
|
||||
pub fn roll_split<R: RandomSource + Clone>(
|
||||
&self,
|
||||
table: &str,
|
||||
random: &mut R,
|
||||
) -> Vec<LootStack> {
|
||||
let Some(json) = self.tables.get(table) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut c = Context {
|
||||
data: self,
|
||||
random: random.clone(),
|
||||
biome: None,
|
||||
visited: Vec::new(),
|
||||
luck: 0.0,
|
||||
open_water: None,
|
||||
entity: None,
|
||||
};
|
||||
let mut items = Vec::new();
|
||||
c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items));
|
||||
*random = c.random;
|
||||
items
|
||||
}
|
||||
/// LootTable.createStackSplitter (every item is enabled).
|
||||
fn split(&self, stack: LootStack, items: &mut Vec<LootStack>) {
|
||||
let max = self.facts(&stack.item).max_stack.max(1);
|
||||
|
||||
@@ -28,7 +28,9 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
|
||||
* the path, water putting them out, and the blocks they light (TNT, campfires,
|
||||
* candles). Pickup: the INTANGIBLE_PROJECTILE ammo the constructor sees, `setOwner`, and
|
||||
* `playerTouch` by a player (creative or not, with room in the inventory or not).
|
||||
* No entities to hit, no rain; sounds, particles and game events are recorded in order. */
|
||||
* Entities: a box in the way that takes the arrow's damage or refuses it (`onHitEntity`'s
|
||||
* REVERSE deflection). No rain; sounds, particles, game events, the damage dealt and
|
||||
* dropped pickups are recorded in order. */
|
||||
public final class VanillaArrowOracle {
|
||||
static final class Border extends WorldBorder {
|
||||
@Override public boolean isInsideCloseToBorder(Entity e,AABB b){return false;}
|
||||
@@ -50,6 +52,22 @@ public final class VanillaArrowOracle {
|
||||
@Override public net.minecraft.world.damagesource.DamageSource lava(){return any;}
|
||||
@Override public net.minecraft.world.damagesource.DamageSource inFire(){return any;}
|
||||
@Override public net.minecraft.world.damagesource.DamageSource onFire(){return any;}
|
||||
@Override public net.minecraft.world.damagesource.DamageSource arrow(AbstractArrow arrow,Entity owner){return any;}
|
||||
}
|
||||
/** The entity in the way (allocated without a constructor): a box at a position that
|
||||
* takes the arrow's damage or refuses it (a raised shield), recording what it was dealt. */
|
||||
static final class Target extends Entity {
|
||||
boolean takes;List<String> events;
|
||||
Target(){super(null,null);}
|
||||
@Override protected void defineSynchedData(net.minecraft.network.syncher.SynchedEntityData.Builder entityData){}
|
||||
@Override protected void readAdditionalSaveData(net.minecraft.world.level.storage.ValueInput input){}
|
||||
@Override protected void addAdditionalSaveData(net.minecraft.world.level.storage.ValueOutput output){}
|
||||
@Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,net.minecraft.world.damagesource.DamageSource source,float damage){
|
||||
events.add(String.format("hurt %08x",Float.floatToIntBits(damage)));return takes;
|
||||
}
|
||||
@Override public boolean isPickable(){return true;}
|
||||
// Untagged: neither DEFLECTS_PROJECTILES nor REDIRECTABLE_PROJECTILE.
|
||||
@Override public boolean is(net.minecraft.tags.TagKey<EntityType<?>> tag){return false;}
|
||||
}
|
||||
static final class Level extends net.minecraft.server.level.ServerLevel {
|
||||
Map<Long,Chunk> chunks;WorldBorder border;net.minecraft.util.RandomSource rng;List<String> events;net.minecraft.server.MinecraftServer server;
|
||||
@@ -64,13 +82,16 @@ public final class VanillaArrowOracle {
|
||||
@Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);}
|
||||
@Override public FluidState getFluidState(BlockPos p){return getBlockState(p).getFluidState();}
|
||||
@Override public List<VoxelShape> getEntityCollisions(Entity e,AABB b){return List.of();}
|
||||
@Override public List<Entity> getEntities(Entity e,AABB b,java.util.function.Predicate<? super Entity> p){return List.of();}
|
||||
Target target;
|
||||
@Override public List<Entity> getEntities(Entity e,AABB b,java.util.function.Predicate<? super Entity> p){
|
||||
return target!=null&&target.getBoundingBox().intersects(b)&&p.test(target)?List.of(target):List.of();
|
||||
}
|
||||
@Override public WorldBorder getWorldBorder(){return border;}
|
||||
@Override public net.minecraft.util.RandomSource getRandom(){return rng;}
|
||||
@Override public boolean isRainingAt(BlockPos p){return false;}
|
||||
@Override public net.minecraft.server.MinecraftServer getServer(){return server;}
|
||||
@Override public void gameEvent(Holder<GameEvent> event,Vec3 pos,GameEvent.Context context){
|
||||
if(event==GameEvent.PROJECTILE_SHOOT)events.add("shoot-event");else if(event==GameEvent.SPLASH)events.add("splash-event");else throw new AssertionError(event);
|
||||
if(event==GameEvent.PROJECTILE_SHOOT)events.add("shoot-event");else if(event==GameEvent.SPLASH)events.add("splash-event");else if(event!=GameEvent.PROJECTILE_LAND)throw new AssertionError(event);
|
||||
}
|
||||
// Projectile.onHit's PROJECTILE_LAND: the game posts it from the hit it is handed.
|
||||
@Override public void gameEvent(Holder<GameEvent> event,BlockPos pos,GameEvent.Context context){
|
||||
@@ -84,6 +105,8 @@ public final class VanillaArrowOracle {
|
||||
chunks.get(key(p.getX()>>4,p.getZ()>>4)).write(p,Block.getId(state));events.add("write "+p.getX()+","+p.getY()+","+p.getZ()+" "+Block.getId(state)+" "+flags);return true;
|
||||
}
|
||||
@Override public boolean addFreshEntity(Entity e){
|
||||
// spawnAtLocation's item (its motion comes from the item's own unseeded random).
|
||||
if(e instanceof net.minecraft.world.entity.item.ItemEntity item){events.add("drop "+bits(item.position())+" "+item.getItem().getCount());return true;}
|
||||
if(!(e instanceof net.minecraft.world.entity.item.PrimedTnt tnt))throw new AssertionError(e);
|
||||
events.add("spawn tnt "+bits(tnt.position())+" "+tnt.getFuse());return true;
|
||||
}
|
||||
@@ -154,7 +177,7 @@ public final class VanillaArrowOracle {
|
||||
// The client's recreateFromPacket snaps a spawned arrow, old position included.
|
||||
a.setOldPosAndRot();
|
||||
a.setCritArrow(row.get("crit").getAsBoolean());a.setNoPhysics(row.get("no_physics").getAsBoolean());
|
||||
String touched="-";
|
||||
String touched="-";level.target=null;
|
||||
for(var value:row.getAsJsonArray("ops")){
|
||||
var op=value.getAsJsonObject();
|
||||
switch(op.get("mode").getAsString()){
|
||||
@@ -178,6 +201,14 @@ public final class VanillaArrowOracle {
|
||||
};
|
||||
a.setOwner(owner);a.setOwner((Entity)null);
|
||||
}
|
||||
// A player-sized box standing at the position.
|
||||
case "target"->{
|
||||
var t=(Target)allocate.invoke(unsafe,Target.class);t.takes=op.get("takes").getAsBoolean();t.events=level.events;
|
||||
var at=VanillaSceneCollisionOracle.vector(op.get("position"));
|
||||
field(Entity.class,"level").set(t,level);field(Entity.class,"position").set(t,at);
|
||||
field(Entity.class,"bb").set(t,EntityDimensions.scalable(0.6F,1.8F).makeBoundingBox(at));
|
||||
level.target=t;
|
||||
}
|
||||
// ArrowItem.asProjectile (dispensers) sets pickup directly.
|
||||
case "pickup"->a.pickup=AbstractArrow.Pickup.byOrdinal(op.get("value").getAsInt());
|
||||
case "touch"->{
|
||||
|
||||
@@ -470,7 +470,7 @@ public final class VanillaDispenserOracle {
|
||||
static final class Clicker extends net.minecraft.server.level.ServerPlayer {
|
||||
VanillaBlockUpdateOracle.World world;
|
||||
boolean creative, sneaking;
|
||||
ItemStack hand;
|
||||
ItemStack hand, offhand;
|
||||
List<String> stats;
|
||||
String using;
|
||||
Clicker() {
|
||||
@@ -485,12 +485,14 @@ public final class VanillaDispenserOracle {
|
||||
@Override public boolean isDescending() { return sneaking; }
|
||||
@Override public EntityType<?> getType() { return EntityTypes.PLAYER; }
|
||||
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
|
||||
@Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; }
|
||||
@Override public ItemStack getItemBySlot(EquipmentSlot slot) {
|
||||
return slot == EquipmentSlot.MAINHAND ? hand : slot == EquipmentSlot.OFFHAND ? offhand : ItemStack.EMPTY;
|
||||
}
|
||||
@Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
|
||||
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
|
||||
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : offhand;
|
||||
}
|
||||
@Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) {
|
||||
if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack;
|
||||
if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack; else offhand = stack;
|
||||
}
|
||||
@Override public void startUsingItem(net.minecraft.world.InteractionHand h) {
|
||||
using = BuiltInRegistries.ITEM.getKey(getItemInHand(h).getItem()).toString();
|
||||
@@ -515,9 +517,9 @@ public final class VanillaDispenserOracle {
|
||||
* A right click on the top of the block at `pos` (`ServerPlayerGameMode.useItemOn`
|
||||
* of the real game mode, survival or creative): the block's `useItemOn` and
|
||||
* `useWithoutItem`, then the item's `useOn` (`BlockItem.place`, falling back
|
||||
* to eating a consumable), and `useItem` when that passes, as
|
||||
* `Minecraft.startUseItem` goes on to. The statistics, the held stack and
|
||||
* the item the player started using follow.
|
||||
* to eating a consumable), and `useItem` when that passes, for the main
|
||||
* hand and then the off hand, as `Minecraft.startUseItem` goes on to. The
|
||||
* statistics, the held stacks and the item the player started using follow.
|
||||
*/
|
||||
static List<String> useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception {
|
||||
if (VanillaBlockUpdateOracle.Server.players == null) {
|
||||
@@ -528,6 +530,7 @@ public final class VanillaDispenserOracle {
|
||||
player.creative = use.get("creative").getAsBoolean();
|
||||
player.sneaking = use.get("sneaking").getAsBoolean();
|
||||
player.hand = stack(use.get("item").getAsString());
|
||||
player.offhand = use.has("offhand") ? stack(use.get("offhand").getAsString()) : ItemStack.EMPTY;
|
||||
player.stats = new ArrayList<>();
|
||||
var abilities = new net.minecraft.world.entity.player.Abilities();
|
||||
abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative;
|
||||
@@ -556,16 +559,18 @@ public final class VanillaDispenserOracle {
|
||||
player.creative ? net.minecraft.world.level.GameType.CREATIVE : net.minecraft.world.level.GameType.SURVIVAL);
|
||||
var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0),
|
||||
net.minecraft.core.Direction.UP, pos, false);
|
||||
var hand = net.minecraft.world.InteractionHand.MAIN_HAND;
|
||||
var result = gameMode.useItemOn(player, w, player.getItemInHand(hand), hand, hit);
|
||||
// Minecraft.startUseItem: a click on a block that neither succeeded nor
|
||||
// failed goes on to use the item in the same hand.
|
||||
if (!(result instanceof net.minecraft.world.InteractionResult.Success)
|
||||
&& !(result instanceof net.minecraft.world.InteractionResult.Fail) && !player.hand.isEmpty()) {
|
||||
gameMode.useItem(player, w, player.getItemInHand(hand), hand);
|
||||
// Minecraft.startUseItem: each hand in turn clicks the block, then uses
|
||||
// its item unless the click succeeded or failed; a success ends it.
|
||||
for (var hand : net.minecraft.world.InteractionHand.values()) {
|
||||
ItemStack held = player.getItemInHand(hand);
|
||||
var result = gameMode.useItemOn(player, w, held, hand, hit);
|
||||
if (result instanceof net.minecraft.world.InteractionResult.Success
|
||||
|| result instanceof net.minecraft.world.InteractionResult.Fail) break;
|
||||
if (!held.isEmpty() && gameMode.useItem(player, w, held, hand) instanceof net.minecraft.world.InteractionResult.Success) break;
|
||||
}
|
||||
List<String> out = new ArrayList<>(player.stats);
|
||||
out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using));
|
||||
out.add("held " + ParityData.canon(player.hand) + " offhand " + ParityData.canon(player.offhand)
|
||||
+ " using " + (player.using == null ? "-" : player.using));
|
||||
var respawn = player.getRespawnConfig();
|
||||
out.add("respawn " + (respawn == null ? "-" : respawn.respawnData().dimension().identifier() + " " + VanillaBlockUpdateOracle.pos(respawn.respawnData().pos())));
|
||||
return out;
|
||||
|
||||
@@ -77,6 +77,11 @@ import net.minecraft.world.phys.Vec3;
|
||||
* here is a fixed "neutral" source (nextInt 0, nextFloat and nextDouble 0.75),
|
||||
* so finalizeSpawn's own outcomes stay out of scope while its effect on later
|
||||
* attempts (the finalized mob's box obstructs them) is deterministic.
|
||||
*
|
||||
* Spawner cases tick a SpawnerBlockEntity; trial cases tick a
|
||||
* TrialSpawnerBlockEntity with the game time advancing, its block's state
|
||||
* changes, sounds, ejected items (loot tables and random sequences of the
|
||||
* vanilla data) and, when asked, the death of every mob it spawned.
|
||||
*/
|
||||
public final class VanillaNaturalSpawnOracle {
|
||||
static Object unsafe;
|
||||
@@ -167,7 +172,10 @@ public final class VanillaNaturalSpawnOracle {
|
||||
int next = 1;
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public Difficulty getDifficulty() { return difficulty; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
/** The game time (trial cases advance it). */
|
||||
long time;
|
||||
net.minecraft.world.level.block.entity.BlockEntity trial;
|
||||
@Override public long getGameTime() { return time; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public BlockState getBlockState(BlockPos pos) {
|
||||
@@ -215,6 +223,23 @@ public final class VanillaNaturalSpawnOracle {
|
||||
log.add(tick + " spawn " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()) + " " + bits(entity.getX()) + " " + bits(entity.getY()) + " " + bits(entity.getZ()) + " " + yaw(entity));
|
||||
return true;
|
||||
}
|
||||
@Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int recursionLeft) {
|
||||
blocks.add(Map.entry(new Box(pos.getX(), pos.getY(), pos.getZ(), pos.getX(), pos.getY(), pos.getZ()), state));
|
||||
if (trial != null && trial.getBlockPos().equals(pos)) trial.setBlockState(state);
|
||||
if (tick >= 0) log.add(tick + " state " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.STATE).map(v -> v.getSerializedName()).orElse("-")
|
||||
+ " " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.OMINOUS).orElse(false));
|
||||
return true;
|
||||
}
|
||||
@Override public void blockEntityChanged(BlockPos pos) {}
|
||||
@Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) {}
|
||||
@Override public Entity getEntity(UUID uuid) {
|
||||
for (Entity e : entities) if (e.getUUID().equals(uuid)) return e;
|
||||
for (Entity e : playerList) if (e.getUUID().equals(uuid)) return e;
|
||||
return null;
|
||||
}
|
||||
@Override public void playSound(Entity except, double x, double y, double z, net.minecraft.sounds.SoundEvent sound, net.minecraft.sounds.SoundSource source, float volume, float pitch) {
|
||||
if (tick >= 0) log.add(tick + " sound " + sound.location() + " " + bits(x) + " " + bits(y) + " " + bits(z) + " " + volume + " " + pitch);
|
||||
}
|
||||
@Override public void blockEvent(BlockPos pos, net.minecraft.world.level.block.Block block, int b0, int b1) { if (tick >= 0) log.add(tick + " bevent " + b0 + " " + b1); }
|
||||
@Override public void sendBlockUpdated(BlockPos pos, BlockState old, BlockState current, int flags) { if (tick >= 0) log.add(tick + " update"); }
|
||||
@Override public void levelEvent(Entity source, int type, BlockPos pos, int data) { if (tick >= 0) log.add(tick + " levent " + type + " " + data); }
|
||||
@@ -249,7 +274,14 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@Override public boolean addFreshEntity(Entity entity) { entities.add(entity); return true; }
|
||||
@Override public boolean addFreshEntity(Entity entity) {
|
||||
if (entity instanceof net.minecraft.world.entity.item.ItemEntity item && tick >= 0) {
|
||||
Vec3 v = item.getDeltaMovement();
|
||||
log.add(tick + " item " + BuiltInRegistries.ITEM.getKey(item.getItem().getItem()) + " " + item.getItem().getCount() + " " + bits(item.getX()) + " " + bits(item.getY()) + " " + bits(item.getZ()) + " " + bits(v.x) + " " + bits(v.y) + " " + bits(v.z));
|
||||
}
|
||||
entities.add(entity);
|
||||
return true;
|
||||
}
|
||||
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
|
||||
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) {
|
||||
if (maxDist == -1.0 && !filter) log.add("try " + (int) Math.floor(x) + " " + (int) Math.floor(z));
|
||||
@@ -257,6 +289,16 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
}
|
||||
|
||||
/** The server: loot tables and random sequences for trial spawner rewards. */
|
||||
static final class OracleServer extends net.minecraft.server.dedicated.DedicatedServer {
|
||||
OracleServer() { super(null, null, null, null, null, null, null, null, null, null); }
|
||||
net.minecraft.server.ReloadableServerRegistries.Holder registries;
|
||||
net.minecraft.world.RandomSequences sequences;
|
||||
long seed;
|
||||
@Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return registries; }
|
||||
@Override public RandomSource getRandomSequence(Identifier key) { return sequences.get(key, seed); }
|
||||
}
|
||||
|
||||
static final class Chunk extends LevelChunk {
|
||||
Chunk() { super((Level) null, (ChunkPos) null); }
|
||||
Lvl level;
|
||||
@@ -352,6 +394,58 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
static String bits(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
|
||||
/**
|
||||
* TrialSpawner.tickServer `ticks` times from game time `t0` at `spos`, on a
|
||||
* trial spawner block in state `state` (ominous when `ominous=1`) loaded
|
||||
* from `snbt` (base64 SNBT). Every `kill` ticks the mobs it spawned die.
|
||||
*/
|
||||
static void trialCase(Lvl level, Map<String, String> c, RegistryAccess access, HolderLookup<net.minecraft.world.level.block.Block> blockLookup,
|
||||
RandomSource mainRandom, List<String> log) throws Exception {
|
||||
level.spawnerRandom = mainRandom;
|
||||
level.tick = -1;
|
||||
String[] sp = c.get("spos").split(",");
|
||||
BlockPos at = new BlockPos(Integer.parseInt(sp[0]), Integer.parseInt(sp[1]), Integer.parseInt(sp[2]));
|
||||
BlockState block = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup,
|
||||
"minecraft:trial_spawner[trial_spawner_state=" + c.getOrDefault("state", "waiting_for_players") + ",ominous=" + c.getOrDefault("ominous", "0").equals("1") + "]", false).blockState();
|
||||
level.blocks.add(Map.entry(new Box(at.getX(), at.getY(), at.getZ(), at.getX(), at.getY(), at.getZ()), block));
|
||||
var nbt = net.minecraft.nbt.TagParser.parseCompoundFully(new String(Base64.getDecoder().decode(c.get("snbt")), StandardCharsets.UTF_8));
|
||||
var entity = new net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity(at, block);
|
||||
entity.setLevel(level);
|
||||
level.trial = entity;
|
||||
entity.getTrialSpawner().load(net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, access, nbt));
|
||||
int ticks = Integer.parseInt(c.getOrDefault("ticks", "1"));
|
||||
long t0 = Long.parseLong(c.getOrDefault("t0", "0"));
|
||||
int kill = Integer.parseInt(c.getOrDefault("kill", "0"));
|
||||
int before = level.entities.size();
|
||||
try {
|
||||
for (int t = 0; t < ticks; t++) {
|
||||
level.tick = t;
|
||||
level.time = t0 + t;
|
||||
BlockState state = level.getBlockState(at);
|
||||
entity.getTrialSpawner().tickServer(level, at, state.getValue(net.minecraft.world.level.block.TrialSpawnerBlock.OMINOUS));
|
||||
if (kill > 0 && t % kill == kill - 1) {
|
||||
int n = 0;
|
||||
for (Iterator<Entity> it = level.entities.subList(before, level.entities.size()).iterator(); it.hasNext(); ) {
|
||||
if (it.next() instanceof Mob) { it.remove(); n++; }
|
||||
}
|
||||
if (n > 0) log.add(t + " kill " + n);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
level.tick = -1;
|
||||
level.spawnerRandom = null;
|
||||
}
|
||||
var out = net.minecraft.world.level.storage.TagValueOutput.createWithContext(net.minecraft.util.ProblemReporter.DISCARDING, access);
|
||||
entity.getTrialSpawner().store(out);
|
||||
CompoundTag saved = out.buildResult();
|
||||
String next = saved.getCompound("spawn_data").flatMap(d -> d.getCompound("entity")).flatMap(e -> e.getString("id")).orElse("-");
|
||||
log.add("end state=" + level.getBlockState(at).getValue(net.minecraft.world.level.block.TrialSpawnerBlock.STATE).getSerializedName()
|
||||
+ " players=" + saved.getListOrEmpty("registered_players").size() + " mobs=" + saved.getListOrEmpty("current_mobs").size()
|
||||
+ " cooldown=" + saved.getLongOr("cooldown_ends_at", 0L) + " next_spawn=" + saved.getLongOr("next_mob_spawns_at", 0L)
|
||||
+ " total=" + saved.getIntOr("total_mobs_spawned", 0) + " data=" + next + " eject=" + saved.getString("ejecting_loot_table").orElse("-"));
|
||||
log.add("next " + mainRandom.nextInt(1000));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
@@ -382,7 +476,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
var structureLookup = access.lookupOrThrow(Registries.STRUCTURE);
|
||||
|
||||
// A server that only answers debug subscribers (path navigation asks).
|
||||
var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
|
||||
var server = (OracleServer) alloc(OracleServer.class);
|
||||
server.registries = new net.minecraft.server.ReloadableServerRegistries.Holder(lookup);
|
||||
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.fake = server;
|
||||
@@ -423,6 +518,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
randomPos.setAccessible(true);
|
||||
Field entityId = Entity.class.getDeclaredField("id");
|
||||
entityId.setAccessible(true);
|
||||
Field eyeHeight = Entity.class.getDeclaredField("eyeHeight");
|
||||
eyeHeight.setAccessible(true);
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
@@ -497,7 +594,12 @@ public final class VanillaNaturalSpawnOracle {
|
||||
OraclePlayer player = (OraclePlayer) alloc(OraclePlayer.class);
|
||||
player.mode = GameType.byName(p.length > 1 ? p[1] : "survival");
|
||||
entityId.setInt(player, 100000 + i);
|
||||
put(player, Entity.class, "position", new Vec3(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2])));
|
||||
Vec3 at = new Vec3(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2]));
|
||||
put(player, Entity.class, "position", at);
|
||||
put(player, Entity.class, "blockPosition", BlockPos.containing(at));
|
||||
put(player, Entity.class, "uuid", new UUID(0L, i + 1));
|
||||
eyeHeight.setFloat(player, 1.62F);
|
||||
put(player, LivingEntity.class, "activeEffects", new HashMap<>());
|
||||
level.playerList.add(player);
|
||||
}
|
||||
level.entities.clear();
|
||||
@@ -510,6 +612,11 @@ public final class VanillaNaturalSpawnOracle {
|
||||
if (p.length > 2 && p[2].equals("p") && e instanceof Mob mob) mob.setPersistenceRequired();
|
||||
level.entities.add(e);
|
||||
}
|
||||
put(level, ServerLevel.class, "players", level.playerList);
|
||||
server.sequences = new net.minecraft.world.RandomSequences();
|
||||
server.seed = level.seed;
|
||||
level.time = 0L;
|
||||
level.trial = null;
|
||||
RandomSource mainRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
|
||||
put(level, Level.class, "random", mainRandom);
|
||||
String mode = c.getOrDefault("mode", "chunk");
|
||||
@@ -547,6 +654,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
log.add("end delay=" + saved.getShortOr("Delay", (short) 0) + " next=" + next + " pots=" + pots);
|
||||
log.add("next " + mainRandom.nextInt(1000));
|
||||
} else if (mode.equals("trial")) {
|
||||
trialCase(level, c, access, blockLookup, mainRandom, log);
|
||||
} else if (mode.equals("gen")) {
|
||||
level.logColumns = true;
|
||||
int n = level.entities.size();
|
||||
|
||||
@@ -4,13 +4,19 @@ import java.io.PrintWriter;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundEvents;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.TickRateManager;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.vehicle.minecart.Minecart;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Drives the real SoundEngine (see VanillaSoundRig) with a script of plays,
|
||||
@@ -33,6 +39,18 @@ public final class VanillaSoundEngineOracle {
|
||||
}
|
||||
}
|
||||
|
||||
/** A minecart the minecart sound instances follow. */
|
||||
public static final class Cart extends Minecart {
|
||||
Cart() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSilent() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
@@ -53,6 +71,10 @@ public final class VanillaSoundEngineOracle {
|
||||
Constructor<UnderLiquidSubSound> sub = UnderLiquidSubSound.class.getDeclaredConstructor(LocalPlayer.class, SoundEvent.class);
|
||||
sub.setAccessible(true);
|
||||
var instances = new TreeMap<String, SoundInstance>();
|
||||
var carts = new TreeMap<String, Cart>();
|
||||
var level = VanillaSoundRig.make(ClientLevel.class);
|
||||
var tickRate = new TickRateManager();
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "tickRateManager", tickRate);
|
||||
var manager = rig.manager;
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
@@ -72,6 +94,9 @@ public final class VanillaSoundEngineOracle {
|
||||
case "loop" -> new BiomeAmbientSoundsHandler.LoopSoundInstance(event);
|
||||
case "uloop" -> new UnderLiquidAmbientSoundInstance(event, actor, LocalPlayer::isUnderWater);
|
||||
case "usub" -> sub.newInstance(actor, event);
|
||||
case "cart" -> new MinecartSoundInstance(carts.get(a[3]));
|
||||
case "rcart", "rcartu" -> new RidingMinecartSoundInstance(actor, carts.get(a[3]), a[2].equals("rcartu"),
|
||||
a[2].equals("rcartu") ? SoundEvents.MINECART_INSIDE_UNDERWATER : SoundEvents.MINECART_INSIDE, 0.0F, 0.75F, 1.0F);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
};
|
||||
if (!a[2].equals("simple")) seed(instance, seed);
|
||||
@@ -99,6 +124,23 @@ public final class VanillaSoundEngineOracle {
|
||||
actor.underwater = a[1].equals("1");
|
||||
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[2].equals("1") ? Entity.RemovalReason.DISCARDED : null);
|
||||
}
|
||||
case "cart" -> {
|
||||
// cart name x y z dx dy dz removed
|
||||
Cart cart = carts.get(a[1]);
|
||||
if (cart == null) {
|
||||
cart = VanillaSoundRig.make(Cart.class);
|
||||
VanillaSoundRig.set(cart, Entity.class, "level", level);
|
||||
carts.put(a[1], cart);
|
||||
}
|
||||
VanillaSoundRig.set(cart, Entity.class, "position", new Vec3(d(a[2]), d(a[3]), d(a[4])));
|
||||
VanillaSoundRig.set(cart, Entity.class, "deltaMovement", new Vec3(d(a[5]), d(a[6]), d(a[7])));
|
||||
VanillaSoundRig.set(cart, Entity.class, "removalReason", a[8].equals("1") ? Entity.RemovalReason.DISCARDED : null);
|
||||
}
|
||||
case "ride" -> VanillaSoundRig.set(actor, Entity.class, "vehicle", a[1].equals("-") ? null : carts.get(a[1]));
|
||||
case "freeze" -> {
|
||||
tickRate.setFrozen(a[1].equals("1"));
|
||||
tickRate.tick();
|
||||
}
|
||||
case "tick" -> manager.tick(a[1].equals("1"));
|
||||
case "forget" -> instances.remove(a[1]);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
|
||||
@@ -20,9 +20,14 @@ burning and non-burning arrows; pickup: arrows from no one, a player or a mob,
|
||||
from intangible ammo (creative, Infinity, multishot extras) or a dispenser,
|
||||
touched in flight, while shaking and when stuck, by survival and creative
|
||||
players with empty, partly and fully filled inventories, and without physics.
|
||||
No entities to hit, no rain.
|
||||
Entities: a player-sized box in the way that takes the arrow's damage (the
|
||||
arrow is spent with its hit sound) or refuses it (a raised shield: the arrow
|
||||
turns back, and drops its pickup when left almost still), struck squarely or
|
||||
grazed within ProjectileUtil's margin, crits drawing from the arrow's random.
|
||||
No rain.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
@@ -181,6 +186,26 @@ def corpus():
|
||||
for creative in [False, True]:
|
||||
ops = ([op('owner', owner)] if owner else []) + [o for _ in range(4) for o in (op('tick'), touch(creative, 'empty'))]
|
||||
yield arrow((rng.uniform(18, 30), 6, rng.uniform(4, 30)), aim(.4, rng.uniform(-180, 180), 0), ops, no_physics=True)
|
||||
# An entity in the way (a player-sized box on the floor) that takes or
|
||||
# refuses the damage: squarely, grazing within the margin (older arrows),
|
||||
# missing, and slow enough to drop on the spot.
|
||||
def target(x, z, takes):
|
||||
return op('target', position=vec((x, 4, z)), takes=takes)
|
||||
for takes in [True, False]:
|
||||
for _ in range(24):
|
||||
tx, tz = rng.uniform(21, 27), rng.uniform(21, 27)
|
||||
yaw, distance = rng.uniform(-180, 180), rng.uniform(1.5, 9)
|
||||
start = (tx + math.sin(math.radians(yaw)) * distance, rng.uniform(4.2, 7.5), tz - math.cos(math.radians(yaw)) * distance)
|
||||
aim_at = (tx + rng.uniform(-.75, .75), rng.uniform(4, 6.2), tz + rng.uniform(-.75, .75))
|
||||
d = [aim_at[i] - start[i] for i in range(3)]
|
||||
speed = rng.choice([.4, 1.1, 2.2, 3]) / math.sqrt(sum(c * c for c in d))
|
||||
yield arrow(start, [c * speed for c in d], [target(tx, tz, takes)] + ticks(45), crit=rng.random() < .5)
|
||||
for pickup in [0, 1]:
|
||||
for speed in [.002, .03, .2]:
|
||||
# Struck in the first tick; the slowest, turned back at a
|
||||
# tenth of its speed, is left almost still and stops.
|
||||
ops = [op('pickup', pickup), target(25.5, 25.5, takes)] + ticks(6)
|
||||
yield arrow((25.199, 4.5, 25.5), (speed, 0, 0), ops)
|
||||
# Despawning 1200 ticks after sticking in the floor.
|
||||
for _ in range(2):
|
||||
yield arrow((rng.uniform(18, 30), 6, rng.uniform(4, 30)), (0, -1, 0), ticks(1215))
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
The oracle runs the real `SoundManager`/`SoundEngine` on OpenAL Soft's "No
|
||||
Output" device (see VanillaSoundRig) and replays scripts of plays (simple,
|
||||
biome loop, underwater loop and sub-sound instances), stops (by instance, by
|
||||
sound and/or source, all), category gains, source volume options and
|
||||
refreshes, channel ends, delayed and queued sounds, pauses and client ticks.
|
||||
biome loop, underwater loop, sub-sound, minecart and riding-minecart
|
||||
instances), stops (by instance, by sound and/or source, all), category gains,
|
||||
source volume options and refreshes, channel ends, delayed and queued sounds,
|
||||
pauses, minecart states and client ticks.
|
||||
After every step it prints each instance's `isActive` and the AL source the
|
||||
engine configured (state, gain, pitch, position, relative, looping, distance
|
||||
model, max distance, rolloff, reference distance), the subtitle notifications
|
||||
@@ -13,6 +14,7 @@ and the channel pool counts. Horizon's `SoundEngine` replays the scripts
|
||||
against a backend that records the same AL source fields.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
|
||||
try:
|
||||
@@ -38,6 +40,9 @@ class Script:
|
||||
self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay,
|
||||
'linear' if linear else 'none', relative, seed)
|
||||
|
||||
def cart(self, name, at, delta, removed=0):
|
||||
self.add('cart', name, *map(dbits, at), *map(dbits, delta), removed)
|
||||
|
||||
def tick(self, n=1, paused=0):
|
||||
for _ in range(n):
|
||||
self.add('tick', paused)
|
||||
@@ -117,6 +122,30 @@ def scripted(s):
|
||||
s.tick(3)
|
||||
s.add('player', 0, 0)
|
||||
s.reset()
|
||||
# Minecarts: the rolling sound and the two riding sounds, by speed,
|
||||
# underwater, frozen ticks, getting out and the cart's removal.
|
||||
s.cart('k', (10.3, 64.0, 5.7), (0.0, 0.0, 0.0))
|
||||
s.play('m', 'k', kind='cart', seed=61)
|
||||
s.tick(2)
|
||||
for i, v in enumerate([0.005, 0.0099, 0.01, 0.1, 0.3, 0.5, 0.51, 0.8, 1.0, 1.2, 2.0, 0.0]):
|
||||
s.cart('k', (10.3 + i * 0.37123, 64.0625, 5.7 - i * 0.1), (v * 0.6, -0.04, v * 0.8))
|
||||
s.tick(2)
|
||||
if i == 4:
|
||||
s.add('freeze', 1)
|
||||
s.tick(3)
|
||||
s.add('freeze', 0)
|
||||
s.add('ride', 'k')
|
||||
s.play('r', 'k', kind='rcartu', seed=62)
|
||||
s.play('i', 'k', kind='rcart', seed=63)
|
||||
if i == 8:
|
||||
s.add('player', 1, 0)
|
||||
s.tick(3)
|
||||
s.add('player', 0, 0)
|
||||
s.add('ride', '-')
|
||||
s.tick(3)
|
||||
s.cart('k', (1.0, 2.0, 3.0), (0.2, 0.0, 0.0), removed=1)
|
||||
s.tick(3)
|
||||
s.reset()
|
||||
# Queued tickables, delayed and manually looped sounds.
|
||||
s.play('q', loop, kind='loop', seed=31)
|
||||
s.add('stop', 'q')
|
||||
@@ -173,6 +202,10 @@ def scripted(s):
|
||||
def fuzz(s, rng, steps):
|
||||
names = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5']
|
||||
live = set()
|
||||
for cart in ('k0', 'k1'):
|
||||
s.cart(cart, (0.0, 64.0, 0.0), (0.0, 0.0, 0.0))
|
||||
s.add('ride', '-')
|
||||
s.add('freeze', 0)
|
||||
for _ in range(steps):
|
||||
op = rng.random()
|
||||
name = rng.choice(names)
|
||||
@@ -210,6 +243,18 @@ def fuzz(s, rng, steps):
|
||||
elif op < 0.57:
|
||||
s.add('forget', name)
|
||||
live.discard(name)
|
||||
elif op < 0.62:
|
||||
speed = rng.choice([0.0, 0.005, 0.01, 0.3, 0.5, 1.0, rng.uniform(0, 1.5)])
|
||||
angle = rng.uniform(0, 6.3)
|
||||
at = (rng.uniform(-50, 50), rng.uniform(0, 80), rng.uniform(-50, 50))
|
||||
s.cart(rng.choice(['k0', 'k1']), at, (speed * math.cos(angle), rng.uniform(-0.1, 0.1), speed * math.sin(angle)), int(rng.random() < 0.08))
|
||||
elif op < 0.65:
|
||||
s.add('ride', rng.choice(['k0', 'k1', '-']))
|
||||
elif op < 0.66:
|
||||
s.add('freeze', int(rng.random() < 0.5))
|
||||
elif op < 0.70:
|
||||
s.play(name, rng.choice(['k0', 'k1']), kind=rng.choice(['cart', 'rcart', 'rcartu']), seed=rng.getrandbits(63))
|
||||
live.add(name)
|
||||
else:
|
||||
s.tick(rng.randrange(1, 6))
|
||||
|
||||
@@ -238,7 +283,8 @@ def main():
|
||||
'AL source parameters set by play/tickInGameSound/refreshCategoryVolume (gain from calculateVolume, clamped pitch, linear '
|
||||
'attenuation distance, looping, position, relative), isActive, the 20-tick minimum lifetime, channel ends, stop by instance/sound/source/all, '
|
||||
'pauseAllExcept/resume, tickMusicWhenPaused, queued tickables, playDelayed and manual looping, LoopSoundInstance, '
|
||||
'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, subtitle notifications and ranges, and the 247/8 channel pools. '
|
||||
'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, MinecartSoundInstance and RidingMinecartSoundInstance ticks (speed, '
|
||||
'riding, underwater, frozen ticks, removal), subtitle notifications and ranges, and the 247/8 channel pools. '
|
||||
'Not compared: decoded sample output, OpenAL panning/HRTF and distance gain inside the mixer, asset loading timing.')
|
||||
print(f'{matched:,} sound engine lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
|
||||
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare trial spawners (TrialSpawner.tickServer and TrialSpawnerState) with vanilla.
|
||||
|
||||
Java (VanillaNaturalSpawnOracle, mode=trial) loads a TrialSpawnerBlockEntity
|
||||
from each case's NBT on the oracle's stand-in ServerLevel, on a trial spawner
|
||||
block in the case's state, and runs `TrialSpawner.tickServer` tick by tick
|
||||
with the game time advancing. Rust (natural_spawn_fixture, mode=trial) loads
|
||||
`mobs::trial_spawner::TrialSpawner` from the same NBT and ticks it on the same
|
||||
world. Both log, tick by tick, the block's state changes, the player
|
||||
detection events, every spawn (type, exact position and yaw bits) with its
|
||||
level and game events, the next spawn data updates, the shutter sounds, each
|
||||
ejected item (type, count, position and velocity bits), and at the end the
|
||||
saved state data and the next draw of the level random, which pins every draw
|
||||
in between.
|
||||
|
||||
Rooms are tuff halls around the spawner with pillars, glass and bars between
|
||||
it and the players (line of sight), players inside and outside the required
|
||||
range in every game mode, configs from the trial chamber registry and inline
|
||||
ones from the edge values up, saved state data (registered players, tracked
|
||||
mobs that are gone, cooldowns, spawn data, a loot table being ejected), every
|
||||
state of the block, every difficulty and both game rules. Every so many ticks
|
||||
the case kills the mobs the spawner added, so waves finish, rewards are
|
||||
ejected and cooldowns run out.
|
||||
|
||||
finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not
|
||||
compared. Ominous spawners (which also drop ominous item spawners) are not in
|
||||
the corpus yet.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_natural_spawn_parity as natural
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import test_natural_spawn_parity as natural
|
||||
|
||||
box = natural.box
|
||||
REGISTRY = ['breeze', 'melee/husk', 'melee/spider', 'melee/zombie', 'ranged/poison_skeleton', 'ranged/skeleton',
|
||||
'ranged/stray', 'slow_ranged/poison_skeleton', 'slow_ranged/skeleton', 'slow_ranged/stray',
|
||||
'small_melee/baby_zombie', 'small_melee/cave_spider', 'small_melee/silverfish', 'small_melee/slime']
|
||||
MOBS = ['zombie', 'husk', 'spider', 'cave_spider', 'skeleton', 'stray', 'bogged', 'breeze', 'slime', 'silverfish',
|
||||
'creeper', 'witch', 'pig', 'blaze']
|
||||
STATES = ['inactive', 'waiting_for_players', 'active', 'waiting_for_reward_ejection', 'ejecting_reward', 'cooldown']
|
||||
TABLES = ['minecraft:spawners/trial_chamber/consumables', 'minecraft:spawners/trial_chamber/key',
|
||||
'minecraft:chests/trial_chambers/reward', 'minecraft:spawners/ominous/trial_chamber/key']
|
||||
|
||||
|
||||
def uuid(rng):
|
||||
return '[I;' + ','.join(str(rng.randrange(-2**31, 2**31)) for _ in range(4)) + ']'
|
||||
|
||||
|
||||
def inline_config(rng):
|
||||
fields = []
|
||||
if rng.random() < 0.6:
|
||||
fields.append(f'spawn_range:{rng.choice([1, 2, 4, 4, 6, 10])}')
|
||||
for key, values in [('total_mobs', [0.0, 1.0, 2.0, 3.5, 6.0]), ('simultaneous_mobs', [0.0, 1.0, 2.0, 3.0]),
|
||||
('total_mobs_added_per_player', [0.0, 0.5, 1.0, 2.0]),
|
||||
('simultaneous_mobs_added_per_player', [0.0, 0.5, 1.0])]:
|
||||
if rng.random() < 0.6:
|
||||
fields.append(f'{key}:{rng.choice(values)}f')
|
||||
if rng.random() < 0.6:
|
||||
fields.append(f'ticks_between_spawn:{rng.choice([0, 1, 5, 20, 40, 160])}')
|
||||
if rng.random() < 0.9:
|
||||
entries = []
|
||||
for _ in range(rng.choice([1, 1, 2, 3])):
|
||||
mob = rng.choice(MOBS)
|
||||
entity = rng.choice([f'{{id:"minecraft:{mob}"}}', f'{{id:"{mob}"}}', f'{{id:"minecraft:{mob}",PersistenceRequired:1b}}',
|
||||
'{id:"minecraft:not_an_entity"}', '{}'] if rng.random() < 0.2 else [f'{{id:"minecraft:{mob}"}}'])
|
||||
entries.append(f'{{data:{{entity:{entity}}},weight:{rng.choice([1, 1, 2, 5, 0])}}}')
|
||||
fields.append('spawn_potentials:[' + ','.join(entries) + ']')
|
||||
if rng.random() < 0.4:
|
||||
entries = [f'{{data:"{rng.choice(TABLES)}",weight:{rng.choice([1, 1, 3, 0])}}}' for _ in range(rng.choice([1, 2, 3]))]
|
||||
fields.append('loot_tables_to_eject:[' + ','.join(entries) + ']')
|
||||
return '{' + ','.join(fields) + '}'
|
||||
|
||||
|
||||
def trial_snbt(rng, now):
|
||||
fields = []
|
||||
r = rng.random()
|
||||
if r < 0.6:
|
||||
name = rng.choice(REGISTRY)
|
||||
fields.append(f'normal_config:"minecraft:trial_chamber/{name}/normal"')
|
||||
fields.append(f'ominous_config:"minecraft:trial_chamber/{name}/ominous"')
|
||||
elif r < 0.9:
|
||||
fields.append(f'normal_config:{inline_config(rng)}')
|
||||
elif r < 0.95:
|
||||
fields.append('normal_config:"minecraft:trial_chamber/not_a_config"')
|
||||
if rng.random() < 0.5:
|
||||
fields.append(f'target_cooldown_length:{rng.choice([0, 1, 20, 45, 100, 200, 36000])}')
|
||||
if rng.random() < 0.4:
|
||||
fields.append(f'required_player_range:{rng.choice([1, 4, 8, 14, 20, 0, 200])}')
|
||||
if rng.random() < 0.15:
|
||||
fields.append('registered_players:[' + ','.join(rng.choice(['[I;0,0,0,1]', uuid(rng)]) for _ in range(rng.randrange(1, 3))) + ']')
|
||||
if rng.random() < 0.15:
|
||||
fields.append('current_mobs:[' + ','.join(uuid(rng) for _ in range(rng.randrange(1, 3))) + ']')
|
||||
if rng.random() < 0.2:
|
||||
fields.append(f'cooldown_ends_at:{now + rng.choice([-50, 0, 30, 100, 300])}L')
|
||||
if rng.random() < 0.2:
|
||||
fields.append(f'next_mob_spawns_at:{now + rng.choice([-5, 0, 10, 60])}L')
|
||||
if rng.random() < 0.15:
|
||||
fields.append(f'total_mobs_spawned:{rng.choice([0, 1, 3, 6, 20])}')
|
||||
if rng.random() < 0.15:
|
||||
fields.append(f'spawn_data:{{entity:{{id:"minecraft:{rng.choice(MOBS)}"}}}}')
|
||||
if rng.random() < 0.08:
|
||||
fields.append(f'ejecting_loot_table:"{rng.choice(TABLES)}"')
|
||||
return '{' + ','.join(fields) + '}'
|
||||
|
||||
|
||||
def room(rng):
|
||||
"""A trial chamber hall around the spawner; returns (world, spawner position)."""
|
||||
w = natural.World(rng)
|
||||
w.dim = 'minecraft:overworld'
|
||||
w.kv['dim'] = w.dim
|
||||
w.kv['biome'] = rng.choice(['minecraft:plains', 'minecraft:dripstone_caves', 'minecraft:deep_dark', 'minecraft:lush_caves'])
|
||||
sx, sy, sz = rng.randrange(-8, 9), rng.randrange(-40, 20), rng.randrange(-8, 9)
|
||||
w.surface = sy
|
||||
half, height = rng.choice([4, 5, 6, 8]), rng.choice([4, 5, 7])
|
||||
w.block(box(sx - 24, sy - 6, sz - 24, sx + 24, sy + 12, sz + 24), rng.choice(['minecraft:tuff_bricks', 'minecraft:stone']))
|
||||
w.block(box(sx - half, sy - 1, sz - half, sx + half, sy - 1, sz + half), rng.choice(['minecraft:chiseled_tuff', 'minecraft:waxed_copper_block']))
|
||||
w.block(box(sx - half, sy, sz - half, sx + half, sy + height - 1, sz + half), 'minecraft:air')
|
||||
if rng.random() < 0.3:
|
||||
# A corridor out of the hall, past the range.
|
||||
w.block(box(sx + half, sy, sz - 1, sx + 22, sy + 2, sz + 1), 'minecraft:air')
|
||||
for _ in range(rng.choice([0, 0, 1, 3, 6])):
|
||||
px, pz = sx + rng.randrange(-half, half + 1), sz + rng.randrange(-half, half + 1)
|
||||
if (px, pz) != (sx, sz):
|
||||
w.block(box(px, sy, pz, px, sy + rng.randrange(0, height), pz),
|
||||
rng.choice(['minecraft:tuff_bricks', 'minecraft:glass', 'minecraft:iron_bars', 'minecraft:oak_slab', 'minecraft:copper_grate']))
|
||||
w.light(box(sx - 24, sy - 2, sz - 24, sx + 24, sy + 12, sz + 24), 0, rng.choice([0, 0, 4, 8, 15]))
|
||||
return w, (sx, sy, sz), half, height
|
||||
|
||||
|
||||
def players(w, rng, spos, half, height):
|
||||
for _ in range(rng.choice([0, 1, 1, 1, 2, 3])):
|
||||
r = rng.random()
|
||||
if r < 0.75:
|
||||
x, y, z = spos[0] + rng.uniform(-half, half + 1), spos[1] + rng.choice([0, 0, 0, 1, height - 2]), spos[2] + rng.uniform(-half, half + 1)
|
||||
else:
|
||||
x, y, z = spos[0] + rng.uniform(-20, 21), spos[1] + rng.choice([0, 0, -8, 10]), spos[2] + rng.uniform(-20, 21)
|
||||
mode = rng.choice(['survival'] * 7 + ['creative', 'adventure', 'spectator'])
|
||||
w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}')
|
||||
|
||||
|
||||
def corpus():
|
||||
rng = random.Random(0x54524941)
|
||||
cases = []
|
||||
for k in range(2500):
|
||||
w, spos, half, height = room(rng)
|
||||
players(w, rng, spos, half, height)
|
||||
natural.common(w, rng, rng.randrange(-2**47, 2**47))
|
||||
w.kv.pop('unloaded', None)
|
||||
w.kv.pop('respawn', None)
|
||||
if rng.random() < 0.05:
|
||||
w.kv['spawners'] = 0
|
||||
if rng.random() < 0.05:
|
||||
w.kv['rules'] = 0
|
||||
t0 = rng.choice([0, 1, 19, 1000, rng.randrange(0, 10**6), rng.randrange(10**9, 10**12)])
|
||||
w.kv['spos'] = f'{spos[0]},{spos[1]},{spos[2]}'
|
||||
w.kv['state'] = rng.choices(STATES, [2, 6, 4, 1, 1, 1])[0]
|
||||
w.kv['snbt'] = base64.b64encode(trial_snbt(rng, t0).encode()).decode()
|
||||
w.kv['t0'] = t0
|
||||
w.kv['ticks'] = rng.choice([1, 2, 20, 41, 100, 200, 400, 600])
|
||||
w.kv['kill'] = rng.choice([0, 1, 7, 20, 60, 60])
|
||||
cases.append(f'trial/{k} mode=trial {w.tokens()}')
|
||||
return cases
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--prepare', action='store_true')
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'rust-trial-spawner-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
if args.prepare:
|
||||
lab.prepare()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
resources = lab.LOCAL / 'horizon-client/26.3'
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java'
|
||||
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
|
||||
tested = base.source_hashes(sources)
|
||||
inputs = build / 'inputs.txt'
|
||||
cases = corpus()
|
||||
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
deps = os.pathsep.join(map(str, libraries))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
|
||||
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
|
||||
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
|
||||
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
|
||||
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust')
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture'
|
||||
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
|
||||
vanilla = (build / 'server.txt').read_text().splitlines()
|
||||
errors = [l for l in vanilla if ' error ' in l]
|
||||
if errors:
|
||||
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
|
||||
rust = (build / 'rust.txt').read_text().splitlines()
|
||||
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
|
||||
if bad or len(vanilla) != len(rust):
|
||||
report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12])
|
||||
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
count = lambda text: sum(line.count(text) for line in vanilla)
|
||||
stats = {'spawns': count(' spawn minecraft:'), 'items': count(' item minecraft:'), 'states': count(' state '),
|
||||
'detections': count(' levent 3013 '), 'rewards': count(' levent 3014 '), 'kills': count(' kill ')}
|
||||
for state in STATES:
|
||||
stats[f'reached_{state}'] = sum(f' state {state} ' in line for line in vanilla)
|
||||
lab.write_json(build / 'report.json', {
|
||||
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
|
||||
**stats, 'sources_sha256': tested,
|
||||
'scope': 'TrialSpawner: load (state data, FullConfig with registry and inline configs), tickServer (mob '
|
||||
'tracking), TrialSpawnerState.tickAndGetNext for every state (display entity, canSpawnInLevel, '
|
||||
'tryDetectPlayers with line of sight, waves and their targets per player, spawnMob with its '
|
||||
'collision, line of sight, spawn rules, yaw and obstruction checks, next spawn data, reward '
|
||||
'ejection with the loot tables and spawnItem, shutter sounds, cooldown) with every level random '
|
||||
'draw. finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not compared.'})
|
||||
print(f'{len(cases):,} trial spawner cases match vanilla (' + ', '.join(f'{v:,} {k}' for k, v in stats.items()) + ')')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -6,7 +6,9 @@ for beds in the Nether and the End.
|
||||
|
||||
Every case has a block at the origin, something above it, and a player three
|
||||
blocks south, survival or creative, hungry or full, sneaking or not, who
|
||||
right-clicks the top face of the origin holding an item. Vanilla runs the real
|
||||
right-clicks the top face of the origin holding an item, sometimes with
|
||||
another (or nothing) in the main hand and the item in the off hand, the
|
||||
main hand trying first. Vanilla runs the real
|
||||
`ServerPlayerGameMode.useItemOn` over the headless level of the dispenser
|
||||
harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and
|
||||
`useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn`
|
||||
@@ -26,6 +28,7 @@ or fall apart (`AbstractBedBlock.useWithoutItem` under the dimension's
|
||||
(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level
|
||||
events, sounds, game events, the used statistic, the held stack, the item the
|
||||
player started using, spawners' next spawn data, potentials and delay, the
|
||||
off hand's stack,
|
||||
player's respawn point, system messages and the level random afterwards.
|
||||
"""
|
||||
import json
|
||||
@@ -144,6 +147,9 @@ def anchor_case(rng, states, case):
|
||||
'distance': 3 if nether else 12}
|
||||
if rng.random() < 0.3:
|
||||
use['respawn'] = rng.choice([[0, 0, 0], [5, 0, 5]])
|
||||
if rng.random() < 0.4:
|
||||
# Glowstone in the off hand: the main hand passes it on (PASS).
|
||||
use['offhand'] = d_plain(rng.choice(['glowstone', 'glowstone', 'apple']), rng.choice([1, 16]))
|
||||
if rng.random() < 0.2:
|
||||
case['rules'] = {'block_explosion_drop_decay': False}
|
||||
case['use_item'] = use
|
||||
@@ -206,6 +212,10 @@ def cases(facts, count, seed):
|
||||
held = '-' if item == '-' else d.plain(item, rng.choice([1, 1, 2, 16, 64]))
|
||||
case['use_item'] = {'item': held, 'creative': rng.random() < 0.2, 'sneaking': rng.random() < 0.2,
|
||||
'food': rng.choice([20, 20, 19, 10, 0])}
|
||||
if rng.random() < 0.3:
|
||||
# The item in the off hand, something else or nothing in the main hand.
|
||||
main = rng.choice(['-', '-', 'stick', 'apple', 'stone', 'bone_meal', 'shield'])
|
||||
case['use_item'].update(offhand=held, item='-' if main == '-' else d.plain(main, rng.choice([1, 16])))
|
||||
case['cells'] = cells
|
||||
case['items'] = []
|
||||
case['mode'] = 'dispense'
|
||||
|
||||
Reference in New Issue
Block a user