Merge pull request #1200 from pirut/claude/upstream-mob-world
🤖 Agent: merged after verify passed and the integration run on the desktop (main 34c3c1cf + the 14 contributor PRs: workspace tests 1,869/0, launcher 113, parity --changed 320/0).
This commit is contained in:
@@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> {
|
|||||||
nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position),
|
nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position),
|
||||||
others: $snapshot,
|
others: $snapshot,
|
||||||
others_grid: $grid,
|
others_grid: $grid,
|
||||||
|
others_index: None,
|
||||||
daylight: (world.day_time.rem_euclid(24000)) < 12000,
|
daylight: (world.day_time.rem_euclid(24000)) < 12000,
|
||||||
game_time: world.game_time,
|
game_time: world.game_time,
|
||||||
day_time: world.day_time,
|
day_time: world.day_time,
|
||||||
|
|||||||
@@ -390,6 +390,7 @@ impl Game<'_> {
|
|||||||
player,
|
player,
|
||||||
others,
|
others,
|
||||||
others_grid: None,
|
others_grid: None,
|
||||||
|
others_index: None,
|
||||||
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
|
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
|
||||||
game_time: self.world.game_time,
|
game_time: self.world.game_time,
|
||||||
day_time: self.world.day_time,
|
day_time: self.world.day_time,
|
||||||
@@ -402,7 +403,7 @@ impl Game<'_> {
|
|||||||
end: self.dim == Dim::End,
|
end: self.dim == Dim::End,
|
||||||
world_seed: self.level.seed,
|
world_seed: self.level.seed,
|
||||||
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
|
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
|
||||||
teams: self.mob_teams(),
|
teams: std::sync::Arc::new(self.mob_teams()),
|
||||||
items: Some(self.res.items()),
|
items: Some(self.res.items()),
|
||||||
difficulty: self.local_difficulty(
|
difficulty: self.local_difficulty(
|
||||||
self.player
|
self.player
|
||||||
@@ -503,9 +504,22 @@ impl Game<'_> {
|
|||||||
let mut keep = Vec::with_capacity(mobs.len());
|
let mut keep = Vec::with_capacity(mobs.len());
|
||||||
let mut grid =
|
let mut grid =
|
||||||
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
|
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
|
||||||
|
// All but the snapshot is the same for every mob of the tick, so
|
||||||
|
// build it once: the player view and the teams scan every UUID.
|
||||||
|
let base = self.mob_world_base(&[]);
|
||||||
|
// Each mob keeps its snapshot slot all tick; the first slot of an
|
||||||
|
// id answers, as a scan would.
|
||||||
|
let mut index = horizon_client::fast_hash::FxHashMap::<u32, u32>::default();
|
||||||
|
for (i, s) in snapshot.iter().enumerate() {
|
||||||
|
index.entry(s.id).or_insert(i as u32);
|
||||||
|
}
|
||||||
for i in 0..mobs.len() {
|
for i in 0..mobs.len() {
|
||||||
let mut w = self.mob_world_base(&snapshot);
|
let mut w = MobWorld {
|
||||||
w.others_grid = Some(&grid);
|
others: &snapshot,
|
||||||
|
others_grid: Some(&grid),
|
||||||
|
others_index: Some(&index),
|
||||||
|
..base.clone()
|
||||||
|
};
|
||||||
let m = &mut mobs[i];
|
let m = &mut mobs[i];
|
||||||
w.nearest_player = super::natural_spawning::nearest_player(
|
w.nearest_player = super::natural_spawning::nearest_player(
|
||||||
&players,
|
&players,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use horizon_client::{
|
|||||||
mobs::{
|
mobs::{
|
||||||
Mob, MobWorld, Species,
|
Mob, MobWorld, Species,
|
||||||
data::{self, MobData},
|
data::{self, MobData},
|
||||||
|
seen_grid::SeenGrid,
|
||||||
spawn_rules::{Dimension, SpawnLevel},
|
spawn_rules::{Dimension, SpawnLevel},
|
||||||
spawn_selection::{
|
spawn_selection::{
|
||||||
self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest,
|
self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest,
|
||||||
@@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> {
|
|||||||
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
|
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
|
||||||
/// The types and boxes of what a spawner created this tick.
|
/// The types and boxes of what a spawner created this tick.
|
||||||
pub(super) pending_ids: std::cell::RefCell<Vec<(String, Aabb)>>,
|
pub(super) pending_ids: std::cell::RefCell<Vec<(String, Aabb)>>,
|
||||||
|
/// The game's mobs by box, built once a pass has asked more than
|
||||||
|
/// [`SCANNED_QUERIES`] box queries (the mobs do not change while it
|
||||||
|
/// holds the game); the first ones scan, as the build costs a few scans.
|
||||||
|
pub(super) boxes: std::cell::OnceCell<MobBoxes>,
|
||||||
|
pub(super) box_queries: std::cell::Cell<u32>,
|
||||||
|
}
|
||||||
|
const SCANNED_QUERIES: u32 = 8;
|
||||||
|
/// A mob not removed: its index in `Game::mobs`, box, alive, and whether
|
||||||
|
/// it is a living shulker.
|
||||||
|
type MobBox = (usize, Aabb, bool, bool);
|
||||||
|
fn mob_box(i: usize, m: &Mob) -> MobBox {
|
||||||
|
let alive = m.alive();
|
||||||
|
(
|
||||||
|
i,
|
||||||
|
m.bounds(),
|
||||||
|
alive,
|
||||||
|
alive && m.species() == Species::Shulker,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/// The boxes of the game's mobs not removed, and a grid over them.
|
||||||
|
pub(super) struct MobBoxes {
|
||||||
|
entries: Vec<MobBox>,
|
||||||
|
grid: SeenGrid,
|
||||||
|
}
|
||||||
|
impl MobBoxes {
|
||||||
|
fn new(mobs: &[Mob]) -> Self {
|
||||||
|
let entries: Vec<_> = mobs
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, m)| !m.removed)
|
||||||
|
.map(|(i, m)| mob_box(i, m))
|
||||||
|
.collect();
|
||||||
|
let grid = SeenGrid::new(entries.iter().map(|e| e.1));
|
||||||
|
Self { entries, grid }
|
||||||
|
}
|
||||||
|
/// The entries whose boxes meet `area` (and possibly a few more).
|
||||||
|
fn near(&self, area: Aabb) -> impl Iterator<Item = MobBox> + '_ {
|
||||||
|
let mut near = Vec::new();
|
||||||
|
let indexed = self.grid.candidates(area, &mut near);
|
||||||
|
let all = (!indexed).then(|| self.entries.iter());
|
||||||
|
near.into_iter()
|
||||||
|
.map(|i| self.entries[i as usize])
|
||||||
|
.chain(all.into_iter().flatten().copied())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
impl GameLevel<'_, '_> {
|
impl GameLevel<'_, '_> {
|
||||||
|
/// The mobs not removed whose boxes may meet `area` (callers test them).
|
||||||
|
fn mobs_near(&self, area: Aabb) -> Box<dyn Iterator<Item = MobBox> + '_> {
|
||||||
|
let asked = self.box_queries.get() + 1;
|
||||||
|
self.box_queries.set(asked);
|
||||||
|
if asked <= SCANNED_QUERIES && self.boxes.get().is_none() {
|
||||||
|
return Box::new(
|
||||||
|
self.game
|
||||||
|
.mobs
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, m)| !m.removed)
|
||||||
|
.map(|(i, m)| mob_box(i, m)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Box::new(
|
||||||
|
self.boxes
|
||||||
|
.get_or_init(|| MobBoxes::new(&self.game.mobs))
|
||||||
|
.near(area),
|
||||||
|
)
|
||||||
|
}
|
||||||
fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> {
|
fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> {
|
||||||
let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?;
|
let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?;
|
||||||
Some(self.game.res.biomes().get(chunk.biome(x, y, z)))
|
Some(self.game.res.biomes().get(chunk.biome(x, y, z)))
|
||||||
@@ -224,12 +289,9 @@ impl NaturalLevel for GameLevel<'_, '_> {
|
|||||||
// getEntityCollisions(null, box): living shulkers are solid.
|
// getEntityCollisions(null, box): living shulkers are solid.
|
||||||
let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7));
|
let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7));
|
||||||
no_collision_empty(&mut scene, bounds)
|
no_collision_empty(&mut scene, bounds)
|
||||||
&& !self.game.mobs.iter().any(|m| {
|
&& !self
|
||||||
m.species() == Species::Shulker
|
.mobs_near(grown)
|
||||||
&& m.alive()
|
.any(|(_, b, _, shulker)| shulker && b.intersects(grown))
|
||||||
&& !m.removed
|
|
||||||
&& m.bounds().intersects(grown)
|
|
||||||
})
|
|
||||||
&& !self
|
&& !self
|
||||||
.pending_ids
|
.pending_ids
|
||||||
.borrow()
|
.borrow()
|
||||||
@@ -244,10 +306,8 @@ impl NaturalLevel for GameLevel<'_, '_> {
|
|||||||
!player
|
!player
|
||||||
&& !self.pending.borrow().iter().any(|b| b.intersects(bounds))
|
&& !self.pending.borrow().iter().any(|b| b.intersects(bounds))
|
||||||
&& !self
|
&& !self
|
||||||
.game
|
.mobs_near(bounds)
|
||||||
.mobs
|
.any(|(_, b, alive, _)| alive && b.intersects(bounds))
|
||||||
.iter()
|
|
||||||
.any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds))
|
|
||||||
}
|
}
|
||||||
fn spawn_mobs(&self) -> bool {
|
fn spawn_mobs(&self) -> bool {
|
||||||
self.game.ui.rules.bool("spawn_mobs")
|
self.game.ui.rules.bool("spawn_mobs")
|
||||||
@@ -289,10 +349,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> {
|
|||||||
}
|
}
|
||||||
fn count_entities(&self, id: &str, bounds: Aabb) -> usize {
|
fn count_entities(&self, id: &str, bounds: Aabb) -> usize {
|
||||||
let mobs = self
|
let mobs = self
|
||||||
.game
|
.mobs_near(bounds)
|
||||||
.mobs
|
.filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds))
|
||||||
.iter()
|
|
||||||
.filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds))
|
|
||||||
.count();
|
.count();
|
||||||
let pending = self
|
let pending = self
|
||||||
.pending_ids
|
.pending_ids
|
||||||
@@ -311,6 +369,8 @@ impl<'a> Game<'a> {
|
|||||||
players: self.level_players(),
|
players: self.level_players(),
|
||||||
pending: Default::default(),
|
pending: Default::default(),
|
||||||
pending_ids: Default::default(),
|
pending_ids: Default::default(),
|
||||||
|
boxes: Default::default(),
|
||||||
|
box_queries: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Creates a mob the spawner accepted, finalized the game's way; the
|
/// Creates a mob the spawner accepted, finalized the game's way; the
|
||||||
|
|||||||
@@ -431,20 +431,18 @@ impl Game<'_> {
|
|||||||
self.score.board.players_team(self.acting_player_name())
|
self.score.board.players_team(self.acting_player_name())
|
||||||
}
|
}
|
||||||
/// The teams of the player and of the mobs on one (empty without teams).
|
/// The teams of the player and of the mobs on one (empty without teams).
|
||||||
pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams {
|
pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> {
|
||||||
let board = &self.score.board;
|
let board = &self.score.board;
|
||||||
if board.teams.is_empty() {
|
if board.teams.is_empty() {
|
||||||
return Default::default();
|
return Default::default();
|
||||||
}
|
}
|
||||||
horizon_client::mobs::Teams {
|
horizon_client::mobs::Teams {
|
||||||
player: self.player_team().cloned(),
|
player: self.player_team(),
|
||||||
mobs: self
|
mobs: self
|
||||||
.persist
|
.persist
|
||||||
.uuids
|
.uuids
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|(id, uuid)| {
|
.filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?)))
|
||||||
Some((*id, board.players_team(&uuid_text(*uuid))?.clone()))
|
|
||||||
})
|
|
||||||
.collect(),
|
.collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1406,6 +1406,7 @@ pub struct PlayerView {
|
|||||||
/// (`EntitySelector.pushableBy` on the client).
|
/// (`EntitySelector.pushableBy` on the client).
|
||||||
pub remote: bool,
|
pub remote: bool,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct MobWorld<'a> {
|
pub struct MobWorld<'a> {
|
||||||
pub world: &'a World,
|
pub world: &'a World,
|
||||||
pub registry: &'a horizon_world::registry::BlockRegistry,
|
pub registry: &'a horizon_world::registry::BlockRegistry,
|
||||||
@@ -1420,6 +1421,8 @@ pub struct MobWorld<'a> {
|
|||||||
pub others: &'a [Seen],
|
pub others: &'a [Seen],
|
||||||
/// `others` by position, when the caller keeps one (the mob ticks).
|
/// `others` by position, when the caller keeps one (the mob ticks).
|
||||||
pub others_grid: Option<&'a seen_grid::SeenGrid>,
|
pub others_grid: Option<&'a seen_grid::SeenGrid>,
|
||||||
|
/// Where each id stands in `others`, when the caller keeps one.
|
||||||
|
pub others_index: Option<&'a crate::fast_hash::FxHashMap<u32, u32>>,
|
||||||
pub daylight: bool,
|
pub daylight: bool,
|
||||||
pub game_time: i64,
|
pub game_time: i64,
|
||||||
pub day_time: i64,
|
pub day_time: i64,
|
||||||
@@ -1438,22 +1441,23 @@ pub struct MobWorld<'a> {
|
|||||||
pub world_seed: i64,
|
pub world_seed: i64,
|
||||||
/// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world).
|
/// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world).
|
||||||
pub sea_level: i32,
|
pub sea_level: i32,
|
||||||
/// The scoreboard teams of the player and the mobs (collision rules).
|
/// The scoreboard teams of the player and the mobs (collision rules),
|
||||||
pub teams: Teams,
|
/// shared: the mob ticks build them once a tick, not once a mob.
|
||||||
|
pub teams: std::sync::Arc<Teams<'a>>,
|
||||||
/// Item data (max stack sizes), when the host has it.
|
/// Item data (max stack sizes), when the host has it.
|
||||||
pub items: Option<&'a crate::items::Items>,
|
pub items: Option<&'a crate::items::Items>,
|
||||||
}
|
}
|
||||||
/// `Entity.getTeam` of the player and of the mobs on a team.
|
/// `Entity.getTeam` of the player and of the mobs on a team.
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
pub struct Teams {
|
pub struct Teams<'a> {
|
||||||
pub player: Option<crate::scoreboard::Team>,
|
pub player: Option<&'a crate::scoreboard::Team>,
|
||||||
pub mobs: HashMap<u32, crate::scoreboard::Team>,
|
pub mobs: HashMap<u32, &'a crate::scoreboard::Team>,
|
||||||
}
|
}
|
||||||
impl Teams {
|
impl<'a> Teams<'a> {
|
||||||
pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> {
|
pub fn of(&self, who: Who) -> Option<&'a crate::scoreboard::Team> {
|
||||||
match who {
|
match who {
|
||||||
Who::Player => self.player.as_ref(),
|
Who::Player => self.player,
|
||||||
Who::Mob(id) => self.mobs.get(&id),
|
Who::Mob(id) => self.mobs.get(&id).copied(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2139,3 +2143,286 @@ mod elytra_tests {
|
|||||||
assert!((wings.angles[1] - 0.08726646).abs() < 0.00001);
|
assert!((wings.angles[1] - 0.08726646).abs() < 0.00001);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
mod teams_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::save::uuid_text;
|
||||||
|
use crate::scoreboard::{Scoreboard, Team};
|
||||||
|
|
||||||
|
/// A board where every other mob is on the player's team, as with a
|
||||||
|
/// datapack that colours its mobs' names.
|
||||||
|
fn board(mobs: u32) -> (Scoreboard, HashMap<u32, [i32; 4]>) {
|
||||||
|
let mut board = Scoreboard::default();
|
||||||
|
board.add_team("red");
|
||||||
|
board.add_to_team("Steve", "red");
|
||||||
|
let uuids: HashMap<u32, [i32; 4]> = (0..mobs)
|
||||||
|
.map(|id| (id, [id as i32, 7, -(id as i32), 11]))
|
||||||
|
.collect();
|
||||||
|
for (id, uuid) in &uuids {
|
||||||
|
if id % 2 == 0 {
|
||||||
|
board.add_to_team(&uuid_text(*uuid), "red");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(board, uuids)
|
||||||
|
}
|
||||||
|
/// `Game::mob_teams` as built for each mob before: owned clones of the teams.
|
||||||
|
fn owned(board: &Scoreboard, uuids: &HashMap<u32, [i32; 4]>) -> HashMap<u32, Team> {
|
||||||
|
uuids
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?.clone())))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
fn borrowed<'a>(board: &'a Scoreboard, uuids: &HashMap<u32, [i32; 4]>) -> Teams<'a> {
|
||||||
|
Teams {
|
||||||
|
player: board.players_team("Steve"),
|
||||||
|
mobs: uuids
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?)))
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn borrowed_teams_answer_as_the_clones() {
|
||||||
|
let (board, uuids) = board(40);
|
||||||
|
let teams = borrowed(&board, &uuids);
|
||||||
|
let old = owned(&board, &uuids);
|
||||||
|
for id in 0..41 {
|
||||||
|
assert_eq!(teams.of(Who::Mob(id)), old.get(&id), "mob {id}");
|
||||||
|
}
|
||||||
|
assert_eq!(teams.of(Who::Player).map(|t| t.name.as_str()), Some("red"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One tick's worth of team building: once per mob (before) against once.
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn teams_cost() {
|
||||||
|
for mobs in [100u32, 250, 500] {
|
||||||
|
let (board, uuids) = board(mobs);
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
for _ in 0..mobs {
|
||||||
|
std::hint::black_box(owned(&board, &uuids));
|
||||||
|
}
|
||||||
|
let before = t.elapsed();
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let reps = 20;
|
||||||
|
for _ in 0..reps {
|
||||||
|
std::hint::black_box(borrowed(&board, &uuids));
|
||||||
|
}
|
||||||
|
let after = t.elapsed() / reps;
|
||||||
|
println!(
|
||||||
|
"{mobs} mobs, half on a team: per tick {:.3} ms -> {:.3} ms",
|
||||||
|
before.as_secs_f64() * 1e3,
|
||||||
|
after.as_secs_f64() * 1e3
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
mod sensor_scan_tests {
|
||||||
|
use super::*;
|
||||||
|
use horizon_core::geometry::Vec3;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn kind() -> Arc<MobType> {
|
||||||
|
Arc::new(MobType {
|
||||||
|
id: "minecraft:cow".into(),
|
||||||
|
species: Species::Cow,
|
||||||
|
width: 0.9,
|
||||||
|
height: 1.4,
|
||||||
|
eye_height: 1.3,
|
||||||
|
category: "creature".into(),
|
||||||
|
max_health: 10.0,
|
||||||
|
speed: 0.2,
|
||||||
|
flying_speed: 0.4,
|
||||||
|
attack_damage: 0.0,
|
||||||
|
attack_knockback: 0.0,
|
||||||
|
follow_range: 16.0,
|
||||||
|
step_height: 0.6,
|
||||||
|
armor: 0.0,
|
||||||
|
armor_toughness: 0.0,
|
||||||
|
knockback_resistance: 0.0,
|
||||||
|
jump_strength: 0.42,
|
||||||
|
attributes: Arc::default(),
|
||||||
|
gravity: 0.08,
|
||||||
|
safe_fall_distance: 3.0,
|
||||||
|
fall_damage_multiplier: 1.0,
|
||||||
|
water_efficiency: 0.0,
|
||||||
|
water_slowdown: 0.8,
|
||||||
|
air_speed: 0.02,
|
||||||
|
baby_scale: 0.5,
|
||||||
|
head_rot_speed: 10.0,
|
||||||
|
max_head_x_rot: 40.0,
|
||||||
|
max_head_y_rot: 75.0,
|
||||||
|
ambient_interval: 120,
|
||||||
|
flags: Flags {
|
||||||
|
animal: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
model: Arc::new(Part::parse("root", &json!({}))),
|
||||||
|
layers: HashMap::new(),
|
||||||
|
texture: String::new(),
|
||||||
|
brain: Brain::Passive,
|
||||||
|
anim: Anim::Rabbit,
|
||||||
|
sounds: [""; 3],
|
||||||
|
step_sound: None,
|
||||||
|
food: Arc::default(),
|
||||||
|
tempt: Arc::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// `n` mobs in pens of 20 spread over a square of `side` blocks, as on a
|
||||||
|
/// server's farms; their snapshot and its grid.
|
||||||
|
fn herd(n: u32, side: f64) -> (Vec<Seen>, seen_grid::SeenGrid) {
|
||||||
|
let kind = kind();
|
||||||
|
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
||||||
|
let mut next = |range: f64| {
|
||||||
|
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
|
||||||
|
(seed >> 11) as f64 / (1u64 << 53) as f64 * range
|
||||||
|
};
|
||||||
|
let mut pen = Vec3::ZERO;
|
||||||
|
let seen: Vec<Seen> = (0..n)
|
||||||
|
.map(|id| {
|
||||||
|
if id % 20 == 0 {
|
||||||
|
pen = Vec3::new(next(side), 64.0, next(side));
|
||||||
|
}
|
||||||
|
let at = Vec3::new(pen.x + next(8.0), 64.0, pen.z + next(8.0));
|
||||||
|
Mob::new(id, kind.clone(), at, 0.0).seen(None)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let grid = seen_grid::SeenGrid::new(seen.iter().map(|s| s.bounds));
|
||||||
|
(seen, grid)
|
||||||
|
}
|
||||||
|
/// `NearestLivingEntitySensor` over every mob, as the brains ran it.
|
||||||
|
fn scan(seen: &[Seen], me: &Seen, area: Aabb) -> Vec<u32> {
|
||||||
|
seen.iter()
|
||||||
|
.filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area))
|
||||||
|
.map(|o| o.id)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
fn indexed(seen: &[Seen], grid: &seen_grid::SeenGrid, me: &Seen, area: Aabb) -> Vec<u32> {
|
||||||
|
let mut near = Vec::new();
|
||||||
|
assert!(grid.candidates(area, &mut near));
|
||||||
|
near.iter()
|
||||||
|
.map(|&i| &seen[i as usize])
|
||||||
|
.filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area))
|
||||||
|
.map(|o| o.id)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_grid_finds_what_the_scan_finds() {
|
||||||
|
let (seen, grid) = herd(600, 160.0);
|
||||||
|
for me in &seen {
|
||||||
|
let area = me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0));
|
||||||
|
assert_eq!(indexed(&seen, &grid, me, area), scan(&seen, me, area));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `MobWorld::seen` once per mob (a target, a breeding partner...), by
|
||||||
|
/// scan as before and by the tick's id index.
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn lookup_cost() {
|
||||||
|
for n in [500u32, 1000, 2000] {
|
||||||
|
let (seen, _) = herd(n, 256.0);
|
||||||
|
let index: crate::fast_hash::FxHashMap<u32, u32> = seen
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, s)| (s.id, i as u32))
|
||||||
|
.collect();
|
||||||
|
let wanted: Vec<u32> = (0..n).map(|i| (i * 7919) % n).collect();
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let a: usize = wanted
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&id| seen.iter().find(|s| s.id == id))
|
||||||
|
.map(|s| s.id as usize)
|
||||||
|
.sum();
|
||||||
|
let before = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let b: usize = wanted
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&id| index.get(&id).map(|&i| &seen[i as usize]))
|
||||||
|
.map(|s| s.id as usize)
|
||||||
|
.sum();
|
||||||
|
let after = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
assert_eq!(a, b);
|
||||||
|
println!(
|
||||||
|
"{n} lookups over {n} mobs ({} B each): {before:.3} ms -> {after:.3} ms",
|
||||||
|
std::mem::size_of::<Seen>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Natural spawning's `isUnobstructed` box test against every mob (real
|
||||||
|
/// `Mob`s), by scan and by a grid built once for the pass.
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn spawn_box_cost() {
|
||||||
|
let kind = kind();
|
||||||
|
for n in [500u32, 1000, 2000] {
|
||||||
|
let (seen, _) = herd(n, 384.0);
|
||||||
|
let mobs: Vec<Mob> = seen
|
||||||
|
.iter()
|
||||||
|
.map(|s| Mob::new(s.id, kind.clone(), s.position, 0.0))
|
||||||
|
.collect();
|
||||||
|
let mut seed = 7u64;
|
||||||
|
let mut next = |range: f64| {
|
||||||
|
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
|
||||||
|
(seed >> 11) as f64 / (1u64 << 53) as f64 * range
|
||||||
|
};
|
||||||
|
let queries: Vec<Aabb> = (0..100)
|
||||||
|
.map(|_| {
|
||||||
|
let (x, z) = (next(384.0), next(384.0));
|
||||||
|
Aabb::new(Vec3::new(x, 64.0, z), Vec3::new(x + 0.9, 65.4, z + 0.9))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let a: Vec<bool> = queries
|
||||||
|
.iter()
|
||||||
|
.map(|&q| {
|
||||||
|
mobs.iter()
|
||||||
|
.any(|m| m.alive() && !m.removed && m.bounds().intersects(q))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let before = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let boxes: Vec<Aabb> = mobs.iter().map(|m| m.bounds()).collect();
|
||||||
|
let grid = seen_grid::SeenGrid::new(boxes.iter().copied());
|
||||||
|
let build = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
let mut near = Vec::new();
|
||||||
|
let b: Vec<bool> = queries
|
||||||
|
.iter()
|
||||||
|
.map(|&q| {
|
||||||
|
assert!(grid.candidates(q, &mut near));
|
||||||
|
near.iter().any(|&i| boxes[i as usize].intersects(q))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let after = t.elapsed().as_secs_f64() * 1e3;
|
||||||
|
assert_eq!(a, b);
|
||||||
|
println!(
|
||||||
|
"{n} mobs, 100 spawn box tests: {before:.3} ms -> {after:.3} ms (grid build {build:.3} ms included)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One tick of sensing: a twentieth of the mobs fire their sensor.
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn sensor_cost() {
|
||||||
|
for (n, side) in [(500u32, 256.0), (1000, 384.0), (2000, 512.0)] {
|
||||||
|
let (seen, grid) = herd(n, side);
|
||||||
|
let time = |f: &dyn Fn(&Seen, Aabb) -> usize| {
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let mut found = 0;
|
||||||
|
for me in &seen {
|
||||||
|
found += f(me, me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0)));
|
||||||
|
}
|
||||||
|
(t.elapsed().as_secs_f64() * 1e3 / 20.0, found)
|
||||||
|
};
|
||||||
|
let (before, a) = time(&|me, area| scan(&seen, me, area).len());
|
||||||
|
let (after, b) = time(&|me, area| indexed(&seen, &grid, me, area).len());
|
||||||
|
assert_eq!(a, b);
|
||||||
|
println!("{n} mobs: per tick {before:.3} ms -> {after:.3} ms");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -606,7 +606,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) {
|
|||||||
let r = m.attrs.follow_range;
|
let r = m.attrs.follow_range;
|
||||||
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
||||||
let mut found: Vec<(Who, f64)> = Vec::new();
|
let mut found: Vec<(Who, f64)> = Vec::new();
|
||||||
for o in w.others {
|
for o in w.others_near(area) {
|
||||||
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
||||||
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -441,7 +441,7 @@ impl Goal for PufferfishPuff {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds));
|
.is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds));
|
||||||
// TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive.
|
// TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive.
|
||||||
let mob = cx.w.others.iter().any(|s| {
|
let mob = cx.w.others_near(area).any(|s| {
|
||||||
s.id != m.id
|
s.id != m.id
|
||||||
&& s.alive
|
&& s.alive
|
||||||
&& !matches!(
|
&& !matches!(
|
||||||
|
|||||||
@@ -391,12 +391,11 @@ impl Goal for LeaveBlock {
|
|||||||
let target = cx.w.world.block(x, y, z);
|
let target = cx.w.world.block(x, y, z);
|
||||||
let below = cx.w.world.block(x, y - 1, z);
|
let below = cx.w.world.block(x, y - 1, z);
|
||||||
let bf = cx.w.facts.get(below);
|
let bf = cx.w.facts.get(below);
|
||||||
let free = !cx.w.others.iter().any(|s| {
|
let block = Aabb::new(
|
||||||
s.bounds.intersects(Aabb::new(
|
Vec3::new(f64::from(x), f64::from(y), f64::from(z)),
|
||||||
Vec3::new(f64::from(x), f64::from(y), f64::from(z)),
|
Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)),
|
||||||
Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)),
|
);
|
||||||
))
|
let free = !cx.w.others_near(block).any(|s| s.bounds.intersects(block));
|
||||||
});
|
|
||||||
if cx.w.facts.is_air(target)
|
if cx.w.facts.is_air(target)
|
||||||
&& !cx.w.facts.is_air(below)
|
&& !cx.w.facts.is_air(below)
|
||||||
&& &*bf.name != "minecraft:bedrock"
|
&& &*bf.name != "minecraft:bedrock"
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
//! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags,
|
//! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags,
|
||||||
//! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`.
|
//! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`.
|
||||||
use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo};
|
use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo};
|
||||||
use horizon_core::{geometry::Vec3, jmath, random::RandomSource};
|
use horizon_core::{
|
||||||
|
geometry::{Aabb, Vec3},
|
||||||
|
jmath,
|
||||||
|
random::RandomSource,
|
||||||
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub const MOVE: u8 = 1;
|
pub const MOVE: u8 = 1;
|
||||||
@@ -970,8 +974,7 @@ impl Goal for LookAtPlayer {
|
|||||||
let (id, only) = (m.id, self.only);
|
let (id, only) = (m.id, self.only);
|
||||||
let at = Vec3::new(m.position.x, m.eye_y(), m.position.z);
|
let at = Vec3::new(m.position.x, m.eye_y(), m.position.z);
|
||||||
let candidates: Vec<(u32, Vec3)> =
|
let candidates: Vec<(u32, Vec3)> =
|
||||||
cx.w.others
|
cx.w.others_near(area)
|
||||||
.iter()
|
|
||||||
.filter(|s| s.id != id && s.alive && s.bounds.intersects(area))
|
.filter(|s| s.id != id && s.alive && s.bounds.intersects(area))
|
||||||
.filter(|s| only.is_none_or(|o| s.species == o))
|
.filter(|s| only.is_none_or(|o| s.species == o))
|
||||||
.map(|s| (s.id, s.position))
|
.map(|s| (s.id, s.position))
|
||||||
@@ -1902,7 +1905,12 @@ impl Goal for FollowParent {
|
|||||||
let species = m.species();
|
let species = m.species();
|
||||||
let pos = m.position;
|
let pos = m.position;
|
||||||
let mut best: Option<(u32, f64)> = None;
|
let mut best: Option<(u32, f64)> = None;
|
||||||
for s in cx.w.others.iter().filter(|s| {
|
// Every position in range puts the box's bottom face in this area.
|
||||||
|
let area = Aabb::new(
|
||||||
|
Vec3::new(pos.x - 9.0, pos.y - 5.0, pos.z - 9.0),
|
||||||
|
Vec3::new(pos.x + 9.0, pos.y + 5.0, pos.z + 9.0),
|
||||||
|
);
|
||||||
|
for s in cx.w.others_near(area).filter(|s| {
|
||||||
s.alive
|
s.alive
|
||||||
&& s.species == species
|
&& s.species == species
|
||||||
&& !s.baby
|
&& !s.baby
|
||||||
|
|||||||
@@ -68,7 +68,10 @@ impl Goal for DefendVillage {
|
|||||||
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
|
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let bad = cx.w.others.iter().any(|s| {
|
// A position inside `b` puts the box's bottom face there (one block
|
||||||
|
// wider, as the box test is strict).
|
||||||
|
let near = b.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||||
|
let bad = cx.w.others_near(near).any(|s| {
|
||||||
s.species == Species::Villager
|
s.species == Species::Villager
|
||||||
&& s.alive
|
&& s.alive
|
||||||
&& s.player_rep <= -100
|
&& s.player_rep <= -100
|
||||||
|
|||||||
@@ -299,7 +299,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) {
|
|||||||
let r = m.attrs.follow_range;
|
let r = m.attrs.follow_range;
|
||||||
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
||||||
let mut found: Vec<(Who, f64)> = Vec::new();
|
let mut found: Vec<(Who, f64)> = Vec::new();
|
||||||
for o in w.others {
|
for o in w.others_near(area) {
|
||||||
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
||||||
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
|||||||
velocity: fling(p.position),
|
velocity: fling(p.position),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
for s in w.others.iter() {
|
for s in w.others_near(area) {
|
||||||
if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) {
|
if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -568,7 +568,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) {
|
|||||||
let r = m.attrs.follow_range;
|
let r = m.attrs.follow_range;
|
||||||
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
||||||
let mut found: Vec<(Who, f64)> = Vec::new();
|
let mut found: Vec<(Who, f64)> = Vec::new();
|
||||||
for o in w.others {
|
for o in w.others_near(area) {
|
||||||
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
||||||
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -492,7 +492,7 @@ fn sense_entities(m: &mut Mob, w: &MobWorld) {
|
|||||||
let r = m.attrs.follow_range;
|
let r = m.attrs.follow_range;
|
||||||
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
let area = m.bounds().inflate(Vec3::new(r, r, r));
|
||||||
let mut found: Vec<(Who, f64)> = Vec::new();
|
let mut found: Vec<(Who, f64)> = Vec::new();
|
||||||
for o in w.others {
|
for o in w.others_near(area) {
|
||||||
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
if o.id != m.id && o.alive && o.bounds.intersects(area) {
|
||||||
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -226,7 +226,13 @@ impl MobWorld<'_> {
|
|||||||
.chain(all.into_iter().flatten())
|
.chain(all.into_iter().flatten())
|
||||||
}
|
}
|
||||||
pub fn seen(&self, id: u32) -> Option<&Seen> {
|
pub fn seen(&self, id: u32) -> Option<&Seen> {
|
||||||
self.others.iter().find(|s| s.id == id)
|
match self.others_index {
|
||||||
|
Some(index) => index
|
||||||
|
.get(&id)
|
||||||
|
.and_then(|&i| self.others.get(i as usize))
|
||||||
|
.filter(|s| s.id == id),
|
||||||
|
None => self.others.iter().find(|s| s.id == id),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/// Living mobs of the given species within `range` of `from`, nearest first.
|
/// Living mobs of the given species within `range` of `from`, nearest first.
|
||||||
pub fn nearby<'s>(
|
pub fn nearby<'s>(
|
||||||
@@ -235,9 +241,15 @@ impl MobWorld<'_> {
|
|||||||
range: f64,
|
range: f64,
|
||||||
pred: impl Fn(&Seen) -> bool + 's,
|
pred: impl Fn(&Seen) -> bool + 's,
|
||||||
) -> impl Iterator<Item = &'s Seen> + 's {
|
) -> impl Iterator<Item = &'s Seen> + 's {
|
||||||
|
// A position within `range` puts the box's bottom face in this area
|
||||||
|
// (one block wider, as the box test is strict).
|
||||||
|
let r = range + 1.0;
|
||||||
|
let area = Aabb::new(
|
||||||
|
Vec3::new(from.x - r, from.y - r, from.z - r),
|
||||||
|
Vec3::new(from.x + r, from.y + r, from.z + r),
|
||||||
|
);
|
||||||
let mut v: Vec<&Seen> = self
|
let mut v: Vec<&Seen> = self
|
||||||
.others
|
.others_near(area)
|
||||||
.iter()
|
|
||||||
.filter(|s| {
|
.filter(|s| {
|
||||||
s.alive
|
s.alive
|
||||||
&& (s.position.x - from.x).abs() <= range
|
&& (s.position.x - from.x).abs() <= range
|
||||||
|
|||||||
Reference in New Issue
Block a user