Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # crates/horizon-client/src/game/initial_spawn.rs
This commit is contained in:
@@ -437,6 +437,8 @@ pub struct EntityView {
|
||||
/// mainhand, offhand, head, chest, legs, feet, body.
|
||||
pub equipment: [Option<ItemView>; 7],
|
||||
pub vehicle: Option<Box<EntityView>>,
|
||||
/// Player: what it looks at within 100 blocks (`PlayerPredicate.lookingAt`).
|
||||
pub looking_at: Option<Box<EntityView>>,
|
||||
pub effects: Vec<(String, i32, i32)>,
|
||||
/// Player: game mode name.
|
||||
pub gamemode: Option<String>,
|
||||
@@ -458,7 +460,7 @@ fn range_f(v: &Value, x: f64) -> bool {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn range_i(v: &Value, x: i64) -> bool {
|
||||
pub fn range_i(v: &Value, x: i64) -> bool {
|
||||
range_f(v, x as f64)
|
||||
}
|
||||
/// A registry id, `#tag`, or list matched against one id.
|
||||
@@ -473,6 +475,51 @@ pub fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// `PotionsPredicate`: the potion in a `HolderSet`, plus a `CollectionPredicate`
|
||||
/// over the potion's effects (`contains`, `count`, `size`).
|
||||
pub fn potions(v: &Value, potion: Option<&str>, w: &dyn World) -> bool {
|
||||
if v.is_null() {
|
||||
return true;
|
||||
}
|
||||
if !v["potions"].is_null() && !potion.is_some_and(|p| id_matches(&v["potions"], "potion", p, w))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let c = &v["effects"];
|
||||
if c.is_null() {
|
||||
return true;
|
||||
}
|
||||
let effects: Vec<(String, i32, i32)> = potion
|
||||
.and_then(crate::brewing::potion)
|
||||
.map(|d| {
|
||||
d.effects
|
||||
.iter()
|
||||
.map(|(id, dur, amp)| (format!("minecraft:{id}"), *amp, *dur))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
// `MobEffectsPredicate.test`: the one listed effect, amplifier and duration.
|
||||
let test = |pred: &Value, e: &(String, i32, i32)| {
|
||||
pred.as_object().is_some_and(|m| {
|
||||
m.get(&e.0).is_some_and(|want| {
|
||||
range_i(&want["amplifier"], i64::from(e.1))
|
||||
&& range_i(&want["duration"], i64::from(e.2))
|
||||
&& want["ambient"].as_bool().is_none_or(|b| !b)
|
||||
&& want["visible"].as_bool().is_none_or(|b| b)
|
||||
})
|
||||
})
|
||||
};
|
||||
c["contains"]
|
||||
.as_array()
|
||||
.is_none_or(|l| l.iter().all(|p| effects.iter().any(|e| test(p, e))))
|
||||
&& c["count"].as_array().is_none_or(|l| {
|
||||
l.iter().all(|entry| {
|
||||
let n = effects.iter().filter(|e| test(&entry["test"], e)).count();
|
||||
range_i(&entry["count"], n as i64)
|
||||
})
|
||||
})
|
||||
&& range_i(&c["size"], effects.len() as i64)
|
||||
}
|
||||
/// `ItemPredicate`.
|
||||
pub fn item(v: &Value, it: &ItemView, w: &dyn World) -> bool {
|
||||
if v.is_null() {
|
||||
@@ -614,6 +661,18 @@ fn components(expected: &Value, have: &[(String, String)]) -> bool {
|
||||
})
|
||||
})
|
||||
}
|
||||
/// `DistancePredicate.matches` between two points.
|
||||
pub fn distance(v: &Value, a: [f64; 3], b: [f64; 3]) -> bool {
|
||||
let d = [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
||||
range_f(&v["x"], d[0].abs())
|
||||
&& range_f(&v["y"], d[1].abs())
|
||||
&& range_f(&v["z"], d[2].abs())
|
||||
&& range_f(&v["horizontal"], (d[0] * d[0] + d[2] * d[2]).sqrt())
|
||||
&& range_f(
|
||||
&v["absolute"],
|
||||
(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(),
|
||||
)
|
||||
}
|
||||
/// `EntityPredicate` (26.x keyed sub-predicates).
|
||||
pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> bool {
|
||||
if v.is_null() {
|
||||
@@ -629,21 +688,7 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo
|
||||
"minecraft:stepping_on" => {
|
||||
location(p, [e.position[0], e.position[1] - 0.5, e.position[2]], w)
|
||||
}
|
||||
"minecraft:distance" | "distance" => {
|
||||
let d = [
|
||||
e.position[0] - origin[0],
|
||||
e.position[1] - origin[1],
|
||||
e.position[2] - origin[2],
|
||||
];
|
||||
range_f(&p["x"], d[0].abs())
|
||||
&& range_f(&p["y"], d[1].abs())
|
||||
&& range_f(&p["z"], d[2].abs())
|
||||
&& range_f(&p["horizontal"], (d[0] * d[0] + d[2] * d[2]).sqrt())
|
||||
&& range_f(
|
||||
&p["absolute"],
|
||||
(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(),
|
||||
)
|
||||
}
|
||||
"minecraft:distance" | "distance" => distance(p, e.position, origin),
|
||||
"minecraft:flags" | "flags" => {
|
||||
let f = |k: &str, have: bool| p[k].as_bool().is_none_or(|want| want == have);
|
||||
f("is_on_fire", e.on_fire)
|
||||
@@ -678,11 +723,16 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo
|
||||
})
|
||||
})
|
||||
}),
|
||||
"minecraft:type_specific/player" => p["gamemode"].as_array().is_none_or(|modes| {
|
||||
e.gamemode
|
||||
.as_deref()
|
||||
.is_some_and(|g| modes.iter().any(|m| m.as_str() == Some(g)))
|
||||
}),
|
||||
"minecraft:type_specific/player" => {
|
||||
p["gamemode"].as_array().is_none_or(|modes| {
|
||||
e.gamemode
|
||||
.as_deref()
|
||||
.is_some_and(|g| modes.iter().any(|m| m.as_str() == Some(g)))
|
||||
}) && (p["looking_at"].is_null()
|
||||
|| e.looking_at
|
||||
.as_ref()
|
||||
.is_some_and(|t| entity(&p["looking_at"], t, w, origin)))
|
||||
}
|
||||
"minecraft:type_specific/lightning" => {
|
||||
range_i(&p["blocks_set_on_fire"], 0)
|
||||
&& (p["entity_struck"].is_null()
|
||||
@@ -703,6 +753,52 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo
|
||||
}
|
||||
true
|
||||
}
|
||||
/// A damage event as `DamagePredicate` sees it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DamageView {
|
||||
/// The damage type id (`minecraft:arrow`).
|
||||
pub kind: String,
|
||||
/// `DamageSource.getDirectEntity` and `getEntity`.
|
||||
pub direct: Option<EntityView>,
|
||||
pub source: Option<EntityView>,
|
||||
/// `DamageSource.isDirect`: the direct entity is the causing one.
|
||||
pub is_direct: bool,
|
||||
/// The damage before and after the shield took its share.
|
||||
pub original: f32,
|
||||
pub actual: f32,
|
||||
pub blocked: bool,
|
||||
}
|
||||
/// `DamagePredicate`, with its `DamageSourcePredicate` as `type`.
|
||||
pub fn damage(v: &Value, d: &DamageView, w: &dyn World, origin: [f64; 3]) -> bool {
|
||||
if v.is_null() {
|
||||
return true;
|
||||
}
|
||||
let by = |key: &str, e: &Option<EntityView>| {
|
||||
v[key].is_null() || e.as_ref().is_some_and(|e| entity(&v[key], e, w, origin))
|
||||
};
|
||||
if !range_f(&v["dealt"], f64::from(d.original))
|
||||
|| !range_f(&v["taken"], f64::from(d.actual))
|
||||
|| !by("source_entity", &d.source)
|
||||
|| v["blocked"].as_bool().is_some_and(|b| b != d.blocked)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let ty = &v["type"];
|
||||
let tags_ok = ty["tags"].as_array().into_iter().flatten().all(|t| {
|
||||
let tag = t["id"].as_str().unwrap_or("");
|
||||
let tag = tag.strip_prefix('#').unwrap_or(tag);
|
||||
w.in_tag("damage_type", tag, &d.kind) == t["expected"].as_bool().unwrap_or(true)
|
||||
});
|
||||
let direct_ok = ty["direct_entity"].is_null()
|
||||
|| d.direct
|
||||
.as_ref()
|
||||
.is_some_and(|e| entity(&ty["direct_entity"], e, w, origin));
|
||||
let source_ok = ty["source_entity"].is_null()
|
||||
|| d.source
|
||||
.as_ref()
|
||||
.is_some_and(|e| entity(&ty["source_entity"], e, w, origin));
|
||||
tags_ok && direct_ok && source_ok && ty["is_direct"].as_bool().is_none_or(|b| b == d.is_direct)
|
||||
}
|
||||
/// The entities a loot-style condition list may refer to.
|
||||
pub struct Entities<'a> {
|
||||
pub this: Option<&'a EntityView>,
|
||||
|
||||
@@ -35,8 +35,10 @@ enum Animate {
|
||||
Campfire {
|
||||
spawn_particles: bool,
|
||||
},
|
||||
/// Leaves: optional falling-leaf particle and chance, tinted by foliage.
|
||||
Leaves(Option<(T, f32)>),
|
||||
/// Leaves: optional falling-leaf particle and chance; a tinted leaf takes
|
||||
/// the biome foliage colour unless a fixed colour is given (azalea); and
|
||||
/// whether they have the poplar ambient sound (`AmbientLeavesBlockSoundPlayer`).
|
||||
Leaves(Option<(T, f32)>, Option<u32>, bool),
|
||||
NetherPortal,
|
||||
EnchantingTable,
|
||||
EndRod([i32; 3]),
|
||||
@@ -47,8 +49,11 @@ enum Animate {
|
||||
CandleCake,
|
||||
BrewingStand,
|
||||
EnderChest,
|
||||
/// FallingBlock with its dust colour.
|
||||
Falling(u32),
|
||||
/// FallingBlock with its dust colour; sand also has the ambient desert sound
|
||||
/// (`SandBlock.animateTick`).
|
||||
Falling(u32, bool),
|
||||
/// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`).
|
||||
Beehive,
|
||||
RedstoneOre,
|
||||
RedstoneWire {
|
||||
power: u8,
|
||||
@@ -70,6 +75,8 @@ enum Animate {
|
||||
waterlogged: bool,
|
||||
},
|
||||
EndPortal,
|
||||
/// `WetSpongeBlock.animateTick`.
|
||||
WetSponge,
|
||||
}
|
||||
fn step(facing: &str) -> [i32; 3] {
|
||||
match facing {
|
||||
@@ -104,10 +111,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
spawn_particles: false,
|
||||
},
|
||||
"oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves"
|
||||
| "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))),
|
||||
"cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))),
|
||||
"pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))),
|
||||
"spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None),
|
||||
| "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None, false),
|
||||
"cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None, false),
|
||||
"pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None, false),
|
||||
"red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None, true),
|
||||
"orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None, true),
|
||||
"yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None, true),
|
||||
// The azalea blocks drop tinted leaves of the fixed colour -9399763.
|
||||
"azalea_leaves" | "flowering_azalea_leaves" => {
|
||||
Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D), false)
|
||||
}
|
||||
"spruce_leaves" => Animate::Leaves(None, None, false),
|
||||
"nether_portal" => Animate::NetherPortal,
|
||||
"enchanting_table" => Animate::EnchantingTable,
|
||||
"end_rod" => Animate::EndRod(facing()),
|
||||
@@ -116,9 +130,18 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
"mycelium" => Animate::Mycelium,
|
||||
"brewing_stand" => Animate::BrewingStand,
|
||||
"ender_chest" => Animate::EnderChest,
|
||||
"sand" => Animate::Falling(0xDBD3A0),
|
||||
"red_sand" => Animate::Falling(0xA95821),
|
||||
"gravel" => Animate::Falling(0x807C7B),
|
||||
"sand" => Animate::Falling(0xDBD3A0, true),
|
||||
"red_sand" => Animate::Falling(0xA95821, true),
|
||||
"gravel" => Animate::Falling(0x807C7B, false),
|
||||
// AnvilBlock/ConcretePowderBlock.getDustColor is the map colour;
|
||||
// DragonEggBlock's is black.
|
||||
"anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7, false),
|
||||
"dragon_egg" => Animate::Falling(0x000000, false),
|
||||
_ if name.ends_with("_concrete_powder") => Animate::Falling(
|
||||
concrete_powder_color(name.trim_end_matches("_concrete_powder")),
|
||||
false,
|
||||
),
|
||||
"beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive,
|
||||
"redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre,
|
||||
"redstone_wire" => {
|
||||
let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0);
|
||||
@@ -149,6 +172,10 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
waterlogged: prop("waterlogged").as_deref() == Some("true"),
|
||||
},
|
||||
"end_portal" => Animate::EndPortal,
|
||||
"wet_sponge" => Animate::WetSponge,
|
||||
// BrushableBlock has no dust colour of its own, so the dust is the map colour.
|
||||
"suspicious_sand" => Animate::Falling(0xF7E9A3, false),
|
||||
"suspicious_gravel" => Animate::Falling(0x707070, false),
|
||||
"sculk_sensor" | "calibrated_sculk_sensor"
|
||||
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
|
||||
{
|
||||
@@ -161,6 +188,27 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
_ => Animate::None,
|
||||
}
|
||||
}
|
||||
/// `DyeColor.getMapColor` of a concrete powder colour.
|
||||
fn concrete_powder_color(dye: &str) -> u32 {
|
||||
match dye {
|
||||
"white" => 0xFFFFFF,
|
||||
"orange" => 0xD87F33,
|
||||
"magenta" => 0xB24CD8,
|
||||
"light_blue" => 0x6699D8,
|
||||
"yellow" => 0xE5E533,
|
||||
"lime" => 0x7FCC19,
|
||||
"pink" => 0xF27FA5,
|
||||
"gray" => 0x4C4C4C,
|
||||
"light_gray" => 0x999999,
|
||||
"cyan" => 0x4C7F99,
|
||||
"purple" => 0x7F3FB2,
|
||||
"blue" => 0x334CB2,
|
||||
"brown" => 0x664C33,
|
||||
"green" => 0x667F33,
|
||||
"red" => 0x993333,
|
||||
_ => 0x191919,
|
||||
}
|
||||
}
|
||||
/// `RedstoneWireBlock.COLORS`.
|
||||
fn redstone_color(power: u8) -> [f32; 3] {
|
||||
let f = f32::from(power) / 15.0;
|
||||
@@ -194,6 +242,10 @@ pub struct AnimateTables {
|
||||
power_transmitter: Vec<bool>,
|
||||
/// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil).
|
||||
dried_ghast_sounds: Vec<bool>,
|
||||
/// `#triggers_ambient_desert_sand_block_sounds` (sand, red sand).
|
||||
desert_sand_sounds: Vec<bool>,
|
||||
/// `#required_for_poplar_leaf_ambience` (overworld natural logs).
|
||||
poplar_leaf_logs: Vec<bool>,
|
||||
/// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged).
|
||||
burnable: Vec<bool>,
|
||||
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
|
||||
@@ -269,6 +321,8 @@ impl AnimateTables {
|
||||
power_provider: by_state("minecraft:enchantment_power_provider"),
|
||||
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
|
||||
dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"),
|
||||
desert_sand_sounds: by_state("minecraft:triggers_ambient_desert_sand_block_sounds"),
|
||||
poplar_leaf_logs: by_state("minecraft:required_for_poplar_leaf_ambience"),
|
||||
burnable,
|
||||
ambient,
|
||||
})
|
||||
@@ -357,6 +411,10 @@ impl AnimateContext<'_> {
|
||||
fn add(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) {
|
||||
engine.add(&ParticleOptions::simple(ty), p, v);
|
||||
}
|
||||
/// `Level.addAlwaysVisibleParticle`: still shown under the Minimal option now and then.
|
||||
fn add_visible(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) {
|
||||
engine.add_with(&ParticleOptions::simple(ty), p, v, false, true);
|
||||
}
|
||||
fn sound(engine: &mut ParticleEngine, name: &'static str, p: [f64; 3], volume: f32, pitch: f32) {
|
||||
engine.sounds.push((name, p, volume, pitch));
|
||||
}
|
||||
@@ -504,6 +562,53 @@ fn try_spawn_drip(
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `BeehiveBlock.trySpawnDripParticles`.
|
||||
fn beehive_drip(
|
||||
tables: &AnimateTables,
|
||||
engine: &mut ParticleEngine,
|
||||
ctx: &AnimateContext,
|
||||
state: BlockStateId,
|
||||
pos: [i32; 3],
|
||||
) {
|
||||
if ctx.facts.get(state).fluid != Fluid::None || engine.random().next_float() < 0.3 {
|
||||
return;
|
||||
}
|
||||
let Some((bottom, top, bounds)) = ctx.shape_y(pos) else {
|
||||
return;
|
||||
};
|
||||
if top < 1.0
|
||||
|| tables
|
||||
.impermeable
|
||||
.get(state.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let y = if bottom > 0.0 {
|
||||
f64::from(pos[1]) + bottom - 0.05
|
||||
} else {
|
||||
let below = [pos[0], pos[1] - 1, pos[2]];
|
||||
let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1);
|
||||
// `belowTop < 1 || !isCollisionShapeFullBlock` and no fluid below.
|
||||
if (below_top < 1.0 || !ctx.sturdy(below))
|
||||
&& ctx.facts.get(ctx.state(below)).fluid == Fluid::None
|
||||
{
|
||||
f64::from(pos[1]) - 0.05
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let r = engine.random();
|
||||
let (a, b) = (r.next_double(), r.next_double());
|
||||
let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2]));
|
||||
let p = [
|
||||
fx + bounds[0] + (bounds[1] - bounds[0]) * a,
|
||||
y,
|
||||
fz + bounds[2] + (bounds[3] - bounds[2]) * b,
|
||||
];
|
||||
add(engine, T::DrippingHoney, p, [0.0; 3]);
|
||||
}
|
||||
/// `WaterFluid.animateTick` / `LavaFluid.animateTick`.
|
||||
fn fluid_animate_tick(
|
||||
engine: &mut ParticleEngine,
|
||||
@@ -685,7 +790,7 @@ fn block_animate_tick(
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::Leaves(falling) => {
|
||||
Animate::Leaves(falling, fixed_tint, poplar) => {
|
||||
let below = [pos[0], pos[1] - 1, pos[2]];
|
||||
// LeavesBlock.makeDrippingWaterParticles.
|
||||
if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1
|
||||
@@ -697,6 +802,9 @@ fn block_animate_tick(
|
||||
add(engine, T::DrippingWater, p, [0.0; 3]);
|
||||
}
|
||||
}
|
||||
if poplar {
|
||||
leaves_ambient_sound(tables, engine, ctx, state, pos);
|
||||
}
|
||||
// FallingParticlesLeavesBlock.makeFallingLeavesParticles.
|
||||
if let Some((ty, chance)) = falling
|
||||
&& engine.random().next_float() < chance
|
||||
@@ -705,7 +813,7 @@ fn block_animate_tick(
|
||||
let r = engine.random();
|
||||
let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()];
|
||||
let options = if ty == T::TintedLeaves {
|
||||
let c = ctx.foliage(pos);
|
||||
let c = fixed_tint.unwrap_or_else(|| ctx.foliage(pos));
|
||||
let f = |s: u32| ((c >> s) & 255) as f32 / 255.0;
|
||||
ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0])
|
||||
} else {
|
||||
@@ -869,7 +977,7 @@ fn block_animate_tick(
|
||||
fy + 1.0 + f64::from(r.next_float()),
|
||||
fz + f64::from(r.next_float()),
|
||||
];
|
||||
add(engine, T::SulfurBubbles, p, [0.0; 3]);
|
||||
add_visible(engine, T::SulfurBubbles, p, [0.0; 3]);
|
||||
}
|
||||
if next_int(engine.random(), 10) == 0 {
|
||||
let name = "minecraft:block.potent_sulfur.noxious_gas";
|
||||
@@ -877,6 +985,36 @@ fn block_animate_tick(
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::WetSponge => {
|
||||
// Direction.getRandom: DOWN, UP, NORTH, SOUTH, WEST, EAST.
|
||||
const DIRECTIONS: [[i32; 3]; 6] = [
|
||||
[0, -1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, -1],
|
||||
[0, 0, 1],
|
||||
[-1, 0, 0],
|
||||
[1, 0, 0],
|
||||
];
|
||||
let d = DIRECTIONS[next_int(engine.random(), 6) as usize];
|
||||
// The sponge occludes, so only a sturdy neighbour face hides the drip.
|
||||
if d != [0, 1, 0] && !ctx.sturdy([pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]) {
|
||||
let r = engine.random();
|
||||
let p = match d {
|
||||
[0, -1, 0] => [fx + r.next_double(), fy - 0.05, fz + r.next_double()],
|
||||
[dx, _, 0] => {
|
||||
let y = fy + r.next_double() * 0.8;
|
||||
let z = fz + r.next_double();
|
||||
[fx + if dx > 0 { 1.1 } else { 0.05 }, y, z]
|
||||
}
|
||||
[_, _, dz] => {
|
||||
let y = fy + r.next_double() * 0.8;
|
||||
let x = fx + r.next_double();
|
||||
[x, y, fz + if dz > 0 { 1.1 } else { 0.05 }]
|
||||
}
|
||||
};
|
||||
add(engine, T::DrippingWater, p, [0.0; 3]);
|
||||
}
|
||||
}
|
||||
Animate::Mycelium => {
|
||||
let r = engine.random();
|
||||
if next_int(r, 10) == 0 {
|
||||
@@ -959,7 +1097,7 @@ fn block_animate_tick(
|
||||
add(engine, T::Portal, p, v);
|
||||
}
|
||||
}
|
||||
Animate::Falling(color) => {
|
||||
Animate::Falling(color, sand) => {
|
||||
if next_int(engine.random(), 16) == 0 {
|
||||
let below = ctx.facts.get(ctx.state([pos[0], pos[1] - 1, pos[2]]));
|
||||
// FallingBlock.isFree: air, fire, liquids or replaceable.
|
||||
@@ -976,6 +1114,21 @@ fn block_animate_tick(
|
||||
);
|
||||
}
|
||||
}
|
||||
// AmbientDesertBlockSoundsPlayer.playAmbientSandSounds: only for the air block.
|
||||
if sand
|
||||
&& ctx.state([pos[0], pos[1] + 1, pos[2]]) == ctx.world.air
|
||||
&& next_int(engine.random(), 2100) == 0
|
||||
&& sand_sound_nearby(tables, ctx, pos)
|
||||
{
|
||||
sound(engine, "minecraft:block.sand.idle", [fx, fy, fz], 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
Animate::Beehive => {
|
||||
// BeehiveBlock.animateTick: nextInt(1) + 1 attempts.
|
||||
let attempts = next_int(engine.random(), 1) + 1;
|
||||
for _ in 0..attempts {
|
||||
beehive_drip(tables, engine, ctx, state, pos);
|
||||
}
|
||||
}
|
||||
Animate::RedstoneOre => {
|
||||
for d in [
|
||||
@@ -1086,7 +1239,7 @@ fn block_animate_tick(
|
||||
}
|
||||
Animate::BubbleColumn { drag } => {
|
||||
if drag {
|
||||
add(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]);
|
||||
add_visible(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]);
|
||||
let r = engine.random();
|
||||
if next_int(r, 200) == 0 {
|
||||
let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15);
|
||||
@@ -1099,7 +1252,7 @@ fn block_animate_tick(
|
||||
);
|
||||
}
|
||||
} else {
|
||||
add(
|
||||
add_visible(
|
||||
engine,
|
||||
T::BubbleColumnUp,
|
||||
[fx + 0.5, fy, fz + 0.5],
|
||||
@@ -1111,7 +1264,7 @@ fn block_animate_tick(
|
||||
fy + f64::from(r.next_float()),
|
||||
fz + f64::from(r.next_float()),
|
||||
];
|
||||
add(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]);
|
||||
add_visible(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]);
|
||||
let r = engine.random();
|
||||
if next_int(r, 200) == 0 {
|
||||
let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15);
|
||||
@@ -1189,6 +1342,91 @@ fn block_animate_tick(
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `AmbientLeavesBlockSoundPlayer.playAmbientLeavesSounds` for the poplar leaves:
|
||||
/// one log and three leaves of the same kind around the block.
|
||||
fn leaves_ambient_sound(
|
||||
tables: &AnimateTables,
|
||||
engine: &mut ParticleEngine,
|
||||
ctx: &AnimateContext,
|
||||
state: BlockStateId,
|
||||
pos: [i32; 3],
|
||||
) {
|
||||
if next_int(engine.random(), 300) != 0 {
|
||||
return;
|
||||
}
|
||||
let Some(name) = ctx.registry.state(state).map(|s| &s.name) else {
|
||||
return;
|
||||
};
|
||||
let (mut logs, mut leaves) = (0, 0);
|
||||
for d in [[0, -1], [1, 0], [0, 1], [-1, 0]] {
|
||||
let neighbor = ctx.state([pos[0] + d[0], pos[1], pos[2] + d[1]]);
|
||||
if tables
|
||||
.poplar_leaf_logs
|
||||
.get(neighbor.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
{
|
||||
logs += 1;
|
||||
}
|
||||
if ctx
|
||||
.registry
|
||||
.state(neighbor)
|
||||
.is_some_and(|s| &s.name == name)
|
||||
{
|
||||
leaves += 1;
|
||||
}
|
||||
if logs == 1 && leaves == 3 {
|
||||
let p = pos.map(f64::from);
|
||||
sound(engine, "minecraft:block.poplar_leaves.ambient", p, 1.0, 1.0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `AmbientDesertBlockSoundsPlayer.shouldPlayAmbientSandSound`: sand in the
|
||||
/// surface column eight blocks away on all four sides.
|
||||
fn sand_sound_nearby(tables: &AnimateTables, ctx: &AnimateContext, pos: [i32; 3]) -> bool {
|
||||
let is_sand = |p: [i32; 3]| {
|
||||
tables
|
||||
.desert_sand_sounds
|
||||
.get(ctx.state(p).0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
};
|
||||
let (mut found, mut checked) = (0, 0);
|
||||
for d in [[0, -8], [8, 0], [0, 8], [-8, 0]] {
|
||||
let (x, z) = (pos[0] + d[0], pos[2] + d[1]);
|
||||
// columnContainsTriggeringBlock.
|
||||
let surface = ctx.world.world_surface(x, z, |s| ctx.facts.is_air(s)) - 1;
|
||||
let matches = if (surface - pos[1]).abs() > 5 {
|
||||
let mut y = pos[1] + 6;
|
||||
let mut above_air = ctx.is_air([x, y, z]);
|
||||
y -= 1;
|
||||
let mut hit = false;
|
||||
for _ in 0..10 {
|
||||
if above_air && is_sand([x, y, z]) {
|
||||
hit = true;
|
||||
break;
|
||||
}
|
||||
above_air = ctx.is_air([x, y, z]);
|
||||
y -= 1;
|
||||
}
|
||||
hit
|
||||
} else {
|
||||
ctx.is_air([x, surface + 1, z]) && is_sand([x, surface, z])
|
||||
};
|
||||
if matches {
|
||||
found += 1;
|
||||
if found > 3 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
checked += 1;
|
||||
if 4 - checked + found < 3 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `AbstractCandleBlock.addParticlesAndSound`.
|
||||
fn candle(engine: &mut ParticleEngine, p: [f64; 3]) {
|
||||
let r = engine.random();
|
||||
@@ -1209,21 +1447,32 @@ fn candle(engine: &mut ParticleEngine, p: [f64; 3]) {
|
||||
}
|
||||
add(engine, T::SmallFlame, p, [0.0; 3]);
|
||||
}
|
||||
/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items).
|
||||
/// `CampfireBlockEntity.particleTick` for every lit campfire; `cooking` says
|
||||
/// which of a campfire's four slots hold an item.
|
||||
pub fn campfire_particles<'a>(
|
||||
tables: &AnimateTables,
|
||||
engine: &mut ParticleEngine,
|
||||
ctx: &AnimateContext,
|
||||
blocks: impl Iterator<Item = &'a ([i32; 3], u32)>,
|
||||
cooking: &dyn Fn([i32; 3]) -> [bool; 4],
|
||||
) {
|
||||
for &(pos, state) in blocks {
|
||||
if !tables.is_lit_campfire(state) {
|
||||
continue;
|
||||
}
|
||||
let signal = ctx
|
||||
let properties = ctx
|
||||
.registry
|
||||
.state(BlockStateId(state))
|
||||
.is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true"));
|
||||
.map(|s| &s.properties);
|
||||
let prop = |k: &str| properties.and_then(|p| p.get(k)).map(String::as_str);
|
||||
let signal = prop("signal_fire") == Some("true");
|
||||
// Direction.get2DDataValue: south, west, north, east.
|
||||
let rotation = match prop("facing") {
|
||||
Some("west") => 1,
|
||||
Some("north") => 2,
|
||||
Some("east") => 3,
|
||||
_ => 0,
|
||||
};
|
||||
let r = engine.random();
|
||||
if r.next_float() < 0.11 {
|
||||
let count = next_int(r, 2) + 2;
|
||||
@@ -1231,6 +1480,28 @@ pub fn campfire_particles<'a>(
|
||||
make_campfire_smoke(engine, pos, signal, false);
|
||||
}
|
||||
}
|
||||
// The smoke over each cooking item, at the slot's corner of the fire.
|
||||
let occupied = cooking(pos);
|
||||
for (slot, _) in occupied.iter().enumerate().filter(|(_, held)| **held) {
|
||||
if engine.random().next_float() >= 0.2 {
|
||||
continue;
|
||||
}
|
||||
// Direction.from2DDataValue((slot + rotation) % 4) and its clockwise side.
|
||||
let (step, clockwise) = match (slot + rotation) % 4 {
|
||||
0 => ([0.0, 1.0], [-1.0, 0.0]),
|
||||
1 => ([-1.0, 0.0], [0.0, -1.0]),
|
||||
2 => ([0.0, -1.0], [1.0, 0.0]),
|
||||
_ => ([1.0, 0.0], [0.0, 1.0]),
|
||||
};
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5 - step[0] * 0.3125 + clockwise[0] * 0.3125,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5 - step[1] * 0.3125 + clockwise[1] * 0.3125,
|
||||
];
|
||||
for _ in 0..4 {
|
||||
add(engine, T::Smoke, at, [0.0, 5.0e-4, 0.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `CampfireBlock.makeParticles` (always visible, overriding the limiter);
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::{
|
||||
collisions::SceneCollisions,
|
||||
mobs::Who,
|
||||
motion::{FluidResources, LAVA, WATER},
|
||||
projectiles::{Hit, Projectile},
|
||||
projectiles::{Hit, Projectile, ProjectileKind},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -132,6 +132,10 @@ pub enum ArrowSound {
|
||||
HitGround,
|
||||
/// `entity.generic.extinguish_fire`.
|
||||
Extinguish,
|
||||
/// A thrown trident's `getDefaultHitGroundSoundEvent` (`item.trident.hit_ground`).
|
||||
TridentHitGround,
|
||||
/// `ThrownTrident.onHitEntity`'s `item.trident.hit`.
|
||||
TridentHit,
|
||||
}
|
||||
/// What a burning arrow does to the block it hits (`onProjectileHit`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -156,7 +160,11 @@ pub struct ArrowState {
|
||||
/// `pickupItemStack`: what picking the arrow up gives.
|
||||
pub pickup_item: crate::items::ItemStack,
|
||||
pub no_physics: bool,
|
||||
/// `AbstractArrow.getPierceLevel`.
|
||||
pub pierce: u8,
|
||||
/// `piercingIgnoreEntityIds`: the entities a piercing arrow has gone
|
||||
/// through (cleared when it sticks in a block).
|
||||
pub pierced: Vec<Who>,
|
||||
/// `Entity.remainingFireTicks`.
|
||||
pub fire_ticks: i32,
|
||||
pub fall_distance: f64,
|
||||
@@ -165,6 +173,9 @@ pub struct ArrowState {
|
||||
pub was_eye_in_water: bool,
|
||||
pub first_tick: bool,
|
||||
pub has_been_shot: bool,
|
||||
/// `ThrownTrident.dealtDamage`: it has hit an entity (or sat in a block
|
||||
/// for over 4 ticks) and hits no more.
|
||||
pub dealt_damage: bool,
|
||||
pub removed: bool,
|
||||
/// The arrow's own random (`Entity.random`).
|
||||
pub random: LegacyRandom,
|
||||
@@ -199,6 +210,7 @@ impl ArrowState {
|
||||
pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1),
|
||||
no_physics: false,
|
||||
pierce: 0,
|
||||
pierced: Vec::new(),
|
||||
fire_ticks: 0,
|
||||
fall_distance: 0.0,
|
||||
fluids: EntityFluidInteraction::new([WATER, LAVA]),
|
||||
@@ -206,6 +218,7 @@ impl ArrowState {
|
||||
was_eye_in_water: false,
|
||||
first_tick: true,
|
||||
has_been_shot: false,
|
||||
dealt_damage: false,
|
||||
removed: false,
|
||||
random,
|
||||
events: Vec::new(),
|
||||
@@ -362,6 +375,29 @@ fn bounds(at: Vec3) -> Aabb {
|
||||
Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w),
|
||||
)
|
||||
}
|
||||
/// The bounding box of an arrow, or a thrown trident, at `at`.
|
||||
pub fn arrow_bounds(at: Vec3) -> Aabb {
|
||||
bounds(at)
|
||||
}
|
||||
/// The blocks an arrow that moved from `from` to `to` was inside
|
||||
/// (`Entity.checkInsideBlocks`: the sweep of its box, 16 steps at most), for
|
||||
/// the blocks that react to it (`entityInside`).
|
||||
pub fn blocks_inside(from: Vec3, to: Vec3) -> Vec<BlockPos> {
|
||||
let deflated = bounds(to).deflate(Vec3::new(
|
||||
f64::from(1.0e-5f32),
|
||||
f64::from(1.0e-5f32),
|
||||
f64::from(1.0e-5f32),
|
||||
));
|
||||
let mut inside = Vec::new();
|
||||
let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| {
|
||||
if iteration >= 16 {
|
||||
return false;
|
||||
}
|
||||
inside.push(p);
|
||||
true
|
||||
});
|
||||
inside
|
||||
}
|
||||
/// `Projectile.lerpRotation`.
|
||||
fn lerp_rotation(mut old: f32, new: f32) -> f32 {
|
||||
while new - old < -180.0 {
|
||||
@@ -423,18 +459,29 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity
|
||||
let Some(mut st) = p.arrow.take() else {
|
||||
return false;
|
||||
};
|
||||
let trident = matches!(p.kind, ProjectileKind::Trident);
|
||||
let mut ticker = Ticker {
|
||||
p,
|
||||
st: &mut st,
|
||||
scene,
|
||||
};
|
||||
match outcome {
|
||||
EntityHit::Hurt | EntityHit::Refused if trident => ticker.trident_bounce(),
|
||||
EntityHit::Hurt => {
|
||||
ticker.hit_sound();
|
||||
ticker.st.removed = true;
|
||||
// A piercing arrow flies on (`getPierceLevel() <= 0` discards).
|
||||
if ticker.st.pierce == 0 {
|
||||
ticker.st.removed = true;
|
||||
}
|
||||
}
|
||||
EntityHit::Refused => ticker.turn_back(),
|
||||
EntityHit::Deflected => {}
|
||||
EntityHit::Deflected => {
|
||||
// The deflection comes before `onHitEntity` adds the entity to
|
||||
// `piercingIgnoreEntityIds`.
|
||||
if ticker.st.pierce > 0 {
|
||||
ticker.st.pierced.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
ticker.finish();
|
||||
p.stuck = st.in_ground;
|
||||
@@ -464,7 +511,16 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
p.z,
|
||||
))
|
||||
}
|
||||
/// Whether this is a `ThrownTrident` (`AbstractArrow` with its own water
|
||||
/// inertia, sounds and hit).
|
||||
fn trident(&self) -> bool {
|
||||
matches!(self.p.kind, ProjectileKind::Trident)
|
||||
}
|
||||
fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit {
|
||||
// ThrownTrident.tick.
|
||||
if self.trident() && self.st.in_ground_time > 4 {
|
||||
self.st.dealt_damage = true;
|
||||
}
|
||||
let physics = !self.st.no_physics;
|
||||
let movement = self.p.velocity;
|
||||
let block_pos = self.block_position();
|
||||
@@ -512,8 +568,9 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.st.in_ground_time = 0;
|
||||
let original = self.position();
|
||||
if self.st.was_touching_water {
|
||||
// getWaterInertia, then the bubbles behind it.
|
||||
self.p.velocity = self.p.velocity.scale(f64::from(0.6f32));
|
||||
// getWaterInertia (0.99 for a trident), then the bubbles behind it.
|
||||
let inertia = if self.trident() { 0.99f32 } else { 0.6f32 };
|
||||
self.p.velocity = self.p.velocity.scale(f64::from(inertia));
|
||||
let v = self.p.velocity;
|
||||
for _ in 0..4 {
|
||||
self.st.events.push(ArrowEvent::Particle {
|
||||
@@ -639,7 +696,8 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.st.life = 0;
|
||||
}
|
||||
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
|
||||
/// block (piercing is not modelled).
|
||||
/// block. A piercing arrow that hits an entity here goes on from it next
|
||||
/// tick (`finish_entity_hit`); vanilla's loop goes on within the same tick.
|
||||
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);
|
||||
@@ -649,10 +707,16 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
.expand_towards(self.p.velocity)
|
||||
.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||
let mut best: Option<(Who, Vec3, f64)> = None;
|
||||
// ThrownTrident.findHitEntity: none once it has dealt damage.
|
||||
let targets = if self.st.dealt_damage { &[] } else { targets };
|
||||
for (who, b) in targets {
|
||||
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
|
||||
continue;
|
||||
}
|
||||
// canHitEntity: not an entity a piercing arrow has gone through.
|
||||
if self.st.pierced.contains(who) {
|
||||
continue;
|
||||
}
|
||||
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).
|
||||
@@ -667,6 +731,15 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.p.position = next;
|
||||
self.apply_effects_from_blocks(from, next);
|
||||
if let Some((who, at, _)) = best {
|
||||
// AbstractArrow.onHitEntity: past pierce level + 1 entities the
|
||||
// arrow is discarded before it hurts the next one.
|
||||
if self.st.pierce > 0 {
|
||||
if self.st.pierced.len() > usize::from(self.st.pierce) {
|
||||
self.st.removed = true;
|
||||
return Hit::None;
|
||||
}
|
||||
self.st.pierced.push(who);
|
||||
}
|
||||
return Hit::Entity { who, at };
|
||||
}
|
||||
let Some((at, pos, face)) = block else {
|
||||
@@ -706,12 +779,33 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
/// `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);
|
||||
let sound = if self.trident() {
|
||||
ArrowSound::TridentHitGround
|
||||
} else {
|
||||
ArrowSound::HitGround
|
||||
};
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::HitGround,
|
||||
sound,
|
||||
volume: 1.0,
|
||||
pitch,
|
||||
});
|
||||
}
|
||||
/// `ThrownTrident.onHitEntity` after the hurt, whether it landed or not:
|
||||
/// the hit sound, then `deflect(REVERSE, ..., (0.02, 0.2, 0.02))`. The
|
||||
/// trident keeps flying (it has dealt its damage) and falls.
|
||||
fn trident_bounce(&mut self) {
|
||||
self.st.dealt_damage = true;
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::TridentHit,
|
||||
volume: 1.0,
|
||||
pitch: 1.0,
|
||||
});
|
||||
// ProjectileDeflection.REVERSE.
|
||||
let rotation = 170.0 + self.st.random.next_float() * 20.0;
|
||||
let v = self.p.velocity;
|
||||
self.p.velocity = Vec3::new(v.x * (-0.02 * 0.5), v.y * (-0.2 * 0.5), v.z * (-0.02 * 0.5));
|
||||
self.p.yaw += rotation;
|
||||
}
|
||||
/// `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.
|
||||
@@ -752,6 +846,7 @@ impl Ticker<'_, '_, '_, '_> {
|
||||
self.st.shake = 7;
|
||||
self.p.set_critical(false);
|
||||
self.st.pierce = 0;
|
||||
self.st.pierced.clear();
|
||||
}
|
||||
/// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`.
|
||||
fn may_interact(&self) -> bool {
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! `filter`, `unstitch` and `paletted_permutations` sources run in order
|
||||
//! against the resource tree; a later source replaces an earlier sprite of
|
||||
//! the same id and a filter removes the matching ones.
|
||||
use crate::packs::pattern::Pattern;
|
||||
use horizon_assets::palette::apply_palette;
|
||||
use horizon_client_core::pattern::Pattern;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
|
||||
@@ -719,11 +719,6 @@ impl Audio {
|
||||
self.play(event, at, volume, pitch);
|
||||
self.capture = capture;
|
||||
}
|
||||
/// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the
|
||||
/// client (the entity's own random there, never the server's world random).
|
||||
pub fn hurt_pitch(&mut self) -> f32 {
|
||||
(self.random.next_float() - self.random.next_float()) * 0.2 + 1.0
|
||||
}
|
||||
/// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound.
|
||||
pub fn play_button_click(&mut self) {
|
||||
self.play_instance(
|
||||
|
||||
@@ -179,7 +179,7 @@ fn agent() -> ureq::Agent {
|
||||
}
|
||||
|
||||
/// The discovery document, fetched once per game (a failure is retried next time).
|
||||
fn discovery() -> Result<Arc<serde_json::Value>, JoinError> {
|
||||
pub(crate) fn discovery() -> Result<Arc<serde_json::Value>, JoinError> {
|
||||
static CACHE: Mutex<Option<Arc<serde_json::Value>>> = Mutex::new(None);
|
||||
if let Some(d) = CACHE.lock().unwrap().clone() {
|
||||
return Ok(d);
|
||||
|
||||
@@ -450,6 +450,54 @@ mod tests {
|
||||
assert_eq!(view_chunks(32), 2573);
|
||||
assert_eq!(view_chunks(0), 0);
|
||||
}
|
||||
/// The status a fake control answers with: the player is where it should
|
||||
/// be, nothing is queued, and the world holds `chunks` resident chunks.
|
||||
fn status(chunks: u64) -> String {
|
||||
serde_json::json!({
|
||||
"player": {"position": [0.0, 64.0, 0.0]},
|
||||
"pending_chunks": 0,
|
||||
"screen": "playing",
|
||||
"render_distance": 12,
|
||||
"chunks": chunks,
|
||||
"generated_chunks": chunks,
|
||||
"meshed_sections": 0,
|
||||
"streaming": {},
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_load_waits_for_the_chunks_a_teleport_starts() {
|
||||
// Right after a teleport the game reports steady counts and nothing
|
||||
// queued for over a second, before the integrated server has sent the
|
||||
// first chunk: the quiet rule alone would call that loaded, and the
|
||||
// scene would be measured over an empty view (#1749).
|
||||
const LATE: usize = 30;
|
||||
let (tx, rx) = mpsc::channel::<Request>();
|
||||
let polls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let counted = std::sync::Arc::clone(&polls);
|
||||
let server = thread::spawn(move || {
|
||||
let mut seen = 0;
|
||||
while let Ok(request) = rx.recv() {
|
||||
if request.line == "status" {
|
||||
let chunks = if seen < LATE { 0 } else { 400 };
|
||||
seen += 1;
|
||||
counted.store(seen, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = request.reply.send(status(chunks));
|
||||
} else {
|
||||
let _ = request.reply.send("{}".to_owned());
|
||||
}
|
||||
}
|
||||
});
|
||||
let control = Control(tx);
|
||||
wait_loaded(&control, |_| true).expect("the scene loads");
|
||||
assert!(
|
||||
polls.load(std::sync::atomic::Ordering::SeqCst) > LATE,
|
||||
"the load finished before the chunks arrived"
|
||||
);
|
||||
drop(control);
|
||||
let _ = server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaw_matches_vanilla() {
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Right-to-left text (`FormattedBidiReorder.reorder`, behind
|
||||
//! `Language.getVisualOrder`): the logical text a player types becomes the
|
||||
//! glyphs a font draws left to right. Arabic letters are shaped into their
|
||||
//! joined presentation forms (ICU's `ArabicShaping` with `LETTERS_SHAPE`), the
|
||||
//! text is reordered by the Unicode bidirectional algorithm, and characters in
|
||||
//! right-to-left runs are mirrored. Left-to-right text comes back unchanged.
|
||||
use crate::text::{Span, Text};
|
||||
use std::borrow::Cow;
|
||||
use unicode_bidi::{
|
||||
BidiClass, Direction, Level, ParagraphBidiInfo, bidi_class, get_base_direction,
|
||||
};
|
||||
|
||||
/// How a letter joins its neighbours, as ICU's shaper sees it: `Right` joins
|
||||
/// the letter before it only, `Dual` both neighbours, `Mark` is skipped over
|
||||
/// (diacritics) and `None` never joins.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Join {
|
||||
None,
|
||||
Right,
|
||||
Dual,
|
||||
Mark,
|
||||
}
|
||||
use Join::{Dual, Mark, Right};
|
||||
|
||||
/// ICU's joining table (`araLink`): code point ranges and their class, with the
|
||||
/// lam-alef ligatures at the end. Anything else is `Join::None`.
|
||||
const JOINS: &[(u32, u32, Join)] = &[
|
||||
(0x0622, 0x0625, Right),
|
||||
(0x0626, 0x0626, Dual),
|
||||
(0x0627, 0x0627, Right),
|
||||
(0x0628, 0x0628, Dual),
|
||||
(0x0629, 0x0629, Right),
|
||||
(0x062A, 0x062E, Dual),
|
||||
(0x062F, 0x0632, Right),
|
||||
(0x0633, 0x063A, Dual),
|
||||
(0x0640, 0x0647, Dual),
|
||||
(0x0648, 0x0649, Right),
|
||||
(0x064A, 0x064A, Dual),
|
||||
(0x064B, 0x0656, Mark),
|
||||
(0x0670, 0x0670, Mark),
|
||||
(0x0671, 0x0673, Right),
|
||||
(0x0675, 0x0677, Right),
|
||||
(0x0678, 0x0687, Dual),
|
||||
(0x0688, 0x0699, Right),
|
||||
(0x069A, 0x06B9, Dual),
|
||||
(0x06BA, 0x06BA, Right),
|
||||
(0x06BB, 0x06BF, Dual),
|
||||
(0x06C0, 0x06C0, Right),
|
||||
(0x06C1, 0x06C1, Dual),
|
||||
(0x06C2, 0x06CB, Right),
|
||||
(0x06CC, 0x06CC, Dual),
|
||||
(0x06CD, 0x06CD, Right),
|
||||
(0x06CE, 0x06D1, Dual),
|
||||
(0x06D2, 0x06D3, Right),
|
||||
(0x200D, 0x200D, Dual),
|
||||
(0x206D, 0x206F, Mark),
|
||||
(0xFEF5, 0xFEFC, Right),
|
||||
];
|
||||
|
||||
/// Letters that have joined forms and the code point of the isolated one; the
|
||||
/// final, initial and medial forms follow it (a right-joining letter has the
|
||||
/// isolated and final only). The lam-alef ligatures are their own letters.
|
||||
/// ICU leaves the extended letters (پ چ ژ ک گ ی and the rest of U+0679 to
|
||||
/// U+06D3) unchanged, so they are in `JOINS` but not here.
|
||||
#[rustfmt::skip]
|
||||
const FORMS: &[(u32, u32)] = &[
|
||||
(0x0622, 0xFE81), (0x0623, 0xFE83), (0x0624, 0xFE85), (0x0625, 0xFE87), (0x0626, 0xFE89),
|
||||
(0x0627, 0xFE8D), (0x0628, 0xFE8F), (0x0629, 0xFE93), (0x062A, 0xFE95), (0x062B, 0xFE99),
|
||||
(0x062C, 0xFE9D), (0x062D, 0xFEA1), (0x062E, 0xFEA5), (0x062F, 0xFEA9), (0x0630, 0xFEAB),
|
||||
(0x0631, 0xFEAD), (0x0632, 0xFEAF), (0x0633, 0xFEB1), (0x0634, 0xFEB5), (0x0635, 0xFEB9),
|
||||
(0x0636, 0xFEBD), (0x0637, 0xFEC1), (0x0638, 0xFEC5), (0x0639, 0xFEC9), (0x063A, 0xFECD),
|
||||
(0x0641, 0xFED1), (0x0642, 0xFED5), (0x0643, 0xFED9), (0x0644, 0xFEDD), (0x0645, 0xFEE1),
|
||||
(0x0646, 0xFEE5), (0x0647, 0xFEE9), (0x0648, 0xFEED), (0x0649, 0xFEEF), (0x064A, 0xFEF1),
|
||||
(0xFEF5, 0xFEF5), (0xFEF7, 0xFEF7), (0xFEF9, 0xFEF9), (0xFEFB, 0xFEFB),
|
||||
];
|
||||
|
||||
/// `Bidi_Mirroring_Glyph` (`UCharacter.getMirror`): each pair is two
|
||||
/// neighbouring characters that mirror each other.
|
||||
const MIRRORED: &str = "\
|
||||
()<>[]{}«»༺༻༼༽᚛᚜‹›⁅⁆⁽⁾₍₎∈∋∉∌∊∍∕⧵∟⯾∠⦣∡⦛∢⦠∤⫮∼∽≃⋍≅≌≒≓\
|
||||
≔≕≤≥≦≧≨≩≪≫≮≯≰≱≲≳≴≵≶≷≸≹≺≻≼≽≾≿⊀⊁⊂⊃⊄⊅⊆⊇⊈⊉⊊⊋⊏⊐⊑⊒⊘⦸⊢⊣⊦⫞\
|
||||
⊨⫤⊩⫣⊫⫥⊰⊱⊲⊳⊴⊵⊶⊷⊸⟜⋉⋊⋋⋌⋐⋑⋖⋗⋘⋙⋚⋛⋜⋝⋞⋟⋠⋡⋢⋣⋤⋥⋦⋧⋨⋩⋪⋫⋬⋭⋰⋱⋲⋺\
|
||||
⋳⋻⋴⋼⋶⋽⋷⋾⌈⌉⌊⌋〈〉❨❩❪❫❬❭❮❯❰❱❲❳❴❵⟃⟄⟅⟆⟈⟉⟋⟍⟕⟖⟝⟞⟢⟣⟤⟥⟦⟧⟨⟩⟪⟫\
|
||||
⟬⟭⟮⟯⦃⦄⦅⦆⦇⦈⦉⦊⦋⦌⦍⦐⦎⦏⦑⦒⦓⦔⦕⦖⦗⦘⦤⦥⦨⦩⦪⦫⦬⦭⦮⦯⧀⧁⧄⧅⧏⧐⧑⧒⧔⧕⧘⧙⧚⧛\
|
||||
⧨⧩⧸⧹⧼⧽⨫⨬⨭⨮⨴⨵⨼⨽⩤⩥⩹⩺⩻⩼⩽⩾⩿⪀⪁⪂⪃⪄⪅⪆⪇⪈⪉⪊⪋⪌⪍⪎⪏⪐⪑⪒⪓⪔⪕⪖⪗⪘⪙⪚\
|
||||
⪛⪜⪝⪞⪟⪠⪡⪢⪦⪧⪨⪩⪪⪫⪬⪭⪯⪰⪱⪲⪳⪴⪵⪶⪷⪸⪹⪺⪻⪼⪽⪾⪿⫀⫁⫂⫃⫄⫅⫆⫇⫈⫉⫊⫋⫌⫍⫎⫏⫐\
|
||||
⫑⫒⫓⫔⫕⫖⫬⫭⫷⫸⫹⫺⸂⸃⸄⸅⸉⸊⸌⸍⸜⸝⸠⸡⸢⸣⸤⸥⸦⸧⸨⸩⹕⹖⹗⹘⹙⹚⹛⹜〈〉《》「」『』【】\
|
||||
〔〕〖〗〘〙〚〛﹙﹚﹛﹜﹝﹞﹤﹥()<>[]{}⦅⦆「」";
|
||||
|
||||
fn join(c: char) -> Join {
|
||||
let c = c as u32;
|
||||
JOINS
|
||||
.iter()
|
||||
.find(|&&(from, to, _)| (from..=to).contains(&c))
|
||||
.map_or(Join::None, |&(_, _, join)| join)
|
||||
}
|
||||
|
||||
/// The letter whose joined form `c` is (ICU shapes the forms again), or `c`.
|
||||
fn letter_of(c: char) -> char {
|
||||
let c32 = c as u32;
|
||||
if !matches!(c32, 0xFE70..=0xFEFC) {
|
||||
return c;
|
||||
}
|
||||
if (0xFE70..0xFE80).contains(&c32) {
|
||||
// The diacritics' forms pair up from fathatan on.
|
||||
return char::from_u32(0x064B + (c32 - 0xFE70) / 2).unwrap_or(c);
|
||||
}
|
||||
FORMS
|
||||
.iter()
|
||||
.find(|&&(letter, iso)| {
|
||||
let forms = if join(char::from_u32(letter).unwrap_or(c)) == Dual {
|
||||
4
|
||||
} else {
|
||||
2
|
||||
};
|
||||
(iso..iso + forms).contains(&c32)
|
||||
})
|
||||
.and_then(|&(letter, _)| char::from_u32(letter))
|
||||
.unwrap_or(c)
|
||||
}
|
||||
|
||||
/// `ArabicShaping(LETTERS_SHAPE).shape`: lam followed by an alef (diacritics
|
||||
/// may sit between) becomes one ligature, then every letter takes the isolated,
|
||||
/// final, initial or medial form its neighbours call for. Diacritics take the
|
||||
/// tatweel form between two joined letters. The text can only get shorter.
|
||||
fn shape(text: &[char]) -> Vec<char> {
|
||||
let letters: Vec<char> = text.iter().map(|&c| letter_of(c)).collect();
|
||||
let mut chars = Vec::with_capacity(letters.len());
|
||||
let mut i = 0;
|
||||
while i < letters.len() {
|
||||
if letters[i] == '\u{644}' {
|
||||
let mut at = i + 1;
|
||||
while letters.get(at).is_some_and(|&c| join(c) == Mark) {
|
||||
at += 1;
|
||||
}
|
||||
let alef = letters.get(at).and_then(|&c| {
|
||||
['\u{622}', '\u{623}', '\u{625}', '\u{627}']
|
||||
.iter()
|
||||
.position(|&a| a == c)
|
||||
});
|
||||
if let Some(alef) = alef {
|
||||
chars.push(char::from_u32(0xFEF5 + 2 * alef as u32).unwrap_or('\u{644}'));
|
||||
chars.extend_from_slice(&letters[i + 1..at]);
|
||||
i = at + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
chars.push(letters[i]);
|
||||
i += 1;
|
||||
}
|
||||
// Whether the nearest letter before joins the next one, and the joins of
|
||||
// the nearest letter after.
|
||||
let mut joins_next = false;
|
||||
let mut out = Vec::with_capacity(chars.len());
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
let next_joins = chars[i + 1..]
|
||||
.iter()
|
||||
.map(|&n| join(n))
|
||||
.find(|&j| j != Mark)
|
||||
.is_some_and(|j| j != Join::None);
|
||||
let kind = join(c);
|
||||
let shaped = match kind {
|
||||
Join::None => {
|
||||
joins_next = false;
|
||||
c
|
||||
}
|
||||
Mark => match c as u32 {
|
||||
m @ 0x064B..=0x0652 => {
|
||||
let iso = 0xFE70 + 2 * (m - 0x064B);
|
||||
let tatweel = joins_next && next_joins && !matches!(m, 0x064C | 0x064D);
|
||||
char::from_u32(iso + u32::from(tatweel)).unwrap_or(c)
|
||||
}
|
||||
_ => c,
|
||||
},
|
||||
Right | Dual => {
|
||||
let to_next = kind == Dual && next_joins;
|
||||
let form = match (joins_next, to_next) {
|
||||
(false, false) => 0,
|
||||
(true, false) => 1,
|
||||
(false, true) => 2,
|
||||
(true, true) => 3,
|
||||
};
|
||||
joins_next = kind == Dual;
|
||||
FORMS
|
||||
.binary_search_by_key(&(c as u32), |&(letter, _)| letter)
|
||||
.ok()
|
||||
.and_then(|at| char::from_u32(FORMS[at].1 + form))
|
||||
.unwrap_or(c)
|
||||
}
|
||||
};
|
||||
out.push(shaped);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `UCharacter.getMirror`.
|
||||
fn mirror(c: char) -> char {
|
||||
if bidi_class(c) != BidiClass::ON {
|
||||
return c;
|
||||
}
|
||||
let mut pairs = MIRRORED.chars();
|
||||
while let (Some(a), Some(b)) = (pairs.next(), pairs.next()) {
|
||||
if c == a {
|
||||
return b;
|
||||
}
|
||||
if c == b {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Whether a character can change anything: right-to-left letters and numbers,
|
||||
/// the explicit direction controls and the diacritics that shaping turns into
|
||||
/// letters. Without any, left-to-right text keeps its order.
|
||||
fn directional(c: char) -> bool {
|
||||
c as u32 >= 0x0590
|
||||
&& (matches!(c as u32, 0x064B..=0x0652)
|
||||
|| matches!(
|
||||
bidi_class(c),
|
||||
BidiClass::R
|
||||
| BidiClass::AL
|
||||
| BidiClass::AN
|
||||
| BidiClass::LRE
|
||||
| BidiClass::RLE
|
||||
| BidiClass::LRO
|
||||
| BidiClass::RLO
|
||||
| BidiClass::PDF
|
||||
| BidiClass::LRI
|
||||
| BidiClass::RLI
|
||||
| BidiClass::FSI
|
||||
| BidiClass::PDI
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether `chars` keep their order and shapes: left-to-right text without
|
||||
/// anything directional, in a language that reads left to right by default.
|
||||
fn unchanged(mut chars: impl Iterator<Item = char>, default_rtl: bool) -> bool {
|
||||
!default_rtl && !chars.any(directional)
|
||||
}
|
||||
|
||||
/// `FormattedBidiReorder.reorder`: `chars` shaped, in visual order, with each
|
||||
/// character's position in the shaped text. A character's style is the one at
|
||||
/// its position in the shaped text, as `SubStringSource` takes it (the text
|
||||
/// shrinks at a lam-alef ligature).
|
||||
fn reorder(chars: &[char], default_rtl: bool) -> Vec<(char, usize)> {
|
||||
let shaped = shape(chars);
|
||||
let plain: String = shaped.iter().collect();
|
||||
// DEFAULT_RTL only changes text without a strong character.
|
||||
let level =
|
||||
(default_rtl && get_base_direction(plain.as_str()) == Direction::Mixed).then(Level::rtl);
|
||||
let info = ParagraphBidiInfo::new(&plain, level);
|
||||
let levels = info.reordered_levels_per_char(0..plain.len());
|
||||
ParagraphBidiInfo::reorder_visual(&levels)
|
||||
.into_iter()
|
||||
.map(|i| {
|
||||
let c = if levels[i].is_rtl() {
|
||||
mirror(shaped[i])
|
||||
} else {
|
||||
shaped[i]
|
||||
};
|
||||
(c, i)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `Language.getVisualOrder` of a text (its `§` codes already resolved), for
|
||||
/// the current language's direction.
|
||||
pub fn visual(text: &Text) -> Cow<'_, Text> {
|
||||
let default_rtl = crate::lang::bidirectional();
|
||||
if unchanged(text.chars().map(|(c, _)| c), default_rtl) {
|
||||
return Cow::Borrowed(text);
|
||||
}
|
||||
let chars: Vec<char> = text.chars().map(|(c, _)| c).collect();
|
||||
let styles: Vec<_> = text.chars().map(|(_, style)| style).collect();
|
||||
let mut out = Text::default();
|
||||
for (c, at) in reorder(&chars, default_rtl) {
|
||||
match out.spans.last_mut() {
|
||||
Some(span) if span.style == *styles[at] => span.text.push(c),
|
||||
_ => out.spans.push(Span {
|
||||
text: c.to_string(),
|
||||
style: styles[at].clone(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
|
||||
/// The same for a plain string.
|
||||
pub fn visual_str(s: &str) -> Cow<'_, str> {
|
||||
let default_rtl = crate::lang::bidirectional();
|
||||
if unchanged(s.chars(), default_rtl) {
|
||||
return Cow::Borrowed(s);
|
||||
}
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
Cow::Owned(
|
||||
reorder(&chars, default_rtl)
|
||||
.into_iter()
|
||||
.map(|(c, _)| c)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Biome colours from the pinned biome definitions and colormaps
|
||||
//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`).
|
||||
use crate::Result;
|
||||
use horizon_core::{noise::SimplexNoise, random::LegacyRandom};
|
||||
use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path};
|
||||
|
||||
@@ -33,6 +33,8 @@ pub struct BiomeInfo {
|
||||
pub increased_fire_burnout: bool,
|
||||
pub name: String,
|
||||
pub temperature: f32,
|
||||
/// `temperature_modifier: frozen` (the frozen oceans).
|
||||
pub frozen: bool,
|
||||
pub downfall: f32,
|
||||
pub precipitation: bool,
|
||||
pub grass: u32,
|
||||
@@ -45,6 +47,26 @@ pub struct BiomeInfo {
|
||||
pub fog: Option<u32>,
|
||||
pub water_fog: u32,
|
||||
}
|
||||
impl BiomeInfo {
|
||||
/// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler
|
||||
/// with height above `sea_level + 17`.
|
||||
pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 {
|
||||
use horizon_world::worldgen::biome_temperature::{
|
||||
BiomeTemperatureSettings, TemperatureModifier,
|
||||
};
|
||||
BiomeTemperatureSettings {
|
||||
base_temperature: self.temperature,
|
||||
modifier: if self.frozen {
|
||||
TemperatureModifier::Frozen
|
||||
} else {
|
||||
TemperatureModifier::None
|
||||
},
|
||||
has_precipitation: self.precipitation,
|
||||
downfall: self.downfall,
|
||||
}
|
||||
.height_adjusted(pos, sea_level)
|
||||
}
|
||||
}
|
||||
pub struct Biomes {
|
||||
pub list: Vec<BiomeInfo>,
|
||||
pub index: HashMap<String, u16>,
|
||||
@@ -135,6 +157,7 @@ impl Biomes {
|
||||
.as_bool()
|
||||
.unwrap_or(false),
|
||||
temperature,
|
||||
frozen: v["temperature_modifier"].as_str() == Some("frozen"),
|
||||
downfall,
|
||||
precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
|
||||
grass: color(&effects["grass_color"])
|
||||
|
||||
@@ -648,6 +648,61 @@ impl Conduit {
|
||||
}
|
||||
}
|
||||
|
||||
/// What `ConduitBlockEntity.serverTick`'s 40-tick check decided.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct ConduitCheck {
|
||||
/// The shape changed: `CONDUIT_ACTIVATE` (true) or `CONDUIT_DEACTIVATE`.
|
||||
pub toggled: Option<bool>,
|
||||
/// The frame blocks counted, while the conduit is active: `applyEffects`
|
||||
/// and `updateAndAttackTarget` follow (the attack needs 42 or more).
|
||||
pub frames: Option<usize>,
|
||||
}
|
||||
|
||||
/// `ConduitBlockEntity` (server side): what `serverTick` keeps between ticks.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ConduitServer {
|
||||
shape: Conduit,
|
||||
/// `destroyTarget`: the mob id of the enemy being struck.
|
||||
pub target: Option<u32>,
|
||||
next_ambient_sound: i64,
|
||||
}
|
||||
|
||||
impl ConduitServer {
|
||||
/// The `gameTime % 40` part of `serverTick`: the shape is checked again.
|
||||
pub fn check(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
game_time: i64,
|
||||
is_water: impl Fn([i32; 3]) -> bool,
|
||||
is_frame: impl Fn([i32; 3]) -> bool,
|
||||
) -> Option<ConduitCheck> {
|
||||
if game_time % 40 != 0 {
|
||||
return None;
|
||||
}
|
||||
let active = self.shape.update_shape(pos, &is_water, &is_frame);
|
||||
let toggled = (active != self.shape.is_active).then_some(active);
|
||||
self.shape.is_active = active;
|
||||
Some(ConduitCheck {
|
||||
toggled,
|
||||
frames: active.then_some(self.shape.effect_blocks.len()),
|
||||
})
|
||||
}
|
||||
/// The sounds of an active conduit at the end of `serverTick`: whether
|
||||
/// `CONDUIT_AMBIENT` (every 80 ticks) and `CONDUIT_AMBIENT_SHORT` (every
|
||||
/// 60 to 99 ticks) play.
|
||||
pub fn ambient(&mut self, game_time: i64, random: &mut impl RandomSource) -> (bool, bool) {
|
||||
if !self.shape.is_active {
|
||||
return (false, false);
|
||||
}
|
||||
let short = game_time > self.next_ambient_sound;
|
||||
if short {
|
||||
self.next_ambient_sound =
|
||||
game_time + 60 + i64::from(random.next_int_bound(40).unwrap_or(0));
|
||||
}
|
||||
(game_time % 80 == 0, short)
|
||||
}
|
||||
}
|
||||
|
||||
/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Skull {
|
||||
@@ -832,6 +887,8 @@ pub struct BlockEntityAnims {
|
||||
pub gateways: FxHashMap<[i32; 3], EndGateway>,
|
||||
/// The integrated server's copies of the gateways (`portalTick`).
|
||||
pub gateway_servers: FxHashMap<[i32; 3], EndGateway>,
|
||||
/// The integrated server's copies of the conduits (`serverTick`).
|
||||
pub conduit_servers: FxHashMap<[i32; 3], ConduitServer>,
|
||||
/// The client level's random (conduit particles).
|
||||
pub random: LegacyRandom,
|
||||
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
|
||||
@@ -854,6 +911,7 @@ impl Default for BlockEntityAnims {
|
||||
pots: FxHashMap::default(),
|
||||
gateways: FxHashMap::default(),
|
||||
gateway_servers: FxHashMap::default(),
|
||||
conduit_servers: FxHashMap::default(),
|
||||
random: LegacyRandom::new(0x6c6576656c),
|
||||
kinds: Vec::new(),
|
||||
present: Vec::new(),
|
||||
@@ -909,6 +967,7 @@ impl BlockEntityAnims {
|
||||
self.pots.retain(|p, _| keep(*p));
|
||||
self.gateways.retain(|p, _| keep(*p));
|
||||
self.gateway_servers.retain(|p, _| keep(*p));
|
||||
self.conduit_servers.retain(|p, _| keep(*p));
|
||||
}
|
||||
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
|
||||
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
|
||||
|
||||
@@ -1,973 +0,0 @@
|
||||
//! Vanilla 26.3 block entity NBT for every block entity type.
|
||||
//!
|
||||
//! [`canonical`] is `loadAdditional` followed by `saveWithFullMetadata` for each of
|
||||
//! the 47 `BlockEntityType`s: it reads the fields the type reads (with vanilla's
|
||||
//! defaults and clamps), drops everything else and writes the fields `saveAdditional`
|
||||
//! writes (including its omit-when-empty rules). Nested codec values that Horizon does
|
||||
//! not simulate (spawner entity data, vibration listeners, trial spawner configuration,
|
||||
//! vault data, sculk cursors, sign and banner components, profiles) are carried as
|
||||
//! loaded. The common `BaseContainerBlockEntity` fields (`CustomName`, `lock`) and the
|
||||
//! `RandomizableContainer` loot table fields are handled for every container type.
|
||||
//!
|
||||
//! [`overlay`] merges a block entity Horizon models (and re-encodes from its own,
|
||||
//! partial state) with the NBT it was loaded from, so fields Horizon does not model
|
||||
//! survive and only what the game changed is replaced.
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
fn string(s: &str) -> Tag {
|
||||
Tag::String(s.into())
|
||||
}
|
||||
fn text(tag: Option<&Tag>) -> Option<String> {
|
||||
match tag {
|
||||
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `CompoundTag.getIntOr`: any numeric tag (floats floor).
|
||||
fn int(tag: Option<&Tag>) -> Option<i32> {
|
||||
Some(match tag? {
|
||||
Tag::Byte(v) => i32::from(*v),
|
||||
Tag::Short(v) => i32::from(*v),
|
||||
Tag::Int(v) => *v,
|
||||
Tag::Long(v) => *v as i32,
|
||||
Tag::Float(b) => f32::from_bits(*b).floor() as i32,
|
||||
Tag::Double(b) => f64::from_bits(*b).floor() as i32,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn long(tag: Option<&Tag>) -> Option<i64> {
|
||||
Some(match tag? {
|
||||
Tag::Long(v) => *v,
|
||||
Tag::Float(b) => f32::from_bits(*b).floor() as i64,
|
||||
Tag::Double(b) => f64::from_bits(*b).floor() as i64,
|
||||
other => i64::from(int(Some(other))?),
|
||||
})
|
||||
}
|
||||
fn float(tag: Option<&Tag>) -> Option<f32> {
|
||||
Some(match tag? {
|
||||
Tag::Float(b) => f32::from_bits(*b),
|
||||
Tag::Double(b) => f64::from_bits(*b) as f32,
|
||||
Tag::Long(v) => *v as f32,
|
||||
other => int(Some(other))? as f32,
|
||||
})
|
||||
}
|
||||
fn flag(tag: Option<&Tag>) -> Option<bool> {
|
||||
Some(int(tag)? != 0)
|
||||
}
|
||||
fn boolean(v: bool) -> Tag {
|
||||
Tag::Byte(i8::from(v))
|
||||
}
|
||||
fn f32_tag(v: f32) -> Tag {
|
||||
Tag::Float(v.to_bits())
|
||||
}
|
||||
|
||||
/// What a block entity reads and writes, in `saveAdditional` order.
|
||||
struct Fields<'a> {
|
||||
input: &'a Tag,
|
||||
out: Compound,
|
||||
}
|
||||
impl<'a> Fields<'a> {
|
||||
fn put(&mut self, key: &str, value: Tag) {
|
||||
self.out.insert(key.into(), value);
|
||||
}
|
||||
fn int(&mut self, key: &str, default: i32) {
|
||||
let v = int(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, Tag::Int(v));
|
||||
}
|
||||
fn int_clamped(&mut self, key: &str, default: i32, min: i32, max: i32) {
|
||||
let v = int(self.input.get(key)).unwrap_or(default).clamp(min, max);
|
||||
self.put(key, Tag::Int(v));
|
||||
}
|
||||
fn short(&mut self, key: &str, default: i16) {
|
||||
let v = int(self.input.get(key)).map_or(default, |v| v as i16);
|
||||
self.put(key, Tag::Short(v));
|
||||
}
|
||||
fn long(&mut self, key: &str, default: i64) {
|
||||
let v = long(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, Tag::Long(v));
|
||||
}
|
||||
fn float(&mut self, key: &str, default: f32) {
|
||||
let v = float(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, f32_tag(v));
|
||||
}
|
||||
fn flag(&mut self, key: &str, default: bool) {
|
||||
let v = flag(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, boolean(v));
|
||||
}
|
||||
fn string(&mut self, key: &str, default: &str) {
|
||||
let v = text(self.input.get(key)).unwrap_or_else(|| default.to_owned());
|
||||
self.put(key, string(&v));
|
||||
}
|
||||
/// An optional value written as loaded, when it has the expected shape.
|
||||
fn keep(&mut self, key: &str, valid: impl Fn(&Tag) -> bool) {
|
||||
if let Some(t) = self.input.get(key).filter(|t| valid(t)) {
|
||||
self.put(key, t.clone());
|
||||
}
|
||||
}
|
||||
fn keep_compound(&mut self, key: &str) {
|
||||
self.keep(key, |t| matches!(t, Tag::Compound(_)));
|
||||
}
|
||||
/// A compound that is always written (`default` when absent).
|
||||
fn compound_or(&mut self, key: &str, default: Compound) {
|
||||
let v = match self.input.get(key) {
|
||||
Some(Tag::Compound(c)) => c.clone(),
|
||||
_ => default,
|
||||
};
|
||||
self.put(key, Tag::Compound(v));
|
||||
}
|
||||
/// An optional text component (`storeNullable("CustomName", ComponentSerialization.CODEC)`).
|
||||
fn component(&mut self, key: &str) {
|
||||
if let Some(c) = self.input.get(key).and_then(component) {
|
||||
self.put(key, c);
|
||||
}
|
||||
}
|
||||
/// `LockCode.addToTag`.
|
||||
fn lock(&mut self) {
|
||||
self.keep_compound("lock");
|
||||
}
|
||||
/// `BaseContainerBlockEntity`: the custom name and the lock.
|
||||
fn base_container(&mut self) {
|
||||
self.component("CustomName");
|
||||
self.lock();
|
||||
}
|
||||
/// `RandomizableContainer.tryLoadLootTable` / `trySaveLootTable`; true when the
|
||||
/// block entity has a loot table (and so saves no items).
|
||||
fn loot_table(&mut self) -> bool {
|
||||
let Some(table) = text(self.input.get("LootTable")) else {
|
||||
return false;
|
||||
};
|
||||
self.put("LootTable", string(&table));
|
||||
let seed = long(self.input.get("LootTableSeed")).unwrap_or(0);
|
||||
if seed != 0 {
|
||||
self.put("LootTableSeed", Tag::Long(seed));
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `ContainerHelper.loadAllItems` + `saveAllItems`.
|
||||
fn items(&mut self, size: usize, also_when_empty: bool) {
|
||||
let items = items(self.input.get("Items"), size);
|
||||
if !items.is_empty() || also_when_empty {
|
||||
self.put("Items", Tag::List(items));
|
||||
}
|
||||
}
|
||||
/// A container: loot table or items.
|
||||
fn container(&mut self, size: usize, also_when_empty: bool) {
|
||||
if !self.loot_table() {
|
||||
self.items(size, also_when_empty);
|
||||
}
|
||||
}
|
||||
/// An optional `ItemStack` (`RecordItem`, `Book`, `item`).
|
||||
fn item(&mut self, key: &str) -> bool {
|
||||
match self.input.get(key).and_then(stack) {
|
||||
Some(item) => {
|
||||
self.put(key, item);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ComponentSerialization.CODEC` on loaded NBT: a literal without style is a plain
|
||||
/// string; anything else is kept as loaded.
|
||||
pub fn component(tag: &Tag) -> Option<Tag> {
|
||||
match tag {
|
||||
Tag::String(_) | Tag::List(_) => Some(tag.clone()),
|
||||
Tag::Compound(c) => {
|
||||
if c.len() == 1
|
||||
&& let Some(t @ Tag::String(_)) = c.get(&"text".into())
|
||||
{
|
||||
return Some(t.clone());
|
||||
}
|
||||
Some(tag.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `ItemStack.CODEC`: `id`, `count` (1..=99, default 1) and a non-empty `components`
|
||||
/// patch kept as loaded. None for the empty stack and for invalid stacks.
|
||||
pub fn stack(tag: &Tag) -> Option<Tag> {
|
||||
let id = text(tag.get("id"))?;
|
||||
if id.is_empty() || id == "minecraft:air" {
|
||||
return None;
|
||||
}
|
||||
let count = int(tag.get("count")).unwrap_or(1);
|
||||
if !(1..=99).contains(&count) {
|
||||
return None;
|
||||
}
|
||||
let mut out = vec![("id", string(&id)), ("count", Tag::Int(count))];
|
||||
if let Some(c @ Tag::Compound(map)) = tag.get("components")
|
||||
&& !map.is_empty()
|
||||
{
|
||||
out.push(("components", c.clone()));
|
||||
}
|
||||
Some(Tag::compound(out))
|
||||
}
|
||||
/// `ItemStackTemplate.CODEC`: an item id or `{id, count?, components?}`.
|
||||
fn template(tag: &Tag) -> Option<Tag> {
|
||||
match tag {
|
||||
Tag::String(_) => Some(tag.clone()),
|
||||
Tag::Compound(_) => {
|
||||
let mut out = vec![("id", string(&text(tag.get("id"))?))];
|
||||
if let Some(count) = int(tag.get("count")).filter(|c| *c != 1) {
|
||||
out.push(("count", Tag::Int(count)));
|
||||
}
|
||||
if let Some(c @ Tag::Compound(map)) = tag.get("components")
|
||||
&& !map.is_empty()
|
||||
{
|
||||
out.push(("components", c.clone()));
|
||||
}
|
||||
Some(Tag::compound(out))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `ItemStackWithSlot` entries of a container of `size` slots, by ascending slot.
|
||||
fn items(tag: Option<&Tag>, size: usize) -> Vec<Tag> {
|
||||
let mut slots: Vec<Option<Tag>> = vec![None; size];
|
||||
if let Some(Tag::List(list)) = tag {
|
||||
for entry in list {
|
||||
let (Some(slot), Some(item)) = (int(entry.get("Slot")), stack(entry)) else {
|
||||
continue;
|
||||
};
|
||||
if (0..size as i32).contains(&slot) {
|
||||
slots[slot as usize] = Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
slots
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, item)| {
|
||||
let Tag::Compound(mut c) = item? else {
|
||||
return None;
|
||||
};
|
||||
c.insert("Slot".into(), Tag::Byte(i as i8));
|
||||
Some(Tag::Compound(c))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn int_array(tag: Option<&Tag>) -> Option<&Vec<i32>> {
|
||||
match tag {
|
||||
Some(Tag::IntArray(v)) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A saved `BlockPos` (`[I; x, y, z]`).
|
||||
fn is_pos(tag: &Tag) -> bool {
|
||||
matches!(tag, Tag::IntArray(v) if v.len() == 3)
|
||||
}
|
||||
/// The loaded `SignText` of one side, or the empty text.
|
||||
pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag {
|
||||
let empty = || string("");
|
||||
let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) {
|
||||
Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
messages.resize_with(4, empty);
|
||||
messages.truncate(4);
|
||||
let mut out = vec![
|
||||
("messages", Tag::List(messages)),
|
||||
(
|
||||
"color",
|
||||
string(
|
||||
&tag.and_then(|t| text(t.get("color")))
|
||||
.unwrap_or_else(|| "black".into()),
|
||||
),
|
||||
),
|
||||
(
|
||||
"has_glowing_text",
|
||||
boolean(
|
||||
tag.and_then(|t| flag(t.get("has_glowing_text")))
|
||||
.unwrap_or(false),
|
||||
),
|
||||
),
|
||||
];
|
||||
if let Some(filtered @ Tag::List(list)) = tag.and_then(|t| t.get("filtered_messages"))
|
||||
&& list.len() == 4
|
||||
{
|
||||
out.push(("filtered_messages", filtered.clone()));
|
||||
}
|
||||
Tag::compound(out)
|
||||
}
|
||||
|
||||
/// The id of a block entity compound.
|
||||
pub fn id(tag: &Tag) -> Option<String> {
|
||||
text(tag.get("id"))
|
||||
}
|
||||
|
||||
/// Every `BlockEntityType` id this module knows.
|
||||
pub const TYPES: [&str; 47] = [
|
||||
"minecraft:furnace",
|
||||
"minecraft:chest",
|
||||
"minecraft:trapped_chest",
|
||||
"minecraft:ender_chest",
|
||||
"minecraft:jukebox",
|
||||
"minecraft:dispenser",
|
||||
"minecraft:dropper",
|
||||
"minecraft:sign",
|
||||
"minecraft:hanging_sign",
|
||||
"minecraft:mob_spawner",
|
||||
"minecraft:creaking_heart",
|
||||
"minecraft:piston",
|
||||
"minecraft:brewing_stand",
|
||||
"minecraft:enchanting_table",
|
||||
"minecraft:end_portal",
|
||||
"minecraft:beacon",
|
||||
"minecraft:skull",
|
||||
"minecraft:daylight_detector",
|
||||
"minecraft:hopper",
|
||||
"minecraft:comparator",
|
||||
"minecraft:banner",
|
||||
"minecraft:structure_block",
|
||||
"minecraft:end_gateway",
|
||||
"minecraft:command_block",
|
||||
"minecraft:shulker_box",
|
||||
"minecraft:conduit",
|
||||
"minecraft:barrel",
|
||||
"minecraft:smoker",
|
||||
"minecraft:blast_furnace",
|
||||
"minecraft:lectern",
|
||||
"minecraft:bell",
|
||||
"minecraft:jigsaw",
|
||||
"minecraft:campfire",
|
||||
"minecraft:beehive",
|
||||
"minecraft:sculk_sensor",
|
||||
"minecraft:calibrated_sculk_sensor",
|
||||
"minecraft:sculk_catalyst",
|
||||
"minecraft:sculk_shrieker",
|
||||
"minecraft:chiseled_bookshelf",
|
||||
"minecraft:shelf",
|
||||
"minecraft:brushable_block",
|
||||
"minecraft:decorated_pot",
|
||||
"minecraft:crafter",
|
||||
"minecraft:trial_spawner",
|
||||
"minecraft:vault",
|
||||
"minecraft:test_block",
|
||||
"minecraft:test_instance_block",
|
||||
];
|
||||
/// The two types added after the ones above in 26.3.
|
||||
pub const NEWEST: [&str; 2] = ["minecraft:copper_golem_statue", "minecraft:potent_sulfur"];
|
||||
|
||||
/// The block entity as vanilla would save it after loading `tag` (a full block
|
||||
/// entity compound with `id`, `x`, `y`, `z`); None for an unknown type or a tag
|
||||
/// without a position.
|
||||
pub fn canonical(tag: &Tag) -> Option<Tag> {
|
||||
let id = id(tag)?;
|
||||
let (x, y, z) = (int(tag.get("x"))?, int(tag.get("y"))?, int(tag.get("z"))?);
|
||||
let mut f = Fields {
|
||||
input: tag,
|
||||
out: Compound::new(),
|
||||
};
|
||||
match id.as_str() {
|
||||
"minecraft:furnace" | "minecraft:smoker" | "minecraft:blast_furnace" => {
|
||||
f.base_container();
|
||||
f.int("cooking_time_spent", 0);
|
||||
f.int("cooking_total_time", 0);
|
||||
f.int("lit_time_remaining", 0);
|
||||
f.int("lit_total_time", 0);
|
||||
f.float("speed_multiplier", 1.0);
|
||||
f.items(3, true);
|
||||
let used: Compound = match tag.get("RecipesUsed") {
|
||||
Some(Tag::Compound(c)) => c
|
||||
.iter()
|
||||
.filter_map(|(k, v)| Some((k.clone(), Tag::Int(int(Some(v))?))))
|
||||
.collect(),
|
||||
_ => Compound::new(),
|
||||
};
|
||||
f.put("RecipesUsed", Tag::Compound(used));
|
||||
}
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => {
|
||||
f.base_container();
|
||||
f.container(27, true);
|
||||
}
|
||||
"minecraft:dispenser" | "minecraft:dropper" => {
|
||||
f.base_container();
|
||||
f.container(9, true);
|
||||
}
|
||||
"minecraft:hopper" => {
|
||||
f.base_container();
|
||||
f.container(5, true);
|
||||
f.int("TransferCooldown", -1);
|
||||
}
|
||||
"minecraft:shulker_box" => {
|
||||
f.base_container();
|
||||
f.container(27, false);
|
||||
}
|
||||
"minecraft:crafter" => {
|
||||
f.base_container();
|
||||
f.int("crafting_ticks_remaining", 0);
|
||||
f.container(9, true);
|
||||
let disabled: Vec<i32> = int_array(tag.get("disabled_slots"))
|
||||
.map(|v| v.iter().copied().filter(|s| (0..9).contains(s)).collect())
|
||||
.unwrap_or_default();
|
||||
// `addDisabledSlots`: the slots whose container data is 1, ascending.
|
||||
let mut slots = disabled;
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
f.put("disabled_slots", Tag::IntArray(slots));
|
||||
f.put(
|
||||
"triggered",
|
||||
Tag::Int(int(tag.get("triggered")).unwrap_or(0)),
|
||||
);
|
||||
}
|
||||
"minecraft:ender_chest"
|
||||
| "minecraft:end_portal"
|
||||
| "minecraft:daylight_detector"
|
||||
| "minecraft:bell"
|
||||
| "minecraft:conduit"
|
||||
| "minecraft:copper_golem_statue" => {
|
||||
if id == "minecraft:conduit" {
|
||||
f.keep("Target", |t| matches!(t, Tag::IntArray(v) if v.len() == 4));
|
||||
}
|
||||
}
|
||||
"minecraft:end_gateway" => {
|
||||
f.long("Age", 0);
|
||||
f.keep("exit_portal", |t| {
|
||||
is_pos(t)
|
||||
&& matches!(t, Tag::IntArray(v) if v[1].abs() <= 30_000_000 && v[0].abs() <= 30_000_000 && v[2].abs() <= 30_000_000)
|
||||
});
|
||||
if flag(tag.get("ExactTeleport")) == Some(true) {
|
||||
f.put("ExactTeleport", boolean(true));
|
||||
}
|
||||
}
|
||||
"minecraft:jukebox" => {
|
||||
let has_song = f.item("RecordItem");
|
||||
if has_song
|
||||
&& let Some(ticks) = tag
|
||||
.get("ticks_since_song_started")
|
||||
.and_then(|t| long(Some(t)))
|
||||
&& let Some(Tag::Compound(c)) = f.out.get(&"RecordItem".into())
|
||||
&& is_record(c)
|
||||
{
|
||||
f.put("ticks_since_song_started", Tag::Long(ticks));
|
||||
}
|
||||
}
|
||||
"minecraft:sign" | "minecraft:hanging_sign" => {
|
||||
if flag(tag.get("allow_op_features")) == Some(true) {
|
||||
f.put("allow_op_features", boolean(true));
|
||||
}
|
||||
f.put("front_text", sign_side(tag.get("front_text")));
|
||||
f.put("back_text", sign_side(tag.get("back_text")));
|
||||
f.flag("is_waxed", false);
|
||||
}
|
||||
"minecraft:mob_spawner" => {
|
||||
f.short("Delay", 20);
|
||||
f.short("MinSpawnDelay", 200);
|
||||
f.short("MaxSpawnDelay", 800);
|
||||
f.short("SpawnCount", 4);
|
||||
f.short("MaxNearbyEntities", 6);
|
||||
f.short("RequiredPlayerRange", 16);
|
||||
f.short("SpawnRange", 4);
|
||||
f.keep_compound("SpawnData");
|
||||
let potentials = match tag.get("SpawnPotentials") {
|
||||
Some(t @ Tag::List(_)) => t.clone(),
|
||||
_ => match f.out.get(&"SpawnData".into()) {
|
||||
Some(data) => Tag::List(vec![Tag::compound([
|
||||
("data", data.clone()),
|
||||
("weight", Tag::Int(1)),
|
||||
])]),
|
||||
None => Tag::List(Vec::new()),
|
||||
},
|
||||
};
|
||||
f.put("SpawnPotentials", potentials);
|
||||
}
|
||||
"minecraft:creaking_heart" => {
|
||||
f.keep(
|
||||
"creaking",
|
||||
|t| matches!(t, Tag::IntArray(v) if v.len() == 4),
|
||||
);
|
||||
}
|
||||
"minecraft:piston" => {
|
||||
f.put(
|
||||
"blockState",
|
||||
match tag.get("blockState") {
|
||||
Some(t @ (Tag::String(_) | Tag::Compound(_))) => t.clone(),
|
||||
_ => string("minecraft:air"),
|
||||
},
|
||||
);
|
||||
f.put("facing", Tag::Int(int(tag.get("facing")).unwrap_or(0)));
|
||||
f.float("progress", 0.0);
|
||||
f.flag("extending", false);
|
||||
f.flag("source", false);
|
||||
}
|
||||
"minecraft:brewing_stand" => {
|
||||
f.base_container();
|
||||
f.int("BrewTime", 0);
|
||||
f.int("total_brew_time", 400);
|
||||
f.items(5, true);
|
||||
f.int("Fuel", 0);
|
||||
f.int("total_fuel", 20);
|
||||
f.float("speed_multiplier", 1.0);
|
||||
}
|
||||
"minecraft:enchanting_table" => f.component("CustomName"),
|
||||
"minecraft:beacon" => {
|
||||
for key in ["primary_effect", "secondary_effect"] {
|
||||
if let Some(effect) = text(tag.get(key)) {
|
||||
f.put(key, string(&effect));
|
||||
}
|
||||
}
|
||||
f.int("Levels", 0);
|
||||
f.component("CustomName");
|
||||
f.lock();
|
||||
}
|
||||
"minecraft:skull" => {
|
||||
f.keep("profile", |t| {
|
||||
matches!(t, Tag::Compound(_) | Tag::String(_))
|
||||
});
|
||||
if let Some(sound) = text(tag.get("note_block_sound")) {
|
||||
f.put("note_block_sound", string(&sound));
|
||||
}
|
||||
f.component("custom_name");
|
||||
}
|
||||
"minecraft:comparator" => f.int("OutputSignal", 0),
|
||||
"minecraft:banner" => {
|
||||
if let Some(patterns @ Tag::List(list)) = tag.get("patterns")
|
||||
&& !list.is_empty()
|
||||
{
|
||||
f.put("patterns", patterns.clone());
|
||||
}
|
||||
f.component("CustomName");
|
||||
}
|
||||
"minecraft:structure_block" => {
|
||||
f.string("name", "");
|
||||
f.string("author", "");
|
||||
f.string("metadata", "");
|
||||
f.int_clamped("posX", 0, -48, 48);
|
||||
f.int_clamped("posY", 1, -48, 48);
|
||||
f.int_clamped("posZ", 0, -48, 48);
|
||||
f.int_clamped("sizeX", 0, 0, 48);
|
||||
f.int_clamped("sizeY", 0, 0, 48);
|
||||
f.int_clamped("sizeZ", 0, 0, 48);
|
||||
f.string("rotation", "NONE");
|
||||
f.string("mirror", "NONE");
|
||||
f.string("mode", "DATA");
|
||||
f.flag("ignoreEntities", true);
|
||||
f.flag("strict", false);
|
||||
f.flag("powered", false);
|
||||
f.flag("showair", false);
|
||||
f.flag("showboundingbox", true);
|
||||
f.float("integrity", 1.0);
|
||||
f.long("seed", 0);
|
||||
}
|
||||
"minecraft:command_block" => {
|
||||
f.string("Command", "");
|
||||
f.int("SuccessCount", 0);
|
||||
f.component("CustomName");
|
||||
let track = flag(tag.get("TrackOutput")).unwrap_or(true);
|
||||
f.put("TrackOutput", boolean(track));
|
||||
if track {
|
||||
f.component("LastOutput");
|
||||
}
|
||||
let update = flag(tag.get("UpdateLastExecution")).unwrap_or(true);
|
||||
f.put("UpdateLastExecution", boolean(update));
|
||||
if update && let Some(last) = long(tag.get("LastExecution")).filter(|l| *l != -1) {
|
||||
f.put("LastExecution", Tag::Long(last));
|
||||
}
|
||||
f.flag("powered", false);
|
||||
f.flag("conditionMet", false);
|
||||
f.flag("auto", false);
|
||||
}
|
||||
"minecraft:lectern" => {
|
||||
if f.item("Book") {
|
||||
f.int("Page", 0);
|
||||
}
|
||||
}
|
||||
"minecraft:jigsaw" => {
|
||||
f.string("name", "minecraft:empty");
|
||||
f.string("target", "minecraft:empty");
|
||||
f.string("pool", "minecraft:empty");
|
||||
f.string("final_state", "minecraft:air");
|
||||
f.string("joint", "rollable");
|
||||
f.int("placement_priority", 0);
|
||||
f.int("selection_priority", 0);
|
||||
}
|
||||
"minecraft:campfire" => {
|
||||
f.items(4, true);
|
||||
for key in ["CookingTimes", "CookingTotalTimes"] {
|
||||
let mut times = [0; 4];
|
||||
if let Some(v) = int_array(tag.get(key)) {
|
||||
for (slot, t) in times.iter_mut().zip(v) {
|
||||
*slot = *t;
|
||||
}
|
||||
}
|
||||
f.put(key, Tag::IntArray(times.to_vec()));
|
||||
}
|
||||
}
|
||||
"minecraft:beehive" => {
|
||||
let bees = match tag.get("bees") {
|
||||
Some(Tag::List(list)) => list
|
||||
.iter()
|
||||
.filter_map(|bee| {
|
||||
let data = bee
|
||||
.get("entity_data")
|
||||
.filter(|d| matches!(d, Tag::Compound(_)))?;
|
||||
Some(Tag::compound([
|
||||
("entity_data", data.clone()),
|
||||
("ticks_in_hive", Tag::Int(int(bee.get("ticks_in_hive"))?)),
|
||||
(
|
||||
"min_ticks_in_hive",
|
||||
Tag::Int(int(bee.get("min_ticks_in_hive"))?),
|
||||
),
|
||||
]))
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
f.put("bees", Tag::List(bees));
|
||||
f.keep("flower_pos", is_pos);
|
||||
}
|
||||
"minecraft:sculk_sensor" | "minecraft:calibrated_sculk_sensor" => {
|
||||
f.int("last_vibration_frequency", 0);
|
||||
f.compound_or("listener", listener());
|
||||
}
|
||||
"minecraft:sculk_shrieker" => {
|
||||
f.int("warning_level", 0);
|
||||
f.compound_or("listener", listener());
|
||||
}
|
||||
"minecraft:sculk_catalyst" => {
|
||||
let cursors = match tag.get("cursors") {
|
||||
Some(t @ Tag::List(_)) => t.clone(),
|
||||
_ => Tag::List(Vec::new()),
|
||||
};
|
||||
f.put("cursors", cursors);
|
||||
}
|
||||
"minecraft:chiseled_bookshelf" => {
|
||||
f.items(6, true);
|
||||
f.int("last_interacted_slot", -1);
|
||||
}
|
||||
"minecraft:shelf" => {
|
||||
f.items(3, true);
|
||||
f.flag("align_items_to_bottom", false);
|
||||
}
|
||||
"minecraft:brushable_block" => {
|
||||
if !f.loot_table() {
|
||||
f.item("item");
|
||||
}
|
||||
}
|
||||
"minecraft:decorated_pot" => {
|
||||
if let Some(Tag::Compound(sherds)) = tag.get("sherds") {
|
||||
let kept: Compound = ["back", "left", "right", "front"]
|
||||
.iter()
|
||||
.filter_map(|side| {
|
||||
Some(((*side).into(), template(sherds.get(&(*side).into())?)?))
|
||||
})
|
||||
.collect();
|
||||
if !kept.is_empty() {
|
||||
f.put("sherds", Tag::Compound(kept));
|
||||
}
|
||||
}
|
||||
if !f.loot_table() {
|
||||
f.item("item");
|
||||
}
|
||||
}
|
||||
"minecraft:trial_spawner" => {
|
||||
// `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional
|
||||
// and defaulted by vanilla; they are kept as loaded. No `spawn_data` is
|
||||
// added: an absent one loads as Optional.empty and is not stored, and
|
||||
// an empty entity would keep the spawner from ever picking a mob.
|
||||
if let Tag::Compound(c) = tag {
|
||||
for (k, v) in c {
|
||||
let key = k.to_string_lossy();
|
||||
if !matches!(
|
||||
key.as_str(),
|
||||
"id" | "x" | "y" | "z" | "keepPacked" | "components"
|
||||
) {
|
||||
f.out.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"minecraft:vault" => {
|
||||
// `VaultConfig.DEFAULT` (when the config is absent): the trial key and the
|
||||
// default reward table, which is not saved.
|
||||
f.compound_or(
|
||||
"config",
|
||||
[(
|
||||
"key_item".into(),
|
||||
Tag::compound([
|
||||
("count", Tag::Int(1)),
|
||||
("id", string("minecraft:trial_key")),
|
||||
]),
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
f.compound_or("shared_data", Compound::new());
|
||||
f.compound_or("server_data", Compound::new());
|
||||
}
|
||||
"minecraft:test_block" => {
|
||||
f.string("mode", "fail");
|
||||
f.string("message", "");
|
||||
f.flag("powered", false);
|
||||
}
|
||||
"minecraft:test_instance_block" => {
|
||||
f.compound_or(
|
||||
"data",
|
||||
[
|
||||
("ignore_entities".into(), boolean(false)),
|
||||
("rotation".into(), string("none")),
|
||||
("size".into(), Tag::IntArray(vec![0, 0, 0])),
|
||||
("status".into(), string("cleared")),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
if let Some(errors @ Tag::List(list)) = tag.get("errors")
|
||||
&& !list.is_empty()
|
||||
{
|
||||
f.put("errors", errors.clone());
|
||||
}
|
||||
}
|
||||
"minecraft:potent_sulfur" => f.int("countdown", -1),
|
||||
_ => return None,
|
||||
}
|
||||
let mut out = f.out;
|
||||
out.insert("id".into(), string(&id));
|
||||
out.insert("x".into(), Tag::Int(x));
|
||||
out.insert("y".into(), Tag::Int(y));
|
||||
out.insert("z".into(), Tag::Int(z));
|
||||
out.insert("keepPacked".into(), Tag::Byte(0));
|
||||
out.insert(
|
||||
"components".into(),
|
||||
match tag.get("components") {
|
||||
Some(c @ Tag::Compound(_)) => c.clone(),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
},
|
||||
);
|
||||
Some(Tag::Compound(out))
|
||||
}
|
||||
|
||||
/// `VibrationSystem.Data` for a sensor with no pending vibration.
|
||||
fn listener() -> Compound {
|
||||
[
|
||||
("event_delay".into(), Tag::Int(0)),
|
||||
("selector".into(), Tag::compound([("tick", Tag::Long(-1))])),
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
/// Whether a stack plays a song (`JukeboxSong.fromStack`): a music disc or an item
|
||||
/// with the `jukebox_playable` component.
|
||||
fn is_record(item: &Compound) -> bool {
|
||||
let id = match item.get(&"id".into()) {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => return false,
|
||||
};
|
||||
id.starts_with("minecraft:music_disc_")
|
||||
|| matches!(item.get(&"components".into()), Some(Tag::Compound(c)) if c.contains_key(&"minecraft:jukebox_playable".into()))
|
||||
}
|
||||
|
||||
/// Three-way merge of a block entity: `original` is the NBT it was loaded from,
|
||||
/// `loaded` what Horizon encodes right after decoding it, and `current` what Horizon
|
||||
/// encodes now. Whatever the game left unchanged since loading keeps its original
|
||||
/// form (including the detail Horizon does not model, such as styled text), what it
|
||||
/// changed takes the current value, and keys Horizon never models stay.
|
||||
pub fn overlay(original: &Tag, loaded: &Tag, current: &Tag) -> Tag {
|
||||
if current == loaded {
|
||||
return original.clone();
|
||||
}
|
||||
match (original, loaded, current) {
|
||||
(Tag::Compound(o), Tag::Compound(l), Tag::Compound(c)) => {
|
||||
let mut out = Compound::new();
|
||||
for (key, cv) in c {
|
||||
let value = match (o.get(key), l.get(key)) {
|
||||
(Some(ov), Some(lv)) => overlay(ov, lv, cv),
|
||||
_ => cv.clone(),
|
||||
};
|
||||
out.insert(key.clone(), value);
|
||||
}
|
||||
// Keys the game never models (or models only when present) survive;
|
||||
// keys it removed are gone.
|
||||
for (key, ov) in o {
|
||||
if !c.contains_key(key) && !l.contains_key(key) {
|
||||
out.insert(key.clone(), ov.clone());
|
||||
}
|
||||
}
|
||||
Tag::Compound(out)
|
||||
}
|
||||
(Tag::List(o), Tag::List(l), Tag::List(c)) if keyed_by_slot(c) && keyed_by_slot(l) => {
|
||||
let slot = |t: &Tag| int(t.get("Slot"));
|
||||
Tag::List(
|
||||
c.iter()
|
||||
.map(|cv| {
|
||||
let s = slot(cv);
|
||||
fn find(list: &[Tag], slot: Option<i32>) -> Option<&Tag> {
|
||||
list.iter().find(|t| int(t.get("Slot")) == slot)
|
||||
}
|
||||
match (find(o, s), find(l, s)) {
|
||||
(Some(ov), Some(lv)) => overlay(ov, lv, cv),
|
||||
_ => cv.clone(),
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
_ => current.clone(),
|
||||
}
|
||||
}
|
||||
fn keyed_by_slot(list: &[Tag]) -> bool {
|
||||
list.iter().all(|t| t.get("Slot").is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
fn snbt(s: &str) -> Tag {
|
||||
parse_snbt(s).expect("snbt").0
|
||||
}
|
||||
fn canon(s: &str) -> Tag {
|
||||
canonical(&snbt(s)).expect("known type")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trial_spawner_without_spawn_data_saves_none() {
|
||||
let fresh = canon(
|
||||
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#,
|
||||
);
|
||||
assert_eq!(fresh.get("spawn_data"), None);
|
||||
let picked = canon(
|
||||
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#,
|
||||
);
|
||||
assert_eq!(
|
||||
picked.get("spawn_data"),
|
||||
Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_type_has_defaults() {
|
||||
for id in TYPES.iter().chain(NEWEST.iter()) {
|
||||
let tag = snbt(&format!("{{id:\"{id}\",x:1,y:2,z:3}}"));
|
||||
let out = canonical(&tag).unwrap_or_else(|| panic!("{id}"));
|
||||
assert_eq!(out.get("id"), tag.get("id"));
|
||||
assert_eq!(out.get("keepPacked"), Some(&Tag::Byte(0)), "{id}");
|
||||
assert_eq!(
|
||||
out.get("components"),
|
||||
Some(&Tag::Compound(Compound::new())),
|
||||
"{id}"
|
||||
);
|
||||
}
|
||||
assert!(canonical(&snbt("{id:\"minecraft:nope\",x:1,y:2,z:3}")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn furnace_defaults_match_vanilla() {
|
||||
let out = canon("{id:\"minecraft:furnace\",x:1,y:2,z:3}");
|
||||
assert_eq!(out.get("cooking_total_time"), Some(&Tag::Int(0)));
|
||||
assert_eq!(out.get("speed_multiplier"), Some(&f32_tag(1.0)));
|
||||
assert_eq!(out.get("Items"), Some(&Tag::List(vec![])));
|
||||
assert_eq!(
|
||||
out.get("RecipesUsed"),
|
||||
Some(&Tag::Compound(Compound::new()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loot_table_replaces_items_and_zero_seed_is_omitted() {
|
||||
let out = canon(
|
||||
"{id:\"minecraft:chest\",x:1,y:2,z:3,LootTable:\"minecraft:chests/x\",LootTableSeed:0L,\
|
||||
Items:[{Slot:0b,id:\"minecraft:stone\",count:1}]}",
|
||||
);
|
||||
assert!(out.get("Items").is_none());
|
||||
assert!(out.get("LootTableSeed").is_none());
|
||||
assert_eq!(out.get("LootTable"), Some(&string("minecraft:chests/x")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_are_validated_and_sorted_by_slot() {
|
||||
let out = canon(
|
||||
"{id:\"minecraft:hopper\",x:1,y:2,z:3,Items:[\
|
||||
{Slot:4b,id:\"minecraft:stone\",count:2},{Slot:5b,id:\"minecraft:stone\",count:1},\
|
||||
{Slot:0b,id:\"minecraft:air\",count:1},{Slot:1b,id:\"minecraft:dirt\"},\
|
||||
{Slot:2b,id:\"minecraft:dirt\",count:100}]}",
|
||||
);
|
||||
let Some(Tag::List(items)) = out.get("Items") else {
|
||||
panic!("items")
|
||||
};
|
||||
let slots: Vec<_> = items.iter().map(|i| i.get("Slot").cloned()).collect();
|
||||
assert_eq!(slots, vec![Some(Tag::Byte(1)), Some(Tag::Byte(4))]);
|
||||
assert_eq!(items[0].get("count"), Some(&Tag::Int(1)));
|
||||
assert_eq!(out.get("TransferCooldown"), Some(&Tag::Int(-1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_components_become_strings() {
|
||||
let out =
|
||||
canon("{id:\"minecraft:banner\",x:1,y:2,z:3,CustomName:{text:\"Flag\"},patterns:[]}");
|
||||
assert_eq!(out.get("CustomName"), Some(&string("Flag")));
|
||||
assert!(out.get("patterns").is_none());
|
||||
let styled =
|
||||
canon("{id:\"minecraft:banner\",x:1,y:2,z:3,CustomName:{text:\"F\",color:\"red\"}}");
|
||||
assert!(matches!(styled.get("CustomName"), Some(Tag::Compound(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shulker_box_omits_empty_items_and_structure_block_clamps() {
|
||||
let shulker = canon("{id:\"minecraft:shulker_box\",x:1,y:2,z:3}");
|
||||
assert!(shulker.get("Items").is_none());
|
||||
let structure = canon("{id:\"minecraft:structure_block\",x:1,y:2,z:3,posX:99,sizeY:-4}");
|
||||
assert_eq!(structure.get("posX"), Some(&Tag::Int(48)));
|
||||
assert_eq!(structure.get("sizeY"), Some(&Tag::Int(0)));
|
||||
assert_eq!(structure.get("posY"), Some(&Tag::Int(1)));
|
||||
assert_eq!(structure.get("showboundingbox"), Some(&Tag::Byte(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_is_idempotent() {
|
||||
for id in TYPES.iter().chain(NEWEST.iter()) {
|
||||
let once = canonical(&snbt(&format!("{{id:\"{id}\",x:1,y:2,z:3}}"))).expect("known");
|
||||
assert_eq!(canonical(&once).as_ref(), Some(&once), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_keeps_unchanged_detail_and_takes_changes() {
|
||||
let original = snbt(
|
||||
"{id:\"minecraft:sign\",front_text:{messages:[{text:\"a\",color:\"red\"},\"\",\"\",\"\"]},\
|
||||
back_text:{messages:[\"x\",\"\",\"\",\"\"]},extra:1b}",
|
||||
);
|
||||
let loaded = snbt(
|
||||
"{id:\"minecraft:sign\",front_text:{messages:[\"a\",\"\",\"\",\"\"]},\
|
||||
back_text:{messages:[\"x\",\"\",\"\",\"\"]}}",
|
||||
);
|
||||
let current = snbt(
|
||||
"{id:\"minecraft:sign\",front_text:{messages:[\"a\",\"\",\"\",\"\"]},\
|
||||
back_text:{messages:[\"y\",\"\",\"\",\"\"]}}",
|
||||
);
|
||||
let merged = overlay(&original, &loaded, ¤t);
|
||||
assert_eq!(merged.get("front_text"), original.get("front_text"));
|
||||
assert_eq!(merged.get("back_text"), current.get("back_text"));
|
||||
assert_eq!(merged.get("extra"), original.get("extra"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_merges_container_slots() {
|
||||
let item = |slot: i8, count: i32, extra: &str| {
|
||||
snbt(&format!(
|
||||
"{{Slot:{slot}b,id:\"minecraft:stone\",count:{count}{extra}}}"
|
||||
))
|
||||
};
|
||||
let original = Tag::compound([(
|
||||
"Items",
|
||||
Tag::List(vec![
|
||||
item(0, 1, ",components:{\"minecraft:lore\":[\"x\"]}"),
|
||||
item(1, 1, ""),
|
||||
]),
|
||||
)]);
|
||||
let loaded = Tag::compound([("Items", Tag::List(vec![item(0, 1, ""), item(1, 1, "")]))]);
|
||||
let current = Tag::compound([("Items", Tag::List(vec![item(0, 1, ""), item(1, 5, "")]))]);
|
||||
let merged = overlay(&original, &loaded, ¤t);
|
||||
let Some(Tag::List(items)) = merged.get("Items") else {
|
||||
panic!("items")
|
||||
};
|
||||
assert!(
|
||||
items[0].get("components").is_some(),
|
||||
"slot 0 keeps its lore"
|
||||
);
|
||||
assert_eq!(items[1].get("count"), Some(&Tag::Int(5)));
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,8 @@ pub fn draw_part(
|
||||
layer: 0,
|
||||
color,
|
||||
light,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -610,7 +612,9 @@ fn sign_text_calls(
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, line)| {
|
||||
// The line that fits, in the order it is drawn (getVisualOrder).
|
||||
let shown = first_line(line, data.max_line_width(), &advance);
|
||||
let shown = crate::bidi::visual_str(&shown).into_owned();
|
||||
TextCall {
|
||||
matrix: m,
|
||||
x: -((width(&shown) as i32) / 2) as f32,
|
||||
@@ -648,6 +652,8 @@ fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec<Vertex>) {
|
||||
layer: 0,
|
||||
color: c,
|
||||
light: call.light,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -734,7 +740,7 @@ pub struct Scene<'a> {
|
||||
/// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer`
|
||||
/// profile → skin): a downloaded `skins/<sha1>` slot or the profile's
|
||||
/// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve).
|
||||
pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>,
|
||||
pub skull: &'a dyn Fn([i32; 3]) -> Option<String>,
|
||||
/// Font glyph cell (none for blank glyphs such as the space) and advance.
|
||||
pub glyph: &'a dyn Fn(char) -> (Option<Rect>, f32),
|
||||
}
|
||||
@@ -1286,11 +1292,12 @@ impl BlockEntityRenderer {
|
||||
};
|
||||
// SkullBlockRenderer.getRenderType: the profile's skin when it
|
||||
// resolves, `SKIN_BY_TYPE` (steve) otherwise.
|
||||
let texture = if *kind == SkullType::Player {
|
||||
(scene.skull)(pos).unwrap_or(texture)
|
||||
let skin = if *kind == SkullType::Player {
|
||||
(scene.skull)(pos)
|
||||
} else {
|
||||
texture
|
||||
None
|
||||
};
|
||||
let texture = skin.as_deref().unwrap_or(texture);
|
||||
let (Some(model), Some(paint)) =
|
||||
(self.models.get(model), paint(texture, 0xFFFFFF, packed))
|
||||
else {
|
||||
@@ -1714,6 +1721,8 @@ impl BeamPart {
|
||||
layer: 6,
|
||||
color,
|
||||
light: self.wrap,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1784,6 +1793,7 @@ fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec<Vertex>)
|
||||
layer,
|
||||
color: 0,
|
||||
light: 0,
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ pub const MAP_COLORS: [u32; 62] = [
|
||||
14200723, 8365974,
|
||||
];
|
||||
/// The 12 edges of the unit cube (outline data predating the export).
|
||||
fn cube_edges() -> Vec<[f64; 6]> {
|
||||
pub fn cube_edges() -> Vec<[f64; 6]> {
|
||||
let mut edges = Vec::new();
|
||||
for a in 0..3 {
|
||||
for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] {
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
//! Custom boss bars (`CustomBossEvents`): the `/bossbar` store, its saved
|
||||
//! form (`data/minecraft/custom_boss_events.dat`) and how a bar is shown.
|
||||
use crate::{
|
||||
scoreboard::{Comp, bracketed, comp_text, json_to_tag, literal, tag_to_json},
|
||||
text::{self, Style, Text},
|
||||
};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
pub const COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"];
|
||||
pub const STYLES: [&str; 5] = [
|
||||
"progress",
|
||||
"notched_6",
|
||||
"notched_10",
|
||||
"notched_12",
|
||||
"notched_20",
|
||||
];
|
||||
/// `BossBarColor.getFormatting`. Purple is dark blue in 26.3.
|
||||
pub fn color_rgb(color: &str) -> u32 {
|
||||
let name = match color {
|
||||
"pink" => "red",
|
||||
"red" => "dark_red",
|
||||
"purple" => "dark_blue",
|
||||
other => other,
|
||||
};
|
||||
text::named_color(name).unwrap_or(text::WHITE)
|
||||
}
|
||||
|
||||
/// A version-4 shaped id from a resource id. Saved boss events do not keep
|
||||
/// their UUID (`CustomBossEvents` mints a new one on load).
|
||||
pub fn stable_uuid(id: &str) -> u128 {
|
||||
let mut h = 0xcbf29ce484222325u64;
|
||||
for b in id.as_bytes() {
|
||||
h ^= u64::from(*b);
|
||||
h = h.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
let most = (h as i64) & -61441 | 16384;
|
||||
let least = (h.rotate_left(17) as i64) & 4_611_686_018_427_387_903 | i64::MIN;
|
||||
((most as u64 as u128) << 64) | (least as u64 as u128)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BossBar {
|
||||
pub id: String,
|
||||
/// The `ServerBossEvent` UUID. Not saved.
|
||||
pub uuid: u128,
|
||||
pub name: Comp,
|
||||
pub color: String,
|
||||
pub style: String,
|
||||
pub value: i32,
|
||||
pub max: i32,
|
||||
/// `ServerBossEvent.visible`. A new bar is visible; nobody sees it until
|
||||
/// a player is added.
|
||||
pub visible: bool,
|
||||
pub darken: bool,
|
||||
pub music: bool,
|
||||
pub fog: bool,
|
||||
/// `CustomBossEvent.players`, the UUIDs told about the bar.
|
||||
pub players: Vec<[i32; 4]>,
|
||||
}
|
||||
impl BossBar {
|
||||
pub fn new(id: &str, name: Comp) -> Self {
|
||||
Self {
|
||||
id: id.to_owned(),
|
||||
uuid: stable_uuid(id),
|
||||
name,
|
||||
color: "white".into(),
|
||||
style: "progress".into(),
|
||||
value: 0,
|
||||
max: 100,
|
||||
visible: true,
|
||||
darken: false,
|
||||
music: false,
|
||||
fog: false,
|
||||
players: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// `CustomBossEvent.getDisplayName`.
|
||||
pub fn display_name(&self) -> Text {
|
||||
let style = Style {
|
||||
color: Some(color_rgb(&self.color)),
|
||||
hover: Some(Box::new(Text::literal(self.id.clone()))),
|
||||
..Style::default()
|
||||
};
|
||||
// ComponentUtils.wrapInSquareBrackets(name).withStyle(...): the
|
||||
// brackets take the colour too.
|
||||
bracketed(comp_text(&self.name)).with_style(&style)
|
||||
}
|
||||
/// The filled fraction of the bar (`BossEvent.getProgress`).
|
||||
pub fn progress(&self) -> f32 {
|
||||
(self.value as f32 / self.max.max(1) as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BossBars {
|
||||
pub bars: Vec<BossBar>,
|
||||
}
|
||||
impl BossBars {
|
||||
pub fn get(&self, id: &str) -> Option<&BossBar> {
|
||||
self.bars.iter().find(|b| b.id == id)
|
||||
}
|
||||
pub fn get_mut(&mut self, id: &str) -> Option<&mut BossBar> {
|
||||
self.bars.iter_mut().find(|b| b.id == id)
|
||||
}
|
||||
pub fn add(&mut self, id: &str, name: Comp) -> bool {
|
||||
if self.get(id).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.bars.push(BossBar::new(id, name));
|
||||
true
|
||||
}
|
||||
pub fn remove(&mut self, id: &str) {
|
||||
self.bars.retain(|b| b.id != id);
|
||||
}
|
||||
pub fn ids(&self) -> Vec<String> {
|
||||
self.bars.iter().map(|b| b.id.clone()).collect()
|
||||
}
|
||||
/// The saved compound (`CustomBossEvent.Packed`).
|
||||
pub fn pack(&self) -> Tag {
|
||||
let mut c = Compound::new();
|
||||
for b in &self.bars {
|
||||
let players = b
|
||||
.players
|
||||
.iter()
|
||||
.map(|u| Tag::IntArray(u.to_vec()))
|
||||
.collect();
|
||||
c.insert(
|
||||
b.id.as_str().into(),
|
||||
Tag::compound([
|
||||
("Name", json_to_tag(&b.name)),
|
||||
("Visible", Tag::Byte(i8::from(b.visible))),
|
||||
("Value", Tag::Int(b.value)),
|
||||
("Max", Tag::Int(b.max)),
|
||||
("Color", Tag::String(b.color.as_str().into())),
|
||||
("Overlay", Tag::String(b.style.as_str().into())),
|
||||
("DarkenScreen", Tag::Byte(i8::from(b.darken))),
|
||||
("PlayBossMusic", Tag::Byte(i8::from(b.music))),
|
||||
("CreateWorldFog", Tag::Byte(i8::from(b.fog))),
|
||||
("Players", Tag::List(players)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
Tag::Compound(c)
|
||||
}
|
||||
pub fn unpack(data: &Tag) -> Self {
|
||||
let mut bars = Vec::new();
|
||||
if let Tag::Compound(c) = data {
|
||||
for (id, e) in c {
|
||||
let get = |k: &str| e.get(k);
|
||||
let text = |k: &str, d: &str| match get(k) {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => d.to_owned(),
|
||||
};
|
||||
let num = |k: &str, d: i32| match get(k) {
|
||||
Some(Tag::Int(v)) => *v,
|
||||
Some(Tag::Short(v)) => i32::from(*v),
|
||||
Some(Tag::Byte(v)) => i32::from(*v),
|
||||
_ => d,
|
||||
};
|
||||
let players = match get("Players") {
|
||||
Some(Tag::List(l)) => l
|
||||
.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::IntArray(a) if a.len() == 4 => Some([a[0], a[1], a[2], a[3]]),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let id = id.to_string_lossy();
|
||||
bars.push(BossBar {
|
||||
uuid: stable_uuid(&id),
|
||||
id,
|
||||
name: get("Name").map_or_else(|| literal(""), tag_to_json),
|
||||
color: text("Color", "white"),
|
||||
style: text("Overlay", "progress"),
|
||||
value: num("Value", 0),
|
||||
max: num("Max", 100),
|
||||
visible: num("Visible", 0) != 0,
|
||||
darken: num("DarkenScreen", 0) != 0,
|
||||
music: num("PlayBossMusic", 0) != 0,
|
||||
fog: num("CreateWorldFog", 0) != 0,
|
||||
players,
|
||||
});
|
||||
}
|
||||
}
|
||||
Self { bars }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bars_round_trip_and_show() {
|
||||
let mut b = BossBars::default();
|
||||
assert!(b.add("test:x", literal("Hello")));
|
||||
assert!(!b.add("test:x", literal("Again")));
|
||||
let bar = b.get_mut("test:x").unwrap();
|
||||
bar.color = "pink".into();
|
||||
bar.style = "notched_10".into();
|
||||
bar.value = 25;
|
||||
bar.max = 50;
|
||||
bar.visible = true;
|
||||
bar.darken = true;
|
||||
bar.players = vec![[1, 2, 3, 4]];
|
||||
let back = BossBars::unpack(&b.pack());
|
||||
assert_eq!(back, b);
|
||||
let bar = b.get("test:x").unwrap();
|
||||
assert_eq!(bar.progress(), 0.5);
|
||||
assert_eq!(bar.display_name().plain(), "chat.square_brackets");
|
||||
assert_eq!(color_rgb("pink"), text::RED);
|
||||
assert_eq!(color_rgb("purple"), text::named_color("dark_blue").unwrap());
|
||||
b.remove("test:x");
|
||||
assert!(b.bars.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,8 @@ pub fn geometry(
|
||||
color: 0xffff_ffff,
|
||||
light: stage_light(stage),
|
||||
normal: [0; 4],
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,232 +9,10 @@ use crate::{
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashSet, fs, path::Path, sync::Arc};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Category {
|
||||
Beneficial,
|
||||
Harmful,
|
||||
Neutral,
|
||||
}
|
||||
/// A `MobEffect`: id (without namespace), colour, category, instantaneous.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct EffectDef {
|
||||
pub id: &'static str,
|
||||
pub color: u32,
|
||||
pub category: Category,
|
||||
pub instant: bool,
|
||||
}
|
||||
const fn fx(id: &'static str, color: u32, category: Category) -> EffectDef {
|
||||
EffectDef {
|
||||
id,
|
||||
color,
|
||||
category,
|
||||
instant: false,
|
||||
}
|
||||
}
|
||||
use Category::{Beneficial as B, Harmful as H, Neutral as N};
|
||||
/// `MobEffects` in registration order.
|
||||
pub const EFFECTS: &[EffectDef] = &[
|
||||
fx("speed", 3402751, B),
|
||||
fx("slowness", 9154528, H),
|
||||
fx("haste", 14270531, B),
|
||||
fx("mining_fatigue", 4866583, H),
|
||||
fx("strength", 16762624, B),
|
||||
EffectDef {
|
||||
id: "instant_health",
|
||||
color: 16262179,
|
||||
category: B,
|
||||
instant: true,
|
||||
},
|
||||
EffectDef {
|
||||
id: "instant_damage",
|
||||
color: 11101546,
|
||||
category: H,
|
||||
instant: true,
|
||||
},
|
||||
fx("jump_boost", 16646020, B),
|
||||
fx("nausea", 5578058, H),
|
||||
fx("regeneration", 13458603, B),
|
||||
fx("resistance", 9520880, B),
|
||||
fx("fire_resistance", 16750848, B),
|
||||
fx("water_breathing", 10017472, B),
|
||||
fx("invisibility", 16185078, B),
|
||||
fx("blindness", 2039587, H),
|
||||
fx("night_vision", 12779366, B),
|
||||
fx("hunger", 5797459, H),
|
||||
fx("weakness", 4738376, H),
|
||||
fx("poison", 8889187, H),
|
||||
fx("wither", 7561558, H),
|
||||
fx("health_boost", 16284963, B),
|
||||
fx("absorption", 2445989, B),
|
||||
EffectDef {
|
||||
id: "saturation",
|
||||
color: 16262179,
|
||||
category: B,
|
||||
instant: true,
|
||||
},
|
||||
fx("glowing", 9740385, N),
|
||||
fx("levitation", 13565951, H),
|
||||
fx("luck", 5882118, B),
|
||||
fx("unluck", 12624973, H),
|
||||
fx("slow_falling", 15978425, B),
|
||||
fx("conduit_power", 1950417, B),
|
||||
fx("dolphins_grace", 8954814, B),
|
||||
fx("bad_omen", 745784, N),
|
||||
fx("hero_of_the_village", 4521796, B),
|
||||
fx("darkness", 2696993, H),
|
||||
fx("trial_omen", 1484454, N),
|
||||
fx("raid_omen", 14565464, N),
|
||||
fx("wind_charged", 12438015, H),
|
||||
fx("weaving", 7891290, H),
|
||||
fx("oozing", 10092451, H),
|
||||
fx("infested", 9214860, H),
|
||||
fx("breath_of_the_nautilus", 65518, B),
|
||||
];
|
||||
pub fn effect(id: &str) -> Option<&'static EffectDef> {
|
||||
let id = id.trim_start_matches("minecraft:");
|
||||
EFFECTS.iter().find(|e| e.id == id)
|
||||
}
|
||||
/// A `Potion`: id, name suffix (`item.minecraft.potion.effect.<name>`) and
|
||||
/// effects as (effect, duration ticks, amplifier).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PotionDef {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
pub effects: &'static [(&'static str, i32, i32)],
|
||||
}
|
||||
const fn p(
|
||||
id: &'static str,
|
||||
name: &'static str,
|
||||
effects: &'static [(&'static str, i32, i32)],
|
||||
) -> PotionDef {
|
||||
PotionDef { id, name, effects }
|
||||
}
|
||||
/// `Potions` in registration order.
|
||||
pub const POTIONS: &[PotionDef] = &[
|
||||
p("water", "water", &[]),
|
||||
p("mundane", "mundane", &[]),
|
||||
p("thick", "thick", &[]),
|
||||
p("awkward", "awkward", &[]),
|
||||
p("night_vision", "night_vision", &[("night_vision", 3600, 0)]),
|
||||
p(
|
||||
"long_night_vision",
|
||||
"night_vision",
|
||||
&[("night_vision", 9600, 0)],
|
||||
),
|
||||
p("invisibility", "invisibility", &[("invisibility", 3600, 0)]),
|
||||
p(
|
||||
"long_invisibility",
|
||||
"invisibility",
|
||||
&[("invisibility", 9600, 0)],
|
||||
),
|
||||
p("leaping", "leaping", &[("jump_boost", 3600, 0)]),
|
||||
p("long_leaping", "leaping", &[("jump_boost", 9600, 0)]),
|
||||
p("strong_leaping", "leaping", &[("jump_boost", 1800, 1)]),
|
||||
p(
|
||||
"fire_resistance",
|
||||
"fire_resistance",
|
||||
&[("fire_resistance", 3600, 0)],
|
||||
),
|
||||
p(
|
||||
"long_fire_resistance",
|
||||
"fire_resistance",
|
||||
&[("fire_resistance", 9600, 0)],
|
||||
),
|
||||
p("swiftness", "swiftness", &[("speed", 3600, 0)]),
|
||||
p("long_swiftness", "swiftness", &[("speed", 9600, 0)]),
|
||||
p("strong_swiftness", "swiftness", &[("speed", 1800, 1)]),
|
||||
p("slowness", "slowness", &[("slowness", 1800, 0)]),
|
||||
p("long_slowness", "slowness", &[("slowness", 4800, 0)]),
|
||||
p("strong_slowness", "slowness", &[("slowness", 400, 3)]),
|
||||
p(
|
||||
"turtle_master",
|
||||
"turtle_master",
|
||||
&[("slowness", 400, 3), ("resistance", 400, 2)],
|
||||
),
|
||||
p(
|
||||
"long_turtle_master",
|
||||
"turtle_master",
|
||||
&[("slowness", 800, 3), ("resistance", 800, 2)],
|
||||
),
|
||||
p(
|
||||
"strong_turtle_master",
|
||||
"turtle_master",
|
||||
&[("slowness", 400, 5), ("resistance", 400, 3)],
|
||||
),
|
||||
p(
|
||||
"water_breathing",
|
||||
"water_breathing",
|
||||
&[("water_breathing", 3600, 0)],
|
||||
),
|
||||
p(
|
||||
"long_water_breathing",
|
||||
"water_breathing",
|
||||
&[("water_breathing", 9600, 0)],
|
||||
),
|
||||
p("healing", "healing", &[("instant_health", 1, 0)]),
|
||||
p("strong_healing", "healing", &[("instant_health", 1, 1)]),
|
||||
p("harming", "harming", &[("instant_damage", 1, 0)]),
|
||||
p("strong_harming", "harming", &[("instant_damage", 1, 1)]),
|
||||
p("poison", "poison", &[("poison", 900, 0)]),
|
||||
p("long_poison", "poison", &[("poison", 1800, 0)]),
|
||||
p("strong_poison", "poison", &[("poison", 432, 1)]),
|
||||
p("regeneration", "regeneration", &[("regeneration", 900, 0)]),
|
||||
p(
|
||||
"long_regeneration",
|
||||
"regeneration",
|
||||
&[("regeneration", 1800, 0)],
|
||||
),
|
||||
p(
|
||||
"strong_regeneration",
|
||||
"regeneration",
|
||||
&[("regeneration", 450, 1)],
|
||||
),
|
||||
p("strength", "strength", &[("strength", 3600, 0)]),
|
||||
p("long_strength", "strength", &[("strength", 9600, 0)]),
|
||||
p("strong_strength", "strength", &[("strength", 1800, 1)]),
|
||||
p("weakness", "weakness", &[("weakness", 1800, 0)]),
|
||||
p("long_weakness", "weakness", &[("weakness", 4800, 0)]),
|
||||
p("luck", "luck", &[("luck", 6000, 0)]),
|
||||
p("slow_falling", "slow_falling", &[("slow_falling", 1800, 0)]),
|
||||
p(
|
||||
"long_slow_falling",
|
||||
"slow_falling",
|
||||
&[("slow_falling", 4800, 0)],
|
||||
),
|
||||
p("wind_charged", "wind_charged", &[("wind_charged", 3600, 0)]),
|
||||
p("weaving", "weaving", &[("weaving", 3600, 0)]),
|
||||
p("oozing", "oozing", &[("oozing", 3600, 0)]),
|
||||
p("infested", "infested", &[("infested", 3600, 0)]),
|
||||
];
|
||||
pub fn potion(id: &str) -> Option<&'static PotionDef> {
|
||||
let id = id.trim_start_matches("minecraft:");
|
||||
POTIONS.iter().find(|p| p.id == id)
|
||||
}
|
||||
/// `PotionContents.BASE_POTION_COLOR` (ARGB -13083194) as RGB.
|
||||
pub const BASE_POTION_COLOR: u32 = 0x385DC6;
|
||||
/// `PotionContents.getColor`: amplifier-weighted mix of visible effect colours.
|
||||
pub fn potion_color(id: Option<&str>) -> u32 {
|
||||
let Some(def) = id.and_then(potion) else {
|
||||
return BASE_POTION_COLOR;
|
||||
};
|
||||
let (mut r, mut g, mut b, mut total) = (0u32, 0u32, 0u32, 0u32);
|
||||
for (e, _, amp) in def.effects {
|
||||
let Some(e) = effect(e) else { continue };
|
||||
let w = *amp as u32 + 1;
|
||||
r += w * (e.color >> 16 & 255);
|
||||
g += w * (e.color >> 8 & 255);
|
||||
b += w * (e.color & 255);
|
||||
total += w;
|
||||
}
|
||||
match (
|
||||
r.checked_div(total),
|
||||
g.checked_div(total),
|
||||
b.checked_div(total),
|
||||
) {
|
||||
(Some(r), Some(g), Some(b)) => (r << 16) | (g << 8) | b,
|
||||
_ => BASE_POTION_COLOR,
|
||||
}
|
||||
}
|
||||
pub use horizon_client_core::potions::{
|
||||
BASE_POTION_COLOR, Category, EFFECTS, EffectDef, POTIONS, PotionDef, effect, namespaced,
|
||||
potion, potion_color,
|
||||
};
|
||||
/// `MobEffectUtil.formatDuration` at 20 TPS: m:ss or h:mm:ss.
|
||||
pub fn format_duration(ticks: i32) -> String {
|
||||
let secs = ticks / 20;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `BundleContents.Mutable`: what a bundle takes in and gives back, by
|
||||
//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click
|
||||
//! overrides on it.
|
||||
use crate::item_data::BundleSelected;
|
||||
use crate::items::{ItemStack, Items};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
@@ -97,6 +98,8 @@ pub fn can_be_in_bundle(stack: &ItemStack) -> bool {
|
||||
pub struct Contents {
|
||||
items: Vec<ItemStack>,
|
||||
weight: Weight,
|
||||
/// `selectedItem`: an index into `items`, -1 for none.
|
||||
selected: i32,
|
||||
}
|
||||
|
||||
impl Contents {
|
||||
@@ -104,9 +107,11 @@ impl Contents {
|
||||
pub fn of(items: &Items, stack: &ItemStack) -> Option<Self> {
|
||||
let inside = contents_of(items, stack)?.to_vec();
|
||||
let weight = contents_weight(items, &inside);
|
||||
let selected = stack.data().map_or(-1, |d| d.bundle_selected.0);
|
||||
Some(Self {
|
||||
items: inside,
|
||||
weight,
|
||||
selected,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -154,18 +159,26 @@ impl Contents {
|
||||
amount
|
||||
}
|
||||
|
||||
/// `removeOne`: the first stack (Horizon keeps no selected item).
|
||||
/// `removeOne`: the selected stack, else the first; nothing is selected after.
|
||||
pub fn remove_one(&mut self, items: &Items) -> Option<ItemStack> {
|
||||
if self.items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let stack = self.items.remove(0);
|
||||
let at =
|
||||
usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 });
|
||||
let stack = self.items.remove(at);
|
||||
self.weight = self
|
||||
.weight
|
||||
.sub(item_weight(items, &stack).times(stack.count));
|
||||
self.selected = -1;
|
||||
Some(stack)
|
||||
}
|
||||
|
||||
/// `getSelectedItemIndex`.
|
||||
pub fn selected(&self) -> i32 {
|
||||
self.selected
|
||||
}
|
||||
|
||||
/// The stacks inside, in display order (the first is the next out).
|
||||
pub fn items(&self) -> &[ItemStack] {
|
||||
&self.items
|
||||
@@ -200,11 +213,28 @@ impl Contents {
|
||||
|
||||
/// `toImmutable`, written back into the bundle's component.
|
||||
pub fn store(self, bundle: &mut ItemStack) {
|
||||
bundle.data_mut().bundle_contents = self.items;
|
||||
let data = bundle.data_mut();
|
||||
data.bundle_contents = self.items;
|
||||
data.bundle_selected = BundleSelected(self.selected);
|
||||
bundle.tidy();
|
||||
}
|
||||
}
|
||||
|
||||
/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the
|
||||
/// selected one already or outside the contents.
|
||||
pub fn toggle_selected(bundle: &mut ItemStack, index: i32) {
|
||||
let Some(data) = bundle.extra.as_deref_mut() else {
|
||||
return;
|
||||
};
|
||||
let inside = (0..data.bundle_contents.len() as i32).contains(&index);
|
||||
let selected = if data.bundle_selected.0 != index && inside {
|
||||
index
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
data.bundle_selected = BundleSelected(selected);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Weight;
|
||||
@@ -232,8 +262,10 @@ pub struct TooltipLayout {
|
||||
/// The component's own width (96) and height, the text's excluded.
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Each slot's top-left and the stack in it, in reading order.
|
||||
/// Each slot's top-left and the stack in it, in drawing order.
|
||||
pub slots: Vec<([f32; 2], ItemStack)>,
|
||||
/// The position in `slots` of the selected item, which is drawn highlighted.
|
||||
pub selected: Option<usize>,
|
||||
/// The `+N` of the items past the grid: its top-left and the count.
|
||||
pub overflow: Option<([f32; 2], u32)>,
|
||||
/// The progress bar's top-left, its fill's width out of 94, and whether
|
||||
@@ -266,6 +298,7 @@ pub fn tooltip_layout(
|
||||
width: 96.0,
|
||||
height: description_height + 13.0 + 8.0,
|
||||
slots: Vec::new(),
|
||||
selected: None,
|
||||
overflow: None,
|
||||
bar: [x + offset, y + description_height + 4.0],
|
||||
fill: 0.0,
|
||||
@@ -282,6 +315,7 @@ pub fn tooltip_layout(
|
||||
let x_start = x + offset + 96.0;
|
||||
let y_start = y + grid_height;
|
||||
let mut slots = Vec::with_capacity(shown.len());
|
||||
let mut selected = None;
|
||||
let mut overflow = None;
|
||||
// Rows fill bottom-up and columns right-to-left, as vanilla draws them.
|
||||
let mut slot = 0;
|
||||
@@ -290,8 +324,13 @@ pub fn tooltip_layout(
|
||||
let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
|
||||
if hidden > 0 && row == 1 && column == 1 {
|
||||
overflow = Some((at, hidden));
|
||||
} else if let Some(stack) = shown.get(slot) {
|
||||
slots.push((at, stack.clone()));
|
||||
} else if slot < shown.len() {
|
||||
// `extractSlot`: the cell of slot number n holds item `size - n`.
|
||||
let index = shown.len() - 1 - slot;
|
||||
if usize::try_from(contents.selected()) == Ok(index) {
|
||||
selected = Some(slots.len());
|
||||
}
|
||||
slots.push((at, shown[index].clone()));
|
||||
slot += 1;
|
||||
}
|
||||
}
|
||||
@@ -301,6 +340,7 @@ pub fn tooltip_layout(
|
||||
width: 96.0,
|
||||
height: grid_height + 13.0 + 8.0,
|
||||
slots,
|
||||
selected,
|
||||
overflow,
|
||||
bar: [x + offset, y + grid_height + 4.0],
|
||||
// `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
|
||||
@@ -349,8 +389,8 @@ mod tooltip_tests {
|
||||
assert_eq!(layout.slots.len(), 12);
|
||||
assert_eq!(layout.overflow, None);
|
||||
assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
|
||||
// Rows fill bottom-up and columns right-to-left: the first item is in
|
||||
// the bottom-right cell, the twelfth in the top-left.
|
||||
// Rows fill bottom-up and columns right-to-left: the twelfth item is in
|
||||
// the bottom-right cell, the first in the top-left.
|
||||
assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
|
||||
assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
|
||||
assert_eq!(layout.slots[11].0, [0.0, 0.0]);
|
||||
|
||||
@@ -40,6 +40,8 @@ pub struct Interaction {
|
||||
/// The cauldron's new state.
|
||||
pub block: Option<BlockState>,
|
||||
pub sound: Option<&'static str>,
|
||||
/// The custom statistic the player earns (`use_cauldron`, ...).
|
||||
pub stat: Option<&'static str>,
|
||||
}
|
||||
|
||||
fn state(name: &str, level: Option<u8>) -> BlockState {
|
||||
@@ -57,6 +59,7 @@ fn pass() -> Interaction {
|
||||
outcome: Outcome::Pass,
|
||||
block: None,
|
||||
sound: None,
|
||||
stat: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,11 +120,12 @@ fn lowered(cauldron: &BlockState) -> BlockState {
|
||||
}
|
||||
}
|
||||
|
||||
fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction {
|
||||
fn changed(block: BlockState, sound: Option<&'static str>, stat: &'static str) -> Interaction {
|
||||
Interaction {
|
||||
outcome: Outcome::Success,
|
||||
block: Some(block),
|
||||
sound,
|
||||
stat: Some(stat),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,18 +183,22 @@ pub fn interact(
|
||||
stack.data_mut().dyed_color = None;
|
||||
stack.tidy();
|
||||
}
|
||||
return changed(lowered(cauldron), None);
|
||||
return changed(lowered(cauldron), None, "clean_armor");
|
||||
}
|
||||
let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| {
|
||||
if !can_fill {
|
||||
return pass();
|
||||
}
|
||||
filled(player, ItemStack::new(new, 1), true);
|
||||
changed(state("minecraft:cauldron", None), Some(sound))
|
||||
changed(
|
||||
state("minecraft:cauldron", None),
|
||||
Some(sound),
|
||||
"use_cauldron",
|
||||
)
|
||||
};
|
||||
let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| {
|
||||
filled(player, ItemStack::new("minecraft:bucket", 1), true);
|
||||
changed(block, Some(sound))
|
||||
changed(block, Some(sound), "fill_cauldron")
|
||||
};
|
||||
match item {
|
||||
"minecraft:lava_bucket" => {
|
||||
@@ -199,6 +207,7 @@ pub fn interact(
|
||||
outcome: Outcome::Consume,
|
||||
block: None,
|
||||
sound: None,
|
||||
stat: None,
|
||||
}
|
||||
} else {
|
||||
empty_bucket(
|
||||
@@ -221,6 +230,7 @@ pub fn interact(
|
||||
outcome: Outcome::Consume,
|
||||
block: None,
|
||||
sound: None,
|
||||
stat: None,
|
||||
}
|
||||
} else {
|
||||
empty_bucket(
|
||||
@@ -241,6 +251,7 @@ pub fn interact(
|
||||
changed(
|
||||
state("minecraft:water_cauldron", Some(1)),
|
||||
Some("minecraft:item.bottle.empty"),
|
||||
"use_cauldron",
|
||||
)
|
||||
}
|
||||
("water", "minecraft:bucket") => fill_bucket(
|
||||
@@ -255,7 +266,11 @@ pub fn interact(
|
||||
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"),
|
||||
true,
|
||||
);
|
||||
changed(lowered(cauldron), Some("minecraft:item.bottle.fill"))
|
||||
changed(
|
||||
lowered(cauldron),
|
||||
Some("minecraft:item.bottle.fill"),
|
||||
"use_cauldron",
|
||||
)
|
||||
}
|
||||
("water", "minecraft:potion") => {
|
||||
if level == 3 || !water_potion {
|
||||
@@ -266,7 +281,7 @@ pub fn interact(
|
||||
// BlockState.cycle on a 1..=3 property
|
||||
next.properties
|
||||
.insert("level".into(), (level % 3 + 1).to_string());
|
||||
changed(next, Some("minecraft:item.bottle.empty"))
|
||||
changed(next, Some("minecraft:item.bottle.empty"), "use_cauldron")
|
||||
}
|
||||
("water", name)
|
||||
if name
|
||||
@@ -283,7 +298,7 @@ pub fn interact(
|
||||
cleaned.data_mut().banner_patterns.pop();
|
||||
cleaned.tidy();
|
||||
filled(player, cleaned, false);
|
||||
changed(lowered(cauldron), None)
|
||||
changed(lowered(cauldron), None, "clean_banner")
|
||||
}
|
||||
("water", name)
|
||||
if name
|
||||
@@ -292,7 +307,7 @@ pub fn interact(
|
||||
.is_some_and(|c| COLORS.contains(&c)) =>
|
||||
{
|
||||
filled(player, held.transmute("minecraft:shulker_box", 1), false);
|
||||
changed(lowered(cauldron), None)
|
||||
changed(lowered(cauldron), None, "clean_shulker_box")
|
||||
}
|
||||
("lava", "minecraft:bucket") => fill_bucket(
|
||||
player,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! threads can mesh and light immutable snapshots while the game thread edits
|
||||
//! (copy-on-write through `Arc::make_mut`).
|
||||
use horizon_core::paletted::{PalettedContainer, Strategy};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -155,7 +156,7 @@ pub struct Chunk {
|
||||
/// positions, applied once by LevelChunk.postProcessGeneration.
|
||||
pub postprocess: Vec<[i32; 3]>,
|
||||
/// Saved data Horizon keeps but does not simulate (save.rs).
|
||||
pub saved: Option<Arc<crate::save::ChunkExtras>>,
|
||||
pub saved: Option<Arc<ChunkExtras>>,
|
||||
/// Entities read from a save (vanilla entity NBT), spawned on arrival.
|
||||
pub entities: Vec<horizon_world::nbt::Tag>,
|
||||
/// Structure starts reaching into this chunk (`structures.References`):
|
||||
@@ -309,6 +310,76 @@ impl Chunk {
|
||||
}
|
||||
}
|
||||
|
||||
/// A proto chunk saved before it became final. Decoration writes into a
|
||||
/// chunk's neighbours, and decorated chunks wait for theirs, so the chunks
|
||||
/// past the finished ones hold writes that generating them again would lose
|
||||
/// (whole structure pieces, trees, ores). Vanilla saves its proto chunks too.
|
||||
pub struct SavedProto {
|
||||
/// Blocks, scheduled ticks (in `saved`) and post-processing marks.
|
||||
pub column: Chunk,
|
||||
/// Decorated itself (`features`), not only written to by its neighbours
|
||||
/// (`terrain`).
|
||||
pub decorated: bool,
|
||||
/// Block entity data in placement order, with `x`, `y` and `z`.
|
||||
pub block_entities: Vec<Tag>,
|
||||
/// Entities placed by structures, with absolute `Pos`.
|
||||
pub entities: Vec<Tag>,
|
||||
}
|
||||
|
||||
/// A container's loot table and what Horizon rolled from it. Vanilla keeps
|
||||
/// `LootTable` and `LootTableSeed` until the container is first opened;
|
||||
/// Horizon rolls when it generates or loads the chunk, and saves the table
|
||||
/// again while the container still holds exactly the rolled items.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RolledLoot {
|
||||
pub pos: (i32, i32, i32),
|
||||
pub table: String,
|
||||
/// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable).
|
||||
pub seed: Option<i64>,
|
||||
/// The rolled `Items`.
|
||||
pub items: Tag,
|
||||
}
|
||||
impl RolledLoot {
|
||||
/// Puts the loot table back in place of `Items` while they are still the
|
||||
/// roll; false once the container holds anything else.
|
||||
pub fn restore(&self, map: &mut Compound) -> bool {
|
||||
if map.get(&"Items".into()) != Some(&self.items) {
|
||||
return false;
|
||||
}
|
||||
map.remove(&"Items".into());
|
||||
map.insert("LootTable".into(), Tag::String(self.table.as_str().into()));
|
||||
if let Some(seed) = self.seed.filter(|s| *s != 0) {
|
||||
map.insert("LootTableSeed".into(), Tag::Long(seed));
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Save data loaded with a chunk that Horizon keeps but does not simulate.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ChunkExtras {
|
||||
/// Chunk root keys written back as loaded (structures, PostProcessing,
|
||||
/// InhabitedTime, blending data, ...).
|
||||
pub root: Compound,
|
||||
/// Block entities Horizon does not model.
|
||||
pub block_entities: Vec<Tag>,
|
||||
/// The NBT of the modelled block entities as loaded, to restore the fields and
|
||||
/// detail Horizon does not model when it saves them (`block_entity_nbt::overlay`).
|
||||
pub block_entity_sources: Vec<((i32, i32, i32), Tag)>,
|
||||
/// Every saved block entity's position in the order of the save's list,
|
||||
/// the order `SerializableChunkData` puts them in the chunk's maps.
|
||||
pub block_entity_order: Vec<(i32, i32, i32)>,
|
||||
/// Scheduled ticks (`block_ticks`/`fluid_ticks`): delays relative to the
|
||||
/// save time. Registered with the level's tick scheduler on arrival and
|
||||
/// replaced with the scheduler's pending ticks when saving.
|
||||
pub block_ticks: Vec<horizon_core::ticks::SavedTick>,
|
||||
pub fluid_ticks: Vec<horizon_core::ticks::SavedTick>,
|
||||
/// Game time written as `LastUpdate`.
|
||||
pub last_update: i64,
|
||||
/// Containers still holding their loot table's roll.
|
||||
pub rolled_loot: Vec<RolledLoot>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -76,14 +76,11 @@ impl<'a> IntoIterator for &'a ChunkMap {
|
||||
}
|
||||
}
|
||||
impl crate::light::LightWorld for ChunkMap {
|
||||
fn state(&self, x: i32, y: i32, z: i32) -> Option<u32> {
|
||||
self.columns.state(x, y, z)
|
||||
fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc<crate::chunk::Section>> {
|
||||
self.columns.section(cx, s, cz)
|
||||
}
|
||||
fn light(&self, x: i32, y: i32, z: i32) -> Option<u8> {
|
||||
self.columns.light(x, y, z)
|
||||
}
|
||||
fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) {
|
||||
self.columns.set_light(x, y, z, packed);
|
||||
fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: crate::chunk::Light) {
|
||||
self.columns.set_section_light(cx, s, cz, light);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +103,13 @@ mod tests {
|
||||
for column in map.values_mut() {
|
||||
Arc::make_mut(column).light_loaded = true;
|
||||
}
|
||||
crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0);
|
||||
crate::light::LightWorld::set_section_light(
|
||||
&mut map,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
crate::chunk::Light::Uniform(0),
|
||||
);
|
||||
assert_eq!(inserted, map.membership_revision());
|
||||
map.remove(&(0, 0));
|
||||
map.insert((1, 0), chunk);
|
||||
|
||||
@@ -179,6 +179,8 @@ impl Mesh {
|
||||
layer: 4,
|
||||
color: u32::MAX,
|
||||
light: shade,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -54,6 +54,27 @@ fn strider_liquid_shape() -> VoxelShape {
|
||||
VoxelShape::from_cube([1, 2, 1], &[true, false]).expect("a valid half-block column")
|
||||
}
|
||||
|
||||
// Vanilla scopes this direction to Entity.move while a piston pushes it.
|
||||
thread_local! {
|
||||
static PISTON_NOCLIP: std::cell::Cell<Option<horizon_core::geometry::Direction>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Suppress the moving part of pistons moving in this direction during a push.
|
||||
pub fn with_piston_noclip<T>(
|
||||
direction: horizon_core::geometry::Direction,
|
||||
f: impl FnOnce() -> T,
|
||||
) -> T {
|
||||
struct Reset(Option<horizon_core::geometry::Direction>);
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
PISTON_NOCLIP.with(|value| value.set(self.0));
|
||||
}
|
||||
}
|
||||
let previous = PISTON_NOCLIP.with(|value| value.replace(Some(direction)));
|
||||
let _reset = Reset(previous);
|
||||
f()
|
||||
}
|
||||
|
||||
pub struct SceneCollisions<'w, 'r> {
|
||||
pub world: &'w World,
|
||||
pub binding: &'w BlockCollisionRegistry<'r>,
|
||||
@@ -140,8 +161,21 @@ impl<W: EntityMovementWorld<Error = io::Error>> EntityMovementWorld for EntityCo
|
||||
border.collision_shape().map(Some).map_err(io::Error::other)
|
||||
}
|
||||
}
|
||||
impl EntityCollisions<'_, SceneCollisions<'_, '_>> {
|
||||
/// `SceneCollisions::resolve` that also stops at the entity boxes.
|
||||
impl<'a, W> EntityCollisions<'a, W>
|
||||
where
|
||||
W: BlockCollisionWorld<Error = io::Error> + EntityMovementWorld<Error = io::Error>,
|
||||
{
|
||||
/// `EntityCollisions` for a body the world border also stops: the border
|
||||
/// and the body's own x and z (`WorldBorder.isInsideCloseToBorder`).
|
||||
pub fn with_border(blocks: W, border: &'a BorderGeometry, at: [f64; 2]) -> Self {
|
||||
Self {
|
||||
blocks,
|
||||
entities: &[],
|
||||
border: Some((border, at)),
|
||||
}
|
||||
}
|
||||
/// `SceneCollisions::resolve` that also stops at the entity boxes and,
|
||||
/// with a border, at the world border's walls.
|
||||
pub fn resolve(
|
||||
&mut self,
|
||||
bounds: Aabb,
|
||||
@@ -149,12 +183,11 @@ impl EntityCollisions<'_, SceneCollisions<'_, '_>> {
|
||||
max_step: f32,
|
||||
on_ground: bool,
|
||||
) -> Result<Vec3> {
|
||||
let context = self.blocks.context(bounds);
|
||||
Ok(resolve_world_movement(
|
||||
self,
|
||||
MovementRequest {
|
||||
entity: EntityIdentity(0),
|
||||
context,
|
||||
context: CollisionContext::position(bounds.min_position().y),
|
||||
bounds,
|
||||
movement,
|
||||
max_step,
|
||||
@@ -324,7 +357,7 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> {
|
||||
return Ok(None);
|
||||
};
|
||||
pistons
|
||||
.collision_shape(self, p, piston, None)
|
||||
.collision_shape(self, p, piston, PISTON_NOCLIP.with(|value| value.get()))
|
||||
.map(Some)
|
||||
.map_err(io::Error::other)
|
||||
}
|
||||
@@ -388,6 +421,42 @@ impl PowderSnowWorld for SceneCollisions<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A collision world without blocks: no chunk is resident, so only the
|
||||
/// world border stops a body.
|
||||
pub struct EmptyCollisions;
|
||||
|
||||
impl BlockCollisionWorld for EmptyCollisions {
|
||||
type Error = io::Error;
|
||||
type Chunk = ChunkPos;
|
||||
fn collision_chunk(&mut self, _: ChunkPos) -> io::Result<Option<ChunkPos>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn collision_block(&mut self, _: ChunkPos, _: BlockPos) -> io::Result<CollisionBlock> {
|
||||
Err(io::Error::other("no chunk is resident"))
|
||||
}
|
||||
fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
fn context_shape(
|
||||
&mut self,
|
||||
_: CollisionBlock,
|
||||
_: BlockPos,
|
||||
_: &CollisionContext<'_>,
|
||||
) -> io::Result<VoxelShape> {
|
||||
Ok(VoxelShape::empty())
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityMovementWorld for EmptyCollisions {
|
||||
type Error = io::Error;
|
||||
fn entity_collisions(&mut self, _: EntityIdentity, _: Aabb) -> io::Result<Vec<VoxelShape>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn movement_border(&mut self, _: EntityIdentity, _: Aabb) -> io::Result<Option<VoxelShape>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collision queries over any block lookup (test worlds without chunks):
|
||||
/// every chunk is present, nothing is suffocating, no entities collide.
|
||||
pub struct LookupCollisions<'w, 'r> {
|
||||
@@ -475,3 +544,70 @@ impl PowderSnowWorld for LookupCollisions<'_, '_> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod piston_noclip_tests {
|
||||
use super::*;
|
||||
use horizon_core::geometry::Direction;
|
||||
|
||||
#[test]
|
||||
fn piston_noclip_is_scoped_and_restored_after_unwind() {
|
||||
assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None);
|
||||
with_piston_noclip(Direction::East, || {
|
||||
assert_eq!(
|
||||
PISTON_NOCLIP.with(|value| value.get()),
|
||||
Some(Direction::East)
|
||||
);
|
||||
let _ =
|
||||
std::panic::catch_unwind(|| with_piston_noclip(Direction::West, || panic!("test")));
|
||||
assert_eq!(
|
||||
PISTON_NOCLIP.with(|value| value.get()),
|
||||
Some(Direction::East)
|
||||
);
|
||||
});
|
||||
assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod border_movement_tests {
|
||||
use super::*;
|
||||
|
||||
/// A border 10 wide around the origin: its wall's inner face is at x = 5.
|
||||
fn border() -> BorderGeometry {
|
||||
BorderGeometry::new([0.0, 0.0], 10.0, 29_999_984).expect("a border")
|
||||
}
|
||||
|
||||
/// `WorldBorder.isInsideCloseToBorder` and `WorldBorder.getCollisionShape`:
|
||||
/// a body inside close to the border collides with the border's walls.
|
||||
#[test]
|
||||
fn a_body_next_to_the_border_stops_at_its_wall() {
|
||||
// A body 0.6 wide, 0.4 blocks short of the wall, moved east into it.
|
||||
let bounds = Aabb::new(Vec3::new(4.0, 0.0, 0.0), Vec3::new(4.6, 1.8, 0.6));
|
||||
let border = border();
|
||||
let mut collisions = EntityCollisions::with_border(EmptyCollisions, &border, [4.3, 0.3]);
|
||||
let moved = collisions
|
||||
.resolve(bounds, Vec3::new(0.51, 0.0, 0.0), 0.0, false)
|
||||
.expect("the movement resolves");
|
||||
// The wall stops the body 0.4 blocks short of the whole move.
|
||||
assert!(
|
||||
(moved.x - 0.4).abs() < 1.0e-9,
|
||||
"the body was not stopped by the border: {moved:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Away from the border, the same body moves the whole way.
|
||||
#[test]
|
||||
fn a_body_away_from_the_border_moves_whole() {
|
||||
let bounds = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.6, 1.8, 0.6));
|
||||
let border = border();
|
||||
let mut collisions = EntityCollisions::with_border(EmptyCollisions, &border, [0.3, 0.3]);
|
||||
let moved = collisions
|
||||
.resolve(bounds, Vec3::new(0.51, 0.0, 0.0), 0.0, false)
|
||||
.expect("the movement resolves");
|
||||
assert!(
|
||||
(moved.x - 0.51).abs() < 1.0e-9,
|
||||
"the body did not move the whole way: {moved:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,460 +0,0 @@
|
||||
//! BlockStateParser: block states (`stone`, `oak_stairs[facing=up]{...}`)
|
||||
//! and block predicates (`#logs[axis=y]`), with vanilla's suggestions.
|
||||
use super::args::{BlockInput, Registries, read_identifier, suggest_resources};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Sugg {
|
||||
Nothing,
|
||||
Item,
|
||||
BlockIdOrTag,
|
||||
Tag,
|
||||
OpenVaguePropertiesOrNbt,
|
||||
OpenNbt,
|
||||
OpenPropertiesOrNbt,
|
||||
PropertyNameOrEnd,
|
||||
VaguePropertyNameOrEnd,
|
||||
PropertyName,
|
||||
VaguePropertyName,
|
||||
Equals,
|
||||
PropertyValues(String),
|
||||
NextPropertyOrEnd,
|
||||
VaguePropertyValue(String),
|
||||
}
|
||||
|
||||
type Props = Vec<(String, Vec<String>)>;
|
||||
|
||||
pub struct BlockParser<'r, 'a> {
|
||||
reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
for_testing: bool,
|
||||
allow_nbt: bool,
|
||||
id: String,
|
||||
/// The block's state definition (properties and values).
|
||||
definition: Option<&'r Props>,
|
||||
properties: Vec<(String, String)>,
|
||||
vague: Vec<(String, String)>,
|
||||
tag: Option<String>,
|
||||
nbt: Option<String>,
|
||||
sugg: Sugg,
|
||||
}
|
||||
|
||||
fn is_int_property(values: &[String]) -> bool {
|
||||
!values.is_empty() && values.iter().all(|v| v.parse::<i32>().is_ok())
|
||||
}
|
||||
/// Property.getValue.
|
||||
fn property_value(values: &[String], raw: &str) -> Option<String> {
|
||||
if is_int_property(values) {
|
||||
let v: i32 = super::args::java_parse_int(raw)?;
|
||||
let s = v.to_string();
|
||||
return values.contains(&s).then_some(s);
|
||||
}
|
||||
values.iter().any(|v| v == raw).then(|| raw.to_owned())
|
||||
}
|
||||
/// addSuggestions: every value (integers as integer suggestions).
|
||||
fn add_values(builder: &mut SuggestionsBuilder, values: &[String]) {
|
||||
let ints = is_int_property(values);
|
||||
for v in values {
|
||||
if ints {
|
||||
builder.suggest_int(v.parse().unwrap_or(0));
|
||||
} else {
|
||||
builder.suggest(v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r, 'a> BlockParser<'r, 'a> {
|
||||
pub fn new(
|
||||
reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
for_testing: bool,
|
||||
allow_nbt: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
reader,
|
||||
reg,
|
||||
for_testing,
|
||||
allow_nbt,
|
||||
id: "minecraft:".into(),
|
||||
definition: None,
|
||||
properties: Vec::new(),
|
||||
vague: Vec::new(),
|
||||
tag: None,
|
||||
nbt: None,
|
||||
sugg: Sugg::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_members(&self) -> &'r [String] {
|
||||
match &self.tag {
|
||||
Some(t) => self
|
||||
.reg
|
||||
.block_tag_members
|
||||
.get(t)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]),
|
||||
None => &[],
|
||||
}
|
||||
}
|
||||
fn block_props(&self, id: &str) -> &'r [(String, Vec<String>)] {
|
||||
self.reg.blocks.get(id).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn parse(&mut self) -> CmdResult<BlockInput> {
|
||||
self.sugg = if self.for_testing {
|
||||
Sugg::BlockIdOrTag
|
||||
} else {
|
||||
Sugg::Item
|
||||
};
|
||||
if self.reader.can_read() && self.reader.peek() == '#' {
|
||||
self.read_tag()?;
|
||||
self.sugg = Sugg::OpenVaguePropertiesOrNbt;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.read_vague_properties()?;
|
||||
self.sugg = Sugg::OpenNbt;
|
||||
}
|
||||
} else {
|
||||
self.read_block()?;
|
||||
self.sugg = Sugg::OpenPropertiesOrNbt;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.read_properties()?;
|
||||
self.sugg = Sugg::OpenNbt;
|
||||
}
|
||||
}
|
||||
if self.allow_nbt && self.reader.can_read() && self.reader.peek() == '{' {
|
||||
self.sugg = Sugg::Nothing;
|
||||
let start = self.reader.cursor;
|
||||
super::snbt::parse_compound_argument(self.reader)?;
|
||||
self.nbt = Some(self.reader.string[start..self.reader.cursor].to_owned());
|
||||
}
|
||||
let (id, properties) = match &self.tag {
|
||||
Some(t) => (t.clone(), self.vague.clone()),
|
||||
None => (self.id.clone(), self.properties.clone()),
|
||||
};
|
||||
Ok(BlockInput {
|
||||
id,
|
||||
properties,
|
||||
tag: self.tag.is_some(),
|
||||
nbt: self.nbt.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_block(&mut self) -> CmdResult<()> {
|
||||
let start = self.reader.cursor;
|
||||
self.id = read_identifier(self.reader)?;
|
||||
match self.reg.blocks.get(&self.id) {
|
||||
Some(props) => {
|
||||
self.definition = Some(props);
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
self.reader.cursor = start;
|
||||
Err(CommandError::tr_at(
|
||||
"argument.block.id.invalid",
|
||||
&[&self.id],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_tag(&mut self) -> CmdResult<()> {
|
||||
if !self.for_testing {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.tag.disallowed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
let start = self.reader.cursor;
|
||||
self.reader.expect('#')?;
|
||||
self.sugg = Sugg::Tag;
|
||||
let id = read_identifier(self.reader)?;
|
||||
if !self.reg.tags("minecraft:block").contains(&id) {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.block.tag.unknown",
|
||||
&[&id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.tag = Some(id);
|
||||
Ok(())
|
||||
}
|
||||
fn read_properties(&mut self) -> CmdResult<()> {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::PropertyNameOrEnd;
|
||||
self.reader.skip_whitespace();
|
||||
let definition = self.definition.map(Vec::as_slice).unwrap_or(&[]);
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
let key_start = self.reader.cursor;
|
||||
let key = self.reader.read_string()?;
|
||||
let Some((_, values)) = definition.iter().find(|(n, _)| *n == key) else {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.unknown",
|
||||
&[&self.id, &key],
|
||||
self.reader,
|
||||
));
|
||||
};
|
||||
if self.properties.iter().any(|(n, _)| *n == key) {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.duplicate",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::Equals;
|
||||
if !self.reader.can_read() || self.reader.peek() != '=' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.novalue",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::PropertyValues(key.clone());
|
||||
let start = self.reader.cursor;
|
||||
let raw = self.reader.read_string()?;
|
||||
match property_value(values, &raw) {
|
||||
Some(v) => self.properties.push((key, v)),
|
||||
None => {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.invalid",
|
||||
&[&self.id, &raw, &key],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
self.sugg = Sugg::NextPropertyOrEnd;
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() {
|
||||
if self.reader.peek() != ',' {
|
||||
if self.reader.peek() != ']' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::PropertyName;
|
||||
}
|
||||
}
|
||||
if self.reader.can_read() {
|
||||
self.reader.skip();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
fn read_vague_properties(&mut self) -> CmdResult<()> {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::VaguePropertyNameOrEnd;
|
||||
let mut value_start: Option<usize> = None;
|
||||
self.reader.skip_whitespace();
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
let key_start = self.reader.cursor;
|
||||
let key = self.reader.read_string()?;
|
||||
if self.vague.iter().any(|(n, _)| *n == key) {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.duplicate",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
if !self.reader.can_read() || self.reader.peek() != '=' {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.novalue",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::VaguePropertyValue(key.clone());
|
||||
value_start = Some(self.reader.cursor);
|
||||
let value = self.reader.read_string()?;
|
||||
self.vague.push((key, value));
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() {
|
||||
value_start = None;
|
||||
if self.reader.peek() != ',' {
|
||||
if self.reader.peek() != ']' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::VaguePropertyName;
|
||||
}
|
||||
}
|
||||
if self.reader.can_read() {
|
||||
self.reader.skip();
|
||||
Ok(())
|
||||
} else {
|
||||
if let Some(v) = value_start {
|
||||
self.reader.cursor = v;
|
||||
}
|
||||
Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn has_block_entity(&self) -> bool {
|
||||
if self.tag.is_none() {
|
||||
return self.reg.block_entities.contains(&self.id);
|
||||
}
|
||||
self.tag_members()
|
||||
.iter()
|
||||
.any(|b| self.reg.block_entities.contains(b))
|
||||
}
|
||||
|
||||
pub fn fill_suggestions(&self, builder: &mut SuggestionsBuilder) {
|
||||
let mut b = builder.offset(self.reader.cursor);
|
||||
let empty = b.remaining().is_empty();
|
||||
let definition = self.definition.map(Vec::as_slice).unwrap_or(&[]);
|
||||
match &self.sugg {
|
||||
Sugg::Nothing => {}
|
||||
Sugg::Item => {
|
||||
let ids: Vec<&String> = self.reg.blocks.keys().collect();
|
||||
suggest_resources(&mut b, ids, "");
|
||||
}
|
||||
Sugg::Tag => suggest_resources(&mut b, self.reg.tags("minecraft:block"), "#"),
|
||||
Sugg::BlockIdOrTag => {
|
||||
suggest_resources(&mut b, self.reg.tags("minecraft:block"), "#");
|
||||
let ids: Vec<&String> = self.reg.blocks.keys().collect();
|
||||
suggest_resources(&mut b, ids, "");
|
||||
}
|
||||
Sugg::OpenVaguePropertiesOrNbt => {
|
||||
if empty && self.tag.is_some() {
|
||||
let members = self.tag_members();
|
||||
if members.iter().any(|m| !self.block_props(m).is_empty()) {
|
||||
b.suggest("[");
|
||||
}
|
||||
if members.iter().any(|m| self.reg.block_entities.contains(m)) {
|
||||
b.suggest("{");
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::OpenNbt => {
|
||||
if empty && self.has_block_entity() {
|
||||
b.suggest("{");
|
||||
}
|
||||
}
|
||||
Sugg::OpenPropertiesOrNbt => {
|
||||
if empty {
|
||||
if !definition.is_empty() {
|
||||
b.suggest("[");
|
||||
}
|
||||
if self.reg.block_entities.contains(&self.id) {
|
||||
b.suggest("{");
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::PropertyNameOrEnd | Sugg::PropertyName => {
|
||||
if matches!(self.sugg, Sugg::PropertyNameOrEnd) && empty {
|
||||
b.suggest("]");
|
||||
}
|
||||
let prefix = b.remaining_lower();
|
||||
for (name, _) in definition {
|
||||
if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix)
|
||||
{
|
||||
b.suggest(format!("{name}="));
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::VaguePropertyNameOrEnd | Sugg::VaguePropertyName => {
|
||||
if matches!(self.sugg, Sugg::VaguePropertyNameOrEnd) && empty {
|
||||
b.suggest("]");
|
||||
}
|
||||
let prefix = b.remaining_lower();
|
||||
for m in self.tag_members() {
|
||||
for (name, _) in self.block_props(m) {
|
||||
if !self.vague.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) {
|
||||
b.suggest(format!("{name}="));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::Equals => {
|
||||
if empty {
|
||||
b.suggest("=");
|
||||
}
|
||||
}
|
||||
Sugg::PropertyValues(key) => {
|
||||
if let Some((_, values)) = definition.iter().find(|(n, _)| n == key) {
|
||||
add_values(&mut b, values);
|
||||
}
|
||||
}
|
||||
Sugg::NextPropertyOrEnd => {
|
||||
if empty {
|
||||
b.suggest("]");
|
||||
}
|
||||
if empty && self.properties.len() < definition.len() {
|
||||
b.suggest(",");
|
||||
}
|
||||
}
|
||||
Sugg::VaguePropertyValue(key) => {
|
||||
let mut more = false;
|
||||
for m in self.tag_members() {
|
||||
let props = self.block_props(m);
|
||||
if let Some((_, values)) = props.iter().find(|(n, _)| n == key) {
|
||||
add_values(&mut b, values);
|
||||
}
|
||||
if !more {
|
||||
more = props
|
||||
.iter()
|
||||
.any(|(n, _)| !self.vague.iter().any(|(v, _)| v == n));
|
||||
}
|
||||
}
|
||||
if more {
|
||||
b.suggest(",");
|
||||
}
|
||||
b.suggest("]");
|
||||
}
|
||||
}
|
||||
builder.add(b);
|
||||
}
|
||||
}
|
||||
|
||||
/// BlockStateParser.parseForBlock / parseForTesting (the reader is rewound on errors).
|
||||
pub fn parse(reader: &mut Reader, reg: &Registries, for_testing: bool) -> CmdResult<BlockInput> {
|
||||
let cursor = reader.cursor;
|
||||
let r = BlockParser::new(reader, reg, for_testing, true).parse();
|
||||
if r.is_err() {
|
||||
reader.cursor = cursor;
|
||||
}
|
||||
r
|
||||
}
|
||||
/// BlockStateParser.fillSuggestions.
|
||||
pub fn suggest(builder: &mut SuggestionsBuilder, reg: &Registries, for_testing: bool) {
|
||||
let mut reader = Reader {
|
||||
string: builder.input,
|
||||
cursor: builder.start,
|
||||
};
|
||||
let mut parser = BlockParser::new(&mut reader, reg, for_testing, true);
|
||||
let _ = parser.parse();
|
||||
parser.fill_suggestions(builder);
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
//! ResourceOrIdArgument and the data-fixer-upper decoding of inline values
|
||||
//! commands accept (loot predicates, item modifiers, slot sources, context
|
||||
//! providers, dialogs), reproducing the codec error messages vanilla reports.
|
||||
use super::args::{Registries, is_id_char, parse_identifier};
|
||||
use super::{CmdResult, CommandError, Reader};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
|
||||
pub fn snbt(t: &Tag) -> String {
|
||||
crate::snbt::to_snbt(t)
|
||||
}
|
||||
pub fn not_map(t: &Tag) -> String {
|
||||
format!("Not a map: {}", snbt(t))
|
||||
}
|
||||
pub fn not_list(t: &Tag) -> String {
|
||||
format!("Not a list: {}", snbt(t))
|
||||
}
|
||||
pub fn no_key(key: &str, t: &Tag) -> String {
|
||||
format!("No key {key} in MapLike[{}]", snbt(t))
|
||||
}
|
||||
pub fn either(a: String, b: String) -> String {
|
||||
format!("Failed to parse either. First: {a}; Second: {b}")
|
||||
}
|
||||
pub fn get<'t>(map: &'t Compound, key: &str) -> Option<&'t Tag> {
|
||||
map.get(&JavaString::from(key))
|
||||
}
|
||||
pub fn is_number(t: &Tag) -> bool {
|
||||
matches!(
|
||||
t,
|
||||
Tag::Byte(_) | Tag::Short(_) | Tag::Int(_) | Tag::Long(_) | Tag::Float(_) | Tag::Double(_)
|
||||
)
|
||||
}
|
||||
pub fn as_string(t: &Tag) -> Option<String> {
|
||||
match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// KeyDispatchCodec over a type registry: the map, its `type` and the
|
||||
/// type's own fields (`fields` checks them).
|
||||
fn dispatch(
|
||||
t: &Tag,
|
||||
reg: &Registries,
|
||||
type_registry: &str,
|
||||
fields: &dyn Fn(&str, &Compound, &Tag) -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
let Tag::Compound(map) = t else {
|
||||
return Err(not_map(t));
|
||||
};
|
||||
let Some(ty) = get(map, "type") else {
|
||||
return Err(no_key("type", t));
|
||||
};
|
||||
let Some(name) = as_string(ty) else {
|
||||
return Err("Not a string".into());
|
||||
};
|
||||
let Some(id) = parse_identifier(&name) else {
|
||||
return Err(format!("Not a valid resource location: {name}"));
|
||||
};
|
||||
let known = reg.ids(type_registry);
|
||||
if !known.is_empty() && !known.contains(&id) {
|
||||
return Err(format!(
|
||||
"Unknown registry key in ResourceKey[minecraft:root / {type_registry}]: {id}"
|
||||
));
|
||||
}
|
||||
fields(&id, map, t)
|
||||
}
|
||||
/// Required fields, reported in vanilla's order when missing.
|
||||
fn require(map: &Compound, t: &Tag, keys: &[&str]) -> Result<(), String> {
|
||||
let missing: Vec<String> = keys
|
||||
.iter()
|
||||
.filter(|k| get(map, k).is_none())
|
||||
.map(|k| no_key(k, t))
|
||||
.collect();
|
||||
if missing.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(missing.join("; "))
|
||||
}
|
||||
}
|
||||
/// The required fields of each context number provider type, in the
|
||||
/// order DataFixerUpper reports them missing (the reverse of the record's).
|
||||
fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> {
|
||||
match id.trim_start_matches("minecraft:") {
|
||||
"uniform" => require(map, t, &["max", "min"]),
|
||||
"constant" => require(map, t, &["value"]),
|
||||
"binomial" => require(map, t, &["p", "n"]),
|
||||
"add" | "mul" | "avg" | "max" | "min" | "length" => require(map, t, &["inputs"]),
|
||||
"sub" | "div" | "mod" | "floor_div" | "floor_mod" => require(map, t, &["right", "left"]),
|
||||
"pow" => require(map, t, &["exponent", "base"]),
|
||||
"abs" | "negate" | "from_float" | "from_int" | "floor" | "ceil" | "round" | "sqrt"
|
||||
| "sin" | "cos" | "truncate" => require(map, t, &["input"]),
|
||||
"conditional" => require(map, t, &["on_true", "condition"]),
|
||||
"number_dispatcher" => require(map, t, &["cases"]),
|
||||
"weighted_list" => require(map, t, &["distribution"]),
|
||||
"enchantment_level" => require(map, t, &["amount"]),
|
||||
"score" => require(map, t, &["score", "target"]),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// A holder list codec: a single element, a `#tag`, or a list.
|
||||
fn element_or_list(t: &Tag, element: &dyn Fn(&Tag) -> Result<(), String>) -> Result<(), String> {
|
||||
let first = match element(t) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
let tag_ref = match as_string(t) {
|
||||
Some(s) if s.starts_with('#') => return Ok(()),
|
||||
Some(_) => "Not a tag id".to_owned(),
|
||||
None => "Not a string".to_owned(),
|
||||
};
|
||||
let list = match t {
|
||||
Tag::List(items) => {
|
||||
let errors: Vec<String> = items.iter().filter_map(|i| element(i).err()).collect();
|
||||
if errors.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
errors.join("; ")
|
||||
}
|
||||
_ => not_list(t),
|
||||
};
|
||||
let last = element(t).err().unwrap_or_default();
|
||||
Err(either(first, either(tag_ref, either(list, last))))
|
||||
}
|
||||
|
||||
/// Decode an inline value of a ResourceOrIdArgument registry.
|
||||
pub fn decode(registry: &str, t: &Tag, reg: &Registries) -> Result<(), String> {
|
||||
match registry {
|
||||
"minecraft:context_int_provider" | "minecraft:context_float_provider" => {
|
||||
if is_number(t) {
|
||||
return Ok(());
|
||||
}
|
||||
let ty = format!("{registry}_type");
|
||||
let second = dispatch(t, reg, &ty, &provider_fields);
|
||||
second.map_err(|e| either("Not a number".into(), e))
|
||||
}
|
||||
"minecraft:predicate" => {
|
||||
dispatch(t, reg, "minecraft:loot_condition_type", &|_, _, _| Ok(()))
|
||||
}
|
||||
"minecraft:item_modifier" => element_or_list(t, &|x| {
|
||||
dispatch(x, reg, "minecraft:loot_function_type", &|_, _, _| Ok(()))
|
||||
}),
|
||||
"minecraft:slot_source" => element_or_list(t, &|x| {
|
||||
dispatch(x, reg, "minecraft:slot_source_type", &|_, _, _| Ok(()))
|
||||
}),
|
||||
// Dialog types: CommonDialogData's title, then each type's own.
|
||||
"minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|id, map, t| {
|
||||
let own: &[&str] = match id {
|
||||
"minecraft:confirmation" => &["yes", "no"],
|
||||
"minecraft:multi_action" => &["actions"],
|
||||
"minecraft:dialog_list" => &["dialogs"],
|
||||
_ => &[],
|
||||
};
|
||||
let keys: Vec<&str> = std::iter::once("title")
|
||||
.chain(own.iter().copied())
|
||||
.collect();
|
||||
require(map, t, &keys)
|
||||
}),
|
||||
"minecraft:worldgen/feature" | "minecraft:loot_table" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifier.readNonEmpty (None when empty or invalid).
|
||||
fn read_non_empty(reader: &mut Reader) -> Option<String> {
|
||||
let start = reader.cursor;
|
||||
while reader.can_read() && is_id_char(reader.peek()) {
|
||||
reader.skip();
|
||||
}
|
||||
let raw = &reader.string[start..reader.cursor];
|
||||
let id = if raw.is_empty() {
|
||||
None
|
||||
} else {
|
||||
parse_identifier(raw)
|
||||
};
|
||||
if id.is_none() {
|
||||
reader.cursor = start;
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// ResourceOrIdArgument.parse: a registry id (checked) or an inline SNBT
|
||||
/// value decoded with the registry's codec.
|
||||
pub fn resource_or_id(reader: &mut Reader, reg: &Registries, registry: &str) -> CmdResult<()> {
|
||||
let start = reader.cursor;
|
||||
let mut r = reader.clone();
|
||||
r.skip_whitespace();
|
||||
if let Some(id) = read_non_empty(&mut r) {
|
||||
reader.cursor = r.cursor;
|
||||
if !reg.ids(registry).contains(&id) {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.resource_or_id.no_such_element",
|
||||
&[&id, ®istry],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
reader.cursor = start;
|
||||
let tag = super::snbt::parse_tag_argument(reader)?;
|
||||
decode(registry, &tag, reg)
|
||||
.map_err(|m| CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader))
|
||||
}
|
||||
@@ -1,364 +0,0 @@
|
||||
//! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of
|
||||
//! SNBT text components, with the data-fixer-upper error messages
|
||||
//! (ComponentArgument, StyleArgument and component-valued item data).
|
||||
use super::codec::{get, no_key, not_list, not_map};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
/// A DataResult error: its message and whether it carries a partial result.
|
||||
struct E {
|
||||
msg: String,
|
||||
partial: bool,
|
||||
}
|
||||
type R = Result<(), E>;
|
||||
fn err(msg: impl Into<String>) -> R {
|
||||
Err(E {
|
||||
msg: msg.into(),
|
||||
partial: false,
|
||||
})
|
||||
}
|
||||
fn partial(msg: impl Into<String>) -> R {
|
||||
Err(E {
|
||||
msg: msg.into(),
|
||||
partial: true,
|
||||
})
|
||||
}
|
||||
/// Codec.either.
|
||||
fn either(first: R, second: impl FnOnce() -> R) -> R {
|
||||
let a = match first {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
let b = match second() {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if a.partial {
|
||||
return Err(a);
|
||||
}
|
||||
if b.partial {
|
||||
return Err(b);
|
||||
}
|
||||
err(format!(
|
||||
"Failed to parse either. First: {}; Second: {}",
|
||||
a.msg, b.msg
|
||||
))
|
||||
}
|
||||
fn is_string(t: &Tag) -> bool {
|
||||
matches!(t, Tag::String(_))
|
||||
}
|
||||
fn string(t: &Tag) -> R {
|
||||
if is_string(t) {
|
||||
Ok(())
|
||||
} else {
|
||||
err("Not a string")
|
||||
}
|
||||
}
|
||||
fn string_of(t: &Tag) -> Option<String> {
|
||||
match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// ListCodec: element errors (newest first) with the decoded rest as partial.
|
||||
fn list(t: &Tag, element: &dyn Fn(&Tag) -> R) -> Result<usize, E> {
|
||||
let Tag::List(items) = t else {
|
||||
return Err(E {
|
||||
msg: not_list(t),
|
||||
partial: false,
|
||||
});
|
||||
};
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
let mut ok = 0;
|
||||
for i in items {
|
||||
match element(i) {
|
||||
Ok(()) => ok += 1,
|
||||
Err(e) => {
|
||||
if e.partial {
|
||||
ok += 1;
|
||||
}
|
||||
errors.push(e.msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
return Ok(ok);
|
||||
}
|
||||
errors.reverse();
|
||||
Err(E {
|
||||
msg: errors.join("; "),
|
||||
partial: true,
|
||||
})
|
||||
}
|
||||
/// ExtraCodecs.nonEmptyList(listOf(element)).
|
||||
fn non_empty_list(t: &Tag, element: &dyn Fn(&Tag) -> R) -> R {
|
||||
match list(t, element) {
|
||||
Ok(0) => err("List must have contents"),
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) if !e.partial => Err(e),
|
||||
Err(e) => {
|
||||
// The partial result is validated too.
|
||||
let decoded = match t {
|
||||
Tag::List(items) => items.iter().filter(|i| element(i).is_ok()).count(),
|
||||
_ => 0,
|
||||
};
|
||||
if decoded == 0 {
|
||||
err(format!("{}; List must have contents", e.msg))
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bool_value(t: &Tag) -> R {
|
||||
if super::codec::is_number(t) {
|
||||
Ok(())
|
||||
} else {
|
||||
err("Not a number")
|
||||
}
|
||||
}
|
||||
/// Identifier.CODEC.
|
||||
pub fn identifier(t: &Tag) -> Result<(), String> {
|
||||
let Some(s) = string_of(t) else {
|
||||
return Err("Not a string".into());
|
||||
};
|
||||
let (ns, path) = match s.split_once(':') {
|
||||
Some(("", p)) => ("minecraft".to_owned(), p.to_owned()),
|
||||
Some((n, p)) => (n.to_owned(), p.to_owned()),
|
||||
None => ("minecraft".to_owned(), s.clone()),
|
||||
};
|
||||
let ns_ok = ns != ".."
|
||||
&& ns
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
|
||||
if !ns_ok {
|
||||
return Err(format!(
|
||||
"Not a valid resource location: {s} Non [a-z0-9_.-] character in namespace of location: {ns}:{path}"
|
||||
));
|
||||
}
|
||||
let path_ok = path.chars().all(|c| {
|
||||
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')
|
||||
});
|
||||
if !path_ok {
|
||||
return Err(format!(
|
||||
"Not a valid resource location: {s} Non [a-z0-9/._-] character in path of location: {ns}:{path}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// TextColor.CODEC.
|
||||
fn color(t: &Tag) -> R {
|
||||
let Some(s) = string_of(t) else {
|
||||
return partial("Not a string");
|
||||
};
|
||||
if let Some(hex) = s.strip_prefix('#') {
|
||||
let digits = hex.strip_prefix(['+', '-']).unwrap_or(hex);
|
||||
let valid = !digits.is_empty() && digits.chars().all(|c| c.is_ascii_hexdigit());
|
||||
return match i64::from_str_radix(hex, 16) {
|
||||
Ok(v) if valid && i32::try_from(v).is_ok() => {
|
||||
if (0..=0xFF_FFFF).contains(&v) {
|
||||
Ok(())
|
||||
} else {
|
||||
partial(format!("Color value out of range: {s}"))
|
||||
}
|
||||
}
|
||||
_ => partial(format!("Invalid color value: {s}")),
|
||||
};
|
||||
}
|
||||
if crate::text::named_color(&s).is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
partial(format!("Invalid color name: {s}"))
|
||||
}
|
||||
}
|
||||
/// A KeyDispatch over an action enum (`Unknown element name:`), with
|
||||
/// required fields per action.
|
||||
fn action_event(t: &Tag, actions: &[(&str, &[&str])]) -> R {
|
||||
let Tag::Compound(map) = t else {
|
||||
return partial(not_map(t));
|
||||
};
|
||||
let Some(action) = get(map, "action") else {
|
||||
return partial(no_key("action", t));
|
||||
};
|
||||
let Some(name) = string_of(action) else {
|
||||
return partial("Not a string");
|
||||
};
|
||||
let Some((_, fields)) = actions.iter().find(|(a, _)| *a == name) else {
|
||||
return partial(format!("Unknown element name:{name}"));
|
||||
};
|
||||
for f in *fields {
|
||||
if get(map, f).is_none() {
|
||||
return partial(no_key(f, t));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
const CLICK_ACTIONS: &[(&str, &[&str])] = &[
|
||||
("open_url", &["url"]),
|
||||
("open_file", &["path"]),
|
||||
("run_command", &["command"]),
|
||||
("suggest_command", &["command"]),
|
||||
("show_dialog", &["dialog"]),
|
||||
("change_page", &["page"]),
|
||||
("copy_to_clipboard", &["value"]),
|
||||
("custom", &["id"]),
|
||||
];
|
||||
const HOVER_ACTIONS: &[(&str, &[&str])] = &[
|
||||
("show_text", &["value"]),
|
||||
("show_item", &["id"]),
|
||||
("show_entity", &["id", "uuid"]),
|
||||
];
|
||||
/// Style.Serializer.MAP_CODEC (every field optional; errors keep a partial style).
|
||||
fn style_fields(map: &Compound) -> R {
|
||||
if let Some(c) = get(map, "color") {
|
||||
color(c)?;
|
||||
}
|
||||
for key in [
|
||||
"bold",
|
||||
"italic",
|
||||
"underlined",
|
||||
"strikethrough",
|
||||
"obfuscated",
|
||||
] {
|
||||
if let Some(v) = get(map, key)
|
||||
&& bool_value(v).is_err()
|
||||
{
|
||||
return partial("Not a number");
|
||||
}
|
||||
}
|
||||
if let Some(v) = get(map, "click_event") {
|
||||
action_event(v, CLICK_ACTIONS)?;
|
||||
}
|
||||
if let Some(v) = get(map, "hover_event") {
|
||||
action_event(v, HOVER_ACTIONS)?;
|
||||
}
|
||||
if let Some(v) = get(map, "insertion")
|
||||
&& !is_string(v)
|
||||
{
|
||||
return partial("Not a string");
|
||||
}
|
||||
if let Some(v) = get(map, "font")
|
||||
&& let Err(m) = identifier(v)
|
||||
{
|
||||
return partial(m);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn selector_string(t: &Tag) -> bool {
|
||||
let Some(s) = string_of(t) else { return false };
|
||||
let reg = super::args::Registries {
|
||||
permission: 4,
|
||||
..Default::default()
|
||||
};
|
||||
let mut r = super::Reader::new(&s);
|
||||
super::selector::parse(&mut r, ®, true).is_ok() && !r.can_read()
|
||||
}
|
||||
fn optional_component(map: &Compound, key: &str) -> bool {
|
||||
get(map, key).is_none_or(|v| component(v).is_ok())
|
||||
}
|
||||
/// The content codecs (PlainText, Translatable, Keybind, Score, Selector, Nbt, Object).
|
||||
fn content(kind: &str, map: &Compound) -> bool {
|
||||
match kind {
|
||||
"text" => get(map, "text").is_some_and(is_string),
|
||||
"translatable" => {
|
||||
get(map, "translate").is_some_and(is_string)
|
||||
&& get(map, "fallback").is_none_or(is_string)
|
||||
&& get(map, "with").is_none_or(|w| matches!(w, Tag::List(_)))
|
||||
}
|
||||
"keybind" => get(map, "keybind").is_some_and(is_string),
|
||||
"score" => match get(map, "score") {
|
||||
Some(Tag::Compound(s)) => {
|
||||
get(s, "name").is_some_and(is_string) && get(s, "objective").is_some_and(is_string)
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
"selector" => {
|
||||
get(map, "selector").is_some_and(selector_string)
|
||||
&& optional_component(map, "separator")
|
||||
}
|
||||
"nbt" => {
|
||||
let path_ok = get(map, "nbt")
|
||||
.and_then(string_of)
|
||||
.is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok());
|
||||
let source = if let Some(e) = get(map, "entity") {
|
||||
selector_string(e)
|
||||
} else if let Some(b) = get(map, "block") {
|
||||
string_of(b).is_some_and(|s| {
|
||||
let reg = super::args::Registries::default();
|
||||
let mut r = super::Reader::new(&s);
|
||||
super::ArgType::BlockPos.parse(&mut r, ®).is_ok() && !r.can_read()
|
||||
})
|
||||
} else if let Some(s) = get(map, "storage") {
|
||||
identifier(s).is_ok()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
path_ok && source && optional_component(map, "separator")
|
||||
}
|
||||
"object" => {
|
||||
let kind = get(map, "object").and_then(string_of);
|
||||
let atlas = || {
|
||||
get(map, "sprite").is_some_and(|s| identifier(s).is_ok())
|
||||
&& get(map, "atlas").is_none_or(|a| identifier(a).is_ok())
|
||||
};
|
||||
let player = || get(map, "player").is_some();
|
||||
match kind.as_deref() {
|
||||
Some("atlas") => atlas(),
|
||||
Some("player") => player(),
|
||||
Some(_) => false,
|
||||
None => atlas() || player(),
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
const CONTENT_TYPES: [&str; 7] = [
|
||||
"text",
|
||||
"translatable",
|
||||
"keybind",
|
||||
"score",
|
||||
"selector",
|
||||
"nbt",
|
||||
"object",
|
||||
];
|
||||
fn full(t: &Tag) -> R {
|
||||
let Tag::Compound(map) = t else {
|
||||
return err(not_map(t));
|
||||
};
|
||||
let contents_ok = if let Some(ty) = get(map, "type") {
|
||||
let Some(name) = string_of(ty) else {
|
||||
return err("Not a string");
|
||||
};
|
||||
if !CONTENT_TYPES.contains(&name.as_str()) {
|
||||
return err(format!("Unknown element id: {name}"));
|
||||
}
|
||||
content(&name, map)
|
||||
} else {
|
||||
CONTENT_TYPES.iter().any(|k| content(k, map))
|
||||
};
|
||||
if !contents_ok {
|
||||
return err("No matching codec found");
|
||||
}
|
||||
if let Some(extra) = get(map, "extra") {
|
||||
match non_empty_list(extra, &component) {
|
||||
Ok(()) => {}
|
||||
Err(e) => return partial(e.msg),
|
||||
}
|
||||
}
|
||||
style_fields(map)
|
||||
}
|
||||
fn component(t: &Tag) -> R {
|
||||
either(either(string(t), || non_empty_list(t, &component)), || {
|
||||
full(t)
|
||||
})
|
||||
}
|
||||
/// ComponentSerialization.CODEC.parse: the error message on failure.
|
||||
pub fn decode(t: &Tag) -> Result<(), String> {
|
||||
component(t).map_err(|e| e.msg)
|
||||
}
|
||||
/// Style.Serializer.CODEC.parse.
|
||||
pub fn decode_style(t: &Tag) -> Result<(), String> {
|
||||
match t {
|
||||
Tag::Compound(map) => style_fields(map).map_err(|e| e.msg),
|
||||
_ => Err(not_map(t)),
|
||||
}
|
||||
}
|
||||
@@ -1,657 +0,0 @@
|
||||
//! ItemParser (item stacks with components, `stone[damage=5]`) and
|
||||
//! ItemPredicateArgument (ComponentPredicateParser's packrat grammar:
|
||||
//! `#logs[count~1..|!damage]`), with vanilla's errors and suggestions.
|
||||
use super::args::{
|
||||
ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources,
|
||||
};
|
||||
use super::codec::{either, is_number, not_map, snbt};
|
||||
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, opt, seq};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::rc::Rc;
|
||||
|
||||
fn int_of(t: &Tag) -> Option<i64> {
|
||||
Some(match t {
|
||||
Tag::Byte(v) => i64::from(*v),
|
||||
Tag::Short(v) => i64::from(*v),
|
||||
Tag::Int(v) => i64::from(*v),
|
||||
Tag::Long(v) => *v as i32 as i64,
|
||||
Tag::Float(v) => f32::from_bits(*v) as i32 as i64,
|
||||
Tag::Double(v) => f64::from_bits(*v) as i32 as i64,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// The codecs of the item components commands commonly set.
|
||||
pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> {
|
||||
match id {
|
||||
"minecraft:damage" | "minecraft:repair_cost" => {
|
||||
let v = int_of(t).ok_or("Not a number")?;
|
||||
if v < 0 {
|
||||
return Err(format!("Value must be non-negative: {v}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"minecraft:max_damage" => {
|
||||
let v = int_of(t).ok_or("Not a number")?;
|
||||
if v <= 0 {
|
||||
return Err(format!("Value must be positive: {v}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"minecraft:max_stack_size" => {
|
||||
let v = int_of(t).ok_or("Not a number")?;
|
||||
if !(1..=99).contains(&v) {
|
||||
return Err(format!("Value must be within range [1;99]: {v}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"minecraft:rarity" => match t {
|
||||
Tag::String(s) => {
|
||||
let s = s.to_string_lossy();
|
||||
if ["common", "uncommon", "rare", "epic"].contains(&s.as_str()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Unknown element name:{s}"))
|
||||
}
|
||||
}
|
||||
_ => Err("Not a string".into()),
|
||||
},
|
||||
"minecraft:enchantments" | "minecraft:stored_enchantments" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
},
|
||||
"minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t),
|
||||
// TypedEntityData.codec: the type is the compound's id.
|
||||
"minecraft:block_entity_data" => match t {
|
||||
Tag::Compound(c) => match c.get(&"id".into()) {
|
||||
None => Err(format!("Expected 'id' field in {}", snbt(t))),
|
||||
Some(Tag::String(id)) => {
|
||||
let id = id.to_string_lossy();
|
||||
let id = if id.contains(':') {
|
||||
id
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
let known = crate::block_entity_nbt::TYPES
|
||||
.iter()
|
||||
.chain(&crate::block_entity_nbt::NEWEST)
|
||||
.any(|k| *k == id);
|
||||
if known {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: {id}"
|
||||
))
|
||||
}
|
||||
}
|
||||
Some(_) => Ok(()),
|
||||
},
|
||||
_ => Ok(()),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// MinMaxBounds.Ints.CODEC.
|
||||
fn int_bounds(t: &Tag) -> Result<(), String> {
|
||||
match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ if is_number(t) => Ok(()),
|
||||
_ => Err(either(not_map(t), "Not a number".into())),
|
||||
}
|
||||
}
|
||||
/// DataComponentPredicate type codecs.
|
||||
pub fn decode_predicate(id: &str, t: &Tag) -> Result<(), String> {
|
||||
match id {
|
||||
"minecraft:count" => int_bounds(t),
|
||||
"minecraft:damage" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ItemParser -------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ISugg {
|
||||
Nothing,
|
||||
Item,
|
||||
StartComponents,
|
||||
ComponentAssignmentOrRemoval,
|
||||
Component,
|
||||
Assignment,
|
||||
NextOrEndComponents,
|
||||
}
|
||||
|
||||
struct ItemState<'r, 'a> {
|
||||
reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
sugg: ISugg,
|
||||
}
|
||||
impl ItemState<'_, '_> {
|
||||
fn parse(&mut self) -> CmdResult<ItemInput> {
|
||||
self.sugg = ISugg::Item;
|
||||
let cursor = self.reader.cursor;
|
||||
let id = read_identifier(self.reader)?;
|
||||
if !self.reg.ids("minecraft:item").contains(&id) {
|
||||
self.reader.cursor = cursor;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.item.id.invalid",
|
||||
&[&id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.sugg = ISugg::StartComponents;
|
||||
let mut components = None;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.sugg = ISugg::Nothing;
|
||||
let start = self.reader.cursor;
|
||||
self.read_components()?;
|
||||
components = Some(self.reader.string[start..self.reader.cursor].to_owned());
|
||||
}
|
||||
Ok(ItemInput {
|
||||
id,
|
||||
tag: false,
|
||||
any: false,
|
||||
components,
|
||||
})
|
||||
}
|
||||
fn component_type(&mut self) -> CmdResult<String> {
|
||||
if !self.reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.item.component.expected",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
let cursor = self.reader.cursor;
|
||||
let id = read_identifier(self.reader)?;
|
||||
if self.reg.persistent_components.contains(&id) {
|
||||
return Ok(id);
|
||||
}
|
||||
self.reader.cursor = cursor;
|
||||
Err(CommandError::tr_at(
|
||||
"arguments.item.component.unknown",
|
||||
&[&id],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
fn read_components(&mut self) -> CmdResult<()> {
|
||||
self.reader.expect('[')?;
|
||||
self.sugg = ISugg::ComponentAssignmentOrRemoval;
|
||||
let mut visited: Vec<String> = Vec::new();
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() && self.reader.peek() == '!' {
|
||||
self.reader.skip();
|
||||
self.sugg = ISugg::Component;
|
||||
let ty = self.component_type()?;
|
||||
if visited.contains(&ty) {
|
||||
return Err(CommandError::tr(
|
||||
"arguments.item.component.repeated",
|
||||
&[&ty],
|
||||
));
|
||||
}
|
||||
visited.push(ty);
|
||||
self.sugg = ISugg::Nothing;
|
||||
self.reader.skip_whitespace();
|
||||
} else {
|
||||
let ty = self.component_type()?;
|
||||
if visited.contains(&ty) {
|
||||
return Err(CommandError::tr(
|
||||
"arguments.item.component.repeated",
|
||||
&[&ty],
|
||||
));
|
||||
}
|
||||
visited.push(ty.clone());
|
||||
self.sugg = ISugg::Assignment;
|
||||
self.reader.skip_whitespace();
|
||||
self.reader.expect('=')?;
|
||||
self.sugg = ISugg::Nothing;
|
||||
self.reader.skip_whitespace();
|
||||
let cursor = self.reader.cursor;
|
||||
let tag = super::snbt::parse_tag_argument(self.reader)?;
|
||||
if let Err(m) = decode_component(&ty, &tag) {
|
||||
self.reader.cursor = cursor;
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.item.component.malformed",
|
||||
&[&ty, &m],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
}
|
||||
self.sugg = ISugg::NextOrEndComponents;
|
||||
if !self.reader.can_read() || self.reader.peek() != ',' {
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = ISugg::ComponentAssignmentOrRemoval;
|
||||
if !self.reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.item.component.expected",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
self.reader.expect(']')?;
|
||||
self.sugg = ISugg::Nothing;
|
||||
Ok(())
|
||||
}
|
||||
fn suggest_component(&self, b: &mut SuggestionsBuilder, suffix: &str) {
|
||||
let contents = b.remaining_lower();
|
||||
for id in &self.reg.persistent_components {
|
||||
let matched = if contents.contains(':') {
|
||||
super::args::matches_sub_str(&contents, id)
|
||||
} else {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
super::args::matches_sub_str(&contents, ns)
|
||||
|| super::args::matches_sub_str(&contents, path)
|
||||
};
|
||||
if matched {
|
||||
b.suggest(format!("{id}{suffix}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn fill(&self, builder: &mut SuggestionsBuilder) {
|
||||
let mut b = builder.offset(self.reader.cursor);
|
||||
let empty = b.remaining().is_empty();
|
||||
match self.sugg {
|
||||
ISugg::Nothing => {}
|
||||
ISugg::Item => suggest_resources(&mut b, self.reg.ids("minecraft:item"), ""),
|
||||
ISugg::StartComponents => {
|
||||
if empty {
|
||||
b.suggest("[");
|
||||
}
|
||||
}
|
||||
ISugg::ComponentAssignmentOrRemoval => {
|
||||
b.suggest("!");
|
||||
self.suggest_component(&mut b, "=");
|
||||
}
|
||||
ISugg::Component => self.suggest_component(&mut b, ""),
|
||||
ISugg::Assignment => {
|
||||
if empty {
|
||||
b.suggest("=");
|
||||
}
|
||||
}
|
||||
ISugg::NextOrEndComponents => {
|
||||
if empty {
|
||||
b.suggest(",");
|
||||
b.suggest("]");
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.add(b);
|
||||
}
|
||||
}
|
||||
|
||||
/// ItemArgument.parse (ItemParser.parse; the reader is rewound on errors).
|
||||
pub fn parse_stack(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemInput> {
|
||||
let cursor = reader.cursor;
|
||||
let r = ItemState {
|
||||
reader,
|
||||
reg,
|
||||
sugg: ISugg::Nothing,
|
||||
}
|
||||
.parse();
|
||||
if r.is_err() {
|
||||
reader.cursor = cursor;
|
||||
}
|
||||
r
|
||||
}
|
||||
/// ItemParser.fillSuggestions.
|
||||
pub fn suggest_stack(builder: &mut SuggestionsBuilder, reg: &Registries) {
|
||||
let mut reader = Reader {
|
||||
string: builder.input,
|
||||
cursor: builder.start,
|
||||
};
|
||||
let mut state = ItemState {
|
||||
reader: &mut reader,
|
||||
reg,
|
||||
sugg: ISugg::Nothing,
|
||||
};
|
||||
let _ = state.parse();
|
||||
state.fill(builder);
|
||||
}
|
||||
|
||||
// ---- ItemPredicateArgument ------------------------------------------------
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TypeRes {
|
||||
Item(String),
|
||||
Tag(String),
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum IV {
|
||||
Id(String),
|
||||
Type(Option<TypeRes>),
|
||||
Elem(TypeRes),
|
||||
Unit,
|
||||
Test,
|
||||
Comp(String),
|
||||
Pred(String),
|
||||
Tag(Tag),
|
||||
List(Vec<IV>),
|
||||
}
|
||||
impl Value for IV {
|
||||
fn list(items: Vec<Self>) -> Self {
|
||||
IV::List(items)
|
||||
}
|
||||
}
|
||||
|
||||
fn reg<'a>(state: &State<'a, IV>) -> &'a Registries {
|
||||
state
|
||||
.ctx
|
||||
.and_then(|c| c.downcast_ref::<Registries>())
|
||||
.expect("item predicate grammar needs the registries")
|
||||
}
|
||||
|
||||
/// IdentifierParseRule: skip whitespace, a non-empty identifier (no error).
|
||||
fn id_rule(state: &mut State<IV>) -> Option<IV> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
let start = r.cursor;
|
||||
while r.can_read() && is_id_char(r.peek()) {
|
||||
r.skip();
|
||||
}
|
||||
let raw = &r.string[start..r.cursor];
|
||||
let id = if raw.is_empty() {
|
||||
None
|
||||
} else {
|
||||
parse_identifier(raw)
|
||||
};
|
||||
match id {
|
||||
Some(id) => {
|
||||
state.set_reader(&r);
|
||||
Some(IV::Id(id))
|
||||
}
|
||||
None => {
|
||||
r.cursor = start;
|
||||
state.set_reader(&r);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ResourceLookupRule: an identifier validated by `validate`.
|
||||
fn lookup(
|
||||
state: &mut State<IV>,
|
||||
id_rule: usize,
|
||||
possible: Rc<Vec<String>>,
|
||||
validate: &dyn Fn(&str, &Reader) -> Result<IV, CommandError>,
|
||||
) -> Option<IV> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
state.set_reader(&r);
|
||||
let mark = state.cursor;
|
||||
match state.parse(id_rule) {
|
||||
Some(IV::Id(id)) => match validate(&id, &state.reader()) {
|
||||
Ok(v) => Some(v),
|
||||
Err(e) => {
|
||||
state.store(mark, Sugg::Resources(possible), Reason::Error(e));
|
||||
None
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
state.store(
|
||||
mark,
|
||||
Sugg::Resources(possible),
|
||||
Reason::Delayed("argument.id.invalid", Vec::new()),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn predicate_grammar() -> Grammar<IV> {
|
||||
let mut g: Grammar<IV> = Grammar::new();
|
||||
let id = g.put_custom("id", id_rule);
|
||||
let ty = g.named("type");
|
||||
let conditions = g.named("conditions");
|
||||
let ty2 = g.named("type");
|
||||
g.put_term(
|
||||
"top",
|
||||
alt(vec![
|
||||
seq(vec![ty, ch('['), Term::Cut, opt(conditions), ch(']')]),
|
||||
ty2,
|
||||
]),
|
||||
|s| {
|
||||
let mut out = Vec::new();
|
||||
if let Some(t) = s.scope.get("type") {
|
||||
out.push(t);
|
||||
}
|
||||
if let Some(IV::List(c)) = s.scope.get("conditions") {
|
||||
out.extend(c);
|
||||
}
|
||||
Some(IV::List(out))
|
||||
},
|
||||
);
|
||||
let element = g.named("element_type");
|
||||
let tag = g.named("tag_type");
|
||||
let any = g.named("any_type");
|
||||
g.put_term(
|
||||
"type",
|
||||
alt(vec![element, seq(vec![ch('#'), Term::Cut, tag]), any]),
|
||||
|s| {
|
||||
Some(IV::Type(
|
||||
match s.scope.get_any(&["element_type", "tag_type"]) {
|
||||
Some(IV::Elem(t)) => Some(t),
|
||||
_ => None,
|
||||
},
|
||||
))
|
||||
},
|
||||
);
|
||||
g.put_term("any_type", ch('*'), |_| Some(IV::Unit));
|
||||
g.put_custom("element_type", move |s| {
|
||||
let r = reg(s);
|
||||
let items = Rc::new(r.ids("minecraft:item").to_vec());
|
||||
lookup(s, id, items, &|id, reader| {
|
||||
if r.ids("minecraft:item").iter().any(|i| i == id) {
|
||||
Ok(IV::Elem(TypeRes::Item(id.to_owned())))
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"argument.item.id.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
))
|
||||
}
|
||||
})
|
||||
});
|
||||
g.put_custom("tag_type", move |s| {
|
||||
let r = reg(s);
|
||||
let tags = Rc::new(r.tags("minecraft:item").to_vec());
|
||||
lookup(s, id, tags, &|id, reader| {
|
||||
if r.tags("minecraft:item").iter().any(|i| i == id) {
|
||||
Ok(IV::Elem(TypeRes::Tag(id.to_owned())))
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"arguments.item.tag.unknown",
|
||||
&[&id],
|
||||
reader,
|
||||
))
|
||||
}
|
||||
})
|
||||
});
|
||||
let alternatives = g.named("alternatives");
|
||||
let rest = g.named("conditions");
|
||||
g.put_term(
|
||||
"conditions",
|
||||
seq(vec![alternatives, opt(seq(vec![ch(','), rest]))]),
|
||||
|s| {
|
||||
let mut out = vec![IV::Test];
|
||||
if let Some(IV::List(c)) = s.scope.get("conditions") {
|
||||
out.extend(c);
|
||||
}
|
||||
Some(IV::List(out))
|
||||
},
|
||||
);
|
||||
let term = g.named("term");
|
||||
let rest = g.named("alternatives");
|
||||
g.put_term(
|
||||
"alternatives",
|
||||
seq(vec![term, opt(seq(vec![ch('|'), rest]))]),
|
||||
|s| {
|
||||
let mut out = vec![s.scope.get("term").unwrap_or(IV::Test)];
|
||||
if let Some(IV::List(c)) = s.scope.get("alternatives") {
|
||||
out.extend(c);
|
||||
}
|
||||
Some(IV::List(out))
|
||||
},
|
||||
);
|
||||
let test = g.named("test");
|
||||
let negation = g.named("negation");
|
||||
g.put_term("term", alt(vec![test, seq(vec![ch('!'), negation])]), |s| {
|
||||
s.scope.get_any(&["test", "negation"])
|
||||
});
|
||||
let test = g.named("test");
|
||||
g.put_term("negation", test, |_| Some(IV::Test));
|
||||
let comp = g.named("component_type");
|
||||
let tag_a = g.named("tag");
|
||||
let pred = g.named("predicate_type");
|
||||
let tag_b = g.named("tag");
|
||||
let comp2 = g.named("component_type");
|
||||
g.put_term(
|
||||
"test",
|
||||
alt(vec![
|
||||
seq(vec![comp, ch('='), Term::Cut, tag_a]),
|
||||
seq(vec![pred, ch('~'), Term::Cut, tag_b]),
|
||||
comp2,
|
||||
]),
|
||||
|s| {
|
||||
let value = match s.scope.get("tag") {
|
||||
Some(IV::Tag(t)) => Some(t),
|
||||
_ => None,
|
||||
};
|
||||
let reader = s.reader();
|
||||
let result = if let Some(IV::Pred(p)) = s.scope.get("predicate_type") {
|
||||
decode_predicate(&p, value.as_ref().unwrap_or(&Tag::End)).map_err(|m| {
|
||||
CommandError::tr_at("arguments.item.predicate.malformed", &[&p, &m], &reader)
|
||||
})
|
||||
} else if let (Some(IV::Comp(c)), Some(v)) = (s.scope.get("component_type"), value) {
|
||||
decode_component(&c, &v).map_err(|m| {
|
||||
CommandError::tr_at("arguments.item.component.malformed", &[&c, &m], &reader)
|
||||
})
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
match result {
|
||||
Ok(()) => Some(IV::Test),
|
||||
Err(e) => {
|
||||
s.store(s.cursor, Sugg::Empty, Reason::Error(e));
|
||||
None
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
g.put_custom("component_type", move |s| {
|
||||
let r = reg(s);
|
||||
let mut list = vec!["minecraft:count".to_owned()];
|
||||
list.extend(r.persistent_components.iter().cloned());
|
||||
lookup(s, id, Rc::new(list), &|id, reader| {
|
||||
if id == "minecraft:count" {
|
||||
return Ok(IV::Comp(id.to_owned()));
|
||||
}
|
||||
let known = r
|
||||
.ids("minecraft:data_component_type")
|
||||
.iter()
|
||||
.any(|c| c == id);
|
||||
if known && r.persistent_components.iter().any(|c| c == id) {
|
||||
Ok(IV::Comp(id.to_owned()))
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"arguments.item.component.unknown",
|
||||
&[&id],
|
||||
reader,
|
||||
))
|
||||
}
|
||||
})
|
||||
});
|
||||
g.put_custom("predicate_type", move |s| {
|
||||
let r = reg(s);
|
||||
let mut list = vec!["minecraft:count".to_owned()];
|
||||
list.extend(
|
||||
r.ids("minecraft:data_component_predicate_type")
|
||||
.iter()
|
||||
.cloned(),
|
||||
);
|
||||
lookup(s, id, Rc::new(list), &|id, reader| {
|
||||
if id == "minecraft:count"
|
||||
|| r.ids("minecraft:data_component_predicate_type")
|
||||
.iter()
|
||||
.any(|c| c == id)
|
||||
{
|
||||
return Ok(IV::Pred(id.to_owned()));
|
||||
}
|
||||
if r.ids("minecraft:data_component_type")
|
||||
.iter()
|
||||
.any(|c| c == id)
|
||||
{
|
||||
// A component existence predicate (decodes Unit).
|
||||
return Ok(IV::Pred(format!("exists:{id}")));
|
||||
}
|
||||
Err(CommandError::tr_at(
|
||||
"arguments.item.predicate.unknown",
|
||||
&[&id],
|
||||
reader,
|
||||
))
|
||||
})
|
||||
});
|
||||
g.put_custom("tag", |s| super::snbt::rule_in(s, IV::Tag));
|
||||
g.top = g.id("top");
|
||||
g
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PREDICATE: Grammar<IV> = predicate_grammar();
|
||||
}
|
||||
/// ItemPredicateArgument.parse.
|
||||
pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemInput> {
|
||||
let start = reader.cursor;
|
||||
let result = PREDICATE.with(|g| g.parse_for_commands_with(reader, Some(reg)))?;
|
||||
let IV::List(items) = result else {
|
||||
return Err(CommandError::tr_at("argument.id.invalid", &[], reader));
|
||||
};
|
||||
let text = &reader.string[start..reader.cursor];
|
||||
let (id, tag, any) = match items.first() {
|
||||
Some(IV::Type(Some(TypeRes::Item(i)))) => (i.clone(), false, false),
|
||||
Some(IV::Type(Some(TypeRes::Tag(t)))) => (t.clone(), true, false),
|
||||
_ => ("*".to_owned(), false, true),
|
||||
};
|
||||
let components = text.find('[').map(|i| text[i..].to_owned());
|
||||
Ok(ItemInput {
|
||||
id,
|
||||
tag,
|
||||
any,
|
||||
components,
|
||||
})
|
||||
}
|
||||
/// ItemPredicateArgument.listSuggestions.
|
||||
pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
|
||||
PREDICATE.with(|g| g.parse_for_suggestions_with(builder, Some(reg)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::decode_component;
|
||||
|
||||
fn check(snbt: &str) -> Result<(), String> {
|
||||
let tag = horizon_world::nbt::parse_snbt(snbt).expect("snbt").0;
|
||||
decode_component("minecraft:block_entity_data", &tag)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_entity_data_needs_a_known_type() {
|
||||
assert_eq!(check("{id:\"chest\",Lock:1}"), Ok(()));
|
||||
assert_eq!(
|
||||
check("{Command:\"say\"}"),
|
||||
Err("Expected 'id' field in {Command:\"say\"}".into())
|
||||
);
|
||||
assert_eq!(
|
||||
check("{id:\"minecraft:stone\"}"),
|
||||
Err("Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: minecraft:stone".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,403 +0,0 @@
|
||||
//! The command tree a server sends (ClientboundCommandsPacket) as a
|
||||
//! dispatcher the chat parses, colours and completes with
|
||||
//! (ClientPacketListener.handleCommands).
|
||||
//!
|
||||
//! The packet holds each argument's parser and its network properties. A
|
||||
//! node the client's own vanilla tree has at the same path takes that node's
|
||||
//! argument type and suggestion provider (the parsers' suggestion lists and
|
||||
//! the custom providers are the same code on both sides); any other node
|
||||
//! (another server's or a mod's) gets the type its parser and properties
|
||||
//! describe.
|
||||
use super::{ArgType, Dispatcher, Node, NodeKind, Suggests};
|
||||
use horizon_protocol::packets::play::{ARGUMENT_TYPES, ArgumentProperties, Commands};
|
||||
use std::{
|
||||
collections::{HashSet, VecDeque},
|
||||
sync::{Mutex, OnceLock},
|
||||
};
|
||||
|
||||
/// The command id of every executable node of a server's tree: the chat
|
||||
/// sends the command, the server runs it.
|
||||
pub const SERVER_COMMAND: &str = "server";
|
||||
|
||||
/// The dispatcher for a server's tree. `local` is the client's own tree
|
||||
/// (vanilla's), whose matching nodes lend their types and providers.
|
||||
pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher {
|
||||
let count = packet.nodes.len();
|
||||
let root = usize::try_from(packet.root)
|
||||
.ok()
|
||||
.filter(|&r| r < count)
|
||||
.unwrap_or(0);
|
||||
// The packet's root becomes node 0, the others follow in packet order.
|
||||
let index = |i: usize| -> usize {
|
||||
if i == root {
|
||||
0
|
||||
} else if i < root {
|
||||
i + 1
|
||||
} else {
|
||||
i
|
||||
}
|
||||
};
|
||||
let valid = |c: &i32| usize::try_from(*c).ok().filter(|&c| c < count);
|
||||
// The local node at the same path, found breadth first from the roots
|
||||
// along children (redirects are not paths of their own).
|
||||
let mut matched: Vec<Option<usize>> = vec![None; count];
|
||||
matched[root] = Some(0);
|
||||
let mut queue = VecDeque::from([root]);
|
||||
let mut seen = HashSet::from([root]);
|
||||
while let Some(n) = queue.pop_front() {
|
||||
for c in packet.nodes[n].children.iter().filter_map(valid) {
|
||||
if !seen.insert(c) {
|
||||
continue;
|
||||
}
|
||||
let node = &packet.nodes[c];
|
||||
matched[c] = matched[n].and_then(|l| {
|
||||
local.nodes[l].children.iter().copied().find(|&lc| {
|
||||
let ln = &local.nodes[lc];
|
||||
ln.name() == node.name
|
||||
&& matches!(
|
||||
(&ln.kind, node.kind),
|
||||
(NodeKind::Literal(_), 1) | (NodeKind::Argument { .. }, 2)
|
||||
)
|
||||
})
|
||||
});
|
||||
queue.push_back(c);
|
||||
}
|
||||
}
|
||||
let mut nodes = vec![None; count];
|
||||
for (i, node) in packet.nodes.iter().enumerate() {
|
||||
let local_node = matched[i].map(|l| &local.nodes[l]);
|
||||
let kind = match node.kind {
|
||||
1 => NodeKind::Literal(node.name.clone()),
|
||||
2 => {
|
||||
let ty = match local_node.map(|l| &l.kind) {
|
||||
Some(NodeKind::Argument { ty, .. }) => ty.clone(),
|
||||
_ => node
|
||||
.parser
|
||||
.as_ref()
|
||||
.map_or(ArgType::Word, |(id, props)| argument_type(*id, props)),
|
||||
};
|
||||
NodeKind::Argument {
|
||||
name: node.name.clone(),
|
||||
ty,
|
||||
}
|
||||
}
|
||||
_ => NodeKind::Root,
|
||||
};
|
||||
// The server's providers, as the client knows them
|
||||
// (ArgumentNodeStub.build): its own custom ones arrive as `ask_server`.
|
||||
let suggests = node.suggestions.as_deref().and_then(provider);
|
||||
nodes[index(i)] = Some(Node {
|
||||
kind: if i == root { NodeKind::Root } else { kind },
|
||||
children: node.children.iter().filter_map(valid).map(index).collect(),
|
||||
command: node.executable.then_some(SERVER_COMMAND),
|
||||
redirect: node.redirect.as_ref().and_then(valid).map(index),
|
||||
// The server sent only what the player may use.
|
||||
permission: 0,
|
||||
suggests,
|
||||
});
|
||||
}
|
||||
let mut d = Dispatcher::new();
|
||||
if count > 0 {
|
||||
d.nodes = nodes.into_iter().flatten().collect();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// SuggestionProviders by id (`SuggestionProviders.getProvider`).
|
||||
fn provider(id: &str) -> Option<Suggests> {
|
||||
match id {
|
||||
"minecraft:ask_server" => Some(Suggests::AskServer),
|
||||
"minecraft:summonable_entities" => Some(Suggests::SummonableEntities),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A registry name kept for the life of the game (argument types hold
|
||||
/// `&'static str`): each distinct name is stored once.
|
||||
fn intern(name: &str) -> &'static str {
|
||||
static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
|
||||
let mut names = NAMES
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(&n) = names.get(name) {
|
||||
return n;
|
||||
}
|
||||
let n: &'static str = Box::leak(name.to_owned().into_boxed_str());
|
||||
names.insert(n);
|
||||
n
|
||||
}
|
||||
|
||||
/// The argument type a parser and its properties describe
|
||||
/// (ArgumentTypeInfo.Template.instantiate).
|
||||
pub fn argument_type(id: i32, props: &[u8]) -> ArgType {
|
||||
let Some(name) = usize::try_from(id).ok().and_then(|i| ARGUMENT_TYPES.get(i)) else {
|
||||
return ArgType::Word;
|
||||
};
|
||||
let p = ArgumentProperties::decode(id, props).unwrap_or(ArgumentProperties::None);
|
||||
let registry = || match &p {
|
||||
ArgumentProperties::Registry(r) => intern(r),
|
||||
_ => "",
|
||||
};
|
||||
match *name {
|
||||
"brigadier:bool" => ArgType::Bool,
|
||||
"brigadier:integer" => match p {
|
||||
ArgumentProperties::Integer { min, max } => ArgType::Integer {
|
||||
min: min.unwrap_or(i32::MIN),
|
||||
max: max.unwrap_or(i32::MAX),
|
||||
},
|
||||
_ => ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
},
|
||||
// No long type of its own: a double over the same bounds reads
|
||||
// the same digits.
|
||||
"brigadier:long" => match p {
|
||||
ArgumentProperties::Long { min, max } => ArgType::Double {
|
||||
min: min.map_or(f64::MIN, |v| v as f64),
|
||||
max: max.map_or(f64::MAX, |v| v as f64),
|
||||
},
|
||||
_ => ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
},
|
||||
"brigadier:float" => match p {
|
||||
ArgumentProperties::Float { min, max } => ArgType::Float {
|
||||
min: min.unwrap_or(f32::MIN),
|
||||
max: max.unwrap_or(f32::MAX),
|
||||
},
|
||||
_ => ArgType::Float {
|
||||
min: f32::MIN,
|
||||
max: f32::MAX,
|
||||
},
|
||||
},
|
||||
"brigadier:double" => match p {
|
||||
ArgumentProperties::Double { min, max } => ArgType::Double {
|
||||
min: min.unwrap_or(f64::MIN),
|
||||
max: max.unwrap_or(f64::MAX),
|
||||
},
|
||||
_ => ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
},
|
||||
"brigadier:string" => match p {
|
||||
ArgumentProperties::String(1) => ArgType::Str,
|
||||
ArgumentProperties::String(2) => ArgType::Greedy,
|
||||
_ => ArgType::Word,
|
||||
},
|
||||
"minecraft:entity" => match p {
|
||||
ArgumentProperties::Entity {
|
||||
single,
|
||||
players_only,
|
||||
} => ArgType::Entity {
|
||||
single,
|
||||
players: players_only,
|
||||
},
|
||||
_ => ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
},
|
||||
},
|
||||
"minecraft:game_profile" => ArgType::GameProfile,
|
||||
"minecraft:block_pos" => ArgType::BlockPos,
|
||||
"minecraft:column_pos" => ArgType::ColumnPos,
|
||||
"minecraft:vec3" => ArgType::Vec3 { center: true },
|
||||
"minecraft:vec2" => ArgType::Vec2,
|
||||
"minecraft:block_state" => ArgType::BlockState,
|
||||
"minecraft:block_predicate" => ArgType::BlockPredicate,
|
||||
"minecraft:item_stack" => ArgType::Item,
|
||||
"minecraft:item_predicate" => ArgType::ItemPredicate,
|
||||
"minecraft:team_color" => ArgType::TeamColor,
|
||||
"minecraft:hex_color" => ArgType::HexColor,
|
||||
"minecraft:component" => ArgType::Component,
|
||||
"minecraft:style" => ArgType::Style,
|
||||
"minecraft:message" => ArgType::Message,
|
||||
"minecraft:nbt_compound_tag" => ArgType::Nbt,
|
||||
"minecraft:nbt_tag" => ArgType::NbtTag,
|
||||
"minecraft:nbt_path" => ArgType::NbtPath,
|
||||
"minecraft:objective" => ArgType::Objective,
|
||||
"minecraft:objective_criteria" => ArgType::Criteria,
|
||||
"minecraft:operation" => ArgType::Operation,
|
||||
"minecraft:particle" => ArgType::Particle,
|
||||
"minecraft:angle" => ArgType::Angle,
|
||||
"minecraft:rotation" => ArgType::Rotation,
|
||||
"minecraft:scoreboard_slot" => ArgType::ScoreboardSlot,
|
||||
"minecraft:score_holder" => ArgType::ScoreHolder {
|
||||
multiple: matches!(p, ArgumentProperties::ScoreHolder { multiple: true }),
|
||||
},
|
||||
"minecraft:swizzle" => ArgType::Swizzle,
|
||||
"minecraft:team" => ArgType::Team,
|
||||
"minecraft:item_slot" => ArgType::Slot,
|
||||
"minecraft:item_slots" => ArgType::Slots,
|
||||
"minecraft:resource_location" => ArgType::Id("none"),
|
||||
"minecraft:function" => ArgType::Function,
|
||||
"minecraft:entity_anchor" => ArgType::Anchor,
|
||||
"minecraft:int_range" => ArgType::IntRange,
|
||||
"minecraft:float_range" => ArgType::FloatRange,
|
||||
"minecraft:dimension" => ArgType::Dimension,
|
||||
"minecraft:gamemode" => ArgType::GameMode,
|
||||
"minecraft:time" => ArgType::Time {
|
||||
min: match p {
|
||||
ArgumentProperties::Time { min } => min,
|
||||
_ => 0,
|
||||
},
|
||||
},
|
||||
"minecraft:resource_or_tag" => ArgType::ResOrTag(registry()),
|
||||
"minecraft:resource_or_tag_key" => ArgType::ResOrTagKey(registry()),
|
||||
"minecraft:resource" => ArgType::Res(registry()),
|
||||
"minecraft:resource_key" => ArgType::ResKey(registry()),
|
||||
"minecraft:resource_selector" => ArgType::ResourceSelector(registry()),
|
||||
"minecraft:template_mirror" => ArgType::Enum(&["none", "front_back", "left_right"]),
|
||||
"minecraft:template_rotation" => {
|
||||
ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"])
|
||||
}
|
||||
"minecraft:heightmap" => ArgType::Enum(&[
|
||||
"world_surface",
|
||||
"motion_blocking",
|
||||
"motion_blocking_no_leaves",
|
||||
"ocean_floor",
|
||||
]),
|
||||
"minecraft:swing_animation" => ArgType::Enum(&["none", "whack", "stab"]),
|
||||
"minecraft:loot_table" => ArgType::ResourceOrId("minecraft:loot_table"),
|
||||
"minecraft:loot_predicate" => ArgType::ResourceOrId("minecraft:predicate"),
|
||||
"minecraft:loot_modifier" => ArgType::ResourceOrId("minecraft:item_modifier"),
|
||||
"minecraft:context_float_provider" => {
|
||||
ArgType::ResourceOrId("minecraft:context_float_provider")
|
||||
}
|
||||
"minecraft:context_int_provider" => ArgType::ResourceOrId("minecraft:context_int_provider"),
|
||||
"minecraft:slot_source" => ArgType::SlotSource,
|
||||
"minecraft:dialog" => ArgType::ResourceOrId("minecraft:dialog"),
|
||||
"minecraft:feature" => ArgType::ResourceOrId("minecraft:worldgen/feature"),
|
||||
"minecraft:uuid" => ArgType::Uuid,
|
||||
_ => ArgType::Word,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_protocol::{
|
||||
buf::{Codec, Reader, Writer},
|
||||
packets::play::CommandNode,
|
||||
};
|
||||
|
||||
fn literal(name: &str, children: Vec<i32>, executable: bool) -> CommandNode {
|
||||
CommandNode {
|
||||
kind: 1,
|
||||
executable,
|
||||
restricted: false,
|
||||
children,
|
||||
redirect: None,
|
||||
name: name.into(),
|
||||
parser: None,
|
||||
suggestions: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn argument(name: &str, parser: &str, props: Vec<u8>, executable: bool) -> CommandNode {
|
||||
let id = ARGUMENT_TYPES.iter().position(|p| *p == parser).unwrap() as i32;
|
||||
CommandNode {
|
||||
kind: 2,
|
||||
executable,
|
||||
restricted: false,
|
||||
children: Vec::new(),
|
||||
redirect: None,
|
||||
name: name.into(),
|
||||
parser: Some((id, props)),
|
||||
suggestions: Some("minecraft:ask_server".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree with the root last (as vanilla's numbering need not put it
|
||||
/// first), a vanilla command and one the client does not know.
|
||||
fn packet() -> Commands {
|
||||
let mut range = Writer::new();
|
||||
range.u8(3);
|
||||
range.i32(1);
|
||||
range.i32(64);
|
||||
Commands {
|
||||
nodes: vec![
|
||||
literal("give", vec![2], false),
|
||||
literal("warp", vec![3], false),
|
||||
argument("targets", "minecraft:entity", vec![2], false),
|
||||
argument("count", "brigadier:integer", range.data, true),
|
||||
CommandNode {
|
||||
kind: 0,
|
||||
executable: false,
|
||||
restricted: false,
|
||||
children: vec![0, 1],
|
||||
redirect: None,
|
||||
name: String::new(),
|
||||
parser: None,
|
||||
suggestions: None,
|
||||
},
|
||||
],
|
||||
root: 4,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argument_nodes_round_trip() {
|
||||
let p = packet();
|
||||
let mut w = Writer::new();
|
||||
Commands::write(&p, &mut w);
|
||||
let back = Commands::read(&mut Reader::new(&w.data)).unwrap();
|
||||
assert_eq!(back, p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_tree_becomes_a_dispatcher() {
|
||||
let local = super::super::vanilla::dispatcher();
|
||||
let d = from_packet(&packet(), local);
|
||||
assert!(matches!(d.nodes[0].kind, NodeKind::Root));
|
||||
let warp = d.find("warp").expect("warp");
|
||||
let count = d.nodes[warp].children[0];
|
||||
match &d.nodes[count].kind {
|
||||
NodeKind::Argument {
|
||||
ty: ArgType::Integer { min, max },
|
||||
..
|
||||
} => assert_eq!((*min, *max), (1, 64)),
|
||||
other => panic!("count is {other:?}"),
|
||||
}
|
||||
assert_eq!(d.nodes[count].command, Some(SERVER_COMMAND));
|
||||
// `give <targets>` is vanilla's: it keeps the client's type.
|
||||
let give = d.find("give").expect("give");
|
||||
let targets = d.nodes[give].children[0];
|
||||
assert!(matches!(
|
||||
d.nodes[targets].kind,
|
||||
NodeKind::Argument {
|
||||
ty: ArgType::Entity {
|
||||
single: false,
|
||||
players: true
|
||||
},
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_argument_type_decodes() {
|
||||
for (id, name) in ARGUMENT_TYPES.iter().enumerate() {
|
||||
let mut w = Writer::new();
|
||||
match *name {
|
||||
"brigadier:integer" | "brigadier:long" | "brigadier:float" | "brigadier:double" => {
|
||||
w.u8(0)
|
||||
}
|
||||
"brigadier:string" => w.varint(2),
|
||||
"minecraft:entity" | "minecraft:score_holder" => w.u8(1),
|
||||
"minecraft:time" => w.i32(0),
|
||||
n if n.starts_with("minecraft:resource") && n != "minecraft:resource_location" => {
|
||||
w.string("minecraft:item")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut r = Reader::new(&w.data);
|
||||
ArgumentProperties::read(&mut r, id as i32).unwrap();
|
||||
assert_eq!(r.remaining(), 0, "{name}");
|
||||
let _ = argument_type(id as i32, &w.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
//! A port of vanilla's packrat parsing library (`net.minecraft.util.parsing.packrat`):
|
||||
//! terms, named rules with per-position memoisation, scopes with frames,
|
||||
//! cuts, and the "longest only" error collector whose entries become both
|
||||
//! the parse error and the completion suggestions.
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder, args};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
pub type Atom = &'static str;
|
||||
pub type RuleId = usize;
|
||||
|
||||
/// A value a rule produces (an element of `Scope`).
|
||||
pub trait Value: Clone {
|
||||
fn list(items: Vec<Self>) -> Self;
|
||||
}
|
||||
|
||||
/// Why a term failed (DelayedException or a ready exception).
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Reason {
|
||||
/// A translatable exception created at the error cursor.
|
||||
Delayed(&'static str, Vec<String>),
|
||||
/// An exception with its own cursor.
|
||||
Error(CommandError),
|
||||
}
|
||||
|
||||
/// SuggestionSupplier.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Sugg {
|
||||
Empty,
|
||||
Values(Rc<Vec<String>>),
|
||||
/// ResourceSuggestion: ids completed with suggestResource.
|
||||
Resources(Rc<Vec<String>>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Key {
|
||||
Frame(usize),
|
||||
Atom(Atom),
|
||||
}
|
||||
|
||||
/// Scope: a stack of frames of atom values.
|
||||
pub struct Scope<V> {
|
||||
stack: Vec<(Key, Option<V>)>,
|
||||
top_entry: usize,
|
||||
top_marker: usize,
|
||||
}
|
||||
impl<V: Clone> Scope<V> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
stack: vec![(Key::Frame(0), None)],
|
||||
top_entry: 0,
|
||||
top_marker: 0,
|
||||
}
|
||||
}
|
||||
fn set(&mut self, i: usize, key: Key, value: Option<V>) {
|
||||
while self.stack.len() <= i {
|
||||
self.stack.push((Key::Frame(0), None));
|
||||
}
|
||||
self.stack[i] = (key, value);
|
||||
}
|
||||
fn value_index(&self, atoms: &[Atom]) -> Option<usize> {
|
||||
let mut i = self.top_entry;
|
||||
while i > self.top_marker {
|
||||
if let Key::Atom(a) = self.stack[i].0
|
||||
&& atoms.contains(&a)
|
||||
{
|
||||
return Some(i);
|
||||
}
|
||||
i -= 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
fn setup_new_frame(&mut self) {
|
||||
self.top_entry += 1;
|
||||
let prev = self.top_marker;
|
||||
self.set(self.top_entry, Key::Frame(prev), None);
|
||||
self.top_marker = self.top_entry;
|
||||
}
|
||||
fn previous_marker(&self, marker: usize) -> usize {
|
||||
match self.stack[marker].0 {
|
||||
Key::Frame(p) => p,
|
||||
Key::Atom(_) => 0,
|
||||
}
|
||||
}
|
||||
pub fn push_frame(&mut self) {
|
||||
self.setup_new_frame();
|
||||
}
|
||||
pub fn pop_frame(&mut self) {
|
||||
let marker = self.top_marker;
|
||||
self.top_entry = marker - 1;
|
||||
self.top_marker = self.previous_marker(marker);
|
||||
}
|
||||
fn split_frame(&mut self) {
|
||||
let current = self.top_marker;
|
||||
let n = self.top_entry - self.top_marker;
|
||||
self.setup_new_frame();
|
||||
let mut target = self.top_entry;
|
||||
for source in current + 1..current + 1 + n {
|
||||
target += 1;
|
||||
let key = self.stack[source].0;
|
||||
self.set(target, key, None);
|
||||
}
|
||||
self.top_entry = target;
|
||||
}
|
||||
fn clear_frame_values(&mut self) {
|
||||
let mut i = self.top_entry;
|
||||
while i > self.top_marker {
|
||||
self.stack[i].1 = None;
|
||||
i -= 1;
|
||||
}
|
||||
}
|
||||
fn merge_frame(&mut self) {
|
||||
let previous_marker = self.previous_marker(self.top_marker);
|
||||
let mut previous = previous_marker;
|
||||
let mut current = self.top_marker;
|
||||
while current < self.top_entry {
|
||||
previous += 1;
|
||||
current += 1;
|
||||
let (new_key, new_value) = self.stack[current].clone();
|
||||
let old_key = self.stack.get(previous).map(|e| e.0);
|
||||
if old_key != Some(new_key) {
|
||||
self.set(previous, new_key, new_value);
|
||||
} else if new_value.is_some() {
|
||||
self.stack[previous].1 = new_value;
|
||||
}
|
||||
}
|
||||
self.top_entry = previous;
|
||||
self.top_marker = previous_marker;
|
||||
}
|
||||
pub fn put(&mut self, atom: Atom, value: V) {
|
||||
match self.value_index(&[atom]) {
|
||||
Some(i) => self.stack[i].1 = Some(value),
|
||||
None => {
|
||||
self.top_entry += 1;
|
||||
self.set(self.top_entry, Key::Atom(atom), Some(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn get(&self, atom: Atom) -> Option<V> {
|
||||
self.value_index(&[atom])
|
||||
.and_then(|i| self.stack[i].1.clone())
|
||||
}
|
||||
/// Scope.getAny: the newest of several atoms.
|
||||
pub fn get_any(&self, atoms: &[Atom]) -> Option<V> {
|
||||
self.value_index(atoms)
|
||||
.and_then(|i| self.stack[i].1.clone())
|
||||
}
|
||||
/// Whether the atom has an entry (even a null one).
|
||||
pub fn has(&self, atom: Atom) -> bool {
|
||||
self.value_index(&[atom]).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A rule: a term with an action, or hand-written parsing.
|
||||
pub enum Rule<V> {
|
||||
Term(Term<V>, Rc<dyn Fn(&mut State<V>) -> Option<V>>),
|
||||
Custom(Rc<dyn Fn(&mut State<V>) -> Option<V>>),
|
||||
}
|
||||
|
||||
pub enum Term<V> {
|
||||
Seq(Vec<Term<V>>),
|
||||
Alt(Vec<Term<V>>),
|
||||
Opt(Box<Term<V>>),
|
||||
Repeated {
|
||||
rule: RuleId,
|
||||
list: Atom,
|
||||
min: usize,
|
||||
},
|
||||
RepeatedSep {
|
||||
rule: RuleId,
|
||||
list: Atom,
|
||||
sep: Box<Term<V>>,
|
||||
min: usize,
|
||||
trailing: bool,
|
||||
},
|
||||
Look(Box<Term<V>>, bool),
|
||||
Marker(Atom, V),
|
||||
Cut,
|
||||
Empty,
|
||||
Fail(Reason),
|
||||
Named {
|
||||
rule: RuleId,
|
||||
store: Atom,
|
||||
},
|
||||
/// StringReaderTerms.TerminalCharacters: one of `values` (or `accept`).
|
||||
Chars {
|
||||
values: Vec<char>,
|
||||
accept: Option<fn(char) -> bool>,
|
||||
},
|
||||
/// StringReaderTerms.TerminalWord.
|
||||
Word(String),
|
||||
}
|
||||
|
||||
pub fn seq<V>(t: Vec<Term<V>>) -> Term<V> {
|
||||
Term::Seq(t)
|
||||
}
|
||||
pub fn alt<V>(t: Vec<Term<V>>) -> Term<V> {
|
||||
Term::Alt(t)
|
||||
}
|
||||
pub fn opt<V>(t: Term<V>) -> Term<V> {
|
||||
Term::Opt(Box::new(t))
|
||||
}
|
||||
pub fn ch<V>(c: char) -> Term<V> {
|
||||
Term::Chars {
|
||||
values: vec![c],
|
||||
accept: None,
|
||||
}
|
||||
}
|
||||
pub fn chs<V>(a: char, b: char) -> Term<V> {
|
||||
Term::Chars {
|
||||
values: vec![a, b],
|
||||
accept: None,
|
||||
}
|
||||
}
|
||||
pub fn look<V>(t: Term<V>) -> Term<V> {
|
||||
Term::Look(Box::new(t), true)
|
||||
}
|
||||
|
||||
/// Dictionary: named rules, with forward references.
|
||||
pub struct Grammar<V> {
|
||||
names: Vec<Atom>,
|
||||
rules: Vec<Option<Rule<V>>>,
|
||||
pub top: RuleId,
|
||||
}
|
||||
impl<V: Value> Default for Grammar<V> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl<V: Value> Grammar<V> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
names: Vec::new(),
|
||||
rules: Vec::new(),
|
||||
top: 0,
|
||||
}
|
||||
}
|
||||
/// Dictionary.forward / getOrCreateEntry.
|
||||
pub fn id(&mut self, name: Atom) -> RuleId {
|
||||
if let Some(i) = self.names.iter().position(|n| *n == name) {
|
||||
return i;
|
||||
}
|
||||
self.names.push(name);
|
||||
self.rules.push(None);
|
||||
self.names.len() - 1
|
||||
}
|
||||
pub fn put(&mut self, name: Atom, rule: Rule<V>) -> RuleId {
|
||||
let id = self.id(name);
|
||||
assert!(self.rules[id].is_none(), "Trying to override rule: {name}");
|
||||
self.rules[id] = Some(rule);
|
||||
id
|
||||
}
|
||||
pub fn put_term(
|
||||
&mut self,
|
||||
name: Atom,
|
||||
term: Term<V>,
|
||||
action: impl Fn(&mut State<V>) -> Option<V> + 'static,
|
||||
) -> RuleId {
|
||||
self.put(name, Rule::Term(term, Rc::new(action)))
|
||||
}
|
||||
pub fn put_custom(
|
||||
&mut self,
|
||||
name: Atom,
|
||||
f: impl Fn(&mut State<V>) -> Option<V> + 'static,
|
||||
) -> RuleId {
|
||||
self.put(name, Rule::Custom(Rc::new(f)))
|
||||
}
|
||||
/// Dictionary.named: parse the rule and store it under its own name.
|
||||
pub fn named(&mut self, name: Atom) -> Term<V> {
|
||||
let rule = self.id(name);
|
||||
Term::Named { rule, store: name }
|
||||
}
|
||||
/// Dictionary.namedWithAlias.
|
||||
pub fn named_as(&mut self, name: Atom, store: Atom) -> Term<V> {
|
||||
let rule = self.id(name);
|
||||
Term::Named { rule, store }
|
||||
}
|
||||
|
||||
/// Grammar.parseForCommands: parse at the reader's cursor; on failure
|
||||
/// the first error stored at the furthest position.
|
||||
pub fn parse_for_commands(&self, reader: &mut Reader) -> CmdResult<V> {
|
||||
self.parse_for_commands_with(reader, None)
|
||||
}
|
||||
/// parse_for_commands with a context value the rules can read (`State::ctx`).
|
||||
pub fn parse_for_commands_with(
|
||||
&self,
|
||||
reader: &mut Reader,
|
||||
ctx: Option<&dyn std::any::Any>,
|
||||
) -> CmdResult<V> {
|
||||
let mut state = State::new(self, reader.string, reader.cursor);
|
||||
state.ctx = ctx;
|
||||
let result = state.parse_top();
|
||||
reader.cursor = state.cursor;
|
||||
match result {
|
||||
Some(v) => Ok(v),
|
||||
None => Err(state.first_error()),
|
||||
}
|
||||
}
|
||||
/// Grammar.parseForSuggestions.
|
||||
pub fn parse_for_suggestions(&self, builder: &mut SuggestionsBuilder) {
|
||||
self.parse_for_suggestions_with(builder, None)
|
||||
}
|
||||
pub fn parse_for_suggestions_with(
|
||||
&self,
|
||||
builder: &mut SuggestionsBuilder,
|
||||
ctx: Option<&dyn std::any::Any>,
|
||||
) {
|
||||
let mut state = State::new(self, builder.input, builder.start);
|
||||
state.ctx = ctx;
|
||||
state.parse_top();
|
||||
if state.errors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut offset = builder.offset(state.last_cursor.max(0) as usize);
|
||||
for (sugg, _) in &state.errors {
|
||||
match sugg {
|
||||
Sugg::Empty => {}
|
||||
Sugg::Values(v) => offset.suggest_matching(v.iter().map(String::as_str)),
|
||||
Sugg::Resources(ids) => args::suggest_resources(&mut offset, ids.iter(), ""),
|
||||
}
|
||||
}
|
||||
builder.add(offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// CachedParseState over a string (StringReaderParserState) with a
|
||||
/// LongestOnly error collector.
|
||||
pub struct State<'g, V> {
|
||||
grammar: &'g Grammar<V>,
|
||||
pub input: &'g str,
|
||||
pub cursor: usize,
|
||||
cache: HashMap<(usize, RuleId), Option<(V, usize)>>,
|
||||
pub scope: Scope<V>,
|
||||
controls: Vec<bool>,
|
||||
errors: Vec<(Sugg, Reason)>,
|
||||
last_cursor: isize,
|
||||
/// Context for the rules (e.g. the registries a lookup checks).
|
||||
pub ctx: Option<&'g dyn std::any::Any>,
|
||||
}
|
||||
const UNBOUND: usize = usize::MAX;
|
||||
impl<'g, V: Value> State<'g, V> {
|
||||
pub fn new(grammar: &'g Grammar<V>, input: &'g str, cursor: usize) -> Self {
|
||||
Self {
|
||||
grammar,
|
||||
input,
|
||||
cursor,
|
||||
cache: HashMap::new(),
|
||||
scope: Scope::new(),
|
||||
controls: Vec::new(),
|
||||
errors: Vec::new(),
|
||||
last_cursor: -1,
|
||||
ctx: None,
|
||||
}
|
||||
}
|
||||
pub fn reader(&self) -> Reader<'g> {
|
||||
Reader {
|
||||
string: self.input,
|
||||
cursor: self.cursor,
|
||||
}
|
||||
}
|
||||
pub fn set_reader(&mut self, r: &Reader) {
|
||||
self.cursor = r.cursor;
|
||||
}
|
||||
fn discard_shorter(&mut self, cursor: usize) {
|
||||
if cursor as isize > self.last_cursor {
|
||||
self.last_cursor = cursor as isize;
|
||||
self.errors.clear();
|
||||
}
|
||||
}
|
||||
/// ErrorCollector.store.
|
||||
pub fn store(&mut self, cursor: usize, sugg: Sugg, reason: Reason) {
|
||||
self.discard_shorter(cursor);
|
||||
if cursor as isize == self.last_cursor {
|
||||
self.errors.push((sugg, reason));
|
||||
}
|
||||
}
|
||||
pub fn store_at_mark(&mut self, reason: Reason) {
|
||||
self.store(self.cursor, Sugg::Empty, reason);
|
||||
}
|
||||
fn parse_top(&mut self) -> Option<V> {
|
||||
let r = self.parse(self.grammar.top);
|
||||
if r.is_some() {
|
||||
self.discard_shorter(self.cursor);
|
||||
}
|
||||
r
|
||||
}
|
||||
fn first_error(&self) -> CommandError {
|
||||
if let Some((_, reason)) = self.errors.first() {
|
||||
return match reason {
|
||||
Reason::Delayed(key, args) => {
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
args.iter().map(|a| a as &dyn std::fmt::Display).collect();
|
||||
CommandError::tr_at(
|
||||
key,
|
||||
&args,
|
||||
&Reader {
|
||||
string: self.input,
|
||||
cursor: self.last_cursor.max(0) as usize,
|
||||
},
|
||||
)
|
||||
}
|
||||
Reason::Error(e) => e.clone(),
|
||||
};
|
||||
}
|
||||
CommandError::new(crate::text::Text::literal("Failed to parse"))
|
||||
}
|
||||
/// CachedParseState.parse: a named rule, memoised per position.
|
||||
pub fn parse(&mut self, rule: RuleId) -> Option<V> {
|
||||
let mark = self.cursor;
|
||||
if let Some(entry) = self.cache.get(&(mark, rule)) {
|
||||
return match entry {
|
||||
None => None,
|
||||
Some((v, after)) => {
|
||||
let v = v.clone();
|
||||
self.cursor = *after;
|
||||
Some(v)
|
||||
}
|
||||
};
|
||||
}
|
||||
let result = match self.grammar.rules[rule].as_ref() {
|
||||
Some(Rule::Term(term, action)) => {
|
||||
let action = action.clone();
|
||||
self.scope.push_frame();
|
||||
let ok = self.term(term, UNBOUND, false);
|
||||
let r = if ok { action(self) } else { None };
|
||||
self.scope.pop_frame();
|
||||
r
|
||||
}
|
||||
Some(Rule::Custom(f)) => {
|
||||
let f = f.clone();
|
||||
f(self)
|
||||
}
|
||||
None => panic!("Unbound rule {}", self.grammar.names[rule]),
|
||||
};
|
||||
let entry = result.clone().map(|v| (v, self.cursor));
|
||||
self.cache.insert((mark, rule), entry);
|
||||
result
|
||||
}
|
||||
fn skip_whitespace(&mut self) {
|
||||
let mut r = self.reader();
|
||||
r.skip_whitespace();
|
||||
self.cursor = r.cursor;
|
||||
}
|
||||
fn term(&mut self, term: &'g Term<V>, control: usize, silent: bool) -> bool {
|
||||
match term {
|
||||
Term::Seq(items) => {
|
||||
let mark = self.cursor;
|
||||
for t in items {
|
||||
if !self.term(t, control, silent) {
|
||||
self.cursor = mark;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
Term::Alt(items) => {
|
||||
self.controls.push(false);
|
||||
let ctl = self.controls.len() - 1;
|
||||
let mark = self.cursor;
|
||||
self.scope.split_frame();
|
||||
let mut ok = false;
|
||||
for t in items {
|
||||
if self.term(t, ctl, silent) {
|
||||
self.scope.merge_frame();
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
self.scope.clear_frame_values();
|
||||
self.cursor = mark;
|
||||
if self.controls[ctl] {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
self.scope.pop_frame();
|
||||
}
|
||||
self.controls.pop();
|
||||
ok
|
||||
}
|
||||
Term::Opt(t) => {
|
||||
let mark = self.cursor;
|
||||
if !self.term(t, control, silent) {
|
||||
self.cursor = mark;
|
||||
}
|
||||
true
|
||||
}
|
||||
Term::Repeated { rule, list, min } => {
|
||||
let mark = self.cursor;
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let entry = self.cursor;
|
||||
match self.parse(*rule) {
|
||||
Some(v) => items.push(v),
|
||||
None => {
|
||||
self.cursor = entry;
|
||||
if items.len() < *min {
|
||||
self.cursor = mark;
|
||||
return false;
|
||||
}
|
||||
self.scope.put(list, V::list(items));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Term::RepeatedSep {
|
||||
rule,
|
||||
list,
|
||||
sep,
|
||||
min,
|
||||
trailing,
|
||||
} => {
|
||||
let list_mark = self.cursor;
|
||||
let mut items = Vec::new();
|
||||
let mut first = true;
|
||||
loop {
|
||||
let before = self.cursor;
|
||||
if !first && !self.term(sep, control, silent) {
|
||||
self.cursor = before;
|
||||
break;
|
||||
}
|
||||
let after = self.cursor;
|
||||
match self.parse(*rule) {
|
||||
Some(v) => items.push(v),
|
||||
None => {
|
||||
if first {
|
||||
self.cursor = after;
|
||||
} else {
|
||||
if !*trailing {
|
||||
self.cursor = list_mark;
|
||||
return false;
|
||||
}
|
||||
self.cursor = after;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
if items.len() < *min {
|
||||
self.cursor = list_mark;
|
||||
return false;
|
||||
}
|
||||
self.scope.put(list, V::list(items));
|
||||
true
|
||||
}
|
||||
Term::Look(t, positive) => {
|
||||
let mark = self.cursor;
|
||||
let r = self.term(t, control, true);
|
||||
self.cursor = mark;
|
||||
*positive == r
|
||||
}
|
||||
Term::Marker(atom, v) => {
|
||||
self.scope.put(atom, v.clone());
|
||||
true
|
||||
}
|
||||
Term::Cut => {
|
||||
if control != UNBOUND {
|
||||
self.controls[control] = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
Term::Empty => true,
|
||||
Term::Fail(reason) => {
|
||||
if !silent {
|
||||
self.store(self.cursor, Sugg::Empty, reason.clone());
|
||||
}
|
||||
false
|
||||
}
|
||||
Term::Named { rule, store } => match self.parse(*rule) {
|
||||
Some(v) => {
|
||||
self.scope.put(store, v);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Term::Chars { values, accept } => {
|
||||
self.skip_whitespace();
|
||||
let cursor = self.cursor;
|
||||
let mut r = self.reader();
|
||||
if r.can_read() {
|
||||
let c = r.read();
|
||||
self.cursor = r.cursor;
|
||||
let ok = match accept {
|
||||
Some(f) => f(c),
|
||||
None => values.contains(&c),
|
||||
};
|
||||
if ok {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if !silent {
|
||||
let joined = values
|
||||
.iter()
|
||||
.map(char::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
let sugg = Sugg::Values(Rc::new(values.iter().map(char::to_string).collect()));
|
||||
self.store(
|
||||
cursor,
|
||||
sugg,
|
||||
Reason::Delayed("argument.literal.incorrect", vec![joined]),
|
||||
);
|
||||
}
|
||||
false
|
||||
}
|
||||
Term::Word(word) => {
|
||||
self.skip_whitespace();
|
||||
let cursor = self.cursor;
|
||||
let mut r = self.reader();
|
||||
let value = r.read_unquoted_string();
|
||||
self.cursor = r.cursor;
|
||||
if value != word {
|
||||
if !silent {
|
||||
self.store(
|
||||
cursor,
|
||||
Sugg::Values(Rc::new(vec![word.clone()])),
|
||||
Reason::Delayed("argument.literal.incorrect", vec![word.clone()]),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,813 +0,0 @@
|
||||
//! EntitySelectorParser and EntitySelectorOptions: `@e[...]` selectors,
|
||||
//! player names and UUIDs, with the suggestion state vanilla keeps while
|
||||
//! parsing (`fillSuggestions`).
|
||||
use super::args::{
|
||||
AdvCondition, GameMode, Registries, Selector, Sort, read_double_bounds, read_float_bounds,
|
||||
read_identifier, read_int_bounds, suggest_resources,
|
||||
};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
|
||||
/// The option names in vanilla's registration order.
|
||||
const OPTIONS: [&str; 21] = [
|
||||
"name",
|
||||
"distance",
|
||||
"level",
|
||||
"x",
|
||||
"y",
|
||||
"z",
|
||||
"dx",
|
||||
"dy",
|
||||
"dz",
|
||||
"x_rotation",
|
||||
"y_rotation",
|
||||
"limit",
|
||||
"sort",
|
||||
"gamemode",
|
||||
"team",
|
||||
"type",
|
||||
"tag",
|
||||
"nbt",
|
||||
"scores",
|
||||
"advancements",
|
||||
"predicate",
|
||||
];
|
||||
const SELECTOR_KINDS: [(&str, &str); 6] = [
|
||||
("@p", "argument.entity.selector.nearestPlayer"),
|
||||
("@a", "argument.entity.selector.allPlayers"),
|
||||
("@r", "argument.entity.selector.randomPlayer"),
|
||||
("@s", "argument.entity.selector.self"),
|
||||
("@e", "argument.entity.selector.allEntities"),
|
||||
("@n", "argument.entity.selector.nearestEntity"),
|
||||
];
|
||||
|
||||
/// InvertableSetOptionState.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct InvertableSet {
|
||||
/// 0 none, 1 single, 2 multiple.
|
||||
state: u8,
|
||||
tags: Vec<String>,
|
||||
}
|
||||
impl InvertableSet {
|
||||
fn can_parse_positive(&self) -> bool {
|
||||
self.state == 0
|
||||
}
|
||||
fn can_parse_negative(&self) -> bool {
|
||||
self.state != 1
|
||||
}
|
||||
fn can_parse_any_tag(&self) -> bool {
|
||||
self.can_parse_negative()
|
||||
}
|
||||
fn can_parse_tag(&self, tag: &str) -> bool {
|
||||
self.can_parse_any_tag() && !self.tags.iter().any(|t| t == tag)
|
||||
}
|
||||
fn can_parse_any(&self) -> bool {
|
||||
self.state != 1
|
||||
}
|
||||
fn can_parse_element(&self, inverted: bool) -> bool {
|
||||
if inverted {
|
||||
self.can_parse_negative()
|
||||
} else {
|
||||
self.can_parse_positive()
|
||||
}
|
||||
}
|
||||
fn mark_element(&mut self, inverted: bool) {
|
||||
self.state = if inverted { 2 } else { 1 };
|
||||
}
|
||||
fn mark_tag(&mut self, tag: String) {
|
||||
self.state = 2;
|
||||
self.tags.push(tag);
|
||||
}
|
||||
}
|
||||
|
||||
/// The suggestion function the parser last set.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Sugg {
|
||||
Nothing,
|
||||
NameOrSelector,
|
||||
Name,
|
||||
Selector,
|
||||
OpenOptions,
|
||||
OptionsKeyOrClose,
|
||||
OptionsKey,
|
||||
OptionsNextOrClose,
|
||||
Sort,
|
||||
GameMode,
|
||||
Type,
|
||||
}
|
||||
|
||||
/// EntitySelectorParser over a reader.
|
||||
pub struct SelectorParser<'r, 'a> {
|
||||
pub reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
allow_selectors: bool,
|
||||
s: Selector,
|
||||
sugg: Sugg,
|
||||
start_position: usize,
|
||||
current_entity: bool,
|
||||
has_distance: bool,
|
||||
has_level: bool,
|
||||
has_rot_x: bool,
|
||||
has_rot_y: bool,
|
||||
name_option: InvertableSet,
|
||||
limited: bool,
|
||||
sorted: bool,
|
||||
gamemode_option: InvertableSet,
|
||||
team_option: InvertableSet,
|
||||
type_option: InvertableSet,
|
||||
scores_option: bool,
|
||||
advancements_option: bool,
|
||||
}
|
||||
|
||||
/// UUID.fromString.
|
||||
pub fn java_uuid(name: &str) -> Option<u128> {
|
||||
if name.encode_utf16().count() > 36 {
|
||||
return None;
|
||||
}
|
||||
let parts: Vec<&str> = name.split('-').collect();
|
||||
if parts.len() != 5 {
|
||||
return None;
|
||||
}
|
||||
let mut v: [i64; 5] = [0; 5];
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
// Long.parseLong(s, 16): an optional sign then hex digits.
|
||||
let digits = p.strip_prefix(['+', '-']).unwrap_or(p);
|
||||
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
v[i] = i64::from_str_radix(p, 16).ok()?;
|
||||
}
|
||||
let msb = (((v[0] as u64) & 0xffff_ffff) << 32)
|
||||
| (((v[1] as u64) & 0xffff) << 16)
|
||||
| ((v[2] as u64) & 0xffff);
|
||||
let lsb = (((v[3] as u64) & 0xffff) << 48) | ((v[4] as u64) & 0xffff_ffff_ffff);
|
||||
Some((u128::from(msb) << 64) | u128::from(lsb))
|
||||
}
|
||||
|
||||
fn rollback(
|
||||
reader: &mut Reader,
|
||||
start: usize,
|
||||
key: &str,
|
||||
args: &[&dyn std::fmt::Display],
|
||||
) -> CommandError {
|
||||
reader.cursor = start;
|
||||
CommandError::tr_at(key, args, reader)
|
||||
}
|
||||
|
||||
impl<'r, 'a> SelectorParser<'r, 'a> {
|
||||
pub fn new(reader: &'r mut Reader<'a>, reg: &'r Registries, allow_selectors: bool) -> Self {
|
||||
Self {
|
||||
reader,
|
||||
reg,
|
||||
allow_selectors,
|
||||
s: Selector::default(),
|
||||
sugg: Sugg::Nothing,
|
||||
start_position: 0,
|
||||
current_entity: false,
|
||||
has_distance: false,
|
||||
has_level: false,
|
||||
has_rot_x: false,
|
||||
has_rot_y: false,
|
||||
name_option: InvertableSet::default(),
|
||||
limited: false,
|
||||
sorted: false,
|
||||
gamemode_option: InvertableSet::default(),
|
||||
team_option: InvertableSet::default(),
|
||||
type_option: InvertableSet::default(),
|
||||
scores_option: false,
|
||||
advancements_option: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// EntitySelectorParser.parse.
|
||||
pub fn parse(&mut self) -> CmdResult<Selector> {
|
||||
self.start_position = self.reader.cursor;
|
||||
self.sugg = Sugg::NameOrSelector;
|
||||
if self.reader.can_read() && self.reader.peek() == '@' {
|
||||
if !self.allow_selectors {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.selector.not_allowed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.parse_selector()?;
|
||||
} else {
|
||||
self.parse_name_or_uuid()?;
|
||||
}
|
||||
Ok(self.s.clone())
|
||||
}
|
||||
|
||||
fn parse_selector(&mut self) -> CmdResult<()> {
|
||||
self.sugg = Sugg::Selector;
|
||||
if !self.reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.selector.missing",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
let start = self.reader.cursor;
|
||||
let kind = self.reader.read();
|
||||
let s = &mut self.s;
|
||||
s.kind = kind;
|
||||
match kind {
|
||||
'a' => {
|
||||
s.limit = usize::MAX;
|
||||
s.include_entities = false;
|
||||
s.types.push(("minecraft:player".into(), false));
|
||||
}
|
||||
'e' => {
|
||||
s.limit = usize::MAX;
|
||||
s.include_entities = true;
|
||||
}
|
||||
'n' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = true;
|
||||
s.sort = Sort::Nearest;
|
||||
}
|
||||
'p' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = false;
|
||||
s.sort = Sort::Nearest;
|
||||
s.types.push(("minecraft:player".into(), false));
|
||||
}
|
||||
'r' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = false;
|
||||
s.sort = Sort::Random;
|
||||
s.types.push(("minecraft:player".into(), false));
|
||||
}
|
||||
's' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = true;
|
||||
self.current_entity = true;
|
||||
}
|
||||
other => {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.selector.unknown",
|
||||
&[&format!("@{other}")],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
self.sugg = Sugg::OpenOptions;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::OptionsKeyOrClose;
|
||||
self.parse_options()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_name_or_uuid(&mut self) -> CmdResult<()> {
|
||||
if self.reader.can_read() {
|
||||
self.sugg = Sugg::Name;
|
||||
}
|
||||
let start = self.reader.cursor;
|
||||
let name = self.reader.read_string()?;
|
||||
if let Some(uuid) = java_uuid(&name) {
|
||||
self.s.uuid = Some(uuid);
|
||||
self.s.include_entities = true;
|
||||
self.s.player_name = Some(name);
|
||||
} else {
|
||||
if name.is_empty() || name.encode_utf16().count() > 16 {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.invalid",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.s.include_entities = false;
|
||||
self.s.player_name = Some(name);
|
||||
}
|
||||
self.s.kind = '\0';
|
||||
self.s.limit = 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn can_use(&self, option: &str) -> bool {
|
||||
match option {
|
||||
"name" => self.name_option.can_parse_any(),
|
||||
"distance" => !self.has_distance,
|
||||
"level" => !self.has_level,
|
||||
"x" => self.s.pos[0].is_none(),
|
||||
"y" => self.s.pos[1].is_none(),
|
||||
"z" => self.s.pos[2].is_none(),
|
||||
"dx" => self.s.delta[0].is_none(),
|
||||
"dy" => self.s.delta[1].is_none(),
|
||||
"dz" => self.s.delta[2].is_none(),
|
||||
"x_rotation" => !self.has_rot_x,
|
||||
"y_rotation" => !self.has_rot_y,
|
||||
"limit" => !self.current_entity && !self.limited,
|
||||
"sort" => !self.current_entity && !self.sorted,
|
||||
"gamemode" => self.gamemode_option.can_parse_any(),
|
||||
"team" => self.team_option.can_parse_any(),
|
||||
"type" => self.type_option.can_parse_any(),
|
||||
"scores" => !self.scores_option,
|
||||
"advancements" => !self.advancements_option,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_options(&mut self) -> CmdResult<()> {
|
||||
self.sugg = Sugg::OptionsKey;
|
||||
self.reader.skip_whitespace();
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
let start = self.reader.cursor;
|
||||
let key = self.reader.read_string()?;
|
||||
if !OPTIONS.contains(&key.as_str()) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.unknown",
|
||||
&[&key],
|
||||
));
|
||||
}
|
||||
if !self.can_use(&key) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&key],
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
if !self.reader.can_read() || self.reader.peek() != '=' {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.valueless",
|
||||
&[&key],
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::Nothing;
|
||||
self.handle(&key)?;
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::OptionsNextOrClose;
|
||||
if self.reader.can_read() {
|
||||
if self.reader.peek() != ',' {
|
||||
if self.reader.peek() != ']' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.options.unterminated",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::OptionsKey;
|
||||
}
|
||||
}
|
||||
if self.reader.can_read() {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::Nothing;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"argument.entity.options.unterminated",
|
||||
&[],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn should_invert(&mut self) -> bool {
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() && self.reader.peek() == '!' {
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
fn is_tag(&mut self) -> bool {
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() && self.reader.peek() == '#' {
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(&mut self, key: &str) -> CmdResult<()> {
|
||||
match key {
|
||||
"name" => {
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
let name = self.reader.read_string()?;
|
||||
if !self.name_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"name"],
|
||||
));
|
||||
}
|
||||
self.name_option.mark_element(inverted);
|
||||
self.s.names.push((name, inverted));
|
||||
}
|
||||
"distance" => {
|
||||
let start = self.reader.cursor;
|
||||
let value = read_double_bounds(self.reader)?;
|
||||
if value.0.is_some_and(|v| v < 0.0) || value.1.is_some_and(|v| v < 0.0) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.distance.negative",
|
||||
&[],
|
||||
));
|
||||
}
|
||||
self.s.distance = Some(value);
|
||||
self.has_distance = true;
|
||||
}
|
||||
"level" => {
|
||||
let start = self.reader.cursor;
|
||||
let value = read_int_bounds(self.reader)?;
|
||||
if value.0.is_some_and(|v| v < 0) || value.1.is_some_and(|v| v < 0) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.level.negative",
|
||||
&[],
|
||||
));
|
||||
}
|
||||
self.s.level = Some(value);
|
||||
self.has_level = true;
|
||||
self.s.include_entities = false;
|
||||
}
|
||||
"x" | "y" | "z" => {
|
||||
let i = usize::from(key.as_bytes()[0] - b'x');
|
||||
self.s.pos[i] = Some(self.reader.read_double()?);
|
||||
}
|
||||
"dx" | "dy" | "dz" => {
|
||||
let i = usize::from(key.as_bytes()[1] - b'x');
|
||||
self.s.delta[i] = Some(self.reader.read_double()?);
|
||||
}
|
||||
"x_rotation" | "y_rotation" => {
|
||||
let (lo, hi) = read_float_bounds(self.reader)?;
|
||||
let range = (lo.map(f64::from), hi.map(f64::from));
|
||||
if key == "x_rotation" {
|
||||
self.s.x_rotation = Some(range);
|
||||
self.has_rot_x = true;
|
||||
} else {
|
||||
self.s.y_rotation = Some(range);
|
||||
self.has_rot_y = true;
|
||||
}
|
||||
}
|
||||
"limit" => {
|
||||
let start = self.reader.cursor;
|
||||
let count = self.reader.read_int()?;
|
||||
if count < 1 {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.limit.toosmall",
|
||||
&[],
|
||||
));
|
||||
}
|
||||
self.s.limit = count as usize;
|
||||
self.limited = true;
|
||||
}
|
||||
"sort" => {
|
||||
let start = self.reader.cursor;
|
||||
let name = self.reader.read_unquoted_string();
|
||||
self.sugg = Sugg::Sort;
|
||||
self.s.sort = match name {
|
||||
"nearest" => Sort::Nearest,
|
||||
"furthest" => Sort::Furthest,
|
||||
"random" => Sort::Random,
|
||||
"arbitrary" => Sort::Arbitrary,
|
||||
_ => {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.sort.irreversible",
|
||||
&[&name],
|
||||
));
|
||||
}
|
||||
};
|
||||
self.sorted = true;
|
||||
}
|
||||
"gamemode" => {
|
||||
self.sugg = Sugg::GameMode;
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
if !self.gamemode_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"gamemode"],
|
||||
));
|
||||
}
|
||||
let name = self.reader.read_unquoted_string();
|
||||
if GameMode::from_name(name).is_none() {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.mode.invalid",
|
||||
&[&name],
|
||||
));
|
||||
}
|
||||
self.s.include_entities = false;
|
||||
self.s.gamemodes.push((name.to_owned(), inverted));
|
||||
self.gamemode_option.mark_element(inverted);
|
||||
}
|
||||
"team" => {
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
let name = self.reader.read_unquoted_string().to_owned();
|
||||
if !self.team_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"team"],
|
||||
));
|
||||
}
|
||||
self.s.teams.push((name, inverted));
|
||||
self.team_option.mark_element(inverted);
|
||||
}
|
||||
"type" => {
|
||||
self.sugg = Sugg::Type;
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
if self.is_tag() {
|
||||
if !self.type_option.can_parse_any_tag() {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"type"],
|
||||
));
|
||||
}
|
||||
let id = read_identifier(self.reader)?;
|
||||
if !self.type_option.can_parse_tag(&id) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"type"],
|
||||
));
|
||||
}
|
||||
self.s.types.push((format!("#{id}"), inverted));
|
||||
self.type_option.mark_tag(id);
|
||||
} else {
|
||||
if !self.type_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"type"],
|
||||
));
|
||||
}
|
||||
let id = read_identifier(self.reader)?;
|
||||
let types = self.reg.ids("minecraft:entity_type");
|
||||
if !types.is_empty() && !types.contains(&id) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.type.invalid",
|
||||
&[&id],
|
||||
));
|
||||
}
|
||||
if id == "minecraft:player" && !inverted {
|
||||
self.s.include_entities = false;
|
||||
}
|
||||
if !inverted {
|
||||
// limitToType replaces the player type of @a/@p/@r.
|
||||
self.s.types.retain(|(t, n)| *n || t.starts_with('#'));
|
||||
}
|
||||
self.s.types.push((id, inverted));
|
||||
self.type_option.mark_element(inverted);
|
||||
}
|
||||
}
|
||||
"tag" => {
|
||||
let inverted = self.should_invert();
|
||||
let tag = self.reader.read_unquoted_string().to_owned();
|
||||
self.s.tags.push((tag, inverted));
|
||||
}
|
||||
"nbt" => {
|
||||
let inverted = self.should_invert();
|
||||
let start = self.reader.cursor;
|
||||
super::snbt::parse_compound_argument(self.reader)?;
|
||||
let text = self.reader.string[start..self.reader.cursor].to_owned();
|
||||
self.s.nbt.push((text, inverted));
|
||||
}
|
||||
"scores" => {
|
||||
let r = &mut *self.reader;
|
||||
r.expect('{')?;
|
||||
r.skip_whitespace();
|
||||
let mut expected = Vec::new();
|
||||
while r.can_read() && r.peek() != '}' {
|
||||
r.skip_whitespace();
|
||||
let name = r.read_unquoted_string().to_owned();
|
||||
r.skip_whitespace();
|
||||
r.expect('=')?;
|
||||
r.skip_whitespace();
|
||||
let value = read_int_bounds(r)?;
|
||||
expected.push((name, value));
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == ',' {
|
||||
r.skip();
|
||||
}
|
||||
}
|
||||
r.expect('}')?;
|
||||
self.s.scores.extend(expected);
|
||||
self.scores_option = true;
|
||||
}
|
||||
"advancements" => {
|
||||
let r = &mut *self.reader;
|
||||
r.expect('{')?;
|
||||
r.skip_whitespace();
|
||||
let mut expected = Vec::new();
|
||||
while r.can_read() && r.peek() != '}' {
|
||||
r.skip_whitespace();
|
||||
let name = read_identifier(r)?;
|
||||
r.skip_whitespace();
|
||||
r.expect('=')?;
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == '{' {
|
||||
let mut progress = Vec::new();
|
||||
r.skip_whitespace();
|
||||
r.expect('{')?;
|
||||
r.skip_whitespace();
|
||||
while r.can_read() && r.peek() != '}' {
|
||||
r.skip_whitespace();
|
||||
let criterion = r.read_unquoted_string().to_owned();
|
||||
r.skip_whitespace();
|
||||
r.expect('=')?;
|
||||
r.skip_whitespace();
|
||||
let value = r.read_boolean()?;
|
||||
progress.push((criterion, value));
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == ',' {
|
||||
r.skip();
|
||||
}
|
||||
}
|
||||
r.skip_whitespace();
|
||||
r.expect('}')?;
|
||||
r.skip_whitespace();
|
||||
expected.push((name, AdvCondition::Criteria(progress)));
|
||||
} else {
|
||||
let value = r.read_boolean()?;
|
||||
expected.push((name, AdvCondition::Done(value)));
|
||||
}
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == ',' {
|
||||
r.skip();
|
||||
}
|
||||
}
|
||||
r.expect('}')?;
|
||||
if !expected.is_empty() {
|
||||
self.s.include_entities = false;
|
||||
}
|
||||
self.s.advancements.extend(expected);
|
||||
self.advancements_option = true;
|
||||
}
|
||||
"predicate" => {
|
||||
let inverted = self.should_invert();
|
||||
let id = read_identifier(self.reader)?;
|
||||
self.s.predicates.push((id, inverted));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fill_selectors(builder: &mut SuggestionsBuilder) {
|
||||
for (s, tip) in SELECTOR_KINDS {
|
||||
builder.suggest_tooltip(s, crate::lang::get(tip));
|
||||
}
|
||||
}
|
||||
|
||||
/// EntitySelectorParser.fillSuggestions: `names` adds the name
|
||||
/// candidates (online players for most arguments).
|
||||
pub fn fill_suggestions(
|
||||
&self,
|
||||
builder: &mut SuggestionsBuilder,
|
||||
names: &dyn Fn(&mut SuggestionsBuilder),
|
||||
) {
|
||||
let mut b = builder.offset(self.reader.cursor);
|
||||
match self.sugg {
|
||||
Sugg::Nothing => {}
|
||||
Sugg::NameOrSelector => {
|
||||
names(&mut b);
|
||||
if self.allow_selectors {
|
||||
Self::fill_selectors(&mut b);
|
||||
}
|
||||
}
|
||||
Sugg::Name => {
|
||||
let mut sub = b.offset(self.start_position);
|
||||
names(&mut sub);
|
||||
b.add(sub);
|
||||
}
|
||||
Sugg::Selector => {
|
||||
let mut sub = b.offset(b.start - 1);
|
||||
Self::fill_selectors(&mut sub);
|
||||
b.add(sub);
|
||||
}
|
||||
Sugg::OpenOptions => b.suggest("["),
|
||||
Sugg::OptionsKeyOrClose => {
|
||||
b.suggest("]");
|
||||
self.suggest_names(&mut b);
|
||||
}
|
||||
Sugg::OptionsKey => self.suggest_names(&mut b),
|
||||
Sugg::OptionsNextOrClose => {
|
||||
b.suggest(",");
|
||||
b.suggest("]");
|
||||
}
|
||||
Sugg::Sort => b.suggest_matching(["nearest", "furthest", "random", "arbitrary"]),
|
||||
Sugg::GameMode => {
|
||||
let state = &self.gamemode_option;
|
||||
let mut prefix = b.remaining_lower();
|
||||
let mut add_normal = state.can_parse_positive();
|
||||
let mut add_inverted = state.can_parse_negative();
|
||||
if !prefix.is_empty() {
|
||||
if prefix.starts_with('!') {
|
||||
add_normal = false;
|
||||
prefix.remove(0);
|
||||
} else {
|
||||
add_inverted = false;
|
||||
}
|
||||
}
|
||||
for mode in GameMode::ALL {
|
||||
if mode.name().starts_with(&prefix) {
|
||||
if add_inverted {
|
||||
b.suggest(format!("!{}", mode.name()));
|
||||
}
|
||||
if add_normal {
|
||||
b.suggest(mode.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::Type => {
|
||||
let state = &self.type_option;
|
||||
let types = self.reg.ids("minecraft:entity_type");
|
||||
if state.can_parse_negative() {
|
||||
suggest_resources(&mut b, types, "!");
|
||||
}
|
||||
if state.can_parse_positive() {
|
||||
suggest_resources(&mut b, types, "");
|
||||
}
|
||||
if state.can_parse_any_tag() {
|
||||
let tags: Vec<String> = self
|
||||
.reg
|
||||
.tags("minecraft:entity_type")
|
||||
.iter()
|
||||
.filter(|t| state.can_parse_tag(t))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !tags.is_empty() {
|
||||
suggest_resources(&mut b, &tags, "#");
|
||||
suggest_resources(&mut b, &tags, "!#");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.add(b);
|
||||
}
|
||||
|
||||
fn suggest_names(&self, b: &mut SuggestionsBuilder) {
|
||||
let lower = b.remaining_lower();
|
||||
for o in OPTIONS {
|
||||
if self.can_use(o) && o.starts_with(&lower) {
|
||||
b.suggest_tooltip(
|
||||
format!("{o}="),
|
||||
crate::lang::get(&format!("argument.entity.options.{o}.description")),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a selector from `reader` (EntitySelectorParser.parse).
|
||||
pub fn parse(reader: &mut Reader, reg: &Registries, allow_selectors: bool) -> CmdResult<Selector> {
|
||||
SelectorParser::new(reader, reg, allow_selectors).parse()
|
||||
}
|
||||
|
||||
/// Re-parse the text from `builder.start` and fill the selector suggestions.
|
||||
pub fn suggest(
|
||||
builder: &mut SuggestionsBuilder,
|
||||
reg: &Registries,
|
||||
names: &dyn Fn(&mut SuggestionsBuilder),
|
||||
) {
|
||||
let mut reader = Reader {
|
||||
string: builder.input,
|
||||
cursor: builder.start,
|
||||
};
|
||||
let mut parser = SelectorParser::new(&mut reader, reg, reg.permission >= 2);
|
||||
let _ = parser.parse();
|
||||
parser.fill_suggestions(builder, names);
|
||||
}
|
||||
@@ -1,981 +0,0 @@
|
||||
//! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its
|
||||
//! error messages and completion suggestions, producing NBT tags.
|
||||
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
use std::rc::Rc;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TypeSuffix {
|
||||
Float,
|
||||
Double,
|
||||
Byte,
|
||||
Short,
|
||||
Int,
|
||||
Long,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Base {
|
||||
Binary,
|
||||
Decimal,
|
||||
Hex,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArrayPrefix {
|
||||
Byte,
|
||||
Int,
|
||||
Long,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IntLit {
|
||||
minus: bool,
|
||||
base: Base,
|
||||
digits: String,
|
||||
/// Some(true) signed, Some(false) unsigned.
|
||||
signed: Option<bool>,
|
||||
ty: Option<TypeSuffix>,
|
||||
}
|
||||
|
||||
/// The values SnbtGrammar's rules produce.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SV {
|
||||
Tag(Tag),
|
||||
Str(String),
|
||||
/// A sign: true for minus.
|
||||
Sign(bool),
|
||||
Suffix(Option<bool>, Option<TypeSuffix>),
|
||||
Type(TypeSuffix),
|
||||
Int(IntLit),
|
||||
/// float exponent: (minus, digits)
|
||||
Exp(bool, String),
|
||||
Prefix(ArrayPrefix),
|
||||
List(Vec<SV>),
|
||||
Entry(String, Tag),
|
||||
}
|
||||
impl Value for SV {
|
||||
fn list(items: Vec<Self>) -> Self {
|
||||
SV::List(items)
|
||||
}
|
||||
}
|
||||
fn delayed(key: &'static str) -> Reason {
|
||||
Reason::Delayed(key, Vec::new())
|
||||
}
|
||||
|
||||
fn can_start_number(c: char) -> bool {
|
||||
matches!(c, '+' | '-' | '.' | '0'..='9')
|
||||
}
|
||||
|
||||
/// NumberRunParseRule.
|
||||
fn number_run(
|
||||
state: &mut State<SV>,
|
||||
accept: fn(char) -> bool,
|
||||
no_value: &'static str,
|
||||
) -> Option<SV> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
state.set_reader(&r);
|
||||
let start = state.cursor;
|
||||
let rest = &state.input[start..];
|
||||
let len: usize = rest
|
||||
.chars()
|
||||
.take_while(|c| accept(*c))
|
||||
.map(char::len_utf8)
|
||||
.sum();
|
||||
if len == 0 {
|
||||
state.store_at_mark(delayed(no_value));
|
||||
return None;
|
||||
}
|
||||
let s = &rest[..len];
|
||||
if s.starts_with('_') || s.ends_with('_') {
|
||||
state.store_at_mark(delayed("snbt.parser.underscore_not_allowed"));
|
||||
return None;
|
||||
}
|
||||
state.cursor = start + len;
|
||||
Some(SV::Str(s.to_owned()))
|
||||
}
|
||||
/// GreedyPredicateParseRule (no whitespace skipping).
|
||||
fn greedy(
|
||||
state: &mut State<SV>,
|
||||
accept: fn(char) -> bool,
|
||||
min: usize,
|
||||
max: usize,
|
||||
error: Reason,
|
||||
) -> Option<SV> {
|
||||
let start = state.cursor;
|
||||
let rest = &state.input[start..];
|
||||
let mut len = 0;
|
||||
let mut count = 0;
|
||||
for c in rest.chars() {
|
||||
if !accept(c) || count >= max {
|
||||
break;
|
||||
}
|
||||
len += c.len_utf8();
|
||||
count += c.len_utf16();
|
||||
}
|
||||
if count < min {
|
||||
state.store_at_mark(error);
|
||||
return None;
|
||||
}
|
||||
state.cursor = start + len;
|
||||
Some(SV::Str(rest[..len].to_owned()))
|
||||
}
|
||||
|
||||
fn number_error(message: String) -> Reason {
|
||||
Reason::Delayed("snbt.parser.number_parse_failure", vec![message])
|
||||
}
|
||||
fn for_input(s: &str, radix: u32) -> String {
|
||||
if radix == 10 {
|
||||
format!("For input string: \"{s}\"")
|
||||
} else {
|
||||
format!("For input string: \"{s}\" under radix {radix}")
|
||||
}
|
||||
}
|
||||
/// Long.parseLong(s, radix) with its NumberFormatException messages.
|
||||
fn parse_long(s: &str, radix: u32) -> Result<i64, String> {
|
||||
let digits = s.strip_prefix(['-', '+']).unwrap_or(s);
|
||||
if digits.is_empty() {
|
||||
return Err(for_input(s, radix));
|
||||
}
|
||||
i64::from_str_radix(s.strip_prefix('+').unwrap_or(s), radix).map_err(|_| for_input(s, radix))
|
||||
}
|
||||
fn parse_int(s: &str, radix: u32) -> Result<i32, String> {
|
||||
let v = parse_long(s, radix).map_err(|_| for_input(s, radix))?;
|
||||
i32::try_from(v).map_err(|_| for_input(s, radix))
|
||||
}
|
||||
fn parse_small(s: &str, radix: u32, lo: i32, hi: i32) -> Result<i32, String> {
|
||||
let v = parse_int(s, radix)?;
|
||||
if v < lo || v > hi {
|
||||
return Err(format!("Value out of range. Value:\"{s}\" Radix:{radix}"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
fn parse_unsigned_int(s: &str, radix: u32) -> Result<i32, String> {
|
||||
if s.starts_with('-') {
|
||||
return Err(format!(
|
||||
"Illegal leading minus sign on unsigned string {s}."
|
||||
));
|
||||
}
|
||||
let len = s.chars().count();
|
||||
if len <= 5 || (radix == 10 && len <= 9) {
|
||||
return parse_int(s, radix);
|
||||
}
|
||||
let v = parse_long(s, radix)?;
|
||||
if (v as u64) & 0xffff_ffff_0000_0000 == 0 {
|
||||
Ok(v as u32 as i32)
|
||||
} else {
|
||||
Err(format!("String value {s} exceeds range of unsigned int."))
|
||||
}
|
||||
}
|
||||
fn parse_unsigned_long(s: &str, radix: u32) -> Result<i64, String> {
|
||||
if s.starts_with('-') {
|
||||
return Err(format!(
|
||||
"Illegal leading minus sign on unsigned string {s}."
|
||||
));
|
||||
}
|
||||
let digits = s.strip_prefix('+').unwrap_or(s);
|
||||
match u64::from_str_radix(digits, radix) {
|
||||
Ok(v) => Ok(v as i64),
|
||||
Err(_) => {
|
||||
if digits.chars().all(|c| c.is_digit(radix)) && !digits.is_empty() {
|
||||
Err(format!("String value {s} exceeds range of unsigned long."))
|
||||
} else {
|
||||
Err(for_input(s, radix))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntLit {
|
||||
fn signed_or_default(&self) -> bool {
|
||||
self.signed.unwrap_or(self.base == Base::Decimal)
|
||||
}
|
||||
fn cleaned(&self) -> String {
|
||||
let mut out = String::new();
|
||||
if self.minus {
|
||||
out.push('-');
|
||||
}
|
||||
out.extend(self.digits.chars().filter(|c| *c != '_'));
|
||||
out
|
||||
}
|
||||
/// IntegerLiteral.create with the given type.
|
||||
fn create(&self, ty: TypeSuffix, state: &mut State<SV>) -> Option<Tag> {
|
||||
let signed = self.signed_or_default();
|
||||
if !signed && self.minus {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_non_negative_number"));
|
||||
return None;
|
||||
}
|
||||
let s = self.cleaned();
|
||||
let radix = match self.base {
|
||||
Base::Binary => 2,
|
||||
Base::Decimal => 10,
|
||||
Base::Hex => 16,
|
||||
};
|
||||
let r = if signed {
|
||||
match ty {
|
||||
TypeSuffix::Byte => parse_small(&s, radix, -128, 127).map(|v| Tag::Byte(v as i8)),
|
||||
TypeSuffix::Short => {
|
||||
parse_small(&s, radix, -32768, 32767).map(|v| Tag::Short(v as i16))
|
||||
}
|
||||
TypeSuffix::Int => parse_int(&s, radix).map(Tag::Int),
|
||||
TypeSuffix::Long => parse_long(&s, radix).map(Tag::Long),
|
||||
_ => {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_integer_type"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match ty {
|
||||
TypeSuffix::Byte => parse_int(&s, radix).and_then(|v| {
|
||||
if v >> 8 == 0 {
|
||||
Ok(Tag::Byte(v as u8 as i8))
|
||||
} else {
|
||||
Err(format!("out of range: {v}"))
|
||||
}
|
||||
}),
|
||||
TypeSuffix::Short => parse_int(&s, radix).and_then(|v| {
|
||||
if v >> 16 == 0 {
|
||||
Ok(Tag::Short(v as u16 as i16))
|
||||
} else {
|
||||
Err(format!("out of range: {v}"))
|
||||
}
|
||||
}),
|
||||
TypeSuffix::Int => parse_unsigned_int(&s, radix).map(Tag::Int),
|
||||
TypeSuffix::Long => parse_unsigned_long(&s, radix).map(Tag::Long),
|
||||
_ => {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_integer_type"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
};
|
||||
match r {
|
||||
Ok(t) => Some(t),
|
||||
Err(m) => {
|
||||
state.store_at_mark(number_error(m));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn float_tag(text: &str, ty: Option<TypeSuffix>, state: &mut State<SV>) -> Option<Tag> {
|
||||
match ty {
|
||||
Some(TypeSuffix::Float) => {
|
||||
let v: f32 = text.parse().unwrap_or(f32::NAN);
|
||||
if !v.is_finite() {
|
||||
state.store_at_mark(delayed("snbt.parser.infinity_not_allowed"));
|
||||
return None;
|
||||
}
|
||||
Some(Tag::Float(v.to_bits()))
|
||||
}
|
||||
None | Some(TypeSuffix::Double) => {
|
||||
let v: f64 = text.parse().unwrap_or(f64::NAN);
|
||||
if !v.is_finite() {
|
||||
state.store_at_mark(delayed("snbt.parser.infinity_not_allowed"));
|
||||
return None;
|
||||
}
|
||||
Some(Tag::Double(v.to_bits()))
|
||||
}
|
||||
_ => {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_float_type"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_str(state: &State<SV>, atom: &'static str) -> Option<String> {
|
||||
match state.scope.get(atom) {
|
||||
Some(SV::Str(s)) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn get_tag(state: &State<SV>, atom: &'static str) -> Option<Tag> {
|
||||
match state.scope.get(atom) {
|
||||
Some(SV::Tag(t)) => Some(t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn get_list(state: &State<SV>, atom: &'static str) -> Vec<SV> {
|
||||
match state.scope.get(atom) {
|
||||
Some(SV::List(l)) => l,
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(c: char) -> bool {
|
||||
c.is_ascii_hexdigit()
|
||||
}
|
||||
|
||||
/// SnbtGrammar.createParser over NBT.
|
||||
pub fn grammar() -> Grammar<SV> {
|
||||
let mut g: Grammar<SV> = Grammar::new();
|
||||
g.put_term(
|
||||
"sign",
|
||||
alt(vec![
|
||||
seq(vec![ch('+'), Term::Marker("sign", SV::Sign(false))]),
|
||||
seq(vec![ch('-'), Term::Marker("sign", SV::Sign(true))]),
|
||||
]),
|
||||
|s| s.scope.get("sign"),
|
||||
);
|
||||
let suffix = |signed: Option<bool>, ty: TypeSuffix| {
|
||||
Term::Marker("integer_suffix", SV::Suffix(signed, Some(ty)))
|
||||
};
|
||||
let types = |signed: Option<bool>| {
|
||||
alt(vec![
|
||||
seq(vec![chs('b', 'B'), suffix(signed, TypeSuffix::Byte)]),
|
||||
seq(vec![chs('s', 'S'), suffix(signed, TypeSuffix::Short)]),
|
||||
seq(vec![chs('i', 'I'), suffix(signed, TypeSuffix::Int)]),
|
||||
seq(vec![chs('l', 'L'), suffix(signed, TypeSuffix::Long)]),
|
||||
])
|
||||
};
|
||||
g.put_term(
|
||||
"integer_suffix",
|
||||
alt(vec![
|
||||
seq(vec![chs('u', 'U'), types(Some(false))]),
|
||||
seq(vec![chs('s', 'S'), types(Some(true))]),
|
||||
seq(vec![chs('b', 'B'), suffix(None, TypeSuffix::Byte)]),
|
||||
seq(vec![chs('s', 'S'), suffix(None, TypeSuffix::Short)]),
|
||||
seq(vec![chs('i', 'I'), suffix(None, TypeSuffix::Int)]),
|
||||
seq(vec![chs('l', 'L'), suffix(None, TypeSuffix::Long)]),
|
||||
]),
|
||||
|s| s.scope.get("integer_suffix"),
|
||||
);
|
||||
g.put_custom("binary_numeral", |s| {
|
||||
number_run(
|
||||
s,
|
||||
|c| matches!(c, '0' | '1' | '_'),
|
||||
"snbt.parser.expected_binary_numeral",
|
||||
)
|
||||
});
|
||||
g.put_custom("decimal_numeral", |s| {
|
||||
number_run(
|
||||
s,
|
||||
|c| c.is_ascii_digit() || c == '_',
|
||||
"snbt.parser.expected_decimal_numeral",
|
||||
)
|
||||
});
|
||||
g.put_custom("hex_numeral", |s| {
|
||||
number_run(
|
||||
s,
|
||||
|c| c.is_ascii_hexdigit() || c == '_',
|
||||
"snbt.parser.expected_hex_numeral",
|
||||
)
|
||||
});
|
||||
let sign = g.named("sign");
|
||||
let hex_numeral = g.named("hex_numeral");
|
||||
let binary_numeral = g.named("binary_numeral");
|
||||
let decimal = g.named("decimal_numeral");
|
||||
let decimal2 = g.named("decimal_numeral");
|
||||
let isuffix = g.named("integer_suffix");
|
||||
g.put_term(
|
||||
"integer_literal",
|
||||
seq(vec![
|
||||
opt(sign),
|
||||
alt(vec![
|
||||
seq(vec![
|
||||
ch('0'),
|
||||
Term::Cut,
|
||||
alt(vec![
|
||||
seq(vec![chs('x', 'X'), Term::Cut, hex_numeral]),
|
||||
seq(vec![chs('b', 'B'), binary_numeral]),
|
||||
seq(vec![
|
||||
decimal,
|
||||
Term::Cut,
|
||||
Term::Fail(delayed("snbt.parser.leading_zero_not_allowed")),
|
||||
]),
|
||||
Term::Marker("decimal_numeral", SV::Str("0".into())),
|
||||
]),
|
||||
]),
|
||||
decimal2,
|
||||
]),
|
||||
opt(isuffix),
|
||||
]),
|
||||
|s| {
|
||||
let (signed, ty) = match s.scope.get("integer_suffix") {
|
||||
Some(SV::Suffix(a, b)) => (a, b),
|
||||
_ => (None, None),
|
||||
};
|
||||
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
|
||||
let (base, digits) = if let Some(d) = get_str(s, "decimal_numeral") {
|
||||
(Base::Decimal, d)
|
||||
} else if let Some(h) = get_str(s, "hex_numeral") {
|
||||
(Base::Hex, h)
|
||||
} else {
|
||||
(
|
||||
Base::Binary,
|
||||
get_str(s, "binary_numeral").unwrap_or_default(),
|
||||
)
|
||||
};
|
||||
Some(SV::Int(IntLit {
|
||||
minus,
|
||||
base,
|
||||
digits,
|
||||
signed,
|
||||
ty,
|
||||
}))
|
||||
},
|
||||
);
|
||||
g.put_term(
|
||||
"float_type_suffix",
|
||||
alt(vec![
|
||||
seq(vec![
|
||||
chs('f', 'F'),
|
||||
Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float)),
|
||||
]),
|
||||
seq(vec![
|
||||
chs('d', 'D'),
|
||||
Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double)),
|
||||
]),
|
||||
]),
|
||||
|s| s.scope.get("float_type_suffix"),
|
||||
);
|
||||
let sign = g.named("sign");
|
||||
let decimal = g.named("decimal_numeral");
|
||||
g.put_term(
|
||||
"float_exponent_part",
|
||||
seq(vec![chs('e', 'E'), opt(sign), decimal]),
|
||||
|s| {
|
||||
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
|
||||
Some(SV::Exp(
|
||||
minus,
|
||||
get_str(s, "decimal_numeral").unwrap_or_default(),
|
||||
))
|
||||
},
|
||||
);
|
||||
let sign = g.named("sign");
|
||||
let mut whole = || g.named_as("decimal_numeral", "float_whole_part");
|
||||
let (w1, w2, w3) = (whole(), whole(), whole());
|
||||
let f1 = g.named_as("decimal_numeral", "float_fraction_part");
|
||||
let f2 = g.named_as("decimal_numeral", "float_fraction_part");
|
||||
let mut exp = || g.named("float_exponent_part");
|
||||
let (e1, e2, e3, e4) = (exp(), exp(), exp(), exp());
|
||||
let mut fs = || g.named("float_type_suffix");
|
||||
let (s1, s2, s3, s4) = (fs(), fs(), fs(), fs());
|
||||
g.put_term(
|
||||
"float_literal",
|
||||
seq(vec![
|
||||
opt(sign),
|
||||
alt(vec![
|
||||
seq(vec![w1, ch('.'), Term::Cut, opt(f1), opt(e1), opt(s1)]),
|
||||
seq(vec![ch('.'), Term::Cut, f2, opt(e2), opt(s2)]),
|
||||
seq(vec![w2, e3, Term::Cut, opt(s3)]),
|
||||
seq(vec![w3, opt(e4), s4]),
|
||||
]),
|
||||
]),
|
||||
|s| {
|
||||
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
|
||||
let mut text = String::new();
|
||||
if minus {
|
||||
text.push('-');
|
||||
}
|
||||
if let Some(w) = get_str(s, "float_whole_part") {
|
||||
text.extend(w.chars().filter(|c| *c != '_'));
|
||||
}
|
||||
if let Some(f) = get_str(s, "float_fraction_part") {
|
||||
text.push('.');
|
||||
text.extend(f.chars().filter(|c| *c != '_'));
|
||||
}
|
||||
if let Some(SV::Exp(m, d)) = s.scope.get("float_exponent_part") {
|
||||
text.push('e');
|
||||
if m {
|
||||
text.push('-');
|
||||
}
|
||||
text.extend(d.chars().filter(|c| *c != '_'));
|
||||
}
|
||||
let ty = match s.scope.get("float_type_suffix") {
|
||||
Some(SV::Type(t)) => Some(t),
|
||||
_ => None,
|
||||
};
|
||||
float_tag(&text, ty, s).map(SV::Tag)
|
||||
},
|
||||
);
|
||||
for (name, n) in [
|
||||
("string_hex_2", 2),
|
||||
("string_hex_4", 4),
|
||||
("string_hex_8", 8),
|
||||
] {
|
||||
g.put_custom(name, move |s| {
|
||||
greedy(
|
||||
s,
|
||||
hex,
|
||||
n,
|
||||
n,
|
||||
Reason::Delayed("snbt.parser.expected_hex_escape", vec![n.to_string()]),
|
||||
)
|
||||
});
|
||||
}
|
||||
g.put_custom("string_unicode_name", |s| {
|
||||
greedy(
|
||||
s,
|
||||
|c| c.is_ascii_alphanumeric() || c == '-' || c == ' ',
|
||||
1,
|
||||
usize::MAX,
|
||||
delayed("snbt.parser.invalid_character_name"),
|
||||
)
|
||||
});
|
||||
let esc = |c: char, v: &str| {
|
||||
seq(vec![
|
||||
ch(c),
|
||||
Term::Marker("string_escape_sequence", SV::Str(v.into())),
|
||||
])
|
||||
};
|
||||
let h2 = g.named("string_hex_2");
|
||||
let h4 = g.named("string_hex_4");
|
||||
let h8 = g.named("string_hex_8");
|
||||
let un = g.named("string_unicode_name");
|
||||
g.put_term(
|
||||
"string_escape_sequence",
|
||||
alt(vec![
|
||||
esc('b', "\u{8}"),
|
||||
esc('s', " "),
|
||||
esc('t', "\t"),
|
||||
esc('n', "\n"),
|
||||
esc('f', "\u{c}"),
|
||||
esc('r', "\r"),
|
||||
esc('\\', "\\"),
|
||||
esc('\'', "'"),
|
||||
esc('"', "\""),
|
||||
seq(vec![ch('x'), h2]),
|
||||
seq(vec![ch('u'), h4]),
|
||||
seq(vec![ch('U'), h8]),
|
||||
seq(vec![ch('N'), ch('{'), un, ch('}')]),
|
||||
]),
|
||||
|s| {
|
||||
if let Some(SV::Str(plain)) = s.scope.get_any(&["string_escape_sequence"]) {
|
||||
return Some(SV::Str(plain));
|
||||
}
|
||||
if let Some(SV::Str(h)) =
|
||||
s.scope
|
||||
.get_any(&["string_hex_2", "string_hex_4", "string_hex_8"])
|
||||
{
|
||||
let cp = u32::from_str_radix(&h, 16).unwrap_or(u32::MAX);
|
||||
if cp > 0x10ffff {
|
||||
s.store_at_mark(Reason::Delayed(
|
||||
"snbt.parser.invalid_codepoint",
|
||||
vec![format!("U+{cp:08X}")],
|
||||
));
|
||||
return None;
|
||||
}
|
||||
return Some(SV::Str(
|
||||
char::from_u32(cp).unwrap_or('\u{fffd}').to_string(),
|
||||
));
|
||||
}
|
||||
// Character.codePointOf: Unicode names are not tabulated here.
|
||||
s.store_at_mark(delayed("snbt.parser.invalid_character_name"));
|
||||
None
|
||||
},
|
||||
);
|
||||
g.put_custom("string_plain_contents", |s| {
|
||||
greedy(
|
||||
s,
|
||||
|c| !matches!(c, '"' | '\'' | '\\'),
|
||||
1,
|
||||
usize::MAX,
|
||||
delayed("snbt.parser.invalid_string_contents"),
|
||||
)
|
||||
});
|
||||
for (chunk, contents, other) in [
|
||||
(
|
||||
"single_quoted_string_chunk",
|
||||
"single_quoted_string_contents",
|
||||
'"',
|
||||
),
|
||||
(
|
||||
"double_quoted_string_chunk",
|
||||
"double_quoted_string_contents",
|
||||
'\'',
|
||||
),
|
||||
] {
|
||||
let plain = g.named_as("string_plain_contents", "string_contents");
|
||||
let escape = g.named_as("string_escape_sequence", "string_contents");
|
||||
g.put_term(
|
||||
chunk,
|
||||
alt(vec![
|
||||
plain,
|
||||
seq(vec![ch('\\'), escape]),
|
||||
seq(vec![
|
||||
ch(other),
|
||||
Term::Marker("string_contents", SV::Str(other.to_string())),
|
||||
]),
|
||||
]),
|
||||
|s| s.scope.get("string_contents"),
|
||||
);
|
||||
let rule = g.id(chunk);
|
||||
g.put_term(
|
||||
contents,
|
||||
Term::Repeated {
|
||||
rule,
|
||||
list: "string_chunks",
|
||||
min: 0,
|
||||
},
|
||||
|s| {
|
||||
let mut out = String::new();
|
||||
for v in get_list(s, "string_chunks") {
|
||||
if let SV::Str(x) = v {
|
||||
out.push_str(&x);
|
||||
}
|
||||
}
|
||||
Some(SV::Str(out))
|
||||
},
|
||||
);
|
||||
}
|
||||
let dq = g.named_as("double_quoted_string_contents", "string_contents");
|
||||
let sq = g.named_as("single_quoted_string_contents", "string_contents");
|
||||
g.put_term(
|
||||
"quoted_string_literal",
|
||||
alt(vec![
|
||||
seq(vec![ch('"'), Term::Cut, opt(dq), ch('"')]),
|
||||
seq(vec![ch('\''), opt(sq), ch('\'')]),
|
||||
]),
|
||||
|s| s.scope.get("string_contents"),
|
||||
);
|
||||
g.put_custom("unquoted_string", |s| {
|
||||
let mut r = s.reader();
|
||||
r.skip_whitespace();
|
||||
s.set_reader(&r);
|
||||
let cursor = s.cursor;
|
||||
let v = r.read_unquoted_string();
|
||||
s.set_reader(&r);
|
||||
if v.is_empty() {
|
||||
s.store(
|
||||
cursor,
|
||||
Sugg::Empty,
|
||||
delayed("snbt.parser.expected_unquoted_string"),
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Some(SV::Str(v.to_owned()))
|
||||
});
|
||||
let literal = g.id("literal");
|
||||
g.put_term(
|
||||
"arguments",
|
||||
Term::RepeatedSep {
|
||||
rule: literal,
|
||||
list: "arguments",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("arguments"),
|
||||
);
|
||||
let uq = g.named("unquoted_string");
|
||||
let args = g.named("arguments");
|
||||
g.put_term(
|
||||
"unquoted_string_or_builtin",
|
||||
seq(vec![uq, opt(seq(vec![ch('('), args, ch(')')]))]),
|
||||
|s| {
|
||||
let contents = get_str(s, "unquoted_string").unwrap_or_default();
|
||||
let first = contents.chars().next();
|
||||
if first.is_some_and(|c| !can_start_number(c)) {
|
||||
if let Some(SV::List(arguments)) = s.scope.get("arguments") {
|
||||
return builtin(&contents, arguments, s);
|
||||
}
|
||||
if contents.eq_ignore_ascii_case("true") {
|
||||
return Some(SV::Tag(Tag::Byte(1)));
|
||||
}
|
||||
if contents.eq_ignore_ascii_case("false") {
|
||||
return Some(SV::Tag(Tag::Byte(0)));
|
||||
}
|
||||
return Some(SV::Tag(Tag::String(JavaString::from(contents.as_str()))));
|
||||
}
|
||||
let ids = ["false", "true", "bool", "uuid"].map(String::from).to_vec();
|
||||
s.store(
|
||||
s.cursor,
|
||||
Sugg::Values(Rc::new(ids)),
|
||||
delayed("snbt.parser.invalid_unquoted_start"),
|
||||
);
|
||||
None
|
||||
},
|
||||
);
|
||||
let qs = g.named("quoted_string_literal");
|
||||
let uq = g.named("unquoted_string");
|
||||
g.put_term("map_key", alt(vec![qs, uq]), |s| {
|
||||
s.scope
|
||||
.get_any(&["quoted_string_literal", "unquoted_string"])
|
||||
});
|
||||
let key = g.named("map_key");
|
||||
let lit = g.named("literal");
|
||||
g.put_term("map_entry", seq(vec![key, ch(':'), lit]), |s| {
|
||||
let key = get_str(s, "map_key").unwrap_or_default();
|
||||
if key.is_empty() {
|
||||
s.store_at_mark(delayed("snbt.parser.empty_key"));
|
||||
return None;
|
||||
}
|
||||
let value = get_tag(s, "literal")?;
|
||||
Some(SV::Entry(key, value))
|
||||
});
|
||||
let entry = g.id("map_entry");
|
||||
g.put_term(
|
||||
"map_entries",
|
||||
Term::RepeatedSep {
|
||||
rule: entry,
|
||||
list: "map_entries",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("map_entries"),
|
||||
);
|
||||
let entries = g.named("map_entries");
|
||||
g.put_term("map_literal", seq(vec![ch('{'), entries, ch('}')]), |s| {
|
||||
let mut map = Compound::new();
|
||||
for e in get_list(s, "map_entries") {
|
||||
if let SV::Entry(k, v) = e {
|
||||
map.insert(JavaString::from(k.as_str()), v);
|
||||
}
|
||||
}
|
||||
Some(SV::Tag(Tag::Compound(map)))
|
||||
});
|
||||
g.put_term(
|
||||
"list_entries",
|
||||
Term::RepeatedSep {
|
||||
rule: literal,
|
||||
list: "list_entries",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("list_entries"),
|
||||
);
|
||||
g.put_term(
|
||||
"array_prefix",
|
||||
alt(vec![
|
||||
seq(vec![
|
||||
ch('B'),
|
||||
Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte)),
|
||||
]),
|
||||
seq(vec![
|
||||
ch('L'),
|
||||
Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long)),
|
||||
]),
|
||||
seq(vec![
|
||||
ch('I'),
|
||||
Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int)),
|
||||
]),
|
||||
]),
|
||||
|s| s.scope.get("array_prefix"),
|
||||
);
|
||||
let int_lit = g.id("integer_literal");
|
||||
g.put_term(
|
||||
"int_array_entries",
|
||||
Term::RepeatedSep {
|
||||
rule: int_lit,
|
||||
list: "int_array_entries",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("int_array_entries"),
|
||||
);
|
||||
let prefix = g.named("array_prefix");
|
||||
let ia = g.named("int_array_entries");
|
||||
let le = g.named("list_entries");
|
||||
g.put_term(
|
||||
"list_literal",
|
||||
seq(vec![
|
||||
ch('['),
|
||||
alt(vec![seq(vec![prefix, ch(';'), ia]), le]),
|
||||
ch(']'),
|
||||
]),
|
||||
|s| {
|
||||
if let Some(SV::Prefix(p)) = s.scope.get("array_prefix") {
|
||||
let entries = get_list(s, "int_array_entries");
|
||||
return array(p, entries, s).map(SV::Tag);
|
||||
}
|
||||
let items: Vec<Tag> = get_list(s, "list_entries")
|
||||
.into_iter()
|
||||
.filter_map(|v| match v {
|
||||
SV::Tag(t) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Some(SV::Tag(Tag::List(items)))
|
||||
},
|
||||
);
|
||||
let float_lit = g.named_as("float_literal", "literal");
|
||||
let int_named = g.named("integer_literal");
|
||||
let quoted = g.named("quoted_string_literal");
|
||||
let map = g.named_as("map_literal", "literal");
|
||||
let list = g.named_as("list_literal", "literal");
|
||||
let builtin_term = g.named_as("unquoted_string_or_builtin", "literal");
|
||||
g.put_term(
|
||||
"literal",
|
||||
alt(vec![
|
||||
seq(vec![
|
||||
look(Term::Chars {
|
||||
values: Vec::new(),
|
||||
accept: Some(can_start_number),
|
||||
}),
|
||||
alt(vec![float_lit, int_named]),
|
||||
]),
|
||||
seq(vec![look(chs('"', '\'')), Term::Cut, quoted]),
|
||||
seq(vec![look(ch('{')), Term::Cut, map]),
|
||||
seq(vec![look(ch('[')), Term::Cut, list]),
|
||||
builtin_term,
|
||||
]),
|
||||
|s| {
|
||||
if let Some(q) = get_str(s, "quoted_string_literal") {
|
||||
return Some(SV::Tag(Tag::String(JavaString::from(q.as_str()))));
|
||||
}
|
||||
if let Some(SV::Int(i)) = s.scope.get("integer_literal") {
|
||||
let ty = i.ty.unwrap_or(TypeSuffix::Int);
|
||||
return i.create(ty, s).map(SV::Tag);
|
||||
}
|
||||
s.scope.get("literal")
|
||||
},
|
||||
);
|
||||
g.top = literal;
|
||||
g
|
||||
}
|
||||
|
||||
fn array(p: ArrayPrefix, entries: Vec<SV>, s: &mut State<SV>) -> Option<Tag> {
|
||||
let (default, allowed): (TypeSuffix, &[TypeSuffix]) = match p {
|
||||
ArrayPrefix::Byte => (TypeSuffix::Byte, &[]),
|
||||
ArrayPrefix::Int => (TypeSuffix::Int, &[TypeSuffix::Byte, TypeSuffix::Short]),
|
||||
ArrayPrefix::Long => (
|
||||
TypeSuffix::Long,
|
||||
&[TypeSuffix::Byte, TypeSuffix::Short, TypeSuffix::Int],
|
||||
),
|
||||
};
|
||||
let mut values: Vec<i64> = Vec::new();
|
||||
for e in entries {
|
||||
let SV::Int(lit) = e else { continue };
|
||||
let ty = match lit.ty {
|
||||
None => default,
|
||||
Some(t) if t == default || allowed.contains(&t) => t,
|
||||
Some(_) => {
|
||||
s.store_at_mark(delayed("snbt.parser.invalid_array_element_type"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let v = match lit.create(ty, s)? {
|
||||
Tag::Byte(v) => i64::from(v),
|
||||
Tag::Short(v) => i64::from(v),
|
||||
Tag::Int(v) => i64::from(v),
|
||||
Tag::Long(v) => v,
|
||||
_ => 0,
|
||||
};
|
||||
values.push(v);
|
||||
}
|
||||
Some(match p {
|
||||
ArrayPrefix::Byte => Tag::ByteArray(values.iter().map(|v| *v as i8 as u8).collect()),
|
||||
ArrayPrefix::Int => Tag::IntArray(values.iter().map(|v| *v as i32).collect()),
|
||||
ArrayPrefix::Long => Tag::LongArray(values),
|
||||
})
|
||||
}
|
||||
|
||||
fn builtin(id: &str, arguments: Vec<SV>, s: &mut State<SV>) -> Option<SV> {
|
||||
let args: Vec<Tag> = arguments
|
||||
.into_iter()
|
||||
.filter_map(|v| match v {
|
||||
SV::Tag(t) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
match (id, args.len()) {
|
||||
("bool", 1) => {
|
||||
let b = match &args[0] {
|
||||
Tag::Byte(v) => Some(*v != 0),
|
||||
Tag::Short(v) => Some(*v != 0),
|
||||
Tag::Int(v) => Some(*v != 0),
|
||||
Tag::Long(v) => Some(*v != 0),
|
||||
Tag::Float(v) => Some(f32::from_bits(*v) != 0.0),
|
||||
Tag::Double(v) => Some(f64::from_bits(*v) != 0.0),
|
||||
_ => None,
|
||||
};
|
||||
match b {
|
||||
Some(b) => Some(SV::Tag(Tag::Byte(i8::from(b)))),
|
||||
None => {
|
||||
s.store_at_mark(delayed("snbt.parser.expected_number_or_boolean"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
("uuid", 1) => {
|
||||
let parsed = match &args[0] {
|
||||
Tag::String(text) => super::selector::java_uuid(&text.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
match parsed {
|
||||
Some(u) => Some(SV::Tag(Tag::IntArray(vec![
|
||||
(u >> 96) as u32 as i32,
|
||||
(u >> 64) as u32 as i32,
|
||||
(u >> 32) as u32 as i32,
|
||||
u as u32 as i32,
|
||||
]))),
|
||||
None => {
|
||||
s.store_at_mark(delayed("snbt.parser.expected_string_uuid"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
s.store_at_mark(Reason::Delayed(
|
||||
"snbt.parser.no_such_operation",
|
||||
vec![format!("{id}/{}", args.len())],
|
||||
));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GRAMMAR: Grammar<SV> = grammar();
|
||||
}
|
||||
|
||||
/// TagParser.parseAsArgument: one SNBT value at the reader's cursor.
|
||||
pub fn parse_tag_argument(reader: &mut Reader) -> CmdResult<Tag> {
|
||||
GRAMMAR.with(|g| match g.parse_for_commands(reader)? {
|
||||
SV::Tag(t) => Ok(t),
|
||||
_ => Err(CommandError::tr_at(
|
||||
"argument.nbt.expected.compound",
|
||||
&[],
|
||||
reader,
|
||||
)),
|
||||
})
|
||||
}
|
||||
/// TagParser.parseCompoundAsArgument.
|
||||
pub fn parse_compound_argument(reader: &mut Reader) -> CmdResult<Compound> {
|
||||
match parse_tag_argument(reader)? {
|
||||
Tag::Compound(c) => Ok(c),
|
||||
_ => Err(CommandError::tr_at(
|
||||
"argument.nbt.expected.compound",
|
||||
&[],
|
||||
reader,
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// TagParser.parseFully.
|
||||
pub fn parse_fully(text: &str) -> CmdResult<Tag> {
|
||||
let mut reader = Reader::new(text);
|
||||
let tag = parse_tag_argument(&mut reader)?;
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() {
|
||||
return Err(CommandError::tr_at("argument.nbt.trailing", &[], &reader));
|
||||
}
|
||||
Ok(tag)
|
||||
}
|
||||
/// The grammar's completion suggestions (ParserBasedArgument.listSuggestions).
|
||||
pub fn suggest(builder: &mut SuggestionsBuilder) {
|
||||
GRAMMAR.with(|g| g.parse_for_suggestions(builder));
|
||||
}
|
||||
/// Parse with an outer state (TagParseRule inside another grammar).
|
||||
pub fn rule_in<V: super::packrat::Value>(
|
||||
state: &mut State<V>,
|
||||
wrap: impl Fn(Tag) -> V,
|
||||
) -> Option<V> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
state.set_reader(&r);
|
||||
let mark = state.cursor;
|
||||
let mut reader = state.reader();
|
||||
match parse_tag_argument(&mut reader) {
|
||||
Ok(t) => {
|
||||
state.set_reader(&reader);
|
||||
Some(wrap(t))
|
||||
}
|
||||
Err(e) => {
|
||||
state.store(mark, Sugg::Empty, Reason::Error(e));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,612 +0,0 @@
|
||||
use super::{args::*, vanilla, *};
|
||||
|
||||
fn reg() -> Registries {
|
||||
let mut r = Registries {
|
||||
permission: 4,
|
||||
..Registries::default()
|
||||
};
|
||||
r.items = vec![
|
||||
"minecraft:diamond".into(),
|
||||
"minecraft:diamond_sword".into(),
|
||||
"minecraft:stone".into(),
|
||||
];
|
||||
r.blocks.insert("minecraft:stone".into(), vec![]);
|
||||
r.blocks.insert(
|
||||
"minecraft:oak_stairs".into(),
|
||||
vec![
|
||||
("facing".into(), vec!["north".into(), "south".into()]),
|
||||
("half".into(), vec!["top".into(), "bottom".into()]),
|
||||
],
|
||||
);
|
||||
r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()];
|
||||
r.entity_types = vec![
|
||||
"minecraft:pig".into(),
|
||||
"minecraft:player".into(),
|
||||
"minecraft:zombie".into(),
|
||||
];
|
||||
r.players = vec!["Player".into()];
|
||||
r.dimensions = vec!["minecraft:overworld".into()];
|
||||
r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()];
|
||||
// The registry elements the commands below name (vanilla checks them while parsing).
|
||||
let mut registry = |name: &str, ids: &[&str]| {
|
||||
r.by_registry.insert(
|
||||
name.into(),
|
||||
RegistryIds {
|
||||
ids: ids.iter().map(|s| (*s).to_owned()).collect(),
|
||||
tags: Vec::new(),
|
||||
},
|
||||
);
|
||||
};
|
||||
registry(
|
||||
"minecraft:worldgen/biome",
|
||||
&["minecraft:desert", "minecraft:plains"],
|
||||
);
|
||||
registry(
|
||||
"minecraft:damage_type",
|
||||
&["minecraft:fall", "minecraft:magic"],
|
||||
);
|
||||
registry(
|
||||
"minecraft:attribute",
|
||||
&["minecraft:max_health", "minecraft:scale"],
|
||||
);
|
||||
registry("minecraft:item_modifier", &["a:b"]);
|
||||
registry("minecraft:predicate", &["a:b"]);
|
||||
registry(
|
||||
"minecraft:loot_table",
|
||||
&[
|
||||
"minecraft:chests/simple_dungeon",
|
||||
"minecraft:chests/x",
|
||||
"minecraft:gameplay/fishing",
|
||||
],
|
||||
);
|
||||
registry(
|
||||
"minecraft:entity_type",
|
||||
&["minecraft:pig", "minecraft:player", "minecraft:zombie"],
|
||||
);
|
||||
registry(
|
||||
"minecraft:item",
|
||||
&[
|
||||
"minecraft:diamond",
|
||||
"minecraft:diamond_sword",
|
||||
"minecraft:stone",
|
||||
],
|
||||
);
|
||||
r
|
||||
}
|
||||
fn run(input: &str) -> CmdResult<(String, Vec<String>)> {
|
||||
let reg = reg();
|
||||
let parse = vanilla::dispatcher().parse(input, ®);
|
||||
let (ctx, id) = parse.executable()?;
|
||||
Ok((
|
||||
id.to_owned(),
|
||||
ctx.args.iter().map(|a| a.name.clone()).collect(),
|
||||
))
|
||||
}
|
||||
fn suggestions(input: &str) -> Vec<String> {
|
||||
let reg = reg();
|
||||
let d = vanilla::dispatcher();
|
||||
let parse = d.parse(input, ®);
|
||||
d.suggestions(&parse, input.len(), ®)
|
||||
.1
|
||||
.into_iter()
|
||||
.map(|s| s.text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_matches_brigadier() {
|
||||
let mut r = Reader::new("12 -3.5 abc \"q\\\"x\" true");
|
||||
assert_eq!(r.read_int().unwrap(), 12);
|
||||
r.skip();
|
||||
assert_eq!(r.read_double().unwrap(), -3.5);
|
||||
r.skip();
|
||||
assert_eq!(r.read_unquoted_string(), "abc");
|
||||
r.skip();
|
||||
assert_eq!(r.read_string().unwrap(), "q\"x");
|
||||
r.skip();
|
||||
assert!(r.read_boolean().unwrap());
|
||||
let e = Reader::new("1.5").read_int().unwrap_err();
|
||||
assert_eq!(e.message.plain(), "parsing.int.invalid");
|
||||
assert_eq!(e.context().unwrap(), "<--[HERE]");
|
||||
}
|
||||
#[test]
|
||||
fn parses_vanilla_commands() {
|
||||
assert_eq!(run("gamemode creative").unwrap().0, "gamemode");
|
||||
assert_eq!(
|
||||
run("gamemode creative @s").unwrap().1,
|
||||
["gamemode", "target"]
|
||||
);
|
||||
assert_eq!(
|
||||
run("give @s minecraft:diamond 64").unwrap().1,
|
||||
["targets", "item", "count"]
|
||||
);
|
||||
assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location");
|
||||
assert_eq!(run("tp Player").unwrap().0, "teleport.destination");
|
||||
assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location");
|
||||
assert_eq!(
|
||||
run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0,
|
||||
"teleport.targets.location"
|
||||
);
|
||||
assert_eq!(run("time set 1000").unwrap().0, "time.set");
|
||||
assert_eq!(run("time set 1d").unwrap().0, "time.set");
|
||||
assert_eq!(run("time set day").unwrap().0, "time.set.marker");
|
||||
assert_eq!(run("time query gametime").unwrap().0, "time.query.gametime");
|
||||
assert_eq!(run("weather rain 10s").unwrap().0, "weather");
|
||||
assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience");
|
||||
assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule");
|
||||
assert_eq!(
|
||||
run("gamerule minecraft:random_tick_speed 10").unwrap().0,
|
||||
"gamerule"
|
||||
);
|
||||
assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill");
|
||||
assert_eq!(
|
||||
run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone")
|
||||
.unwrap()
|
||||
.0,
|
||||
"fill"
|
||||
);
|
||||
assert_eq!(
|
||||
run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0,
|
||||
"clone"
|
||||
);
|
||||
assert_eq!(
|
||||
run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0,
|
||||
"setblock"
|
||||
);
|
||||
assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon");
|
||||
assert_eq!(run("difficulty hard").unwrap().0, "difficulty");
|
||||
assert_eq!(run("say hello @p").unwrap().0, "say");
|
||||
let reg = reg();
|
||||
let parse =
|
||||
vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", ®);
|
||||
let (ctx, _) = parse.executable().unwrap();
|
||||
assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move"));
|
||||
}
|
||||
#[test]
|
||||
fn vanilla_error_messages() {
|
||||
let e = run("foo").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
assert_eq!(e.cursor, 0);
|
||||
let e = run("gamemode").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
let e = run("gamemode creatve").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.gamemode.invalid");
|
||||
// GameModeArgument reports the error after the word.
|
||||
assert_eq!(e.cursor, 16);
|
||||
let e = run("give @s minecraft:dirt").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.item.id.invalid");
|
||||
let e = run("give @s diamond 0").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.integer.low");
|
||||
let e = run("gamemode creative @e").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.player.entities");
|
||||
let e = run("setblock 1 2").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.pos3d.incomplete");
|
||||
let e = run("setblock 1 2 3 oak_stairs[facing=up]").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.block.property.invalid");
|
||||
}
|
||||
#[test]
|
||||
fn commands_need_allow_commands() {
|
||||
// IntegratedServer.getProfilePermissions: the owner of a world without
|
||||
// Allow Commands is at LevelBasedPermissionSet.ALL.
|
||||
let reg = Registries {
|
||||
permission: 0,
|
||||
..reg()
|
||||
};
|
||||
let d = vanilla::game_dispatcher();
|
||||
let e = d.parse("gamemode creative", ®).executable().unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
assert!(d.parse("me waves", ®).executable().is_ok());
|
||||
let parse = d.parse("", ®);
|
||||
// Brigadier itself lists every literal; the chat's (client tree) only
|
||||
// the ones the player may use.
|
||||
assert!(
|
||||
d.suggestions(&parse, 0, ®)
|
||||
.1
|
||||
.iter()
|
||||
.any(|s| s.text == "gamemode")
|
||||
);
|
||||
let root: Vec<String> = d
|
||||
.client_suggestions(&parse, 0, ®)
|
||||
.1
|
||||
.into_iter()
|
||||
.map(|s| s.text)
|
||||
.collect();
|
||||
// Commands.java with CommandSelection.INTEGRATED: seed and version need no level.
|
||||
assert_eq!(
|
||||
root,
|
||||
[
|
||||
"help", "list", "me", "msg", "random", "seed", "teammsg", "tell", "tm", "trigger",
|
||||
"version", "w"
|
||||
]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn suggestions_like_vanilla() {
|
||||
let root = suggestions("");
|
||||
assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned()));
|
||||
assert_eq!(suggestions("game"), ["gamemode", "gamerule"]);
|
||||
assert_eq!(
|
||||
suggestions("gamemode "),
|
||||
["adventure", "creative", "spectator", "survival"]
|
||||
);
|
||||
assert_eq!(suggestions("gamemode c"), ["creative"]);
|
||||
assert_eq!(
|
||||
suggestions("give @s dia"),
|
||||
["minecraft:diamond", "minecraft:diamond_sword"]
|
||||
);
|
||||
// Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr).
|
||||
assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]);
|
||||
assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]);
|
||||
assert_eq!(suggestions("kill @e"), ["["]);
|
||||
assert_eq!(suggestions("kill @e[ty"), ["type="]);
|
||||
assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned()));
|
||||
assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]);
|
||||
// BlockStateParser suggests every value of the property, unfiltered.
|
||||
assert_eq!(
|
||||
suggestions("setblock 0 0 0 oak_stairs[facing=n"),
|
||||
["north", "south"]
|
||||
);
|
||||
assert_eq!(
|
||||
suggestions("tp "),
|
||||
[
|
||||
"@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"
|
||||
]
|
||||
);
|
||||
assert_eq!(suggestions("time set 5"), ["d", "s", "t"]);
|
||||
assert!(suggestions("time set ").contains(&"minecraft:day".to_owned()));
|
||||
}
|
||||
#[test]
|
||||
fn smart_usage_matches_brigadier() {
|
||||
let d = vanilla::dispatcher();
|
||||
let usage = |name: &str| {
|
||||
d.smart_usage(0, 4)
|
||||
.into_iter()
|
||||
.find(|(n, _)| d.nodes[*n].name() == name)
|
||||
.unwrap()
|
||||
.1
|
||||
};
|
||||
assert_eq!(usage("gamemode"), "gamemode <gamemode> [<target>]");
|
||||
assert_eq!(usage("give"), "give <targets> <item> [<count>]");
|
||||
assert_eq!(usage("kill"), "kill [<targets>]");
|
||||
assert_eq!(usage("weather"), "weather (clear|rain|thunder)");
|
||||
assert_eq!(usage("tp"), "tp -> teleport");
|
||||
assert_eq!(
|
||||
usage("difficulty"),
|
||||
"difficulty [peaceful|easy|normal|hard]"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn local_coordinates_follow_view() {
|
||||
// Facing south (yaw 0) moves +Z.
|
||||
let p = Coordinates::Local([0.0, 0.0, 2.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
|
||||
assert!((p[2] - 2.0).abs() < 1e-6 && p[0].abs() < 1e-6);
|
||||
// ^1 (left) while facing south is +X.
|
||||
let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
|
||||
assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}");
|
||||
let w = Coordinates::World([
|
||||
Coord {
|
||||
relative: true,
|
||||
value: 1.0,
|
||||
},
|
||||
Coord {
|
||||
relative: false,
|
||||
value: 5.0,
|
||||
},
|
||||
Coord {
|
||||
relative: true,
|
||||
value: 0.0,
|
||||
},
|
||||
]);
|
||||
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_and_tag_commands_parse() {
|
||||
let (id, args) = run("data get entity @s Pos 2.5").unwrap();
|
||||
assert_eq!(id, "data.get");
|
||||
assert_eq!(args, ["target", "path", "scale"]);
|
||||
assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get");
|
||||
assert_eq!(
|
||||
run("item modify entity @s weapon.mainhand a:b").unwrap().0,
|
||||
"item.modify"
|
||||
);
|
||||
assert_eq!(
|
||||
run("item modify block 1 2 3 container.0 a:b").unwrap().0,
|
||||
"item.modify"
|
||||
);
|
||||
assert_eq!(run("data get storage my:store").unwrap().0, "data.get");
|
||||
assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge");
|
||||
assert_eq!(
|
||||
run("data remove entity @s foo.bar[1]").unwrap().0,
|
||||
"data.remove"
|
||||
);
|
||||
let (id, args) = run("data modify storage a:b x.y insert 2 from entity @s Pos[0]").unwrap();
|
||||
assert_eq!(id, "data.modify");
|
||||
assert_eq!(
|
||||
args,
|
||||
["target", "targetPath", "index", "source", "sourcePath"]
|
||||
);
|
||||
assert_eq!(
|
||||
run("data modify block 1 2 3 Text1 set string storage a:b x 1 3")
|
||||
.unwrap()
|
||||
.0,
|
||||
"data.modify"
|
||||
);
|
||||
assert_eq!(
|
||||
run("data modify storage a:b l append value [1,2]")
|
||||
.unwrap()
|
||||
.0,
|
||||
"data.modify"
|
||||
);
|
||||
assert!(run("data modify storage a:b l explode value 1").is_err());
|
||||
assert!(run("data get storage a:b {broken").is_err());
|
||||
assert!(run("data merge storage a:b 5").is_err());
|
||||
assert_eq!(run("tag @e[tag=!x] add foo").unwrap().0, "tag.add");
|
||||
assert_eq!(run("tag @s list").unwrap().0, "tag.list");
|
||||
// Selector options added for scoreboards and NBT.
|
||||
assert!(run("kill @e[scores={a=1..},team=red,nbt={x:1b},tag=t]").is_ok());
|
||||
assert!(run("kill @e[scores={a=1..]").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoke_commands_parse() {
|
||||
for line in [
|
||||
"tag @s list",
|
||||
"random value 1..6",
|
||||
"team list",
|
||||
"data get storage a:b",
|
||||
"scoreboard objectives list",
|
||||
"function test:a",
|
||||
"execute store result score #r t run function test:a",
|
||||
"schedule function test:a 20t",
|
||||
"datapack list",
|
||||
"bossbar list",
|
||||
"item replace entity @s hotbar.0 with minecraft:stone 3",
|
||||
] {
|
||||
assert!(run(line).is_ok(), "{line}: {:?}", run(line).err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_tree_covers_vanilla_forms() {
|
||||
for line in [
|
||||
"execute as @a at @s run say hi",
|
||||
"execute store result score @s x run data get entity @s Health",
|
||||
"execute store success bossbar minecraft:b value run say hi",
|
||||
"execute store result storage a:b out int 1.5 run time query gametime",
|
||||
"execute store result entity @s Air short 1 run say hi",
|
||||
"execute if score @s a = @s b run say hi",
|
||||
"execute unless score @s a matches ..5 run say hi",
|
||||
"execute if block ~ ~ ~ minecraft:stone",
|
||||
"execute if blocks 0 0 0 1 1 1 5 5 5 masked run say hi",
|
||||
"execute if biome ~ ~ ~ minecraft:plains",
|
||||
"execute if loaded ~ ~ ~",
|
||||
"execute if dimension minecraft:overworld",
|
||||
"execute if data entity @s Inventory[0]",
|
||||
"execute unless data storage a:b x run say hi",
|
||||
"execute if predicate a:b",
|
||||
"execute if function a:b run say hi",
|
||||
"execute if items entity @s hotbar.* minecraft:stone",
|
||||
"execute if slots block 0 0 0 container.*",
|
||||
"execute positioned over world_surface run say hi",
|
||||
"execute summon minecraft:pig run say hi",
|
||||
"execute on vehicle run say hi",
|
||||
"execute on passengers as @s run say hi",
|
||||
"execute rotated as @s facing entity @s eyes align xyz anchored feet in minecraft:overworld run say hi",
|
||||
] {
|
||||
assert!(run(line).is_ok(), "{line}: {:?}", run(line).err());
|
||||
}
|
||||
assert!(run("execute positioned over nothing run say hi").is_err());
|
||||
assert!(run("execute on nobody run say hi").is_err());
|
||||
assert!(run("execute store result score @s").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_and_misc_trees() {
|
||||
assert_eq!(run("function a:b").unwrap().0, "function");
|
||||
assert_eq!(run("function #a:tag {x:1}").unwrap().0, "function");
|
||||
assert_eq!(
|
||||
run("function a:b with storage c:d path.x").unwrap().0,
|
||||
"function"
|
||||
);
|
||||
assert_eq!(run("return 5").unwrap().0, "return.value");
|
||||
assert_eq!(run("return fail").unwrap().0, "return.fail");
|
||||
assert_eq!(run("return run say hi").unwrap().0, "say");
|
||||
assert_eq!(
|
||||
run("schedule function a:b 5s append").unwrap().0,
|
||||
"schedule.function"
|
||||
);
|
||||
assert_eq!(run("schedule clear a:b").unwrap().0, "schedule.clear");
|
||||
assert_eq!(run("random roll 1..20").unwrap().0, "random.roll");
|
||||
assert_eq!(
|
||||
run("random reset * 5 true false").unwrap().0,
|
||||
"random.reset"
|
||||
);
|
||||
assert_eq!(run("teammsg hi there").unwrap().0, "teammsg");
|
||||
assert_eq!(run("tm hi").unwrap().0, "teammsg");
|
||||
assert_eq!(
|
||||
run("bossbar set a:b color pink").unwrap().0,
|
||||
"bossbar.set.color"
|
||||
);
|
||||
assert_eq!(
|
||||
run("bossbar set a:b players @a").unwrap().0,
|
||||
"bossbar.set.players"
|
||||
);
|
||||
assert_eq!(run("bossbar get a:b max").unwrap().0, "bossbar.get");
|
||||
assert_eq!(
|
||||
run("item fill block 1 2 3 container.* with minecraft:stone 5")
|
||||
.unwrap()
|
||||
.0,
|
||||
"item"
|
||||
);
|
||||
assert_eq!(
|
||||
run("item replace entity @s armor.head from block 0 0 0 container.3")
|
||||
.unwrap()
|
||||
.0,
|
||||
"item"
|
||||
);
|
||||
assert_eq!(run("tick rate 40").unwrap().0, "tick.rate");
|
||||
assert_eq!(run("tick step 1s").unwrap().0, "tick.step");
|
||||
assert_eq!(run("reload").unwrap().0, "reload");
|
||||
assert_eq!(
|
||||
run("datapack enable \"file/x\" after \"file/y\"")
|
||||
.unwrap()
|
||||
.0,
|
||||
"datapack.enable"
|
||||
);
|
||||
assert!(run("bossbar set a:b value -1").is_err());
|
||||
assert!(run("item replace entity @s nowhere.0 with minecraft:stone").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_command_trees() {
|
||||
for (line, id) in [
|
||||
("recipe give @s *", "recipe.give"),
|
||||
("recipe take @a minecraft:stick", "recipe.take"),
|
||||
("damage @e[limit=1] 5", "damage"),
|
||||
(
|
||||
"damage @s 3.5 minecraft:magic by @e[limit=1] from @s",
|
||||
"damage",
|
||||
),
|
||||
("damage @s 3 minecraft:fall at ~ ~ ~", "damage"),
|
||||
("rotate @s 90 0", "rotate"),
|
||||
("rotate @s facing entity @e[limit=1] eyes", "rotate"),
|
||||
("rotate @s facing 0 64 0", "rotate"),
|
||||
("swing", "swing"),
|
||||
("swing @e offhand whack 10", "swing"),
|
||||
("playsound minecraft:entity.cow.ambient", "playsound"),
|
||||
(
|
||||
"playsound minecraft:block.stone.break block @s ~ ~ ~ 1 1 0.5",
|
||||
"playsound",
|
||||
),
|
||||
("stopsound @s", "stopsound"),
|
||||
("stopsound @s * minecraft:ambient.cave", "stopsound"),
|
||||
("stopsound @s music minecraft:music.game", "stopsound"),
|
||||
("particle minecraft:smoke", "particle"),
|
||||
(
|
||||
"particle minecraft:dust{color:[1.0,0.0,0.0],scale:2.0} ~ ~ ~ 0.1 0.1 0.1 0 10 force @a",
|
||||
"particle",
|
||||
),
|
||||
(
|
||||
"particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~",
|
||||
"particle",
|
||||
),
|
||||
("attribute @s minecraft:max_health get 2", "attribute.get"),
|
||||
(
|
||||
"attribute @s minecraft:max_health base set 40",
|
||||
"attribute.base.set",
|
||||
),
|
||||
(
|
||||
"attribute @s minecraft:scale modifier add a:b 1.5 add_multiplied_base",
|
||||
"attribute.modifier.add",
|
||||
),
|
||||
(
|
||||
"attribute @s minecraft:scale modifier remove a:b",
|
||||
"attribute.modifier.remove",
|
||||
),
|
||||
(
|
||||
"attribute @s minecraft:scale modifier value get a:b 2",
|
||||
"attribute.modifier.get",
|
||||
),
|
||||
("ride @s mount @e[limit=1]", "ride.mount"),
|
||||
("ride @s dismount", "ride.dismount"),
|
||||
("spreadplayers 0 0 5 20 false @a", "spreadplayers"),
|
||||
("spreadplayers ~ ~ 5 20 under 100 true @e", "spreadplayers"),
|
||||
("forceload add 0 0 100 100", "forceload.add"),
|
||||
("forceload remove all", "forceload.remove.all"),
|
||||
("forceload query", "forceload.query"),
|
||||
("forceload query ~ ~", "forceload.query"),
|
||||
(
|
||||
"fillbiome 0 0 0 10 10 10 minecraft:plains replace minecraft:desert",
|
||||
"fillbiome",
|
||||
),
|
||||
("worldborder set 100 5s", "worldborder.set"),
|
||||
("worldborder add -10", "worldborder.add"),
|
||||
("worldborder center 5 5", "worldborder.center"),
|
||||
("worldborder damage amount 1", "worldborder.damage.amount"),
|
||||
("worldborder warning time 10s", "worldborder.warning.time"),
|
||||
("worldborder get", "worldborder.get"),
|
||||
(
|
||||
"loot give @s loot minecraft:chests/simple_dungeon",
|
||||
"loot.loot",
|
||||
),
|
||||
("loot spawn ~ ~ ~ kill @e[limit=1]", "loot.kill"),
|
||||
("loot insert 0 0 0 mine 1 2 3 mainhand", "loot.mine"),
|
||||
(
|
||||
"loot replace entity @s hotbar.0 3 fish minecraft:gameplay/fishing 0 0 0",
|
||||
"loot.fish",
|
||||
),
|
||||
(
|
||||
"loot replace block 1 2 3 container.5 loot minecraft:chests/x",
|
||||
"loot.loot",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0,
|
||||
id,
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
assert!(run("playsound minecraft:x invalid_source").is_err());
|
||||
assert!(run("particle minecraft:not_a_particle").is_err());
|
||||
assert!(run("damage @s -1").is_err());
|
||||
assert!(run("spreadplayers 0 0 5 0 false @a").is_err());
|
||||
assert!(run("worldborder warning distance -1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn place_template_tree() {
|
||||
for line in [
|
||||
"place template minecraft:igloo/top",
|
||||
"place template minecraft:igloo/top ~ ~ ~",
|
||||
"place template minecraft:igloo/top 1 2 3 clockwise_90 left_right 0.5 12 strict",
|
||||
] {
|
||||
assert_eq!(
|
||||
run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0,
|
||||
"place"
|
||||
);
|
||||
}
|
||||
assert!(run("place template minecraft:x ~ ~ ~ sideways").is_err());
|
||||
assert!(run("place template minecraft:x ~ ~ ~ none none 2").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn mod_commands_join_the_tree_for_every_player() {
|
||||
let reg = Registries {
|
||||
permission: 0,
|
||||
..reg()
|
||||
};
|
||||
let d = vanilla::game_dispatcher().with_mod_commands(["where"]);
|
||||
for line in ["where", "where north 12"] {
|
||||
let parse = d.parse(line, ®);
|
||||
assert_eq!(parse.executable().unwrap().1, MOD_COMMAND, "{line}");
|
||||
}
|
||||
let parse = d.parse("w", ®);
|
||||
let names: Vec<String> = d
|
||||
.client_suggestions(&parse, 1, ®)
|
||||
.1
|
||||
.into_iter()
|
||||
.map(|s| s.text)
|
||||
.collect();
|
||||
assert!(names.contains(&"where".to_owned()), "{names:?}");
|
||||
// The game's own tree is left as it was.
|
||||
assert!(vanilla::game_dispatcher().find("where").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizon_commands_are_off_unless_the_server_turns_them_on() {
|
||||
// By default the game runs vanilla's tree: /help lists no /pregen.
|
||||
assert!(vanilla::game_dispatcher().find("pregen").is_none());
|
||||
for dev in [false, true] {
|
||||
let vanilla_tree = vanilla::game_tree(dev, false);
|
||||
assert!(vanilla_tree.find("pregen").is_none());
|
||||
let d = vanilla::game_tree(dev, true);
|
||||
let parse = d.parse("pregen start 100 circle", ®());
|
||||
assert_eq!(parse.executable().unwrap().1, "pregen.start");
|
||||
// Vanilla's commands are the same with or without it.
|
||||
assert_eq!(
|
||||
d.nodes[0].children.len(),
|
||||
vanilla_tree.nodes[0].children.len() + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
//! The `/data` and `/tag` command trees (DataCommands, TagCommand).
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITIES, GAMEMASTERS},
|
||||
};
|
||||
|
||||
const ENTITY: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
};
|
||||
|
||||
/// `ArgProvider.wrap` for each of entity, block and storage: calls `then`
|
||||
/// with the node holding the provider's argument.
|
||||
fn providers(
|
||||
d: &mut Dispatcher,
|
||||
parent: usize,
|
||||
role: &str,
|
||||
mut then: impl FnMut(&mut Dispatcher, usize),
|
||||
) {
|
||||
let e = d.literal(parent, "entity");
|
||||
let a = d.argument(e, role, ENTITY);
|
||||
then(d, a);
|
||||
let b = d.literal(parent, "block");
|
||||
let a = d.argument(b, &format!("{role}Pos"), ArgType::BlockPos);
|
||||
then(d, a);
|
||||
let s = d.literal(parent, "storage");
|
||||
let a = d.argument(s, role, ArgType::Id("storages"));
|
||||
then(d, a);
|
||||
}
|
||||
|
||||
/// LootContextSources.addContextSources: `default`, `block <computePos>`
|
||||
/// and `entity <computeTarget>`, each completed by `then`.
|
||||
pub fn context_sources(
|
||||
d: &mut Dispatcher,
|
||||
node: usize,
|
||||
then: &mut dyn FnMut(&mut Dispatcher, usize),
|
||||
) {
|
||||
let default = d.literal(node, "default");
|
||||
then(d, default);
|
||||
let block = d.literal(node, "block");
|
||||
let pos = d.argument(block, "computePos", ArgType::BlockPos);
|
||||
then(d, pos);
|
||||
let entity = d.literal(node, "entity");
|
||||
let target = d.argument(entity, "computeTarget", ENTITY);
|
||||
then(d, target);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
// compute (default | block <pos> | entity <target>) (float <provider> [<scale>] | integer <provider>)
|
||||
let compute = d.literal(root, "compute");
|
||||
d.requires(compute, GAMEMASTERS);
|
||||
context_sources(d, compute, &mut |d, node| {
|
||||
let f = d.literal(node, "float");
|
||||
let p = d.argument(
|
||||
f,
|
||||
"provider",
|
||||
ArgType::ResourceOrId("minecraft:context_float_provider"),
|
||||
);
|
||||
d.executes(p, "compute");
|
||||
let scale = d.argument(
|
||||
p,
|
||||
"scale",
|
||||
ArgType::Float {
|
||||
min: f32::MIN,
|
||||
max: f32::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(scale, "compute");
|
||||
let i = d.literal(node, "integer");
|
||||
let p = d.argument(
|
||||
i,
|
||||
"provider",
|
||||
ArgType::ResourceOrId("minecraft:context_int_provider"),
|
||||
);
|
||||
d.executes(p, "compute");
|
||||
});
|
||||
|
||||
let data = d.literal(root, "data");
|
||||
d.requires(data, GAMEMASTERS);
|
||||
|
||||
let merge = d.literal(data, "merge");
|
||||
providers(d, merge, "target", |d, a| {
|
||||
let nbt = d.argument(a, "nbt", ArgType::Nbt);
|
||||
d.executes(nbt, "data.merge");
|
||||
});
|
||||
let get = d.literal(data, "get");
|
||||
providers(d, get, "target", |d, a| {
|
||||
d.executes(a, "data.get");
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "data.get");
|
||||
let scale = d.argument(
|
||||
path,
|
||||
"scale",
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(scale, "data.get");
|
||||
});
|
||||
let remove = d.literal(data, "remove");
|
||||
providers(d, remove, "target", |d, a| {
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "data.remove");
|
||||
});
|
||||
let modify = d.literal(data, "modify");
|
||||
providers(d, modify, "target", |d, a| {
|
||||
let target_path = d.argument(a, "targetPath", ArgType::NbtPath);
|
||||
// insert <index> | prepend | append | set | merge, then the source.
|
||||
let mut ops = Vec::new();
|
||||
let insert = d.literal(target_path, "insert");
|
||||
let index = d.argument(
|
||||
insert,
|
||||
"index",
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
);
|
||||
ops.push(index);
|
||||
for op in ["prepend", "append", "set", "merge"] {
|
||||
ops.push(d.literal(target_path, op));
|
||||
}
|
||||
for op in ops {
|
||||
let from = d.literal(op, "from");
|
||||
providers(d, from, "source", |d, s| {
|
||||
d.executes(s, "data.modify");
|
||||
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
|
||||
d.executes(sp, "data.modify");
|
||||
});
|
||||
let string = d.literal(op, "string");
|
||||
providers(d, string, "source", |d, s| {
|
||||
d.executes(s, "data.modify");
|
||||
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
|
||||
d.executes(sp, "data.modify");
|
||||
let int = || ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
};
|
||||
let start = d.argument(sp, "start", int());
|
||||
d.executes(start, "data.modify");
|
||||
let end = d.argument(start, "end", int());
|
||||
d.executes(end, "data.modify");
|
||||
});
|
||||
let compute = d.literal(op, "compute");
|
||||
context_sources(d, compute, &mut |d, node| {
|
||||
for (kind, registry) in [
|
||||
("float", "minecraft:context_float_provider"),
|
||||
("integer", "minecraft:context_int_provider"),
|
||||
] {
|
||||
let k = d.literal(node, kind);
|
||||
let p = d.argument(k, "provider", ArgType::ResourceOrId(registry));
|
||||
d.executes(p, "data.modify");
|
||||
}
|
||||
});
|
||||
let value = d.literal(op, "value");
|
||||
let v = d.argument(value, "value", ArgType::NbtTag);
|
||||
d.executes(v, "data.modify");
|
||||
}
|
||||
});
|
||||
|
||||
// tag <targets> add|remove <name> | list
|
||||
let tag = d.literal(root, "tag");
|
||||
d.requires(tag, GAMEMASTERS);
|
||||
let targets = d.argument(tag, "targets", ENTITIES);
|
||||
for word in ["add", "remove"] {
|
||||
let w = d.literal(targets, word);
|
||||
let name = d.argument(w, "name", ArgType::Word);
|
||||
d.executes(
|
||||
name,
|
||||
if word == "add" {
|
||||
"tag.add"
|
||||
} else {
|
||||
"tag.remove"
|
||||
},
|
||||
);
|
||||
}
|
||||
let list = d.literal(targets, "list");
|
||||
d.executes(list, "tag.list");
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
//! The `/execute` tree (ExecuteCommand): modifiers redirect back to
|
||||
//! `execute`, `run` to the root; conditions both execute (as a test) and
|
||||
//! continue the chain; `store` redirects with a result callback.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, Resource},
|
||||
vanilla::{ENTITIES, GAMEMASTERS},
|
||||
};
|
||||
|
||||
/// HeightmapTypeArgument: the types kept after world generation.
|
||||
pub const HEIGHTMAPS: &[&str] = &[
|
||||
"world_surface",
|
||||
"ocean_floor",
|
||||
"motion_blocking",
|
||||
"motion_blocking_no_leaves",
|
||||
];
|
||||
pub const RELATIONS: [&str; 8] = [
|
||||
"owner",
|
||||
"leasher",
|
||||
"target",
|
||||
"attacker",
|
||||
"vehicle",
|
||||
"controller",
|
||||
"origin",
|
||||
"passengers",
|
||||
];
|
||||
|
||||
/// A conditional's end: it runs as a test and continues the chain.
|
||||
fn conditional(d: &mut Dispatcher, node: usize, ex: usize) {
|
||||
d.executes(node, "execute");
|
||||
d.redirect(node, ex);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let ex = d.literal(root, "execute");
|
||||
d.requires(ex, GAMEMASTERS);
|
||||
let run = d.literal(ex, "run");
|
||||
d.redirect(run, root);
|
||||
for name in ["as", "at"] {
|
||||
let l = d.literal(ex, name);
|
||||
let t = d.argument(l, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
}
|
||||
let positioned = d.literal(ex, "positioned");
|
||||
let pos = d.argument(positioned, "pos", ArgType::Vec3 { center: true });
|
||||
d.redirect(pos, ex);
|
||||
let as_ = d.literal(positioned, "as");
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let over = d.literal(positioned, "over");
|
||||
let hm = d.argument(
|
||||
over,
|
||||
"heightmap",
|
||||
ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid"),
|
||||
);
|
||||
d.redirect(hm, ex);
|
||||
let rotated = d.literal(ex, "rotated");
|
||||
let rot = d.argument(rotated, "rot", ArgType::Rotation);
|
||||
d.redirect(rot, ex);
|
||||
let as_ = d.literal(rotated, "as");
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let facing = d.literal(ex, "facing");
|
||||
let pos = d.argument(facing, "pos", ArgType::Vec3 { center: true });
|
||||
d.redirect(pos, ex);
|
||||
let entity = d.literal(facing, "entity");
|
||||
let t = d.argument(entity, "targets", ENTITIES);
|
||||
let anchor = d.argument(t, "anchor", ArgType::Anchor);
|
||||
d.redirect(anchor, ex);
|
||||
let align = d.literal(ex, "align");
|
||||
let axes = d.argument(align, "axes", ArgType::Swizzle);
|
||||
d.redirect(axes, ex);
|
||||
let anchored = d.literal(ex, "anchored");
|
||||
let anchor = d.argument(anchored, "anchor", ArgType::Anchor);
|
||||
d.redirect(anchor, ex);
|
||||
let in_ = d.literal(ex, "in");
|
||||
let dim = d.argument(in_, "dimension", ArgType::Dimension);
|
||||
d.redirect(dim, ex);
|
||||
let summon = d.literal(ex, "summon");
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.suggests(e, super::Suggests::SummonableEntities);
|
||||
d.redirect(e, ex);
|
||||
let on = d.literal(ex, "on");
|
||||
for r in RELATIONS {
|
||||
let l = d.literal(on, r);
|
||||
d.redirect(l, ex);
|
||||
}
|
||||
store(d, ex);
|
||||
for mode in ["if", "unless"] {
|
||||
let m = d.literal(ex, mode);
|
||||
conditionals(d, m, ex);
|
||||
}
|
||||
}
|
||||
|
||||
fn store(d: &mut Dispatcher, ex: usize) {
|
||||
let store = d.literal(ex, "store");
|
||||
for kind in ["result", "success"] {
|
||||
let k = d.literal(store, kind);
|
||||
let score = d.literal(k, "score");
|
||||
let targets = d.argument(score, "targets", ArgType::ScoreHolder { multiple: true });
|
||||
let objective = d.argument(targets, "objective", ArgType::Objective);
|
||||
d.redirect(objective, ex);
|
||||
let bossbar = d.literal(k, "bossbar");
|
||||
let id = d.argument(bossbar, "id", ArgType::Id("bossbars"));
|
||||
for what in ["value", "max"] {
|
||||
let w = d.literal(id, what);
|
||||
d.redirect(w, ex);
|
||||
}
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
let p = d.literal(k, provider);
|
||||
let a = match provider {
|
||||
"entity" => d.argument(
|
||||
p,
|
||||
"target",
|
||||
ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
},
|
||||
),
|
||||
"block" => d.argument(p, "targetPos", ArgType::BlockPos),
|
||||
_ => d.argument(p, "target", ArgType::Id("storages")),
|
||||
};
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
for ty in ["int", "float", "short", "long", "double", "byte"] {
|
||||
let t = d.literal(path, ty);
|
||||
let scale = d.argument(
|
||||
t,
|
||||
"scale",
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
);
|
||||
d.redirect(scale, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
|
||||
let block = d.literal(m, "block");
|
||||
let pos = d.argument(block, "pos", ArgType::BlockPos);
|
||||
let predicate = d.argument(pos, "block", ArgType::BlockPredicate);
|
||||
conditional(d, predicate, ex);
|
||||
|
||||
let biome = d.literal(m, "biome");
|
||||
let pos = d.argument(biome, "pos", ArgType::BlockPos);
|
||||
let b = d.argument(pos, "biome", ArgType::ResOrTag("minecraft:worldgen/biome"));
|
||||
conditional(d, b, ex);
|
||||
|
||||
let loaded = d.literal(m, "loaded");
|
||||
let pos = d.argument(loaded, "pos", ArgType::BlockPos);
|
||||
conditional(d, pos, ex);
|
||||
|
||||
let dimension = d.literal(m, "dimension");
|
||||
let dim = d.argument(dimension, "dimension", ArgType::Dimension);
|
||||
conditional(d, dim, ex);
|
||||
|
||||
let score = d.literal(m, "score");
|
||||
let target = d.argument(score, "target", ArgType::ScoreHolder { multiple: false });
|
||||
let objective = d.argument(target, "targetObjective", ArgType::Objective);
|
||||
for op in ["=", "<", "<=", ">", ">="] {
|
||||
let o = d.literal(objective, op);
|
||||
let source = d.argument(o, "source", ArgType::ScoreHolder { multiple: false });
|
||||
let so = d.argument(source, "sourceObjective", ArgType::Objective);
|
||||
conditional(d, so, ex);
|
||||
}
|
||||
let matches = d.literal(objective, "matches");
|
||||
let range = d.argument(matches, "range", ArgType::IntRange);
|
||||
conditional(d, range, ex);
|
||||
|
||||
let blocks = d.literal(m, "blocks");
|
||||
let start = d.argument(blocks, "start", ArgType::BlockPos);
|
||||
let end = d.argument(start, "end", ArgType::BlockPos);
|
||||
let dest = d.argument(end, "destination", ArgType::BlockPos);
|
||||
for mode in ["all", "masked"] {
|
||||
let l = d.literal(dest, mode);
|
||||
conditional(d, l, ex);
|
||||
}
|
||||
|
||||
let entity = d.literal(m, "entity");
|
||||
let targets = d.argument(entity, "entities", ENTITIES);
|
||||
conditional(d, targets, ex);
|
||||
|
||||
let predicate = d.literal(m, "predicate");
|
||||
let p = d.argument(
|
||||
predicate,
|
||||
"predicate",
|
||||
ArgType::ResourceOrId("minecraft:predicate"),
|
||||
);
|
||||
conditional(d, p, ex);
|
||||
|
||||
let stopwatch = d.literal(m, "stopwatch");
|
||||
let id = d.argument(stopwatch, "id", ArgType::Id("stopwatches"));
|
||||
let range = d.argument(id, "range", ArgType::FloatRange);
|
||||
conditional(d, range, ex);
|
||||
|
||||
let function = d.literal(m, "function");
|
||||
let name = d.argument(function, "name", ArgType::Function);
|
||||
d.suggests(name, super::Suggests::Functions);
|
||||
// ExecuteIfFunctionCustomModifier: a fork only (not a test command).
|
||||
d.redirect(name, ex);
|
||||
|
||||
let data = d.literal(m, "data");
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
let p = d.literal(data, provider);
|
||||
let a = match provider {
|
||||
"entity" => d.argument(
|
||||
p,
|
||||
"source",
|
||||
ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
},
|
||||
),
|
||||
"block" => d.argument(p, "sourcePos", ArgType::BlockPos),
|
||||
_ => d.argument(p, "source", ArgType::Id("storages")),
|
||||
};
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
conditional(d, path, ex);
|
||||
}
|
||||
|
||||
// items / slots (entity|block) <slots> [<predicate>]
|
||||
for kind in ["items", "slots"] {
|
||||
let k = d.literal(m, kind);
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(k, provider);
|
||||
let a = if provider == "entity" {
|
||||
d.argument(
|
||||
p,
|
||||
"source",
|
||||
ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
d.argument(p, "sourcePos", ArgType::BlockPos)
|
||||
};
|
||||
let slots = d.argument(a, "slots", ArgType::SlotSource);
|
||||
if kind == "items" {
|
||||
let item = d.argument(slots, "item_predicate", ArgType::ItemPredicate);
|
||||
conditional(d, item, ex);
|
||||
} else {
|
||||
conditional(d, slots, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
//! Commands of the hosted game rather than the world: `/dialog`, `/kick`,
|
||||
//! `/posteffect`, `/fetchprofile`, `/spectate`, `/publish`, `/unpublish`,
|
||||
//! `/waypoint`, `/debug`, `/jfr` and `/test`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITY, GAMEMASTERS, PLAYER, PLAYERS},
|
||||
};
|
||||
|
||||
const ADMINS: u8 = 3;
|
||||
const OWNERS: u8 = 4;
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
// DialogCommand
|
||||
let dialog = d.literal(root, "dialog");
|
||||
d.requires(dialog, GAMEMASTERS);
|
||||
let show = d.literal(dialog, "show");
|
||||
let t = d.argument(show, "targets", PLAYERS);
|
||||
let dl = d.argument(t, "dialog", ArgType::ResourceOrId("minecraft:dialog"));
|
||||
d.executes(dl, "dialog.show");
|
||||
let clear = d.literal(dialog, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "dialog.clear");
|
||||
|
||||
// KickCommand
|
||||
let kick = d.literal(root, "kick");
|
||||
d.requires(kick, ADMINS);
|
||||
let t = d.argument(kick, "targets", PLAYERS);
|
||||
d.executes(t, "kick");
|
||||
let reason = d.argument(t, "reason", ArgType::Message);
|
||||
d.executes(reason, "kick");
|
||||
|
||||
// PostEffectCommand
|
||||
let pe = d.literal(root, "posteffect");
|
||||
d.requires(pe, GAMEMASTERS);
|
||||
let add = d.literal(pe, "add");
|
||||
let t = d.argument(add, "targets", PLAYERS);
|
||||
let id = d.argument(t, "posteffect", ArgType::Id("post_effects"));
|
||||
d.executes(id, "posteffect.add");
|
||||
let clear = d.literal(pe, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "posteffect.clear");
|
||||
let list = d.literal(pe, "list");
|
||||
let t = d.argument(list, "target", PLAYER);
|
||||
d.executes(t, "posteffect.list");
|
||||
let remove = d.literal(pe, "remove");
|
||||
let t = d.argument(remove, "targets", PLAYERS);
|
||||
let id = d.argument(t, "posteffect", ArgType::Id("post_effects"));
|
||||
d.executes(id, "posteffect.remove");
|
||||
|
||||
// FetchProfileCommand
|
||||
let fp = d.literal(root, "fetchprofile");
|
||||
d.requires(fp, GAMEMASTERS);
|
||||
let name = d.literal(fp, "name");
|
||||
let n = d.argument(name, "name", ArgType::Greedy);
|
||||
d.executes(n, "fetchprofile");
|
||||
let id = d.literal(fp, "id");
|
||||
let u = d.argument(id, "id", ArgType::Uuid);
|
||||
d.executes(u, "fetchprofile");
|
||||
let entity = d.literal(fp, "entity");
|
||||
let e = d.argument(entity, "entity", ENTITY);
|
||||
d.executes(e, "fetchprofile");
|
||||
|
||||
// SpectateCommand
|
||||
let spectate = d.literal(root, "spectate");
|
||||
d.requires(spectate, GAMEMASTERS);
|
||||
d.executes(spectate, "spectate");
|
||||
let target = d.argument(spectate, "target", ENTITY);
|
||||
d.executes(target, "spectate");
|
||||
let player = d.argument(target, "player", PLAYER);
|
||||
d.executes(player, "spectate");
|
||||
|
||||
// PublishCommand / UnpublishCommand
|
||||
let publish = d.literal(root, "publish");
|
||||
d.requires(publish, OWNERS);
|
||||
d.executes(publish, "publish");
|
||||
let allow = d.argument(publish, "allowCommands", ArgType::Bool);
|
||||
d.executes(allow, "publish");
|
||||
let port = d.argument(allow, "port", ArgType::Integer { min: 0, max: 65535 });
|
||||
d.executes(port, "publish");
|
||||
let unpublish = d.literal(root, "unpublish");
|
||||
d.requires(unpublish, OWNERS);
|
||||
d.executes(unpublish, "unpublish");
|
||||
|
||||
// WaypointCommand
|
||||
let wp = d.literal(root, "waypoint");
|
||||
d.requires(wp, GAMEMASTERS);
|
||||
let list = d.literal(wp, "list");
|
||||
d.executes(list, "waypoint.list");
|
||||
let modify = d.literal(wp, "modify");
|
||||
let w = d.argument(modify, "waypoint", ENTITY);
|
||||
let color = d.literal(w, "color");
|
||||
let c = d.argument(color, "color", ArgType::TeamColor);
|
||||
d.executes(c, "waypoint.modify");
|
||||
let hex = d.literal(color, "hex");
|
||||
let h = d.argument(hex, "color", ArgType::HexColor);
|
||||
d.executes(h, "waypoint.modify");
|
||||
let reset = d.literal(color, "reset");
|
||||
d.executes(reset, "waypoint.modify");
|
||||
let style = d.literal(w, "style");
|
||||
let reset = d.literal(style, "reset");
|
||||
d.executes(reset, "waypoint.modify");
|
||||
let set = d.literal(style, "set");
|
||||
let st = d.argument(set, "style", ArgType::Id("none"));
|
||||
d.executes(st, "waypoint.modify");
|
||||
|
||||
// DebugCommand
|
||||
let debug = d.literal(root, "debug");
|
||||
d.requires(debug, ADMINS);
|
||||
for name in ["start", "stop"] {
|
||||
let l = d.literal(debug, name);
|
||||
d.executes(l, "debug");
|
||||
}
|
||||
let function = d.literal(debug, "function");
|
||||
d.requires(function, ADMINS);
|
||||
let n = d.argument(function, "name", ArgType::Function);
|
||||
d.suggests(n, super::Suggests::Functions);
|
||||
d.executes(n, "debug");
|
||||
|
||||
// JfrCommand (registered when the JVM profiler is available)
|
||||
let jfr = d.literal(root, "jfr");
|
||||
d.requires(jfr, OWNERS);
|
||||
for name in ["start", "stop"] {
|
||||
let l = d.literal(jfr, name);
|
||||
d.executes(l, "jfr");
|
||||
}
|
||||
|
||||
// TestCommand (release build: no export subcommands)
|
||||
let test = d.literal(root, "test");
|
||||
d.requires(test, GAMEMASTERS);
|
||||
let tests = ArgType::ResourceSelector("minecraft:test_instance");
|
||||
let int0 = ArgType::Integer {
|
||||
min: 0,
|
||||
max: i32::MAX,
|
||||
};
|
||||
let int = ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
};
|
||||
// numberOfTimes [untilFailed [rotationSteps [testsPerRow]]], or only
|
||||
// the first two.
|
||||
let retry = |d: &mut Dispatcher, node: usize, id: &'static str, build_info: bool| {
|
||||
let n = d.argument(node, "numberOfTimes", int0.clone());
|
||||
d.executes(n, id);
|
||||
let u = d.argument(n, "untilFailed", ArgType::Bool);
|
||||
d.executes(u, id);
|
||||
if build_info {
|
||||
let r = d.argument(u, "rotationSteps", int.clone());
|
||||
d.executes(r, id);
|
||||
let t = d.argument(r, "testsPerRow", int.clone());
|
||||
d.executes(t, id);
|
||||
}
|
||||
};
|
||||
let run = d.literal(test, "run");
|
||||
let t = d.argument(run, "tests", tests.clone());
|
||||
d.executes(t, "test.run");
|
||||
retry(d, t, "test.run", true);
|
||||
let multiple = d.literal(test, "runmultiple");
|
||||
let t = d.argument(multiple, "tests", tests.clone());
|
||||
d.executes(t, "test.run");
|
||||
let a = d.argument(t, "amount", int.clone());
|
||||
d.executes(a, "test.run");
|
||||
for name in ["runthese", "runclosest", "runthat"] {
|
||||
let l = d.literal(test, name);
|
||||
d.executes(l, "test.run.found");
|
||||
retry(d, l, "test.run.found", false);
|
||||
}
|
||||
let failed = d.literal(test, "runfailed");
|
||||
d.executes(failed, "test.run.found");
|
||||
let only = d.argument(failed, "onlyRequiredTests", ArgType::Bool);
|
||||
d.executes(only, "test.run.found");
|
||||
retry(d, only, "test.run.found", true);
|
||||
retry(d, failed, "test.run.found", true);
|
||||
let verify = d.literal(test, "verify");
|
||||
let t = d.argument(verify, "tests", tests.clone());
|
||||
d.executes(t, "test.verify");
|
||||
let locate = d.literal(test, "locate");
|
||||
let t = d.argument(locate, "tests", tests);
|
||||
d.executes(t, "test.locate");
|
||||
for name in [
|
||||
"resetclosest",
|
||||
"resetthese",
|
||||
"resetthat",
|
||||
"clearthat",
|
||||
"clearthese",
|
||||
] {
|
||||
let l = d.literal(test, name);
|
||||
d.executes(l, "test.clear");
|
||||
}
|
||||
let all = d.literal(test, "clearall");
|
||||
d.executes(all, "test.clear");
|
||||
let r = d.argument(all, "radius", int.clone());
|
||||
d.executes(r, "test.clear");
|
||||
let stop = d.literal(test, "stop");
|
||||
d.executes(stop, "test.stop");
|
||||
let pos = d.literal(test, "pos");
|
||||
d.executes(pos, "test.pos");
|
||||
let var = d.argument(pos, "var", ArgType::Word);
|
||||
d.executes(var, "test.pos");
|
||||
let create = d.literal(test, "create");
|
||||
let id = d.argument(create, "id", ArgType::Id("none"));
|
||||
d.executes(id, "test.create");
|
||||
let w = d.argument(id, "width", int.clone());
|
||||
d.executes(w, "test.create");
|
||||
let h = d.argument(w, "height", int.clone());
|
||||
let depth = d.argument(h, "depth", int);
|
||||
d.executes(depth, "test.create");
|
||||
}
|
||||
@@ -1,319 +0,0 @@
|
||||
//! Smaller command trees: `/bossbar`, `/function`, `/return`, `/schedule`,
|
||||
//! `/random`, `/tick`, `/teammsg`, `/reload` and `/datapack`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITIES, GAMEMASTERS, PLAYERS},
|
||||
};
|
||||
|
||||
fn int() -> ArgType {
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
}
|
||||
}
|
||||
fn int_min(min: i32) -> ArgType {
|
||||
ArgType::Integer { min, max: i32::MAX }
|
||||
}
|
||||
pub const ADMINS: u8 = 3;
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
item(d, root);
|
||||
bossbar(d, root);
|
||||
function(d, root);
|
||||
stopwatch(d, root);
|
||||
|
||||
// return <value> | fail | run <command>
|
||||
let ret = d.literal(root, "return");
|
||||
d.requires(ret, GAMEMASTERS);
|
||||
let v = d.argument(ret, "value", int());
|
||||
d.executes(v, "return.value");
|
||||
let fail = d.literal(ret, "fail");
|
||||
d.executes(fail, "return.fail");
|
||||
let run = d.literal(ret, "run");
|
||||
d.redirect(run, root);
|
||||
|
||||
// schedule function <function> <time> [append|replace] | clear <function>
|
||||
let schedule = d.literal(root, "schedule");
|
||||
d.requires(schedule, GAMEMASTERS);
|
||||
let f = d.literal(schedule, "function");
|
||||
let name = d.argument(f, "function", ArgType::Function);
|
||||
d.suggests(name, super::Suggests::Functions);
|
||||
let time = d.argument(name, "time", ArgType::Time { min: 0 });
|
||||
d.executes(time, "schedule.function");
|
||||
for mode in ["append", "replace"] {
|
||||
let m = d.literal(time, mode);
|
||||
d.executes(m, "schedule.function");
|
||||
}
|
||||
let clear = d.literal(schedule, "clear");
|
||||
let id = d.argument(clear, "function", ArgType::Id("schedules"));
|
||||
d.executes(id, "schedule.clear");
|
||||
|
||||
// random (value|roll) <range> [<sequence>] | reset (*|<sequence>) ...
|
||||
let random = d.literal(root, "random");
|
||||
for kind in ["value", "roll"] {
|
||||
let k = d.literal(random, kind);
|
||||
let range = d.argument(k, "range", ArgType::IntRange);
|
||||
let id = if kind == "value" {
|
||||
"random.value"
|
||||
} else {
|
||||
"random.roll"
|
||||
};
|
||||
d.executes(range, id);
|
||||
let seq = d.argument(range, "sequence", ArgType::Id("random_sequences"));
|
||||
d.requires(seq, GAMEMASTERS);
|
||||
d.executes(seq, id);
|
||||
}
|
||||
let reset = d.literal(random, "reset");
|
||||
d.requires(reset, GAMEMASTERS);
|
||||
let all = d.literal(reset, "*");
|
||||
d.executes(all, "random.reset");
|
||||
let seq = d.argument(reset, "sequence", ArgType::Id("random_sequences"));
|
||||
d.executes(seq, "random.reset");
|
||||
for parent in [all, seq] {
|
||||
let seed = d.argument(parent, "seed", int());
|
||||
d.executes(seed, "random.reset");
|
||||
let world = d.argument(seed, "includeWorldSeed", ArgType::Bool);
|
||||
d.executes(world, "random.reset");
|
||||
let seq_id = d.argument(world, "includeSequenceId", ArgType::Bool);
|
||||
d.executes(seq_id, "random.reset");
|
||||
}
|
||||
|
||||
// tick query | rate <rate> | step [stop|<time>] | sprint (stop|<time>) | freeze | unfreeze
|
||||
let tick = d.literal(root, "tick");
|
||||
d.requires(tick, ADMINS);
|
||||
let q = d.literal(tick, "query");
|
||||
d.executes(q, "tick.query");
|
||||
let rate = d.literal(tick, "rate");
|
||||
let r = d.argument(
|
||||
rate,
|
||||
"rate",
|
||||
ArgType::Float {
|
||||
min: 1.0,
|
||||
max: 10000.0,
|
||||
},
|
||||
);
|
||||
d.suggests(r, super::Suggests::Fixed(&["20"]));
|
||||
d.executes(r, "tick.rate");
|
||||
let step = d.literal(tick, "step");
|
||||
d.executes(step, "tick.step");
|
||||
let stop = d.literal(step, "stop");
|
||||
d.executes(stop, "tick.step.stop");
|
||||
let t = d.argument(step, "time", ArgType::Time { min: 1 });
|
||||
d.suggests(t, super::Suggests::Fixed(&["1t", "1s"]));
|
||||
d.executes(t, "tick.step");
|
||||
let sprint = d.literal(tick, "sprint");
|
||||
let stop = d.literal(sprint, "stop");
|
||||
d.executes(stop, "tick.sprint.stop");
|
||||
let t = d.argument(sprint, "time", ArgType::Time { min: 1 });
|
||||
d.suggests(t, super::Suggests::Fixed(&["60s", "1d", "3d"]));
|
||||
d.executes(t, "tick.sprint");
|
||||
let unfreeze = d.literal(tick, "unfreeze");
|
||||
d.executes(unfreeze, "tick.unfreeze");
|
||||
let freeze = d.literal(tick, "freeze");
|
||||
d.executes(freeze, "tick.freeze");
|
||||
|
||||
// teammsg / tm <message>
|
||||
let teammsg = d.literal(root, "teammsg");
|
||||
let m = d.argument(teammsg, "message", ArgType::Message);
|
||||
d.executes(m, "teammsg");
|
||||
let tm = d.literal(root, "tm");
|
||||
d.redirect(tm, teammsg);
|
||||
|
||||
// reload
|
||||
let reload = d.literal(root, "reload");
|
||||
d.requires(reload, GAMEMASTERS);
|
||||
d.executes(reload, "reload");
|
||||
|
||||
// datapack list [available|enabled] | enable|disable <name> ...
|
||||
let datapack = d.literal(root, "datapack");
|
||||
d.requires(datapack, GAMEMASTERS);
|
||||
let list = d.literal(datapack, "list");
|
||||
d.executes(list, "datapack.list");
|
||||
for w in ["available", "enabled"] {
|
||||
let l = d.literal(list, w);
|
||||
d.executes(l, "datapack.list");
|
||||
}
|
||||
let enable = d.literal(datapack, "enable");
|
||||
let name = d.argument(enable, "name", ArgType::Name("datapacks_disabled"));
|
||||
d.executes(name, "datapack.enable");
|
||||
for w in ["first", "last"] {
|
||||
let l = d.literal(name, w);
|
||||
d.executes(l, "datapack.enable");
|
||||
}
|
||||
for w in ["before", "after"] {
|
||||
let l = d.literal(name, w);
|
||||
let other = d.argument(l, "existing", ArgType::Name("datapacks_enabled"));
|
||||
d.executes(other, "datapack.enable");
|
||||
}
|
||||
let create = d.literal(datapack, "create");
|
||||
d.requires(create, 4);
|
||||
let id = d.argument(create, "id", ArgType::Str);
|
||||
let description = d.argument(id, "description", ArgType::Component);
|
||||
d.executes(description, "datapack.create");
|
||||
let disable = d.literal(datapack, "disable");
|
||||
let name = d.argument(disable, "name", ArgType::Name("datapacks_enabled"));
|
||||
d.executes(name, "datapack.disable");
|
||||
}
|
||||
|
||||
/// `item (replace|fill|override) (entity|block) <target> <slots> (with <item> [<count>] | from ...)`.
|
||||
fn item(d: &mut Dispatcher, root: usize) {
|
||||
let item = d.literal(root, "item");
|
||||
d.requires(item, GAMEMASTERS);
|
||||
let modify = d.literal(item, "modify");
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(modify, provider);
|
||||
let target = if provider == "entity" {
|
||||
d.argument(p, "target", ENTITIES)
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slot = d.argument(target, "slot", ArgType::SlotSource);
|
||||
let modifier = d.argument(
|
||||
slot,
|
||||
"modifier",
|
||||
ArgType::ResourceOrId("minecraft:item_modifier"),
|
||||
);
|
||||
d.executes(modifier, "item.modify");
|
||||
}
|
||||
for mode in ["replace", "fill", "override"] {
|
||||
let m = d.literal(item, mode);
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(m, provider);
|
||||
let target = if provider == "entity" {
|
||||
d.argument(p, "target", ENTITIES)
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slots = d.argument(target, "slots", ArgType::SlotSource);
|
||||
let with = d.literal(slots, "with");
|
||||
let it = d.argument(with, "item", ArgType::Item);
|
||||
d.executes(it, "item");
|
||||
let count = d.argument(it, "count", ArgType::Integer { min: 1, max: 99 });
|
||||
d.executes(count, "item");
|
||||
let from = d.literal(slots, "from");
|
||||
for src in ["entity", "block"] {
|
||||
let s = d.literal(from, src);
|
||||
let source = if src == "entity" {
|
||||
d.argument(s, "source", ENTITIES)
|
||||
} else {
|
||||
d.argument(s, "sourcePos", ArgType::BlockPos)
|
||||
};
|
||||
let source_slots = d.argument(source, "sourceSlots", ArgType::SlotSource);
|
||||
d.executes(source_slots, "item");
|
||||
let modifier = d.argument(
|
||||
source_slots,
|
||||
"modifier",
|
||||
ArgType::ResourceOrId("minecraft:item_modifier"),
|
||||
);
|
||||
d.executes(modifier, "item");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bossbar(d: &mut Dispatcher, root: usize) {
|
||||
let b = d.literal(root, "bossbar");
|
||||
d.requires(b, GAMEMASTERS);
|
||||
let add = d.literal(b, "add");
|
||||
let id = d.argument(add, "id", ArgType::Id("bossbars_new"));
|
||||
let name = d.argument(id, "name", ArgType::Component);
|
||||
d.executes(name, "bossbar.add");
|
||||
let remove = d.literal(b, "remove");
|
||||
let id = d.argument(remove, "id", ArgType::Id("bossbars"));
|
||||
d.executes(id, "bossbar.remove");
|
||||
let list = d.literal(b, "list");
|
||||
d.executes(list, "bossbar.list");
|
||||
let set = d.literal(b, "set");
|
||||
let id = d.argument(set, "id", ArgType::Id("bossbars"));
|
||||
let name_l = d.literal(id, "name");
|
||||
let name = d.argument(name_l, "name", ArgType::Component);
|
||||
d.executes(name, "bossbar.set.name");
|
||||
let color = d.literal(id, "color");
|
||||
for c in crate::bossbar::COLORS {
|
||||
let l = d.literal(color, c);
|
||||
d.executes(l, "bossbar.set.color");
|
||||
}
|
||||
let style = d.literal(id, "style");
|
||||
for s in crate::bossbar::STYLES {
|
||||
let l = d.literal(style, s);
|
||||
d.executes(l, "bossbar.set.style");
|
||||
}
|
||||
let value = d.literal(id, "value");
|
||||
let v = d.argument(value, "value", int_min(0));
|
||||
d.executes(v, "bossbar.set.value");
|
||||
let max = d.literal(id, "max");
|
||||
let v = d.argument(max, "max", int_min(1));
|
||||
d.executes(v, "bossbar.set.max");
|
||||
let visible = d.literal(id, "visible");
|
||||
let v = d.argument(visible, "visible", ArgType::Bool);
|
||||
d.executes(v, "bossbar.set.visible");
|
||||
let players = d.literal(id, "players");
|
||||
d.executes(players, "bossbar.set.players");
|
||||
let t = d.argument(players, "targets", PLAYERS);
|
||||
d.executes(t, "bossbar.set.players");
|
||||
let get = d.literal(b, "get");
|
||||
let id = d.argument(get, "id", ArgType::Id("bossbars"));
|
||||
for w in ["value", "max", "visible", "players"] {
|
||||
let l = d.literal(id, w);
|
||||
d.executes(l, "bossbar.get");
|
||||
}
|
||||
}
|
||||
|
||||
fn function(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "function");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
let name = d.argument(f, "name", ArgType::Function);
|
||||
d.suggests(name, super::Suggests::Functions);
|
||||
d.executes(name, "function");
|
||||
let args = d.argument(name, "arguments", ArgType::Nbt);
|
||||
d.executes(args, "function");
|
||||
let with = d.literal(name, "with");
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
let p = d.literal(with, provider);
|
||||
let a = match provider {
|
||||
"entity" => d.argument(
|
||||
p,
|
||||
"source",
|
||||
ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
},
|
||||
),
|
||||
"block" => d.argument(p, "sourcePos", ArgType::BlockPos),
|
||||
_ => d.argument(p, "source", ArgType::Id("storages")),
|
||||
};
|
||||
d.executes(a, "function");
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "function");
|
||||
}
|
||||
}
|
||||
|
||||
/// stopwatch create <id> | query <id> [<scale>] | restart <id> | remove <id>
|
||||
fn stopwatch(d: &mut Dispatcher, root: usize) {
|
||||
let sw = d.literal(root, "stopwatch");
|
||||
d.requires(sw, GAMEMASTERS);
|
||||
let create = d.literal(sw, "create");
|
||||
let id = d.argument(create, "id", ArgType::Id("none"));
|
||||
d.executes(id, "stopwatch.create");
|
||||
let query = d.literal(sw, "query");
|
||||
let id = d.argument(query, "id", ArgType::Id("stopwatches"));
|
||||
d.executes(id, "stopwatch.query");
|
||||
let scale = d.argument(
|
||||
id,
|
||||
"scale",
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(scale, "stopwatch.query");
|
||||
for (name, command) in [
|
||||
("restart", "stopwatch.restart"),
|
||||
("remove", "stopwatch.remove"),
|
||||
] {
|
||||
let l = d.literal(sw, name);
|
||||
let id = d.argument(l, "id", ArgType::Id("stopwatches"));
|
||||
d.executes(id, command);
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
//! The `/scoreboard`, `/team` and `/trigger` command trees
|
||||
//! (ScoreboardCommand, TeamCommand, TriggerCommand).
|
||||
use super::{Dispatcher, args::ArgType, vanilla::GAMEMASTERS};
|
||||
|
||||
const HOLDERS: ArgType = ArgType::ScoreHolder { multiple: true };
|
||||
const HOLDER: ArgType = ArgType::ScoreHolder { multiple: false };
|
||||
|
||||
/// `addNumberFormats`: blank | fixed <contents> | styled <style>, and the
|
||||
/// node itself clears the format.
|
||||
fn number_formats(d: &mut Dispatcher, top: usize, id: &'static str) {
|
||||
d.executes(top, id);
|
||||
let blank = d.literal(top, "blank");
|
||||
d.executes(blank, id);
|
||||
let fixed = d.literal(top, "fixed");
|
||||
let contents = d.argument(fixed, "contents", ArgType::Component);
|
||||
d.executes(contents, id);
|
||||
let styled = d.literal(top, "styled");
|
||||
let style = d.argument(styled, "style", ArgType::Style);
|
||||
d.executes(style, id);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
scoreboard(d, root);
|
||||
team(d, root);
|
||||
|
||||
// trigger <objective> [add|set <value>]
|
||||
let trigger = d.literal(root, "trigger");
|
||||
let objective = d.argument(trigger, "objective", ArgType::Objective);
|
||||
d.suggests(objective, super::Suggests::Triggers);
|
||||
d.executes(objective, "trigger");
|
||||
for mode in ["add", "set"] {
|
||||
let m = d.literal(objective, mode);
|
||||
let v = d.argument(
|
||||
m,
|
||||
"value",
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(
|
||||
v,
|
||||
if mode == "add" {
|
||||
"trigger.add"
|
||||
} else {
|
||||
"trigger.set"
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn scoreboard(d: &mut Dispatcher, root: usize) {
|
||||
let sb = d.literal(root, "scoreboard");
|
||||
d.requires(sb, GAMEMASTERS);
|
||||
|
||||
let objectives = d.literal(sb, "objectives");
|
||||
let list = d.literal(objectives, "list");
|
||||
d.executes(list, "scoreboard.objectives.list");
|
||||
let add = d.literal(objectives, "add");
|
||||
let name = d.argument(add, "objective", ArgType::Word);
|
||||
let criteria = d.argument(name, "criteria", ArgType::Criteria);
|
||||
d.executes(criteria, "scoreboard.objectives.add");
|
||||
let display = d.argument(criteria, "displayName", ArgType::Component);
|
||||
d.executes(display, "scoreboard.objectives.add");
|
||||
let modify = d.literal(objectives, "modify");
|
||||
let objective = d.argument(modify, "objective", ArgType::Objective);
|
||||
let dn = d.literal(objective, "displayname");
|
||||
let display = d.argument(dn, "displayName", ArgType::Component);
|
||||
d.executes(display, "scoreboard.objectives.modify.displayname");
|
||||
let rt = d.literal(objective, "rendertype");
|
||||
for kind in ["integer", "hearts"] {
|
||||
let k = d.literal(rt, kind);
|
||||
d.executes(k, "scoreboard.objectives.modify.rendertype");
|
||||
}
|
||||
let au = d.literal(objective, "displayautoupdate");
|
||||
let v = d.argument(au, "value", ArgType::Bool);
|
||||
d.executes(v, "scoreboard.objectives.modify.displayautoupdate");
|
||||
let nf = d.literal(objective, "numberformat");
|
||||
number_formats(d, nf, "scoreboard.objectives.modify.numberformat");
|
||||
let remove = d.literal(objectives, "remove");
|
||||
let objective = d.argument(remove, "objective", ArgType::Objective);
|
||||
d.executes(objective, "scoreboard.objectives.remove");
|
||||
let setdisplay = d.literal(objectives, "setdisplay");
|
||||
let slot = d.argument(setdisplay, "slot", ArgType::ScoreboardSlot);
|
||||
d.executes(slot, "scoreboard.objectives.setdisplay");
|
||||
let objective = d.argument(slot, "objective", ArgType::Objective);
|
||||
d.executes(objective, "scoreboard.objectives.setdisplay");
|
||||
|
||||
let players = d.literal(sb, "players");
|
||||
let list = d.literal(players, "list");
|
||||
d.executes(list, "scoreboard.players.list");
|
||||
let target = d.argument(list, "target", HOLDER);
|
||||
d.executes(target, "scoreboard.players.list");
|
||||
// set / add / remove <targets> <objective> <score>
|
||||
for (word, min, id) in [
|
||||
("set", i32::MIN, "scoreboard.players.set"),
|
||||
("add", 0, "scoreboard.players.add"),
|
||||
("remove", 0, "scoreboard.players.remove"),
|
||||
] {
|
||||
let w = d.literal(players, word);
|
||||
let t = d.argument(w, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
let s = d.argument(o, "score", ArgType::Integer { min, max: i32::MAX });
|
||||
d.executes(s, id);
|
||||
}
|
||||
let get = d.literal(players, "get");
|
||||
let t = d.argument(get, "target", HOLDER);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.get");
|
||||
let reset = d.literal(players, "reset");
|
||||
let t = d.argument(reset, "targets", HOLDERS);
|
||||
d.executes(t, "scoreboard.players.reset");
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.reset");
|
||||
let enable = d.literal(players, "enable");
|
||||
let t = d.argument(enable, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.suggests(o, super::Suggests::EnableTriggers);
|
||||
d.executes(o, "scoreboard.players.enable");
|
||||
let display = d.literal(players, "display");
|
||||
let name = d.literal(display, "name");
|
||||
let t = d.argument(name, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.display.name");
|
||||
let n = d.argument(o, "name", ArgType::Component);
|
||||
d.executes(n, "scoreboard.players.display.name");
|
||||
let nf = d.literal(display, "numberformat");
|
||||
let t = d.argument(nf, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
number_formats(d, o, "scoreboard.players.display.numberformat");
|
||||
let operation = d.literal(players, "operation");
|
||||
let t = d.argument(operation, "targets", HOLDERS);
|
||||
let to = d.argument(t, "targetObjective", ArgType::Objective);
|
||||
let op = d.argument(to, "operation", ArgType::Operation);
|
||||
let source = d.argument(op, "source", HOLDERS);
|
||||
let so = d.argument(source, "sourceObjective", ArgType::Objective);
|
||||
d.executes(so, "scoreboard.players.operation");
|
||||
}
|
||||
|
||||
fn team(d: &mut Dispatcher, root: usize) {
|
||||
let team = d.literal(root, "team");
|
||||
d.requires(team, GAMEMASTERS);
|
||||
let list = d.literal(team, "list");
|
||||
d.executes(list, "team.list");
|
||||
let t = d.argument(list, "team", ArgType::Team);
|
||||
d.executes(t, "team.list");
|
||||
let add = d.literal(team, "add");
|
||||
let t = d.argument(add, "team", ArgType::Word);
|
||||
d.executes(t, "team.add");
|
||||
let dn = d.argument(t, "displayName", ArgType::Component);
|
||||
d.executes(dn, "team.add");
|
||||
let remove = d.literal(team, "remove");
|
||||
let t = d.argument(remove, "team", ArgType::Team);
|
||||
d.executes(t, "team.remove");
|
||||
let empty = d.literal(team, "empty");
|
||||
let t = d.argument(empty, "team", ArgType::Team);
|
||||
d.executes(t, "team.empty");
|
||||
let join = d.literal(team, "join");
|
||||
let t = d.argument(join, "team", ArgType::Team);
|
||||
d.executes(t, "team.join");
|
||||
let m = d.argument(t, "members", HOLDERS);
|
||||
d.executes(m, "team.join");
|
||||
let leave = d.literal(team, "leave");
|
||||
let m = d.argument(leave, "members", HOLDERS);
|
||||
d.executes(m, "team.leave");
|
||||
|
||||
let modify = d.literal(team, "modify");
|
||||
let t = d.argument(modify, "team", ArgType::Team);
|
||||
let dn = d.literal(t, "displayName");
|
||||
let v = d.argument(dn, "displayName", ArgType::Component);
|
||||
d.executes(v, "team.modify.displayname");
|
||||
let color = d.literal(t, "color");
|
||||
let reset = d.literal(color, "reset");
|
||||
d.executes(reset, "team.modify.color.reset");
|
||||
let v = d.argument(color, "value", ArgType::TeamColor);
|
||||
d.executes(v, "team.modify.color");
|
||||
for (word, id) in [
|
||||
("friendlyFire", "team.modify.friendlyfire"),
|
||||
("seeFriendlyInvisibles", "team.modify.seefriendlyinvisibles"),
|
||||
] {
|
||||
let w = d.literal(t, word);
|
||||
let v = d.argument(w, "allowed", ArgType::Bool);
|
||||
d.executes(v, id);
|
||||
}
|
||||
for (word, id, values) in [
|
||||
(
|
||||
"nametagVisibility",
|
||||
"team.modify.nametagvisibility",
|
||||
["never", "hideForOtherTeams", "hideForOwnTeam", "always"],
|
||||
),
|
||||
(
|
||||
"deathMessageVisibility",
|
||||
"team.modify.deathmessagevisibility",
|
||||
["never", "hideForOtherTeams", "hideForOwnTeam", "always"],
|
||||
),
|
||||
(
|
||||
"collisionRule",
|
||||
"team.modify.collisionrule",
|
||||
["never", "pushOwnTeam", "pushOtherTeams", "always"],
|
||||
),
|
||||
] {
|
||||
let w = d.literal(t, word);
|
||||
for value in values {
|
||||
let v = d.literal(w, value);
|
||||
d.executes(v, id);
|
||||
}
|
||||
}
|
||||
for (word, id) in [
|
||||
("prefix", "team.modify.prefix"),
|
||||
("suffix", "team.modify.suffix"),
|
||||
] {
|
||||
let w = d.literal(t, word);
|
||||
let v = d.argument(w, word, ArgType::Component);
|
||||
d.executes(v, id);
|
||||
}
|
||||
}
|
||||
@@ -1,419 +0,0 @@
|
||||
//! Command trees that act on entities and the world: `/recipe`, `/damage`,
|
||||
//! `/rotate`, `/swing`, `/playsound`, `/stopsound`, `/particle`,
|
||||
//! `/attribute`, `/ride`, `/spreadplayers`, `/loot`, `/forceload`,
|
||||
//! `/fillbiome`, `/worldborder`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, integer},
|
||||
vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS},
|
||||
};
|
||||
use crate::settings::SOUND_SOURCES;
|
||||
|
||||
fn float(min: f32) -> ArgType {
|
||||
ArgType::Float { min, max: f32::MAX }
|
||||
}
|
||||
fn double() -> ArgType {
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
recipe(d, root);
|
||||
damage(d, root);
|
||||
rotate_swing(d, root);
|
||||
sounds(d, root);
|
||||
particle(d, root);
|
||||
attribute(d, root);
|
||||
|
||||
// ride <target> (mount <vehicle> | dismount)
|
||||
let ride = d.literal(root, "ride");
|
||||
d.requires(ride, GAMEMASTERS);
|
||||
let target = d.argument(ride, "target", ENTITY);
|
||||
let mount = d.literal(target, "mount");
|
||||
let vehicle = d.argument(mount, "vehicle", ENTITY);
|
||||
d.executes(vehicle, "ride.mount");
|
||||
let dismount = d.literal(target, "dismount");
|
||||
d.executes(dismount, "ride.dismount");
|
||||
|
||||
// spreadplayers <center> <spreadDistance> <maxRange> [under <maxHeight>] <respectTeams> <targets>
|
||||
let spread = d.literal(root, "spreadplayers");
|
||||
d.requires(spread, GAMEMASTERS);
|
||||
let center = d.argument(spread, "center", ArgType::Vec2);
|
||||
let dist = d.argument(center, "spreadDistance", float(0.0));
|
||||
let range = d.argument(dist, "maxRange", float(1.0));
|
||||
let respect = d.argument(range, "respectTeams", ArgType::Bool);
|
||||
let targets = d.argument(respect, "targets", ENTITIES);
|
||||
d.executes(targets, "spreadplayers");
|
||||
let under = d.literal(range, "under");
|
||||
let height = d.argument(under, "maxHeight", integer(i32::MIN));
|
||||
let respect = d.argument(height, "respectTeams", ArgType::Bool);
|
||||
let targets = d.argument(respect, "targets", ENTITIES);
|
||||
d.executes(targets, "spreadplayers");
|
||||
|
||||
// place template <template> [<pos> [<rotation> [<mirror> [<integrity> [<seed> [strict]]]]]]
|
||||
let place = d.literal(root, "place");
|
||||
d.requires(place, GAMEMASTERS);
|
||||
let feature = d.literal(place, "feature");
|
||||
let f = d.argument(
|
||||
feature,
|
||||
"feature",
|
||||
ArgType::ResourceOrId("minecraft:worldgen/feature"),
|
||||
);
|
||||
d.executes(f, "place.feature");
|
||||
let pos = d.argument(f, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "place.feature");
|
||||
let jigsaw = d.literal(place, "jigsaw");
|
||||
let pool = d.argument(
|
||||
jigsaw,
|
||||
"pool",
|
||||
ArgType::ResKey("minecraft:worldgen/template_pool"),
|
||||
);
|
||||
let target = d.argument(pool, "target", ArgType::Id("none"));
|
||||
let depth = d.argument(target, "max_depth", ArgType::Integer { min: 1, max: 20 });
|
||||
d.executes(depth, "place.jigsaw");
|
||||
let position = d.argument(depth, "position", ArgType::BlockPos);
|
||||
d.executes(position, "place.jigsaw");
|
||||
let structure = d.literal(place, "structure");
|
||||
let st = d.argument(
|
||||
structure,
|
||||
"structure",
|
||||
ArgType::ResKey("minecraft:worldgen/structure"),
|
||||
);
|
||||
d.executes(st, "place.structure");
|
||||
let pos = d.argument(st, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "place.structure");
|
||||
let template = d.literal(place, "template");
|
||||
let id = d.argument(template, "template", ArgType::Id("templates"));
|
||||
d.executes(id, "place");
|
||||
let pos = d.argument(id, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "place");
|
||||
let rotation = d.argument(
|
||||
pos,
|
||||
"rotation",
|
||||
ArgType::StrEnum(
|
||||
&["none", "clockwise_90", "180", "counterclockwise_90"],
|
||||
"argument.enum.invalid",
|
||||
),
|
||||
);
|
||||
d.executes(rotation, "place");
|
||||
let mirror = d.argument(
|
||||
rotation,
|
||||
"mirror",
|
||||
ArgType::StrEnum(
|
||||
&["none", "left_right", "front_back"],
|
||||
"argument.enum.invalid",
|
||||
),
|
||||
);
|
||||
d.executes(mirror, "place");
|
||||
let integrity = d.argument(mirror, "integrity", ArgType::Float { min: 0.0, max: 1.0 });
|
||||
d.executes(integrity, "place");
|
||||
let seed = d.argument(integrity, "seed", integer(i32::MIN));
|
||||
d.executes(seed, "place");
|
||||
let strict = d.literal(seed, "strict");
|
||||
d.executes(strict, "place");
|
||||
|
||||
forceload(d, root);
|
||||
fillbiome(d, root);
|
||||
worldborder(d, root);
|
||||
loot(d, root);
|
||||
}
|
||||
|
||||
fn recipe(d: &mut Dispatcher, root: usize) {
|
||||
let recipe = d.literal(root, "recipe");
|
||||
d.requires(recipe, GAMEMASTERS);
|
||||
for (word, id) in [("give", "recipe.give"), ("take", "recipe.take")] {
|
||||
let w = d.literal(recipe, word);
|
||||
let t = d.argument(w, "targets", PLAYERS);
|
||||
let r = d.argument(t, "recipe", ArgType::ResKey("minecraft:recipe"));
|
||||
d.executes(r, id);
|
||||
let all = d.literal(t, "*");
|
||||
d.executes(all, id);
|
||||
}
|
||||
}
|
||||
|
||||
fn damage(d: &mut Dispatcher, root: usize) {
|
||||
let damage = d.literal(root, "damage");
|
||||
d.requires(damage, GAMEMASTERS);
|
||||
let target = d.argument(damage, "target", ENTITY);
|
||||
let amount = d.argument(target, "amount", float(0.0));
|
||||
d.executes(amount, "damage");
|
||||
let ty = d.argument(amount, "damageType", ArgType::Res("minecraft:damage_type"));
|
||||
d.executes(ty, "damage");
|
||||
let at = d.literal(ty, "at");
|
||||
let loc = d.argument(at, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "damage");
|
||||
let by = d.literal(ty, "by");
|
||||
let entity = d.argument(by, "entity", ENTITY);
|
||||
d.executes(entity, "damage");
|
||||
let from = d.literal(entity, "from");
|
||||
let cause = d.argument(from, "cause", ENTITY);
|
||||
d.executes(cause, "damage");
|
||||
}
|
||||
|
||||
fn rotate_swing(d: &mut Dispatcher, root: usize) {
|
||||
let rotate = d.literal(root, "rotate");
|
||||
d.requires(rotate, GAMEMASTERS);
|
||||
let target = d.argument(rotate, "target", ENTITY);
|
||||
let rot = d.argument(target, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "rotate");
|
||||
let facing = d.literal(target, "facing");
|
||||
let entity = d.literal(facing, "entity");
|
||||
let fe = d.argument(entity, "facingEntity", ENTITY);
|
||||
d.executes(fe, "rotate");
|
||||
let anchor = d.argument(fe, "facingAnchor", ArgType::Anchor);
|
||||
d.executes(anchor, "rotate");
|
||||
let loc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "rotate");
|
||||
|
||||
let swing = d.literal(root, "swing");
|
||||
d.requires(swing, GAMEMASTERS);
|
||||
d.executes(swing, "swing");
|
||||
let targets = d.argument(swing, "targets", ENTITIES);
|
||||
d.executes(targets, "swing");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(targets, hand);
|
||||
d.executes(h, "swing");
|
||||
let animation = d.argument(
|
||||
h,
|
||||
"animation",
|
||||
ArgType::StrEnum(
|
||||
&["none", "whack", "stab"],
|
||||
"argument.swing_animation.invalid",
|
||||
),
|
||||
);
|
||||
d.executes(animation, "swing");
|
||||
let duration = d.argument(animation, "duration", ArgType::Time { min: 1 });
|
||||
d.executes(duration, "swing");
|
||||
}
|
||||
}
|
||||
|
||||
fn sounds(d: &mut Dispatcher, root: usize) {
|
||||
let play = d.literal(root, "playsound");
|
||||
d.requires(play, GAMEMASTERS);
|
||||
let sound = d.argument(play, "sound", ArgType::Id("sounds"));
|
||||
d.executes(sound, "playsound");
|
||||
let stop = d.literal(root, "stopsound");
|
||||
d.requires(stop, GAMEMASTERS);
|
||||
let stop_targets = d.argument(stop, "targets", PLAYERS);
|
||||
d.executes(stop_targets, "stopsound");
|
||||
let any = d.literal(stop_targets, "*");
|
||||
let any_sound = d.argument(any, "sound", ArgType::Id("sounds"));
|
||||
d.executes(any_sound, "stopsound");
|
||||
for source in SOUND_SOURCES {
|
||||
let s = d.literal(sound, source);
|
||||
d.executes(s, "playsound");
|
||||
let targets = d.argument(s, "targets", PLAYERS);
|
||||
d.executes(targets, "playsound");
|
||||
let pos = d.argument(targets, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "playsound");
|
||||
let volume = d.argument(pos, "volume", float(0.0));
|
||||
d.executes(volume, "playsound");
|
||||
let pitch = d.argument(volume, "pitch", ArgType::Float { min: 0.0, max: 2.0 });
|
||||
d.executes(pitch, "playsound");
|
||||
let min = d.argument(pitch, "minVolume", ArgType::Float { min: 0.0, max: 1.0 });
|
||||
d.executes(min, "playsound");
|
||||
|
||||
let ls = d.literal(stop_targets, source);
|
||||
d.executes(ls, "stopsound");
|
||||
let lsound = d.argument(ls, "sound", ArgType::Id("sounds"));
|
||||
d.executes(lsound, "stopsound");
|
||||
}
|
||||
}
|
||||
|
||||
fn particle(d: &mut Dispatcher, root: usize) {
|
||||
let particle = d.literal(root, "particle");
|
||||
d.requires(particle, GAMEMASTERS);
|
||||
let name = d.argument(particle, "name", ArgType::Particle);
|
||||
d.executes(name, "particle");
|
||||
let pos = d.argument(name, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "particle");
|
||||
let delta = d.argument(pos, "delta", ArgType::Vec3 { center: false });
|
||||
let speed = d.argument(delta, "speed", float(0.0));
|
||||
let count = d.argument(speed, "count", integer(0));
|
||||
d.executes(count, "particle");
|
||||
for mode in ["force", "normal"] {
|
||||
let m = d.literal(count, mode);
|
||||
d.executes(m, "particle");
|
||||
let viewers = d.argument(m, "viewers", PLAYERS);
|
||||
d.executes(viewers, "particle");
|
||||
}
|
||||
}
|
||||
|
||||
fn attribute(d: &mut Dispatcher, root: usize) {
|
||||
let attribute = d.literal(root, "attribute");
|
||||
d.requires(attribute, GAMEMASTERS);
|
||||
let target = d.argument(attribute, "target", ENTITY);
|
||||
let attr = d.argument(target, "attribute", ArgType::Res("minecraft:attribute"));
|
||||
let get = d.literal(attr, "get");
|
||||
d.executes(get, "attribute.get");
|
||||
let scale = d.argument(get, "scale", double());
|
||||
d.executes(scale, "attribute.get");
|
||||
let base = d.literal(attr, "base");
|
||||
let set = d.literal(base, "set");
|
||||
let value = d.argument(set, "value", double());
|
||||
d.executes(value, "attribute.base.set");
|
||||
let bget = d.literal(base, "get");
|
||||
d.executes(bget, "attribute.base.get");
|
||||
let bscale = d.argument(bget, "scale", double());
|
||||
d.executes(bscale, "attribute.base.get");
|
||||
let reset = d.literal(base, "reset");
|
||||
d.executes(reset, "attribute.base.reset");
|
||||
let modifier = d.literal(attr, "modifier");
|
||||
let add = d.literal(modifier, "add");
|
||||
let id = d.argument(add, "id", ArgType::Id("attribute_modifiers"));
|
||||
let value = d.argument(id, "value", double());
|
||||
for op in ["add_value", "add_multiplied_base", "add_multiplied_total"] {
|
||||
let o = d.literal(value, op);
|
||||
d.executes(o, "attribute.modifier.add");
|
||||
}
|
||||
let remove = d.literal(modifier, "remove");
|
||||
let rid = d.argument(remove, "id", ArgType::Id("attribute_modifiers"));
|
||||
d.executes(rid, "attribute.modifier.remove");
|
||||
let value_l = d.literal(modifier, "value");
|
||||
let vget = d.literal(value_l, "get");
|
||||
let vid = d.argument(vget, "id", ArgType::Id("attribute_modifiers"));
|
||||
d.executes(vid, "attribute.modifier.get");
|
||||
let vscale = d.argument(vid, "scale", double());
|
||||
d.executes(vscale, "attribute.modifier.get");
|
||||
}
|
||||
|
||||
fn forceload(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "forceload");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
for (word, id) in [("add", "forceload.add"), ("remove", "forceload.remove")] {
|
||||
let w = d.literal(f, word);
|
||||
let from = d.argument(w, "from", ArgType::ColumnPos);
|
||||
d.executes(from, id);
|
||||
let to = d.argument(from, "to", ArgType::ColumnPos);
|
||||
d.executes(to, id);
|
||||
if word == "remove" {
|
||||
let all = d.literal(w, "all");
|
||||
d.executes(all, "forceload.remove.all");
|
||||
}
|
||||
}
|
||||
let query = d.literal(f, "query");
|
||||
d.executes(query, "forceload.query");
|
||||
let pos = d.argument(query, "pos", ArgType::ColumnPos);
|
||||
d.executes(pos, "forceload.query");
|
||||
}
|
||||
|
||||
fn fillbiome(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "fillbiome");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
let from = d.argument(f, "from", ArgType::BlockPos);
|
||||
let to = d.argument(from, "to", ArgType::BlockPos);
|
||||
let biome = d.argument(to, "biome", ArgType::Res("minecraft:worldgen/biome"));
|
||||
d.executes(biome, "fillbiome");
|
||||
let replace = d.literal(biome, "replace");
|
||||
let filter = d.argument(
|
||||
replace,
|
||||
"filter",
|
||||
ArgType::ResOrTag("minecraft:worldgen/biome"),
|
||||
);
|
||||
d.executes(filter, "fillbiome");
|
||||
}
|
||||
|
||||
fn worldborder(d: &mut Dispatcher, root: usize) {
|
||||
let w = d.literal(root, "worldborder");
|
||||
d.requires(w, GAMEMASTERS);
|
||||
let dist = || ArgType::Double {
|
||||
min: -5.999_996_8e7,
|
||||
max: 5.999_996_8e7,
|
||||
};
|
||||
for word in ["add", "set"] {
|
||||
let l = d.literal(w, word);
|
||||
let distance = d.argument(l, "distance", dist());
|
||||
let id = if word == "add" {
|
||||
"worldborder.add"
|
||||
} else {
|
||||
"worldborder.set"
|
||||
};
|
||||
d.executes(distance, id);
|
||||
let time = d.argument(distance, "time", ArgType::Time { min: 0 });
|
||||
d.executes(time, id);
|
||||
}
|
||||
let center = d.literal(w, "center");
|
||||
let pos = d.argument(center, "pos", ArgType::Vec2);
|
||||
d.executes(pos, "worldborder.center");
|
||||
let damage = d.literal(w, "damage");
|
||||
let amount = d.literal(damage, "amount");
|
||||
let per = d.argument(amount, "damagePerBlock", float(0.0));
|
||||
d.executes(per, "worldborder.damage.amount");
|
||||
let buffer = d.literal(damage, "buffer");
|
||||
let b = d.argument(buffer, "distance", float(0.0));
|
||||
d.executes(b, "worldborder.damage.buffer");
|
||||
let get = d.literal(w, "get");
|
||||
d.executes(get, "worldborder.get");
|
||||
let warning = d.literal(w, "warning");
|
||||
let wd = d.literal(warning, "distance");
|
||||
let v = d.argument(wd, "distance", integer(0));
|
||||
d.executes(v, "worldborder.warning.distance");
|
||||
let wt = d.literal(warning, "time");
|
||||
let v = d.argument(wt, "time", ArgType::Time { min: 0 });
|
||||
d.executes(v, "worldborder.warning.time");
|
||||
}
|
||||
|
||||
/// `loot (replace|insert|give|spawn) ... (fish|loot|kill|mine)`.
|
||||
fn loot(d: &mut Dispatcher, root: usize) {
|
||||
let loot = d.literal(root, "loot");
|
||||
d.requires(loot, GAMEMASTERS);
|
||||
// Targets.
|
||||
let mut targets = Vec::new();
|
||||
let replace = d.literal(loot, "replace");
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(replace, provider);
|
||||
let a = if provider == "entity" {
|
||||
d.argument(p, "entities", ENTITIES)
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slot = d.argument(a, "slot", ArgType::Slot);
|
||||
targets.push(slot);
|
||||
let count = d.argument(slot, "count", integer(0));
|
||||
targets.push(count);
|
||||
}
|
||||
let insert = d.literal(loot, "insert");
|
||||
targets.push(d.argument(insert, "targetPos", ArgType::BlockPos));
|
||||
let give = d.literal(loot, "give");
|
||||
targets.push(d.argument(give, "players", PLAYERS));
|
||||
let spawn = d.literal(loot, "spawn");
|
||||
targets.push(d.argument(spawn, "targetPos", ArgType::Vec3 { center: true }));
|
||||
// Sources.
|
||||
for t in targets {
|
||||
let fish = d.literal(t, "fish");
|
||||
let table = d.argument(
|
||||
fish,
|
||||
"loot_table",
|
||||
ArgType::ResourceOrId("minecraft:loot_table"),
|
||||
);
|
||||
let pos = d.argument(table, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "loot.fish");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(pos, hand);
|
||||
d.executes(h, "loot.fish");
|
||||
}
|
||||
let tool = d.argument(pos, "tool", ArgType::Item);
|
||||
d.executes(tool, "loot.fish");
|
||||
let l = d.literal(t, "loot");
|
||||
let lt = d.argument(
|
||||
l,
|
||||
"loot_table",
|
||||
ArgType::ResourceOrId("minecraft:loot_table"),
|
||||
);
|
||||
d.executes(lt, "loot.loot");
|
||||
let kill = d.literal(t, "kill");
|
||||
let target = d.argument(kill, "target", ENTITY);
|
||||
d.executes(target, "loot.kill");
|
||||
let mine = d.literal(t, "mine");
|
||||
let pos = d.argument(mine, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "loot.mine");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(pos, hand);
|
||||
d.executes(h, "loot.mine");
|
||||
}
|
||||
let tool = d.argument(pos, "tool", ArgType::Item);
|
||||
d.executes(tool, "loot.mine");
|
||||
}
|
||||
}
|
||||
@@ -1,614 +0,0 @@
|
||||
//! The vanilla command tree (Commands.java registrations) for the commands
|
||||
//! Horizon implements. Leaves carry command ids that the game executes;
|
||||
//! mode keywords are read back from the parsed literals.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, Resource, integer},
|
||||
};
|
||||
use crate::gamerules::{RULES, Value};
|
||||
|
||||
/// Permission levels (Commands.LEVEL_*).
|
||||
pub const ALL: u8 = 0;
|
||||
pub const GAMEMASTERS: u8 = 2;
|
||||
|
||||
pub const PLAYERS: ArgType = ArgType::Entity {
|
||||
single: false,
|
||||
players: true,
|
||||
};
|
||||
pub const PLAYER: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: true,
|
||||
};
|
||||
pub const ENTITIES: ArgType = ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
pub const ENTITY: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
};
|
||||
|
||||
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
|
||||
|
||||
pub fn build() -> Dispatcher {
|
||||
build_with(true)
|
||||
}
|
||||
/// The tree Commands registers; `dev` adds the commands vanilla only
|
||||
/// registers in development builds (raid, warden_spawn_tracker).
|
||||
pub fn build_with(dev: bool) -> Dispatcher {
|
||||
let mut d = registered(dev);
|
||||
apply_vanilla_order(&mut d);
|
||||
d
|
||||
}
|
||||
/// The tree in the order Horizon's code registers it, before
|
||||
/// [`vanilla_order`](super::vanilla_order) puts children in vanilla's order
|
||||
/// (tools/generate_command_order.py compares the two).
|
||||
pub fn registered(dev: bool) -> Dispatcher {
|
||||
let mut d = Dispatcher::new();
|
||||
let root = 0;
|
||||
|
||||
advancement(&mut d, root);
|
||||
|
||||
// help [<command>]
|
||||
let help = d.literal(root, "help");
|
||||
d.executes(help, "help");
|
||||
let c = d.argument(help, "command", ArgType::Greedy);
|
||||
d.executes(c, "help");
|
||||
|
||||
// gamemode <gamemode> [<target>]
|
||||
let gm = d.literal(root, "gamemode");
|
||||
d.requires(gm, GAMEMASTERS);
|
||||
let mode = d.argument(gm, "gamemode", ArgType::GameMode);
|
||||
d.executes(mode, "gamemode");
|
||||
let t = d.argument(mode, "target", PLAYERS);
|
||||
d.executes(t, "gamemode");
|
||||
|
||||
let dgm = d.literal(root, "defaultgamemode");
|
||||
d.requires(dgm, GAMEMASTERS);
|
||||
let mode = d.argument(dgm, "gamemode", ArgType::GameMode);
|
||||
d.executes(mode, "defaultgamemode");
|
||||
|
||||
// give <targets> <item> [<count>]
|
||||
let give = d.literal(root, "give");
|
||||
d.requires(give, GAMEMASTERS);
|
||||
let targets = d.argument(give, "targets", PLAYERS);
|
||||
let item = d.argument(targets, "item", ArgType::Item);
|
||||
d.executes(item, "give");
|
||||
let count = d.argument(item, "count", integer(1));
|
||||
d.executes(count, "give");
|
||||
|
||||
// teleport / tp
|
||||
let tp = d.literal(root, "teleport");
|
||||
d.requires(tp, GAMEMASTERS);
|
||||
let loc = d.argument(tp, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "teleport.location");
|
||||
let dest = d.argument(tp, "destination", ENTITY);
|
||||
d.executes(dest, "teleport.destination");
|
||||
let targets = d.argument(tp, "targets", ENTITIES);
|
||||
let loc = d.argument(targets, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "teleport.targets.location");
|
||||
let rot = d.argument(loc, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "teleport.targets.location");
|
||||
let facing = d.literal(loc, "facing");
|
||||
let fe = d.literal(facing, "entity");
|
||||
let fent = d.argument(fe, "facingEntity", ENTITY);
|
||||
d.executes(fent, "teleport.targets.location");
|
||||
let anchor = d.argument(fent, "facingAnchor", ArgType::Anchor);
|
||||
d.executes(anchor, "teleport.targets.location");
|
||||
let floc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
|
||||
d.executes(floc, "teleport.targets.location");
|
||||
let dest = d.argument(targets, "destination", ENTITY);
|
||||
d.executes(dest, "teleport.targets.destination");
|
||||
let alias = d.literal(root, "tp");
|
||||
d.requires(alias, GAMEMASTERS);
|
||||
d.redirect(alias, tp);
|
||||
|
||||
// time: clock nodes for the dimension's default clock, plus `of <clock>`.
|
||||
let time = d.literal(root, "time");
|
||||
d.requires(time, GAMEMASTERS);
|
||||
clock_nodes(&mut d, time);
|
||||
let query = d.literal(time, "query");
|
||||
let gt = d.literal(query, "gametime");
|
||||
d.executes(gt, "time.query.gametime");
|
||||
let of = d.literal(time, "of");
|
||||
let clock = d.argument(of, "clock", ArgType::Resource(Resource::Clock));
|
||||
clock_nodes(&mut d, clock);
|
||||
|
||||
// weather (clear|rain|thunder) [<duration>]
|
||||
let weather = d.literal(root, "weather");
|
||||
d.requires(weather, GAMEMASTERS);
|
||||
for kind in ["clear", "rain", "thunder"] {
|
||||
let k = d.literal(weather, kind);
|
||||
d.executes(k, "weather");
|
||||
let dur = d.argument(k, "duration", ArgType::Time { min: 1 });
|
||||
d.executes(dur, "weather");
|
||||
}
|
||||
|
||||
if dev {
|
||||
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
|
||||
let raid = d.literal(root, "raid");
|
||||
d.requires(raid, 3);
|
||||
let start = d.literal(raid, "start");
|
||||
let level = d.argument(start, "omenlvl", integer(0));
|
||||
d.executes(level, "raid.start");
|
||||
for (name, id) in [
|
||||
("stop", "raid.stop"),
|
||||
("check", "raid.check"),
|
||||
("spawnleader", "raid.spawnleader"),
|
||||
("glow", "raid.glow"),
|
||||
] {
|
||||
let n = d.literal(raid, name);
|
||||
d.executes(n, id);
|
||||
}
|
||||
let sound = d.literal(raid, "sound");
|
||||
let kind = d.argument(sound, "type", ArgType::Greedy);
|
||||
d.executes(kind, "raid.sound");
|
||||
let setomen = d.literal(raid, "setomen");
|
||||
let level = d.argument(setomen, "level", integer(0));
|
||||
d.executes(level, "raid.setomen");
|
||||
}
|
||||
|
||||
// kill [<targets>]
|
||||
let kill = d.literal(root, "kill");
|
||||
d.requires(kill, GAMEMASTERS);
|
||||
d.executes(kill, "kill");
|
||||
let t = d.argument(kill, "targets", ENTITIES);
|
||||
d.executes(t, "kill");
|
||||
|
||||
// effect clear [<targets> [<effect>]] | give <targets> <effect> [<seconds>|infinite [<amplifier> [<hideParticles>]]]
|
||||
let effect = d.literal(root, "effect");
|
||||
d.requires(effect, GAMEMASTERS);
|
||||
let clear = d.literal(effect, "clear");
|
||||
d.executes(clear, "effect.clear");
|
||||
let t = d.argument(clear, "targets", ENTITIES);
|
||||
d.executes(t, "effect.clear");
|
||||
let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect));
|
||||
d.executes(e, "effect.clear");
|
||||
let give = d.literal(effect, "give");
|
||||
let t = d.argument(give, "targets", ENTITIES);
|
||||
let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect));
|
||||
d.executes(e, "effect.give");
|
||||
let seconds = d.argument(
|
||||
e,
|
||||
"seconds",
|
||||
ArgType::Integer {
|
||||
min: 1,
|
||||
max: 1_000_000,
|
||||
},
|
||||
);
|
||||
let infinite = d.literal(e, "infinite");
|
||||
for duration in [seconds, infinite] {
|
||||
d.executes(duration, "effect.give");
|
||||
let amp = d.argument(duration, "amplifier", ArgType::Integer { min: 0, max: 255 });
|
||||
d.executes(amp, "effect.give");
|
||||
let hide = d.argument(amp, "hideParticles", ArgType::Bool);
|
||||
d.executes(hide, "effect.give");
|
||||
}
|
||||
|
||||
// enchant <targets> <enchantment> [<level>]
|
||||
let enchant = d.literal(root, "enchant");
|
||||
d.requires(enchant, GAMEMASTERS);
|
||||
let t = d.argument(enchant, "targets", ENTITIES);
|
||||
let e = d.argument(t, "enchantment", ArgType::Resource(Resource::Enchantment));
|
||||
d.executes(e, "enchant");
|
||||
let level = d.argument(e, "level", integer(0));
|
||||
d.executes(level, "enchant");
|
||||
|
||||
// summon <entity> [<pos>] [<nbt>]
|
||||
let summon = d.literal(root, "summon");
|
||||
d.requires(summon, GAMEMASTERS);
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.suggests(e, super::Suggests::SummonableEntities);
|
||||
d.executes(e, "summon");
|
||||
let pos = d.argument(e, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "summon");
|
||||
let nbt = d.argument(pos, "nbt", ArgType::Nbt);
|
||||
d.executes(nbt, "summon");
|
||||
|
||||
// setblock <pos> <block> [destroy|keep|replace|strict]
|
||||
let sb = d.literal(root, "setblock");
|
||||
d.requires(sb, GAMEMASTERS);
|
||||
let pos = d.argument(sb, "pos", ArgType::BlockPos);
|
||||
let block = d.argument(pos, "block", ArgType::BlockState);
|
||||
d.executes(block, "setblock");
|
||||
for m in ["destroy", "keep", "replace", "strict"] {
|
||||
let l = d.literal(block, m);
|
||||
d.executes(l, "setblock");
|
||||
}
|
||||
|
||||
// fill <from> <to> <block> [modes]
|
||||
let fill = d.literal(root, "fill");
|
||||
d.requires(fill, GAMEMASTERS);
|
||||
let from = d.argument(fill, "from", ArgType::BlockPos);
|
||||
let to = d.argument(from, "to", ArgType::BlockPos);
|
||||
let block = d.argument(to, "block", ArgType::BlockState);
|
||||
fill_modes(&mut d, block);
|
||||
let replace = d.literal(block, "replace");
|
||||
d.executes(replace, "fill");
|
||||
let filter = d.argument(replace, "filter", ArgType::BlockPredicate);
|
||||
fill_modes(&mut d, filter);
|
||||
let keep = d.literal(block, "keep");
|
||||
d.executes(keep, "fill");
|
||||
|
||||
// clone [from <dim>] <begin> <end> [to <dim>] <destination> [strict] [mask] [mode]
|
||||
let clone = d.literal(root, "clone");
|
||||
d.requires(clone, GAMEMASTERS);
|
||||
clone_begin(&mut d, clone);
|
||||
let from = d.literal(clone, "from");
|
||||
let dim = d.argument(from, "sourceDimension", ArgType::Dimension);
|
||||
clone_begin(&mut d, dim);
|
||||
|
||||
// experience / xp
|
||||
let xp = d.literal(root, "experience");
|
||||
d.requires(xp, GAMEMASTERS);
|
||||
for (op, min) in [("add", i32::MIN), ("set", 0)] {
|
||||
let o = d.literal(xp, op);
|
||||
let t = d.argument(o, "target", PLAYERS);
|
||||
let amount = d.argument(t, "amount", integer(min));
|
||||
d.executes(amount, "experience");
|
||||
for unit in ["points", "levels"] {
|
||||
let u = d.literal(amount, unit);
|
||||
d.executes(u, "experience");
|
||||
}
|
||||
}
|
||||
let q = d.literal(xp, "query");
|
||||
let t = d.argument(q, "target", PLAYER);
|
||||
for unit in ["points", "levels"] {
|
||||
let u = d.literal(t, unit);
|
||||
d.executes(u, "experience");
|
||||
}
|
||||
let alias = d.literal(root, "xp");
|
||||
d.requires(alias, GAMEMASTERS);
|
||||
d.redirect(alias, xp);
|
||||
|
||||
// gamerule <rule> [<value>] (short and namespaced names)
|
||||
let gr = d.literal(root, "gamerule");
|
||||
d.requires(gr, GAMEMASTERS);
|
||||
for rule in RULES {
|
||||
for name in [rule.name.to_owned(), format!("minecraft:{}", rule.name)] {
|
||||
let r = d.literal(gr, &name);
|
||||
d.executes(r, "gamerule");
|
||||
let ty = match rule.default {
|
||||
Value::Bool(_) => ArgType::Bool,
|
||||
Value::Int(_) => ArgType::Integer {
|
||||
min: rule.min,
|
||||
max: rule.max,
|
||||
},
|
||||
};
|
||||
let v = d.argument(r, "value", ty);
|
||||
d.executes(v, "gamerule");
|
||||
}
|
||||
}
|
||||
|
||||
// difficulty [<difficulty>]
|
||||
let diff = d.literal(root, "difficulty");
|
||||
d.requires(diff, GAMEMASTERS);
|
||||
d.executes(diff, "difficulty");
|
||||
for name in DIFFICULTIES {
|
||||
let l = d.literal(diff, name);
|
||||
d.executes(l, "difficulty");
|
||||
}
|
||||
|
||||
// seed and version: everyone in the integrated server.
|
||||
let seed = d.literal(root, "seed");
|
||||
d.executes(seed, "seed");
|
||||
let version = d.literal(root, "version");
|
||||
d.executes(version, "version");
|
||||
|
||||
// spawnpoint [<targets>] [<pos>] [<rotation>]
|
||||
let sp = d.literal(root, "spawnpoint");
|
||||
d.requires(sp, GAMEMASTERS);
|
||||
d.executes(sp, "spawnpoint");
|
||||
let t = d.argument(sp, "targets", PLAYERS);
|
||||
d.executes(t, "spawnpoint");
|
||||
let pos = d.argument(t, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "spawnpoint");
|
||||
let rot = d.argument(pos, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "spawnpoint");
|
||||
|
||||
// setworldspawn [<pos>] [<rotation>]
|
||||
let ws = d.literal(root, "setworldspawn");
|
||||
d.requires(ws, GAMEMASTERS);
|
||||
d.executes(ws, "setworldspawn");
|
||||
let pos = d.argument(ws, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "setworldspawn");
|
||||
let rot = d.argument(pos, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "setworldspawn");
|
||||
|
||||
// clear [<targets>] [<item>] [<maxCount>]
|
||||
let clear = d.literal(root, "clear");
|
||||
d.requires(clear, GAMEMASTERS);
|
||||
d.executes(clear, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "clear");
|
||||
let item = d.argument(t, "item", ArgType::ItemPredicate);
|
||||
d.executes(item, "clear");
|
||||
let max = d.argument(item, "maxCount", integer(0));
|
||||
d.executes(max, "clear");
|
||||
|
||||
// locate (structure|biome) <...>
|
||||
let locate = d.literal(root, "locate");
|
||||
d.requires(locate, GAMEMASTERS);
|
||||
let s = d.literal(locate, "structure");
|
||||
let a = d.argument(
|
||||
s,
|
||||
"structure",
|
||||
ArgType::ResOrTagKey("minecraft:worldgen/structure"),
|
||||
);
|
||||
d.executes(a, "locate.structure");
|
||||
let b = d.literal(locate, "biome");
|
||||
let a = d.argument(b, "biome", ArgType::ResOrTag("minecraft:worldgen/biome"));
|
||||
d.executes(a, "locate.biome");
|
||||
let p = d.literal(locate, "poi");
|
||||
let a = d.argument(
|
||||
p,
|
||||
"poi",
|
||||
ArgType::ResOrTag("minecraft:point_of_interest_type"),
|
||||
);
|
||||
d.executes(a, "locate.poi");
|
||||
|
||||
if dev {
|
||||
// warden_spawn_tracker (clear | set <warning_level>)
|
||||
let tracker = d.literal(root, "warden_spawn_tracker");
|
||||
d.requires(tracker, GAMEMASTERS);
|
||||
let clear = d.literal(tracker, "clear");
|
||||
d.executes(clear, "warden_spawn_tracker.clear");
|
||||
let set = d.literal(tracker, "set");
|
||||
let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 });
|
||||
d.executes(level, "warden_spawn_tracker.set");
|
||||
}
|
||||
|
||||
// say / me / msg / list
|
||||
let say = d.literal(root, "say");
|
||||
d.requires(say, GAMEMASTERS);
|
||||
let m = d.argument(say, "message", ArgType::Message);
|
||||
d.executes(m, "say");
|
||||
let me = d.literal(root, "me");
|
||||
let m = d.argument(me, "action", ArgType::Message);
|
||||
d.executes(m, "me");
|
||||
let msg = d.literal(root, "msg");
|
||||
let t = d.argument(msg, "targets", PLAYERS);
|
||||
let m = d.argument(t, "message", ArgType::Message);
|
||||
d.executes(m, "msg");
|
||||
for alias in ["tell", "w"] {
|
||||
let a = d.literal(root, alias);
|
||||
d.redirect(a, msg);
|
||||
}
|
||||
let list = d.literal(root, "list");
|
||||
d.executes(list, "list");
|
||||
let uuids = d.literal(list, "uuids");
|
||||
d.executes(uuids, "list");
|
||||
|
||||
// tellraw <targets> <message>
|
||||
let tellraw = d.literal(root, "tellraw");
|
||||
d.requires(tellraw, GAMEMASTERS);
|
||||
let t = d.argument(tellraw, "targets", PLAYERS);
|
||||
let m = d.argument(t, "message", ArgType::Component);
|
||||
d.executes(m, "tellraw");
|
||||
|
||||
// title <targets> clear|reset|title|subtitle|actionbar <title>|times <in> <stay> <out>
|
||||
let title = d.literal(root, "title");
|
||||
d.requires(title, GAMEMASTERS);
|
||||
let t = d.argument(title, "targets", PLAYERS);
|
||||
for mode in ["clear", "reset"] {
|
||||
let l = d.literal(t, mode);
|
||||
d.executes(l, "title");
|
||||
}
|
||||
for mode in ["title", "subtitle", "actionbar"] {
|
||||
let l = d.literal(t, mode);
|
||||
let c = d.argument(l, "title", ArgType::Component);
|
||||
d.executes(c, "title");
|
||||
}
|
||||
let times = d.literal(t, "times");
|
||||
let fade_in = d.argument(times, "fadeIn", ArgType::Time { min: 0 });
|
||||
let stay = d.argument(fade_in, "stay", ArgType::Time { min: 0 });
|
||||
let fade_out = d.argument(stay, "fadeOut", ArgType::Time { min: 0 });
|
||||
d.executes(fade_out, "title");
|
||||
|
||||
super::tree_scoreboard::register(&mut d, root);
|
||||
super::tree_data::register(&mut d, root);
|
||||
super::tree_execute::register(&mut d, root);
|
||||
super::tree_misc::register(&mut d, root);
|
||||
super::tree_world::register(&mut d, root);
|
||||
super::tree_extra::register(&mut d, root);
|
||||
d
|
||||
}
|
||||
|
||||
/// AdvancementCommands: grant|revoke <targets> only|from|until|through
|
||||
/// <advancement> | everything; `only` takes an optional criterion.
|
||||
fn advancement(d: &mut Dispatcher, root: usize) {
|
||||
let adv = d.literal(root, "advancement");
|
||||
d.requires(adv, GAMEMASTERS);
|
||||
for action in ["grant", "revoke"] {
|
||||
let a = d.literal(adv, action);
|
||||
let t = d.argument(a, "targets", PLAYERS);
|
||||
for mode in ["only", "from", "until", "through"] {
|
||||
let m = d.literal(t, mode);
|
||||
let id = d.argument(m, "advancement", ArgType::ResKey("minecraft:advancement"));
|
||||
d.executes(id, "advancement");
|
||||
if mode == "only" {
|
||||
let c = d.argument(id, "criterion", ArgType::Greedy);
|
||||
d.suggests(c, super::Suggests::AdvancementCriteria);
|
||||
d.executes(c, "advancement");
|
||||
}
|
||||
}
|
||||
let e = d.literal(t, "everything");
|
||||
d.executes(e, "advancement");
|
||||
}
|
||||
}
|
||||
|
||||
/// TimeCommand.addClockNodes.
|
||||
fn clock_nodes(d: &mut Dispatcher, node: usize) {
|
||||
let set = d.literal(node, "set");
|
||||
let t = d.argument(set, "time", ArgType::Time { min: 0 });
|
||||
d.executes(t, "time.set");
|
||||
let marker = d.argument(set, "timemarker", ArgType::Id("time_markers"));
|
||||
d.suggests(marker, super::Suggests::TimeMarkers);
|
||||
d.executes(marker, "time.set.marker");
|
||||
let add = d.literal(node, "add");
|
||||
let t = d.argument(add, "time", ArgType::Time { min: i32::MIN });
|
||||
d.executes(t, "time.add");
|
||||
let pause = d.literal(node, "pause");
|
||||
d.executes(pause, "time.pause");
|
||||
let resume = d.literal(node, "resume");
|
||||
d.executes(resume, "time.resume");
|
||||
let rate = d.literal(node, "rate");
|
||||
let r = d.argument(
|
||||
rate,
|
||||
"rate",
|
||||
ArgType::Float {
|
||||
min: 1.0e-5,
|
||||
max: 1000.0,
|
||||
},
|
||||
);
|
||||
d.executes(r, "time.rate");
|
||||
let query = d.literal(node, "query");
|
||||
let time = d.literal(query, "time");
|
||||
d.executes(time, "time.query.time");
|
||||
let tl = d.argument(query, "timeline", ArgType::Resource(Resource::Timeline));
|
||||
d.executes(tl, "time.query.timeline");
|
||||
let rep = d.literal(tl, "repetition");
|
||||
d.executes(rep, "time.query.repetition");
|
||||
}
|
||||
/// FillCommand.wrapWithMode.
|
||||
fn fill_modes(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "fill");
|
||||
for m in ["outline", "hollow", "destroy", "strict"] {
|
||||
let l = d.literal(node, m);
|
||||
d.executes(l, "fill");
|
||||
}
|
||||
}
|
||||
fn clone_begin(d: &mut Dispatcher, node: usize) {
|
||||
let begin = d.argument(node, "begin", ArgType::BlockPos);
|
||||
let end = d.argument(begin, "end", ArgType::BlockPos);
|
||||
clone_destination(d, end);
|
||||
let to = d.literal(end, "to");
|
||||
let dim = d.argument(to, "targetDimension", ArgType::Dimension);
|
||||
clone_destination(d, dim);
|
||||
}
|
||||
fn clone_destination(d: &mut Dispatcher, node: usize) {
|
||||
let dest = d.argument(node, "destination", ArgType::BlockPos);
|
||||
clone_mask(d, dest);
|
||||
let strict = d.literal(dest, "strict");
|
||||
clone_mask(d, strict);
|
||||
}
|
||||
fn clone_mask(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "clone");
|
||||
for m in ["replace", "masked"] {
|
||||
let l = d.literal(node, m);
|
||||
clone_mode(d, l);
|
||||
}
|
||||
let filtered = d.literal(node, "filtered");
|
||||
let filter = d.argument(filtered, "filter", ArgType::BlockPredicate);
|
||||
clone_mode(d, filter);
|
||||
}
|
||||
fn clone_mode(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "clone");
|
||||
for m in ["force", "move", "normal"] {
|
||||
let l = d.literal(node, m);
|
||||
d.executes(l, "clone");
|
||||
}
|
||||
}
|
||||
/// The shared vanilla tree.
|
||||
/// Reorder node children as vanilla registers them (Brigadier keeps
|
||||
/// children in registration order; smart usage lists them that way).
|
||||
fn apply_vanilla_order(d: &mut Dispatcher) {
|
||||
for (path, order) in super::vanilla_order::ORDER {
|
||||
let mut node = Some(0usize);
|
||||
for name in path.split(' ').filter(|n| !n.is_empty()) {
|
||||
node = node.and_then(|n| {
|
||||
d.nodes[n]
|
||||
.children
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|&c| d.nodes[c].name() == name)
|
||||
});
|
||||
}
|
||||
let Some(n) = node else { continue };
|
||||
let mut children = d.nodes[n].children.clone();
|
||||
let rank = |c: usize| {
|
||||
order
|
||||
.iter()
|
||||
.position(|o| *o == d.nodes[c].name())
|
||||
.unwrap_or(order.len())
|
||||
};
|
||||
children.sort_by_key(|&c| rank(c));
|
||||
d.nodes[n].children = children;
|
||||
}
|
||||
}
|
||||
/// The tree the game runs: a release integrated server's, or with
|
||||
/// `HORIZON_DEV_COMMANDS` set the development one
|
||||
/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands when
|
||||
/// the server turned them on (`set_horizon_commands`).
|
||||
pub fn game_dispatcher() -> &'static Dispatcher {
|
||||
game_tree(
|
||||
std::env::var_os("HORIZON_DEV_COMMANDS").is_some(),
|
||||
HORIZON_COMMANDS.load(std::sync::atomic::Ordering::Relaxed),
|
||||
)
|
||||
}
|
||||
/// Whether this process's server has Horizon's own commands (`/pregen`). Off
|
||||
/// by default, so `/help` and the command tree are vanilla's; a dedicated
|
||||
/// server turns them on with `horizon-pregen=true` in server.properties, the
|
||||
/// game with `--pregen` (docs/pregeneration.md).
|
||||
static HORIZON_COMMANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
/// Turns Horizon's own commands on or off for the trees `game_dispatcher`
|
||||
/// returns from now on.
|
||||
pub fn set_horizon_commands(on: bool) {
|
||||
HORIZON_COMMANDS.store(on, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
/// The server.properties key that turns `/pregen` on (Horizon's own; vanilla
|
||||
/// ignores keys it doesn't know).
|
||||
pub const PREGEN_PROPERTY: &str = "horizon-pregen";
|
||||
pub(crate) fn game_tree(dev: bool, horizon: bool) -> &'static Dispatcher {
|
||||
static HORIZON: [std::sync::OnceLock<Dispatcher>; 2] =
|
||||
[const { std::sync::OnceLock::new() }; 2];
|
||||
match (dev, horizon) {
|
||||
(true, false) => dispatcher(),
|
||||
(false, false) => release_dispatcher(),
|
||||
(dev, true) => HORIZON[usize::from(dev)].get_or_init(|| {
|
||||
let mut d = build_with(dev);
|
||||
horizon_commands(&mut d, 0);
|
||||
d
|
||||
}),
|
||||
}
|
||||
}
|
||||
/// Commands vanilla doesn't have, after its own: `/pregen`
|
||||
/// (docs/pregeneration.md).
|
||||
fn horizon_commands(d: &mut Dispatcher, root: usize) {
|
||||
let pregen = d.literal(root, "pregen");
|
||||
d.requires(pregen, GAMEMASTERS);
|
||||
let start = d.literal(pregen, "start");
|
||||
let radius = d.argument(
|
||||
start,
|
||||
"radius",
|
||||
ArgType::Integer {
|
||||
min: 0,
|
||||
max: 30_000_000,
|
||||
},
|
||||
);
|
||||
d.executes(radius, "pregen.start");
|
||||
for shape in ["square", "circle"] {
|
||||
let shape = d.literal(radius, shape);
|
||||
d.executes(shape, "pregen.start");
|
||||
let center = d.argument(shape, "center", ArgType::ColumnPos);
|
||||
d.executes(center, "pregen.start");
|
||||
}
|
||||
for (word, id) in [
|
||||
("pause", "pregen.pause"),
|
||||
("continue", "pregen.continue"),
|
||||
("cancel", "pregen.cancel"),
|
||||
("status", "pregen.status"),
|
||||
] {
|
||||
let w = d.literal(pregen, word);
|
||||
d.executes(w, id);
|
||||
}
|
||||
}
|
||||
pub fn dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(build)
|
||||
}
|
||||
/// The tree of a release integrated server (no development commands).
|
||||
pub fn release_dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(|| build_with(false))
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
//! The order of node children in vanilla's command tree, for the nodes
|
||||
//! where Horizon's tree registers them differently (path of node names
|
||||
//! from the root, children in vanilla's order). Generated by
|
||||
//! tools/generate_command_order.py; do not edit by hand.
|
||||
|
||||
pub const ORDER: &[(&str, &[&str])] = &[
|
||||
(
|
||||
"",
|
||||
&[
|
||||
"advancement",
|
||||
"attribute",
|
||||
"execute",
|
||||
"bossbar",
|
||||
"clear",
|
||||
"clone",
|
||||
"compute",
|
||||
"damage",
|
||||
"data",
|
||||
"datapack",
|
||||
"debug",
|
||||
"defaultgamemode",
|
||||
"dialog",
|
||||
"difficulty",
|
||||
"effect",
|
||||
"me",
|
||||
"enchant",
|
||||
"experience",
|
||||
"xp",
|
||||
"fill",
|
||||
"fillbiome",
|
||||
"forceload",
|
||||
"function",
|
||||
"gamemode",
|
||||
"gamerule",
|
||||
"give",
|
||||
"help",
|
||||
"item",
|
||||
"kick",
|
||||
"kill",
|
||||
"list",
|
||||
"locate",
|
||||
"loot",
|
||||
"msg",
|
||||
"tell",
|
||||
"w",
|
||||
"swing",
|
||||
"particle",
|
||||
"place",
|
||||
"playsound",
|
||||
"posteffect",
|
||||
"random",
|
||||
"reload",
|
||||
"recipe",
|
||||
"fetchprofile",
|
||||
"return",
|
||||
"ride",
|
||||
"rotate",
|
||||
"say",
|
||||
"schedule",
|
||||
"scoreboard",
|
||||
"seed",
|
||||
"version",
|
||||
"setblock",
|
||||
"spawnpoint",
|
||||
"setworldspawn",
|
||||
"spectate",
|
||||
"spreadplayers",
|
||||
"stopsound",
|
||||
"stopwatch",
|
||||
"summon",
|
||||
"tag",
|
||||
"team",
|
||||
"teammsg",
|
||||
"tm",
|
||||
"teleport",
|
||||
"tp",
|
||||
"tellraw",
|
||||
"test",
|
||||
"tick",
|
||||
"time",
|
||||
"title",
|
||||
"trigger",
|
||||
"waypoint",
|
||||
"weather",
|
||||
"worldborder",
|
||||
"jfr",
|
||||
"publish",
|
||||
"unpublish",
|
||||
],
|
||||
),
|
||||
(
|
||||
"execute",
|
||||
&[
|
||||
"run",
|
||||
"if",
|
||||
"unless",
|
||||
"as",
|
||||
"at",
|
||||
"store",
|
||||
"positioned",
|
||||
"rotated",
|
||||
"facing",
|
||||
"align",
|
||||
"anchored",
|
||||
"in",
|
||||
"summon",
|
||||
"on",
|
||||
],
|
||||
),
|
||||
(
|
||||
"execute if",
|
||||
&[
|
||||
"block",
|
||||
"biome",
|
||||
"loaded",
|
||||
"dimension",
|
||||
"score",
|
||||
"blocks",
|
||||
"entity",
|
||||
"predicate",
|
||||
"function",
|
||||
"stopwatch",
|
||||
"data",
|
||||
"items",
|
||||
"slots",
|
||||
],
|
||||
),
|
||||
(
|
||||
"execute unless",
|
||||
&[
|
||||
"block",
|
||||
"biome",
|
||||
"loaded",
|
||||
"dimension",
|
||||
"score",
|
||||
"blocks",
|
||||
"entity",
|
||||
"predicate",
|
||||
"function",
|
||||
"stopwatch",
|
||||
"data",
|
||||
"items",
|
||||
"slots",
|
||||
],
|
||||
),
|
||||
("execute facing", &["entity", "pos"]),
|
||||
("datapack", &["enable", "disable", "list", "create"]),
|
||||
(
|
||||
"datapack enable name",
|
||||
&["after", "before", "last", "first"],
|
||||
),
|
||||
("item", &["replace", "fill", "override", "modify"]),
|
||||
("item replace entity target slots", &["from", "with"]),
|
||||
("item fill entity target slots", &["from", "with"]),
|
||||
("item override entity target slots", &["from", "with"]),
|
||||
(
|
||||
"loot replace entity entities slot",
|
||||
&["fish", "loot", "kill", "mine", "count"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot count fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot count mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot",
|
||||
&["fish", "loot", "kill", "mine", "count"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot count fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot count mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot insert targetPos fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot insert targetPos mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot give players fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot give players mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot spawn targetPos fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot spawn targetPos mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"scoreboard players",
|
||||
&[
|
||||
"list",
|
||||
"set",
|
||||
"get",
|
||||
"add",
|
||||
"remove",
|
||||
"reset",
|
||||
"enable",
|
||||
"display",
|
||||
"operation",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -35,6 +35,23 @@ impl Mode {
|
||||
Self::Redstone => "minecraft:command_block",
|
||||
}
|
||||
}
|
||||
/// `Enum.ordinal`, which `ServerboundSetCommandBlockPacket` writes.
|
||||
pub fn ordinal(self) -> i32 {
|
||||
match self {
|
||||
Self::Sequence => 0,
|
||||
Self::Auto => 1,
|
||||
Self::Redstone => 2,
|
||||
}
|
||||
}
|
||||
/// The mode of a packet's ordinal; `handleSetCommandBlock` treats any
|
||||
/// other value as a plain command block (its `default` branch).
|
||||
pub fn from_ordinal(ordinal: i32) -> Self {
|
||||
match ordinal {
|
||||
0 => Self::Sequence,
|
||||
1 => Self::Auto,
|
||||
_ => Self::Redstone,
|
||||
}
|
||||
}
|
||||
/// `CycleButton`: the next value, wrapping round.
|
||||
pub fn next(self) -> Self {
|
||||
match self {
|
||||
|
||||
@@ -1,311 +0,0 @@
|
||||
//! Text components from commands: `ComponentArgument` reads an SNBT (or JSON)
|
||||
//! value, `ComponentSerialization` turns it into styled text.
|
||||
use crate::text::{Style, Text, named_color};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// `SnbtGrammar`, enough for components: compounds, lists, quoted and
|
||||
/// unquoted strings, numbers (with type suffixes) and booleans. Returns the
|
||||
/// value and the bytes consumed.
|
||||
pub fn parse_snbt(input: &str) -> Result<(Value, usize), String> {
|
||||
let mut p = Parser {
|
||||
s: input.as_bytes(),
|
||||
i: 0,
|
||||
};
|
||||
let v = p.value()?;
|
||||
Ok((v, p.i))
|
||||
}
|
||||
struct Parser<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
impl Parser<'_> {
|
||||
fn ws(&mut self) {
|
||||
while self.i < self.s.len() && self.s[self.i].is_ascii_whitespace() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.s.get(self.i).copied()
|
||||
}
|
||||
fn expect(&mut self, c: u8) -> Result<(), String> {
|
||||
self.ws();
|
||||
if self.peek() == Some(c) {
|
||||
self.i += 1;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("expected '{}'", c as char))
|
||||
}
|
||||
}
|
||||
fn value(&mut self) -> Result<Value, String> {
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b'{') => {
|
||||
self.i += 1;
|
||||
let mut map = Map::new();
|
||||
self.ws();
|
||||
if self.peek() == Some(b'}') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
loop {
|
||||
self.ws();
|
||||
let key = self.string()?;
|
||||
self.expect(b':')?;
|
||||
map.insert(key, self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b'}') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
_ => return Err("expected ',' or '}'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(b'[') => {
|
||||
self.i += 1;
|
||||
let mut list = Vec::new();
|
||||
self.ws();
|
||||
// Typed arrays [B;...], [I;...], [L;...].
|
||||
if matches!(
|
||||
self.s.get(self.i..self.i + 2),
|
||||
Some([b'B' | b'I' | b'L', b';'])
|
||||
) {
|
||||
self.i += 2;
|
||||
}
|
||||
self.ws();
|
||||
if self.peek() == Some(b']') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
loop {
|
||||
list.push(self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b']') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
_ => return Err("expected ',' or ']'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(b'"' | b'\'') => Ok(Value::String(self.string()?)),
|
||||
Some(_) => {
|
||||
let word = self.unquoted();
|
||||
if word.is_empty() {
|
||||
return Err("expected a value".into());
|
||||
}
|
||||
Ok(match word.as_str() {
|
||||
"true" => Value::Bool(true),
|
||||
"false" => Value::Bool(false),
|
||||
_ => {
|
||||
let digits = word
|
||||
.trim_end_matches(['b', 'B', 's', 'S', 'l', 'L', 'f', 'F', 'd', 'D']);
|
||||
match (digits.parse::<i64>(), digits.parse::<f64>()) {
|
||||
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
|
||||
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
|
||||
_ => Value::String(word),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
None => Err("expected a value".into()),
|
||||
}
|
||||
}
|
||||
fn unquoted(&mut self) -> String {
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.' | b'+') {
|
||||
self.i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&self.s[start..self.i]).into_owned()
|
||||
}
|
||||
fn string(&mut self) -> Result<String, String> {
|
||||
self.ws();
|
||||
let Some(q @ (b'"' | b'\'')) = self.peek() else {
|
||||
return Ok(self.unquoted());
|
||||
};
|
||||
self.i += 1;
|
||||
let mut out = Vec::new();
|
||||
while let Some(c) = self.peek() {
|
||||
self.i += 1;
|
||||
match c {
|
||||
b'\\' => {
|
||||
let Some(e) = self.peek() else { break };
|
||||
self.i += 1;
|
||||
out.push(match e {
|
||||
b'n' => b'\n',
|
||||
b't' => b'\t',
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
c if c == q => return Ok(String::from_utf8_lossy(&out).into_owned()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
Err("unterminated string".into())
|
||||
}
|
||||
}
|
||||
/// The style fields of a component object.
|
||||
fn object_style(o: &serde_json::Map<String, Value>) -> Style {
|
||||
let mut style = Style::default();
|
||||
if let Some(c) = o.get("color").and_then(Value::as_str) {
|
||||
style.color = named_color(c).or_else(|| {
|
||||
c.strip_prefix('#')
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
});
|
||||
}
|
||||
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
|
||||
style.bold = flag("bold");
|
||||
style.italic = flag("italic");
|
||||
style.underlined = flag("underlined");
|
||||
style.strikethrough = flag("strikethrough");
|
||||
style.obfuscated = flag("obfuscated");
|
||||
style.font = o.get("font").and_then(crate::text::font_id);
|
||||
// ClickEvent.CODEC: the actions a chat line acts on here. A component
|
||||
// from a server never opens a file.
|
||||
if let Some(e) = o.get("click_event").and_then(Value::as_object) {
|
||||
let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
style.click = match e.get("action").and_then(Value::as_str) {
|
||||
Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand),
|
||||
Some("copy_to_clipboard") => {
|
||||
text("value").map(crate::text::ClickEvent::CopyToClipboard)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
// HoverEvent.ShowText.
|
||||
if let Some(e) = o.get("hover_event").and_then(Value::as_object)
|
||||
&& e.get("action").and_then(Value::as_str) == Some("show_text")
|
||||
&& let Some(value) = e.get("value")
|
||||
{
|
||||
style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s))));
|
||||
}
|
||||
style
|
||||
}
|
||||
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
|
||||
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
|
||||
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
to_text_with(v, resolve, &mut |_| None)
|
||||
}
|
||||
/// `to_text` with a hook resolving other contents (`nbt`) from the object.
|
||||
pub fn to_text_with(
|
||||
v: &Value,
|
||||
resolve: &mut dyn FnMut(&str) -> Text,
|
||||
contents: &mut dyn FnMut(&serde_json::Map<String, Value>) -> Option<Text>,
|
||||
) -> Text {
|
||||
match v {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
Value::Number(n) => Text::literal(n.to_string()),
|
||||
Value::Bool(b) => Text::literal(b.to_string()),
|
||||
// A list is its first element with the rest as siblings.
|
||||
Value::Array(list) => {
|
||||
let Some((first, rest)) = list.split_first() else {
|
||||
return Text::empty();
|
||||
};
|
||||
let mut base = to_text_with(first, resolve, contents);
|
||||
// The siblings take the first component's own style, even when
|
||||
// its text is empty.
|
||||
let style = match first {
|
||||
Value::Object(o) => object_style(o),
|
||||
_ => base
|
||||
.spans
|
||||
.first()
|
||||
.map(|s| s.style.clone())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
for sibling in rest {
|
||||
base.push(to_text_with(sibling, resolve, contents).with_style(&style));
|
||||
}
|
||||
base
|
||||
}
|
||||
Value::Object(o) => {
|
||||
let style = object_style(o);
|
||||
let content = if let Some(t) = contents(o) {
|
||||
t
|
||||
} else if let Some(t) = o.get("text") {
|
||||
match t {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
other => Text::literal(other.to_string()),
|
||||
}
|
||||
} else if let Some(key) = o.get("translate").and_then(Value::as_str) {
|
||||
let args: Vec<Text> = o
|
||||
.get("with")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|x| to_text_with(x, resolve, contents))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let translated = Text::translate(key, &args);
|
||||
match o.get("fallback").and_then(Value::as_str) {
|
||||
Some(fallback) if translated.plain() == key => Text::translate(fallback, &args),
|
||||
_ => translated,
|
||||
}
|
||||
} else if let Some(sel) = o.get("selector").and_then(Value::as_str) {
|
||||
resolve(sel)
|
||||
} else if let Some(key) = o.get("keybind").and_then(Value::as_str) {
|
||||
crate::keybinds::display_name(key)
|
||||
} else {
|
||||
Text::empty()
|
||||
};
|
||||
let mut out = content.with_style(&style);
|
||||
for extra in o
|
||||
.get("extra")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
out.push(to_text_with(extra, resolve, contents).with_style(&style));
|
||||
}
|
||||
out
|
||||
}
|
||||
Value::Null => Text::empty(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn snbt_and_json_components() {
|
||||
let input = "{text:'Hi ',color:red,extra:[{text:\"there\",bold:1b}]} rest";
|
||||
let (v, n) = parse_snbt(input).unwrap();
|
||||
assert_eq!(&input[n..], " rest");
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
assert_eq!(t.plain(), "Hi there");
|
||||
assert_eq!(t.spans[1].style.color, named_color("red"));
|
||||
let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap();
|
||||
assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_font_is_inherited_and_kept() {
|
||||
let (v, _) =
|
||||
parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#)
|
||||
.unwrap();
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect();
|
||||
let (alt, uniform) = (
|
||||
Some("minecraft:alt".into()),
|
||||
Some("minecraft:uniform".into()),
|
||||
);
|
||||
assert_eq!(fonts, [alt.clone(), alt, uniform]);
|
||||
// Back to JSON with the field, which a re-read keeps.
|
||||
let again = to_text(&t.component(), &mut |_| Text::empty());
|
||||
let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect();
|
||||
assert_eq!(kept, fonts);
|
||||
// Not an identifier: no font.
|
||||
let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap();
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
assert_eq!(t.spans[0].style.font, None);
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,18 @@ impl Clicks {
|
||||
self.skip_next_release = true;
|
||||
}
|
||||
|
||||
/// The screen that takes the pointer over starts with its own state:
|
||||
/// `AbstractContainerScreen` holds `isQuickCrafting` and the drag it
|
||||
/// belongs to on the screen, so a screen that opens (or closes) drops
|
||||
/// them. A press whose release never arrived -- the pointer left the
|
||||
/// window -- would otherwise keep the drag running, and `press` answers
|
||||
/// `None` for every later press, so the quick move and the clicks go
|
||||
/// dead on every screen after it.
|
||||
pub fn cancel_drag(&mut self) {
|
||||
self.quick_crafting = None;
|
||||
self.skip_next_release = false;
|
||||
}
|
||||
|
||||
/// `mouseClicked` (no double click): the `slotClicked` input it sends on
|
||||
/// `target`, if any. A press holding a stack starts a quick craft drag
|
||||
/// instead. `cloning` is `keyPickItem` with infinite materials.
|
||||
@@ -301,4 +313,35 @@ mod tests {
|
||||
Some(Input::Pickup)
|
||||
);
|
||||
}
|
||||
|
||||
/// #1737: a press whose release never arrives (the pointer left the
|
||||
/// window) leaves `isQuickCrafting` set, and `press` answers `None` for
|
||||
/// every later press, so the Shift quick move and the clicks on the
|
||||
/// inventory go dead. The drag belongs to the screen that has it
|
||||
/// (`AbstractContainerScreen` holds `isQuickCrafting`), so the screen
|
||||
/// that takes the pointer over drops it and the quick move works again.
|
||||
#[test]
|
||||
fn a_lost_release_does_not_wedge_the_quick_move() {
|
||||
let mut clicks = Clicks::default();
|
||||
let slot = Target::<usize>::Slot(3);
|
||||
// Pressed with a stack carried: a quick craft drag starts, and its
|
||||
// release never arrives.
|
||||
assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None);
|
||||
assert!(clicks.quick_crafting().is_some());
|
||||
// The stuck drag swallows the next press: the Shift quick move stops
|
||||
// working and the inventory stops answering.
|
||||
assert_eq!(clicks.press(&slot, Button::Right, true, true, false), None);
|
||||
// The screen that takes the pointer over starts with its own state.
|
||||
clicks.cancel_drag();
|
||||
assert!(clicks.quick_crafting().is_none());
|
||||
// The quick move works again.
|
||||
assert_eq!(
|
||||
clicks.press(&slot, Button::Right, true, true, false),
|
||||
Some(Input::QuickMove)
|
||||
);
|
||||
assert_eq!(
|
||||
clicks.press(&slot, Button::Left, true, false, false),
|
||||
Some(Input::Pickup)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,18 @@ pub enum BlockEntity {
|
||||
Campfire(Box<Campfire>),
|
||||
/// `SkullBlockEntity` of every skull and head block.
|
||||
Skull(Skull),
|
||||
/// `TheEndGatewayBlockEntity`: its age and configured destination.
|
||||
EndGateway(EndGateway),
|
||||
/// `DaylightDetectorBlockEntity`: no data, only the ticker
|
||||
/// (`DaylightDetectorBlock.tickEntity`).
|
||||
DaylightDetector,
|
||||
}
|
||||
/// `TheEndGatewayBlockEntity`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct EndGateway {
|
||||
pub age: i64,
|
||||
pub exit_portal: Option<[i32; 3]>,
|
||||
pub exact_teleport: bool,
|
||||
}
|
||||
/// `CampfireBlockEntity`: four cooking slots, each with its
|
||||
/// `cookingProgress` and `cookingTime` (the recipe's).
|
||||
@@ -187,6 +199,9 @@ impl Skull {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SkullSkin {
|
||||
pub download: Option<(String, String)>,
|
||||
/// `ResolvableProfile.nameOrId` when the profile is `Dynamic` (a name or
|
||||
/// an id only): the key `skins::Resolver` resolves it by.
|
||||
pub dynamic: Option<crate::skins::NameOrId>,
|
||||
pub fallback: &'static str,
|
||||
}
|
||||
impl SkullSkin {
|
||||
@@ -195,10 +210,21 @@ impl SkullSkin {
|
||||
let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?);
|
||||
Some((url, location))
|
||||
});
|
||||
// A `Dynamic` profile (a name or id only) resolves through the
|
||||
// services when the skull is drawn.
|
||||
let dynamic = crate::skins::dynamic_nbt(profile);
|
||||
// DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id.
|
||||
let fallback = crate::skins::profile_uuid_nbt(profile)
|
||||
.or_else(|| {
|
||||
crate::skins::nbt_text(profile.get("name"))
|
||||
.map(|name| horizon_protocol::crypto::offline_uuid(&name))
|
||||
})
|
||||
.map_or("entity/player/slim/steve", crate::tab_list::default_skin);
|
||||
Self { download, fallback }
|
||||
Self {
|
||||
download,
|
||||
dynamic,
|
||||
fallback,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every
|
||||
@@ -363,6 +389,12 @@ impl BlockEntity {
|
||||
if is_skull(name) {
|
||||
return Some(Self::Skull(Skull::default()));
|
||||
}
|
||||
if name == "minecraft:end_gateway" {
|
||||
return Some(Self::EndGateway(EndGateway::default()));
|
||||
}
|
||||
if name == "minecraft:daylight_detector" {
|
||||
return Some(Self::DaylightDetector);
|
||||
}
|
||||
if name == "minecraft:beacon" {
|
||||
return Some(Self::Beacon(Box::new(Beacon {
|
||||
last_check_y: i32::MIN / 2,
|
||||
@@ -412,6 +444,8 @@ impl BlockEntity {
|
||||
Self::Beehive(_) => "minecraft:beehive",
|
||||
Self::CommandBlock(_) => "minecraft:command_block",
|
||||
Self::Skull(_) => "minecraft:skull",
|
||||
Self::EndGateway(_) => "minecraft:end_gateway",
|
||||
Self::DaylightDetector => "minecraft:daylight_detector",
|
||||
Self::Campfire(_) => "minecraft:campfire",
|
||||
}
|
||||
}
|
||||
@@ -429,7 +463,9 @@ impl BlockEntity {
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_)
|
||||
| Self::Skull(_) => Vec::new(),
|
||||
| Self::EndGateway(_)
|
||||
| Self::Skull(_)
|
||||
| Self::DaylightDetector => Vec::new(),
|
||||
Self::Lectern(l) => l.book.iter().cloned().collect(),
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
@@ -448,7 +484,9 @@ impl BlockEntity {
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_)
|
||||
| Self::Skull(_) => &[],
|
||||
| Self::EndGateway(_)
|
||||
| Self::Skull(_)
|
||||
| Self::DaylightDetector => &[],
|
||||
Self::Crafter(c) => &c.items,
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
@@ -471,7 +509,9 @@ impl BlockEntity {
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_)
|
||||
| Self::Skull(_) => &mut [],
|
||||
| Self::EndGateway(_)
|
||||
| Self::Skull(_)
|
||||
| Self::DaylightDetector => &mut [],
|
||||
Self::Crafter(c) => &mut c.items,
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
@@ -718,6 +758,18 @@ impl Furnace {
|
||||
.recipes_used
|
||||
.entry(recipe_used_key(&recipe.id))
|
||||
.or_insert(0) += 1;
|
||||
// AbstractFurnaceBlockEntity.burn: drying a wet sponge fills
|
||||
// the bucket in the fuel slot.
|
||||
if self.items[0]
|
||||
.as_ref()
|
||||
.is_some_and(|i| &*i.item == "minecraft:wet_sponge")
|
||||
&& self.items[1]
|
||||
.as_ref()
|
||||
.is_some_and(|f| &*f.item == "minecraft:bucket")
|
||||
{
|
||||
self.items[1] =
|
||||
Some(ItemStack::new("minecraft:water_bucket", 1));
|
||||
}
|
||||
if let Some(i) = self.items[0].as_mut() {
|
||||
i.count -= 1;
|
||||
if i.count == 0 {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! add/update with hidden effects, per-tick application of the periodic
|
||||
//! effects (regeneration, poison, wither, hunger, saturation, instant
|
||||
//! effects), and the derived flags the movement and damage code read.
|
||||
use crate::brewing;
|
||||
use horizon_client_core::potions;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct EffectInstance {
|
||||
@@ -179,13 +179,14 @@ impl PlayerEffects {
|
||||
self.list.clear();
|
||||
}
|
||||
/// The effects of a saved player (`Player.active_effects`: id,
|
||||
/// duration, amplifier, ambient, visible).
|
||||
/// duration, amplifier, ambient, particles visible).
|
||||
pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self {
|
||||
let mut effects = Self::default();
|
||||
for (id, duration, amplifier, ambient, _) in saved {
|
||||
if let Some(def) = brewing::effect(id) {
|
||||
for (id, duration, amplifier, ambient, particles) in saved {
|
||||
if let Some(def) = potions::effect(id) {
|
||||
let mut e = EffectInstance::new(def.id, *duration, *amplifier);
|
||||
e.ambient = *ambient;
|
||||
e.visible = *particles;
|
||||
effects.add(e);
|
||||
}
|
||||
}
|
||||
@@ -213,8 +214,9 @@ impl PlayerEffects {
|
||||
}
|
||||
/// `LivingEntity.tickEffects` (server part) with the omens' effect ticks:
|
||||
/// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect`
|
||||
/// (on its last tick). Returns the actions to apply, in order, and
|
||||
/// whether Raid Omen was newly added.
|
||||
/// (on its last tick); `absorption_empty` is `AbsorptionMobEffect`'s
|
||||
/// answer: the effect ends once the absorption is used up. Returns the
|
||||
/// actions to apply, in order, and whether Raid Omen was newly added.
|
||||
///
|
||||
/// Bad Omen turning into a new Raid Omen adds an entry to the map being
|
||||
/// iterated: vanilla's iterator then throws a
|
||||
@@ -224,6 +226,7 @@ impl PlayerEffects {
|
||||
pub fn tick_with(
|
||||
&mut self,
|
||||
omen: &mut dyn FnMut(&EffectInstance) -> OmenTick,
|
||||
absorption_empty: bool,
|
||||
) -> (Vec<EffectAction>, bool) {
|
||||
self.tick_count = self.tick_count.wrapping_add(1);
|
||||
let mut actions = Vec::new();
|
||||
@@ -246,6 +249,7 @@ impl PlayerEffects {
|
||||
let answer = match e.id {
|
||||
"bad_omen" => omen(e),
|
||||
"raid_omen" if t == 1 => omen(e),
|
||||
"absorption" if absorption_empty => OmenTick::Remove,
|
||||
_ => OmenTick::Continue,
|
||||
};
|
||||
match answer {
|
||||
@@ -302,10 +306,10 @@ impl PlayerEffects {
|
||||
) -> (Vec<EffectInstance>, Vec<EffectAction>) {
|
||||
let mut lasting = Vec::new();
|
||||
let mut now = Vec::new();
|
||||
if let Some(def) = potion.and_then(brewing::potion) {
|
||||
if let Some(def) = potion.and_then(potions::potion) {
|
||||
for (id, duration, amp) in def.effects {
|
||||
let id = brewing::effect(id).map_or("speed", |e| e.id);
|
||||
if brewing::effect(id).is_some_and(|e| e.instant) {
|
||||
let id = potions::effect(id).map_or("speed", |e| e.id);
|
||||
if potions::effect(id).is_some_and(|e| e.instant) {
|
||||
now.extend(instant(id, *amp, 1.0));
|
||||
} else {
|
||||
// withScaledDuration: max(floor(d * scale), 1).
|
||||
@@ -465,13 +469,13 @@ mod tests {
|
||||
};
|
||||
// The first tick adds Raid Omen and stops there (the iterator's
|
||||
// ConcurrentModificationException): Bad Omen and Speed stay as they were.
|
||||
let (_, added) = fx.tick_with(&mut convert);
|
||||
let (_, added) = fx.tick_with(&mut convert, false);
|
||||
assert!(added);
|
||||
assert_eq!(fx.get("bad_omen").unwrap().duration, 100);
|
||||
assert_eq!(fx.get("speed").unwrap().duration, 50);
|
||||
assert_eq!(fx.get("raid_omen").unwrap().duration, 600);
|
||||
// The second refreshes Raid Omen and drops Bad Omen.
|
||||
let (_, added) = fx.tick_with(&mut convert);
|
||||
let (_, added) = fx.tick_with(&mut convert, false);
|
||||
assert!(!added);
|
||||
assert!(fx.get("bad_omen").is_none());
|
||||
assert_eq!(fx.get("speed").unwrap().duration, 49);
|
||||
@@ -486,9 +490,9 @@ mod tests {
|
||||
seen.push(e.duration);
|
||||
OmenTick::Remove
|
||||
};
|
||||
fx.tick_with(&mut watch);
|
||||
fx.tick_with(&mut watch, false);
|
||||
assert!(fx.get("raid_omen").is_some());
|
||||
fx.tick_with(&mut watch);
|
||||
fx.tick_with(&mut watch, false);
|
||||
assert!(fx.get("raid_omen").is_none());
|
||||
assert_eq!(seen, vec![1]);
|
||||
}
|
||||
|
||||
@@ -545,6 +545,32 @@ impl Enchantments {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `EnchantmentHelper.forEachModifier` as an item's tooltip lists them: the
|
||||
/// `minecraft:attributes` effects of `stack`'s enchantments as rows of
|
||||
/// (attribute, id, amount, operation, slot group), one per slot group the
|
||||
/// enchantment lists.
|
||||
pub fn modifier_rows(&self, stack: &ItemStack) -> Vec<(String, String, f64, String, String)> {
|
||||
let mut rows = Vec::new();
|
||||
for (id, level) in stack.enchantments() {
|
||||
let Some(e) = self.get(id) else { continue };
|
||||
for a in e.effects["minecraft:attributes"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
for slot in &e.slots {
|
||||
rows.push((
|
||||
a["attribute"].as_str().unwrap_or("").to_owned(),
|
||||
a["id"].as_str().unwrap_or("").to_owned(),
|
||||
f64::from(level_value(&a["amount"], *level)),
|
||||
a["operation"].as_str().unwrap_or("add_value").to_owned(),
|
||||
slot.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
/// Sum of `add_value` amounts of one attribute from enchantments on `stack`.
|
||||
pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 {
|
||||
stack.map_or(0.0, |s| {
|
||||
|
||||
@@ -95,6 +95,15 @@ impl ItemEntity {
|
||||
self.health -= fire_damage as i32;
|
||||
}
|
||||
}
|
||||
// CactusBlock.entityInside: `entity.hurt(cactus, 1.0)`. An item has no
|
||||
// hurt cooldown, so it loses 1 health every tick it touches a cactus
|
||||
// (5 health: gone in 5 ticks). Fire resistance does not help;
|
||||
// `ItemStack.canBeHurtBy` only skips it for a damage_resistant stack.
|
||||
if crate::motion::environment::cactus_contact(world, registry, self.bounds())
|
||||
&& !items.resists_cactus(&self.stack)
|
||||
{
|
||||
self.health -= 1;
|
||||
}
|
||||
ItemEnvironmentTick {
|
||||
alive: self.health > 0,
|
||||
lava_hurt,
|
||||
@@ -385,8 +394,29 @@ pub struct ExperienceOrb {
|
||||
pub value: u32,
|
||||
pub age: u32,
|
||||
pub on_ground: bool,
|
||||
/// `ExperienceOrb.count`: orbs merged into this one; each pickup gives
|
||||
/// `value` once and takes one off.
|
||||
pub count: u32,
|
||||
/// `Entity.tickCount`, which paces `ExperienceOrb.scanForMerges`.
|
||||
pub ticks: u32,
|
||||
}
|
||||
impl ExperienceOrb {
|
||||
pub fn bounds(&self) -> Aabb {
|
||||
let h = 0.25;
|
||||
Aabb::new(
|
||||
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
|
||||
Vec3::new(
|
||||
self.position.x + h,
|
||||
self.position.y + 0.5,
|
||||
self.position.z + h,
|
||||
),
|
||||
)
|
||||
}
|
||||
/// `ExperienceOrb.canMerge(orb, id, value)` for an orb that is not removed:
|
||||
/// the same value and ids a multiple of 40 apart.
|
||||
pub fn can_merge(&self, id: u32, value: u32) -> bool {
|
||||
self.value == value && (self.id as i32).wrapping_sub(id as i32) % 40 == 0
|
||||
}
|
||||
/// ExperienceOrb.getExperienceValue: the largest orb size not above `value`.
|
||||
pub fn split(value: u32) -> u32 {
|
||||
[2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1]
|
||||
@@ -416,7 +446,9 @@ impl ExperienceOrb {
|
||||
facts: &BlockFacts,
|
||||
collision: &BlockCollisionRegistry<'_>,
|
||||
player: Option<[f64; 3]>,
|
||||
next_float: &mut dyn FnMut() -> f32,
|
||||
) -> bool {
|
||||
self.ticks += 1;
|
||||
self.previous = self.position;
|
||||
let block = world.block(
|
||||
self.position.x.floor() as i32,
|
||||
@@ -432,6 +464,14 @@ impl ExperienceOrb {
|
||||
} else {
|
||||
self.velocity.y -= 0.03;
|
||||
}
|
||||
if facts.get(block).fluid == Fluid::Lava {
|
||||
// ExperienceOrb.tick: lava throws the orb back out.
|
||||
self.velocity = Vec3::new(
|
||||
f64::from((next_float() - next_float()) * 0.2),
|
||||
f64::from(0.2f32),
|
||||
f64::from((next_float() - next_float()) * 0.2),
|
||||
);
|
||||
}
|
||||
if let Some(p) = player {
|
||||
let d = [
|
||||
(p[0] - self.position.x) / 8.0,
|
||||
@@ -449,15 +489,7 @@ impl ExperienceOrb {
|
||||
);
|
||||
}
|
||||
}
|
||||
let h = 0.25;
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
|
||||
Vec3::new(
|
||||
self.position.x + h,
|
||||
self.position.y + 0.5,
|
||||
self.position.z + h,
|
||||
),
|
||||
);
|
||||
let bounds = self.bounds();
|
||||
let mut scene = SceneCollisions {
|
||||
world,
|
||||
binding: collision,
|
||||
@@ -494,6 +526,31 @@ impl ExperienceOrb {
|
||||
self.age < 6000
|
||||
}
|
||||
}
|
||||
/// `ExperienceOrb.scanForMerges`, run by each orb on `tickCount % 20 == 1`:
|
||||
/// it absorbs the orbs that `canMerge` within 0.5 blocks of its box,
|
||||
/// adding their counts and keeping the smaller age.
|
||||
pub fn merge_orbs(orbs: &mut Vec<ExperienceOrb>) {
|
||||
let mut removed = vec![false; orbs.len()];
|
||||
for i in 0..orbs.len() {
|
||||
if removed[i] || orbs[i].ticks % 20 != 1 {
|
||||
continue;
|
||||
}
|
||||
let area = orbs[i].bounds().inflate(Vec3::new(0.5, 0.5, 0.5));
|
||||
for j in 0..orbs.len() {
|
||||
if j != i
|
||||
&& !removed[j]
|
||||
&& orbs[j].can_merge(orbs[i].id, orbs[i].value)
|
||||
&& orbs[j].bounds().intersects(area)
|
||||
{
|
||||
orbs[i].count += orbs[j].count;
|
||||
orbs[i].age = orbs[i].age.min(orbs[j].age);
|
||||
removed[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut removed = removed.into_iter();
|
||||
orbs.retain(|_| !removed.next().unwrap_or(false));
|
||||
}
|
||||
/// Player experience (Player.giveExperiencePoints / getXpNeededForNextLevel).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Experience {
|
||||
@@ -525,17 +582,21 @@ impl Experience {
|
||||
7 + level * 2
|
||||
}
|
||||
}
|
||||
/// Returns true when a level was gained.
|
||||
pub fn give(&mut self, points: i32) -> bool {
|
||||
let start = self.level;
|
||||
/// Returns the first multiple of 5 the player reached, where each level
|
||||
/// gained would play the level-up sound (`Player.giveExperienceLevels`).
|
||||
pub fn give(&mut self, points: i32) -> Option<i32> {
|
||||
let mut sound_level = None;
|
||||
self.progress += points as f32 / Self::needed(self.level) as f32;
|
||||
self.total = self.total.saturating_add(points).max(0);
|
||||
while self.progress >= 1.0 {
|
||||
self.progress = (self.progress - 1.0) * Self::needed(self.level) as f32;
|
||||
self.level += 1;
|
||||
if self.level % 5 == 0 {
|
||||
sound_level.get_or_insert(self.level);
|
||||
}
|
||||
self.progress /= Self::needed(self.level) as f32;
|
||||
}
|
||||
self.level > start
|
||||
sound_level
|
||||
}
|
||||
}
|
||||
/// A painting (`Painting`, a `HangingEntity`): the block it hangs in, the
|
||||
|
||||
@@ -14,7 +14,8 @@ struct Globals {
|
||||
// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
|
||||
end_portal_sprites: array<vec4<f32>, 2>,
|
||||
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
|
||||
// y: Nether cardinal lighting, z: how many dynamic_lights are set.
|
||||
// y: Nether cardinal lighting, z: how many dynamic_lights are set,
|
||||
// w: the glint scroll clock (`Glint::scroll_ticks`).
|
||||
time: vec4<f32>,
|
||||
crumbling_sprite: vec4<f32>,
|
||||
// Selection outline parameters (read by terrain.wgsl).
|
||||
@@ -27,6 +28,12 @@ struct Globals {
|
||||
@group(0) @binding(2) var atlas_sampler: sampler;
|
||||
@group(0) @binding(3) var lightmap: texture_2d<f32>;
|
||||
@group(0) @binding(4) var lightmap_sampler: sampler;
|
||||
// enchanted_glint_item on its own repeating texture (vanilla's GlintSampler).
|
||||
@group(0) @binding(5) var glint_tex: texture_2d<f32>;
|
||||
@group(0) @binding(6) var glint_sampler: sampler;
|
||||
// The armour layers' GlintSampler: vanilla samples enchanted_glint_armor with
|
||||
// the same repeating, linearly filtered sampler as the item glint.
|
||||
@group(0) @binding(7) var glint_armor_tex: texture_2d<f32>;
|
||||
struct Out {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@@ -44,6 +51,9 @@ struct Out {
|
||||
// entity.vsh's lightMapColor, multiplied in after the overlay.
|
||||
@location(9) light_color: vec4<f32>,
|
||||
@location(10) @interpolate(flat) weather_rect: vec4<f32>,
|
||||
// The `GLINT_TEXTURING` sample for overlay 7 (item foil), or the model UV
|
||||
// `ARMOR_ENTITY_GLINT_TEXTURING` scrolls for overlay 13 (armour).
|
||||
@location(11) glint_uv: vec2<f32>,
|
||||
}
|
||||
// Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed.
|
||||
fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
|
||||
@@ -103,18 +113,23 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
|
||||
out.spherical = select(length(position), 0.0, overlay >= 2u && overlay <= 4u);
|
||||
out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u && overlay <= 4u);
|
||||
out.overlay = overlay;
|
||||
out.glint_uv = vec2(0.0);
|
||||
if overlay == 4u { out.spherical = length(position); }
|
||||
return out;
|
||||
}
|
||||
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
|
||||
return entity_vertex(position, uv, overlay, color, light, normal);
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>,
|
||||
@location(5) normal: vec4<f32>, @location(6) glint_uv: vec2<f32>) -> Out {
|
||||
var out = entity_vertex(position, uv, overlay, color, light, normal);
|
||||
out.glint_uv = glint_uv;
|
||||
return out;
|
||||
}
|
||||
// Retained bolt-local geometry, translated using the same f64 camera
|
||||
// subtraction as the former CPU path before adding each local f32 position.
|
||||
// The bolt offset is instance attribute 7: 6 is the entity vertex's glint UV.
|
||||
@vertex fn vs_lightning(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>,
|
||||
@location(6) offset: vec3<f32>) -> Out {
|
||||
@location(7) offset: vec3<f32>) -> Out {
|
||||
return entity_vertex(offset + position, uv, overlay, color, light, normal);
|
||||
}
|
||||
struct CloudInfo {
|
||||
@@ -166,6 +181,27 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
if d >= end { return 1.0; }
|
||||
return (d - start) / (end - start);
|
||||
}
|
||||
// TextureTransform.setupGlintTexturing(0.16), ARMOR_ENTITY_GLINT_TEXTURING.
|
||||
// globals.time.w is (Util.getMillis() * glintSpeed * 8) modulo 330000, the
|
||||
// common period of both offsets.
|
||||
fn armor_glint_uv(model: vec2<f32>) -> vec2<f32> {
|
||||
let ticks = globals.time.w;
|
||||
let offset0 = (ticks % 110000.0) / 110000.0;
|
||||
let offset1 = (ticks % 30000.0) / 30000.0;
|
||||
let angle = 0.17453292;
|
||||
let c = cos(angle);
|
||||
let s = sin(angle);
|
||||
let scaled = model * 0.16;
|
||||
return vec2(scaled.x * c - scaled.y * s - offset0,
|
||||
scaled.x * s + scaled.y * c + offset1);
|
||||
}
|
||||
// RenderPipelines.GLINT: the source colour is scaled by itself, so `GlintAlpha`
|
||||
// is squared along with the sample.
|
||||
fn glint_over(color: vec4<f32>, glint: vec4<f32>) -> vec4<f32> {
|
||||
let alpha = globals.fog_ends.w;
|
||||
let g = alpha * glint;
|
||||
return vec4(color.rgb + g.rgb * g.rgb, max(color.a, alpha));
|
||||
}
|
||||
// CRUMBLING_UV_BEGIN
|
||||
fn crumbling_uv(uv: vec2<f32>, packed_origin: vec2<f32>, sprite_size: vec2<f32>, dimensions: vec2<u32>) -> vec2<f32> {
|
||||
let size = vec2<f32>(dimensions);
|
||||
@@ -203,25 +239,60 @@ fn crumbling_uv(uv: vec2<f32>, packed_origin: vec2<f32>, sprite_size: vec2<f32>,
|
||||
// lit texture, then the lightmap, then the glint and fog.
|
||||
color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a);
|
||||
color *= in.light_color;
|
||||
if in.overlay == 7u || in.overlay == 8u {
|
||||
// Enchantment glint (overlay 7, 8 with the hurt tint): the purple
|
||||
// enchanted_glint sheen drifting diagonally over the item's shape.
|
||||
let px = in.uv * vec2<f32>(textureDimensions(atlas));
|
||||
let t = globals.misc.y * 0.05;
|
||||
let band = sin((px.x + px.y) * 0.9 - t * 6.0) * 0.5 + 0.5;
|
||||
let band2 = sin((px.x - px.y) * 0.6 + t * 4.0) * 0.5 + 0.5;
|
||||
let shimmer = pow(band * 0.6 + band2 * 0.4, 2.0);
|
||||
let glint = vec3(0.50, 0.25, 0.80) * (0.25 + 0.75 * shimmer);
|
||||
color = vec4(min(color.rgb + glint * 0.6, vec3(1.0)), color.a);
|
||||
if in.overlay == 7u || in.overlay == 8u || in.overlay == 33u {
|
||||
// 33: a translucent item with the glint.
|
||||
// Enchantment glint: item.fsh's GLINT path, sampled from
|
||||
// enchanted_glint_item at the `GLINT_TEXTURING` UV.
|
||||
color = glint_over(color, textureSample(glint_tex, glint_sampler, in.glint_uv));
|
||||
} else if in.overlay == 13u {
|
||||
// Enchanted armour: enchanted_glint_armor at the scrolling model UV.
|
||||
color = glint_over(
|
||||
color,
|
||||
textureSample(glint_armor_tex, glint_sampler, armor_glint_uv(in.glint_uv)),
|
||||
);
|
||||
}
|
||||
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
|
||||
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
|
||||
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
|
||||
}
|
||||
|
||||
// rendertype_outline.fsh: the vertex colour (the team colour; outline vertices carry no
|
||||
// normal, so no cardinal light) wherever the texture is not fully clear.
|
||||
@fragment fn fs_outline(in: Out) -> @location(0) vec4<f32> {
|
||||
if textureSample(atlas, atlas_sampler, in.uv).a == 0.0 { discard; }
|
||||
return vec4(in.color.rgb, 1.0);
|
||||
}
|
||||
|
||||
fn celestial_color(in: Out) -> vec4<f32> {
|
||||
return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
|
||||
}
|
||||
@fragment fn fs_celestial(in: Out) -> @location(0) vec4<f32> {
|
||||
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
|
||||
return color;
|
||||
return celestial_color(in);
|
||||
}
|
||||
|
||||
// The sky's celestial pass (sun, moon, the End sky): fs_celestial's light,
|
||||
// premultiplied for an additive (one, one) blend, and as alpha how much of it
|
||||
// the texel adds, which the blend takes off the frame's alpha. HDR output
|
||||
// (hdr.wgsl) lifts only where that left it low: the sun's and moon's discs, not
|
||||
// the dark rest of their quads or the dim End sky.
|
||||
@fragment fn fs_sky_celestial(in: Out) -> @location(0) vec4<f32> {
|
||||
let color = celestial_color(in);
|
||||
let added = color.rgb * color.a;
|
||||
return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b))));
|
||||
}
|
||||
|
||||
// RenderPipelines.ENERGY_SWIRL (entity.fsh with EMISSIVE and NO_OVERLAY): the sprite, scrolled by
|
||||
// the UV and repeated within itself, times the layer colour 0xFF808080, unlit; the pipeline adds
|
||||
// it to the frame. The light bytes carry the sprite's origin and the colour bytes its size, both
|
||||
// as breaking::stage_light packs them.
|
||||
@fragment fn fs_energy_swirl(in: Out) -> @location(0) vec4<f32> {
|
||||
let bytes = round(in.color * 255.0);
|
||||
let size = vec2(bytes.x + bytes.y * 256.0, bytes.z + bytes.w * 256.0) / 65535.0;
|
||||
let color = textureSample(atlas, atlas_sampler, crumbling_uv(in.uv, in.wrap, size, textureDimensions(atlas)));
|
||||
if color.a < 0.1 { discard; }
|
||||
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
|
||||
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
|
||||
return vec4(mix(color.rgb * (128.0 / 255.0), globals.fog_color.rgb, f * globals.fog_color.a), color.a);
|
||||
}
|
||||
|
||||
// RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off).
|
||||
|
||||
@@ -186,6 +186,8 @@ mod tests {
|
||||
color: u32::MAX,
|
||||
light: 0,
|
||||
normal: [0; 4],
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
};
|
||||
let prior = vertex([0.0; 3]);
|
||||
let body = [vertex([8.0, -1.0, -1.0]), vertex([10.0, 1.0, 1.0])];
|
||||
|
||||
@@ -180,7 +180,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
("Silent", m.silent),
|
||||
("NoGravity", m.no_gravity),
|
||||
("Glowing", m.glowing),
|
||||
("Invulnerable", m.invulnerable_flag),
|
||||
] {
|
||||
if on {
|
||||
map.insert(key.into(), Tag::Byte(1));
|
||||
@@ -188,6 +187,51 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.remove(&horizon_world::nbt::JavaString::from(key));
|
||||
}
|
||||
}
|
||||
// LivingEntity.addAdditionalSaveData: `active_effects` only when there are
|
||||
// any (MobEffectInstance.CODEC; a mob's effects are never ambient, and one
|
||||
// given with `hideParticles` shows neither particles nor its icon).
|
||||
if m.extra.effects.is_empty() {
|
||||
map.remove(&horizon_world::nbt::JavaString::from("active_effects"));
|
||||
} else {
|
||||
let effects = m
|
||||
.extra
|
||||
.effects
|
||||
.iter()
|
||||
.map(|&(effect, duration, amplifier)| {
|
||||
let shown = !m.extra.hidden_effects.contains(&effect);
|
||||
let mut e = vec![
|
||||
("id", string(crate::brewing::namespaced(effect))),
|
||||
("amplifier", Tag::Byte(amplifier.clamp(0, 255) as u8 as i8)),
|
||||
("duration", Tag::Int(duration)),
|
||||
];
|
||||
if !shown {
|
||||
e.push(("show_particles", Tag::Byte(0)));
|
||||
}
|
||||
e.push(("show_icon", Tag::Byte(i8::from(shown))));
|
||||
Tag::compound(e)
|
||||
});
|
||||
map.insert("active_effects".into(), Tag::List(effects.collect()));
|
||||
}
|
||||
map.insert(
|
||||
"Invulnerable".into(),
|
||||
Tag::Byte(i8::from(m.invulnerable_flag)),
|
||||
);
|
||||
map.insert(
|
||||
"LeftHanded".into(),
|
||||
Tag::Byte(i8::from(m.extra.left_handed)),
|
||||
);
|
||||
// Keys of older formats that structure templates still carry.
|
||||
for key in [
|
||||
"HandItems",
|
||||
"ArmorItems",
|
||||
"HandDropChances",
|
||||
"ArmorDropChances",
|
||||
"Dimension",
|
||||
"HurtByTimestamp",
|
||||
"Leashed",
|
||||
] {
|
||||
map.remove(&horizon_world::nbt::JavaString::from(key));
|
||||
}
|
||||
if m.ticks_frozen > 0 {
|
||||
map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen));
|
||||
} else {
|
||||
@@ -197,7 +241,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))),
|
||||
("LeftHanded", Tag::Byte(0)),
|
||||
("current_impulse_context_reset_grace_time", Tag::Int(0)),
|
||||
(
|
||||
"Brain",
|
||||
Tag::compound([("memories", Tag::Compound(Compound::new()))]),
|
||||
@@ -209,7 +253,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
// Only breedable animals have an age; a loaded creature that was saved without
|
||||
// one (a frog) stays without.
|
||||
let aged = raw.is_none_or(|r| r.get("Age").is_some());
|
||||
if m.kind.category == "creature" && aged {
|
||||
if (m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin) && aged {
|
||||
map.insert("Age".into(), Tag::Int(m.extra.age));
|
||||
map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked)));
|
||||
map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age));
|
||||
@@ -225,7 +269,51 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
if is_animal(id) {
|
||||
map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0)));
|
||||
}
|
||||
let species = m.species();
|
||||
if let Some((_, variant)) =
|
||||
crate::mobs::finalize::species_variant_component(species, m.extra.variant)
|
||||
{
|
||||
map.insert("variant".into(), string(&variant));
|
||||
}
|
||||
if species == crate::mobs::Species::Chicken {
|
||||
map.insert("EggLayTime".into(), Tag::Int(m.extra.egg_time));
|
||||
}
|
||||
let sounds = crate::mobs::finalize::sound_variants(species);
|
||||
if !sounds.is_empty() {
|
||||
let sound = m.extra.sound_variant.and_then(|i| sounds.get(i as usize));
|
||||
let sound = sound.copied().unwrap_or("classic");
|
||||
map.insert(
|
||||
"sound_variant".into(),
|
||||
string(&format!("minecraft:{sound}")),
|
||||
);
|
||||
}
|
||||
match id {
|
||||
// Fox.addAdditionalSaveData; Horizon models only the type.
|
||||
"minecraft:fox" => {
|
||||
let kind = if m.extra.variant == 1 { "snow" } else { "red" };
|
||||
map.insert("Type".into(), string(kind));
|
||||
for (key, value) in [
|
||||
("Trusted", Tag::List(Vec::new())),
|
||||
("Sleeping", Tag::Byte(0)),
|
||||
("Sitting", Tag::Byte(0)),
|
||||
("Crouching", Tag::Byte(0)),
|
||||
] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
"minecraft:rabbit" => {
|
||||
map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant)));
|
||||
map.entry("MoreCarrotTicks".into()).or_insert(Tag::Int(0));
|
||||
}
|
||||
"minecraft:goat" => {
|
||||
map.insert(
|
||||
"IsScreamingGoat".into(),
|
||||
Tag::Byte(i8::from(m.extra.screaming)),
|
||||
);
|
||||
let [left, right] = m.extra.lost_horns;
|
||||
map.insert("HasLeftHorn".into(), Tag::Byte(i8::from(!left)));
|
||||
map.insert("HasRightHorn".into(), Tag::Byte(i8::from(!right)));
|
||||
}
|
||||
"minecraft:creeper" => {
|
||||
for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
@@ -241,10 +329,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting)));
|
||||
map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8));
|
||||
let variant = crate::mobs::tame::CAT_VARIANTS[(m.extra.variant as usize).min(10)];
|
||||
map.insert("variant".into(), string(&format!("minecraft:{variant}")));
|
||||
map.entry("sound_variant".into())
|
||||
.or_insert_with(|| string("minecraft:classic"));
|
||||
}
|
||||
"minecraft:wolf" => {
|
||||
if let Some(owner) = m.extra.owner {
|
||||
@@ -254,17 +338,30 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting)));
|
||||
map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8));
|
||||
let variant = crate::mobs::tame::WOLF_VARIANTS[(m.extra.variant as usize).min(8)].0;
|
||||
map.insert("variant".into(), string(&format!("minecraft:{variant}")));
|
||||
map.entry("sound_variant".into())
|
||||
.or_insert_with(|| string("minecraft:classic"));
|
||||
}
|
||||
"minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => {
|
||||
// Only Piglin.addAdditionalSaveData writes CannotHunt.
|
||||
if id == "minecraft:piglin_brute" {
|
||||
map.remove(&"CannotHunt".into());
|
||||
}
|
||||
map.insert(
|
||||
"IsImmuneToZombification".into(),
|
||||
Tag::Byte(i8::from(m.extra.flag2)),
|
||||
);
|
||||
map.insert("TimeInOverworld".into(), Tag::Int(m.extra.counter2));
|
||||
if id == "minecraft:piglin" {
|
||||
// InventoryCarrier.writeInventoryToTag.
|
||||
map.insert(
|
||||
"Inventory".into(),
|
||||
Tag::List(
|
||||
m.extra
|
||||
.inventory
|
||||
.iter()
|
||||
.map(crate::save::item_to_nbt)
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
"minecraft:horse"
|
||||
| "minecraft:donkey"
|
||||
@@ -275,6 +372,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
| "minecraft:trader_llama" => {
|
||||
map.insert("Tame".into(), Tag::Byte(i8::from(m.extra.tame)));
|
||||
map.insert("Temper".into(), Tag::Int(i32::from(m.extra.variant3)));
|
||||
// AbstractHorse.addAdditionalSaveData; Horizon models neither.
|
||||
for key in ["EatingHaystack", "Bred"] {
|
||||
map.entry(key.into()).or_insert(Tag::Byte(0));
|
||||
}
|
||||
if let Some(owner) = m.extra.owner {
|
||||
map.insert("Owner".into(), Tag::IntArray(owner.to_vec()));
|
||||
}
|
||||
@@ -357,6 +458,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
"minecraft:bat" => {
|
||||
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
|
||||
}
|
||||
"minecraft:turtle" => {
|
||||
map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag)));
|
||||
if let Some(home) = m.extra.home {
|
||||
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
|
||||
}
|
||||
}
|
||||
"minecraft:creaking" => {
|
||||
// home_pos: the heart it is bound to.
|
||||
if let Some(home) = m.extra.home {
|
||||
@@ -384,7 +491,32 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
crate::mobs::villager::write_nbt(m, map);
|
||||
}
|
||||
"minecraft:wandering_trader" => put_offers(map, m),
|
||||
"minecraft:axolotl" => write_axolotl_memories(m, map),
|
||||
"minecraft:axolotl" => {
|
||||
write_axolotl_memories(m, map);
|
||||
map.insert(
|
||||
"Variant".into(),
|
||||
Tag::Int(i32::from(m.extra.variant.min(4))),
|
||||
);
|
||||
}
|
||||
"minecraft:parrot" => {
|
||||
map.insert(
|
||||
"Variant".into(),
|
||||
Tag::Int(i32::from(m.extra.variant.min(4))),
|
||||
);
|
||||
}
|
||||
"minecraft:salmon" => {
|
||||
let size = SALMON_SIZES[usize::from(m.extra.variant).min(2)];
|
||||
map.insert("type".into(), string(size));
|
||||
}
|
||||
// TropicalFish.addAdditionalSaveData: the packed variant.
|
||||
"minecraft:tropical_fish" => {
|
||||
let pattern = m.extra.variant.min(11);
|
||||
let packed = i32::from(pattern >= 6)
|
||||
| i32::from(pattern % 6) << 8
|
||||
| i32::from(m.extra.variant2 & 15) << 16
|
||||
| i32::from(m.extra.variant3 & 15) << 24;
|
||||
map.insert("Variant".into(), Tag::Int(packed));
|
||||
}
|
||||
"minecraft:allay" => {
|
||||
// InventoryCarrier: the fetched stack; the liked player memory.
|
||||
let mut inv = Vec::new();
|
||||
@@ -445,6 +577,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.insert("anger".into(), Tag::compound(Vec::<(&str, Tag)>::new()));
|
||||
}
|
||||
}
|
||||
// Armadillo.addAdditionalSaveData: the time left to the next scute.
|
||||
"minecraft:armadillo" => {
|
||||
map.insert("scute_time".into(), Tag::Int(m.extra.egg_time));
|
||||
}
|
||||
"minecraft:ravager" => {
|
||||
map.insert("AttackTick".into(), Tag::Int(m.extra.counter));
|
||||
map.insert("StunTick".into(), Tag::Int(m.extra.counter2));
|
||||
@@ -479,10 +615,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
)])
|
||||
});
|
||||
}
|
||||
"minecraft:zombie" => {
|
||||
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
|
||||
"minecraft:zombie" | "minecraft:husk" | "minecraft:drowned" => {
|
||||
for (key, value) in [
|
||||
("CanBreakDoors", Tag::Byte(0)),
|
||||
("DrownedConversionTime", Tag::Int(-1)),
|
||||
("InWaterTime", Tag::Int(-1)),
|
||||
] {
|
||||
@@ -507,6 +641,28 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Zombie.addAdditionalSaveData: CanBreakDoors.
|
||||
if crate::mobs::doors::is_zombie(m.species()) {
|
||||
map.insert(
|
||||
"CanBreakDoors".into(),
|
||||
Tag::Byte(i8::from(m.extra.can_break_doors)),
|
||||
);
|
||||
}
|
||||
if matches!(
|
||||
id,
|
||||
"minecraft:zombie"
|
||||
| "minecraft:husk"
|
||||
| "minecraft:drowned"
|
||||
| "minecraft:zombie_villager"
|
||||
| "minecraft:zombified_piglin"
|
||||
| "minecraft:piglin"
|
||||
| "minecraft:zoglin"
|
||||
) {
|
||||
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
|
||||
}
|
||||
if let Some(a) = m.extra.attributes.as_deref() {
|
||||
put_attributes(map, m, a);
|
||||
}
|
||||
crate::mobs::raider::write_nbt(m, map);
|
||||
crate::mobs::riders::write_nbt(m, map);
|
||||
// LivingEntity equipment: what the mob holds now.
|
||||
@@ -589,6 +745,89 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
tag
|
||||
}
|
||||
/// `AttributeMap.pack` for the attributes with a base or permanent modifier
|
||||
/// finalizeSpawn set, over the saved list.
|
||||
fn put_attributes(map: &mut Compound, m: &Mob, a: &crate::mobs::finalize::Attributes) {
|
||||
use crate::mobs::finalize::{self, Attr, Op};
|
||||
let mut list = match map.get(&"attributes".into()) {
|
||||
Some(Tag::List(l)) => l.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for attr in Attr::ALL {
|
||||
let modifiers: Vec<Tag> = a
|
||||
.modifiers
|
||||
.iter()
|
||||
.filter(|x| x.attr == attr)
|
||||
.map(|x| {
|
||||
let op = match x.op {
|
||||
Op::AddValue => "add_value",
|
||||
Op::AddMultipliedBase => "add_multiplied_base",
|
||||
Op::AddMultipliedTotal => "add_multiplied_total",
|
||||
};
|
||||
Tag::compound([
|
||||
("id", string(x.id)),
|
||||
("amount", Tag::Double(x.amount.to_bits())),
|
||||
("operation", string(op)),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
if modifiers.is_empty() && !a.bases.iter().any(|(b, _)| *b == attr) {
|
||||
continue;
|
||||
}
|
||||
let id = format!("minecraft:{}", attr.name());
|
||||
let mut entry = vec![
|
||||
("id", string(&id)),
|
||||
("base", Tag::Double(finalize::base_value(m, attr).to_bits())),
|
||||
];
|
||||
if !modifiers.is_empty() {
|
||||
entry.push(("modifiers", Tag::List(modifiers)));
|
||||
}
|
||||
let entry = Tag::compound(entry);
|
||||
match list
|
||||
.iter_mut()
|
||||
.find(|t| text(t.get("id")).as_deref() == Some(id.as_str()))
|
||||
{
|
||||
Some(t) => *t = entry,
|
||||
None => list.push(entry),
|
||||
}
|
||||
}
|
||||
map.insert("attributes".into(), Tag::List(list));
|
||||
}
|
||||
/// `Brain.Packed`: the memories finalizeSpawn set, over the saved ones.
|
||||
pub fn put_brain(map: &mut Compound, m: &Mob, dimension: &str) {
|
||||
if m.extra.memories.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut memories = match map.get(&"Brain".into()).and_then(|b| b.get("memories")) {
|
||||
Some(Tag::Compound(c)) => c.clone(),
|
||||
_ => Compound::new(),
|
||||
};
|
||||
for &(name, value, ttl) in &m.extra.memories {
|
||||
let value = match name {
|
||||
"hunted_recently" => Tag::Byte(value as i8),
|
||||
"home" => match m.extra.home {
|
||||
Some(p) => Tag::compound([
|
||||
("dimension", string(dimension)),
|
||||
("pos", Tag::IntArray(p.to_vec())),
|
||||
]),
|
||||
None => continue,
|
||||
},
|
||||
_ => Tag::Int(value as i32),
|
||||
};
|
||||
let mut memory = vec![("value", value)];
|
||||
if ttl != i64::MAX {
|
||||
memory.push(("ttl", Tag::Long(ttl)));
|
||||
}
|
||||
memories.insert(
|
||||
format!("minecraft:{name}").as_str().into(),
|
||||
Tag::compound(memory),
|
||||
);
|
||||
}
|
||||
map.insert(
|
||||
"Brain".into(),
|
||||
Tag::compound([("memories", Tag::Compound(memories))]),
|
||||
);
|
||||
}
|
||||
/// `CustomName`: a text component saved as a string or a `{text: ..}` compound.
|
||||
fn custom_name(tag: &Tag) -> Option<String> {
|
||||
match tag.get("CustomName")? {
|
||||
@@ -608,6 +847,22 @@ pub fn name_text(tag: &Tag) -> Text {
|
||||
t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
|
||||
}
|
||||
}
|
||||
/// Mob.finalizeSpawn's follow range bonus in the saved attributes.
|
||||
pub(crate) fn spawn_bonus(tag: &Tag) -> Option<f64> {
|
||||
let Some(Tag::List(attrs)) = tag.get("attributes") else {
|
||||
return None;
|
||||
};
|
||||
let range = attrs
|
||||
.iter()
|
||||
.find(|a| text(a.get("id")).as_deref() == Some("minecraft:follow_range"))?;
|
||||
let Some(Tag::List(modifiers)) = range.get("modifiers") else {
|
||||
return None;
|
||||
};
|
||||
let bonus = modifiers
|
||||
.iter()
|
||||
.find(|x| text(x.get("id")).as_deref() == Some("minecraft:random_spawn_bonus"))?;
|
||||
float(bonus.get("amount"))
|
||||
}
|
||||
pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -> Option<Mob> {
|
||||
let kind = types.get(&self::kind(tag)?)?.clone();
|
||||
let position = position(tag)?;
|
||||
@@ -633,7 +888,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(bonus) = spawn_bonus(tag) {
|
||||
use crate::mobs::finalize::{Attr, Op, add_modifier};
|
||||
let id = "minecraft:random_spawn_bonus";
|
||||
add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase);
|
||||
}
|
||||
m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32);
|
||||
// LivingEntity.setHealth clamps to the max health: a horse or llama is made
|
||||
// with the type's and saved before it drops to the one it rolled. (Only
|
||||
// the base is read here, so the clamp would cut a leader zombie's bonus.)
|
||||
if crate::mobs::equine::is_equine(m.species()) {
|
||||
m.health = m.health.min(m.attrs.max_health);
|
||||
}
|
||||
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
|
||||
// What it holds (equipment.mainhand / offhand), when saved.
|
||||
if let Some(eq) = tag.get("equipment") {
|
||||
@@ -674,7 +940,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
|
||||
m.custom_name = custom_name(tag);
|
||||
m.custom_name_text = tag.get("CustomName").map(name_text);
|
||||
if m.kind.category == "creature" {
|
||||
m.extra.left_handed = flag(tag, "LeftHanded");
|
||||
if m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin {
|
||||
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
|
||||
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
|
||||
m.extra.age_locked = flag(tag, "AgeLocked");
|
||||
@@ -687,6 +954,25 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.no_gravity = flag(tag, "NoGravity");
|
||||
m.glowing = flag(tag, "Glowing");
|
||||
m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32;
|
||||
// LivingEntity.readAdditionalSaveData: the saved `active_effects`, the last
|
||||
// entry of an effect winning.
|
||||
if let Some(Tag::List(effects)) = tag.get("active_effects") {
|
||||
for e in effects {
|
||||
let Some(def) = text(e.get("id")).and_then(|id| crate::brewing::effect(&id)) else {
|
||||
continue;
|
||||
};
|
||||
let effect = crate::brewing::namespaced(def.id);
|
||||
let duration = number(e.get("duration")).unwrap_or(0) as i32;
|
||||
let amplifier = number(e.get("amplifier")).unwrap_or(0) as i32;
|
||||
m.extra.effects.retain(|x| x.0 != effect);
|
||||
m.extra.effects.push((effect, duration, amplifier));
|
||||
// Details.CODEC: `show_particles` defaults to true.
|
||||
m.extra.hidden_effects.retain(|h| *h != effect);
|
||||
if number(e.get("show_particles")) == Some(0) {
|
||||
m.extra.hidden_effects.push(effect);
|
||||
}
|
||||
}
|
||||
}
|
||||
m.silent = flag(tag, "Silent");
|
||||
m.invulnerable_flag = flag(tag, "Invulnerable");
|
||||
if m.species() == crate::mobs::Species::Bat {
|
||||
@@ -706,6 +992,16 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
) {
|
||||
m.extra.flag2 = flag(tag, "IsImmuneToZombification");
|
||||
m.extra.counter2 = number(tag.get("TimeInOverworld")).unwrap_or(0) as i32;
|
||||
if m.species() == crate::mobs::Species::Piglin
|
||||
&& let Some(Tag::List(items)) = tag.get("Inventory")
|
||||
{
|
||||
// InventoryCarrier.readInventoryFromTag (eight slots).
|
||||
m.extra.inventory = items
|
||||
.iter()
|
||||
.filter_map(crate::save::item_from_nbt)
|
||||
.take(8)
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
m.species(),
|
||||
@@ -758,20 +1054,45 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.vector[0] = 0.7;
|
||||
}
|
||||
}
|
||||
if crate::mobs::finalize::species_variant_component(m.species(), 0).is_some()
|
||||
&& let Some(v) = text(tag.get("variant"))
|
||||
{
|
||||
m.extra.variant = crate::mobs::finalize::variant_index(m.species(), &v);
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Chicken
|
||||
&& let Some(t) = number(tag.get("EggLayTime"))
|
||||
{
|
||||
m.extra.egg_time = t as i32;
|
||||
}
|
||||
if let Some(v) = text(tag.get("sound_variant")) {
|
||||
let v = v.trim_start_matches("minecraft:");
|
||||
let sounds = crate::mobs::finalize::sound_variants(m.species());
|
||||
m.extra.sound_variant = sounds.iter().position(|n| *n == v).map(|i| i as u8);
|
||||
}
|
||||
match m.species() {
|
||||
crate::mobs::Species::Fox => {
|
||||
m.extra.variant = u8::from(text(tag.get("Type")).as_deref() == Some("snow"));
|
||||
}
|
||||
crate::mobs::Species::Rabbit => {
|
||||
// Rabbit.Variant.byId: an unknown id is brown.
|
||||
m.extra.variant = match number(tag.get("RabbitType")).unwrap_or(0) {
|
||||
v @ (0..=5 | 99) => v as u8,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
crate::mobs::Species::Goat => {
|
||||
m.extra.screaming = flag(tag, "IsScreamingGoat");
|
||||
let horn = |key| number(tag.get(key)).is_some_and(|v| v == 0);
|
||||
m.extra.lost_horns = [horn("HasLeftHorn"), horn("HasRightHorn")];
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Cat {
|
||||
m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner"));
|
||||
m.extra.tame = m.extra.owner.is_some();
|
||||
m.extra.sitting = flag(tag, "Sitting");
|
||||
m.extra.color =
|
||||
number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15);
|
||||
if let Some(Tag::String(v)) = tag.get("variant") {
|
||||
let v = v.to_string().unwrap_or_default();
|
||||
let v = v.trim_start_matches("minecraft:");
|
||||
m.extra.variant = crate::mobs::tame::CAT_VARIANTS
|
||||
.iter()
|
||||
.position(|n| *n == v)
|
||||
.unwrap_or(0) as u8;
|
||||
}
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Wolf {
|
||||
let health = m.health;
|
||||
@@ -782,14 +1103,6 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.sitting = flag(tag, "Sitting");
|
||||
m.extra.color =
|
||||
number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15);
|
||||
if let Some(Tag::String(v)) = tag.get("variant") {
|
||||
let v = v.to_string().unwrap_or_default();
|
||||
let v = v.trim_start_matches("minecraft:");
|
||||
m.extra.variant = crate::mobs::tame::WOLF_VARIANTS
|
||||
.iter()
|
||||
.position(|(n, _)| *n == v)
|
||||
.unwrap_or(0) as u8;
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
m.species(),
|
||||
@@ -808,6 +1121,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
if m.species() == crate::mobs::Species::Axolotl {
|
||||
restore_axolotl_memories(&mut m, tag);
|
||||
}
|
||||
read_variant(&mut m, tag);
|
||||
m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
|
||||
m.air = number(tag.get("Air")).unwrap_or(300) as i32;
|
||||
if m.species() == crate::mobs::Species::Allay {
|
||||
@@ -847,6 +1161,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
{
|
||||
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Turtle {
|
||||
// Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`.
|
||||
m.extra.flag = flag(tag, "has_egg");
|
||||
m.extra.home = Some(match tag.get("home_pos") {
|
||||
Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]],
|
||||
_ => [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
],
|
||||
});
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Wither {
|
||||
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
|
||||
}
|
||||
@@ -876,6 +1202,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
st.vibration = crate::sculk::Data::from_nbt(listener);
|
||||
}
|
||||
}
|
||||
// Armadillo.readAdditionalSaveData: keeps the constructor's time when absent.
|
||||
if m.species() == crate::mobs::Species::Armadillo
|
||||
&& let Some(t) = number(tag.get("scute_time"))
|
||||
{
|
||||
m.extra.egg_time = t as i32;
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Ravager {
|
||||
m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32;
|
||||
m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32;
|
||||
@@ -925,6 +1257,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") {
|
||||
crate::mobs::finalize::set_baby(&mut m, true);
|
||||
}
|
||||
// Zombie.readAdditionalSaveData: setCanBreakDoors.
|
||||
if crate::mobs::doors::is_zombie(m.species()) {
|
||||
crate::mobs::doors::set_can_break_doors(&mut m, flag(tag, "CanBreakDoors"));
|
||||
}
|
||||
crate::mobs::raider::read_nbt(&mut m, tag);
|
||||
crate::mobs::riders::read_nbt(&mut m, tag);
|
||||
// A mob saved mid-death finishes dying; one saved dead is dropped.
|
||||
@@ -1043,18 +1379,18 @@ pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
|
||||
("Health", Tag::Short(5)),
|
||||
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
|
||||
("Value", Tag::Short(o.value.min(i16::MAX as u32) as i16)),
|
||||
("Count", Tag::Int(1)),
|
||||
("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
tag
|
||||
}
|
||||
/// One Horizon orb per counted orb (vanilla merges orbs of equal value).
|
||||
/// One orb with its merged `Count`.
|
||||
pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
|
||||
let Some(position) = position(tag) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
|
||||
let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32;
|
||||
let orb = ExperienceOrb {
|
||||
id: 0,
|
||||
position,
|
||||
@@ -1063,8 +1399,10 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
|
||||
value: number(tag.get("Value")).unwrap_or(1).max(1) as u32,
|
||||
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
|
||||
on_ground: flag(tag, "OnGround"),
|
||||
count,
|
||||
ticks: 0,
|
||||
};
|
||||
vec![orb; count]
|
||||
vec![orb]
|
||||
}
|
||||
|
||||
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
|
||||
@@ -1913,7 +2251,7 @@ mod tests {
|
||||
assert_eq!(number(tag.get("Health")), Some(5));
|
||||
}
|
||||
#[test]
|
||||
fn orbs_expand_their_count() {
|
||||
fn orbs_keep_their_count() {
|
||||
let o = ExperienceOrb {
|
||||
id: 0,
|
||||
position: Vec3::new(1.0, 2.0, 3.0),
|
||||
@@ -1922,12 +2260,14 @@ mod tests {
|
||||
value: 7,
|
||||
age: 3,
|
||||
on_ground: false,
|
||||
count: 3,
|
||||
ticks: 0,
|
||||
};
|
||||
let mut tag = orb_to_nbt(&o, [0; 4]);
|
||||
put(&mut tag, "Count", Tag::Int(3));
|
||||
let tag = orb_to_nbt(&o, [0; 4]);
|
||||
let back = orbs_from_nbt(&tag);
|
||||
assert_eq!(back.len(), 3);
|
||||
assert_eq!(back.len(), 1);
|
||||
assert_eq!(back[0].value, 7);
|
||||
assert_eq!(back[0].count, 3);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1969,6 +2309,41 @@ fn write_axolotl_memories(m: &Mob, map: &mut Compound) {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The variant tags `Axolotl`, `Rabbit`, `Parrot`, `Salmon` and
|
||||
/// `TropicalFish` read; a missing tag is the default variant (a medium
|
||||
/// salmon, otherwise index 0).
|
||||
fn read_variant(m: &mut Mob, tag: &Tag) {
|
||||
use crate::mobs::Species as S;
|
||||
let int = |key| number(tag.get(key)).unwrap_or(0) as i32;
|
||||
match m.species() {
|
||||
S::Axolotl | S::Parrot => m.extra.variant = int("Variant").clamp(0, 4) as u8,
|
||||
// Rabbit.Variant.LEGACY_CODEC: an unknown id is brown.
|
||||
S::Rabbit => {
|
||||
m.extra.variant = match int("RabbitType") {
|
||||
v @ (0..=5 | 99) => v as u8,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
S::Salmon => {
|
||||
m.extra.variant = text(tag.get("type"))
|
||||
.and_then(|t| SALMON_SIZES.iter().position(|v| *v == t))
|
||||
.unwrap_or(1) as u8;
|
||||
}
|
||||
S::TropicalFish => {
|
||||
let packed = int("Variant");
|
||||
let (size, index) = (packed & 0xFF, (packed >> 8) & 0xFF);
|
||||
// TropicalFish.Pattern.byId: an unknown id is a kob.
|
||||
m.extra.variant = if size <= 1 && index < 6 {
|
||||
(size * 6 + index) as u8
|
||||
} else {
|
||||
0
|
||||
};
|
||||
m.extra.variant2 = ((packed >> 16) & 15) as u8;
|
||||
m.extra.variant3 = ((packed >> 24) & 15) as u8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
|
||||
let memories = tag.get("Brain").and_then(|b| b.get("memories"));
|
||||
let ttl = memories
|
||||
@@ -1992,12 +2367,39 @@ fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
|
||||
}
|
||||
}
|
||||
const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
|
||||
/// `Salmon.Variant` names, by id.
|
||||
const SALMON_SIZES: [&str; 3] = ["small", "medium", "large"];
|
||||
/// `TropicalFish.Pattern` names in enum order: the six small patterns, then
|
||||
/// the six large ones (the order of `extra.variant`).
|
||||
const TROPICAL_PATTERNS: [&str; 12] = [
|
||||
"kob",
|
||||
"sunstreak",
|
||||
"snooper",
|
||||
"dasher",
|
||||
"brinely",
|
||||
"spotty",
|
||||
"flopper",
|
||||
"stripey",
|
||||
"glitter",
|
||||
"blockfish",
|
||||
"betty",
|
||||
"clayfish",
|
||||
];
|
||||
/// `Bucketable.saveDefaultDataToBucketTag`, with the age an axolotl and a
|
||||
/// tadpole add (`saveToBucketTag`).
|
||||
pub fn bucket_data(m: &Mob) -> Tag {
|
||||
let mut data = Tag::compound([
|
||||
("Age", Tag::Int(m.extra.age)),
|
||||
("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))),
|
||||
("Health", Tag::Float(m.health.to_bits())),
|
||||
]);
|
||||
let mut data = Tag::compound([("Health", Tag::Float(m.health.to_bits()))]);
|
||||
if matches!(
|
||||
m.species(),
|
||||
crate::mobs::Species::Axolotl | crate::mobs::Species::Tadpole
|
||||
) {
|
||||
put(&mut data, "Age", Tag::Int(m.extra.age));
|
||||
put(
|
||||
&mut data,
|
||||
"AgeLocked",
|
||||
Tag::Byte(i8::from(m.extra.age_locked)),
|
||||
);
|
||||
}
|
||||
for (key, on) in [
|
||||
("NoAI", m.no_ai),
|
||||
("Silent", m.silent),
|
||||
@@ -2027,6 +2429,29 @@ pub fn bucket_components(m: &Mob) -> crate::item_data::StackData {
|
||||
.unwrap_or(&"lucy");
|
||||
data.set_other("minecraft:axolotl/variant", Some(string(variant)));
|
||||
}
|
||||
// Salmon.saveToBucketTag: the size.
|
||||
if m.species() == crate::mobs::Species::Salmon {
|
||||
let size = SALMON_SIZES
|
||||
.get(usize::from(m.extra.variant))
|
||||
.unwrap_or(&"medium");
|
||||
data.set_other("minecraft:salmon/size", Some(string(size)));
|
||||
}
|
||||
// TropicalFish.saveToBucketTag: the pattern and both colours.
|
||||
if m.species() == crate::mobs::Species::TropicalFish {
|
||||
let dye = |i: u8| crate::mobs::render::DYE_NAMES[usize::from(i) & 15];
|
||||
let pattern = TROPICAL_PATTERNS
|
||||
.get(usize::from(m.extra.variant))
|
||||
.unwrap_or(&"kob");
|
||||
data.set_other("minecraft:tropical_fish/pattern", Some(string(pattern)));
|
||||
data.set_other(
|
||||
"minecraft:tropical_fish/base_color",
|
||||
Some(string(dye(m.extra.variant2))),
|
||||
);
|
||||
data.set_other(
|
||||
"minecraft:tropical_fish/pattern_color",
|
||||
Some(string(dye(m.extra.variant3))),
|
||||
);
|
||||
}
|
||||
data
|
||||
}
|
||||
pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
|
||||
@@ -2077,6 +2502,39 @@ pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
|
||||
{
|
||||
m.extra.variant = id as u8;
|
||||
}
|
||||
// Salmon.applyImplicitComponents: the size.
|
||||
if m.species() == crate::mobs::Species::Salmon
|
||||
&& let Some(name) = text(components.other("minecraft:salmon/size"))
|
||||
&& let Some(id) = SALMON_SIZES
|
||||
.iter()
|
||||
.position(|&v| v == name.trim_start_matches("minecraft:"))
|
||||
{
|
||||
m.extra.variant = id as u8;
|
||||
}
|
||||
// TropicalFish.applyImplicitComponent: the pattern and both colours.
|
||||
if m.species() == crate::mobs::Species::TropicalFish {
|
||||
let name = |key| text(components.other(key));
|
||||
let dye = |key| {
|
||||
name(key).and_then(|n| {
|
||||
crate::mobs::render::DYE_NAMES
|
||||
.iter()
|
||||
.position(|&v| v == n.trim_start_matches("minecraft:"))
|
||||
})
|
||||
};
|
||||
if let Some(id) = name("minecraft:tropical_fish/pattern").and_then(|n| {
|
||||
TROPICAL_PATTERNS
|
||||
.iter()
|
||||
.position(|&v| v == n.trim_start_matches("minecraft:"))
|
||||
}) {
|
||||
m.extra.variant = id as u8;
|
||||
}
|
||||
if let Some(id) = dye("minecraft:tropical_fish/base_color") {
|
||||
m.extra.variant2 = id as u8;
|
||||
}
|
||||
if let Some(id) = dye("minecraft:tropical_fish/pattern_color") {
|
||||
m.extra.variant3 = id as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2287,6 +2745,123 @@ mod sheep_nbt_tests {
|
||||
let back = mob_from_nbt(&tag, &types, 2).unwrap();
|
||||
assert_eq!((back.extra.color, back.extra.sheared), (14, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn farm_animals_keep_their_variant_and_sound_variant() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("items.json").exists() {
|
||||
return;
|
||||
}
|
||||
let data = crate::mobs::MobTypes::load(&root).unwrap();
|
||||
let types: HashMap<String, Arc<MobType>> = data
|
||||
.types
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), Arc::new(v.clone())))
|
||||
.collect();
|
||||
let mut m = Mob::new(
|
||||
1,
|
||||
types["minecraft:pig"].clone(),
|
||||
Vec3::new(0.0, 4.0, 0.0),
|
||||
0.0,
|
||||
);
|
||||
let tag = mob_to_nbt(&m, [1, 2, 3, 4], None);
|
||||
assert_eq!(
|
||||
text(tag.get("variant")).as_deref(),
|
||||
Some("minecraft:temperate")
|
||||
);
|
||||
assert_eq!(
|
||||
text(tag.get("sound_variant")).as_deref(),
|
||||
Some("minecraft:classic")
|
||||
);
|
||||
// Spawned in a warm biome with the mini sounds.
|
||||
(m.extra.variant, m.extra.sound_variant) = (1, Some(2));
|
||||
let tag = mob_to_nbt(&m, [1, 2, 3, 4], None);
|
||||
assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:warm"));
|
||||
assert_eq!(
|
||||
text(tag.get("sound_variant")).as_deref(),
|
||||
Some("minecraft:mini")
|
||||
);
|
||||
let back = mob_from_nbt(&tag, &types, 2).unwrap();
|
||||
assert_eq!((back.extra.variant, back.extra.sound_variant), (1, Some(2)));
|
||||
let mut hen = Mob::new(
|
||||
3,
|
||||
types["minecraft:chicken"].clone(),
|
||||
Vec3::new(0.0, 4.0, 0.0),
|
||||
0.0,
|
||||
);
|
||||
(hen.extra.variant, hen.extra.egg_time) = (2, 7795);
|
||||
let tag = mob_to_nbt(&hen, [1, 2, 3, 4], None);
|
||||
assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:cold"));
|
||||
let back = mob_from_nbt(&tag, &types, 4).unwrap();
|
||||
assert_eq!((back.extra.variant, back.extra.egg_time), (2, 7795));
|
||||
// The sound variants are indices into the registries finalizeSpawn draws from.
|
||||
use crate::mobs::{Species, finalize};
|
||||
let registries = finalize::SpawnRegistries::load(&root);
|
||||
for (species, registry) in [
|
||||
(Species::Pig, ®istries.pig_sound),
|
||||
(Species::Cow, ®istries.cow_sound),
|
||||
(Species::Chicken, ®istries.chicken_sound),
|
||||
(Species::Cat, ®istries.cat_sound),
|
||||
(Species::Wolf, ®istries.wolf_sound),
|
||||
] {
|
||||
assert_eq!(
|
||||
finalize::sound_variants(species),
|
||||
registry.names,
|
||||
"{species:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foxes_rabbits_and_goats_keep_their_kind() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("items.json").exists() {
|
||||
return;
|
||||
}
|
||||
let data = crate::mobs::MobTypes::load(&root).unwrap();
|
||||
let types: HashMap<String, Arc<MobType>> = data
|
||||
.types
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), Arc::new(v.clone())))
|
||||
.collect();
|
||||
let new = |kind: &str| Mob::new(1, types[kind].clone(), Vec3::new(0.0, 4.0, 0.0), 0.0);
|
||||
let round_trip = |m: &Mob| {
|
||||
let tag = mob_to_nbt(m, [1, 2, 3, 4], None);
|
||||
(mob_from_nbt(&tag, &types, 2).unwrap(), tag)
|
||||
};
|
||||
let mut fox = new("minecraft:fox");
|
||||
fox.extra.variant = 1;
|
||||
let (back, tag) = round_trip(&fox);
|
||||
assert_eq!(text(tag.get("Type")).as_deref(), Some("snow"));
|
||||
assert_eq!(number(tag.get("Sleeping")), Some(0));
|
||||
assert_eq!(back.extra.variant, 1);
|
||||
let mut rabbit = new("minecraft:rabbit");
|
||||
rabbit.extra.variant = 4;
|
||||
let (back, tag) = round_trip(&rabbit);
|
||||
assert_eq!(number(tag.get("RabbitType")), Some(4));
|
||||
assert_eq!(back.extra.variant, 4);
|
||||
let mut goat = new("minecraft:goat");
|
||||
(goat.extra.screaming, goat.extra.lost_horns) = (true, [false, true]);
|
||||
let (back, tag) = round_trip(&goat);
|
||||
assert_eq!(number(tag.get("HasRightHorn")), Some(0));
|
||||
assert_eq!(
|
||||
(back.extra.screaming, back.extra.lost_horns),
|
||||
(true, [false, true])
|
||||
);
|
||||
// A goat saved without horn flags has both, as vanilla reads it.
|
||||
let bare = Tag::compound([
|
||||
("id", string("minecraft:goat")),
|
||||
("Pos", doubles(&[0.5, 64.0, 0.5])),
|
||||
]);
|
||||
assert_eq!(
|
||||
mob_from_nbt(&bare, &types, 3).unwrap().extra.lost_horns,
|
||||
[false; 2]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -35,6 +35,18 @@ impl Damage {
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
/// A block that starts to fall: anvils hurt, and a brushable block
|
||||
/// breaks where it lands (BrushableBlock.tick: disableDrop).
|
||||
pub fn falling(block: &str) -> Self {
|
||||
if block.ends_with("anvil") {
|
||||
Self::anvil()
|
||||
} else {
|
||||
Self {
|
||||
cancel_drop: block.starts_with("minecraft:suspicious_"),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn from_nbt(tag: &Tag, anvil: bool) -> Self {
|
||||
Self {
|
||||
hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0),
|
||||
@@ -181,6 +193,14 @@ pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_brushable_blocks_break_where_they_land() {
|
||||
assert!(Damage::falling("minecraft:suspicious_gravel").cancel_drop);
|
||||
assert!(Damage::falling("minecraft:suspicious_sand").cancel_drop);
|
||||
assert!(!Damage::falling("minecraft:gravel").cancel_drop);
|
||||
assert!(Damage::falling("minecraft:chipped_anvil").hurt_entities);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() {
|
||||
let damage = Damage::anvil();
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
//! Iteration order of the Java hash collections vanilla's scoreboard keeps
|
||||
//! its names in: fastutil's `Object2ObjectOpenHashMap<String, _>` (open
|
||||
//! addressing with linear probing, backward-shift deletion and rehashing at
|
||||
//! the load factor) and `java.util.HashSet<String>` (chained buckets split on
|
||||
//! resize). Commands list, and `scoreboard.dat` saves, in these orders.
|
||||
|
||||
/// The keys of a fastutil open hash map in their table slots.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OpenOrder {
|
||||
keys: Vec<Option<String>>,
|
||||
size: usize,
|
||||
min_n: usize,
|
||||
load: f32,
|
||||
}
|
||||
impl Default for OpenOrder {
|
||||
/// `new Object2ObjectOpenHashMap<>()`: 16 expected entries, load 0.75.
|
||||
fn default() -> Self {
|
||||
Self::new(16, 0.75)
|
||||
}
|
||||
}
|
||||
/// `String.hashCode`.
|
||||
pub fn java_hash(s: &str) -> i32 {
|
||||
s.encode_utf16()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
|
||||
}
|
||||
/// `HashCommon.mix`.
|
||||
fn mix(x: i32) -> usize {
|
||||
let h = (x as u32).wrapping_mul(0x9E37_79B9);
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
/// `HashCommon.arraySize`.
|
||||
fn array_size(expected: usize, f: f32) -> usize {
|
||||
let wanted = (expected as f64 / f64::from(f)).ceil() as usize;
|
||||
wanted.max(2).next_power_of_two()
|
||||
}
|
||||
/// `HashCommon.maxFill`.
|
||||
fn max_fill(n: usize, f: f32) -> usize {
|
||||
((n as f64 * f64::from(f)).ceil() as usize).min(n - 1)
|
||||
}
|
||||
impl OpenOrder {
|
||||
pub fn new(expected: usize, load: f32) -> Self {
|
||||
let n = array_size(expected, load);
|
||||
Self {
|
||||
keys: vec![None; n],
|
||||
size: 0,
|
||||
min_n: n,
|
||||
load,
|
||||
}
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
fn slot(&self, key: &str) -> usize {
|
||||
mix(java_hash(key)) & (self.keys.len() - 1)
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return true;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `put`: false when the key was already there.
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return false;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key.to_owned());
|
||||
// `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`.
|
||||
let old = self.size;
|
||||
self.size += 1;
|
||||
if old >= max_fill(self.keys.len(), self.load) {
|
||||
self.rehash(array_size(self.size + 1, self.load));
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `remove`: false when the key was not there.
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
loop {
|
||||
match &self.keys[pos] {
|
||||
None => return false,
|
||||
Some(k) if k == key => break,
|
||||
Some(_) => pos = (pos + 1) & mask,
|
||||
}
|
||||
}
|
||||
self.size -= 1;
|
||||
self.shift_keys(pos);
|
||||
let n = self.keys.len();
|
||||
if n > self.min_n && self.size < max_fill(n, self.load) / 4 && n > 16 {
|
||||
self.rehash(n / 2);
|
||||
}
|
||||
true
|
||||
}
|
||||
fn shift_keys(&mut self, mut pos: usize) {
|
||||
let mask = self.keys.len() - 1;
|
||||
loop {
|
||||
let last = pos;
|
||||
pos = (last + 1) & mask;
|
||||
loop {
|
||||
let Some(curr) = self.keys[pos].clone() else {
|
||||
self.keys[last] = None;
|
||||
return;
|
||||
};
|
||||
let slot = self.slot(&curr);
|
||||
let stop = if last <= pos {
|
||||
last >= slot || slot > pos
|
||||
} else {
|
||||
last >= slot && slot > pos
|
||||
};
|
||||
if stop {
|
||||
self.keys[last] = Some(curr);
|
||||
break;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn rehash(&mut self, new_n: usize) {
|
||||
let old = std::mem::replace(&mut self.keys, vec![None; new_n]);
|
||||
let mask = new_n - 1;
|
||||
// `for (int j = realSize(); j-- != 0;) { while (key[--i] == null); ... }`
|
||||
for key in old.into_iter().rev().flatten() {
|
||||
let mut pos = mix(java_hash(&key)) & mask;
|
||||
while self.keys[pos].is_some() {
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key);
|
||||
}
|
||||
}
|
||||
/// `iterator()` and `forEach`: from the last slot down.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().rev().flatten().map(String::as_str)
|
||||
}
|
||||
/// `spliterator()` (what `stream()` uses): from the first slot up.
|
||||
pub fn stream(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().flatten().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys of a `java.util.HashSet<String>` in their buckets.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HashSetOrder {
|
||||
/// Empty until the first insertion (`HashMap.resize` on first `put`).
|
||||
table: Vec<Vec<String>>,
|
||||
size: usize,
|
||||
}
|
||||
/// `HashMap.hash`.
|
||||
fn spread(s: &str) -> usize {
|
||||
let h = java_hash(s) as u32;
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
impl HashSetOrder {
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
self.table[i].iter().any(|k| k == key)
|
||||
}
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
self.table = vec![Vec::new(); 16];
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
if self.table[i].iter().any(|k| k == key) {
|
||||
return false;
|
||||
}
|
||||
self.table[i].push(key.to_owned());
|
||||
self.size += 1;
|
||||
if self.size > self.table.len() * 3 / 4 {
|
||||
self.resize();
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Doubles the table; each bucket splits into its low and high halves in order.
|
||||
fn resize(&mut self) {
|
||||
let old = std::mem::take(&mut self.table);
|
||||
let n = old.len() * 2;
|
||||
self.table = vec![Vec::new(); n];
|
||||
for bucket in old {
|
||||
for key in bucket {
|
||||
let i = spread(&key) & (n - 1);
|
||||
self.table[i].push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
let Some(at) = self.table[i].iter().position(|k| k == key) else {
|
||||
return false;
|
||||
};
|
||||
self.table[i].remove(at);
|
||||
self.size -= 1;
|
||||
true
|
||||
}
|
||||
pub fn iter(&self) -> impl Iterator<Item = &String> {
|
||||
self.table.iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hash_and_order() {
|
||||
assert_eq!(java_hash("harness"), {
|
||||
"harness"
|
||||
.chars()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))
|
||||
});
|
||||
let mut o = OpenOrder::new(16, 0.5);
|
||||
for k in ["harness", "harness_h"] {
|
||||
o.insert(k);
|
||||
}
|
||||
assert_eq!(o.iter().count(), 2);
|
||||
let mut asc: Vec<&str> = o.stream().collect();
|
||||
asc.reverse();
|
||||
assert_eq!(asc, o.iter().collect::<Vec<_>>());
|
||||
o.remove("harness");
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
for i in 0..40 {
|
||||
o.insert(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.iter().count(), 41);
|
||||
for i in 0..40 {
|
||||
o.remove(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_set_buckets() {
|
||||
let mut s = HashSetOrder::default();
|
||||
for i in 0..30 {
|
||||
assert!(s.insert(&format!("p{i}")));
|
||||
}
|
||||
assert!(!s.insert("p3"));
|
||||
assert_eq!(s.len(), 30);
|
||||
assert!(s.remove("p3") && !s.contains("p3"));
|
||||
// "Aa" and "BB" share a hash: insertion order within the bucket.
|
||||
let mut t = HashSetOrder::default();
|
||||
t.insert("BB");
|
||||
t.insert("Aa");
|
||||
assert_eq!(t.iter().collect::<Vec<_>>(), vec!["BB", "Aa"]);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,8 @@ pub fn flames(
|
||||
color: 0xffff_ffff,
|
||||
light: 0xf000 | (u32::from(scene_light >> 4) * 16),
|
||||
normal: [0; 4],
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
remaining -= 0.45;
|
||||
|
||||
@@ -889,12 +889,17 @@ impl Font {
|
||||
if s.contains('§') {
|
||||
return self.width_text(&Text::legacy(s));
|
||||
}
|
||||
s.chars().map(|c| self.glyph(c).advance).sum::<f32>().ceil()
|
||||
crate::bidi::visual_str(s)
|
||||
.chars()
|
||||
.map(|c| self.glyph(c).advance)
|
||||
.sum::<f32>()
|
||||
.ceil()
|
||||
}
|
||||
/// Font.width of a component: `§` codes in the spans are formatting,
|
||||
/// not glyphs.
|
||||
/// not glyphs. Right-to-left text is measured as it is drawn, shaped.
|
||||
pub fn width_text(&self, t: &Text) -> f32 {
|
||||
t.resolved()
|
||||
let t = t.resolved();
|
||||
crate::bidi::visual(&t)
|
||||
.chars()
|
||||
.map(|(c, s)| self.advance(c, s))
|
||||
.sum::<f32>()
|
||||
|
||||
+1166
-287
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@ use horizon_client::{
|
||||
text::{self, Style, Text},
|
||||
toasts::Slide,
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||
@@ -82,6 +83,8 @@ pub(super) struct AdvState {
|
||||
pub(super) quiet: bool,
|
||||
/// The inventory last seen by `inventory_changed`.
|
||||
pub(super) last_inventory: u64,
|
||||
/// `ServerPlayer.levitationStartPos` and `levitationStartTime`.
|
||||
pub(super) levitation: Option<([f64; 3], u64)>,
|
||||
/// While the game acts for a network player (`as_guest`): the
|
||||
/// advancements whose progress changed (`progressChanged`), the recipes
|
||||
/// unlocked and the announcements, for their client and everyone's.
|
||||
@@ -180,6 +183,14 @@ impl adv::World for View<'_, '_> {
|
||||
"block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)),
|
||||
"entity_type" => self.0.res.mob_data().entity_has(tag, id),
|
||||
"worldgen/biome" => self.0.res.mob_data().biome_has(tag, id),
|
||||
"damage_type" => self
|
||||
.0
|
||||
.res
|
||||
.stations()
|
||||
.enchantments
|
||||
.damage_tags
|
||||
.get(tag)
|
||||
.is_some_and(|t| t.contains(id)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -647,6 +658,28 @@ impl Game<'_> {
|
||||
};
|
||||
adv::conditions(&c["player"], &ctx, w)
|
||||
});
|
||||
// ServerPlayer.onEffectAdded and onEffectsRemoved keep the start of a
|
||||
// levitation; tick fires LEVITATION while there is one.
|
||||
let levitating = self
|
||||
.potions
|
||||
.effects
|
||||
.list
|
||||
.iter()
|
||||
.any(|e| e.id == "levitation");
|
||||
match (levitating, self.adv.levitation) {
|
||||
(true, None) => {
|
||||
let at = self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z]);
|
||||
self.adv.levitation = at.map(|at| (at, self.ticks));
|
||||
}
|
||||
(false, Some(_)) => self.adv.levitation = None,
|
||||
_ => {}
|
||||
}
|
||||
if let Some((start, since)) = self.adv.levitation {
|
||||
self.trigger_levitation(start, (self.ticks - since) as i64);
|
||||
}
|
||||
if self.ticks.is_multiple_of(20) {
|
||||
let me = self.player_entity();
|
||||
self.trigger("minecraft:location", |c, w| {
|
||||
@@ -681,6 +714,123 @@ impl Game<'_> {
|
||||
adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w)
|
||||
});
|
||||
}
|
||||
/// `LevitationTrigger`: how far the player rose from where it started
|
||||
/// levitating, and for how long.
|
||||
fn trigger_levitation(&mut self, start: [f64; 3], duration: i64) {
|
||||
let me = self.player_entity();
|
||||
self.trigger("minecraft:levitation", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w)
|
||||
&& (c["distance"].is_null() || adv::distance(&c["distance"], start, me.position))
|
||||
&& adv::range_i(&c["duration"], duration)
|
||||
});
|
||||
}
|
||||
/// `ServerPlayer.updateUsingItem`: USING_ITEM for the item in use, with
|
||||
/// what the player looks at (`PlayerPredicate.lookingAt`).
|
||||
pub(super) fn trigger_using_item(&mut self, stack: &ItemStack) {
|
||||
if self.remote.is_some() || self.no_player_here() {
|
||||
return;
|
||||
}
|
||||
let mut me = self.player_entity();
|
||||
me.looking_at = self.looking_at_entity().map(Box::new);
|
||||
let it = item_view(stack);
|
||||
self.trigger("minecraft:using_item", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w)
|
||||
});
|
||||
}
|
||||
/// The mob a 100 block ray from the eyes meets first, if no block is in
|
||||
/// the way (`ProjectileUtil.getEntityHitResult` and `hasLineOfSight`).
|
||||
fn looking_at_entity(&self) -> Option<EntityView> {
|
||||
let eye = self.eye_position()?;
|
||||
let dir = super::view_vector(self.yaw, self.pitch);
|
||||
let (m, _) = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| m.alive())
|
||||
.filter_map(|m| Some((m, super::ray_box(eye, dir, 100.0, m.bounds())?)))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
// `LivingEntity.hasLineOfSight`: eye to the target's eye height,
|
||||
// `ClipContext.Block.COLLIDER`, no fluids, within 128 blocks.
|
||||
let from = Vec3::new(eye[0], eye[1], eye[2]);
|
||||
let to = Vec3::new(m.position.x, m.eye_y(), m.position.z);
|
||||
let world = self.mob_world_base(&[]);
|
||||
let clear = to.distance(from) <= 128.0 && world.clear_between(from, to, false);
|
||||
clear.then(|| self.mob_entity(m))
|
||||
}
|
||||
/// `PlayerHurtEntityTrigger`: the player, the damage and the victim.
|
||||
pub(super) fn trigger_player_hurt_entity(
|
||||
&mut self,
|
||||
victim: &EntityView,
|
||||
damage: &adv::DamageView,
|
||||
) {
|
||||
let me = self.player_entity();
|
||||
let (victim, damage) = (victim.clone(), damage.clone());
|
||||
self.trigger("minecraft:player_hurt_entity", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
let vctx = adv::Entities {
|
||||
this: Some(&victim),
|
||||
..pctx
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w)
|
||||
&& adv::damage(&c["damage"], &damage, w, me.position)
|
||||
&& adv::conditions(&c["entity"], &vctx, w)
|
||||
});
|
||||
}
|
||||
/// The player's hit on `victim` as `LivingEntity.hurtServer` reports it:
|
||||
/// `kind` damage of `amount` from `direct` (the player's own hand when
|
||||
/// `None`), nothing blocked.
|
||||
pub(super) fn player_hit(
|
||||
&mut self,
|
||||
victim: &EntityView,
|
||||
kind: &str,
|
||||
direct: Option<EntityView>,
|
||||
amount: f32,
|
||||
) {
|
||||
let me = self.player_entity();
|
||||
self.trigger_player_hurt_entity(
|
||||
victim,
|
||||
&adv::DamageView {
|
||||
kind: kind.to_owned(),
|
||||
is_direct: direct.is_none(),
|
||||
direct: direct.or_else(|| Some(me.clone())),
|
||||
source: Some(me),
|
||||
original: amount,
|
||||
actual: amount,
|
||||
blocked: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
/// `EntityHurtPlayerTrigger`: the player and the damage it took.
|
||||
pub(super) fn trigger_entity_hurt_player(&mut self, damage: &adv::DamageView) {
|
||||
let me = self.player_entity();
|
||||
let damage = damage.clone();
|
||||
self.trigger("minecraft:entity_hurt_player", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w)
|
||||
&& adv::damage(&c["damage"], &damage, w, me.position)
|
||||
});
|
||||
}
|
||||
/// A player condition plus one item (`item` key).
|
||||
pub(super) fn trigger_item(&mut self, name: &str, stack: &ItemStack) {
|
||||
let me = self.player_entity();
|
||||
@@ -708,6 +858,72 @@ impl Game<'_> {
|
||||
let it = item_view(stack);
|
||||
self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w));
|
||||
}
|
||||
/// `BrewedPotionTrigger`: the potion contents of a stack taken from a
|
||||
/// brewing stand.
|
||||
pub(super) fn trigger_brewed_potion(&mut self, stack: &ItemStack) {
|
||||
let me = self.player_entity();
|
||||
let potion = stack.potion().map(str::to_owned);
|
||||
self.trigger("minecraft:brewed_potion", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w)
|
||||
&& adv::potions(&c["potion"], potion.as_deref(), w)
|
||||
});
|
||||
}
|
||||
/// `TradeTrigger`: the villager and the item the trade gave.
|
||||
pub(super) fn trigger_trade(&mut self, villager: &EntityView, stack: &ItemStack) {
|
||||
let me = self.player_entity();
|
||||
let villager = villager.clone();
|
||||
let it = item_view(stack);
|
||||
self.trigger("minecraft:villager_trade", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
let vctx = adv::Entities {
|
||||
this: Some(&villager),
|
||||
..pctx
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w)
|
||||
&& adv::conditions(&c["villager"], &vctx, w)
|
||||
&& adv::item(&c["item"], &it, w)
|
||||
});
|
||||
}
|
||||
/// `FishingRodHookedTrigger`: the rod, what the hook is in (or the hook)
|
||||
/// and the items it caught.
|
||||
pub(super) fn trigger_fishing_rod_hooked(
|
||||
&mut self,
|
||||
rod: &ItemStack,
|
||||
hooked: &EntityView,
|
||||
items: &[ItemStack],
|
||||
) {
|
||||
let me = self.player_entity();
|
||||
let rod = item_view(rod);
|
||||
let hooked = hooked.clone();
|
||||
let items: Vec<ItemView> = items.iter().map(item_view).collect();
|
||||
self.trigger("minecraft:fishing_rod_hooked", move |c, w| {
|
||||
let pctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
let ectx = adv::Entities {
|
||||
this: Some(&hooked),
|
||||
..pctx
|
||||
};
|
||||
adv::conditions(&c["player"], &pctx, w)
|
||||
&& adv::item(&c["rod"], &rod, w)
|
||||
&& adv::conditions(&c["entity"], &ectx, w)
|
||||
&& (c["item"].is_null() || items.iter().any(|i| adv::item(&c["item"], i, w)))
|
||||
});
|
||||
}
|
||||
/// `EnterBlockTrigger`: the block, its state properties and the player.
|
||||
pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) {
|
||||
let Some(definition) = self.pack.assets.registry.state(state).cloned() else {
|
||||
|
||||
@@ -419,6 +419,9 @@ impl Game<'_> {
|
||||
Screen::Advancements => "advancements",
|
||||
Screen::WorldOptions => "world-options",
|
||||
Screen::Friends => "friends",
|
||||
Screen::ServerLinks => "server-links",
|
||||
Screen::ConfirmLink => "confirm-link",
|
||||
Screen::DialogWarning => "dialog-warning",
|
||||
Screen::CommandBlock => "command-block",
|
||||
Screen::Win => "win",
|
||||
Screen::Mod => "mod",
|
||||
@@ -565,6 +568,22 @@ impl Game<'_> {
|
||||
"generate_structures": options.structures,
|
||||
"bonus_chest": options.bonus_chest(),
|
||||
}),
|
||||
Mode::CreateFlat {
|
||||
name,
|
||||
seed,
|
||||
options,
|
||||
flat,
|
||||
..
|
||||
} => json!({
|
||||
"mode": "customize-flat",
|
||||
"fields": { "name": name, "seed": seed },
|
||||
"superflat": options.flat,
|
||||
"biome": flat.settings().biome,
|
||||
"layers": flat.settings().layers.iter().map(|layer| json!({
|
||||
"block": layer.block,
|
||||
"height": layer.height,
|
||||
})).collect::<Vec<_>>(),
|
||||
}),
|
||||
Mode::Edit {
|
||||
world,
|
||||
name,
|
||||
@@ -707,9 +726,12 @@ impl Game<'_> {
|
||||
// the recipe buttons of the page, page arrows, filter and tabs.
|
||||
let book = self.recipe_book_targets();
|
||||
if !book.is_empty() {
|
||||
let (open, filtering) = self.recipe_book_flags().unwrap_or_default();
|
||||
v["recipe_book"] = json!({
|
||||
"targets": book.iter().map(|t| t.rect).collect::<Vec<_>>(),
|
||||
"known": self.recipe_book_known(),
|
||||
"open": open,
|
||||
"filtering": filtering,
|
||||
});
|
||||
}
|
||||
v["slot_ids"] = json!(
|
||||
|
||||
@@ -131,7 +131,8 @@ impl Game<'_> {
|
||||
let m = &mut self.mobs[i];
|
||||
m.extra.ints[1] -= 1;
|
||||
m.extra.ints[3] = 60;
|
||||
self.spawn_item(ItemStack::new(&item, 1), from, v, 40);
|
||||
// ItemEntity.setDefaultPickUpDelay.
|
||||
self.spawn_item(ItemStack::new(&item, 1), from, v, 10);
|
||||
if self.world.game_time % 7 == 0 && self.world.random.next_double() < 0.9 {
|
||||
const PITCHES: [f32; 16] = [
|
||||
0.5625, 0.625, 0.75, 0.9375, 1.0, 1.0, 1.125, 1.25, 1.5, 1.875, 2.0, 2.25, 2.5,
|
||||
@@ -160,7 +161,7 @@ impl Game<'_> {
|
||||
}
|
||||
// Allay.duplicateAllay: entity event 18, three spawnHeartParticle.
|
||||
let id = self.mobs[index].id;
|
||||
self.particles_around_mob(id, "heart", horizon_client::particles::Burst::ALLAY);
|
||||
self.mob_event_particles(id, 18);
|
||||
self.audio
|
||||
.play("minecraft:block.amethyst_block.chime", Some(at), 2.0, 1.0);
|
||||
self.consume_held();
|
||||
|
||||
@@ -453,6 +453,11 @@ impl Game<'_> {
|
||||
}
|
||||
// ArmorStand.swapItem.
|
||||
match held {
|
||||
// A player with infinite materials puts a copy of one on an empty
|
||||
// slot and keeps the stack.
|
||||
Some(h) if self.creative && current.is_none() => {
|
||||
self.armor_stands[i].equipment[slot] = Some(ItemStack { count: 1, ..h });
|
||||
}
|
||||
Some(h) if h.count > 1 => {
|
||||
if current.is_some() {
|
||||
return true;
|
||||
@@ -706,6 +711,20 @@ impl Game<'_> {
|
||||
let color = undyed.map_or(0xFFFF_FFFF, |c| {
|
||||
0xFF00_0000 | (c & 0xFF) << 16 | (c & 0xFF00) | (c >> 16) & 0xFF
|
||||
});
|
||||
// ArmorStandRenderer's HumanoidArmorLayer: the armour glint
|
||||
// when `stack.hasFoil()`, as on a living entity.
|
||||
let item_glint = self
|
||||
.res
|
||||
.items()
|
||||
.enchantments
|
||||
.props
|
||||
.get(&stack.item)
|
||||
.is_some_and(|p| p.glint);
|
||||
let overlay = if stack.has_foil(item_glint) {
|
||||
horizon_client::mobs::render::ARMOR_GLINT
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let layer_poses = Poses::new(part);
|
||||
horizon_client::mobs::render::draw(
|
||||
part,
|
||||
@@ -714,7 +733,7 @@ impl Game<'_> {
|
||||
uv,
|
||||
color,
|
||||
packed,
|
||||
0,
|
||||
overlay,
|
||||
out,
|
||||
);
|
||||
// EquipmentLayerRenderer: the trim layer over the armour.
|
||||
@@ -729,7 +748,7 @@ impl Game<'_> {
|
||||
trim,
|
||||
0xFFFF_FFFF,
|
||||
packed,
|
||||
0,
|
||||
overlay,
|
||||
out,
|
||||
);
|
||||
}
|
||||
@@ -872,6 +891,7 @@ impl Game<'_> {
|
||||
lights: Some(horizon_client::block_entity_render::diffuse_lights(
|
||||
self.dim == super::Dim::Nether,
|
||||
)),
|
||||
glint: self.glint(),
|
||||
};
|
||||
let profile = stack
|
||||
.extra
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
//! player breaks the hive or fire reaches it.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
beehive::{self, Beehive, HiveHost, Release},
|
||||
containers::BlockEntity,
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Who, bee},
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -194,19 +196,139 @@ impl Game<'_> {
|
||||
}
|
||||
self.anger_nearby_bees(at);
|
||||
}
|
||||
/// `BeehiveBlock.useItemOn` with `held` in the acting hand: shears take
|
||||
/// the honeycombs and a glass bottle a honey bottle from a full hive
|
||||
/// (honey level 5), then the honey level resets and, unless a campfire
|
||||
/// smokes the hive, the bees come out angry. True when it took the click.
|
||||
pub(super) fn use_beehive(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> Result<bool> {
|
||||
let Some(held) = held else { return Ok(false) };
|
||||
let shears = &*held.item == "minecraft:shears";
|
||||
if !shears && &*held.item != "minecraft:glass_bottle" {
|
||||
return Ok(false);
|
||||
}
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if !matches!(
|
||||
&*self.res.facts().get(state).name,
|
||||
"minecraft:beehive" | "minecraft:bee_nest"
|
||||
) {
|
||||
return Ok(false);
|
||||
}
|
||||
let prop = |key: &str| {
|
||||
self.pack
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get(key).cloned())
|
||||
};
|
||||
if prop("honey_level").and_then(|v| v.parse::<i32>().ok()) != Some(5) {
|
||||
return Ok(false);
|
||||
}
|
||||
let facing = beehive::facing_step(prop("facing").as_deref());
|
||||
let at = self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z]);
|
||||
if shears {
|
||||
// dropHoneycomb (harvest/beehive), the shear sound, hurtAndBreak.
|
||||
for stack in self.sequence_loot(
|
||||
"minecraft:harvest/beehive",
|
||||
"minecraft:harvest/beehive",
|
||||
Some(held),
|
||||
) {
|
||||
self.pop_resource(pos, stack);
|
||||
}
|
||||
self.audio
|
||||
.play("minecraft:block.beehive.shear", at, 1.0, 1.0);
|
||||
self.damage_held(1);
|
||||
self.post_block_game_event("minecraft:shear", pos, self.sculk_actor(), None);
|
||||
} else {
|
||||
// shrink(1), then the honey bottle in the hand, the inventory or
|
||||
// on the ground.
|
||||
self.audio.play("minecraft:item.bottle.fill", at, 1.0, 1.0);
|
||||
let cell = self.held_mut();
|
||||
if let Some(s) = cell.as_mut() {
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
*cell = None;
|
||||
}
|
||||
}
|
||||
let bottle = ItemStack::new("minecraft:honey_bottle", 1);
|
||||
if self.held().is_none() {
|
||||
*self.held_mut() = Some(bottle);
|
||||
} else if let Some(rest) = self.give(bottle)
|
||||
&& let Some(eye) = self.eye_position()
|
||||
{
|
||||
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
|
||||
}
|
||||
self.post_block_game_event("minecraft:fluid_pickup", pos, self.sculk_actor(), None);
|
||||
}
|
||||
self.stats.add("used", &held.item, 1);
|
||||
let smokey = beehive::smokey(&self.mob_world_base(&[]), pos);
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if !smokey
|
||||
&& matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.bees.is_empty())
|
||||
{
|
||||
self.anger_nearby_bees(pos);
|
||||
}
|
||||
// resetHoneyLevel.
|
||||
if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) {
|
||||
self.level_set(pos, reset)?;
|
||||
}
|
||||
if !smokey
|
||||
&& let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key)
|
||||
{
|
||||
// emptyAllLivingFromHive: the bees within 4 blocks of the player
|
||||
// go for them.
|
||||
let released = hive.release_all(
|
||||
pos,
|
||||
facing,
|
||||
None,
|
||||
Release::Emergency,
|
||||
&mut GameHive { game: self },
|
||||
);
|
||||
self.world
|
||||
.block_entities
|
||||
.put(key, BlockEntity::Beehive(hive));
|
||||
if let Some(p) = self.player_view().map(|p| p.position) {
|
||||
for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) {
|
||||
if m.distance_sqr(p) <= 16.0 {
|
||||
m.ai.target = Some(Who::Player);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// ServerPlayerGameMode.useItemOn: the action was consumed.
|
||||
self.trigger_block("minecraft:item_used_on_block", pos, held);
|
||||
Ok(true)
|
||||
}
|
||||
/// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down)
|
||||
/// without a target go for a player in the same box.
|
||||
fn anger_nearby_bees(&mut self, at: [i32; 3]) {
|
||||
/// without a target go for a random player in the same box, the window's
|
||||
/// own or a guest (`None` is the window's player).
|
||||
pub(super) fn anger_nearby_bees(&mut self, at: [i32; 3]) {
|
||||
let min = Vec3::new(
|
||||
f64::from(at[0]) - 8.0,
|
||||
f64::from(at[1]) - 6.0,
|
||||
f64::from(at[2]) - 8.0,
|
||||
);
|
||||
let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0));
|
||||
if !self
|
||||
let mut players: Vec<Option<u32>> = Vec::new();
|
||||
if self
|
||||
.player_view()
|
||||
.is_some_and(|p| p.bounds.intersects(area))
|
||||
{
|
||||
players.push(None);
|
||||
}
|
||||
if let Some(host) = self.lan.as_ref() {
|
||||
players.extend(
|
||||
host.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
|
||||
.filter(|g| super::lan_mobs::guest_bounds(g).intersects(area))
|
||||
.map(|g| Some(g.conn)),
|
||||
);
|
||||
}
|
||||
if players.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut bees: Vec<usize> = (0..self.mobs.len())
|
||||
@@ -219,9 +341,20 @@ impl Game<'_> {
|
||||
.collect();
|
||||
bees.retain(|&i| self.mobs[i].ai.target.is_none());
|
||||
for i in bees {
|
||||
// Util.getRandom over the one player.
|
||||
let _ = self.world.random.next_int_bound(1);
|
||||
// Util.getRandom over the players.
|
||||
let pick = self
|
||||
.world
|
||||
.random
|
||||
.next_int_bound(players.len() as i32)
|
||||
.unwrap_or(0) as usize;
|
||||
self.mobs[i].ai.target = Some(Who::Player);
|
||||
// The player a mob sees is its guest binding, else the window's.
|
||||
if let Some(host) = self.lan.as_mut() {
|
||||
match players[pick] {
|
||||
Some(conn) => host.mob_players.insert(self.mobs[i].id, conn),
|
||||
None => host.mob_players.remove(&self.mobs[i].id),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,14 @@
|
||||
//! [`Game::block_anim`] and [`Game::chest_lid`].
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
|
||||
block_entity_anim::{
|
||||
BellEntity, ConduitServer, ConduitTarget, EndGateway, Shulker, ShulkerStatus, Ticker,
|
||||
},
|
||||
block_entity_render::BlockAnim,
|
||||
collisions::{SceneCollisions, no_collision_empty},
|
||||
containers::BlockEntity,
|
||||
effects::EffectInstance,
|
||||
mobs::{Damage, DamageKind},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
save::number,
|
||||
skins,
|
||||
@@ -16,6 +20,7 @@ use horizon_client::{
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
position::BlockPos,
|
||||
random::RandomSource,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
@@ -71,23 +76,24 @@ impl Game<'_> {
|
||||
/// A player opened (`open`) or closed the container at `key`: the opener
|
||||
/// count block event (`ContainerOpenersCounter` / `ShulkerBoxBlockEntity`
|
||||
/// `startOpen`/`stopOpen`) for chests, ender chests and shulker boxes,
|
||||
/// on both halves of a double chest (`CompoundContainer`).
|
||||
pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) {
|
||||
/// on both halves of a double chest (`CompoundContainer`). True when the
|
||||
/// count went from 0 to 1 or back to 0: the only moments the container
|
||||
/// plays its open or close sound.
|
||||
pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) -> bool {
|
||||
// Spectators never count as openers.
|
||||
if !self.spectator() {
|
||||
self.container_openers_changed(key, open);
|
||||
}
|
||||
!self.spectator() && self.container_openers_changed(key, open)
|
||||
}
|
||||
/// `container_opener_event` for a player who is not a spectator (a guest).
|
||||
pub(super) fn container_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
|
||||
pub(super) fn container_openers_changed(&mut self, key: (i32, i32, i32), open: bool) -> bool {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]).0;
|
||||
match self.be_anims.ticker(state) {
|
||||
Some(Ticker::Lid) => {
|
||||
self.lid_openers_changed(key, open);
|
||||
let edge = self.lid_openers_changed(key, open);
|
||||
if let Some(other) = self.chest_other_half(key) {
|
||||
self.lid_openers_changed(other, open);
|
||||
}
|
||||
edge
|
||||
}
|
||||
_ if self
|
||||
.res
|
||||
@@ -97,26 +103,27 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
== "minecraft:barrel" =>
|
||||
{
|
||||
self.barrel_openers_changed(key, open);
|
||||
self.barrel_openers_changed(key, open)
|
||||
}
|
||||
Some(Ticker::Shulker { .. }) => {
|
||||
let shulker = self.be_anims.shulkers.entry(pos).or_default();
|
||||
let (count, _) = if open {
|
||||
let (count, edge) = if open {
|
||||
shulker.start_open()
|
||||
} else {
|
||||
shulker.stop_open()
|
||||
};
|
||||
self.block_entity_event(pos, 1, count);
|
||||
self.lan_block_event(pos, 1, count);
|
||||
edge
|
||||
}
|
||||
_ => {}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// `ContainerOpenersCounter.incrementOpeners` / `decrementOpeners` of the
|
||||
/// chest at `key` (the host and the guests are counted), then
|
||||
/// `ChestBlockEntity.signalOpenCount`: block event 1 with the count, here
|
||||
/// and for the guests.
|
||||
fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
|
||||
/// and for the guests. True when the count crossed zero.
|
||||
fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) -> bool {
|
||||
let (before, count) = self.count_opener(key, open);
|
||||
let pos = [key.0, key.1, key.2];
|
||||
self.block_entity_event(pos, 1, count);
|
||||
@@ -134,12 +141,15 @@ impl Game<'_> {
|
||||
b.update_neighbors_at(level, ticks, p.offset(0, -1, 0), block);
|
||||
});
|
||||
}
|
||||
(before == 0) != (count == 0)
|
||||
}
|
||||
/// `BarrelBlockEntity.openersCounter`: the first opener opens the barrel
|
||||
/// (`open=true`), the last one to leave closes it (`updateBlockState`).
|
||||
fn barrel_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
|
||||
/// True when the count crossed zero.
|
||||
fn barrel_openers_changed(&mut self, key: (i32, i32, i32), open: bool) -> bool {
|
||||
let (before, count) = self.count_opener(key, open);
|
||||
if (before == 0) != (count == 0) {
|
||||
let edge = (before == 0) != (count == 0);
|
||||
if edge {
|
||||
self.set_bool_prop(
|
||||
key,
|
||||
"open",
|
||||
@@ -147,6 +157,7 @@ impl Game<'_> {
|
||||
horizon_world::level::flags::UPDATE_ALL,
|
||||
);
|
||||
}
|
||||
edge
|
||||
}
|
||||
/// One opener more (`open`) or less at `key`: the count before and after
|
||||
/// (`ContainerOpenersCounter.incrementOpeners` / `decrementOpeners`).
|
||||
@@ -218,9 +229,12 @@ impl Game<'_> {
|
||||
/// The client tickers of the loaded animated block entities, once per
|
||||
/// client tick (`ClientLevel.tickBlockEntities`).
|
||||
pub(super) fn tick_block_entity_anims(&mut self) {
|
||||
// A server has no window, but its gateways and conduits still run
|
||||
// their server tickers; a client of one only animates what it is sent.
|
||||
if self.remote.is_none() {
|
||||
self.tick_conduit_servers();
|
||||
}
|
||||
let Some(r) = &self.renderer else {
|
||||
// A server has no window, but its gateways still run their
|
||||
// server ticker.
|
||||
if self.remote.is_none() {
|
||||
self.tick_gateway_servers();
|
||||
}
|
||||
@@ -337,6 +351,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Ticker::Conduit => {
|
||||
let target = self.conduit_target(pos);
|
||||
let world = &self.world;
|
||||
let facts = self.res.facts();
|
||||
let registry = self.pack.assets.registry;
|
||||
@@ -356,7 +371,7 @@ impl Game<'_> {
|
||||
time,
|
||||
is_water,
|
||||
is_frame,
|
||||
None,
|
||||
target,
|
||||
self.particles.random(),
|
||||
);
|
||||
let nautilus = ParticleOptions::simple(ParticleType::Nautilus);
|
||||
@@ -383,6 +398,248 @@ impl Game<'_> {
|
||||
}
|
||||
self.be_anims.present = positions;
|
||||
}
|
||||
/// `ConduitBlockEntity.serverTick` of every conduit in the chunks that
|
||||
/// tick blocks, with or without a renderer. The conduits are looked for
|
||||
/// when the shape is checked, every 40 ticks (they have no block entity
|
||||
/// of their own here).
|
||||
fn tick_conduit_servers(&mut self) {
|
||||
if self.world.game_time % 40 == 0 {
|
||||
self.find_conduits();
|
||||
}
|
||||
let mut positions: Vec<[i32; 3]> = self.be_anims.conduit_servers.keys().copied().collect();
|
||||
positions.sort_unstable();
|
||||
for pos in positions {
|
||||
self.tick_conduit_server(pos);
|
||||
}
|
||||
}
|
||||
/// Sets `be_anims.conduit_servers` to the conduits in the
|
||||
/// chunks that tick blocks, keeping the state of those already known.
|
||||
fn find_conduits(&mut self) {
|
||||
let levels = self.tickets.levels();
|
||||
let kinds = &self.be_anims.kinds;
|
||||
let is_conduit = |id: u32| matches!(kinds.get(id as usize), Some(Some(Ticker::Conduit)));
|
||||
let mut found = Vec::new();
|
||||
for (&(cx, cz), chunk) in &self.world.chunks {
|
||||
if !levels.block_ticking_at(cx * 16, cz * 16) {
|
||||
continue;
|
||||
}
|
||||
for (si, section) in chunk.sections.iter().enumerate() {
|
||||
if !section.blocks.maybe_has(is_conduit) {
|
||||
continue;
|
||||
}
|
||||
for i in 0..4096 {
|
||||
if is_conduit(section.get(i)) {
|
||||
found.push([
|
||||
cx * 16 + (i & 15) as i32,
|
||||
horizon_client::chunk::MIN_Y + si as i32 * 16 + (i >> 8) as i32,
|
||||
cz * 16 + ((i >> 4) & 15) as i32,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut old = std::mem::take(&mut self.be_anims.conduit_servers);
|
||||
for pos in found {
|
||||
let known = old.remove(&pos).unwrap_or_default();
|
||||
self.be_anims.conduit_servers.insert(pos, known);
|
||||
}
|
||||
}
|
||||
/// `ConduitBlockEntity.serverTick` of the conduit at `pos`, in a chunk
|
||||
/// that ticks blocks: the shape check every 40 ticks with its sounds, the
|
||||
/// power for players in range, the hurt for an enemy, then the ambient
|
||||
/// sounds.
|
||||
fn tick_conduit_server(&mut self, pos: [i32; 3]) {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]).0;
|
||||
if self.be_anims.ticker(state) != Some(Ticker::Conduit) {
|
||||
// Broken since the chunks were searched.
|
||||
self.be_anims.conduit_servers.remove(&pos);
|
||||
return;
|
||||
}
|
||||
if !self.tickets.levels().block_ticking_at(pos[0], pos[2])
|
||||
|| !self.border.contains(f64::from(pos[0]), f64::from(pos[2]))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let time = self.world.game_time;
|
||||
let mut conduit = self
|
||||
.be_anims
|
||||
.conduit_servers
|
||||
.remove(&pos)
|
||||
.unwrap_or_default();
|
||||
let check = {
|
||||
let world = &self.world;
|
||||
let facts = self.res.facts();
|
||||
let registry = self.pack.assets.registry;
|
||||
let frames = self
|
||||
.res
|
||||
.items()
|
||||
.block_tags
|
||||
.get("minecraft:conduit_effect_block");
|
||||
// Level.isWaterAt: the fluid at the position is water.
|
||||
let is_water = |p: [i32; 3]| {
|
||||
facts.get(world.block(p[0], p[1], p[2])).fluid
|
||||
== horizon_client::blocks::Fluid::Water
|
||||
};
|
||||
let is_frame = |p: [i32; 3]| {
|
||||
registry
|
||||
.state(world.block(p[0], p[1], p[2]))
|
||||
.is_some_and(|s| frames.is_some_and(|f| f.contains(&s.name)))
|
||||
};
|
||||
conduit.check(pos, time, is_water, is_frame)
|
||||
};
|
||||
let centre = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
if let Some(check) = check {
|
||||
if let Some(active) = check.toggled {
|
||||
let sound = if active {
|
||||
"minecraft:block.conduit.activate"
|
||||
} else {
|
||||
"minecraft:block.conduit.deactivate"
|
||||
};
|
||||
self.audio.play(sound, Some(centre), 1.0, 1.0);
|
||||
}
|
||||
if let Some(frames) = check.frames {
|
||||
self.conduit_apply_effects(pos, frames);
|
||||
self.conduit_attack(&mut conduit, pos, frames >= 42);
|
||||
}
|
||||
}
|
||||
let (ambient, short) = conduit.ambient(time, &mut self.world.random);
|
||||
if ambient {
|
||||
self.audio
|
||||
.play("minecraft:block.conduit.ambient", Some(centre), 1.0, 1.0);
|
||||
}
|
||||
if short {
|
||||
self.audio.play(
|
||||
"minecraft:block.conduit.ambient_short",
|
||||
Some(centre),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
self.be_anims.conduit_servers.insert(pos, conduit);
|
||||
}
|
||||
/// `ConduitBlockEntity.applyEffects`: conduit power for every player
|
||||
/// in water or rain within `frames / 7 * 16` blocks.
|
||||
fn conduit_apply_effects(&mut self, pos: [i32; 3], frames: usize) {
|
||||
let range = (frames / 7 * 16) as i64;
|
||||
self.for_each_player(|g| {
|
||||
let Some(p) = g.player.as_ref().filter(|p| !p.health.dead_or_dying()) else {
|
||||
return;
|
||||
};
|
||||
if g.spectator() {
|
||||
return;
|
||||
}
|
||||
let at = p.position;
|
||||
let in_water = p.fluids.was_touching_water;
|
||||
let top = at.y + f64::from(p.dimensions.height);
|
||||
// BlockPos.closerThan: the squared distance under range squared.
|
||||
let d = [at.x, at.y, at.z]
|
||||
.map(|v| v.floor() as i64)
|
||||
.iter()
|
||||
.zip(pos)
|
||||
.map(|(a, b)| (a - i64::from(b)).pow(2))
|
||||
.sum::<i64>();
|
||||
if d >= range * range || !(in_water || g.in_rain(at, top)) {
|
||||
return;
|
||||
}
|
||||
let power = EffectInstance {
|
||||
ambient: true,
|
||||
..EffectInstance::new("conduit_power", 260, 0)
|
||||
};
|
||||
g.potions.effects.add(power);
|
||||
});
|
||||
}
|
||||
/// `Entity.isInRain`: rain at the block position or at the top of the box.
|
||||
pub(super) fn in_rain(&mut self, at: Vec3, top: f64) -> bool {
|
||||
let p = BlockPos::new(
|
||||
at.x.floor() as i32,
|
||||
at.y.floor() as i32,
|
||||
at.z.floor() as i32,
|
||||
);
|
||||
let up = BlockPos::new(p.x, top.floor() as i32, p.z);
|
||||
self.with_level(|b, level, _| b.is_raining_at(level, p) || b.is_raining_at(level, up))
|
||||
}
|
||||
/// `ConduitBlockEntity.updateAndAttackTarget`: while the conduit hunts
|
||||
/// (42 frame blocks) its target stays until it dies or leaves the 8
|
||||
/// blocks, else a random enemy in water or rain is chosen; the target
|
||||
/// takes 4 magic damage.
|
||||
fn conduit_attack(&mut self, conduit: &mut ConduitServer, pos: [i32; 3], hunting: bool) {
|
||||
conduit.target = match conduit.target {
|
||||
_ if !hunting => None,
|
||||
None => self.conduit_new_target(pos),
|
||||
Some(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id && !m.removed)
|
||||
.filter(|m| {
|
||||
let at = [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i64);
|
||||
m.alive()
|
||||
&& at
|
||||
.iter()
|
||||
.zip(pos)
|
||||
.map(|(a, b)| (a - i64::from(b)).pow(2))
|
||||
.sum::<i64>()
|
||||
< 64
|
||||
})
|
||||
.map(|m| m.id),
|
||||
};
|
||||
let Some(m) = conduit
|
||||
.target
|
||||
.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
m.damage(4.0, Damage::of(DamageKind::Magic));
|
||||
self.audio
|
||||
.play("minecraft:block.conduit.attack.target", Some(at), 1.0, 1.0);
|
||||
}
|
||||
/// `ConduitBlockEntity.selectNewTarget`: one of the enemies in water or
|
||||
/// rain whose box meets the conduit's block inflated by 8.
|
||||
fn conduit_new_target(&mut self, pos: [i32; 3]) -> Option<u32> {
|
||||
let [x, y, z] = pos.map(f64::from);
|
||||
let area = Aabb::new(
|
||||
Vec3::new(x - 8.0, y - 8.0, z - 8.0),
|
||||
Vec3::new(x + 9.0, y + 9.0, z + 9.0),
|
||||
);
|
||||
let near: Vec<(u32, bool, Vec3, f64)> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| m.hostile() && !m.removed && m.bounds().intersects(area))
|
||||
.map(|m| {
|
||||
let top = m.position.y + f64::from(m.height());
|
||||
(m.id, m.fluids.in_water, m.position, top)
|
||||
})
|
||||
.collect();
|
||||
let candidates: Vec<u32> = near
|
||||
.into_iter()
|
||||
.filter(|&(_, in_water, at, top)| in_water || self.in_rain(at, top))
|
||||
.map(|(id, ..)| id)
|
||||
.collect();
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let pick = self
|
||||
.world
|
||||
.random
|
||||
.next_int_bound(candidates.len() as i32)
|
||||
.unwrap_or(0);
|
||||
Some(candidates[pick as usize])
|
||||
}
|
||||
/// The conduit's `destroyTarget` as the client draws it.
|
||||
fn conduit_target(&self, pos: [i32; 3]) -> Option<ConduitTarget> {
|
||||
let id = self.be_anims.conduit_servers.get(&pos)?.target?;
|
||||
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
|
||||
Some(ConduitTarget {
|
||||
position: [m.position.x, m.position.y, m.position.z],
|
||||
eye_y: m.eye_y(),
|
||||
width: m.width(),
|
||||
height: m.height(),
|
||||
})
|
||||
}
|
||||
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
|
||||
/// gateways a server keeps a copy of, in block-ticking chunks
|
||||
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
|
||||
@@ -474,21 +731,38 @@ impl Game<'_> {
|
||||
/// the player head at `pos`. The skin download is started here; while it
|
||||
/// is in flight (or when it cannot be got) the profile's default skin
|
||||
/// stands in. A head with no profile answers None: `SKIN_BY_TYPE`.
|
||||
pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> {
|
||||
pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<String> {
|
||||
let Some(BlockEntity::Skull(skull)) =
|
||||
self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let skin = skull.skin.as_ref()?;
|
||||
if let Some((url, location)) = &skin.download {
|
||||
self.skin_downloads
|
||||
.borrow_mut()
|
||||
.state(skins::Kind::Skin, url);
|
||||
if self.gui.atlas.sprites.contains_key(location) {
|
||||
// The texture a packed or resolved `textures` property fetches: the
|
||||
// download of a static profile, or the one the services answer for a
|
||||
// `Dynamic` (name- or id-only) profile.
|
||||
let download = skin.download.clone().or_else(|| {
|
||||
let key = skin.dynamic.as_ref()?;
|
||||
let skins::Resolve::Done(Some(profile)) = self.skin_profiles.borrow_mut().state(key)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let (value, signature) = profile.textures()?;
|
||||
let url = skins::unpack(&value, signature, &skins::TEXTURE_URIS).skin?;
|
||||
let location = skins::skin_location(&skins::texture_hash(&url)?);
|
||||
Some((url, location))
|
||||
});
|
||||
if let Some((url, location)) = download {
|
||||
let mut downloads = self.skin_downloads.borrow_mut();
|
||||
if self.gui.atlas.sprites.contains_key(&location) {
|
||||
let _ = downloads.state(skins::Kind::Skin, &url);
|
||||
return Some(location);
|
||||
}
|
||||
// Its slot was evicted: offer the image again.
|
||||
if downloads.state(skins::Kind::Skin, &url) == skins::Download::Ready {
|
||||
downloads.again(&location);
|
||||
}
|
||||
}
|
||||
Some(skin.fallback)
|
||||
Some(skin.fallback.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use horizon_client::{
|
||||
block_entities::{Pos, Ticking},
|
||||
containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS},
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_world::registry::BlockStateId;
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -56,6 +57,7 @@ impl Game<'_> {
|
||||
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
|
||||
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
|
||||
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
|
||||
Some(BlockEntity::DaylightDetector) => self.tick_daylight_detector(pos),
|
||||
Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
|
||||
_ => {}
|
||||
}
|
||||
@@ -94,6 +96,7 @@ impl Game<'_> {
|
||||
| "minecraft:beehive"
|
||||
| "minecraft:bee_nest"
|
||||
| "minecraft:brewing_stand"
|
||||
| "minecraft:daylight_detector"
|
||||
// Lit, cookTick; unlit, cooldownTick.
|
||||
| "minecraft:campfire"
|
||||
| "minecraft:soul_campfire" => Ticking::Yes,
|
||||
@@ -117,6 +120,16 @@ impl Game<'_> {
|
||||
let levels = self.tickets.levels();
|
||||
move |x, z| levels.block_ticking_at(x, z)
|
||||
}
|
||||
/// `DaylightDetectorBlock.tickEntity` of the detector at `pos`.
|
||||
fn tick_daylight_detector(&mut self, pos: Pos) {
|
||||
// It updates every 20 game ticks (the behaviour checks this too).
|
||||
if self.world.game_time % 20 != 0 {
|
||||
return;
|
||||
}
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
self.with_level(|b, level, ticks| b.tick_daylight_detector(level, ticks, at));
|
||||
let _ = self.process_level_events();
|
||||
}
|
||||
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
|
||||
/// its block's `lit` following it.
|
||||
fn tick_furnace(&mut self, pos: Pos) -> Result<()> {
|
||||
|
||||
@@ -862,7 +862,7 @@ impl Game<'_> {
|
||||
let a = alpha as f32;
|
||||
let range = super::entity_culling::default_range(
|
||||
glam::DVec3::new(WIDTH, HEIGHT, WIDTH),
|
||||
self.settings.entity_distance,
|
||||
self.view_scale(),
|
||||
);
|
||||
for b in &self.boats {
|
||||
let entity_start = out.len();
|
||||
|
||||
@@ -8,7 +8,7 @@ use horizon_client::{
|
||||
containers::{BlockEntity, Lectern},
|
||||
first_person::Hand,
|
||||
hud::{HudBatch, rgba},
|
||||
item_data::WrittenBook,
|
||||
item_data::{StackData, WrittenBook},
|
||||
items::ItemStack,
|
||||
menu::{Kind, Menu},
|
||||
text::Text,
|
||||
@@ -59,14 +59,86 @@ pub(super) enum BookScreen {
|
||||
page_edit: ui::EditBox,
|
||||
},
|
||||
View {
|
||||
pages: Vec<String>,
|
||||
pages: Vec<Text>,
|
||||
page: usize,
|
||||
lectern: Option<(i32, i32, i32)>,
|
||||
},
|
||||
}
|
||||
/// The pages a book screen reads: a written book's components (so their
|
||||
/// click events stay), else a writable book's text.
|
||||
fn view_pages(data: Option<&StackData>) -> Vec<Text> {
|
||||
let Some(data) = data else { return Vec::new() };
|
||||
let Some(w) = &data.written else {
|
||||
return data.writable_pages.iter().map(Text::literal).collect();
|
||||
};
|
||||
let tagged = w.page_tags.len() == w.pages.len();
|
||||
w.pages
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, page)| match tagged.then(|| &w.page_tags[i]) {
|
||||
Some(tag @ horizon_world::nbt::Tag::Compound(_)) => {
|
||||
horizon_client::entity_nbt::name_text(tag)
|
||||
}
|
||||
_ => Text::literal(page),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
impl Game<'_> {
|
||||
fn book_lines(&self, page: &str) -> Vec<Text> {
|
||||
self.gui.atlas.font.split(&Text::literal(page), 114.0)
|
||||
self.page_lines(&Text::literal(page))
|
||||
}
|
||||
fn page_lines(&self, page: &Text) -> Vec<Text> {
|
||||
self.gui.atlas.font.split(page, 114.0)
|
||||
}
|
||||
/// `BookViewScreen.mouseClicked`: the click event of the text under the
|
||||
/// cursor on the page.
|
||||
fn book_link_at(&self, page: &Text, left: f32) -> Option<horizon_client::text::ClickEvent> {
|
||||
let (mx, my) = self.cursor;
|
||||
let row = ((my - 32.0) / 9.0).floor();
|
||||
if row < 0.0 || row >= LINES as f32 {
|
||||
return None;
|
||||
}
|
||||
let lines = self.page_lines(page);
|
||||
let line = lines.get(row as usize)?.resolve_legacy();
|
||||
let mut x = mx - (left + 36.0);
|
||||
if x < 0.0 {
|
||||
return None;
|
||||
}
|
||||
for (c, style) in line.chars() {
|
||||
x -= self.gui.atlas.font.advance(c, style);
|
||||
if x < 0.0 {
|
||||
return style.click.clone();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `BookViewScreen.handleClickEvent`: a page link turns to its page
|
||||
/// (`forcePage`), a web link goes through the confirm-link flow.
|
||||
fn book_follow_link(
|
||||
&mut self,
|
||||
link: horizon_client::text::ClickEvent,
|
||||
count: usize,
|
||||
lectern: Option<(i32, i32, i32)>,
|
||||
) {
|
||||
use horizon_client::text::ClickEvent;
|
||||
match link {
|
||||
ClickEvent::ChangePage(target) => {
|
||||
let target = (target - 1).clamp(0, count.saturating_sub(1) as i32);
|
||||
let Some(BookScreen::View { page, .. }) = self.book.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if let Some(key) = lectern {
|
||||
// LecternScreen.forcePage: the menu's button 100 + page.
|
||||
if target != *page as i32 {
|
||||
self.lectern_button(key, 100 + target);
|
||||
}
|
||||
} else if target != *page as i32 {
|
||||
*page = target as usize;
|
||||
}
|
||||
}
|
||||
ClickEvent::OpenUrl(url) => self.click_url(url),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`).
|
||||
/// A server's player writes in its own client's editor
|
||||
@@ -115,11 +187,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
"minecraft:written_book" => BookScreen::View {
|
||||
pages: stack
|
||||
.data()
|
||||
.and_then(|d| d.written.as_ref())
|
||||
.map(|w| w.pages.clone())
|
||||
.unwrap_or_default(),
|
||||
pages: view_pages(stack.data()),
|
||||
page: 0,
|
||||
lectern: None,
|
||||
},
|
||||
@@ -215,6 +283,7 @@ impl Game<'_> {
|
||||
author,
|
||||
generation: 0,
|
||||
pages,
|
||||
page_tags: Vec::new(),
|
||||
});
|
||||
*stack = written;
|
||||
} else {
|
||||
@@ -685,11 +754,7 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
let Some(book) = &l.book else { return false };
|
||||
let data = book.data();
|
||||
let pages = data
|
||||
.and_then(|d| d.written.as_ref().map(|w| w.pages.clone()))
|
||||
.or_else(|| data.map(|d| d.writable_pages.clone()))
|
||||
.unwrap_or_default();
|
||||
let pages = view_pages(book.data());
|
||||
let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
|
||||
self.stats.custom("interact_with_lectern", 1);
|
||||
self.open_book(BookScreen::View {
|
||||
@@ -811,11 +876,7 @@ impl Game<'_> {
|
||||
page,
|
||||
}) = self.book.as_mut()
|
||||
{
|
||||
let data = book.as_ref().and_then(ItemStack::data);
|
||||
*pages = data
|
||||
.and_then(|d| d.written.as_ref().map(|w| w.pages.clone()))
|
||||
.or_else(|| data.map(|d| d.writable_pages.clone()))
|
||||
.unwrap_or_default();
|
||||
*pages = view_pages(book.as_ref().and_then(ItemStack::data));
|
||||
*page = (*page).min(pages.len().saturating_sub(1));
|
||||
}
|
||||
}
|
||||
@@ -955,7 +1016,10 @@ impl Game<'_> {
|
||||
lectern,
|
||||
}) => {
|
||||
let (page, count, lectern) = (*page, pages.len(), *lectern);
|
||||
if page + 1 < count && inside(left + 116.0, 159.0, 23.0, 13.0) {
|
||||
// The text's click event first, then the buttons.
|
||||
if let Some(link) = pages.get(page).and_then(|t| self.book_link_at(t, left)) {
|
||||
self.book_follow_link(link, count, lectern);
|
||||
} else if page + 1 < count && inside(left + 116.0, 159.0, 23.0, 13.0) {
|
||||
self.turn_page(true);
|
||||
} else if page > 0 && inside(left + 43.0, 159.0, 23.0, 13.0) {
|
||||
self.turn_page(false);
|
||||
@@ -1009,9 +1073,12 @@ impl Game<'_> {
|
||||
}
|
||||
};
|
||||
let indicator = |batch: &mut HudBatch, page: usize, count: usize| {
|
||||
let text = tr("book.pageIndicator", "Page %s of %s")
|
||||
.replacen("%s", &(page + 1).to_string(), 1)
|
||||
.replacen("%s", &count.max(1).to_string(), 1);
|
||||
// BookViewScreen.getPageNumberMessage: 26.3's en_us template is
|
||||
// positional ("Page %1$s of %2$s").
|
||||
let text = horizon_protocol::text::format_java(
|
||||
&tr("book.pageIndicator", "Page %1$s of %2$s"),
|
||||
&[(page + 1).to_string(), count.max(1).to_string()],
|
||||
);
|
||||
let tw = HudBatch::text_width(atlas, &text);
|
||||
batch.text(atlas, &text, left + 148.0 - tw, top + 16.0, BLACK, false);
|
||||
};
|
||||
@@ -1195,7 +1262,7 @@ impl Game<'_> {
|
||||
} => {
|
||||
indicator(batch, *page, pages.len());
|
||||
if let Some(text) = pages.get(*page) {
|
||||
for (i, line) in self.book_lines(text).iter().take(LINES).enumerate() {
|
||||
for (i, line) in self.page_lines(text).iter().take(LINES).enumerate() {
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
line,
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! `BundleMouseActions`: the wheel over a bundle in a container screen selects
|
||||
//! one of the items it shows, which a click that takes one out of it then takes
|
||||
//! (`BundleContents.Mutable.removeOne`). Moving off the bundle clears the
|
||||
//! selection. On a server the selection is sent to it (`ServerboundSelectBundleItemPacket`).
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
bundle::{Contents, toggle_selected},
|
||||
mouse::ScrollWheelHandler,
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Serverbound as S};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BundleMouse {
|
||||
wheel: ScrollWheelHandler,
|
||||
/// The slot under the cursor at the last tick (`AbstractContainerScreen.hoveredSlot`).
|
||||
hovered: Option<usize>,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A slot a bundle can be selected in: the player's inventory, the off hand and a
|
||||
/// container's own slots. A server only knows these in the inventory and chest-like menus.
|
||||
fn bundle_slot(&mut self, slot: usize) -> bool {
|
||||
(slot < 36 || slot == 504 || (300..500).contains(&slot))
|
||||
&& (self.remote.is_none() || self.remote_storage_open())
|
||||
&& (slot < 36 || slot == 504 || self.slots().contains(&slot))
|
||||
}
|
||||
|
||||
/// `BundleMouseActions.onMouseScrolled`: the wheel over a bundle moves the selection
|
||||
/// through the items its tooltip shows. True when the bundle took the wheel.
|
||||
pub(super) fn bundle_scroll(&mut self, x: f64, y: f64) -> bool {
|
||||
let Some(slot) = self.inventory_target().0 else {
|
||||
return false;
|
||||
};
|
||||
if !self.bundle_slot(slot) {
|
||||
return false;
|
||||
}
|
||||
let stack = self.slot_mut(slot).clone();
|
||||
let items = self.res.items();
|
||||
let Some(bundle) = stack.filter(|s| items.get(&s.item).is_some_and(|i| i.bundle)) else {
|
||||
return false;
|
||||
};
|
||||
let shown = Contents::of(items, &bundle).map_or(0, |c| c.shown_count());
|
||||
if shown == 0 {
|
||||
return false;
|
||||
}
|
||||
let (wheel_x, wheel_y) = self.bundle_mouse.wheel.on_mouse_scroll(x, y);
|
||||
let wheel = if wheel_y == 0 { -wheel_x } else { wheel_y };
|
||||
if wheel != 0 {
|
||||
let selected = bundle.data().map_or(-1, |d| d.bundle_selected.0);
|
||||
let next = ScrollWheelHandler::next_selection(f64::from(wheel), selected, shown as i32);
|
||||
if next != selected {
|
||||
self.select_bundle(slot, next);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `BundleMouseActions.toggleSelectedBundleItem`: the stack here and, on a server, there.
|
||||
fn select_bundle(&mut self, slot: usize, index: i32) {
|
||||
if let Some(stack) = self.slot_mut(slot) {
|
||||
toggle_selected(stack, index);
|
||||
}
|
||||
if self.remote.is_some() {
|
||||
let (_, menu) = self.remote_menu();
|
||||
if let Some(menu_slot) = Self::menu_slot_index(&menu, slot) {
|
||||
self.send(S::SelectBundleItem(play::SelectBundleItem {
|
||||
slot: menu_slot as i32,
|
||||
index,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `BundleMouseActions.unselectedBundleItem` for the bundle in `slot`, if it has a selection.
|
||||
pub(super) fn unselect_bundle(&mut self, slot: usize) {
|
||||
if !self.bundle_slot(slot) {
|
||||
return;
|
||||
}
|
||||
let selected = self
|
||||
.slot_mut(slot)
|
||||
.as_ref()
|
||||
.and_then(|s| s.data())
|
||||
.is_some_and(|d| d.bundle_selected.0 >= 0);
|
||||
if selected {
|
||||
self.select_bundle(slot, -1);
|
||||
}
|
||||
}
|
||||
|
||||
/// `AbstractContainerScreen.onStopHovering` (and `onClose`): leaving a slot, or the
|
||||
/// screen, clears the bundle's selection.
|
||||
pub(super) fn tick_bundle_hover(&mut self) {
|
||||
let now = if self.screen == Screen::Inventory {
|
||||
self.inventory_target().0
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(left) = std::mem::replace(&mut self.bundle_mouse.hovered, now)
|
||||
&& Some(left) != now
|
||||
{
|
||||
self.unselect_bundle(left);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -695,12 +695,78 @@ impl Game<'_> {
|
||||
Some(ClickEvent::OpenFile(path)) => {
|
||||
super::packs::open_folder(std::path::Path::new(&path));
|
||||
}
|
||||
Some(ClickEvent::OpenUrl(url)) => self.click_url(url),
|
||||
Some(ClickEvent::SuggestCommand(command)) => {
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
screen.suggest_command(&m, &c, &command);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
// Screen.defaultHandleClickEvent: a page link means nothing in chat.
|
||||
Some(ClickEvent::ChangePage(_)) | None => {}
|
||||
}
|
||||
}
|
||||
/// `Screen.clickUrlAction`: nothing with Web Links off, else the link
|
||||
/// opens, after the confirmation unless Prompt on Links is off.
|
||||
pub(super) fn click_url(&mut self, url: String) {
|
||||
if !self.settings.chat_links {
|
||||
return;
|
||||
}
|
||||
if self.settings.file.bool("chatLinksPrompt") {
|
||||
self.link_prompt = Some(url);
|
||||
} else {
|
||||
super::packs::open_uri(&url);
|
||||
}
|
||||
}
|
||||
/// `ConfirmLinkScreen` (untrusted): the link and its warning over the
|
||||
/// chat, answered yes to open it.
|
||||
fn link_prompt_layout(
|
||||
&self,
|
||||
url: &str,
|
||||
size: (f32, f32),
|
||||
) -> horizon_client::confirm_screen::Confirm {
|
||||
let warning = Text::translate("chat.link.warning", &[]).with_color(0xFF_CCCC);
|
||||
let message = Text::literal(url)
|
||||
.append(Text::literal("\n"))
|
||||
.append(warning);
|
||||
horizon_client::confirm_screen::Confirm::new(
|
||||
&self.gui.atlas.font,
|
||||
size,
|
||||
&Text::translate("chat.link.confirm", &[]),
|
||||
&message,
|
||||
)
|
||||
}
|
||||
pub(super) fn draw_link_prompt(&self, batch: &mut HudBatch) {
|
||||
let Some(url) = &self.link_prompt else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.gui.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
horizon_client::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
|
||||
let (yes, no) = (
|
||||
Text::translate("gui.yes", &[]),
|
||||
Text::translate("gui.no", &[]),
|
||||
);
|
||||
self.link_prompt_layout(url, (w, h))
|
||||
.draw(batch, atlas, self.cursor, [&yes, &no]);
|
||||
}
|
||||
/// The prompt's answer: the link opens on yes; either way the chat is back.
|
||||
pub(super) fn answer_link_prompt(&mut self, yes: bool) {
|
||||
if let Some(url) = self.link_prompt.take()
|
||||
&& yes
|
||||
{
|
||||
super::packs::open_uri(&url);
|
||||
}
|
||||
}
|
||||
pub(super) fn link_prompt_click(&mut self) {
|
||||
let Some(url) = &self.link_prompt else {
|
||||
return;
|
||||
};
|
||||
let answer = self
|
||||
.link_prompt_layout(url, self.gui_size())
|
||||
.answer_at(self.cursor);
|
||||
if let Some(yes) = answer {
|
||||
self.audio.play_button_click();
|
||||
self.answer_link_prompt(yes);
|
||||
}
|
||||
}
|
||||
/// Chat lines over the HUD (focused while the chat screen is open).
|
||||
@@ -789,6 +855,11 @@ impl Game<'_> {
|
||||
pub(super) fn sync_rules(&mut self) {
|
||||
self.world.health_rules.natural_regeneration =
|
||||
self.ui.rules.bool("natural_health_regeneration");
|
||||
// Player.isInvulnerableTo: the damage-type rules.
|
||||
self.world.health_rules.drowning_damage = self.ui.rules.bool("drowning_damage");
|
||||
self.world.health_rules.fall_damage = self.ui.rules.bool("fall_damage");
|
||||
self.world.health_rules.fire_damage = self.ui.rules.bool("fire_damage");
|
||||
self.world.health_rules.freeze_damage = self.ui.rules.bool("freeze_damage");
|
||||
use horizon_world::food::Difficulty;
|
||||
self.world.health_rules.difficulty = match self.ui.difficulty {
|
||||
0 => Difficulty::Peaceful,
|
||||
@@ -801,7 +872,11 @@ impl Game<'_> {
|
||||
pub(super) fn load_world_state(&mut self) {
|
||||
self.ui.rules = GameRules::load(&self.world_root);
|
||||
self.ui.clock = WorldClock::default();
|
||||
self.ui.difficulty = read_difficulty(&self.world_root).unwrap_or(2);
|
||||
// PrimaryLevelData: the difficulty comes back from level.dat's difficulty_settings.
|
||||
self.ui.difficulty = horizon_client::title::DIFFICULTIES
|
||||
.iter()
|
||||
.position(|d| *d == self.level.difficulty)
|
||||
.map_or(2, |i| i as u8);
|
||||
if let Ok(bytes) = std::fs::read(self.world_root.join("data/minecraft/world_clocks.dat"))
|
||||
&& let Ok(raw) = horizon_world::compression::Compression::Gzip.decode(&bytes, 1 << 20)
|
||||
&& let Ok((root, _)) =
|
||||
@@ -826,9 +901,9 @@ impl Game<'_> {
|
||||
self.build_registries();
|
||||
self.sync_rules();
|
||||
}
|
||||
/// Save the clock and the difficulty beside level.dat (Level.write saves
|
||||
/// the game rules: a second writer of game_rules.dat could leave it with
|
||||
/// the rules loaded when the world opened).
|
||||
/// Save the clock beside level.dat (Level.write saves the game rules: a
|
||||
/// second writer of game_rules.dat could leave it with the rules loaded
|
||||
/// when the world opened).
|
||||
pub(super) fn save_world_state(&mut self) {
|
||||
if self.world_root.as_os_str().is_empty() {
|
||||
return;
|
||||
@@ -876,9 +951,6 @@ impl Game<'_> {
|
||||
if let Err(e) = horizon_client::save::write_dat(&path, root) {
|
||||
log::warn!("the world clocks were not written: {e}");
|
||||
}
|
||||
if let Err(e) = write_difficulty(&self.world_root, self.ui.difficulty) {
|
||||
log::warn!("the difficulty was not written: {e}");
|
||||
}
|
||||
}
|
||||
/// Death message in chat (CombatTracker.getDeathMessage, as far as the
|
||||
/// cause is known to the client).
|
||||
@@ -988,34 +1060,6 @@ pub fn screenshot_name(dir: &std::path::Path) -> String {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
fn read_difficulty(world: &std::path::Path) -> Option<u8> {
|
||||
let bytes = std::fs::read(world.join("level.dat")).ok()?;
|
||||
let raw = horizon_world::compression::Compression::Gzip
|
||||
.decode(&bytes, 64 << 20)
|
||||
.ok()?;
|
||||
let (root, _) =
|
||||
horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()).ok()?;
|
||||
match root.tag.get("Data")?.get("Difficulty")? {
|
||||
horizon_world::nbt::Tag::Byte(b) => Some((*b).clamp(0, 3) as u8),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Patch `Data.Difficulty` in level.dat (Level::write stores the default).
|
||||
fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client::Result<()> {
|
||||
use horizon_world::{compression::Compression, nbt};
|
||||
let path = world.join("level.dat");
|
||||
let bytes = std::fs::read(&path)?;
|
||||
let raw = Compression::Gzip.decode(&bytes, 64 << 20)?;
|
||||
let (mut root, _) = nbt::read_named(&raw, nbt::Limits::default()).map_err(|e| e.to_string())?;
|
||||
if let Some(data) = root.tag.get_mut("Data")
|
||||
&& let Some(d) = data.get_mut("Difficulty")
|
||||
{
|
||||
*d = nbt::Tag::Byte(difficulty as i8);
|
||||
}
|
||||
let out = nbt::write_named(&root, nbt::Limits::default()).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&path, Compression::Gzip.encode(&out)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `IntegratedServer.getProfilePermissions` for the owner: `OWNER` (4) when
|
||||
/// commands are allowed, else `ALL` (0).
|
||||
|
||||
@@ -4,8 +4,12 @@
|
||||
//! on the game that has the window, in-frame or following a server, never on
|
||||
//! a server: nothing of them goes over the network.
|
||||
use super::Game;
|
||||
use horizon_client::blocks::RenderShape;
|
||||
use horizon_client::mobs::{MobEvent, ambient};
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
use horizon_client::motion::{LAVA, WATER};
|
||||
use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType};
|
||||
use horizon_client::pose::Pose;
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn tick_client_ambient(&mut self) {
|
||||
@@ -33,5 +37,209 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.eye_particles();
|
||||
self.sprint_dust();
|
||||
self.effect_swirls();
|
||||
}
|
||||
|
||||
/// `Entity.baseTick`'s `spawnSprintParticle` on a client: dust of the
|
||||
/// block under a sprinting player's feet streams back from them every
|
||||
/// tick, for the window's own player and for the other players it sees.
|
||||
fn sprint_dust(&mut self) {
|
||||
// Each runner's feet, movement and supporting block.
|
||||
let mut runners: Vec<(Vec3, Vec3, Option<[i32; 3]>)> = Vec::new();
|
||||
// Entity.canSpawnSprintParticle.
|
||||
if let Some(p) = self.player.as_ref()
|
||||
&& p.sprinting
|
||||
&& !p.spectator
|
||||
&& p.pose != Pose::Crouching
|
||||
&& !p.health.dead_or_dying()
|
||||
&& !p.fluids.was_touching_water
|
||||
&& !p.is_in_lava()
|
||||
&& p.fluid_height(WATER) <= 0.0
|
||||
&& p.fluid_height(LAVA) <= 0.0
|
||||
{
|
||||
let support = p.ground.supporting_block.map(|b| [b.x, b.y, b.z]);
|
||||
runners.push((p.position, p.velocity, support));
|
||||
}
|
||||
let guests = self.lan.iter().flat_map(|host| host.models.values());
|
||||
for m in self.mobs.iter().chain(guests) {
|
||||
// Another player's fluids aren't known here: none where they stand.
|
||||
let feet = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
if m.extra.sprinting
|
||||
&& !m.extra.crouching
|
||||
&& m.alive()
|
||||
&& &*m.kind.id == "minecraft:player"
|
||||
&& self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(feet[0], feet[1], feet[2]))
|
||||
.fluid_level
|
||||
== 0
|
||||
{
|
||||
runners.push((m.position, m.position.subtract(m.previous), None));
|
||||
}
|
||||
}
|
||||
for (position, movement, support) in runners {
|
||||
// Entity.getOnPosLegacy: getOnPos(0.2).
|
||||
let below = (position.y - f64::from(0.2f32)).floor() as i32;
|
||||
let tall = |game: &Self, s: [i32; 3]| {
|
||||
let name = game.block_name(s);
|
||||
[
|
||||
"minecraft:fences",
|
||||
"minecraft:walls",
|
||||
"minecraft:fence_gates",
|
||||
]
|
||||
.iter()
|
||||
.any(|tag| game.block_in_tag(tag, &name))
|
||||
};
|
||||
let at = match support {
|
||||
Some(s) if tall(self, s) => s,
|
||||
Some(s) => [s[0], below, s[2]],
|
||||
None => [position.x.floor() as i32, below, position.z.floor() as i32],
|
||||
};
|
||||
let state = self.world.block(at[0], at[1], at[2]);
|
||||
if self.res.facts().get(state).render_shape == RenderShape::Invisible {
|
||||
continue;
|
||||
}
|
||||
let Some((sprite, tint)) = self.particle_sprite(state, at) else {
|
||||
continue;
|
||||
};
|
||||
let width = f64::from(0.6f32);
|
||||
let r = self.particles.random();
|
||||
let mut x = position.x + (r.next_double() - 0.5) * width;
|
||||
let mut z = position.z + (r.next_double() - 0.5) * width;
|
||||
// Clamped into the block when the feet are in another column.
|
||||
if position.x.floor() as i32 != at[0] {
|
||||
x = x.clamp(f64::from(at[0]), f64::from(at[0]) + 1.0);
|
||||
}
|
||||
if position.z.floor() as i32 != at[2] {
|
||||
z = z.clamp(f64::from(at[2]), f64::from(at[2]) + 1.0);
|
||||
}
|
||||
self.particles.add(
|
||||
&ParticleOptions::block(ParticleType::Block, sprite, tint),
|
||||
[x, position.y + 0.1, z],
|
||||
[movement.x * -4.0, 1.5, movement.z * -4.0],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `LivingEntity.tickEffects` on a client: the swirls around an entity
|
||||
/// with visible effects, from the particles its synched data lists. The
|
||||
/// window's player has its own effects, a server's mobs and players the
|
||||
/// list the server sent, and the mobs and guests of a game in the frame
|
||||
/// theirs.
|
||||
fn effect_swirls(&mut self) {
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let effects = &self.potions.effects.list;
|
||||
let list: Vec<_> = effects
|
||||
.iter()
|
||||
.filter(|e| e.visible)
|
||||
.filter_map(|e| effect_particle(e.id, e.ambient))
|
||||
.collect();
|
||||
let ambient = effects.iter().filter(|e| e.visible).all(|e| e.ambient);
|
||||
let invisible = effects.iter().any(|e| e.id == "invisibility");
|
||||
let size = (
|
||||
f64::from(p.dimensions.width),
|
||||
f64::from(p.dimensions.height),
|
||||
);
|
||||
swirl(
|
||||
&mut self.particles,
|
||||
p.position,
|
||||
size,
|
||||
&list,
|
||||
ambient,
|
||||
invisible,
|
||||
);
|
||||
}
|
||||
let guests = self.lan.iter().flat_map(|host| host.models.values());
|
||||
for m in self.mobs.iter().chain(guests) {
|
||||
if !m.alive() {
|
||||
continue;
|
||||
}
|
||||
let size = (f64::from(m.width()), f64::from(m.height()));
|
||||
let invisible = m.invisible || m.has_effect("minecraft:invisibility");
|
||||
if m.extra.effect_particles.is_empty() {
|
||||
// A mob of this game: its own effects, visible and not ambient.
|
||||
if m.extra.effects.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let list: Vec<_> = m
|
||||
.extra
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|e| !m.extra.hidden_effects.contains(&e.0))
|
||||
.filter_map(|e| effect_particle(e.0, false))
|
||||
.collect();
|
||||
swirl(
|
||||
&mut self.particles,
|
||||
m.position,
|
||||
size,
|
||||
&list,
|
||||
false,
|
||||
invisible,
|
||||
);
|
||||
} else {
|
||||
let list = &m.extra.effect_particles;
|
||||
let ambient = m.extra.effect_ambient;
|
||||
swirl(
|
||||
&mut self.particles,
|
||||
m.position,
|
||||
size,
|
||||
list,
|
||||
ambient,
|
||||
invisible,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `MobEffect.particleFactory`: the omens have particles of their own, any
|
||||
/// other effect an entity effect in its colour, faint when ambient.
|
||||
pub(super) fn effect_particle(effect: &str, ambient: bool) -> Option<ParticleOptions> {
|
||||
Some(match effect.trim_start_matches("minecraft:") {
|
||||
"trial_omen" => ParticleOptions::simple(ParticleType::TrialOmen),
|
||||
"raid_omen" => ParticleOptions::simple(ParticleType::RaidOmen),
|
||||
other => {
|
||||
let color = horizon_client::brewing::effect(other)?.color;
|
||||
let channel = |shift: u32| ((color >> shift) & 255) as f32 / 255.0;
|
||||
// MobEffect.AMBIENT_ALPHA is 38 of 255.
|
||||
let alpha = if ambient { 38.0 / 255.0 } else { 1.0 };
|
||||
ParticleOptions::colored(
|
||||
ParticleType::EntityEffect,
|
||||
[channel(16), channel(8), channel(0), alpha],
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// One tick of `LivingEntity.tickEffects`' client branch: a one in four
|
||||
/// chance (one in fifteen while invisible, a fifth of either when all the
|
||||
/// effects are ambient) of one of the particles at a random spot of the box.
|
||||
fn swirl(
|
||||
particles: &mut ParticleEngine,
|
||||
feet: Vec3,
|
||||
size: (f64, f64),
|
||||
list: &[ParticleOptions],
|
||||
ambient: bool,
|
||||
invisible: bool,
|
||||
) {
|
||||
if list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let bound = if invisible { 15 } else { 4 } * if ambient { 5 } else { 1 };
|
||||
let r = particles.random();
|
||||
let Ok(0) = r.next_int_bound(bound) else {
|
||||
return;
|
||||
};
|
||||
// Util.getRandom, then getRandomX(0.5), getRandomY and getRandomZ.
|
||||
let pick = r.next_int_bound(list.len() as i32).unwrap_or_default() as usize;
|
||||
let x = feet.x + size.0 * (2.0 * r.next_double() - 1.0) * 0.5;
|
||||
let y = feet.y + size.1 * r.next_double();
|
||||
let z = feet.z + size.0 * (2.0 * r.next_double() - 1.0) * 0.5;
|
||||
particles.add(&list[pick], [x, y, z], [1.0; 3]);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
//! The player's `CombatTracker`: the damage taken lately, who dealt it and
|
||||
//! where the player fell from, turned into the vanilla death message.
|
||||
use super::{Game, chat::PLAYER_NAME};
|
||||
use horizon_client::{health::HealthEvent, motion::MotionEvent, text::Text};
|
||||
use horizon_client::{
|
||||
health::HealthEvent,
|
||||
motion::MotionEvent,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
/// `EntityEvent.DROWN_PARTICLES`: broadcast with the drowning damage.
|
||||
pub(super) const DROWN_EVENT: i8 = 67;
|
||||
|
||||
struct Entry {
|
||||
damage_type: String,
|
||||
@@ -10,6 +19,9 @@ struct Entry {
|
||||
fall_distance: f32,
|
||||
/// The causing entity: its id (for comparisons) and display name.
|
||||
attacker: Option<(u32, Text)>,
|
||||
/// The direct entity's display name when no entity caused the damage
|
||||
/// (`DamageSource.directEntity`: a potion with no thrower, a cloud).
|
||||
direct: Option<Text>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct CombatTracker {
|
||||
@@ -19,6 +31,8 @@ pub(super) struct CombatTracker {
|
||||
/// Attackers of damage dealt this tick, claimed by the matching
|
||||
/// `RecordedDamage` event.
|
||||
pending: Vec<(String, (u32, Text))>,
|
||||
/// `pending` for a direct entity with no causing entity: only its name.
|
||||
pending_direct: Vec<(String, Text)>,
|
||||
/// `LivingEntity.lastHurtByMob` and its timestamp (the kill credit).
|
||||
last_hurt_by: Option<((u32, Text), i64)>,
|
||||
/// The mob the player last hurt (`getLastHurtMob`) and when.
|
||||
@@ -31,11 +45,54 @@ pub(super) struct CombatTracker {
|
||||
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
|
||||
/// fire decides whom the blast may hurt.
|
||||
pub(super) explosion_source: Option<u32>,
|
||||
/// The blast now going off comes from a primed TNT, creeper, wither
|
||||
/// skull, wither or TNT minecart, the sources that empty a hive they
|
||||
/// destroy (`BeehiveBlock.getDrops`).
|
||||
pub(super) hive_emptying_blast: bool,
|
||||
/// The mob that owns the projectile exploding now (`getIndirectSourceEntity`):
|
||||
/// the mobs the blast hurts record it as their attacker.
|
||||
pub(super) explosion_owner: Option<u32>,
|
||||
/// Charged creepers whose blast just went off and that have not dropped
|
||||
/// a head yet (`Creeper.droppedSkulls`): they are gone from the mob list,
|
||||
/// but the mobs they killed still ask for their loot.
|
||||
pub(super) charged_exploders: Vec<u32>,
|
||||
/// The player's fall distance before this tick's movement (as of the
|
||||
/// end of the last one).
|
||||
fall_before: f64,
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `LivingEntity.makeDrownParticles`: eight bubbles around the entity,
|
||||
/// moving with it.
|
||||
pub(super) fn drown_particles(&mut self, at: [f64; 3], velocity: [f64; 3]) {
|
||||
let bubble = ParticleOptions::simple(ParticleType::Bubble);
|
||||
for _ in 0..8 {
|
||||
let mut triangle = || {
|
||||
let r = self.particles.random();
|
||||
r.next_double() - r.next_double()
|
||||
};
|
||||
let p = [at[0] + triangle(), at[1] + triangle(), at[2] + triangle()];
|
||||
self.particles.add(&bubble, p, velocity);
|
||||
}
|
||||
}
|
||||
/// Entity event 67 from a server, for this client's own player or an
|
||||
/// entity it draws.
|
||||
pub(super) fn remote_drown(&mut self, id: i32) {
|
||||
let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id);
|
||||
let body = if own {
|
||||
self.player.as_ref().map(|p| {
|
||||
let (at, v) = (p.position, p.velocity);
|
||||
([at.x, at.y, at.z], [v.x, v.y, v.z])
|
||||
})
|
||||
} else {
|
||||
self.mobs.iter().find(|m| m.id == id as u32).map(|m| {
|
||||
let (at, v) = (m.position, m.velocity);
|
||||
([at.x, at.y, at.z], [v.x, v.y, v.z])
|
||||
})
|
||||
};
|
||||
if let Some((at, v)) = body {
|
||||
self.drown_particles(at, v);
|
||||
}
|
||||
}
|
||||
/// The display name of a mob: its custom name or its type's name.
|
||||
pub(super) fn mob_display_name(&self, id: u32) -> Option<Text> {
|
||||
let m = self.mobs.iter().find(|m| m.id == id)?;
|
||||
@@ -62,17 +119,38 @@ impl Game<'_> {
|
||||
.pending
|
||||
.push((damage_type.to_owned(), (id, name)));
|
||||
}
|
||||
/// The `DamageSource.directEntity` of the next `damage_type` damage when
|
||||
/// nothing caused it (a splash potion nobody threw): the death message
|
||||
/// names it instead (`getLocalizedDeathMessage`). It is no kill credit.
|
||||
pub(super) fn note_direct_entity(&mut self, damage_type: &str, name: Text) {
|
||||
self.combat
|
||||
.pending_direct
|
||||
.push((damage_type.to_owned(), name));
|
||||
}
|
||||
/// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the
|
||||
/// source's `DamageEffects` (`Player.getHurtSound`).
|
||||
pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) {
|
||||
let pitch = self.audio.hurt_pitch();
|
||||
self.audio.play(sound, Some(at), 1.0, pitch);
|
||||
// Player.getVoicePitch: always 1.0.
|
||||
self.audio.play(sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
/// `CombatTracker.recordDamage` for the motion events of this tick.
|
||||
pub(super) fn record_combat(&mut self, events: &[MotionEvent]) {
|
||||
self.recheck_combat();
|
||||
for e in events {
|
||||
let (name, amount) = match e {
|
||||
// LivingEntity.getDamageAfterMagicAbsorb (Resistance) and
|
||||
// Player.actuallyHurt (absorption hearts) and
|
||||
// LivingEntity.hurtServer (the shield, only for an accepted
|
||||
// hit), in tenths.
|
||||
MotionEvent::Health(HealthEvent::Statistic { name, amount }) => {
|
||||
match *name {
|
||||
"resisted" => self.stats.custom("damage_resisted", *amount),
|
||||
"absorbed" => self.stats.custom("damage_absorbed", *amount),
|
||||
"blocked" => self.stats.custom("damage_blocked_by_shield", *amount),
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
MotionEvent::Health(HealthEvent::RecordedDamage { source, amount }) => {
|
||||
let Some(d) = self.motion.health.damage.definition(*source) else {
|
||||
continue;
|
||||
@@ -90,6 +168,15 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.position(|(t, _)| *t == name)
|
||||
.map(|i| self.combat.pending.remove(i).1);
|
||||
let direct = match attacker {
|
||||
Some(_) => None,
|
||||
None => self
|
||||
.combat
|
||||
.pending_direct
|
||||
.iter()
|
||||
.position(|(t, _)| *t == name)
|
||||
.map(|i| self.combat.pending_direct.remove(i).1),
|
||||
};
|
||||
let (fall_location, fall_distance) = self.fall_location();
|
||||
let now = self.world.game_time;
|
||||
if let Some(a) = &attacker {
|
||||
@@ -107,10 +194,16 @@ impl Game<'_> {
|
||||
fall_location,
|
||||
fall_distance,
|
||||
attacker,
|
||||
direct,
|
||||
});
|
||||
self.combat.last_damage = now;
|
||||
// InfestedMobEffect.onMobHurt.
|
||||
if self.potions.effects.get("infested").is_some() {
|
||||
self.player_infested();
|
||||
}
|
||||
}
|
||||
self.combat.pending.clear();
|
||||
self.combat.pending_direct.clear();
|
||||
self.combat.fall_before = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
|
||||
}
|
||||
/// `FallLocation.getCurrentFallLocation` and the fall distance so far.
|
||||
@@ -220,6 +313,7 @@ impl Game<'_> {
|
||||
let entries = std::mem::take(&mut self.combat.entries);
|
||||
let killing = entries.last().expect("checked above");
|
||||
let killer = killing.attacker.clone();
|
||||
let direct = killing.direct.clone();
|
||||
if def.1 == "fall_variants"
|
||||
&& let Some(knock) = knock.and_then(|i| entries.get(i))
|
||||
{
|
||||
@@ -244,15 +338,22 @@ impl Game<'_> {
|
||||
.append(Text::literal("]"));
|
||||
return Text::translate(&format!("{key}.message"), &[me, link]);
|
||||
}
|
||||
// `getLocalizedDeathMessage`: the causing entity's name, or the
|
||||
// direct entity's when nothing caused the damage.
|
||||
if let Some((_, name)) = killer {
|
||||
return Text::translate(&key, &[me, name]);
|
||||
}
|
||||
if let Some(name) = direct {
|
||||
return Text::translate(&key, &[me, name]);
|
||||
}
|
||||
// getKillCredit: the last mob that hurt the player in the past 100 ticks.
|
||||
if let Some(((_, name), at)) = &self.combat.last_hurt_by
|
||||
&& self.world.game_time - at <= 100
|
||||
{
|
||||
return Text::translate(&format!("{key}.player"), &[me, name.clone()]);
|
||||
}
|
||||
// No entity at all: the one-argument message, as vanilla sends it (a
|
||||
// template that names a killer then shows as written).
|
||||
Text::translate(&key, &[me])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand`
|
||||
//! through the command system with the block's output, and
|
||||
//! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it.
|
||||
use super::{Game, Screen, commands::execute::Source};
|
||||
use super::{Game, Screen, commands::execute::Source, lan::LanHost};
|
||||
use horizon_client::{
|
||||
command_block::{self, CommandBlock, Mode},
|
||||
containers::BlockEntity,
|
||||
@@ -12,6 +12,7 @@ use horizon_client::{
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_protocol::packets::play::{self, Serverbound as S};
|
||||
use horizon_world::{
|
||||
chunk::BlockState,
|
||||
level::flags,
|
||||
@@ -35,6 +36,16 @@ pub(super) struct CommandBlockScreen {
|
||||
auto: bool,
|
||||
}
|
||||
|
||||
/// What `ServerboundSetCommandBlockPacket` carries.
|
||||
struct CommandBlockEdit {
|
||||
pos: Pos,
|
||||
command: String,
|
||||
track_output: bool,
|
||||
mode: Mode,
|
||||
conditional: bool,
|
||||
auto: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Button {
|
||||
Output,
|
||||
@@ -186,6 +197,18 @@ impl Game<'_> {
|
||||
pub(super) fn can_use_game_master_blocks(&self) -> bool {
|
||||
self.creative && self.ui.registries.permission >= 2
|
||||
}
|
||||
/// `CommandBlock.useWithoutItem` on a server's client, which opens the
|
||||
/// screen itself (`Player.openCommandBlock`) while the server only
|
||||
/// answers the click: the block at `pos`, when it is a command block the
|
||||
/// player may edit.
|
||||
pub(super) fn open_command_block_if_editable(&mut self, pos: Pos) {
|
||||
let is_command_block = self
|
||||
.block_state_at(pos)
|
||||
.is_some_and(|state| Mode::of_block(&state.name).is_some());
|
||||
if is_command_block && self.can_use_game_master_blocks() {
|
||||
self.open_command_block(pos);
|
||||
}
|
||||
}
|
||||
fn command_block(&self, pos: Pos) -> Option<&CommandBlock> {
|
||||
match self.world.block_entities.get(&pos)? {
|
||||
BlockEntity::CommandBlock(c) => Some(c),
|
||||
@@ -572,12 +595,66 @@ impl Game<'_> {
|
||||
s.command.insert_text(&allowed);
|
||||
}
|
||||
}
|
||||
/// `ServerGamePacketListenerImpl.handleSetCommandBlock`.
|
||||
/// The edit screen's Done: a server's client sends the packet, the
|
||||
/// window's own world applies it (`handleSetCommandBlock`).
|
||||
fn set_command_block(&mut self, s: &CommandBlockScreen) {
|
||||
if !self.can_use_game_master_blocks() {
|
||||
self.system_message(Text::translate("advMode.notAllowed", &[]));
|
||||
return;
|
||||
}
|
||||
let edit = CommandBlockEdit {
|
||||
pos: s.pos,
|
||||
command: s.command.value.clone(),
|
||||
track_output: s.track_output,
|
||||
mode: s.mode,
|
||||
conditional: s.conditional,
|
||||
auto: s.auto,
|
||||
};
|
||||
if self.remote.is_some() {
|
||||
self.send(S::SetCommandBlock(play::SetCommandBlock {
|
||||
pos: [edit.pos.0, edit.pos.1, edit.pos.2],
|
||||
command: edit.command,
|
||||
mode: edit.mode.ordinal(),
|
||||
flags: i8::from(edit.track_output)
|
||||
| (i8::from(edit.conditional) << 1)
|
||||
| (i8::from(edit.auto) << 2),
|
||||
}));
|
||||
} else {
|
||||
self.apply_command_block(&edit);
|
||||
}
|
||||
}
|
||||
/// `ServerGamePacketListenerImpl.handleSetCommandBlock` for a guest: the
|
||||
/// block is edited only by a creative player with game master commands.
|
||||
pub(super) fn lan_set_command_block(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: play::SetCommandBlock,
|
||||
) {
|
||||
let Some(g) = host.hub.guest(conn) else {
|
||||
return;
|
||||
};
|
||||
let allowed = g.creative() && g.permission >= 2;
|
||||
let edit = CommandBlockEdit {
|
||||
pos: (p.pos[0], p.pos[1], p.pos[2]),
|
||||
command: p.command,
|
||||
track_output: p.flags & 1 != 0,
|
||||
mode: Mode::from_ordinal(p.mode),
|
||||
conditional: p.flags & 2 != 0,
|
||||
auto: p.flags & 4 != 0,
|
||||
};
|
||||
self.as_guest(host, conn, |game| {
|
||||
if allowed {
|
||||
game.apply_command_block(&edit);
|
||||
// BaseCommandBlock.onUpdated: the clients get the new command.
|
||||
game.mark_block_entity_updated(edit.pos);
|
||||
} else {
|
||||
game.system_message(Text::translate("advMode.notAllowed", &[]));
|
||||
}
|
||||
});
|
||||
}
|
||||
/// What `handleSetCommandBlock` does once the player may edit the block.
|
||||
fn apply_command_block(&mut self, s: &CommandBlockEdit) {
|
||||
let pos = s.pos;
|
||||
let registry = self.pack.assets.registry;
|
||||
let Some(current) = self.block_state_at(pos) else {
|
||||
@@ -609,7 +686,7 @@ impl Game<'_> {
|
||||
}
|
||||
let _ = self.process_level_events();
|
||||
}
|
||||
let command = s.command.value.clone();
|
||||
let command = s.command.clone();
|
||||
let Some(c) = command_block_mut(&mut self.world, pos) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -42,9 +42,10 @@ pub(super) enum Target {
|
||||
Guest(u32),
|
||||
Mob(u32),
|
||||
Item(u32),
|
||||
Orb(usize),
|
||||
/// By index in `creatures.projectiles`.
|
||||
Projectile(usize),
|
||||
/// An experience orb, by its entity id.
|
||||
Orb(u32),
|
||||
/// A projectile, by its entity id.
|
||||
Projectile(u32),
|
||||
Stand(u32),
|
||||
Frame(u32),
|
||||
Painting(u32),
|
||||
@@ -53,6 +54,10 @@ pub(super) enum Target {
|
||||
/// An entity of a type Horizon does not simulate (markers, displays,
|
||||
/// interactions...): kept as its saved data at a position.
|
||||
Other(u32),
|
||||
/// An End crystal, by its entity id (`minecraft:end_crystal`).
|
||||
Crystal(u32),
|
||||
/// The Ender Dragon, by its entity id (`minecraft:ender_dragon`).
|
||||
Dragon(u32),
|
||||
}
|
||||
/// An entity of a type Horizon does not simulate: its compound lives in the
|
||||
/// entity memory (`persist.raw`), its position and rotation here.
|
||||
@@ -340,14 +345,16 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|i| i.id == id)
|
||||
.map(|i| [i.position.x, i.position.y, i.position.z]),
|
||||
Target::Orb(i) => self
|
||||
Target::Orb(id) => self
|
||||
.orbs
|
||||
.get(i)
|
||||
.iter()
|
||||
.find(|o| o.id == id)
|
||||
.map(|o| [o.position.x, o.position.y, o.position.z]),
|
||||
Target::Projectile(i) => self
|
||||
Target::Projectile(id) => self
|
||||
.creatures
|
||||
.projectiles
|
||||
.get(i)
|
||||
.iter()
|
||||
.find(|a| a.id == id)
|
||||
.map(|a| [a.position.x, a.position.y, a.position.z]),
|
||||
Target::Stand(id) => self
|
||||
.armor_stands
|
||||
@@ -385,6 +392,16 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|o| o.id == id)
|
||||
.map(|o| [o.position.x, o.position.y, o.position.z]),
|
||||
Target::Crystal(id) => self
|
||||
.crystals
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map(|c| [c.position.x, c.position.y, c.position.z]),
|
||||
Target::Dragon(id) => self
|
||||
.dragon
|
||||
.as_ref()
|
||||
.filter(|d| d.id == id)
|
||||
.map(|d| [d.position.x, d.position.y, d.position.z]),
|
||||
}
|
||||
}
|
||||
pub(super) fn target_type(&self, t: Target) -> String {
|
||||
@@ -399,10 +416,11 @@ impl Game<'_> {
|
||||
}),
|
||||
Target::Item(_) => "minecraft:item".into(),
|
||||
Target::Orb(_) => "minecraft:experience_orb".into(),
|
||||
Target::Projectile(i) => self
|
||||
Target::Projectile(id) => self
|
||||
.creatures
|
||||
.projectiles
|
||||
.get(i)
|
||||
.iter()
|
||||
.find(|p| p.id == id)
|
||||
.map_or_else(String::new, |p| p.kind.id().into()),
|
||||
Target::Stand(_) => "minecraft:armor_stand".into(),
|
||||
Target::Frame(id) => {
|
||||
@@ -428,6 +446,8 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|o| o.id == id)
|
||||
.map_or_else(String::new, |o| o.kind.clone()),
|
||||
Target::Crystal(_) => "minecraft:end_crystal".into(),
|
||||
Target::Dragon(_) => "minecraft:ender_dragon".into(),
|
||||
}
|
||||
}
|
||||
/// The name of the player the game acts for: a guest's own while their
|
||||
@@ -512,51 +532,72 @@ impl Game<'_> {
|
||||
s.pos[2].unwrap_or(p[2]),
|
||||
]
|
||||
};
|
||||
let mut candidates: Vec<Target> = Vec::new();
|
||||
let mut source_candidates: Vec<Target> = Vec::new();
|
||||
match (s.kind, self.command_source) {
|
||||
// @s: the executing entity (none for a server source).
|
||||
('s', Some(source)) => candidates.extend(source.entity),
|
||||
('s', None) => candidates.extend(self.source_entity()),
|
||||
('s', Some(source)) => source_candidates.extend(source.entity),
|
||||
('s', None) => source_candidates.extend(self.source_entity()),
|
||||
// A guest in place is among the players, in join order.
|
||||
_ if self.player.is_some() && self.lan_acting.is_none() => {
|
||||
candidates.push(Target::Player);
|
||||
source_candidates.push(Target::Player);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if s.kind != 's' {
|
||||
use horizon_client::projectiles::ProjectileKind as K;
|
||||
candidates.extend(self.player_candidates(s));
|
||||
candidates.extend(
|
||||
self.mobs
|
||||
.iter()
|
||||
.filter(|m| m.death_time == 0)
|
||||
.map(|m| Target::Mob(m.id)),
|
||||
);
|
||||
candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
|
||||
candidates.extend((0..self.orbs.len()).map(Target::Orb));
|
||||
candidates.extend(
|
||||
self.creatures
|
||||
.projectiles
|
||||
.iter()
|
||||
.enumerate()
|
||||
// The kinds /data can write (entity_nbt).
|
||||
.filter(|(_, p)| {
|
||||
p.arrow.is_some()
|
||||
|| matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
|
||||
})
|
||||
.map(|(i, _)| Target::Projectile(i)),
|
||||
);
|
||||
candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
|
||||
candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
|
||||
candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
|
||||
candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id)));
|
||||
candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id)));
|
||||
candidates.extend(self.others.iter().map(|o| Target::Other(o.id)));
|
||||
source_candidates.extend(self.player_candidates(s));
|
||||
}
|
||||
let source_dim = self.dim;
|
||||
// A selector with a spatial constraint reaches the level the command
|
||||
// runs in only; an unbounded one reaches every loaded level
|
||||
// (EntitySelector.findEntities).
|
||||
let dims = if s.world_limited() {
|
||||
vec![source_dim]
|
||||
} else {
|
||||
self.loaded_dims()
|
||||
};
|
||||
let mut out: Vec<(Target, f64)> = Vec::new();
|
||||
for dim in dims {
|
||||
let back = self.enter_command_level(dim);
|
||||
let mut candidates = Vec::new();
|
||||
if dim == source_dim {
|
||||
candidates.append(&mut source_candidates);
|
||||
}
|
||||
if s.kind != 's' {
|
||||
candidates.extend(self.level_candidates());
|
||||
}
|
||||
out.extend(self.select_in_level(candidates, s, origin));
|
||||
if let Some(back) = back {
|
||||
self.enter_command_level(back);
|
||||
}
|
||||
}
|
||||
match s.sort {
|
||||
Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)),
|
||||
Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)),
|
||||
Sort::Random => {
|
||||
for i in (1..out.len()).rev() {
|
||||
let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
|
||||
out.swap(i, j);
|
||||
}
|
||||
}
|
||||
Sort::Arbitrary => {}
|
||||
}
|
||||
out.into_iter()
|
||||
.take(s.limit.max(1))
|
||||
.map(|(t, _)| t)
|
||||
.collect()
|
||||
}
|
||||
/// The candidates of the level in place that pass the selector
|
||||
/// (EntitySelector.getPredicate).
|
||||
fn select_in_level(
|
||||
&mut self,
|
||||
candidates: Vec<Target>,
|
||||
s: &Selector,
|
||||
origin: [f64; 3],
|
||||
) -> Vec<(Target, f64)> {
|
||||
let level = self.experience.level;
|
||||
let creative = self.creative;
|
||||
let passing = self.selector_extra_filter(&candidates, s);
|
||||
let mut out: Vec<(Target, f64)> = candidates
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter_map(|t| {
|
||||
let p = self.target_position(t)?;
|
||||
@@ -628,23 +669,102 @@ impl Game<'_> {
|
||||
}
|
||||
Some((t, d2))
|
||||
})
|
||||
.collect();
|
||||
match s.sort {
|
||||
Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)),
|
||||
Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)),
|
||||
Sort::Random => {
|
||||
for i in (1..out.len()).rev() {
|
||||
let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
|
||||
out.swap(i, j);
|
||||
}
|
||||
}
|
||||
Sort::Arbitrary => {}
|
||||
}
|
||||
out.into_iter()
|
||||
.take(s.limit.max(1))
|
||||
.map(|(t, _)| t)
|
||||
.collect()
|
||||
}
|
||||
/// The entities of the level in place a selector can find.
|
||||
fn level_candidates(&self) -> Vec<Target> {
|
||||
use horizon_client::projectiles::ProjectileKind as K;
|
||||
let mut candidates = Vec::new();
|
||||
candidates.extend(
|
||||
self.mobs
|
||||
.iter()
|
||||
.filter(|m| m.death_time == 0)
|
||||
.map(|m| Target::Mob(m.id)),
|
||||
);
|
||||
candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
|
||||
candidates.extend(self.orbs.iter().map(|o| Target::Orb(o.id)));
|
||||
candidates.extend(
|
||||
self.creatures
|
||||
.projectiles
|
||||
.iter()
|
||||
// The kinds /data can write (entity_nbt).
|
||||
.filter(|p| {
|
||||
p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
|
||||
})
|
||||
.map(|p| Target::Projectile(p.id)),
|
||||
);
|
||||
candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
|
||||
candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
|
||||
candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
|
||||
candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id)));
|
||||
candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id)));
|
||||
candidates.extend(self.others.iter().map(|o| Target::Other(o.id)));
|
||||
// The End crystals and the dragon (EndCrystal and EnderDragon
|
||||
// are entities of their own).
|
||||
candidates.extend(self.crystals.iter().map(|c| Target::Crystal(c.id)));
|
||||
if let Some(d) = &self.dragon {
|
||||
candidates.push(Target::Dragon(d.id));
|
||||
}
|
||||
candidates
|
||||
}
|
||||
/// The loaded levels, in the order the server holds them: the
|
||||
/// overworld, the nether, the end (MinecraftServer.getAllLevels).
|
||||
fn loaded_dims(&self) -> Vec<Dim> {
|
||||
let mut dims = vec![self.dim];
|
||||
dims.extend(self.levels.parked_dims());
|
||||
dims.sort_by_key(|d| match d {
|
||||
Dim::Overworld => 0,
|
||||
Dim::Nether => 1,
|
||||
Dim::End => 2,
|
||||
});
|
||||
dims
|
||||
}
|
||||
/// Whether the level in place holds the entity a target names.
|
||||
fn level_holds(&self, t: Target) -> bool {
|
||||
match t {
|
||||
// A player is in no level of its own.
|
||||
Target::Player | Target::Guest(_) => true,
|
||||
Target::Mob(id) => self.mobs.iter().any(|m| m.id == id),
|
||||
Target::Item(id) => self.dropped.iter().any(|i| i.id == id),
|
||||
Target::Orb(id) => self.orbs.iter().any(|o| o.id == id),
|
||||
Target::Projectile(id) => self.creatures.projectiles.iter().any(|p| p.id == id),
|
||||
Target::Stand(id) => self.armor_stands.iter().any(|a| a.id == id),
|
||||
Target::Frame(id) => self.item_frames.iter().any(|f| f.id == id),
|
||||
Target::Painting(id) => self.paintings.iter().any(|p| p.id == id),
|
||||
Target::Boat(id) => self.boats.iter().any(|b| b.id == id),
|
||||
Target::Cart(id) => self.carts.iter().any(|c| c.id == id),
|
||||
Target::Other(id) => self.others.iter().any(|o| o.id == id),
|
||||
Target::Crystal(id) => self.crystals.iter().any(|c| c.id == id),
|
||||
Target::Dragon(id) => self.dragon.as_ref().is_some_and(|d| d.id == id),
|
||||
}
|
||||
}
|
||||
/// Run `f` with the level that holds the entity a target names in place
|
||||
/// (the entity ids are unique across the loaded levels) and put the
|
||||
/// level back afterwards. `f` does not run when no level holds the
|
||||
/// entity.
|
||||
pub(in crate::game) fn in_target_level<R>(
|
||||
&mut self,
|
||||
t: Target,
|
||||
f: impl FnOnce(&mut Self) -> R,
|
||||
) -> Option<R> {
|
||||
if self.level_holds(t) {
|
||||
return Some(f(self));
|
||||
}
|
||||
for dim in self.levels.parked_dims() {
|
||||
let back = self.enter_command_level(dim);
|
||||
if self.level_holds(t) {
|
||||
let r = f(self);
|
||||
if let Some(back) = back {
|
||||
self.enter_command_level(back);
|
||||
}
|
||||
return Some(r);
|
||||
}
|
||||
if let Some(back) = back {
|
||||
self.enter_command_level(back);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn entity_tag_matches(&self, tag: &str, ty: &str) -> bool {
|
||||
let path = self.options.resources.join(format!(
|
||||
"data/minecraft/tags/entity_type/{}.json",
|
||||
@@ -1104,6 +1224,10 @@ impl Game<'_> {
|
||||
Ok(targets.len() as i32)
|
||||
}
|
||||
fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) {
|
||||
// An entity in another level is teleported in the level that holds it.
|
||||
let _ = self.in_target_level(t, |g| g.teleport_to_in_level(t, pos, rotation));
|
||||
}
|
||||
fn teleport_to_in_level(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) {
|
||||
let v = Vec3::new(pos[0], pos[1], pos[2]);
|
||||
match t {
|
||||
Target::Guest(_) => {
|
||||
@@ -1152,14 +1276,14 @@ impl Game<'_> {
|
||||
i.previous = v;
|
||||
}
|
||||
}
|
||||
Target::Orb(i) => {
|
||||
if let Some(o) = self.orbs.get_mut(i) {
|
||||
Target::Orb(id) => {
|
||||
if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) {
|
||||
o.position = v;
|
||||
o.previous = v;
|
||||
}
|
||||
}
|
||||
Target::Projectile(i) => {
|
||||
if let Some(a) = self.creatures.projectiles.get_mut(i) {
|
||||
Target::Projectile(id) => {
|
||||
if let Some(a) = self.creatures.projectiles.iter_mut().find(|a| a.id == id) {
|
||||
a.position = v;
|
||||
a.previous = v;
|
||||
}
|
||||
@@ -1199,6 +1323,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Crystal(id) => {
|
||||
if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) {
|
||||
c.position = v;
|
||||
}
|
||||
}
|
||||
Target::Dragon(id) => {
|
||||
if let Some(d) = self.dragon.as_mut().filter(|d| d.id == id) {
|
||||
d.position = v;
|
||||
d.previous = v;
|
||||
}
|
||||
}
|
||||
// Wall-mounted entities do not move.
|
||||
Target::Frame(_) | Target::Painting(_) => {}
|
||||
}
|
||||
@@ -1558,6 +1693,10 @@ impl Game<'_> {
|
||||
Ok(duration.unwrap_or(-1))
|
||||
}
|
||||
fn kill_target(&mut self, t: Target) {
|
||||
// An entity in another level is killed in the level that holds it.
|
||||
let _ = self.in_target_level(t, |g| g.kill_target_in_level(t));
|
||||
}
|
||||
fn kill_target_in_level(&mut self, t: Target) {
|
||||
match t {
|
||||
Target::Guest(_) => {
|
||||
self.for_player(t, |g| g.kill_target(Target::Player));
|
||||
@@ -1577,16 +1716,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Target::Item(id) => self.dropped.retain(|i| i.id != id),
|
||||
Target::Orb(i) => {
|
||||
if i < self.orbs.len() {
|
||||
self.orbs[i].age = u32::MAX / 2;
|
||||
Target::Orb(id) => {
|
||||
if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) {
|
||||
o.age = u32::MAX / 2;
|
||||
}
|
||||
}
|
||||
// cmd_kill goes from the highest index down.
|
||||
Target::Projectile(i) => {
|
||||
if i < self.creatures.projectiles.len() {
|
||||
self.creatures.projectiles.remove(i);
|
||||
}
|
||||
Target::Projectile(id) => {
|
||||
self.creatures.projectiles.retain(|p| p.id != id);
|
||||
}
|
||||
Target::Stand(id) => self.armor_stands.retain(|a| a.id != id),
|
||||
Target::Frame(id) => self.item_frames.retain(|f| f.id != id),
|
||||
@@ -1594,7 +1730,11 @@ impl Game<'_> {
|
||||
Target::Boat(id) => self.boats.retain(|b| b.id != id),
|
||||
Target::Cart(id) => self.carts.retain(|c| c.id != id),
|
||||
Target::Other(id) => self.others.retain(|o| o.id != id),
|
||||
Target::Crystal(id) => self.kill_crystal(id),
|
||||
Target::Dragon(id) => self.kill_dragon(id),
|
||||
}
|
||||
// The orbs marked for removal are gone (Entity.kill removes them).
|
||||
self.orbs.retain(|o| o.age < u32::MAX / 2);
|
||||
}
|
||||
fn cmd_kill(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = if ctx.get("targets").is_some() {
|
||||
@@ -1602,19 +1742,18 @@ impl Game<'_> {
|
||||
} else {
|
||||
vec![self.implied_player()]
|
||||
};
|
||||
let names: Vec<Text> = targets.iter().map(|&t| self.target_name(t)).collect();
|
||||
// Remove indexed entities from the back so earlier indices stay valid.
|
||||
let mut ordered = targets.clone();
|
||||
ordered.sort_by_key(|t| {
|
||||
std::cmp::Reverse(match t {
|
||||
Target::Orb(i) | Target::Projectile(i) => *i,
|
||||
_ => 0,
|
||||
})
|
||||
});
|
||||
for t in ordered {
|
||||
let mut names: Vec<Text> = Vec::new();
|
||||
for &t in &targets {
|
||||
// The name of an entity in another level is read there.
|
||||
let name = match self.in_target_level(t, |g| g.target_name(t)) {
|
||||
Some(name) => name,
|
||||
None => self.target_name(t),
|
||||
};
|
||||
names.push(name);
|
||||
}
|
||||
for &t in &targets {
|
||||
self.kill_target(t);
|
||||
}
|
||||
self.orbs.retain(|o| o.age < u32::MAX / 2);
|
||||
let message = if targets.len() == 1 {
|
||||
Text::translate("commands.kill.success.single", &[names[0].clone()])
|
||||
} else {
|
||||
@@ -1697,6 +1836,8 @@ impl Game<'_> {
|
||||
value: 0,
|
||||
age: 0,
|
||||
on_ground: false,
|
||||
count: 1,
|
||||
ticks: 0,
|
||||
});
|
||||
name = Text::translate("entity.minecraft.experience_orb", &[]);
|
||||
}
|
||||
@@ -1704,6 +1845,20 @@ impl Game<'_> {
|
||||
self.spawn_bolt(pos, false);
|
||||
name = Text::translate("entity.minecraft.lightning_bolt", &[]);
|
||||
}
|
||||
"end_crystal" => {
|
||||
// EndCrystal's constructor takes an id from the entity
|
||||
// counter, and the crystal is shown with its base.
|
||||
self.next_entity += 1;
|
||||
self.crystals.push(super::dragon::Crystal {
|
||||
id: self.next_entity,
|
||||
position: Vec3::new(pos[0], pos[1], pos[2]),
|
||||
show_bottom: true,
|
||||
time: self.world.random.next_int_bound(100_000).unwrap_or(0),
|
||||
beam: None,
|
||||
invulnerable: false,
|
||||
});
|
||||
name = Text::translate("entity.minecraft.end_crystal", &[]);
|
||||
}
|
||||
k if super::minecarts::CartKind::from_id(&kind).is_some() => {
|
||||
let cart_kind = super::minecarts::CartKind::from_id(&kind)
|
||||
.unwrap_or(super::minecarts::CartKind::Rideable);
|
||||
@@ -1894,8 +2049,7 @@ impl Game<'_> {
|
||||
return false;
|
||||
}
|
||||
self.world.block_entities.insert(key, new);
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let _ = self.world.set(pos[0], pos[1], pos[2], state);
|
||||
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
|
||||
true
|
||||
}
|
||||
/// RandomizableContainer.tryLoadLootTable for a tag a command gives a
|
||||
|
||||
@@ -31,8 +31,13 @@ fn set_key(tag: &mut Tag, key: &str, value: Tag) {
|
||||
impl Game<'_> {
|
||||
// ---- entity data ---------------------------------------------------
|
||||
|
||||
/// `NbtPredicate.getEntityTagToCompare`: the entity as saved.
|
||||
/// `NbtPredicate.getEntityTagToCompare`: the entity as saved. An entity
|
||||
/// in another level is read in the level that holds it.
|
||||
pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option<Tag> {
|
||||
self.in_target_level(t, |g| g.entity_nbt_in_level(t))
|
||||
.flatten()
|
||||
}
|
||||
fn entity_nbt_in_level(&mut self, t: Target) -> Option<Tag> {
|
||||
let player_uuid = self.level.player_uuid;
|
||||
Some(match t {
|
||||
Target::Guest(_) => {
|
||||
@@ -113,9 +118,11 @@ impl Game<'_> {
|
||||
let o = self.others.iter().find(|o| o.id == id)?.clone();
|
||||
self.other_to_nbt(&o, uuid)
|
||||
}
|
||||
Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
|
||||
Target::Projectile(i) => {
|
||||
let p = self.creatures.projectiles.get(i)?;
|
||||
Target::Orb(id) => {
|
||||
entity_nbt::orb_to_nbt(self.orbs.iter().find(|o| o.id == id)?, random_uuid())
|
||||
}
|
||||
Target::Projectile(id) => {
|
||||
let p = self.creatures.projectiles.iter().find(|p| p.id == id)?;
|
||||
let owner = if p.owner == Some(horizon_client::mobs::Who::Player) {
|
||||
player_uuid
|
||||
} else {
|
||||
@@ -129,6 +136,16 @@ impl Game<'_> {
|
||||
entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None)
|
||||
.or_else(|| entity_nbt::fireball_to_nbt(p, random_uuid(), owner, None))?
|
||||
}
|
||||
Target::Crystal(id) => {
|
||||
let c = self.crystals.iter().find(|c| c.id == id)?;
|
||||
let (uuid, raw) = self.persist_anon("minecraft:end_crystal", c.position);
|
||||
c.to_nbt(uuid.unwrap_or_else(random_uuid), raw)
|
||||
}
|
||||
Target::Dragon(id) => {
|
||||
let d = self.dragon.as_ref().filter(|d| d.id == id)?;
|
||||
let (uuid, raw) = self.persist_anon("minecraft:ender_dragon", d.position);
|
||||
d.to_nbt(uuid.unwrap_or_else(random_uuid), raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
/// `Entity.load` of new data (`EntityDataAccessor.setData`): the entity is
|
||||
@@ -397,6 +414,19 @@ impl Game<'_> {
|
||||
}
|
||||
pub(super) fn cmd_data(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let target = self.data_ref(ctx, 0)?;
|
||||
// An entity in another level is read and written in the level that
|
||||
// holds it.
|
||||
if let DataRef::Entity(t) = &target {
|
||||
let t = *t;
|
||||
let target = target.clone();
|
||||
return match self.in_target_level(t, |g| g.cmd_data_in(id, ctx, target)) {
|
||||
Some(r) => r,
|
||||
None => Err(err("argument.entity.notfound.entity", &[])),
|
||||
};
|
||||
}
|
||||
self.cmd_data_in(id, ctx, target)
|
||||
}
|
||||
fn cmd_data_in(&mut self, id: &str, ctx: &Context, target: DataRef) -> R<i32> {
|
||||
match id {
|
||||
"data.merge" => {
|
||||
let Some(Arg::Str(nbt)) = ctx.get("nbt") else {
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! `/effect` (EffectCommands) and `/enchant` (EnchantCommand).
|
||||
use super::{Arg, Context, Game, R, Target, err, texts};
|
||||
use horizon_client::{
|
||||
brewing,
|
||||
brewing::{self, namespaced},
|
||||
effects::EffectInstance,
|
||||
text::{self, Style, Text},
|
||||
};
|
||||
use std::{collections::HashMap, sync::OnceLock};
|
||||
|
||||
/// `CommandResponseTracker` over targets: elements with a non-zero result.
|
||||
#[derive(Default)]
|
||||
@@ -21,24 +20,6 @@ impl Tracker {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Namespaced effect ids for mob effect storage.
|
||||
fn namespaced(id: &'static str) -> &'static str {
|
||||
static IDS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
|
||||
IDS.get_or_init(|| {
|
||||
brewing::EFFECTS
|
||||
.iter()
|
||||
.map(|e| {
|
||||
(
|
||||
e.id,
|
||||
&*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.get(id)
|
||||
.copied()
|
||||
.unwrap_or(id)
|
||||
}
|
||||
fn effect_name(id: &str) -> Text {
|
||||
Text::translate(&format!("effect.minecraft.{id}"), &[])
|
||||
}
|
||||
@@ -91,7 +72,12 @@ impl Game<'_> {
|
||||
}
|
||||
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
Some(m) => {
|
||||
m.add_effect(namespaced(effect.id), duration, amplifier);
|
||||
let name = namespaced(effect.id);
|
||||
m.add_effect(name, duration, amplifier);
|
||||
m.extra.hidden_effects.retain(|h| *h != name);
|
||||
if !particles {
|
||||
m.extra.hidden_effects.push(name);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
@@ -154,6 +140,10 @@ impl Game<'_> {
|
||||
m.extra
|
||||
.effects
|
||||
.retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id)));
|
||||
let left = &m.extra.effects;
|
||||
m.extra
|
||||
.hidden_effects
|
||||
.retain(|h| left.iter().any(|x| x.0 == *h));
|
||||
m.extra.effects.len() != before
|
||||
}
|
||||
None => false,
|
||||
|
||||
@@ -145,9 +145,42 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map_or(0.0, |m| m.eye_y() - m.position.y),
|
||||
_ => 0.0,
|
||||
// ArmorStand.getDefaultDimensions: a marker's are empty, a small
|
||||
// stand's are BABY_DIMENSIONS, whose eye height is 0.9875F.
|
||||
Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) {
|
||||
Some(a) if a.marker => 0.0,
|
||||
Some(a) if a.small => f64::from(0.9875f32),
|
||||
_ => self.type_eye_height(&self.target_type(t)),
|
||||
},
|
||||
// Entity.getEyeHeight: the type's dimensions.
|
||||
_ => self.type_eye_height(&self.target_type(t)),
|
||||
}
|
||||
}
|
||||
/// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`,
|
||||
/// read once: a float, widened as `Entity.getEyeY` does.
|
||||
fn type_eye_height(&self, ty: &str) -> f64 {
|
||||
static EYE_HEIGHTS: std::sync::OnceLock<std::collections::HashMap<String, f64>> =
|
||||
std::sync::OnceLock::new();
|
||||
EYE_HEIGHTS
|
||||
.get_or_init(|| {
|
||||
std::fs::read(self.options.resources.join("entity-types.json"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
.and_then(|v| {
|
||||
v.as_object().map(|o| {
|
||||
o.iter()
|
||||
.filter_map(|(k, t)| {
|
||||
Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32)))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.get(ty)
|
||||
.copied()
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
/// EntityAnchorArgument.Anchor.apply.
|
||||
pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] {
|
||||
match s.entity {
|
||||
@@ -467,9 +500,10 @@ impl Game<'_> {
|
||||
"positioned" if c.has("as") => targets(self)?
|
||||
.into_iter()
|
||||
.filter_map(|t| {
|
||||
// withPosition keeps the anchor (only `positioned <pos>`
|
||||
// resets it to the feet).
|
||||
Some(Source {
|
||||
pos: self.target_position(t)?,
|
||||
eyes: false,
|
||||
..s
|
||||
})
|
||||
})
|
||||
@@ -606,6 +640,73 @@ impl Game<'_> {
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
// Leashable.getLeashHolder: a fence knot is not an entity here.
|
||||
Some("leasher") => match entity {
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.and_then(|m| m.extra.leash.map(|holder| (holder, m.extra.leash_player)))
|
||||
.and_then(|(holder, player)| match holder {
|
||||
// The player who tied it (the host's when unrecorded).
|
||||
horizon_client::mobs::leash::Holder::Player => {
|
||||
let uuid = player.or(self.level.player_uuid)?;
|
||||
self.target_by_uuid(horizon_client::lan::playerdata::ints_uuid(uuid))
|
||||
}
|
||||
horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)),
|
||||
horizon_client::mobs::leash::Holder::Knot(_) => None,
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
// TraceableEntity.getOwner: who shot a projectile, who threw an
|
||||
// item, who summoned a vex.
|
||||
Some("origin") => match entity {
|
||||
Target::Projectile(id) => self
|
||||
.creatures
|
||||
.projectiles
|
||||
.iter()
|
||||
.find(|p| p.id == id)
|
||||
.and_then(|p| match (p.owner?, p.guest) {
|
||||
// A guest's shot: `Who::Player` is them.
|
||||
(horizon_client::mobs::Who::Player, Some(conn))
|
||||
if self.lan_acting == Some(conn) =>
|
||||
{
|
||||
Some(Target::Player)
|
||||
}
|
||||
(horizon_client::mobs::Who::Player, Some(conn)) => {
|
||||
Some(Target::Guest(conn))
|
||||
}
|
||||
(horizon_client::mobs::Who::Player, None) => Some(Target::Player),
|
||||
(horizon_client::mobs::Who::Mob(id), _) => Some(Target::Mob(id)),
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
Target::Item(id) => self
|
||||
.dropped
|
||||
.iter()
|
||||
.find(|d| d.id == id)
|
||||
.and_then(|d| d.thrower)
|
||||
.and_then(|words| {
|
||||
let uuid = words
|
||||
.iter()
|
||||
.fold(0u128, |all, w| all << 32 | u128::from(*w as u32));
|
||||
self.target_by_uuid(uuid)
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id && m.kind.id == "minecraft:vex")
|
||||
.map(|m| m.extra.counter2 as u32)
|
||||
.filter(|owner| *owner != 0)
|
||||
.map(Target::Mob)
|
||||
.into_iter()
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(),
|
||||
Some("controller") | Some("passengers") => match entity {
|
||||
Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => {
|
||||
@@ -807,10 +908,12 @@ impl Game<'_> {
|
||||
.coords(c, "pos")
|
||||
.map(|co| co.block(self.source_position(), self.source_rotation()));
|
||||
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
|
||||
return Ok(flag(
|
||||
dimension == self.dim
|
||||
&& p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))),
|
||||
));
|
||||
// ExecuteCommand.isChunkLoaded: ENTITY_TICKING, which is past lit.
|
||||
let loaded = |p: [i32; 3]| {
|
||||
let key = (p[0] >> 4, p[2] >> 4);
|
||||
self.world.chunks.contains_key(&key) && self.streaming.is_lit(key.0, key.1)
|
||||
};
|
||||
return Ok(flag(dimension == self.dim && p.is_some_and(loaded)));
|
||||
}
|
||||
if c.has("dimension") {
|
||||
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
|
||||
|
||||
@@ -244,7 +244,11 @@ impl Game<'_> {
|
||||
/// hand them the next jobs as soon as each one is done, rather than once
|
||||
/// a tick.
|
||||
pub(in crate::game) fn pump_pregen(&mut self, until: Instant) {
|
||||
while self.pregen_runs_here() {
|
||||
// Force-loaded chunks too: decorating in vanilla's order, a chunk
|
||||
// waits for its neighbours far more often than once a tick allows.
|
||||
while self.pregen_runs_here()
|
||||
|| (!self.streaming.forced.is_empty() && self.streaming.busy())
|
||||
{
|
||||
let now = Instant::now();
|
||||
if now >= until {
|
||||
break;
|
||||
|
||||
@@ -120,6 +120,9 @@ impl Game<'_> {
|
||||
tracker.track(&holder(chunk_text(x, z)), i32::from(changed));
|
||||
}
|
||||
}
|
||||
if add {
|
||||
self.streaming.rank_forced(cx0, cz0, cx1, cz1);
|
||||
}
|
||||
let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1));
|
||||
let verb = if add { "added" } else { "removed" };
|
||||
let (message, total) = tracker.message(
|
||||
|
||||
@@ -14,10 +14,11 @@ impl Game<'_> {
|
||||
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
|
||||
// NbtContents.resolve: the path's values in the entity, block or
|
||||
// storage data, rich-styled (or plain, or interpreted), ", "-joined.
|
||||
// ScoreContents.resolve: the holder's score in the objective.
|
||||
let nbt_values = std::cell::RefCell::new(Vec::new());
|
||||
{
|
||||
let mut collect = |o: &serde_json::Map<String, serde_json::Value>| {
|
||||
if o.contains_key("nbt") {
|
||||
if o.contains_key("nbt") || o.contains_key("score") {
|
||||
nbt_values.borrow_mut().push(o.clone());
|
||||
}
|
||||
};
|
||||
@@ -40,7 +41,11 @@ impl Game<'_> {
|
||||
}
|
||||
let mut resolved: Vec<(serde_json::Map<String, serde_json::Value>, Text)> = Vec::new();
|
||||
for o in nbt_values.into_inner() {
|
||||
let t = self.resolve_nbt_component(&o);
|
||||
let t = if o.contains_key("score") {
|
||||
self.resolve_score_component(&o)?
|
||||
} else {
|
||||
self.resolve_nbt_component(&o)
|
||||
};
|
||||
resolved.push((o, t));
|
||||
}
|
||||
let mut resolve = |raw: &str| -> Text {
|
||||
@@ -73,6 +78,54 @@ impl Game<'_> {
|
||||
},
|
||||
))
|
||||
}
|
||||
/// The text of a `score` component (ScoreContents.resolve): the named
|
||||
/// holder's score, `*` being the player the command runs for.
|
||||
fn resolve_score_component(
|
||||
&mut self,
|
||||
o: &serde_json::Map<String, serde_json::Value>,
|
||||
) -> R<Text> {
|
||||
let score = o.get("score");
|
||||
let field = |k: &str| score.and_then(|s| s.get(k)).and_then(|v| v.as_str());
|
||||
let (name, objective) = (
|
||||
field("name").unwrap_or(""),
|
||||
field("objective").unwrap_or(""),
|
||||
);
|
||||
// findTargetName: a selector that matches one entity is that entity,
|
||||
// one that matches none is just the name.
|
||||
let mut reader = horizon_client::command::Reader::new(name);
|
||||
let ty = horizon_client::command::args::ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
let mut holder = name.to_owned();
|
||||
if let Ok(Arg::Entity(sel)) = ty.parse(&mut reader, &self.ui.registries)
|
||||
&& !reader.can_read()
|
||||
{
|
||||
let found = self.select(&sel);
|
||||
if found.len() > 1 {
|
||||
return Err(err("argument.entity.toomany", &[]));
|
||||
}
|
||||
if let Some(t) = found.first().and_then(|t| self.holder_name(*t)) {
|
||||
holder = t;
|
||||
}
|
||||
}
|
||||
if holder == "*" {
|
||||
holder = self.acting_player_name().to_owned();
|
||||
}
|
||||
let board = &self.score.board;
|
||||
let (Some(objective), Some(score)) =
|
||||
(board.objective(objective), board.score(&holder, objective))
|
||||
else {
|
||||
return Ok(Text::empty());
|
||||
};
|
||||
// numberFormatOrDefault(StyledFormat.NO_STYLE).
|
||||
let format = (score.number_format.clone())
|
||||
.or_else(|| objective.number_format.clone())
|
||||
.unwrap_or(horizon_client::scoreboard::NumberFormat::Styled(
|
||||
serde_json::json!({}),
|
||||
));
|
||||
Ok(format.format(score.value))
|
||||
}
|
||||
/// The text of an `nbt` component.
|
||||
fn resolve_nbt_component(&mut self, o: &serde_json::Map<String, serde_json::Value>) -> Text {
|
||||
use horizon_world::nbt::Tag;
|
||||
@@ -136,28 +189,40 @@ impl Game<'_> {
|
||||
}
|
||||
out
|
||||
}
|
||||
fn player_targets(&mut self, ctx: &Context) -> R<usize> {
|
||||
// Only the local player can receive messages and titles.
|
||||
/// The players the command reaches: the window's own and the LAN guests.
|
||||
fn player_targets(&mut self, ctx: &Context) -> R<Vec<Target>> {
|
||||
let targets = self.entities(ctx, "targets", true)?;
|
||||
Ok(targets.iter().filter(|t| **t == Target::Player).count())
|
||||
Ok(targets
|
||||
.into_iter()
|
||||
.filter(|t| matches!(t, Target::Player | Target::Guest(_)))
|
||||
.collect())
|
||||
}
|
||||
pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R<i32> {
|
||||
let n = self.player_targets(ctx)?;
|
||||
let players = self.player_targets(ctx)?;
|
||||
let message = self.component_arg(ctx, "message")?;
|
||||
if n > 0 {
|
||||
self.system_message(message);
|
||||
// Each player's chat (a guest's through the connection).
|
||||
for &t in &players {
|
||||
self.for_player(t, |g| g.system_message(message.clone()));
|
||||
}
|
||||
Ok(n as i32)
|
||||
Ok(players.len() as i32)
|
||||
}
|
||||
pub(super) fn cmd_title(&mut self, ctx: &Context) -> R<i32> {
|
||||
let n = self.player_targets(ctx)?;
|
||||
let name = self.target_name(Target::Player);
|
||||
let players = self.player_targets(ctx)?;
|
||||
let n = players.len();
|
||||
let name = players
|
||||
.first()
|
||||
.map_or_else(Text::empty, |t| self.target_name(*t));
|
||||
let single = n == 1;
|
||||
let key = if ctx.has("clear") {
|
||||
self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false }));
|
||||
self.titles_or_packet(
|
||||
&players,
|
||||
Titles::clear,
|
||||
C::ClearTitles(play::Bool1 { value: false }),
|
||||
);
|
||||
"cleared"
|
||||
} else if ctx.has("reset") {
|
||||
self.titles_or_packet(
|
||||
&players,
|
||||
|t| {
|
||||
t.clear();
|
||||
t.reset_times();
|
||||
@@ -172,6 +237,7 @@ impl Game<'_> {
|
||||
};
|
||||
let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut"));
|
||||
self.titles_or_packet(
|
||||
&players,
|
||||
|t| t.set_times(fade_in, stay, fade_out),
|
||||
C::SetTitlesAnimation(play::TitlesAnimation {
|
||||
fade_in,
|
||||
@@ -186,13 +252,17 @@ impl Game<'_> {
|
||||
text: component_nbt(&text.component()),
|
||||
};
|
||||
if ctx.has("subtitle") {
|
||||
self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent));
|
||||
self.titles_or_packet(&players, |t| t.set_subtitle(text), C::SetSubtitleText(sent));
|
||||
"show.subtitle"
|
||||
} else if ctx.has("actionbar") {
|
||||
self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent));
|
||||
self.titles_or_packet(
|
||||
&players,
|
||||
|t| t.set_overlay(text, false),
|
||||
C::SetActionBarText(sent),
|
||||
);
|
||||
"show.actionbar"
|
||||
} else {
|
||||
self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent));
|
||||
self.titles_or_packet(&players, |t| t.set_title(text), C::SetTitleText(sent));
|
||||
"show.title"
|
||||
}
|
||||
};
|
||||
@@ -207,13 +277,27 @@ impl Game<'_> {
|
||||
self.feedback(message);
|
||||
Ok(n as i32)
|
||||
}
|
||||
/// The player the title is for: the guest acting now is sent the packet
|
||||
/// (TitleCommand's `connection.send`), the window's own player shows it.
|
||||
fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) {
|
||||
if self.lan_acting.is_some() {
|
||||
self.guest_packets.push(packet);
|
||||
} else {
|
||||
local(&mut self.titles);
|
||||
/// TitleCommand's `connection.send` for each player: a guest is sent the
|
||||
/// packet, the window's own player shows it.
|
||||
fn titles_or_packet(&mut self, players: &[Target], local: impl FnOnce(&mut Titles), packet: C) {
|
||||
let mut local = Some(local);
|
||||
for &t in players {
|
||||
match t {
|
||||
Target::Player if self.lan_acting.is_some() => {
|
||||
self.guest_packets.push(packet.clone());
|
||||
}
|
||||
Target::Player => {
|
||||
if let Some(local) = local.take() {
|
||||
local(&mut self.titles);
|
||||
}
|
||||
}
|
||||
Target::Guest(conn) => {
|
||||
if let Some(host) = self.lan.as_ref() {
|
||||
host.hub.send_to(conn, &packet);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,9 +115,11 @@ impl Game<'_> {
|
||||
"in_fire" | "campfire" | "hot_floor" => DamageKind::InFire,
|
||||
"lava" => DamageKind::Lava,
|
||||
"drown" => DamageKind::Drown,
|
||||
"dry_out" => DamageKind::DryOut,
|
||||
"magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic,
|
||||
"sting" => DamageKind::Sting,
|
||||
"cactus" | "sweet_berry_bush" => DamageKind::Cactus,
|
||||
"freeze" => DamageKind::Freeze,
|
||||
"in_wall" => DamageKind::InWall,
|
||||
"thorns" => DamageKind::Thorns,
|
||||
_ => DamageKind::Generic,
|
||||
@@ -140,27 +142,37 @@ impl Game<'_> {
|
||||
Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(),
|
||||
_ => None,
|
||||
};
|
||||
let cause = match ctx.get("cause") {
|
||||
Some(Arg::Entity(_)) => self.entities(ctx, "cause", false)?.first().copied(),
|
||||
_ => None,
|
||||
};
|
||||
let from = match ctx.get("location") {
|
||||
Some(Arg::Coords(_)) => self.position_arg(ctx, "location"),
|
||||
_ => by.and_then(|t| self.target_position(t)),
|
||||
};
|
||||
let hurt = match target {
|
||||
// The causing mob is the one the hit is credited to and thorns
|
||||
// answer; the source position gives the knockback its direction.
|
||||
Target::Player => {
|
||||
if self.creative || self.spectator() {
|
||||
// `DamageSource(type, cause, by)`: the death message names the
|
||||
// causing entity, else the direct one. A mob is noted by
|
||||
// `hurt_player_from`, a player here.
|
||||
if let Some(t @ (Target::Player | Target::Guest(_))) = cause.or(by) {
|
||||
let name = self.target_name(t);
|
||||
self.note_direct_entity(&ty, name);
|
||||
}
|
||||
if self.spectator() {
|
||||
false
|
||||
} else if let Some(player) = self.player.as_mut() {
|
||||
match self.motion.health.damage.id(&ty) {
|
||||
Some(id) => player
|
||||
.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false),
|
||||
None => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
let attacker = match cause.or(by) {
|
||||
Some(Target::Mob(i)) => Some(Some(i)),
|
||||
_ => Some(None),
|
||||
};
|
||||
self.hurt_player_from(amount, from, &ty, attacker)
|
||||
}
|
||||
}
|
||||
Target::Mob(id) => {
|
||||
let attacker = by.and_then(|t| match t {
|
||||
let attacker = cause.or(by).and_then(|t| match t {
|
||||
Target::Player => Some(Who::Player),
|
||||
Target::Mob(i) => Some(Who::Mob(i)),
|
||||
_ => None,
|
||||
@@ -301,9 +313,18 @@ impl Game<'_> {
|
||||
float("minVolume", 0.0),
|
||||
);
|
||||
let range = if volume > 1.0 { 16.0 * volume } else { 16.0 };
|
||||
// PlaySoundCommand: one seed for every player.
|
||||
let seed = self.world.random.next_long();
|
||||
let here = self.dim.id();
|
||||
let mut tracker = Tracker::default();
|
||||
for t in targets {
|
||||
if t != Target::Player {
|
||||
if !matches!(t, Target::Player | Target::Guest(_)) {
|
||||
continue;
|
||||
}
|
||||
// Only players in the source's level hear it.
|
||||
if let Target::Guest(conn) = t
|
||||
&& self.command_guest(conn).is_none_or(|g| g.dimension != here)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(p) = self.target_position(t) else {
|
||||
@@ -327,8 +348,26 @@ impl Game<'_> {
|
||||
} else {
|
||||
(pos, volume)
|
||||
};
|
||||
self.audio.play_on(source, &sound, Some(at), v, pitch);
|
||||
tracker.mark(&holder(Text::literal(self.acting_player_name())));
|
||||
// The connection is sent the sound; the window's own player
|
||||
// plays it.
|
||||
let guest = match t {
|
||||
Target::Guest(conn) => Some(conn),
|
||||
_ => self.lan_acting,
|
||||
};
|
||||
match guest.and_then(|conn| Some((conn, self.lan.as_ref()?))) {
|
||||
Some((conn, host)) => {
|
||||
let packet = host
|
||||
.hub
|
||||
.sound_packet(&sound, at, v, pitch, source as i32, seed);
|
||||
if t == Target::Player {
|
||||
self.guest_packets.push(packet);
|
||||
} else {
|
||||
host.hub.send_to(conn, &packet);
|
||||
}
|
||||
}
|
||||
None => self.audio.play_on(source, &sound, Some(at), v, pitch),
|
||||
}
|
||||
tracker.mark(&holder(self.target_name(t)));
|
||||
}
|
||||
let name = Text::literal(sound.clone());
|
||||
let (message, total) = tracker.message(
|
||||
@@ -605,8 +644,10 @@ impl Game<'_> {
|
||||
let reached = reached.len() as i32;
|
||||
if !local {
|
||||
} else if count <= 0 {
|
||||
// No count: one particle with the delta as velocity.
|
||||
self.particles.create(&options, pos, delta);
|
||||
// handleParticleEvent, count 0: one particle, the speed times
|
||||
// the delta as velocity (both sent as floats, multiplied as floats).
|
||||
self.particles
|
||||
.create(&options, pos, delta.map(|d| f64::from(speed * d as f32)));
|
||||
} else {
|
||||
for _ in 0..count {
|
||||
let r = self.particles.random();
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use super::{Game, commands::compute::ComputeContext};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
mobs::villager,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
@@ -86,6 +87,82 @@ impl Game<'_> {
|
||||
self.composter_add(pos, &layers);
|
||||
(stack.count > 0).then_some(stack)
|
||||
}
|
||||
/// `WorkAtComposter.compostItems` for the villager at `mob`: a full
|
||||
/// composter is emptied, then up to 20 wheat or beetroot seeds go in
|
||||
/// (keeping 10 of each kind) until the composter reaches level 7. Level
|
||||
/// event 1500 plays once, at the end.
|
||||
pub(super) fn villager_compost_items(&mut self, mob: usize, pos: [i32; 3]) {
|
||||
let at = BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
let Some(mut before) = self.composter_level(pos) else {
|
||||
return;
|
||||
};
|
||||
if before == 8 {
|
||||
self.with_level(|b, level, ticks| b.composter_extract(level, ticks, at));
|
||||
let _ = self.process_level_events();
|
||||
before = 0;
|
||||
}
|
||||
let mut remaining = 20;
|
||||
let mut amounts: Vec<(std::sync::Arc<str>, i32)> = Vec::new();
|
||||
let slots = villager::ext(&self.mobs[mob]).map_or(0, |e| e.inventory.len());
|
||||
'slots: for slot in (0..slots).rev() {
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
}
|
||||
let stack = villager::ext_mut(&mut self.mobs[mob]).inventory[slot].clone();
|
||||
if !matches!(
|
||||
&*stack.item,
|
||||
"minecraft:wheat_seeds" | "minecraft:beetroot_seeds"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let known = amounts.iter().position(|(item, _)| *item == stack.item);
|
||||
let total = known.map_or(0, |k| amounts[k].1) + stack.count as i32;
|
||||
match known {
|
||||
Some(k) => amounts[k].1 = total,
|
||||
None => amounts.push((stack.item.clone(), total)),
|
||||
}
|
||||
let uses = (total - 10).min(remaining).min(stack.count as i32);
|
||||
if uses <= 0 {
|
||||
continue;
|
||||
}
|
||||
remaining -= uses;
|
||||
for _ in 0..uses {
|
||||
self.villager_insert_item(mob, slot, &stack, pos);
|
||||
if self.composter_level(pos) == Some(7) {
|
||||
break 'slots;
|
||||
}
|
||||
}
|
||||
}
|
||||
let after = self.composter_level(pos).unwrap_or(before);
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.composter_fill_effects(level, ticks, at, after != before)
|
||||
});
|
||||
let _ = self.process_level_events();
|
||||
}
|
||||
/// `ComposterBlock.insertItem` with a villager's stack: below level 7 a
|
||||
/// compostable item is used up and may add a layer.
|
||||
fn villager_insert_item(&mut self, mob: usize, slot: usize, stack: &ItemStack, pos: [i32; 3]) {
|
||||
if self.composter_level(pos).is_none_or(|level| level >= 7) {
|
||||
return;
|
||||
}
|
||||
let Some(layers) = self.compostable(stack) else {
|
||||
return;
|
||||
};
|
||||
let context = ComputeContext {
|
||||
block: Some(pos),
|
||||
target: None,
|
||||
};
|
||||
let layers = self.provider_int(&layers, &context, 0).unwrap_or(0);
|
||||
let at = BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
self.with_level(|b, level, ticks| b.composter_layer(level, ticks, at, layers));
|
||||
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
|
||||
let _ = self.process_level_events();
|
||||
let inventory = &mut villager::ext_mut(&mut self.mobs[mob]).inventory;
|
||||
inventory[slot].count -= 1;
|
||||
if inventory[slot].count == 0 {
|
||||
inventory.remove(slot);
|
||||
}
|
||||
}
|
||||
/// `ComposterBlock.handleFill` (level event 1500) on the client: the
|
||||
/// fill sound and ten composter particles above the compost.
|
||||
pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) {
|
||||
|
||||
@@ -19,7 +19,17 @@ use std::convert::Infallible;
|
||||
|
||||
type ItemConsumable = Consumable<String, ConsumeEffect>;
|
||||
|
||||
/// `EntityEvent.USE_ITEM_COMPLETE`: the server finished the player's use.
|
||||
pub(super) const USE_ITEM_COMPLETE_EVENT: i8 = 9;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `ServerPlayer.completeUsingItem`: the player's own client is told
|
||||
/// first, and completes the use itself (eating the food there too).
|
||||
pub(super) fn send_use_item_complete(&mut self) {
|
||||
if self.lan_acting.is_some() {
|
||||
self.guest_entity_events.push(USE_ITEM_COMPLETE_EVENT);
|
||||
}
|
||||
}
|
||||
/// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`.
|
||||
pub(super) fn emit_consume(
|
||||
&mut self,
|
||||
@@ -57,6 +67,17 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.player.burp", self.feet(), 0.5, pitch);
|
||||
}
|
||||
// SuspiciousStewEffects.onConsume, a ConsumableListener: each entry is
|
||||
// added as a `MobEffectInstance(effect, duration)` (amplifier 0).
|
||||
if let Some(data) = stack.extra.as_deref() {
|
||||
for (id, duration) in &data.stew_effects {
|
||||
if let Some(def) = horizon_client::brewing::effect(id) {
|
||||
self.add_player_effect(horizon_client::effects::EffectInstance::new(
|
||||
def.id, *duration, 0,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for effect in &consumable.effects {
|
||||
self.apply_consume_effect(effect);
|
||||
}
|
||||
|
||||
@@ -628,6 +628,9 @@ impl Game<'_> {
|
||||
// The port, or the game rules' search and number boxes.
|
||||
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
|
||||
Screen::WorldOptions => self.world_options_text(Some(text)),
|
||||
Screen::Inventory if self.mod_browser_typing() => {
|
||||
self.mod_browser_text((text != "\\b").then_some(text), text == "\\b")
|
||||
}
|
||||
Screen::Inventory if self.recipe_search_focused() => {
|
||||
self.recipe_text(Some(text), false)
|
||||
}
|
||||
@@ -875,6 +878,9 @@ impl Game<'_> {
|
||||
Screen::Advancements => "advancements",
|
||||
Screen::WorldOptions => "world-options",
|
||||
Screen::Friends => "friends",
|
||||
Screen::ServerLinks => "server-links",
|
||||
Screen::ConfirmLink => "confirm-link",
|
||||
Screen::DialogWarning => "dialog-warning",
|
||||
Screen::CommandBlock => "command-block",
|
||||
Screen::Win => "win",
|
||||
Screen::Mod => "mod",
|
||||
@@ -1080,6 +1086,9 @@ impl Game<'_> {
|
||||
"flashes": self.lightning_seen[1], "flash": self.flash});
|
||||
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
|
||||
status["projectiles"] = json!(self.projectiles_status());
|
||||
let mut fangs_vertices = Vec::new();
|
||||
self.fangs_geometry(glam::DVec3::ZERO, 0.5, &mut fangs_vertices);
|
||||
status["fangs_vertices"] = json!(fangs_vertices.len());
|
||||
status["maps"] = json!(self.maps_status());
|
||||
// The particles made so far, by type.
|
||||
status["particles"] = json!(self.particles.made());
|
||||
|
||||
@@ -44,13 +44,13 @@ impl Game<'_> {
|
||||
slot: usize,
|
||||
stack: Option<ItemStack>,
|
||||
) {
|
||||
if let Some(e) = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_mut(&(chest[0], chest[1], chest[2]))
|
||||
let key = (chest[0], chest[1], chest[2]);
|
||||
if let Some(e) = self.world.block_entities.get_mut(&key)
|
||||
&& let Some(s) = e.slots_mut().get_mut(slot)
|
||||
{
|
||||
*s = stack;
|
||||
// TransportItemsBetweenContainers calls Container.setChanged.
|
||||
self.container_changed(key);
|
||||
}
|
||||
}
|
||||
/// `ContainerOpenersCounter.recheckOpeners` every five ticks: the golems
|
||||
|
||||
@@ -218,8 +218,9 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
/// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to
|
||||
/// death and a natural heart drops experience.
|
||||
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
|
||||
/// death and a natural heart drops experience. `onExplosionHit` does the
|
||||
/// same for the creaking (`by_player` false), without the experience.
|
||||
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3], by_player: bool) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if !matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
@@ -242,7 +243,7 @@ impl Game<'_> {
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("natural").cloned())
|
||||
.is_some_and(|v| v == "true");
|
||||
if natural && !self.creative && !self.spectator() {
|
||||
if by_player && natural && !self.creative && !self.spectator() {
|
||||
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
|
||||
self.spawn_orbs(
|
||||
[
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,7 @@
|
||||
//! finds the ammo for bows and crossbows.
|
||||
use super::{Game, shield::OFFHAND_SLOT, view_vector};
|
||||
use horizon_client::{
|
||||
enchant::EffectContext,
|
||||
items::ItemStack,
|
||||
mobs::Who,
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
@@ -152,6 +153,20 @@ impl Game<'_> {
|
||||
};
|
||||
let charged = std::mem::take(&mut bow.data_mut().charged);
|
||||
bow.tidy();
|
||||
let weapon = bow.clone();
|
||||
// AbstractArrow's constructor: `getPiercingCount` of the weapon.
|
||||
let pierce = self
|
||||
.res
|
||||
.stations()
|
||||
.enchantments
|
||||
.modify_value(
|
||||
Some(&weapon),
|
||||
"minecraft:projectile_piercing",
|
||||
&EffectContext::default(),
|
||||
&mut self.world.random,
|
||||
0.0,
|
||||
)
|
||||
.clamp(0.0, 127.0) as u8;
|
||||
let count = charged.len();
|
||||
// getShootingPower: a rocket among them slows every shot.
|
||||
let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) {
|
||||
@@ -204,9 +219,10 @@ impl Game<'_> {
|
||||
if let Some(a) = arrow.arrow.as_mut() {
|
||||
a.set_item(ammo);
|
||||
a.set_owner(Some(Who::Player));
|
||||
a.pierce = pierce;
|
||||
}
|
||||
arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
self.add_projectile(arrow);
|
||||
}
|
||||
self.player_projectile_shot();
|
||||
let pitch = if index == 0 {
|
||||
|
||||
@@ -348,11 +348,15 @@ impl Game<'_> {
|
||||
let Some(state) = self.pack.assets.registry.default_state(&name) else {
|
||||
return;
|
||||
};
|
||||
let at = [
|
||||
c.position.x.floor() as i32,
|
||||
c.position.y.floor() as i32,
|
||||
c.position.z.floor() as i32,
|
||||
];
|
||||
let p = c.position;
|
||||
// Entity.getY(2/3) is relative to the cushion's quarter-block height.
|
||||
let particle_at = [p.x, p.y + 0.25 * (2.0 / 3.0), p.z];
|
||||
// Guest actions temporarily take self.lan; flush once the hub is back.
|
||||
// Queue before resolving a sprite: a dedicated server has no renderer.
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_cushion_breaks.push((state, particle_at));
|
||||
}
|
||||
let at = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
|
||||
let Some((sprite, tint)) = self.particle_sprite(state, at) else {
|
||||
return;
|
||||
};
|
||||
@@ -361,14 +365,8 @@ impl Game<'_> {
|
||||
sprite,
|
||||
tint,
|
||||
);
|
||||
let p = c.position;
|
||||
self.particles.send_particles(
|
||||
&options,
|
||||
[p.x, p.y + 0.666_666_7, p.z],
|
||||
[0.25, 0.0625, 0.25],
|
||||
0.05,
|
||||
10,
|
||||
);
|
||||
self.particles
|
||||
.send_particles(&options, particle_at, [0.25, 0.0625, 0.25], 0.05, 10);
|
||||
}
|
||||
|
||||
/// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100.
|
||||
@@ -455,8 +453,7 @@ impl Game<'_> {
|
||||
glam::DVec3::new(lo.x, lo.y, lo.z),
|
||||
glam::DVec3::new(hi.x, hi.y, hi.z),
|
||||
);
|
||||
let range =
|
||||
super::entity_culling::default_range(hi - lo, self.settings.entity_distance);
|
||||
let range = super::entity_culling::default_range(hi - lo, self.view_scale());
|
||||
if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use horizon_client::{
|
||||
save::VERSION_NAME,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::geometry::Axis;
|
||||
use horizon_core::geometry::{Axis, Vec3};
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
/// `ChatFormatting.YELLOW` and `RED`.
|
||||
@@ -766,7 +766,8 @@ impl Game<'_> {
|
||||
}
|
||||
let lerp = |a: f64, b: f64| a + f64::from(alpha) * (b - a);
|
||||
let lerpf = |a: f32, b: f32| a + alpha * (b - a);
|
||||
for m in &self.mobs {
|
||||
let guests = self.lan.iter().flat_map(|h| h.models.values());
|
||||
for m in self.mobs.iter().chain(guests) {
|
||||
if m.removed || m.invisible || m.has_effect("minecraft:invisibility") {
|
||||
continue;
|
||||
}
|
||||
@@ -796,6 +797,159 @@ impl Game<'_> {
|
||||
// EntityType.ITEM: 0.25 by 0.25, eyes at 0.2125.
|
||||
g.hitbox(pos, (0.25, 0.25), 0.2125, false, (0.0, 0.0));
|
||||
}
|
||||
// The other entities (EntityTypes sizes; eyes at 0.85 of the height
|
||||
// unless the type sets one). `at` is the interpolated position.
|
||||
let at = |previous: Vec3, now: Vec3| {
|
||||
[
|
||||
lerp(previous.x, now.x),
|
||||
lerp(previous.y, now.y),
|
||||
lerp(previous.z, now.z),
|
||||
]
|
||||
};
|
||||
for p in &self.paintings {
|
||||
let (min, max) = p.bounds();
|
||||
let centre = std::array::from_fn(|i| (min[i] + max[i]) / 2.0);
|
||||
g.entity_box(min, max, centre, 0.425, false, step_view(p.step()));
|
||||
}
|
||||
for f in self.item_frames.iter().filter(|f| !f.invisible) {
|
||||
let (min, max) = f.bounds();
|
||||
let centre = std::array::from_fn(|i| (min[i] + max[i]) / 2.0);
|
||||
g.entity_box(min, max, centre, 0.0, false, step_view(f.step()));
|
||||
}
|
||||
for c in &self.cushions {
|
||||
let (min, max) = c.bounds();
|
||||
let p = c.position;
|
||||
g.entity_box(min, max, [p.x, p.y, p.z], 0.2125, false, (0.0, c.yaw));
|
||||
}
|
||||
for a in self.armor_stands.iter().filter(|a| !a.invisible) {
|
||||
// ArmorStand.getDimensions: a marker has none, a small one is
|
||||
// half scale with its eyes at 0.9875.
|
||||
let (size, eye) = match (a.marker, a.small) {
|
||||
(true, _) => ((0.0, 0.0), 0.0),
|
||||
(_, true) => ((0.25, 0.9875), 0.9875),
|
||||
_ => ((0.5, 1.975), 1.7775),
|
||||
};
|
||||
let p = a.position;
|
||||
g.hitbox([p.x, p.y, p.z], size, eye, true, (0.0, a.yaw));
|
||||
}
|
||||
for b in &self.boats {
|
||||
let h = super::boats::HEIGHT as f32;
|
||||
g.hitbox(
|
||||
at(b.previous, b.position),
|
||||
(super::boats::WIDTH as f32, h),
|
||||
h,
|
||||
false,
|
||||
(0.0, b.yaw),
|
||||
);
|
||||
}
|
||||
for c in &self.carts {
|
||||
let (w, h) = (
|
||||
super::minecarts::WIDTH as f32,
|
||||
super::minecarts::HEIGHT as f32,
|
||||
);
|
||||
g.hitbox(
|
||||
at(c.previous, c.position),
|
||||
(w, h),
|
||||
h * 0.85,
|
||||
false,
|
||||
(0.0, c.yaw),
|
||||
);
|
||||
}
|
||||
for o in &self.orbs {
|
||||
g.hitbox(
|
||||
at(o.previous, o.position),
|
||||
(0.5, 0.5),
|
||||
0.425,
|
||||
false,
|
||||
(0.0, 0.0),
|
||||
);
|
||||
}
|
||||
for f in &self.falling {
|
||||
g.hitbox(
|
||||
at(f.previous, f.position),
|
||||
(0.98, 0.98),
|
||||
0.833,
|
||||
false,
|
||||
(0.0, 0.0),
|
||||
);
|
||||
}
|
||||
for t in &self.tnts {
|
||||
g.hitbox(
|
||||
at(t.previous, t.position),
|
||||
(0.98, 0.98),
|
||||
0.15,
|
||||
false,
|
||||
(0.0, 0.0),
|
||||
);
|
||||
}
|
||||
for c in &self.crystals {
|
||||
let p = c.position;
|
||||
g.hitbox([p.x, p.y, p.z], (2.0, 2.0), 1.7, false, (0.0, 0.0));
|
||||
}
|
||||
for p in &self.creatures.projectiles {
|
||||
use horizon_client::projectiles::ProjectileKind as K;
|
||||
let (size, eye) = match p.kind {
|
||||
K::Arrow { .. } | K::Trident => (0.5, 0.13),
|
||||
K::Snowball | K::Egg | K::EnderPearl | K::LlamaSpit | K::Potion { .. } => {
|
||||
(0.25, 0.2125)
|
||||
}
|
||||
K::SmallFireball | K::ShulkerBullet { .. } | K::WitherSkull { .. } => {
|
||||
(0.3125, 0.265_625)
|
||||
}
|
||||
K::WindCharge | K::BreezeWindCharge => (0.3125, 0.0),
|
||||
K::LargeFireball { .. } => (1.0, 0.85),
|
||||
};
|
||||
g.hitbox(
|
||||
at(p.previous, p.position),
|
||||
(size, size),
|
||||
eye,
|
||||
false,
|
||||
(p.pitch, p.yaw),
|
||||
);
|
||||
}
|
||||
for t in &self.tridents {
|
||||
g.hitbox(
|
||||
at(t.previous, t.position),
|
||||
(0.5, 0.5),
|
||||
0.13,
|
||||
false,
|
||||
(t.pitch, t.yaw),
|
||||
);
|
||||
}
|
||||
for r in &self.rockets {
|
||||
// Projectile.updateRotation: the look follows the motion.
|
||||
let v = r.velocity;
|
||||
let yaw = v.x.atan2(v.z).to_degrees() as f32;
|
||||
let pitch = v.y.atan2(v.x.hypot(v.z)).to_degrees() as f32;
|
||||
g.hitbox(
|
||||
at(r.previous, r.position),
|
||||
(0.25, 0.25),
|
||||
0.2125,
|
||||
false,
|
||||
(pitch, yaw),
|
||||
);
|
||||
}
|
||||
for h in self
|
||||
.hook
|
||||
.iter()
|
||||
.map(|h| (h.previous, h.position))
|
||||
.chain(self.remote_hooks.iter().map(|h| (h.previous, h.position)))
|
||||
{
|
||||
g.hitbox(at(h.0, h.1), (0.25, 0.25), 0.2125, false, (0.0, 0.0));
|
||||
}
|
||||
for b in &self.bolts {
|
||||
g.hitbox(b.at, (0.0, 0.0), 0.0, false, (0.0, 0.0));
|
||||
}
|
||||
// The dragon: 16 by 8, a living entity; its parts follow.
|
||||
if let Some(d) = &self.dragon {
|
||||
g.hitbox(
|
||||
at(d.previous, d.position),
|
||||
(16.0, 8.0),
|
||||
6.8,
|
||||
true,
|
||||
(0.0, d.yaw),
|
||||
);
|
||||
}
|
||||
// The dragon's parts.
|
||||
for (id, b) in self.special_targets() {
|
||||
if (super::dragon::SPECIAL..super::dragon::SPECIAL + 8).contains(&id) {
|
||||
@@ -828,3 +982,12 @@ impl Game<'_> {
|
||||
g
|
||||
}
|
||||
}
|
||||
|
||||
/// The (x, y) rotations whose view vector is the step of a direction.
|
||||
fn step_view(step: [i32; 3]) -> (f32, f32) {
|
||||
let [x, y, z] = step.map(f64::from);
|
||||
(
|
||||
(-y).asin().to_degrees() as f32,
|
||||
(-x.atan2(z)).to_degrees() as f32,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ use horizon_client::{
|
||||
use horizon_protocol::text::translatable;
|
||||
use horizon_world::nbt::{JavaString, Tag};
|
||||
use std::{
|
||||
io::Write,
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex, OnceLock, mpsc},
|
||||
time::{Duration, Instant},
|
||||
@@ -89,7 +90,9 @@ fn log_from(thread: &str, level: &str, message: &str) {
|
||||
}
|
||||
});
|
||||
// Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log.
|
||||
println!(
|
||||
// The launcher can close its stdout pipe while the server keeps running.
|
||||
let _ = writeln!(
|
||||
std::io::stdout().lock(),
|
||||
"[{}] [{thread}/{level}]: {message}",
|
||||
chrono::Local::now().format("%H:%M:%S")
|
||||
);
|
||||
@@ -618,6 +621,22 @@ impl Game<'_> {
|
||||
log_ips: props.log_ips,
|
||||
}),
|
||||
resource_pack: props.resource_pack.clone(),
|
||||
// DedicatedServer.serverLinks: `bug-report-link` as the only link
|
||||
// (ServerLinks.KnownLinkType.BUG_REPORT is id 0).
|
||||
server_links: if props.bug_report_link.is_empty() {
|
||||
Vec::new()
|
||||
} else if super::server_links::valid_untrusted_uri(&props.bug_report_link) {
|
||||
vec![horizon_protocol::packets::configuration::ServerLink {
|
||||
kind: horizon_protocol::packets::configuration::ServerLinkKind::Known(0),
|
||||
link: props.bug_report_link.clone(),
|
||||
}]
|
||||
} else {
|
||||
log(
|
||||
"WARN",
|
||||
&format!("Failed to parse bug link {}", props.bug_report_link),
|
||||
);
|
||||
Vec::new()
|
||||
},
|
||||
};
|
||||
let config = HubConfig {
|
||||
default_game_mode: game_mode,
|
||||
@@ -654,6 +673,9 @@ impl Game<'_> {
|
||||
// DedicatedServer.initServer ends with saveEverything(false, true, true).
|
||||
self.save_game()?;
|
||||
self.log_saved_levels();
|
||||
if let Some(host) = self.lan.as_mut() {
|
||||
host.hub.entity_range_percent = props.entity_broadcast_range_percentage;
|
||||
}
|
||||
let mut state = ServerState {
|
||||
lists,
|
||||
console,
|
||||
@@ -1308,3 +1330,110 @@ fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?);
|
||||
Some((w, h))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{capture_log, log, log_from};
|
||||
use std::{
|
||||
fs,
|
||||
io::{self, BufRead, BufReader, Read, Write},
|
||||
process::{Command, Stdio},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
const LOGIN: &str = "Player[/127.0.0.1:0] logged in with entity id 2 at (0.5, 115.0, 0.5)";
|
||||
const WARNING: &str = "Authentication warning";
|
||||
const READY: &str = "horizon-console-log-ready\n";
|
||||
const CHILD_HOME: &str = "HORIZON_TEST_CONSOLE_LOG_HOME";
|
||||
|
||||
fn assert_log_lines(text: &str) {
|
||||
let expected = [
|
||||
format!("] [Server thread/INFO]: {LOGIN}"),
|
||||
format!("] [User Authenticator #1/WARN]: {WARNING}"),
|
||||
];
|
||||
assert_eq!(text.lines().count(), expected.len());
|
||||
for (line, suffix) in text.lines().zip(expected) {
|
||||
assert!(line.starts_with('['));
|
||||
assert!(chrono::NaiveTime::parse_from_str(&line[1..9], "%H:%M:%S").is_ok());
|
||||
assert_eq!(&line[9..], suffix);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn console_logging_survives_closed_stdout() {
|
||||
if let Some(home) = std::env::var_os(CHILD_HOME) {
|
||||
horizon_client::logging::init(std::path::Path::new(&home), "Server thread");
|
||||
// Let the parent close the real stdout pipe only after libtest's startup output.
|
||||
io::stdout().write_all(READY.as_bytes()).unwrap();
|
||||
io::stdout().flush().unwrap();
|
||||
io::stdin().read_exact(&mut [0]).unwrap();
|
||||
std::thread::Builder::new()
|
||||
.name("Server thread".into())
|
||||
.spawn(|| {
|
||||
let captured = capture_log(|| {
|
||||
log("INFO", LOGIN);
|
||||
log_from("User Authenticator #1", "WARN", WARNING);
|
||||
});
|
||||
assert_eq!(captured, [LOGIN, WARNING]);
|
||||
horizon_client::logging::flush();
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
// Libtest's final status also writes to stdout; only the game logger is under test.
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
for closed_stdout in [false, true] {
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let home = std::env::temp_dir().join(format!(
|
||||
"horizon-console-log-test-{}-{unique}",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir(&home).unwrap();
|
||||
let mut child = Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"game::dedicated::tests::console_logging_survives_closed_stdout",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_HOME, &home)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdout = BufReader::new(child.stdout.take().unwrap());
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
assert!(
|
||||
stdout.read_line(&mut line).unwrap() > 0,
|
||||
"child was not ready"
|
||||
);
|
||||
if line.ends_with(READY) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if closed_stdout {
|
||||
drop(stdout); // No reader remains: the next console write gets EPIPE.
|
||||
} else {
|
||||
child.stdout = Some(stdout.into_inner());
|
||||
}
|
||||
child.stdin.take().unwrap().write_all(&[1]).unwrap();
|
||||
let output = child.wait_with_output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"closed_stdout={closed_stdout}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
if !closed_stdout {
|
||||
assert_log_lines(std::str::from_utf8(&output.stdout).unwrap());
|
||||
}
|
||||
assert_log_lines(&fs::read_to_string(home.join("logs/latest.log")).unwrap());
|
||||
fs::remove_dir_all(home).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +120,11 @@ impl Game<'_> {
|
||||
p.guest = guest;
|
||||
// Not into the one who turned it on its way out.
|
||||
p.left_owner = false;
|
||||
// `AbstractHurtingProjectile.onDeflection` by an attack, and the
|
||||
// `needsSync` that `AIM_DEFLECT` sets: a server's players see it turn
|
||||
// at once, not at the fireball's next update ten ticks later.
|
||||
p.acceleration = 0.1;
|
||||
p.needs_sync = true;
|
||||
self.reset_attack_strength();
|
||||
self.swing_arm();
|
||||
let from = self
|
||||
|
||||
@@ -725,6 +725,11 @@ impl Game<'_> {
|
||||
match self.world.block_entities.get_mut(&p) {
|
||||
Some(BlockEntity::Jukebox(j)) => j.record = stack,
|
||||
Some(BlockEntity::Lectern(l)) => l.book = stack,
|
||||
Some(BlockEntity::Campfire(c)) => {
|
||||
if let Some(cell) = c.items.get_mut(slot) {
|
||||
*cell = stack;
|
||||
}
|
||||
}
|
||||
Some(e) => {
|
||||
if let Some(cell) = e.slots_mut().get_mut(slot) {
|
||||
*cell = stack;
|
||||
@@ -1126,14 +1131,18 @@ impl Game<'_> {
|
||||
let (p, v) = (b.position, b.velocity);
|
||||
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
|
||||
}
|
||||
// A merged orb prints once per count, as the oracle does: whether orbs
|
||||
// merge depends on entity ids, which differ from vanilla's.
|
||||
for o in &self.orbs {
|
||||
let (p, v) = (o.position, o.velocity);
|
||||
out.push(line(
|
||||
"minecraft:experience_orb",
|
||||
[p.x, p.y, p.z],
|
||||
[v.x, v.y, v.z],
|
||||
"",
|
||||
));
|
||||
for _ in 0..o.count.max(1) {
|
||||
out.push(line(
|
||||
"minecraft:experience_orb",
|
||||
[p.x, p.y, p.z],
|
||||
[v.x, v.y, v.z],
|
||||
"",
|
||||
));
|
||||
}
|
||||
}
|
||||
for c in &self.carts {
|
||||
let (p, v) = (c.position, c.velocity);
|
||||
|
||||
@@ -982,7 +982,7 @@ impl Game<'_> {
|
||||
| "minecraft:lingering_potion" => {
|
||||
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
|
||||
shot.shoot(&mut own, dir, power, uncertainty);
|
||||
self.launch_thrown(one, at, shot.velocity);
|
||||
self.launch_thrown(one, at, shot.velocity, None);
|
||||
}
|
||||
"minecraft:firework_rocket" => {
|
||||
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
|
||||
@@ -1034,7 +1034,7 @@ impl Game<'_> {
|
||||
a.pickup = horizon_client::arrows::Pickup::Allowed;
|
||||
}
|
||||
shot.shoot(&mut own, dir, power, uncertainty);
|
||||
self.creatures.projectiles.push(shot);
|
||||
self.add_projectile(shot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ pub(super) const SPECIAL: u32 = u32::MAX - 4096;
|
||||
const CRYSTAL_IDS: u32 = SPECIAL + 16;
|
||||
const FIGHT_FILE: &str = "data/minecraft/ender_dragon_fight.dat";
|
||||
const MAX_HEALTH: f32 = 200.0;
|
||||
/// `Mob.getAmbientSoundInterval`.
|
||||
const AMBIENT_INTERVAL: i32 = 80;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Fight {
|
||||
@@ -270,6 +272,8 @@ pub(super) struct Dragon {
|
||||
flame_count: i32,
|
||||
sitting_damage: f32,
|
||||
growl: i32,
|
||||
/// `Mob.ambientSoundTime`.
|
||||
ambient_time: i32,
|
||||
ticks: i32,
|
||||
/// DragonFlightHistory: (y, yRot) samples, newest at `head`.
|
||||
history: [(f64, f32); 64],
|
||||
@@ -291,11 +295,11 @@ pub(super) enum FightWho {
|
||||
}
|
||||
/// A player in the End as the dragon sees it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct FightPlayer {
|
||||
who: FightWho,
|
||||
position: Vec3,
|
||||
bounds: Aabb,
|
||||
alive: bool,
|
||||
pub(super) struct FightPlayer {
|
||||
pub(super) who: FightWho,
|
||||
pub(super) position: Vec3,
|
||||
pub(super) bounds: Aabb,
|
||||
pub(super) alive: bool,
|
||||
creative: bool,
|
||||
spectator: bool,
|
||||
}
|
||||
@@ -397,6 +401,7 @@ impl Dragon {
|
||||
flame_count: 0,
|
||||
sitting_damage: 0.0,
|
||||
growl: 100,
|
||||
ambient_time: 0,
|
||||
ticks: 0,
|
||||
history: [(position.y, yaw); 64],
|
||||
head: 0,
|
||||
@@ -693,7 +698,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// The players in the level the dragon sees (`level.players()`): the
|
||||
/// window's own, then every guest in the level.
|
||||
fn fight_players(&self) -> Vec<FightPlayer> {
|
||||
pub(super) fn fight_players(&self) -> Vec<FightPlayer> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
out.push(FightPlayer {
|
||||
@@ -722,7 +727,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Run `f` as the fight's player `who` (a guest's turn, its knockback
|
||||
/// sent to its client).
|
||||
fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) {
|
||||
pub(super) fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) {
|
||||
match who {
|
||||
FightWho::Host => f(self),
|
||||
FightWho::Guest(conn) => {
|
||||
@@ -828,8 +833,10 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
let time = self.world.random.next_int_bound(100_000).unwrap_or(0);
|
||||
// EndCrystal's constructor takes an id from the entity counter.
|
||||
self.next_entity += 1;
|
||||
self.crystals.push(Crystal {
|
||||
id: 0,
|
||||
id: self.next_entity,
|
||||
position: at,
|
||||
show_bottom: true,
|
||||
time,
|
||||
@@ -987,6 +994,8 @@ impl Game<'_> {
|
||||
};
|
||||
let hurt = d.hurt(part, damage, counts, arrow);
|
||||
if hurt == (Hurt::Landed { full: true }) {
|
||||
// Mob.playHurtSound: the ambient sound clock starts again.
|
||||
d.ambient_time = -AMBIENT_INTERVAL;
|
||||
let at = [d.position.x, d.position.y, d.position.z];
|
||||
let pitch = 0.8 + self.world.random.next_float() * 0.3;
|
||||
self.audio
|
||||
@@ -1566,6 +1575,7 @@ impl Game<'_> {
|
||||
age: 0,
|
||||
duration: 200,
|
||||
from_dragon: true,
|
||||
potion: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1658,6 +1668,24 @@ impl Game<'_> {
|
||||
self.tick_dragon_death();
|
||||
return;
|
||||
}
|
||||
// Mob.baseTick: the ambient sound, rarer right after one.
|
||||
let roll = d.random.next_int_bound(1000).unwrap_or(999);
|
||||
let waited = d.ambient_time;
|
||||
d.ambient_time += 1;
|
||||
if roll < waited {
|
||||
d.ambient_time = -AMBIENT_INTERVAL;
|
||||
let at = [d.position.x, d.position.y, d.position.z];
|
||||
// LivingEntity.getVoicePitch, from the dragon's own random.
|
||||
let r = &mut d.random;
|
||||
let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0;
|
||||
self.audio.play(
|
||||
"minecraft:entity.ender_dragon.ambient",
|
||||
Some(at),
|
||||
5.0,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
let d = self.dragon.as_mut().expect("dragon");
|
||||
// Flapping, growls and the flap sound.
|
||||
let flap_was = (d.old_flap * std::f32::consts::TAU).cos();
|
||||
let v = d.velocity;
|
||||
@@ -2078,12 +2106,18 @@ impl Game<'_> {
|
||||
age: 0,
|
||||
duration: 600,
|
||||
from_dragon: false,
|
||||
potion: None,
|
||||
});
|
||||
self.audio.play(
|
||||
"minecraft:entity.dragon_fireball.explode",
|
||||
Some([next.x, next.y, next.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
// DragonFireball.onHit: level event 2006 (the burst of dragon
|
||||
// breath and the explosion sound) at its block position.
|
||||
self.level_event_at(
|
||||
2006,
|
||||
[
|
||||
next.x.floor() as i32,
|
||||
next.y.floor() as i32,
|
||||
next.z.floor() as i32,
|
||||
],
|
||||
1,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
@@ -2110,6 +2144,10 @@ impl Game<'_> {
|
||||
let mut harmed: Vec<(FightWho, f32)> = Vec::new();
|
||||
let mut clouds = std::mem::take(&mut self.breath_clouds);
|
||||
clouds.retain_mut(|c| {
|
||||
// Lingering potions' clouds tick with the potions.
|
||||
if c.potion.is_some() {
|
||||
return true;
|
||||
}
|
||||
c.age += 1;
|
||||
if c.age >= c.duration {
|
||||
return false;
|
||||
@@ -2127,10 +2165,12 @@ impl Game<'_> {
|
||||
c.at[1],
|
||||
c.at[2] + f64::from(a.sin() * d),
|
||||
];
|
||||
self.particles.add(
|
||||
self.particles.add_with(
|
||||
&ParticleOptions::simple(ParticleType::DragonBreath),
|
||||
at,
|
||||
[0.0, 0.0, 0.0],
|
||||
false,
|
||||
true,
|
||||
);
|
||||
}
|
||||
// AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity.
|
||||
@@ -2157,11 +2197,14 @@ impl Game<'_> {
|
||||
}
|
||||
/// Damage from the dragon, which is its causing entity
|
||||
/// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the
|
||||
/// death message names it.
|
||||
/// death message names it, or the cloud once the dragon is gone.
|
||||
fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) {
|
||||
if let Some(id) = self.dragon.as_ref().map(|d| d.id) {
|
||||
let name = Text::translate("entity.minecraft.ender_dragon", &[]);
|
||||
self.note_named_attacker(damage_type, id, name);
|
||||
} else if damage_type == "minecraft:indirect_magic" {
|
||||
let name = Text::translate("entity.minecraft.area_effect_cloud", &[]);
|
||||
self.note_direct_entity(damage_type, name);
|
||||
}
|
||||
self.hurt_player_by(damage_type, amount);
|
||||
}
|
||||
@@ -2254,8 +2297,22 @@ pub(super) struct Breath {
|
||||
pub(super) at: [f64; 3],
|
||||
pub(super) radius: f32,
|
||||
pub(super) age: i32,
|
||||
duration: i32,
|
||||
from_dragon: bool,
|
||||
pub(super) duration: i32,
|
||||
pub(super) from_dragon: bool,
|
||||
/// A lingering potion's cloud (`ThrownLingeringPotion`): what it applies.
|
||||
pub(super) potion: Option<super::potions::PotionCloud>,
|
||||
}
|
||||
impl Breath {
|
||||
/// `AreaEffectCloud.isWaiting`: before its wait time (20 ticks, 10 for a
|
||||
/// lingering potion's).
|
||||
pub(super) fn waiting(&self) -> bool {
|
||||
self.age
|
||||
< if self.potion.is_some() {
|
||||
super::potions::LINGERING_WAIT
|
||||
} else {
|
||||
20
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `EnderDragonRenderer` and `EnderDragonModel.setupAnim`.
|
||||
@@ -2482,6 +2539,8 @@ impl Game<'_> {
|
||||
layer: 2,
|
||||
color: c,
|
||||
light: 0,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2547,6 +2606,8 @@ impl Game<'_> {
|
||||
layer: 6,
|
||||
color: c,
|
||||
light: wrap_light,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
(last_sin, last_cos, last_u) = (sin, cos, uu);
|
||||
@@ -2592,13 +2653,17 @@ impl Game<'_> {
|
||||
layer: 0,
|
||||
color: 0xFFFF_FFFF,
|
||||
light: 240 | 240 << 8,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn fight_ready(&mut self) -> bool {
|
||||
self.load_fight();
|
||||
self.fight.loaded
|
||||
// spawnExitPortal runs from scanState and the dragon's death, both
|
||||
// only with players in the fight.
|
||||
self.fight.loaded && self.fight.players
|
||||
}
|
||||
pub(super) fn exit_portal(&self) -> Option<[i32; 3]> {
|
||||
self.fight.exit_portal
|
||||
@@ -2830,8 +2895,11 @@ impl Game<'_> {
|
||||
return false;
|
||||
}
|
||||
let time = self.world.random.next_int_bound(100_000).unwrap_or(0);
|
||||
// EndCrystal's constructor takes an id from the entity counter, so
|
||||
// the crystal is an entity a command can name (`@e[type=end_crystal]`).
|
||||
self.next_entity += 1;
|
||||
self.crystals.push(Crystal {
|
||||
id: 0,
|
||||
id: self.next_entity,
|
||||
position: Vec3::new(x + 0.5, y, z + 0.5),
|
||||
show_bottom: false,
|
||||
time,
|
||||
@@ -2848,6 +2916,21 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// `EndCrystal.kill` (`/kill`): the crystal is removed, without a blast
|
||||
/// (`Entity.kill` does not hurt it).
|
||||
pub(super) fn kill_crystal(&mut self, id: u32) {
|
||||
if let Some(i) = self.crystals.iter().position(|c| c.id == id) {
|
||||
self.destroy_crystal(i, None, CrystalDamage::Explosion);
|
||||
}
|
||||
}
|
||||
/// `EnderDragon.kill` (`/kill`): `Entity.kill` removes the entity, it
|
||||
/// does not hurt it (the dragon flies its death flight when its health
|
||||
/// runs out).
|
||||
pub(super) fn kill_dragon(&mut self, id: u32) {
|
||||
if self.dragon.as_ref().is_some_and(|d| d.id == id) {
|
||||
self.dragon = None;
|
||||
}
|
||||
}
|
||||
/// Any entity touching `room` (`Level.getEntities(null, box)`).
|
||||
fn entity_in(&self, room: Aabb) -> bool {
|
||||
let touches = |lo: Vec3, hi: Vec3| {
|
||||
|
||||
@@ -3,10 +3,14 @@
|
||||
//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power
|
||||
//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`),
|
||||
//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and
|
||||
//! the armor attribute effects (respiration, depth strider, ...).
|
||||
//! the armor attribute effects (respiration, depth strider, ...) and Soul
|
||||
//! Speed's `location_changed` and `tick` effects.
|
||||
use super::Game;
|
||||
use horizon_client::{enchant::EffectContext, items::ItemStack};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_client::{
|
||||
enchant::{EffectContext, Enchantments, level_value},
|
||||
items::ItemStack,
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
|
||||
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -153,8 +157,10 @@ impl Game<'_> {
|
||||
items: Some(self.res.items()),
|
||||
..Default::default()
|
||||
};
|
||||
// minecraft:post_attack ignite effects of the attacker's weapon (fire aspect).
|
||||
// minecraft:post_attack effects of the attacker's weapon on the victim:
|
||||
// ignite (fire aspect) and apply_mob_effect (bane of arthropods).
|
||||
let mut ignite = 0.0f32;
|
||||
let mut mob_effects = Vec::new();
|
||||
for (id, level) in held.enchantments() {
|
||||
let Some(def) = self.res.stations().enchantments.get(id) else {
|
||||
continue;
|
||||
@@ -164,24 +170,33 @@ impl Game<'_> {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if effect["enchanted"] == "attacker"
|
||||
&& effect["affected"] == "victim"
|
||||
&& effect["effect"]["type"] == "minecraft:ignite"
|
||||
let e = &effect["effect"];
|
||||
let kind_of = e["type"].as_str();
|
||||
if effect["enchanted"] != "attacker"
|
||||
|| effect["affected"] != "victim"
|
||||
|| !matches!(
|
||||
kind_of,
|
||||
Some("minecraft:ignite" | "minecraft:apply_mob_effect")
|
||||
)
|
||||
{
|
||||
let mut random = self.world.random.clone();
|
||||
let ok = effect.get("requirements").is_none_or(|r| {
|
||||
self.res
|
||||
.stations()
|
||||
.enchantments
|
||||
.condition(r, *level, &ctx, &mut random)
|
||||
});
|
||||
self.world.random = random;
|
||||
if ok {
|
||||
ignite = ignite.max(horizon_client::enchant::level_value(
|
||||
&effect["effect"]["duration"],
|
||||
*level,
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut random = self.world.random.clone();
|
||||
let ok = effect.get("requirements").is_none_or(|r| {
|
||||
self.res
|
||||
.stations()
|
||||
.enchantments
|
||||
.condition(r, *level, &ctx, &mut random)
|
||||
});
|
||||
self.world.random = random;
|
||||
if !ok {
|
||||
continue;
|
||||
}
|
||||
if kind_of == Some("minecraft:ignite") {
|
||||
ignite =
|
||||
ignite.max(horizon_client::enchant::level_value(&e["duration"], *level));
|
||||
} else {
|
||||
mob_effects.push((e.clone(), *level));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,8 +206,41 @@ impl Game<'_> {
|
||||
{
|
||||
m.ignite_for_ticks((ignite * 20.0) as i32);
|
||||
}
|
||||
for (effect, level) in mob_effects {
|
||||
self.apply_mob_effect(mob, &effect, level);
|
||||
}
|
||||
self.post_attack_bursts(&held, &kind);
|
||||
}
|
||||
/// `ApplyMobEffect.apply`: one of `to_apply` (a single id or a list) for a
|
||||
/// random duration and amplifier between the level-based bounds.
|
||||
fn apply_mob_effect(&mut self, mob: usize, effect: &serde_json::Value, level: u32) {
|
||||
use horizon_client::enchant::level_value;
|
||||
let Some(m) = self.mobs.get_mut(mob) else {
|
||||
return;
|
||||
};
|
||||
let ids: Vec<&str> = match &effect["to_apply"] {
|
||||
serde_json::Value::String(id) => vec![id.as_str()],
|
||||
serde_json::Value::Array(list) => list.iter().filter_map(|v| v.as_str()).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
// HolderSet.getRandomElement, then Mth.randomBetween for both values.
|
||||
let pick = m.random.next_int_bound(ids.len() as i32).unwrap_or(0) as usize;
|
||||
let mut between = |min: &str, max: &str| {
|
||||
let (lo, hi) = (
|
||||
level_value(&effect[min], level),
|
||||
level_value(&effect[max], level),
|
||||
);
|
||||
m.random.next_float() * (hi - lo) + lo
|
||||
};
|
||||
let ticks = (between("min_duration", "max_duration") * 20.0).round() as i32;
|
||||
let amplifier = (between("min_amplifier", "max_amplifier").round() as i32).max(0);
|
||||
if let Some(id) = super::potions::mob_effect_id(ids[pick]) {
|
||||
m.add_effect(id, ticks, amplifier);
|
||||
}
|
||||
}
|
||||
/// `minecraft:post_attack` explode effects on the attacker (wind burst):
|
||||
/// a burst at the player's feet that only knocks back and triggers
|
||||
/// blocks (`ExplodeEffect` with `block_interaction: trigger`).
|
||||
@@ -303,8 +351,10 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
hits.push(1.0 + self.world.random.next_float() * 4.0);
|
||||
// ChangeItemDamage -> ItemStack.hurtAndBreak: unbreaking applies.
|
||||
let loss = self.durability_loss(&stack, 2);
|
||||
if let Some(s) = self.armor[slot].as_mut() {
|
||||
s.damage += 2;
|
||||
s.damage += loss;
|
||||
if self
|
||||
.res
|
||||
.items()
|
||||
@@ -384,7 +434,9 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Bow enchantments at release: (extra base damage, infinity keeps the arrow).
|
||||
pub(super) fn bow_enchantments(&mut self) -> (f64, bool) {
|
||||
/// `ammo` is the item being fired: `Enchantment.itemContext` hands it to the
|
||||
/// `ammo_use` conditions as the tool, so Infinity only frees plain arrows.
|
||||
pub(super) fn bow_enchantments(&mut self, ammo: &str) -> (f64, bool) {
|
||||
let Some(bow) = self.inventory[self.selected].clone() else {
|
||||
return (0.0, false);
|
||||
};
|
||||
@@ -403,7 +455,7 @@ impl Game<'_> {
|
||||
0.0,
|
||||
);
|
||||
let ammo_ctx = EffectContext {
|
||||
tool: Some("minecraft:arrow"),
|
||||
tool: Some(ammo),
|
||||
items: Some(self.res.items()),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -456,6 +508,134 @@ impl Game<'_> {
|
||||
}
|
||||
ignite
|
||||
}
|
||||
/// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of
|
||||
/// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The
|
||||
/// `location_changed` effects run when the player enters a new block, lands,
|
||||
/// or its boots change:
|
||||
/// - the speed and movement efficiency modifiers turn on over a soul speed
|
||||
/// block (not flying, not riding) and stay on while airborne, then off
|
||||
/// (`enchantment_active_check`);
|
||||
/// - the boots lose 1 durability with a 4% chance when on such a block.
|
||||
///
|
||||
/// Every fifth tick the player walking on one also gets a soul particle
|
||||
/// (returned as its position and velocity, for the caller to show or send
|
||||
/// to the players around) and sometimes a sound. Runs for the window's own
|
||||
/// player and for each guest on the server (`guest_server_tick`); a remote
|
||||
/// client leaves it to its server.
|
||||
pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> {
|
||||
const ID: &str = "minecraft:soul_speed";
|
||||
let player = self.player.as_mut()?;
|
||||
if player.client_side {
|
||||
return None;
|
||||
}
|
||||
let level = self.armor[3]
|
||||
.as_ref()
|
||||
.map_or(0, |s| s.enchantment_level(ID));
|
||||
let position = player.position;
|
||||
let (on_ground, flying) = (player.ground.on_ground, player.flying);
|
||||
let moved = position.subtract(player.old_position);
|
||||
let (tick, width) = (player.health.tick_count, player.dimensions.width);
|
||||
let fx = &mut player.location_effects;
|
||||
let on_soul = fx.on_soul_speed_block;
|
||||
let block = BlockPos::containing(position);
|
||||
let changed_block = fx.block.replace(block) != Some(block);
|
||||
let landed = std::mem::take(&mut fx.landed);
|
||||
// Changed boots: `stopLocationBasedEffects`, then the effects run again.
|
||||
let equipped = std::mem::replace(&mut fx.boots_level, level) != level;
|
||||
let was_active = fx.applied_level;
|
||||
let mut active = was_active > 0 && !equipped;
|
||||
let mut wear = false;
|
||||
if level > 0 && (changed_block || landed || equipped) {
|
||||
let riding = self.riding.is_some();
|
||||
let wanted = !riding && !flying && (on_soul || (active && !on_ground));
|
||||
active = wanted;
|
||||
// `random_chance` is the first term of the wear's `all_of`: it
|
||||
// draws from the level random before the block is looked at.
|
||||
let roll = self.world.random.next_float() < 0.04;
|
||||
wear = roll && on_ground && on_soul;
|
||||
}
|
||||
fx.applied_level = if active { level } else { 0 };
|
||||
// `Entity.getKnownMovement` horizontal speed of at least 1.0E-5.
|
||||
let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10;
|
||||
let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0;
|
||||
// The attribute effects were applied to the player before: swap them.
|
||||
if was_active > 0 && (!active || equipped) {
|
||||
for (attribute, id, _, op) in
|
||||
soul_speed_modifiers(&self.res.stations().enchantments, was_active)
|
||||
{
|
||||
let _ = player.set_modifier(&attribute, &id, 0.0, &op, false);
|
||||
}
|
||||
}
|
||||
if active && (was_active == 0 || equipped) {
|
||||
for (attribute, id, amount, op) in
|
||||
soul_speed_modifiers(&self.res.stations().enchantments, level)
|
||||
{
|
||||
let _ = player.set_modifier(&attribute, &id, amount, &op, true);
|
||||
}
|
||||
}
|
||||
if wear && !self.creative {
|
||||
self.wear_boots(1);
|
||||
}
|
||||
if level == 0 {
|
||||
return None;
|
||||
}
|
||||
let r = &mut self.world.random;
|
||||
// `spawn_particles`: in the bounding box, 0.1 above the feet, thrown
|
||||
// back against the movement (-0.2) and up (0.1).
|
||||
let particle = tick_effects.then(|| {
|
||||
let x = position.x + (r.next_double() - 0.5) * f64::from(width);
|
||||
let z = position.z + (r.next_double() - 0.5) * f64::from(width);
|
||||
(
|
||||
[x, position.y + 0.1, z],
|
||||
[moved.x * -0.2, 0.1, moved.z * -0.2],
|
||||
)
|
||||
});
|
||||
// `play_sound`: its `random_chance` (35%) comes first in its `all_of`,
|
||||
// so the level random is drawn every tick the boots are worn; volume
|
||||
// 0.6, pitch 0.6 to 1.0.
|
||||
if r.next_float() < 0.35 && tick_effects {
|
||||
let pitch = r.next_float() * 0.4 + 0.6;
|
||||
self.audio.play(
|
||||
"minecraft:particle.soul_escape",
|
||||
Some([position.x, position.y, position.z]),
|
||||
0.6,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
particle
|
||||
}
|
||||
/// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`):
|
||||
/// Unbreaking applies, and they break when worn out.
|
||||
fn wear_boots(&mut self, amount: u32) {
|
||||
let Some(stack) = self.armor[3].clone() else {
|
||||
return;
|
||||
};
|
||||
let loss = self.durability_loss(&stack, amount);
|
||||
let max = self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.map_or(0, |info| info.max_damage);
|
||||
if max == 0 {
|
||||
return;
|
||||
}
|
||||
let Some(boots) = self.armor[3].as_mut() else {
|
||||
return;
|
||||
};
|
||||
boots.damage += loss;
|
||||
if boots.damage >= max {
|
||||
self.armor[3] = None;
|
||||
if let Some(eye) = self.eye_position() {
|
||||
self.audio.play(
|
||||
"minecraft:entity.item.break",
|
||||
Some(eye),
|
||||
0.8,
|
||||
0.8 + self.world.random.next_float() * 0.4,
|
||||
);
|
||||
}
|
||||
self.apply_equipment();
|
||||
}
|
||||
}
|
||||
/// Enchantment attribute modifiers of worn armor (respiration, depth strider...).
|
||||
/// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`),
|
||||
/// so the same enchantment on two pieces stacks instead of replacing itself.
|
||||
@@ -479,3 +659,28 @@ impl Game<'_> {
|
||||
self.potions.enchant_modifiers = wanted;
|
||||
}
|
||||
}
|
||||
|
||||
/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation),
|
||||
/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`.
|
||||
fn soul_speed_modifiers(
|
||||
enchantments: &Enchantments,
|
||||
level: u32,
|
||||
) -> Vec<(String, String, f64, String)> {
|
||||
let Some(e) = enchantments.get("minecraft:soul_speed") else {
|
||||
return Vec::new();
|
||||
};
|
||||
e.effects["minecraft:location_changed"][0]["effect"]["effects"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|a| a["type"] == "minecraft:attribute")
|
||||
.map(|a| {
|
||||
(
|
||||
a["attribute"].as_str().unwrap_or("").to_owned(),
|
||||
format!("{}/feet", a["id"].as_str().unwrap_or("")),
|
||||
f64::from(level_value(&a["amount"], level)),
|
||||
a["operation"].as_str().unwrap_or("add_value").to_owned(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
containers::{BlockEntity, EndGateway},
|
||||
environment::Environment,
|
||||
items::ItemStack,
|
||||
mesher::Vertex,
|
||||
@@ -20,7 +21,7 @@ use horizon_core::{
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
/// ServerLevel.END_SPAWN_POINT.
|
||||
const END_SPAWN: [i32; 3] = [100, 50, 0];
|
||||
pub(super) const END_SPAWN: [i32; 3] = [100, 50, 0];
|
||||
/// EnderDragonFight gateway ring radius and height.
|
||||
const GATEWAY_RADIUS: f64 = 96.0;
|
||||
const GATEWAY_Y: i32 = 75;
|
||||
@@ -28,14 +29,64 @@ const GATEWAY_Y: i32 = 75;
|
||||
const GATEWAY_FILE: &str = "horizon-end-gateways.json";
|
||||
|
||||
/// A gateway teleport waiting for its destination chunks.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum GatewayJob {
|
||||
/// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway.
|
||||
Find { gateway: [i32; 3] },
|
||||
/// `exact` is the gateway's own `ExactTeleport`, read while its chunk is loaded.
|
||||
Find { gateway: [i32; 3], exact: bool },
|
||||
/// A known exit (exact, or findExitPosition around it).
|
||||
Known { exit: [i32; 3], exact: bool },
|
||||
}
|
||||
|
||||
impl GatewayJob {
|
||||
/// TheEndGatewayBlockEntity.getPortalPosition, with legacy save fallbacks.
|
||||
fn for_gateway(
|
||||
gateway: [i32; 3],
|
||||
entity: Option<&BlockEntity>,
|
||||
legacy: Option<([i32; 3], bool)>,
|
||||
) -> Self {
|
||||
let configured = match entity {
|
||||
Some(BlockEntity::EndGateway(g)) => g.exit_portal.map(|exit| (exit, g.exact_teleport)),
|
||||
_ => None,
|
||||
};
|
||||
match configured.or(legacy) {
|
||||
Some((exit, exact)) => Self::Known { exit, exact },
|
||||
// Worldgen return gateways (end_gateway_return) lead exactly to the End spawn.
|
||||
None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => Self::Known {
|
||||
exit: END_SPAWN,
|
||||
exact: true,
|
||||
},
|
||||
None => Self::Find {
|
||||
gateway,
|
||||
exact: exact_teleport(entity),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `TheEndGatewayBlockEntity.exactTeleport` of the block entity at a gateway
|
||||
/// (false without one).
|
||||
fn exact_teleport(entity: Option<&BlockEntity>) -> bool {
|
||||
matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport)
|
||||
}
|
||||
|
||||
/// Moves an exit that only the side file knew into the gateway's block entity, unless the block
|
||||
/// entity has its own; true when it took the saved one.
|
||||
fn adopt_saved_exit(entity: &mut EndGateway, (exit, exact): ([i32; 3], bool)) -> bool {
|
||||
if entity.exit_portal.is_some() {
|
||||
return false;
|
||||
}
|
||||
entity.exit_portal = Some(exit);
|
||||
entity.exact_teleport = exact;
|
||||
true
|
||||
}
|
||||
|
||||
/// The end of `getPortalPosition`: the exit itself when the teleport is exact,
|
||||
/// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`).
|
||||
fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] {
|
||||
if exact { exit } else { find(exit) }
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct EndState {
|
||||
/// Gateway position -> (exit, exact teleport); loaded lazily from the save.
|
||||
@@ -248,16 +299,25 @@ impl Game<'_> {
|
||||
layer: 2,
|
||||
color,
|
||||
light: 0,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// LightmapRenderStateExtractor: End flashes add to the sky light factor.
|
||||
/// LightmapRenderStateExtractor: End flashes add to the sky light factor
|
||||
/// unless Hide Lightning Flashes is on (the sky sprite is not gated), a
|
||||
/// third of it under a boss bar's world fog.
|
||||
pub(super) fn end_flash_sky(&self, sky: &mut horizon_client::environment::Sky, partial: f64) {
|
||||
if self.dim == Dim::End {
|
||||
sky.sky_light_factor += self.end.flash.intensity(partial as f32);
|
||||
if self.dim == Dim::End && !self.settings.file.bool("hideLightningFlashes") {
|
||||
let intensity = self.end.flash.intensity(partial as f32);
|
||||
sky.sky_light_factor += if self.boss_overlay.should_create_world_fog() {
|
||||
intensity / 3.0
|
||||
} else {
|
||||
intensity
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,7 +684,9 @@ impl Game<'_> {
|
||||
|
||||
/// EnderDragonFight without a dragon: once the centre of the main island
|
||||
/// is loaded, place the active exit portal (EndPodiumFeature) and the
|
||||
/// first gateway (spawnNewGateway) if the portal is not there yet.
|
||||
/// first gateway (spawnNewGateway) if the portal is not there yet. Like
|
||||
/// scanState and spawnExitPortal, only while the fight has no exit portal
|
||||
/// location: a podium that is later broken stays broken.
|
||||
fn ensure_exit_portal(&mut self) -> Result<()> {
|
||||
if self.travelling.is_some()
|
||||
|| !(-1..=0).all(|cz| (-1..=0).all(|cx| self.streaming.is_lit(cx, cz)))
|
||||
@@ -634,8 +696,14 @@ impl Game<'_> {
|
||||
}
|
||||
let won = self.fight.previously_killed;
|
||||
let gateway = self.first_gateway();
|
||||
if (0..256).any(|y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") {
|
||||
// The podium exists; the gateway may have been out of range when it was placed.
|
||||
if self.exit_portal().is_none() {
|
||||
// findExitPortal remembers the location of a podium that is already there.
|
||||
if let Some(level) = self.podium_level() {
|
||||
self.set_exit_portal([0, level, 0]);
|
||||
}
|
||||
}
|
||||
if self.exit_portal().is_some() {
|
||||
// The gateway may have been out of range when it was placed.
|
||||
if won
|
||||
&& self.world.loaded(gateway[0], gateway[2])
|
||||
&& &*self.block_name(gateway) != "minecraft:end_gateway"
|
||||
@@ -666,17 +734,40 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The portal level of the podium around the centre column, read from the
|
||||
/// bedrock that EndPodiumFeature places (rim at the portal level, disc
|
||||
/// below it, the torch column) so a broken column does not hide it.
|
||||
fn podium_level(&self) -> Option<i32> {
|
||||
let mut offsets: Vec<[i32; 3]> = (0..4).map(|dy| [0, dy, 0]).collect();
|
||||
for z in -4..=4i32 {
|
||||
for x in -4..=4i32 {
|
||||
let flat = f64::from(x * x + z * z);
|
||||
if (6.25..12.25).contains(&flat) {
|
||||
offsets.push([x, 0, z]);
|
||||
} else if flat + 1.0 < 6.25 {
|
||||
offsets.push([x, -1, z]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(1..253)
|
||||
.map(|y| {
|
||||
let score = offsets
|
||||
.iter()
|
||||
.filter(|o| &*self.block_name([o[0], y + o[1], o[2]]) == "minecraft:bedrock")
|
||||
.count();
|
||||
(score, y)
|
||||
})
|
||||
.filter(|&(score, _)| score >= 3)
|
||||
.max()
|
||||
.map(|(_, y)| y)
|
||||
}
|
||||
/// `spawnExitPortal(true)` after the dragon dies.
|
||||
pub(super) fn activate_exit_portal(&mut self) -> Result<()> {
|
||||
let origin = match self.exit_portal() {
|
||||
Some(o) => o,
|
||||
None => {
|
||||
// The rim's level: the top of the bedrock column minus three.
|
||||
let top = (0..256)
|
||||
.rev()
|
||||
.find(|&y| &*self.block_name([0, y, 0]) == "minecraft:bedrock")
|
||||
.unwrap_or(64);
|
||||
[0, top - 3, 0]
|
||||
// The rim's level, found without assuming the centre column is intact.
|
||||
[0, self.podium_level().unwrap_or(61), 0]
|
||||
}
|
||||
};
|
||||
self.place_podium(origin, true)
|
||||
@@ -779,6 +870,11 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.get_or_insert_with((origin[0], origin[1], origin[2]), || {
|
||||
BlockEntity::EndGateway(Default::default())
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -800,8 +896,7 @@ impl Game<'_> {
|
||||
self.end.exits.as_mut().expect("loaded exits")
|
||||
}
|
||||
|
||||
fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> {
|
||||
self.gateway_exits().insert(gateway, (exit, exact));
|
||||
fn save_gateway_exits(&mut self) -> Result<()> {
|
||||
let list: Vec<_> = self
|
||||
.gateway_exits()
|
||||
.iter()
|
||||
@@ -813,6 +908,35 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops a gateway's entry from the side file: its block entity is the source of truth.
|
||||
fn forget_gateway_exit(&mut self, gateway: [i32; 3]) -> Result<()> {
|
||||
if self.gateway_exits().remove(&gateway).is_some() {
|
||||
self.save_gateway_exits()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> {
|
||||
// TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit).
|
||||
let key = (gateway[0], gateway[1], gateway[2]);
|
||||
let chunk = (gateway[0] >> 4, gateway[2] >> 4);
|
||||
// The gateway's chunk can be unloaded by now (travel waits for the destination): the
|
||||
// exit then waits in the side file until the gateway is used again (`gateway_job`).
|
||||
if self.world.chunks.contains_key(&chunk)
|
||||
&& let BlockEntity::EndGateway(g) = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_or_insert_with(key, || BlockEntity::EndGateway(Default::default()))
|
||||
{
|
||||
g.exit_portal = Some(exit);
|
||||
g.exact_teleport = exact;
|
||||
self.world.modified.insert(chunk);
|
||||
return self.forget_gateway_exit(gateway);
|
||||
}
|
||||
self.gateway_exits().insert(gateway, (exit, exact));
|
||||
self.save_gateway_exits()
|
||||
}
|
||||
|
||||
/// EndGatewayBlock.entityInside and TheEndGatewayBlockEntity.getPortalPosition:
|
||||
/// travel within the End, waiting for the destination chunks to load.
|
||||
fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> {
|
||||
@@ -832,25 +956,39 @@ impl Game<'_> {
|
||||
/// its exit, or the search for one, and the spot to load before either
|
||||
/// is resolved ([`Game::resolve_gateway`]).
|
||||
pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) {
|
||||
let known = self.gateway_exits().get(&gateway).copied();
|
||||
let job = match known {
|
||||
Some((exit, exact)) => GatewayJob::Known { exit, exact },
|
||||
// Worldgen return gateways (end_gateway_return) lead exactly to the End spawn.
|
||||
None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => {
|
||||
GatewayJob::Known {
|
||||
exit: END_SPAWN,
|
||||
exact: true,
|
||||
}
|
||||
let mut known = self.gateway_exits().get(&gateway).copied();
|
||||
// Once the gateway's chunk is loaded its block entity is the source of truth: an exit the
|
||||
// side file kept for it moves there, and the entry is dropped, so removing or replacing
|
||||
// the exit (`/data remove block`) is not undone by an old entry.
|
||||
let key = (gateway[0], gateway[1], gateway[2]);
|
||||
let chunk = (gateway[0] >> 4, gateway[2] >> 4);
|
||||
if let Some(saved) = known
|
||||
&& self.world.chunks.contains_key(&chunk)
|
||||
&& let BlockEntity::EndGateway(g) = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_or_insert_with(key, || BlockEntity::EndGateway(Default::default()))
|
||||
{
|
||||
if adopt_saved_exit(g, saved) {
|
||||
self.world.modified.insert(chunk);
|
||||
}
|
||||
None => GatewayJob::Find { gateway },
|
||||
};
|
||||
known = None;
|
||||
let _ = self.forget_gateway_exit(gateway);
|
||||
}
|
||||
let job = GatewayJob::for_gateway(
|
||||
gateway,
|
||||
self.world
|
||||
.block_entities
|
||||
.get(&(gateway[0], gateway[1], gateway[2])),
|
||||
known,
|
||||
);
|
||||
let destination = match job {
|
||||
GatewayJob::Known { exit, .. } => Vec3::new(
|
||||
f64::from(exit[0]) + 0.5,
|
||||
f64::from(exit[1]),
|
||||
f64::from(exit[2]) + 0.5,
|
||||
),
|
||||
GatewayJob::Find { gateway } => {
|
||||
GatewayJob::Find { gateway, .. } => {
|
||||
let d = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2]))
|
||||
.normalize_or_zero()
|
||||
* 1024.0;
|
||||
@@ -907,12 +1045,10 @@ impl Game<'_> {
|
||||
[p[0], p[1] + 1, p[2]]
|
||||
};
|
||||
match job {
|
||||
GatewayJob::Known { exit, exact } => Ok(bottom_center(if exact {
|
||||
exit
|
||||
} else {
|
||||
find_exit(self, exit)
|
||||
})),
|
||||
GatewayJob::Find { gateway } => {
|
||||
GatewayJob::Known { exit, exact } => Ok(bottom_center(exit_target(exit, exact, |e| {
|
||||
find_exit(self, e)
|
||||
}))),
|
||||
GatewayJob::Find { gateway, exact } => {
|
||||
// findExitPortalXZPosTentative over the loaded chunks.
|
||||
let dir = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2]))
|
||||
.normalize_or_zero();
|
||||
@@ -972,8 +1108,11 @@ impl Game<'_> {
|
||||
let exit = [tallest[0], tallest[1] + 10, tallest[2]];
|
||||
self.place_gateway(exit)?;
|
||||
self.set_gateway_exit(exit, gateway, false)?;
|
||||
self.set_gateway_exit(gateway, exit, false)?;
|
||||
Ok(bottom_center(find_exit(self, exit)))
|
||||
// setExitPosition keeps the gateway's own exactTeleport.
|
||||
self.set_gateway_exit(gateway, exit, exact)?;
|
||||
Ok(bottom_center(exit_target(exit, exact, |e| {
|
||||
find_exit(self, e)
|
||||
})))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1265,8 +1404,103 @@ impl Game<'_> {
|
||||
layer: 0,
|
||||
color: 0xFFFF_FFFF,
|
||||
light: full,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_client::containers::EndGateway;
|
||||
|
||||
#[test]
|
||||
fn a_saved_exit_moves_into_a_gateway_without_one() {
|
||||
let saved = ([8, 100, 0], true);
|
||||
let mut bare = EndGateway::default();
|
||||
assert!(adopt_saved_exit(&mut bare, saved));
|
||||
assert_eq!(bare.exit_portal, Some([8, 100, 0]));
|
||||
assert!(bare.exact_teleport);
|
||||
// The block entity's own exit wins over a stale entry.
|
||||
let mut own = EndGateway {
|
||||
exit_portal: Some([1, 2, 3]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!adopt_saved_exit(&mut own, saved));
|
||||
assert_eq!(own.exit_portal, Some([1, 2, 3]));
|
||||
assert!(!own.exact_teleport);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_exit_keeps_the_gateways_exact_teleport() {
|
||||
let exact = BlockEntity::EndGateway(EndGateway {
|
||||
exact_teleport: true,
|
||||
..Default::default()
|
||||
});
|
||||
let plain = BlockEntity::EndGateway(EndGateway::default());
|
||||
assert!(exact_teleport(Some(&exact)));
|
||||
assert!(!exact_teleport(Some(&plain)));
|
||||
assert!(!exact_teleport(None));
|
||||
assert!(!exact_teleport(Some(&BlockEntity::DaylightDetector)));
|
||||
let exit = [8, 100, 0];
|
||||
// Exact: the exit itself, nothing is searched for.
|
||||
assert_eq!(exit_target(exit, true, |_| panic!("searched")), exit);
|
||||
assert_eq!(
|
||||
exit_target(exit, false, |e| [e[0], e[1] + 11, e[2]]),
|
||||
[8, 111, 0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_gateway_job_prefers_block_entity_then_legacy_then_heuristic() {
|
||||
let gateway = [702, 100, 0];
|
||||
let exit = [8, 100, 0];
|
||||
for exact in [true, false] {
|
||||
let entity = BlockEntity::EndGateway(EndGateway {
|
||||
exit_portal: Some(exit),
|
||||
exact_teleport: exact,
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(
|
||||
GatewayJob::for_gateway(gateway, Some(&entity), Some((END_SPAWN, !exact))),
|
||||
GatewayJob::Known { exit, exact },
|
||||
);
|
||||
}
|
||||
let empty = BlockEntity::EndGateway(EndGateway::default());
|
||||
for entity in [None, Some(&empty)] {
|
||||
assert_eq!(
|
||||
GatewayJob::for_gateway(gateway, entity, Some((exit, false))),
|
||||
GatewayJob::Known { exit, exact: false }
|
||||
);
|
||||
assert_eq!(
|
||||
GatewayJob::for_gateway(gateway, entity, None),
|
||||
GatewayJob::Known {
|
||||
exit: END_SPAWN,
|
||||
exact: true
|
||||
}
|
||||
);
|
||||
let nearby = [96, 75, 0];
|
||||
let exact = BlockEntity::EndGateway(EndGateway {
|
||||
exact_teleport: true,
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(
|
||||
GatewayJob::for_gateway(nearby, Some(&exact), None),
|
||||
GatewayJob::Find {
|
||||
gateway: nearby,
|
||||
exact: true
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
GatewayJob::for_gateway(nearby, entity, None),
|
||||
GatewayJob::Find {
|
||||
gateway: nearby,
|
||||
exact: false
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,12 +60,27 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Entity.setViewScale (LevelExtractor.extractVisibleEntities): the entity
|
||||
/// distance option times the render distance's boost — 1 at 8 chunks, 2.5
|
||||
/// at 20 or more. The render distance is the client setting, capped by
|
||||
/// the server's view distance when connected
|
||||
/// (Options.getEffectiveRenderDistance).
|
||||
pub(super) fn view_scale(&self) -> f64 {
|
||||
let distance = match &self.remote {
|
||||
Some(r) => self.settings.render_distance.min(r.view_distance),
|
||||
None => self.settings.render_distance,
|
||||
};
|
||||
(f64::from(distance) / 8.0).clamp(1.0, 2.5) * f64::from(self.settings.entity_distance)
|
||||
}
|
||||
}
|
||||
|
||||
/// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding
|
||||
/// box's mean edge, scaled by the entity distance option.
|
||||
pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 {
|
||||
/// box's mean edge, scaled by the view scale.
|
||||
pub(super) fn default_range(size: glam::DVec3, view_scale: f64) -> f64 {
|
||||
let edge = (size.x + size.y + size.z) / 3.0;
|
||||
let edge = if edge.is_nan() { 1.0 } else { edge };
|
||||
edge * 64.0 * f64::from(view_scale)
|
||||
edge * 64.0 * view_scale
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
|
||||
@@ -296,15 +296,23 @@ impl Game<'_> {
|
||||
if !creative
|
||||
&& !spectator
|
||||
&& hurtable
|
||||
&& let Ok(o) = p.hurt_blocking(
|
||||
&& let Ok(o) = p.hurt_caused_by(
|
||||
&self.motion.health,
|
||||
self.world.health_rules,
|
||||
id,
|
||||
amount,
|
||||
blocking,
|
||||
// The exploding mob is the causing entity.
|
||||
exploding.is_some(),
|
||||
)
|
||||
{
|
||||
outcome = o;
|
||||
// dealDefaultKnockback's `indicateDamage` points at the blast
|
||||
// (the source position), not the no-direction fallback.
|
||||
if o.knockback && o.blocked <= 0.0 {
|
||||
p.health
|
||||
.indicate_damage(center[0] - feet[0], center[2] - feet[2], p.yaw);
|
||||
}
|
||||
}
|
||||
if !spectator && !(creative && flying) {
|
||||
p.velocity = Vec3::new(
|
||||
@@ -314,9 +322,6 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if outcome.hurt && !creative {
|
||||
self.hurt_armor(amount);
|
||||
}
|
||||
if raised {
|
||||
self.after_block(outcome, amount, None, false);
|
||||
}
|
||||
@@ -391,9 +396,18 @@ impl Game<'_> {
|
||||
[feet[0] - w, feet[1], feet[2] - w],
|
||||
[feet[0] + w, feet[1] + h, feet[2] + w],
|
||||
);
|
||||
// The exploding mob is the damage source's entity, so victims
|
||||
// it kills drop its charged-creeper loot (`Creeper.killedEntity`).
|
||||
let source = horizon_client::mobs::Damage {
|
||||
kind: horizon_client::mobs::DamageKind::Explosion,
|
||||
attacker: None,
|
||||
// A projectile's owner (`getIndirectSourceEntity`), else
|
||||
// the exploding mob itself.
|
||||
attacker: self
|
||||
.combat
|
||||
.explosion_owner
|
||||
.or(exploding)
|
||||
.filter(|&o| o != m.id)
|
||||
.map(horizon_client::mobs::Who::Mob),
|
||||
from: Some(center),
|
||||
};
|
||||
if hurtable && !m.damage(damage(dist, exposure), source) {
|
||||
@@ -489,6 +503,15 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
/// Runs an explosion whose source empties the hives it destroys
|
||||
/// (`BeehiveBlock.getDrops`: primed TNT, creeper, wither skull, wither,
|
||||
/// TNT minecart).
|
||||
pub(super) fn with_hive_emptying_blast<R>(&mut self, blast: impl FnOnce(&mut Self) -> R) -> R {
|
||||
self.combat.hive_emptying_blast = true;
|
||||
let result = blast(self);
|
||||
self.combat.hive_emptying_blast = false;
|
||||
result
|
||||
}
|
||||
/// `Level.explode` on the server: positions, entities, blocks, fire; then
|
||||
/// the client's explosion sound.
|
||||
pub(super) fn server_explode(
|
||||
@@ -571,16 +594,16 @@ impl Game<'_> {
|
||||
let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7;
|
||||
self.audio
|
||||
.play("minecraft:entity.generic.explode", Some(center), 4.0, pitch);
|
||||
let block_count = if interaction == BlockInteraction::Keep {
|
||||
0
|
||||
} else {
|
||||
targets.len()
|
||||
};
|
||||
// ServerLevel.explode sends toBlow.size() whatever the interaction, and
|
||||
// `ServerExplosion.isSmall` also covers an explosion that keeps blocks.
|
||||
let block_count = targets.len();
|
||||
let small = radius < 2.0 || interaction == BlockInteraction::Keep;
|
||||
let (world, facts) = (&self.world, self.res.facts());
|
||||
self.particles.explosion(center, radius, block_count, &|b| {
|
||||
facts.is_air(world.block(b[0], b[1], b[2]))
|
||||
});
|
||||
self.lan_explode(center, radius, block_count);
|
||||
self.particles
|
||||
.explosion(center, small, block_count, radius, &|b| {
|
||||
facts.is_air(world.block(b[0], b[1], b[2]))
|
||||
});
|
||||
self.lan_explode(center, small, radius, block_count);
|
||||
Ok(())
|
||||
}
|
||||
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
|
||||
@@ -597,9 +620,30 @@ impl Game<'_> {
|
||||
}
|
||||
let name = self.res.facts().get(state).name.clone();
|
||||
let is_tnt = &*name == "minecraft:tnt";
|
||||
// CreakingHeartBlock.onExplosionHit: its creaking dies (no
|
||||
// experience, as Horizon does not track a TNT's owner).
|
||||
if &*name == "minecraft:creaking_heart" {
|
||||
self.creaking_heart_broken(pos, false);
|
||||
}
|
||||
// Block.onExplosionHit: the drops copy from the block entity, which
|
||||
// then spills its contents as the block turns to air.
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let is_hive = matches!(&*name, "minecraft:beehive" | "minecraft:bee_nest");
|
||||
// BeehiveBlock.getDrops: the bees of a hive blown up by TNT, a
|
||||
// creeper, a wither skull, a wither or a TNT minecart come out.
|
||||
if is_hive && self.combat.hive_emptying_blast {
|
||||
let facing = self
|
||||
.pack
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("facing").cloned());
|
||||
self.empty_hive(
|
||||
pos,
|
||||
horizon_client::beehive::facing_step(facing.as_deref()),
|
||||
horizon_client::beehive::Release::Emergency,
|
||||
);
|
||||
}
|
||||
if let Some(entity) = self.world.block_entities.get(&key).cloned() {
|
||||
let custom = self.world.block_names.get(&key).cloned();
|
||||
self.pending.record(pos, &entity, &name, custom);
|
||||
@@ -620,6 +664,7 @@ impl Game<'_> {
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
decay,
|
||||
false,
|
||||
);
|
||||
for mut stack in drops {
|
||||
if &*stack.item == "minecraft:air" || stack.count == 0 {
|
||||
@@ -631,6 +676,10 @@ impl Game<'_> {
|
||||
}
|
||||
self.pending.clear(pos);
|
||||
self.level_set(pos, self.world.air)?;
|
||||
// BeehiveBlock.onExplosionHit: the bees about turn on the player.
|
||||
if is_hive {
|
||||
self.anger_nearby_bees(pos);
|
||||
}
|
||||
// TntBlock.wasExploded: new PrimedTnt (its push drawn first), then
|
||||
// getRandomShortFuse(80); no game event.
|
||||
if is_tnt && self.ui.rules.bool("tnt_explodes") {
|
||||
|
||||
@@ -64,6 +64,25 @@ impl Game<'_> {
|
||||
pos: BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
data: 0,
|
||||
});
|
||||
} else if self
|
||||
.res
|
||||
.facts()
|
||||
.get(block.state)
|
||||
.name
|
||||
.starts_with("minecraft:suspicious_")
|
||||
{
|
||||
// BrushableBlock.onBrokenAfterFall.
|
||||
let at = BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
self.level_events.push(LevelEvent::LevelEvent {
|
||||
id: 2001,
|
||||
pos: at,
|
||||
data: block.state.0 as i32,
|
||||
});
|
||||
self.level_events.push(LevelEvent::GameEvent {
|
||||
pos: at,
|
||||
event: "minecraft:block_destroy",
|
||||
state: None,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -108,16 +127,10 @@ impl Game<'_> {
|
||||
} else {
|
||||
amount
|
||||
};
|
||||
let hurt = if let Some(p) = self.player.as_mut()
|
||||
if let Some(p) = self.player.as_mut()
|
||||
&& let Some(id) = self.motion.health.damage.id(kind)
|
||||
{
|
||||
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if hurt {
|
||||
self.hurt_armor(amount);
|
||||
let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,13 @@ use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Fangs {
|
||||
pos: [f64; 3],
|
||||
yaw: f32,
|
||||
pub id: u32,
|
||||
pub pos: [f64; 3],
|
||||
pub yaw: f32,
|
||||
warmup: i32,
|
||||
life: i32,
|
||||
pub life: i32,
|
||||
owner: u32,
|
||||
started: bool,
|
||||
pub started: bool,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct FangState {
|
||||
@@ -21,6 +22,11 @@ pub(super) struct FangState {
|
||||
}
|
||||
impl Game<'_> {
|
||||
pub(super) fn add_fangs(&mut self, at: [f64; 3], yaw: f32, delay: i32, owner: u32) {
|
||||
self.next_entity += 1;
|
||||
self.insert_fangs(self.next_entity, at, yaw, delay, owner);
|
||||
}
|
||||
|
||||
pub(super) fn insert_fangs(&mut self, id: u32, at: [f64; 3], yaw: f32, delay: i32, owner: u32) {
|
||||
if self.fangs.model.is_none() {
|
||||
self.fangs.model = horizon_client::mobs::load_model(
|
||||
&self.options.resources,
|
||||
@@ -29,6 +35,7 @@ impl Game<'_> {
|
||||
.map(Arc::new);
|
||||
}
|
||||
self.fangs.list.push(Fangs {
|
||||
id,
|
||||
pos: at,
|
||||
yaw,
|
||||
warmup: delay,
|
||||
@@ -37,6 +44,30 @@ impl Game<'_> {
|
||||
started: false,
|
||||
});
|
||||
}
|
||||
/// `EvokerFangs.handleEntityEvent`: only event 4 starts a client attack.
|
||||
pub(super) fn remote_fangs_event(&mut self, id: u32, event: i8) {
|
||||
if event == 4
|
||||
&& let Some(f) = self.fangs.list.iter_mut().find(|f| f.id == id)
|
||||
{
|
||||
f.started = true;
|
||||
self.audio.play_unshared(
|
||||
"minecraft:entity.evoker_fangs.attack",
|
||||
Some(f.pos),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `EvokerFangs.tick`: clients only advance animation, never damage or discard.
|
||||
pub(super) fn tick_remote_fangs(&mut self) {
|
||||
for f in &mut self.fangs.list {
|
||||
if f.started {
|
||||
f.life -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `EvokerFangs.tick`.
|
||||
pub(super) fn tick_fangs(&mut self) {
|
||||
let mut list = std::mem::take(&mut self.fangs.list);
|
||||
@@ -50,7 +81,8 @@ impl Game<'_> {
|
||||
}
|
||||
if !f.started {
|
||||
f.started = true;
|
||||
self.audio.play(
|
||||
self.lan_entity_event(f.id as i32, 4, f.pos);
|
||||
self.audio.play_unshared(
|
||||
"minecraft:entity.evoker_fangs.attack",
|
||||
Some(f.pos),
|
||||
1.0,
|
||||
@@ -71,26 +103,49 @@ impl Game<'_> {
|
||||
let b = horizon_core::geometry::Aabb::new(lo, hi);
|
||||
// Every player in the box, the server's players too.
|
||||
let pos = f.pos;
|
||||
// `EvokerFangs.dealDamageTo`: indirectMagic(fangs, owner) while the
|
||||
// owner lives, plain magic (nobody to name) once it is gone.
|
||||
let owner = self
|
||||
.mobs
|
||||
.iter()
|
||||
.any(|m| m.id == f.owner && m.alive())
|
||||
.then_some(f.owner);
|
||||
let bite = move |g: &mut Self| {
|
||||
if let Some(p) = g.player_view()
|
||||
&& p.alive
|
||||
&& p.bounds.intersects(b)
|
||||
{
|
||||
g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic");
|
||||
let kind = match owner {
|
||||
Some(_) => "minecraft:indirect_magic",
|
||||
None => "minecraft:magic",
|
||||
};
|
||||
g.mob_hits_player_caused(6.0, pos, kind, owner);
|
||||
}
|
||||
};
|
||||
bite(self);
|
||||
self.each_guest_hit(bite);
|
||||
// `AbstractIllager.considersEntityAsAlly`: with no teams, the illager
|
||||
// tag is allied; `Evoker.considersEntityAsAlly` adds a vex whose
|
||||
// owner is allied (itself or another illager). Teams are not modelled.
|
||||
let illager = |s: Species| {
|
||||
matches!(
|
||||
s,
|
||||
Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator
|
||||
)
|
||||
};
|
||||
let illagers: Vec<u32> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| illager(m.species()))
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
// A missing owner hurts everyone (`currentOwner == null`).
|
||||
let owner_known = illagers.contains(&f.owner);
|
||||
for m in &mut self.mobs {
|
||||
let ally = matches!(
|
||||
m.species(),
|
||||
Species::Evoker
|
||||
| Species::Illusioner
|
||||
| Species::Vex
|
||||
| Species::Pillager
|
||||
| Species::Vindicator
|
||||
| Species::Witch
|
||||
);
|
||||
let ally = owner_known
|
||||
&& (illager(m.species())
|
||||
|| m.species() == Species::Vex
|
||||
&& illagers.contains(&(m.extra.counter2 as u32)));
|
||||
if m.id != f.owner && !ally && m.alive() && m.bounds().intersects(b) {
|
||||
m.damage(
|
||||
6.0,
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(super) struct Rocket {
|
||||
/// The entity id a server tracks it by (0 until it is tracked).
|
||||
pub id: u32,
|
||||
pub(super) position: Vec3,
|
||||
previous: Vec3,
|
||||
pub(super) previous: Vec3,
|
||||
pub(super) velocity: Vec3,
|
||||
life: i32,
|
||||
lifetime: i32,
|
||||
@@ -62,11 +62,56 @@ impl Rocket {
|
||||
item,
|
||||
}
|
||||
}
|
||||
/// One tick of a server's client: the previous position, then `step`.
|
||||
pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) {
|
||||
/// One tick of a server's client: the rocket flies on by itself between
|
||||
/// the server's updates (a rocket that follows an entity is placed by the
|
||||
/// caller).
|
||||
pub(super) fn remote_step(&mut self, scene: &mut SceneCollisions) {
|
||||
self.previous = self.position;
|
||||
if self.attached_to.is_none() {
|
||||
self.free_flight(scene);
|
||||
}
|
||||
self.life += 1;
|
||||
self.position = step(self.position);
|
||||
}
|
||||
/// `FireworkRocketEntity.tick` for a rocket attached to no entity: speed
|
||||
/// up (an angled one keeps its motion) and rise, then move. True when a
|
||||
/// block stopped it.
|
||||
fn free_flight(&mut self, scene: &mut SceneCollisions) -> bool {
|
||||
let h = 0.125;
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
|
||||
Vec3::new(
|
||||
self.position.x + h,
|
||||
self.position.y + 2.0 * h,
|
||||
self.position.z + h,
|
||||
),
|
||||
);
|
||||
let wanted = if self.angled {
|
||||
self.velocity
|
||||
} else {
|
||||
Vec3::new(
|
||||
self.velocity.x * 1.15,
|
||||
self.velocity.y + 0.04,
|
||||
self.velocity.z * 1.15,
|
||||
)
|
||||
};
|
||||
let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) else {
|
||||
return false;
|
||||
};
|
||||
let blocked = (moved.x - wanted.x).abs() > 1e-7
|
||||
|| (moved.y - wanted.y).abs() > 1e-7
|
||||
|| (moved.z - wanted.z).abs() > 1e-7;
|
||||
let horizontal = (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7;
|
||||
self.position = Vec3::new(
|
||||
self.position.x + moved.x,
|
||||
self.position.y + moved.y,
|
||||
self.position.z + moved.z,
|
||||
);
|
||||
self.velocity = if horizontal {
|
||||
Vec3::new(self.velocity.x, wanted.y, self.velocity.z)
|
||||
} else {
|
||||
wanted
|
||||
};
|
||||
blocked
|
||||
}
|
||||
/// Position and motion (the dispenser parity fixture).
|
||||
pub(super) fn motion(&self) -> (Vec3, Vec3) {
|
||||
@@ -191,46 +236,14 @@ impl Game<'_> {
|
||||
r.velocity = p.velocity;
|
||||
}
|
||||
} else {
|
||||
// Not shot at an angle: accelerate (unless blocked sideways) and rise.
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
let h = 0.125;
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(r.position.x - h, r.position.y, r.position.z - h),
|
||||
Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h),
|
||||
);
|
||||
let wanted = if r.angled {
|
||||
r.velocity
|
||||
} else {
|
||||
Vec3::new(
|
||||
r.velocity.x * 1.15,
|
||||
r.velocity.y + 0.04,
|
||||
r.velocity.z * 1.15,
|
||||
)
|
||||
};
|
||||
if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) {
|
||||
let blocked = (moved.x - wanted.x).abs() > 1e-7
|
||||
|| (moved.y - wanted.y).abs() > 1e-7
|
||||
|| (moved.z - wanted.z).abs() > 1e-7;
|
||||
if r.angled && blocked {
|
||||
// hitTargetOrDeflectSelf: explode on the block.
|
||||
r.life = r.lifetime;
|
||||
}
|
||||
let horizontal =
|
||||
(moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7;
|
||||
r.position = Vec3::new(
|
||||
r.position.x + moved.x,
|
||||
r.position.y + moved.y,
|
||||
r.position.z + moved.z,
|
||||
);
|
||||
r.velocity = if horizontal {
|
||||
Vec3::new(r.velocity.x, wanted.y, r.velocity.z)
|
||||
} else {
|
||||
wanted
|
||||
};
|
||||
if r.free_flight(&mut scene) && r.angled {
|
||||
// hitTargetOrDeflectSelf: explode on the block.
|
||||
r.life = r.lifetime;
|
||||
}
|
||||
}
|
||||
let at = [r.position.x, r.position.y, r.position.z];
|
||||
@@ -372,24 +385,23 @@ impl Game<'_> {
|
||||
if self.creative || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let hurt = if let Some(p) = self.player.as_mut()
|
||||
if let Some(p) = self.player.as_mut()
|
||||
&& !p.health.dead_or_dying()
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
|
||||
{
|
||||
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if hurt {
|
||||
self.hurt_armor(amount);
|
||||
let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
|
||||
}
|
||||
}
|
||||
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
|
||||
/// lit at the rocket's light probe.
|
||||
pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
let orientation = glam::Mat4::from_quat(self.camera_orientation());
|
||||
for r in self.rockets.iter().filter(|r| !r.attached) {
|
||||
// shouldRender: not while attached to an entity (`isAttachedToEntity`).
|
||||
for r in self
|
||||
.rockets
|
||||
.iter()
|
||||
.filter(|r| !r.attached && r.attached_to.is_none())
|
||||
{
|
||||
// FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks;
|
||||
// EntityRenderer.shouldRender: its 0.25 box in the view.
|
||||
if !self.standing_entity_in_view(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! bobbing, lure and bite timers, open water, hooking mobs, retrieving the
|
||||
//! `gameplay/fishing` loot) and `FishingHookRenderer` (bobber and line).
|
||||
use super::{Game, view_vector};
|
||||
use horizon_client::advancements::EntityView;
|
||||
use horizon_client::lan::{entity::States, hub::Hub};
|
||||
use horizon_client::{
|
||||
blocks::Fluid,
|
||||
@@ -30,8 +31,8 @@ enum State {
|
||||
pub(super) struct Hook {
|
||||
/// Its entity id, which a server's players track it under.
|
||||
id: u32,
|
||||
position: Vec3,
|
||||
previous: Vec3,
|
||||
pub(super) position: Vec3,
|
||||
pub(super) previous: Vec3,
|
||||
velocity: Vec3,
|
||||
state: State,
|
||||
life: i32,
|
||||
@@ -77,7 +78,7 @@ impl Game<'_> {
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8);
|
||||
if self.hook.is_some() {
|
||||
let damage = self.retrieve_hook();
|
||||
let damage = self.retrieve_hook(stack);
|
||||
self.damage_held(damage);
|
||||
self.audio.play(
|
||||
"minecraft:entity.fishing_bobber.retrieve",
|
||||
@@ -143,7 +144,7 @@ impl Game<'_> {
|
||||
true
|
||||
}
|
||||
/// `FishingHook.retrieve`: the rod damage it costs.
|
||||
fn retrieve_hook(&mut self) -> u32 {
|
||||
fn retrieve_hook(&mut self, rod: &ItemStack) -> u32 {
|
||||
let Some(hook) = self.hook.take() else {
|
||||
return 0;
|
||||
};
|
||||
@@ -154,37 +155,64 @@ impl Game<'_> {
|
||||
let mut damage = 0;
|
||||
if let State::Hooked(id) = hook.state {
|
||||
// pullEntity: 0.1 of the way to the owner.
|
||||
let d = Vec3::new(
|
||||
owner.x - hook.position.x,
|
||||
owner.y - hook.position.y,
|
||||
owner.z - hook.position.z,
|
||||
);
|
||||
let pulled = |v: Vec3| Vec3::new(v.x + d.x * 0.1, v.y + d.y * 0.1, v.z + d.z * 0.1);
|
||||
let mut hooked_item = false;
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
let d = Vec3::new(
|
||||
owner.x - hook.position.x,
|
||||
owner.y - hook.position.y,
|
||||
owner.z - hook.position.z,
|
||||
);
|
||||
m.velocity = Vec3::new(
|
||||
m.velocity.x + d.x * 0.1,
|
||||
m.velocity.y + d.y * 0.1,
|
||||
m.velocity.z + d.z * 0.1,
|
||||
);
|
||||
m.velocity = pulled(m.velocity);
|
||||
} else if let Some(item) = self.dropped.iter_mut().find(|i| i.id == id) {
|
||||
item.velocity = pulled(item.velocity);
|
||||
hooked_item = true;
|
||||
}
|
||||
damage = 5;
|
||||
// CriteriaTriggers.FISHING_ROD_HOOKED with no items.
|
||||
let hooked = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map(|m| self.mob_entity(m));
|
||||
if let Some(hooked) = hooked {
|
||||
self.trigger_fishing_rod_hooked(rod, &hooked, &[]);
|
||||
}
|
||||
// `hookedIn instanceof ItemEntity ? 3 : 5`.
|
||||
damage = if hooked_item { 3 } else { 5 };
|
||||
} else if hook.nibble > 0 {
|
||||
let biome = self.biome_name_at(hook.position);
|
||||
let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources)
|
||||
else {
|
||||
return damage;
|
||||
};
|
||||
// `withLuck(this.luck + owner.getLuck())`: the rod's Luck of the Sea
|
||||
// plus the owner's luck attribute (the Luck and Bad Luck effects).
|
||||
let owner_luck = self
|
||||
.player
|
||||
.as_mut()
|
||||
.and_then(|p| p.attribute("minecraft:luck").ok())
|
||||
.unwrap_or(0.0) as f32;
|
||||
let mut random = self.world.random.clone();
|
||||
let items = loot.roll(
|
||||
"minecraft:gameplay/fishing",
|
||||
&mut random,
|
||||
hook.luck as f32,
|
||||
hook.luck as f32 + owner_luck,
|
||||
biome.as_deref(),
|
||||
Some(hook.open_water),
|
||||
);
|
||||
self.world.random = random;
|
||||
// FishingHook.retrieve: fish_caught for a catch.
|
||||
self.stats.custom("fish_caught", 1);
|
||||
let mut caught = Vec::new();
|
||||
for stack in items {
|
||||
// FishingHook.retrieve: fish_caught for each catch in #minecraft:fishes.
|
||||
if self
|
||||
.res
|
||||
.items()
|
||||
.item_tags
|
||||
.get("minecraft:fishes")
|
||||
.is_some_and(|t| t.contains(stack.item.as_str()))
|
||||
{
|
||||
self.stats.custom("fish_caught", 1);
|
||||
}
|
||||
let mut item = ItemStack {
|
||||
item: Arc::from(stack.item.as_str()),
|
||||
count: stack.count.max(1) as u32,
|
||||
@@ -205,6 +233,7 @@ impl Game<'_> {
|
||||
if let Some(potion) = &stack.potion {
|
||||
item = item.with_potion(potion);
|
||||
}
|
||||
caught.push(item.clone());
|
||||
let (dx, dy, dz) = (
|
||||
owner.x - hook.position.x,
|
||||
owner.y - hook.position.y,
|
||||
@@ -224,6 +253,15 @@ impl Game<'_> {
|
||||
let xp = self.world.random.next_int_bound(6).unwrap_or(0) as u32 + 1;
|
||||
self.spawn_orbs([owner.x, owner.y + 0.5, owner.z + 0.5], xp);
|
||||
}
|
||||
// CriteriaTriggers.FISHING_ROD_HOOKED: the hook itself is the entity.
|
||||
let bobber = EntityView {
|
||||
kind: "minecraft:fishing_bobber".into(),
|
||||
position: [hook.position.x, hook.position.y, hook.position.z],
|
||||
on_ground: hook.on_ground,
|
||||
fishing_open_water: Some(hook.open_water),
|
||||
..Default::default()
|
||||
};
|
||||
self.trigger_fishing_rod_hooked(rod, &bobber, &caught);
|
||||
damage = 1;
|
||||
}
|
||||
if hook.on_ground {
|
||||
@@ -416,6 +454,8 @@ impl Game<'_> {
|
||||
let options = ParticleOptions::simple(kind);
|
||||
self.particles
|
||||
.send_particles(&options, at, spread, speed, count);
|
||||
// The players a server serves are sent them too.
|
||||
self.lan_send_particles(&options, at, spread, speed, count);
|
||||
}
|
||||
/// `FishingHook.tick`.
|
||||
pub(super) fn tick_fishing(&mut self) {
|
||||
@@ -457,35 +497,47 @@ impl Game<'_> {
|
||||
self.hook = Some(h);
|
||||
return;
|
||||
}
|
||||
// checkCollision: hook the first living mob it touches.
|
||||
// checkCollision: hook the first living mob it touches, or (via
|
||||
// `canHitEntity`) a dropped item.
|
||||
let bb = bounds(h.position);
|
||||
let (lo, hi) = (bb.min_position(), bb.max_position());
|
||||
if let Some(m) = self.mobs.iter().find(|m| {
|
||||
let mb = m.bounds();
|
||||
let (a, z) = (mb.min_position(), mb.max_position());
|
||||
m.alive()
|
||||
&& a.x < hi.x
|
||||
&& lo.x < z.x
|
||||
&& a.y < hi.y
|
||||
&& lo.y < z.y
|
||||
&& a.z < hi.z
|
||||
&& lo.z < z.z
|
||||
}) {
|
||||
h.state = State::Hooked(m.id);
|
||||
let touches = |b: Aabb| {
|
||||
let (a, z) = (b.min_position(), b.max_position());
|
||||
a.x < hi.x && lo.x < z.x && a.y < hi.y && lo.y < z.y && a.z < hi.z && lo.z < z.z
|
||||
};
|
||||
let hit = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.alive() && touches(m.bounds()))
|
||||
.map(|m| m.id)
|
||||
.or_else(|| {
|
||||
self.dropped
|
||||
.iter()
|
||||
.find(|i| touches(i.bounds()))
|
||||
.map(|i| i.id)
|
||||
});
|
||||
if let Some(id) = hit {
|
||||
h.state = State::Hooked(id);
|
||||
h.velocity = Vec3::ZERO;
|
||||
self.hook = Some(h);
|
||||
return;
|
||||
}
|
||||
}
|
||||
State::Hooked(id) => {
|
||||
match self.mobs.iter().find(|m| m.id == id && m.alive()) {
|
||||
Some(m) => {
|
||||
h.position = Vec3::new(
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) * 0.8,
|
||||
m.position.z,
|
||||
)
|
||||
}
|
||||
// updateHookedEntity: ride the hooked mob or item at 0.8 of its height.
|
||||
let hooked = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id && m.alive())
|
||||
.map(|m| (m.position, f64::from(m.height())))
|
||||
.or_else(|| {
|
||||
self.dropped
|
||||
.iter()
|
||||
.find(|i| i.id == id)
|
||||
.map(|i| (i.position, horizon_client::entities::ItemEntity::WIDTH))
|
||||
});
|
||||
match hooked {
|
||||
Some((at, height)) => h.position = Vec3::new(at.x, at.y + height * 0.8, at.z),
|
||||
None => h.state = State::Flying,
|
||||
}
|
||||
self.hook = Some(h);
|
||||
@@ -614,6 +666,8 @@ impl Game<'_> {
|
||||
layer: 0,
|
||||
color: 0xFFFF_FFFF,
|
||||
light: packed,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -741,8 +795,8 @@ impl Game<'_> {
|
||||
pub(super) struct RemoteHook {
|
||||
id: u32,
|
||||
owner: u32,
|
||||
position: Vec3,
|
||||
previous: Vec3,
|
||||
pub(super) position: Vec3,
|
||||
pub(super) previous: Vec3,
|
||||
}
|
||||
|
||||
impl Hook {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user