Merge origin/main into refactor/horizon-command

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-26 22:06:35 +01:00
106 changed files with 4682 additions and 583 deletions
+30 -58
View File
@@ -26,35 +26,46 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
# The commit the event names: a fork's later pushes need another run-parity label.
# The commit the event names: a fork's later pushes need another run-parity label. The next step merges
# main into it.
ref: ${{ inputs.head }}
fetch-depth: 0
persist-credentials: false
# Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs.
clean: false
- name: The head merged into main (what merging it would land)
id: merge
env:
BASE_SHA: ${{ inputs.base }}
HEAD_SHA: ${{ inputs.head }}
run: |
# Harness fixes and game fixes that reached main since the branch was made then apply here too: a head
# tested alone failed harnesses already fixed on main (server_knockback before #2114, mob_ai's heap before
# #2270, save_roundtrip before #2212). Selection then compares with this main, so it sees only the pull
# request's own changes. A head that conflicts with main is tested alone.
set -euo pipefail
git merge --abort 2>/dev/null || true
git fetch -q --no-tags origin +refs/heads/main:refs/remotes/origin/main
main=$(git rev-parse origin/main)
if git -c user.name=parity -c user.email=parity@localhost merge -q --no-edit --no-ff "$main" >/dev/null 2>&1; then
echo "base=$main" >> "$GITHUB_OUTPUT"
echo "Tested: head ${HEAD_SHA:0:9} merged into main ${main:0:9}" | tee -a "$GITHUB_STEP_SUMMARY"
else
git merge --abort
echo "base=$BASE_SHA" >> "$GITHUB_OUTPUT"
echo "::warning::head ${HEAD_SHA:0:9} conflicts with main ${main:0:9}: tested alone, without main's fixes"
echo "Tested: head ${HEAD_SHA:0:9} alone (it conflicts with main ${main:0:9})" | tee -a "$GITHUB_STEP_SUMMARY"
fi
- uses: dtolnay/rust-toolchain@stable
- name: Tools from the runner
run: bash tools/ci/runner-env.sh
- name: Vanilla data, and resources prepared by this preparer
env:
BASE_SHA: ${{ inputs.base }}
run: |
# main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
# the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
set -euo pipefail
if git rev-parse --verify -q origin/main >/dev/null \
&& git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
bash "$RUNNER_TEMP/vanilla-data.sh"
else
bash tools/ci/vanilla-data.sh
fi
run: bash tools/ci/vanilla-data.sh
- name: The prepared output is the one the preparer's OUTPUT_VERSION says
env:
BASE_SHA: ${{ inputs.base }}
BASE_SHA: ${{ steps.merge.outputs.base }}
run: |
# The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither
# the tool nor the number, so there is nothing to check.
# A head made before OUTPUT_VERSION (#1947) that conflicts with main has neither the tool nor the number.
if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then
echo "This head's preparer has no OUTPUT_VERSION: nothing to check"
exit 0
@@ -65,47 +76,8 @@ jobs:
- name: The harnesses this change can affect
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ inputs.base }}
run: |
# main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a
# branch made before a better selection landed gets it too; the head's own runner then runs those
# harnesses. A branch that changes the selection itself selects with its own code.
set -euo pipefail
own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner
fork_point=$(git merge-base "$BASE_SHA" HEAD)
if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then
own
exit
fi
had_reach=$(git ls-files tools/parity_reach.py)
git show origin/main:tools/parity.py > tools/parity.py
git show origin/main:tools/parity_reach.py > tools/parity_reach.py
status=0
python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$?
git checkout -- tools/parity.py
if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi
cat .local/parity-selection.txt
if [ "$status" != 0 ]; then
echo "main's selection failed: the head's own selection runs"
own
exit
fi
names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true)
# The summary line says how many would run: a count that doesn't match the names read (a format change)
# must not let the job pass untested.
expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p')
count=$(printf '%s' "$names" | grep -c . || true)
if [ -z "$expected" ] || [ "$expected" != "$count" ]; then
echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs"
own
exit
fi
if [ "$count" = 0 ]; then
echo "Nothing to run."
exit 0
fi
# shellcheck disable=SC2086
python3 tools/parity.py $names --timeout 2400
BASE_SHA: ${{ steps.merge.outputs.base }}
run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
Generated
+7
View File
@@ -216,6 +216,13 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "beacons"
version = "0.1.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "bit-set"
version = "0.10.0"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", "crates/horizon-command", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", "crates/horizon-command", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "crates/horizon-mod-sdk/examples/beacons", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
resolver = "2"
[workspace.package]
+5
View File
@@ -266,6 +266,11 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
format!("{} quiet command(s)", lines.len())
}
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
Output::SetBlocks {
dimension, blocks, ..
} => {
format!("set {} block(s) in {dimension}", blocks.len())
}
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
Output::Shake { strength, seconds } => {
@@ -1057,6 +1057,7 @@ pub fn main() -> horizon_client::Result<()> {
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
effects: Vec::new(),
uuid: PLAYER_UUID,
allies: Default::default(),
remote: false,
@@ -164,6 +164,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
.iter()
.filter_map(|e| match e {
MotionEvent::Fall(e) => Some(e.trace()),
// The oracle's player wears no armor; the game applies this one.
MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt { .. }) => None,
MotionEvent::Health(e) => Some(e.trace()),
MotionEvent::Snowflake { position, velocity } => Some(format!(
"snowflake {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
+55 -3
View File
@@ -156,7 +156,11 @@ pub struct ArrowState {
/// `pickupItemStack`: what picking the arrow up gives.
pub pickup_item: crate::items::ItemStack,
pub no_physics: bool,
/// `AbstractArrow.getPierceLevel`.
pub pierce: u8,
/// `piercingIgnoreEntityIds`: the entities a piercing arrow has gone
/// through (cleared when it sticks in a block).
pub pierced: Vec<Who>,
/// `Entity.remainingFireTicks`.
pub fire_ticks: i32,
pub fall_distance: f64,
@@ -199,6 +203,7 @@ impl ArrowState {
pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1),
no_physics: false,
pierce: 0,
pierced: Vec::new(),
fire_ticks: 0,
fall_distance: 0.0,
fluids: EntityFluidInteraction::new([WATER, LAVA]),
@@ -362,6 +367,29 @@ fn bounds(at: Vec3) -> Aabb {
Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w),
)
}
/// The bounding box of an arrow, or a thrown trident, at `at`.
pub fn arrow_bounds(at: Vec3) -> Aabb {
bounds(at)
}
/// The blocks an arrow that moved from `from` to `to` was inside
/// (`Entity.checkInsideBlocks`: the sweep of its box, 16 steps at most), for
/// the blocks that react to it (`entityInside`).
pub fn blocks_inside(from: Vec3, to: Vec3) -> Vec<BlockPos> {
let deflated = bounds(to).deflate(Vec3::new(
f64::from(1.0e-5f32),
f64::from(1.0e-5f32),
f64::from(1.0e-5f32),
));
let mut inside = Vec::new();
let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| {
if iteration >= 16 {
return false;
}
inside.push(p);
true
});
inside
}
/// `Projectile.lerpRotation`.
fn lerp_rotation(mut old: f32, new: f32) -> f32 {
while new - old < -180.0 {
@@ -431,10 +459,19 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity
match outcome {
EntityHit::Hurt => {
ticker.hit_sound();
ticker.st.removed = true;
// A piercing arrow flies on (`getPierceLevel() <= 0` discards).
if ticker.st.pierce == 0 {
ticker.st.removed = true;
}
}
EntityHit::Refused => ticker.turn_back(),
EntityHit::Deflected => {}
EntityHit::Deflected => {
// The deflection comes before `onHitEntity` adds the entity to
// `piercingIgnoreEntityIds`.
if ticker.st.pierce > 0 {
ticker.st.pierced.pop();
}
}
}
ticker.finish();
p.stuck = st.in_ground;
@@ -639,7 +676,8 @@ impl Ticker<'_, '_, '_, '_> {
self.st.life = 0;
}
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
/// block (piercing is not modelled).
/// block. A piercing arrow that hits an entity here goes on from it next
/// tick (`finish_entity_hit`); vanilla's loop goes on within the same tick.
fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit {
let block = self.scene.clip(from, to);
let end = block.map_or(to, |b| b.0);
@@ -653,6 +691,10 @@ impl Ticker<'_, '_, '_, '_> {
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
continue;
}
// canHitEntity: not an entity a piercing arrow has gone through.
if self.st.pierced.contains(who) {
continue;
}
if let Some(at) = self.entity_hit(b, from, end, margin) {
// Sorted by the distance to the entity's position (the
// stable sort keeps the first of equals).
@@ -667,6 +709,15 @@ impl Ticker<'_, '_, '_, '_> {
self.p.position = next;
self.apply_effects_from_blocks(from, next);
if let Some((who, at, _)) = best {
// AbstractArrow.onHitEntity: past pierce level + 1 entities the
// arrow is discarded before it hurts the next one.
if self.st.pierce > 0 {
if self.st.pierced.len() > usize::from(self.st.pierce) {
self.st.removed = true;
return Hit::None;
}
self.st.pierced.push(who);
}
return Hit::Entity { who, at };
}
let Some((at, pos, face)) = block else {
@@ -752,6 +803,7 @@ impl Ticker<'_, '_, '_, '_> {
self.st.shake = 7;
self.p.set_critical(false);
self.st.pierce = 0;
self.st.pierced.clear();
}
/// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`.
fn may_interact(&self) -> bool {
@@ -648,6 +648,61 @@ impl Conduit {
}
}
/// What `ConduitBlockEntity.serverTick`'s 40-tick check decided.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ConduitCheck {
/// The shape changed: `CONDUIT_ACTIVATE` (true) or `CONDUIT_DEACTIVATE`.
pub toggled: Option<bool>,
/// The frame blocks counted, while the conduit is active: `applyEffects`
/// and `updateAndAttackTarget` follow (the attack needs 42 or more).
pub frames: Option<usize>,
}
/// `ConduitBlockEntity` (server side): what `serverTick` keeps between ticks.
#[derive(Clone, Debug, Default)]
pub struct ConduitServer {
shape: Conduit,
/// `destroyTarget`: the mob id of the enemy being struck.
pub target: Option<u32>,
next_ambient_sound: i64,
}
impl ConduitServer {
/// The `gameTime % 40` part of `serverTick`: the shape is checked again.
pub fn check(
&mut self,
pos: [i32; 3],
game_time: i64,
is_water: impl Fn([i32; 3]) -> bool,
is_frame: impl Fn([i32; 3]) -> bool,
) -> Option<ConduitCheck> {
if game_time % 40 != 0 {
return None;
}
let active = self.shape.update_shape(pos, &is_water, &is_frame);
let toggled = (active != self.shape.is_active).then_some(active);
self.shape.is_active = active;
Some(ConduitCheck {
toggled,
frames: active.then_some(self.shape.effect_blocks.len()),
})
}
/// The sounds of an active conduit at the end of `serverTick`: whether
/// `CONDUIT_AMBIENT` (every 80 ticks) and `CONDUIT_AMBIENT_SHORT` (every
/// 60 to 99 ticks) play.
pub fn ambient(&mut self, game_time: i64, random: &mut impl RandomSource) -> (bool, bool) {
if !self.shape.is_active {
return (false, false);
}
let short = game_time > self.next_ambient_sound;
if short {
self.next_ambient_sound =
game_time + 60 + i64::from(random.next_int_bound(40).unwrap_or(0));
}
(game_time % 80 == 0, short)
}
}
/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Skull {
@@ -832,6 +887,8 @@ pub struct BlockEntityAnims {
pub gateways: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the gateways (`portalTick`).
pub gateway_servers: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the conduits (`serverTick`).
pub conduit_servers: FxHashMap<[i32; 3], ConduitServer>,
/// The client level's random (conduit particles).
pub random: LegacyRandom,
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
@@ -854,6 +911,7 @@ impl Default for BlockEntityAnims {
pots: FxHashMap::default(),
gateways: FxHashMap::default(),
gateway_servers: FxHashMap::default(),
conduit_servers: FxHashMap::default(),
random: LegacyRandom::new(0x6c6576656c),
kinds: Vec::new(),
present: Vec::new(),
@@ -909,6 +967,7 @@ impl BlockEntityAnims {
self.pots.retain(|p, _| keep(*p));
self.gateways.retain(|p, _| keep(*p));
self.gateway_servers.retain(|p, _| keep(*p));
self.conduit_servers.retain(|p, _| keep(*p));
}
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
+13 -3
View File
@@ -98,6 +98,9 @@ pub enum BlockEntity {
Campfire(Box<Campfire>),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
/// `DaylightDetectorBlockEntity`: no data, only the ticker
/// (`DaylightDetectorBlock.tickEntity`).
DaylightDetector,
}
/// `CampfireBlockEntity`: four cooking slots, each with its
/// `cookingProgress` and `cookingTime` (the recipe's).
@@ -363,6 +366,9 @@ impl BlockEntity {
if is_skull(name) {
return Some(Self::Skull(Skull::default()));
}
if name == "minecraft:daylight_detector" {
return Some(Self::DaylightDetector);
}
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -412,6 +418,7 @@ impl BlockEntity {
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
Self::DaylightDetector => "minecraft:daylight_detector",
Self::Campfire(_) => "minecraft:campfire",
}
}
@@ -429,7 +436,8 @@ impl BlockEntity {
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_)
| Self::Skull(_) => Vec::new(),
| Self::Skull(_)
| Self::DaylightDetector => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -448,7 +456,8 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
| Self::Skull(_) => &[],
| Self::Skull(_)
| Self::DaylightDetector => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
@@ -471,7 +480,8 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
| Self::Skull(_) => &mut [],
| Self::Skull(_)
| Self::DaylightDetector => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
+66 -9
View File
@@ -95,6 +95,15 @@ impl ItemEntity {
self.health -= fire_damage as i32;
}
}
// CactusBlock.entityInside: `entity.hurt(cactus, 1.0)`. An item has no
// hurt cooldown, so it loses 1 health every tick it touches a cactus
// (5 health: gone in 5 ticks). Fire resistance does not help;
// `ItemStack.canBeHurtBy` only skips it for a damage_resistant stack.
if crate::motion::environment::cactus_contact(world, registry, self.bounds())
&& !items.resists_cactus(&self.stack)
{
self.health -= 1;
}
ItemEnvironmentTick {
alive: self.health > 0,
lava_hurt,
@@ -385,8 +394,29 @@ pub struct ExperienceOrb {
pub value: u32,
pub age: u32,
pub on_ground: bool,
/// `ExperienceOrb.count`: orbs merged into this one; each pickup gives
/// `value` once and takes one off.
pub count: u32,
/// `Entity.tickCount`, which paces `ExperienceOrb.scanForMerges`.
pub ticks: u32,
}
impl ExperienceOrb {
pub fn bounds(&self) -> Aabb {
let h = 0.25;
Aabb::new(
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
Vec3::new(
self.position.x + h,
self.position.y + 0.5,
self.position.z + h,
),
)
}
/// `ExperienceOrb.canMerge(orb, id, value)` for an orb that is not removed:
/// the same value and ids a multiple of 40 apart.
pub fn can_merge(&self, id: u32, value: u32) -> bool {
self.value == value && (self.id as i32).wrapping_sub(id as i32) % 40 == 0
}
/// ExperienceOrb.getExperienceValue: the largest orb size not above `value`.
pub fn split(value: u32) -> u32 {
[2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1]
@@ -416,7 +446,9 @@ impl ExperienceOrb {
facts: &BlockFacts,
collision: &BlockCollisionRegistry<'_>,
player: Option<[f64; 3]>,
next_float: &mut dyn FnMut() -> f32,
) -> bool {
self.ticks += 1;
self.previous = self.position;
let block = world.block(
self.position.x.floor() as i32,
@@ -432,6 +464,14 @@ impl ExperienceOrb {
} else {
self.velocity.y -= 0.03;
}
if facts.get(block).fluid == Fluid::Lava {
// ExperienceOrb.tick: lava throws the orb back out.
self.velocity = Vec3::new(
f64::from((next_float() - next_float()) * 0.2),
f64::from(0.2f32),
f64::from((next_float() - next_float()) * 0.2),
);
}
if let Some(p) = player {
let d = [
(p[0] - self.position.x) / 8.0,
@@ -449,15 +489,7 @@ impl ExperienceOrb {
);
}
}
let h = 0.25;
let bounds = Aabb::new(
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
Vec3::new(
self.position.x + h,
self.position.y + 0.5,
self.position.z + h,
),
);
let bounds = self.bounds();
let mut scene = SceneCollisions {
world,
binding: collision,
@@ -494,6 +526,31 @@ impl ExperienceOrb {
self.age < 6000
}
}
/// `ExperienceOrb.scanForMerges`, run by each orb on `tickCount % 20 == 1`:
/// it absorbs the orbs that `canMerge` within 0.5 blocks of its box,
/// adding their counts and keeping the smaller age.
pub fn merge_orbs(orbs: &mut Vec<ExperienceOrb>) {
let mut removed = vec![false; orbs.len()];
for i in 0..orbs.len() {
if removed[i] || orbs[i].ticks % 20 != 1 {
continue;
}
let area = orbs[i].bounds().inflate(Vec3::new(0.5, 0.5, 0.5));
for j in 0..orbs.len() {
if j != i
&& !removed[j]
&& orbs[j].can_merge(orbs[i].id, orbs[i].value)
&& orbs[j].bounds().intersects(area)
{
orbs[i].count += orbs[j].count;
orbs[i].age = orbs[i].age.min(orbs[j].age);
removed[j] = true;
}
}
}
let mut removed = removed.into_iter();
orbs.retain(|_| !removed.next().unwrap_or(false));
}
/// Player experience (Player.giveExperiencePoints / getXpNeededForNextLevel).
#[derive(Clone, Copy, Debug, Default)]
pub struct Experience {
+152 -14
View File
@@ -265,6 +265,19 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Tag::Byte(i8::from(m.extra.flag2)),
);
map.insert("TimeInOverworld".into(), Tag::Int(m.extra.counter2));
if id == "minecraft:piglin" {
// InventoryCarrier.writeInventoryToTag.
map.insert(
"Inventory".into(),
Tag::List(
m.extra
.inventory
.iter()
.map(crate::save::item_to_nbt)
.collect(),
),
);
}
}
"minecraft:horse"
| "minecraft:donkey"
@@ -357,6 +370,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:bat" => {
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
}
"minecraft:turtle" => {
map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag)));
if let Some(home) = m.extra.home {
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
}
}
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
@@ -482,7 +501,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:zombie" => {
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
for (key, value) in [
("CanBreakDoors", Tag::Byte(0)),
("DrownedConversionTime", Tag::Int(-1)),
("InWaterTime", Tag::Int(-1)),
] {
@@ -507,6 +525,13 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
_ => {}
}
// Zombie.addAdditionalSaveData: CanBreakDoors.
if crate::mobs::doors::is_zombie(m.species()) {
map.insert(
"CanBreakDoors".into(),
Tag::Byte(i8::from(m.extra.can_break_doors)),
);
}
crate::mobs::raider::write_nbt(m, map);
crate::mobs::riders::write_nbt(m, map);
// LivingEntity equipment: what the mob holds now.
@@ -706,6 +731,16 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
) {
m.extra.flag2 = flag(tag, "IsImmuneToZombification");
m.extra.counter2 = number(tag.get("TimeInOverworld")).unwrap_or(0) as i32;
if m.species() == crate::mobs::Species::Piglin
&& let Some(Tag::List(items)) = tag.get("Inventory")
{
// InventoryCarrier.readInventoryFromTag (eight slots).
m.extra.inventory = items
.iter()
.filter_map(crate::save::item_from_nbt)
.take(8)
.collect();
}
}
if matches!(
m.species(),
@@ -847,6 +882,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
{
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
}
if m.species() == crate::mobs::Species::Turtle {
// Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`.
m.extra.flag = flag(tag, "has_egg");
m.extra.home = Some(match tag.get("home_pos") {
Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]],
_ => [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
],
});
}
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
@@ -925,6 +972,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") {
crate::mobs::finalize::set_baby(&mut m, true);
}
// Zombie.readAdditionalSaveData: setCanBreakDoors.
if crate::mobs::doors::is_zombie(m.species()) {
crate::mobs::doors::set_can_break_doors(&mut m, flag(tag, "CanBreakDoors"));
}
crate::mobs::raider::read_nbt(&mut m, tag);
crate::mobs::riders::read_nbt(&mut m, tag);
// A mob saved mid-death finishes dying; one saved dead is dropped.
@@ -1043,18 +1094,18 @@ pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
("Health", Tag::Short(5)),
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
("Value", Tag::Short(o.value.min(i16::MAX as u32) as i16)),
("Count", Tag::Int(1)),
("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)),
] {
put(&mut tag, key, value);
}
tag
}
/// One Horizon orb per counted orb (vanilla merges orbs of equal value).
/// One orb with its merged `Count`.
pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
let Some(position) = position(tag) else {
return Vec::new();
};
let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32;
let orb = ExperienceOrb {
id: 0,
position,
@@ -1063,8 +1114,10 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
value: number(tag.get("Value")).unwrap_or(1).max(1) as u32,
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
on_ground: flag(tag, "OnGround"),
count,
ticks: 0,
};
vec![orb; count]
vec![orb]
}
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
@@ -1913,7 +1966,7 @@ mod tests {
assert_eq!(number(tag.get("Health")), Some(5));
}
#[test]
fn orbs_expand_their_count() {
fn orbs_keep_their_count() {
let o = ExperienceOrb {
id: 0,
position: Vec3::new(1.0, 2.0, 3.0),
@@ -1922,12 +1975,14 @@ mod tests {
value: 7,
age: 3,
on_ground: false,
count: 3,
ticks: 0,
};
let mut tag = orb_to_nbt(&o, [0; 4]);
put(&mut tag, "Count", Tag::Int(3));
let tag = orb_to_nbt(&o, [0; 4]);
let back = orbs_from_nbt(&tag);
assert_eq!(back.len(), 3);
assert_eq!(back.len(), 1);
assert_eq!(back[0].value, 7);
assert_eq!(back[0].count, 3);
}
}
@@ -1992,12 +2047,39 @@ fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
}
}
const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
/// `Salmon.Variant` names, by id.
const SALMON_SIZES: [&str; 3] = ["small", "medium", "large"];
/// `TropicalFish.Pattern` names in enum order: the six small patterns, then
/// the six large ones (the order of `extra.variant`).
const TROPICAL_PATTERNS: [&str; 12] = [
"kob",
"sunstreak",
"snooper",
"dasher",
"brinely",
"spotty",
"flopper",
"stripey",
"glitter",
"blockfish",
"betty",
"clayfish",
];
/// `Bucketable.saveDefaultDataToBucketTag`, with the age an axolotl and a
/// tadpole add (`saveToBucketTag`).
pub fn bucket_data(m: &Mob) -> Tag {
let mut data = Tag::compound([
("Age", Tag::Int(m.extra.age)),
("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))),
("Health", Tag::Float(m.health.to_bits())),
]);
let mut data = Tag::compound([("Health", Tag::Float(m.health.to_bits()))]);
if matches!(
m.species(),
crate::mobs::Species::Axolotl | crate::mobs::Species::Tadpole
) {
put(&mut data, "Age", Tag::Int(m.extra.age));
put(
&mut data,
"AgeLocked",
Tag::Byte(i8::from(m.extra.age_locked)),
);
}
for (key, on) in [
("NoAI", m.no_ai),
("Silent", m.silent),
@@ -2027,6 +2109,29 @@ pub fn bucket_components(m: &Mob) -> crate::item_data::StackData {
.unwrap_or(&"lucy");
data.set_other("minecraft:axolotl/variant", Some(string(variant)));
}
// Salmon.saveToBucketTag: the size.
if m.species() == crate::mobs::Species::Salmon {
let size = SALMON_SIZES
.get(usize::from(m.extra.variant))
.unwrap_or(&"medium");
data.set_other("minecraft:salmon/size", Some(string(size)));
}
// TropicalFish.saveToBucketTag: the pattern and both colours.
if m.species() == crate::mobs::Species::TropicalFish {
let dye = |i: u8| crate::mobs::render::DYE_NAMES[usize::from(i) & 15];
let pattern = TROPICAL_PATTERNS
.get(usize::from(m.extra.variant))
.unwrap_or(&"kob");
data.set_other("minecraft:tropical_fish/pattern", Some(string(pattern)));
data.set_other(
"minecraft:tropical_fish/base_color",
Some(string(dye(m.extra.variant2))),
);
data.set_other(
"minecraft:tropical_fish/pattern_color",
Some(string(dye(m.extra.variant3))),
);
}
data
}
pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
@@ -2077,6 +2182,39 @@ pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
{
m.extra.variant = id as u8;
}
// Salmon.applyImplicitComponents: the size.
if m.species() == crate::mobs::Species::Salmon
&& let Some(name) = text(components.other("minecraft:salmon/size"))
&& let Some(id) = SALMON_SIZES
.iter()
.position(|&v| v == name.trim_start_matches("minecraft:"))
{
m.extra.variant = id as u8;
}
// TropicalFish.applyImplicitComponent: the pattern and both colours.
if m.species() == crate::mobs::Species::TropicalFish {
let name = |key| text(components.other(key));
let dye = |key| {
name(key).and_then(|n| {
crate::mobs::render::DYE_NAMES
.iter()
.position(|&v| v == n.trim_start_matches("minecraft:"))
})
};
if let Some(id) = name("minecraft:tropical_fish/pattern").and_then(|n| {
TROPICAL_PATTERNS
.iter()
.position(|&v| v == n.trim_start_matches("minecraft:"))
}) {
m.extra.variant = id as u8;
}
if let Some(id) = dye("minecraft:tropical_fish/base_color") {
m.extra.variant2 = id as u8;
}
if let Some(id) = dye("minecraft:tropical_fish/pattern_color") {
m.extra.variant3 = id as u8;
}
}
}
#[cfg(test)]
+236 -48
View File
@@ -186,6 +186,7 @@ mod win;
mod wind;
mod wither;
mod world_loading;
mod zombie_reinforcements;
mod zombie_villagers;
use horizon_client::{
Result,
@@ -537,6 +538,8 @@ struct GameLevel<'w> {
events: &'w mut Vec<LevelEvent>,
dimension: LevelDimension,
darken: i32,
/// The environment of the level's dimension (`SUN_ANGLE`).
environment: &'w Environment,
raining: bool,
thundering: bool,
player_box: Option<([f64; 3], [f64; 3])>,
@@ -545,6 +548,8 @@ struct GameLevel<'w> {
player_collision: Option<PlayerCollision>,
/// Minecart boxes (detector rails).
cart_boxes: Vec<([f64; 3], [f64; 3])>,
/// 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>,
biomes: &'w Biomes,
@@ -803,6 +808,11 @@ impl LevelAccess for GameLevel<'_> {
fn sky_darken(&self) -> i32 {
self.darken
}
fn sun_angle(&self, _pos: BlockPos) -> f32 {
self.environment
.sample(self.world.day_time, None, None)
.sun_angle
}
fn is_raining(&self) -> bool {
self.raining
}
@@ -871,8 +881,9 @@ impl LevelAccess for GameLevel<'_> {
fn is_ticking_chunk(&self, chunk: horizon_core::position::ChunkPos) -> bool {
self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z)
}
/// Entities that trigger pressure plates, tripwires and detector rails:
/// the players (the host and the LAN guests, mobs) and the minecarts.
/// 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.
fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize {
let hit = |(lo, hi): &([f64; 3], [f64; 3])| {
area.intersects(Aabb::new(
@@ -881,6 +892,7 @@ impl LevelAccess for GameLevel<'_> {
))
};
let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count();
let arrows = || self.arrow_boxes.iter().filter(|b| hit(b)).count();
let players = || {
self.player_box
.iter()
@@ -890,6 +902,7 @@ impl LevelAccess for GameLevel<'_> {
};
match query {
EntityQuery::Minecart => carts(),
EntityQuery::Arrows => arrows(),
EntityQuery::Mobs => players(),
EntityQuery::Everything => players() + carts(),
}
@@ -2225,8 +2238,9 @@ impl Game<'_> {
ticks: 0,
});
}
/// `Block.getDrops`: the block's loot table, drawing from its server random
/// sequence (`LootContext.Builder.create`), else the level random.
/// `Block.getDrops` for a block a player breaks: the block's loot table
/// with the player as `this`, drawing from its server random sequence
/// (`LootContext.Builder.create`), else the level random.
fn block_loot_at(
&mut self,
pos: [i32; 3],
@@ -2240,9 +2254,9 @@ impl Game<'_> {
let random = self.rand_sequences.get(&sequence, self.level.seed);
self.res
.items()
.block_drops_with(registry, state, held, &dynamic, random)
.block_drops_by_player(registry, state, held, &dynamic, random)
}
None => self.res.items().block_drops_with(
None => self.res.items().block_drops_by_player(
registry,
state,
held,
@@ -2286,11 +2300,13 @@ impl Game<'_> {
// Player.drop: the drop statistics.
self.stats.add("dropped", &thrown.item, thrown.count as i32);
self.stats.custom("drop", 1);
self.throw_from_eyes(thrown, eye);
self.throw_from_eyes(thrown, eye, true);
}
/// `Player.createItemStackToDrop`: an item entity thrown from the eyes
/// along the view direction.
fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3]) {
/// along the view direction. `thrown_from_hand` (`drop(stack, true)`, the
/// drop key) names the player as the thrower; `drop(stack, false)`, for
/// what no longer fits in the inventory, does not.
fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3], thrown_from_hand: bool) {
let (yaw, pitch) = (
f64::from(self.yaw).to_radians(),
f64::from(self.pitch).to_radians(),
@@ -2304,7 +2320,7 @@ impl Game<'_> {
yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength,
];
self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40);
if self.lan_acting.is_none() {
if thrown_from_hand && self.lan_acting.is_none() {
let uuid = self.level.ensure_player_uuid();
self.dropped.last_mut().unwrap().thrower = Some(uuid);
}
@@ -2511,6 +2527,18 @@ impl Game<'_> {
)
})
.collect();
let arrow_boxes = self
.creatures
.projectiles
.iter()
.filter(|p| p.arrow.is_some())
.map(|p| p.position)
.chain(self.tridents.iter().map(|t| t.position))
.map(|at| {
let b = horizon_client::arrows::arrow_bounds(at);
(b.min_position().components(), b.max_position().components())
})
.collect();
let guest_boxes = self.lan_block_trigger_boxes();
let dimension = match self.dim {
Dim::Overworld => LevelDimension::Overworld,
@@ -2541,6 +2569,7 @@ impl Game<'_> {
};
let mut level = GameLevel {
cart_boxes,
arrow_boxes,
blockers,
world: &mut self.world,
facts: self.res.facts(),
@@ -2548,6 +2577,11 @@ impl Game<'_> {
events: &mut self.level_events,
dimension,
darken,
environment: match dimension {
LevelDimension::Overworld => self.res.environment(),
LevelDimension::Nether => self.res.nether_environment(),
LevelDimension::End => self.res.end_environment(),
},
raining: rain > 0.2,
thundering: thunder > 0.9,
player_box,
@@ -2674,8 +2708,9 @@ impl Game<'_> {
.copied()
.filter(|&(x, z)| levels.random_ticking(x, z) && ticking_chunk(&self.world, x, z))
.collect();
// Entity.checkInsideBlocks for the plates, tripwires and detector rails
// under the players (the host and the LAN guests) and the minecarts.
// Entity.checkInsideBlocks for the plates, tripwires, detector rails and
// buttons under the players (the host and the LAN guests), the minecarts
// and the arrows.
let mut inside = Vec::new();
let guests = self.lan_block_trigger_boxes();
let boxes = self
@@ -2707,6 +2742,24 @@ impl Game<'_> {
}
}
}
// AbstractArrow.applyEffectsFromBlocks: the blocks every arrow passed
// through this tick (a wooden button is pressed by one inside it), and
// the ones a thrown trident is in.
for p in self
.creatures
.projectiles
.iter()
.filter(|p| p.arrow.is_some())
{
inside.extend(horizon_client::arrows::blocks_inside(
p.previous, p.position,
));
}
for t in &self.tridents {
inside.extend(horizon_client::arrows::blocks_inside(
t.position, t.position,
));
}
// BigDripleafBlock.entityInside also asks whether the player stands on
// the ground and how high its feet are: the leaves its box's feet
// layer is inside (the host and the LAN guests).
@@ -2901,6 +2954,9 @@ impl Game<'_> {
1501 => Some(("minecraft:block.lava.extinguish", 0.5)),
1009 => Some(("minecraft:block.fire.extinguish", 0.5)),
1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)),
// LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break).
1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)),
1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)),
1030 => Some(("minecraft:block.anvil.use", 1.0)),
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
1031 => Some(("minecraft:block.anvil.land", 0.3)),
@@ -2920,9 +2976,14 @@ impl Game<'_> {
1029 | 1030 | 1042 | 1043 | 1044 => {
self.world.random.next_float() * 0.1 + 0.9
}
1019 | 1021 => {
(self.world.random.next_float() - self.world.random.next_float())
* 0.2
+ 1.0
}
_ => 1.0,
};
if matches!(id, 1029 | 1030) {
if matches!(id, 1019 | 1021 | 1029 | 1030) {
// Clients play the anvil sound from its level event;
// capturing it also sends a duplicate sound packet.
self.audio.play_unshared(name, c, volume, pitch);
@@ -3052,6 +3113,11 @@ impl Game<'_> {
kind: "hatch_sniffer",
..
} => self.hatch_sniffer([pos.x, pos.y, pos.z]),
LevelEvent::BlockEvent {
pos,
state,
kind: "hatch_turtles",
} => self.hatch_turtles([pos.x, pos.y, pos.z], state),
LevelEvent::BlockEvent {
pos,
kind: "portal_spawn",
@@ -3089,6 +3155,10 @@ impl Game<'_> {
.name
.clone();
let key = (pos[0], pos[1], pos[2]);
if self.chest_menu_blocked(key, &name) {
// The use still succeeds, but no menu, stat or piglin anger.
return;
}
if &*name == "minecraft:lectern" {
self.open_lectern(pos);
return;
@@ -4435,12 +4505,6 @@ impl Game<'_> {
let events = std::mem::take(&mut player.events);
let spin_hit = player.spin_hit.take();
let glider_wear = std::mem::take(&mut player.glider_wear);
if glider_wear > 0
&& !self.creative
&& let Some(elytra) = self.armor[1].as_mut()
{
elytra.damage += glider_wear;
}
let feet = [player.position.x, player.position.y, player.position.z];
let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z];
self.previous_eye = self.eye;
@@ -4451,9 +4515,20 @@ impl Game<'_> {
};
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
// `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear.
if glider_wear > 0
&& !self.creative
&& let Some(stack) = self.armor[1].clone()
{
let loss = self.durability_loss(&stack, glider_wear);
if let Some(elytra) = self.armor[1].as_mut() {
elytra.damage += loss;
}
}
self.tick_avatar(before, riding);
self.end_spin_attack(spin_hit);
self.record_combat(&events);
self.wear_armor(&events);
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet),
@@ -4626,7 +4701,7 @@ impl Game<'_> {
&& let Some(stack) = self.carried.take()
&& let Some(eye) = self.eye_position()
{
self.throw_from_eyes(stack, eye);
self.throw_from_eyes(stack, eye, false);
}
}
self.tick_world(running)
@@ -4946,7 +5021,7 @@ impl Game<'_> {
self.capture(true);
}
}
fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
fn draw_item(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
self.draw_item_model(batch, stack, x, y);
@@ -5036,7 +5111,7 @@ impl Game<'_> {
/// `GuiGraphicsExtractor.itemDecorations`: the count (or `count_text`)
/// and damage bar.
fn draw_item_decorations(
&mut self,
&self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
@@ -5163,12 +5238,12 @@ impl Game<'_> {
for d in &draws {
if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d {
let stack = if slot == 40 {
self.offhand.clone()
self.offhand.as_ref()
} else {
self.inventory[slot as usize].clone()
self.inventory[slot as usize].as_ref()
};
if let Some(stack) = stack {
self.draw_item(&mut batch, &stack, x as f32, y as f32);
self.draw_item(&mut batch, stack, x as f32, y as f32);
}
}
}
@@ -5394,6 +5469,7 @@ impl Game<'_> {
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
) => {}
None => {
@@ -5665,6 +5741,7 @@ impl Game<'_> {
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
@@ -5732,7 +5809,8 @@ impl Game<'_> {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
// AbstractContainerMenu.dropOrPlaceInInventory: `drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
self.craft_size = 2;
@@ -7866,6 +7944,9 @@ impl Game<'_> {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
} else {
// Left for the end of the tick.
self.mobs[index].outbox.push(event);
}
}
self.weapon_hit(index);
@@ -8540,15 +8621,54 @@ impl Game<'_> {
}
self.apply_enchantment_attributes();
}
/// Inventory.hurtArmor: each piece loses max(1, damage / 4) durability.
fn hurt_armor(&mut self, damage: f32) {
/// The armor hits among a tick's motion events (`Player.hurtArmor` from
/// `getDamageAfterArmorAbsorb`), whatever the damage: a mob, an explosion,
/// a cactus, lava, a campfire.
fn wear_armor(&mut self, events: &[MotionEvent]) {
for event in events {
if let MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt {
source,
amount,
}) = event
{
self.hurt_armor(*source, *amount);
}
}
}
/// `Player.hurtArmor` -> `LivingEntity.doHurtEquipment`: each worn piece that
/// wears when its wearer is hurt loses max(1, damage / 4) durability, except
/// to a fire source when the piece resists fire (`ItemStack.canBeHurtBy`).
fn hurt_armor(&mut self, source: horizon_world::damage_source::DamageTypeId, damage: f32) {
if damage <= 0.0 {
return;
}
let amount = ((damage / 4.0) as u32).max(1);
let name = self
.motion
.health
.damage
.definition(source)
.map(|d| d.name.clone())
.unwrap_or_default();
let fire = self
.motion
.health
.damage
.in_tag(source, "minecraft:is_fire");
let mut broke = false;
let losses: Vec<u32> = (0..4)
.map(|i| {
self.armor[i]
.clone()
.map_or(amount, |s| self.durability_loss(&s, amount))
.map(|i| match self.armor[i].clone() {
Some(s)
if self
.res
.items()
.get(&s.item)
.is_some_and(|info| info.equip_damage_on_hurt)
&& !(fire && self.res.items().resists_fire(&s, &name)) =>
{
self.durability_loss(&s, amount)
}
_ => 0,
})
.collect();
for (slot, amount) in self.armor.iter_mut().zip(losses) {
@@ -8645,7 +8765,8 @@ impl Game<'_> {
}
fn drop_stack(&mut self, stack: ItemStack) {
if let Some(eye) = self.0.eye_position() {
self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40);
// ItemUtils.createFilledResult: `player.drop(stack, false)`.
self.0.throw_from_eyes(stack, eye, false);
}
}
}
@@ -8883,6 +9004,24 @@ impl Game<'_> {
}
}
}
/// `ItemStack.hurtWithoutBreaking`: Unbreaking applies, but the stack stops at
/// one point of durability left instead of breaking.
fn hurt_held_without_breaking(&mut self, amount: u32) {
if self.creative {
return;
}
let Some(held) = self.held().cloned() else {
return;
};
let amount = self.durability_loss(&held, amount);
let max = self.res.items().get(&held.item).map_or(0, |i| i.max_damage);
if amount == 0 || max == 0 {
return;
}
if let Some(stack) = self.held_mut().as_mut() {
stack.damage = (stack.damage + amount).min(max - 1);
}
}
/// Block tool use: distinguish success, failure and fall-through for hand feedback.
fn use_tool(
&mut self,
@@ -8970,7 +9109,8 @@ impl Game<'_> {
} else if let Some(rest) = self.give(filled)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
// ItemUtils.createFilledResult: `player.drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
return Ok(UseResult::Success { swing: true });
@@ -9120,8 +9260,29 @@ impl Game<'_> {
while value > 0 {
let v = ExperienceOrb::split(value);
value -= v;
let _merge_id = self.world.random.next_int_bound(40);
self.add_orb(at, v);
let merge_id = self.world.random.next_int_bound(40).unwrap_or(0);
self.award_orb(at, v, merge_id);
}
}
/// `ExperienceOrb.tryMergeToExisting`: an orb of the same value within a
/// 1 block box of `at`, whose id is a multiple of 40 from `merge_id`, takes
/// the new one as one more in its count (and restarts its age); otherwise
/// a fresh orb spawns.
fn award_orb(&mut self, at: [f64; 3], value: u32, merge_id: i32) {
let centre = Vec3::new(at[0], at[1], at[2]);
let half = Vec3::new(0.5, 0.5, 0.5);
let area = Aabb::new(centre.subtract(half), centre.add_vector(half));
// A server's orbs are its own; a LAN or server guest only shows them.
let target = self.remote.is_none().then(|| {
self.orbs
.iter_mut()
.find(|o| o.can_merge(merge_id as u32, value) && o.bounds().intersects(area))
});
if let Some(Some(orb)) = target {
orb.count += 1;
orb.age = 0;
} else {
self.add_orb(at, value);
}
}
/// `new ExperienceOrb(level, pos, Vec3.ZERO, value)`: yaw and motion from
@@ -9143,6 +9304,8 @@ impl Game<'_> {
value,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
});
}
fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool {
@@ -9219,18 +9382,31 @@ impl Game<'_> {
}),
);
}
// Player.aiStep: the pickup area is the box inflated by (1, 0.5, 1).
let bounds = player.map(|p| {
let w = f64::from(p.dimensions.width) / 2.0;
(
[p.position.x - w, p.position.y, p.position.z - w],
[
p.position.x + w,
p.position.y + f64::from(p.dimensions.height),
p.position.z + w,
p.position.x - w - 1.0,
p.position.y - 0.5,
p.position.z - w - 1.0,
],
[
p.position.x + w + 1.0,
p.position.y + f64::from(p.dimensions.height) + 0.5,
p.position.z + w + 1.0,
],
)
});
let mut orbs = std::mem::take(&mut self.orbs);
// An orb has no random of its own here: lava draws from one made on
// first use, apart from the level stream.
let mut lava_random = None;
let mut next_float = || {
lava_random
.get_or_insert_with(dispenser::entity_random)
.next_float()
};
orbs.retain_mut(|o| {
let distance = |feet: &[f64; 3]| -> f64 {
(feet[0] - o.position.x).powi(2)
@@ -9242,12 +9418,22 @@ impl Game<'_> {
.filter(|(feet, _)| distance(feet) < 64.0)
.min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0)))
.map(|(_, target)| *target);
o.tick(&self.world, self.res.facts(), self.collision, target)
o.tick(
&self.world,
self.res.facts(),
self.collision,
target,
&mut next_float,
)
});
// ExperienceOrb.scanForMerges runs on the server only.
if self.remote.is_none() {
horizon_client::entities::merge_orbs(&mut orbs);
}
let mut gained = 0;
let mut taken = Vec::new();
if let Some((min, max)) = bounds {
orbs.retain(|o| {
orbs.retain_mut(|o| {
let touching = o.position.x + 0.25 > min[0]
&& o.position.x - 0.25 < max[0]
&& o.position.y + 0.5 > min[1]
@@ -9255,11 +9441,13 @@ impl Game<'_> {
&& o.position.z + 0.25 > min[2]
&& o.position.z - 0.25 < max[2];
if touching && self.xp_delay == 0 {
// ExperienceOrb.playerTouch: one orb every 2 ticks.
// ExperienceOrb.playerTouch: one orb every 2 ticks; a
// merged orb gives its value once per count.
self.xp_delay = 2;
gained += o.value;
taken.push(o.clone());
return false;
o.count -= 1;
return o.count > 0;
}
true
});
@@ -9335,7 +9523,10 @@ impl Game<'_> {
};
// BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1).
let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]);
let (power_bonus, infinity) = self.bow_enchantments();
let ammo = arrow_slot
.and_then(|i| self.stack_in(i).cloned())
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
let (power_bonus, infinity) = self.bow_enchantments(&ammo.item);
let kind = horizon_client::projectiles::ProjectileKind::Arrow {
base_damage: 2.0 + power_bonus,
critical: power >= 1.0,
@@ -9349,9 +9540,6 @@ impl Game<'_> {
// ProjectileWeaponItem.useAmmo: creative and Infinity draw without
// using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player)
// lets it be picked up.
let ammo = arrow_slot
.and_then(|i| self.stack_in(i).cloned())
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(&horizon_client::arrows::drawn_ammo(
&ammo,
@@ -453,6 +453,11 @@ impl Game<'_> {
}
// ArmorStand.swapItem.
match held {
// A player with infinite materials puts a copy of one on an empty
// slot and keeps the stack.
Some(h) if self.creative && current.is_none() => {
self.armor_stands[i].equipment[slot] = Some(ItemStack { count: 1, ..h });
}
Some(h) if h.count > 1 => {
if current.is_some() {
return true;
@@ -5,10 +5,14 @@
//! [`Game::block_anim`] and [`Game::chest_lid`].
use super::Game;
use horizon_client::{
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
block_entity_anim::{
BellEntity, ConduitServer, ConduitTarget, EndGateway, Shulker, ShulkerStatus, Ticker,
},
block_entity_render::BlockAnim,
collisions::{SceneCollisions, no_collision_empty},
containers::BlockEntity,
effects::EffectInstance,
mobs::{Damage, DamageKind},
particles::{ParticleOptions, ParticleType},
save::number,
skins,
@@ -16,6 +20,7 @@ use horizon_client::{
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::nbt::Tag;
@@ -218,9 +223,12 @@ impl Game<'_> {
/// The client tickers of the loaded animated block entities, once per
/// client tick (`ClientLevel.tickBlockEntities`).
pub(super) fn tick_block_entity_anims(&mut self) {
// A server has no window, but its gateways and conduits still run
// their server tickers; a client of one only animates what it is sent.
if self.remote.is_none() {
self.tick_conduit_servers();
}
let Some(r) = &self.renderer else {
// A server has no window, but its gateways still run their
// server ticker.
if self.remote.is_none() {
self.tick_gateway_servers();
}
@@ -337,6 +345,7 @@ impl Game<'_> {
}
}
Ticker::Conduit => {
let target = self.conduit_target(pos);
let world = &self.world;
let facts = self.res.facts();
let registry = self.pack.assets.registry;
@@ -356,7 +365,7 @@ impl Game<'_> {
time,
is_water,
is_frame,
None,
target,
self.particles.random(),
);
let nautilus = ParticleOptions::simple(ParticleType::Nautilus);
@@ -383,6 +392,248 @@ impl Game<'_> {
}
self.be_anims.present = positions;
}
/// `ConduitBlockEntity.serverTick` of every conduit in the chunks that
/// tick blocks, with or without a renderer. The conduits are looked for
/// when the shape is checked, every 40 ticks (they have no block entity
/// of their own here).
fn tick_conduit_servers(&mut self) {
if self.world.game_time % 40 == 0 {
self.find_conduits();
}
let mut positions: Vec<[i32; 3]> = self.be_anims.conduit_servers.keys().copied().collect();
positions.sort_unstable();
for pos in positions {
self.tick_conduit_server(pos);
}
}
/// Sets `be_anims.conduit_servers` to the conduits in the
/// chunks that tick blocks, keeping the state of those already known.
fn find_conduits(&mut self) {
let levels = self.tickets.levels();
let kinds = &self.be_anims.kinds;
let is_conduit = |id: u32| matches!(kinds.get(id as usize), Some(Some(Ticker::Conduit)));
let mut found = Vec::new();
for (&(cx, cz), chunk) in &self.world.chunks {
if !levels.block_ticking_at(cx * 16, cz * 16) {
continue;
}
for (si, section) in chunk.sections.iter().enumerate() {
if !section.blocks.maybe_has(is_conduit) {
continue;
}
for i in 0..4096 {
if is_conduit(section.get(i)) {
found.push([
cx * 16 + (i & 15) as i32,
horizon_client::chunk::MIN_Y + si as i32 * 16 + (i >> 8) as i32,
cz * 16 + ((i >> 4) & 15) as i32,
]);
}
}
}
}
let mut old = std::mem::take(&mut self.be_anims.conduit_servers);
for pos in found {
let known = old.remove(&pos).unwrap_or_default();
self.be_anims.conduit_servers.insert(pos, known);
}
}
/// `ConduitBlockEntity.serverTick` of the conduit at `pos`, in a chunk
/// that ticks blocks: the shape check every 40 ticks with its sounds, the
/// power for players in range, the hurt for an enemy, then the ambient
/// sounds.
fn tick_conduit_server(&mut self, pos: [i32; 3]) {
let state = self.world.block(pos[0], pos[1], pos[2]).0;
if self.be_anims.ticker(state) != Some(Ticker::Conduit) {
// Broken since the chunks were searched.
self.be_anims.conduit_servers.remove(&pos);
return;
}
if !self.tickets.levels().block_ticking_at(pos[0], pos[2])
|| !self.border.contains(f64::from(pos[0]), f64::from(pos[2]))
{
return;
}
let time = self.world.game_time;
let mut conduit = self
.be_anims
.conduit_servers
.remove(&pos)
.unwrap_or_default();
let check = {
let world = &self.world;
let facts = self.res.facts();
let registry = self.pack.assets.registry;
let frames = self
.res
.items()
.block_tags
.get("minecraft:conduit_effect_block");
// Level.isWaterAt: the fluid at the position is water.
let is_water = |p: [i32; 3]| {
facts.get(world.block(p[0], p[1], p[2])).fluid
== horizon_client::blocks::Fluid::Water
};
let is_frame = |p: [i32; 3]| {
registry
.state(world.block(p[0], p[1], p[2]))
.is_some_and(|s| frames.is_some_and(|f| f.contains(&s.name)))
};
conduit.check(pos, time, is_water, is_frame)
};
let centre = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
if let Some(check) = check {
if let Some(active) = check.toggled {
let sound = if active {
"minecraft:block.conduit.activate"
} else {
"minecraft:block.conduit.deactivate"
};
self.audio.play(sound, Some(centre), 1.0, 1.0);
}
if let Some(frames) = check.frames {
self.conduit_apply_effects(pos, frames);
self.conduit_attack(&mut conduit, pos, frames >= 42);
}
}
let (ambient, short) = conduit.ambient(time, &mut self.world.random);
if ambient {
self.audio
.play("minecraft:block.conduit.ambient", Some(centre), 1.0, 1.0);
}
if short {
self.audio.play(
"minecraft:block.conduit.ambient_short",
Some(centre),
1.0,
1.0,
);
}
self.be_anims.conduit_servers.insert(pos, conduit);
}
/// `ConduitBlockEntity.applyEffects`: conduit power for every player
/// in water or rain within `frames / 7 * 16` blocks.
fn conduit_apply_effects(&mut self, pos: [i32; 3], frames: usize) {
let range = (frames / 7 * 16) as i64;
self.for_each_player(|g| {
let Some(p) = g.player.as_ref().filter(|p| !p.health.dead_or_dying()) else {
return;
};
if g.spectator() {
return;
}
let at = p.position;
let in_water = p.fluids.was_touching_water;
let top = at.y + f64::from(p.dimensions.height);
// BlockPos.closerThan: the squared distance under range squared.
let d = [at.x, at.y, at.z]
.map(|v| v.floor() as i64)
.iter()
.zip(pos)
.map(|(a, b)| (a - i64::from(b)).pow(2))
.sum::<i64>();
if d >= range * range || !(in_water || g.in_rain(at, top)) {
return;
}
let power = EffectInstance {
ambient: true,
..EffectInstance::new("conduit_power", 260, 0)
};
g.potions.effects.add(power);
});
}
/// `Entity.isInRain`: rain at the block position or at the top of the box.
fn in_rain(&mut self, at: Vec3, top: f64) -> bool {
let p = BlockPos::new(
at.x.floor() as i32,
at.y.floor() as i32,
at.z.floor() as i32,
);
let up = BlockPos::new(p.x, top.floor() as i32, p.z);
self.with_level(|b, level, _| b.is_raining_at(level, p) || b.is_raining_at(level, up))
}
/// `ConduitBlockEntity.updateAndAttackTarget`: while the conduit hunts
/// (42 frame blocks) its target stays until it dies or leaves the 8
/// blocks, else a random enemy in water or rain is chosen; the target
/// takes 4 magic damage.
fn conduit_attack(&mut self, conduit: &mut ConduitServer, pos: [i32; 3], hunting: bool) {
conduit.target = match conduit.target {
_ if !hunting => None,
None => self.conduit_new_target(pos),
Some(id) => self
.mobs
.iter()
.find(|m| m.id == id && !m.removed)
.filter(|m| {
let at = [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i64);
m.alive()
&& at
.iter()
.zip(pos)
.map(|(a, b)| (a - i64::from(b)).pow(2))
.sum::<i64>()
< 64
})
.map(|m| m.id),
};
let Some(m) = conduit
.target
.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id))
else {
return;
};
let at = [m.position.x, m.position.y, m.position.z];
m.damage(4.0, Damage::of(DamageKind::Magic));
self.audio
.play("minecraft:block.conduit.attack.target", Some(at), 1.0, 1.0);
}
/// `ConduitBlockEntity.selectNewTarget`: one of the enemies in water or
/// rain whose box meets the conduit's block inflated by 8.
fn conduit_new_target(&mut self, pos: [i32; 3]) -> Option<u32> {
let [x, y, z] = pos.map(f64::from);
let area = Aabb::new(
Vec3::new(x - 8.0, y - 8.0, z - 8.0),
Vec3::new(x + 9.0, y + 9.0, z + 9.0),
);
let near: Vec<(u32, bool, Vec3, f64)> = self
.mobs
.iter()
.filter(|m| m.hostile() && !m.removed && m.bounds().intersects(area))
.map(|m| {
let top = m.position.y + f64::from(m.height());
(m.id, m.fluids.in_water, m.position, top)
})
.collect();
let candidates: Vec<u32> = near
.into_iter()
.filter(|&(_, in_water, at, top)| in_water || self.in_rain(at, top))
.map(|(id, ..)| id)
.collect();
if candidates.is_empty() {
return None;
}
let pick = self
.world
.random
.next_int_bound(candidates.len() as i32)
.unwrap_or(0);
Some(candidates[pick as usize])
}
/// The conduit's `destroyTarget` as the client draws it.
fn conduit_target(&self, pos: [i32; 3]) -> Option<ConduitTarget> {
let id = self.be_anims.conduit_servers.get(&pos)?.target?;
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
Some(ConduitTarget {
position: [m.position.x, m.position.y, m.position.z],
eye_y: m.eye_y(),
width: m.width(),
height: m.height(),
})
}
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
/// gateways a server keeps a copy of, in block-ticking chunks
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
@@ -10,6 +10,7 @@ use horizon_client::{
block_entities::{Pos, Ticking},
containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS},
};
use horizon_core::position::BlockPos;
use horizon_world::registry::BlockStateId;
impl Game<'_> {
@@ -56,6 +57,7 @@ impl Game<'_> {
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
Some(BlockEntity::DaylightDetector) => self.tick_daylight_detector(pos),
Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
_ => {}
}
@@ -94,6 +96,7 @@ impl Game<'_> {
| "minecraft:beehive"
| "minecraft:bee_nest"
| "minecraft:brewing_stand"
| "minecraft:daylight_detector"
// Lit, cookTick; unlit, cooldownTick.
| "minecraft:campfire"
| "minecraft:soul_campfire" => Ticking::Yes,
@@ -117,6 +120,16 @@ impl Game<'_> {
let levels = self.tickets.levels();
move |x, z| levels.block_ticking_at(x, z)
}
/// `DaylightDetectorBlock.tickEntity` of the detector at `pos`.
fn tick_daylight_detector(&mut self, pos: Pos) {
// It updates every 20 game ticks (the behaviour checks this too).
if self.world.game_time % 20 != 0 {
return;
}
let at = BlockPos::new(pos.0, pos.1, pos.2);
self.with_level(|b, level, ticks| b.tick_daylight_detector(level, ticks, at));
let _ = self.process_level_events();
}
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
/// its block's `lit` following it.
fn tick_furnace(&mut self, pos: Pos) -> Result<()> {
+4
View File
@@ -31,6 +31,10 @@ pub(super) struct CombatTracker {
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
/// fire decides whom the blast may hurt.
pub(super) explosion_source: Option<u32>,
/// Charged creepers whose blast just went off and that have not dropped
/// a head yet (`Creeper.droppedSkulls`): they are gone from the mob list,
/// but the mobs they killed still ask for their loot.
pub(super) charged_exploders: Vec<u32>,
/// The player's fall distance before this tick's movement (as of the
/// end of the last one).
fall_before: f64,
@@ -1697,6 +1697,8 @@ impl Game<'_> {
value: 0,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
});
name = Text::translate("entity.minecraft.experience_orb", &[]);
}
@@ -5,6 +5,7 @@
use super::{Game, commands::compute::ComputeContext};
use horizon_client::{
items::ItemStack,
mobs::villager,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{position::BlockPos, random::RandomSource};
@@ -86,6 +87,82 @@ impl Game<'_> {
self.composter_add(pos, &layers);
(stack.count > 0).then_some(stack)
}
/// `WorkAtComposter.compostItems` for the villager at `mob`: a full
/// composter is emptied, then up to 20 wheat or beetroot seeds go in
/// (keeping 10 of each kind) until the composter reaches level 7. Level
/// event 1500 plays once, at the end.
pub(super) fn villager_compost_items(&mut self, mob: usize, pos: [i32; 3]) {
let at = BlockPos::new(pos[0], pos[1], pos[2]);
let Some(mut before) = self.composter_level(pos) else {
return;
};
if before == 8 {
self.with_level(|b, level, ticks| b.composter_extract(level, ticks, at));
let _ = self.process_level_events();
before = 0;
}
let mut remaining = 20;
let mut amounts: Vec<(std::sync::Arc<str>, i32)> = Vec::new();
let slots = villager::ext(&self.mobs[mob]).map_or(0, |e| e.inventory.len());
'slots: for slot in (0..slots).rev() {
if remaining <= 0 {
break;
}
let stack = villager::ext_mut(&mut self.mobs[mob]).inventory[slot].clone();
if !matches!(
&*stack.item,
"minecraft:wheat_seeds" | "minecraft:beetroot_seeds"
) {
continue;
}
let known = amounts.iter().position(|(item, _)| *item == stack.item);
let total = known.map_or(0, |k| amounts[k].1) + stack.count as i32;
match known {
Some(k) => amounts[k].1 = total,
None => amounts.push((stack.item.clone(), total)),
}
let uses = (total - 10).min(remaining).min(stack.count as i32);
if uses <= 0 {
continue;
}
remaining -= uses;
for _ in 0..uses {
self.villager_insert_item(mob, slot, &stack, pos);
if self.composter_level(pos) == Some(7) {
break 'slots;
}
}
}
let after = self.composter_level(pos).unwrap_or(before);
self.with_level(|b, level, ticks| {
b.composter_fill_effects(level, ticks, at, after != before)
});
let _ = self.process_level_events();
}
/// `ComposterBlock.insertItem` with a villager's stack: below level 7 a
/// compostable item is used up and may add a layer.
fn villager_insert_item(&mut self, mob: usize, slot: usize, stack: &ItemStack, pos: [i32; 3]) {
if self.composter_level(pos).is_none_or(|level| level >= 7) {
return;
}
let Some(layers) = self.compostable(stack) else {
return;
};
let context = ComputeContext {
block: Some(pos),
target: None,
};
let layers = self.provider_int(&layers, &context, 0).unwrap_or(0);
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.composter_layer(level, ticks, at, layers));
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
let _ = self.process_level_events();
let inventory = &mut villager::ext_mut(&mut self.mobs[mob]).inventory;
inventory[slot].count -= 1;
if inventory[slot].count == 0 {
inventory.remove(slot);
}
}
/// `ComposterBlock.handleFill` (level event 1500) on the client: the
/// fill sound and ten composter particles above the compost.
pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) {
+270 -37
View File
@@ -193,6 +193,7 @@ impl Game<'_> {
velocity: p.velocity,
yaw: self.yaw,
hero: self.potions.effects.get("hero_of_the_village").is_some(),
effects: self.potions.effects.list.iter().map(|e| e.id).collect(),
uuid: self.level.player_uuid.unwrap_or_default(),
allies: std::sync::Arc::new(self.player_allies()),
remote: false,
@@ -497,6 +498,8 @@ impl Game<'_> {
self.died.insert(m.id);
self.mob_died(&m);
}
// Their victims have been looted: no charged creeper is waiting any more.
self.combat.charged_exploders.clear();
let uuid = self.level.player_uuid;
let mut snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
let mut events = Vec::new();
@@ -779,7 +782,17 @@ impl Game<'_> {
.mobs
.iter()
.find(|o| o.id == id)
.map(|o| drops::loot_entity(o, None)),
.map(|o| drops::loot_entity(o, None))
// A charged creeper's blast kills after the creeper left the list.
.or_else(|| {
self.combat
.charged_exploders
.contains(&id)
.then(|| LootEntity {
powered: true,
..LootEntity::new("minecraft:creeper")
})
}),
None => None,
};
let direct = match d.kind {
@@ -815,12 +828,12 @@ impl Game<'_> {
world_seed: self.level.seed,
};
let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences);
if skulls
&& let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker)
&& let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id)
{
if skulls && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) {
// Creeper.droppedSkulls: one head per charged explosion.
creeper.extra.charged = false;
self.combat.charged_exploders.retain(|c| *c != id);
if let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) {
creeper.extra.charged = false;
}
}
let raider = horizon_client::mobs::raider::is_raider(m.species());
for d in items {
@@ -838,6 +851,47 @@ impl Game<'_> {
}
}
}
/// `LivingEntity.dropFromGiftLootTable`: the gift table from its random
/// sequence with the mob as `this` (a chicken's egg depends on its
/// variant); the loot data of the game's resources decides, and without it
/// the items' table engine (no entity) rolls it.
fn drop_gift_loot(&mut self, mob: u32, table: &'static str, at: [f64; 3]) {
use horizon_client::mobs::drops;
use horizon_world::loot::EntityLootParams;
let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
let this = self
.mobs
.iter()
.find(|m| m.id == mob)
.map(|m| drops::loot_entity(m, None));
let stacks = match (loot, this) {
(Some(loot), Some(this)) if loot.has_table(table) => {
let params = EntityLootParams {
this,
..EntityLootParams::default()
};
let seed = self.level.seed;
match loot.random_sequence(table) {
Some(id) => {
let random = self.rand_sequences.get(id, seed);
loot.roll_entity(table, random, &params)
.iter()
.filter(|s| !s.is_empty())
.map(from_loot)
.collect()
}
None => Vec::new(),
}
}
_ => self
.res
.items()
.loot_table(table, false, None, &mut self.world.random),
};
for d in stacks {
self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
}
}
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
for e in events {
match e {
@@ -903,16 +957,24 @@ impl Game<'_> {
owner,
} => self.add_fangs(at, yaw, delay, owner),
MobEvent::Shoot(..) => {}
MobEvent::ExplosionSource { mob, charged } => {
self.combat.explosion_source = Some(mob);
if charged {
self.combat.charged_exploders.push(mob);
}
}
MobEvent::Explode(at, radius) => {
// The exploding mob causes the damage (Creeper.explodeCreeper).
let source_mob = self
.mobs
.iter()
.filter(|m| {
(m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0
})
.map(|m| m.id)
.next();
let source_mob = self.combat.explosion_source.or_else(|| {
self.mobs
.iter()
.filter(|m| {
(m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2)
< 1.0
})
.map(|m| m.id)
.next()
});
if let Some(id) = source_mob {
self.note_attacker("minecraft:explosion", id);
}
@@ -943,6 +1005,9 @@ impl Game<'_> {
volume,
pitch,
);
} else {
// Left for the end of the tick.
t.outbox.push(event);
}
}
}
@@ -1045,6 +1110,40 @@ impl Game<'_> {
self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open));
self.process_level_events()?;
}
MobEvent::BreakDoor { pos } => {
// BreakDoorGoal.tick: removeBlock, then level events 1021
// and 2001 with the state that is there now.
let air = self.world.air;
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, at, air, 3));
self.process_level_events()?;
self.level_event_at(1021, pos, 0);
let left = self.world.block(pos[0], pos[1], pos[2]);
self.level_event_at(2001, pos, left.0 as i32);
}
MobEvent::DestroyProgress { mob, pos, progress } => {
self.destroy_block_progress(mob as i32, pos, progress);
// ServerLevel.destroyBlockProgress: every player nearby sees it.
if let Some(host) = self.lan.as_ref() {
host.hub.broadcast_near(
[f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
64.0,
&horizon_protocol::packets::play::Clientbound::BlockDestruction(
horizon_protocol::packets::play::BlockDestruction {
id: mob as i32,
pos,
progress: if (0..10).contains(&progress) {
progress as u8
} else {
255
},
},
),
None,
);
}
}
MobEvent::LevelEvent { id, pos, data } => self.level_event_at(id, pos, data),
MobEvent::SetBlockName { pos, name, effect } => {
if effect {
let old = self.world.block(pos[0], pos[1], pos[2]);
@@ -1190,6 +1289,10 @@ impl Game<'_> {
self.mob_vibration_particle(from, to, ticks)
}
MobEvent::DigParticles { at } => self.warden_dig_particles(at),
MobEvent::BlockBreakEffect { pos, block } => {
let state = self.world.block(block[0], block[1], block[2]);
self.destroy_particles(pos, state);
}
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
MobEvent::CreakingHurt {
home,
@@ -1200,12 +1303,14 @@ impl Game<'_> {
self.creaking_tear_down(center, spread)
}
MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob),
MobEvent::Reinforcements { mob, target } => self.call_reinforcements(mob, target),
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth {
parent,
partner,
child,
} => self.villager_birth(parent, partner, child),
MobEvent::WorkAtComposter { mob, pos } => self.villager_work_at_composter(mob, pos),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
@@ -1226,19 +1331,51 @@ impl Game<'_> {
m.ai.aggressive |= aggressive;
}
}
MobEvent::GiftLoot { table, at } => {
let drops =
self.res
.items()
.loot_table(table, false, None, &mut self.world.random);
for d in drops {
self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
MobEvent::GiftLoot { mob, table, at } => {
// Turtle.ageBoundaryReached: only with mob loot on.
if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops")
{
continue;
}
self.drop_gift_loot(mob, table, at);
}
}
}
Ok(())
}
/// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle
/// per egg, a day from grown, with the egg as its home (the sound, the
/// crumbs and the block's removal came from the level).
pub(super) fn hatch_turtles(
&mut self,
pos: [i32; 3],
state: horizon_world::registry::BlockStateId,
) {
let eggs = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("eggs"))
.and_then(|v| v.parse::<i32>().ok())
.unwrap_or(1);
for i in 0..eggs {
let at = [
f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2,
f64::from(pos[1]),
f64::from(pos[2]) + 0.3,
];
if let Some(id) = self.spawn_mob("minecraft:turtle", at, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.extra.age = -24000;
m.extra.home = Some(pos);
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
}
}
}
fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
@@ -1301,6 +1438,8 @@ impl Game<'_> {
.unwrap_or_else(|| parent.clone());
let mut child = parent.clone();
child.baby = true;
// TurtleBreedGoal.breed triggers it without a child.
let turtle = p.species() == Species::Turtle;
if matches!(
(
p.species(),
@@ -1313,7 +1452,7 @@ impl Game<'_> {
) {
child.kind = "minecraft:mule".into();
}
self.trigger_bred(&parent, &partner_view, Some(&child));
self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child));
}
if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) {
q.extra.age = 6000;
@@ -1325,6 +1464,19 @@ impl Game<'_> {
self.lay_sniffer_egg(&p);
return;
}
// TurtleBreedGoal.breed: the goal gave the mother her egg; only the
// experience is left, and only with mob loot on.
if p.species() == Species::Turtle {
// One `new ExperienceOrb` of 1 to 7 from the mother's random (not
// split up as `ExperienceOrb.award` does).
if self.ui.rules.bool("mob_drops")
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent)
{
let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32;
self.add_orb([p.position.x, p.position.y, p.position.z], xp);
}
return;
}
let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
// A horse and a donkey have a mule.
@@ -1557,7 +1709,6 @@ impl Game<'_> {
r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]);
}
}
self.hurt_armor(amount);
// The thorns hurt the entity that caused the hit, if there is one.
if let Some(a) = attacker.or(owner) {
self.thorns(a);
@@ -2012,6 +2163,23 @@ impl Game<'_> {
self.creatures.projectiles.push(arrow);
}
}
/// `TargetBlock.onProjectileHit`: a target block takes its power from
/// where the projectile landed and resets after 20 ticks for an arrow, 8
/// for any other projectile. A player's shot counts as a target hit.
fn target_block_hit(&mut self, p: &Projectile, pos: [i32; 3], at: Vec3, face: [i32; 3]) {
let block = BlockPos::new(pos[0], pos[1], pos[2]);
let arrow = p.arrow.is_some();
let location = [at.x, at.y, at.z];
let hit = self.with_level(|b, level, ticks| {
b.target_projectile_hit(level, ticks, block, location, face, arrow)
});
if hit.is_some() {
let _ = self.process_level_events();
if p.owner == Some(Who::Player) {
self.stats.custom("target_hit", 1);
}
}
}
pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
self.combat.projectile_owner = match p.owner {
Some(Who::Mob(id)) => Some(id),
@@ -2021,6 +2189,13 @@ impl Game<'_> {
Hit::Entity { at, .. } | Hit::Block { at, .. } => at,
Hit::None => return Ok(()),
};
// Projectile.onHitBlock: BlockState.onProjectileHit, for every
// projectile (a wind charge out of the world's top has no face).
if let Hit::Block { pos, face, .. } = hit
&& face != [0; 3]
{
self.target_block_hit(p, pos, at, face);
}
if let Hit::Entity {
who: Who::Mob(id),
at,
@@ -2383,12 +2558,14 @@ impl Game<'_> {
// ShulkerBullet.onHitEntity: 4 damage, then levitation for 10 s.
(ProjectileKind::ShulkerBullet { .. }, Hit::Entity { who, .. }) => match who {
Who::Player => {
if !self.creative {
self.mob_hits_player(
// Only a hit that hurt (`wasHurt`) brings the levitation.
if !self.creative
&& self.mob_hits_player(
4.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:mob_projectile",
);
)
{
self.give_player_effect("minecraft:levitation", 200, 0);
}
}
@@ -2397,6 +2574,8 @@ impl Game<'_> {
&& m.damage(4.0, source)
{
m.extra.levitation = 200;
// Shulker.hurtServer: a shulker hit by a bullet.
horizon_client::mobs::shulker::hit_by_bullet(m);
}
}
},
@@ -2478,21 +2657,22 @@ impl Game<'_> {
.as_ref()
.map(|h| h.item.to_string())
.unwrap_or_default();
// Bucketable.bucketMobPickup: a water bucket scoops up a fish, a
// tadpole or an axolotl, with the data its bucket carries.
if item == "minecraft:water_bucket"
&& self.mobs[index].species() == Species::Axolotl
&& self.mobs[index].alive()
&& let Some((bucket, sound)) = bucketable(self.mobs[index].species())
{
let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1);
let mut filled = ItemStack::new(bucket, 1);
filled.extra = Some(Box::new(horizon_client::entity_nbt::bucket_components(
&self.mobs[index],
)));
self.audio.play(
"minecraft:item.bucket.fill_axolotl",
Some(self.mobs[index].center()),
1.0,
1.0,
);
self.audio
.play(sound, Some(self.mobs[index].center()), 1.0, 1.0);
self.trigger_item("minecraft:filled_bucket", &filled);
// Leashable.dropLeash, then discard.
let id = self.mobs[index].id;
self.break_leash(id, true, false);
self.mobs[index].removed = true;
if self.creative {
if let Some(rest) = self.give(filled) {
@@ -2546,6 +2726,19 @@ impl Game<'_> {
}
return Ok(true);
}
// Creeper.mobInteract: any item in #creeper_igniters, damaged when it
// is damageable and used up otherwise.
let creeper_igniter = self
.res
.items()
.item_tags
.get("minecraft:creeper_igniters")
.is_some_and(|t| t.contains(&*item));
let damageable = self
.res
.items()
.get(&item)
.is_some_and(|i| i.max_damage > 0);
let m = &mut self.mobs[index];
if !m.alive() {
return Ok(false);
@@ -2561,6 +2754,7 @@ impl Game<'_> {
let mut handled = true;
let mut drops: Vec<(String, u32)> = Vec::new();
let is_food = m.kind.food.contains(&item);
let baby_turtle = species == Species::Turtle && m.is_baby();
match species {
Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => {
give = Some("minecraft:milk_bucket");
@@ -2786,10 +2980,21 @@ impl Game<'_> {
consume = true;
sound = Some("entity.iron_golem.repair");
}
Species::Creeper if item == "minecraft:flint_and_steel" => {
Species::Creeper if creeper_igniter => {
m.extra.flag = true;
sound = Some("item.flintandsteel.use");
self.damage_held_tool();
// FIRECHARGE_USE for a fire charge, else FLINTANDSTEEL_USE,
// at the creeper's feet with a pitch from its own random.
let event = if item == "minecraft:fire_charge" {
"item.firecharge.use"
} else {
"item.flintandsteel.use"
};
eat = Some((event, 1.0, m.random.next_float() * 0.4 + 0.8));
if damageable {
self.damage_held_tool();
} else {
consume = true;
}
}
// Parrot.mobInteract: parrot food may tame a wild one (one time in
// ten); a parrot never takes it as Animal food (isFood is false).
@@ -2839,6 +3044,14 @@ impl Game<'_> {
if !handled {
return Ok(false);
}
// Turtle.ageBoundaryReached: food that finishes a baby's growth.
if baby_turtle && !self.mobs[index].is_baby() {
self.handle_mob_events(vec![MobEvent::GiftLoot {
mob: self.mobs[index].id,
table: "minecraft:gameplay/turtle_grow",
at: feet,
}])?;
}
self.swing_arm();
if let Some(s) = sound {
let pitch =
@@ -3272,6 +3485,26 @@ impl Game<'_> {
}
}
}
/// `Bucketable.getBucketItemStack` and `getPickupSound` of a mob that a water
/// bucket picks up.
fn bucketable(species: Species) -> Option<(&'static str, &'static str)> {
let fish = "minecraft:item.bucket.fill_fish";
Some(match species {
Species::Cod => ("minecraft:cod_bucket", fish),
Species::Salmon => ("minecraft:salmon_bucket", fish),
Species::Pufferfish => ("minecraft:pufferfish_bucket", fish),
Species::TropicalFish => ("minecraft:tropical_fish_bucket", fish),
Species::Tadpole => (
"minecraft:tadpole_bucket",
"minecraft:item.bucket.fill_tadpole",
),
Species::Axolotl => (
"minecraft:axolotl_bucket",
"minecraft:item.bucket.fill_axolotl",
),
_ => return None,
})
}
/// Mob.getBaseExperienceReward
/// The damage type id of a Horizon damage kind.
pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str {
@@ -6,6 +6,7 @@
//! finds the ammo for bows and crossbows.
use super::{Game, shield::OFFHAND_SLOT, view_vector};
use horizon_client::{
enchant::EffectContext,
items::ItemStack,
mobs::Who,
projectiles::{Projectile, ProjectileKind},
@@ -152,6 +153,20 @@ impl Game<'_> {
};
let charged = std::mem::take(&mut bow.data_mut().charged);
bow.tidy();
let weapon = bow.clone();
// AbstractArrow's constructor: `getPiercingCount` of the weapon.
let pierce = self
.res
.stations()
.enchantments
.modify_value(
Some(&weapon),
"minecraft:projectile_piercing",
&EffectContext::default(),
&mut self.world.random,
0.0,
)
.clamp(0.0, 127.0) as u8;
let count = charged.len();
// getShootingPower: a rocket among them slows every shot.
let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) {
@@ -204,6 +219,7 @@ impl Game<'_> {
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(ammo);
a.set_owner(Some(Who::Player));
a.pierce = pierce;
}
arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0);
self.creatures.projectiles.push(arrow);
@@ -1131,14 +1131,18 @@ impl Game<'_> {
let (p, v) = (b.position, b.velocity);
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
// A merged orb prints once per count, as the oracle does: whether orbs
// merge depends on entity ids, which differ from vanilla's.
for o in &self.orbs {
let (p, v) = (o.position, o.velocity);
out.push(line(
"minecraft:experience_orb",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
"",
));
for _ in 0..o.count.max(1) {
out.push(line(
"minecraft:experience_orb",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
"",
));
}
}
for c in &self.carts {
let (p, v) = (c.position, c.velocity);
@@ -384,7 +384,9 @@ impl Game<'_> {
}
}
/// Bow enchantments at release: (extra base damage, infinity keeps the arrow).
pub(super) fn bow_enchantments(&mut self) -> (f64, bool) {
/// `ammo` is the item being fired: `Enchantment.itemContext` hands it to the
/// `ammo_use` conditions as the tool, so Infinity only frees plain arrows.
pub(super) fn bow_enchantments(&mut self, ammo: &str) -> (f64, bool) {
let Some(bow) = self.inventory[self.selected].clone() else {
return (0.0, false);
};
@@ -403,7 +405,7 @@ impl Game<'_> {
0.0,
);
let ammo_ctx = EffectContext {
tool: Some("minecraft:arrow"),
tool: Some(ammo),
items: Some(self.res.items()),
..Default::default()
};
+4 -4
View File
@@ -316,9 +316,6 @@ impl Game<'_> {
);
}
}
if outcome.hurt && !creative {
self.hurt_armor(amount);
}
if raised {
self.after_block(outcome, amount, None, false);
}
@@ -393,9 +390,11 @@ impl Game<'_> {
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
// The exploding mob is the damage source's entity, so victims
// it kills drop its charged-creeper loot (`Creeper.killedEntity`).
let source = horizon_client::mobs::Damage {
kind: horizon_client::mobs::DamageKind::Explosion,
attacker: None,
attacker: exploding.map(horizon_client::mobs::Who::Mob),
from: Some(center),
};
if hurtable && !m.damage(damage(dist, exposure), source) {
@@ -622,6 +621,7 @@ impl Game<'_> {
&mut self.world.random,
Some((&mut self.rand_sequences, self.level.seed)),
decay,
false,
);
for mut stack in drops {
if &*stack.item == "minecraft:air" || stack.count == 0 {
@@ -108,16 +108,10 @@ impl Game<'_> {
} else {
amount
};
let hurt = if let Some(p) = self.player.as_mut()
if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(kind)
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
}
+21 -9
View File
@@ -81,16 +81,28 @@ impl Game<'_> {
};
bite(self);
self.each_guest_hit(bite);
// `AbstractIllager.considersEntityAsAlly`: with no teams, the illager
// tag is allied; `Evoker.considersEntityAsAlly` adds a vex whose
// owner is allied (itself or another illager). Teams are not modelled.
let illager = |s: Species| {
matches!(
s,
Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator
)
};
let illagers: Vec<u32> = self
.mobs
.iter()
.filter(|m| illager(m.species()))
.map(|m| m.id)
.collect();
// A missing owner hurts everyone (`currentOwner == null`).
let owner_known = illagers.contains(&f.owner);
for m in &mut self.mobs {
let ally = matches!(
m.species(),
Species::Evoker
| Species::Illusioner
| Species::Vex
| Species::Pillager
| Species::Vindicator
| Species::Witch
);
let ally = owner_known
&& (illager(m.species())
|| m.species() == Species::Vex
&& illagers.contains(&(m.extra.counter2 as u32)));
if m.id != f.owner && !ally && m.alive() && m.bounds().intersects(b) {
m.damage(
6.0,
+2 -8
View File
@@ -372,17 +372,11 @@ impl Game<'_> {
if self.creative || self.spectator() {
return;
}
let hurt = if let Some(p) = self.player.as_mut()
if let Some(p) = self.player.as_mut()
&& !p.health.dead_or_dying()
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
+64 -35
View File
@@ -154,37 +154,54 @@ impl Game<'_> {
let mut damage = 0;
if let State::Hooked(id) = hook.state {
// pullEntity: 0.1 of the way to the owner.
let d = Vec3::new(
owner.x - hook.position.x,
owner.y - hook.position.y,
owner.z - hook.position.z,
);
let pulled = |v: Vec3| Vec3::new(v.x + d.x * 0.1, v.y + d.y * 0.1, v.z + d.z * 0.1);
let mut hooked_item = false;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
let d = Vec3::new(
owner.x - hook.position.x,
owner.y - hook.position.y,
owner.z - hook.position.z,
);
m.velocity = Vec3::new(
m.velocity.x + d.x * 0.1,
m.velocity.y + d.y * 0.1,
m.velocity.z + d.z * 0.1,
);
m.velocity = pulled(m.velocity);
} else if let Some(item) = self.dropped.iter_mut().find(|i| i.id == id) {
item.velocity = pulled(item.velocity);
hooked_item = true;
}
damage = 5;
// `hookedIn instanceof ItemEntity ? 3 : 5`.
damage = if hooked_item { 3 } else { 5 };
} else if hook.nibble > 0 {
let biome = self.biome_name_at(hook.position);
let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources)
else {
return damage;
};
// `withLuck(this.luck + owner.getLuck())`: the rod's Luck of the Sea
// plus the owner's luck attribute (the Luck and Bad Luck effects).
let owner_luck = self
.player
.as_mut()
.and_then(|p| p.attribute("minecraft:luck").ok())
.unwrap_or(0.0) as f32;
let mut random = self.world.random.clone();
let items = loot.roll(
"minecraft:gameplay/fishing",
&mut random,
hook.luck as f32,
hook.luck as f32 + owner_luck,
biome.as_deref(),
Some(hook.open_water),
);
self.world.random = random;
// FishingHook.retrieve: fish_caught for a catch.
self.stats.custom("fish_caught", 1);
for stack in items {
// FishingHook.retrieve: fish_caught for each catch in #minecraft:fishes.
if self
.res
.items()
.item_tags
.get("minecraft:fishes")
.is_some_and(|t| t.contains(stack.item.as_str()))
{
self.stats.custom("fish_caught", 1);
}
let mut item = ItemStack {
item: Arc::from(stack.item.as_str()),
count: stack.count.max(1) as u32,
@@ -457,35 +474,47 @@ impl Game<'_> {
self.hook = Some(h);
return;
}
// checkCollision: hook the first living mob it touches.
// checkCollision: hook the first living mob it touches, or (via
// `canHitEntity`) a dropped item.
let bb = bounds(h.position);
let (lo, hi) = (bb.min_position(), bb.max_position());
if let Some(m) = self.mobs.iter().find(|m| {
let mb = m.bounds();
let (a, z) = (mb.min_position(), mb.max_position());
m.alive()
&& a.x < hi.x
&& lo.x < z.x
&& a.y < hi.y
&& lo.y < z.y
&& a.z < hi.z
&& lo.z < z.z
}) {
h.state = State::Hooked(m.id);
let touches = |b: Aabb| {
let (a, z) = (b.min_position(), b.max_position());
a.x < hi.x && lo.x < z.x && a.y < hi.y && lo.y < z.y && a.z < hi.z && lo.z < z.z
};
let hit = self
.mobs
.iter()
.find(|m| m.alive() && touches(m.bounds()))
.map(|m| m.id)
.or_else(|| {
self.dropped
.iter()
.find(|i| touches(i.bounds()))
.map(|i| i.id)
});
if let Some(id) = hit {
h.state = State::Hooked(id);
h.velocity = Vec3::ZERO;
self.hook = Some(h);
return;
}
}
State::Hooked(id) => {
match self.mobs.iter().find(|m| m.id == id && m.alive()) {
Some(m) => {
h.position = Vec3::new(
m.position.x,
m.position.y + f64::from(m.height()) * 0.8,
m.position.z,
)
}
// updateHookedEntity: ride the hooked mob or item at 0.8 of its height.
let hooked = self
.mobs
.iter()
.find(|m| m.id == id && m.alive())
.map(|m| (m.position, f64::from(m.height())))
.or_else(|| {
self.dropped
.iter()
.find(|i| i.id == id)
.map(|i| (i.position, horizon_client::entities::ItemEntity::WIDTH))
});
match hooked {
Some((at, height)) => h.position = Vec3::new(at.x, at.y + height * 0.8, at.z),
None => h.state = State::Flying,
}
self.hook = Some(h);
+14 -3
View File
@@ -2301,6 +2301,7 @@ impl Game<'_> {
let marked = std::mem::take(&mut player.health.sync_velocity);
let velocity = marked.then_some(player.velocity);
game.record_combat(&events);
game.wear_armor(&events);
(events, velocity)
});
let Some((events, marked)) = events else {
@@ -2394,9 +2395,13 @@ impl Game<'_> {
}
if (next / 10) % 2 == 0
&& !creative
&& let Some(elytra) = game.armor[1].as_mut()
&& let Some(stack) = game.armor[1].clone()
{
elytra.damage += 1;
// `ItemStack.hurtAndBreak`: Unbreaking can save the wear.
let loss = game.durability_loss(&stack, 1);
if let Some(elytra) = game.armor[1].as_mut() {
elytra.damage += loss;
}
}
let ctx = game.player_context(None);
game.post_game_event("minecraft:elytra_glide", at, ctx);
@@ -2659,7 +2664,13 @@ impl Game<'_> {
.random
.next_int_bound(touching.len() as i32)
.unwrap_or(0) as usize;
let orb = self.orbs.remove(touching[pick]);
// A merged orb gives its value once per count and goes at zero.
let orb = self.orbs[touching[pick]].clone();
if orb.count <= 1 {
self.orbs.remove(touching[pick]);
} else {
self.orbs[touching[pick]].count -= 1;
}
play.xp_delay = 2;
host.hub.take_item(orb.id as i32, id, 1, at);
// ClientPacketListener.handleTakeItemEntity's sound, at the orb.
@@ -370,6 +370,7 @@ mod tests {
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
effects: Vec::new(),
uuid: [0; 4],
allies: Default::default(),
remote: false,
+16
View File
@@ -109,6 +109,19 @@ pub(super) struct Levels {
parked: HashMap<Dim, Parked>,
}
impl Levels {
/// The chunks of each level not in place (capability `world` lends
/// them to server mods for a call).
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
pub(super) fn parked_chunks(
&mut self,
) -> impl Iterator<Item = (Dim, &mut horizon_client::chunk_map::ChunkMap)> {
self.parked
.iter_mut()
.map(|(d, p)| (*d, &mut p.world.chunks))
}
}
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> {
@@ -225,6 +238,7 @@ impl Game<'_> {
swap(&mut a.pots, &mut b.pots);
swap(&mut a.gateways, &mut b.gateways);
swap(&mut a.gateway_servers, &mut b.gateway_servers);
swap(&mut a.conduit_servers, &mut b.conduit_servers);
self.raiding.swap_level(&mut p.raiding);
self.sculk.swap_level(&mut p.sculk);
self.creaking.swap_level(&mut p.creaking);
@@ -313,6 +327,8 @@ impl Game<'_> {
};
self.update_dedicated_streaming();
self.update_world();
// What server mods set in this level since its last tick.
self.apply_mod_block_writes();
result = if paused {
self.tick_lan(true);
Ok(())
+62 -2
View File
@@ -74,14 +74,74 @@ impl Game<'_> {
self.spawn_bolt(at, trap);
}
}
/// `findLightningTargetAround`: a living entity under open sky in the
/// column (3 blocks around), else the top of the column.
/// `ServerLevel.findLightningRod`: `PoiManager.findClosest` over the
/// lightning rod points of interest within 128 blocks of `center` whose
/// block is the top (`WORLD_SURFACE`) of its column; the strike lands one
/// above it. Horizon keeps no point-of-interest index, so this scans the
/// loaded chunks the way `/locate poi` does.
fn find_lightning_rod(&self, center: [i32; 3]) -> Option<[i32; 3]> {
const RANGE: i32 = 128;
let facts = self.res.facts();
let mut is_rod: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
let mut best: Option<(i64, [i32; 3])> = None;
let (cx0, cz0) = ((center[0] - RANGE) >> 4, (center[2] - RANGE) >> 4);
let (cx1, cz1) = ((center[0] + RANGE) >> 4, (center[2] + RANGE) >> 4);
for cx in cx0..=cx1 {
for cz in cz0..=cz1 {
let Some(chunk) = self.world.chunks.get(&(cx, cz)) else {
continue;
};
for (i, section) in chunk.sections.iter().enumerate() {
let mut rod = |state: u32| {
*is_rod.entry(state).or_insert_with(|| {
facts
.get(horizon_world::registry::BlockStateId(state))
.name
.ends_with("lightning_rod")
})
};
if !section.blocks.maybe_has(&mut rod) {
continue;
}
let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32;
for j in 0..4096 {
if !rod(section.get(j)) {
continue;
}
let p = [
cx * 16 + (j & 15) as i32,
base_y + (j >> 8) as i32,
cz * 16 + ((j >> 4) & 15) as i32,
];
let d = [p[0] - center[0], p[1] - center[1], p[2] - center[2]]
.map(|d| i64::from(d) * i64::from(d))
.iter()
.sum::<i64>();
if d > i64::from(RANGE * RANGE) || best.is_some_and(|(b, _)| d >= b) {
continue;
}
let surface = self.world.world_surface(p[0], p[2], |s| facts.is_air(s));
if p[1] == surface - 1 {
best = Some((d, p));
}
}
}
}
}
best.map(|(_, p)| [p[0], p[1] + 1, p[2]])
}
/// `findLightningTargetAround`: the closest lightning rod, else a living
/// entity under open sky in the column (3 blocks around), else the top of
/// the column.
fn lightning_target(&mut self, x: i32, z: i32) -> Option<[i32; 3]> {
if !self.world.loaded(x, z) {
return None;
}
let top =
self.with_level(|b, level, _| b.motion_blocking_top(level, BlockPos::new(x, 0, z)));
if let Some(rod) = self.find_lightning_rod([x, top.y, z]) {
return Some(rod);
}
let sees_sky = |g: &Self, p: [i32; 3]| g.world.light(p[0], p[1], p[2]) >> 4 == 15;
let mut candidates: Vec<[i32; 3]> = self
.mobs
+13 -2
View File
@@ -63,6 +63,14 @@ pub(super) struct ModsState {
/// What players did this tick, for server mods at its end.
#[cfg(feature = "mods")]
pub(super) events: Vec<ModEvent>,
/// A running server mod has capability `world`: its calls get the
/// levels' chunks to read.
#[cfg(feature = "mods")]
pub(super) world: bool,
/// Blocks server mods set, by dimension, made before that level's next
/// tick.
#[cfg(feature = "mods")]
pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>,
/// `command.run` lines for this window's own world, run on the next tick:
/// run at once, their chat lines would reach the mods while their output
/// is still being shown, and a mod answering its own lines would recurse.
@@ -309,6 +317,7 @@ impl Game<'_> {
/// The Mods page's rows, from what loaded.
fn list_mods(&mut self) {
self.mods.server = self.mods.mods.runs_server();
self.mods.world = self.mods.mods.wants_world();
let dev = &self.mods.dev;
self.settings.mods.installed = self
.mods
@@ -673,8 +682,10 @@ impl Game<'_> {
}
Text::literal(line).with_color(text::RED)
}
server
@ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => {
server @ (Output::Tell { .. }
| Output::Broadcast { .. }
| Output::Reply { .. }
| Output::SetBlocks { .. }) => {
self.route_server_output(host.as_deref_mut(), server);
continue;
}
+1 -1
View File
@@ -91,7 +91,7 @@ impl Game<'_> {
})
}
/// `isEyeInFluid(WATER)`: the eye inside the water of its block column.
fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool {
pub(super) fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool {
let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32);
let f = self.res.facts().get(self.world.block(bx, by, bz));
if f.fluid != Fluid::Water {
@@ -155,6 +155,8 @@ mod tests {
value: 1,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
}))
}
+192 -33
View File
@@ -4,18 +4,172 @@
use super::Game;
use horizon_client::{
items::ItemStack,
mobs::{Species, Who, piglin::ADMIRE},
mobs::{
Mob, Species, Who,
finalize::{
SLOT_NAMES, set_drop_chance, set_item, set_slot_enchantments, slot_enchantments,
stored_drop_chance,
},
piglin::{ADMIRE, ATE_RECENTLY},
},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
impl Game<'_> {
fn piglin_loved(&self, item: &str) -> bool {
fn item_in_tag(&self, tag: &str, item: &str) -> bool {
self.res
.items()
.item_tags
.get("minecraft:piglin_loved")
.get(tag)
.is_some_and(|t| t.contains(item))
}
fn piglin_loved(&self, item: &str) -> bool {
self.item_in_tag("minecraft:piglin_loved", item)
}
/// `PiglinAi.isLovedItem` or a preferred weapon (`Piglin.canReplaceCurrentItem`).
fn piglin_wanted(&self, item: &str) -> bool {
self.piglin_loved(item) || self.item_in_tag("minecraft:piglin_preferred_weapons", item)
}
/// The `SLOT_NAMES` index `getEquipmentSlotForItem` picks: armour goes
/// to its slot, anything else to the main hand.
fn piglin_slot(&self, item: &str) -> usize {
let slot = self
.res
.items()
.get(item)
.and_then(|i| i.equip_slot.as_deref())
.filter(|s| matches!(*s, "head" | "chest" | "legs" | "feet"))
.unwrap_or("mainhand");
SLOT_NAMES.iter().position(|n| *n == slot).unwrap_or(0)
}
/// `Piglin.canReplaceCurrentItem`: an empty slot takes anything, a wanted
/// item replaces an unwanted one and never the other way round. Vanilla's
/// armour and weapon comparison for two equal-interest items is left out
/// (the piglin keeps what it has).
fn piglin_can_replace(&self, m: &Mob, item: &str, slot: usize) -> bool {
let Some(current) = horizon_client::mobs::finalize::item(m, slot) else {
return true;
};
self.piglin_wanted(item) && !self.piglin_wanted(&current)
}
/// `SimpleContainer.canAddItem` on the piglin's eight slots.
fn piglin_can_add(&self, m: &Mob, stack: &ItemStack) -> bool {
m.extra.inventory.len() < 8
|| m.extra.inventory.iter().any(|s| {
s.same_item_same_components(stack) && s.count < self.piglin_max_stack(&s.item)
})
}
fn piglin_max_stack(&self, item: &str) -> u32 {
self.res.items().get(item).map_or(64, |i| i.max_stack)
}
/// `PiglinAi.wantsToPickup` (an adult that is not hurt-shy), without
/// the baby rule, which babies skip entirely here.
fn piglin_wants(&self, m: &Mob, stack: &ItemStack) -> bool {
let item = &*stack.item;
if self.item_in_tag("minecraft:piglin_repellents", item) {
return false;
}
let holds_loved = m
.extra
.off_hand
.as_deref()
.is_some_and(|o| self.piglin_loved(o));
if item == "minecraft:gold_ingot" {
return !holds_loved;
}
let space = self.piglin_can_add(m, stack);
if item == "minecraft:gold_nugget" {
space
} else if self.item_in_tag("minecraft:piglin_food", item) {
m.extra.ints[0] <= 0 && space
} else if !self.piglin_loved(item) {
self.piglin_can_replace(m, item, self.piglin_slot(item))
} else {
!holds_loved && space
}
}
/// `Mob.equipItemIfPossible` for a piglin: put it in its slot when that
/// slot takes it (an armour piece that cannot replace what is worn goes
/// to an empty main hand), dropping what it replaces by drop chance.
fn piglin_equip(&mut self, index: usize, stack: &ItemStack) -> bool {
let item = &*stack.item;
let mut slot = self.piglin_slot(item);
let m = &self.mobs[index];
let mut replace = self.piglin_can_replace(m, item, slot);
if slot > 1 && !replace {
slot = 0;
replace = m.extra.main_hand.is_none();
}
if !replace {
return false;
}
let m = &mut self.mobs[index];
let old = horizon_client::mobs::finalize::item(m, slot);
let chance = stored_drop_chance(m, slot);
let drop_old = old.is_some() && (m.random.next_float() - 0.1).max(0.0) < chance;
let old_enchantments = slot_enchantments(m, slot);
set_item(m, slot, item);
// The piglin keeps what the stack carried (Protection IV stays on).
set_slot_enchantments(m, slot, stack.enchantments().to_vec());
// setItemSlotAndDropWhenKilled, then persistenceRequired.
set_drop_chance(m, slot, 2.0);
m.persistent = true;
let at = [m.position.x, m.position.y, m.position.z];
if let (true, Some(old)) = (drop_old, old) {
let mut dropped = ItemStack::new(&old, 1);
dropped.set_crafting_enchantments(old_enchantments);
self.spawn_item(dropped, at, super::dispenser::new_item_motion(), 10);
}
true
}
/// `PiglinAi.putInInventory`: what does not fit is thrown at a random
/// spot nearby.
fn piglin_stash(&mut self, index: usize, mut stack: ItemStack) {
let max = self.piglin_max_stack(&stack.item);
let m = &mut self.mobs[index];
for s in &mut m.extra.inventory {
if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max {
let n = (max - s.count).min(stack.count);
s.count += n;
stack.count -= n;
}
}
while stack.count > 0 && m.extra.inventory.len() < 8 {
let n = stack.count.min(max);
m.extra.inventory.push(ItemStack {
count: n,
..stack.clone()
});
stack.count -= n;
}
if stack.count == 0 {
return;
}
let from = [m.position.x, m.position.y + 1.3, m.position.z];
let r = &mut self.world.random;
let to = [
from[0] + f64::from(r.next_float() * 8.0 - 4.0),
from[1],
from[2] + f64::from(r.next_float() * 8.0 - 4.0),
];
self.piglin_throw(from, to, stack);
}
/// `PiglinAi.stopHoldingOffHandItem` for something that is not
/// bartering currency: wear it if it can, else keep it in the inventory.
fn piglin_keep(&mut self, index: usize, stack: ItemStack) {
// Nuggets keep their whole stack in the inventory (a hand slot here
// holds one item id only).
if &*stack.item == "minecraft:gold_nugget" || !self.piglin_equip(index, &stack) {
self.piglin_stash(index, stack);
}
}
/// `BehaviorUtils.throwItem`: toss a stack from a point toward another.
fn piglin_throw(&mut self, from: [f64; 3], to: [f64; 3], stack: ItemStack) {
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3];
self.spawn_item(stack, from, v, 40);
}
/// `PiglinAi.isWearingSafeArmor`.
pub(super) fn wearing_gold(&self) -> bool {
let tag = self
@@ -28,15 +182,13 @@ impl Game<'_> {
.flatten()
.any(|s| tag.is_some_and(|t| t.contains(&*s.item)))
}
/// Piglins notice gold on the ground within 9 blocks, walk to it and
/// take it (`GoToWantedItem`, `Piglin.pickUpItem`).
/// Piglins notice wanted items on the ground within 9 blocks (`PiglinAi.wantsToPickup`:
/// gold and other loved items, nuggets, food, gear), walk to them and
/// take them (`GoToWantedItem`, `Piglin.pickUpItem`).
pub(super) fn piglin_pickups(&mut self) {
if !self.ui.rules.bool("mob_griefing") {
return;
}
// Whether each item is piglin-loved, kept until an item is added or
// removed (added ones are pushed at the end under a new id).
let mut loved: (Option<(usize, Option<u32>)>, Vec<bool>) = (None, Vec::new());
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Piglin
@@ -44,27 +196,17 @@ impl Game<'_> {
|| m.is_baby()
|| m.extra.using_item > 0
|| m.extra.egg_time > 0
|| m.extra.off_hand.is_some()
{
continue;
}
let pos = m.position;
let key = (self.dropped.len(), self.dropped.last().map(|e| e.id));
if loved.0 != Some(key) {
loved.0 = Some(key);
loved.1 = self
.dropped
.iter()
.map(|e| self.piglin_loved(&e.stack.item))
.collect();
}
let best = self
.dropped
.iter()
.enumerate()
.filter(|&(j, _)| loved.1[j])
.map(|(j, e)| (j, e.position.distance_squared(pos)))
.filter(|(_, d)| *d <= 81.0)
.filter(|&(j, _)| self.piglin_wants(m, &self.dropped[j].stack))
.min_by(|a, b| a.1.total_cmp(&b.1));
let Some((j, _)) = best else {
self.mobs[i].extra.point = None;
@@ -79,24 +221,38 @@ impl Game<'_> {
continue;
}
// Nuggets come whole, anything else one at a time.
let item = e.stack.item.clone();
let (taken_item, id) = (e.clone(), self.mobs[i].id);
let item = e.stack.item.clone();
self.add_pickup(
super::pickups::Taken::Item(Box::new(taken_item)),
super::pickups::Collector::Mob(id),
);
let taken = if &*item == "minecraft:gold_nugget" {
self.dropped.remove(j).stack.count
let stack = if &*item == "minecraft:gold_nugget" {
self.dropped.remove(j).stack
} else {
let e = &mut self.dropped[j];
e.stack.count -= 1;
let one = ItemStack {
count: 1,
..e.stack.clone()
};
if e.stack.count == 0 {
self.dropped.remove(j);
}
1
one
};
let _ = taken;
self.start_admiring(i, item);
if self.piglin_loved(&item) {
self.start_admiring(i, item);
} else if self.item_in_tag("minecraft:piglin_food", &item)
&& self.mobs[i].extra.ints[0] <= 0
{
// PiglinAi.eat: the food is gone and it will not eat for a while.
self.mobs[i].extra.ints[0] = ATE_RECENTLY;
self.mobs[i].nav_stop();
} else {
self.mobs[i].nav_stop();
self.piglin_keep(i, stack);
}
}
}
fn start_admiring(&mut self, index: usize, item: std::sync::Arc<str>) {
@@ -109,14 +265,15 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.piglin.admiring_item", Some(at), 1.0, 1.0);
}
/// `PiglinAi.mobInteract`: hand a piglin something it loves.
/// `PiglinAi.mobInteract`: hand a piglin a gold ingot (only piglin
/// currency is accepted from the hand; other loved items are passed over).
pub(super) fn give_piglin(&mut self, index: usize, item: &str) -> bool {
let m = &self.mobs[index];
if m.species() != Species::Piglin
|| m.is_baby()
|| m.extra.using_item > 0
|| m.extra.egg_time > 0
|| !self.piglin_loved(item)
|| item != "minecraft:gold_ingot"
{
return false;
}
@@ -124,7 +281,8 @@ impl Game<'_> {
true
}
/// `PiglinAi.stopHoldingOffHandItem` after admiring: gold ingots buy a
/// roll of the bartering table, thrown toward the player.
/// roll of the bartering table, thrown toward the player; any other loved
/// item it picked up is kept (worn if it can be, else stored).
pub(super) fn finish_admiring(&mut self, mob: u32) {
let Some(i) = self.mobs.iter().position(|m| m.id == mob) else {
return;
@@ -132,9 +290,13 @@ impl Game<'_> {
let Some(item) = self.mobs[i].extra.off_hand.take() else {
return;
};
if &*item != "minecraft:gold_ingot" {
self.piglin_keep(i, ItemStack::new(&item, 1));
return;
}
let m = &self.mobs[i];
let from = [m.position.x, m.position.y + 1.3, m.position.z];
let items = if &*item == "minecraft:gold_ingot" && !m.is_baby() {
let items = if !m.is_baby() {
self.res.items().loot_table(
"minecraft:gameplay/piglin_bartering",
false,
@@ -176,10 +338,7 @@ impl Game<'_> {
from[2] + f64::from(r.next_float() * 8.0 - 4.0),
]
});
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3];
self.spawn_item(stack, from, v, 40);
self.piglin_throw(from, to, stack);
}
}
/// `PiglinAi.angerNearbyPiglins`.
+22 -1
View File
@@ -276,7 +276,8 @@ impl Game<'_> {
} else if let Some(rest) = self.give(filled)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
// `player.drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
/// Drinking a potion while right-click is held; true when handled.
@@ -400,8 +401,28 @@ impl Game<'_> {
for action in actions {
self.apply_effect_action(action);
}
self.turtle_helmet_tick();
self.apply_effect_status();
}
/// `Player.tick` -> `turtleHelmetTick`: with a turtle helmet on the head
/// and the eyes out of the water, Water Breathing for 200 ticks (no
/// particles, an icon).
fn turtle_helmet_tick(&mut self) {
let Some(p) = self.player.as_ref() else {
return;
};
let eye_y = p.position.y + f64::from(p.dimensions.eye_height);
if !p.health.dead_or_dying()
&& self.armor[0]
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:turtle_helmet")
&& !self.eye_in_water(p.position.x, eye_y, p.position.z)
{
let mut effect = EffectInstance::new("water_breathing", 200, 0);
effect.visible = false;
self.potions.effects.add(effect);
}
}
/// A client's own effects (`LivingEntity.tickEffects` on the client,
/// `MobEffectInstance.tickClient`): they count down, and the server
/// removes them. Their modifiers and flags move the predicted player.
+2
View File
@@ -796,6 +796,8 @@ impl Game<'_> {
let s = m.extra.raider.get_or_insert_with(Box::default);
s.rider = has_rider;
s.in_village = in_village;
// Vindicator.customServerAiStep: `ServerLevel.isRaided`.
s.raided = species == Species::Vindicator && raids.nearby(block).is_some();
if s.raid_id.is_some_and(|id| raids.get(id).is_none()) {
s.raid_id = None;
s.ticks_outside_raid = 0;
+9 -8
View File
@@ -1283,6 +1283,8 @@ impl Game<'_> {
value: 1,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
});
}
if let Some(t) = mob_type {
@@ -2064,7 +2066,10 @@ impl Game<'_> {
{
self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector);
}
self.remove_entity(p.item);
// An orb stays: the server may still hold merged ones in it.
if !orb {
self.remove_entity(p.item);
}
}
// ClientPacketListener.handleSetEntityMotion: knockback on this player.
C::SetEntityMotion(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => {
@@ -4051,15 +4056,11 @@ impl Game<'_> {
world_border: false,
sequence: seq,
}));
let target = [
hit.pos[0] + hit.face[0],
hit.pos[1] + hit.face[1],
hit.pos[2] + hit.face[2],
];
let ticks = self.ticks;
// Only a predicted placement (predict_place) marks a cell whose
// resend plays a place sound: an empty hand or a non-block item
// places nothing (BlockItem.place is where the sound comes from).
if let Some(r) = self.remote.as_mut() {
r.use_target = Some(hit.pos);
r.placing = Some((target, ticks));
}
if reacts {
self.predict_use(&changes, seq);
@@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[
impl Game<'_> {
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
fn parse_state(&self, text: &str) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let registry = &self.pack.assets.registry;
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
parse_state(self.pack.assets.registry, text)
}
pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
let int = |i: usize| -> Result<i32> {
@@ -137,3 +111,36 @@ impl Game<'_> {
}
}
}
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
pub(super) fn parse_state(
registry: &horizon_world::registry::BlockRegistry,
text: &str,
) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
}
+151 -3
View File
@@ -47,19 +47,72 @@ impl Game<'_> {
) -> bool {
false
}
pub(super) fn apply_mod_block_writes(&mut self) {}
}
#[cfg(feature = "mods")]
mod run {
use super::{Game, LanHost, ModEvent, Who};
use horizon_client::chunk_map::ChunkMap;
use horizon_client::{
command::args::GameMode as Mode,
lan::data::component_nbt,
text::{self, Text},
};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::registry::BlockStateId;
use horizon_world::registry::{BlockRegistry, BlockStateId};
/// Blocks queued for levels that don't tick (another dimension, in-frame)
/// are kept up to this many; the oldest go first.
const MAX_QUEUED_WRITES: usize = 1 << 16;
/// Capability `world`'s view during a call: the levels' chunks, moved out
/// of the game for the call and back after it (no copy).
struct LentWorld {
registry: &'static BlockRegistry,
biomes: std::sync::Arc<horizon_client::biome::Biomes>,
dims: Vec<(&'static str, ChunkMap)>,
}
impl WorldView for LentWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(state_string(self.registry, chunk.block(x & 15, y, z & 15)))
}
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(self.biomes.get(chunk.biome(x, y, z)).name.clone())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
crate::game::render_control::parse_state(self.registry, state)
.map(drop)
.map_err(|e| format!("{state}: {e}"))
}
}
/// `minecraft:oak_log[axis=y]`.
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
let Some(s) = registry.state(state) else {
return "minecraft:air".into();
};
if s.properties.is_empty() {
return s.name.clone();
}
let props: Vec<String> = s
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}[{}]", s.name, props.join(","))
}
/// `UUID.toString()`.
fn uuid_string(u: u128) -> String {
@@ -144,6 +197,7 @@ mod run {
let players = self.server_players(None);
let snapshot = self.mod_snapshot_with(players.clone());
self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let before = std::mem::take(&mut self.mods.players);
for p in before
.iter()
@@ -197,8 +251,80 @@ mod run {
}
}
self.mods.mods.server_tick(self.ticks);
self.return_world();
self.mods.players = players;
self.show_mod_output();
self.apply_mod_block_writes();
}
/// Lends the levels' chunks to capability `world` for the calls up to
/// [`Game::return_world`], when a running server mod has it.
fn lend_world(&mut self) {
if !self.mods.world {
return;
}
let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))];
for (dim, chunks) in self.levels.parked_chunks() {
dims.push((dim.id(), std::mem::take(chunks)));
}
let registry = self.pack.assets.registry;
let biomes = self.res.biomes().clone();
self.mods.mods.lend_world(Box::new(LentWorld {
registry,
biomes,
dims,
}));
}
/// Puts back the chunks [`Game::lend_world`] lent.
fn return_world(&mut self) {
let Some(view) = self.mods.mods.take_world() else {
return;
};
let view: Box<dyn std::any::Any> = view;
let Ok(lent) = view.downcast::<LentWorld>() else {
return;
};
let mut dims = lent.dims;
if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) {
self.world.chunks = dims.swap_remove(i).1;
}
for (dim, chunks) in self.levels.parked_chunks() {
if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) {
*chunks = dims.swap_remove(i).1;
}
}
}
/// Makes the blocks server mods set in the level in place, in order,
/// as `/setblock` does. Those of other dimensions wait for their level.
pub(in crate::game) fn apply_mod_block_writes(&mut self) {
if self.mods.block_writes.is_empty() {
return;
}
let dim = self.dim.id();
let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes)
.into_iter()
.partition(|(d, _)| d == dim);
self.mods.block_writes = later;
let registry = self.pack.assets.registry;
for (_, b) in now {
let state = match crate::game::render_control::parse_state(registry, &b.state) {
Ok(state) => state,
Err(e) => {
log::warn!("Horizon: a server mod set {}: {e}", b.state);
continue;
}
};
if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) {
log::debug!(
"Horizon: a server mod's block at {} {} {}: {e:?}",
b.x,
b.y,
b.z
);
}
}
}
/// A player broke (or placed) `state` at `pos`: the player acting now.
@@ -240,8 +366,11 @@ mod run {
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
self.show_mod_output();
self.apply_mod_block_writes();
owned
}
@@ -266,10 +395,14 @@ mod run {
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
if !self.mods.mods.server_command(&me, line) {
self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
if !owned {
return false;
}
self.route_mod_output(Some(host));
self.apply_mod_block_writes();
true
}
@@ -349,6 +482,21 @@ mod run {
self.tell_server_player(host.as_deref_mut(), &p.id, line);
}
}
Output::SetBlocks {
name,
dimension,
blocks,
} => {
let queued = &mut self.mods.block_writes;
queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b)));
if queued.len() > MAX_QUEUED_WRITES {
let over = queued.len() - MAX_QUEUED_WRITES;
queued.drain(..over);
log::warn!(
"Horizon: mod {name} set more blocks than wait for their level: {over} dropped"
);
}
}
_ => {}
}
}
+6 -6
View File
@@ -171,8 +171,8 @@ pub(super) struct Spawn {
pub(super) struct Spill {
pub(super) spawns: Vec<Spawn>,
/// Experience orbs (`ExperienceOrb.award`): where and how much, each
/// having drawn its merge id from the level random.
pub(super) orbs: Vec<([f64; 3], u32)>,
/// and the merge id it drew from the level random.
pub(super) orbs: Vec<([f64; 3], u32, i32)>,
/// Block entities the behaviour removed, for the game's own follow-ups
/// (open screens, playing songs).
pub(super) removed: Vec<([i32; 3], BlockEntity)>,
@@ -342,8 +342,8 @@ impl GameLevel<'_> {
while amount > 0 {
let value = removal::orb_value(amount);
amount -= value;
let _merge_id = self.world.random.next_int_bound(40);
self.spill.orbs.push((at, value));
let merge_id = self.world.random.next_int_bound(40).unwrap_or(0);
self.spill.orbs.push((at, value, merge_id));
}
}
/// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block
@@ -583,8 +583,8 @@ impl Game<'_> {
let motion = s.motion.unwrap_or_else(new_item_motion);
self.spawn_item(s.stack, s.pos, motion, s.delay);
}
for (at, value) in spill.orbs {
self.add_orb(at, value);
for (at, value, merge_id) in spill.orbs {
self.award_orb(at, value, merge_id);
}
for (pos, entity) in spill.removed {
let key = (pos[0], pos[1], pos[2]);
+2 -1
View File
@@ -713,7 +713,8 @@ impl Game<'_> {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
// Inventory.placeItemBackInInventory: `player.drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
/// `Player.giveExperienceLevels`.
+49
View File
@@ -33,6 +33,55 @@ impl Game<'_> {
self.container = Some(key);
self.ender_open = Some(key);
}
/// The block above `key` is a redstone conductor.
fn conductor_above(&self, key: (i32, i32, i32)) -> bool {
let above = self.world.block(key.0, key.1 + 1, key.2);
self.res.behaviours().facts(above).flags
& horizon_world::level::data::state_flags::CONDUCTOR
!= 0
}
/// `ChestBlock.isChestBlockedAt`: a redstone conductor above the chest or
/// a cat sitting on it.
fn chest_blocked_at(&self, key: (i32, i32, i32)) -> bool {
if self.conductor_above(key) {
return true;
}
// isCatSittingOnChest: a cat whose box meets the block above.
let area = horizon_core::geometry::Aabb::new(
horizon_core::geometry::Vec3::new(
f64::from(key.0),
f64::from(key.1 + 1),
f64::from(key.2),
),
horizon_core::geometry::Vec3::new(
f64::from(key.0 + 1),
f64::from(key.1 + 2),
f64::from(key.2 + 1),
),
);
self.mobs.iter().any(|m| {
m.species() == horizon_client::mobs::Species::Cat
&& m.alive()
&& horizon_client::mobs::tame::cat_sitting(m)
&& m.bounds().intersects(area)
})
}
/// `ChestBlock.getMenuProvider` (`combine(.., false)`) and
/// `EnderChestBlock.useWithoutItem`: a blocked chest, or a double chest
/// with either half blocked, opens no menu.
pub(super) fn chest_menu_blocked(&self, key: (i32, i32, i32), name: &str) -> bool {
match name {
"minecraft:chest" | "minecraft:trapped_chest" => {
self.chest_blocked_at(key)
|| self
.chest_partner(key)
.is_some_and(|(other, _)| self.chest_blocked_at(other))
}
// The ender chest only looks at the block above (no cat check).
"minecraft:ender_chest" => self.conductor_above(key),
_ => false,
}
}
/// Closing it copies the items back and leaves no block-entity contents.
pub(super) fn close_ender_chest(&mut self) {
let Some(key) = self.ender_open.take() else {
+87 -11
View File
@@ -1,7 +1,8 @@
//! Tridents: `TridentItem.releaseUsing` (throw after 10 ticks, or Riptide in
//! water or rain) and `ThrownTrident` (arrow flight with 0.99 water inertia,
//! 8 damage plus Impaling, the reversed bounce off a hit, sticking, Loyalty's
//! return to the owner, pickup) with `ThrownTridentRenderer`.
//! return to the owner, pickup) with `ThrownTridentRenderer`, and Channeling's
//! lightning on a hit (`channeling.json`).
use super::{Game, view_vector};
use horizon_client::{
collisions::SceneCollisions,
@@ -10,7 +11,8 @@ use horizon_client::{
mobs::{Damage, DamageKind, Who, anim::Poses},
};
use horizon_core::{
geometry::{Aabb, Vec3},
geometry::{Aabb, Vec3, traverse_blocks},
position::BlockPos,
random::RandomSource,
};
@@ -154,6 +156,69 @@ impl Game<'_> {
p.auto_spin_attack_dmg = 0.0;
}
}
/// The `summon_entity` and `play_sound` effects of `channeling.json`: in a
/// thunderstorm (`weather_check`) a spot that sees the sky (`can_see_sky`)
/// gets a lightning bolt and the thunder sound.
fn channel_lightning(&mut self, at: [f64; 3]) {
// Level.isThundering: the thunder level, in dimensions with weather.
if self.dim != super::Dim::Overworld || self.world.weather.levels(1.0).1 <= 0.9 {
return;
}
// BlockAndLightGetter.canSeeSky: full sky light.
let (x, y, z) = (
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
);
if self.world.light(x, y, z) >> 4 != 15 {
return;
}
self.spawn_bolt(at, false);
self.audio
.play("minecraft:item.trident.thunder", Some(at), 5.0, 1.0);
}
/// `minecraft:hit_block` of Channeling (`AbstractArrow.hitBlockEnchantmentEffects`):
/// the block the trident's path first hits, if it is a lightning rod, with
/// the hit location clamped into the block (`BlockPos.clampLocationWithin`).
fn channel_rod_hit(&mut self, from: Vec3, velocity: Vec3) {
let to = Vec3::new(
from.x + velocity.x,
from.y + velocity.y,
from.z + velocity.z,
);
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
// ClipContext.Block.COLLIDER with Fluid.NONE.
let hit = traverse_blocks(from, to, 1024, |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)
});
let Some(hit) = hit.ok().flatten() else {
return;
};
let state = self.world.block(hit.block.x, hit.block.y, hit.block.z);
if !self.res.facts().get(state).name.ends_with("lightning_rod") {
return;
}
let edge = f64::from(1.0e-5f32);
let clamp =
|v: f64, origin: i32| v.clamp(f64::from(origin) + edge, f64::from(origin) + 1.0 - edge);
self.channel_lightning([
clamp(hit.location.x, hit.block.x),
clamp(hit.location.y, hit.block.y),
clamp(hit.location.z, hit.block.z),
]);
}
/// `TridentItem.releaseUsing`.
pub(super) fn release_trident(&mut self, ticks: u32) {
if ticks < 10 {
@@ -171,10 +236,11 @@ impl Game<'_> {
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z]);
if riptide > 0 {
if !self.in_water_or_rain() {
// `isInWaterOrRain() && !isPassenger()`.
if !self.in_water_or_rain() || self.riding.is_some() {
return;
}
self.damage_held(1);
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);
@@ -195,12 +261,8 @@ impl Game<'_> {
self.audio.play(&sound, at, 1.0, 1.0);
return;
}
// hurtWithoutBreaking, then the thrown copy.
if !self.creative
&& let Some(s) = self.held_mut().as_mut()
{
s.damage += 1;
}
// hurtWithoutBreaking (Unbreaking applies), then the thrown copy.
self.hurt_held_without_breaking(1);
let thrown = self.held().cloned().unwrap_or(stack);
if !self.creative {
*self.held_mut() = None;
@@ -311,9 +373,10 @@ impl Game<'_> {
});
let damage = 8.0 + if aquatic { 2.5 * impaling } else { 0.0 };
t.dealt_damage = true;
let mut hurt_at = None;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
let from = Some([t.position.x, t.position.y, t.position.z]);
m.damage(
let hurt = m.damage(
damage,
Damage {
kind: DamageKind::Arrow,
@@ -321,6 +384,15 @@ impl Game<'_> {
from,
},
);
if hurt {
hurt_at = Some([m.position.x, m.position.y, m.position.z]);
}
}
// `minecraft:post_attack` of Channeling, on the victim.
if let Some(at) = hurt_at
&& t.stack.enchantment_level("minecraft:channeling") > 0
{
self.channel_lightning(at);
}
self.audio.play(
"minecraft:item.trident.hit",
@@ -341,6 +413,7 @@ impl Game<'_> {
subject: None,
};
if let Ok(moved) = scene.resolve(bounds(t.position), t.velocity, 0.0, false) {
let (from, flight) = (t.position, t.velocity);
let blocked = (moved.x - t.velocity.x).abs() > 1e-7
|| (moved.y - t.velocity.y).abs() > 1e-7
|| (moved.z - t.velocity.z).abs() > 1e-7;
@@ -350,6 +423,9 @@ impl Game<'_> {
t.position.z + moved.z,
);
if blocked {
if t.stack.enchantment_level("minecraft:channeling") > 0 {
self.channel_rod_hit(from, flight);
}
t.in_ground = true;
t.velocity = Vec3::ZERO;
self.audio.play(
@@ -21,6 +21,38 @@ impl Game<'_> {
fn item_max_stack(&self, item: &str) -> u32 {
self.res.items().get(item).map_or(64, |i| i.max_stack)
}
/// `WorkAtComposter.useWorkstation`: at a composter the farmer makes
/// bread, then composts seeds.
pub(super) fn villager_work_at_composter(&mut self, id: u32, pos: [i32; 3]) {
let Some(i) = self.villager_index(id) else {
return;
};
if self.composter_level(pos).is_none() {
return;
}
self.villager_make_bread(i);
self.villager_compost_items(i, pos);
}
/// `WorkAtComposter.makeBread`: up to three loaves from nine wheat while
/// the villager holds at most 36 bread; what does not fit drops.
fn villager_make_bread(&mut self, i: usize) {
let max_stack = self.item_max_stack("minecraft:bread");
let e = villager::ext_mut(&mut self.mobs[i]);
if e.count_item("minecraft:bread") > 36 {
return;
}
let loaves = (e.count_item("minecraft:wheat") / 3).min(3);
if loaves == 0 {
return;
}
e.remove_item("minecraft:wheat", loaves * 3);
let left = e.add_item(ItemStack::new("minecraft:bread", loaves), max_stack);
if let Some(rest) = left {
// spawnAtLocation(level, stack, 0.5F)
let p = self.mobs[i].position;
self.spawn_item(rest, [p.x, p.y + 0.5, p.z], [0.0, 0.2, 0.0], 10);
}
}
/// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward
/// a point.
fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) {
@@ -46,6 +46,10 @@ impl WorldRequest {
options: &Options,
settings: &Settings,
) -> Result<PreparedWorld> {
// Before any chunk is read: a loaded container with a loot table is rolled as its chunk
// is decoded (`save::roll_loaded_loot`), and the spawn chunks are read while the world
// opens. Every world opens here: in-frame, on the server thread, on a dedicated server.
horizon_client::structure_blocks::loot_data(&options.resources);
let Self {
save_root,
folder,
@@ -0,0 +1,134 @@
//! `Zombie.hurtServer`'s reinforcements: a hurt zombie on Hard may call
//! another of its kind from 7 to 40 blocks away to fight its target.
use super::Game;
use horizon_client::mobs::{
MobType, Species, Who,
finalize::{self, Attr, Op},
spawn_rules::{self, Reason},
spawn_selection::{self, NaturalLevel},
spawner::SpawnerLevel,
};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::food::Difficulty;
/// `Zombie.REINFORCEMENT_ATTEMPTS`.
const ATTEMPTS: usize = 50;
/// `Zombie.REINFORCEMENT_RANGE_MIN` and `REINFORCEMENT_RANGE_MAX`.
const RANGE_MIN: i32 = 7;
const RANGE_MAX: i32 = 40;
/// One axis of the offset: `Mth.nextInt(random, 7, 40) * Mth.nextInt(random, -1, 1)`.
fn offset(random: &mut LegacyRandom) -> i32 {
let distance = random
.next_int_between_inclusive(RANGE_MIN, RANGE_MAX)
.unwrap_or(RANGE_MIN);
distance * random.next_int_between_inclusive(-1, 1).unwrap_or(0)
}
impl Game<'_> {
/// `Zombie.hurtServer` after the hit: on Hard, with the zombie's chance
/// and monsters spawning, a copy of it appears out of sight and takes
/// `target`; both then call less often.
pub(super) fn call_reinforcements(&mut self, caller: u32, target: Who) {
let Some(index) = self.mobs.iter().position(|m| m.id == caller) else {
return;
};
if self.world.health_rules.difficulty != Difficulty::Hard {
return;
}
let zombie = &mut self.mobs[index];
if f64::from(zombie.random.next_float()) >= zombie.attrs.spawn_reinforcements {
return;
}
// ServerLevel.isSpawningMonsters.
if !self.ui.rules.bool("spawn_mobs") || !self.ui.rules.bool("spawn_monsters") {
return;
}
let kind = zombie.kind.clone();
let from = [
zombie.position.x.floor() as i32,
zombie.position.y.floor() as i32,
zombie.position.z.floor() as i32,
];
let mut own = std::mem::replace(&mut zombie.random, LegacyRandom::new(0));
let mut rules = std::mem::replace(&mut self.world.random, LegacyRandom::new(0));
let spot = self.reinforcement_spot(&kind, from, &mut own, &mut rules);
self.mobs[index].random = own;
self.world.random = rules;
let Some(spot) = spot else {
return;
};
let Some(id) = self.spawn_mob(&kind.id, spot.map(f64::from), false) else {
return;
};
if let Some(reinforcement) = self.mobs.iter_mut().find(|m| m.id == id) {
reinforcement.ai.target = Some(target);
// ZOMBIE_REINFORCEMENT_CALLEE_CHARGE.
finalize::add_modifier(
reinforcement,
Attr::SpawnReinforcements,
"minecraft:reinforcement_callee_charge",
-f64::from(0.05f32),
Op::AddValue,
);
}
// The caller's charge grows by 0.05 each time it calls.
let caller = &mut self.mobs[index];
let charged = finalize::modifier_amount(
caller,
Attr::SpawnReinforcements,
"minecraft:reinforcement_caller_charge",
)
.unwrap_or(0.0);
finalize::add_modifier(
caller,
Attr::SpawnReinforcements,
"minecraft:reinforcement_caller_charge",
charged - 0.05,
Op::AddValue,
);
}
/// The block `Zombie.hurtServer` puts the reinforcement at: the first of
/// 50 random offsets with a valid spawn surface, no alive player within
/// 7 blocks, and room for the zombie standing on the block's corner.
fn reinforcement_spot(
&self,
kind: &MobType,
from: [i32; 3],
own: &mut LegacyRandom,
rules: &mut LegacyRandom,
) -> Option<[i32; 3]> {
let level = self.natural_level();
let (width, height) = (kind.width as f32, kind.height as f32);
for _ in 0..ATTEMPTS {
let [x, y, z] = from.map(|v| v + offset(own));
if !spawn_rules::is_spawn_position_ok(kind.species, &level, x, y, z)
|| !spawn_rules::check_spawn_rules(
kind.species,
&level,
Reason::Reinforcement,
rules,
x,
y,
z,
)
{
continue;
}
// setPos(x, y, z): the box is centred on the block's corner.
let bounds =
spawn_selection::spawn_box(f64::from(x), f64::from(y), f64::from(z), width, height);
// Drowned.canSpawnInLiquids.
let wet_ok = kind.species == Species::Drowned
|| !spawn_selection::contains_any_liquid(&level, bounds);
if !level.alive_player_near(f64::from(x), f64::from(y), f64::from(z), 7.0)
&& level.unobstructed(bounds)
&& level.no_collision(bounds)
&& wet_ok
{
return Some([x, y, z]);
}
}
None
}
}
+14 -2
View File
@@ -111,6 +111,12 @@ pub enum HealthEvent {
amount: f32,
},
Phase(&'static str),
/// `Player.hurtArmor`: a hit that doesn't bypass armor wears the worn
/// pieces (`LivingEntity.getDamageAfterArmorAbsorb`); the game applies it.
ArmorHurt {
source: DamageTypeId,
amount: f32,
},
/// `ServerLevel.broadcastDamageEvent`: the client's
/// `LivingEntity.handleDamageEvent` plays the source's hurt sound.
DamageBroadcast {
@@ -139,6 +145,7 @@ impl HealthEvent {
format!("record-damage {:08x}", amount.to_bits())
}
Self::Phase(name) => name.into(),
Self::ArmorHurt { amount, .. } => format!("hurt-armor {:08x}", amount.to_bits()),
Self::DamageBroadcast { .. } => "broadcast-damage".into(),
Self::Criterion { .. } => "hurt-criterion".into(),
}
@@ -534,9 +541,14 @@ impl ServerDamageEnvironment<Attributes> for Environment<'_> {
fn bypasses(&mut self, kind: Bypass) -> io::Result<bool> {
Ok(self.source.bypasses(kind))
}
fn hurt_armor(&mut self, _: &mut Attributes, _: f32) -> io::Result<()> {
fn hurt_armor(&mut self, _: &mut Attributes, damage: f32) -> io::Result<()> {
// The worn armor lives in the game, which wears it from this event.
self.event(HealthEvent::ArmorHurt {
source: self.source.type_id(),
amount: damage,
});
Ok(())
} // empty equipment
}
fn has_resistance(&mut self) -> io::Result<bool> {
Ok(self.status.resistance.is_some())
}
+78 -3
View File
@@ -113,6 +113,9 @@ pub struct ItemInfo {
pub swappable: bool,
/// `equippable.dispensable` (dispensers may put it on an entity).
pub equip_dispensable: bool,
/// `equippable.damage_on_hurt`: the item wears when its wearer is hurt
/// (false for the elytra).
pub equip_damage_on_hurt: bool,
/// `equippable.allowed_entities` resolved to entity type ids; None allows all.
pub equip_allowed: Option<HashSet<String>>,
pub equip_sound: Option<String>,
@@ -400,6 +403,36 @@ impl Items {
self.get(&stack.item).is_some_and(|i| i.fire_resistant)
}
/// `ItemStack.canBeHurtBy` for the cactus damage type: a `damage_resistant`
/// component naming `minecraft:cactus`, or a damage type tag that holds it.
/// (`#minecraft:is_fire`, as on netherite gear, does not.)
pub fn resists_cactus(&self, stack: &ItemStack) -> bool {
const CACTUS_TAGS: [&str; 5] = [
"#minecraft:bypasses_shield",
"#minecraft:no_knockback",
"#minecraft:panic_environmental_causes",
"#minecraft:panic_causes",
"#minecraft:sulfur_cube_with_block_immune_to",
];
let Some((_, v)) = stack.data().and_then(|data| {
data.other
.iter()
.find(|(key, _)| key == "minecraft:damage_resistant")
}) else {
return false;
};
match v.get("types") {
Some(horizon_world::nbt::Tag::String(id)) => id
.to_string()
.is_ok_and(|id| id == "minecraft:cactus" || CACTUS_TAGS.contains(&id.as_str())),
Some(horizon_world::nbt::Tag::List(ids)) => ids.iter().any(|t| {
matches!(t, horizon_world::nbt::Tag::String(id)
if id.to_string().is_ok_and(|id| id == "minecraft:cactus"))
}),
_ => false,
}
}
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
@@ -596,6 +629,9 @@ impl Items {
equip_dispensable: c["minecraft:equippable"]["dispensable"]
.as_bool()
.unwrap_or(true),
equip_damage_on_hurt: c["minecraft:equippable"]["damage_on_hurt"]
.as_bool()
.unwrap_or(true),
equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] {
Value::String(spec) => Some(entity_spec(&entity_tags, spec)),
Value::Array(list) => Some(
@@ -834,6 +870,7 @@ impl Items {
held: None,
killed_by_player: false,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -898,10 +935,26 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
) -> Vec<ItemStack> {
self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None)
self.block_drops_exploded(
registry, state, held, dynamic, random, sequences, None, false,
)
}
/// `block_drops_with` for a block a player breaks (`Block.playerDestroy`):
/// the player is the loot context's `this` entity, so snow and chorus
/// flower tables see an entity.
pub fn block_drops_by_player(
&self,
registry: &BlockRegistry,
state: BlockStateId,
held: Option<&ItemStack>,
dynamic: &[ItemStack],
random: &mut impl RandomSource,
) -> Vec<ItemStack> {
self.block_drops_exploded(registry, state, held, dynamic, random, None, None, true)
}
/// `block_drops_full` for a block an explosion destroys: `explosion`
/// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`).
/// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`);
/// `breaker` is whether an entity (the player) broke the block.
#[allow(clippy::too_many_arguments)]
pub fn block_drops_exploded(
&self,
@@ -912,8 +965,10 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
explosion: Option<f32>,
breaker: bool,
) -> Vec<ItemStack> {
let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion);
let drops =
self.block_drops_raw(registry, state, held, random, sequences, explosion, breaker);
if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) {
return drops;
}
@@ -928,6 +983,7 @@ impl Items {
})
.collect()
}
#[allow(clippy::too_many_arguments)]
fn block_drops_raw(
&self,
registry: &BlockRegistry,
@@ -936,6 +992,7 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
explosion_radius: Option<f32>,
breaker: bool,
) -> Vec<ItemStack> {
let Some(block) = registry.state(state) else {
return vec![];
@@ -969,6 +1026,7 @@ impl Items {
held,
killed_by_player: false,
explosion_radius,
this_entity: breaker,
};
return ctx.evaluate(table, random);
}
@@ -979,6 +1037,7 @@ impl Items {
held,
killed_by_player: false,
explosion_radius,
this_entity: breaker,
};
ctx.evaluate(table, random)
}
@@ -1002,6 +1061,7 @@ impl Items {
held,
killed_by_player,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -1034,6 +1094,7 @@ impl Items {
held: None,
killed_by_player: false,
explosion_radius: None,
this_entity: false,
};
match table.get("random_sequence").and_then(Value::as_str) {
Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)),
@@ -1059,6 +1120,7 @@ impl Items {
held,
killed_by_player,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -1081,6 +1143,7 @@ impl Items {
held,
killed_by_player,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -1122,6 +1185,8 @@ struct LootContext<'a> {
killed_by_player: bool,
/// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops.
explosion_radius: Option<f32>,
/// `LootContextParams.THIS_ENTITY` is set (a player broke the block).
this_entity: bool,
}
impl LootContext<'_> {
/// Level of an enchantment on the tool / killer's weapon.
@@ -1282,6 +1347,15 @@ impl LootContext<'_> {
};
random.next_float() < chance
}
// `this` with no checks (snow, chorus flower) holds when an entity
// broke the block (LootItemEntityPropertyCondition needs the entity).
"minecraft:entity_properties"
if self.this_entity
&& c["entity"].as_str() == Some("this")
&& c["predicate"].as_object().is_none_or(|p| p.is_empty()) =>
{
true
}
// Entity flags, equipment and damage-source predicates: none hold
// for an unenchanted player kill without fire or lightning.
"minecraft:entity_properties" | "minecraft:damage_source_properties" => false,
@@ -1667,6 +1741,7 @@ mod tests {
held,
killed_by_player: block.is_empty(),
explosion_radius: None,
this_entity: false,
}
}
+76 -2
View File
@@ -25,6 +25,7 @@ pub mod creaking;
pub mod creaking_heart;
pub mod cube;
pub mod data;
pub mod doors;
pub mod drops;
pub mod enderman;
pub mod equine;
@@ -68,6 +69,7 @@ pub mod tame;
pub mod trader;
pub mod transport_items;
pub mod trial_spawner;
pub mod turtle;
pub mod undead;
pub mod vex;
pub mod villager;
@@ -665,6 +667,8 @@ pub struct Extra {
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
/// `Piglin.inventory` (`SimpleContainer(8)`): what it picked up and kept.
pub inventory: Vec<crate::items::ItemStack>,
pub tame: bool,
pub sitting: bool,
/// The owner's UUID (tamed animals).
@@ -973,6 +977,14 @@ pub enum MobEvent {
owner: u32,
},
Shoot([f64; 3], [f64; 3]),
/// The mob the `Explode` right after this comes from
/// (`ServerExplosion.source`), and whether it is a charged creeper: the
/// exploding creeper is already out of the mob list when the game applies
/// the blast, so its victims' loot cannot look it up.
ExplosionSource {
mob: u32,
charged: bool,
},
Explode([f64; 3], f32),
/// Melee or ranged damage to another mob.
AttackMob {
@@ -1009,6 +1021,24 @@ pub enum MobEvent {
pos: [i32; 3],
open: bool,
},
/// `BreakDoorGoal.tick` at its end: the door is removed (`removeBlock`),
/// then level events 1021 and 2001 with the state that is left there.
BreakDoor {
pos: [i32; 3],
},
/// `Level.destroyBlockProgress` for a mob's crack on a block (`-1`
/// clears it).
DestroyProgress {
mob: u32,
pos: [i32; 3],
progress: i32,
},
/// `Level.levelEvent`: the game plays and sends the event.
LevelEvent {
id: i32,
pos: [i32; 3],
data: i32,
},
/// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock).
BreakBlock {
pos: [i32; 3],
@@ -1106,6 +1136,13 @@ pub enum MobEvent {
partner: u32,
child: Option<([i32; 3], Option<u8>)>,
},
/// `WorkAtComposter.useWorkstation`: a farmer at its composter makes
/// bread and composts seeds (the game applies it to the villager's
/// inventory and the block).
WorkAtComposter {
mob: u32,
pos: [i32; 3],
},
/// A villager asks whether enough neighbours want an iron golem.
GolemCheck {
mob: u32,
@@ -1134,8 +1171,10 @@ pub enum MobEvent {
target: Who,
aggressive: bool,
},
/// Drop the loot of a gift table (chicken eggs, armadillo scutes).
/// Drop the loot of a gift table (chicken eggs, sniffer seeds) with the
/// mob as `this` (`LivingEntity.dropFromGiftLootTable`).
GiftLoot {
mob: u32,
table: &'static str,
at: [f64; 3],
},
@@ -1159,6 +1198,18 @@ pub enum MobEvent {
DigParticles {
at: [f64; 3],
},
/// `Zombie.hurtServer`: a zombie hurt with a target in sight (its own,
/// else the attacker) may call a reinforcement against it on Hard.
Reinforcements {
mob: u32,
target: Who,
},
/// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at
/// `block`: a turtle's digging.
BlockBreakEffect {
pos: [i32; 3],
block: [i32; 3],
},
/// `Warden.applyDarknessAround`: darkness for survival players nearby.
Darkness {
at: [f64; 3],
@@ -1255,6 +1306,14 @@ pub struct Seen {
pub sitting: bool,
/// `Entity.isVehicle` or `isPassenger`.
pub ridden: bool,
/// The active effects, without namespace (`slowness`, `poison`...).
pub effects: Vec<&'static str>,
}
impl Seen {
/// `LivingEntity.hasEffect`, by id without namespace.
pub fn has_effect(&self, effect: &str) -> bool {
self.effects.contains(&effect)
}
}
impl Mob {
pub fn burning_time(&self) -> f64 {
@@ -1329,6 +1388,12 @@ impl Mob {
],
sitting: m.extra.sitting,
ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(),
effects: m
.extra
.effects
.iter()
.map(|e| e.0.trim_start_matches("minecraft:"))
.collect(),
}
}
/// `EntityType.getCategory`'s name.
@@ -1473,6 +1538,8 @@ pub struct PlayerView {
pub yaw: f32,
/// The Hero of the Village effect.
pub hero: bool,
/// The active effects, without namespace (`slowness`, `poison`...).
pub effects: Vec<&'static str>,
/// The player's UUID (villagers' gossip is keyed by it).
pub uuid: [i32; 4],
/// The mobs on the player's team (`isAlliedTo`): combat targeting
@@ -1482,6 +1549,12 @@ pub struct PlayerView {
/// (`EntitySelector.pushableBy` on the client).
pub remote: bool,
}
impl PlayerView {
/// `LivingEntity.hasEffect`, by id without namespace.
pub fn has_effect(&self, effect: &str) -> bool {
self.effects.contains(&effect)
}
}
#[derive(Clone)]
pub struct MobWorld<'a> {
pub world: &'a World,
@@ -1857,7 +1930,8 @@ 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, self.attrs.speed) * self.speed_bonus();
let mut v = strider::movement_speed(self, witch::speed(self, self.attrs.speed))
* self.speed_bonus();
for (e, _, amp) in &self.extra.effects {
match *e {
"minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1),
+26 -3
View File
@@ -183,6 +183,9 @@ pub fn register(m: &mut Mob) {
if m.species() == Species::Rabbit {
super::rabbit::register(m);
}
if m.species() == Species::Turtle {
super::turtle::register(m);
}
}
Family::Inert => {}
Family::Witch => super::witch::register(m),
@@ -712,6 +715,14 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
// setAge at the age boundary: refreshDimensions.
if m.extra.age >= 0 {
m.fudge_position_after_size_change(w, bw, bh);
// Turtle.ageBoundaryReached: a grown turtle drops a scute.
if m.species() == Species::Turtle {
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/turtle_grow",
at: [m.position.x, m.position.y, m.position.z],
});
}
}
} else if m.extra.age > 0 {
m.extra.age -= 1;
@@ -746,7 +757,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) && m.extra.head.is_none() {
m.ignite_for_ticks(160);
}
species_ai_step(m, w, events);
species_ai_step(m, w, level_random, events);
}
impl Mob {
/// LivingEntity.isPushable (and the push it takes from `Entity.push(Entity)`):
@@ -944,6 +955,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
| Species::Parched
| Species::WitherSkeleton
| Species::ZombifiedPiglin => undead::custom_server_ai_step(m, cx),
Species::Vindicator => super::illager::vindicator_server_ai_step(m),
Species::Enderman => super::enderman::custom_server_ai_step(m, cx),
Species::Blaze => super::nether::blaze_server_ai_step(m, cx),
Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx),
@@ -955,7 +967,12 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
_ => {}
}
}
fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
fn species_ai_step(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
if family(m.species()) == Family::Aquatic {
aquatic::ai_step(m, w, events);
}
@@ -988,7 +1005,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
Species::Shulker => {
super::shulker::tick(m, w, events);
super::shulker::ai_step(m, w, events);
super::shulker::ai_step(m, w, level_random, events);
}
Species::SnowGolem => super::golem::snow_ai_step(m, w, events),
Species::CopperGolem => super::copper_golem::ai_step(m, w, events),
@@ -999,6 +1016,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events),
Species::Chicken => farm::chicken_ai_step(m, w, events),
Species::Turtle => super::turtle::ai_step(m, w, events),
Species::Sheep if m.extra.anim_ticks > 0 => {
m.extra.anim_ticks -= 1;
}
@@ -1324,6 +1342,11 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
Species::Warden => super::warden::hurt(m, source),
Species::Wolf => super::tame::after_hurt(m, source),
Species::Nautilus | Species::ZombieNautilus => super::nautilus::after_hurt(m, source),
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin => super::undead::after_hurt(m, source),
// NeutralMob: an iron golem hit by the player stays angry a while.
// PiglinAi.wasHurtBy: drop what is being admired, no admiring for
// a while after a player's hit, and anger.
+2 -2
View File
@@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
s,
&Turtle {
on_land: !m.fluids.in_water && m.on_ground,
laying_egg: false,
has_egg: false,
laying_egg: m.extra.flag2,
has_egg: m.extra.flag,
},
),
Species::Strider => strider(p, s, m.rider.is_some()),
+252
View File
@@ -0,0 +1,252 @@
//! Doors a mob gets through on its own: `DoorInteractGoal` with its two
//! users, `BreakDoorGoal` (zombies that can break doors, vindicators in a
//! raid) and `OpenDoorGoal` (`AbstractIllager.RaiderOpenDoorGoal`).
use super::{
Mob, MobEvent, MobWorld, Species,
goals::{Cx, Goal, MOVE, goal_clone, reduced},
nav::NavKind,
raider,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
/// `DefaultDoorBreakTime`: `BreakDoorGoal.getDoorBreakTime` is
/// `max(240, doorBreakTime)`, and the vindicator's 6 is below it.
const DOOR_BREAK_TIME: i32 = 240;
/// `GoalUtils.hasGroundPathNavigation`: ground, wall-climbing and
/// amphibious navigations walk.
pub fn can_navigate_ground(m: &Mob) -> bool {
matches!(
m.ai.nav.kind,
NavKind::Ground | NavKind::WallClimber | NavKind::Amphibious
)
}
/// `Zombie.setCanBreakDoors`: only a mob that walks can break doors, and
/// then its navigation opens them.
pub fn set_can_break_doors(m: &mut Mob, can_break: bool) {
let can_break = can_break && can_navigate_ground(m);
m.extra.can_break_doors = can_break;
m.ai.nav.can_open_doors = can_break;
}
/// The species that extend `Zombie` (`CanBreakDoors` is theirs to save).
pub fn is_zombie(s: Species) -> bool {
matches!(
s,
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin
)
}
/// `DoorBlock.isWoodenDoor`: a door a hand opens, which is any but iron.
fn wooden_door(w: &MobWorld, p: [i32; 3]) -> bool {
let name = w.block_name(p[0], p[1], p[2]);
name.ends_with("_door") && name != "minecraft:iron_door"
}
/// `DoorInteractGoal`'s door: where it is and whether one is there.
#[derive(Clone, Debug, Default)]
struct Interact {
door: [i32; 3],
has_door: bool,
}
impl Interact {
/// `DoorInteractGoal.canUse`: the mob bumped into something and a
/// wooden door is on its path within 1.5 blocks, or at its own head.
fn can_use(&mut self, m: &Mob, w: &MobWorld) -> bool {
if !can_navigate_ground(m) || !m.horizontal_collision {
return false;
}
let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) else {
return false;
};
for node in path
.nodes
.iter()
.take((path.next + 2).min(path.nodes.len()))
{
self.door = [node.x, node.y + 1, node.z];
let dx = m.position.x - f64::from(node.x);
let dz = m.position.z - f64::from(node.z);
if dx * dx + dz * dz <= 2.25 {
self.has_door = wooden_door(w, self.door);
if self.has_door {
return true;
}
}
}
let at = m.position;
self.door = [
at.x.floor() as i32,
at.y.floor() as i32 + 1,
at.z.floor() as i32,
];
self.has_door = wooden_door(w, self.door);
self.has_door
}
/// `DoorInteractGoal.isOpen`: the door is still there and open.
fn is_open(&mut self, w: &MobWorld) -> bool {
if !self.has_door {
return false;
}
let d = self.door;
if !w.block_name(d[0], d[1], d[2]).ends_with("_door") {
self.has_door = false;
return false;
}
w.prop(d[0], d[1], d[2], "open") == Some("true")
}
/// `DoorInteractGoal.setOpen`.
fn set_open(&self, cx: &mut Cx, open: bool) {
let d = self.door;
if self.has_door && cx.w.block_name(d[0], d[1], d[2]).ends_with("_door") {
cx.events.push(MobEvent::SetDoorOpen { pos: d, open });
}
}
}
/// `BlockPos.closerToCenterThan`.
fn closer_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool {
Vec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
)
.distance_squared(at)
< distance * distance
}
/// `BreakDoorGoal`: crack the door in the way for 240 ticks, then remove it.
/// A zombie does it on hard only; `Vindicator.VindicatorBreakDoorGoal` on
/// normal and hard, in a raid, and holds the mob's movement.
#[derive(Clone, Debug)]
pub struct BreakDoor {
interact: Interact,
vindicator: bool,
break_time: i32,
last_break_progress: i32,
}
impl BreakDoor {
/// `Zombie.breakDoorGoal`, added when the zombie can break doors.
pub fn zombie() -> Self {
Self::new(false)
}
/// `Vindicator.VindicatorBreakDoorGoal`.
pub fn vindicator() -> Self {
Self::new(true)
}
fn new(vindicator: bool) -> Self {
Self {
interact: Interact::default(),
vindicator,
break_time: 0,
last_break_progress: -1,
}
}
/// `DOOR_BREAKING_PREDICATE`.
fn valid_difficulty(&self, w: &MobWorld) -> bool {
if self.vindicator {
w.difficulty.normal || w.difficulty.hard
} else {
w.difficulty.hard
}
}
/// `BreakDoorGoal.canUse` after `DoorInteractGoal.canUse`.
fn can_break(&mut self, m: &Mob, w: &MobWorld) -> bool {
self.interact.can_use(m, w)
&& w.mob_griefing
&& self.valid_difficulty(w)
&& !self.interact.is_open(w)
}
}
impl Goal for BreakDoor {
goal_clone!();
fn flags(&self) -> u8 {
if self.vindicator { MOVE } else { 0 }
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if self.vindicator {
return raider::has_active_raid(m)
&& m.random.next_int_bound(reduced(10)).unwrap_or(1) == 0
&& self.can_break(m, cx.w);
}
m.extra.can_break_doors && self.can_break(m, cx.w)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
(!self.vindicator || raider::has_active_raid(m))
&& self.break_time <= DOOR_BREAK_TIME
&& !self.interact.is_open(cx.w)
&& closer_to_center(self.interact.door, m.position, 2.0)
&& self.valid_difficulty(cx.w)
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
self.break_time = 0;
if self.vindicator {
m.ai.no_action_time = 0;
}
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
cx.events.push(MobEvent::DestroyProgress {
mob: m.id,
pos: self.interact.door,
progress: -1,
});
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let door = self.interact.door;
if m.random.next_int_bound(20).unwrap_or(1) == 0 {
cx.events.push(MobEvent::LevelEvent {
id: 1019,
pos: door,
data: 0,
});
if !m.ai.swinging {
m.swing();
}
}
self.break_time += 1;
let progress = (self.break_time as f32 / DOOR_BREAK_TIME as f32 * 10.0) as i32;
if progress != self.last_break_progress {
cx.events.push(MobEvent::DestroyProgress {
mob: m.id,
pos: door,
progress,
});
self.last_break_progress = progress;
}
if self.break_time == DOOR_BREAK_TIME && self.valid_difficulty(cx.w) {
cx.events.push(MobEvent::BreakDoor { pos: door });
}
}
}
/// `AbstractIllager.RaiderOpenDoorGoal` (`OpenDoorGoal` that does not wait
/// to close): open the door in the way during a raid. It never continues, so
/// it closes the door again as soon as it stops.
#[derive(Clone, Debug, Default)]
pub struct RaiderOpenDoor {
interact: Interact,
}
impl Goal for RaiderOpenDoor {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.interact.can_use(m, cx.w) && raider::has_active_raid(m)
}
fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool {
false
}
fn start(&mut self, _m: &mut Mob, cx: &mut Cx) {
self.interact.set_open(cx, true);
}
fn stop(&mut self, _m: &mut Mob, cx: &mut Cx) {
self.interact.set_open(cx, false);
}
}
+11
View File
@@ -351,6 +351,9 @@ pub fn loot_entity(m: &Mob, vehicle: Option<LootEntity>) -> LootEntity {
.to_owned(),
);
}
if s == S::Chicken {
e.chicken_variant = super::finalize::variant_component(m).map(|(_, id)| id);
}
e.powered = s == S::Creeper && m.extra.charged;
e.equipment = SLOTS
.iter()
@@ -456,6 +459,14 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec<Drop
out.push(Drop::Item(loot_stack("minecraft:nether_star", 1)));
}
}
// Piglin.dropCustomDeathLoot: everything in its inventory.
if s == Species::Piglin {
for stack in m.extra.inventory.drain(..) {
let mut item = loot_stack(&stack.item, stack.count as i32);
item.damage = stack.damage as i32;
out.push(Drop::Item(item));
}
}
// dropEquipment: AbstractHorse's inventory, then a chested horse's chest.
if equine::is_equine(s) {
for stack in m.extra.items.iter().flatten() {
+1
View File
@@ -80,6 +80,7 @@ pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::Sound("entity.chicken.egg", at, 1.0, pitch));
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/chicken_lay",
at,
});
+72 -56
View File
@@ -590,6 +590,14 @@ pub fn has_modifier(m: &Mob, a: Attr, id: &str) -> bool {
.as_ref()
.is_some_and(|s| s.modifiers.iter().any(|x| x.attr == a && x.id == id))
}
/// The amount of a permanent modifier, if the mob has it.
pub fn modifier_amount(m: &Mob, a: Attr, id: &str) -> Option<f64> {
m.extra
.attributes
.as_ref()
.and_then(|s| s.modifiers.iter().find(|x| x.attr == a && x.id == id))
.map(|x| x.amount)
}
/// `addOrReplacePermanentModifier`.
pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) {
let s = m.extra.attributes.get_or_insert_with(Box::default);
@@ -605,6 +613,59 @@ pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op)
}
refresh(m, a);
}
/// `Zombie.handleAttributes`, from the zombie's own random.
pub fn zombie_attributes(m: &mut Mob, special: f32, reason: Reason) {
let r = &mut m.random;
let reinforcements = if m.kind.species == Species::ZombifiedPiglin {
0.0
} else {
r.next_double() * f64::from(0.1f32)
};
let knockback = r.next_double() * f64::from(0.05f32);
let follow = r.next_double() * 1.5 * f64::from(special);
let leader = r.next_float() < special * 0.05;
let leader_rolls = leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0));
set_base(m, Attr::SpawnReinforcements, reinforcements);
add_modifier(
m,
Attr::KnockbackResistance,
"minecraft:random_spawn_bonus",
knockback,
Op::AddValue,
);
if follow > 1.0 {
add_modifier(
m,
Attr::FollowRange,
"minecraft:zombie_random_spawn_bonus",
follow,
Op::AddMultipliedTotal,
);
}
if let Some((reinforce, health)) = leader_rolls {
add_modifier(
m,
Attr::SpawnReinforcements,
"minecraft:leader_zombie_bonus",
reinforce,
Op::AddValue,
);
add_modifier(
m,
Attr::MaxHealth,
"minecraft:leader_zombie_bonus",
health,
Op::AddMultipliedTotal,
);
if !matches!(
reason,
Reason::Conversion | Reason::Load | Reason::DimensionTravel
) {
m.health = max_health(m);
}
super::doors::set_can_break_doors(m, true);
}
}
pub fn max_health(m: &Mob) -> f32 {
value(m, Attr::MaxHealth) as f32
}
@@ -829,6 +890,14 @@ pub fn set_item(m: &mut Mob, slot: usize, id: &str) {
}
gear::set(m, gear_slot(slot), Vec::new());
}
/// The enchantments on what `m` has in `slot`.
pub fn slot_enchantments(m: &Mob, slot: usize) -> gear::Levels {
gear::gear(m).map_or_else(Vec::new, |g| g.slots[gear_slot(slot)].clone())
}
/// Replace the enchantments of what `m` has in `slot` (after `set_item`).
pub fn set_slot_enchantments(m: &mut Mob, slot: usize, levels: gear::Levels) {
gear::set(m, gear_slot(slot), levels);
}
/// `Mob.setDropChance`.
pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) {
let c = m
@@ -1144,70 +1213,17 @@ impl<L: FinalizeLevel + ?Sized, R: RandomSource> Ctx<'_, L, R> {
}
}
}
m.extra.can_break_doors = self.float() < special * 0.1;
let can_break_doors = self.float() < special * 0.1;
super::doors::set_can_break_doors(m, can_break_doors);
if reason != Reason::Conversion {
self.populate(m);
self.enchant(m);
}
}
self.halloween(m);
self.zombie_attributes(m, special, reason);
zombie_attributes(m, special, reason);
g
}
/// `Zombie.handleAttributes`, from the zombie's own random.
fn zombie_attributes(&mut self, m: &mut Mob, special: f32, reason: Reason) {
let r = &mut m.random;
let reinforcements = if m.kind.species == Species::ZombifiedPiglin {
0.0
} else {
r.next_double() * f64::from(0.1f32)
};
let knockback = r.next_double() * f64::from(0.05f32);
let follow = r.next_double() * 1.5 * f64::from(special);
let leader = r.next_float() < special * 0.05;
let leader_rolls =
leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0));
set_base(m, Attr::SpawnReinforcements, reinforcements);
add_modifier(
m,
Attr::KnockbackResistance,
"minecraft:random_spawn_bonus",
knockback,
Op::AddValue,
);
if follow > 1.0 {
add_modifier(
m,
Attr::FollowRange,
"minecraft:zombie_random_spawn_bonus",
follow,
Op::AddMultipliedTotal,
);
}
if let Some((reinforce, health)) = leader_rolls {
add_modifier(
m,
Attr::SpawnReinforcements,
"minecraft:leader_zombie_bonus",
reinforce,
Op::AddValue,
);
add_modifier(
m,
Attr::MaxHealth,
"minecraft:leader_zombie_bonus",
health,
Op::AddMultipliedTotal,
);
if !matches!(
reason,
Reason::Conversion | Reason::Load | Reason::DimensionTravel
) {
m.health = max_health(m);
}
m.extra.can_break_doors = true;
}
}
fn husk(&mut self, m: &mut Mob, g: Option<Group>, reason: Reason) -> Option<Group> {
let mut g = self.zombie(m, g, reason);
if reason != Reason::Conversion {
+37
View File
@@ -1210,6 +1210,9 @@ pub struct NearestTarget {
pub interval: i32,
/// Extra condition on the attacker, checked after the random interval.
pub when: Option<fn(&Mob, &MobWorld) -> bool>,
/// Mobs closer than this squared distance are not picked
/// (`GuardianAttackSelector`: `distanceToSqr > 9`).
pub beyond_sqr: Option<f64>,
/// A condition checked before anything else, by subclasses overriding
/// `canUse` (SpiderTargetGoal: only in the dark).
pub gate: Option<fn(&Mob, &MobWorld) -> bool>,
@@ -1242,6 +1245,7 @@ impl NearestTarget {
must_reach: false,
interval: reduced(10),
when: None,
beyond_sqr: None,
gate: None,
label: None,
found: None,
@@ -1274,6 +1278,10 @@ impl NearestTarget {
self.when = Some(f);
self
}
pub fn beyond(mut self, distance_sqr: f64) -> Self {
self.beyond_sqr = Some(distance_sqr);
self
}
pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self {
self.gate = Some(f);
self
@@ -1284,9 +1292,25 @@ impl NearestTarget {
self
}
}
/// `AbstractIllager.canAttack`: a baby `AbstractVillager` is never attacked.
fn illager_spares(attacker: Species, target: &Seen) -> bool {
matches!(
attacker,
Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner
) && target.baby
&& matches!(target.species, Species::Villager | Species::WanderingTrader)
}
/// TargetGoal.canContinueToUse
pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(who) = m.ai.target else { return false };
if let Who::Mob(id) = who
&& cx
.w
.seen(id)
.is_some_and(|s| illager_spares(m.species(), s))
{
return false;
}
let Some(t) = cx.w.target_info(who) else {
return false;
};
@@ -1345,10 +1369,12 @@ impl Goal for NearestTarget {
prey => {
let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z);
let id = m.id;
let attacker = m.species();
let candidates: Vec<(u32, Vec3)> =
cx.w.nearby(pos, range, move |s| {
s.id != id
&& !s.playing_dead
&& !illager_spares(attacker, s)
&& match prey {
Prey::Species(list) => list.contains(&s.species),
Prey::Filter(f) => f(s),
@@ -1361,6 +1387,9 @@ impl Goal for NearestTarget {
if m.distance_sqr(cpos) > range * range {
continue;
}
if self.beyond_sqr.is_some_and(|d| m.distance_sqr(cpos) <= d) {
continue;
}
if !m.sees(cx.w, Who::Mob(cid)) {
continue;
}
@@ -1762,6 +1791,10 @@ impl Goal for Breed {
if tamable && (!m.extra.tame || m.extra.sitting) {
return false;
}
// TurtleBreedGoal.canUse: not while carrying an egg.
if species == Species::Turtle && super::turtle::has_egg(m) {
return false;
}
let id = m.id;
// Horses and donkeys breed together (AbstractHorse.canParent: tame).
// Sniffer.canMate: calm states only.
@@ -1840,6 +1873,10 @@ impl Goal for Breed {
});
m.extra.in_love = 0;
m.extra.age = 6000;
// TurtleBreedGoal.breed: the mother carries an egg, not a baby.
if m.species() == Species::Turtle {
m.extra.flag = true;
}
cx.events.push(MobEvent::Breed {
parent: m.id,
partner: p.id,
+6 -3
View File
@@ -61,7 +61,8 @@ pub fn register(m: &mut Mob) {
NearestTarget::species(
&[Species::Squid, Species::GlowSquid, Species::Axolotl],
true,
),
)
.beyond(9.0),
);
}
/// `GuardianAttackGoal`.
@@ -120,9 +121,11 @@ impl Goal for GuardianAttack {
1.0,
));
} else if self.attack_time >= attack_duration(m) {
// Indirect magic (1, +2 for the elder; NORMAL difficulty), then
// Indirect magic (1, +2 on Hard, +2 for the elder), then
// doHurtTarget.
let magic = if is_elder(m) { 3.0 } else { 1.0 };
let magic = 1.0
+ if cx.w.difficulty.hard { 2.0 } else { 0.0 }
+ if is_elder(m) { 2.0 } else { 0.0 };
let from = [m.position.x, m.position.y, m.position.z];
match who {
Who::Player => cx.events.push(MobEvent::DamagePlayer {
@@ -177,6 +177,10 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
if m.swell >= 30 {
m.swell = 30;
let radius = if m.extra.charged { 6.0 } else { 3.0 };
events.push(MobEvent::ExplosionSource {
mob: m.id,
charged: m.extra.charged,
});
events.push(MobEvent::Explode(
[m.position.x, m.position.y, m.position.z],
radius,
+15 -4
View File
@@ -72,6 +72,8 @@ pub fn register_vindicator(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, avoid_creaking(1.0, 1.2));
g.add(2, super::doors::BreakDoor::vindicator());
g.add(3, super::doors::RaiderOpenDoor::default());
g.add(4, super::raider::HoldGroundAttack::new(10.0));
g.add(5, MeleeAttack::new(1.0, false));
g.add(8, Stroll::new(0.6));
@@ -86,6 +88,13 @@ pub fn register_vindicator(m: &mut Mob) {
.when(|m, _| m.custom_name.as_deref() == Some("Johnny")),
);
}
/// `Vindicator.customServerAiStep`: its navigation opens doors while a raid
/// is at its position.
pub fn vindicator_server_ai_step(m: &mut Mob) {
if super::doors::can_navigate_ground(m) {
m.ai.nav.can_open_doors = super::raider::state(m).is_some_and(|s| s.raided);
}
}
// Evoker state: `counter` spellCastingTickCount, `variant2` the spell
// being cast (0 none, 1 vexes, 2 fangs, 3 wololo), `counter2` the wololo
// sheep's id.
@@ -179,8 +188,8 @@ impl Goal for UseSpell {
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let age = i64::from(m.age);
if self.spell == Spell::Wololo {
// EvokerWololoSpellGoal.canUse: a blue sheep within 16 (4 up or
// down), no target, griefing on.
// EvokerWololoSpellGoal.canUse: a blue sheep within the box
// (16 sideways, 4 up or down) and `range(16)`, no target, griefing on.
if m.ai.target.is_some() || m.extra.counter > 0 || age < self.next || !cx.w.mob_griefing
{
return false;
@@ -196,6 +205,7 @@ impl Goal for UseSpell {
&& (s.position.x - p.x).abs() <= 16.0
&& (s.position.y - p.y).abs() <= 4.0
&& (s.position.z - p.z).abs() <= 16.0
&& s.position.distance_squared(p) <= 16.0 * 16.0
})
.map(|s| s.id)
.collect();
@@ -210,7 +220,8 @@ impl Goal for UseSpell {
return false;
}
if self.spell == Spell::Vexes {
// EvokerSummonSpellGoal: fewer vexes nearby than a roll of 1..8.
// EvokerSummonSpellGoal: fewer vexes within `range(16)` than a
// roll of 1..8.
let p = m.position;
let vexes =
cx.w.others
@@ -218,7 +229,7 @@ impl Goal for UseSpell {
.filter(|s| {
s.species == Species::Vex
&& s.alive
&& s.position.distance_squared(p) <= 16.0 * 16.0 * 3.0
&& s.position.distance_squared(p) <= 16.0 * 16.0
})
.count() as i32;
return m.random.next_int_bound(8).unwrap_or(0) + 1 > vexes;
+75
View File
@@ -15,6 +15,9 @@ use std::f32::consts::PI;
/// `PiglinAi.ADMIRE_DURATION`.
pub const ADMIRE: i32 = 119;
/// `PiglinAi.eat`: the `ATE_RECENTLY` memory lasts 200 ticks (kept in
/// `extra.ints[0]` of a piglin).
pub const ATE_RECENTLY: i32 = 200;
/// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's).
const CONVERSION: i32 = 300;
@@ -45,6 +48,7 @@ pub fn register_piglin(m: &mut Mob) {
g.add(3, super::illager::crossbow_goal(1.0, 8.0));
}
g.add(3, MeleeAttack::new(1.0, true));
g.add(4, PiglinAvoidRepellent);
g.add(4, GoToWantedItem);
g.add(5, Stroll::avoiding_water(0.6));
g.add(6, LookAtPlayer::new(8.0));
@@ -176,6 +180,54 @@ impl Goal for BabyPanic {
self.0.stop(m, cx)
}
}
/// `PiglinAi.avoidRepellent`: `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, false)`
/// of the idle activity. Closer than 8 blocks to a repellent and not walking
/// anywhere, walk away from it.
#[derive(Clone, Debug)]
struct PiglinAvoidRepellent;
impl Goal for PiglinAvoidRepellent {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(r) = m.extra.repellent else {
return false;
};
// The idle activity: not fighting or admiring, and no walk target yet.
if m.ai.target.is_some() || m.extra.using_item > 0 || !m.ai.nav.is_done() {
return false;
}
// Vec3.atBottomCenterOf.
let avoid = [
f64::from(r[0]) + 0.5,
f64::from(r[1]),
f64::from(r[2]) + 0.5,
];
if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 {
return false;
}
for _ in 0..10 {
if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) {
let at = [
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32,
];
m.ai.pending_path = m.create_path_to(cx.w, at, 0);
return m.ai.pending_path.is_some();
}
}
false
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
!m.ai.nav.is_done()
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
let path = m.ai.pending_path.take();
m.nav_move_to_path(path, 1.0);
}
}
/// Admiring a gold item held in the off hand: stand and look at it.
#[derive(Clone, Debug)]
struct Admire;
@@ -257,6 +309,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.ai.target = None;
}
}
if m.species() == Species::Piglin && m.extra.ints[0] > 0 {
m.extra.ints[0] -= 1;
}
// Admiring disabled after being hit by a player.
if m.extra.egg_time > 0 {
m.extra.egg_time -= 1;
@@ -299,6 +354,26 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
} else {
m.extra.counter2 = 0;
}
// PiglinSpecificSensor (every 20 ticks): the nearest repelling block.
if m.species() == Species::Piglin && m.alive() && m.age.wrapping_add(m.id).is_multiple_of(20) {
m.extra.repellent = find_piglin_repellent(m, w);
}
}
/// `PiglinSpecificSensor.findNearestRepellent`: the nearest `#piglin_repellents`
/// block within 8 blocks sideways and 4 up or down; a soul campfire only
/// counts while lit.
fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
let tag = w.block_tags.get("minecraft:piglin_repellents")?;
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
w.nearest_block(at, 8, 4, |p, name| {
tag.contains(name)
&& (name != "minecraft:soul_campfire"
|| w.prop(p[0], p[1], p[2], "lit") == Some("true"))
})
}
/// `HoglinBase.hurtAndThrowTarget`.
pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
+3
View File
@@ -30,6 +30,9 @@ pub struct State {
pub celebrating: bool,
/// The raid is active (`hasActiveRaid`); set by the game every tick.
pub active_raid: bool,
/// A raid is active within 96 blocks (`ServerLevel.isRaided`); set by
/// the game every tick for vindicators.
pub raided: bool,
/// The raid is won or lost (`Raid.isOver`), lost (`isLoss`).
pub raid_over: bool,
pub raid_loss: bool,
+54 -4
View File
@@ -3,7 +3,7 @@
//! their face is lost or when badly hurt, and shrugging off arrows while
//! closed.
use super::{
Damage, DamageKind, Mob, MobEvent, MobWorld, Who,
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{
Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround,
@@ -14,7 +14,7 @@ use crate::projectiles::{Projectile, ProjectileWorld, STEPS};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
random::{LegacyRandom, RandomSource},
};
use std::f32::consts::PI;
@@ -164,12 +164,62 @@ pub fn after_hurt(m: &mut Mob) {
m.extra.flag = true;
}
}
/// The deferred teleport of `after_hurt`.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
/// `Shulker.hurtServer` after a shulker bullet's damage: unless the
/// low-health teleport was drawn instead (`else if`), `hitByShulkerBullet`
/// runs on the next tick. Whether the shell is open is read here, at hurt
/// time, so a goal opening it before that tick cannot change the outcome.
pub fn hit_by_bullet(m: &mut Mob) {
if m.species() == Species::Shulker && !m.extra.flag && m.extra.counter != 0 {
m.extra.flag2 = true;
}
}
/// The deferred teleport of `after_hurt` and `hitByShulkerBullet`.
pub fn ai_step(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
if m.extra.flag {
m.extra.flag = false;
teleport(m, w, events);
}
if m.extra.flag2 {
m.extra.flag2 = false;
hit_by_shulker_bullet(m, w, level_random, events);
}
}
/// `Shulker.hitByShulkerBullet` (only queued by an open shulker): it
/// teleports, and leaves a new one of its colour behind unless shulkers
/// crowd the place (one in five fewer chances for every other shulker
/// within 8 blocks).
fn hit_by_shulker_bullet(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
let old_position = m.position;
let old_box = m.bounds();
if !teleport(m, w, events) {
return;
}
let area = old_box.inflate(Vec3::new(8.0, 8.0, 8.0));
// The shulker itself stands within reach of its old box, so it counts.
let others = w
.others_near(area)
.filter(|s| {
s.alive && s.species == Species::Shulker && s.id != m.id && s.bounds.intersects(area)
})
.count();
let failure_chance = others as f32 / 5.0;
// The level's random, not the shulker's.
if level_random.next_float() < failure_chance {
return;
}
let mut baby = Mob::new(0, m.kind.clone(), old_position, 0.0);
baby.extra.color = m.extra.color;
events.push(MobEvent::Spawn(Box::new(baby)));
}
/// A ProjectileWorld over the mob world, for aiming a new bullet.
struct Probe<'a, 'w> {
@@ -94,6 +94,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
if current == DIGGING && now(m) == m.extra.ints[3] {
let h = head_block(m);
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/sniffer_digging",
at: [f64::from(h[0]), f64::from(h[1]), f64::from(h[2])],
});
@@ -35,6 +35,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b
#[derive(Clone, Copy, Debug)]
pub struct LocalDifficulty {
pub effective: f32,
/// The world difficulty is normal.
pub normal: bool,
/// The world difficulty is hard.
pub hard: bool,
}
@@ -45,9 +47,11 @@ impl LocalDifficulty {
/// the overworld clock, the chunk's inhabited time and the moon.
pub fn new(base: u8, total: i64, inhabited: i64, moon: f32) -> Self {
let hard = base == 3;
let normal = base == 2;
if base == 0 {
return Self {
effective: 0.0,
normal,
hard,
};
}
@@ -60,6 +64,7 @@ impl LocalDifficulty {
}
Self {
effective: f32::from(base) * (0.75 + global + local),
normal,
hard,
}
}
@@ -148,6 +153,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
S::Mooshroom => m.extra.variant = 0,
// Turtle.finalizeSpawn: home is where it spawned.
S::Turtle => {
m.extra.home = Some([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
])
}
S::Frog => m.extra.variant = biome.frog,
S::Wolf => m.extra.variant = biome.wolf,
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
@@ -158,6 +171,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
if m.random.next_float() < 0.05 {
m.extra.age = i32::MIN / 2;
}
// setCanBreakDoors(nextFloat() < special * 0.1), before the gear.
let can_break_doors = m.random.next_float() < difficulty.special() * 0.1;
super::doors::set_can_break_doors(m, can_break_doors);
if m.species() != S::Drowned {
populate_armor(m, difficulty);
}
@@ -191,6 +207,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
// ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword, or
// one time in 20 a golden spear.
S::ZombifiedPiglin => {
// Zombie.finalizeSpawn's setCanBreakDoors.
let can_break_doors = m.random.next_float() < difficulty.special() * 0.1;
super::doors::set_can_break_doors(m, can_break_doors);
let spear = m.random.next_int_bound(20).unwrap_or(1) == 0;
m.extra.main_hand = Some(
if spear {
@@ -264,6 +283,18 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Slime | S::MagmaCube => super::cube::finalize(m),
_ => {}
}
// Zombie.finalizeSpawn ends with handleAttributes: the reinforcement
// chance (and a leader's bonus) that `Zombie.hurtServer` reads.
if matches!(
m.species(),
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin
) {
super::finalize::zombie_attributes(
m,
difficulty.special(),
super::finalize::Reason::Natural,
);
}
}
/// VillagerType.byBiome
pub fn villager_type(b: &BiomeFacts) -> u8 {
+209
View File
@@ -0,0 +1,209 @@
//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her
//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand
//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`,
//! `extra.counter` `layEggCounter` and `extra.home` `homePos`.
use super::{
Mob, MobEvent, MobWorld,
goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced},
};
use horizon_core::random::RandomSource;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(1, Breed::new(1.0));
g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1)));
g.add(4, GoHome::default());
}
/// `Turtle.hasEgg`.
pub fn has_egg(m: &Mob) -> bool {
m.extra.flag
}
/// `Turtle.setLayingEgg`.
fn set_laying_egg(m: &mut Mob, on: bool) {
m.extra.counter = i32::from(on);
m.extra.flag2 = on;
}
/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and
/// loading all set a home; one made any other way is at home where it stands.
fn close_to_home(m: &Mob, distance: f64) -> bool {
let home = m.extra.home.unwrap_or([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]);
let d = [
f64::from(home[0]) + 0.5 - m.position.x,
f64::from(home[1]) + 0.5 - m.position.y,
f64::from(home[2]) + 0.5 - m.position.z,
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance
}
fn block_of(m: &Mob) -> [i32; 3] {
[
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]
}
/// `TurtleEggBlock.isSand`.
fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool {
w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2]))
}
/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 {
let at = block_of(m);
let below = [at[0], at[1] - 1, at[2]];
if is_sand(w, below) {
events.push(MobEvent::BlockBreakEffect {
pos: at,
block: below,
});
}
}
}
/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home
/// walks to sand with air above, digs for 200 ticks and lays it.
#[derive(Clone, Debug)]
struct LayEgg(MoveToBlock);
impl LayEgg {
/// `isValidTarget`: sand with air above it.
fn valid(w: &MobWorld, p: [i32; 3]) -> bool {
w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p)
}
}
impl Goal for LayEgg {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn name(&self) -> &'static str {
"TurtleLayEggGoal"
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !(has_egg(m) && close_to_home(m, 9.0)) {
return false;
}
// MoveToBlockGoal.canUse.
if self.0.next_start > 0 {
self.0.next_start -= 1;
return false;
}
self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
self.0.find_nearest(m, cx.w, Self::valid)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.start(m, cx.w);
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.tick(m, cx.w);
if m.fluids.in_water || !self.0.reached {
return;
}
if m.extra.counter < 1 {
set_laying_egg(m, true);
} else if m.extra.counter > 200 {
let at = [m.position.x, m.position.y, m.position.z];
let pitch = 0.9 + m.random.next_float() * 0.2;
cx.events
.push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch));
// Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand.
let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1;
let registry = cx.w.registry;
let state = registry
.default_state("minecraft:turtle_egg")
.and_then(|d| registry.state(d).cloned())
.and_then(|mut s| {
s.properties.insert("eggs".into(), eggs.to_string());
registry.resolve(&s).ok()
});
let b = self.0.block;
if let Some(state) = state {
cx.events.push(MobEvent::SetBlock {
pos: [b[0], b[1] + 1, b[2]],
state,
});
}
m.extra.flag = false;
set_laying_egg(m, false);
m.extra.in_love = 600;
}
if m.extra.flag2 {
m.extra.counter += 1;
}
}
}
/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult
/// that strayed 64 blocks away does now and then.
#[derive(Clone, Debug, Default)]
struct GoHome {
stuck: bool,
close_to_home_try_ticks: i32,
}
impl Goal for GoHome {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn name(&self) -> &'static str {
"TurtleGoHomeGoal"
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
if m.is_baby() {
false
} else if has_egg(m) {
true
} else {
m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0)
}
}
fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) {
self.stuck = false;
self.close_to_home_try_ticks = 0;
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
!close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let home = m.extra.home.unwrap_or(block_of(m));
let close = close_to_home(m, 16.0);
if close {
self.close_to_home_try_ticks += 1;
}
if !m.ai.nav.is_done() {
return;
}
let to = [
f64::from(home[0]) + 0.5,
f64::from(home[1]),
f64::from(home[2]) + 0.5,
];
let mut next = m
.default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0)
.or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2));
if let Some(at) = next
&& !close
&& cx.w.block_name(
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
) != "minecraft:water"
{
next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2);
}
match next {
Some(at) => {
m.nav_move_to(cx.w, at, 1.0);
}
None => self.stuck = true,
}
}
}
+41 -7
View File
@@ -1,7 +1,8 @@
//! Zombies (zombie, husk, drowned, zombie villager) and skeletons (skeleton,
//! stray, bogged, wither skeleton): goals, bow attacks, water conversion.
use super::{
Mob, MobEvent, Species, Who,
Damage, Mob, MobEvent, Species, Who,
doors::BreakDoor,
goals::{
Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack,
NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone,
@@ -10,11 +11,22 @@ use super::{
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, random::RandomSource};
/// `Zombie.hurtServer`, once the hit landed: a zombie with a target (its own,
/// else a living attacker) asks the game to try calling a reinforcement; the
/// difficulty, chance and spawn tests are the game's (`call_reinforcements`).
pub fn after_hurt(m: &mut Mob, source: &Damage) {
if let Some(target) = m.ai.target.or(source.attacker) {
m.outbox
.push(MobEvent::Reinforcements { mob: m.id, target });
}
}
pub fn register(m: &mut Mob) {
use Species as S;
match m.species() {
S::Zombie | S::Husk | S::ZombieVillager => {
let g = &mut m.ai.goals;
g.add(1, BreakDoor::zombie());
g.add(4, AttackTurtleEgg::default());
g.add(8, LookAtPlayer::new(8.0));
g.add(8, RandomLookAround::default());
@@ -42,6 +54,7 @@ pub fn register(m: &mut Mob) {
S::ZombifiedPiglin => {
// ZombifiedPiglin.addBehaviourGoals: neutral until provoked.
let g = &mut m.ai.goals;
g.add(1, BreakDoor::zombie());
g.add(8, LookAtPlayer::new(8.0));
g.add(8, RandomLookAround::default());
g.add(2, MeleeAttack::new(1.0, false).zombie());
@@ -58,6 +71,7 @@ pub fn register(m: &mut Mob) {
S::Drowned => {
// Zombie.registerGoals, then Drowned.addBehaviourGoals.
let g = &mut m.ai.goals;
g.add(1, BreakDoor::zombie());
g.add(4, AttackTurtleEgg::default());
g.add(8, LookAtPlayer::new(8.0));
g.add(8, RandomLookAround::default());
@@ -136,12 +150,13 @@ pub fn register(m: &mut Mob) {
}
// The AbstractSkeleton constructor's reassessWeaponGoal, after
// registerGoals; the weapon itself comes with finalizeSpawn.
let interval = if matches!(species, S::Bogged | S::Parched) {
70
// getHardAttackInterval / getAttackInterval.
let (hard, normal) = if matches!(species, S::Bogged | S::Parched) {
(50, 70)
} else {
40
(20, 40)
};
m.ai.goals.add(4, SkeletonWeapon::new(interval));
m.ai.goals.add(4, SkeletonWeapon::new(hard, normal));
}
_ => {}
}
@@ -524,13 +539,20 @@ pub struct SkeletonWeapon {
bow: BowAttack,
melee: MeleeAttack,
use_bow: bool,
/// The weapon the goal was last reassessed for.
assessed: Option<bool>,
hard_interval: i32,
normal_interval: i32,
}
impl SkeletonWeapon {
pub fn new(bow_interval: i32) -> Self {
pub fn new(hard_interval: i32, normal_interval: i32) -> Self {
Self {
bow: BowAttack::new(1.0, bow_interval, 15.0),
bow: BowAttack::new(1.0, normal_interval, 15.0),
melee: MeleeAttack::new(1.2, false),
use_bow: false,
assessed: None,
hard_interval,
normal_interval,
}
}
}
@@ -556,6 +578,18 @@ impl Goal for SkeletonWeapon {
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
// The goal registered for the weapon in hand.
self.use_bow = holding_bow(m);
// reassessWeaponGoal: a bow gets the hard interval only on Hard; it
// is picked again when the weapon changes (the first check after
// spawning or loading stands for finalizeSpawn and
// readAdditionalSaveData).
if self.assessed != Some(self.use_bow) {
self.assessed = Some(self.use_bow);
self.bow.interval_min = if cx.w.difficulty.hard {
self.hard_interval
} else {
self.normal_interval
};
}
if self.use_bow {
self.bow.can_use(m, cx)
} else {
+2 -1
View File
@@ -29,6 +29,7 @@ pub fn register(m: &mut Mob) {
g.add(8, RandomMove);
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
g.add(10, LookAtPlayer::mobs(8.0));
// `HurtByTargetGoal(this, Raider.class)`: raiders are ignored, vexes are not.
let mut hurt = HurtByTarget::new().alert();
hurt.ignore = vec![
Species::Pillager,
@@ -36,7 +37,7 @@ pub fn register(m: &mut Mob) {
Species::Evoker,
Species::Illusioner,
Species::Witch,
Species::Vex,
Species::Ravager,
];
m.ai.targets.add(1, hurt);
m.ai.targets.add(2, CopyOwnerTarget);
+18 -24
View File
@@ -448,6 +448,24 @@ impl Ext {
}
(stack.count > 0).then_some(stack)
}
/// `SimpleContainer.removeItemType`: take up to `count` of the item from
/// the first stacks that hold it.
pub fn remove_item(&mut self, item: &str, mut count: u32) {
let mut slot = 0;
while slot < self.inventory.len() && count > 0 {
let s = &mut self.inventory[slot];
if &*s.item == item {
let n = s.count.min(count);
s.count -= n;
count -= n;
if s.count == 0 {
self.inventory.remove(slot);
continue;
}
}
slot += 1;
}
}
pub fn count_item(&self, item: &str) -> u32 {
self.inventory
.iter()
@@ -754,30 +772,6 @@ pub fn finalize_summoned_golem(m: &mut Mob, random: &mut impl RandomSource) {
}
m.extra.left_handed = random.next_float() < 0.05;
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed`
/// (`free_head`: a bed head that is not occupied).
pub fn take_vacant_bed(
claimed: &[[i32; 3]],
from: [i32; 3],
mut free_head: impl FnMut(i32, i32, i32) -> bool,
) -> Option<[i32; 3]> {
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if d <= 48 * 48
&& best.is_none_or(|(b, _)| d < b)
&& free_head(x, y, z)
&& !claimed.contains(&[x, y, z])
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
/// `Villager.canBreed`: enough food, awake and an adult.
pub fn can_breed(m: &Mob) -> bool {
m.species() == Species::Villager
@@ -1242,6 +1242,8 @@ enum B {
WorkAtPoi {
t: Timed,
last_check: i64,
/// `WorkAtComposter` (a farmer's package) rather than `WorkAtPoi`.
composter: bool,
},
StrollAroundPoi {
running: bool,
@@ -1635,7 +1637,11 @@ impl B {
*birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
true
}
B::WorkAtPoi { t, last_check } => {
B::WorkAtPoi {
t,
last_check,
composter,
} => {
let mm = mem(m);
let Some(site) = mm.job_site.value() else {
return false;
@@ -1656,6 +1662,13 @@ impl B {
mm.last_worked_at_poi.set(now);
mm.look_target.set(Tracker::Block(site));
play_work_sound(m, cx);
// WorkAtComposter.useWorkstation, before the restock.
if *composter {
cx.events.push(MobEvent::WorkAtComposter {
mob: m.id,
pos: site,
});
}
restock_if_due(m, cx.w);
true
}
@@ -3396,8 +3409,10 @@ fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool {
&& super::villager::can_breed(m)
&& w.seen(id).is_some_and(|s| s.in_love)
}
/// `VillagerMakeLove.takeVacantBed`: a bed head no villager has claimed.
fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
/// `VillagerMakeLove.takeVacantBed`: `PoiManager.take(HOME, ..., 48)` over a
/// sphere of 48 blocks, the nearest bed head no villager has claimed that the
/// villager can walk to (`canReach`: a path that gets there).
fn take_bed_for_child(m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = w
.others
.iter()
@@ -3405,10 +3420,20 @@ fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
.filter_map(|s| s.bed)
.chain(m.extra.bed)
.collect();
let p = m.position;
let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
super::villager::take_vacant_bed(&claimed, from, |x, y, z| {
w.prop(x, y, z, "part") == Some("head") && w.prop(x, y, z, "occupied") != Some("true")
let from = block_of(m.position);
let mut beds: Vec<[i32; 3]> = homes_in_range(m, w, 48)
.into_iter()
.filter(|p| {
w.prop(p[0], p[1], p[2], "part") == Some("head")
&& w.prop(p[0], p[1], p[2], "occupied") != Some("true")
&& !claimed.contains(p)
})
.collect();
// Nearest first; equally near beds stay in scan order.
beds.sort_by_key(|p| dist_sqr(*p, from));
beds.into_iter().find(|&p| {
m.create_path_to(w, p, Poi::Home.valid_range())
.is_some_and(|path| path.reached)
})
}
/// `BehaviorUtils.lockGazeAndWalkToEachOther`: this villager's half, and
@@ -3775,6 +3800,7 @@ fn packages(baby: bool, seed: i64, farmer: bool) -> Vec<Entry> {
B::WorkAtPoi {
t: timed(60, 60),
last_check: 0,
composter: farmer,
},
7,
),
+17 -3
View File
@@ -193,6 +193,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
}
Who::Player => false,
};
// `target.hasEffect`: a target that already has the effect gets the next one.
let has = |effect: &str| match who {
Who::Player => cx.w.player.as_ref().is_some_and(|p| p.has_effect(effect)),
Who::Mob(id) => cx.w.seen(id).is_some_and(|s| s.has_effect(effect)),
};
let (effect, ticks, amplifier) = if heals {
m.ai.target = None;
if health <= 4.0 {
@@ -200,11 +205,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
} else {
("minecraft:regeneration", 900, 0)
}
} else if dist >= 8.0 {
} else if dist >= 8.0 && !has("slowness") {
("minecraft:slowness", 1800, 0)
} else if health >= 8.0 {
} else if health >= 8.0 && !has("poison") {
("minecraft:poison", 900, 0)
} else if dist <= 3.0 && m.random.next_float() < 0.25 {
} else if dist <= 3.0 && !has("weakness") && m.random.next_float() < 0.25 {
("minecraft:weakness", 1800, 0)
} else {
("minecraft:instant_damage", 1, 0)
@@ -236,6 +241,15 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
pitch,
));
}
/// The movement speed of a witch with `SPEED_MODIFIER_DRINKING` (-0.25,
/// `ADD_VALUE`) while it drinks: it stands still for the 32 ticks.
pub fn speed(m: &Mob, base: f64) -> f64 {
if m.species() == Species::Witch && m.extra.flag {
(base - 0.25).max(0.0)
} else {
base
}
}
/// Witch.aiStep before `super.aiStep()`: the healing cooldown, then drink
/// water breathing, fire resistance, healing or swiftness.
pub fn ai_step(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
+79 -6
View File
@@ -50,6 +50,8 @@ pub struct MotionResources {
pub attributes: Arc<Catalog>,
pub blocks: BoundMovementProperties,
pub climbable: BTreeSet<String>,
/// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes.
pub glide_through: BTreeSet<String>,
pub fall_reset: BTreeSet<String>,
pub landing: BlockLandingRegistry,
pub health: crate::health::HealthResources,
@@ -108,6 +110,7 @@ impl MotionResources {
suppresses_bounce: tag("minecraft:suppresses_bounce")?,
})?,
climbable: tag("minecraft:climbable")?,
glide_through: tag("minecraft:can_glide_through")?,
fall_reset: tag("minecraft:fall_damage_resetting")?,
})
}
@@ -308,6 +311,9 @@ pub struct PlayerMotion {
/// it travels on the server: `isLocalInstanceAuthoritative` is false, so
/// its moves check no fall damage.
pub server_copy: bool,
/// The span of `events` a wall hit on the server's copy pushed (sound and
/// damage): `server_travel` keeps them while it drops the simulated moves.
pub wall_hit_events: Option<std::ops::Range<usize>>,
/// A client's copy of its own player (`Level.isClientSide`): only the
/// server hurts it (`Entity.hurt` does nothing on a client) and ticks its
/// food (`ServerPlayer.tick`). Its hurt animation comes from the server.
@@ -477,6 +483,7 @@ impl PlayerMotion {
freeze_immune: false,
old_position: position,
server_copy: false,
wall_hit_events: None,
client_side: false,
block_effects: true,
powder_snow_entered: Vec::new(),
@@ -765,6 +772,10 @@ impl MotionWorld<'_, '_, '_> {
.state(self.block(p))
.ok_or("missing scene state")?
.name;
// A gliding player passes through vines (`CAN_GLIDE_THROUGH`).
if self.player.fall_flying && self.resources.glide_through.contains(name) {
return Ok(false);
}
let climbable = self.resources.climbable.contains(name);
if climbable {
self.player.last_climbable = Some(p);
@@ -834,9 +845,17 @@ impl MotionWorld<'_, '_, '_> {
let can_glide = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& self.player.status.levitation.is_none()
&& !self.player.fluids.was_touching_water
&& !self.player.is_in_lava();
if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide {
// LocalPlayer.aiStep: `!onClimbable()` before tryToStartFallFlying.
if jumping
&& !toggled
&& !was_jumping
&& !self.climbable()?
&& !self.player.fall_flying
&& can_glide
{
self.player.fall_flying = true;
}
// LivingEntity.tick fallFlyTicks, then updateFallFlying.
@@ -848,8 +867,11 @@ impl MotionWorld<'_, '_, '_> {
self.player.fall_distance = 1.0;
}
self.player.fall_fly_ticks += 1;
// canGlide alone: water and lava don't end a glide.
let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying;
// canGlide alone: water and lava don't end a glide, levitation does.
let still = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& self.player.status.levitation.is_none();
if !still {
self.player.glide_ending = true;
} else if (self.player.fall_fly_ticks + 1) % 10 == 0
@@ -1021,7 +1043,14 @@ impl MotionWorld<'_, '_, '_> {
{
horizon_world::living_fluid::travel_in_fluid(self, input)?;
} else if self.player.fall_flying {
self.travel_fall_flying()?;
// LivingEntity.travelFallFlying: on a climbable the glide ends and
// the player moves like in the air.
if self.climbable()? {
self.travel_in_air(input)?;
self.player.fall_flying = false;
} else {
self.travel_fall_flying()?;
}
} else {
self.travel_in_air(input)?;
}
@@ -1048,7 +1077,14 @@ impl MotionWorld<'_, '_, '_> {
p.server_copy = false;
(p.position, p.ground, p.collision) = (position, ground, collision);
(p.history, p.fall_distance, p.steps) = (history, fall_distance, steps);
// The wall hit is the server's own: its sound and damage events stay.
let kept: Vec<_> = p
.wall_hit_events
.take()
.map(|span| p.events.drain(span).collect())
.unwrap_or_default();
p.events.truncate(events);
p.events.extend(kept);
travelled
}
/// `LivingEntity.checkAutoSpinAttack`: the first living entity in the
@@ -1536,7 +1572,7 @@ impl MotionWorld<'_, '_, '_> {
let lean = pitch;
let look_h = (look.x * look.x + look.z * look.z).sqrt();
let move_h = (v.x * v.x + v.z * v.z).sqrt();
let gravity = 0.08;
let gravity = living_motion::effective_gravity(self)?;
let lift = f64::from(lean.cos()).powi(2);
let mut m = Vec3::new(v.x, v.y + gravity * (-1.0 + lift * 0.75), v.z);
if m.y < 0.0 && look_h > 0.0 {
@@ -1564,7 +1600,44 @@ impl MotionWorld<'_, '_, '_> {
}
self.player.velocity = Vec3::new(m.x * 0.99, m.y * 0.98, m.z * 0.99);
let movement = self.player.velocity;
self.move_self(movement)
self.move_self(movement)?;
// LivingEntity.handleFallFlyingCollisions: only the server hurts.
if !self.player.client_side && self.player.collision.horizontal {
let new_h = {
let v = self.player.velocity;
(v.x * v.x + v.z * v.z).sqrt()
};
let dmg = ((move_h - new_h) * 10.0 - 3.0) as f32;
if dmg > 0.0 {
let first = self.player.events.len();
// getFallDamageSound((int) dmg)
let sound = if dmg as i32 > 4 {
crate::landing::SceneSound::BigFall
} else {
crate::landing::SceneSound::SmallFall
};
self.player
.events
.push(MotionEvent::Fall(crate::landing::FallEvent::Sound {
sound,
position: None,
volume: 1.0,
pitch: 1.0,
}));
let id = self
.resources
.health
.damage
.id("minecraft:fly_into_wall")
.ok_or("missing fly_into_wall damage type")?;
let rules = self.scene.health_rules;
self.player.hurt(&self.resources.health, rules, id, dmg)?;
if self.player.server_copy {
self.player.wall_hit_events = Some(first..self.player.events.len());
}
}
}
Ok(())
}
/// `LocalPlayer.move`: the move, then `updateAutoJump` with the float
/// horizontal displacement.
@@ -161,6 +161,29 @@ pub(crate) fn fire_contact(
}
damage
}
/// `CactusBlock.entityInside`: the box (deflated by `1.0E-5`, as in
/// `Entity.checkInsideBlocks`) touches a cactus; its inside shape is the
/// whole block.
pub(crate) fn cactus_contact(
world: &World,
registry: &horizon_world::registry::BlockRegistry,
bounds: Aabb,
) -> bool {
let b = bounds.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 {
if registry
.state(world.block(x, y, z))
.is_some_and(|s| s.name == "minecraft:cactus")
{
return true;
}
}
}
}
false
}
impl LivingFluidWorld for MotionWorld<'_, '_, '_> {
fn in_water(&mut self) -> Result<bool> {
Ok(self.player.fluids.was_touching_water)
+6 -5
View File
@@ -186,12 +186,13 @@ impl Projectile {
self
}
/// The shooter's bow enchantments; Flame spawns the arrow burning for 100
/// seconds (`projectile_spawned` ignite).
/// seconds (`projectile_spawned` ignite), Piercing sets its pierce level.
pub fn set_bonus(&mut self, bonus: crate::mobs::gear::ArrowBonus) {
if bonus.flame
&& let Some(a) = self.arrow.as_mut()
{
a.ignite_for_seconds(100.0);
if let Some(a) = self.arrow.as_mut() {
if bonus.flame {
a.ignite_for_seconds(100.0);
}
a.pierce = bonus.pierce.min(127) as u8;
}
self.bonus = bonus;
}
+3 -1
View File
@@ -648,6 +648,7 @@ pub fn encode_block_entity(
BlockEntity::Vault(v) => entries.extend(v.save()),
BlockEntity::Beehive(h) => entries.extend(h.to_nbt()),
BlockEntity::CommandBlock(c) => entries.extend(c.save()),
BlockEntity::DaylightDetector => {}
}
Tag::compound(entries)
}
@@ -845,7 +846,8 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_)
| BlockEntity::Skull(_) => {}
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector => {}
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag),
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag),
+113 -9
View File
@@ -175,6 +175,11 @@ pub enum Done {
}
struct Queued {
priority: i64,
/// The column the job is for and what it adds to the column's distance
/// (`Streaming::submit`): the priority is computed again from them when
/// the centre moves (`Streaming::requeue`). None for saves, which go first.
at: Option<(i32, i32)>,
bias: i64,
order: u64,
job: Job,
}
@@ -222,6 +227,9 @@ pub struct Streaming {
/// radius it was last ranked for.
decoration_order: DecorationOrder,
order_area: Option<((i32, i32), i32)>,
/// What the queued jobs' priorities were computed from (`requeue`): the
/// centre, the loading screen, the band, and the extra areas.
queue_basis: (((i32, i32), bool, Option<Band>), Vec<((i32, i32), i32)>),
finishing: FxHashSet<(i32, i32)>,
decorates: bool,
lighting: FxHashMap<(i32, i32), u64>,
@@ -544,6 +552,7 @@ impl Streaming {
saving: 0,
decoration_order: DecorationOrder::default(),
order_area: None,
queue_basis: Default::default(),
finishing: Default::default(),
decorates: generator.decorates(),
lighting: Default::default(),
@@ -648,15 +657,39 @@ impl Streaming {
world.dirty_sections.take_column(x, z);
world.chunks.remove(&(x, z))
}
fn submit(&mut self, priority: i64, job: Job) {
/// Queue a job for the column `at`, nearest first: its distance (`distance`)
/// times four plus `bias`, which orders a column's jobs. A job without a
/// column (a save) goes ahead of every other.
fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) {
self.order += 1;
let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias);
self.shared.queue.lock().unwrap().push(Queued {
priority,
at,
bias,
order: self.order,
job,
});
self.shared.ready.notify_one();
}
/// Rank the queued jobs again when what their priorities were computed
/// from changed: the centre, the extra areas, the band, or the loading
/// screen (ring order, `Ranges::rings`, whose values are far above the
/// distances used after it). Vanilla's chunk task queue follows the
/// current ticket levels in the same way. Without it, generation queued
/// while the loading screen was up waited behind every job queued after
/// it, and with it the decoration of the chunks around the player: at
/// render distance 32 nothing was decorated until every proto chunk had
/// been generated.
fn requeue(&mut self) {
let basis = (self.center, self.loading, self.band);
if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra {
return;
}
self.queue_basis = (basis, self.extra.clone());
let mut queue = self.shared.queue.lock().unwrap();
rank_again(&mut queue, |x, z| self.distance(x, z));
}
fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) {
self.generation_scan.exhausted = false;
self.decorating -= 1;
@@ -686,7 +719,7 @@ impl Streaming {
self.saving += 1;
// Ahead of every other job: a column generated again meanwhile
// would not find them saved.
self.submit(i64::MIN, Job::Save(protos));
self.submit(None, 0, Job::Save(protos));
}
}
fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) {
@@ -829,6 +862,7 @@ impl Streaming {
return (uploads, Vec::new());
}
ExtraCover::refresh(&mut self.cover, &self.extra);
self.requeue();
self.relight_edits(world);
let deferred = std::mem::take(&mut self.deferred);
let received = std::iter::from_fn(|| self.results.try_recv().ok());
@@ -984,7 +1018,7 @@ impl Streaming {
.expect("present proto");
self.finishing.insert((x, z));
self.written.remove(&(x, z));
self.submit(self.distance(x, z) * 4, Job::Finish(proto));
self.submit(Some((x, z)), 0, Job::Finish(proto));
}
}
// Decorate chunks whose 3x3 proto neighbourhood is available, in
@@ -1052,7 +1086,7 @@ impl Streaming {
w.0 = self.decoration_order.rank_or_append(w.2, w.3);
}
wanted.sort_unstable();
for (_, d, x, z) in wanted {
for (_, _, x, z) in wanted {
if self.decorating >= workers * 2 {
break;
}
@@ -1091,7 +1125,7 @@ impl Streaming {
Err(_) => continue,
};
self.decorating += 1;
self.submit(d * 4 + 1, Job::Decorate(x, z, region));
self.submit(Some((x, z)), 1, Job::Decorate(x, z, region));
}
}
self.schedule_generation(world, workers);
@@ -1111,7 +1145,8 @@ impl Streaming {
self.light_snapshots
.insert((x, z), self.light_edit_sequence);
self.submit(
self.distance(x, z) * 4 + 1,
Some((x, z)),
1,
Job::Light(x, z, region, self.sequence, self.sky_light),
);
}
@@ -1183,7 +1218,8 @@ impl Streaming {
self.sequence += 1;
self.meshing.insert((x, sy, z), self.sequence);
self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 },
Some((x, z)),
if first { 2 } else { 0 },
Job::Mesh(
x,
sy,
@@ -1222,9 +1258,9 @@ impl Streaming {
loading: self.loading,
};
if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) {
for (d, x, z) in wanted {
for (_, x, z) in wanted {
self.generating.insert((x, z));
self.submit(d * 4, Job::Generate(x, z));
self.submit(Some((x, z)), 0, Job::Generate(x, z));
}
}
}
@@ -1738,10 +1774,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> {
})
})
}
/// The queued jobs' priorities computed again from each one's column
/// `distance` (`Streaming::submit`).
fn rank_again(queue: &mut BinaryHeap<Queued>, distance: impl Fn(i32, i32) -> i64) {
if queue.is_empty() {
return;
}
let mut jobs = std::mem::take(queue).into_vec();
for job in &mut jobs {
if let Some((x, z)) = job.at {
job.priority = distance(x, z) * 4 + job.bias;
}
}
*queue = BinaryHeap::from(jobs);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queued_jobs_follow_the_centre_and_the_loading_screen() {
let forced = HashSet::new();
let ranges = |center| Ranges {
center,
radius: 32,
extra: &[],
forced: &forced,
cover: None,
band: None,
};
let generate = |x, z, priority, order| Queued {
priority,
at: Some((x, z)),
bias: 0,
order,
job: Job::Generate(x, z),
};
let loading = ranges((0, 0));
let queued = || {
BinaryHeap::from(vec![
// Queued while the loading screen was up: ring order.
generate(3, 1, loading.priority(3, 1, true) * 4, 1),
// Queued after it closed: plain distances, far below any ring past the first.
generate(20, 0, loading.priority(20, 0, false) * 4, 2),
Queued {
priority: i64::MIN,
at: None,
bias: 0,
order: 3,
job: Job::Save(Vec::new()),
},
])
};
let pops = |mut queue: BinaryHeap<Queued>| {
std::iter::from_fn(move || queue.pop())
.map(|q| q.at)
.collect::<Vec<_>>()
};
assert_eq!(
pops(queued()),
[None, Some((20, 0)), Some((3, 1))],
"the stale order"
);
let mut queue = queued();
rank_again(&mut queue, |x, z| loading.priority(x, z, false));
assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]);
// The player moved: the job near the new centre goes first.
let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]);
let moved = ranges((19, 0));
rank_again(&mut queue, |x, z| moved.priority(x, z, false));
assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0)));
}
#[test]
fn view_distance_is_vanillas_shape() {
// ChunkTrackingView.isInViewDistance at render distance 12: a column
@@ -0,0 +1,16 @@
[package]
name = "beacons"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish = false
description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on"
[lib]
crate-type = ["cdylib"]
[dependencies]
horizon-mod-sdk = { path = "../.." }
[lints]
workspace = true
@@ -0,0 +1,8 @@
id = "beacons"
name = "Beacons"
version = "0.1.0"
description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome."
authors = ["Horizon"]
api = "0.3"
side = "server"
capabilities = ["players", "world"]
@@ -0,0 +1,87 @@
//! Example Horizon server mod (`docs/mods.md`, "Server mods") with
//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east
//! of the player, `/ground` reads the block under their feet and the biome.
use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world};
/// How tall `/beacon` builds.
const HEIGHT: i32 = 4;
struct Beacons;
/// The block the player stands in: their feet, floored.
fn feet(player: &Player) -> (i32, i32, i32) {
(
player.x.floor() as i32,
player.y.floor() as i32,
player.z.floor() as i32,
)
}
/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up.
fn pillar(player: &Player) -> Vec<BlockChange> {
let (x, y, z) = feet(player);
(0..HEIGHT)
.map(|dy| BlockChange {
x: x + 2,
y: y + dy,
z,
state: "minecraft:glowstone".into(),
})
.collect()
}
impl ServerMod for Beacons {
fn init() -> Result<(Self, Registration), String> {
Ok((
Beacons,
Registration::new().command("beacon").command("ground"),
))
}
fn command(
&mut self,
player: &Player,
name: &str,
_args: &str,
) -> Result<Option<String>, String> {
let (x, y, z) = feet(player);
if name == "beacon" {
world::set_blocks(&player.dimension, &pillar(player))?;
players::broadcast(&format!(
"{} lit a beacon at {} {y} {z}",
player.name,
x + 2
));
return Ok(None);
}
let below = world::get_block(&player.dimension, x, y - 1, z)
.ok_or("The ground under you isn't loaded")?;
let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default();
Ok(Some(format!("You are standing on {below} in {biome}")))
}
}
horizon_mod_sdk::export_server_mod!(Beacons);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pillar_stands_two_blocks_east() {
let p = Player {
id: String::new(),
name: "Alex".into(),
x: -0.5,
y: 64.0,
z: 3.2,
dimension: "minecraft:overworld".into(),
game_mode: horizon_mod_sdk::server::GameMode::Survival,
health: 20.0,
};
let blocks = pillar(&p);
assert_eq!(blocks.len(), HEIGHT as usize);
assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3));
assert_eq!(blocks[3].y, 67);
}
}
@@ -0,0 +1,22 @@
# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east.
[[step]]
join = "Alex"
blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }]
command = "ground"
expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains"
[[step]]
command = "beacon"
expect.broadcast = ["Alex lit a beacon at 2 64 0"]
expect.blocks = [
{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" },
{ x = 2, y = 67, z = 0, state = "minecraft:glowstone" },
{ x = 2, y = 68, z = 0, state = "minecraft:air" },
]
# Anywhere the script set nothing is air.
[[step]]
player = { x = 10.5, z = 10.5 }
command = "ground"
expect.feedback = "You are standing on minecraft:air in minecraft:plains"
+1
View File
@@ -194,6 +194,7 @@ pub mod server {
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
pub use horizon::mods::players::{self, GameMode, Player};
pub use horizon::mods::world::{self, BlockChange};
/// The server's calls into a mod. Only the hooks [`Registration`] asks
/// for are called; the others may stay as their defaults.
+28
View File
@@ -472,6 +472,33 @@ interface players {
broadcast: func(text: string);
}
/// Capability `world`, server mods only (manifest `api = "0.3"`,
/// experimental): the blocks of the server's loaded chunks, and changes to
/// them through the server's own block updates.
interface %world {
record block-change {
x: s32,
y: s32,
z: s32,
/// `minecraft:oak_log[axis=y]`; properties left out take the block's
/// defaults, `minecraft:stone` alone is the default state.
state: string,
}
/// The block state at a position in a dimension (`minecraft:overworld`,
/// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the
/// server has no chunk loaded there.
get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
/// The biome at a position (`minecraft:plains`, ...), as the server
/// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded.
get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
/// Sets blocks as `/setblock` does: the old block entity removed,
/// neighbours and shapes updated, light, and every player told. Every
/// state is checked now (an error queues nothing); the changes are made
/// in order after this call returns, before that dimension's next tick;
/// one in a chunk not loaded then is skipped. At most 4096 per call.
set-blocks: func(dimension: string, blocks: list<block-change>) -> result<_, string>;
}
/// What the server calls in a server mod (manifest `api = "0.3"`,
/// experimental). Only the hooks `init` asks for are ever called. The player
/// in each event is as the server saw them when it happened.
@@ -534,6 +561,7 @@ world horizon-server-mod {
import log;
import storage;
import players;
import %world;
export server-events;
}
+5 -2
View File
@@ -7,13 +7,13 @@
//! version's level so the launcher can tell before it installs.
/// The newest level this Horizon serves.
pub const LEVEL: u32 = 3;
pub const LEVEL: u32 = 4;
/// Every function the game offers mods, as `interface.function`, with its
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
/// test fails until it is listed here).
pub const FUNCTIONS: [(&str, u32); 34] = [
pub const FUNCTIONS: [(&str, u32); 37] = [
("log.write", 0),
("game.get-player", 0),
("game.get-clock", 0),
@@ -48,6 +48,9 @@ pub const FUNCTIONS: [(&str, u32); 34] = [
("players.broadcast", 1),
("game.raycast", 2),
("command.run-quiet", 3),
("world.get-block", 4),
("world.get-biome", 4),
("world.set-blocks", 4),
];
/// What the game's program carries so the launcher can read its level
+12 -2
View File
@@ -97,9 +97,12 @@ pub enum Capability {
Input,
/// The players on the server and messages to them (server mods).
Players,
/// Blocks in the server's loaded chunks, and changes to them (server
/// mods; client mods later, where the game runs the world).
World,
}
impl Capability {
pub const ALL: [Capability; 10] = [
pub const ALL: [Capability; 11] = [
Capability::GameRead,
Capability::Chat,
Capability::Hud,
@@ -110,10 +113,14 @@ impl Capability {
Capability::Render,
Capability::Input,
Capability::Players,
Capability::World,
];
/// Whether a server mod may have it: the others act on a local player.
pub fn on_server(self) -> bool {
matches!(self, Capability::Storage | Capability::Players)
matches!(
self,
Capability::Storage | Capability::Players | Capability::World
)
}
/// The WIT interface it grants, in `horizon:mods`.
pub fn interface(self) -> &'static str {
@@ -128,6 +135,7 @@ impl Capability {
Capability::Render => "render",
Capability::Input => "input",
Capability::Players => "players",
Capability::World => "world",
}
}
/// May change in any release: a mod uses it only with
@@ -153,6 +161,7 @@ impl Capability {
"see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys"
}
Capability::Players => "see who is on the server and message them",
Capability::World => "read and change the world's blocks",
}
}
/// The capability a component import needs, `Ok(None)` for one every
@@ -188,6 +197,7 @@ impl fmt::Display for Capability {
Capability::Render => "render",
Capability::Input => "input",
Capability::Players => "players",
Capability::World => "world",
};
f.write_str(name)
}
+95 -3
View File
@@ -1,12 +1,13 @@
//! Loading and calling mods with wasmtime's component model.
use crate::manifest::{Manifest, Package, Side};
use server_bindings::{
HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration,
horizon::mods::players,
HorizonServerMod,
exports::horizon::mods::server_events::Registration as ServerRegistration,
horizon::mods::{players, world as mod_world},
};
use std::{
path::{Path, PathBuf},
sync::Arc,
sync::{Arc, Mutex},
time::{Duration, Instant, SystemTime},
};
use wasmtime::{
@@ -25,6 +26,7 @@ mod server_bindings {
wasmtime::component::bindgen!({
path: "../horizon-mod-sdk/wit",
world: "horizon-server-mod",
additional_derives: [PartialEq],
with: {
"horizon:mods/log": super::bindings::horizon::mods::log,
"horizon:mods/storage": super::bindings::horizon::mods::storage,
@@ -52,6 +54,7 @@ use bindings::{
pub use server_bindings::{
exports::horizon::mods::server_events::BlockPos,
horizon::mods::players::{GameMode, Player as ServerPlayer},
horizon::mods::world::BlockChange,
};
type ClientEvents = bindings::exports::horizon::mods::events::Guest;
type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest;
@@ -87,6 +90,8 @@ const FUEL_INIT: u64 = 2_000_000_000;
const FUEL_TICK: u64 = 50_000_000;
const FUEL_FRAME: u64 = 10_000_000;
const FUEL_EVENT: u64 = 100_000_000;
/// Blocks a mod may set per `world.set-blocks` call.
pub const BLOCKS_PER_CALL: usize = 4096;
/// Chat lines a mod may show per call, HUD lines and their length.
const CHAT_PER_CALL: usize = 8;
/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's
@@ -182,6 +187,13 @@ pub enum Output {
text: String,
error: bool,
},
/// `world.set-blocks`: changes to make in `dimension`, in order, each
/// state checked by the [`WorldView`] lent for the call.
SetBlocks {
name: String,
dimension: String,
blocks: Vec<BlockChange>,
},
/// `ui.open-screen`: the mod's entry in `entries()`; what it shows is
/// [`Mods::screen`].
OpenScreen { owner: usize },
@@ -191,6 +203,23 @@ pub enum Output {
Shake { strength: f32, seconds: f32 },
}
/// The game's world as capability `world` reads it during a call: the
/// game lends one with [`Mods::lend_world`] and takes it back after.
pub trait WorldView: std::any::Any + Send {
/// The block state at a position, `minecraft:oak_log[axis=y]`; `None`
/// where no chunk of that dimension is loaded.
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
/// The biome at a position, `minecraft:plains`; `None` as for blocks.
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
/// Whether `dimension` is one the server has.
fn has_dimension(&self, dimension: &str) -> bool;
/// `Err` (why) for a state string that names no block state.
fn check_state(&self, state: &str) -> Result<(), String>;
}
/// The view lent for the current calls, shared by every mod's store.
type WorldSlot = Arc<Mutex<Option<Box<dyn WorldView>>>>;
/// A mod's text panel, drawn every frame until it changes.
#[derive(Clone, Debug)]
pub struct Panel {
@@ -306,6 +335,7 @@ struct State {
/// needs its own budget.
storage_budget: u64,
limits: StoreLimits,
world: WorldSlot,
}
/// The installed mods and the engine running them. `Mods::default()` is
@@ -316,9 +346,33 @@ pub struct Mods {
entries: Vec<Entry>,
snapshot: Arc<Snapshot>,
out: Vec<Output>,
world: WorldSlot,
}
impl Mods {
/// Whether a running mod may use capability `world`: only then is a
/// view worth lending.
pub fn wants_world(&self) -> bool {
self.entries.iter().any(|e| {
e.status == Status::Running
&& e.manifest
.as_ref()
.is_some_and(|m| m.capabilities.contains(&crate::Capability::World))
})
}
/// Lends the game's world to capability `world` for the calls until
/// [`Mods::take_world`]; with none lent, `get-block` finds nothing and
/// `set-blocks` checks only its count.
pub fn lend_world(&mut self, view: Box<dyn WorldView>) {
if let Ok(mut slot) = self.world.lock() {
*slot = Some(view);
}
}
/// The view [`Mods::lend_world`] lent, back to the game.
pub fn take_world(&mut self) -> Option<Box<dyn WorldView>> {
self.world.lock().ok()?.take()
}
/// Reads every mod at `paths` and starts those `enabled` says are on,
/// client and server mods alike. A command that `reserved` (vanilla's
/// commands) or an earlier mod already uses is refused.
@@ -388,6 +442,8 @@ impl Mods {
.map_err(|e| e.to_string())?;
players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
mod_world::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
UiHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
@@ -429,6 +485,7 @@ impl Mods {
.flat_map(|r| r.hooks.commands().iter().cloned())
.collect();
let snapshot = self.snapshot.clone();
let world = self.world.clone();
let (engine, linker) = self.engine()?;
let component =
Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?;
@@ -467,6 +524,7 @@ impl Mods {
.memory_size(MEMORY)
.instances(16)
.build(),
world,
};
let mut store = Store::new(engine, state);
store.limiter(|s| &mut s.limits);
@@ -1153,6 +1211,40 @@ impl chat::Host for State {
});
}
}
impl mod_world::Host for State {
fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
let view = self.world.lock().ok()?;
view.as_ref()?.block(&dimension, x, y, z)
}
fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
let view = self.world.lock().ok()?;
view.as_ref()?.biome(&dimension, x, y, z)
}
fn set_blocks(&mut self, dimension: String, blocks: Vec<BlockChange>) -> Result<(), String> {
if blocks.len() > BLOCKS_PER_CALL {
return Err(format!(
"{} blocks: at most {BLOCKS_PER_CALL} per call",
blocks.len()
));
}
if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) {
if !view.has_dimension(&dimension) {
return Err(format!("no dimension {dimension}"));
}
for b in &blocks {
view.check_state(&b.state)?;
}
}
if !blocks.is_empty() {
self.out.push(Output::SetBlocks {
name: self.name.clone(),
dimension,
blocks,
});
}
Ok(())
}
}
impl players::Host for State {
fn online(&mut self) -> Vec<ServerPlayer> {
self.snapshot.players.clone()
+89 -3
View File
@@ -29,6 +29,54 @@ pub struct TestGame {
/// Every name that joined, for their id.
names: Vec<String>,
tick: u64,
/// Capability `world`'s Overworld: the blocks a script set or the mod
/// changed; every other block, and the other dimensions, are air. Every
/// biome is the dimension's plainest: plains, nether wastes, the end.
pub world: std::collections::BTreeMap<(i32, i32, i32), String>,
}
/// The world a script's mod reads: [`TestGame::world`], copied for a step.
struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>);
impl crate::WorldView for ScriptWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let here = (dimension == "minecraft:overworld")
.then(|| self.0.get(&(x, y, z)).cloned())
.flatten();
Some(here.unwrap_or_else(|| "minecraft:air".into()))
}
fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option<String> {
let biome = match dimension {
"minecraft:overworld" => "minecraft:plains",
"minecraft:the_nether" => "minecraft:nether_wastes",
"minecraft:the_end" => "minecraft:the_end",
_ => return None,
};
Some(biome.into())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
// No registry here: the shape only (the game checks the names).
let name = state.split('[').next().unwrap_or_default();
let plain = |t: &str| {
!t.is_empty()
&& t.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b))
};
let ok = match name.split_once(':') {
Some((ns, path)) => plain(ns) && plain(path),
None => plain(name),
};
let closed = !state.contains('[') || state.ends_with(']');
(ok && closed)
.then_some(())
.ok_or_else(|| format!("{state} is not a block state"))
}
}
/// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing
@@ -71,6 +119,7 @@ impl TestGame {
players: Vec::new(),
names: Vec::new(),
tick: 0,
world: Default::default(),
};
copy_mod(hmod, &copy)?;
game.start()?;
@@ -312,9 +361,10 @@ pub struct ClockSet {
}
/// One step. Its parts happen in this order: `reload`, `title-screen`,
/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`,
/// `place`, `leave`; then `expect` is checked against what the mod showed
/// during the step. For a server mod, `player`, `chat`, `command`, `break`
/// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`,
/// `break`, `place`, `leave`; then the blocks the mod set are made, and
/// `expect` is checked against what the mod showed and changed during the
/// step. For a server mod, `player`, `chat`, `command`, `break`
/// and `place` are the doing of the player named by `as`, or of the first
/// player on.
#[derive(Debug, Default, Deserialize)]
@@ -341,6 +391,10 @@ pub struct Step {
#[serde(rename = "break")]
broken: Option<BlockSet>,
place: Option<BlockSet>,
/// Blocks of the Overworld before the rest of the step (capability
/// `world`); every other block is air.
#[serde(default)]
blocks: Vec<BlockSet>,
#[serde(default)]
expect: Expect,
}
@@ -363,6 +417,9 @@ pub struct Expect {
/// The panel's lines (`[]`: no panel) and its corner.
panel: Option<Vec<String>>,
corner: Option<String>,
/// Blocks of the Overworld after the step, the mod's changes made
/// (capability `world`).
blocks: Option<Vec<BlockSet>>,
/// The mod is turned off during this step, for a reason holding this text.
/// Without it, a mod that stops fails the test.
stopped: Option<String>,
@@ -467,6 +524,11 @@ impl Step {
game.player = None;
game.clock = None;
}
for b in &self.blocks {
game.world.insert((b.x, b.y, b.z), b.state.clone());
}
game.mods
.lend_world(Box::new(ScriptWorld(game.world.clone())));
if let Some(name) = &self.join {
game.join(name);
}
@@ -531,7 +593,19 @@ impl Step {
{
return Err(format!("{name} is not on the server"));
}
game.mods.take_world();
let out = game.drain();
for o in &out {
if let Output::SetBlocks {
dimension, blocks, ..
} = o
&& dimension == "minecraft:overworld"
{
for b in blocks {
game.world.insert((b.x, b.y, b.z), b.state.clone());
}
}
}
let stopped = out.iter().find_map(|o| match o {
Output::Stopped { reason, .. } => Some(reason.as_str()),
_ => None,
@@ -615,6 +689,18 @@ impl Step {
.unwrap_or_default();
same("panel", want, &got)?;
}
if let Some(want) = &e.blocks {
for b in want {
let got = game.world.get(&(b.x, b.y, b.z));
let got = got.map_or("minecraft:air", String::as_str);
if got != b.state {
return Err(format!(
"block at {} {} {}: expected {}, got {got}",
b.x, b.y, b.z, b.state
));
}
}
}
if let Some(want) = &e.corner {
let got = game.panel().map(|p| corner_name(p.corner).to_string());
same("corner", &Some(want.clone()), &got)?;
+30 -5
View File
@@ -47,6 +47,8 @@ fn mods_dir() -> &'static Path {
"-p",
"welcome",
"-p",
"beacons",
"-p",
"horizon-mods-test-guest",
"-p",
"horizon-mods-test-ui-guest",
@@ -70,6 +72,7 @@ fn mods_dir() -> &'static Path {
("coords_hud", example("coords-hud")),
("predator_missile", example("predator-missile")),
("welcome", example("welcome")),
("beacons", example("beacons")),
("horizon_mods_test_guest", GUEST_MANIFEST.to_string()),
("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()),
];
@@ -202,7 +205,7 @@ fn undeclared_capabilities_are_refused() {
/// from the functions they import.
#[test]
fn a_mod_for_a_newer_horizon_is_refused() {
use horizon_mods::api_level::{LEVEL, imports, needed};
use horizon_mods::api_level::{imports, needed};
use wit_parser::{ManglingAndAbi, Resolve};
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit"))
@@ -252,8 +255,8 @@ experimental = ["ui", "render", "input"]
needed(imports(&wasm).unwrap().iter().map(String::as_str)).0
};
assert_eq!(level("coords_hud.hmod"), 0);
// The UI guest shows a minimap (`render.set-minimap`).
assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL);
// The UI guest runs quiet commands (`command.run-quiet`, level 3).
assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 3);
}
#[test]
@@ -866,7 +869,12 @@ capabilities = ["registries"]
fn the_examples_test_scripts_pass() {
let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples");
let mut ran = 0;
for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] {
let examples_and_files = [
("coords-hud", "coords_hud"),
("welcome", "welcome"),
("beacons", "beacons"),
];
for (example, hmod) in examples_and_files {
for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() {
let path = entry.unwrap().path();
let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap();
@@ -877,7 +885,24 @@ fn the_examples_test_scripts_pass() {
ran += 1;
}
}
assert_eq!(ran, 4);
assert_eq!(ran, 5);
}
/// Capability `world` without a world lent (the registry's trial run):
/// `get-block` finds nothing, `set-blocks` checks its count and queues.
#[test]
fn a_server_mod_without_a_world_reads_nothing() {
let mut game = TestGame::load(&mods_dir().join("beacons.hmod")).unwrap();
game.join("Alex");
let alex = game.players[0].clone();
assert!(game.player_command(&alex, "ground"));
let out = game.drain();
assert!(
out.iter()
.any(|o| matches!(o, Output::Reply { text, error: true, .. }
if text == "The ground under you isn't loaded")),
"{out:?}"
);
}
#[test]
+7
View File
@@ -447,6 +447,13 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
if !b.table.bool(state, b.props.powered) {
self.detector_rail_check_pressed(pos, state);
}
} else if data.is(Class::Button) {
// ButtonBlock.entityInside: a wooden button an arrow is inside.
if data.set_type.as_ref().is_some_and(|s| s.arrows)
&& !b.table.bool(state, b.props.powered)
{
self.button_check_pressed(pos, state);
}
} else if data.is(Class::TripWire)
&& !b.table.bool(state, b.props.powered)
&& !self.ticks.has_block_tick(pos, b.block(state))
+59 -13
View File
@@ -195,6 +195,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
let next = table.cycle(state, p.inverted);
self.set_block(pos, next, 2);
self.game_event(pos, "minecraft:block_change");
self.daylight_detector_update_signal(pos, next);
Success
}
Class::Cake => {
@@ -227,19 +228,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
if table.int(state, p.level) != 8 {
return Pass;
}
self.player_effect(
pos,
state,
PlayerEffect::DropItem("minecraft:bone_meal".into()),
);
self.set_block_and_update(pos, table.set_int(state, p.level, 0));
self.game_event(pos, "minecraft:block_change");
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.composter.empty".into(),
volume: 1.0,
pitch: 1.0,
});
self.composter_extract_produce(pos, state);
Success
}
Class::CaveVines | Class::CaveVinesPlant => {
@@ -435,6 +424,25 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
InteractionResult::Success
}
/// `ComposterBlock.extractProduce`: the bone meal pops out, the composter
/// empties and its sound plays.
fn composter_extract_produce(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
self.player_effect(
pos,
state,
PlayerEffect::DropItem("minecraft:bone_meal".into()),
);
self.set_block_and_update(pos, b.table.set_int(state, b.props.level, 0));
self.game_event(pos, "minecraft:block_change");
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.composter.empty".into(),
volume: 1.0,
pitch: 1.0,
});
}
/// `ComposterBlock.addLayer` once its `compostable` provider gave
/// `layers`: the new state (the old one when no layer is added).
fn composter_add_layer(&mut self, pos: BlockPos, layers: i32) -> BlockStateId {
@@ -499,6 +507,44 @@ impl Behaviours {
next
}
/// `ComposterBlock.addLayer` without level event 1500, for a villager
/// that composts several items and sends the event once at the end
/// (`WorkAtComposter.compostItems`). The new state.
pub fn composter_layer<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
layers: i32,
) -> BlockStateId {
self.sim(level, ticks).composter_add_layer(pos, layers)
}
/// `ComposterBlock.extractProduce` by a villager (`WorkAtComposter`).
pub fn composter_extract<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
sim.composter_extract_produce(pos, state);
}
/// Level event 1500 (`WorkAtComposter.spawnComposterFillEffects`): data 1
/// when the composter's state changed.
pub fn composter_fill_effects<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
changed: bool,
) {
self.sim(level, ticks)
.level_event(1500, pos, i32::from(changed));
}
/// `ComposterBlock.empty`: the hopper output container took the bone meal.
pub fn composter_empty<L: LevelAccess + ?Sized>(
&self,
+41
View File
@@ -209,6 +209,9 @@ pub enum EntityQuery {
Mobs,
/// Minecarts only (detector rails).
Minecart,
/// Arrows only (`AbstractArrow`, thrown tridents included): the entities
/// a wooden button senses.
Arrows,
}
/// Side effects reported to the caller, in vanilla call order.
@@ -328,6 +331,10 @@ pub trait LevelAccess {
fn sky_darken(&self) -> i32 {
0
}
/// `EnvironmentAttributes.SUN_ANGLE` at `pos`, in degrees (0 at noon).
fn sun_angle(&self, _pos: BlockPos) -> f32 {
0.0
}
fn is_raining(&self) -> bool {
false
}
@@ -763,6 +770,24 @@ impl Behaviours {
) {
self.sim(level, ticks).entity_inside(pos);
}
/// `DaylightDetectorBlock.tickEntity` of the daylight detector at `pos`:
/// its signal follows the sky every 20 game ticks. The detector's ticker
/// exists only where the dimension has sky light.
pub fn tick_daylight_detector<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
if level.dimension() == Dimension::Nether || level.game_time() % 20 != 0 {
return;
}
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
if sim.b.data(state).is(classes::Class::DaylightDetector) {
sim.daylight_detector_update_signal(pos, state);
}
}
/// `BigDripleafBlock.entityInside` for an entity whose box is inside
/// `pos`: whether it is on the ground and its feet's y (`canEntityTilt`).
pub fn entity_on_big_dripleaf<L: LevelAccess + ?Sized>(
@@ -793,6 +818,22 @@ impl Behaviours {
) -> i32 {
self.sim(level, ticks).best_neighbor_signal(pos)
}
/// `BlockState.onProjectileHit` of a target block (`TargetBlock`) hit by
/// a projectile at `location` on the face with normal `face`; `arrow`
/// for an `AbstractArrow`. Returns the output strength, or None when the
/// block at `pos` is not a target block.
pub fn target_projectile_hit<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
location: [f64; 3],
face: [i32; 3],
arrow: bool,
) -> Option<i32> {
self.sim(level, ticks)
.target_projectile_hit(pos, location, face, arrow)
}
}
/// One mutable view used by the ported behaviour code.
+140 -9
View File
@@ -11,7 +11,10 @@ use super::{
};
use crate::registry::BlockStateId;
use horizon_core::{
geometry::Direction, position::BlockPos, random::RandomSource, ticks::TickPriority,
geometry::{Direction, trig},
position::BlockPos,
random::RandomSource,
ticks::TickPriority,
};
const SIGNAL_ORDER: [Direction; 6] = [
@@ -879,18 +882,109 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
self.game_event(pos, "minecraft:block_activate");
}
/// `ButtonBlock.checkPressed` with no arrows present.
/// `ButtonBlock.tick`.
pub(crate) fn button_tick(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
if !b.table.bool(state, b.props.powered) {
return;
if b.table.bool(state, b.props.powered) {
self.button_check_pressed(pos, state);
}
self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, false));
self.attached_update_neighbours(pos, state);
if let Some(set) = b.data(state).set_type.clone() {
self.sound(pos, &set.button_off, 1.0, 1.0);
}
/// `ButtonBlock.checkPressed`: a button whose type allows arrows is
/// pressed while an arrow is inside its shape, and stays pressed (the
/// release is scheduled again) as long as one is.
pub(crate) fn button_check_pressed(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let data = b.data(state);
let should_be_pressed = data.set_type.as_ref().is_some_and(|s| s.arrows)
&& self
.level
.count_entities(self.button_bounds(pos, state), super::EntityQuery::Arrows)
> 0;
let was_pressed = b.table.bool(state, b.props.powered);
if should_be_pressed != was_pressed {
self.set_block_and_update(
pos,
b.table.set_bool(state, b.props.powered, should_be_pressed),
);
self.attached_update_neighbours(pos, state);
if let Some(set) = data.set_type.clone() {
let sound = if should_be_pressed {
&set.button_on
} else {
&set.button_off
};
self.sound(pos, sound, 1.0, 1.0);
}
self.game_event(
pos,
if should_be_pressed {
"minecraft:block_activate"
} else {
"minecraft:block_deactivate"
},
);
}
if should_be_pressed {
self.schedule_tick(pos, b.block(state), data.ticks_to_stay_pressed);
}
}
/// `ButtonBlock.getShape(...).bounds().move(pos)`: a 6 by 4 plate on the
/// face it is attached to, 2 pixels thick (1 when pressed).
fn button_bounds(&self, pos: BlockPos, state: BlockStateId) -> horizon_core::geometry::Aabb {
use horizon_core::geometry::{Aabb, Vec3};
let b = self.b;
let thickness = if b.table.bool(state, b.props.powered) {
1.0 / 16.0
} else {
2.0 / 16.0
};
let attached = self.face_attached_connected(state).opposite().normal();
let thick = attached.iter().position(|&n| n != 0).unwrap_or(1);
// The 6 pixel side lies across the button's facing.
let wide = if b.facing(state).normal()[2] != 0 {
0
} else {
2
};
let tall = 3 - thick - wide;
let (mut lo, mut hi) = ([0.0; 3], [1.0; 3]);
if attached[thick] > 0 {
lo[thick] = 1.0 - thickness;
} else {
hi[thick] = thickness;
}
(lo[wide], hi[wide]) = (5.0 / 16.0, 11.0 / 16.0);
(lo[tall], hi[tall]) = (6.0 / 16.0, 10.0 / 16.0);
let origin = [f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)];
Aabb::new(
Vec3::new(origin[0] + lo[0], origin[1] + lo[1], origin[2] + lo[2]),
Vec3::new(origin[0] + hi[0], origin[1] + hi[1], origin[2] + hi[2]),
)
}
/// `DaylightDetectorBlock.updateSignalStrength`: the effective sky light
/// at the detector, shaped by the sun's angle (or inverted), as its
/// power.
pub(crate) fn daylight_detector_update_signal(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let mut target = (self.level.sky_light(pos) - self.level.sky_darken()).max(0);
if b.table.bool(state, b.props.inverted) {
target = 15 - target;
} else if target > 0 {
let mut sun_angle = self.level.sun_angle(pos) * trig::DEG_TO_RAD;
let offset = if sun_angle < std::f32::consts::PI {
0.0
} else {
std::f32::consts::TAU
};
sun_angle += (offset - sun_angle) * 0.2;
// Math.round(float).
let scaled = target as f32 * trig::cos(f64::from(sun_angle));
target = (f64::from(scaled) + 0.5).floor() as i32;
}
let target = target.clamp(0, 15);
if b.table.int(state, b.props.power) != target {
self.set_block_and_update(pos, b.table.set_int(state, b.props.power, target));
}
self.game_event(pos, "minecraft:block_deactivate");
}
/// `LeverBlock.pull`.
pub(crate) fn lever_pull(&mut self, pos: BlockPos, state: BlockStateId) {
@@ -1187,6 +1281,43 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.set_block(pos, next, 2);
}
}
/// `TargetBlock.onProjectileHit` for a projectile that hit `face` of the
/// block at `pos` at `location`: the output power from how near the
/// face's centre it landed (1 to 15), reset after 20 ticks for an arrow
/// and 8 for anything else, unless a reset is already scheduled. None
/// when the block is not a target block, else the strength.
pub(crate) fn target_projectile_hit(
&mut self,
pos: BlockPos,
location: [f64; 3],
face: [i32; 3],
arrow: bool,
) -> Option<i32> {
let b = self.b;
let state = self.state(pos);
if !b.data(state).is(Class::Target) {
return None;
}
// `getRedstoneStrength`: the distance from the centre along the
// face's two other axes (Mth.frac of the location, minus a half).
let off = |v: f64| (v - v.floor() - 0.5).abs();
let [dx, dy, dz] = [off(location[0]), off(location[1]), off(location[2])];
let distance = if face[1] != 0 {
dx.max(dz)
} else if face[2] != 0 {
dx.max(dy)
} else {
dy.max(dz)
};
let strength = ((15.0 * ((0.5 - distance) / 0.5).clamp(0.0, 1.0)).ceil() as i32).max(1);
let block = b.block(state);
if !self.ticks.has_block_tick(pos, block) {
// `setOutputPower`.
self.set_block_and_update(pos, b.table.set_int(state, b.props.power, strength));
self.schedule_tick(pos, block, if arrow { 20 } else { 8 });
}
Some(strength)
}
}
/// Order `positions` as a `java.util.HashSet<BlockPos>` of capacity 16 would
+5
View File
@@ -154,6 +154,8 @@ pub struct LootEntity {
pub captain: Option<bool>,
/// A frog's variant id (`minecraft:warm`).
pub frog_variant: Option<String>,
/// A chicken's variant id (`minecraft:warm`).
pub chicken_variant: Option<String>,
/// A charged creeper (`Creeper.isPowered`).
pub powered: bool,
/// Worn and held items by `EquipmentSlot` name (mainhand, offhand,
@@ -862,6 +864,9 @@ impl<R: RandomSource> Context<'_, R> {
"minecraft:frog/variant" => {
e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref()
}
"minecraft:chicken/variant" => {
e.chicken_variant.is_some() && want.as_str() == e.chicken_variant.as_deref()
}
_ => false,
}),
"minecraft:type_specific/sheep" => e
+23 -1
View File
@@ -17,6 +17,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
| `render` | [`render`](#render) | draw on your screen, shake and zoom the camera |
| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys |
| `players` | [`players`](#players) | see who is on the server and message them |
| `world` | [`world`](#world) | read and change the world's blocks |
## World `horizon-mod`
@@ -29,7 +30,7 @@ A client mod: runs in the player's game.
A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs where the world is simulated, on the dedicated server, a LAN host and single player's own server.
- Imports (what the game offers): `log`, `storage`, `players`
- Imports (what the game offers): `log`, `storage`, `players`, `world`
- Exports (what the mod provides): `server-events`
## World `horizon-ui-mod`
@@ -495,6 +496,27 @@ Capability `players`, server mods only (manifest `api = "0.3"`, experimental): t
| `tell` | `func(player: string, text: string) -> bool` | A system message to one player, after the mod's name; false when no player with that id is online. Up to 8 messages per call. |
| `broadcast` | `func(text: string)` | A system message to every player and the server's log, after the mod's name. Counts toward the same 8 per call. |
## `world`
Access: capability `world`.
Capability `world`, server mods only (manifest `api = "0.3"`, experimental): the blocks of the server's loaded chunks, and changes to them through the server's own block updates.
### record `block-change`
| Field | Type | |
| --- | --- | --- |
| `x` | `s32` | |
| `y` | `s32` | |
| `z` | `s32` | |
| `state` | `string` | `minecraft:oak_log[axis=y]`; properties left out take the block's defaults, `minecraft:stone` alone is the default state. |
| Function | Signature | What it does |
| --- | --- | --- |
| `get-block` | `func(dimension: string, x: s32, y: s32, z: s32) -> option<string>` | The block state at a position in a dimension (`minecraft:overworld`, ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the server has no chunk loaded there. |
| `get-biome` | `func(dimension: string, x: s32, y: s32, z: s32) -> option<string>` | The biome at a position (`minecraft:plains`, ...), as the server stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. |
| `set-blocks` | `func(dimension: string, blocks: list<block-change>) -> result<_, string>` | Sets blocks as `/setblock` does: the old block entity removed, neighbours and shapes updated, light, and every player told. Every state is checked now (an error queues nothing); the changes are made in order after this call returns, before that dimension's next tick; one in a chunk not loaded then is skipped. At most 4096 per call. |
## `server-events`
Access: exported by the mod: the game calls it.
+7 -5
View File
@@ -88,11 +88,11 @@ release.
What real mods need next, in the order modpacks and servers need it:
- **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run
on the server thread, a LAN host and the dedicated server today, with joins, chat, commands and players' block
breaking and placing; next entity events, game rules, server commands with typed arguments sent to clients'
command trees.
- **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block
log, so clients and the parity harnesses see vanilla's updates.
on the server thread, a LAN host and the dedicated server today, with joins, chat, commands, players' block
breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` does); next entity events, game rules,
server commands with typed arguments sent to clients' command trees.
- **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities,
and `world` for client mods (raycasts, single player and LAN hosts).
- **Items and inventories**: the player's inventory, held item and open container; item stacks with components.
- **Entities**: query and change entities near a position; spawn from a mod's own entity types (data first).
- **Block entities and menus**: ticking machines with slots and their screens.
@@ -106,6 +106,8 @@ What real mods need next, in the order modpacks and servers need it:
## Changelog
- API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and
`expect.blocks`.
- Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server.
- API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events`
hooks; SDK `server::ServerMod`; example `welcome`.
+1 -1
View File
@@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says
A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every
function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`):
level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of
level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`. A mod needs the level of
the newest function it imports (a component imports only the functions it calls). The level is read from the file,
never declared:
+17 -1
View File
@@ -285,6 +285,7 @@ A step's parts happen in this order:
| --- | --- |
| `reload = true` | stops the mod and starts it again, as a rebuild does in the game: its memory starts over, its `storage` stays |
| `title-screen = true` | no player and no clock until a step sets them |
| `blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:stone" }]` | server mods with `world`: those blocks of the Overworld, before the rest of the step (every other block is air, every biome the dimension's plainest: plains, nether wastes, the end) |
| `player = { x = 3.0, ... }`, `clock = { day-time = 0 }` | changes those fields (`x y z yaw pitch health food dimension`, `game-time day-time`) |
| `ticks = n`, `frames = n` | that many ticks (the game's tick counter and the clock move on), then frames 1/60 s apart |
| `chat = "<Steve> hi"` | a chat line the player receives |
@@ -310,6 +311,7 @@ checked:
| `feedback = "..."`, `error = "..."` | the command's answer, shown plain or in red |
| `panel = ["..."]`, `corner = "top-left"` | its HUD panel's lines (`[]`: no panel) and corner |
| `told = ["Alex: Welcome!"]`, `broadcast = ["..."]` | server mods: every `players.tell` (as `name: text`) and `players.broadcast`, in order |
| `blocks = [{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" }]` | server mods with `world`: those blocks of the Overworld after the step, the mod's `set-blocks` made (the script checks a state's shape; the game checks its name) |
| `stopped = "panic"` | the mod was turned off, for a reason holding this text; without it, a mod that traps, panics or overruns fails the test |
Unknown keys are errors, so a typo never passes silently. The same runner is
@@ -478,6 +480,7 @@ its component targets the WIT world `horizon-server-mod` instead of
| `log` | always | as for client mods |
| `storage` | `storage` | as for client mods, in the server's `horizon-mods/` |
| `players` | `players` | `online()`: id, name, position, dimension, game mode, health of each player on; `tell(id, text)`, `broadcast(text)`: system messages after the mod's name, 8 per call |
| `world` | `world` | `get-block(dimension, x, y, z)`: the state in a loaded chunk, `minecraft:oak_log[axis=y]`; `get-biome(dimension, x, y, z)`: `minecraft:plains`, ...; `set-blocks(dimension, changes)`: up to 4096 per call, checked at once, made as `/setblock` makes them (neighbours, light, block entities, every player told) after the call, before that dimension's next tick |
| Hook (export `server-events`) | When |
|---|---|
@@ -491,7 +494,20 @@ its component targets the WIT world `horizon-server-mod` instead of
Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for
client mods; `players` is for server mods. In Rust: `impl
horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs).
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with
`world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs).
**Capability `world`.** Reads are of the server's loaded chunks as they are
during the call: the game lends a server mod's call the levels' chunk maps
(moved, not copied, and only while a running mod has `world`), so a read
costs a map lookup and no copy of the world. A dimension with no chunk loaded
at a position reads as none. Writes go through the same code as `/setblock`,
so block updates, light, block entities and every client (LAN guests,
dedicated server players) see them as vanilla's; the parity harnesses test
that code. Changes for a dimension whose level isn't ticking wait for it
(in-frame single player ticks only the player's), up to 65,536 blocks; a
change in a chunk that isn't loaded when it is made is skipped, as `/setblock`
refuses one.
**Where they run.** The game that simulates the world starts the server mods
that are on, and only that one:
+18
View File
@@ -44,6 +44,17 @@ Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/pari
Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on.
### Any command on playhorizon: `tools/remote.sh`
For Linux work that doesn't need a whole parity run (a crate's tests, a few harnesses, a server build), `tools/remote.sh <worktree> <command...>` runs the command on playhorizon at the worktree's commit and streams its output back; its exit status is the command's. Commit and push first: the host fetches the commit from GitHub, and nothing else leaves this machine (no files, no credentials, no environment). Each worktree keeps one checkout there, `~/remote-work/<name>` with its own `target/`, so the next run only rebuilds what changed, and one run per name goes at a time. The command runs niced in the host's CI slice, pinned to CPUs 4-7 (`--cpus`; 0-3 stay free for benchmarks), with scratch game and launcher homes and the vanilla data linked as CI links it; a command naming `parity`, `lan_e2e` or `horizon-prepare` also gets `.local/horizon-client`, prepared as CI prepares it. Logs stay in `~/remote-work/<name>.logs/`; `--list` shows the checkouts, `--gc [DAYS]` removes old ones.
```sh
tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib # 33 s, warm
tools/remote.sh . python3 tools/parity.py food # 19 s warm (4 min the first time); here: 188 s, 229 CPU-seconds
```
The host is lent by a partner who keeps hypervisor access: send it no secret, token or credential, and never take a result from it as a CI result.
### Shards and Rust scopes
A harness can declare, at the top level of its script:
@@ -133,6 +144,13 @@ when named and in the nightly audit (`--all`). LAN writes `results.json`
with the host mode and each result beside its screenshots and logs. A skipped
case is recorded explicitly and does not count as passing coverage.
`known_flaky` in `tools/parity_hosts.json` lists harnesses that fail now and then for a
cause not fixed yet, each with its reason. One that fails runs once more from
scratch, and a pass then counts. `parity.py` prints a `RETRIED` line for it
in its summary and in the CI job's summary (PR parity and parity-main), so the
flake stays visible. No other harness gets this retry. Fix the cause, then take
the harness off the list.
The game-binary fixture audit keeps these complementary direct rule tests:
- `command_harness.rs`: command feedback, styled spans and result callbacks,
+6 -3
View File
@@ -32,6 +32,12 @@ copy is: the Mac mini, his Linux desktop and playhorizon (below). Their runners
between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes
stand.
The job tests the pull request's head merged into main's current tip, which is what merging it would land: harness
and game fixes that reached main after the branch was made apply to it too, and an old branch runs main's runner
scripts and selection unless it changes them. The base for the selection is that main commit, so only the pull
request's own changes count. The job summary names the main commit. A head that conflicts with main is tested
alone, with a warning. The check is still reported on the head.
1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH
(Homebrew and `java_home` on the Mac; on Linux what `linux-runner.sh` pinned, else nixpkgs), and sccache when
the machine has it.
@@ -50,9 +56,6 @@ stand.
modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any
harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to
`Cargo.lock` or `research-lock.json` affects every harness. Each harness has 25 minutes, the job 45.
The selection runs with main's `tools/parity.py` and `tools/parity_reach.py` (`--changed <base> --list`), so a
branch made before a better selection landed gets it too, and the head's own `parity.py` then runs the named
harnesses. A branch that changes either file selects with its own code.
Failed harnesses' logs are uploaded as the `parity-logs` artifact.
@@ -461,7 +461,9 @@ public final class VanillaDispenserOracle {
line.append(' ').append(num(v.x)).append(' ').append(num(v.y)).append(' ').append(num(v.z));
if (e instanceof ItemEntity item) line.append(' ').append(ParityData.canon(item.getItem()));
if (e instanceof PrimedTnt tnt) line.append(" fuse=").append(tnt.getFuse());
result.add(line.toString());
// An orb that took others in (ExperienceOrb.tryMergeToExisting) prints once per
// count: whether orbs merge depends on entity ids, which Horizon doesn't share.
for (int n = e instanceof ExperienceOrb orb ? orbCount(orb) : 1; n > 0; n--) result.add(line.toString());
}
for (int i = 0; i < targets.size(); i++) result.add(describe(i, targets.get(i)));
for (String s : w.log.toString().split("\n")) {
@@ -821,6 +823,16 @@ public final class VanillaDispenserOracle {
}
/** A target's state after dispensing: removal, equipment and readiness for shearing. */
static int orbCount(ExperienceOrb orb) {
try {
var f = ExperienceOrb.class.getDeclaredField("count");
f.setAccessible(true);
return f.getInt(orb);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
static String describe(int index, Entity e) {
StringBuilder line = new StringBuilder("T " + index + " " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()));
if (e.isRemoved()) line.append(" removed");
+81 -3
View File
@@ -290,9 +290,6 @@ class OracleReuseTests(unittest.TestCase):
self.assertEqual(self.output.read_text(), "b")
if __name__ == "__main__":
unittest.main()
class LargeOutputTests(unittest.TestCase):
def test_a_pass_clears_only_its_own_directory(self):
@@ -323,3 +320,84 @@ class LargeOutputTests(unittest.TestCase):
listing.write_text(f"{own / 'server.txt'}\n{own / 'client.txt'}\n")
parity.clear_large_outputs("state_provider#2", trace)
self.assertEqual(sorted(path.name for path in own.iterdir()), ["report.json", "server.txt"])
class FakeExecutor:
"""Runs nothing: each start of a harness takes the next status from its script, a list."""
name, dead, max_peak = "fake", False, None
def __init__(self):
self.started, self.finished = [], []
def free(self):
return 1
def accepts(self, name):
return True
def fits(self, expected, only_here=True):
return True
def start(self, label, script, reuse, expected, shard=None):
self.started.append((label, reuse))
self.finished.append((label, {"status": script.pop(0), "seconds": 1.0, "dependencies": []}))
return True
def poll(self):
finished, self.finished = self.finished, []
return finished
class KnownFlakyTests(unittest.TestCase):
def run_harnesses(self, scripts, flaky, rounds=None):
executor = FakeExecutor()
state = {"harnesses": {name: {"status": "pass", "oracle_reuse": True} for name in scripts}}
with tempfile.TemporaryDirectory() as tmp, mock.patch.multiple(parity, STATE_DIR=Path(tmp), SHARED=Path(tmp)), \
mock.patch.object(parity, "save_state"), mock.patch.object(parity, "time") as clock:
clock.monotonic.return_value = 0.0
results, _ = parity.run(scripts, state, None, "env", [executor], True, rounds, flaky)
return results, executor.started
def test_a_known_flaky_failure_runs_once_more_from_scratch_and_says_so(self):
results, started = self.run_harnesses({"dedicated_server": ["fail", "pass"]}, {"dedicated_server": "timer"})
self.assertEqual(results["dedicated_server"]["status"], "pass")
self.assertEqual(results["dedicated_server"]["retried"], "known flaky")
# The first run reused oracle results; a known flaky harness doesn't lose that by flaking.
self.assertTrue(results["dedicated_server"]["oracle_reuse"])
self.assertEqual(started, [("dedicated_server", True), ("dedicated_server", False)])
def test_only_once(self):
results, started = self.run_harnesses({"dedicated_server": ["fail", "fail"]}, {"dedicated_server": "timer"})
self.assertEqual(results["dedicated_server"]["status"], "fail")
self.assertEqual(len(started), 2)
def test_other_harnesses_keep_only_the_reused_oracle_retry(self):
results, started = self.run_harnesses({"food": ["fail", "pass"]}, {"dedicated_server": "timer"})
self.assertEqual((results["food"]["status"], results["food"]["retried"]), ("pass", "reused oracle results"))
self.assertEqual(started, [("food", True), ("food", False)])
self.assertFalse(results["food"]["oracle_reuse"])
def test_repeated_runs_get_no_retry(self):
results, started = self.run_harnesses({"dedicated_server": ["pass", "fail"]}, {"dedicated_server": "timer"},
rounds={"dedicated_server": 2})
self.assertEqual((results["dedicated_server"]["status"], len(started)), ("fail", 2))
def test_retries_reach_the_job_summary(self):
with tempfile.TemporaryDirectory() as tmp:
summary = Path(tmp) / "summary.md"
with mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": str(summary)}), \
mock.patch("builtins.print"):
parity.report_retries({"dedicated_server": {"status": "pass", "retried": "known flaky"},
"food": {"status": "pass"}}, {"dedicated_server": "timer"})
text = summary.read_text()
self.assertIn("RETRIED dedicated_server: failed, then passed on its one retry (known flaky: timer", text)
self.assertNotIn("food", text)
def test_the_known_flaky_list_has_a_reason_per_harness(self):
flaky = parity.known_flaky(parity.host_config())
self.assertTrue(all(isinstance(reason, str) and len(reason) > 20 for reason in flaky.values()))
self.assertTrue(set(flaky) <= {parity.base_name(name) for name in parity.harnesses()})
if __name__ == "__main__":
unittest.main()

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