diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 4870216cd..777e90054 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -68,6 +68,8 @@ pub enum BlockEntity { Crafter(Crafter), /// `SpawnerBlockEntity` (`crate::mobs::spawner`). Spawner(Box), + /// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`). + TrialSpawner(Box), /// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`). Beehive(Box), } @@ -187,6 +189,9 @@ impl BlockEntity { if name == "minecraft:spawner" { return Some(Self::Spawner(Box::default())); } + if name == "minecraft:trial_spawner" { + return Some(Self::TrialSpawner(Box::default())); + } if name == "minecraft:beehive" || name == "minecraft:bee_nest" { return Some(Self::Beehive(Box::default())); } @@ -266,6 +271,7 @@ impl BlockEntity { Self::Crafter(_) => "minecraft:crafter", Self::CreakingHeart(_) => "minecraft:creaking_heart", Self::Spawner(_) => "minecraft:mob_spawner", + Self::TrialSpawner(_) => "minecraft:trial_spawner", Self::Beehive(_) => "minecraft:beehive", } } @@ -276,9 +282,11 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => { - Vec::new() - } + Self::Beacon(_) + | Self::CreakingHeart(_) + | Self::Spawner(_) + | Self::TrialSpawner(_) + | Self::Beehive(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -297,7 +305,10 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &[], Self::Crafter(c) => &c.items, - Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &[], + Self::CreakingHeart(_) + | Self::Spawner(_) + | Self::TrialSpawner(_) + | Self::Beehive(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -312,7 +323,10 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &mut [], Self::Crafter(c) => &mut c.items, - Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &mut [], + Self::CreakingHeart(_) + | Self::Spawner(_) + | Self::TrialSpawner(_) + | Self::Beehive(_) => &mut [], } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a329311c7..d9a169a09 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -116,6 +116,7 @@ mod titles; mod tnt; mod totem; mod trading; +mod trial_spawner; mod trident; mod villagers; mod wandering_trader; @@ -3826,6 +3827,7 @@ impl Game<'_> { | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) | BlockEntity::Spawner(_) + | BlockEntity::TrialSpawner(_) | BlockEntity::Beehive(_), ) => {} None => { @@ -4076,6 +4078,7 @@ impl Game<'_> { | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) | BlockEntity::Spawner(_) + | BlockEntity::TrialSpawner(_) | BlockEntity::Beehive(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), @@ -5587,6 +5590,7 @@ impl Game<'_> { self.tick_beacons(); self.tick_creaking_hearts()?; self.tick_spawners()?; + self.tick_trial_spawners()?; self.tick_beehives(); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { @@ -9350,6 +9354,7 @@ pub fn run() -> Result<()> { log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); let facts = BlockFacts::load(&root, assets.registry)?; let mob_data = horizon_client::mobs::MobData::load(&root, &facts); + horizon_client::mobs::trial_spawner::load_registry(&root); log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32()); let items = Items::load(&root, assets.registry, &facts)?; log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 83d7ddfb3..0992bac02 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -26,7 +26,7 @@ use std::collections::HashMap; /// The game level as natural spawning reads it. pub(super) struct GameLevel<'g, 'a> { pub(super) game: &'g Game<'a>, - w: MobWorld<'g>, + pub(super) w: MobWorld<'g>, /// Boxes of the mobs this pass created, not yet in the game's list. pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index ef61d58ee..30b8cc67b 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -20,7 +20,7 @@ use std::collections::{HashMap, HashSet}; type Pos = (i32, i32, i32); /// What a spawner tick decided to add, created once the level is free. -enum Planned { +pub(super) enum Planned { /// `finalizeSpawn` ran on a fresh mob. Finalized(Mob), /// A mob loaded from the spawn data (with its passengers). @@ -113,7 +113,12 @@ impl Game<'_> { spawner.server_tick(&level, &mut random, pos, &mut spawn, &mut events); } self.world.random = random; - // Provisional ids (counting down from u32::MAX) become the mobs' ids. + let ids = self.add_planned(planned); + self.apply_spawner_events(key, events, &ids) + } + /// Creates the mobs a spawner tick planned; their provisional ids + /// (counting down from u32::MAX) map to the mobs' ids. + pub(super) fn add_planned(&mut self, planned: Vec) -> HashMap { let mut ids = HashMap::new(); for (i, plan) in planned.into_iter().enumerate() { let provisional = u32::MAX - i as u32; @@ -133,11 +138,11 @@ impl Game<'_> { ids.insert(provisional, id); } } - self.apply_spawner_events(key, events, &ids) + ids } /// The spawner's `loadEntityRecursive` and `tryAddFreshEntityWithPassengers`: /// the mob it will add (created after the tick) and its box. - fn plan_spawner_mob( + pub(super) fn plan_spawner_mob( &self, l: &super::natural_spawning::GameLevel, r: &SpawnerSpawn, @@ -151,6 +156,8 @@ impl Game<'_> { let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32); let difficulty = self.local_difficulty(r.position); spawning::finalize(&mut mob, &facts, &difficulty); + // TrialSpawner.spawnMob: setPersistenceRequired. + mob.persistent = r.trial; horizon_client::mobs::raider::finalize( &mut mob, horizon_client::mobs::raider::Reason::Other, @@ -187,6 +194,9 @@ impl Game<'_> { Tag::Float(0f32.to_bits()), ]), ); + if r.trial { + tag.insert("PersistenceRequired".into(), Tag::Byte(1)); + } let tag = Tag::Compound(tag); let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?; let bounds = mob.bounds(); diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs new file mode 100644 index 000000000..6427cbeb1 --- /dev/null +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -0,0 +1,230 @@ +//! Trial spawners in the game: `TrialSpawner.tickServer` for every trial +//! spawner (`mobs::trial_spawner`), the block's state as it changes, the mobs +//! it adds and the rewards it ejects. +use super::{Game, natural_spawning::GameLevel, spawner::Planned}; +use horizon_client::{ + Result, + containers::BlockEntity, + items::ItemStack, + mobs::{ + Who, + spawner::SpawnerSpawn, + trial_spawner::{ + TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState, Uuid, + }, + }, +}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::nbt::Tag; +use std::collections::HashMap; + +type Pos = (i32, i32, i32); + +impl TrialSpawnerLevel for GameLevel<'_, '_> { + fn game_time(&self) -> i64 { + self.game.world.game_time + } + fn mob_spawning(&self) -> bool { + self.game.ui.rules.bool("spawn_mobs") + } + fn players(&self) -> Vec { + let (Some(p), Some(view)) = (self.game.player.as_ref(), self.game.player_view()) else { + return Vec::new(); + }; + vec![TrialPlayer { + uuid: self.game.level.player_uuid.unwrap_or_default(), + block: [p.position.x, p.position.y, p.position.z].map(|v| v.floor() as i32), + eye: view.eye, + creative: self.game.creative, + spectator: self.game.spectator(), + }] + } + fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> { + let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + self.w.visual_hit(v(from), v(to)) + } + fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]> { + let (id, _) = self.game.persist.uuids.iter().find(|(_, u)| **u == uuid)?; + let m = self.game.mobs.iter().find(|m| m.id == *id)?; + (!m.removed && m.alive()) + .then(|| [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i32)) + } +} + +impl Game<'_> { + /// Every trial spawner's server tick. + pub(super) fn tick_trial_spawners(&mut self) -> Result<()> { + let keys: Vec = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_))) + .map(|(k, _)| *k) + .collect(); + for key in keys { + let state = self.world.block(key.0, key.1, key.2); + let Some(block) = self.res.assets.registry.state(state).cloned() else { + continue; + }; + if block.name != "minecraft:trial_spawner" { + continue; + } + let Some(BlockEntity::TrialSpawner(mut spawner)) = + self.world.block_entities.remove(&key) + else { + continue; + }; + let current = block + .properties + .get("trial_spawner_state") + .and_then(|s| TrialState::from_name(s)) + .unwrap_or_default(); + let ominous = block.properties.get("ominous").is_some_and(|v| v == "true"); + let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous); + self.world + .block_entities + .insert(key, BlockEntity::TrialSpawner(spawner)); + result?; + } + Ok(()) + } + fn server_tick_trial_spawner( + &mut self, + key: Pos, + spawner: &mut TrialSpawner, + current: TrialState, + ominous: bool, + ) -> Result<()> { + let pos = [key.0, key.1, key.2]; + let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); + let mut sequences = std::mem::take(&mut self.rand_sequences); + let mut events = Vec::new(); + let mut planned: Vec = Vec::new(); + let mut uuids: Vec<(u32, Uuid)> = Vec::new(); + let mut ejected: Vec<(ItemStack, [f64; 3])> = Vec::new(); + let next = { + let level = self.natural_level(); + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + let seed = self.level.seed; + let mut spawn = |l: &GameLevel, r: &SpawnerSpawn| { + let added = l.game.plan_spawner_mob(l, r, &mut planned)?; + let uuid = match planned.last_mut() { + Some(Planned::Loaded(Tag::Compound(tag))) => { + let tag_uuid = + horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone())); + tag_uuid.unwrap_or_else(|| { + let uuid = horizon_client::save::random_uuid(); + tag.insert("UUID".into(), Tag::IntArray(uuid.to_vec())); + uuid + }) + } + _ => horizon_client::save::random_uuid(), + }; + uuids.push((added.id, uuid)); + Some(uuid) + }; + // TrialSpawner.ejectReward: the table's items, each thrown up out + // of the spawner (DefaultDispenseItemBehavior.spawnItem, accuracy 2). + let mut eject = |table: &str, random: &mut LegacyRandom| { + let Some(loot) = &loot else { + return false; + }; + let drops = match loot.random_sequence(table) { + Some(s) => loot.roll_split(table, sequences.get(s, seed)), + None => loot.roll_split(table, random), + }; + for stack in &drops { + // The power, which only scales the direction's x and z (0 going up). + random.next_double(); + let spread = 0.017_227_5 * 2.0; + let v = [ + random.triangle(0.0, spread), + random.triangle(0.2, spread), + random.triangle(0.0, spread), + ]; + ejected.push(( + horizon_client::structure_blocks::loot_item_with_components(stack), + v, + )); + } + !drops.is_empty() + }; + spawner.server_tick( + &level, + &mut random, + pos, + current, + ominous, + &mut spawn, + &mut eject, + &mut events, + ) + }; + self.world.random = random; + self.rand_sequences = sequences; + let ids = self.add_planned(planned); + let mut by_uuid = HashMap::new(); + for (provisional, uuid) in uuids { + if let Some(id) = ids.get(&provisional) { + self.persist.uuids.insert(*id, uuid); + by_uuid.insert(uuid, *id); + } + } + let center = pos.map(|v| f64::from(v) + 0.5); + // Vec3.atBottomCenterOf(pos).relative(UP, 1.2), lowered by spawnItem. + let above = [center[0], center[1] + 0.7 - 0.125, center[2]]; + for (stack, v) in ejected { + self.spawn_item(stack, above, v, 0); + } + if next != current || ominous != spawner.is_ominous { + self.set_trial_spawner_state(key, next, spawner.is_ominous)?; + } + for event in events { + match event { + TrialEvent::BlockUpdated => self.trial_spawner_updated(key), + TrialEvent::LevelEvent(id, at, data) => self.level_event_at(id, at, data), + TrialEvent::Sound(name) => { + self.audio + .play(&format!("minecraft:{name}"), Some(center), 1.0, 1.0) + } + // Written with the state above. + TrialEvent::OminousSet(_) => {} + TrialEvent::EntityPlace(uuid, at) => { + let who = by_uuid.get(&uuid).map(|id| Who::Mob(*id)); + self.post_block_game_event("minecraft:entity_place", at, who, None); + } + } + } + Ok(()) + } + /// `setState` (and `removeOminous`): the block's state and ominous flag. + fn set_trial_spawner_state( + &mut self, + key: Pos, + state: TrialState, + ominous: bool, + ) -> Result<()> { + let current = self.world.block(key.0, key.1, key.2); + let Some(mut block) = self.res.assets.registry.state(current).cloned() else { + return Ok(()); + }; + block + .properties + .insert("trial_spawner_state".into(), state.name().into()); + block + .properties + .insert("ominous".into(), ominous.to_string()); + let id = self.res.assets.registry.resolve(&block)?; + self.level_set([key.0, key.1, key.2], id) + } + /// `markUpdated`: the clients load the new update tag. + fn trial_spawner_updated(&mut self, key: Pos) { + if let Some(log) = self.world.block_log.as_mut() { + log.push(key); + } + self.world.modified.insert((key.0 >> 4, key.2 >> 4)); + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 501de736f..9660d237e 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -527,6 +527,7 @@ pub fn encode_block_entity( } } BlockEntity::Spawner(s) => entries.extend(s.save()), + BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Beehive(h) => entries.extend(h.to_nbt()), } Tag::compound(entries) @@ -656,6 +657,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), + BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag), BlockEntity::Beehive(h) => **h = crate::beehive::Beehive::from_nbt(tag), } Some((pos, entity)) diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index ea399937e..f400522df 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -45,6 +45,27 @@ fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack { item } +/// A rolled stack as an item with its enchantments (stored ones on a +/// book), potion and ominous bottle level. +pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = loot_item(s); + for (id, level) in &s.enchantments { + let level = (*level).max(0) as u32; + if &*item.item == "minecraft:enchanted_book" { + crate::item_data::set_level(&mut item.data_mut().stored_enchantments, id, level); + } else { + item.enchant(id, level); + } + } + if let Some(potion) = &s.potion { + item = item.with_potion(potion); + } + if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { + item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); + } + item +} + /// The exploration map search an item still waits for, removed from it. pub fn take_pending_map(item: &mut ItemStack) -> Option { let data = item.extra.as_deref_mut()?; @@ -123,6 +144,9 @@ pub fn block_entities( if let BlockEntity::Spawner(s) = &mut entity { **s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone())); } + if let BlockEntity::TrialSpawner(s) = &mut entity { + **s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone())); + } if let (BlockEntity::Chest(slots), Some(table), Some(loot)) = (&mut entity, text(nbt, "LootTable"), loot) { diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 50101c577..8f5a15db4 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -79,6 +79,9 @@ impl VanillaTerrain { } } let loot = dir.parent().and_then(crate::structure_blocks::loot_data); + if let Some(root) = dir.parent() { + crate::mobs::trial_spawner::load_registry(root); + } let mut tick_blocks = Vec::with_capacity(registry.len()); let mut tick_states = Vec::new(); let mut last: Option<&str> = None;