Merge main into fix/bundle-dump-on-use
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,4 +4,4 @@
|
||||
# A line with only `paused` stops every reviewer's `/nightly` (Ludovic's still work).
|
||||
kacpherek # added by Ludovic, 2026-10-27
|
||||
rdbtCVS # added by Ludovic, 2026-10-27
|
||||
levzzz5154 # added by Ludovic, 2026-10-27
|
||||
Online5277 # added by Ludovic, 2026-10-27 (his top three by merged pull requests)
|
||||
|
||||
@@ -190,19 +190,31 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
|
||||
.filter(|p| *p >= 1)
|
||||
.map(crate::text::ClickEvent::ChangePage),
|
||||
Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand),
|
||||
Some("run_command") => text("command").map(crate::text::ClickEvent::RunCommand),
|
||||
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))));
|
||||
// HoverEvent.ShowText and ShowItem.
|
||||
if let Some(e) = o.get("hover_event").and_then(Value::as_object) {
|
||||
match e.get("action").and_then(Value::as_str) {
|
||||
Some("show_text") => {
|
||||
if let Some(value) = e.get("value") {
|
||||
style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s))));
|
||||
}
|
||||
}
|
||||
Some("show_item") if e.get("id").is_some_and(Value::is_string) => {
|
||||
style.hover_item = Some(Box::new(Value::Object(e.clone())));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
style.insertion = o
|
||||
.get("insertion")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned);
|
||||
style
|
||||
}
|
||||
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
|
||||
|
||||
@@ -47,6 +47,8 @@ pub enum ClickEvent {
|
||||
/// `ClickEvent.ChangePage`: a book's page, counted from 1.
|
||||
ChangePage(i32),
|
||||
SuggestCommand(String),
|
||||
/// `ClickEvent.RunCommand`: the command, with or without its `/`.
|
||||
RunCommand(String),
|
||||
CopyToClipboard(String),
|
||||
/// A local file to open with the system handler.
|
||||
/// Only allow this in locally constructed messages, never server/LAN text.
|
||||
@@ -65,6 +67,10 @@ pub struct Style {
|
||||
pub click: Option<ClickEvent>,
|
||||
/// Hover text.
|
||||
pub hover: Option<Box<Text>>,
|
||||
/// `HoverEvent.ShowItem`: the event's `{id, count?, components?}` object.
|
||||
pub hover_item: Option<Box<Value>>,
|
||||
/// `Style.insertion`: the text a Shift-click puts in the chat box.
|
||||
pub insertion: Option<String>,
|
||||
/// The font (`FontDescription.Resource`), a full id like
|
||||
/// `minecraft:alt`; the default font when unset.
|
||||
pub font: Option<String>,
|
||||
@@ -94,6 +100,12 @@ impl Style {
|
||||
if self.hover.is_none() {
|
||||
self.hover.clone_from(&base.hover);
|
||||
}
|
||||
if self.hover_item.is_none() {
|
||||
self.hover_item.clone_from(&base.hover_item);
|
||||
}
|
||||
if self.insertion.is_none() {
|
||||
self.insertion.clone_from(&base.insertion);
|
||||
}
|
||||
if self.font.is_none() {
|
||||
self.font.clone_from(&base.font);
|
||||
}
|
||||
@@ -499,7 +511,7 @@ impl Text {
|
||||
}
|
||||
|
||||
/// The style fields of a component's JSON.
|
||||
const STYLE_KEYS: [&str; 9] = [
|
||||
const STYLE_KEYS: [&str; 10] = [
|
||||
"color",
|
||||
"bold",
|
||||
"italic",
|
||||
@@ -508,6 +520,7 @@ const STYLE_KEYS: [&str; 9] = [
|
||||
"obfuscated",
|
||||
"click_event",
|
||||
"hover_event",
|
||||
"insertion",
|
||||
"font",
|
||||
];
|
||||
/// Style.Serializer: the fields a style sets.
|
||||
@@ -541,6 +554,9 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
|
||||
ClickEvent::CopyToClipboard(value) => {
|
||||
json!({ "action": "copy_to_clipboard", "value": value })
|
||||
}
|
||||
ClickEvent::RunCommand(command) => {
|
||||
json!({ "action": "run_command", "command": command })
|
||||
}
|
||||
ClickEvent::OpenFile(path) => json!({ "action": "open_file", "path": path }),
|
||||
};
|
||||
out.push(("click_event".to_owned(), event));
|
||||
@@ -550,6 +566,13 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
|
||||
"hover_event".to_owned(),
|
||||
json!({ "action": "show_text", "value": hover.component() }),
|
||||
));
|
||||
} else if let Some(Value::Object(item)) = style.hover_item.as_deref() {
|
||||
let mut event = item.clone();
|
||||
event.insert("action".into(), "show_item".into());
|
||||
out.push(("hover_event".to_owned(), Value::Object(event)));
|
||||
}
|
||||
if let Some(insertion) = &style.insertion {
|
||||
out.push(("insertion".to_owned(), insertion.clone().into()));
|
||||
}
|
||||
if let Some(font) = &style.font {
|
||||
out.push(("font".to_owned(), font.clone().into()));
|
||||
|
||||
@@ -74,6 +74,9 @@ pub fn main() -> Result<()> {
|
||||
biomes: &biomes,
|
||||
registry: assets.registry,
|
||||
raining_at: &|_| false,
|
||||
height_no_leaves: &|_| 0,
|
||||
firefly_bush_sounds: false,
|
||||
sky_darken: 0,
|
||||
marker: target.map(|name| (name, &options as &dyn Fn(_) -> _)),
|
||||
model_offset: &|_, _, _| None,
|
||||
gateway_particles: &|_, _| 0,
|
||||
|
||||
@@ -570,6 +570,10 @@ fn player_damage(e: &MobEvent) -> f32 {
|
||||
MobEvent::AttackPlayer(amount, _)
|
||||
| MobEvent::AttackPlayerWithEffect { amount, .. }
|
||||
| MobEvent::DamagePlayer { amount, .. } => *amount,
|
||||
MobEvent::SonicBoom {
|
||||
target: Who::Player,
|
||||
..
|
||||
} => 10.0,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
@@ -583,6 +587,10 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
|
||||
MobEvent::AttackPlayer(amount, _)
|
||||
| MobEvent::AttackPlayerWithEffect { amount, .. }
|
||||
| MobEvent::DamagePlayer { amount, .. } => *amount > 0.0,
|
||||
MobEvent::SonicBoom {
|
||||
target: Who::Player,
|
||||
..
|
||||
} => true,
|
||||
// ServerExplosion.hurtEntities: within twice the radius every hit does damage.
|
||||
MobEvent::Explode(at, radius, _) => {
|
||||
let d = Vec3::new(at[0], at[1], at[2])
|
||||
|
||||
@@ -93,6 +93,14 @@ enum Animate {
|
||||
LightningRod(usize),
|
||||
/// `WetSpongeBlock.animateTick`.
|
||||
WetSponge,
|
||||
FireflyBush,
|
||||
/// An open eyeblossom (`Type.OPEN.emitSounds()`).
|
||||
OpenEyeblossom,
|
||||
PaleHangingMoss,
|
||||
/// `DryVegetationBlock`: a dead bush.
|
||||
DeadBush,
|
||||
/// `ShortDryGrassBlock` and `TallDryGrassBlock`.
|
||||
DryGrass,
|
||||
}
|
||||
fn step(facing: &str) -> [i32; 3] {
|
||||
match facing {
|
||||
@@ -225,6 +233,11 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
// 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),
|
||||
"firefly_bush" => Animate::FireflyBush,
|
||||
"open_eyeblossom" => Animate::OpenEyeblossom,
|
||||
"pale_hanging_moss" => Animate::PaleHangingMoss,
|
||||
"dead_bush" => Animate::DeadBush,
|
||||
"short_dry_grass" | "tall_dry_grass" => Animate::DryGrass,
|
||||
"sculk_sensor" | "calibrated_sculk_sensor"
|
||||
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
|
||||
{
|
||||
@@ -295,6 +308,10 @@ pub struct AnimateTables {
|
||||
desert_sand_sounds: Vec<bool>,
|
||||
/// `#required_for_poplar_leaf_ambience` (overworld natural logs).
|
||||
poplar_leaf_logs: Vec<bool>,
|
||||
/// `#triggers_ambient_desert_dry_vegetation_block_sounds`.
|
||||
desert_dry_vegetation_sounds: Vec<bool>,
|
||||
terracotta: Vec<bool>,
|
||||
pale_oak_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`).
|
||||
@@ -391,6 +408,11 @@ impl AnimateTables {
|
||||
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"),
|
||||
desert_dry_vegetation_sounds: by_state(
|
||||
"minecraft:triggers_ambient_desert_dry_vegetation_block_sounds",
|
||||
),
|
||||
terracotta: by_state("minecraft:terracotta"),
|
||||
pale_oak_logs: by_state("minecraft:pale_oak_logs"),
|
||||
burnable,
|
||||
ambient,
|
||||
})
|
||||
@@ -416,6 +438,12 @@ pub struct AnimateContext<'a> {
|
||||
pub registry: &'a BlockRegistry,
|
||||
/// `Level.isRainingAt`.
|
||||
pub raining_at: &'a dyn Fn([i32; 3]) -> bool,
|
||||
/// `getHeight(MOTION_BLOCKING_NO_LEAVES, x, z)` at a position's column.
|
||||
pub height_no_leaves: &'a dyn Fn([i32; 3]) -> i32,
|
||||
/// `EnvironmentAttributes.FIREFLY_BUSH_SOUNDS` (overworld day timeline).
|
||||
pub firefly_bush_sounds: bool,
|
||||
/// `Level.getSkyDarken`, for `getMaxLocalRawBrightness`.
|
||||
pub sky_darken: i32,
|
||||
/// Creative main-hand marker block and a resolver for each placed state's sprite.
|
||||
pub marker: Option<(&'a str, &'a dyn Fn(BlockStateId) -> Option<ParticleOptions>)>,
|
||||
/// `BlockState.getOffset` of a state at (x, z), for blocks with a random model offset.
|
||||
@@ -474,6 +502,12 @@ impl AnimateContext<'_> {
|
||||
],
|
||||
))
|
||||
}
|
||||
/// `Level.getMaxLocalRawBrightness`: the brighter of block light and
|
||||
/// sky light less the sky darkening.
|
||||
fn max_local_raw_brightness(&self, p: [i32; 3]) -> i32 {
|
||||
let light = self.world.light(p[0], p[1], p[2]);
|
||||
i32::from(light & 15).max(i32::from(light >> 4) - self.sky_darken)
|
||||
}
|
||||
fn offset_of(&self, state: BlockStateId, p: [i32; 3]) -> [f64; 3] {
|
||||
(self.model_offset)(state, p[0], p[2]).unwrap_or([0.0; 3])
|
||||
}
|
||||
@@ -532,7 +566,7 @@ fn do_animate_tick(
|
||||
return;
|
||||
}
|
||||
let state = ctx.state(pos);
|
||||
block_animate_tick(tables, engine, ctx, state, pos);
|
||||
block_animate_tick(tables, engine, ctx, state, pos, center);
|
||||
let facts = ctx.facts.get(state);
|
||||
if facts.fluid != Fluid::None {
|
||||
fluid_animate_tick(
|
||||
@@ -688,6 +722,22 @@ fn beehive_drip(
|
||||
];
|
||||
add(engine, T::DrippingHoney, p, [0.0; 3]);
|
||||
}
|
||||
/// `AmbientDesertBlockSoundsPlayer.shouldPlayDesertDryVegetationBlockSounds`:
|
||||
/// sand or terracotta two blocks deep.
|
||||
fn desert_dry_vegetation_sounds(
|
||||
tables: &AnimateTables,
|
||||
ctx: &AnimateContext,
|
||||
below: [i32; 3],
|
||||
) -> bool {
|
||||
let triggers = |p: [i32; 3]| {
|
||||
tables
|
||||
.desert_dry_vegetation_sounds
|
||||
.get(ctx.state(p).0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
};
|
||||
triggers(below) && triggers([below[0], below[1] - 1, below[2]])
|
||||
}
|
||||
/// `WaterFluid.animateTick` / `LavaFluid.animateTick`.
|
||||
fn fluid_animate_tick(
|
||||
engine: &mut ParticleEngine,
|
||||
@@ -763,6 +813,7 @@ fn block_animate_tick(
|
||||
ctx: &AnimateContext,
|
||||
state: BlockStateId,
|
||||
pos: [i32; 3],
|
||||
player: [i32; 3],
|
||||
) {
|
||||
let (fx, fy, fz) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
|
||||
match tables.kind(state) {
|
||||
@@ -1152,6 +1203,99 @@ fn block_animate_tick(
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::FireflyBush => {
|
||||
// FireflyBushBlock.animateTick: the idle sound on a quiet night
|
||||
// under open sky, and fireflies in the dark within 5 blocks.
|
||||
if next_int(engine.random(), 30) == 0
|
||||
&& ctx.firefly_bush_sounds
|
||||
&& (ctx.height_no_leaves)(pos) <= pos[1]
|
||||
{
|
||||
let name = "minecraft:block.firefly_bush.idle";
|
||||
sound(engine, name, [fx, fy, fz], 1.0, 1.0);
|
||||
}
|
||||
if ctx.max_local_raw_brightness(pos) <= 13 {
|
||||
let r = engine.random();
|
||||
if r.next_double() <= 0.7 {
|
||||
let p = [
|
||||
fx + r.next_double() * 10.0 - 5.0,
|
||||
fy + r.next_double() * 5.0,
|
||||
fz + r.next_double() * 10.0 - 5.0,
|
||||
];
|
||||
add(engine, T::Firefly, p, [0.0; 3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::OpenEyeblossom => {
|
||||
// EyeblossomBlock.animateTick: pale moss below.
|
||||
if next_int(engine.random(), 700) == 0 {
|
||||
let below = ctx.state([pos[0], pos[1] - 1, pos[2]]);
|
||||
if ctx
|
||||
.registry
|
||||
.state(below)
|
||||
.is_some_and(|s| s.name == "minecraft:pale_moss_block")
|
||||
{
|
||||
let name = "minecraft:block.eyeblossom.idle";
|
||||
sound(engine, name, [fx, fy, fz], 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::PaleHangingMoss => {
|
||||
// HangingMossBlock.animateTick: under pale oak logs or leaves.
|
||||
if next_int(engine.random(), 500) == 0 {
|
||||
let above = ctx.state([pos[0], pos[1] + 1, pos[2]]);
|
||||
let pale_leaves = ctx
|
||||
.registry
|
||||
.state(above)
|
||||
.is_some_and(|s| s.name == "minecraft:pale_oak_leaves");
|
||||
if pale_leaves
|
||||
|| tables
|
||||
.pale_oak_logs
|
||||
.get(above.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let name = "minecraft:block.pale_hanging_moss.idle";
|
||||
sound(engine, name, [fx, fy, fz], 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::DeadBush => {
|
||||
// AmbientDesertBlockSoundsPlayer.playAmbientDeadBushSounds.
|
||||
if next_int(engine.random(), 130) == 0 {
|
||||
let below = [pos[0], pos[1] - 1, pos[2]];
|
||||
let state = ctx.state(below);
|
||||
let red_sand = ctx
|
||||
.registry
|
||||
.state(state)
|
||||
.is_some_and(|s| s.name == "minecraft:red_sand");
|
||||
let terracotta = tables
|
||||
.terracotta
|
||||
.get(state.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false);
|
||||
if (red_sand || terracotta) && next_int(engine.random(), 3) != 0 {
|
||||
return;
|
||||
}
|
||||
if desert_dry_vegetation_sounds(tables, ctx, below) {
|
||||
let name = "minecraft:block.deadbush.idle";
|
||||
sound(engine, name, [fx, fy, fz], 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::DryGrass => {
|
||||
// AmbientDesertBlockSoundsPlayer.playAmbientDryGrassSounds:
|
||||
// played at the player.
|
||||
if next_int(engine.random(), 200) == 0
|
||||
&& desert_dry_vegetation_sounds(tables, ctx, [pos[0], pos[1] - 1, pos[2]])
|
||||
{
|
||||
let at = [
|
||||
f64::from(player[0]) + 0.5,
|
||||
f64::from(player[1]),
|
||||
f64::from(player[2]) + 0.5,
|
||||
];
|
||||
sound(engine, "minecraft:block.dry_grass.ambient", at, 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
Animate::EndPortal => {
|
||||
// EndPortalBlock.animateTick: one smoke particle above the surface.
|
||||
let r = engine.random();
|
||||
|
||||
@@ -66,6 +66,13 @@ impl BiomeInfo {
|
||||
}
|
||||
.height_adjusted(pos, sea_level)
|
||||
}
|
||||
/// `Biome.getPrecipitationAt` in the Overworld (sea level 63): None
|
||||
/// without precipitation, else whether it falls as snow
|
||||
/// (`getHeightAdjustedTemperature` below 0.15).
|
||||
pub fn snows_at(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
||||
self.precipitation
|
||||
.then(|| self.temperature_at(BlockPos::new(x, y, z), 63) < 0.15)
|
||||
}
|
||||
}
|
||||
pub struct Biomes {
|
||||
pub list: Vec<BiomeInfo>,
|
||||
|
||||
@@ -5,7 +5,11 @@
|
||||
//! (`entity-models.json`); transforms, animation and textures follow each
|
||||
//! vanilla renderer. Faces are lit like the `entity` shader: the lightmap at
|
||||
//! the block plus `minecraft_mix_light` with the level's two diffuse lights.
|
||||
use crate::{hud::Rect, mesher::Vertex, world::World};
|
||||
use crate::{
|
||||
hud::Rect,
|
||||
mesher::{CULL_BACK, Vertex},
|
||||
world::World,
|
||||
};
|
||||
use glam::{DVec3, Mat4, Quat, Vec3};
|
||||
use horizon_core::geometry::{
|
||||
Direction,
|
||||
@@ -1416,6 +1420,7 @@ impl BlockEntityRenderer {
|
||||
m *= around(Mat4::from_rotation_y(turn * decay), pivot);
|
||||
}
|
||||
}
|
||||
let first = out.len();
|
||||
if let Some(paint) =
|
||||
paint("entity/decorated_pot/decorated_pot_base", 0xFFFFFF, packed)
|
||||
{
|
||||
@@ -1433,6 +1438,11 @@ impl BlockEntityRenderer {
|
||||
draw_part(part, side, m, &none, paint, out);
|
||||
}
|
||||
}
|
||||
// `DecoratedPotRenderer` submits every part with `entitySolid`, which culls
|
||||
// back faces: the flat `top` and `bottom` planes show one side each.
|
||||
for vertex in &mut out[first..] {
|
||||
vertex.normal = CULL_BACK;
|
||||
}
|
||||
}
|
||||
Kind::EndPortal => {
|
||||
// TheEndPortalRenderer.TRANSFORMATION: y from 6/16 to 12/16; only the
|
||||
@@ -2128,4 +2138,70 @@ mod tests {
|
||||
assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}");
|
||||
assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab");
|
||||
}
|
||||
/// `DecoratedPotRenderer` submits every part with `RenderTypes.entitySolid`,
|
||||
/// whose pipeline culls back faces. The pot's `top` and `bottom` are flat
|
||||
/// boxes, so without that cull both sides of each plane are drawn and they
|
||||
/// z-fight: the pot renders wrong.
|
||||
#[test]
|
||||
fn the_decorated_pot_culls_its_back_faces() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("entity-models.json").exists() {
|
||||
return;
|
||||
}
|
||||
let assets = crate::assets::Assets::load(&root).unwrap();
|
||||
let registry = assets.registry;
|
||||
let renderer = BlockEntityRenderer::load(&root, registry).unwrap();
|
||||
let state = registry.default_state("minecraft:decorated_pot").unwrap();
|
||||
let sprites: HashMap<String, Rect> = [
|
||||
"entity/decorated_pot/decorated_pot_base",
|
||||
"entity/decorated_pot/decorated_pot_side",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
(
|
||||
name.to_owned(),
|
||||
Rect {
|
||||
u0: 0.25,
|
||||
v0: 0.125,
|
||||
u1: 0.375,
|
||||
v1: 0.25,
|
||||
w: 16,
|
||||
h: 16,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let world = World::new(BlockStateId(0), 1);
|
||||
let scene = Scene {
|
||||
camera: DVec3::ZERO,
|
||||
orientation: Quat::IDENTITY,
|
||||
anim: &|_| BlockAnim::default(),
|
||||
texts: None,
|
||||
partial: 0.5,
|
||||
game_time: 0,
|
||||
max_y: 320,
|
||||
world: &world,
|
||||
sprites: &sprites,
|
||||
nether: false,
|
||||
lid: &|_| 0.0,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
skull: &|_| None,
|
||||
glyph: &|_| (None, 0.0),
|
||||
};
|
||||
let mut verts = Vec::new();
|
||||
renderer.render_block(&scene, [0; 3], state.0, Mat4::IDENTITY, 0xff, &mut verts);
|
||||
// Vanilla submits 28 quads for a plain pot, and the cull keeps them all.
|
||||
assert_eq!(
|
||||
verts.len() / 4,
|
||||
28,
|
||||
"the pot submits all of vanilla's quads"
|
||||
);
|
||||
assert!(
|
||||
verts.iter().all(|v| v.normal == CULL_BACK),
|
||||
"entitySolid culls the pot's back faces"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -556,26 +556,34 @@ impl Chat {
|
||||
pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option<Text> {
|
||||
self.style_at(font, height, x, y)?.hover.map(|h| *h)
|
||||
}
|
||||
/// ChatComponent.getClickedComponentStyleAt.
|
||||
fn style_at(
|
||||
&self,
|
||||
font: &crate::font::Font,
|
||||
height: i32,
|
||||
x: f64,
|
||||
y: f64,
|
||||
) -> Option<crate::text::Style> {
|
||||
/// The wrapped line under a GUI-space cursor while chat is focused, and
|
||||
/// the cursor's x within it (the text starts at 0).
|
||||
fn line_at(&self, height: i32, x: f64, y: f64) -> Option<(&Line, f64)> {
|
||||
let scale = self.options.scale as f32;
|
||||
let mut x = x / f64::from(scale) - 4.0;
|
||||
let x = x / f64::from(scale) - 4.0;
|
||||
let bottom = hud_layout::floor((height - 40) as f32 / scale);
|
||||
let from_bottom = f64::from(bottom) - y / f64::from(scale);
|
||||
if x < 0.0 || x >= f64::from(self.max_width()) || from_bottom <= 0.0 {
|
||||
if x >= f64::from(self.max_width()) || from_bottom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let row = (from_bottom / f64::from(self.options.line_height())).ceil() as usize - 1;
|
||||
if row >= self.lines_per_page(true) {
|
||||
return None;
|
||||
}
|
||||
let line = self.lines.get(self.scroll + row)?;
|
||||
Some((self.lines.get(self.scroll + row)?, x))
|
||||
}
|
||||
/// ChatComponent.getClickedComponentStyleAt.
|
||||
pub fn style_at(
|
||||
&self,
|
||||
font: &crate::font::Font,
|
||||
height: i32,
|
||||
x: f64,
|
||||
y: f64,
|
||||
) -> Option<crate::text::Style> {
|
||||
let (line, mut x) = self.line_at(height, x, y)?;
|
||||
if x < 0.0 {
|
||||
return None;
|
||||
}
|
||||
let content = line.content.resolve_legacy();
|
||||
for (c, style) in content.chars() {
|
||||
x -= f64::from(font.advance(c, style));
|
||||
@@ -585,6 +593,13 @@ impl Chat {
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Whether the cursor is on a line's indicator bar while chat is focused
|
||||
/// (`DrawingFocusedGraphicsAccess.handleTag`), whose tooltip is the
|
||||
/// message tag's text.
|
||||
pub fn indicator_at(&self, height: i32, x: f64, y: f64) -> bool {
|
||||
self.line_at(height, x, y)
|
||||
.is_some_and(|(line, x)| line.indicator.is_some() && (-4.0..-2.0).contains(&x))
|
||||
}
|
||||
/// Plain text of the newest messages (for tests and the control socket).
|
||||
pub fn recent_lines(&self, n: usize) -> Vec<String> {
|
||||
self.messages
|
||||
|
||||
@@ -63,13 +63,24 @@ impl Confirm {
|
||||
atlas: &HudAtlas,
|
||||
cursor: (f32, f32),
|
||||
labels: [&Text; 2],
|
||||
) {
|
||||
self.draw_active(batch, atlas, cursor, labels, true);
|
||||
}
|
||||
/// `draw` with the buttons greyed out while `setDelay` runs (`active` false).
|
||||
pub fn draw_active(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
atlas: &HudAtlas,
|
||||
cursor: (f32, f32),
|
||||
labels: [&Text; 2],
|
||||
active: bool,
|
||||
) {
|
||||
for (line, x, y) in &self.lines {
|
||||
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
|
||||
}
|
||||
for ((bx, by), label) in self.buttons.into_iter().zip(labels) {
|
||||
let hover = ui::hovered(cursor, bx, by, 150.0, 20.0);
|
||||
ui::button(batch, atlas, bx, by, 150.0, 20.0, label, true, hover);
|
||||
let hover = active && ui::hovered(cursor, bx, by, 150.0, 20.0);
|
||||
ui::button(batch, atlas, bx, by, 150.0, 20.0, label, active, hover);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,15 +129,16 @@ fn periodic(id: &str, tick: i32, amp: i32) -> Option<EffectAction> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `InstantenousMobEffect.applyInstantenousEffect` (potions apply these directly).
|
||||
/// `HealOrHarmMobEffect.applyInstantaneousEffect` (potions apply these directly;
|
||||
/// the amount rounds to the nearest whole point).
|
||||
pub fn instant(id: &str, amp: i32, scale: f64) -> Option<EffectAction> {
|
||||
match id {
|
||||
"instant_health" => Some(EffectAction::Heal(
|
||||
(scale * f64::from(4 << amp.min(30))) as i32 as f32,
|
||||
(scale * f64::from(4 << amp.min(30)) + 0.5) as i32 as f32,
|
||||
)),
|
||||
"instant_damage" => Some(EffectAction::Hurt(
|
||||
"minecraft:magic",
|
||||
(scale * f64::from(6 << amp.min(30))) as i32 as f32,
|
||||
(scale * f64::from(6 << amp.min(30)) + 0.5) as i32 as f32,
|
||||
)),
|
||||
"saturation" => Some(EffectAction::Eat(amp + 1, 1.0)),
|
||||
_ => None,
|
||||
|
||||
@@ -19,6 +19,8 @@ pub struct ItemEntity {
|
||||
pub id: u32,
|
||||
pub stack: ItemStack,
|
||||
pub thrower: Option<[i32; 4]>,
|
||||
/// `ItemEntity.target`: the only player who may pick the item up.
|
||||
pub target: Option<[i32; 4]>,
|
||||
pub position: Vec3,
|
||||
pub previous: Vec3,
|
||||
pub velocity: Vec3,
|
||||
@@ -355,7 +357,10 @@ pub fn merge_with_neighbours(
|
||||
}
|
||||
// ItemEntity.areMergable: both fit one stack of the same item and components.
|
||||
let (this, other) = (&items[i].stack, &items[j].stack);
|
||||
if this.count + other.count > max_stack(other) || !this.same_item_same_components(other) {
|
||||
if items[i].target != items[j].target
|
||||
|| this.count + other.count > max_stack(other)
|
||||
|| !this.same_item_same_components(other)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (to, from) = if other.count < this.count {
|
||||
@@ -951,6 +956,7 @@ mod fire_environment_tests {
|
||||
let make = |id: &str| ItemEntity {
|
||||
id: 1,
|
||||
thrower: None,
|
||||
target: None,
|
||||
stack: ItemStack {
|
||||
item: std::sync::Arc::from(id),
|
||||
count: 1,
|
||||
@@ -1047,6 +1053,7 @@ mod merge_tests {
|
||||
ItemEntity {
|
||||
id: 0,
|
||||
thrower: None,
|
||||
target: None,
|
||||
stack: ItemStack {
|
||||
item: std::sync::Arc::from(id),
|
||||
count,
|
||||
|
||||
@@ -189,6 +189,7 @@ mod tests {
|
||||
extra: None,
|
||||
},
|
||||
thrower: None,
|
||||
target: None,
|
||||
position: at,
|
||||
previous: at,
|
||||
velocity: Vec3::ZERO,
|
||||
|
||||
@@ -54,6 +54,8 @@ struct Out {
|
||||
// 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>,
|
||||
// 1 drops the quad's back-facing pixels (Vertex::normal w = 1), like a culling render type.
|
||||
@location(12) @interpolate(flat) cull: u32,
|
||||
}
|
||||
// Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed.
|
||||
fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
|
||||
@@ -102,7 +104,10 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
|
||||
// minecraft_mix_light: the vertex colour times the cardinal light only.
|
||||
var c = color;
|
||||
var back = c;
|
||||
if normal.w != 0.0 {
|
||||
// Normal w: 0 keeps the baked colour, +-127 shades by the normal, and a small positive 1
|
||||
// keeps the baked colour but culls back faces (entitySolid models such as the decorated pot).
|
||||
out.cull = select(0u, 1u, normal.w > 0.0 && normal.w < 0.5);
|
||||
if abs(normal.w) >= 0.5 {
|
||||
c = vec4(c.rgb * entity_light(normal.xyz, globals.time.y != 0.0), c.a);
|
||||
back = select(c, vec4(back.rgb * entity_light(-normal.xyz, globals.time.y != 0.0), back.a), normal.w < 0.0);
|
||||
}
|
||||
@@ -234,7 +239,7 @@ fn crumbling_uv(uv: vec2<f32>, packed_origin: vec2<f32>, sprite_size: vec2<f32>,
|
||||
// clouds.fsh: alpha fades out towards the cloud fog end.
|
||||
return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y)));
|
||||
}
|
||||
if color.a < 0.1 { discard; }
|
||||
if color.a < 0.1 || (in.cull != 0u && !front) { discard; }
|
||||
// entity.fsh calculateFinalColor: the overlay (hurt red, TNT white) over the
|
||||
// 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);
|
||||
|
||||
@@ -515,6 +515,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
"Variant".into(),
|
||||
Tag::Int(i32::from(m.extra.variant.min(4))),
|
||||
);
|
||||
if let Some(owner) = m.extra.owner {
|
||||
map.insert("Owner".into(), Tag::IntArray(owner.to_vec()));
|
||||
} else {
|
||||
map.remove(&"Owner".into());
|
||||
}
|
||||
map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting)));
|
||||
}
|
||||
"minecraft:salmon" => {
|
||||
let size = SALMON_SIZES[usize::from(m.extra.variant).min(2)];
|
||||
@@ -552,7 +558,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
"memories",
|
||||
Tag::compound([(
|
||||
"minecraft:liked_player",
|
||||
Tag::compound([("value", Tag::IntArray(vec![0, 0, 0, 1]))]),
|
||||
Tag::compound([(
|
||||
"value",
|
||||
Tag::IntArray(m.extra.owner.unwrap_or([0, 0, 0, 1]).to_vec()),
|
||||
)]),
|
||||
)]),
|
||||
)]),
|
||||
);
|
||||
@@ -606,6 +615,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.insert("life_ticks".into(), Tag::Int(m.extra.egg_time));
|
||||
}
|
||||
}
|
||||
"minecraft:endermite" => {
|
||||
map.insert("Lifetime".into(), Tag::Int(m.extra.counter));
|
||||
}
|
||||
"minecraft:shulker" => {
|
||||
map.insert("AttachFace".into(), Tag::Byte(m.extra.variant3 as i8));
|
||||
map.insert("Peek".into(), Tag::Byte(m.extra.counter as i8));
|
||||
@@ -712,6 +724,17 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
equipment.insert(slot.into(), crate::save::item_to_nbt(&stack));
|
||||
continue;
|
||||
}
|
||||
// A wolf's armor keeps the durability it lost.
|
||||
if slot == "body"
|
||||
&& m.species() == crate::mobs::Species::Wolf
|
||||
&& let Some(id) = item
|
||||
{
|
||||
let mut stack = crate::items::ItemStack::new(id, 1);
|
||||
stack.damage = m.extra.body_damage.max(0) as u32;
|
||||
stack.extra = m.extra.body_extra.clone();
|
||||
equipment.insert(slot.into(), crate::save::item_to_nbt(&stack));
|
||||
continue;
|
||||
}
|
||||
match item {
|
||||
Some(id) => {
|
||||
let keep = matches!(
|
||||
@@ -1111,6 +1134,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.variant = gene("MainGene");
|
||||
m.extra.variant2 = gene("HiddenGene");
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Parrot {
|
||||
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");
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Wolf {
|
||||
let health = m.health;
|
||||
m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner"));
|
||||
@@ -1118,6 +1146,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
crate::mobs::tame::set_tame(&mut m, tame);
|
||||
m.health = health;
|
||||
m.extra.sitting = flag(tag, "Sitting");
|
||||
let armor = tag
|
||||
.get("equipment")
|
||||
.and_then(|e| e.get("body"))
|
||||
.and_then(crate::save::item_from_nbt);
|
||||
m.extra.body_damage = armor.as_ref().map_or(0, |s| s.damage as i32);
|
||||
m.extra.body_extra = armor.and_then(|s| s.extra);
|
||||
m.extra.color =
|
||||
number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15);
|
||||
}
|
||||
@@ -1148,11 +1182,14 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.ints[1] = number(first.get("count")).unwrap_or(1) as i32;
|
||||
}
|
||||
m.extra.egg_time = number(tag.get("DuplicationCooldown")).unwrap_or(0) as i32;
|
||||
m.extra.tame = tag
|
||||
let liked = tag
|
||||
.get("Brain")
|
||||
.and_then(|b| b.get("memories"))
|
||||
.and_then(|b| b.get("minecraft:liked_player"))
|
||||
.is_some();
|
||||
.and_then(|b| b.get("minecraft:liked_player"));
|
||||
m.extra.tame = liked.is_some();
|
||||
m.extra.owner = liked
|
||||
.and_then(|l| l.get("value"))
|
||||
.and_then(|v| crate::save::uuid_from_tag(Some(v)));
|
||||
}
|
||||
if crate::mobs::camel::is_camel(m.species()) {
|
||||
let sitting = matches!(tag.get("LastPoseTick"), Some(Tag::Long(v)) if *v < 0);
|
||||
@@ -1230,6 +1267,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32;
|
||||
m.extra.anim_ticks = number(tag.get("RoarTick")).unwrap_or(0) as i32;
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Endermite {
|
||||
m.extra.counter = number(tag.get("Lifetime")).unwrap_or(0) as i32;
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Vex {
|
||||
if let Some(Tag::IntArray(v)) = tag.get("bound_pos")
|
||||
&& v.len() == 3
|
||||
@@ -1320,6 +1360,11 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) ->
|
||||
} else if let Tag::Compound(map) = &mut tag {
|
||||
map.remove(&"Thrower".into());
|
||||
}
|
||||
if let Some(target) = e.target {
|
||||
put(&mut tag, "Owner", Tag::IntArray(target.to_vec()));
|
||||
} else if let Tag::Compound(map) = &mut tag {
|
||||
map.remove(&"Owner".into());
|
||||
}
|
||||
tag
|
||||
}
|
||||
pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemEntity> {
|
||||
@@ -1331,6 +1376,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemE
|
||||
id,
|
||||
stack,
|
||||
thrower: uuid_from_tag(tag.get("Thrower")),
|
||||
target: uuid_from_tag(tag.get("Owner")),
|
||||
position,
|
||||
previous: position,
|
||||
velocity: motion(tag),
|
||||
@@ -2240,6 +2286,7 @@ mod tests {
|
||||
health: 2,
|
||||
fire_ticks: 73,
|
||||
thrower: Some([5, 6, 7, 8]),
|
||||
target: None,
|
||||
id: 7,
|
||||
stack: ItemStack {
|
||||
item: Arc::from("minecraft:diamond_pickaxe"),
|
||||
|
||||
@@ -26,6 +26,13 @@ pub enum ItemPose {
|
||||
Bow {
|
||||
ticks_used: f32,
|
||||
},
|
||||
/// A spear being charged (`ItemUseAnimation.SPEAR`): the time held and
|
||||
/// the ticks since its last hit's feedback.
|
||||
Spear {
|
||||
kinetic: crate::spear::Kinetic,
|
||||
time_held: f32,
|
||||
ticks_since_hit: f32,
|
||||
},
|
||||
Crossbow {
|
||||
ticks_used: Option<f32>,
|
||||
charge_duration: f32,
|
||||
@@ -69,6 +76,16 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
|
||||
if matches!(pose, ItemPose::Using) {
|
||||
return m;
|
||||
}
|
||||
// The spear's own place in the hand, without the equip height.
|
||||
if let ItemPose::Spear {
|
||||
kinetic,
|
||||
time_held,
|
||||
ticks_since_hit,
|
||||
} = pose
|
||||
{
|
||||
return Mat4::from_translation(Vec3::new(invert * 0.56, -0.52, -0.72))
|
||||
* crate::spear::first_person_use(&kinetic, ticks_since_hit, time_held, !left);
|
||||
}
|
||||
if matches!(pose, ItemPose::SpinAttack) {
|
||||
return m
|
||||
* Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3))
|
||||
|
||||
@@ -18,6 +18,7 @@ mod boats;
|
||||
mod books;
|
||||
mod bossbars;
|
||||
mod breezes;
|
||||
mod brush;
|
||||
mod bundles;
|
||||
mod campfire;
|
||||
mod campfire_douse;
|
||||
@@ -149,6 +150,7 @@ mod recipe_book;
|
||||
mod remote;
|
||||
mod remote_chunks;
|
||||
mod remote_mob_data;
|
||||
mod remote_mob_particles;
|
||||
mod remote_mob_use;
|
||||
mod remote_objects;
|
||||
mod remote_projectiles;
|
||||
@@ -169,9 +171,11 @@ mod server_packs;
|
||||
mod server_travel;
|
||||
mod shader_packs;
|
||||
mod shield;
|
||||
mod shoulders;
|
||||
mod sign_edit;
|
||||
mod sniffers;
|
||||
mod spawner;
|
||||
mod spear;
|
||||
mod spill;
|
||||
mod startup_menu;
|
||||
mod station_control;
|
||||
@@ -577,12 +581,19 @@ struct GameLevel<'w> {
|
||||
player_collision: Option<PlayerCollision>,
|
||||
/// Minecart boxes (detector rails).
|
||||
cart_boxes: Vec<([f64; 3], [f64; 3])>,
|
||||
/// The item frames a comparator reads through a conductor.
|
||||
item_frames: &'w [horizon_client::entities::ItemFrame],
|
||||
/// Each minecart's kind and comparator signal, in `cart_boxes` order.
|
||||
cart_signals: Vec<(minecarts::CartKind, i32)>,
|
||||
/// Arrow and thrown trident boxes (wooden buttons).
|
||||
arrow_boxes: Vec<([f64; 3], [f64; 3])>,
|
||||
/// The other entities that keep blocks from being placed into them.
|
||||
blockers: Blockers<'w>,
|
||||
/// Item entities, experience orbs and projectiles, which trigger plates and
|
||||
/// tripwires but never keep a block from being placed.
|
||||
dropped: &'w [ItemEntity],
|
||||
orbs: &'w [ExperienceOrb],
|
||||
projectiles: &'w [horizon_client::projectiles::Projectile],
|
||||
biomes: &'w Biomes,
|
||||
seed: i64,
|
||||
behaviours: &'w Behaviours,
|
||||
@@ -657,6 +668,53 @@ impl EntityObstructionWorld for BuildingObstruction {
|
||||
}
|
||||
}
|
||||
impl GameLevel<'_> {
|
||||
/// The mobs that trigger plates and tripwires: living entities that don't
|
||||
/// ignore block triggers (`Entity.isIgnoringBlockTriggers`: bats; armor
|
||||
/// stands are not in `mobs`).
|
||||
fn mob_trigger_boxes(&self) -> impl Iterator<Item = Aabb> + '_ {
|
||||
self.blockers
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| !m.removed && m.species() != horizon_client::mobs::Species::Bat)
|
||||
.map(Mob::bounds)
|
||||
}
|
||||
/// The non-living entities that trigger plates and tripwires (boats,
|
||||
/// crystals, primed TNT, falling blocks, item entities, experience orbs and
|
||||
/// projectiles).
|
||||
fn other_trigger_boxes(&self) -> impl Iterator<Item = Aabb> + '_ {
|
||||
let b = self.blockers;
|
||||
let square = |p: Vec3, size: f64| {
|
||||
Aabb::new(
|
||||
Vec3::new(p.x - size / 2.0, p.y, p.z - size / 2.0),
|
||||
Vec3::new(p.x + size / 2.0, p.y + size, p.z + size / 2.0),
|
||||
)
|
||||
};
|
||||
b.boats
|
||||
.iter()
|
||||
.map(boats::Boat::bounds)
|
||||
.chain(b.crystals.iter().map(|c| {
|
||||
// EntityType.END_CRYSTAL: 2 x 2.
|
||||
let p = c.position;
|
||||
Aabb::new(
|
||||
Vec3::new(p.x - 1.0, p.y, p.z - 1.0),
|
||||
Vec3::new(p.x + 1.0, p.y + 2.0, p.z + 1.0),
|
||||
)
|
||||
}))
|
||||
.chain(b.tnts.iter().map(tnt::PrimedTnt::bounds))
|
||||
.chain(
|
||||
b.falling
|
||||
.iter()
|
||||
.map(|f| horizon_client::falling_block::bounds(f.position)),
|
||||
)
|
||||
.chain(self.dropped.iter().map(ItemEntity::bounds))
|
||||
// EntityType.EXPERIENCE_ORB: 0.5 x 0.5.
|
||||
.chain(self.orbs.iter().map(move |o| square(o.position, 0.5)))
|
||||
.chain(
|
||||
self.projectiles
|
||||
.iter()
|
||||
.map(move |p| square(p.position, p.kind.size())),
|
||||
)
|
||||
}
|
||||
/// `DetectorRailBlock.getAnalogOutputSignal`: a powered rail reads the
|
||||
/// minecart on it, a command block cart first (its success count, which
|
||||
/// is 0 here), else the first container cart's fullness.
|
||||
@@ -786,6 +844,20 @@ impl LevelAccess for GameLevel<'_> {
|
||||
}
|
||||
machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos)
|
||||
}
|
||||
fn item_frame_analog_output(&self, pos: BlockPos, facing: Direction) -> Option<i32> {
|
||||
let mut frames = self
|
||||
.item_frames
|
||||
.iter()
|
||||
.filter(|f| f.pos == [pos.x, pos.y, pos.z] && f.facing == facing as u8);
|
||||
let frame = frames.next().filter(|_| frames.next().is_none())?;
|
||||
// ItemFrame.getAnalogOutput.
|
||||
Some(
|
||||
frame
|
||||
.item
|
||||
.as_ref()
|
||||
.map_or(0, |_| i32::from(frame.rotation % 8) + 1),
|
||||
)
|
||||
}
|
||||
fn block_entity_signal(
|
||||
&self,
|
||||
pos: BlockPos,
|
||||
@@ -957,8 +1029,9 @@ impl LevelAccess for GameLevel<'_> {
|
||||
self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z)
|
||||
}
|
||||
/// Entities that trigger pressure plates, tripwires, detector rails and
|
||||
/// wooden buttons: the players (the host and the LAN guests, mobs) and
|
||||
/// the minecarts, and for `EntityQuery::Arrows` the arrows.
|
||||
/// wooden buttons: the players (the host and the LAN guests), the mobs,
|
||||
/// the minecarts and the other entities that don't ignore block triggers,
|
||||
/// and for `EntityQuery::Arrows` the arrows.
|
||||
fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize {
|
||||
let hit = |(lo, hi): &([f64; 3], [f64; 3])| {
|
||||
area.intersects(Aabb::new(
|
||||
@@ -967,6 +1040,16 @@ impl LevelAccess for GameLevel<'_> {
|
||||
))
|
||||
};
|
||||
let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count();
|
||||
let mobs = || {
|
||||
self.mob_trigger_boxes()
|
||||
.filter(|b| area.intersects(*b))
|
||||
.count()
|
||||
};
|
||||
let others = || {
|
||||
self.other_trigger_boxes()
|
||||
.filter(|b| area.intersects(*b))
|
||||
.count()
|
||||
};
|
||||
let arrows = || self.arrow_boxes.iter().filter(|b| hit(b)).count();
|
||||
let players = || {
|
||||
self.player_box
|
||||
@@ -978,8 +1061,8 @@ impl LevelAccess for GameLevel<'_> {
|
||||
match query {
|
||||
EntityQuery::Minecart => carts(),
|
||||
EntityQuery::Arrows => arrows(),
|
||||
EntityQuery::Mobs => players(),
|
||||
EntityQuery::Everything => players() + carts(),
|
||||
EntityQuery::Mobs => players() + mobs(),
|
||||
EntityQuery::Everything => players() + carts() + mobs() + others(),
|
||||
}
|
||||
}
|
||||
fn emit(&mut self, event: LevelEvent) {
|
||||
@@ -1460,6 +1543,9 @@ struct Game<'a> {
|
||||
spawn_spiral: horizon_client::world_spawn::ChunkSpiral,
|
||||
/// A new player's spawn search, while its candidates' chunks load.
|
||||
player_spawn: Option<horizon_client::world_spawn::PlayerSpawnFinder>,
|
||||
/// Chunks a respawn search waits for this tick, kept loading beside the
|
||||
/// player's own (taken by `update_world`).
|
||||
spawn_wait: Vec<(i32, i32)>,
|
||||
mobs: Vec<Mob>,
|
||||
creatures: creatures::Creatures,
|
||||
sculk: sculk::SculkState,
|
||||
@@ -1549,6 +1635,8 @@ struct Game<'a> {
|
||||
/// The head of the bed while sleeping; the visual timer also survives waking.
|
||||
sleeping: Option<[i32; 3]>,
|
||||
sleep_timer: u32,
|
||||
/// `SleepStatus`'s active and sleeping players at the last announcement.
|
||||
sleep_seen: (i64, i64),
|
||||
dim: Dim,
|
||||
world_root: PathBuf,
|
||||
/// The world is superflat (`ServerLevel.isFlat`, for every dimension).
|
||||
@@ -1754,6 +1842,9 @@ struct Game<'a> {
|
||||
guest_use: Option<GuestUse>,
|
||||
/// Level events of this tick for the guests, and the guest acting now.
|
||||
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
|
||||
/// Jukebox level events 1010 (song name) and 1011 (`None`) for the guests;
|
||||
/// the song's network id is only known once the hub is in hand.
|
||||
lan_songs: Vec<([i32; 3], Option<String>)>,
|
||||
lan_cushion_breaks: Vec<(horizon_world::registry::BlockStateId, [f64; 3])>,
|
||||
/// Block events (position, b0, b1, state) and entity events (id, event,
|
||||
/// position) for the guests.
|
||||
@@ -1761,6 +1852,18 @@ struct Game<'a> {
|
||||
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
|
||||
/// Successful crits (attacking guest, hit entity), queued while the hub is taken.
|
||||
lan_critical_hits: Vec<(Option<u32>, i32, bool)>,
|
||||
/// Spear stabs that landed (the stabbing guest), queued while the hub is
|
||||
/// taken: `broadcastEntityEvent(player, 2)`.
|
||||
lan_kinetic_hits: Vec<Option<u32>>,
|
||||
/// `LivingEntity.recentKineticEnemies`: when each player (a guest, or the
|
||||
/// window's own) last stabbed each entity this use.
|
||||
stabbed: HashMap<(Option<u32>, u32), i64>,
|
||||
/// The movement a guest's client reported this tick
|
||||
/// (`ServerPlayer.getKnownMovement`), for their turn.
|
||||
known_movement: Vec3,
|
||||
/// `LivingEntity.lastKineticHitFeedbackTime` of the entities that felt a
|
||||
/// spear's hit (`spear::OWN` is this window's player), in game time.
|
||||
kinetic_feedback: HashMap<i32, i64>,
|
||||
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
|
||||
lan_global_events: Vec<(i32, [i32; 3], i32)>,
|
||||
/// `ContainerOpenersCounter`: how many players (the host and the guests)
|
||||
@@ -1804,6 +1907,8 @@ struct Game<'a> {
|
||||
boss_overlay: horizon_client::boss_overlay::BossOverlay,
|
||||
exec: commands::execute::ExecState,
|
||||
rand_sequences: horizon_client::random_sequences::RandomSequences,
|
||||
/// `BrushableBlockEntity`'s brush counts of the blocks being brushed.
|
||||
brushing: brush::Brushing,
|
||||
border: horizon_client::worldborder::WorldBorder,
|
||||
/// `WorldBorderRenderer` and its render state.
|
||||
border_renderer: horizon_client::border_render::BorderRenderer,
|
||||
@@ -2145,6 +2250,7 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.is_some_and(|s| &*s.item == "minecraft:leather_boots");
|
||||
let freeze_immune = self.wears_freeze_immune();
|
||||
let burn_immune = self.wears_burn_from_stepping_immunity();
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return;
|
||||
};
|
||||
@@ -2157,6 +2263,7 @@ impl Game<'_> {
|
||||
let _ = player.set_sleeping(sleeping);
|
||||
player.leather_boots = leather_boots;
|
||||
player.freeze_immune = freeze_immune;
|
||||
player.burn_from_stepping_immune = burn_immune;
|
||||
player.fluids.fast_lava = self.dim == Dim::Nether;
|
||||
}
|
||||
fn held_slot(&self) -> usize {
|
||||
@@ -2400,6 +2507,7 @@ impl Game<'_> {
|
||||
health: 5,
|
||||
fire_ticks: 0,
|
||||
thrower: None,
|
||||
target: None,
|
||||
id: self.next_entity,
|
||||
stack,
|
||||
position: p,
|
||||
@@ -2623,6 +2731,7 @@ impl Game<'_> {
|
||||
],
|
||||
);
|
||||
let feet = [p.position.x, p.position.y, p.position.z];
|
||||
let own = self.level.ensure_player_uuid();
|
||||
let mut kept = Vec::with_capacity(items.len());
|
||||
for mut item in items {
|
||||
let b = item.bounds();
|
||||
@@ -2632,7 +2741,8 @@ impl Game<'_> {
|
||||
&& b.max_position().y > min[1]
|
||||
&& b.min_position().z < max[2]
|
||||
&& b.max_position().z > min[2];
|
||||
if touching && item.pickup_delay == 0 {
|
||||
// ItemEntity.playerTouch: no pickup delay, and the target (if any) is this player.
|
||||
if touching && item.pickup_delay == 0 && item.target.is_none_or(|t| t == own) {
|
||||
let before = item.stack.count;
|
||||
let kind = item.stack.item.clone();
|
||||
match self.give(item.stack.clone()) {
|
||||
@@ -2766,9 +2876,13 @@ impl Game<'_> {
|
||||
};
|
||||
let mut level = GameLevel {
|
||||
cart_boxes,
|
||||
item_frames: &self.item_frames,
|
||||
cart_signals,
|
||||
arrow_boxes,
|
||||
blockers,
|
||||
dropped: &self.dropped,
|
||||
orbs: &self.orbs,
|
||||
projectiles: &self.creatures.projectiles,
|
||||
world: &mut self.world,
|
||||
facts: self.res.facts(),
|
||||
collision: self.collision,
|
||||
@@ -2912,7 +3026,8 @@ impl Game<'_> {
|
||||
.collect();
|
||||
// Entity.checkInsideBlocks for the plates, tripwires, detector rails and
|
||||
// buttons under the players (the host and the LAN guests), the minecarts
|
||||
// and the arrows.
|
||||
// and the arrows (the mobs and other entities are added in `with_level`
|
||||
// below).
|
||||
let mut inside = Vec::new();
|
||||
let guests = self.lan_block_trigger_boxes();
|
||||
let boxes = self
|
||||
@@ -2991,7 +3106,21 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.with_level(|b, level, ticks| {
|
||||
for pos in inside {
|
||||
// The mobs and the other entities (items, orbs, projectiles...) too.
|
||||
let mut touched: Vec<BlockPos> = Vec::new();
|
||||
for bounds in level.mob_trigger_boxes().chain(level.other_trigger_boxes()) {
|
||||
let (lo, hi) = (bounds.min_position(), bounds.max_position());
|
||||
for x in (lo.x + 1e-7).floor() as i32..=(hi.x - 1e-7).floor() as i32 {
|
||||
for y in (lo.y + 1e-7).floor() as i32..=(hi.y - 1e-7).floor() as i32 {
|
||||
for z in (lo.z + 1e-7).floor() as i32..=(hi.z - 1e-7).floor() as i32 {
|
||||
touched.push(BlockPos::new(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
touched.sort_unstable_by_key(|p| (p.x, p.y, p.z));
|
||||
touched.dedup();
|
||||
for pos in inside.into_iter().chain(touched) {
|
||||
b.entity_inside(level, ticks, pos);
|
||||
}
|
||||
for (pos, on_ground, feet_y) in standing {
|
||||
@@ -3108,6 +3237,12 @@ impl Game<'_> {
|
||||
data,
|
||||
} => self.sculk_charge_event(pos, data),
|
||||
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
|
||||
// LevelEventHandler 1010 and 1011: the parrots nearby dance or stop.
|
||||
LevelEvent::LevelEvent {
|
||||
id: id @ (1010 | 1011),
|
||||
pos,
|
||||
..
|
||||
} => self.notify_record_playing([pos.x, pos.y, pos.z], id == 1010),
|
||||
// LevelEventHandler 2019 and 2020: the crack on a face of the
|
||||
// block being mined, with its hit sound for 2020.
|
||||
LevelEvent::LevelEvent {
|
||||
@@ -3118,6 +3253,11 @@ impl Game<'_> {
|
||||
let face = horizon_core::geometry::Direction::ALL[data.clamp(0, 5) as usize];
|
||||
self.breaking_block_effects([pos.x, pos.y, pos.z], face.normal(), id == 2020);
|
||||
}
|
||||
LevelEvent::LevelEvent {
|
||||
id: 3008,
|
||||
pos,
|
||||
data,
|
||||
} => self.brush_complete_event([pos.x, pos.y, pos.z], data),
|
||||
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
|
||||
self.spawner_burst([pos.x, pos.y, pos.z])
|
||||
}
|
||||
@@ -3379,6 +3519,11 @@ impl Game<'_> {
|
||||
kind: "command_block",
|
||||
..
|
||||
} => self.command_block_tick(pos),
|
||||
LevelEvent::BlockEvent {
|
||||
pos,
|
||||
kind: "brushable",
|
||||
..
|
||||
} => self.brushable_tick([pos.x, pos.y, pos.z]),
|
||||
LevelEvent::BlockEvent {
|
||||
pos, kind: "hatch", ..
|
||||
} => {
|
||||
@@ -4159,11 +4304,19 @@ impl Game<'_> {
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
// BrushItem.useOn: brushing starts on the block aimed at (CONSUME).
|
||||
if block_hit.is_some() && &*stack.item == "minecraft:brush" {
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
if !on_block
|
||||
&& (self.raise_shield(self.held_slot())
|
||||
|| self.use_fishing_rod(&stack)
|
||||
|| self.use_crossbow(&stack)
|
||||
|| self.use_trident(&stack)
|
||||
|| self.use_spear(&stack)
|
||||
|| self.boost_firework(&stack)
|
||||
|| self.use_empty_map(&stack)
|
||||
|| self.use_book(&stack)
|
||||
@@ -4449,6 +4602,12 @@ impl Game<'_> {
|
||||
self.using = Some((slot, ticks + 1));
|
||||
return;
|
||||
}
|
||||
// ItemStack.onUseTick: a spear stabs what its speed allows, until released.
|
||||
if horizon_client::spear::Kinetic::of(&stack.item).is_some() {
|
||||
self.spear_tick(&stack, ticks);
|
||||
self.using = Some((slot, ticks + 1));
|
||||
return;
|
||||
}
|
||||
if &*stack.item == "minecraft:spyglass" {
|
||||
// SpyglassItem.USE_DURATION, then finishUsingItem.
|
||||
if ticks + 1 >= 1200 {
|
||||
@@ -4460,6 +4619,10 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if &*stack.item == "minecraft:brush" {
|
||||
self.tick_brush(slot, ticks);
|
||||
return;
|
||||
}
|
||||
if info.bundle {
|
||||
self.tick_bundle(slot, ticks);
|
||||
return;
|
||||
@@ -4766,11 +4929,22 @@ impl Game<'_> {
|
||||
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
return Ok(());
|
||||
}
|
||||
// WorldSpawn: the stored column, lifted onto its current surface.
|
||||
let y = self
|
||||
.land_column(s.x.floor() as i32, s.z.floor() as i32)
|
||||
.map_or(s.y, f64::from);
|
||||
Vec3::new(s.x, y.max(s.y), s.z)
|
||||
let column = [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32];
|
||||
if self.level.world_spawn == Some(column) {
|
||||
// TeleportTransition.missingRespawnBlock: PlayerSpawnFinder
|
||||
// around the world spawn, not its exact column; its candidates'
|
||||
// chunks load first.
|
||||
let Some(feet) = self.find_player_spawn(column)? else {
|
||||
return Ok(());
|
||||
};
|
||||
feet
|
||||
} else {
|
||||
// A spawnpoint: the stored column, lifted onto its current surface.
|
||||
let y = self
|
||||
.land_column(column[0], column[2])
|
||||
.map_or(s.y, f64::from);
|
||||
Vec3::new(s.x, y.max(s.y), s.z)
|
||||
}
|
||||
};
|
||||
let mut player = PlayerMotion::new(self.motion, feet)?;
|
||||
player.yaw = self.yaw;
|
||||
@@ -4794,6 +4968,7 @@ impl Game<'_> {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.died_at = Some(Instant::now());
|
||||
self.ui.death_text = None;
|
||||
self.ui.death_confirm = None;
|
||||
self.capture(false);
|
||||
}
|
||||
self.previous_position = feet;
|
||||
@@ -5133,7 +5308,13 @@ impl Game<'_> {
|
||||
}
|
||||
self.powder_snow_fire()?;
|
||||
self.rain_extinguish_in_frame();
|
||||
// LivingEntity.baseTick: a new block position runs the worn
|
||||
// enchantments' location_changed effects (frost walker) on the server.
|
||||
if self.remote.is_none() {
|
||||
self.location_changed_effects(before.2, before.0);
|
||||
}
|
||||
self.tick_totem();
|
||||
self.handle_shoulder_entities();
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -5147,6 +5328,9 @@ impl Game<'_> {
|
||||
let feet = [player.position.x, player.position.y, player.position.z];
|
||||
let at = [feet[0], feet[1] + 1.32, feet[2]];
|
||||
let killer = self.combat_killer_kind();
|
||||
// Player.die: the dimension and block of the death.
|
||||
self.level.last_death =
|
||||
Some((self.dim.id().to_owned(), feet.map(|v| v.floor() as i32)));
|
||||
self.death_message();
|
||||
// ServerPlayer.die: deaths, and the time-since counters restart.
|
||||
self.stats.custom("deaths", 1);
|
||||
@@ -5256,6 +5440,7 @@ impl Game<'_> {
|
||||
self.tick_friends();
|
||||
horizon_client::spans::time("tick_hand", || self.tick_hand());
|
||||
horizon_client::spans::time("tick_sleep", || self.tick_sleep());
|
||||
self.announce_sleep_status();
|
||||
horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?;
|
||||
if running {
|
||||
horizon_client::spans::time("tick_end", || self.tick_end())?;
|
||||
@@ -5863,6 +6048,19 @@ impl Game<'_> {
|
||||
.health_hud
|
||||
.left_height
|
||||
.max(self.health_hud.right_height);
|
||||
// Hud.playAirBubblePoppedSound: Player.playSound (PLAYERS), heard
|
||||
// by this client only.
|
||||
if let Some((volume, pitch)) = self.health_hud.bubble_pop_sound.take() {
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
let players = horizon_client::settings::SOUND_SOURCES
|
||||
.iter()
|
||||
.position(|s| *s == "player")
|
||||
.unwrap_or(0);
|
||||
let capture = self.audio.capture.take();
|
||||
self.audio
|
||||
.play_on(players, "ui.hud.bubble_pop", Some(at), volume, pitch);
|
||||
self.audio.capture = capture;
|
||||
}
|
||||
}
|
||||
if contextual == ContextualBar::Locator {
|
||||
let draws = self.locator_bar_draws(wi, hi);
|
||||
@@ -8186,8 +8384,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// `Player.getAttackStrengthScale(0.5)`.
|
||||
fn attack_strength_scale(&self) -> f32 {
|
||||
let speed = self.attack_item_info().map_or(0.0, |i| i.attack_speed);
|
||||
let delay = 20.0 / (4.0 + speed).max(0.1);
|
||||
let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed());
|
||||
((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0)
|
||||
}
|
||||
/// `Player.isSweepAttack`: a charged, grounded sword hit below the movement limit.
|
||||
@@ -8224,18 +8421,9 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0);
|
||||
}
|
||||
/// The damage and knockback part of `Player.doSweepAttack` after a sweep
|
||||
/// hit on the mob at `target`: every other living mob in its box grown by
|
||||
/// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative
|
||||
/// too), but the player's allies
|
||||
/// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the
|
||||
/// weapon's enchantments, scaled by the attack strength, and is pushed 0.4
|
||||
/// along the player's yaw.
|
||||
pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let from = [p.position.x, p.position.y, p.position.z];
|
||||
/// What `Player.doSweepAttack` deals before the target's enchantment
|
||||
/// bonus and the attack strength: `1 + sweeping_damage_ratio * baseDamage`.
|
||||
pub(super) fn sweep_base_damage(&self, scale: f32) -> f32 {
|
||||
// `baseDamage` of `Player.attack` before a critical hit (a sweep has
|
||||
// none) and the enchantments: the attack damage attribute with the
|
||||
// strength and weakness effects, scaled by the attack strength.
|
||||
@@ -8251,7 +8439,21 @@ impl Game<'_> {
|
||||
"minecraft:sweeping_damage_ratio",
|
||||
)
|
||||
.clamp(0.0, 1.0) as f32;
|
||||
let sweep_damage = 1.0 + ratio * base_damage;
|
||||
1.0 + ratio * base_damage
|
||||
}
|
||||
/// The damage and knockback part of `Player.doSweepAttack` after a sweep
|
||||
/// hit on the mob at `target`: every other living mob in its box grown by
|
||||
/// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative
|
||||
/// too), but the player's allies
|
||||
/// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the
|
||||
/// weapon's enchantments, scaled by the attack strength, and is pushed 0.4
|
||||
/// along the player's yaw.
|
||||
pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let from = [p.position.x, p.position.y, p.position.z];
|
||||
let sweep_damage = self.sweep_base_damage(scale);
|
||||
let hit_box = self.mobs[target]
|
||||
.bounds()
|
||||
.inflate(horizon_core::geometry::Vec3::new(1.0, 0.25, 1.0));
|
||||
@@ -8286,6 +8488,10 @@ impl Game<'_> {
|
||||
.insert(self.mobs[i].id, self.lan_acting);
|
||||
}
|
||||
}
|
||||
// `getEntitiesOfClass(LivingEntity.class)` takes the other players too.
|
||||
let mut sweep = self.player_sweep(sweep_damage, scale);
|
||||
sweep.hit_box = hit_box;
|
||||
self.sweep_other_players(sweep);
|
||||
}
|
||||
/// `Player.attack`'s sounds when a vehicle takes the hit (it always does,
|
||||
/// and can't be hit critically): knockback when sprinting at full
|
||||
@@ -10323,7 +10529,17 @@ impl Game<'_> {
|
||||
let ticks_used =
|
||||
owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0);
|
||||
use horizon_client::first_person::ItemPose;
|
||||
// ItemUseAnimation.SPEAR.
|
||||
let spear = using
|
||||
.then(|| horizon_client::spear::Kinetic::of(&stack.item))
|
||||
.flatten()
|
||||
.map(|kinetic| ItemPose::Spear {
|
||||
kinetic,
|
||||
time_held: ticks_used,
|
||||
ticks_since_hit: self.kinetic_hit_ticks(a),
|
||||
});
|
||||
let pose = match &*stack.item {
|
||||
_ if let Some(pose) = spear => pose,
|
||||
"minecraft:bow" if using => ItemPose::Bow { ticks_used },
|
||||
"minecraft:crossbow" => {
|
||||
let charged = stack.data().is_some_and(|d| !d.charged.is_empty());
|
||||
@@ -10445,19 +10661,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Whether precipitation at a column is snow (Biome.coldEnoughToSnow:
|
||||
/// base temperature lowered above y 80) or none (no precipitation).
|
||||
/// height adjusted temperature) or none (no precipitation).
|
||||
fn precipitation(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
||||
let chunk = self.world.chunks.get(&(x >> 4, z >> 4))?;
|
||||
let b = self.res.biomes().get(chunk.biome(x, y, z));
|
||||
if !b.precipitation {
|
||||
return None;
|
||||
}
|
||||
let t = if y > 80 {
|
||||
b.temperature - (y - 80) as f32 * 0.05 / 40.0
|
||||
} else {
|
||||
b.temperature
|
||||
};
|
||||
Some(t < 0.15)
|
||||
self.res
|
||||
.biomes()
|
||||
.get(chunk.biome(x, y, z))
|
||||
.snows_at(x, y, z)
|
||||
}
|
||||
/// `Level.isRainingAt`: it rains, the sky light is 15, nothing that stops
|
||||
/// motion is above, and the biome's precipitation there is rain.
|
||||
@@ -10759,6 +10969,8 @@ impl Game<'_> {
|
||||
self.wake_up();
|
||||
}
|
||||
self.wake_guests();
|
||||
// SleepStatus.removeAllSleepers: waking everyone is not announced.
|
||||
self.sleep_seen.1 = 0;
|
||||
}
|
||||
}
|
||||
fn creative_origin(batch: &HudBatch) -> (f32, f32) {
|
||||
@@ -12077,8 +12289,14 @@ impl Game<'_> {
|
||||
self.streaming.loading =
|
||||
self.options.execution_role.is_client() && self.loading_reason().is_some();
|
||||
self.tick_pregen();
|
||||
let areas = self.streaming.extra.len();
|
||||
let waiting = std::mem::take(&mut self.spawn_wait);
|
||||
self.streaming
|
||||
.extra
|
||||
.extend(waiting.into_iter().map(|chunk| (chunk, 0)));
|
||||
let (uploads, unloaded) =
|
||||
horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world));
|
||||
self.streaming.extra.truncate(areas);
|
||||
if let Some(lod) = &mut self.lod {
|
||||
self.lod_observe
|
||||
.extend(uploads.iter().map(|(key, _)| (key.0, key.2)));
|
||||
@@ -12771,6 +12989,20 @@ impl ApplicationHandler for Game<'_> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// ConfirmScreen.keyPressed: Escape answers no, once its delay is over.
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.screen == Screen::Dead && self.ui.death_confirm.is_some() =>
|
||||
{
|
||||
if event.state == ElementState::Pressed
|
||||
&& event.physical_key == PhysicalKey::Code(KeyCode::Escape)
|
||||
&& self
|
||||
.ui
|
||||
.death_confirm
|
||||
.is_some_and(|t| t.elapsed().as_millis() >= 1000)
|
||||
{
|
||||
self.death_confirm_answer(false)?;
|
||||
}
|
||||
}
|
||||
// ConfirmScreen.keyPressed: Escape answers no.
|
||||
WindowEvent::KeyboardInput { event, .. } if self.link_prompt.is_some() => {
|
||||
if event.state == ElementState::Pressed
|
||||
@@ -13432,6 +13664,7 @@ impl<'a> Game<'a> {
|
||||
spawn_origin: None,
|
||||
spawn_spiral: Default::default(),
|
||||
player_spawn: None,
|
||||
spawn_wait: Vec::new(),
|
||||
mobs: Vec::new(),
|
||||
creatures: Default::default(),
|
||||
sculk: Default::default(),
|
||||
@@ -13485,6 +13718,7 @@ impl<'a> Game<'a> {
|
||||
lightning_seen: [0; 2],
|
||||
sleeping: None,
|
||||
sleep_timer: 0,
|
||||
sleep_seen: (0, 0),
|
||||
dim: Dim::Overworld,
|
||||
world_root: PathBuf::new(),
|
||||
world_flat: false,
|
||||
@@ -13612,10 +13846,15 @@ impl<'a> Game<'a> {
|
||||
forced_hit: None,
|
||||
guest_use: None,
|
||||
lan_events: Vec::new(),
|
||||
lan_songs: Vec::new(),
|
||||
lan_cushion_breaks: Vec::new(),
|
||||
lan_block_events: Vec::new(),
|
||||
lan_entity_events: Vec::new(),
|
||||
lan_critical_hits: Vec::new(),
|
||||
lan_kinetic_hits: Vec::new(),
|
||||
stabbed: HashMap::new(),
|
||||
known_movement: Vec3::ZERO,
|
||||
kinetic_feedback: HashMap::new(),
|
||||
lan_global_events: Vec::new(),
|
||||
lid_openers: HashMap::new(),
|
||||
lan_acting: None,
|
||||
@@ -13639,6 +13878,7 @@ impl<'a> Game<'a> {
|
||||
boss_overlay: Default::default(),
|
||||
exec: Default::default(),
|
||||
rand_sequences: Default::default(),
|
||||
brushing: Default::default(),
|
||||
border: Default::default(),
|
||||
border_renderer: Default::default(),
|
||||
border_state: Default::default(),
|
||||
@@ -14299,10 +14539,10 @@ fn build_renderer(
|
||||
previous,
|
||||
api,
|
||||
))?;
|
||||
renderer.hud.fire_animations = atlas
|
||||
.fire_animations
|
||||
renderer.hud.sprite_animations = atlas
|
||||
.sprite_animations
|
||||
.iter()
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), (usize::MAX, 0, 0)))
|
||||
.collect();
|
||||
Ok(renderer)
|
||||
}
|
||||
@@ -14359,10 +14599,10 @@ fn loading_renderer(
|
||||
api,
|
||||
))?;
|
||||
if let Some(atlas) = atlas {
|
||||
renderer.hud.fire_animations = atlas
|
||||
.fire_animations
|
||||
renderer.hud.sprite_animations = atlas
|
||||
.sprite_animations
|
||||
.iter()
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), (usize::MAX, 0, 0)))
|
||||
.collect();
|
||||
}
|
||||
Ok(renderer)
|
||||
|
||||
@@ -876,6 +876,19 @@ impl Game<'_> {
|
||||
let it = item_view(stack);
|
||||
self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w));
|
||||
}
|
||||
/// `ConstructBeaconTrigger`: the pyramid levels of the new beacon.
|
||||
pub(super) fn trigger_construct_beacon(&mut self, levels: i32) {
|
||||
let me = self.player_entity();
|
||||
self.trigger("minecraft:construct_beacon", 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::range_i(&c["level"], i64::from(levels))
|
||||
});
|
||||
}
|
||||
/// `EnchantedItemTrigger`: the enchanted item and the levels it cost.
|
||||
pub(super) fn trigger_enchanted_item(&mut self, stack: &ItemStack, levels: i32) {
|
||||
let me = self.player_entity();
|
||||
|
||||
@@ -8,7 +8,6 @@ use horizon_core::random::RandomSource;
|
||||
impl Game<'_> {
|
||||
pub(super) fn tick_allays(&mut self) {
|
||||
let griefing = self.ui.rules.bool("mob_griefing");
|
||||
let player = self.player.as_ref().map(|p| p.position);
|
||||
// The playing jukeboxes, found at the first allay: no allay starts
|
||||
// or stops one, and the block entities run into the thousands.
|
||||
let mut jukeboxes: Option<Vec<(i32, i32, i32)>> = None;
|
||||
@@ -58,7 +57,7 @@ impl Game<'_> {
|
||||
};
|
||||
let Some((j, _)) = wanted else {
|
||||
self.mobs[i].extra.point = None;
|
||||
self.allay_deliver(i, player);
|
||||
self.allay_deliver(i);
|
||||
continue;
|
||||
};
|
||||
let e = &self.dropped[j];
|
||||
@@ -90,14 +89,46 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `AllayAi.getLikedPlayer`: the player the allay was given an item by,
|
||||
/// found by UUID among the host and the guests of the level (the window
|
||||
/// is a guest on the server thread), when they are not a spectator and
|
||||
/// within 64 blocks.
|
||||
fn allay_liked_player(&self, i: usize) -> Option<horizon_core::geometry::Vec3> {
|
||||
let m = &self.mobs[i];
|
||||
if !m.extra.tame {
|
||||
return None;
|
||||
}
|
||||
// An allay saved before its player was kept belongs to the host.
|
||||
let uuid = m
|
||||
.extra
|
||||
.owner
|
||||
.filter(|u| *u != [0, 0, 0, 1])
|
||||
.or(self.level.player_uuid)
|
||||
.unwrap_or([0, 0, 0, 1]);
|
||||
let host = self
|
||||
.player_view()
|
||||
.filter(|p| !p.spectator && self.level.player_uuid.unwrap_or([0, 0, 0, 1]) == uuid)
|
||||
.map(|p| p.position);
|
||||
let found = host.or_else(|| {
|
||||
self.lan_present()
|
||||
.into_iter()
|
||||
.find(|p| p.uuid == uuid && !p.spectator)
|
||||
.map(|p| {
|
||||
horizon_core::geometry::Vec3::new(p.position[0], p.position[1], p.position[2])
|
||||
})
|
||||
});
|
||||
found.filter(|p| p.distance_squared(m.position) < 64.0 * 64.0)
|
||||
}
|
||||
/// `GoAndGiveItemsToTarget` / `AllayAi.throwItem`: within 3 blocks of
|
||||
/// the deposit, one item a tick, each restarting the three-second pause
|
||||
/// before it picks anything up again.
|
||||
fn allay_deliver(&mut self, i: usize, player: Option<horizon_core::geometry::Vec3>) {
|
||||
fn allay_deliver(&mut self, i: usize) {
|
||||
let m = &self.mobs[i];
|
||||
if m.extra.ints[1] <= 0 {
|
||||
return;
|
||||
}
|
||||
let player = self.allay_liked_player(i);
|
||||
let m = &self.mobs[i];
|
||||
let target = match m.extra.home.filter(|_| m.extra.ints[2] > 0) {
|
||||
Some(h) => horizon_core::geometry::Vec3::new(
|
||||
f64::from(h[0]) + 0.5,
|
||||
@@ -167,11 +198,14 @@ impl Game<'_> {
|
||||
self.consume_held();
|
||||
return true;
|
||||
}
|
||||
let acting = self.acting_uuid();
|
||||
let holds = m.extra.main_hand.is_some();
|
||||
if !holds && !item.is_empty() {
|
||||
let m = &mut self.mobs[index];
|
||||
m.extra.main_hand = Some(item.into());
|
||||
m.extra.tame = true;
|
||||
// `Allay.mobInteract` remembers LIKED_PLAYER by UUID.
|
||||
m.extra.owner = Some(acting);
|
||||
self.audio
|
||||
.play("minecraft:entity.allay.item_given", Some(at), 2.0, 1.0);
|
||||
self.consume_held();
|
||||
@@ -186,6 +220,7 @@ impl Game<'_> {
|
||||
.unwrap_or_else(|| "minecraft:air".into());
|
||||
let carried = std::mem::take(&mut m.extra.ints[1]);
|
||||
m.extra.tame = false;
|
||||
m.extra.owner = None;
|
||||
self.audio
|
||||
.play("minecraft:entity.allay.item_taken", Some(at), 2.0, 1.0);
|
||||
if carried > 0 {
|
||||
|
||||
@@ -164,11 +164,35 @@ impl Game<'_> {
|
||||
let (was, is) = (previous > 0, b.levels > 0);
|
||||
if !was && is {
|
||||
self.beacon_sound([x, y, z], "minecraft:block.beacon.activate");
|
||||
let levels = b.levels;
|
||||
self.for_each_player(|g| g.beacon_constructed([x, y, z], levels));
|
||||
} else if was && !is {
|
||||
self.beacon_sound([x, y, z], "minecraft:block.beacon.deactivate");
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `BeaconBlockEntity.tick` after activating: `CONSTRUCT_BEACON` for a
|
||||
/// player in the box `AABB(x, y, z, x, y - 4, z).inflate(10, 5, 10)`.
|
||||
fn beacon_constructed(&mut self, p: [i32; 3], levels: i32) {
|
||||
let Some(bb) = self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|pl| pl.dimensions.bounds(pl.position))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (lo, hi) = (bb.min_position(), bb.max_position());
|
||||
let [x, y, z] = p.map(f64::from);
|
||||
if lo.x < x + 10.0
|
||||
&& hi.x > x - 10.0
|
||||
&& lo.y < y + 5.0
|
||||
&& hi.y > y - 9.0
|
||||
&& lo.z < z + 10.0
|
||||
&& hi.z > z - 10.0
|
||||
{
|
||||
self.trigger_construct_beacon(levels);
|
||||
}
|
||||
}
|
||||
pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
|
||||
let at = [
|
||||
f64::from(p[0]) + 0.5,
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Brushing suspicious sand and gravel: `BrushItem.onUseTick` and
|
||||
//! `BrushableBlockEntity`. The block's loot table stays in its saved block
|
||||
//! entity (like a decorated pot's) until the first counted stroke rolls it.
|
||||
use super::{Game, Hit, decorated_pot, spill, view_vector};
|
||||
use horizon_client::{
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
save,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// `BrushItem.USE_DURATION`.
|
||||
const USE_DURATION: u32 = 200;
|
||||
|
||||
/// A brushable block's counters. Vanilla never saves them: the block's
|
||||
/// `dusted` state is all that is left after a reload.
|
||||
#[derive(Default)]
|
||||
pub(super) struct BrushState {
|
||||
count: i32,
|
||||
resets_at: i64,
|
||||
cooldown_ends_at: i64,
|
||||
hit_face: Option<[i32; 3]>,
|
||||
}
|
||||
|
||||
/// `BrushableBlockEntity.getCompletionState`: the `dusted` property.
|
||||
fn completion_state(count: i32) -> i32 {
|
||||
match count {
|
||||
0 => 0,
|
||||
1..=2 => 1,
|
||||
3..=5 => 2,
|
||||
_ => 3,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type Brushing = HashMap<[i32; 3], BrushState>;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `BrushItem.onUseTick` for a brush used `ticks` ticks so far, the
|
||||
/// hand of `slot` acting.
|
||||
pub(super) fn tick_brush(&mut self, slot: usize, ticks: u32) {
|
||||
// No block under the crosshair: releaseUsingItem.
|
||||
let Some(hit) = self.pick() else {
|
||||
self.using = None;
|
||||
return;
|
||||
};
|
||||
let elapsed = ticks + 1;
|
||||
// The last tick before the backswing.
|
||||
if elapsed % 10 == 5 {
|
||||
self.brush_stroke(&hit, slot);
|
||||
}
|
||||
// The use ends after 200 ticks; the held button starts it again.
|
||||
self.using = (elapsed < USE_DURATION).then_some((slot, elapsed));
|
||||
}
|
||||
|
||||
/// One stroke on the block aimed at: dust (this window only), the brush
|
||||
/// sound, and the block entity's count. The brush wears when the block
|
||||
/// changed state.
|
||||
fn brush_stroke(&mut self, hit: &Hit, slot: usize) {
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let name = self.res.facts().get(state).name.clone();
|
||||
let (sound, brushable) = match &*name {
|
||||
"minecraft:suspicious_sand" => ("minecraft:item.brush.brushing.sand", true),
|
||||
"minecraft:suspicious_gravel" => ("minecraft:item.brush.brushing.gravel", true),
|
||||
_ => ("minecraft:item.brush.brushing.generic", false),
|
||||
};
|
||||
if self.lan_acting.is_none() {
|
||||
self.brush_dust(hit, slot == super::shield::OFFHAND_SLOT);
|
||||
}
|
||||
let at = hit.pos.map(|v| f64::from(v) + 0.5);
|
||||
self.audio.play(sound, Some(at), 1.0, 1.0);
|
||||
if brushable && self.brush_block(hit.pos, hit.face) {
|
||||
self.damage_held(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// `BrushItem.spawnDustParticles`.
|
||||
pub(super) fn brush_dust(&mut self, hit: &Hit, off_hand: bool) {
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let Some((sprite, tint)) = self.particle_sprite(state, hit.pos) else {
|
||||
return;
|
||||
};
|
||||
let options = ParticleOptions::block(ParticleType::Block, sprite, tint);
|
||||
// The arm that brushes: the main arm, or the other one for the off hand.
|
||||
let flip = if off_hand == self.settings.main_hand_left {
|
||||
1.0
|
||||
} else {
|
||||
-1.0
|
||||
};
|
||||
let view = view_vector(self.yaw, self.pitch);
|
||||
// DustParticlesDelta.fromDirection.
|
||||
let (dx, dz) = match hit.face {
|
||||
[0, _, 0] => (view[2], -view[0]),
|
||||
[0, 0, -1] => (1.0, -0.1),
|
||||
[0, 0, 1] => (-1.0, 0.1),
|
||||
[-1, 0, 0] => (-0.1, -1.0),
|
||||
_ => (0.1, 1.0),
|
||||
};
|
||||
let count = 7 + self.particles.level_random().next_int_bound(5).unwrap_or(0);
|
||||
let x = hit.point[0] - if hit.face == [-1, 0, 0] { 1.0e-6 } else { 0.0 };
|
||||
let z = hit.point[2] - if hit.face == [0, 0, -1] { 1.0e-6 } else { 0.0 };
|
||||
for _ in 0..count {
|
||||
let random = self.particles.level_random();
|
||||
let v = [
|
||||
dx * flip * 3.0 * random.next_double(),
|
||||
0.0,
|
||||
dz * flip * 3.0 * random.next_double(),
|
||||
];
|
||||
self.particles.add(&options, [x, hit.point[1], z], v);
|
||||
}
|
||||
}
|
||||
|
||||
/// `BrushableBlockEntity.brush`: whether the block changed (the brush wears).
|
||||
fn brush_block(&mut self, pos: [i32; 3], face: [i32; 3]) -> bool {
|
||||
let time = self.world.game_time;
|
||||
let mut brush = self.brushing.remove(&pos).unwrap_or_default();
|
||||
brush.hit_face.get_or_insert(face);
|
||||
brush.resets_at = time + 40;
|
||||
if time < brush.cooldown_ends_at {
|
||||
self.brushing.insert(pos, brush);
|
||||
return false;
|
||||
}
|
||||
brush.cooldown_ends_at = time + 10;
|
||||
self.unpack_brush_loot(pos);
|
||||
let before = completion_state(brush.count);
|
||||
brush.count += 1;
|
||||
if brush.count >= 10 {
|
||||
self.brushing_completed(pos, brush.hit_face);
|
||||
return true;
|
||||
}
|
||||
self.schedule_brushable_tick(pos);
|
||||
let after = completion_state(brush.count);
|
||||
self.brushing.insert(pos, brush);
|
||||
if before != after {
|
||||
self.set_dusted(pos, after);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `BrushableBlockEntity.unpackLootTable`: the table's roll becomes the
|
||||
/// block entity's item.
|
||||
fn unpack_brush_loot(&mut self, pos: [i32; 3]) {
|
||||
let Some(mut tag) = spill::saved_entity(&self.world, pos) else {
|
||||
return;
|
||||
};
|
||||
if tag.get("LootTable").is_none() {
|
||||
return;
|
||||
}
|
||||
let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
|
||||
decorated_pot::unpack_loot(
|
||||
&mut tag,
|
||||
loot.as_deref(),
|
||||
&mut self.world.random,
|
||||
&mut self.rand_sequences,
|
||||
self.level.seed,
|
||||
);
|
||||
spill::put_saved_entity(&mut self.world, pos, tag);
|
||||
}
|
||||
|
||||
/// `BrushableBlockEntity.brushingCompleted`: the item drops out of the
|
||||
/// brushed face and the block turns into its sand or gravel.
|
||||
fn brushing_completed(&mut self, pos: [i32; 3], face: Option<[i32; 3]>) {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let turns_into = match &*self.res.facts().get(state).name {
|
||||
"minecraft:suspicious_sand" => "minecraft:sand",
|
||||
"minecraft:suspicious_gravel" => "minecraft:gravel",
|
||||
_ => "minecraft:air",
|
||||
};
|
||||
// dropContent: the item at the middle of the block beside that face.
|
||||
let item = spill::saved_entity(&self.world, pos)
|
||||
.and_then(|tag| tag.get("item").and_then(save::item_from_nbt));
|
||||
if let Some(mut item) = item {
|
||||
let face = face.unwrap_or([0, 1, 0]);
|
||||
let take = 10 + self.world.random.next_int_bound(21).unwrap_or(0);
|
||||
item.count = item.count.min(take as u32);
|
||||
let at = [
|
||||
f64::from(pos[0] + face[0]) + 0.5,
|
||||
f64::from(pos[1] + face[1]) + 0.625,
|
||||
f64::from(pos[2] + face[2]) + 0.5,
|
||||
];
|
||||
self.spawn_item(item, at, [0.0; 3], 0);
|
||||
}
|
||||
// Level event 3008 for every player, then the block change.
|
||||
self.level_event_at(3008, pos, state.0 as i32);
|
||||
if let Some(base) = self.pack.assets.registry.default_state(turns_into) {
|
||||
let _ = self.level_set(pos, base);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_dusted(&mut self, pos: [i32; 3], dusted: i32) {
|
||||
let registry = self.pack.assets.registry;
|
||||
let Some(mut state) = registry
|
||||
.state(self.world.block(pos[0], pos[1], pos[2]))
|
||||
.cloned()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
state.properties.insert("dusted".into(), dusted.to_string());
|
||||
if let Ok(state) = registry.resolve(&state) {
|
||||
let _ = self.level_set(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_brushable_tick(&mut self, pos: [i32; 3]) {
|
||||
let at = horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
self.with_level(|b, level, ticks| b.schedule_tick(level, ticks, at, 2));
|
||||
}
|
||||
|
||||
/// `BrushableBlockEntity.checkReset`, from `BrushableBlock.tick`: a block
|
||||
/// left alone loses two counts, again every four ticks.
|
||||
pub(super) fn brushable_tick(&mut self, pos: [i32; 3]) {
|
||||
let time = self.world.game_time;
|
||||
let Some(mut brush) = self.brushing.remove(&pos) else {
|
||||
return;
|
||||
};
|
||||
let before = completion_state(brush.count);
|
||||
if brush.count != 0 && time >= brush.resets_at {
|
||||
brush.count = (brush.count - 2).max(0);
|
||||
brush.resets_at = time + 4;
|
||||
}
|
||||
let after = completion_state(brush.count);
|
||||
if brush.count != 0 {
|
||||
self.brushing.insert(pos, brush);
|
||||
self.schedule_brushable_tick(pos);
|
||||
}
|
||||
if before != after {
|
||||
self.set_dusted(pos, after);
|
||||
}
|
||||
}
|
||||
|
||||
/// Level event 3008 (`LevelEventHandler`): the finished block's sound
|
||||
/// and break particles.
|
||||
pub(super) fn brush_complete_event(&mut self, pos: [i32; 3], data: i32) {
|
||||
let state = horizon_world::registry::BlockStateId(data as u32);
|
||||
let sound = match &*self.res.facts().get(state).name {
|
||||
"minecraft:suspicious_sand" => "minecraft:item.brush.brushing.sand.complete",
|
||||
"minecraft:suspicious_gravel" => "minecraft:item.brush.brushing.gravel.complete",
|
||||
_ => "",
|
||||
};
|
||||
if !sound.is_empty() {
|
||||
let at = pos.map(|v| f64::from(v) + 0.5);
|
||||
// Each client plays it from the event itself.
|
||||
self.audio.play_unshared(sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
self.destroy_particles(pos, state);
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,9 @@ pub struct UiState {
|
||||
/// Death screen cause and when the player died (buttons wait 20 ticks).
|
||||
pub death_text: Option<Text>,
|
||||
pub died_at: Option<std::time::Instant>,
|
||||
/// `DeathScreen.TitleConfirmScreen` and when it opened (its buttons wait
|
||||
/// 20 ticks, `setDelay`).
|
||||
pub death_confirm: Option<std::time::Instant>,
|
||||
/// `LivingEntity.deathTime` of the window's player: ticks since it died.
|
||||
pub death_time: u32,
|
||||
}
|
||||
@@ -750,12 +753,25 @@ impl Game<'_> {
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
match self.ui.chat.click_at(
|
||||
let Some(style) = self.ui.chat.style_at(
|
||||
&self.gui.atlas.font,
|
||||
height as i32,
|
||||
cursor.0 as f64,
|
||||
cursor.1 as f64,
|
||||
) {
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
// ChatScreen.handleComponentClicked: with Shift held only an
|
||||
// insertion acts, else only the click event.
|
||||
if self.has_shift_down() {
|
||||
if let Some(insertion) = style.insertion
|
||||
&& let Some(screen) = self.ui.chat_screen.as_mut()
|
||||
{
|
||||
screen.type_text(&m, &c, &insertion);
|
||||
}
|
||||
return;
|
||||
}
|
||||
match style.click {
|
||||
Some(ClickEvent::CopyToClipboard(value)) => {
|
||||
use horizon_client::clipboard::Clipboard;
|
||||
self.clipboard.set(&value);
|
||||
@@ -769,6 +785,7 @@ impl Game<'_> {
|
||||
screen.suggest_command(&m, &c, &command);
|
||||
}
|
||||
}
|
||||
Some(ClickEvent::RunCommand(command)) => self.click_command(&command),
|
||||
// Screen.defaultHandleClickEvent: a page link means nothing in chat.
|
||||
Some(ClickEvent::ChangePage(_)) | None => {}
|
||||
}
|
||||
@@ -837,6 +854,22 @@ impl Game<'_> {
|
||||
self.answer_link_prompt(yes);
|
||||
}
|
||||
}
|
||||
/// `Screen.clickCommandAction`: run a clicked command as the player
|
||||
/// without adding it to the chat history. A client mod's command goes
|
||||
/// first, as `ClientPacketListener.sendUnattendedCommand` lets client
|
||||
/// commands take it. (Vanilla asks first when the command fails to
|
||||
/// parse; here the server answers it.)
|
||||
fn click_command(&mut self, command: &str) {
|
||||
let command = command.strip_prefix('/').unwrap_or(command);
|
||||
if self.mod_command(command) {
|
||||
return;
|
||||
}
|
||||
if self.remote.is_some() {
|
||||
self.send_chat(&format!("/{command}"));
|
||||
} else if !self.local_server_mod_command(command) {
|
||||
self.run_command(command);
|
||||
}
|
||||
}
|
||||
/// Chat lines over the HUD (focused while the chat screen is open).
|
||||
pub(super) fn draw_chat(&mut self, batch: &mut HudBatch) {
|
||||
let focused = self.screen == Screen::Chat;
|
||||
@@ -891,17 +924,39 @@ impl Game<'_> {
|
||||
);
|
||||
horizon_client::screen_draw::paint(batch, &self.gui.atlas, &button);
|
||||
}
|
||||
// The hovered message part's tooltip, one row per line of its text.
|
||||
if let Some(hover) = self.ui.chat.hover_at(
|
||||
&self.gui.atlas.font,
|
||||
batch.height as i32,
|
||||
f64::from(self.cursor.0),
|
||||
f64::from(self.cursor.1),
|
||||
) {
|
||||
let lines = hover_rows(&hover);
|
||||
// The hovered message part's tooltip (`renderComponentHoverEffect`),
|
||||
// or the text of the message tag under the cursor.
|
||||
let height = batch.height as i32;
|
||||
let (cx, cy) = (f64::from(self.cursor.0), f64::from(self.cursor.1));
|
||||
let wrap = (batch.width as i32 / 2).max(200);
|
||||
if let Some(style) = self.ui.chat.style_at(&self.gui.atlas.font, height, cx, cy) {
|
||||
if let Some(hover) = style.hover {
|
||||
let lines = self.wrapped_rows(&hover, wrap);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
} else if let Some(stack) = style
|
||||
.hover_item
|
||||
.as_deref()
|
||||
.and_then(horizon_client::item_data::stack_from_hover)
|
||||
.filter(|s| self.res.items().get(&s.item).is_some())
|
||||
{
|
||||
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
|
||||
}
|
||||
} else if self.ui.chat.indicator_at(height, cx, cy) {
|
||||
// GuiMessageTag.systemSinglePlayer's text, split at 210.
|
||||
let tag = Text::translate("chat.tag.system_single_player", &[]);
|
||||
let lines = self.wrapped_rows(&tag, 210);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
}
|
||||
}
|
||||
/// `Font.split`: a tooltip text wrapped at `width`, one white row per line.
|
||||
fn wrapped_rows(&self, text: &Text, width: i32) -> Vec<(Text, u32)> {
|
||||
let split = self
|
||||
.gui
|
||||
.atlas
|
||||
.font
|
||||
.split(&text.resolve_legacy(), width as f32);
|
||||
split.into_iter().map(|row| (row, u32::MAX)).collect()
|
||||
}
|
||||
/// Advance the overworld clock (ServerClockManager.tick) when
|
||||
/// `advance_time` allows it.
|
||||
pub(super) fn advance_clock(&mut self) {
|
||||
@@ -1046,6 +1101,7 @@ impl Game<'_> {
|
||||
let cause = self.ui.death_cause.take();
|
||||
self.ui.died_at = Some(std::time::Instant::now());
|
||||
self.ui.death_text = None;
|
||||
self.ui.death_confirm = None;
|
||||
if !self.ui.rules.bool("show_death_messages") {
|
||||
return;
|
||||
}
|
||||
@@ -1154,26 +1210,3 @@ pub fn screenshot_name(dir: &std::path::Path) -> String {
|
||||
fn owner_permission(allow_commands: bool) -> u8 {
|
||||
if allow_commands { 4 } else { 0 }
|
||||
}
|
||||
|
||||
/// A hover text's rows for the tooltip: split at line breaks, each in the
|
||||
/// colour of its first styled character (white without one).
|
||||
fn hover_rows(hover: &horizon_client::text::Text) -> Vec<(String, u32)> {
|
||||
let mut rows = vec![(String::new(), None)];
|
||||
for (c, style) in hover.resolve_legacy().chars() {
|
||||
if c == '\n' {
|
||||
rows.push((String::new(), None));
|
||||
continue;
|
||||
}
|
||||
let row = rows.last_mut().expect("one row");
|
||||
if row.0.is_empty() {
|
||||
row.1 = style.color;
|
||||
}
|
||||
row.0.push(c);
|
||||
}
|
||||
rows.into_iter()
|
||||
.map(|(text, color)| {
|
||||
let [_, r, g, b] = color.unwrap_or(0xFF_FFFF).to_be_bytes();
|
||||
(text, horizon_client::hud::rgba(r, g, b, 255))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1162,6 +1162,17 @@ impl Game<'_> {
|
||||
// An air stack is empty: nothing is given (but the message still is).
|
||||
let empty = id == "minecraft:air";
|
||||
for &t in targets.iter().filter(|_| !empty) {
|
||||
// The player's UUID, which an item they could not hold is set to.
|
||||
let conn = match t {
|
||||
Target::Guest(conn) => Some(conn),
|
||||
_ => self.lan_acting,
|
||||
};
|
||||
let uuid = match conn {
|
||||
Some(conn) => self
|
||||
.command_guest(conn)
|
||||
.map(|g| horizon_client::lan::playerdata::uuid_ints(g.uuid)),
|
||||
None => Some(self.level.ensure_player_uuid()),
|
||||
};
|
||||
self.for_player(t, |g| {
|
||||
let mut remaining = count;
|
||||
while remaining > 0 {
|
||||
@@ -1178,8 +1189,19 @@ impl Game<'_> {
|
||||
.target_position(Target::Player)
|
||||
.unwrap_or(g.source_position());
|
||||
if let Some(rest) = left {
|
||||
// Inventory full: drop the rest at the player's feet without pickup delay.
|
||||
g.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0);
|
||||
// Inventory full: Player.createItemStackToDrop (thrown from
|
||||
// the eyes), then setNoPickUpDelay and setTarget(player).
|
||||
let eye = g.eye_position().unwrap_or([
|
||||
p[0],
|
||||
p[1] + g.target_eye_height(Target::Player),
|
||||
p[2],
|
||||
]);
|
||||
g.throw_from_eyes(rest, eye, false);
|
||||
if let Some(item) = g.dropped.last_mut() {
|
||||
item.thrower = None;
|
||||
item.pickup_delay = 0;
|
||||
item.target = uuid;
|
||||
}
|
||||
} else {
|
||||
let r = &mut g.world.random;
|
||||
let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0;
|
||||
@@ -1447,7 +1469,7 @@ impl Game<'_> {
|
||||
{
|
||||
return Err(err("commands.teleport.invalidPosition", &[]));
|
||||
}
|
||||
let mut rotation = match ctx.get("rotation") {
|
||||
let rotation = match ctx.get("rotation") {
|
||||
Some(Arg::Coords(c)) => Some(c.rotation(self.source_rotation())),
|
||||
_ => None,
|
||||
};
|
||||
@@ -1462,21 +1484,31 @@ impl Game<'_> {
|
||||
(Some(f), _) => Some(f),
|
||||
(None, Some(_)) => {
|
||||
let e = self.entities(ctx, "facingEntity", false)?[0];
|
||||
// EntityAnchorArgument.Anchor.apply: the feet, or the eyes.
|
||||
let eyes = matches!(ctx.get("facingAnchor"), Some(Arg::Anchor(true)));
|
||||
let eye_height = if eyes { self.target_eye_height(e) } else { 0.0 };
|
||||
self.target_position(e)
|
||||
.map(|p| [p[0], p[1] + if eyes { 1.62 } else { 0.0 }, p[2]])
|
||||
.map(|p| [p[0], p[1] + eye_height, p[2]])
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(f) = facing {
|
||||
let eye = pos[1] + 1.62;
|
||||
// Entity.lookAt: from the source's anchor (the feet, unless `anchored
|
||||
// eyes`) on the teleported entity, so the eyes depend on the target.
|
||||
let anchored_eyes = self.command_source.is_some_and(|s| s.eyes);
|
||||
let look_at = |this: &Self, t: Target| {
|
||||
let f = facing?;
|
||||
let eye = if anchored_eyes {
|
||||
pos[1] + this.target_eye_height(t)
|
||||
} else {
|
||||
pos[1]
|
||||
};
|
||||
let (dx, dy, dz) = (f[0] - pos[0], f[1] - eye, f[2] - pos[2]);
|
||||
let horizontal = (dx * dx + dz * dz).sqrt();
|
||||
rotation = Some([
|
||||
Some([
|
||||
((dz.atan2(dx).to_degrees()) - 90.0) as f32,
|
||||
(-(dy.atan2(horizontal).to_degrees())) as f32,
|
||||
]);
|
||||
}
|
||||
])
|
||||
};
|
||||
// A server's player in another level than the source's (`execute
|
||||
// in`, the console's Overworld) moves there (ServerPlayer.teleport
|
||||
// into another level), after the command.
|
||||
@@ -1486,6 +1518,7 @@ impl Game<'_> {
|
||||
None => self.dim,
|
||||
};
|
||||
for &t in &targets {
|
||||
let rotation = look_at(self, t).or(rotation);
|
||||
if self.teleport_across(t, source_level, pos, rotation) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -105,6 +105,7 @@ impl Game<'_> {
|
||||
match ty.trim_start_matches("minecraft:") {
|
||||
"player_attack" => DamageKind::PlayerAttack,
|
||||
"mace_smash" => DamageKind::MaceSmash,
|
||||
"spear" => DamageKind::Spear,
|
||||
"mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
|
||||
"arrow" => DamageKind::Arrow,
|
||||
"thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
|
||||
@@ -118,7 +119,8 @@ impl Game<'_> {
|
||||
"dry_out" => DamageKind::DryOut,
|
||||
"magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic,
|
||||
"sting" => DamageKind::Sting,
|
||||
"cactus" | "sweet_berry_bush" => DamageKind::Cactus,
|
||||
"cactus" => DamageKind::Cactus,
|
||||
"sweet_berry_bush" => DamageKind::SweetBerryBush,
|
||||
"freeze" => DamageKind::Freeze,
|
||||
"in_wall" => DamageKind::InWall,
|
||||
"thorns" => DamageKind::Thorns,
|
||||
@@ -1219,7 +1221,7 @@ impl Game<'_> {
|
||||
/// LivingEntity.stopRiding for a mob: off its vehicle
|
||||
/// (Entity.removePassenger), then to where the vehicle lets it out
|
||||
/// (LivingEntity.dismountVehicle).
|
||||
fn dismount_mob(&mut self, rider: u32) {
|
||||
pub(in crate::game) fn dismount_mob(&mut self, rider: u32) {
|
||||
let Some(i) = self.mobs.iter().position(|m| m.id == rider) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ use horizon_client::{
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
geometry::{Aabb, Direction, Vec3, traverse_blocks},
|
||||
position::BlockPos,
|
||||
random::RandomSource,
|
||||
};
|
||||
@@ -49,6 +49,9 @@ pub(super) struct Creatures {
|
||||
/// Mace smash knockback on the other players from a guest's turn, waiting
|
||||
/// for it to end (game/mace.rs).
|
||||
pub smash_pushes: Vec<super::mace::SmashPush>,
|
||||
/// Sweep attacks from a guest's turn, waiting for it to end
|
||||
/// (game/lan_pvp.rs).
|
||||
pub sweeps: Vec<super::lan_pvp::Sweep>,
|
||||
/// Explosion packets from a guest's turn, waiting for it to end
|
||||
/// (centre, small, radius, blocks hit; game/lan_particles.rs).
|
||||
pub lan_explosions: Vec<([f64; 3], bool, f32, usize)>,
|
||||
@@ -56,6 +59,8 @@ pub(super) struct Creatures {
|
||||
pub elder_apparition: i32,
|
||||
/// The wandering trader spawner's clock.
|
||||
pub trader: super::wandering_trader::Spawner,
|
||||
/// When each player last put a parrot on a shoulder (`timeEntitySatOnShoulder`).
|
||||
pub shoulder_time: std::collections::HashMap<[i32; 4], i64>,
|
||||
/// The cat spawner's countdown (`CatSpawner.nextTick`).
|
||||
pub cat_tick: i32,
|
||||
/// Particles from a guest's turn, waiting for it to end
|
||||
@@ -451,9 +456,10 @@ impl Game<'_> {
|
||||
teams: std::sync::Arc::new(self.mob_teams()),
|
||||
items: Some(self.res.items()),
|
||||
lid_openers: &self.lid_openers,
|
||||
// The first player in the level: a server has no player of its own.
|
||||
difficulty: self.local_difficulty(
|
||||
self.player
|
||||
.as_ref()
|
||||
self.level_players()
|
||||
.first()
|
||||
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]),
|
||||
),
|
||||
}
|
||||
@@ -508,6 +514,7 @@ impl Game<'_> {
|
||||
self.tick_wandering_trader();
|
||||
self.tick_patrol_spawner();
|
||||
self.tick_cat_spawner();
|
||||
self.tick_village_siege();
|
||||
}
|
||||
self.tick_raids();
|
||||
self.tick_creature_entities()
|
||||
@@ -938,6 +945,55 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Melee or ranged damage to another mob; whether the hit landed.
|
||||
fn mob_hits_mob(&mut self, target: u32, amount: f32, source: Damage) -> bool {
|
||||
let mut killed = false;
|
||||
let mut hurt = false;
|
||||
let mut infested = false;
|
||||
if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) {
|
||||
let hit = t.damage(amount, source);
|
||||
hurt = hit;
|
||||
if hit {
|
||||
killed = !t.alive();
|
||||
// The hurt or death sound the mob raised.
|
||||
let center = t.center();
|
||||
for event in std::mem::take(&mut t.outbox) {
|
||||
match event {
|
||||
MobEvent::Sound(s, _, volume, pitch) => {
|
||||
self.audio
|
||||
.play(&format!("minecraft:{s}"), Some(center), volume, pitch);
|
||||
}
|
||||
MobEvent::Infested { .. } => infested = true,
|
||||
other => {
|
||||
// Left for the end of the tick.
|
||||
t.outbox.push(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if infested {
|
||||
self.mob_infested(target);
|
||||
}
|
||||
if hurt
|
||||
&& let Some(Who::Mob(attacker)) = source.attacker
|
||||
&& let Some(m) = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == attacker && m.species() == Species::Axolotl)
|
||||
{
|
||||
self.audio.play(
|
||||
"minecraft:entity.axolotl.attack",
|
||||
Some([m.position.x, m.position.y, m.position.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
if killed && let Some(Who::Mob(killer)) = source.attacker {
|
||||
self.zombie_killed(killer, target);
|
||||
}
|
||||
hurt
|
||||
}
|
||||
/// `InfestedMobEffect.onMobHurt` for a mob: silverfish from half its height up.
|
||||
pub(super) fn mob_infested(&mut self, mob: u32) {
|
||||
if let Some(m) = self.mobs.iter().find(|m| m.id == mob) {
|
||||
@@ -1017,6 +1073,20 @@ impl Game<'_> {
|
||||
MobEvent::EntityEvent { mob, event, at } => {
|
||||
self.lan_entity_event(mob as i32, event, at)
|
||||
}
|
||||
MobEvent::LevelParticles {
|
||||
kind,
|
||||
at,
|
||||
spread,
|
||||
speed,
|
||||
count,
|
||||
} => {
|
||||
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
|
||||
let options = horizon_client::particles::ParticleOptions::simple(ty);
|
||||
self.particles
|
||||
.send_particles(&options, at, spread, speed, count);
|
||||
self.lan_level_particles(&options, at, spread, speed, count);
|
||||
}
|
||||
}
|
||||
MobEvent::Sound(name, at, volume, pitch)
|
||||
| MobEvent::LocalSound(name, at, volume, pitch) => {
|
||||
self.audio
|
||||
@@ -1155,54 +1225,48 @@ impl Game<'_> {
|
||||
amount,
|
||||
source,
|
||||
} => {
|
||||
let mut killed = false;
|
||||
let mut hurt = false;
|
||||
let mut infested = false;
|
||||
if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) {
|
||||
let hit = t.damage(amount, source);
|
||||
hurt = hit;
|
||||
if hit {
|
||||
killed = !t.alive();
|
||||
// The hurt or death sound the mob raised.
|
||||
let center = t.center();
|
||||
for event in std::mem::take(&mut t.outbox) {
|
||||
match event {
|
||||
MobEvent::Sound(s, _, volume, pitch) => {
|
||||
self.audio.play(
|
||||
&format!("minecraft:{s}"),
|
||||
Some(center),
|
||||
volume,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
MobEvent::Infested { .. } => infested = true,
|
||||
other => {
|
||||
// Left for the end of the tick.
|
||||
t.outbox.push(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.mob_hits_mob(target, amount, source);
|
||||
}
|
||||
MobEvent::SonicBoom {
|
||||
target,
|
||||
attacker,
|
||||
from,
|
||||
direction,
|
||||
} => {
|
||||
// SonicBoom: the push only follows a hit that landed, scaled
|
||||
// by the target's KNOCKBACK_RESISTANCE.
|
||||
let (hurt, resistance) = match target {
|
||||
Who::Player => {
|
||||
let hurt = self.mob_hits_player(10.0, from, "minecraft:sonic_boom");
|
||||
let resistance = self.player.as_mut().map_or(0.0, |p| {
|
||||
p.attribute("minecraft:knockback_resistance").unwrap_or(0.0)
|
||||
});
|
||||
(hurt, resistance)
|
||||
}
|
||||
}
|
||||
if infested {
|
||||
self.mob_infested(target);
|
||||
}
|
||||
if hurt
|
||||
&& let Some(Who::Mob(attacker)) = source.attacker
|
||||
&& let Some(m) = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == attacker && m.species() == Species::Axolotl)
|
||||
{
|
||||
self.audio.play(
|
||||
"minecraft:entity.axolotl.attack",
|
||||
Some([m.position.x, m.position.y, m.position.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
if killed && let Some(Who::Mob(killer)) = source.attacker {
|
||||
self.zombie_killed(killer, target);
|
||||
Who::Mob(id) => {
|
||||
let source = Damage {
|
||||
kind: DamageKind::SonicBoom,
|
||||
attacker: Some(Who::Mob(attacker)),
|
||||
from: Some(from),
|
||||
};
|
||||
let hurt = self.mob_hits_mob(id, 10.0, source);
|
||||
let resistance = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map_or(0.0, |m| self.mob_knockback_resistance(m));
|
||||
(hurt, resistance)
|
||||
}
|
||||
};
|
||||
if hurt {
|
||||
let horizontal = 2.5 * (1.0 - resistance);
|
||||
let vertical = 0.5 * (1.0 - resistance);
|
||||
let velocity = [
|
||||
direction[0] * horizontal,
|
||||
direction[1] * vertical,
|
||||
direction[2] * horizontal,
|
||||
];
|
||||
self.handle_mob_events(vec![MobEvent::Push { target, velocity }])?;
|
||||
}
|
||||
}
|
||||
MobEvent::FinishAdmiring { mob } => self.finish_admiring(mob),
|
||||
@@ -1232,6 +1296,7 @@ impl Game<'_> {
|
||||
}
|
||||
MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob),
|
||||
MobEvent::EnterHive { mob, hive } => self.bee_enter_hive(mob, hive),
|
||||
MobEvent::ParrotToShoulder { mob } => self.parrot_to_shoulder(mob),
|
||||
MobEvent::Infested { mob } => self.mob_infested(mob),
|
||||
MobEvent::Gift { target, item } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target)
|
||||
@@ -1250,6 +1315,14 @@ impl Game<'_> {
|
||||
m.ai.target = Some(target);
|
||||
}
|
||||
}
|
||||
MobEvent::HuntHoglin { mob, target, ticks } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
m.extra.ints[0] = ticks;
|
||||
if m.ai.target.is_none() {
|
||||
m.ai.target = Some(Who::Mob(target));
|
||||
}
|
||||
}
|
||||
}
|
||||
MobEvent::Projectile(mut p) => {
|
||||
self.next_entity += 1;
|
||||
p.id = self.next_entity;
|
||||
@@ -1345,8 +1418,50 @@ impl Game<'_> {
|
||||
self.world.set(pos[0], pos[1], pos[2], state)?;
|
||||
}
|
||||
}
|
||||
MobEvent::Infest {
|
||||
pos,
|
||||
infested,
|
||||
poof,
|
||||
} => {
|
||||
let registry = &self.pack.assets.registry;
|
||||
let old = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if let Some(mut state) = registry.state(old).cloned() {
|
||||
let (from, to) = if infested {
|
||||
("minecraft:", "minecraft:infested_")
|
||||
} else {
|
||||
("minecraft:infested_", "minecraft:")
|
||||
};
|
||||
state.name = state.name.replacen(from, to, 1);
|
||||
if let Ok(id) = registry.resolve(&state) {
|
||||
self.world.set(pos[0], pos[1], pos[2], id)?;
|
||||
}
|
||||
}
|
||||
if let Some(mob) = poof {
|
||||
self.mob_poof(mob);
|
||||
}
|
||||
}
|
||||
MobEvent::BreakBlock { pos, drop } => {
|
||||
let old = self.world.block(pos[0], pos[1], pos[2]);
|
||||
// InfestedBlock.spawnAfterBreak: its silverfish comes out
|
||||
// when blocks drop.
|
||||
if drop
|
||||
&& self
|
||||
.res
|
||||
.facts()
|
||||
.get(old)
|
||||
.name
|
||||
.starts_with("minecraft:infested_")
|
||||
&& self.ui.rules.bool("block_drops")
|
||||
{
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
if let Some(id) = self.spawn_mob("minecraft:silverfish", at, false) {
|
||||
self.mob_poof(id);
|
||||
}
|
||||
}
|
||||
// Block.spawnDestroyParticles: fire breaks leave nothing.
|
||||
if !self.res.facts().get(old).has_class("BaseFireBlock") {
|
||||
self.destroy_particles(pos, old);
|
||||
@@ -2379,6 +2494,22 @@ impl Game<'_> {
|
||||
8.0,
|
||||
)
|
||||
}
|
||||
/// `BellBlock.onProjectileHit`: a projectile that strikes the bell proper
|
||||
/// rings it, and a player's shot counts as the player's ring.
|
||||
fn bell_projectile_hit(&mut self, p: &Projectile, pos: [i32; 3], at: Vec3, face: [i32; 3]) {
|
||||
let Some(face) = Direction::ALL.into_iter().find(|d| d.normal() == face) else {
|
||||
return;
|
||||
};
|
||||
let block = BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
let rang = self
|
||||
.with_level(|b, level, ticks| b.bell_projectile_hit(level, ticks, block, face, at.y));
|
||||
if rang {
|
||||
let _ = self.process_level_events();
|
||||
if p.owner == Some(Who::Player) {
|
||||
self.stats.custom("bell_ring", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// What an arrow's tick asked for: its particles and sounds.
|
||||
fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) {
|
||||
use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction};
|
||||
@@ -2521,6 +2652,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
|
||||
// Projectile.onHitBlock: BlockState.onProjectileHit, for every
|
||||
// projectile (a wind charge out of the world's top has no face).
|
||||
if let Hit::Block { pos, at, face } = hit
|
||||
&& face != [0; 3]
|
||||
{
|
||||
self.bell_projectile_hit(p, pos, at, face);
|
||||
}
|
||||
self.combat.projectile_owner = match p.owner {
|
||||
Some(Who::Mob(id)) => Some(id),
|
||||
_ => None,
|
||||
@@ -3009,7 +3147,7 @@ impl Game<'_> {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
|
||||
&& m.damage(4.0, source)
|
||||
{
|
||||
m.extra.levitation = 200;
|
||||
m.add_effect("minecraft:levitation", 200, 0);
|
||||
// Shulker.hurtServer: a shulker hit by a bullet.
|
||||
horizon_client::mobs::shulker::hit_by_bullet(m);
|
||||
}
|
||||
@@ -3173,6 +3311,10 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
if self.interact_shear_mob(index, &item) {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
// AbstractHorse.mobInteract: feed, equip or ride.
|
||||
if self.interact_mount(index, &item) {
|
||||
self.swing_arm();
|
||||
@@ -3208,13 +3350,25 @@ impl Game<'_> {
|
||||
.items()
|
||||
.get(&item)
|
||||
.is_some_and(|i| i.max_damage > 0);
|
||||
let parrot_poisonous = self
|
||||
.res
|
||||
.items()
|
||||
.item_tags
|
||||
.get("minecraft:parrot_poisonous_food")
|
||||
.is_some_and(|t| t.contains(&*item));
|
||||
let acting = self.acting_player_uuid();
|
||||
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|
||||
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight);
|
||||
let held_damage = held.as_ref().map_or(0, |h| h.damage as i32);
|
||||
let held_extra = held.as_ref().and_then(|h| h.extra.clone());
|
||||
let m = &mut self.mobs[index];
|
||||
if !m.alive() {
|
||||
return Ok(false);
|
||||
}
|
||||
let species = m.species();
|
||||
let center = m.center();
|
||||
// Wolf armor the owner takes off with shears or leaves a dropped stack of.
|
||||
let mut armor_drop: Option<ItemStack> = None;
|
||||
let mut consume = false;
|
||||
let mut give: Option<&str> = None;
|
||||
let mut sound: Option<&str> = None;
|
||||
@@ -3299,6 +3453,23 @@ impl Game<'_> {
|
||||
handled = false;
|
||||
}
|
||||
}
|
||||
// Entity.interact: shears take a tamed wolf's armor off for its owner.
|
||||
Species::Wolf
|
||||
if item == "minecraft:shears"
|
||||
&& m.extra.tame
|
||||
&& m.extra.owner == Some(acting)
|
||||
&& m.extra.head.is_some()
|
||||
&& !sneaking =>
|
||||
{
|
||||
let mut stack = ItemStack::new("minecraft:wolf_armor", 1);
|
||||
stack.damage = m.extra.body_damage.max(0) as u32;
|
||||
stack.extra = m.extra.body_extra.take();
|
||||
armor_drop = Some(stack);
|
||||
m.extra.head = None;
|
||||
m.extra.body_damage = 0;
|
||||
eat = Some(("item.armor.unequip_wolf", 1.0, 1.0));
|
||||
self.damage_held_tool();
|
||||
}
|
||||
// Wolf.mobInteract: heal, dye the collar or sit/stand when tame;
|
||||
// a bone tames a wild one a third of the time.
|
||||
Species::Wolf if m.extra.tame && is_food && m.health < m.attrs.max_health => {
|
||||
@@ -3313,6 +3484,36 @@ impl Game<'_> {
|
||||
m.health = (m.health + heal).min(m.attrs.max_health);
|
||||
consume = true;
|
||||
}
|
||||
// Wolf.mobInteract: the owner puts wolf armor on a tamed adult.
|
||||
Species::Wolf
|
||||
if item == "minecraft:wolf_armor"
|
||||
&& m.extra.tame
|
||||
&& m.extra.owner == Some(acting)
|
||||
&& m.extra.head.is_none()
|
||||
&& !m.is_baby() =>
|
||||
{
|
||||
m.extra.head = Some(item.as_str().into());
|
||||
m.extra.body_damage = held_damage;
|
||||
m.extra.body_extra = held_extra;
|
||||
consume = true;
|
||||
eat = Some(("item.armor.equip_wolf", 1.0, 1.0));
|
||||
}
|
||||
// Wolf.mobInteract: an armadillo scute repairs a sitting wolf's
|
||||
// armor by an eighth of its durability.
|
||||
Species::Wolf
|
||||
if item == "minecraft:armadillo_scute"
|
||||
&& m.extra.tame
|
||||
&& m.extra.owner == Some(acting)
|
||||
&& m.extra.sitting
|
||||
&& m.extra.head.is_some()
|
||||
&& m.extra.body_damage > 0 =>
|
||||
{
|
||||
m.extra.body_damage = (m.extra.body_damage
|
||||
- (horizon_client::mobs::WOLF_ARMOR_DURABILITY as f32 * 0.125) as i32)
|
||||
.max(0);
|
||||
consume = true;
|
||||
eat = Some(("item.wolf_armor.repair", 1.0, 1.0));
|
||||
}
|
||||
Species::Wolf
|
||||
if m.extra.tame
|
||||
&& m.extra.owner == Some(acting)
|
||||
@@ -3432,6 +3633,15 @@ impl Game<'_> {
|
||||
m.position.z.floor() as i32 >> 4,
|
||||
));
|
||||
}
|
||||
// Parrot.mobInteract: the owner makes a tame parrot on the ground
|
||||
// sit or stand (poisonous food is handled apart).
|
||||
Species::Parrot if m.extra.tame && m.on_ground && !parrot_poisonous => {
|
||||
m.extra.sitting = !m.extra.sitting;
|
||||
self.world.modified.insert((
|
||||
m.position.x.floor() as i32 >> 4,
|
||||
m.position.z.floor() as i32 >> 4,
|
||||
));
|
||||
}
|
||||
Species::Cat if !m.extra.tame && is_food => {
|
||||
consume = true;
|
||||
m.persistent = true;
|
||||
@@ -3489,7 +3699,7 @@ impl Game<'_> {
|
||||
let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0;
|
||||
if tamed {
|
||||
m.extra.tame = true;
|
||||
m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1]));
|
||||
m.extra.owner = Some(acting);
|
||||
}
|
||||
// TamableAnimal.spawnTamingParticles (entity event 7 or 6).
|
||||
self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 });
|
||||
@@ -3609,6 +3819,9 @@ impl Game<'_> {
|
||||
self.spawn_item(rest, at, [0.0, 0.0, 0.0], 40);
|
||||
}
|
||||
}
|
||||
if let Some(stack) = armor_drop {
|
||||
self.spawn_item(stack, [center[0], center[1] + 0.5, center[2]], [0.0; 3], 10);
|
||||
}
|
||||
for (item, count) in drops {
|
||||
for _ in 0..count {
|
||||
let v = [
|
||||
@@ -3631,6 +3844,39 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
/// `SnowGolem.mobInteract` and `Bogged.mobInteract` with shears: the
|
||||
/// pumpkin or the mushrooms come off (the shearing loot table), the shear
|
||||
/// game event is posted and the tool takes one damage.
|
||||
fn interact_shear_mob(&mut self, index: usize, item: &str) -> bool {
|
||||
let m = &self.mobs[index];
|
||||
if item != "minecraft:shears" || !m.alive() || m.extra.sheared {
|
||||
return false;
|
||||
}
|
||||
let (sound, table, height) = match m.species() {
|
||||
Species::SnowGolem => (
|
||||
"minecraft:entity.snow_golem.shear",
|
||||
"minecraft:shearing/snow_golem",
|
||||
m.eye_height(),
|
||||
),
|
||||
Species::Bogged => (
|
||||
"minecraft:entity.bogged.shear",
|
||||
"minecraft:shearing/bogged",
|
||||
f64::from(m.height()),
|
||||
),
|
||||
_ => return false,
|
||||
};
|
||||
let at = m.position;
|
||||
let tool = self.held().cloned();
|
||||
self.audio.play(sound, Some([at.x, at.y, at.z]), 1.0, 1.0);
|
||||
self.mobs[index].extra.sheared = true;
|
||||
for stack in self.sequence_loot(table, table, tool.as_ref()) {
|
||||
self.spawn_at_location(at, height, stack);
|
||||
}
|
||||
let ctx = self.who_context(Some(horizon_client::mobs::Who::Player), None);
|
||||
self.post_game_event("minecraft:shear", [at.x, at.y, at.z], ctx);
|
||||
self.damage_held_tool();
|
||||
true
|
||||
}
|
||||
/// `Armadillo.mobInteract`: a brush brushes a scute off an adult
|
||||
/// (`brushOffScute`) and loses 16 durability.
|
||||
fn interact_armadillo(&mut self, index: usize, item: &str) -> bool {
|
||||
@@ -3979,6 +4225,18 @@ impl Game<'_> {
|
||||
&armor,
|
||||
out,
|
||||
);
|
||||
if &*mob.kind.id == "minecraft:player" {
|
||||
// PlayerRenderer's WingsLayer and SpinAttackEffectLayer.
|
||||
self.player_elytra_geometry(
|
||||
mob,
|
||||
mob.extra.chest.as_deref(),
|
||||
camera,
|
||||
alpha as f32,
|
||||
packed,
|
||||
out,
|
||||
);
|
||||
self.spin_attack_geometry(mob, camera, alpha as f32, packed, out);
|
||||
}
|
||||
self.mob_block_geometry(mob, camera, alpha, packed, out);
|
||||
if let Some(rgb) = outline {
|
||||
self.mark_outline(&out[entity_start..], rgb);
|
||||
@@ -4213,6 +4471,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
|
||||
match kind {
|
||||
K::PlayerAttack => "minecraft:player_attack",
|
||||
K::MaceSmash => "minecraft:mace_smash",
|
||||
K::Spear => "minecraft:spear",
|
||||
K::MobAttack => "minecraft:mob_attack",
|
||||
K::Arrow => "minecraft:arrow",
|
||||
K::Thrown => "minecraft:thrown",
|
||||
@@ -4229,6 +4488,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
|
||||
K::Magic => "minecraft:magic",
|
||||
K::Sting => "minecraft:sting",
|
||||
K::Cactus => "minecraft:cactus",
|
||||
K::SweetBerryBush => "minecraft:sweet_berry_bush",
|
||||
K::Generic => "minecraft:generic",
|
||||
K::InWall => "minecraft:in_wall",
|
||||
K::Thorns => "minecraft:thorns",
|
||||
@@ -4289,13 +4549,10 @@ impl Game<'_> {
|
||||
f64::from((pos[0] >> 4) * 16 + 8),
|
||||
f64::from((pos[2] >> 4) * 16 + 8),
|
||||
];
|
||||
let spectator = self.spectator();
|
||||
let Some(close) = self.player.as_ref().filter(|_| !spectator).map(|p| {
|
||||
let close = self.level_players().iter().any(|p| {
|
||||
let (dx, dz) = (p.position.x - centre[0], p.position.z - centre[1]);
|
||||
dx * dx + dz * dz < 16384.0
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
!p.spectator && dx * dx + dz * dz < 16384.0
|
||||
});
|
||||
if !close {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -673,6 +673,9 @@ impl Game<'_> {
|
||||
return Ok(());
|
||||
}
|
||||
self.sync_ops(&lists);
|
||||
if let Some(host) = self.lan.as_mut() {
|
||||
host.hub.spawn_protection = props.spawn_protection;
|
||||
}
|
||||
log(
|
||||
"INFO",
|
||||
&format!(
|
||||
|
||||
@@ -672,6 +672,7 @@ impl Game<'_> {
|
||||
}
|
||||
let source = match source.kind {
|
||||
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
|
||||
horizon_client::mobs::DamageKind::Spear => "minecraft:spear",
|
||||
_ => "minecraft:player_attack",
|
||||
};
|
||||
out.push(format!(
|
||||
|
||||
@@ -1122,14 +1122,11 @@ impl Game<'_> {
|
||||
if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
|
||||
return false;
|
||||
}
|
||||
let modifiers = self
|
||||
.attack_item_info()
|
||||
.map(|i| (i.attack_damage, i.attack_speed))
|
||||
.unwrap_or((0.0, 0.0));
|
||||
let speed = (4.0 + modifiers.1).max(0.1);
|
||||
let scale = ((self.attack_ticks as f32 + 0.5) / (20.0 / speed)).clamp(0.0, 1.0);
|
||||
let hand_damage = self.attack_item_info().map_or(0.0, |i| i.attack_damage);
|
||||
let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed());
|
||||
let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0);
|
||||
let mut amount =
|
||||
(1.0 + modifiers.0 + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8);
|
||||
(1.0 + hand_damage + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8);
|
||||
let falling = self
|
||||
.player
|
||||
.as_ref()
|
||||
@@ -3029,14 +3026,11 @@ impl Game<'_> {
|
||||
let (a, b) = (room.min_position(), room.max_position());
|
||||
lo.x < b.x && hi.x > a.x && lo.y < b.y && hi.y > a.y && lo.z < b.z && hi.z > a.z
|
||||
};
|
||||
let player = self.player.as_ref().is_some_and(|p| {
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
let h = f64::from(p.dimensions.height);
|
||||
touches(
|
||||
Vec3::new(p.position.x - w, p.position.y, p.position.z - w),
|
||||
Vec3::new(p.position.x + w, p.position.y + h, p.position.z + w),
|
||||
)
|
||||
});
|
||||
// Level.getEntities: the host's player and every guest in the level.
|
||||
let player = self
|
||||
.fight_players()
|
||||
.iter()
|
||||
.any(|p| !p.spectator && touches(p.bounds.min_position(), p.bounds.max_position()));
|
||||
player
|
||||
|| self.crystals.iter().any(|c| {
|
||||
touches(
|
||||
|
||||
@@ -3,14 +3,18 @@
|
||||
//! 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, ...) and Soul
|
||||
//! Speed's `location_changed` and `tick` effects.
|
||||
//! the armor attribute effects (respiration, depth strider, ...), Soul
|
||||
//! Speed's `location_changed` and `tick` effects and the
|
||||
//! `minecraft:location_changed` disk effect (frost walker).
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
enchant::{EffectContext, Enchantments, level_value},
|
||||
items::ItemStack,
|
||||
mobs::Who,
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
use horizon_world::{fluid::FluidKind, level::LevelAccess, registry::BlockStateId};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -69,7 +73,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// `getEnchantedDamage - base`: damage bonus of the held weapon against a mob type.
|
||||
pub(super) fn enchant_damage_bonus(&mut self, target: &str) -> f32 {
|
||||
let Some(held) = self.inventory[self.selected].clone() else {
|
||||
let Some(held) = self.held().cloned() else {
|
||||
return 0.0;
|
||||
};
|
||||
let ctx = EffectContext {
|
||||
@@ -102,7 +106,7 @@ impl Game<'_> {
|
||||
/// whether the hit is that knockback attack.
|
||||
pub(super) fn extra_knockback(&mut self, target_kind: &str, scale: f32) -> (f32, bool) {
|
||||
let knockback_attack = scale > 0.9 && self.player.as_ref().is_some_and(|p| p.sprinting);
|
||||
let enchanted = match self.inventory[self.selected].clone() {
|
||||
let enchanted = match self.held().cloned() {
|
||||
Some(held) => {
|
||||
let ctx = EffectContext {
|
||||
this: Some(target_kind),
|
||||
@@ -144,7 +148,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// After a successful melee hit: fire aspect and wind burst.
|
||||
pub(super) fn post_attack(&mut self, mob: usize) {
|
||||
let Some(held) = self.inventory[self.selected].clone() else {
|
||||
let Some(held) = self.held().cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(m) = self.mobs.get(mob) else { return };
|
||||
@@ -636,6 +640,173 @@ impl Game<'_> {
|
||||
self.apply_equipment();
|
||||
}
|
||||
}
|
||||
/// `EnchantmentHelper.runLocationChangedEffects` for the worn armor of the
|
||||
/// player, run on the server once the player has moved: `LivingEntity.baseTick`
|
||||
/// runs it when the block position changed, `checkFallDamage` when it lands.
|
||||
/// `from` and `was_on_ground` are where and how the tick began.
|
||||
pub(super) fn location_changed_effects(&mut self, from: [f64; 3], was_on_ground: bool) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
let on_ground = p.ground.on_ground;
|
||||
let cell = |v: [f64; 3]| v.map(|c| c.floor() as i32);
|
||||
if cell(from) == cell(at) && !(on_ground && !was_on_ground) {
|
||||
return;
|
||||
}
|
||||
let riding = self.riding.is_some();
|
||||
let mut disks = Vec::new();
|
||||
for (stack, slot) in self.armor.iter().zip(["head", "chest", "legs", "feet"]) {
|
||||
let Some(stack) = stack else { continue };
|
||||
for (id, level) in stack.enchantments() {
|
||||
let Some(def) = self.res.stations().enchantments.get(id) else {
|
||||
continue;
|
||||
};
|
||||
if !def
|
||||
.slots
|
||||
.iter()
|
||||
.any(|s| s == slot || s == "armor" || s == "any")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for effect in def.effects["minecraft:location_changed"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if effect["effect"]["type"] == "minecraft:replace_disk"
|
||||
&& location_requirements(&effect["requirements"], on_ground, riding)
|
||||
{
|
||||
disks.push((effect["effect"].clone(), *level));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (effect, level) in disks {
|
||||
self.replace_disk(&effect, level, at);
|
||||
}
|
||||
}
|
||||
/// `ReplaceDisk.apply`: the blocks of the disk around `at` that pass the
|
||||
/// predicate become the effect's state, and each placement is a game event.
|
||||
fn replace_disk(&mut self, effect: &Value, level: u32, at: [f64; 3]) {
|
||||
let registry = self.pack.assets.registry;
|
||||
let spec = &effect["block_state"];
|
||||
let Some(default) = spec["id"].as_str().and_then(|n| registry.default_state(n)) else {
|
||||
return;
|
||||
};
|
||||
let Some(mut state) = registry.state(default).cloned() else {
|
||||
return;
|
||||
};
|
||||
for (k, v) in spec["properties"].as_object().into_iter().flatten() {
|
||||
state
|
||||
.properties
|
||||
.insert(k.clone(), v.as_str().unwrap_or("").to_owned());
|
||||
}
|
||||
let new = registry.resolve(&state).unwrap_or(default);
|
||||
let radius = level_value(&effect["radius"], level) as i32;
|
||||
let height = level_value(&effect["height"], level) as i32;
|
||||
let offset = cell_offset(effect);
|
||||
let center = [0, 1, 2].map(|i| at[i].floor() as i32 + offset[i]);
|
||||
let event = effect["trigger_game_event"].as_str() == Some("minecraft:block_place");
|
||||
for dy in (height - 1).min(0)..=0 {
|
||||
for dz in -radius..=radius {
|
||||
for dx in -radius..=radius {
|
||||
let pos = [center[0] + dx, center[1] + dy, center[2] + dz];
|
||||
let (x, z) = (
|
||||
f64::from(pos[0]) + 0.5 - at[0],
|
||||
f64::from(pos[2]) + 0.5 - at[2],
|
||||
);
|
||||
if x * x + z * z >= f64::from(radius * radius)
|
||||
|| !self.disk_predicate(&effect["predicate"], pos, new)
|
||||
|| self.level_set(pos, new).is_err()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if event {
|
||||
self.post_block_game_event(
|
||||
"minecraft:block_place",
|
||||
pos,
|
||||
Some(Who::Player),
|
||||
Some(new),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The `BlockPredicate` subset the disk effect uses, tested at `pos`; no
|
||||
/// predicate matches everything.
|
||||
fn disk_predicate(&mut self, p: &Value, pos: [i32; 3], placed: BlockStateId) -> bool {
|
||||
if p.is_null() {
|
||||
return true;
|
||||
}
|
||||
let offset = cell_offset(p);
|
||||
let at = [0, 1, 2].map(|i| pos[i] + offset[i]);
|
||||
let state = self.world.block(at[0], at[1], at[2]);
|
||||
let b = self.res.behaviours();
|
||||
let names = |v: &Value| -> Vec<String> {
|
||||
match v {
|
||||
Value::String(s) => vec![s.clone()],
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.filter_map(|n| n.as_str().map(String::from))
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
};
|
||||
match p["type"].as_str().unwrap_or("") {
|
||||
"minecraft:all_of" => p["predicates"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|q| self.disk_predicate(q, pos, placed)),
|
||||
// `MatchingBlockTagPredicate`
|
||||
"minecraft:matching_block_tag" => b
|
||||
.tag(p["tag"].as_str().unwrap_or("").trim_start_matches('#'))
|
||||
.is_some_and(|t| t.contains(b.block(state))),
|
||||
// `MatchingBlocksPredicate`
|
||||
"minecraft:matching_blocks" => {
|
||||
names(&p["blocks"]).iter().any(|n| n == b.table.name(state))
|
||||
}
|
||||
// `MatchingFluidsPredicate`: Fluids.WATER is the source.
|
||||
"minecraft:matching_fluids" => {
|
||||
let fluid = b.fluid(state);
|
||||
names(&p["fluids"]).iter().any(|n| match n.as_str() {
|
||||
"minecraft:water" => fluid.kind() == FluidKind::Water && fluid.is_source(),
|
||||
"minecraft:flowing_water" => {
|
||||
fluid.kind() == FluidKind::Water && !fluid.is_source()
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
// `UnobstructedPredicate`: no building-blocking entity in the block.
|
||||
"minecraft:unobstructed" => self.with_level(|_, level, _| {
|
||||
level.is_unobstructed(BlockPos::new(pos[0], pos[1], pos[2]), placed)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// Whether a worn enchantment gives immunity to `#burn_from_stepping`
|
||||
/// damage (frost walker's `minecraft:damage_immunity`).
|
||||
pub(crate) fn wears_burn_from_stepping_immunity(&self) -> bool {
|
||||
self.armor
|
||||
.iter()
|
||||
.zip(["head", "chest", "legs", "feet"])
|
||||
.any(|(stack, slot)| {
|
||||
stack
|
||||
.iter()
|
||||
.flat_map(ItemStack::enchantments)
|
||||
.any(|(id, _)| {
|
||||
self.res.stations().enchantments.get(id).is_some_and(|def| {
|
||||
def.effects.get("minecraft:damage_immunity").is_some()
|
||||
&& def
|
||||
.slots
|
||||
.iter()
|
||||
.any(|s| s == slot || s == "armor" || s == "any")
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
/// 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.
|
||||
@@ -684,3 +855,35 @@ fn soul_speed_modifiers(
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An effect's or predicate's `offset` vector (zero when absent).
|
||||
fn cell_offset(v: &Value) -> [i32; 3] {
|
||||
let at = |i: usize| {
|
||||
v["offset"]
|
||||
.get(i)
|
||||
.and_then(Value::as_i64)
|
||||
.map_or(0, |n| n as i32)
|
||||
};
|
||||
[at(0), at(1), at(2)]
|
||||
}
|
||||
/// The loot-condition subset a `location_changed` effect requires of the
|
||||
/// wearer: standing on the ground and not riding (frost walker).
|
||||
fn location_requirements(req: &Value, on_ground: bool, riding: bool) -> bool {
|
||||
match req["type"].as_str().unwrap_or("") {
|
||||
"" if req.is_null() => true,
|
||||
"minecraft:all_of" => req["terms"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|t| location_requirements(t, on_ground, riding)),
|
||||
"minecraft:inverted" => !location_requirements(&req["term"], on_ground, riding),
|
||||
"minecraft:entity_properties" => {
|
||||
let p = &req["predicate"];
|
||||
p["minecraft:flags"]["is_on_ground"]
|
||||
.as_bool()
|
||||
.is_none_or(|v| v == on_ground)
|
||||
&& (p["minecraft:vehicle"].is_null() || riding)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use horizon_client::{
|
||||
motion::PlayerMotion,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
vanillagen::VanillaTerrain,
|
||||
world_spawn::PlayerSpawnFinder,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
@@ -581,7 +582,15 @@ impl Game<'_> {
|
||||
let position = if let Some(job) = self.end.job.take() {
|
||||
self.resolve_gateway(job, target)?
|
||||
} else {
|
||||
let (position, yaw) = self.end_arrival(target)?;
|
||||
let mut finder = self.player_spawn.take();
|
||||
let arrival = self.end_arrival(target, &mut finder);
|
||||
self.player_spawn = finder;
|
||||
let Some((position, yaw)) = arrival? else {
|
||||
// A spawn candidate's chunk is loading: try again next tick.
|
||||
self.travelling = Some((player, target));
|
||||
self.end_travel = true;
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(yaw) = yaw {
|
||||
self.yaw = yaw;
|
||||
player.yaw = yaw;
|
||||
@@ -606,7 +615,13 @@ impl Game<'_> {
|
||||
/// Where an End portal's traveller lands once `target` has loaded, and
|
||||
/// the yaw it faces there: the platform below the End's spawn point,
|
||||
/// facing west, or the top of the Overworld's spawn column.
|
||||
pub(super) fn end_arrival(&mut self, target: Vec3) -> Result<(Vec3, Option<f32>)> {
|
||||
/// None while a candidate of the world spawn's search loads (`finder`
|
||||
/// keeps it, see `search_spawn`).
|
||||
pub(super) fn end_arrival(
|
||||
&mut self,
|
||||
target: Vec3,
|
||||
finder: &mut Option<PlayerSpawnFinder>,
|
||||
) -> Result<Option<(Vec3, Option<f32>)>> {
|
||||
if self.dim == Dim::End {
|
||||
// EndPlatformFeature.createEndPlatform below the spawn point.
|
||||
let origin = [END_SPAWN[0], END_SPAWN[1] - 1, END_SPAWN[2]];
|
||||
@@ -626,22 +641,32 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
// Direction.WEST.toYRot().
|
||||
return Ok((target, Some(90.0)));
|
||||
return Ok(Some((target, Some(90.0))));
|
||||
}
|
||||
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: where the bed or
|
||||
// anchor puts the player, facing it; else onto the spawn column.
|
||||
let mut target = target;
|
||||
if let Some(c) = self.respawn_config.filter(|c| c.dim == self.dim) {
|
||||
if let Some((at, yaw)) = self.find_respawn_and_use(c, false)? {
|
||||
return Ok((at, Some(yaw)));
|
||||
return Ok(Some((at, Some(yaw))));
|
||||
}
|
||||
let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]);
|
||||
target = Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5);
|
||||
}
|
||||
let y = self
|
||||
.land_column(target.x.floor() as i32, target.z.floor() as i32)
|
||||
.map_or(target.y, f64::from);
|
||||
Ok((Vec3::new(target.x, y, target.z), None))
|
||||
let (x, z) = (target.x.floor() as i32, target.z.floor() as i32);
|
||||
// TeleportTransition.missingRespawnBlock: PlayerSpawnFinder around
|
||||
// the world spawn.
|
||||
if let Some(world) = self.level.world_spawn.filter(|w| w[0] == x && w[2] == z) {
|
||||
return Ok(match self.search_spawn(world, finder) {
|
||||
Ok(at) => Some((at, None)),
|
||||
Err(chunk) => {
|
||||
self.spawn_wait.push(chunk);
|
||||
None
|
||||
}
|
||||
});
|
||||
}
|
||||
let y = self.land_column(x, z).map_or(target.y, f64::from);
|
||||
Ok(Some((Vec3::new(target.x, y, target.z), None)))
|
||||
}
|
||||
|
||||
/// Dying away from the Overworld respawns at the world spawn there.
|
||||
|
||||
@@ -7,6 +7,7 @@ use horizon_assets::{bake::bake_model, model::CuboidModel, resolve::ModelLibrary
|
||||
use horizon_client::{entities::ItemFrame, items::ItemStack, mesher::Vertex};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
position::BlockPos,
|
||||
random::RandomSource,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
@@ -223,6 +224,7 @@ impl Game<'_> {
|
||||
}
|
||||
let p = self.item_frames[i].pos;
|
||||
self.world.modified.insert((p[0] >> 4, p[2] >> 4));
|
||||
self.frame_output_changed(p);
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
@@ -255,8 +257,17 @@ impl Game<'_> {
|
||||
}
|
||||
self.drop_frame_items(&f, with_frame, true);
|
||||
self.world.modified.insert((f.pos[0] >> 4, f.pos[2] >> 4));
|
||||
if f.item.is_some() {
|
||||
self.frame_output_changed(f.pos);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `ItemFrame.setItem` / `setRotation`: `updateNeighbourForOutputSignal`, so
|
||||
/// the comparators reading the frame take its new signal.
|
||||
fn frame_output_changed(&mut self, pos: [i32; 3]) {
|
||||
let at = BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
self.with_level(|b, level, ticks| b.update_neighbour_for_output_signal(level, ticks, at));
|
||||
}
|
||||
/// `ItemFrame.dropItem`: the frame (when breaking) and the held item.
|
||||
fn drop_frame_items(&mut self, f: &ItemFrame, with_frame: bool, by_player: bool) {
|
||||
if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) {
|
||||
@@ -300,6 +311,9 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play(&sound(&f, "break"), Some(center(&f)), 1.0, 1.0);
|
||||
self.drop_frame_items(&f, true, false);
|
||||
if f.item.is_some() {
|
||||
self.frame_output_changed(f.pos);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,12 +352,21 @@ impl Game<'_> {
|
||||
_ => name.ends_with("shulker_box"),
|
||||
}
|
||||
}
|
||||
/// `Attributes.ATTACK_SPEED` with the main-hand item's modifier.
|
||||
/// `Attributes.ATTACK_SPEED` with the main-hand item's modifier and the
|
||||
/// Haste and Mining Fatigue modifiers (`ADD_MULTIPLIED_TOTAL`), clamped to
|
||||
/// the attribute's range.
|
||||
pub(super) fn main_hand_attack_speed(&self) -> f64 {
|
||||
horizon_client::attack_strength::BASE_ATTACK_SPEED
|
||||
let value = horizon_client::attack_strength::BASE_ATTACK_SPEED
|
||||
+ self
|
||||
.attack_item_info()
|
||||
.map_or(0.0, |i| f64::from(i.attack_speed))
|
||||
.map_or(0.0, |i| f64::from(i.attack_speed));
|
||||
self.potions
|
||||
.effects
|
||||
.modifiers()
|
||||
.into_iter()
|
||||
.filter(|m| m.0 == "minecraft:attack_speed")
|
||||
.fold(value, |v, m| v * (1.0 + m.2))
|
||||
.clamp(0.0, 1024.0)
|
||||
}
|
||||
/// The item whose attack damage and speed modifiers the player has (`attack_item`).
|
||||
pub(super) fn attack_item_info(&self) -> Option<&horizon_client::items::ItemInfo> {
|
||||
|
||||
@@ -212,39 +212,58 @@ impl Game<'_> {
|
||||
)
|
||||
.is_ok_and(|shape| shape.is_empty())
|
||||
}
|
||||
/// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a
|
||||
/// player who has no position yet. None while a candidate's chunk loads.
|
||||
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
|
||||
let mut finder = match self.player_spawn {
|
||||
Some(finder) => finder,
|
||||
None => self.spawn_finder(suggestion),
|
||||
};
|
||||
let found = loop {
|
||||
/// PlayerSpawnFinder.findSpawn around the world spawn, as far as the loaded
|
||||
/// chunks allow: the feet of the first free column within the respawn
|
||||
/// radius, else the suggestion's own column. The finder waits in `state`
|
||||
/// (None to begin); Err gives the chunk of the candidate being waited for,
|
||||
/// which the caller must have loaded (the finder tries at most 1024
|
||||
/// columns).
|
||||
pub(super) fn search_spawn(
|
||||
&self,
|
||||
suggestion: [i32; 3],
|
||||
state: &mut Option<PlayerSpawnFinder>,
|
||||
) -> std::result::Result<Vec3, (i32, i32)> {
|
||||
let mut finder = state
|
||||
.take()
|
||||
.unwrap_or_else(|| self.spawn_finder(suggestion));
|
||||
let suggestion = finder.suggestion;
|
||||
loop {
|
||||
let Some(candidate) = finder.next_candidate() else {
|
||||
break Some(self.fixup_spawn_height(suggestion));
|
||||
return Ok(self.fixup_spawn_height(suggestion));
|
||||
};
|
||||
let (x, z) = match candidate {
|
||||
SpawnCandidate::Column(x, z) => (x, z),
|
||||
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
|
||||
};
|
||||
if !self.streaming.is_lit(x >> 4, z >> 4) {
|
||||
self.streaming.center = (x >> 4, z >> 4);
|
||||
finder.retry();
|
||||
break None;
|
||||
*state = Some(finder);
|
||||
return Err((x >> 4, z >> 4));
|
||||
}
|
||||
match candidate {
|
||||
SpawnCandidate::Column(x, z) => {
|
||||
if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z)
|
||||
&& self.player_fits(pos)
|
||||
{
|
||||
break Some(bottom_center(pos));
|
||||
return Ok(bottom_center(pos));
|
||||
}
|
||||
}
|
||||
SpawnCandidate::Suggestion => break Some(self.fixup_spawn_height(suggestion)),
|
||||
SpawnCandidate::Suggestion => return Ok(self.fixup_spawn_height(suggestion)),
|
||||
}
|
||||
};
|
||||
self.player_spawn = found.is_none().then_some(finder);
|
||||
Ok(found)
|
||||
}
|
||||
}
|
||||
/// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a
|
||||
/// player who has no position yet. None while a candidate's chunk loads.
|
||||
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
|
||||
let mut state = self.player_spawn.take();
|
||||
match self.search_spawn(suggestion, &mut state) {
|
||||
Ok(feet) => Ok(Some(feet)),
|
||||
Err(chunk) => {
|
||||
self.streaming.center = chunk;
|
||||
self.player_spawn = state;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut
|
||||
/// by the world border; the suggestion itself in adventure mode.
|
||||
|
||||
@@ -171,6 +171,9 @@ fn use_duration(components: &Components) -> i32 {
|
||||
let seconds = c["consume_seconds"].as_f64().unwrap_or(1.6);
|
||||
return (seconds * 20.0) as i32;
|
||||
}
|
||||
if components.get("minecraft:kinetic_weapon").is_some() {
|
||||
return 72_000;
|
||||
}
|
||||
let item_model = components
|
||||
.get("minecraft:item_model")
|
||||
.and_then(Value::as_str)
|
||||
@@ -180,8 +183,9 @@ fn use_duration(components: &Components) -> i32 {
|
||||
| "minecraft:crossbow"
|
||||
| "minecraft:trident"
|
||||
| "minecraft:spyglass"
|
||||
| "minecraft:goat_horn"
|
||||
| "minecraft:brush" => 72_000,
|
||||
| "minecraft:goat_horn" => 72_000,
|
||||
// BrushItem.USE_DURATION.
|
||||
"minecraft:brush" => 200,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -249,6 +253,11 @@ impl Game<'_> {
|
||||
owner.main_arm_left = self.settings.main_hand_left;
|
||||
owner.is_local_player = true;
|
||||
owner.is_view_entity = true;
|
||||
owner.last_death_location = self
|
||||
.level
|
||||
.last_death
|
||||
.clone()
|
||||
.map(|(dimension, pos)| GlobalPos { dimension, pos });
|
||||
if let (Some((slot, ticks)), Some(stack)) = (self.using, stack)
|
||||
&& self.stack_in(slot) == Some(stack)
|
||||
{
|
||||
|
||||
@@ -6,10 +6,15 @@ use super::Game;
|
||||
use horizon_client::{
|
||||
containers::{BlockEntity, Jukebox},
|
||||
items::ItemStack,
|
||||
mobs::Species,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
position::BlockPos,
|
||||
random::RandomSource,
|
||||
};
|
||||
use horizon_world::level::flags as level_flags;
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -97,7 +102,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Level event 1010: the song from the jukebox, and the "Now Playing" overlay.
|
||||
fn start_song(&mut self, pos: [i32; 3], song: &str) {
|
||||
self.stop_song(pos);
|
||||
self.stop_sound(pos);
|
||||
let Some(s) = self.res.items().songs.get(song).cloned() else {
|
||||
return;
|
||||
};
|
||||
@@ -109,12 +114,38 @@ impl Game<'_> {
|
||||
self.titles
|
||||
.set_overlay(Text::translate("record.nowPlaying", &[description]), true);
|
||||
self.update_song_volumes();
|
||||
self.notify_record_playing(pos, true);
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_songs.push((pos, Some(song.to_owned())));
|
||||
}
|
||||
}
|
||||
fn stop_song(&mut self, pos: [i32; 3]) {
|
||||
fn stop_sound(&mut self, pos: [i32; 3]) {
|
||||
if let Some(id) = self.jukebox_sounds.remove(&(pos[0], pos[1], pos[2])) {
|
||||
self.audio.stop_and_release(id);
|
||||
}
|
||||
}
|
||||
/// Level event 1011: the song ends, here and for the guests.
|
||||
fn stop_song(&mut self, pos: [i32; 3]) {
|
||||
self.stop_sound(pos);
|
||||
self.notify_record_playing(pos, false);
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_songs.push((pos, None));
|
||||
}
|
||||
}
|
||||
/// `LevelEventHandler.notifyNearbyEntities` (level events 1010 and 1011):
|
||||
/// parrots within three blocks of the jukebox start or stop dancing.
|
||||
pub(super) fn notify_record_playing(&mut self, pos: [i32; 3], playing: bool) {
|
||||
let min = Vec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
|
||||
let area = Aabb::new(min, min.add_vector(Vec3::new(1.0, 1.0, 1.0)))
|
||||
.inflate(Vec3::new(3.0, 3.0, 3.0));
|
||||
for m in self
|
||||
.mobs
|
||||
.iter_mut()
|
||||
.filter(|m| m.species() == Species::Parrot && m.bounds().intersects(area))
|
||||
{
|
||||
m.extra.party_jukebox = playing.then_some(pos);
|
||||
}
|
||||
}
|
||||
/// `popOutTheItem`: the disc above the jukebox, and the song stops.
|
||||
fn eject_record(&mut self, pos: [i32; 3]) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
|
||||
@@ -457,6 +457,13 @@ fn mob_meta(
|
||||
}
|
||||
defaults.push((19, serializer::BYTE, Value::Byte(0)));
|
||||
}
|
||||
"minecraft:parrot" => {
|
||||
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
|
||||
let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 };
|
||||
if flags != 0 {
|
||||
meta.push((18, serializer::BYTE, Value::Byte(flags)));
|
||||
}
|
||||
}
|
||||
"minecraft:cat" | "minecraft:wolf" => {
|
||||
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
|
||||
let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 };
|
||||
@@ -527,6 +534,14 @@ fn mob_meta(
|
||||
meta.push((19, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
}
|
||||
// HappyGhast.STAYS_STILL (after AgeableMob's two and IS_LEASH_HOLDER),
|
||||
// set while `serverStillTimeout > 0` (`syncStayStillFlag`).
|
||||
"minecraft:happy_ghast" => {
|
||||
if horizon_client::mobs::happy_ghast::on_still_timeout(m) {
|
||||
meta.push((19, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
defaults.push((19, serializer::BOOLEAN, Value::Bool(false)));
|
||||
}
|
||||
// Villager.DATA_VILLAGER_DATA and ZombieVillager's (after Zombie's three).
|
||||
"minecraft:villager" | "minecraft:zombie_villager" => {
|
||||
use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
|
||||
@@ -724,7 +739,7 @@ fn mob_meta(
|
||||
defaults.push((index, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
}
|
||||
// Enderman.DATA_CARRY_STATE.
|
||||
// Enderman.DATA_CARRY_STATE and DATA_CREEPY (angry: the open mouth).
|
||||
"minecraft:enderman" => {
|
||||
if let Some(state) = e.carried {
|
||||
meta.push((
|
||||
@@ -733,6 +748,10 @@ fn mob_meta(
|
||||
Value::Id(state.0 as i32),
|
||||
));
|
||||
}
|
||||
if e.flag {
|
||||
meta.push((17, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -794,8 +813,17 @@ fn mob_equipment(
|
||||
let stack = ItemStack {
|
||||
item: item.clone(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
// A wolf's armor shows its cracks.
|
||||
damage: if slot == 6 && m.species() == horizon_client::mobs::Species::Wolf {
|
||||
e.body_damage.max(0) as u32
|
||||
} else {
|
||||
0
|
||||
},
|
||||
extra: if slot == 6 && m.species() == horizon_client::mobs::Species::Wolf {
|
||||
e.body_extra.clone()
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
out.push((slot, hub.stack(&Some(stack))));
|
||||
}
|
||||
@@ -1078,6 +1106,7 @@ impl Game<'_> {
|
||||
self.world.light_log = None;
|
||||
self.audio.capture = None;
|
||||
self.lan_events.clear();
|
||||
self.lan_songs.clear();
|
||||
self.lan_critical_hits.clear();
|
||||
self.lan_cushion_breaks.clear();
|
||||
self.streaming.extra.clear();
|
||||
@@ -1300,6 +1329,9 @@ impl Game<'_> {
|
||||
&mut e.meta,
|
||||
&mut e.defaults,
|
||||
);
|
||||
// HappyGhast.aiStep: requiresPrecisePosition while on a still timeout.
|
||||
e.precise = m.species() == horizon_client::mobs::Species::HappyGhast
|
||||
&& horizon_client::mobs::happy_ghast::on_still_timeout(m);
|
||||
mob_freeze_meta(m, &mut e.meta, &mut e.defaults);
|
||||
mob_equipment(m, hub, &mut e.equipment);
|
||||
self.mob_attributes(m, &mut e.attributes);
|
||||
@@ -1569,6 +1601,8 @@ impl Game<'_> {
|
||||
// A blast from a guest's attack, and a mace's wind burst.
|
||||
self.flush_lan_explosions();
|
||||
let _ = self.flush_wind_bursts();
|
||||
// A sweep attack's reach to the other players from a guest's attack.
|
||||
self.flush_sweeps();
|
||||
// Particles a guest's turn sent (sweep attack, damage indicator, a hook's splashes).
|
||||
self.flush_lan_particles();
|
||||
}
|
||||
@@ -1671,10 +1705,11 @@ impl Game<'_> {
|
||||
match e {
|
||||
horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => {
|
||||
// The acting guest does not predict the egg's teleport
|
||||
// particles, bone meal's growth, or anvil result sounds
|
||||
// (these levelEvent calls name no excluded player), nor
|
||||
// the digger's own crack and hit sound (2019, 2020).
|
||||
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030 | 2019 | 2020) {
|
||||
// particles, bone meal's growth, anvil result sounds, or a
|
||||
// finished brushing (these levelEvent calls name no
|
||||
// excluded player), nor the digger's own crack and hit
|
||||
// sound (2019, 2020).
|
||||
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030 | 2019 | 2020 | 3008) {
|
||||
None
|
||||
} else {
|
||||
self.lan_acting
|
||||
@@ -1736,6 +1771,7 @@ impl Game<'_> {
|
||||
/// Send the tick's level events, sounds and mob animations.
|
||||
fn lan_flush_effects(&mut self, host: &mut LanHost) {
|
||||
let critical_hits = std::mem::take(&mut self.lan_critical_hits);
|
||||
let kinetic_hits = std::mem::take(&mut self.lan_kinetic_hits);
|
||||
for (state, at) in std::mem::take(&mut self.lan_cushion_breaks) {
|
||||
if let Some(id) = host
|
||||
.hub
|
||||
@@ -1770,6 +1806,16 @@ impl Game<'_> {
|
||||
}
|
||||
host.hub.level_event(kind, pos, data, acting);
|
||||
}
|
||||
// Level events 1010 and 1011: the guests' parrots dance or stop.
|
||||
for (pos, song) in std::mem::take(&mut self.lan_songs) {
|
||||
match song {
|
||||
Some(name) => {
|
||||
let id = host.hub.registry_id("minecraft:jukebox_song", &name);
|
||||
host.hub.level_event(1010, pos, id.unwrap_or(0), None);
|
||||
}
|
||||
None => host.hub.level_event(1011, pos, 0, None),
|
||||
}
|
||||
}
|
||||
for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) {
|
||||
host.hub.block_event(pos, b0, b1, state);
|
||||
}
|
||||
@@ -1814,7 +1860,12 @@ impl Game<'_> {
|
||||
// A projectile is the direct entity of its hit: not tracked here.
|
||||
let melee = matches!(
|
||||
source.kind,
|
||||
K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom
|
||||
K::PlayerAttack
|
||||
| K::MaceSmash
|
||||
| K::Spear
|
||||
| K::MobAttack
|
||||
| K::Sting
|
||||
| K::SonicBoom
|
||||
);
|
||||
let direct = cause.filter(|_| melee);
|
||||
host.hub.damage_event(m.id as i32, kind, cause, direct, at);
|
||||
@@ -1835,6 +1886,19 @@ impl Game<'_> {
|
||||
seen.insert(m.id, (m.hurt_time, dead, swing));
|
||||
}
|
||||
host.mob_state.insert(self.dim, seen);
|
||||
// Level.broadcastEntityEvent(player, 2) of a spear's stab.
|
||||
for attacker in kinetic_hits {
|
||||
let hit = match attacker {
|
||||
None => self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| (host.host_entity, [p.position.x, p.position.y, p.position.z])),
|
||||
Some(conn) => host.hub.guest(conn).map(|g| (g.entity_id, g.position)),
|
||||
};
|
||||
if let Some((id, at)) = hit {
|
||||
host.hub.entity_event(id, 2, at);
|
||||
}
|
||||
}
|
||||
for (attacker, target, magic) in critical_hits {
|
||||
let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| {
|
||||
host.hub.guest(conn).map(|g| g.entity_id)
|
||||
@@ -1899,10 +1963,18 @@ impl Game<'_> {
|
||||
m.head_yaw = g.head_yaw;
|
||||
m.head_pitch = g.pitch;
|
||||
let mut target = m.body_yaw;
|
||||
if dx * dx + dz * dz > 0.002_500_000_2 {
|
||||
target = (dz.atan2(dx) as f32).to_degrees() - 90.0;
|
||||
}
|
||||
let wrap = |a: f32| (a + 180.0).rem_euclid(360.0) - 180.0;
|
||||
if dx * dx + dz * dz > 0.002_500_000_2 {
|
||||
// LivingEntity.tick: walking backwards the body faces away
|
||||
// from the walk direction, not along it.
|
||||
let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0;
|
||||
let facing = (wrap(g.yaw) - walk).abs();
|
||||
target = if 95.0 < facing && facing < 265.0 {
|
||||
walk - 180.0
|
||||
} else {
|
||||
walk
|
||||
};
|
||||
}
|
||||
m.body_yaw += wrap(target - m.body_yaw) * 0.3;
|
||||
let diff = wrap(g.yaw - m.body_yaw);
|
||||
if diff.abs() > 50.0 {
|
||||
@@ -1926,6 +1998,27 @@ impl Game<'_> {
|
||||
m.extra.crouching = g.sneaking;
|
||||
m.extra.avatar_pose = g.pose();
|
||||
m.extra.sprinting = g.sprinting;
|
||||
// Entity.DATA_POSE and the shared and living flags the others
|
||||
// get (hub::guest_body): gliding, swimming, Riptide's spin.
|
||||
let body = lan::hub::guest_body(g);
|
||||
m.extra.fall_flying = body.gliding;
|
||||
m.extra.synced_pose = if body.swimming || body.crawling { 3 } else { 0 };
|
||||
m.extra.auto_spin_attack = body.spin_attack;
|
||||
m.velocity = g
|
||||
.motion
|
||||
.as_ref()
|
||||
.map_or(Vec3::new(dx, dy, dz), |motion| motion.velocity);
|
||||
m.tick_avatar_pose(
|
||||
g.motion
|
||||
.as_ref()
|
||||
.is_some_and(|motion| motion.fluids.was_touching_water),
|
||||
);
|
||||
// CrossbowItem.isCharged: the held crossbow's projectiles.
|
||||
m.extra.charged = g
|
||||
.inventory
|
||||
.get(g.selected)
|
||||
.and_then(|s| s.as_ref())
|
||||
.is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty()));
|
||||
// LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects.
|
||||
let visible = || g.effects.list.iter().filter(|e| e.visible);
|
||||
m.extra.effect_particles = visible()
|
||||
@@ -2000,6 +2093,15 @@ impl Game<'_> {
|
||||
),
|
||||
out,
|
||||
);
|
||||
self.player_elytra_geometry(
|
||||
m,
|
||||
m.extra.chest.as_deref(),
|
||||
camera,
|
||||
alpha as f32,
|
||||
packed,
|
||||
out,
|
||||
);
|
||||
self.spin_attack_geometry(m, camera, alpha as f32, packed, out);
|
||||
self.held_item_geometry(m, camera, alpha, packed, true, out);
|
||||
// LivingEntity.isCurrentlyGlowing: the guest's Glowing effect.
|
||||
let guest = host.hub.guest(*conn);
|
||||
|
||||
@@ -388,6 +388,7 @@ impl Game<'_> {
|
||||
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
|
||||
std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked);
|
||||
std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book);
|
||||
std::mem::swap(&mut self.level.player_extra, &mut g.saved);
|
||||
std::mem::swap(&mut self.stats, &mut play.stats);
|
||||
std::mem::swap(&mut self.hook, &mut play.hook);
|
||||
let adv_loaded = std::mem::replace(&mut self.adv.loaded, true);
|
||||
@@ -643,6 +644,7 @@ impl Game<'_> {
|
||||
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
|
||||
std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked);
|
||||
std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book);
|
||||
std::mem::swap(&mut self.level.player_extra, &mut g.saved);
|
||||
std::mem::swap(&mut self.stats, &mut play.stats);
|
||||
std::mem::swap(&mut self.hook, &mut play.hook);
|
||||
self.adv.loaded = adv_loaded;
|
||||
@@ -971,6 +973,45 @@ impl Game<'_> {
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
|
||||
}
|
||||
|
||||
/// DedicatedServer.isUnderSpawnProtection: no operators, an operator or a
|
||||
/// radius of 0 or less is never under it; else a block within the radius
|
||||
/// of the world spawn (square, in the Overworld) is.
|
||||
fn under_spawn_protection(&self, host: &LanHost, gi: usize, pos: [i32; 3]) -> bool {
|
||||
let g = &host.hub.guests[gi];
|
||||
let radius = host.hub.spawn_protection;
|
||||
if self.options.dedicated.is_none() || radius <= 0 || g.dimension != "minecraft:overworld" {
|
||||
return false;
|
||||
}
|
||||
let Some(spawn) = self.level.world_spawn else {
|
||||
return false;
|
||||
};
|
||||
if host.hub.ops.is_empty() || host.hub.ops.contains_key(&g.uuid) {
|
||||
return false;
|
||||
}
|
||||
let dx = pos[0].abs_diff(spawn[0]);
|
||||
let dz = pos[2].abs_diff(spawn[2]);
|
||||
dx.max(dz) <= radius as u32
|
||||
}
|
||||
|
||||
/// ServerPlayer.sendSpawnProtectionMessage.
|
||||
fn spawn_protection_message(&self, host: &LanHost, conn: u32, pos: [i32; 3]) {
|
||||
let message = horizon_client::text::Text::translate(
|
||||
"build.spawn_protection",
|
||||
&[horizon_client::text::Text::literal(format!(
|
||||
"{}, {}, {}",
|
||||
pos[0], pos[1], pos[2]
|
||||
))],
|
||||
)
|
||||
.with_color(horizon_client::text::RED);
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
content: horizon_client::lan::data::component_nbt(&message.component()),
|
||||
overlay: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// A packet from a guest that the hub does not handle itself.
|
||||
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
@@ -995,6 +1036,12 @@ impl Game<'_> {
|
||||
if spectator {
|
||||
return;
|
||||
}
|
||||
// ServerPlayerGameMode.handleBlockBreakAction: no dig starts
|
||||
// under spawn protection (the ack puts the block back).
|
||||
if self.under_spawn_protection(host, gi, a.pos) {
|
||||
self.spawn_protection_message(host, conn, a.pos);
|
||||
return;
|
||||
}
|
||||
let face = direction(i32::from(a.direction));
|
||||
let play = host.play.entry(conn).or_default();
|
||||
play.digging = Some((a.pos, face));
|
||||
@@ -1122,19 +1169,25 @@ impl Game<'_> {
|
||||
],
|
||||
};
|
||||
let hand = if p.hand == 1 { Hand::Off } else { Hand::Main };
|
||||
let logged = self.world.block_log.as_ref().map_or(0, Vec::len);
|
||||
let heard = self.audio.capture.as_ref().map_or(0, Vec::len);
|
||||
let swung = self.as_guest(host, conn, |g| {
|
||||
g.forced_hit = Some(hit);
|
||||
g.guest_use = Some(GuestUse::OnBlock(hand));
|
||||
let swings = g.swings_started;
|
||||
let _ = g.use_item();
|
||||
g.forced_hit = None;
|
||||
g.guest_use = None;
|
||||
g.swings_started != swings
|
||||
});
|
||||
self.lan_swing_back(host, conn, swung);
|
||||
self.guest_use_sounds(host, conn, logged, heard);
|
||||
// handleUseItemOn: under spawn protection nothing is used or
|
||||
// placed; the player is told and the blocks below go back.
|
||||
if self.under_spawn_protection(host, gi, p.pos) {
|
||||
self.spawn_protection_message(host, conn, p.pos);
|
||||
} else {
|
||||
let logged = self.world.block_log.as_ref().map_or(0, Vec::len);
|
||||
let heard = self.audio.capture.as_ref().map_or(0, Vec::len);
|
||||
let swung = self.as_guest(host, conn, |g| {
|
||||
g.forced_hit = Some(hit);
|
||||
g.guest_use = Some(GuestUse::OnBlock(hand));
|
||||
let swings = g.swings_started;
|
||||
let _ = g.use_item();
|
||||
g.forced_hit = None;
|
||||
g.guest_use = None;
|
||||
g.swings_started != swings
|
||||
});
|
||||
self.lan_swing_back(host, conn, swung);
|
||||
self.guest_use_sounds(host, conn, logged, heard);
|
||||
}
|
||||
// The client predicted a result: correct it with what really is.
|
||||
for pos in [
|
||||
p.pos,
|
||||
@@ -1663,9 +1716,21 @@ impl Game<'_> {
|
||||
if self.look_at_entity(host, gi, id, None).is_none() {
|
||||
return;
|
||||
}
|
||||
self.as_guest(host, conn, |g| {
|
||||
g.attack();
|
||||
});
|
||||
// A mace's smash sets the attacker's velocity and sends it at once, before the
|
||||
// Wind Burst's push (MaceItem.hurtEnemy, then the post-attack effects).
|
||||
let sent = self
|
||||
.as_guest(host, conn, |g| {
|
||||
let marked = g
|
||||
.player
|
||||
.as_mut()
|
||||
.is_some_and(|p| std::mem::take(&mut p.health.sync_velocity));
|
||||
g.attack();
|
||||
let p = g.player.as_mut()?;
|
||||
let sent = std::mem::replace(&mut p.health.sync_velocity, marked);
|
||||
sent.then_some(p.velocity)
|
||||
})
|
||||
.flatten();
|
||||
self.send_guest_motion(host, conn, sent);
|
||||
// The mob now answers to this guest (game/lan_mobs.rs).
|
||||
if let Ok(id) = u32::try_from(id) {
|
||||
host.mob_players.insert(id, conn);
|
||||
@@ -1968,6 +2033,10 @@ impl Game<'_> {
|
||||
}
|
||||
if let Some(config) = elsewhere {
|
||||
self.respawn_trip(conn, config);
|
||||
} else if in_frame_bed.is_none() && host.hub.guests[i].spawn.is_none() {
|
||||
// TeleportTransition.createDefault: no point of its own, so the
|
||||
// world spawn's free column once its chunks have loaded.
|
||||
self.world_spawn_trip(conn);
|
||||
}
|
||||
if let Some(c) = in_frame_bed
|
||||
&& self.dim == super::Dim::Overworld
|
||||
@@ -1986,6 +2055,10 @@ impl Game<'_> {
|
||||
host.hub.guests[i].yaw = yaw;
|
||||
[at.x, at.y, at.z]
|
||||
});
|
||||
if found.is_none() {
|
||||
// TeleportTransition.missingRespawnBlock.
|
||||
self.world_spawn_trip(conn);
|
||||
}
|
||||
host.hub.teleport(i, Some(at));
|
||||
}
|
||||
if away && let Err(e) = self.enter_level(Some(host), back) {
|
||||
@@ -2031,7 +2104,13 @@ impl Game<'_> {
|
||||
let using = play.using.is_some();
|
||||
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
||||
if digging.is_some() || using || delayed {
|
||||
// ServerPlayer.getKnownMovement: the move their client just sent.
|
||||
let movement = host.hub.guests[gi]
|
||||
.moves
|
||||
.last()
|
||||
.map_or(Vec3::ZERO, |m| Vec3::new(m.0[0], m.0[1], m.0[2]));
|
||||
self.as_guest(host, conn, |g| {
|
||||
g.known_movement = movement;
|
||||
g.attack_ticks = g.attack_ticks.saturating_add(1);
|
||||
if let Some((pos, face)) = digging {
|
||||
g.forced_hit = Some(Hit {
|
||||
@@ -2130,7 +2209,7 @@ impl Game<'_> {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if g.health <= 0.0 && !g.dead {
|
||||
g.dead = true;
|
||||
g.last_death = Some(g.position.map(|v| v.floor() as i32));
|
||||
g.last_death = Some((g.dimension.clone(), g.position.map(|v| v.floor() as i32)));
|
||||
let (id, at) = (g.entity_id, g.position);
|
||||
let reward = Experience {
|
||||
level: g.xp_level,
|
||||
@@ -2211,11 +2290,10 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the
|
||||
/// host's player and the guests: of the players not in spectator mode,
|
||||
/// players_sleeping_percentage of them (at least one) are in bed, and as
|
||||
/// many have slept 100 ticks.
|
||||
pub(super) fn enough_slept(&self) -> bool {
|
||||
/// `SleepStatus.update`'s counts over the host's player and the guests:
|
||||
/// the players not in spectator mode, how many are in bed, and how many
|
||||
/// of those have slept 100 ticks.
|
||||
fn sleep_counts(&self) -> (i64, i64, i64) {
|
||||
let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64);
|
||||
let mut count = |in_bed: bool, timer: u32| {
|
||||
active += 1;
|
||||
@@ -2239,11 +2317,64 @@ impl Game<'_> {
|
||||
count(g.bed.is_some(), g.sleep_timer);
|
||||
}
|
||||
}
|
||||
(active, sleeping, deep)
|
||||
}
|
||||
|
||||
/// `SleepStatus.sleepersNeeded`.
|
||||
fn sleepers_needed(&self, active: i64) -> i64 {
|
||||
let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0));
|
||||
let needed = ((active * percent + 99) / 100).max(1);
|
||||
((active * percent + 99) / 100).max(1)
|
||||
}
|
||||
|
||||
/// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the
|
||||
/// host's player and the guests: of the players not in spectator mode,
|
||||
/// players_sleeping_percentage of them (at least one) are in bed, and as
|
||||
/// many have slept 100 ticks.
|
||||
pub(super) fn enough_slept(&self) -> bool {
|
||||
let (active, sleeping, deep) = self.sleep_counts();
|
||||
let needed = self.sleepers_needed(active);
|
||||
sleeping >= needed && deep >= needed
|
||||
}
|
||||
|
||||
/// `ServerLevel.updateSleepingPlayerList` and `announceSleepStatus`: when
|
||||
/// the players or the sleepers change, a published or dedicated world
|
||||
/// shows everyone "n/m players sleeping", or "Sleeping through this
|
||||
/// night" once enough are in bed, on the action bar.
|
||||
pub(super) fn announce_sleep_status(&mut self) {
|
||||
let (active, sleeping, _) = self.sleep_counts();
|
||||
let (old_active, old_sleeping) = self.sleep_seen;
|
||||
self.sleep_seen = (active, sleeping);
|
||||
let changed = (old_sleeping > 0 || sleeping > 0)
|
||||
&& (old_active != active || old_sleeping != sleeping);
|
||||
let published = self.lan.is_some() || self.options.dedicated.is_some();
|
||||
if !changed || !published {
|
||||
return;
|
||||
}
|
||||
// ServerLevel.canSleepThroughNights.
|
||||
if self.ui.rules.int("players_sleeping_percentage") > 100 {
|
||||
return;
|
||||
}
|
||||
let needed = self.sleepers_needed(active);
|
||||
let text = if sleeping >= needed {
|
||||
horizon_client::text::Text::translate("sleep.skipping_night", &[])
|
||||
} else {
|
||||
horizon_client::text::Text::translate(
|
||||
"sleep.players_sleeping",
|
||||
&[
|
||||
horizon_client::text::Text::literal(sleeping.to_string()),
|
||||
horizon_client::text::Text::literal(needed.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
if let Some(host) = self.lan.as_ref() {
|
||||
host.hub
|
||||
.overlay_message(horizon_client::lan::data::component_nbt(&text.component()));
|
||||
}
|
||||
if self.options.dedicated.is_none() {
|
||||
self.titles.set_overlay(text, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerLevel.wakeUpAllPlayers` for the guests.
|
||||
pub(super) fn wake_guests(&mut self) {
|
||||
if let Some(host) = self.lan.as_mut() {
|
||||
@@ -2299,16 +2430,19 @@ impl Game<'_> {
|
||||
if !g.effects.list.is_empty() {
|
||||
self.as_guest(host, conn, |game| game.tick_mob_effects());
|
||||
}
|
||||
self.as_guest(host, conn, |game| game.handle_shoulder_entities());
|
||||
return;
|
||||
}
|
||||
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
|
||||
let at = g.position;
|
||||
let (sneaking, sleeping) = (g.sneaking, g.sleeping);
|
||||
let riding = g.vehicle.is_some();
|
||||
let mut soul = None;
|
||||
let events = self.as_guest(host, conn, |game| {
|
||||
let (rules, motion) = (game.world.health_rules, game.motion);
|
||||
let health = &motion.health;
|
||||
let freeze_immune = game.wears_freeze_immune();
|
||||
let burn_immune = game.wears_burn_from_stepping_immunity();
|
||||
let Some(player) = game.player.as_mut() else {
|
||||
return (Vec::new(), None);
|
||||
};
|
||||
@@ -2323,6 +2457,12 @@ impl Game<'_> {
|
||||
w.player.health.advance_clock();
|
||||
let _ = w.fluid_base_tick();
|
||||
w.player.ground.on_ground = from_ground;
|
||||
// Player.aiStep: a flying player that isn't riding starts every tick
|
||||
// with no fall distance, so flying down in creative and switching to
|
||||
// survival lands without the flight's distance.
|
||||
if w.player.flying && !riding {
|
||||
w.player.fall_distance = 0.0;
|
||||
}
|
||||
let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect();
|
||||
// Entity.move's movementThisTick: each move, from where the
|
||||
// tick's first one started.
|
||||
@@ -2374,6 +2514,7 @@ impl Game<'_> {
|
||||
w.player.shift_key_down = sneaking;
|
||||
let _ = w.player.set_sleeping(sleeping);
|
||||
w.player.freeze_immune = freeze_immune;
|
||||
w.player.burn_from_stepping_immune = burn_immune;
|
||||
let _ = w.server_block_damage(start);
|
||||
let _ = w.update_soul_speed_block();
|
||||
let _ = w.tick_environment_damage();
|
||||
@@ -2402,12 +2543,16 @@ impl Game<'_> {
|
||||
for d in travelled {
|
||||
game.movement_stats(Vec3::new(d[0], d[1], d[2]));
|
||||
}
|
||||
// LivingEntity.baseTick: a new block position runs the worn
|
||||
// enchantments' location_changed effects (frost walker).
|
||||
game.location_changed_effects([start.x, start.y, start.z], from_ground);
|
||||
// LivingEntity.baseTick: outside the world border, then tickEffects.
|
||||
game.border_damage();
|
||||
game.tick_mob_effects();
|
||||
// Soul Speed's effects (LivingEntity.baseTick's location_changed
|
||||
// and tick effects); its particle goes to the players around.
|
||||
soul = game.tick_soul_speed();
|
||||
game.handle_shoulder_entities();
|
||||
let Some(player) = game.player.as_mut() else {
|
||||
return (Vec::new(), None);
|
||||
};
|
||||
@@ -2446,7 +2591,10 @@ impl Game<'_> {
|
||||
if let Some((at, velocity)) = soul {
|
||||
super::lan_particles::send_soul_particle(host, at, velocity);
|
||||
}
|
||||
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
|
||||
self.as_guest(host, conn, |game| {
|
||||
game.sculk_step_on_player();
|
||||
game.tick_player_sculk_events();
|
||||
});
|
||||
for event in events {
|
||||
match event {
|
||||
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at),
|
||||
@@ -2750,9 +2898,15 @@ impl Game<'_> {
|
||||
|
||||
/// Dropped items touching a guest go into their inventory.
|
||||
fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) {
|
||||
let (conn, mode, position, id) = {
|
||||
let (conn, mode, position, id, uuid) = {
|
||||
let g = &host.hub.guests[gi];
|
||||
(g.conn, g.game_mode, g.position, g.entity_id)
|
||||
(
|
||||
g.conn,
|
||||
g.game_mode,
|
||||
g.position,
|
||||
g.entity_id,
|
||||
horizon_client::lan::playerdata::uuid_ints(g.uuid),
|
||||
)
|
||||
};
|
||||
if mode == SPECTATOR || self.dropped.is_empty() {
|
||||
return;
|
||||
@@ -2763,6 +2917,7 @@ impl Game<'_> {
|
||||
.enumerate()
|
||||
.filter(|(_, d)| {
|
||||
d.pickup_delay == 0
|
||||
&& d.target.is_none_or(|t| t == uuid)
|
||||
&& (d.position.x - position[0]).abs() < 1.5
|
||||
&& (d.position.z - position[2]).abs() < 1.5
|
||||
&& d.position.y > position[1] - 0.6
|
||||
|
||||
@@ -24,6 +24,37 @@ fn slot_in_group(group: &str, slot: &str) -> bool {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `getAttributeValue(KNOCKBACK_RESISTANCE)` of a mob: its own value plus
|
||||
/// the modifiers of the items it wears or holds in matching slots.
|
||||
pub(super) fn mob_knockback_resistance(&self, m: &Mob) -> f64 {
|
||||
let e = &m.extra;
|
||||
let slots = [
|
||||
("mainhand", &e.main_hand),
|
||||
("offhand", &e.off_hand),
|
||||
("feet", &e.feet),
|
||||
("legs", &e.legs),
|
||||
("chest", &e.chest),
|
||||
("head", &e.head),
|
||||
];
|
||||
let mut extra = Vec::new();
|
||||
for (slot, item) in slots {
|
||||
let Some(info) = item.as_ref().and_then(|i| self.res.items().get(i)) else {
|
||||
continue;
|
||||
};
|
||||
for (attribute, _, amount, op, group) in &info.modifiers {
|
||||
if attribute == "minecraft:knockback_resistance" && slot_in_group(group, slot) {
|
||||
let op = match operation_named(op) {
|
||||
1 => Op::AddMultipliedBase,
|
||||
2 => Op::AddMultipliedTotal,
|
||||
_ => Op::AddValue,
|
||||
};
|
||||
extra.push((*amount, op));
|
||||
}
|
||||
}
|
||||
}
|
||||
finalize::value_with(m, Attr::KnockbackResistance, &extra)
|
||||
}
|
||||
|
||||
/// The registry id of a client-syncable attribute the entity type has
|
||||
/// (`AttributeMap.getInstance` is null for the others), by name.
|
||||
fn synced_attribute(&self, entity: &str, name: &str) -> Option<i32> {
|
||||
|
||||
@@ -425,6 +425,9 @@ impl Game<'_> {
|
||||
let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false);
|
||||
e.pitch = t.pitch;
|
||||
e.velocity = at(t.velocity);
|
||||
// Projectile.getAddEntityPacket: the owner's id; a trident here is
|
||||
// always the host player's.
|
||||
e.data = owner(Some(horizon_client::mobs::Who::Player));
|
||||
e.meta = arrow_meta(false, t.no_physics, 0, t.in_ground);
|
||||
// ThrownTrident.ID_LOYALTY and ID_FOIL.
|
||||
if t.loyalty != 0 {
|
||||
|
||||
@@ -83,6 +83,10 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool {
|
||||
MobEvent::AttackPlayer(..)
|
||||
| MobEvent::AttackPlayerWithEffect { .. }
|
||||
| MobEvent::DamagePlayer { .. }
|
||||
| MobEvent::SonicBoom {
|
||||
target: Who::Player,
|
||||
..
|
||||
}
|
||||
| MobEvent::Push {
|
||||
target: Who::Player,
|
||||
..
|
||||
@@ -101,6 +105,7 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool {
|
||||
}
|
||||
| MobEvent::EffectPlayer { .. }
|
||||
| MobEvent::AxolotlSupportPlayer
|
||||
| MobEvent::ParrotToShoulder { .. }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,40 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerLevel.sendParticles` of a mob's particles: a packet to each
|
||||
/// player within 32 blocks. The window draws its own copy.
|
||||
pub(super) fn lan_level_particles(
|
||||
&self,
|
||||
options: &ParticleOptions,
|
||||
at: [f64; 3],
|
||||
spread: [f64; 3],
|
||||
speed: f64,
|
||||
count: u32,
|
||||
) {
|
||||
let (Some(host), Some(particle)) = (&self.lan, self.network_particle(options, None)) else {
|
||||
return;
|
||||
};
|
||||
let packet = C::LevelParticles(play::LevelParticles {
|
||||
particle,
|
||||
override_limiter: false,
|
||||
always_show: false,
|
||||
pos: at,
|
||||
dist: spread.map(|d| d as f32),
|
||||
max_speed: [speed as f32; 3],
|
||||
count: count as i32,
|
||||
randomization: 0,
|
||||
});
|
||||
for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
|
||||
// ServerLevel compares the player's block centre, strictly within 32.
|
||||
let distance: f64 = (0..3)
|
||||
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
|
||||
.sum();
|
||||
if distance < 32.0 * 32.0 {
|
||||
g.send(&packet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the
|
||||
/// landing block's crumbs: drawn in this window, when it has one, and
|
||||
/// sent to each player within 32 blocks. `host` is the hub of a guest's
|
||||
|
||||
@@ -12,6 +12,7 @@ use horizon_client::{
|
||||
mobs::Who,
|
||||
projectiles::{Hit, Projectile, ProjectileKind},
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
|
||||
/// The player projectiles that meet other players: arrows (their hurt), and
|
||||
/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0
|
||||
@@ -24,7 +25,7 @@ pub(super) fn meets_players(kind: &ProjectileKind) -> bool {
|
||||
}
|
||||
|
||||
/// Who a player's attack lands on.
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Victim {
|
||||
Host,
|
||||
Guest(u32),
|
||||
@@ -49,6 +50,26 @@ pub(super) struct Strike {
|
||||
knockback_attack: bool,
|
||||
/// The attacker's team, for the victim's `Player.canHarmPlayer`.
|
||||
team: Option<horizon_client::scoreboard::Team>,
|
||||
/// The sweep's damage to the players around the victim.
|
||||
sweep_hit: Option<Sweep>,
|
||||
}
|
||||
|
||||
/// A sweep attack's reach to the other players (`Player.doSweepAttack`),
|
||||
/// worked out as the attacker.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Sweep {
|
||||
/// The attacking guest (none: the host).
|
||||
attacker: Option<u32>,
|
||||
from: [f64; 3],
|
||||
/// The damage after the enchantments and the attack strength.
|
||||
damage: f32,
|
||||
/// The push along the attacker's yaw.
|
||||
knockback: (f64, f64),
|
||||
team: Option<horizon_client::scoreboard::Team>,
|
||||
/// The target's box grown by (1, 0.25, 1).
|
||||
pub(super) hit_box: Aabb,
|
||||
/// The player the sweep started from, which it spares.
|
||||
skip: Option<Victim>,
|
||||
}
|
||||
|
||||
impl Strike {
|
||||
@@ -127,6 +148,10 @@ impl Game<'_> {
|
||||
let from = [p.position.x, p.position.y, p.position.z];
|
||||
let (amount, scale, crit, magic) = self.melee_damage("minecraft:player");
|
||||
let sweep = self.sweep_attack_position(scale, crit);
|
||||
let sweep_hit = sweep.map(|_| {
|
||||
let base = self.sweep_base_damage(scale);
|
||||
self.player_sweep(base, scale)
|
||||
});
|
||||
let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale);
|
||||
let (xd, zd) = self.extra_knockback_direction();
|
||||
self.attack_ticks = 0;
|
||||
@@ -151,6 +176,7 @@ impl Game<'_> {
|
||||
knockback: (strength, xd, zd),
|
||||
knockback_attack,
|
||||
team: self.player_team().cloned(),
|
||||
sweep_hit,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -344,9 +370,118 @@ impl Game<'_> {
|
||||
};
|
||||
if let Some(at) = s.sweep.filter(|_| hurt) {
|
||||
self.sweep_attack(at, Some(s.from));
|
||||
// The other players next to the victim (Player.doSweepAttack).
|
||||
let bounds = match victim {
|
||||
Victim::Host => self.player.as_ref().map(|p| p.bounds()),
|
||||
Victim::Guest(conn) => host.hub.guest(conn).map(guest_bounds),
|
||||
};
|
||||
if let (Some(sweep), Some(bounds)) = (&s.sweep_hit, bounds) {
|
||||
self.sweep_players(
|
||||
host,
|
||||
&Sweep {
|
||||
hit_box: bounds.inflate(Vec3::new(1.0, 0.25, 1.0)),
|
||||
skip: Some(victim),
|
||||
..sweep.clone()
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
self.audio.play(sound, Some(s.from), 1.0, 1.0);
|
||||
}
|
||||
hurt
|
||||
}
|
||||
|
||||
/// The sweep of the player in place, for the players it reaches: the
|
||||
/// damage (`1 + ratio * baseDamage`, plus the enchantments against a
|
||||
/// player, scaled by the attack strength) and who hits. The box is set
|
||||
/// by the caller.
|
||||
pub(super) fn player_sweep(&mut self, base: f32, scale: f32) -> Sweep {
|
||||
let from = self
|
||||
.player
|
||||
.as_ref()
|
||||
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]);
|
||||
let damage = (base + self.enchant_damage_bonus("minecraft:player")) * scale;
|
||||
Sweep {
|
||||
attacker: self.lan_acting,
|
||||
from,
|
||||
damage,
|
||||
knockback: self.extra_knockback_direction(),
|
||||
team: self.player_team().cloned(),
|
||||
hit_box: Aabb::new(Vec3::ZERO, Vec3::ZERO),
|
||||
skip: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A sweep from a mob hit reaches the other players. Inside a guest's
|
||||
/// turn the host holds the other players (`as_guest`), so it waits for
|
||||
/// the turn to end.
|
||||
pub(super) fn sweep_other_players(&mut self, sweep: Sweep) {
|
||||
if self.lan_acting.is_some() {
|
||||
self.creatures.sweeps.push(sweep);
|
||||
} else if let Some(mut host) = self.lan.take() {
|
||||
self.sweep_players(&mut host, &sweep);
|
||||
self.lan = Some(host);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sweeps guests' turns put off.
|
||||
pub(super) fn flush_sweeps(&mut self) {
|
||||
for sweep in std::mem::take(&mut self.creatures.sweeps) {
|
||||
self.sweep_other_players(sweep);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Player.doSweepAttack` on the players: each other player in the box,
|
||||
/// closer than 3 blocks (`distanceToSqr < 9`) and not an ally
|
||||
/// (`isAlliedTo`), is hurt (`ServerPlayer.canHarmPlayer`: the `pvp` rule)
|
||||
/// and pushed 0.4 along the attacker's yaw.
|
||||
pub(super) fn sweep_players(&mut self, host: &mut LanHost, sweep: &Sweep) {
|
||||
let from = Vec3::new(sweep.from[0], sweep.from[1], sweep.from[2]);
|
||||
let mut victims = Vec::new();
|
||||
if sweep.attacker.is_some()
|
||||
&& self.options.dedicated.is_none()
|
||||
&& !self.spectator()
|
||||
&& let Some(p) = self.player.as_ref()
|
||||
&& !p.health.dead_or_dying()
|
||||
&& p.bounds().intersects(sweep.hit_box)
|
||||
&& p.position.distance_squared(from) < 9.0
|
||||
{
|
||||
victims.push((Victim::Host, self.player_team().cloned()));
|
||||
}
|
||||
for g in &host.hub.guests {
|
||||
if host.hub.here(g)
|
||||
&& g.loaded
|
||||
&& !g.dead
|
||||
&& !g.spectator()
|
||||
&& sweep.attacker != Some(g.conn)
|
||||
&& guest_bounds(g).intersects(sweep.hit_box)
|
||||
&& Vec3::new(g.position[0], g.position[1], g.position[2]).distance_squared(from)
|
||||
< 9.0
|
||||
{
|
||||
let team = self.score.board.players_team(&g.name).cloned();
|
||||
victims.push((Victim::Guest(g.conn), team));
|
||||
}
|
||||
}
|
||||
let (xd, zd) = sweep.knockback;
|
||||
let land = |g: &mut Self| {
|
||||
let hurt = g.mob_hits_player(sweep.damage, sweep.from, "minecraft:player_attack");
|
||||
if hurt {
|
||||
g.knock_back_player(0.4, xd, zd);
|
||||
}
|
||||
};
|
||||
for (victim, team) in victims {
|
||||
if sweep.skip == Some(victim)
|
||||
|| horizon_client::scoreboard::teams_allied(team.as_ref(), sweep.team.as_ref())
|
||||
|| !self.ui.rules.bool("pvp")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match victim {
|
||||
Victim::Host => land(self),
|
||||
Victim::Guest(conn) => {
|
||||
self.guest_struck_by(host, conn, land);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,8 +46,12 @@ impl Game<'_> {
|
||||
if !self.with_level(|b, level, _| b.is_raining_at(level, p)) {
|
||||
continue;
|
||||
}
|
||||
// Skeleton trap: effective difficulty / 100 (regional difficulty approximated).
|
||||
let difficulty = f64::from(self.ui.difficulty) * 0.75;
|
||||
// Skeleton trap: the local effective difficulty / 100
|
||||
// (`getCurrentDifficultyAt(pos)`).
|
||||
let difficulty = f64::from(
|
||||
self.local_difficulty([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])])
|
||||
.effective,
|
||||
);
|
||||
let below = &self
|
||||
.res
|
||||
.facts()
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
enchant::EffectContext,
|
||||
items::ItemStack,
|
||||
mobs::{Damage, Mob, Species},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
@@ -135,7 +136,7 @@ impl Game<'_> {
|
||||
/// `LivingEntity.hurtServer` of the mob at `index` by the player's hit:
|
||||
/// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor.
|
||||
pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool {
|
||||
let held = self.inventory[self.selected].clone();
|
||||
let held = self.held().cloned();
|
||||
let kind = self.mobs[index].kind.id.clone();
|
||||
let ctx = EffectContext {
|
||||
this: Some(&kind),
|
||||
@@ -144,6 +145,7 @@ impl Game<'_> {
|
||||
is_direct: true,
|
||||
damage_type: Some(match source.kind {
|
||||
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
|
||||
horizon_client::mobs::DamageKind::Spear => "minecraft:spear",
|
||||
_ => "minecraft:player_attack",
|
||||
}),
|
||||
items: Some(self.res.items()),
|
||||
@@ -173,7 +175,7 @@ impl Game<'_> {
|
||||
/// the post-attack enchantments, then `postHurtEnemy` with the weapon's
|
||||
/// wear.
|
||||
pub(super) fn weapon_hit(&mut self, index: usize) {
|
||||
let Some(stack) = self.inventory[self.selected].clone() else {
|
||||
let Some(stack) = self.held().cloned() else {
|
||||
return;
|
||||
};
|
||||
let weapon = self
|
||||
@@ -193,16 +195,26 @@ impl Game<'_> {
|
||||
if smash && let Some(p) = self.player.as_mut() {
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
// ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack).
|
||||
self.weapon_wear(&stack);
|
||||
}
|
||||
/// `ItemStack.postHurtEnemy`: `hurtAndBreak(weapon.itemDamagePerAttack)` of
|
||||
/// the weapon in the acting hand.
|
||||
pub(super) fn weapon_wear(&mut self, stack: &ItemStack) {
|
||||
let weapon = self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
|
||||
if let Some((per_attack, max)) = weapon
|
||||
&& max > 0
|
||||
&& !self.creative
|
||||
{
|
||||
let loss = self.durability_loss(&stack, per_attack);
|
||||
if let Some(held) = self.inventory[self.selected].as_mut() {
|
||||
let loss = self.durability_loss(stack, per_attack);
|
||||
let cell = self.held_mut();
|
||||
if let Some(held) = cell.as_mut() {
|
||||
held.damage += loss;
|
||||
if held.damage >= max {
|
||||
self.inventory[self.selected] = None;
|
||||
*cell = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,6 +228,9 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
p.velocity = Vec3::new(p.velocity.x, f64::from(0.01f32), p.velocity.z);
|
||||
// A server player's client is told (ClientboundSetEntityMotionPacket): it moves by
|
||||
// itself, so without it a Wind Burst's push would add to the speed of the fall.
|
||||
p.health.sync_velocity = true;
|
||||
// calculateImpactPosition: an earlier impact below the player stays.
|
||||
let impact = match p.impulse.impact_position {
|
||||
Some(at) if at.y <= p.position.y => at,
|
||||
|
||||
@@ -1189,6 +1189,7 @@ mod item_column_tests {
|
||||
id,
|
||||
stack: ItemStack::new("minecraft:stone", 1),
|
||||
thrower: None,
|
||||
target: None,
|
||||
position: at,
|
||||
previous: at,
|
||||
velocity: Vec3::ZERO,
|
||||
|
||||
@@ -5,11 +5,15 @@ use super::Game;
|
||||
use horizon_client::{
|
||||
mobs::{
|
||||
Species,
|
||||
drops::{self, SLOTS},
|
||||
finalize::equip_stack,
|
||||
gear::{self, ARMOR, MAIN},
|
||||
spawner::equipment_table,
|
||||
},
|
||||
raid::{self, RaiderType},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::{loot::EntityLootParams, nbt::Tag};
|
||||
|
||||
/// `EnchantmentsByCostWithDifficulty` of `mob_spawn_equipment`.
|
||||
const MIN_COST: i32 = 5;
|
||||
@@ -47,6 +51,58 @@ fn slot_item(m: &horizon_client::mobs::Mob, slot: usize) -> Option<std::sync::Ar
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Mob.equip(EquipmentTable)` for a spawner's `equipment`: the loot table
|
||||
/// (the mob as `this`, its random sequence) is rolled and each stack goes
|
||||
/// in the slot `EquipmentUser.resolveSlot` picks, with the table's drop
|
||||
/// chance for that slot.
|
||||
pub(super) fn equip_from_table(&mut self, id: u32, table: &Tag) {
|
||||
let Some((name, chances)) = equipment_table(table) else {
|
||||
return;
|
||||
};
|
||||
let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
|
||||
return;
|
||||
};
|
||||
if !loot.has_table(&name) {
|
||||
return;
|
||||
}
|
||||
let params = EntityLootParams {
|
||||
this: drops::loot_entity(m, None),
|
||||
..EntityLootParams::default()
|
||||
};
|
||||
let seed = self.level.seed;
|
||||
let stacks = match loot.random_sequence(&name) {
|
||||
Some(sequence) => {
|
||||
let random = self.rand_sequences.get(sequence, seed);
|
||||
loot.roll_entity(&name, random, ¶ms)
|
||||
}
|
||||
None => loot.roll_entity(&name, &mut self.world.random, ¶ms),
|
||||
};
|
||||
let mut inserted: Vec<usize> = Vec::new();
|
||||
for stack in stacks.iter().filter(|s| !s.is_empty()) {
|
||||
// `resolveSlot`: an `equippable` item goes in its own slot, any
|
||||
// other in the main hand, each slot once.
|
||||
let slot = match self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.and_then(|i| i.equip_slot.as_deref())
|
||||
{
|
||||
Some(name) => SLOTS.iter().position(|s| *s == name),
|
||||
None => Some(0),
|
||||
};
|
||||
let Some(slot) = slot.filter(|s| !inserted.contains(s)) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
equip_stack(m, slot, stack, chances[slot]);
|
||||
}
|
||||
inserted.push(slot);
|
||||
}
|
||||
}
|
||||
/// `Mob.populateDefaultEquipmentEnchantments`: the weapon one time in
|
||||
/// four and each piece of armour one time in two, scaled by the local
|
||||
/// difficulty, enchanted as if at an enchanting table of cost 5 to 22.
|
||||
|
||||
@@ -297,7 +297,8 @@ impl Game<'_> {
|
||||
let p = plan.approximate;
|
||||
let centre = Vec3::new(f64::from(p.x) + 0.5, f64::from(p.y), f64::from(p.z) + 0.5);
|
||||
if plan.dim == Dim::End {
|
||||
if let Err(e) = self.end_arrival(centre) {
|
||||
// In the End the arrival only builds the platform: no spawn search.
|
||||
if let Err(e) = self.end_arrival(centre, &mut None) {
|
||||
log::error!("End platform: {e}");
|
||||
}
|
||||
return centre;
|
||||
|
||||
@@ -279,11 +279,13 @@ impl Game<'_> {
|
||||
/// horse is a trap for fifteen minutes; a player within ten blocks springs
|
||||
/// it.
|
||||
pub(super) fn tick_skeleton_traps(&mut self) {
|
||||
let player = self
|
||||
.player
|
||||
.as_ref()
|
||||
.filter(|p| !p.health.dead_or_dying())
|
||||
.map(|p| p.position);
|
||||
// `Level.hasNearbyAlivePlayer`: alive, not a spectator, in the level.
|
||||
let players: Vec<_> = self
|
||||
.level_players()
|
||||
.into_iter()
|
||||
.filter(|p| p.alive && !p.spectator)
|
||||
.map(|p| p.position)
|
||||
.collect();
|
||||
let mut sprung = Vec::new();
|
||||
for m in &mut self.mobs {
|
||||
if m.species() != Species::SkeletonHorse || !m.extra.trap || !m.alive() {
|
||||
@@ -296,7 +298,10 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if player.is_some_and(|p| m.distance_sqr(p) < TRAP_RANGE * TRAP_RANGE) {
|
||||
if players
|
||||
.iter()
|
||||
.any(|&p| m.distance_sqr(p) < TRAP_RANGE * TRAP_RANGE)
|
||||
{
|
||||
sprung.push(m.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,7 +381,15 @@ impl Game<'_> {
|
||||
m.head_pitch = pitch;
|
||||
let mut target = m.body_yaw;
|
||||
if dx * dx + dz * dz > 0.002_500_000_2 {
|
||||
target = (dz.atan2(dx) as f32).to_degrees() - 90.0;
|
||||
// LivingEntity.tick: walking backwards the body faces away from
|
||||
// the walk direction, not along it.
|
||||
let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0;
|
||||
let facing = (wrap(yaw) - walk).abs();
|
||||
target = if 95.0 < facing && facing < 265.0 {
|
||||
walk - 180.0
|
||||
} else {
|
||||
walk
|
||||
};
|
||||
}
|
||||
if swinging {
|
||||
target = yaw;
|
||||
@@ -463,7 +471,14 @@ impl Game<'_> {
|
||||
&self.player_armor_layers(),
|
||||
out,
|
||||
);
|
||||
self.player_elytra_geometry(m, camera, alpha as f32, packed, out);
|
||||
self.player_elytra_geometry(
|
||||
m,
|
||||
self.armor[1].as_ref().map(|s| &*s.item),
|
||||
camera,
|
||||
alpha as f32,
|
||||
packed,
|
||||
out,
|
||||
);
|
||||
self.spin_attack_geometry(m, camera, alpha as f32, packed, out);
|
||||
self.held_item_geometry(m, camera, alpha, packed, true, out);
|
||||
// LivingEntity.isCurrentlyGlowing: the Glowing effect. A server's client is
|
||||
@@ -528,7 +543,14 @@ impl Game<'_> {
|
||||
&self.player_armor_layers(),
|
||||
&mut verts,
|
||||
);
|
||||
self.player_elytra_geometry(&m, camera, 1.0, 240 | 240 << 8, &mut verts);
|
||||
self.player_elytra_geometry(
|
||||
&m,
|
||||
self.armor[1].as_ref().map(|s| &*s.item),
|
||||
camera,
|
||||
1.0,
|
||||
240 | 240 << 8,
|
||||
&mut verts,
|
||||
);
|
||||
self.held_item_geometry(&m, camera, 1.0, 240 | 240 << 8, false, &mut verts);
|
||||
let height = if m.extra.crouching { 1.5 } else { 1.8 };
|
||||
// PictureInPictureRenderer: the box centre, (size, size, -size);
|
||||
@@ -567,17 +589,18 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn player_elytra_geometry(
|
||||
/// `WingsLayer` for a player wearing `chest`.
|
||||
pub(super) fn player_elytra_geometry(
|
||||
&self,
|
||||
m: &Mob,
|
||||
chest: Option<&str>,
|
||||
camera: glam::DVec3,
|
||||
partial: f32,
|
||||
light: u32,
|
||||
out: &mut Vec<horizon_client::mesher::Vertex>,
|
||||
) {
|
||||
let Some(asset) = self.armor[1]
|
||||
.as_ref()
|
||||
.and_then(|s| self.res.items().get(&s.item))
|
||||
let Some(asset) = chest
|
||||
.and_then(|item| self.res.items().get(item))
|
||||
.and_then(|i| i.equip_asset.as_ref())
|
||||
else {
|
||||
return;
|
||||
@@ -617,7 +640,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning
|
||||
/// player (`SpinAttackEffectModel.setupAnim`).
|
||||
fn spin_attack_geometry(
|
||||
pub(super) fn spin_attack_geometry(
|
||||
&self,
|
||||
m: &Mob,
|
||||
camera: glam::DVec3,
|
||||
|
||||
@@ -119,6 +119,22 @@ fn mob_can_be_affected(
|
||||
|| (effect != "regeneration" && effect != "poison")
|
||||
}
|
||||
}
|
||||
/// `ThrownSplashPotion.onHitAsPotion`: the squared distance from the potion's
|
||||
/// box at the hit point to an entity's box grown by the hit margin
|
||||
/// (`ProjectileUtil.computeMargin`), for entities that meet the potion's box
|
||||
/// grown by (4, 2, 4); none when it is 16 or more.
|
||||
fn splash_distance_sqr(at: Vec3, age: u32, bounds: Aabb) -> Option<f64> {
|
||||
let potion = Aabb::new(
|
||||
Vec3::new(at.x - 0.125, at.y, at.z - 0.125),
|
||||
Vec3::new(at.x + 0.125, at.y + 0.25, at.z + 0.125),
|
||||
);
|
||||
if !potion.inflate(Vec3::new(4.0, 2.0, 4.0)).intersects(bounds) {
|
||||
return None;
|
||||
}
|
||||
let margin = ((f64::from(age) - 2.0) / 20.0).clamp(0.0, 0.3);
|
||||
let d2 = potion.distance_squared_to_box(bounds.inflate(Vec3::new(margin, margin, margin)));
|
||||
(d2 < 16.0).then_some(d2)
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `LivingEntity.triggerOnDeathMobEffects` (`onMobRemoved` with the reason
|
||||
/// KILLED) for what Oozing, Weaving and Wind Charged do when their bearer
|
||||
@@ -804,15 +820,15 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
if let Some((p, mob)) = hit {
|
||||
landed.push((t.stack.clone(), p, mob, t.owner.clone()));
|
||||
landed.push((t.stack.clone(), p, mob, t.age, t.owner.clone()));
|
||||
return false;
|
||||
}
|
||||
t.position = next;
|
||||
t.age < 1200 && t.position.y > -128.0
|
||||
});
|
||||
self.potions.thrown = thrown;
|
||||
for (stack, at, mob, owner) in landed {
|
||||
self.splash(&stack, at, mob, owner);
|
||||
for (stack, at, mob, age, owner) in landed {
|
||||
self.splash(&stack, at, mob, age, owner);
|
||||
}
|
||||
}
|
||||
/// `AreaEffectCloud.tick` for the lingering potions' clouds: the client
|
||||
@@ -1079,17 +1095,20 @@ impl Game<'_> {
|
||||
&mut self,
|
||||
effects: &'static [(&'static str, i32, i32)],
|
||||
at: Vec3,
|
||||
age: u32,
|
||||
source: &Text,
|
||||
) {
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let center = Vec3::new(
|
||||
p.position.x,
|
||||
p.position.y + f64::from(p.dimensions.height) / 2.0,
|
||||
p.position.z,
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(p.position.x - w, p.position.y, p.position.z - w),
|
||||
Vec3::new(
|
||||
p.position.x + w,
|
||||
p.position.y + f64::from(p.dimensions.height),
|
||||
p.position.z + w,
|
||||
),
|
||||
);
|
||||
let d2 =
|
||||
(center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2);
|
||||
if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) {
|
||||
if let Some(d2) = splash_distance_sqr(at, age, bounds) {
|
||||
let intensity = 1.0 - d2.sqrt() / 4.0;
|
||||
for (id, duration, amp) in effects {
|
||||
let instant = brewing::effect(id).is_some_and(|e| e.instant);
|
||||
@@ -1110,8 +1129,15 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `ThrownSplashPotion.onHitAsPotion`, or `ThrownLingeringPotion.onHitAsPotion`
|
||||
/// for a lingering potion; `mob` is where it hit a mob.
|
||||
fn splash(&mut self, stack: &ItemStack, at: Vec3, mob: Option<Vec3>, owner: Option<Text>) {
|
||||
/// for a lingering potion; `mob` is where it hit a mob, `age` its age.
|
||||
fn splash(
|
||||
&mut self,
|
||||
stack: &ItemStack,
|
||||
at: Vec3,
|
||||
mob: Option<Vec3>,
|
||||
age: u32,
|
||||
owner: Option<Text>,
|
||||
) {
|
||||
let block = [at.x, at.y, at.z].map(|v| v.floor() as i32);
|
||||
if &*stack.item == "minecraft:experience_bottle" {
|
||||
// ThrownExperienceBottle.onHit: the water-coloured splash (level
|
||||
@@ -1169,15 +1195,14 @@ impl Game<'_> {
|
||||
// message names by the owner, else by the potion.
|
||||
let source =
|
||||
owner.unwrap_or_else(|| Text::translate("entity.minecraft.splash_potion", &[]));
|
||||
self.for_each_player(|g| g.splash_on_player(def.effects, at, &source));
|
||||
self.for_each_player(|g| g.splash_on_player(def.effects, at, age, &source));
|
||||
// Mobs take the instant effects (undead invert healing and harming).
|
||||
let undead = &self.res.stations().enchantments.entity_tags;
|
||||
let mut hits = Vec::new();
|
||||
for (i, m) in self.mobs.iter().enumerate() {
|
||||
let d2 = (m.position.x - at.x).powi(2)
|
||||
+ (m.position.y + m.kind.height / 2.0 - at.y).powi(2)
|
||||
+ (m.position.z - at.z).powi(2);
|
||||
if m.alive() && d2 < 16.0 {
|
||||
if m.alive()
|
||||
&& let Some(d2) = splash_distance_sqr(at, age, m.bounds())
|
||||
{
|
||||
let inverted = undead
|
||||
.get("minecraft:inverted_healing_and_harm")
|
||||
.is_some_and(|t| t.contains(&m.kind.id));
|
||||
@@ -1204,12 +1229,12 @@ impl Game<'_> {
|
||||
let m = &mut self.mobs[i];
|
||||
if harm {
|
||||
m.hurt(
|
||||
(intensity * f64::from(6 << amp)) as i32 as f32,
|
||||
(intensity * f64::from(6 << amp) + 0.5) as i32 as f32,
|
||||
Some([at.x, at.y, at.z]),
|
||||
&mut self.world.random,
|
||||
);
|
||||
} else {
|
||||
m.health = (m.health + (intensity * f64::from(4 << amp)) as i32 as f32)
|
||||
m.health = (m.health + (intensity * f64::from(4 << amp) + 0.5) as i32 as f32)
|
||||
.min(m.kind.max_health);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ use std::collections::{HashMap, HashSet};
|
||||
#[derive(Default)]
|
||||
pub(super) struct Raiding {
|
||||
patrol: PatrolSpawner,
|
||||
siege: Siege,
|
||||
/// The raids of the dimension the player is in, and that dimension.
|
||||
raids: Raids,
|
||||
loaded: Option<Dim>,
|
||||
@@ -38,6 +39,17 @@ pub(super) struct Raiding {
|
||||
homes: HashMap<i32, (i64, std::sync::Arc<Vec<[i32; 3]>>)>,
|
||||
}
|
||||
|
||||
/// `VillageSiege`: whether tonight is a siege, whether the spot is chosen,
|
||||
/// and the zombies still to spawn there.
|
||||
#[derive(Default)]
|
||||
struct Siege {
|
||||
tonight: bool,
|
||||
set_up: bool,
|
||||
zombies_to_spawn: i32,
|
||||
next_spawn_time: i32,
|
||||
spot: [i32; 3],
|
||||
}
|
||||
|
||||
impl Raiding {
|
||||
/// Exchange the level-held parts (`ServerLevel.getRaids`) with another
|
||||
/// level's (game/levels.rs).
|
||||
@@ -102,11 +114,12 @@ impl RaidLevel for Lvl<'_, '_> {
|
||||
&& g.res.facts().is_air(g.world.block(x, y, z))
|
||||
}
|
||||
fn player(&self) -> Option<RaidPlayer> {
|
||||
let p = self.game.player.as_ref()?;
|
||||
// The first player in the level: a server has no player of its own.
|
||||
let p = self.game.level_players().into_iter().next()?;
|
||||
Some(RaidPlayer {
|
||||
position: [p.position.x, p.position.y, p.position.z],
|
||||
block: block_of(p.position),
|
||||
alive: !p.health.dead_or_dying(),
|
||||
alive: p.alive,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -174,12 +187,13 @@ impl PatrolLevel for PatrolCx<'_, '_, '_> {
|
||||
fn bright_outside(&self) -> bool {
|
||||
self.level.game.dim == Dim::Overworld && self.level.game.sky_darken() < 4
|
||||
}
|
||||
/// `PatrolSpawner.tick` picks from `level.players()`: the local player
|
||||
/// and every guest in the level.
|
||||
fn patrol_players(&self) -> Vec<([i32; 3], bool)> {
|
||||
let g = self.level.game;
|
||||
g.player
|
||||
.as_ref()
|
||||
.map(|p| (block_of(p.position), g.spectator()))
|
||||
.into_iter()
|
||||
self.level
|
||||
.players
|
||||
.iter()
|
||||
.map(|p| (block_of(p.position), p.spectator))
|
||||
.collect()
|
||||
}
|
||||
fn sections_to_village(&self, pos: [i32; 3]) -> i32 {
|
||||
@@ -633,7 +647,7 @@ impl Game<'_> {
|
||||
/// `Raid.playSound`: the horn, 13 blocks away from the player toward the
|
||||
/// wave, for players within 64 blocks or in the raid.
|
||||
fn raid_horn(&mut self, id: i32, pos: [i32; 3]) {
|
||||
let Some(p) = self.player.as_ref().map(|p| p.position) else {
|
||||
let Some(p) = self.level_players().first().map(|p| p.position) else {
|
||||
return;
|
||||
};
|
||||
let in_raid = self.raiding.raids.get(id).is_some_and(|r| r.bar.player);
|
||||
@@ -791,7 +805,7 @@ impl Game<'_> {
|
||||
let has_rider = ridden.contains(&m.id);
|
||||
let target_golem = matches!(m.ai.target, Some(horizon_client::mobs::Who::Mob(t)) if golems.contains(&t));
|
||||
let target_player = m.ai.target == Some(horizon_client::mobs::Who::Player);
|
||||
let (health, age, range) = (m.health, m.age, m.attrs.follow_range);
|
||||
let (health, range) = (m.health, m.attrs.follow_range);
|
||||
let raids = &mut self.raiding.raids;
|
||||
let s = m.extra.raider.get_or_insert_with(Box::default);
|
||||
s.rider = has_rider;
|
||||
@@ -836,11 +850,9 @@ impl Game<'_> {
|
||||
{
|
||||
joins.push((m.id, id, health));
|
||||
}
|
||||
// PathfindToRaidGoal.recruitNearby.
|
||||
if s.active_raid
|
||||
&& !s.raid_over
|
||||
&& !s.in_village
|
||||
&& age % 20 == 0
|
||||
// PathfindToRaidGoal.tick: recruitNearby, only while the goal runs.
|
||||
if std::mem::take(&mut s.recruit_due)
|
||||
&& s.active_raid
|
||||
&& let Some(id) = s.raid_id
|
||||
{
|
||||
recruit.push((id, position));
|
||||
@@ -1218,6 +1230,140 @@ impl Game<'_> {
|
||||
self.spawn_event_mob("minecraft:pillager", at, m.leader, raider::Reason::Patrol);
|
||||
}
|
||||
}
|
||||
/// `VillageSiege.tick`: at midnight one night in ten, 20 zombies spawn
|
||||
/// two ticks apart near a village 32 blocks from a player standing in it.
|
||||
pub(super) fn tick_village_siege(&mut self) {
|
||||
if self.dim != Dim::Overworld {
|
||||
return;
|
||||
}
|
||||
let enemies = self.ui.rules.bool("spawn_mobs") && self.ui.rules.bool("spawn_monsters");
|
||||
if self.sky_darken() < 4 || !enemies {
|
||||
self.raiding.siege.tonight = false;
|
||||
self.raiding.siege.set_up = false;
|
||||
return;
|
||||
}
|
||||
// ClockTimeMarkers.ROLL_VILLAGE_SIEGE: tick 18000 of the 24000 tick day.
|
||||
if self.world.day_time.rem_euclid(24000) == 18000 {
|
||||
self.raiding.siege.tonight = self.world.random.next_int_bound(10).unwrap_or(1) == 0;
|
||||
}
|
||||
if !self.raiding.siege.tonight {
|
||||
return;
|
||||
}
|
||||
if !self.raiding.siege.set_up {
|
||||
if !self.try_to_setup_siege() {
|
||||
return;
|
||||
}
|
||||
self.raiding.siege.set_up = true;
|
||||
}
|
||||
if self.raiding.siege.next_spawn_time > 0 {
|
||||
self.raiding.siege.next_spawn_time -= 1;
|
||||
return;
|
||||
}
|
||||
self.raiding.siege.next_spawn_time = 2;
|
||||
if self.raiding.siege.zombies_to_spawn > 0 {
|
||||
self.try_spawn_siege_zombie();
|
||||
self.raiding.siege.zombies_to_spawn -= 1;
|
||||
} else {
|
||||
self.raiding.siege.tonight = false;
|
||||
}
|
||||
}
|
||||
/// `ServerLevel.isVillage`: within one section of a village.
|
||||
fn is_village(centers: &HashSet<(i32, i32, i32)>, pos: [i32; 3]) -> bool {
|
||||
sections_to_village(centers, section(pos)) <= 1
|
||||
}
|
||||
/// `VillageSiege.tryToSetupSiege`: the first player standing in a village
|
||||
/// picks a spot 32 blocks away (ten tries); true when one stood in a
|
||||
/// village, even if no spot was found.
|
||||
fn try_to_setup_siege(&mut self) -> bool {
|
||||
let centers = self.village_centers();
|
||||
for player in self.level_players() {
|
||||
if player.spectator {
|
||||
continue;
|
||||
}
|
||||
let center = block_of(player.position);
|
||||
if !Self::is_village(¢ers, center)
|
||||
|| self.natural_level().biome_tag(
|
||||
"minecraft:without_zombie_sieges",
|
||||
center[0],
|
||||
center[1],
|
||||
center[2],
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for _ in 0..10 {
|
||||
let angle = self.world.random.next_float() * std::f32::consts::TAU;
|
||||
let spot = [
|
||||
center[0] + (angle.cos() * 32.0).floor() as i32,
|
||||
center[1],
|
||||
center[2] + (angle.sin() * 32.0).floor() as i32,
|
||||
];
|
||||
if self.find_siege_spawn_pos(¢ers, spot).is_some() {
|
||||
self.raiding.siege.spot = spot;
|
||||
self.raiding.siege.next_spawn_time = 0;
|
||||
self.raiding.siege.zombies_to_spawn = 20;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `VillageSiege.trySpawn`: one zombie, in a random yaw.
|
||||
fn try_spawn_siege_zombie(&mut self) {
|
||||
let centers = self.village_centers();
|
||||
let spot = self.raiding.siege.spot;
|
||||
let Some(at) = self.find_siege_spawn_pos(¢ers, spot) else {
|
||||
return;
|
||||
};
|
||||
let Some(id) = self.spawn_event_mob("minecraft:zombie", at, false, raider::Reason::Event)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let yaw = self.world.random.next_float() * 360.0;
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
(m.yaw, m.previous_yaw, m.body_yaw, m.previous_body_yaw) = (yaw, yaw, yaw, yaw);
|
||||
(m.head_yaw, m.previous_head_yaw) = (yaw, yaw);
|
||||
}
|
||||
self.spawn_jockeys(id, false);
|
||||
}
|
||||
/// `VillageSiege.findRandomSpawnPos`: ten tries within 8 blocks of the
|
||||
/// spot for a village column where a zombie may spawn.
|
||||
fn find_siege_spawn_pos(
|
||||
&mut self,
|
||||
centers: &HashSet<(i32, i32, i32)>,
|
||||
spot: [i32; 3],
|
||||
) -> Option<[f64; 3]> {
|
||||
let mut random = std::mem::replace(
|
||||
&mut self.world.random,
|
||||
horizon_core::random::LegacyRandom::new(0),
|
||||
);
|
||||
let mut found = None;
|
||||
for _ in 0..10 {
|
||||
let x = spot[0] + random.next_int_bound(16).unwrap_or(0) - 8;
|
||||
let z = spot[2] + random.next_int_bound(16).unwrap_or(0) - 8;
|
||||
if !self.world.chunks.contains_key(&(x >> 4, z >> 4)) {
|
||||
continue;
|
||||
}
|
||||
let y = self.surface_height(x, z);
|
||||
if Self::is_village(centers, [x, y, z])
|
||||
&& spawn_rules::check_spawn_rules(
|
||||
Species::Zombie,
|
||||
&self.natural_level(),
|
||||
spawn_rules::Reason::Event,
|
||||
&mut random,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
)
|
||||
{
|
||||
found = Some([f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.world.random = random;
|
||||
found
|
||||
}
|
||||
/// A raider's ominous banner (drop chance 2.0: always dropped) and a
|
||||
/// patrol captain's ominous bottle (`entities/pillager`).
|
||||
/// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the
|
||||
|
||||
@@ -160,6 +160,9 @@ pub(super) struct Remote {
|
||||
stepped: HashMap<i32, SteppedInterpolation>,
|
||||
/// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it.
|
||||
head_lerps: HashMap<i32, (f32, u32)>,
|
||||
/// The happy ghast the player just got off, until the server's teleport
|
||||
/// puts the player on top of it (`place_ghast_under`).
|
||||
pub(super) ghast_dismount: Option<u32>,
|
||||
/// Item entities waiting for their item data: where they are and their
|
||||
/// motion.
|
||||
pending_items: HashMap<i32, ([f64; 3], Vec3)>,
|
||||
@@ -206,7 +209,7 @@ pub(super) struct Remote {
|
||||
placing: Option<([i32; 3], u64)>,
|
||||
/// `CommonPlayerSpawnInfo.isFlat`: the level is a superflat one.
|
||||
pub(super) flat: bool,
|
||||
death_message: Option<String>,
|
||||
death_message: Option<horizon_client::text::Text>,
|
||||
/// `LocalPlayer.showDeathScreen`: off with `immediate_respawn`.
|
||||
show_death_screen: bool,
|
||||
player_type: Option<Arc<MobType>>,
|
||||
@@ -478,6 +481,7 @@ impl Game<'_> {
|
||||
lerps: HashMap::new(),
|
||||
stepped: HashMap::new(),
|
||||
head_lerps: HashMap::new(),
|
||||
ghast_dismount: None,
|
||||
pending_items: HashMap::new(),
|
||||
health: (20.0, 20, 5.0),
|
||||
flash_on_set_health: false,
|
||||
@@ -696,10 +700,14 @@ impl Game<'_> {
|
||||
}
|
||||
let text = content.plain();
|
||||
log::info!("[chat] {text}");
|
||||
// addServerSystemMessage and addClientSystemMessage both carry
|
||||
// GuiMessageTag.systemSinglePlayer: the grey bar at the line's left.
|
||||
let indicator = (source != horizon_client::chat::ChatSource::Player)
|
||||
.then_some(horizon_client::chat::SYSTEM_INDICATOR);
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
content,
|
||||
None,
|
||||
indicator,
|
||||
source,
|
||||
self.ticks,
|
||||
self.screen == Screen::Chat,
|
||||
@@ -1031,6 +1039,12 @@ impl Game<'_> {
|
||||
r.predictions.clear();
|
||||
self.set_mode_id(spawn.game_type);
|
||||
self.dim = Dim::from_id(&spawn.dimension);
|
||||
// ClientPacketListener.handleLogin / handleRespawn: the server's
|
||||
// Player.getLastDeathLocation, for the recovery compass.
|
||||
self.level.last_death = spawn
|
||||
.last_death
|
||||
.as_ref()
|
||||
.map(|d| (d.dimension.clone(), d.pos));
|
||||
if !same {
|
||||
let mut streaming = Streaming::new(
|
||||
Arc::new(NoTerrain),
|
||||
@@ -1444,6 +1458,17 @@ impl Game<'_> {
|
||||
{
|
||||
return;
|
||||
}
|
||||
// A thrown trident is an arrow: placed at once, flown on by its tick.
|
||||
if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id as u32) {
|
||||
if path.is_some() {
|
||||
t.position = Vec3::new(position[0], position[1], position[2]);
|
||||
}
|
||||
if let Some((yaw, pitch)) = rotation {
|
||||
t.yaw = yaw;
|
||||
t.pitch = pitch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// So does a firework rocket: its own tick flies it on.
|
||||
if path.is_some()
|
||||
&& let Some(f) = self.rockets.iter_mut().find(|f| f.id == id as u32)
|
||||
@@ -2161,7 +2186,23 @@ impl Game<'_> {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
// CrossbowItem.isCharged: the main hand's `charged_projectiles`
|
||||
// (AvatarRenderer.getArmPose holds a loaded crossbow up).
|
||||
let charged = p.slots.iter().find(|(slot, _)| *slot == 0).map(|(_, s)| {
|
||||
s.as_ref().is_some_and(|s| {
|
||||
matches!(
|
||||
s.component(horizon_protocol::item::component::CHARGED_PROJECTILES),
|
||||
Some(horizon_protocol::item::Component::Stacks(list))
|
||||
if !list.is_empty()
|
||||
)
|
||||
})
|
||||
});
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
|
||||
if let Some(charged) = charged
|
||||
&& &*m.kind.id == "minecraft:player"
|
||||
{
|
||||
m.extra.charged = charged;
|
||||
}
|
||||
// The body slot (6: horse armour, llama carpet, harness)
|
||||
// is kept in `head`, as Horizon's own mobs do.
|
||||
let body = horizon_client::mobs::drops::head_is_body(m.species());
|
||||
@@ -2174,7 +2215,11 @@ impl Game<'_> {
|
||||
3 => e.legs = item,
|
||||
4 => e.chest = item,
|
||||
5 if !body => e.head = item,
|
||||
6 if body => e.head = item,
|
||||
6 if body => {
|
||||
// A wolf's armor shows its cracks.
|
||||
e.body_damage = stack.as_ref().map_or(0, |s| s.damage as i32);
|
||||
e.head = item;
|
||||
}
|
||||
7 => m.set_saddle(stack),
|
||||
_ => {}
|
||||
}
|
||||
@@ -2261,6 +2306,10 @@ impl Game<'_> {
|
||||
self.remote_firework_explosion(p.id);
|
||||
}
|
||||
self.remote_fangs_event(p.id as u32, p.event);
|
||||
// LivingEntity.handleEntityEvent 2: a spear's hit felt.
|
||||
if p.event == 2 {
|
||||
self.remote_kinetic_hit(p.id);
|
||||
}
|
||||
// LocalPlayer.setPermissions also refreshes an open World Options screen.
|
||||
if (24..=28).contains(&p.event)
|
||||
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
|
||||
@@ -2268,6 +2317,10 @@ impl Game<'_> {
|
||||
self.ui.registries.permission = (p.event - 24) as u8;
|
||||
self.remote_world_options_permission(p.event >= 26);
|
||||
}
|
||||
// Ravager.handleEntityEvent 69: the roar's puff and push.
|
||||
if p.event == 69 {
|
||||
self.remote_ravager_roar(p.id);
|
||||
}
|
||||
if p.event == 1
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
&& m.species() == horizon_client::mobs::Species::Rabbit
|
||||
@@ -2412,6 +2465,7 @@ impl Game<'_> {
|
||||
{
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.death_time = 0;
|
||||
self.ui.death_confirm = None;
|
||||
self.capture(false);
|
||||
}
|
||||
}
|
||||
@@ -2419,7 +2473,7 @@ impl Game<'_> {
|
||||
// The component resolves in the client's current language, as
|
||||
// the chat line does, not in the language the session joined
|
||||
// with (`Remote.lang` is the vanilla server-language table).
|
||||
let message = remote_text(&p.message).plain();
|
||||
let message = remote_text(&p.message);
|
||||
let me = self.remote.as_ref().is_some_and(|r| r.entity_id == p.id);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.death_message = Some(message);
|
||||
@@ -2431,6 +2485,7 @@ impl Game<'_> {
|
||||
if self.remote.as_ref().is_none_or(|r| r.show_death_screen) {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.death_time = 0;
|
||||
self.ui.death_confirm = None;
|
||||
self.capture(false);
|
||||
} else {
|
||||
self.respawn_player()?;
|
||||
@@ -3258,6 +3313,7 @@ impl Game<'_> {
|
||||
health: 5,
|
||||
fire_ticks: 0,
|
||||
thrower: None,
|
||||
target: None,
|
||||
id: id as u32,
|
||||
stack,
|
||||
position: at,
|
||||
@@ -3294,6 +3350,8 @@ impl Game<'_> {
|
||||
p.velocity = v;
|
||||
} else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) {
|
||||
b.velocity = v;
|
||||
} else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id as u32) {
|
||||
t.velocity = v;
|
||||
} else if let Some(r) = self.rockets.iter_mut().find(|r| r.id == id as u32) {
|
||||
r.velocity = v;
|
||||
} else if let Some(p) = self
|
||||
@@ -3318,6 +3376,37 @@ impl Game<'_> {
|
||||
p.health.food.saturation = saturation;
|
||||
}
|
||||
}
|
||||
/// `ServerPlayer.dismountTo` lands a rider at the ghast's own (x, maxY, z)
|
||||
/// (`HappyGhast.getDismountLocationForPassenger`). A vanilla client
|
||||
/// simulates the ghast it rides, so its copy is where the server has it;
|
||||
/// this window's copy trails the server's by the stepped interpolation and
|
||||
/// would rise into the rider's feet, which lets the rider fall through.
|
||||
/// Put the copy under the landing spot.
|
||||
fn place_ghast_under(&mut self, id: u32, spot: Vec3) {
|
||||
let Some(m) = self
|
||||
.mobs
|
||||
.iter_mut()
|
||||
.find(|m| m.id == id && m.species() == horizon_client::mobs::Species::HappyGhast)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let at = Vec3::new(spot.x, spot.y - f64::from(m.height()), spot.z);
|
||||
// Only a teleport that is that dismount: right above the ghast.
|
||||
if (at.x - m.position.x).powi(2) + (at.z - m.position.z).powi(2) > 25.0
|
||||
|| (at.y - m.position.y).abs() > 5.0
|
||||
{
|
||||
return;
|
||||
}
|
||||
m.position = at;
|
||||
m.previous = at;
|
||||
if let Some(handler) = self
|
||||
.remote
|
||||
.as_mut()
|
||||
.and_then(|r| r.stepped.get_mut(&(id as i32)))
|
||||
{
|
||||
handler.cancel();
|
||||
}
|
||||
}
|
||||
/// ClientPacketListener.handleMovePlayer.
|
||||
fn remote_teleport(&mut self, p: &play::PlayerPosition) -> Result<()> {
|
||||
use play::relative as rel;
|
||||
@@ -3377,6 +3466,9 @@ impl Game<'_> {
|
||||
self.previous_position = position;
|
||||
self.yaw = yaw;
|
||||
self.pitch = pitch;
|
||||
if let Some(id) = self.remote.as_mut().and_then(|r| r.ghast_dismount.take()) {
|
||||
self.place_ghast_under(id, position);
|
||||
}
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
// handleMovePlayer does not change LocalPlayer.sendPosition's
|
||||
// baseline: the next tick must still report the corrected state.
|
||||
@@ -3844,15 +3936,12 @@ impl Game<'_> {
|
||||
let head_lerps = &mut r.head_lerps;
|
||||
let players = &r.level_players;
|
||||
let mut using = Vec::new();
|
||||
let mut wither_heads = Vec::new();
|
||||
let mut mob_fx = Vec::new();
|
||||
for m in &mut self.mobs {
|
||||
let player = players.contains_key(&(m.id as i32));
|
||||
if !running && !player {
|
||||
continue;
|
||||
}
|
||||
if m.species() == horizon_client::mobs::Species::Wither {
|
||||
wither_heads.extend((0..3).map(|i| horizon_client::mobs::wither::head_pos(m, i)));
|
||||
}
|
||||
m.previous = m.position;
|
||||
m.previous_yaw = m.yaw;
|
||||
m.previous_body_yaw = m.body_yaw;
|
||||
@@ -3887,6 +3976,17 @@ impl Game<'_> {
|
||||
if m.species() == horizon_client::mobs::Species::PolarBear {
|
||||
horizon_client::mobs::polar_bear::client_tick(m);
|
||||
}
|
||||
// The particles these mobs' own ticks draw on the client side.
|
||||
{
|
||||
use horizon_client::mobs::{Species as S, cube, illusioner, nautilus, wither};
|
||||
match m.species() {
|
||||
S::Slime | S::MagmaCube | S::SulfurCube => cube::client_tick(m, &mut mob_fx),
|
||||
S::Nautilus | S::ZombieNautilus => nautilus::client_tick(m, &mut mob_fx),
|
||||
S::Illusioner => illusioner::client_tick(m, &mut mob_fx),
|
||||
S::Wither => wither::client_smoke(m, &mut mob_fx),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if m.hurt_time > 0 {
|
||||
m.hurt_time -= 1;
|
||||
}
|
||||
@@ -3947,6 +4047,8 @@ impl Game<'_> {
|
||||
// a player's body following its walk and look.
|
||||
if player {
|
||||
remote_player_head_turn(m);
|
||||
// LivingEntity.tick: the glide count, wings and swim amount.
|
||||
m.tick_avatar_pose(m.fluids.in_water);
|
||||
} else if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
}
|
||||
@@ -3992,19 +4094,7 @@ impl Game<'_> {
|
||||
d.tick(world, facts, collision, false, &self.res.motion().fluids);
|
||||
}
|
||||
head_lerps.retain(|_, (_, steps)| *steps > 0);
|
||||
// WitherBoss.aiStep runs on a client too: smoke around each head.
|
||||
let smoke = horizon_client::particles::ParticleOptions::simple(
|
||||
horizon_client::particles::ParticleType::Smoke,
|
||||
);
|
||||
for h in wither_heads {
|
||||
let r = self.particles.random();
|
||||
let at = [
|
||||
h[0] + r.next_gaussian() * 0.3,
|
||||
h[1] + r.next_gaussian() * 0.3,
|
||||
h[2] + r.next_gaussian() * 0.3,
|
||||
];
|
||||
self.particles.add(&smoke, at, [0.0; 3]);
|
||||
}
|
||||
let _ = self.handle_mob_events(mob_fx);
|
||||
for (item, ticks, at, eye, pitch, yaw) in using {
|
||||
self.remote_player_eating(&item, ticks, at, eye, pitch, yaw);
|
||||
}
|
||||
@@ -4451,6 +4541,15 @@ impl Game<'_> {
|
||||
if reacts {
|
||||
self.predict_use(&changes, seq);
|
||||
self.open_command_block_if_editable((hit.pos[0], hit.pos[1], hit.pos[2]));
|
||||
} else if held.as_ref().is_some_and(|s| &*s.item == "minecraft:brush") {
|
||||
// BrushItem.useOn: brushing starts here (CONSUME, no swing); the
|
||||
// server brushes and the dust is this client's own.
|
||||
self.with_hand(hand, |g| {
|
||||
if g.using.is_none() {
|
||||
g.using = Some((g.held_slot(), 0));
|
||||
}
|
||||
});
|
||||
return true;
|
||||
} else if let Some(stack) = held.as_ref()
|
||||
&& self.predict_item_on_block(stack, &hit)
|
||||
{
|
||||
@@ -4749,6 +4848,8 @@ impl Game<'_> {
|
||||
}
|
||||
// SpyglassItem.use (its sound is the server's).
|
||||
"minecraft:spyglass" => true,
|
||||
// Item.use: a kinetic weapon starts being used.
|
||||
id if horizon_client::spear::Kinetic::of(id).is_some() => true,
|
||||
// ShieldItem.use: anything that blocks attacks, off cooldown.
|
||||
_ => {
|
||||
self.raise_shield(self.held_slot());
|
||||
@@ -4765,7 +4866,8 @@ impl Game<'_> {
|
||||
matches!(
|
||||
&*stack.item,
|
||||
"minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass"
|
||||
) || self.blocks_attacks(stack).is_some()
|
||||
) || horizon_client::spear::Kinetic::of(&stack.item).is_some()
|
||||
|| self.blocks_attacks(stack).is_some()
|
||||
}
|
||||
|
||||
/// The rest of Minecraft.startUseItem once the main hand's target passed:
|
||||
@@ -4809,6 +4911,30 @@ impl Game<'_> {
|
||||
// Another hotbar slot picked: LivingEntity.updatingUsingItem sees a
|
||||
// different stack in the hand. The off hand keeps its item.
|
||||
let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT;
|
||||
// BrushItem.onUseTick: with no block aimed the use ends (the server
|
||||
// ends it too); a stroke shows its dust. Its sounds are the server's.
|
||||
if stack
|
||||
.as_ref()
|
||||
.is_some_and(|s| &*s.item == "minecraft:brush")
|
||||
{
|
||||
let elapsed = ticks + 1;
|
||||
let hit = self.pick().filter(|_| in_hand);
|
||||
if let Some(hit) = &hit
|
||||
&& elapsed % 10 == 5
|
||||
{
|
||||
self.brush_dust(hit, slot == super::shield::OFFHAND_SLOT);
|
||||
}
|
||||
if hit.is_none() && in_hand {
|
||||
self.send(S::PlayerAction(play::PlayerAction {
|
||||
action: 6,
|
||||
pos: [0; 3],
|
||||
direction: 0,
|
||||
sequence: 0,
|
||||
}));
|
||||
}
|
||||
self.using = hit.and(Some((slot, elapsed))).filter(|_| elapsed < 200);
|
||||
return;
|
||||
}
|
||||
// BundleItem.getUseDuration: 200 ticks, the server drops the contents.
|
||||
if stack
|
||||
.as_ref()
|
||||
@@ -4958,7 +5084,9 @@ impl Game<'_> {
|
||||
match key {
|
||||
KeyCode::KeyF if !self.spectator() => self.remote_swap_hands(),
|
||||
KeyCode::KeyQ if !self.spectator() => {
|
||||
let all = self.keys.contains(&KeyCode::ControlLeft);
|
||||
// Minecraft.hasControlDown: the physical keys, so a toggled
|
||||
// sprint on Left Control does not make Q drop the stack.
|
||||
let all = self.has_control_down();
|
||||
self.remote_drop(all);
|
||||
}
|
||||
KeyCode::KeyE if self.riding_mount_with_menu() => {
|
||||
@@ -5653,8 +5781,16 @@ impl Game<'_> {
|
||||
if self.screen == Screen::Dead
|
||||
&& let Some(message) = &r.death_message
|
||||
{
|
||||
let tw = HudBatch::text_width(atlas, message);
|
||||
batch.text(atlas, message, (w - tw) / 2.0, 85.0, u32::MAX, true);
|
||||
// DeathScreen draws the styled cause component.
|
||||
let tw = atlas.font.width_text(message);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
message,
|
||||
((w - tw) / 2.0).floor(),
|
||||
85.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// Shared flag 6 of an entity on a server's client (`None` without a server).
|
||||
@@ -5949,7 +6085,8 @@ fn hand_id(hand: Hand) -> i32 {
|
||||
/// server decides; this is the client's guess of whether to go on.
|
||||
fn item_has_use(info: &horizon_client::items::ItemInfo) -> bool {
|
||||
let id = info.id.trim_start_matches("minecraft:");
|
||||
info.consumable.is_some()
|
||||
id.ends_with("_spear")
|
||||
|| info.consumable.is_some()
|
||||
|| info.equip_slot.is_some()
|
||||
|| info.blocks_attacks.is_some()
|
||||
|| horizon_client::items::bucket_contents(&info.id).is_some()
|
||||
@@ -6019,7 +6156,18 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
|
||||
direction: 0,
|
||||
sequence: 0,
|
||||
}));
|
||||
self.0.using = None;
|
||||
// MultiPlayerGameMode.releaseUsingItem also runs `Item.releaseUsing` here: the
|
||||
// player moves by itself, so a Riptide launch happens on the client.
|
||||
let hand = self.0.used_hand();
|
||||
if let Some((slot, ticks)) = self.0.using.take()
|
||||
&& let Some(hand) = hand
|
||||
&& self
|
||||
.0
|
||||
.stack_in(slot)
|
||||
.is_some_and(|s| &*s.item == "minecraft:trident")
|
||||
{
|
||||
self.0.with_hand(hand, |g| g.release_trident(ticks));
|
||||
}
|
||||
}
|
||||
fn start_attack(&mut self) -> bool {
|
||||
self.0.remote_start_attack()
|
||||
|
||||
@@ -17,6 +17,9 @@ use horizon_protocol::registry::{Builtin, Dynamic};
|
||||
fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_entity: i32) {
|
||||
let species = m.species();
|
||||
let baby = super::lan::baby_index(&m.kind.id);
|
||||
if &*m.kind.id == "minecraft:player" {
|
||||
player_poses(m, values);
|
||||
}
|
||||
for (index, _, value) in values {
|
||||
match (*index, value) {
|
||||
// Entity.DATA_POSE: a player's or mannequin's box follows it.
|
||||
@@ -117,6 +120,9 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
|
||||
(Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => {
|
||||
m.extra.size = (*size).clamp(1, 127);
|
||||
}
|
||||
// Enderman.DATA_CREEPY (after DATA_CARRY_STATE): the open mouth
|
||||
// and raised head of an angry enderman.
|
||||
(Species::Enderman, 17, Value::Bool(creepy)) => m.extra.flag = *creepy,
|
||||
// Warden.CLIENT_ANGER_LEVEL: the heartbeat's pace.
|
||||
(Species::Warden, 16, Value::Int(anger)) => {
|
||||
if let Some(st) = m.extra.warden.as_mut() {
|
||||
@@ -212,6 +218,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
|
||||
// Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's
|
||||
// IS_CELEBRATING takes 16).
|
||||
(Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging,
|
||||
// HappyGhast.STAYS_STILL (after AgeableMob's two and IS_LEASH_HOLDER):
|
||||
// `isOnStillTimeout` on a client, which keeps the ghast solid to
|
||||
// the player (`canBeCollidedWith`).
|
||||
(Species::HappyGhast, 19, Value::Bool(still)) => m.extra.counter = i32::from(*still),
|
||||
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
|
||||
(Species::Evoker | Species::Illusioner, 17, Value::Byte(spell)) => {
|
||||
m.extra.variant2 = (*spell).max(0) as u8;
|
||||
@@ -280,6 +290,21 @@ fn apply_registry_data(
|
||||
}
|
||||
}
|
||||
|
||||
/// What another player's pose draws from: gliding (Entity.isFallFlying, flag
|
||||
/// 0x80 of the shared flags), the pose (swimming), Riptide's spin
|
||||
/// (LivingEntity.isAutoSpinAttack, flag 4) and a loaded crossbow in the
|
||||
/// hand (the held stack comes with SetEquipment).
|
||||
fn player_poses(m: &mut Mob, values: &[(u8, i32, Value)]) {
|
||||
for (index, _, value) in values {
|
||||
match (*index, value) {
|
||||
(0, Value::Byte(flags)) => m.extra.fall_flying = flags & -128 != 0,
|
||||
(6, Value::Id(pose)) => m.extra.synced_pose = (*pose).clamp(0, 17) as u8,
|
||||
(8, Value::Byte(flags)) => m.extra.auto_spin_attack = flags & 4 != 0,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The options of a synched particle list: an entity effect carries its ARGB
|
||||
/// colour, the omens none.
|
||||
fn swirls(list: &[Particle], builtin: &Builtin) -> Vec<ParticleOptions> {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Particles a client of a server draws for a mob's entity event, which the
|
||||
//! server does not send as a particle packet.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
mobs::Species,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Ravager.handleEntityEvent(69)`: forty puffs of smoke from the middle
|
||||
/// of its box, then `applyRoarKnockbackClient`: this client's own player
|
||||
/// within 4 blocks is thrown away from it.
|
||||
pub(super) fn remote_ravager_roar(&mut self, id: i32) {
|
||||
let Some(m) = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id as u32 && m.species() == Species::Ravager)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (center, at, area) = (
|
||||
m.center(),
|
||||
m.position,
|
||||
m.bounds().inflate(Vec3::new(4.0, 4.0, 4.0)),
|
||||
);
|
||||
let options = ParticleOptions::simple(ParticleType::Poof);
|
||||
for _ in 0..40 {
|
||||
let r = self.particles.random();
|
||||
let v = [
|
||||
r.next_gaussian() * 0.2,
|
||||
r.next_gaussian() * 0.2,
|
||||
r.next_gaussian() * 0.2,
|
||||
];
|
||||
self.particles.add(&options, center, v);
|
||||
}
|
||||
if let Some(view) = self.player_view()
|
||||
&& view.alive
|
||||
&& view.bounds.intersects(area)
|
||||
&& let Some(p) = self.player.as_mut()
|
||||
{
|
||||
// strongKnockback.
|
||||
let (xd, zd) = (p.position.x - at.x, p.position.z - at.z);
|
||||
let dd = (xd * xd + zd * zd).max(0.001);
|
||||
p.velocity = p
|
||||
.velocity
|
||||
.add_vector(Vec3::new(xd / dd * 4.0, 0.2, zd / dd * 4.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,8 @@ impl Game<'_> {
|
||||
) && !baby
|
||||
}
|
||||
Species::Sheep => item == "minecraft:shears" || item.ends_with("_dye"),
|
||||
// SnowGolem.mobInteract: shears take the pumpkin off.
|
||||
Species::SnowGolem => item == "minecraft:shears" && !m.extra.sheared,
|
||||
// Bucketable.bucketMobPickup.
|
||||
Species::Cod
|
||||
| Species::Salmon
|
||||
|
||||
@@ -207,6 +207,8 @@ impl Game<'_> {
|
||||
"minecraft:trident" => {
|
||||
let mut t = super::trident::ThrownTrident::remote(id, at, yaw, pitch);
|
||||
t.velocity = velocity;
|
||||
// Projectile.getAddEntityPacket: the owner's id is the data.
|
||||
t.owner = data as u32;
|
||||
self.tridents.push(t);
|
||||
}
|
||||
"minecraft:firework_rocket" => {
|
||||
@@ -350,6 +352,15 @@ impl Game<'_> {
|
||||
(9, Value::Bool(show)) => c.show_bottom = *show,
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id) {
|
||||
// AbstractArrow.ID_FLAGS (no physics) and IN_GROUND, and
|
||||
// ThrownTrident.ID_LOYALTY.
|
||||
match (index, value) {
|
||||
(8, Value::Byte(flags)) => t.no_physics = flags & 2 != 0,
|
||||
(10, Value::Bool(in_ground)) => t.in_ground = *in_ground,
|
||||
(11, Value::Byte(loyalty)) => t.loyalty = u32::from(*loyalty as u8),
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) {
|
||||
match (&mut p.kind, index, value) {
|
||||
// AbstractArrow.ID_FLAGS (critical) and IN_GROUND.
|
||||
@@ -383,6 +394,25 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Entity.getEyePosition` of a projectile's owner: this game's player or
|
||||
/// another player the server sent.
|
||||
fn remote_eye(&self, id: u32) -> Option<Vec3> {
|
||||
let me = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.and_then(|r| u32::try_from(r.entity_id).ok());
|
||||
if me == Some(id) {
|
||||
let eye = self.eye_position()?;
|
||||
return Some(Vec3::new(eye[0], eye[1], eye[2]));
|
||||
}
|
||||
let m = self.mobs.iter().find(|m| m.id == id)?;
|
||||
Some(Vec3::new(
|
||||
m.position.x,
|
||||
m.position.y + m.eye_height(),
|
||||
m.position.z,
|
||||
))
|
||||
}
|
||||
|
||||
/// One tick of interpolation, as `tick_remote_objects`.
|
||||
pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
|
||||
self.tick_remote_fangs();
|
||||
@@ -416,6 +446,7 @@ impl Game<'_> {
|
||||
// updates (10 to 20 ticks apart); a block stops them there, and only
|
||||
// the server decides what they hit.
|
||||
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
|
||||
let mut tridents = std::mem::take(&mut self.tridents);
|
||||
{
|
||||
let w = self.mob_world_base(&[]);
|
||||
let world = super::creatures::ProjWorld {
|
||||
@@ -434,8 +465,12 @@ impl Game<'_> {
|
||||
_ => remote_projectile_tick(p, &world),
|
||||
}
|
||||
}
|
||||
for t in &mut tridents {
|
||||
t.remote_tick(&world, self.remote_eye(t.owner));
|
||||
}
|
||||
}
|
||||
self.creatures.projectiles = projectiles;
|
||||
self.tridents = tridents;
|
||||
let trails: Vec<Vec3> = self
|
||||
.creatures
|
||||
.projectiles
|
||||
@@ -444,10 +479,6 @@ impl Game<'_> {
|
||||
.map(|p| p.position)
|
||||
.collect();
|
||||
self.smoke_trails(trails);
|
||||
for t in &mut self.tridents {
|
||||
let id = t.id;
|
||||
t.remote_step(|at| step(id, at));
|
||||
}
|
||||
// FireworkRocketEntity.tick: a rocket attached to an entity follows it
|
||||
// and boosts it client-side too (attachedToEntity.isFallFlying), and
|
||||
// every rocket leaves its spark trail on a client.
|
||||
|
||||
@@ -128,6 +128,17 @@ impl Game<'_> {
|
||||
} else if self.riding == Some(vehicle_id) {
|
||||
// The server takes the player out, then teleports it.
|
||||
self.riding = None;
|
||||
// HappyGhast.removePassenger: a still timeout of 10 (the server's
|
||||
// STAYS_STILL confirms it), and the rider lands on top of the ghast
|
||||
// (`place_ghast_under`).
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| {
|
||||
m.id == vehicle_id && m.species() == horizon_client::mobs::Species::HappyGhast
|
||||
}) {
|
||||
m.extra.counter = 10;
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.ghast_dismount = Some(vehicle_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,10 +19,29 @@ use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
|
||||
/// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one.
|
||||
fn motion_blocking(world: &World, facts: &BlockFacts, x: i32, z: i32, from: i32) -> i32 {
|
||||
motion_blocking_leaves(world, facts, x, z, from, true)
|
||||
}
|
||||
/// `motion_blocking` where leaves count only for MOTION_BLOCKING, not for
|
||||
/// MOTION_BLOCKING_NO_LEAVES.
|
||||
fn motion_blocking_leaves(
|
||||
world: &World,
|
||||
facts: &BlockFacts,
|
||||
x: i32,
|
||||
z: i32,
|
||||
from: i32,
|
||||
leaves: bool,
|
||||
) -> i32 {
|
||||
let mut y = from.min(MIN_Y + HEIGHT - 1);
|
||||
while y > MIN_Y {
|
||||
let f = facts.get(world.block(x, y, z));
|
||||
if f.full_collision || f.fluid != Fluid::None || f.name.contains("leaves") {
|
||||
// #minecraft:leaves block motion, but MOTION_BLOCKING_NO_LEAVES skips them
|
||||
// (their water still counts).
|
||||
let blocks = if f.name.ends_with("_leaves") {
|
||||
leaves
|
||||
} else {
|
||||
f.full_collision
|
||||
};
|
||||
if blocks || f.fluid != Fluid::None {
|
||||
return y + 1;
|
||||
}
|
||||
y -= 1;
|
||||
@@ -34,16 +53,7 @@ fn rains_at(world: &World, biomes: &Biomes, x: i32, y: i32, z: i32) -> bool {
|
||||
let Some(chunk) = world.chunks.get(&(x >> 4, z >> 4)) else {
|
||||
return false;
|
||||
};
|
||||
let b = biomes.get(chunk.biome(x, y, z));
|
||||
if !b.precipitation {
|
||||
return false;
|
||||
}
|
||||
let t = if y > 80 {
|
||||
b.temperature - (y - 80) as f32 * 0.05 / 40.0
|
||||
} else {
|
||||
b.temperature
|
||||
};
|
||||
t >= 0.15
|
||||
biomes.get(chunk.biome(x, y, z)).snows_at(x, y, z) == Some(false)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -293,6 +303,11 @@ impl Game<'_> {
|
||||
&& motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1]
|
||||
&& rains_at(world, biomes, p[0], p[1], p[2])
|
||||
};
|
||||
let height_no_leaves =
|
||||
|p: [i32; 3]| motion_blocking_leaves(world, facts, p[0], p[2], i32::MAX, false);
|
||||
// The day timeline: firefly bush sounds from 12600 to 23400.
|
||||
let firefly_bush_sounds = self.dim == Dim::Overworld
|
||||
&& (12600..23401).contains(&self.world.day_time.rem_euclid(24000));
|
||||
let tables = &self.pack.context.tables;
|
||||
let model_offset = |state, x, z| tables.offset(state, x, z);
|
||||
let gateway_particles = |state, p| {
|
||||
@@ -310,6 +325,9 @@ impl Game<'_> {
|
||||
biomes,
|
||||
registry: self.pack.assets.registry,
|
||||
raining_at: &raining_at,
|
||||
height_no_leaves: &height_no_leaves,
|
||||
firefly_bush_sounds,
|
||||
sky_darken: self.sky_darken(),
|
||||
marker: marker.map(|name| (name, &marker_options as &dyn Fn(_) -> _)),
|
||||
model_offset: &model_offset,
|
||||
gateway_particles: &gateway_particles,
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
command::args::GameMode,
|
||||
confirm_screen::Confirm,
|
||||
hud::{HudBatch, rgba},
|
||||
text::{self, Text},
|
||||
ui,
|
||||
@@ -103,6 +104,14 @@ fn pause_icons(w: f32, h: f32, links: bool) -> [(f32, f32, &'static str); 4] {
|
||||
]
|
||||
}
|
||||
/// DeathScreen.init: a hardcore player can only spectate.
|
||||
/// `DeathScreen.TitleConfirmScreen`: its title and the yes and no labels.
|
||||
fn death_confirm_texts() -> (Text, [Text; 2]) {
|
||||
let t = |key: &str| Text::translate(key, &[]);
|
||||
(
|
||||
t("deathScreen.quit.confirm"),
|
||||
[t("deathScreen.titleScreen"), t("deathScreen.respawn")],
|
||||
)
|
||||
}
|
||||
fn death_buttons(w: f32, h: f32, hardcore: bool) -> [(f32, f32, &'static str, u8); 2] {
|
||||
let respawn = if hardcore {
|
||||
"deathScreen.spectate"
|
||||
@@ -267,6 +276,20 @@ impl Game<'_> {
|
||||
),
|
||||
);
|
||||
}
|
||||
// DeathScreen.handleExitToTitleScreen: the TitleConfirmScreen takes the
|
||||
// screen over, on the same background.
|
||||
if let Some(opened) = self.ui.death_confirm {
|
||||
let (title, labels) = death_confirm_texts();
|
||||
let size = self.gui_size();
|
||||
Confirm::new(&atlas.font, size, &title, &Text::literal("")).draw_active(
|
||||
batch,
|
||||
atlas,
|
||||
self.cursor,
|
||||
[&labels[0], &labels[1]],
|
||||
opened.elapsed().as_millis() >= 1000,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let title = if self.level.hardcore {
|
||||
"deathScreen.title.hardcore"
|
||||
} else {
|
||||
@@ -382,6 +405,23 @@ impl Game<'_> {
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(opened) = self.ui.death_confirm {
|
||||
// ConfirmScreen.setDelay: both buttons wait 20 ticks.
|
||||
if opened.elapsed().as_millis() < 1000 {
|
||||
return Ok(());
|
||||
}
|
||||
let (title, _) = death_confirm_texts();
|
||||
let confirm = Confirm::new(
|
||||
&self.gui.atlas.font,
|
||||
self.gui_size(),
|
||||
&title,
|
||||
&Text::literal(""),
|
||||
);
|
||||
if let Some(yes) = confirm.answer_at(self.cursor) {
|
||||
self.death_confirm_answer(yes)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let size = self
|
||||
.renderer
|
||||
.as_ref()
|
||||
@@ -391,6 +431,27 @@ impl Game<'_> {
|
||||
.into_iter()
|
||||
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
|
||||
.map(|d| d.3);
|
||||
// handleExitToTitleScreen: outside hardcore, Title Screen asks first.
|
||||
if hit == Some(1) && !self.level.hardcore {
|
||||
self.ui.death_confirm = Some(std::time::Instant::now());
|
||||
self.audio.play_button_click();
|
||||
return Ok(());
|
||||
}
|
||||
self.death_action(hit)
|
||||
}
|
||||
/// The confirm screen's answer: yes leaves the world, no respawns
|
||||
/// (`DeathScreen.handleExitToTitleScreen`'s callback).
|
||||
pub(super) fn death_confirm_answer(&mut self, yes: bool) -> Result<()> {
|
||||
self.ui.death_confirm = None;
|
||||
if yes {
|
||||
self.audio.play_button_click();
|
||||
self.close_world()
|
||||
} else {
|
||||
self.death_action(Some(0))
|
||||
}
|
||||
}
|
||||
/// A death screen button: 0 respawns (or spectates in hardcore), 1 leaves.
|
||||
fn death_action(&mut self, hit: Option<u8>) -> Result<()> {
|
||||
match hit {
|
||||
Some(0) => self.respawn_player()?,
|
||||
Some(1) => self.close_world()?,
|
||||
|
||||
@@ -876,17 +876,26 @@ impl Game<'_> {
|
||||
/// `SculkSensorBlock.stepOn` and `SculkShriekerBlock.stepOn`: standing on
|
||||
/// them is heard (or seen) every tick.
|
||||
fn sculk_step_on(&mut self) {
|
||||
self.sculk_step_on_player();
|
||||
let mut standing: Vec<(Who, [f64; 3])> = Vec::new();
|
||||
if let Some(p) = self.player.as_ref()
|
||||
&& p.ground.on_ground
|
||||
{
|
||||
standing.push((Who::Player, [p.position.x, p.position.y, p.position.z]));
|
||||
}
|
||||
for m in &self.mobs {
|
||||
if m.alive() && m.on_ground {
|
||||
standing.push((Who::Mob(m.id), [m.position.x, m.position.y, m.position.z]));
|
||||
}
|
||||
}
|
||||
self.sculk_stand_on(standing);
|
||||
}
|
||||
/// `stepOn` for the player in place: the host, or a guest swapped in
|
||||
/// (`guest_server_tick`), as a server has no player of its own.
|
||||
pub(super) fn sculk_step_on_player(&mut self) {
|
||||
if let Some(p) = self.player.as_ref()
|
||||
&& p.ground.on_ground
|
||||
{
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
self.sculk_stand_on(vec![(Who::Player, at)]);
|
||||
}
|
||||
}
|
||||
fn sculk_stand_on(&mut self, standing: Vec<(Who, [f64; 3])>) {
|
||||
for (who, at) in standing {
|
||||
// getOnPosLegacy: 0.2 below the feet.
|
||||
let key = (
|
||||
@@ -1108,23 +1117,10 @@ impl Game<'_> {
|
||||
/// in the way (`isUnobstructed`), and no block collision.
|
||||
fn warden_fits(&self, mob: &Mob) -> bool {
|
||||
let bounds = mob.bounds();
|
||||
let player_blocks = !self.spectator()
|
||||
&& self.player.as_ref().is_some_and(|p| {
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
let b = horizon_core::geometry::Aabb::new(
|
||||
horizon_core::geometry::Vec3::new(
|
||||
p.position.x - w,
|
||||
p.position.y,
|
||||
p.position.z - w,
|
||||
),
|
||||
horizon_core::geometry::Vec3::new(
|
||||
p.position.x + w,
|
||||
p.position.y + f64::from(p.dimensions.height),
|
||||
p.position.z + w,
|
||||
),
|
||||
);
|
||||
!p.health.dead_or_dying() && b.intersects(bounds)
|
||||
});
|
||||
let player_blocks = self
|
||||
.level_players()
|
||||
.iter()
|
||||
.any(|p| p.alive && !p.spectator && p.bounds.intersects(bounds));
|
||||
if player_blocks
|
||||
|| self
|
||||
.mobs
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::end::GatewayJob;
|
||||
use super::nether_portal::{PLAYER_DELAY, Plan};
|
||||
use super::respawn_anchor::RespawnConfig;
|
||||
use super::{Dim, Game, lan::LanHost};
|
||||
use horizon_client::{lan::hub::TickCtx, text::Text};
|
||||
use horizon_client::{lan::hub::TickCtx, text::Text, world_spawn::PlayerSpawnFinder};
|
||||
use horizon_core::{geometry::Vec3, position::BlockPos};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
|
||||
@@ -31,6 +31,11 @@ pub(super) struct Trip {
|
||||
/// A respawn at this point outside the Overworld, resolved through its
|
||||
/// block on arrival.
|
||||
respawn: Option<RespawnConfig>,
|
||||
/// A respawn at the world spawn, moved onto a free column within the
|
||||
/// respawn radius once the chunks around it have loaded.
|
||||
world_spawn: bool,
|
||||
/// The search for that column while a candidate's chunk loads.
|
||||
finder: Option<PlayerSpawnFinder>,
|
||||
/// Sent by a command: the player is already where it goes.
|
||||
placed: bool,
|
||||
}
|
||||
@@ -66,10 +71,11 @@ impl Game<'_> {
|
||||
/// in it (Nether portals count up their transition time, End portals
|
||||
/// take them at once).
|
||||
pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) {
|
||||
// Outside a server only the respawns at the world spawn wait for chunks.
|
||||
self.arrive_server_trips(host);
|
||||
if self.options.dedicated.is_none() {
|
||||
return;
|
||||
}
|
||||
self.arrive_server_trips(host);
|
||||
let conns: Vec<u32> = host
|
||||
.hub
|
||||
.guests
|
||||
@@ -253,6 +259,8 @@ impl Game<'_> {
|
||||
plan,
|
||||
gateway: None,
|
||||
respawn: None,
|
||||
world_spawn: false,
|
||||
finder: None,
|
||||
placed: false,
|
||||
});
|
||||
if let Err(e) = self.enter_level(Some(host), source) {
|
||||
@@ -272,6 +280,8 @@ impl Game<'_> {
|
||||
plan: None,
|
||||
gateway: None,
|
||||
respawn: Some(config),
|
||||
world_spawn: false,
|
||||
finder: None,
|
||||
placed: false,
|
||||
});
|
||||
}
|
||||
@@ -304,6 +314,28 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// TeleportTransition.createDefault and missingRespawnBlock: the player
|
||||
/// waits at the world spawn for its chunks, then PlayerSpawnFinder puts
|
||||
/// it on a free column within the respawn radius.
|
||||
pub(super) fn world_spawn_trip(&mut self, conn: u32) {
|
||||
let Some([x, y, z]) = self.level.world_spawn else {
|
||||
return;
|
||||
};
|
||||
self.server_trips.retain(|t| !t.is(conn));
|
||||
self.server_trips.push(Trip {
|
||||
conn,
|
||||
dim: Dim::Overworld,
|
||||
target: Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5),
|
||||
end: false,
|
||||
plan: None,
|
||||
gateway: None,
|
||||
respawn: None,
|
||||
world_spawn: true,
|
||||
finder: None,
|
||||
placed: false,
|
||||
});
|
||||
}
|
||||
|
||||
/// TeleportTransition.missingRespawnBlock: the world spawn, in the
|
||||
/// Overworld.
|
||||
fn respawn_at_world_spawn(&mut self, host: &mut LanHost, conn: u32) {
|
||||
@@ -318,6 +350,7 @@ impl Game<'_> {
|
||||
rotation: None,
|
||||
});
|
||||
self.run_level_teleports(host);
|
||||
self.world_spawn_trip(conn);
|
||||
}
|
||||
|
||||
/// `TheEndGatewayBlockEntity.getPortalPosition` and the teleport within
|
||||
@@ -343,6 +376,8 @@ impl Game<'_> {
|
||||
plan: None,
|
||||
gateway: Some(job),
|
||||
respawn: None,
|
||||
world_spawn: false,
|
||||
finder: None,
|
||||
placed: false,
|
||||
});
|
||||
}
|
||||
@@ -369,7 +404,7 @@ impl Game<'_> {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
let trip = self.server_trips.remove(k);
|
||||
let mut trip = self.server_trips.remove(k);
|
||||
if trip.placed {
|
||||
continue;
|
||||
}
|
||||
@@ -383,6 +418,22 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else if trip.world_spawn {
|
||||
// PlayerSpawnFinder.findSpawn around the world spawn.
|
||||
let suggestion =
|
||||
[trip.target.x, trip.target.y, trip.target.z].map(|v| v.floor() as i32);
|
||||
match self.search_spawn(suggestion, &mut trip.finder) {
|
||||
// The respawn already put the player on this column:
|
||||
// vanilla teleports once, so no second move.
|
||||
Ok(at) if host.hub.guests[i].position == [at.x, at.y, at.z] => continue,
|
||||
Ok(at) => (at, yaw),
|
||||
Err(chunk) => {
|
||||
self.spawn_wait.push(chunk);
|
||||
self.server_trips.insert(k, trip);
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else if let Some(job) = trip.gateway {
|
||||
match self.resolve_gateway(job, trip.target) {
|
||||
Ok(at) => (at, yaw),
|
||||
@@ -392,12 +443,19 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
} else if trip.end {
|
||||
let arrival = match self.as_guest(host, trip.conn, |g| g.end_arrival(trip.target)) {
|
||||
let arrival = match self.as_guest(host, trip.conn, |g| {
|
||||
g.end_arrival(trip.target, &mut trip.finder)
|
||||
}) {
|
||||
Some(arrival) => arrival,
|
||||
None => self.end_arrival(trip.target),
|
||||
None => self.end_arrival(trip.target, &mut trip.finder),
|
||||
};
|
||||
match arrival {
|
||||
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
|
||||
Ok(Some((at, turned))) => (at, turned.unwrap_or(yaw)),
|
||||
Ok(None) => {
|
||||
self.server_trips.insert(k, trip);
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("End arrival: {e}");
|
||||
(trip.target, yaw)
|
||||
@@ -458,6 +516,8 @@ impl Game<'_> {
|
||||
plan: None,
|
||||
gateway: None,
|
||||
respawn: None,
|
||||
world_spawn: false,
|
||||
finder: None,
|
||||
placed: true,
|
||||
});
|
||||
if let Err(e) = self.enter_level(Some(host), source) {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Parrots on a player's shoulder: a tame parrot lands on its owner
|
||||
//! (`LandOnOwnersShoulderGoal`), is kept as the player's `ShoulderEntityLeft`
|
||||
//! or `ShoulderEntityRight`, and flies off again when the player is hurt,
|
||||
//! falls, swims, flies or sleeps (`ServerPlayer.handleShoulderEntities`).
|
||||
use super::Game;
|
||||
use horizon_client::mobs::Species;
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
const KEYS: [&str; 2] = ["ShoulderEntityLeft", "ShoulderEntityRight"];
|
||||
|
||||
/// A shoulder slot holds a parrot when its compound is not empty.
|
||||
fn occupied(extra: &Tag, key: &str) -> bool {
|
||||
matches!(extra.get(key), Some(Tag::Compound(c)) if !c.is_empty())
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `ServerPlayer.setEntityOnShoulder` for a parrot that touched its
|
||||
/// owner: stored in the first free slot, the parrot gone from the world.
|
||||
pub(super) fn parrot_to_shoulder(&mut self, mob: u32) {
|
||||
let Some(i) = self
|
||||
.mobs
|
||||
.iter()
|
||||
.position(|m| m.id == mob && m.alive() && !m.removed && m.species() == Species::Parrot)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
// The acting player must be the saved owner (`getOwner`).
|
||||
if !horizon_client::mobs::tame::owned_by(self.mobs[i].extra.owner, self.acting_uuid()) {
|
||||
return;
|
||||
}
|
||||
if self.riding.is_some()
|
||||
|| !p.ground.on_ground
|
||||
|| p.fluids.was_touching_water
|
||||
|| p.in_powder_snow
|
||||
|| p.flying
|
||||
{
|
||||
return;
|
||||
}
|
||||
let extra = self
|
||||
.level
|
||||
.player_extra
|
||||
.get_or_insert_with(|| Tag::Compound(Default::default()));
|
||||
let Some(key) = KEYS.into_iter().find(|k| !occupied(extra, k)) else {
|
||||
return;
|
||||
};
|
||||
let tag = self.mob_tree_nbt(i);
|
||||
if let Some(Tag::Compound(map)) = self.level.player_extra.as_mut() {
|
||||
map.insert(key.into(), tag);
|
||||
}
|
||||
let (uuid, now) = (self.acting_uuid(), self.world.game_time);
|
||||
self.creatures.shoulder_time.insert(uuid, now);
|
||||
self.mobs[i].removed = true;
|
||||
}
|
||||
|
||||
/// `ServerPlayer.handleShoulderEntities`: the parrots leave the shoulder
|
||||
/// of a player who falls, swims, flies, sleeps, is hurt, dying, a
|
||||
/// spectator or spinning with a riptide.
|
||||
pub(super) fn handle_shoulder_entities(&mut self) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let any = self
|
||||
.level
|
||||
.player_extra
|
||||
.as_ref()
|
||||
.is_some_and(|e| KEYS.iter().any(|k| occupied(e, k)));
|
||||
if any
|
||||
&& (p.fall_distance > 0.5
|
||||
|| p.fluids.was_touching_water
|
||||
|| p.flying
|
||||
|| p.spectator
|
||||
|| p.in_powder_snow
|
||||
|| p.auto_spin_attack_ticks > 0
|
||||
|| p.health.hurt.hurt_time > 0
|
||||
|| p.health.dead_or_dying()
|
||||
|| self.sleeping.is_some())
|
||||
{
|
||||
self.remove_entities_on_shoulder();
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerPlayer.removeEntitiesOnShoulder` (not within a second of the
|
||||
/// landing) and `respawnEntityOnShoulder`: the parrots come back at the
|
||||
/// player, still owned by them.
|
||||
fn remove_entities_on_shoulder(&mut self) {
|
||||
let (uuid, now) = (self.acting_uuid(), self.world.game_time);
|
||||
if self
|
||||
.creatures
|
||||
.shoulder_time
|
||||
.get(&uuid)
|
||||
.is_some_and(|t| t + 20 >= now)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(p) = self.player.as_ref().map(|p| p.position) else {
|
||||
return;
|
||||
};
|
||||
let Some(Tag::Compound(map)) = self.level.player_extra.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let tags: Vec<Tag> = KEYS
|
||||
.iter()
|
||||
.filter_map(|k| map.remove(&(*k).into()))
|
||||
.collect();
|
||||
let pos = [p.x, p.y + f64::from(0.7_f32), p.z];
|
||||
for mut tag in tags {
|
||||
let Tag::Compound(c) = &mut tag else {
|
||||
continue;
|
||||
};
|
||||
if c.is_empty() {
|
||||
continue;
|
||||
}
|
||||
c.insert(
|
||||
"Pos".into(),
|
||||
Tag::List(pos.iter().map(|v| Tag::Double(v.to_bits())).collect()),
|
||||
);
|
||||
c.insert("Owner".into(), Tag::IntArray(uuid.to_vec()));
|
||||
self.load_mob(tag, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,8 @@ use super::Game;
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Species, sniffer},
|
||||
particles::Particle,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
impl Game<'_> {
|
||||
/// The egg item at the parent (`Sniffer.spawnChildFromBreeding`; the
|
||||
@@ -46,15 +45,20 @@ impl Game<'_> {
|
||||
/// block's hit sound between the 1.7th and the 6th second of the
|
||||
/// digging animation) and `playSearchingSound`.
|
||||
pub(super) fn tick_sniffer_effects(&mut self) {
|
||||
let Some(camera) = self.player.as_ref().map(|p| p.position) else {
|
||||
// Vanilla runs these on each client: a sniffer within 32 blocks of
|
||||
// any player in the level (the host and the guests) shows them.
|
||||
let players = self.level_players();
|
||||
if players.is_empty() {
|
||||
return;
|
||||
};
|
||||
}
|
||||
for i in 0..self.mobs.len() {
|
||||
let m = &self.mobs[i];
|
||||
if m.species() != Species::Sniffer
|
||||
|| !m.alive()
|
||||
|| m.silent
|
||||
|| m.position.distance_squared(camera) > 32.0 * 32.0
|
||||
|| !players
|
||||
.iter()
|
||||
.any(|p| m.position.distance_squared(p.position) <= 32.0 * 32.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -79,20 +83,20 @@ impl Game<'_> {
|
||||
}
|
||||
let head = sniffer::head_block(m);
|
||||
let below = self.world.block(head[0], head[1] - 1, head[2]);
|
||||
let Some((sprite, tint)) = self.particle_sprite(below, [head[0], head[1] - 1, head[2]])
|
||||
else {
|
||||
if self
|
||||
.particle_sprite(below, [head[0], head[1] - 1, head[2]])
|
||||
.is_none()
|
||||
{
|
||||
continue;
|
||||
};
|
||||
}
|
||||
let dust = [
|
||||
f64::from(head[0]) + 0.5,
|
||||
f64::from(head[1]) + 0.5 - f64::from(0.65_f32),
|
||||
f64::from(head[2]) + 0.5,
|
||||
];
|
||||
for _ in 0..30 {
|
||||
let particle =
|
||||
Particle::terrain(&mut self.world.random, dust, [0.0; 3], sprite.clone(), tint);
|
||||
self.particles.push(particle);
|
||||
}
|
||||
// Drawn in this window when it has one, and sent to the players
|
||||
// within 32 blocks (the server thread's window is one of them).
|
||||
self.landing_dust(None, below, Vec3::new(dust[0], dust[1], dust[2]), 30, 0.0);
|
||||
if self.mobs[i].age.is_multiple_of(10) {
|
||||
let hit = self.res.facts().get(below).sounds.hit.clone();
|
||||
self.audio.play(&hit, Some(at), 0.5, 0.5);
|
||||
|
||||
@@ -21,10 +21,11 @@ type Pos = (i32, i32, i32);
|
||||
|
||||
/// What a spawner tick decided to add, created once the level is free.
|
||||
pub(super) enum Planned {
|
||||
/// `finalizeSpawn` ran on a fresh mob.
|
||||
Finalized(Mob),
|
||||
/// A mob loaded from the spawn data (with its passengers).
|
||||
Loaded(Tag),
|
||||
/// `finalizeSpawn` ran on a fresh mob; the spawn data's `equipment`.
|
||||
Finalized(Mob, Option<Tag>),
|
||||
/// A mob loaded from the spawn data (with its passengers) and its
|
||||
/// `equipment`.
|
||||
Loaded(Tag, Option<Tag>),
|
||||
}
|
||||
|
||||
/// What the spawner code keeps between ticks.
|
||||
@@ -120,18 +121,24 @@ impl Game<'_> {
|
||||
for (i, plan) in planned.into_iter().enumerate() {
|
||||
let provisional = u32::MAX - i as u32;
|
||||
let id = match plan {
|
||||
Planned::Finalized(mut mob) => {
|
||||
Planned::Finalized(mut mob, equipment) => {
|
||||
self.next_entity += 1;
|
||||
mob.id = self.next_entity;
|
||||
let id = mob.id;
|
||||
self.mobs.push(mob);
|
||||
self.enchant_spawn_equipment(id);
|
||||
self.spawn_jockeys(id, true);
|
||||
Some(id)
|
||||
Some((id, equipment))
|
||||
}
|
||||
Planned::Loaded(tag, equipment) => {
|
||||
self.load_mob(tag, None).map(|id| (id, equipment))
|
||||
}
|
||||
Planned::Loaded(tag) => self.load_mob(tag, None),
|
||||
};
|
||||
if let Some(id) = id {
|
||||
if let Some((id, equipment)) = id {
|
||||
// `nextSpawnData.getEquipment().ifPresent(mob::equip)`.
|
||||
if let Some(table) = equipment {
|
||||
self.equip_from_table(id, &table);
|
||||
}
|
||||
ids.insert(provisional, id);
|
||||
}
|
||||
}
|
||||
@@ -169,7 +176,7 @@ impl Game<'_> {
|
||||
mob.previous_head_yaw = 0.0;
|
||||
}
|
||||
let bounds = mob.bounds();
|
||||
planned.push(Planned::Finalized(mob));
|
||||
planned.push(Planned::Finalized(mob, r.equipment.cloned()));
|
||||
bounds
|
||||
} else {
|
||||
// A UUID already in the level is refused.
|
||||
@@ -197,7 +204,7 @@ impl Game<'_> {
|
||||
let tag = Tag::Compound(tag);
|
||||
let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), 0)?;
|
||||
let bounds = mob.bounds();
|
||||
planned.push(Planned::Loaded(tag));
|
||||
planned.push(Planned::Loaded(tag, r.equipment.cloned()));
|
||||
bounds
|
||||
};
|
||||
l.pending.borrow_mut().push(bounds);
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Spears (`KineticWeapon`): holding the use button charges the spear, and
|
||||
//! from `delay_ticks` on every living entity along the view that the
|
||||
//! player's speed allows is stabbed: the damage grows with the speed
|
||||
//! relative to the target, the knockback and the dismount need the
|
||||
//! attacker's own speed, and each condition runs out after its time
|
||||
//! (`Item.use`, `ItemStack.onUseTick`, `KineticWeapon.damageEntities`,
|
||||
//! `Player.stabAttack`). The hit's feedback (`onKineticHit`) reaches the
|
||||
//! players around as entity event 2.
|
||||
use super::{Game, view_vector};
|
||||
use horizon_client::{
|
||||
collisions::SceneCollisions,
|
||||
items::ItemStack,
|
||||
mobs::Damage,
|
||||
spear::{HIT_FEEDBACK_TICKS, Kinetic, REACH},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
position::BlockPos,
|
||||
};
|
||||
|
||||
/// The key of this window's own player in `Game::kinetic_feedback`.
|
||||
pub(super) const OWN: i32 = i32::MIN;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Item.use` of a kinetic weapon: `startUsingItem` with a new
|
||||
/// `recentKineticEnemies`, and `KineticWeapon.makeSound` at the user.
|
||||
pub(super) fn use_spear(&mut self, stack: &ItemStack) -> bool {
|
||||
let Some(kinetic) = Kinetic::of(&stack.item) else {
|
||||
return false;
|
||||
};
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
let actor = self.lan_acting;
|
||||
self.stabbed.retain(|(who, _), _| *who != actor);
|
||||
if let Some(p) = &self.player {
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
self.audio.play(kinetic.sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `ServerPlayer.getKnownMovement` of the acting player: what they moved
|
||||
/// in the last tick. A guest's comes with their moves.
|
||||
fn known_player_movement(&self) -> Vec3 {
|
||||
if self.lan_acting.is_some() {
|
||||
return self.known_movement;
|
||||
}
|
||||
self.player
|
||||
.as_ref()
|
||||
.map_or(Vec3::ZERO, |p| p.position.subtract(self.previous_position))
|
||||
}
|
||||
|
||||
/// `Entity.getKnownSpeed` of the mob at `index`, per second: its root
|
||||
/// vehicle's (`KineticWeapon.getMotion`).
|
||||
fn mob_speed(&self, index: usize) -> Vec3 {
|
||||
let mut mob = &self.mobs[index];
|
||||
while let Some(vehicle) = mob
|
||||
.extra
|
||||
.mount
|
||||
.and_then(|v| self.mobs.iter().find(|m| m.id == v))
|
||||
{
|
||||
mob = vehicle;
|
||||
}
|
||||
mob.position.subtract(mob.previous).scale(20.0)
|
||||
}
|
||||
|
||||
/// `Level.clip` with COLLIDER shapes and no fluids: where the segment
|
||||
/// first meets a block, if it does (tall grass lets a stab through).
|
||||
fn clip_collider(&self, from: Vec3, to: Vec3) -> Option<Vec3> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if self.res.facts().is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|hit| hit.location)
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// `ProjectileUtil.getHitEntitiesAlong` for the mobs: those whose box the
|
||||
/// segment `from`..`to` meets, or comes within the margin of with no
|
||||
/// block between.
|
||||
fn mobs_along(&self, from: Vec3, to: Vec3, margin: f64) -> Vec<usize> {
|
||||
let grow = Vec3::new(margin, margin, margin);
|
||||
let mut hits = Vec::new();
|
||||
for (i, m) in self.mobs.iter().enumerate() {
|
||||
// PiercingWeapon.canHitEntity: alive, and not the vehicle ridden.
|
||||
if !m.alive() || m.removed || self.riding == Some(m.id) {
|
||||
continue;
|
||||
}
|
||||
let bounds: Aabb = m.bounds();
|
||||
let hit = bounds.contains(from)
|
||||
|| bounds.clip(from, to).is_some()
|
||||
|| (margin > 0.0
|
||||
&& bounds.inflate(grow).clip(from, to).is_some_and(|outside| {
|
||||
let centre = bounds.center();
|
||||
let toward = self.clip_collider(outside, centre).unwrap_or(centre);
|
||||
bounds.clip(outside, toward).is_some()
|
||||
}));
|
||||
if hit {
|
||||
hits.push(i);
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// `KineticWeapon.damageEntities`: one tick of the spear in use, `ticks`
|
||||
/// ticks into the use.
|
||||
pub(super) fn spear_tick(&mut self, stack: &ItemStack, ticks: u32) {
|
||||
let Some(kinetic) = Kinetic::of(&stack.item) else {
|
||||
return;
|
||||
};
|
||||
let used = ticks as i32 - kinetic.delay_ticks;
|
||||
let (Some(eye), Some(feet)) = (
|
||||
self.eye_position(),
|
||||
self.player.as_ref().map(|p| p.position),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if used < 0 || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let eye = Vec3::new(eye[0], eye[1], eye[2]);
|
||||
let look = view_vector(self.yaw, self.pitch);
|
||||
let look = Vec3::new(look[0], look[1], look[2]);
|
||||
let movement = self.known_player_movement();
|
||||
let attacker_speed = look.dot(movement.scale(20.0));
|
||||
// AttackRange.effectiveMinRange and effectiveMaxRange for a player.
|
||||
let (min, max) = if self.creative {
|
||||
(REACH.min_creative, REACH.max_creative)
|
||||
} else {
|
||||
(REACH.min, REACH.max)
|
||||
};
|
||||
let from = eye.add_vector(look.scale(f64::from(min)));
|
||||
let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0)));
|
||||
// A block closer than the minimum reach takes the whole stab.
|
||||
if let Some(block) = self.clip_collider(eye, to) {
|
||||
to = block;
|
||||
if eye.distance_squared(to) < eye.distance_squared(from) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let now = self.world.game_time;
|
||||
let actor = self.lan_acting;
|
||||
let mut affected = false;
|
||||
for i in self.mobs_along(from, to, f64::from(REACH.hitbox_margin)) {
|
||||
let key = (actor, self.mobs[i].id);
|
||||
let recent = self
|
||||
.stabbed
|
||||
.get(&key)
|
||||
.is_some_and(|&t| now - t < i64::from(kinetic.contact_cooldown_ticks));
|
||||
if recent {
|
||||
continue;
|
||||
}
|
||||
self.stabbed.insert(key, now);
|
||||
let target_speed = look.dot(self.mob_speed(i));
|
||||
let relative = (attacker_speed - target_speed).max(0.0);
|
||||
// An entity factor of 1 for a player.
|
||||
let dismounts = kinetic.dismount.test(used, attacker_speed, relative, 1.0);
|
||||
let pushes = kinetic.knockback.test(used, attacker_speed, relative, 1.0);
|
||||
let damages = kinetic.damage.test(used, attacker_speed, relative, 1.0);
|
||||
if dismounts || pushes || damages {
|
||||
// The attack damage attribute's base value (1) and the speed.
|
||||
let amount = 1.0 + (relative * f64::from(kinetic.damage_multiplier)).floor() as f32;
|
||||
affected |= self.stab_mob(i, amount, damages, pushes, dismounts);
|
||||
}
|
||||
}
|
||||
if affected {
|
||||
// Level.broadcastEntityEvent(player, 2), felt by the player too.
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_kinetic_hits.push(actor);
|
||||
}
|
||||
let who = actor.map_or(OWN, |conn| conn as i32);
|
||||
self.kinetic_hit_feedback(who, &kinetic, [feet.x, feet.y, feet.z]);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Player.stabAttack` on the mob at `index`: whether it was affected.
|
||||
fn stab_mob(
|
||||
&mut self,
|
||||
index: usize,
|
||||
base_damage: f32,
|
||||
deals_damage: bool,
|
||||
deals_knockback: bool,
|
||||
dismounts: bool,
|
||||
) -> bool {
|
||||
let kind = format!(
|
||||
"minecraft:{}",
|
||||
self.mobs[index].kind.id.trim_start_matches("minecraft:")
|
||||
);
|
||||
let id = self.mobs[index].id;
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let from = [p.position.x, p.position.y, p.position.z];
|
||||
// The enchantments' share, with no attack strength scaling for a
|
||||
// weapon in use.
|
||||
let magic_boost = self.enchant_damage_bonus(&kind);
|
||||
let total = if deals_damage {
|
||||
base_damage + magic_boost
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let old_health = self.mobs[index].health;
|
||||
let hurt = deals_damage && self.hurt_by_player(index, total, Damage::spear(from));
|
||||
// causeExtraKnockback: a push of 0.4, then the weapon's Knockback.
|
||||
if deals_knockback {
|
||||
let (xd, zd) = self.extra_knockback_direction();
|
||||
self.mobs[index].knockback(0.4, xd, zd);
|
||||
let (strength, _) = self.extra_knockback(&kind, 0.0);
|
||||
self.mobs[index].knockback(f64::from(strength), xd, zd);
|
||||
}
|
||||
let dismounted = dismounts && self.mobs[index].extra.mount.is_some();
|
||||
if dismounted {
|
||||
self.dismount_mob(id);
|
||||
}
|
||||
if !hurt && !deals_knockback && !dismounted {
|
||||
return false;
|
||||
}
|
||||
let mob = &self.mobs[index];
|
||||
let (feet, width, height) = (
|
||||
[mob.position.x, mob.position.y, mob.position.z],
|
||||
mob.kind.width,
|
||||
mob.kind.height,
|
||||
);
|
||||
// attackVisualEffects: no attack sound, the enchantments' magic crit.
|
||||
if magic_boost > 0.0 {
|
||||
self.critical_hit(self.lan_acting, id as i32, feet, width, height, true);
|
||||
}
|
||||
self.combat.last_hurt_mob = Some((id, self.world.game_time));
|
||||
// itemAttackInteraction: hurtEnemy (statistic, wear), and the
|
||||
// post-attack enchantments when the target was hurt.
|
||||
if let Some(stack) = self.held().cloned() {
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
if hurt {
|
||||
self.post_attack(index);
|
||||
}
|
||||
self.weapon_wear(&stack);
|
||||
}
|
||||
// damageStatsAndHearts.
|
||||
let actual = old_health - self.mobs[index].health;
|
||||
self.stats
|
||||
.custom("damage_dealt", (actual * 10.0).round() as i32);
|
||||
if actual > 2.0 {
|
||||
let indicator = horizon_client::particles::ParticleOptions::simple(
|
||||
horizon_client::particles::ParticleType::DamageIndicator,
|
||||
);
|
||||
self.particles.send_particles(
|
||||
&indicator,
|
||||
[feet[0], feet[1] + height * 0.5, feet[2]],
|
||||
[0.1, 0.0, 0.1],
|
||||
0.2,
|
||||
(actual * 0.5) as u32,
|
||||
);
|
||||
}
|
||||
if hurt {
|
||||
self.last_hurt_by_player.insert(id, self.lan_acting);
|
||||
}
|
||||
if let Some(p) = self.player.as_mut()
|
||||
&& !self.creative
|
||||
{
|
||||
p.cause_food_exhaustion(0.1);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `LivingEntity.onKineticHit` for `entity`: the hit feels (the spear
|
||||
/// moves back, `kinetic_hit_ticks`) and sounds, at most once every ten
|
||||
/// ticks.
|
||||
pub(super) fn kinetic_hit_feedback(&mut self, entity: i32, kinetic: &Kinetic, at: [f64; 3]) {
|
||||
let now = self.world.game_time;
|
||||
if self
|
||||
.kinetic_feedback
|
||||
.get(&entity)
|
||||
.is_none_or(|&t| now - t > HIT_FEEDBACK_TICKS)
|
||||
{
|
||||
self.kinetic_feedback.insert(entity, now);
|
||||
self.audio
|
||||
.play_unshared(kinetic.hit_sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `getTicksSinceLastKineticHitFeedback` of this window's player.
|
||||
pub(super) fn kinetic_hit_ticks(&self, partial: f32) -> f32 {
|
||||
self.kinetic_feedback
|
||||
.get(&OWN)
|
||||
.map_or(0.0, |&t| (self.world.game_time - t) as f32 + partial)
|
||||
}
|
||||
|
||||
/// `LivingEntity.handleEntityEvent(2)` on a server's client: the
|
||||
/// player `id` (this one, or another) was hit by the spear it uses.
|
||||
pub(super) fn remote_kinetic_hit(&mut self, id: i32) {
|
||||
let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id);
|
||||
let (item, at) = if own {
|
||||
let item = self
|
||||
.using
|
||||
.and_then(|(slot, _)| self.stack_in(slot))
|
||||
.map(|s| s.item.clone());
|
||||
let at = self.player.as_ref().map(|p| p.position);
|
||||
(item, at)
|
||||
} else {
|
||||
let mob = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id as u32 && m.extra.using_item > 0);
|
||||
let item = mob.and_then(|m| {
|
||||
if m.extra.using_off_hand {
|
||||
m.extra.off_hand.clone()
|
||||
} else {
|
||||
m.extra.main_hand.clone()
|
||||
}
|
||||
});
|
||||
(item, mob.map(|m| m.position))
|
||||
};
|
||||
if let (Some(kinetic), Some(at)) = (item.as_deref().and_then(Kinetic::of), at) {
|
||||
self.kinetic_hit_feedback(if own { OWN } else { id }, &kinetic, [at.x, at.y, at.z]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -163,7 +163,7 @@ impl Game<'_> {
|
||||
let mut spawn = |l: &GameLevel, r: &SpawnerSpawn| {
|
||||
let added = l.game.plan_spawner_mob(l, r, &mut planned)?;
|
||||
let uuid = match planned.last_mut() {
|
||||
Some(Planned::Loaded(Tag::Compound(tag))) => {
|
||||
Some(Planned::Loaded(Tag::Compound(tag), _)) => {
|
||||
let tag_uuid =
|
||||
horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone()));
|
||||
tag_uuid.unwrap_or_else(|| {
|
||||
|
||||
@@ -10,6 +10,7 @@ use horizon_client::{
|
||||
items::ItemStack,
|
||||
mesher::Vertex,
|
||||
mobs::{Damage, DamageKind, Who, anim::Poses},
|
||||
projectiles::ProjectileWorld,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
@@ -33,6 +34,8 @@ pub(super) struct ThrownTrident {
|
||||
pub(super) no_physics: bool,
|
||||
returning: u32,
|
||||
creative_only: bool,
|
||||
/// The entity id a server sent as its owner (the one Loyalty returns it to).
|
||||
pub(super) owner: u32,
|
||||
/// The guest that threw it (`Projectile.getOwner`); `None` for the host.
|
||||
guest: Option<u32>,
|
||||
}
|
||||
@@ -54,13 +57,72 @@ impl ThrownTrident {
|
||||
no_physics: false,
|
||||
returning: 0,
|
||||
creative_only: false,
|
||||
owner: 0,
|
||||
guest: None,
|
||||
}
|
||||
}
|
||||
/// One tick of a server's client: the previous position, then `step`.
|
||||
pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) {
|
||||
/// `ThrownTrident.tick`'s Loyalty return: pulled up and towards the
|
||||
/// owner's eye.
|
||||
fn loyalty_pull(&mut self, owner_eye: Vec3) {
|
||||
let v = Vec3::new(
|
||||
owner_eye.x - self.position.x,
|
||||
owner_eye.y - self.position.y,
|
||||
owner_eye.z - self.position.z,
|
||||
);
|
||||
self.position.y += v.y * 0.015 * f64::from(self.loyalty);
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1e-9);
|
||||
let accel = 0.05 * f64::from(self.loyalty);
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * 0.95 + v.x / len * accel,
|
||||
self.velocity.y * 0.95 + v.y / len * accel,
|
||||
self.velocity.z * 0.95 + v.z / len * accel,
|
||||
);
|
||||
}
|
||||
/// `ThrownTrident.tick` on a server's client: it flies on by itself
|
||||
/// between the server's updates (`AbstractArrow.tick`: gravity and drag,
|
||||
/// a block holds it), and Loyalty pulls it back to its owner; only the
|
||||
/// server decides what it hits.
|
||||
pub(super) fn remote_tick(&mut self, w: &impl ProjectileWorld, owner_eye: Option<Vec3>) {
|
||||
self.previous = self.position;
|
||||
self.position = step(self.position);
|
||||
if self.in_ground_time > 4 {
|
||||
self.dealt_damage = true;
|
||||
}
|
||||
if self.loyalty > 0
|
||||
&& (self.dealt_damage || self.no_physics)
|
||||
&& let Some(eye) = owner_eye
|
||||
{
|
||||
self.no_physics = true;
|
||||
self.in_ground = false;
|
||||
self.loyalty_pull(eye);
|
||||
}
|
||||
if self.in_ground && !self.no_physics {
|
||||
self.in_ground_time += 1;
|
||||
return;
|
||||
}
|
||||
self.in_ground_time = 0;
|
||||
let m = self.velocity;
|
||||
let (x, z) = if self.no_physics {
|
||||
(-m.x, -m.z)
|
||||
} else {
|
||||
(m.x, m.z)
|
||||
};
|
||||
self.yaw = x.atan2(z).to_degrees() as f32;
|
||||
self.pitch = m.y.atan2(m.x.hypot(m.z)).to_degrees() as f32;
|
||||
let to = self.position.add_vector(m);
|
||||
if !self.no_physics
|
||||
&& let Some((at, _, _)) = w.clip(self.position, to)
|
||||
{
|
||||
self.position = at;
|
||||
self.velocity = Vec3::ZERO;
|
||||
self.in_ground = true;
|
||||
return;
|
||||
}
|
||||
self.position = to;
|
||||
// A trident's water inertia (0.99) equals the air drag.
|
||||
self.velocity = self.velocity.scale(0.99);
|
||||
if !self.no_physics {
|
||||
self.velocity.y -= 0.05;
|
||||
}
|
||||
}
|
||||
}
|
||||
const HALF: f64 = 0.25;
|
||||
@@ -244,7 +306,12 @@ impl Game<'_> {
|
||||
if !self.in_water_or_rain() || self.riding.is_some() {
|
||||
return;
|
||||
}
|
||||
self.hurt_held_without_breaking(1);
|
||||
// `hurtWithoutBreaking` and the sound belong to the server; a server's
|
||||
// client only launches.
|
||||
let server_client = self.remote.is_some();
|
||||
if !server_client {
|
||||
self.hurt_held_without_breaking(1);
|
||||
}
|
||||
// trident_spin_attack_strength: 1.5 + 0.75 per level above the first.
|
||||
let strength = 1.5 + 0.75 * (riptide as f32 - 1.0);
|
||||
let d = view_vector(self.yaw, self.pitch);
|
||||
@@ -277,8 +344,14 @@ impl Game<'_> {
|
||||
p.position.y += moved.y;
|
||||
}
|
||||
}
|
||||
let sound = format!("minecraft:item.trident.riptide_{}", riptide.min(3));
|
||||
self.audio.play(&sound, at, 1.0, 1.0);
|
||||
if !server_client {
|
||||
let sound = format!("minecraft:item.trident.riptide_{}", riptide.min(3));
|
||||
self.audio.play(&sound, at, 1.0, 1.0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The server throws the trident.
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
// hurtWithoutBreaking (Unbreaking applies), then the thrown copy.
|
||||
@@ -322,6 +395,7 @@ impl Game<'_> {
|
||||
no_physics: false,
|
||||
returning: 0,
|
||||
creative_only: self.creative,
|
||||
owner: 0,
|
||||
guest: self.lan_acting,
|
||||
});
|
||||
self.player_projectile_shot();
|
||||
@@ -365,19 +439,7 @@ impl Game<'_> {
|
||||
if t.loyalty > 0 && (t.dealt_damage || t.no_physics) {
|
||||
t.no_physics = true;
|
||||
t.in_ground = false;
|
||||
let v = Vec3::new(
|
||||
owner_eye.x - t.position.x,
|
||||
owner_eye.y - t.position.y,
|
||||
owner_eye.z - t.position.z,
|
||||
);
|
||||
t.position.y += v.y * 0.015 * f64::from(t.loyalty);
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1e-9);
|
||||
let accel = 0.05 * f64::from(t.loyalty);
|
||||
t.velocity = Vec3::new(
|
||||
t.velocity.x * 0.95 + v.x / len * accel,
|
||||
t.velocity.y * 0.95 + v.y / len * accel,
|
||||
t.velocity.z * 0.95 + v.z / len * accel,
|
||||
);
|
||||
t.loyalty_pull(owner_eye);
|
||||
if t.returning == 0 {
|
||||
self.audio.play(
|
||||
"minecraft:item.trident.return",
|
||||
|
||||
@@ -71,7 +71,8 @@ impl Game<'_> {
|
||||
/// After a wither skeleton skull is placed: the T of soul sand (or soul
|
||||
/// soil) under three skulls, upright along X or Z, becomes a wither.
|
||||
pub(super) fn check_wither_spawn(&mut self, placed: [i32; 3]) -> horizon_client::Result<()> {
|
||||
if !self.is_wither_skull(placed) {
|
||||
// Nothing is built in Peaceful (`level.getDifficulty() != PEACEFUL`).
|
||||
if self.ui.difficulty == 0 || !self.is_wither_skull(placed) {
|
||||
return Ok(());
|
||||
}
|
||||
// Pattern rows top to bottom: "^^^", "###", "~#~" ('~' air).
|
||||
|
||||
@@ -3587,7 +3587,7 @@ impl Renderer {
|
||||
if self.animated_textures {
|
||||
self.animate(&mut encoder, frame.ticks);
|
||||
self.hud
|
||||
.animate_fire(&mut self.uploads, &mut encoder, frame.ticks);
|
||||
.animate_sprites(&mut self.uploads, &mut encoder, frame.ticks);
|
||||
}
|
||||
self.update_lightmap(
|
||||
&mut encoder,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! textures, and a batch of textured quads in GUI pixels (vanilla's automatic
|
||||
//! GUI scale is applied when drawing).
|
||||
use crate::Result;
|
||||
use horizon_assets::animation::AnimationMetadata;
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
fs,
|
||||
@@ -64,7 +65,10 @@ pub struct HudAtlas {
|
||||
/// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others
|
||||
/// sample as vanilla's defaults (nearest, repeat).
|
||||
pub flags: HashMap<String, TextureFlags>,
|
||||
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>,
|
||||
/// Every animated block or item sprite the atlas packs: its atlas rect
|
||||
/// and the mcmeta-driven frame list, re-uploaded into the rect as the
|
||||
/// frames turn (vanilla's stitched atlas animates all of these).
|
||||
pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>,
|
||||
/// The default font (bitmap sheets in this atlas, unifont rasterized on demand).
|
||||
pub font: crate::font::Font,
|
||||
/// `misc/enchanted_glint_item` as its own image: vanilla's `GlintSampler`
|
||||
@@ -147,6 +151,21 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
/// A packed atlas image: sprite name, size and RGBA pixels.
|
||||
type PackedImage = (String, u32, u32, Vec<u8>);
|
||||
/// A frame of an animated strip at `x, y`, nearest-resampled to the longer
|
||||
/// side of the frame: array layers are square, as `Sprites::load` keeps them
|
||||
/// for the world's sprite arrays.
|
||||
fn strip_frame(pixels: &[u8], stride: u32, x: u32, y: u32, w: u32, h: u32) -> Vec<u8> {
|
||||
let side = w.max(h);
|
||||
let mut out = Vec::with_capacity((side * side * 4) as usize);
|
||||
for row in 0..side {
|
||||
let source_row = y + row * h / side;
|
||||
for column in 0..side {
|
||||
let at = ((source_row * stride + x + column * w / side) * 4) as usize;
|
||||
out.extend_from_slice(&pixels[at..at + 4]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `image` inside a one-texel border copied from its opposite edges, the
|
||||
/// texels repeat addressing reads past each edge.
|
||||
fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage {
|
||||
@@ -378,7 +397,7 @@ impl HudAtlas {
|
||||
let s = p.to_string_lossy();
|
||||
!s.contains("title/background") && !s.contains("realms") && !s.contains("presets")
|
||||
});
|
||||
type Decoded = (PackedImage, Option<TextureFlags>, Option<(u32, u32)>);
|
||||
type Decoded = (PackedImage, Option<TextureFlags>, Option<(u32, u32)>, bool);
|
||||
let decode_one = |path: &PathBuf| -> Option<Decoded> {
|
||||
let name = path
|
||||
.strip_prefix(&textures)
|
||||
@@ -386,12 +405,35 @@ impl HudAtlas {
|
||||
.with_extension("")
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let (w, mut h, pixels) = decode(path).ok()?;
|
||||
// Animated strips keep their first frame.
|
||||
let (mut w, mut h, pixels) = decode(path).ok()?;
|
||||
let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok();
|
||||
let animation = mcmeta
|
||||
.as_deref()
|
||||
.and_then(|json| serde_json::from_str::<serde_json::Value>(json).ok())
|
||||
.and_then(|meta| {
|
||||
meta.get("animation")
|
||||
.and_then(|section| AnimationMetadata::from_json(§ion.to_string()).ok())
|
||||
});
|
||||
// An animated strip keeps its first frame: the region the mcmeta's
|
||||
// frame size picks (`AnimationMetadataSection.frameSize`), which is
|
||||
// the top-left square unless it names other dimensions or the
|
||||
// frames run along a row.
|
||||
let frames = name.starts_with("block/") || name.starts_with("item/");
|
||||
let pixels = if frames && h > w {
|
||||
h = w;
|
||||
pixels[..(w * w * 4) as usize].to_vec()
|
||||
let pixels = if frames {
|
||||
let stride = w;
|
||||
let [fw, fh] = animation.as_ref().map_or([w.min(h) as i32; 2], |meta| {
|
||||
meta.frame_size(w as i32, h as i32)
|
||||
});
|
||||
match (u32::try_from(fw), u32::try_from(fh)) {
|
||||
(Ok(fw), Ok(fh))
|
||||
if fw > 0 && fh > 0 && w % fw == 0 && h % fh == 0 && (fw, fh) != (w, h) =>
|
||||
{
|
||||
let side = fw.max(fh);
|
||||
(w, h) = (side, side);
|
||||
strip_frame(&pixels, stride, 0, 0, fw, fh)
|
||||
}
|
||||
_ => pixels,
|
||||
}
|
||||
} else {
|
||||
pixels
|
||||
};
|
||||
@@ -399,16 +441,19 @@ impl HudAtlas {
|
||||
let gui_size = default_textures
|
||||
.as_ref()
|
||||
.and_then(|d| png_size(&d.join(format!("{name}.png"))))
|
||||
.map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh }))
|
||||
.map(|(dw, dh)| {
|
||||
let side = dw.min(dh);
|
||||
if frames { (side, side) } else { (dw, dh) }
|
||||
})
|
||||
.filter(|&size| size != (w, h));
|
||||
let flags = fs::read_to_string(path.with_extension("png.mcmeta"))
|
||||
.ok()
|
||||
.and_then(|json| TextureFlags::from_mcmeta(&json));
|
||||
let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta);
|
||||
let animated = frames && animation.is_some();
|
||||
let (gw, gh) = gui_size.unwrap_or((w, h));
|
||||
(gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some((
|
||||
(name, w, h, pixels),
|
||||
flags,
|
||||
gui_size,
|
||||
animated,
|
||||
))
|
||||
};
|
||||
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
|
||||
@@ -427,14 +472,18 @@ impl HudAtlas {
|
||||
});
|
||||
let mut flags = HashMap::new();
|
||||
let mut gui_sizes = HashMap::new();
|
||||
let mut animated: Vec<String> = Vec::new();
|
||||
let mut images: Vec<PackedImage> = Vec::with_capacity(decoded.len());
|
||||
for (image, image_flags, gui_size) in decoded {
|
||||
for (image, image_flags, gui_size, is_animated) in decoded {
|
||||
if let Some(f) = image_flags {
|
||||
flags.insert(image.0.clone(), f);
|
||||
}
|
||||
if let Some(size) = gui_size {
|
||||
gui_sizes.insert(image.0.clone(), size);
|
||||
}
|
||||
if is_animated {
|
||||
animated.push(image.0.clone());
|
||||
}
|
||||
images.push(image);
|
||||
}
|
||||
if full {
|
||||
@@ -500,35 +549,32 @@ impl HudAtlas {
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut fire_sprites = crate::sprites::Sprites::default();
|
||||
let mut fire_animations = Vec::new();
|
||||
for name in [
|
||||
"block/fire_0",
|
||||
"block/fire_1",
|
||||
"block/soul_fire_0",
|
||||
"block/soul_fire_1",
|
||||
] {
|
||||
if let Some(rect) = sprites.get(name).copied() {
|
||||
let layer = fire_sprites.insert(root, &format!("minecraft:{name}"))?;
|
||||
if let Some(animation) = fire_sprites
|
||||
.animations
|
||||
.iter()
|
||||
.find(|a| a.layer == layer)
|
||||
.cloned()
|
||||
{
|
||||
let (tw, th) = rect.texels((width, height));
|
||||
let image = animation.resized_pixels(animation.frame(0), tw, th);
|
||||
let x = (rect.u0 * width as f32).round() as usize;
|
||||
let y = (rect.v0 * height as f32).round() as usize;
|
||||
let row_bytes = tw as usize * 4;
|
||||
for row in 0..th as usize {
|
||||
let dst = ((y + row) * width as usize + x) * 4;
|
||||
let src = row * row_bytes;
|
||||
pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]);
|
||||
}
|
||||
fire_animations.push((rect, animation));
|
||||
}
|
||||
// Every animated sprite animates: the packed strip is the raw first
|
||||
// frame, while the mcmeta's frame list may start anywhere, so each
|
||||
// animation's frame(0) overwrites its atlas rect before drawing.
|
||||
let mut loaded = crate::sprites::Sprites::default();
|
||||
let mut sprite_animations = Vec::new();
|
||||
animated.sort();
|
||||
for name in animated {
|
||||
let Some(rect) = sprites.get(&name).copied() else {
|
||||
continue;
|
||||
};
|
||||
let layer = loaded.insert(root, &format!("minecraft:{name}"))?;
|
||||
let Some(animation) = loaded.animations.iter().find(|a| a.layer == layer).cloned()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (tw, th) = rect.texels((width, height));
|
||||
let image = animation.resized_pixels(animation.frame(0), tw, th);
|
||||
let x = (rect.u0 * width as f32).round() as usize;
|
||||
let y = (rect.v0 * height as f32).round() as usize;
|
||||
let row_bytes = tw as usize * 4;
|
||||
for row in 0..th as usize {
|
||||
let dst = ((y + row) * width as usize + x) * 4;
|
||||
let src = row * row_bytes;
|
||||
pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]);
|
||||
}
|
||||
sprite_animations.push((rect, animation));
|
||||
}
|
||||
let white = sprites["horizon/white"];
|
||||
let glint = Self::glint_texture(root, defaults, "enchanted_glint_item");
|
||||
@@ -548,7 +594,7 @@ impl HudAtlas {
|
||||
sprites,
|
||||
translucent,
|
||||
flags,
|
||||
fire_animations,
|
||||
sprite_animations,
|
||||
glint,
|
||||
glint_armor,
|
||||
font,
|
||||
@@ -1082,7 +1128,7 @@ impl HudUniform {
|
||||
}
|
||||
}
|
||||
pub struct HudRenderer {
|
||||
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>,
|
||||
pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation, (usize, usize, u32))>,
|
||||
/// The shared atlas texture, for run-time glyph uploads.
|
||||
pub atlas_texture: Option<wgpu::Texture>,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
@@ -1311,7 +1357,7 @@ impl HudRenderer {
|
||||
});
|
||||
Ok(Self {
|
||||
atlas_texture: None,
|
||||
fire_animations: Vec::new(),
|
||||
sprite_animations: Vec::new(),
|
||||
pipeline,
|
||||
invert_pipeline,
|
||||
additive_pipeline,
|
||||
@@ -1324,7 +1370,7 @@ impl HudRenderer {
|
||||
capacity,
|
||||
})
|
||||
}
|
||||
pub fn animate_fire(
|
||||
pub fn animate_sprites(
|
||||
&mut self,
|
||||
uploads: &mut crate::gfx::upload::Uploads,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
@@ -1333,13 +1379,31 @@ impl HudRenderer {
|
||||
let Some(texture) = &self.atlas_texture else {
|
||||
return;
|
||||
};
|
||||
for (rect, animation, previous) in &mut self.fire_animations {
|
||||
let frame = animation.frame(tick);
|
||||
if frame == *previous {
|
||||
for (rect, animation, previous) in &mut self.sprite_animations {
|
||||
// `SpriteContents.AnimationState`: the frame from the mcmeta's
|
||||
// list, blended into the next one by the sub-frame's thousandths
|
||||
// when the sprite interpolates.
|
||||
let blend = animation.blend(tick);
|
||||
let state = (blend.frame, blend.next, blend.millis);
|
||||
if state == *previous {
|
||||
continue;
|
||||
}
|
||||
let (w, h) = rect.texels((texture.width(), texture.height()));
|
||||
let pixels = animation.resized_pixels(frame, w, h);
|
||||
let pixels = if blend.millis == 0 {
|
||||
animation.resized_pixels(blend.frame, w, h)
|
||||
} else {
|
||||
let current = animation.resized_pixels(blend.frame, w, h);
|
||||
let next = animation.resized_pixels(blend.next, w, h);
|
||||
let millis = blend.millis;
|
||||
current
|
||||
.iter()
|
||||
.zip(next)
|
||||
.map(|(&a, b)| {
|
||||
((u32::from(a) * (1000 - millis) + u32::from(b) * millis + 500) / 1000)
|
||||
as u8
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
uploads.texture(
|
||||
encoder,
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
@@ -1356,7 +1420,7 @@ impl HudRenderer {
|
||||
h,
|
||||
&pixels,
|
||||
);
|
||||
*previous = frame;
|
||||
*previous = state;
|
||||
}
|
||||
}
|
||||
/// Stage the batch's atlas patches, vertices and uniform: before the
|
||||
@@ -1522,6 +1586,80 @@ impl HudRenderer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Write a PNG `width x height` whose `frames` stacked rows are solid
|
||||
/// colours, then its mcmeta beside it.
|
||||
fn write_strip(path: &Path, width: u32, height: u32, frames: &[[u8; 4]], mcmeta: Option<&str>) {
|
||||
let file = std::io::BufWriter::new(fs::File::create(path).unwrap());
|
||||
let mut encoder = png::Encoder::new(file, width, height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder.write_header().unwrap();
|
||||
let mut pixels = Vec::with_capacity((width * height * 4) as usize);
|
||||
for frame in frames {
|
||||
let rows = height / frames.len() as u32;
|
||||
pixels.extend((0..width * rows).flat_map(|_| *frame));
|
||||
}
|
||||
writer.write_image_data(&pixels).unwrap();
|
||||
writer.finish().unwrap();
|
||||
if let Some(mcmeta) = mcmeta {
|
||||
let meta = path.with_extension("png.mcmeta");
|
||||
fs::write(meta, mcmeta).unwrap();
|
||||
}
|
||||
}
|
||||
/// A resource root holding one animated block texture: a strip of two
|
||||
/// 16x16 frames, red then blue, whose mcmeta starts on the blue one.
|
||||
fn animated_root() -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("horizon-atlas-anim-{}", std::process::id()));
|
||||
let block = root.join("assets/minecraft/textures/block");
|
||||
fs::create_dir_all(&block).unwrap();
|
||||
write_strip(
|
||||
&block.join("test_anim.png"),
|
||||
16,
|
||||
32,
|
||||
&[[255, 0, 0, 255], [0, 0, 255, 255]],
|
||||
Some(r#"{"animation": {"frames": [1, 0]}}"#),
|
||||
);
|
||||
root
|
||||
}
|
||||
fn texel_at(atlas: &HudAtlas, rect: Rect, x: u32, y: u32) -> [u8; 4] {
|
||||
let px = (rect.u0 * atlas.width as f32).round() as u32 + x;
|
||||
let py = (rect.v0 * atlas.height as f32).round() as u32 + y;
|
||||
let at = ((py * atlas.width + px) * 4) as usize;
|
||||
atlas.pixels[at..at + 4].try_into().unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn animated_block_sprites_register_and_pack_their_first_mcmeta_frame() {
|
||||
let root = animated_root();
|
||||
let atlas = HudAtlas::build(&root).unwrap();
|
||||
let (rect, animation) = atlas
|
||||
.sprite_animations
|
||||
.iter()
|
||||
.find(|(_, animation)| animation.frame_count() == 2)
|
||||
.expect("the animated block sprite");
|
||||
// The mcmeta's list starts on the strip's second (blue) frame.
|
||||
assert_eq!(animation.frame(0), 1);
|
||||
assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16));
|
||||
assert_eq!(texel_at(&atlas, *rect, 0, 0), [0, 0, 255, 255]);
|
||||
assert_eq!(texel_at(&atlas, *rect, 15, 15), [0, 0, 255, 255]);
|
||||
}
|
||||
#[test]
|
||||
fn a_strip_frames_size_comes_from_its_mcmeta() {
|
||||
let root = animated_root();
|
||||
let block = root.join("assets/minecraft/textures/block");
|
||||
// A row of two frames with the animation's own frame size.
|
||||
write_strip(
|
||||
&block.join("test_row.png"),
|
||||
32,
|
||||
16,
|
||||
&[[0, 255, 0, 255], [255, 255, 0, 255]],
|
||||
Some(r#"{"animation": {"width": 16, "height": 16}}"#),
|
||||
);
|
||||
let atlas = HudAtlas::build(&root).unwrap();
|
||||
let rect = atlas.sprites["block/test_row"];
|
||||
// The first frame is the left 16x16, not the whole row.
|
||||
assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16));
|
||||
assert_eq!(texel_at(&atlas, rect, 0, 0), [0, 255, 0, 255]);
|
||||
}
|
||||
/// `count` images of `w x h`; layout reads only their sizes.
|
||||
fn sized(count: usize, w: u32, h: u32) -> Vec<PackedImage> {
|
||||
(0..count)
|
||||
|
||||
@@ -490,6 +490,11 @@ pub struct HealthHud {
|
||||
/// above them.
|
||||
pub left_height: i32,
|
||||
pub right_height: i32,
|
||||
/// `Hud.lastBubblePopSoundPlayed`.
|
||||
pub last_bubble_pop_sound: i32,
|
||||
/// The `ui.hud.bubble_pop` volume and pitch `playAirBubblePoppedSound`
|
||||
/// asked for this frame; the caller plays it and clears it.
|
||||
pub bubble_pop_sound: Option<(f32, f32)>,
|
||||
}
|
||||
|
||||
pub struct HealthInputs {
|
||||
@@ -761,12 +766,22 @@ impl HealthHud {
|
||||
let popping = bubble(0);
|
||||
let delay = i32::from(air != 0 && i.under_water);
|
||||
let empty = 10 - bubble(delay);
|
||||
if !i.under_water {
|
||||
self.last_bubble_pop_sound = 0;
|
||||
}
|
||||
for b in 1..=10 {
|
||||
let x = x_right - (b - 1) * 8 - 9;
|
||||
if b <= full {
|
||||
out.push(sprite("hud/air", x, y, 9, 9));
|
||||
} else if full != popping && b == popping && i.under_water {
|
||||
out.push(sprite("hud/air_bursting", x, y, 9, 9));
|
||||
// Hud.playAirBubblePoppedSound.
|
||||
if self.last_bubble_pop_sound != b {
|
||||
let volume = 0.5 + 0.1 * (empty - 3 + 1).max(0) as f32;
|
||||
let pitch = 1.0 + 0.1 * (empty - 5 + 1).max(0) as f32;
|
||||
self.bubble_pop_sound = Some((volume, pitch));
|
||||
self.last_bubble_pop_sound = b;
|
||||
}
|
||||
} else if b > 10 - empty {
|
||||
let wobble = if empty == 10 && i.tick % 2 == 0 {
|
||||
next(2)
|
||||
|
||||
@@ -439,6 +439,11 @@ fn template_from(tag: &Tag) -> Option<ItemStack> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The stack a `show_item` hover event holds (`HoverEvent.ShowItem`): its
|
||||
/// `{id, count?, components?}` object.
|
||||
pub fn stack_from_hover(event: &serde_json::Value) -> Option<ItemStack> {
|
||||
template_from(&crate::scoreboard::json_to_tag(event))
|
||||
}
|
||||
/// Sorted-key, type-annotated text of a tag (the differential harnesses
|
||||
/// print the same form from the vanilla side).
|
||||
pub fn canon_tag(tag: &Tag) -> String {
|
||||
|
||||
@@ -12,7 +12,7 @@ mod special;
|
||||
use crate::{
|
||||
block_entity_render::{ModelPart, diffuse},
|
||||
hud::Rect,
|
||||
mesher::Vertex,
|
||||
mesher::{CULL_BACK, Vertex},
|
||||
};
|
||||
use glam::{Mat3, Mat4, Vec3};
|
||||
use horizon_assets::{
|
||||
@@ -49,6 +49,8 @@ pub struct ItemQuad {
|
||||
pub foil: Foil,
|
||||
/// `MaterialInfo.lightEmission` (block light floor).
|
||||
pub light_emission: u8,
|
||||
/// The render type culls back faces (`entitySolid`): world drawing discards them.
|
||||
pub cull_back: bool,
|
||||
/// The quad's sprite has translucent pixels (`MaterialInfo.itemRenderType`
|
||||
/// is a translucent sheet): drawn with the translucent entities.
|
||||
pub translucent: bool,
|
||||
@@ -307,6 +309,7 @@ fn submit_quads(
|
||||
color: argb(color),
|
||||
foil,
|
||||
light_emission: q.light_emission,
|
||||
cull_back: false,
|
||||
translucent: translucent || q.material.force_translucent,
|
||||
});
|
||||
}
|
||||
@@ -787,7 +790,7 @@ impl ItemSink for WorldSink<'_> {
|
||||
for (i, (p, uv)) in q.pos.iter().zip(q.uv).enumerate() {
|
||||
let glint_uv = glint.map_or([0.0, 0.0], |glint| glint.uv(q.foil_uv[i]));
|
||||
self.out.push(Vertex {
|
||||
normal: [0; 4],
|
||||
normal: if q.cull_back { CULL_BACK } else { [0; 4] },
|
||||
pos: p.to_array(),
|
||||
uv,
|
||||
layer: overlay,
|
||||
|
||||
@@ -377,6 +377,7 @@ mod tests {
|
||||
color,
|
||||
foil: Foil::None,
|
||||
light_emission: 0,
|
||||
cull_back: false,
|
||||
translucent: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,17 @@ pub(super) fn load_parts(root: &Path) -> HashMap<String, ModelPart> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Marks every quad passed on as drawn with a back-face-culling render type (`entitySolid`).
|
||||
struct CullBack<'a>(&'a mut dyn ItemSink);
|
||||
impl ItemSink for CullBack<'_> {
|
||||
fn quad(&mut self, quad: ItemQuad) {
|
||||
self.0.quad(ItemQuad {
|
||||
cull_back: true,
|
||||
..quad
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A pose override for a named part (`setupAnim`).
|
||||
type Adjust<'a> = &'a dyn Fn(&str, &mut [f32; 9]);
|
||||
fn none(_: &str, _: &mut [f32; 9]) {}
|
||||
@@ -120,6 +131,7 @@ fn draw(
|
||||
color,
|
||||
foil,
|
||||
light_emission: 0,
|
||||
cull_back: false,
|
||||
translucent: false,
|
||||
});
|
||||
}
|
||||
@@ -571,6 +583,8 @@ pub(super) fn submit(
|
||||
}
|
||||
SpecialKind::DecoratedPot => {
|
||||
let sides = pot_sides(argument);
|
||||
// `DecoratedPotRenderer` draws every part with `entitySolid`.
|
||||
let sink = &mut CullBack(sink);
|
||||
if let Some(base) = renderer.part("decorated_pot_base")
|
||||
&& let Some(r) = sprites
|
||||
.get("entity/decorated_pot/decorated_pot_base")
|
||||
@@ -674,4 +688,51 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `DecoratedPotRenderer` draws every part with `RenderTypes.entitySolid`,
|
||||
/// whose pipeline culls back faces: the pot's flat `top` and `bottom`
|
||||
/// planes would otherwise show both sides and z-fight in the hand too.
|
||||
#[test]
|
||||
fn the_decorated_pot_item_culls_its_back_faces() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("entity-models.json").exists() {
|
||||
return;
|
||||
}
|
||||
let renderer = ItemRenderer::load(&root).unwrap();
|
||||
let sprite = Rect {
|
||||
u0: 0.25,
|
||||
v0: 0.125,
|
||||
u1: 0.375,
|
||||
v1: 0.25,
|
||||
w: 16,
|
||||
h: 16,
|
||||
};
|
||||
let sprites: HashMap<String, Rect> = [
|
||||
"entity/decorated_pot/decorated_pot_base",
|
||||
"entity/decorated_pot/decorated_pot_side",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|name| (name.to_owned(), sprite))
|
||||
.collect();
|
||||
let model = SpecialModel {
|
||||
kind: SpecialKind::DecoratedPot,
|
||||
};
|
||||
let mut quads: Vec<ItemQuad> = Vec::new();
|
||||
submit(
|
||||
&renderer,
|
||||
&model,
|
||||
&Value::Null,
|
||||
false,
|
||||
Mat4::IDENTITY,
|
||||
&sprites,
|
||||
&super::super::NoHost,
|
||||
&mut quads,
|
||||
);
|
||||
assert!(!quads.is_empty(), "the pot item draws its parts");
|
||||
assert!(
|
||||
quads.iter().all(|q| q.cull_back),
|
||||
"entitySolid culls the pot's back faces"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +215,7 @@ pub struct Guest {
|
||||
/// last sent about itself.
|
||||
pub sent_shared: i8,
|
||||
/// Where the player last died (Player.lastDeathLocation), sent with the respawn.
|
||||
pub last_death: Option<[i32; 3]>,
|
||||
pub last_death: Option<(String, [i32; 3])>,
|
||||
/// The last action sequence to acknowledge at the next tick (-1: none).
|
||||
pub ack_up_to: std::cell::Cell<i32>,
|
||||
pub sent_selected: usize,
|
||||
|
||||
@@ -199,6 +199,9 @@ pub struct Hub {
|
||||
pub ops: std::collections::HashMap<u128, u8>,
|
||||
/// `entity-broadcast-range-percentage` (dedicated servers).
|
||||
pub entity_range_percent: i32,
|
||||
/// `spawn-protection` (dedicated servers): the radius around the world
|
||||
/// spawn that only operators may change.
|
||||
pub spawn_protection: i32,
|
||||
chat_type: i32,
|
||||
dimension_type: i32,
|
||||
clock_ids: Vec<i32>,
|
||||
@@ -369,6 +372,7 @@ impl Hub {
|
||||
stepping: 0,
|
||||
ops: Default::default(),
|
||||
entity_range_percent: 100,
|
||||
spawn_protection: 0,
|
||||
weather: (false, 0.0, 0.0),
|
||||
level_sync: Default::default(),
|
||||
chat_type,
|
||||
@@ -489,6 +493,13 @@ impl Hub {
|
||||
overlay: false,
|
||||
}));
|
||||
}
|
||||
/// `ServerPlayer.sendOverlayMessage` to every guest (the action bar).
|
||||
pub fn overlay_message(&self, content: Tag) {
|
||||
self.broadcast(&C::SystemChat(play::SystemChat {
|
||||
content,
|
||||
overlay: true,
|
||||
}));
|
||||
}
|
||||
/// A chat message from the host (a disguised chat: the host has no
|
||||
/// connection to sign with).
|
||||
pub fn chat(&self, sender: &str, text: &str) {
|
||||
@@ -606,16 +617,24 @@ impl Hub {
|
||||
|
||||
// ---- joining -------------------------------------------------------
|
||||
|
||||
fn spawn_info(&self, game_mode: i32) -> play::SpawnInfo {
|
||||
fn spawn_info(&self, i: usize) -> play::SpawnInfo {
|
||||
let g = &self.guests[i];
|
||||
play::SpawnInfo {
|
||||
dimension_type: self.dimension_type,
|
||||
dimension: self.config.dimension.clone(),
|
||||
seed: horizon_core::biome::obfuscate_seed(self.config.seed),
|
||||
game_type: game_mode,
|
||||
game_type: g.game_mode,
|
||||
previous_game_type: None,
|
||||
debug: false,
|
||||
flat: self.flat_world,
|
||||
last_death: None,
|
||||
// Player.getLastDeathLocation.
|
||||
last_death: g
|
||||
.last_death
|
||||
.as_ref()
|
||||
.map(|(dimension, pos)| play::GlobalPos {
|
||||
dimension: dimension.clone(),
|
||||
pos: *pos,
|
||||
}),
|
||||
portal_cooldown: 0,
|
||||
sea_level: 63,
|
||||
}
|
||||
@@ -684,7 +703,7 @@ impl Hub {
|
||||
reduced_debug_info: false,
|
||||
show_death_screen: !self.immediate_respawn,
|
||||
limited_crafting: false,
|
||||
spawn: self.spawn_info(mode),
|
||||
spawn: self.spawn_info(i),
|
||||
// MinecraftServer.usesAuthentication, enforceSecureProfile.
|
||||
online_mode: self.lan.shared.config.online.is_some(),
|
||||
enforces_secure_chat: self.enforces_secure_chat(),
|
||||
@@ -2520,14 +2539,7 @@ impl Hub {
|
||||
/// level loading screen from the Respawn packet until the level info's "level chunks load
|
||||
/// start" event and the chunk under the player, so the packets follow vanilla's order.
|
||||
pub fn respawn(&mut self, i: usize, at: [f64; 3], ctx: &TickCtx) {
|
||||
let mode = self.guests[i].game_mode;
|
||||
let mut info = self.spawn_info(mode);
|
||||
// Player.getLastDeathLocation, set where the player died.
|
||||
// The level they died in: theirs until now.
|
||||
info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos {
|
||||
dimension: self.guests[i].dimension.clone(),
|
||||
pos,
|
||||
});
|
||||
let info = self.spawn_info(i);
|
||||
self.close_container_for(i);
|
||||
let g = &mut self.guests[i];
|
||||
// PlayerList.respawn: into the level in place (the respawn level).
|
||||
@@ -2640,8 +2652,7 @@ impl Hub {
|
||||
portal_sound: bool,
|
||||
ctx: &TickCtx,
|
||||
) {
|
||||
let mode = self.guests[i].game_mode;
|
||||
let info = self.spawn_info(mode);
|
||||
let info = self.spawn_info(i);
|
||||
self.close_container_for(i);
|
||||
let g = &mut self.guests[i];
|
||||
g.dimension = self.config.dimension.clone();
|
||||
@@ -2738,7 +2749,7 @@ fn ticking_state(rate: f32, frozen: bool) -> C {
|
||||
}
|
||||
|
||||
/// What the others see of a guest's body, from its server-side state.
|
||||
fn guest_body(g: &Guest) -> BodyFlags {
|
||||
pub fn guest_body(g: &Guest) -> BodyFlags {
|
||||
let m = g.motion.as_deref();
|
||||
BodyFlags {
|
||||
gliding: g.fall_flying,
|
||||
|
||||
@@ -86,6 +86,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
guest.respawn_elsewhere = level.respawn_elsewhere.clone();
|
||||
guest.saved = level.player_extra.clone();
|
||||
guest.seen_credits = level.seen_credits;
|
||||
guest.last_death = level.last_death.clone();
|
||||
let extra = level.player_extra.as_ref();
|
||||
let short = |key: &str, default: i64| {
|
||||
extra
|
||||
@@ -168,6 +169,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
|
||||
level.respawn_elsewhere = guest.respawn_elsewhere.clone();
|
||||
level.on_ground = guest.on_ground;
|
||||
level.seen_credits = guest.seen_credits;
|
||||
level.last_death = guest.last_death.clone();
|
||||
level.player_extra = guest.saved.clone();
|
||||
// The live body's fire, air and fall distance (Entity.saveWithoutId),
|
||||
// or what the file had while the player has no body yet.
|
||||
|
||||
@@ -169,6 +169,7 @@ pub mod skins;
|
||||
pub mod sound_engine;
|
||||
pub mod sound_events;
|
||||
pub mod spans;
|
||||
pub mod spear;
|
||||
pub mod sprint;
|
||||
pub mod sprites;
|
||||
pub mod stations;
|
||||
|
||||
@@ -36,11 +36,15 @@ pub struct Vertex {
|
||||
pub color: u32,
|
||||
/// Smooth light, 16x fixed point: sky in bits 0..8, block in bits 8..16.
|
||||
pub light: u32,
|
||||
/// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour.
|
||||
/// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour,
|
||||
/// [`CULL_BACK`] to keep it and also drop back-facing pixels.
|
||||
pub normal: [i8; 4],
|
||||
/// The `GLINT_TEXTURING` atlas UV for a foil item quad; zero elsewhere.
|
||||
pub glint_uv: [f32; 2],
|
||||
}
|
||||
/// `Vertex::normal` of a baked-colour quad of an `entitySolid` model: the render type culls
|
||||
/// back faces, which the entity pipelines here do not, so `entity.wgsl` discards them.
|
||||
pub const CULL_BACK: [i8; 4] = [0, 0, 0, 1];
|
||||
/// A section vertex: vanilla's `DefaultVertexFormat.BLOCK` (position, colour,
|
||||
/// UV0, UV2) with the sprite's array layer beside the light, in 24 bytes
|
||||
/// rather than vanilla's 28: the UV is fixed point, which holds model UVs
|
||||
@@ -57,7 +61,7 @@ pub struct TerrainVertex {
|
||||
/// UV within the sprite, `UV_STEPS` per unit (`TerrainVertex::new`,
|
||||
/// `terrain.wgsl`'s `terrain_uv`).
|
||||
pub(crate) uv: [u16; 2],
|
||||
/// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves.
|
||||
/// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves and quads over opaque texels.
|
||||
pub layer: u16,
|
||||
/// Smooth light, 16x fixed point: sky in the low byte, block in the high one.
|
||||
pub light: u16,
|
||||
@@ -892,8 +896,9 @@ impl Mesher<'_> {
|
||||
target.push(TerrainVertex::new(
|
||||
[p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]],
|
||||
q.uv[i],
|
||||
// Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout.
|
||||
if !self.cutout_leaves && state.leaves {
|
||||
// Opaque leaves (forceOpaque) and quads over opaque texels draw in the
|
||||
// solid layer: no alpha cutout (a dirt path's side skips its clear top row).
|
||||
if face.opaque && !face.translucent || !self.cutout_leaves && state.leaves {
|
||||
face.layer as u16 | OPAQUE_LAYER
|
||||
} else {
|
||||
face.layer as u16
|
||||
|
||||
@@ -53,6 +53,7 @@ pub mod nautilus;
|
||||
pub mod nav;
|
||||
pub mod nether;
|
||||
pub mod panda;
|
||||
pub mod parrot;
|
||||
pub mod path;
|
||||
pub mod phantom;
|
||||
pub mod piglin;
|
||||
@@ -514,6 +515,8 @@ pub enum DamageKind {
|
||||
PlayerAttack,
|
||||
/// `mace_smash`: a mace hit after a fall (the player attack tags too).
|
||||
MaceSmash,
|
||||
/// `spear`: a stab of a spear (the player attack tags too).
|
||||
Spear,
|
||||
MobAttack,
|
||||
Arrow,
|
||||
Thrown,
|
||||
@@ -530,6 +533,8 @@ pub enum DamageKind {
|
||||
Magic,
|
||||
Sting,
|
||||
Cactus,
|
||||
/// `sweet_berry_bush`.
|
||||
SweetBerryBush,
|
||||
Generic,
|
||||
InWall,
|
||||
Thorns,
|
||||
@@ -576,6 +581,14 @@ impl Damage {
|
||||
from: Some(from),
|
||||
}
|
||||
}
|
||||
/// `DamageSources.spear`: a player's stab with a spear.
|
||||
pub fn spear(from: [f64; 3]) -> Self {
|
||||
Self {
|
||||
kind: DamageKind::Spear,
|
||||
attacker: Some(Who::Player),
|
||||
from: Some(from),
|
||||
}
|
||||
}
|
||||
pub fn mob(id: u32, from: [f64; 3]) -> Self {
|
||||
Self {
|
||||
kind: DamageKind::MobAttack,
|
||||
@@ -592,6 +605,7 @@ impl Damage {
|
||||
| DamageKind::DryOut
|
||||
| DamageKind::Generic
|
||||
| DamageKind::InWall
|
||||
| DamageKind::SweetBerryBush
|
||||
)
|
||||
}
|
||||
/// DamageTypeTags.BYPASSES_ARMOR
|
||||
@@ -628,6 +642,7 @@ impl Damage {
|
||||
| DamageKind::DryOut
|
||||
| DamageKind::Magic
|
||||
| DamageKind::Cactus
|
||||
| DamageKind::SweetBerryBush
|
||||
| DamageKind::Generic
|
||||
| DamageKind::InWall
|
||||
| DamageKind::Freeze
|
||||
@@ -652,6 +667,8 @@ pub struct Attrs {
|
||||
pub spawn_reinforcements: f64,
|
||||
pub jump_strength: f64,
|
||||
}
|
||||
/// `minecraft:wolf_armor`'s maximum damage.
|
||||
pub const WOLF_ARMOR_DURABILITY: i32 = 64;
|
||||
/// Species-specific persistent state (variants, colours, taming, ageing...).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Extra {
|
||||
@@ -685,6 +702,10 @@ pub struct Extra {
|
||||
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
|
||||
pub pick_up_loot: bool,
|
||||
pub saddled: bool,
|
||||
/// The durability a wolf's body armor (`extra.head`) has lost.
|
||||
pub body_damage: i32,
|
||||
/// The components (dye, name...) of that armor stack.
|
||||
pub body_extra: Option<Box<crate::item_data::StackData>>,
|
||||
/// The saddle's components (name, enchantments...) when it is not a bare
|
||||
/// one; `saddled` stays the gameplay flag.
|
||||
pub saddle_stack: Option<crate::items::ItemStack>,
|
||||
@@ -695,6 +716,8 @@ pub struct Extra {
|
||||
pub inventory: Vec<crate::items::ItemStack>,
|
||||
pub tame: bool,
|
||||
pub sitting: bool,
|
||||
/// `Parrot.partyParrot` and `jukebox`: the playing jukebox it dances to.
|
||||
pub party_jukebox: Option<[i32; 3]>,
|
||||
/// The owner's UUID (tamed animals).
|
||||
pub owner: Option<[i32; 4]>,
|
||||
/// Slime/magma cube size (0 = not sized).
|
||||
@@ -705,7 +728,6 @@ pub struct Extra {
|
||||
pub anger: i32,
|
||||
pub carried: Option<horizon_world::registry::BlockStateId>,
|
||||
pub charged: bool,
|
||||
pub levitation: i32,
|
||||
/// Held item ids (main hand, off hand) and head item.
|
||||
pub main_hand: Option<Arc<str>>,
|
||||
pub off_hand: Option<Arc<str>>,
|
||||
@@ -719,6 +741,8 @@ pub struct Extra {
|
||||
pub blocking: bool,
|
||||
pub fall_flying: bool,
|
||||
pub fall_fly_ticks: i32,
|
||||
/// `Entity.DATA_POSE` of another player, as the server sent it.
|
||||
pub synced_pose: u8,
|
||||
/// `LivingEntity.isAutoSpinAttack` (Riptide).
|
||||
pub auto_spin_attack: bool,
|
||||
pub main_hand_left: bool,
|
||||
@@ -862,6 +886,8 @@ pub struct Mob {
|
||||
pub previous_swell: i32,
|
||||
pub ambient_timer: i32,
|
||||
pub fall_distance: f64,
|
||||
/// `Entity.stuckSpeedMultiplier`: the next move is scaled by it.
|
||||
pub stuck_multiplier: Vec3,
|
||||
/// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving
|
||||
/// block has pushed this mob this tick (0.51 at most on any axis).
|
||||
pub piston: horizon_world::piston_movement::PistonMovement,
|
||||
@@ -943,6 +969,16 @@ pub enum MobEvent {
|
||||
event: i8,
|
||||
at: [f64; 3],
|
||||
},
|
||||
/// `ServerLevel.sendParticles`: drawn here and sent to the players within
|
||||
/// 32 blocks, which spread and speed the way the client does for a count
|
||||
/// (a count of 0 is one particle moving by speed times spread).
|
||||
LevelParticles {
|
||||
kind: &'static str,
|
||||
at: [f64; 3],
|
||||
spread: [f64; 3],
|
||||
speed: f64,
|
||||
count: u32,
|
||||
},
|
||||
Sound(&'static str, [f64; 3], f32, f32),
|
||||
/// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the
|
||||
/// chest's opener count goes up or down (interaction range 3).
|
||||
@@ -956,6 +992,11 @@ pub enum MobEvent {
|
||||
mob: u32,
|
||||
hive: [i32; 3],
|
||||
},
|
||||
/// `LandOnOwnersShoulderGoal`: a tame parrot touched its owner and sits
|
||||
/// on their shoulder (the host stores its tag and discards it).
|
||||
ParrotToShoulder {
|
||||
mob: u32,
|
||||
},
|
||||
/// `CopperGolem.turnToStatue`.
|
||||
BecomeStatue {
|
||||
mob: u32,
|
||||
@@ -1037,6 +1078,15 @@ pub enum MobEvent {
|
||||
target: Who,
|
||||
velocity: [f64; 3],
|
||||
},
|
||||
/// `SonicBoom`: 10 damage to the target, then a push along `direction`
|
||||
/// (the unit vector from the warden's chest to the target's eyes) only
|
||||
/// if the hit landed, less the target's knockback resistance.
|
||||
SonicBoom {
|
||||
target: Who,
|
||||
attacker: u32,
|
||||
from: [f64; 3],
|
||||
direction: [f64; 3],
|
||||
},
|
||||
/// `Entity.move(MoverType.SHULKER, delta)`: shift a target's position
|
||||
/// (an opening shulker lifts what stands on its shell).
|
||||
Shift {
|
||||
@@ -1084,6 +1134,13 @@ pub enum MobEvent {
|
||||
mob: u32,
|
||||
target: Who,
|
||||
},
|
||||
/// `StartHuntingHoglin` for a nearby adult piglin: it takes the hoglin as
|
||||
/// its anger target (when it has none) and starts its `HUNTED_RECENTLY` wait.
|
||||
HuntHoglin {
|
||||
mob: u32,
|
||||
target: u32,
|
||||
ticks: i32,
|
||||
},
|
||||
Projectile(crate::projectiles::Projectile),
|
||||
/// Spawn a new mob (breeding, slime splitting, chicken eggs...).
|
||||
Spawn(Box<Mob>),
|
||||
@@ -1126,6 +1183,14 @@ pub enum MobEvent {
|
||||
pos: [i32; 3],
|
||||
data: i32,
|
||||
},
|
||||
/// `InfestedBlock.infestedStateByHost` (`infested`) or `hostStateByInfested`
|
||||
/// for the block there, keeping its axis; `poof` is the silverfish that
|
||||
/// hid in it (`spawnAnim`).
|
||||
Infest {
|
||||
pos: [i32; 3],
|
||||
infested: bool,
|
||||
poof: Option<u32>,
|
||||
},
|
||||
/// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock).
|
||||
BreakBlock {
|
||||
pos: [i32; 3],
|
||||
@@ -1365,6 +1430,8 @@ pub struct Seen {
|
||||
pub baby: bool,
|
||||
pub in_love: bool,
|
||||
pub tame: bool,
|
||||
/// A tamed animal's owner (`getOwner`).
|
||||
pub owner: Option<[i32; 4]>,
|
||||
pub hostile: bool,
|
||||
pub target: Option<Who>,
|
||||
pub health: f32,
|
||||
@@ -1414,12 +1481,16 @@ pub struct Seen {
|
||||
pub stats: [f64; 3],
|
||||
/// `Wolf.isInSittingPose`.
|
||||
pub sitting: bool,
|
||||
/// `Entity.isSilent`.
|
||||
pub silent: bool,
|
||||
/// `Entity.isVehicle` or `isPassenger`.
|
||||
pub ridden: bool,
|
||||
/// `Attributes.KNOCKBACK_RESISTANCE`.
|
||||
pub knockback_resistance: f64,
|
||||
/// The active effects, without namespace (`slowness`, `poison`...).
|
||||
pub effects: Vec<&'static str>,
|
||||
/// A piglin's `HUNTED_RECENTLY` memory.
|
||||
pub hunted_recently: bool,
|
||||
}
|
||||
impl Seen {
|
||||
/// `LivingEntity.hasEffect`, by id without namespace.
|
||||
@@ -1470,6 +1541,7 @@ impl Mob {
|
||||
m.extra.in_love > 0
|
||||
},
|
||||
tame: m.extra.tame,
|
||||
owner: m.extra.owner,
|
||||
hostile: m.hostile(),
|
||||
target: m.ai.target,
|
||||
health: m.health,
|
||||
@@ -1505,6 +1577,7 @@ impl Mob {
|
||||
m.attrs.speed,
|
||||
],
|
||||
sitting: m.extra.sitting,
|
||||
silent: m.silent,
|
||||
ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(),
|
||||
knockback_resistance: m.attrs.knockback_resistance,
|
||||
effects: m
|
||||
@@ -1513,6 +1586,7 @@ impl Mob {
|
||||
.iter()
|
||||
.map(|e| e.0.trim_start_matches("minecraft:"))
|
||||
.collect(),
|
||||
hunted_recently: m.species() == Species::Piglin && m.extra.ints[0] > 0,
|
||||
}
|
||||
}
|
||||
/// `EntityType.getCategory`'s name.
|
||||
@@ -1794,6 +1868,7 @@ impl Mob {
|
||||
// Mob.ambientSoundTime starts at 0.
|
||||
ambient_timer: 0,
|
||||
fall_distance: 0.0,
|
||||
stuck_multiplier: Vec3::ZERO,
|
||||
piston: Default::default(),
|
||||
persistent: false,
|
||||
random,
|
||||
@@ -1866,13 +1941,17 @@ impl Mob {
|
||||
}
|
||||
}
|
||||
pub fn bounds(&self) -> Aabb {
|
||||
self.bounds_at(self.position)
|
||||
}
|
||||
/// `Entity.makeBoundingBox(position)`.
|
||||
pub fn bounds_at(&self, position: Vec3) -> Aabb {
|
||||
let w = f64::from(self.width()) / 2.0;
|
||||
Aabb::new(
|
||||
Vec3::new(self.position.x - w, self.position.y, self.position.z - w),
|
||||
Vec3::new(position.x - w, position.y, position.z - w),
|
||||
Vec3::new(
|
||||
self.position.x + w,
|
||||
self.position.y + f64::from(self.height()),
|
||||
self.position.z + w,
|
||||
position.x + w,
|
||||
position.y + f64::from(self.height()),
|
||||
position.z + w,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -1996,18 +2075,29 @@ impl Mob {
|
||||
if epf > 0.0 {
|
||||
amount *= 1.0 - epf / 25.0;
|
||||
}
|
||||
// Wolf.actuallyHurt: wolf armor takes the damage instead of the wolf.
|
||||
let absorbed = self.wolf_armor_absorbs(&source);
|
||||
let mut knock = true;
|
||||
if self.invulnerable as f32 > 10.0 {
|
||||
if amount <= self.last_hurt {
|
||||
return false;
|
||||
}
|
||||
self.health -= amount - self.last_hurt;
|
||||
let dealt = amount - self.last_hurt;
|
||||
if absorbed {
|
||||
self.hurt_wolf_armor(dealt);
|
||||
} else {
|
||||
self.health -= dealt;
|
||||
}
|
||||
self.last_hurt = amount;
|
||||
knock = false;
|
||||
} else {
|
||||
self.last_hurt = amount;
|
||||
self.invulnerable = 20;
|
||||
self.health -= amount;
|
||||
if absorbed {
|
||||
self.hurt_wolf_armor(amount);
|
||||
} else {
|
||||
self.health -= amount;
|
||||
}
|
||||
self.hurt_time = 10;
|
||||
}
|
||||
// Animal.actuallyHurt: damage taken ends love mode (`resetLove`).
|
||||
@@ -2038,7 +2128,12 @@ impl Mob {
|
||||
// playHurtSound (Mob: also resets the ambient sound clock) or the
|
||||
// death sound: makeSound draws the voice pitch whenever there is a sound.
|
||||
let dead = !self.alive();
|
||||
let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }];
|
||||
// Wolf.getHurtSound: the armor's own sound when it takes the hit.
|
||||
let sound = if absorbed {
|
||||
"item.wolf_armor.damage"
|
||||
} else {
|
||||
ai::voice_sounds(self)[if dead { 2 } else { 1 }]
|
||||
};
|
||||
if !dead {
|
||||
self.ambient_timer = -self.ambient_interval();
|
||||
}
|
||||
@@ -2062,6 +2157,46 @@ impl Mob {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `Wolf.canArmorAbsorb`: it wears wolf armor and the damage type is not
|
||||
/// in `#bypasses_wolf_armor` (drowning, magic, thorns, in a wall, out of
|
||||
/// the world and the untyped kills).
|
||||
fn wolf_armor_absorbs(&self, source: &Damage) -> bool {
|
||||
self.species() == Species::Wolf
|
||||
&& self.extra.head.as_deref() == Some("minecraft:wolf_armor")
|
||||
&& !matches!(
|
||||
source.kind,
|
||||
DamageKind::Drown
|
||||
| DamageKind::Magic
|
||||
| DamageKind::InWall
|
||||
| DamageKind::Thorns
|
||||
| DamageKind::OutOfWorld
|
||||
| DamageKind::Generic
|
||||
)
|
||||
}
|
||||
/// `Wolf.actuallyHurt`: the armor loses `ceil(damage)` durability, cracks
|
||||
/// at `Crackiness.WOLF_ARMOR` steps and breaks at its maximum.
|
||||
fn hurt_wolf_armor(&mut self, damage: f32) {
|
||||
let crack = |lost: i32| {
|
||||
let left = (WOLF_ARMOR_DURABILITY - lost) as f32 / WOLF_ARMOR_DURABILITY as f32;
|
||||
[0.95_f32, 0.69, 0.32].iter().filter(|t| left < **t).count()
|
||||
};
|
||||
let before = self.extra.body_damage;
|
||||
let after = before + damage.ceil() as i32;
|
||||
let at = [self.position.x, self.position.y, self.position.z];
|
||||
if after >= WOLF_ARMOR_DURABILITY {
|
||||
self.extra.head = None;
|
||||
self.extra.body_damage = 0;
|
||||
self.extra.body_extra = None;
|
||||
self.outbox
|
||||
.push(MobEvent::Sound("item.wolf_armor.break", at, 1.0, 1.0));
|
||||
} else {
|
||||
self.extra.body_damage = after;
|
||||
if crack(before) != crack(after) {
|
||||
self.outbox
|
||||
.push(MobEvent::Sound("item.wolf_armor.crack", at, 1.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// LivingEntity.knockback(power, xd, zd) towards the negative direction.
|
||||
pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) {
|
||||
let power = power * (1.0 - self.attrs.knockback_resistance);
|
||||
@@ -2110,8 +2245,10 @@ impl Mob {
|
||||
/// Movement speed attribute bonus (baby zombies, sprinting modifiers).
|
||||
/// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level).
|
||||
pub fn movement_speed(&self) -> f64 {
|
||||
let mut v = strider::movement_speed(self, witch::speed(self, self.attrs.speed))
|
||||
* self.speed_bonus();
|
||||
let mut v = strider::movement_speed(
|
||||
self,
|
||||
witch::speed(self, self.attrs.speed) + enderman::attacking_speed(self),
|
||||
) * self.speed_bonus();
|
||||
for (e, _, amp) in &self.extra.effects {
|
||||
match *e {
|
||||
"minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1),
|
||||
@@ -2503,6 +2640,25 @@ impl SwimAnimation {
|
||||
}
|
||||
}
|
||||
|
||||
impl Mob {
|
||||
/// The part of `LivingEntity.tick` and `aiStep` that animates another
|
||||
/// player from its synched pose and flags: the glide count, the wings
|
||||
/// (`elytraAnimationState`) and the swim amount (`updateSwimAmount`).
|
||||
pub fn tick_avatar_pose(&mut self, in_water: bool) {
|
||||
let e = &mut self.extra;
|
||||
e.fall_fly_ticks = if e.fall_flying {
|
||||
e.fall_fly_ticks + 1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// LivingEntity.isVisuallySwimming: the swimming pose, or the gliding
|
||||
// pose after the glide ended.
|
||||
let visually = e.synced_pose == 3 || (!e.fall_flying && e.synced_pose == 1);
|
||||
e.elytra.tick(e.fall_flying, e.crouching, self.velocity);
|
||||
e.swim.tick(visually, in_water);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod elytra_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -123,7 +123,7 @@ pub fn family(s: Species) -> Family {
|
||||
| S::Parched
|
||||
| S::WitherSkeleton
|
||||
| S::ZombifiedPiglin => Family::Undead,
|
||||
S::Creeper | S::Spider | S::CaveSpider => Family::Hostile,
|
||||
S::Creeper | S::Spider | S::CaveSpider | S::Silverfish => Family::Hostile,
|
||||
S::Squid
|
||||
| S::GlowSquid
|
||||
| S::Cod
|
||||
@@ -182,9 +182,12 @@ pub fn register(m: &mut Mob) {
|
||||
Family::Undead => undead::register(m),
|
||||
Family::Hostile => hostile::register(m),
|
||||
Family::Aquatic => aquatic::register(m),
|
||||
// Turtle.registerGoals has its own list, none of the generic goals.
|
||||
Family::Generic if m.species() == Species::Turtle => super::turtle::register(m),
|
||||
Family::Generic if m.species() == Species::Armadillo => super::armadillo::register(m),
|
||||
Family::Generic if m.species() == Species::Frog => super::frog::register(m),
|
||||
Family::Generic if m.species() == Species::Fox => super::fox::register(m),
|
||||
Family::Generic if m.species() == Species::Parrot => super::tame::register_parrot(m),
|
||||
Family::Generic => {
|
||||
generic(m);
|
||||
if m.species() == Species::Rabbit {
|
||||
@@ -202,9 +205,6 @@ pub fn register(m: &mut Mob) {
|
||||
gravity: true,
|
||||
};
|
||||
}
|
||||
if m.species() == Species::Turtle {
|
||||
super::turtle::register(m);
|
||||
}
|
||||
if m.species() == Species::Goat {
|
||||
super::goat::register(m);
|
||||
}
|
||||
@@ -442,9 +442,16 @@ pub fn tick(
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if !m.no_ai {
|
||||
if m.no_ai {
|
||||
// Mob.aiStep still runs without AI (only serverAiStep is skipped),
|
||||
// so the endermite's life keeps counting.
|
||||
if m.species() == Species::Endermite {
|
||||
endermite_lifetime(m);
|
||||
}
|
||||
} else {
|
||||
ai_step(m, w, level_random, events);
|
||||
}
|
||||
effects_from_blocks(m, w);
|
||||
if m.species() == Species::Rabbit {
|
||||
super::rabbit::post_tick(m);
|
||||
}
|
||||
@@ -480,6 +487,59 @@ pub fn tick(
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `LivingEntity.aiStep` -> `Entity.applyEffectsFromBlocks` for the blocks
|
||||
/// that hurt or hold a mob: the cactus (`CactusBlock.entityInside`, 1) and the
|
||||
/// sweet berry bush (`SweetBerryBushBlock.entityInside`: stuck at 0.8, 0.75,
|
||||
/// 0.8, and a grown bush pricks for 1 when the mob moved at least 0.003 on X
|
||||
/// or Z this tick). The blocks are those the mob's box touches anywhere along
|
||||
/// its move this tick, from where it started to where it ended.
|
||||
fn effects_from_blocks(m: &mut Mob, w: &MobWorld) {
|
||||
let mut visited: Vec<[i32; 3]> = Vec::new();
|
||||
let travel = m.position.subtract(m.previous);
|
||||
let longest = travel.x.abs().max(travel.y.abs()).max(travel.z.abs());
|
||||
let steps = ((longest / 0.2).ceil() as i32).clamp(1, 100);
|
||||
for step in 0..=steps {
|
||||
if !m.alive() {
|
||||
return;
|
||||
}
|
||||
let at = m
|
||||
.previous
|
||||
.add_vector(travel.scale(f64::from(step) / f64::from(steps)));
|
||||
let b = m.bounds_at(at).deflate(Vec3::new(1e-5, 1e-5, 1e-5));
|
||||
for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 {
|
||||
for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 {
|
||||
for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 {
|
||||
let p = [x, y, z];
|
||||
if visited.contains(&p) {
|
||||
continue;
|
||||
}
|
||||
match w.block_name(x, y, z) {
|
||||
"minecraft:cactus" => {
|
||||
m.damage(1.0, Damage::of(DamageKind::Cactus));
|
||||
}
|
||||
"minecraft:sweet_berry_bush"
|
||||
if !matches!(m.species(), Species::Fox | Species::Bee) =>
|
||||
{
|
||||
m.fall_distance = 0.0;
|
||||
m.stuck_multiplier =
|
||||
Vec3::new(f64::from(0.8_f32), 0.75, f64::from(0.8_f32));
|
||||
let moved = m.previous.subtract(m.position);
|
||||
if w.prop(x, y, z, "age") != Some("0")
|
||||
&& moved.horizontal_distance_squared() > 0.0
|
||||
&& (moved.x.abs() >= f64::from(0.003_f32)
|
||||
|| moved.z.abs() >= f64::from(0.003_f32))
|
||||
{
|
||||
m.damage(1.0, Damage::of(DamageKind::SweetBerryBush));
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
visited.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// LivingEntity.updateSwingTime (6-tick swing duration).
|
||||
pub fn tick_swing(m: &mut Mob) {
|
||||
if m.ai.swinging {
|
||||
@@ -725,6 +785,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
"entity.wolf.pant"
|
||||
}
|
||||
}
|
||||
Species::Parrot => super::parrot::ambient(m, w),
|
||||
Species::Cat if m.extra.tame && m.extra.in_love > 0 => "entity.cat.purr",
|
||||
Species::Cat if !m.extra.tame => "entity.cat.stray_ambient",
|
||||
Species::PolarBear if m.is_baby() => "entity.polar_bear.ambient_baby",
|
||||
@@ -776,6 +837,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
|
||||
fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &mut Vec<MobEvent>) {
|
||||
if m.species() == Species::Parrot {
|
||||
super::parrot::ai_step(m, w, level_random, events);
|
||||
}
|
||||
// Witch.aiStep runs before super.aiStep().
|
||||
if m.species() == Species::Witch {
|
||||
let far = m
|
||||
@@ -837,8 +901,8 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
if m.kind.flags.climber {
|
||||
m.climbing = m.horizontal_collision;
|
||||
}
|
||||
// AgeableMob.aiStep: a forced age-up's particles (positions drawn on the
|
||||
// server too), then the age.
|
||||
// AgeableMob.aiStep: a forced age-up's particles (`sendParticles`, so the
|
||||
// players are sent them), then the age.
|
||||
if m.extra.forced_age_timer > 0 {
|
||||
if m.extra.forced_age_timer % 4 == 0 {
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
@@ -847,10 +911,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
let y = m.position.y + h * r.next_double() + 0.5;
|
||||
let z = m.position.z + w * (2.0 * r.next_double() - 1.0);
|
||||
// sendParticles(HAPPY_VILLAGER, x, y, z, 1, 0, 0, 0, 0): exactly there, at rest.
|
||||
events.push(MobEvent::Particles {
|
||||
events.push(MobEvent::LevelParticles {
|
||||
kind: "happy_villager",
|
||||
at: [x, y, z],
|
||||
count: 0,
|
||||
spread: [0.0; 3],
|
||||
speed: 0.0,
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
m.extra.forced_age_timer -= 1;
|
||||
@@ -1141,6 +1207,16 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Endermite.aiStep: `counter` is the life; an endermite not required to
|
||||
/// persist is discarded at 2400.
|
||||
fn endermite_lifetime(m: &mut Mob) {
|
||||
if !m.persistent {
|
||||
m.extra.counter += 1;
|
||||
}
|
||||
if m.extra.counter >= 2400 {
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
fn species_ai_step(
|
||||
m: &mut Mob,
|
||||
w: &MobWorld,
|
||||
@@ -1152,6 +1228,9 @@ fn species_ai_step(
|
||||
}
|
||||
match m.species() {
|
||||
Species::Enderman => super::enderman::ai_step(m, w, events),
|
||||
// Endermite.aiStep: `counter` is the life; an endermite not required
|
||||
// to persist is discarded at 2400.
|
||||
Species::Endermite => endermite_lifetime(m),
|
||||
Species::Wolf => super::tame::ai_step(m, w, events),
|
||||
Species::Cat => super::tame::cat_ai_step(m, events),
|
||||
Species::Blaze => super::nether::blaze_ai_step(m, events),
|
||||
@@ -1463,6 +1542,9 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
if m.species() == Species::Strider {
|
||||
return super::strider::walk_target_value(m, w, p);
|
||||
}
|
||||
if m.species() == Species::Turtle {
|
||||
return super::turtle::walk_target_value(m, w, p, light());
|
||||
}
|
||||
// Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best.
|
||||
if m.species() == Species::Hoglin {
|
||||
let near = m.extra.repellent.is_some_and(|r| {
|
||||
@@ -1532,6 +1614,10 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
|
||||
super::panda::hurt(m);
|
||||
true
|
||||
}
|
||||
Species::Silverfish => {
|
||||
super::hostile::silverfish_hurt(m, source);
|
||||
true
|
||||
}
|
||||
Species::Enderman => super::enderman::on_damage(m, source),
|
||||
Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider
|
||||
if source.is_fire() =>
|
||||
|
||||
@@ -244,6 +244,8 @@ pub enum ArmPose {
|
||||
CrossbowCharge,
|
||||
/// Raising a trident to throw it (or to launch with Riptide).
|
||||
ThrowTrident,
|
||||
/// A spear held out (`HumanoidModel.ArmPose.SPEAR`), at rest or charging.
|
||||
Spear,
|
||||
}
|
||||
/// HumanoidModel.setupAnim with empty hands (endermen).
|
||||
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
|
||||
@@ -295,6 +297,10 @@ pub struct Hum {
|
||||
pub swing_right_arm: Option<bool>,
|
||||
/// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it.
|
||||
pub left_main: bool,
|
||||
/// The spear each arm (right, left) holds, and how long that arm has
|
||||
/// been using it (`ticksUsingItem(arm)`, 0 when it is not).
|
||||
pub spear: [Option<crate::spear::Kinetic>; 2],
|
||||
pub spear_ticks: [f32; 2],
|
||||
}
|
||||
impl Hum {
|
||||
pub fn new(right: ArmPose, left: ArmPose) -> Self {
|
||||
@@ -313,6 +319,8 @@ impl Hum {
|
||||
using_item: false,
|
||||
swing_right_arm: None,
|
||||
left_main: false,
|
||||
spear: [None; 2],
|
||||
spear_ticks: [0.0; 2],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,6 +396,23 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
|
||||
}
|
||||
ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right),
|
||||
ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right),
|
||||
// SpearAnimations.thirdPersonHandUse.
|
||||
ArmPose::Spear => {
|
||||
let side = usize::from(!right);
|
||||
let Some(kinetic) = h.spear[side] else {
|
||||
return;
|
||||
};
|
||||
let (x, y, z) = crate::spear::third_person_arm(
|
||||
&kinetic,
|
||||
h.spear_ticks[side],
|
||||
right,
|
||||
(hx, hy),
|
||||
h.fall_flying || h.swim > 0.0,
|
||||
);
|
||||
p.xrot(arm, x);
|
||||
p.yrot(arm, y);
|
||||
p.get(arm)[5] += z;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`).
|
||||
@@ -687,6 +712,14 @@ pub fn setup(
|
||||
ArmPose::Empty
|
||||
};
|
||||
let using_main = m.extra.using_item > 0 && !m.extra.using_off_hand;
|
||||
// AvatarRenderer.getArmPose: an arm holding a spear (at rest too).
|
||||
let spear_in = |hand: &Option<std::sync::Arc<str>>| {
|
||||
hand.as_deref()
|
||||
.filter(|_| player)
|
||||
.and_then(crate::spear::Kinetic::of)
|
||||
};
|
||||
let (main_spear, off_spear) =
|
||||
(spear_in(&m.extra.main_hand), spear_in(&m.extra.off_hand));
|
||||
let pose = if player {
|
||||
match m.extra.main_hand.as_deref() {
|
||||
Some(_) if using_main && m.extra.blocking => ArmPose::Block,
|
||||
@@ -698,6 +731,7 @@ pub fn setup(
|
||||
Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => {
|
||||
ArmPose::CrossbowHold
|
||||
}
|
||||
Some(_) if main_spear.is_some() => ArmPose::Spear,
|
||||
Some(_) => ArmPose::Item,
|
||||
None => ArmPose::Empty,
|
||||
}
|
||||
@@ -705,7 +739,9 @@ pub fn setup(
|
||||
right
|
||||
};
|
||||
let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() {
|
||||
if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking {
|
||||
if off_spear.is_some() {
|
||||
ArmPose::Spear
|
||||
} else if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking {
|
||||
ArmPose::Block
|
||||
} else {
|
||||
ArmPose::Item
|
||||
@@ -731,6 +767,17 @@ pub fn setup(
|
||||
h.using_item = m.extra.using_item > 0;
|
||||
h.swing_right_arm = m.extra.swing_right_arm;
|
||||
h.left_main = m.main_arm_left();
|
||||
let main_side = usize::from(m.main_arm_left());
|
||||
h.spear[main_side] = main_spear;
|
||||
h.spear[1 - main_side] = off_spear;
|
||||
if m.extra.using_item > 0 {
|
||||
let using_side = if m.extra.using_off_hand {
|
||||
1 - main_side
|
||||
} else {
|
||||
main_side
|
||||
};
|
||||
h.spear_ticks[using_side] = m.extra.using_item as f32 + s.partial;
|
||||
}
|
||||
humanoid(p, s, &h);
|
||||
if m.ai.aggressive && !bow {
|
||||
// SkeletonModel melee pose.
|
||||
|
||||
@@ -981,7 +981,9 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
|
||||
let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial;
|
||||
let speed = m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial;
|
||||
// `Parrot.isFlying` is `!onGround`, in water too.
|
||||
let pose = if m.extra.sitting {
|
||||
let pose = if m.extra.party_jukebox.is_some() {
|
||||
ParrotPose::Party
|
||||
} else if m.extra.sitting {
|
||||
ParrotPose::Sitting
|
||||
} else if !m.on_ground {
|
||||
ParrotPose::Flying
|
||||
|
||||
@@ -118,6 +118,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
|
||||
source.kind,
|
||||
DamageKind::PlayerAttack
|
||||
| DamageKind::MaceSmash
|
||||
| DamageKind::Spear
|
||||
| DamageKind::MobAttack
|
||||
| DamageKind::Arrow
|
||||
| DamageKind::Thrown
|
||||
|
||||
@@ -151,37 +151,49 @@ pub fn jump(m: &mut Mob) {
|
||||
};
|
||||
m.velocity.y = f64::from(m.jump_power() + boost);
|
||||
}
|
||||
/// `AbstractCubeMob.tick`'s landing splash: crumbs of goo (or flames) around
|
||||
/// the cube's feet, drawn by the side that ticks the mob.
|
||||
fn landing_splash(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
let size = m.width() * 2.0;
|
||||
let radius = size / 2.0;
|
||||
let kind = match m.species() {
|
||||
Species::MagmaCube => "flame",
|
||||
Species::SulfurCube => "sulfur_cube_goo",
|
||||
_ => "item_slime",
|
||||
};
|
||||
let mut i = 0;
|
||||
while (i as f32) < size * 16.0 {
|
||||
let dir = m.random.next_float() * std::f64::consts::TAU as f32;
|
||||
let d = m.random.next_float() * 0.5 + 0.5;
|
||||
let xd = trig::sin(f64::from(dir)) * radius * d;
|
||||
let zd = trig::cos(f64::from(dir)) * radius * d;
|
||||
events.push(MobEvent::Particles {
|
||||
kind,
|
||||
at: [
|
||||
m.position.x + f64::from(xd),
|
||||
m.position.y,
|
||||
m.position.z + f64::from(zd),
|
||||
],
|
||||
count: 0,
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
/// `AbstractCubeMob.tick` on a client of a server: the landing splash follows
|
||||
/// the on-ground flag the server sends.
|
||||
pub fn client_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if m.on_ground && !m.extra.flag2 {
|
||||
landing_splash(m, events);
|
||||
}
|
||||
m.extra.flag2 = m.on_ground;
|
||||
}
|
||||
/// AbstractCubeMob.tick squish and landing sounds, plus contact damage.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let v = &mut m.anim.v;
|
||||
v[SQUISH] += (v[TARGET_SQUISH] - v[SQUISH]) * 0.5;
|
||||
let was = m.extra.flag2;
|
||||
if m.on_ground && !was {
|
||||
// The landing splash: drawn on the server too, where it spawns nothing.
|
||||
let size = m.width() * 2.0;
|
||||
let radius = size / 2.0;
|
||||
let kind = match m.species() {
|
||||
Species::MagmaCube => "flame",
|
||||
Species::SulfurCube => "sulfur_cube_goo",
|
||||
_ => "item_slime",
|
||||
};
|
||||
let mut i = 0;
|
||||
while (i as f32) < size * 16.0 {
|
||||
let dir = m.random.next_float() * std::f64::consts::TAU as f32;
|
||||
let d = m.random.next_float() * 0.5 + 0.5;
|
||||
let xd = trig::sin(f64::from(dir)) * radius * d;
|
||||
let zd = trig::cos(f64::from(dir)) * radius * d;
|
||||
events.push(MobEvent::Particles {
|
||||
kind,
|
||||
at: [
|
||||
m.position.x + f64::from(xd),
|
||||
m.position.y,
|
||||
m.position.z + f64::from(zd),
|
||||
],
|
||||
count: 0,
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
landing_splash(m, events);
|
||||
let squish = match (m.species(), tiny(m)) {
|
||||
(Species::SulfurCube, _) => super::sulfur_cube::squish_sound(m),
|
||||
(Species::MagmaCube, true) => "entity.magma_cube.squish_small",
|
||||
|
||||
@@ -251,6 +251,9 @@ pub fn slot_item(m: &Mob, slot: &str) -> Option<LootStack> {
|
||||
1
|
||||
};
|
||||
let mut stack = loot_stack(item?, count as i32);
|
||||
if slot == "body" && m.species() == Species::Wolf {
|
||||
stack.damage = m.extra.body_damage;
|
||||
}
|
||||
if let (Some(index), Some(g)) = (index, gear::gear(m)) {
|
||||
for (e, l) in &g.slots[index] {
|
||||
stack.enchantments.push((e.to_string(), *l as i32));
|
||||
@@ -288,6 +291,8 @@ pub fn clear_slot(m: &mut Mob, slot: &str) {
|
||||
}
|
||||
"body" if body => {
|
||||
m.extra.head = None;
|
||||
m.extra.body_damage = 0;
|
||||
m.extra.body_extra = None;
|
||||
return;
|
||||
}
|
||||
"saddle" => {
|
||||
|
||||
@@ -154,6 +154,15 @@ fn teleport_towards(
|
||||
let z = m.position.z + (m.random.next_double() - 0.5) * 8.0 - d[2] * 16.0;
|
||||
teleport_to(m, w, x, y, z, events)
|
||||
}
|
||||
/// `Enderman.SPEED_MODIFIER_ATTACKING`, an ADD_VALUE modifier `setTarget`
|
||||
/// adds while the enderman has a target.
|
||||
pub fn attacking_speed(m: &Mob) -> f64 {
|
||||
if m.species() == Species::Enderman && m.ai.target.is_some() {
|
||||
f64::from(0.15f32)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
/// Enderman.customServerAiStep: in daylight, flee by teleporting. The End has a
|
||||
/// fixed time, so `Level.isBrightOutside` is never true there.
|
||||
pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
|
||||
@@ -516,9 +516,13 @@ fn effect_modifiers(m: &Mob, a: Attr) -> impl Iterator<Item = (f64, Op)> + '_ {
|
||||
}
|
||||
/// `AttributeInstance.getValue`: the base, then the modifiers by operation.
|
||||
pub fn value(m: &Mob, a: Attr) -> f64 {
|
||||
compute(m, a, true)
|
||||
compute(m, a, true, &[])
|
||||
}
|
||||
fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 {
|
||||
/// `value` with more modifiers, such as the ones worn equipment grants.
|
||||
pub fn value_with(m: &Mob, a: Attr, extra: &[(f64, Op)]) -> f64 {
|
||||
compute(m, a, true, extra)
|
||||
}
|
||||
fn compute(m: &Mob, a: Attr, with_transient: bool, extra: &[(f64, Op)]) -> f64 {
|
||||
let mut base = base_value(m, a);
|
||||
let empty = Vec::new();
|
||||
let mods = m.extra.attributes.as_ref().map_or(&empty, |s| &s.modifiers);
|
||||
@@ -531,6 +535,7 @@ fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 {
|
||||
ops.extend(transient(m, a));
|
||||
ops.extend(effect_modifiers(m, a));
|
||||
}
|
||||
ops.extend(extra.iter().copied());
|
||||
for (amount, op) in &ops {
|
||||
if *op == Op::AddValue {
|
||||
base += amount;
|
||||
@@ -573,7 +578,7 @@ fn refresh(m: &mut Mob, a: Attr) {
|
||||
/// The value without the transient baby modifier (`speed_bonus` applies
|
||||
/// that one to movement speed).
|
||||
fn base_with_modifiers(m: &Mob, a: Attr) -> f64 {
|
||||
compute(m, a, false)
|
||||
compute(m, a, false, &[])
|
||||
}
|
||||
/// `AttributeInstance.setBaseValue`.
|
||||
pub fn set_base(m: &mut Mob, a: Attr, v: f64) {
|
||||
@@ -898,6 +903,28 @@ pub fn slot_enchantments(m: &Mob, slot: usize) -> gear::Levels {
|
||||
pub fn set_slot_enchantments(m: &mut Mob, slot: usize, levels: gear::Levels) {
|
||||
gear::set(m, gear_slot(slot), levels);
|
||||
}
|
||||
/// `EquipmentUser.equip` for one rolled stack: `setItemSlot` puts the item in
|
||||
/// `slot` with its own enchantments, then the slot's drop chance is stored
|
||||
/// when the table names one.
|
||||
pub fn equip_stack(
|
||||
m: &mut Mob,
|
||||
slot: usize,
|
||||
stack: &horizon_world::loot::LootStack,
|
||||
drop_chance: Option<f32>,
|
||||
) {
|
||||
set_item(m, slot, &stack.item);
|
||||
if slot <= HEAD {
|
||||
let levels = stack
|
||||
.enchantments
|
||||
.iter()
|
||||
.map(|(id, level)| (Arc::from(id.as_str()), (*level).max(0) as u32))
|
||||
.collect();
|
||||
gear::set(m, gear_slot(slot), levels);
|
||||
}
|
||||
if let Some(chance) = drop_chance {
|
||||
set_drop_chance(m, slot, chance);
|
||||
}
|
||||
}
|
||||
/// `Mob.setDropChance`.
|
||||
pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) {
|
||||
let c = m
|
||||
|
||||
@@ -675,6 +675,9 @@ pub struct Panic {
|
||||
pub speed: f64,
|
||||
/// Only the damage of `#panic_environmental_causes` (an armadillo).
|
||||
pub environmental: bool,
|
||||
/// `TurtlePanicGoal`: always look for water this far away, not only
|
||||
/// when on fire.
|
||||
pub water_range: Option<i32>,
|
||||
pos: [f64; 3],
|
||||
}
|
||||
impl Panic {
|
||||
@@ -682,9 +685,15 @@ impl Panic {
|
||||
Self {
|
||||
speed,
|
||||
environmental: false,
|
||||
water_range: None,
|
||||
pos: [0.0; 3],
|
||||
}
|
||||
}
|
||||
/// `TurtlePanicGoal`.
|
||||
pub fn looking_for_water(mut self, range: i32) -> Self {
|
||||
self.water_range = Some(range);
|
||||
self
|
||||
}
|
||||
}
|
||||
pub fn should_panic(m: &Mob) -> bool {
|
||||
m.last_damage
|
||||
@@ -707,18 +716,19 @@ impl Goal for Panic {
|
||||
if !wanted {
|
||||
return false;
|
||||
}
|
||||
if m.fire_ticks > 0 {
|
||||
let range = self.water_range.or((m.fire_ticks > 0).then_some(5));
|
||||
if let Some(range) = range {
|
||||
let (bx, by, bz) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
);
|
||||
if cx.w.data.state(cx.w.world.block(bx, by, bz)).top == 0.0 {
|
||||
// findBlocksInBoxByManhattanDistance(pos, 5, 1) for water.
|
||||
// findBlocksInBoxByManhattanDistance(pos, range, 1) for water.
|
||||
let mut best: Option<([i32; 3], i32)> = None;
|
||||
for dy in -1i32..=1 {
|
||||
for dx in -5i32..=5 {
|
||||
for dz in -5i32..=5 {
|
||||
for dx in -range..=range {
|
||||
for dz in -range..=range {
|
||||
let d = dx.abs() + dy.abs() + dz.abs();
|
||||
if cx.w.fluid(bx + dx, by + dy, bz + dz) == crate::blocks::Fluid::Water
|
||||
&& best.is_none_or(|b| d < b.1)
|
||||
|
||||
@@ -341,12 +341,12 @@ fn snowball_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
let zd = t.position.z - m.position.z;
|
||||
let yo = (xd * xd + zd * zd).sqrt() * 0.2;
|
||||
let mut p = Projectile::new(ProjectileKind::Snowball, start, Some(Who::Mob(m.id)));
|
||||
// rangedAttackUncertainty: 14 - 4 * difficulty (normal: 6).
|
||||
// SnowGolem.rangedAttackUncertainty: 12 on every difficulty.
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd + yo - start.y, zd],
|
||||
1.6,
|
||||
6.0,
|
||||
12.0,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 0.4 / (m.random.next_float() * 0.4 + 0.8);
|
||||
|
||||
@@ -291,7 +291,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
&& let Some((d, _)) = m.last_damage
|
||||
&& matches!(
|
||||
d.kind,
|
||||
DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack
|
||||
DamageKind::PlayerAttack
|
||||
| DamageKind::MaceSmash
|
||||
| DamageKind::Spear
|
||||
| DamageKind::MobAttack
|
||||
)
|
||||
{
|
||||
let from = [m.position.x, m.position.y, m.position.z];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Creepers (swelling, explosions) and spiders (wall climbing, daylight
|
||||
//! neutrality, leaping).
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
|
||||
goals::{
|
||||
Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LeapAtTarget, LookAtPlayer, MOVE,
|
||||
MeleeAttack, NearestTarget, RandomLookAround, Stroll, goal_clone,
|
||||
@@ -54,9 +54,157 @@ pub fn register(m: &mut Mob) {
|
||||
);
|
||||
m.ai.nav.kind = super::nav::NavKind::WallClimber;
|
||||
}
|
||||
S::Silverfish => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(1, Float);
|
||||
g.add(3, SilverfishWakeUpFriends);
|
||||
g.add(4, MeleeAttack::new(1.0, false));
|
||||
g.add(5, SilverfishMergeWithStone::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new().alert());
|
||||
m.ai.targets.add(2, NearestTarget::player(true));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// `Silverfish.hurtServer`: a hit by an entity (or magic damage) starts the
|
||||
/// countdown of its wake-up goal, kept in `extra.counter`.
|
||||
pub fn silverfish_hurt(m: &mut Mob, source: &Damage) {
|
||||
if (source.attacker.is_some() || source.kind == DamageKind::Magic) && m.extra.counter == 0 {
|
||||
m.extra.counter = super::goals::reduced(20);
|
||||
}
|
||||
}
|
||||
/// `Silverfish.SilverfishWakeUpFriendsGoal`: 20 ticks after being hurt, the
|
||||
/// infested blocks within 10 blocks sideways and 5 up or down break (or turn
|
||||
/// back into stone with mob griefing off), until a coin flip stops it.
|
||||
#[derive(Clone, Debug)]
|
||||
struct SilverfishWakeUpFriends;
|
||||
impl Goal for SilverfishWakeUpFriends {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"SilverfishWakeUpFriendsGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
m.extra.counter > 0
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.extra.counter -= 1;
|
||||
if m.extra.counter > 0 {
|
||||
return;
|
||||
}
|
||||
let base = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
// The loops' offsets go 0, 1, -1, 2, -2 and so on.
|
||||
let offsets = |limit: i32| std::iter::once(0).chain((1..=limit).flat_map(|i| [i, -i]));
|
||||
for y in offsets(5) {
|
||||
for x in offsets(10) {
|
||||
for z in offsets(10) {
|
||||
let pos = [base[0] + x, base[1] + y, base[2] + z];
|
||||
if !cx
|
||||
.w
|
||||
.block_name(pos[0], pos[1], pos[2])
|
||||
.starts_with("minecraft:infested_")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if cx.w.mob_griefing {
|
||||
cx.events.push(MobEvent::BreakBlock { pos, drop: true });
|
||||
} else {
|
||||
cx.events.push(MobEvent::Infest {
|
||||
pos,
|
||||
infested: false,
|
||||
poof: None,
|
||||
});
|
||||
}
|
||||
if m.random.next_boolean() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Silverfish.SilverfishMergeWithStoneGoal`: a stroll that, now and then
|
||||
/// with mob griefing on, hides in a stone block next to the silverfish.
|
||||
#[derive(Clone, Debug)]
|
||||
struct SilverfishMergeWithStone {
|
||||
stroll: Stroll,
|
||||
merge: Option<[i32; 3]>,
|
||||
}
|
||||
impl Default for SilverfishMergeWithStone {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stroll: Stroll::new(1.0).interval(10),
|
||||
merge: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for SilverfishMergeWithStone {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"SilverfishMergeWithStoneGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.ai.target.is_some() || !m.ai.nav.is_done() {
|
||||
return false;
|
||||
}
|
||||
if cx.w.mob_griefing
|
||||
&& m.random
|
||||
.next_int_bound(super::goals::reduced(10))
|
||||
.unwrap_or(1)
|
||||
== 0
|
||||
{
|
||||
// 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[m.random.next_int_bound(6).unwrap_or(0) as usize];
|
||||
let pos = [
|
||||
m.position.x.floor() as i32 + d[0],
|
||||
(m.position.y + 0.5).floor() as i32 + d[1],
|
||||
m.position.z.floor() as i32 + d[2],
|
||||
];
|
||||
if super::spawn_selection::infested_host(cx.w.block_name(pos[0], pos[1], pos[2])) {
|
||||
self.merge = Some(pos);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
self.merge = None;
|
||||
self.stroll.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.merge.is_none() && self.stroll.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(pos) = self.merge else {
|
||||
return self.stroll.start(m, cx);
|
||||
};
|
||||
if super::spawn_selection::infested_host(cx.w.block_name(pos[0], pos[1], pos[2])) {
|
||||
cx.events.push(MobEvent::Infest {
|
||||
pos,
|
||||
infested: true,
|
||||
poof: Some(m.id),
|
||||
});
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.stroll.stop(m, cx);
|
||||
}
|
||||
}
|
||||
/// Entity.getLightLevelDependentMagicValue at the eye.
|
||||
pub fn mob_brightness(m: &Mob, w: &MobWorld) -> f32 {
|
||||
w.brightness(
|
||||
|
||||
@@ -152,20 +152,7 @@ pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if !m.has_effect(INVISIBILITY) {
|
||||
return;
|
||||
}
|
||||
let hurt = m.hurt_time;
|
||||
let age = m.age;
|
||||
let mut il = m.extra.illusions.take().unwrap_or_default();
|
||||
il.ticks = (il.ticks - 1).max(0);
|
||||
if hurt == 1 || age.is_multiple_of(1200) {
|
||||
il.ticks = 3;
|
||||
for i in 0..COPIES {
|
||||
il.offsets[0][i] = il.offsets[1][i];
|
||||
let r = &mut m.random;
|
||||
let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
|
||||
let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64;
|
||||
let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
|
||||
il.offsets[1][i] = [x, y, z];
|
||||
}
|
||||
if step(m) {
|
||||
events.push(MobEvent::Particles {
|
||||
kind: "minecraft:cloud",
|
||||
at: [m.position.x, m.position.y + 0.9, m.position.z],
|
||||
@@ -177,6 +164,47 @@ pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// `Illusioner.aiStep` on a client of a server: invisible is the synched
|
||||
/// shared flag. The puff is drawn here exactly (sixteen `addParticle`s); the
|
||||
/// sound comes from the server.
|
||||
pub fn client_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if !m.invisible || !step(m) {
|
||||
return;
|
||||
}
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
for _ in 0..16 {
|
||||
// getRandomX(0.5), getRandomY() and getZ(0.5), which is not random.
|
||||
let x = m.position.x + w * (2.0 * m.random.next_double() - 1.0) * 0.5;
|
||||
let y = m.position.y + h * m.random.next_double();
|
||||
events.push(MobEvent::ParticleAt {
|
||||
kind: "cloud",
|
||||
at: [x, y, m.position.z + w * 0.5],
|
||||
velocity: [0.0; 3],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The image offsets' clock of an invisible illusioner. True when the images
|
||||
/// jumped to new offsets (hurt, or once a minute), which the puff goes with.
|
||||
fn step(m: &mut Mob) -> bool {
|
||||
let hurt = m.hurt_time;
|
||||
let age = m.age;
|
||||
let mut il = m.extra.illusions.take().unwrap_or_default();
|
||||
il.ticks = (il.ticks - 1).max(0);
|
||||
let jumped = hurt == 1 || age.is_multiple_of(1200);
|
||||
if jumped {
|
||||
il.ticks = 3;
|
||||
for i in 0..COPIES {
|
||||
il.offsets[0][i] = il.offsets[1][i];
|
||||
let r = &mut m.random;
|
||||
let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
|
||||
let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64;
|
||||
let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
|
||||
il.offsets[1][i] = [x, y, z];
|
||||
}
|
||||
} else if hurt == 9 {
|
||||
il.ticks = 3;
|
||||
for i in 0..COPIES {
|
||||
@@ -185,6 +213,7 @@ pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
}
|
||||
m.extra.illusions = Some(il);
|
||||
jumped
|
||||
}
|
||||
|
||||
/// `Illusioner.getIllusionOffsets`.
|
||||
|
||||
@@ -505,7 +505,14 @@ impl Mob {
|
||||
/// Entity.move with block collisions and step-up; updates collision flags
|
||||
/// and fall distance (Entity.checkFallDamage).
|
||||
pub fn do_move(&mut self, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let wanted = self.velocity;
|
||||
let mut wanted = self.velocity;
|
||||
// Entity.move: a block the mob is stuck in (sweet berry bush) scales
|
||||
// this move once and stops it.
|
||||
if self.stuck_multiplier.length_squared() > 1.0e-7 {
|
||||
wanted = wanted.multiply(self.stuck_multiplier);
|
||||
self.stuck_multiplier = Vec3::ZERO;
|
||||
self.velocity = Vec3::ZERO;
|
||||
}
|
||||
let step = self.kind.step_height as f32;
|
||||
let mut scene = SceneCollisions {
|
||||
world: w.world,
|
||||
@@ -990,8 +997,14 @@ impl Mob {
|
||||
movement.y = 0.2;
|
||||
}
|
||||
let mut y = movement.y;
|
||||
if self.extra.levitation > 0 {
|
||||
y += (0.05 * 1.0 - movement.y) * 0.2;
|
||||
// LivingEntity.travelInAir: levitation lifts by its amplifier.
|
||||
if let Some(&(_, _, amp)) = self
|
||||
.extra
|
||||
.effects
|
||||
.iter()
|
||||
.find(|e| e.0 == "minecraft:levitation")
|
||||
{
|
||||
y += (0.05 * f64::from(amp + 1) - movement.y) * 0.2;
|
||||
} else {
|
||||
y -= self.gravity();
|
||||
}
|
||||
|
||||
@@ -293,19 +293,28 @@ fn bubbles(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
f64::from(yaw.cos() * pitch.cos()),
|
||||
];
|
||||
let spread = m.random.next_double() * 0.8 * (1.0 + speed);
|
||||
for _ in 0..3 {
|
||||
let _ = (f64::from(m.random.next_float()) - 0.5) * spread;
|
||||
}
|
||||
events.push(MobEvent::Particles {
|
||||
let velocity = [
|
||||
(f64::from(m.random.next_float()) - 0.5) * spread,
|
||||
(f64::from(m.random.next_float()) - 0.5) * spread,
|
||||
(f64::from(m.random.next_float()) - 0.5) * spread,
|
||||
];
|
||||
events.push(MobEvent::ParticleAt {
|
||||
kind: "bubble",
|
||||
at: [
|
||||
m.position.x - dir[0] * 1.1,
|
||||
m.position.y - dir[1] + 0.25,
|
||||
m.position.z - dir[2] * 1.1,
|
||||
],
|
||||
count: 1,
|
||||
velocity,
|
||||
});
|
||||
}
|
||||
/// `AbstractNautilus.tick` on a client of a server: the bubbles of a nautilus
|
||||
/// in the water, from the motion the server sent.
|
||||
pub fn client_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if m.fluids.in_water {
|
||||
bubbles(m, events);
|
||||
}
|
||||
}
|
||||
fn in_water_at(w: &MobWorld, p: Vec3) -> bool {
|
||||
w.fluid(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32) == Fluid::Water
|
||||
}
|
||||
|
||||
@@ -580,6 +580,11 @@ impl Mob {
|
||||
if self.species() == super::Species::Bee {
|
||||
return super::bee::stable_destination(w, p);
|
||||
}
|
||||
if self.species() == super::Species::Turtle
|
||||
&& let Some(stable) = super::turtle::stable_destination(self, w, p)
|
||||
{
|
||||
return stable;
|
||||
}
|
||||
// StriderPathNavigation: lava too.
|
||||
if self.kind.flags.lava_walker && w.block_name(p[0], p[1], p[2]) == "minecraft:lava" {
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! What `Parrot.aiStep` adds: imitating the mobs around it (`imitateNearbyMobs`,
|
||||
//! the ambient sound of `getAmbient`) and dancing near a playing jukebox.
|
||||
use super::{Mob, MobEvent, MobWorld, Species};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
|
||||
/// `Parrot.MOB_SOUND_MAP` (the happy ghast's is `SoundEvents.EMPTY`: "").
|
||||
const IMITATIONS: [(Species, &str); 41] = [
|
||||
(Species::Blaze, "entity.parrot.imitate.blaze"),
|
||||
(Species::Bogged, "entity.parrot.imitate.bogged"),
|
||||
(Species::Breeze, "entity.parrot.imitate.breeze"),
|
||||
(Species::CamelHusk, "entity.parrot.imitate.camel_husk"),
|
||||
(Species::CaveSpider, "entity.parrot.imitate.spider"),
|
||||
(Species::Creaking, "entity.parrot.imitate.creaking"),
|
||||
(Species::Creeper, "entity.parrot.imitate.creeper"),
|
||||
(Species::Drowned, "entity.parrot.imitate.drowned"),
|
||||
(
|
||||
Species::ElderGuardian,
|
||||
"entity.parrot.imitate.elder_guardian",
|
||||
),
|
||||
(Species::Endermite, "entity.parrot.imitate.endermite"),
|
||||
(Species::Evoker, "entity.parrot.imitate.evoker"),
|
||||
(Species::Ghast, "entity.parrot.imitate.ghast"),
|
||||
(Species::HappyGhast, ""),
|
||||
(Species::Guardian, "entity.parrot.imitate.guardian"),
|
||||
(Species::Hoglin, "entity.parrot.imitate.hoglin"),
|
||||
(Species::Husk, "entity.parrot.imitate.husk"),
|
||||
(Species::Illusioner, "entity.parrot.imitate.illusioner"),
|
||||
(Species::MagmaCube, "entity.parrot.imitate.magma_cube"),
|
||||
(Species::Parched, "entity.parrot.imitate.parched"),
|
||||
(Species::Phantom, "entity.parrot.imitate.phantom"),
|
||||
(Species::Piglin, "entity.parrot.imitate.piglin"),
|
||||
(Species::PiglinBrute, "entity.parrot.imitate.piglin_brute"),
|
||||
(Species::Pillager, "entity.parrot.imitate.pillager"),
|
||||
(Species::Ravager, "entity.parrot.imitate.ravager"),
|
||||
(Species::Shulker, "entity.parrot.imitate.shulker"),
|
||||
(Species::Silverfish, "entity.parrot.imitate.silverfish"),
|
||||
(Species::Skeleton, "entity.parrot.imitate.skeleton"),
|
||||
(Species::Slime, "entity.parrot.imitate.slime"),
|
||||
(Species::Spider, "entity.parrot.imitate.spider"),
|
||||
(Species::Stray, "entity.parrot.imitate.stray"),
|
||||
(Species::Vex, "entity.parrot.imitate.vex"),
|
||||
(Species::Vindicator, "entity.parrot.imitate.vindicator"),
|
||||
(Species::Warden, "entity.parrot.imitate.warden"),
|
||||
(Species::Witch, "entity.parrot.imitate.witch"),
|
||||
(Species::Wither, "entity.parrot.imitate.wither"),
|
||||
(
|
||||
Species::WitherSkeleton,
|
||||
"entity.parrot.imitate.wither_skeleton",
|
||||
),
|
||||
(Species::Zoglin, "entity.parrot.imitate.zoglin"),
|
||||
(Species::Zombie, "entity.parrot.imitate.zombie"),
|
||||
(Species::ZombieHorse, "entity.parrot.imitate.zombie_horse"),
|
||||
(
|
||||
Species::ZombieNautilus,
|
||||
"entity.parrot.imitate.zombie_nautilus",
|
||||
),
|
||||
(
|
||||
Species::ZombieVillager,
|
||||
"entity.parrot.imitate.zombie_villager",
|
||||
),
|
||||
];
|
||||
|
||||
fn imitation(species: Species) -> Option<&'static str> {
|
||||
IMITATIONS.iter().find(|i| i.0 == species).map(|i| i.1)
|
||||
}
|
||||
|
||||
/// `Parrot.getPitch`.
|
||||
fn pitch(random: &mut LegacyRandom) -> f32 {
|
||||
(random.next_float() - random.next_float()) * 0.2 + 1.0
|
||||
}
|
||||
|
||||
/// The start of `Parrot.aiStep`: a jukebox that is gone or farther than
|
||||
/// 3.46 blocks stops the dance, and one tick in 400 the parrot imitates a
|
||||
/// mob nearby.
|
||||
pub fn ai_step(
|
||||
m: &mut Mob,
|
||||
w: &MobWorld,
|
||||
level_random: &mut LegacyRandom,
|
||||
events: &mut Vec<MobEvent>,
|
||||
) {
|
||||
if let Some(at) = m.extra.party_jukebox {
|
||||
let d = |i: usize, v: f64| f64::from(at[i]) + 0.5 - v;
|
||||
let (x, y, z) = (d(0, m.position.x), d(1, m.position.y), d(2, m.position.z));
|
||||
let jukebox = &*w.facts.get(w.world.block(at[0], at[1], at[2])).name == "minecraft:jukebox";
|
||||
if x * x + y * y + z * z >= 3.46 * 3.46 || !jukebox {
|
||||
m.extra.party_jukebox = None;
|
||||
}
|
||||
}
|
||||
if level_random.next_int_bound(400).unwrap_or(1) == 0 {
|
||||
imitate_nearby_mobs(m, w, level_random, events);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Parrot.imitateNearbyMobs`: half the time, a random imitable mob within 20
|
||||
/// blocks is heard through the parrot's own mouth.
|
||||
fn imitate_nearby_mobs(
|
||||
m: &Mob,
|
||||
w: &MobWorld,
|
||||
random: &mut LegacyRandom,
|
||||
events: &mut Vec<MobEvent>,
|
||||
) {
|
||||
if !m.alive() || m.silent || random.next_int_bound(2).unwrap_or(1) != 0 {
|
||||
return;
|
||||
}
|
||||
let area = m.bounds().inflate(Vec3::new(20.0, 20.0, 20.0));
|
||||
let mobs: Vec<_> = w
|
||||
.others
|
||||
.iter()
|
||||
.filter(|s| s.alive && imitation(s.species).is_some() && s.bounds.intersects(area))
|
||||
.collect();
|
||||
if mobs.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mob = mobs[random.next_int_bound(mobs.len() as i32).unwrap_or(0) as usize];
|
||||
if mob.silent {
|
||||
return;
|
||||
}
|
||||
if let Some(sound) = imitation(mob.species).filter(|s| !s.is_empty()) {
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
events.push(MobEvent::Sound(sound, at, 0.7, pitch(random)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `Parrot.getAmbient`: now and then (outside peaceful) the voice of a random
|
||||
/// imitable mob instead of the parrot's own.
|
||||
pub fn ambient(m: &mut Mob, w: &MobWorld) -> &'static str {
|
||||
if w.difficulty.effective > 0.0 && m.random.next_int_bound(1000).unwrap_or(1) == 0 {
|
||||
let i = m
|
||||
.random
|
||||
.next_int_bound(IMITATIONS.len() as i32)
|
||||
.unwrap_or(0);
|
||||
return IMITATIONS[i as usize].1;
|
||||
}
|
||||
"entity.parrot.ambient"
|
||||
}
|
||||
@@ -6,7 +6,8 @@ use super::{
|
||||
anim::{Poses, State},
|
||||
goals::{
|
||||
Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack,
|
||||
NearestTarget, Prey, RandomLookAround, Stroll, goal_clone,
|
||||
NearestTarget, Prey, RandomLookAround, Stroll, TARGET, TargetState, goal_clone,
|
||||
target_continue,
|
||||
},
|
||||
};
|
||||
use horizon_core::geometry::{Vec3, trig::Mth};
|
||||
@@ -62,15 +63,94 @@ pub fn register_piglin(m: &mut Mob) {
|
||||
m.ai.targets.add(1, hurt);
|
||||
m.ai.targets
|
||||
.add(2, NearestTarget::player(true).when(hostile_to_player));
|
||||
m.ai.targets.add(
|
||||
3,
|
||||
NearestTarget::new(
|
||||
Prey::Filter(|s| s.species == Species::Hoglin && s.baby),
|
||||
true,
|
||||
)
|
||||
.interval(10)
|
||||
.when(|m, _| !m.is_baby()),
|
||||
);
|
||||
m.ai.targets.add(3, HuntHoglin::default());
|
||||
// `PiglinAi.initMemories`: the first hunt waits too.
|
||||
m.extra.ints[0] = time_between_hunts(m);
|
||||
}
|
||||
/// `PiglinAi.TIME_BETWEEN_HUNTS`: 30 to 120 seconds.
|
||||
fn time_between_hunts(m: &mut Mob) -> i32 {
|
||||
m.random
|
||||
.next_int_between_inclusive(600, 2400)
|
||||
.unwrap_or(600)
|
||||
}
|
||||
/// `StartHuntingHoglin`: an adult piglin that is not angry, has not hunted
|
||||
/// recently and sees no adult piglin that has, goes for the nearest adult
|
||||
/// hoglin it sees; then it and the adult piglins near it wait before the next
|
||||
/// hunt, and the others join in (`broadcastAngerTarget`).
|
||||
#[derive(Clone, Debug)]
|
||||
struct HuntHoglin {
|
||||
found: Option<u32>,
|
||||
st: TargetState,
|
||||
}
|
||||
impl Default for HuntHoglin {
|
||||
fn default() -> Self {
|
||||
let mut st = TargetState::default();
|
||||
st.unseen_memory = 60;
|
||||
Self { found: None, st }
|
||||
}
|
||||
}
|
||||
impl Goal for HuntHoglin {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
TARGET
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.is_baby() || m.extra.ints[0] > 0 || m.extra.anger > 0 || m.ai.target.is_some() {
|
||||
return false;
|
||||
}
|
||||
let range = m.attrs.follow_range;
|
||||
let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z);
|
||||
let id = m.id;
|
||||
if cx
|
||||
.w
|
||||
.nearby(pos, range, |s| {
|
||||
s.id != id && s.species == Species::Piglin && !s.baby && s.hunted_recently
|
||||
})
|
||||
.next()
|
||||
.is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let hoglins: Vec<(u32, Vec3)> =
|
||||
cx.w.nearby(pos, range, |s| s.species == Species::Hoglin && !s.baby)
|
||||
.map(|s| (s.id, s.position))
|
||||
.collect();
|
||||
self.found = hoglins
|
||||
.into_iter()
|
||||
.find(|&(hoglin, at)| {
|
||||
m.distance_sqr(at) <= range * range && m.sees(cx.w, Who::Mob(hoglin))
|
||||
})
|
||||
.map(|(hoglin, _)| hoglin);
|
||||
self.found.is_some()
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
target_continue(&mut self.st, true, m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(hoglin) = self.found else { return };
|
||||
m.ai.target = Some(Who::Mob(hoglin));
|
||||
m.extra.ints[0] = time_between_hunts(m);
|
||||
let range = m.attrs.follow_range;
|
||||
let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z);
|
||||
let id = m.id;
|
||||
let others: Vec<u32> =
|
||||
cx.w.nearby(pos, range, |s| {
|
||||
s.id != id && s.species == Species::Piglin && !s.baby
|
||||
})
|
||||
.map(|s| s.id)
|
||||
.collect();
|
||||
for mob in others {
|
||||
let ticks = time_between_hunts(m);
|
||||
cx.events.push(MobEvent::HuntHoglin {
|
||||
mob,
|
||||
target: hoglin,
|
||||
ticks,
|
||||
});
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.ai.target = None;
|
||||
}
|
||||
}
|
||||
pub fn register_brute(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
@@ -394,6 +474,19 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if m.species() == Species::Hoglin && m.alive() {
|
||||
hoglin_repellent(m, w);
|
||||
}
|
||||
if m.species() == Species::Piglin {
|
||||
if m.extra.ints[0] > 0 {
|
||||
m.extra.ints[0] -= 1;
|
||||
}
|
||||
// `StopAttackingIfTargetInvalid`: a hoglin handed over by a hunt
|
||||
// broadcast has no target goal of its own to drop it when it dies.
|
||||
if let Some(who @ Who::Mob(_)) = m.ai.target
|
||||
&& w.target_info(who)
|
||||
.is_none_or(|t| !t.alive || !t.can_be_seen_as_enemy)
|
||||
{
|
||||
m.ai.target = None;
|
||||
}
|
||||
}
|
||||
if m.extra.anger > 0 {
|
||||
m.extra.anger -= 1;
|
||||
if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) {
|
||||
|
||||
@@ -46,6 +46,9 @@ pub struct State {
|
||||
/// Banners with no path to them, and until when (game time):
|
||||
/// `unreachableBannerCache`.
|
||||
pub unreachable_banners: Vec<(u32, i64)>,
|
||||
/// `PathfindToRaidGoal.tick` ran its 20 tick recruitment: the game
|
||||
/// recruits the raiders around this one.
|
||||
pub recruit_due: bool,
|
||||
/// Beds around the raid's centre.
|
||||
pub homes: Option<std::sync::Arc<Vec<[i32; 3]>>>,
|
||||
/// A ravager carrying a raider, set every tick from `Extra::rider`.
|
||||
@@ -105,6 +108,10 @@ pub fn state(m: &Mob) -> Option<&State> {
|
||||
pub fn state_mut(m: &mut Mob) -> &mut State {
|
||||
m.extra.raider.get_or_insert_with(Box::default)
|
||||
}
|
||||
/// `Raider.getCurrentRaid() != null`.
|
||||
pub fn in_raid(m: &Mob) -> bool {
|
||||
state(m).is_some_and(|s| s.raid_id.is_some())
|
||||
}
|
||||
pub fn has_active_raid(m: &Mob) -> bool {
|
||||
state(m).is_some_and(|s| s.active_raid)
|
||||
}
|
||||
@@ -122,7 +129,7 @@ pub fn register(m: &mut Mob) {
|
||||
m.extra.raider = Some(Box::default());
|
||||
m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595));
|
||||
m.ai.goals.add(1, ObtainBanner::default());
|
||||
m.ai.goals.add(3, PathfindToRaid);
|
||||
m.ai.goals.add(3, PathfindToRaid::default());
|
||||
m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0));
|
||||
m.ai.goals.add(5, Celebration);
|
||||
}
|
||||
@@ -379,9 +386,11 @@ impl Goal for ObtainBanner {
|
||||
}
|
||||
|
||||
/// `PathfindToRaidGoal`: outside the village, head for the raid's centre in
|
||||
/// hops of up to 15 blocks.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PathfindToRaid;
|
||||
/// hops of up to 15 blocks, recruiting nearby raiders every 20 ticks.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PathfindToRaid {
|
||||
recruitment_tick: i32,
|
||||
}
|
||||
impl PathfindToRaid {
|
||||
fn valid(s: &State) -> bool {
|
||||
s.active_raid && !s.raid_over && !s.in_village
|
||||
@@ -402,6 +411,12 @@ impl Goal for PathfindToRaid {
|
||||
let Some(c) = state(m).map(|s| s.raid_center) else {
|
||||
return;
|
||||
};
|
||||
if m.age as i32 > self.recruitment_tick {
|
||||
self.recruitment_tick = m.age as i32 + 20;
|
||||
if let Some(s) = m.extra.raider.as_deref_mut() {
|
||||
s.recruit_due = true;
|
||||
}
|
||||
}
|
||||
if m.ai.nav.is_done() {
|
||||
let to = [
|
||||
f64::from(c[0]) + 0.5,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user