Merge main into the LAN branch
This commit is contained in:
@@ -57,6 +57,8 @@ enum Animate {
|
||||
drag: bool,
|
||||
},
|
||||
Fire,
|
||||
/// An active sculk sensor.
|
||||
SculkSensor,
|
||||
}
|
||||
fn step(facing: &str) -> [i32; 3] {
|
||||
match facing {
|
||||
@@ -128,6 +130,11 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
drag: prop("drag").as_deref() == Some("true"),
|
||||
},
|
||||
"fire" | "soul_fire" => Animate::Fire,
|
||||
"sculk_sensor" | "calibrated_sculk_sensor"
|
||||
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
|
||||
{
|
||||
Animate::SculkSensor
|
||||
}
|
||||
_ if name.ends_with("candle_cake") && lit => Animate::CandleCake,
|
||||
_ if (name == "candle" || name.ends_with("_candle")) && lit => {
|
||||
Animate::Candles(prop("candles").and_then(|c| c.parse().ok()).unwrap_or(1))
|
||||
@@ -905,6 +912,35 @@ fn block_animate_tick(
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::SculkSensor => {
|
||||
// SculkSensorBlock.animateTick.
|
||||
let r = engine.random();
|
||||
let direction = r.next_int_bound(6).unwrap_or(0);
|
||||
// Direction.values(): down, up, north, south, west, east.
|
||||
if direction >= 2 {
|
||||
let step = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]][direction as usize - 2];
|
||||
let x = fx
|
||||
+ 0.5
|
||||
+ if step[0] == 0 {
|
||||
0.5 - r.next_double()
|
||||
} else {
|
||||
f64::from(step[0]) * 0.6
|
||||
};
|
||||
let z = fz
|
||||
+ 0.5
|
||||
+ if step[2] == 0 {
|
||||
0.5 - r.next_double()
|
||||
} else {
|
||||
f64::from(step[2]) * 0.6
|
||||
};
|
||||
let ya = f64::from(r.next_float() * 0.04);
|
||||
engine.add(
|
||||
&crate::particles::ParticleOptions::sculk_to_redstone(),
|
||||
[x, fy + 0.25, z],
|
||||
[0.0, ya, 0.0],
|
||||
);
|
||||
}
|
||||
}
|
||||
Animate::RespawnAnchor => {
|
||||
let r = engine.random();
|
||||
if next_int(r, 100) == 0 {
|
||||
|
||||
@@ -26,6 +26,9 @@ struct Voice {
|
||||
step: f64,
|
||||
left: f32,
|
||||
right: f32,
|
||||
/// The sound event and `SoundSource` index (what `/stopsound` matches).
|
||||
event: Arc<str>,
|
||||
source: usize,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Mixer {
|
||||
@@ -49,8 +52,25 @@ struct MusicTrack {
|
||||
/// Set by the decoder thread once the voice is in the mixer (or failed).
|
||||
ready: Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
/// A sound the player could have heard (`SoundEventListener.onPlaySound`):
|
||||
/// what the subtitle overlay needs.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Heard {
|
||||
/// The `subtitle` translation key of the sound event.
|
||||
pub subtitle: String,
|
||||
/// Where it played (None = relative to the listener, e.g. UI sounds).
|
||||
pub at: Option<[f64; 3]>,
|
||||
/// `SoundEngine.getRange`: infinite for relative and non-attenuated sounds.
|
||||
pub range: f32,
|
||||
pub looping: bool,
|
||||
}
|
||||
pub struct Audio {
|
||||
_stream: Option<cpal::Stream>,
|
||||
/// `subtitle` keys of `sounds.json` events.
|
||||
subtitles: HashMap<String, String>,
|
||||
/// Record `Heard` sounds (the subtitle overlay is listening).
|
||||
pub record_heard: bool,
|
||||
heard: Vec<Heard>,
|
||||
mixer: Arc<Mutex<Mixer>>,
|
||||
rate: u32,
|
||||
root: PathBuf,
|
||||
@@ -62,6 +82,8 @@ pub struct Audio {
|
||||
pub master: f32,
|
||||
music: Option<MusicTrack>,
|
||||
next_tracked: u64,
|
||||
/// A `SoundSource` index the next sound plays on (`/playsound`).
|
||||
source_override: Option<usize>,
|
||||
}
|
||||
fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
|
||||
use symphonia::core::{
|
||||
@@ -108,6 +130,7 @@ fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
|
||||
impl Audio {
|
||||
pub fn new(root: &Path) -> Self {
|
||||
let mut events = HashMap::new();
|
||||
let mut subtitles = HashMap::new();
|
||||
if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json"))
|
||||
&& let Ok(Value::Object(map)) = serde_json::from_slice::<Value>(&text)
|
||||
{
|
||||
@@ -135,6 +158,9 @@ impl Audio {
|
||||
},
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(key) = def["subtitle"].as_str() {
|
||||
subtitles.insert(format!("minecraft:{name}"), key.to_owned());
|
||||
}
|
||||
events.insert(format!("minecraft:{name}"), variants);
|
||||
}
|
||||
}
|
||||
@@ -151,6 +177,9 @@ impl Audio {
|
||||
};
|
||||
Self {
|
||||
_stream: stream,
|
||||
subtitles,
|
||||
record_heard: false,
|
||||
heard: Vec::new(),
|
||||
mixer,
|
||||
rate,
|
||||
root: root.to_owned(),
|
||||
@@ -162,6 +191,7 @@ impl Audio {
|
||||
master: 1.0,
|
||||
music: None,
|
||||
next_tracked: 0,
|
||||
source_override: None,
|
||||
}
|
||||
}
|
||||
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<(cpal::Stream, u32)> {
|
||||
@@ -279,12 +309,27 @@ impl Audio {
|
||||
}
|
||||
/// Play a sound event at a world position (None = non-positional UI sound).
|
||||
pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) {
|
||||
if self._stream.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(variant) = self.resolve(event, 0) else {
|
||||
return;
|
||||
};
|
||||
if self.record_heard
|
||||
&& let Some(key) = self.subtitles.get(event)
|
||||
{
|
||||
let range = if at.is_some() {
|
||||
variant.attenuation * volume.max(1.0)
|
||||
} else {
|
||||
f32::INFINITY
|
||||
};
|
||||
self.heard.push(Heard {
|
||||
subtitle: key.clone(),
|
||||
at,
|
||||
range,
|
||||
looping: false,
|
||||
});
|
||||
}
|
||||
if self._stream.is_none() {
|
||||
return;
|
||||
}
|
||||
let file = variant.name.trim_start_matches("minecraft:").to_owned();
|
||||
let entry = self.cache.entry(file.clone()).or_insert_with(|| {
|
||||
decode(
|
||||
@@ -297,9 +342,12 @@ impl Audio {
|
||||
let Some((samples, rate)) = entry.clone() else {
|
||||
return;
|
||||
};
|
||||
let source = self
|
||||
.source_override
|
||||
.unwrap_or_else(|| crate::settings::sound_source(event));
|
||||
let volume = (volume * variant.volume).clamp(0.0, 1.0)
|
||||
* self.master
|
||||
* crate::settings::event_volume(event);
|
||||
* crate::settings::source_volume(source);
|
||||
let pitch = (pitch * variant.pitch).clamp(0.5, 2.0);
|
||||
let (mut left, mut right) = (volume, volume);
|
||||
if let Some(p) = at {
|
||||
@@ -333,6 +381,8 @@ impl Audio {
|
||||
step,
|
||||
left,
|
||||
right,
|
||||
event: event.into(),
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -356,6 +406,7 @@ impl Audio {
|
||||
let step_scale = f64::from(variant.pitch.clamp(0.5, 2.0)) / f64::from(self.rate);
|
||||
let ready = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let (mixer, done) = (self.mixer.clone(), ready.clone());
|
||||
let music_event = event.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
if let Some((samples, rate)) = decode(&path)
|
||||
&& let Ok(mut m) = mixer.lock()
|
||||
@@ -367,6 +418,8 @@ impl Audio {
|
||||
step: f64::from(rate) * step_scale,
|
||||
left: volume,
|
||||
right: volume,
|
||||
event: music_event.as_str().into(),
|
||||
source: 1,
|
||||
});
|
||||
}
|
||||
done.store(true, std::sync::atomic::Ordering::Release);
|
||||
@@ -407,6 +460,50 @@ impl Audio {
|
||||
pub fn music_event(&self) -> Option<&str> {
|
||||
self.music.as_ref().map(|t| t.event.as_str())
|
||||
}
|
||||
/// Every sound event id (for command completion).
|
||||
pub fn event_names(&self) -> Vec<String> {
|
||||
let mut v: Vec<String> = self.events.keys().cloned().collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
/// Play a sound on a given `SoundSource` index (`/playsound`).
|
||||
pub fn play_on(
|
||||
&mut self,
|
||||
source: usize,
|
||||
event: &str,
|
||||
at: Option<[f64; 3]>,
|
||||
volume: f32,
|
||||
pitch: f32,
|
||||
) {
|
||||
self.source_override = Some(source);
|
||||
self.play(event, at, volume, pitch);
|
||||
self.source_override = None;
|
||||
}
|
||||
/// `ClientboundStopSoundPacket`: stop the playing sounds of an event
|
||||
/// and/or a source.
|
||||
pub fn stop_sounds(&mut self, event: Option<&str>, source: Option<usize>) {
|
||||
let matches = |v: &Voice| {
|
||||
event.is_none_or(|e| &*v.event == e) && source.is_none_or(|s| v.source == s)
|
||||
};
|
||||
if let Ok(mut m) = self.mixer.lock() {
|
||||
m.voices.retain(|v| !matches(v));
|
||||
m.tracked.retain(|t| !matches(&t.voice));
|
||||
if m.music.as_ref().is_some_and(matches) {
|
||||
m.music = None;
|
||||
}
|
||||
}
|
||||
if self
|
||||
.music
|
||||
.as_ref()
|
||||
.is_some_and(|t| event.is_none_or(|e| t.event == e) && source.is_none_or(|s| s == 1))
|
||||
{
|
||||
self.music = None;
|
||||
}
|
||||
}
|
||||
/// The sounds played since the last call, for the subtitle overlay.
|
||||
pub fn take_heard(&mut self) -> Vec<Heard> {
|
||||
std::mem::take(&mut self.heard)
|
||||
}
|
||||
/// `SoundManager.updateCategoryVolume(MUSIC, gain)`.
|
||||
pub fn set_music_gain(&mut self, gain: f32) {
|
||||
if let Ok(mut m) = self.mixer.lock() {
|
||||
@@ -416,8 +513,18 @@ impl Audio {
|
||||
/// Play a relative (non-positional) tickable sound instance the caller
|
||||
/// keeps a handle to: ambient loops (`looping`) and sub-sounds.
|
||||
pub fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option<u64> {
|
||||
self._stream.as_ref()?;
|
||||
let variant = self.resolve(event, 0)?;
|
||||
if self.record_heard
|
||||
&& let Some(key) = self.subtitles.get(event)
|
||||
{
|
||||
self.heard.push(Heard {
|
||||
subtitle: key.clone(),
|
||||
at: None,
|
||||
range: f32::INFINITY,
|
||||
looping,
|
||||
});
|
||||
}
|
||||
self._stream.as_ref()?;
|
||||
let file = variant.name.trim_start_matches("minecraft:").to_owned();
|
||||
let root = &self.root;
|
||||
let (samples, rate) = self
|
||||
@@ -443,6 +550,8 @@ impl Audio {
|
||||
step,
|
||||
left: gain,
|
||||
right: gain,
|
||||
event: event.into(),
|
||||
source: crate::settings::sound_source(event),
|
||||
},
|
||||
looping,
|
||||
volume: volume.clamp(0.0, 1.0),
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
//! Banner patterns: the `banner_pattern` registry and its tags, the
|
||||
//! `banner_patterns` layers carried by banner items, shields and placed
|
||||
//! banners, and the loom rules of `LoomMenu` (selectable patterns, the
|
||||
//! six-layer limit and the result stack).
|
||||
use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items};
|
||||
use horizon_world::nbt::Tag;
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path, sync::Arc};
|
||||
|
||||
/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BannerLayer {
|
||||
pub pattern: Arc<str>,
|
||||
pub color: Arc<str>,
|
||||
}
|
||||
impl BannerLayer {
|
||||
pub fn new(pattern: &str, color: &str) -> Self {
|
||||
Self {
|
||||
pattern: Arc::from(pattern),
|
||||
color: Arc::from(color),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`).
|
||||
pub const MAX_LAYERS: usize = 6;
|
||||
|
||||
/// One `banner_pattern` registry entry.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pattern {
|
||||
pub id: Arc<str>,
|
||||
/// `asset_id` path, the texture under `entity/banner` and `entity/shield`.
|
||||
pub asset: String,
|
||||
pub translation_key: String,
|
||||
}
|
||||
|
||||
/// The pattern registry, its tags and the item components the loom reads.
|
||||
#[derive(Default)]
|
||||
pub struct Banners {
|
||||
patterns: Vec<Pattern>,
|
||||
/// `#minecraft:no_item_required`, in tag order.
|
||||
no_item_required: Vec<Arc<str>>,
|
||||
/// Item -> `dye` component.
|
||||
dyes: HashMap<Arc<str>, Arc<str>>,
|
||||
/// Item -> `provides_banner_patterns`, in tag order.
|
||||
provided: HashMap<Arc<str>, Vec<Arc<str>>>,
|
||||
}
|
||||
|
||||
fn read_tag(root: &Path, name: &str, depth: u32) -> Vec<Arc<str>> {
|
||||
if depth > 8 {
|
||||
return Vec::new();
|
||||
}
|
||||
let path = root.join(format!(
|
||||
"data/minecraft/tags/banner_pattern/{}.json",
|
||||
name.trim_start_matches("minecraft:")
|
||||
));
|
||||
let Some(v) = fs::read(path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for value in v["values"].as_array().into_iter().flatten() {
|
||||
let Some(s) = value.as_str().or_else(|| value["id"].as_str()) else {
|
||||
continue;
|
||||
};
|
||||
match s.strip_prefix('#') {
|
||||
Some(tag) => out.extend(read_tag(root, tag, depth + 1)),
|
||||
None => out.push(Arc::from(s)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Banners {
|
||||
pub fn load(root: &Path) -> Self {
|
||||
let mut banners = Self::default();
|
||||
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/banner_pattern"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "json"))
|
||||
.collect();
|
||||
files.sort();
|
||||
for path in files {
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(v) = fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let asset = v["asset_id"]
|
||||
.as_str()
|
||||
.unwrap_or(stem)
|
||||
.trim_start_matches("minecraft:")
|
||||
.to_owned();
|
||||
banners.patterns.push(Pattern {
|
||||
id: Arc::from(format!("minecraft:{stem}").as_str()),
|
||||
asset,
|
||||
translation_key: v["translation_key"].as_str().unwrap_or_default().to_owned(),
|
||||
});
|
||||
}
|
||||
banners.no_item_required = read_tag(root, "no_item_required", 0);
|
||||
if let Some(raw) = fs::read(root.join("items.json")).ok().and_then(|b| {
|
||||
serde_json::from_slice::<std::collections::BTreeMap<String, Value>>(&b).ok()
|
||||
}) {
|
||||
for (item, c) in raw {
|
||||
let id: Arc<str> = Arc::from(item.as_str());
|
||||
if let Some(dye) = c["minecraft:dye"].as_str() {
|
||||
banners.dyes.insert(id.clone(), Arc::from(dye));
|
||||
}
|
||||
match &c["minecraft:provides_banner_patterns"] {
|
||||
Value::String(tag) if tag.starts_with('#') => {
|
||||
banners.provided.insert(id, read_tag(root, &tag[1..], 0));
|
||||
}
|
||||
Value::String(single) => {
|
||||
banners
|
||||
.provided
|
||||
.insert(id, vec![Arc::from(single.as_str())]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
banners
|
||||
}
|
||||
pub fn pattern(&self, id: &str) -> Option<&Pattern> {
|
||||
self.patterns.iter().find(|p| &*p.id == id)
|
||||
}
|
||||
/// `Sheets.getBannerSprite` texture name of a pattern.
|
||||
pub fn banner_texture(&self, id: &str) -> String {
|
||||
match self.pattern(id) {
|
||||
Some(p) => format!("entity/banner/{}", p.asset),
|
||||
None => format!("entity/banner/{}", id.trim_start_matches("minecraft:")),
|
||||
}
|
||||
}
|
||||
/// `Sheets.getShieldSprite` texture name of a pattern.
|
||||
pub fn shield_texture(&self, id: &str) -> String {
|
||||
match self.pattern(id) {
|
||||
Some(p) => format!("entity/shield/{}", p.asset),
|
||||
None => format!("entity/shield/{}", id.trim_start_matches("minecraft:")),
|
||||
}
|
||||
}
|
||||
/// `BannerPatternLayers.Layer.description` translation key.
|
||||
pub fn layer_key(&self, layer: &BannerLayer) -> String {
|
||||
let base = self.pattern(&layer.pattern).map_or_else(
|
||||
|| {
|
||||
format!(
|
||||
"block.minecraft.banner.{}",
|
||||
layer.pattern.trim_start_matches("minecraft:")
|
||||
)
|
||||
},
|
||||
|p| p.translation_key.clone(),
|
||||
);
|
||||
format!("{base}.{}", layer.color)
|
||||
}
|
||||
/// `LoomMenu.isDyeItem`: the dye colour of a loom dye.
|
||||
pub fn loom_dye(&self, items: &Items, stack: &ItemStack) -> Option<Arc<str>> {
|
||||
let tagged = items
|
||||
.item_tags
|
||||
.get("minecraft:loom_dyes")
|
||||
.is_some_and(|t| t.contains(&*stack.item));
|
||||
tagged
|
||||
.then(|| self.dyes.get(&stack.item).cloned())
|
||||
.flatten()
|
||||
}
|
||||
/// `LoomMenu.isPatternItem`.
|
||||
pub fn is_pattern_item(&self, items: &Items, stack: &ItemStack) -> bool {
|
||||
items
|
||||
.item_tags
|
||||
.get("minecraft:loom_patterns")
|
||||
.is_some_and(|t| t.contains(&*stack.item))
|
||||
&& self.provided.contains_key(&stack.item)
|
||||
}
|
||||
/// `LoomMenu.getSelectablePatterns`.
|
||||
pub fn selectable(&self, pattern_item: Option<&ItemStack>) -> Vec<Arc<str>> {
|
||||
match pattern_item {
|
||||
None => self.no_item_required.clone(),
|
||||
Some(stack) => self.provided.get(&stack.item).cloned().unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `BannerItem`: a banner's dye colour from its item id.
|
||||
pub fn banner_color(item: &str) -> Option<&'static str> {
|
||||
let name = item.strip_prefix("minecraft:")?.strip_suffix("_banner")?;
|
||||
DYES.iter().map(|d| d.0).find(|d| *d == name)
|
||||
}
|
||||
/// `DyeColor.getTextureDiffuseColor` (RGB) by dye name.
|
||||
pub fn dye_rgb(name: &str) -> u32 {
|
||||
DYES.iter().find(|d| d.0 == name).map_or(0xFFFFFF, |d| d.1)
|
||||
}
|
||||
/// The layers of a banner or shield stack.
|
||||
pub fn layers(stack: &ItemStack) -> &[BannerLayer] {
|
||||
stack.data().map_or(&[], |d| &d.banner_patterns)
|
||||
}
|
||||
/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour.
|
||||
pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack {
|
||||
let mut result = ItemStack {
|
||||
count: 1,
|
||||
..banner.clone()
|
||||
};
|
||||
result
|
||||
.data_mut()
|
||||
.banner_patterns
|
||||
.push(BannerLayer::new(pattern, dye));
|
||||
result
|
||||
}
|
||||
/// Whether the banner already carries the loom's limit.
|
||||
pub fn has_max_layers(banner: &ItemStack) -> bool {
|
||||
layers(banner).len() >= MAX_LAYERS
|
||||
}
|
||||
|
||||
/// The `banner_patterns` NBT list of layers.
|
||||
pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag {
|
||||
Tag::List(
|
||||
layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
Tag::compound([
|
||||
("pattern", Tag::String((&*l.pattern).into())),
|
||||
("color", Tag::String((&*l.color).into())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec<BannerLayer> {
|
||||
let Some(Tag::List(list)) = tag else {
|
||||
return Vec::new();
|
||||
};
|
||||
list.iter()
|
||||
.filter_map(|e| {
|
||||
let text = |k: &str| match e.get(k) {
|
||||
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
let pattern = text("pattern")?;
|
||||
let color = text("color")?;
|
||||
Some(BannerLayer::new(
|
||||
&if pattern.contains(':') {
|
||||
pattern
|
||||
} else {
|
||||
format!("minecraft:{pattern}")
|
||||
},
|
||||
&color,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// Keeps `item_data` linked: the `StackData` fields the banner code reads.
|
||||
pub fn set_layers(stack: &mut ItemStack, layers: Vec<BannerLayer>) {
|
||||
let data: &mut item_data::StackData = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
stack.tidy();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn banners() -> Banners {
|
||||
let mut b = Banners {
|
||||
no_item_required: vec![Arc::from("minecraft:stripe_top")],
|
||||
..Default::default()
|
||||
};
|
||||
b.provided.insert(
|
||||
Arc::from("minecraft:flower_banner_pattern"),
|
||||
vec![Arc::from("minecraft:flower")],
|
||||
);
|
||||
b
|
||||
}
|
||||
#[test]
|
||||
fn selectable_follow_the_pattern_item() {
|
||||
let b = banners();
|
||||
assert_eq!(b.selectable(None).len(), 1);
|
||||
let item = ItemStack::new("minecraft:flower_banner_pattern", 1);
|
||||
assert_eq!(&*b.selectable(Some(&item))[0], "minecraft:flower");
|
||||
}
|
||||
#[test]
|
||||
fn banner_colour_comes_from_the_item() {
|
||||
assert_eq!(
|
||||
banner_color("minecraft:light_gray_banner"),
|
||||
Some("light_gray")
|
||||
);
|
||||
assert_eq!(banner_color("minecraft:white_banner"), Some("white"));
|
||||
assert_eq!(banner_color("minecraft:white_wool"), None);
|
||||
}
|
||||
#[test]
|
||||
fn loom_adds_a_layer_up_to_the_limit() {
|
||||
let mut banner = ItemStack::new("minecraft:white_banner", 3);
|
||||
for i in 0..MAX_LAYERS {
|
||||
assert!(!has_max_layers(&banner));
|
||||
banner = loom_result(&banner, "red", "minecraft:cross");
|
||||
assert_eq!(banner.count, 1);
|
||||
assert_eq!(layers(&banner).len(), i + 1);
|
||||
}
|
||||
assert!(has_max_layers(&banner));
|
||||
}
|
||||
#[test]
|
||||
fn layers_round_trip_through_nbt() {
|
||||
let l = vec![
|
||||
BannerLayer::new("minecraft:flower", "red"),
|
||||
BannerLayer::new("minecraft:border", "black"),
|
||||
];
|
||||
assert_eq!(layers_from_nbt(Some(&layers_to_nbt(&l))), l);
|
||||
}
|
||||
}
|
||||
@@ -700,6 +700,8 @@ pub struct Scene<'a> {
|
||||
pub lid: &'a dyn Fn([i32; 3]) -> f32,
|
||||
/// Sign block-entity data at a position.
|
||||
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
|
||||
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
|
||||
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
|
||||
/// Font glyph cell and advance.
|
||||
pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>,
|
||||
}
|
||||
@@ -773,6 +775,13 @@ impl BlockEntityRenderer {
|
||||
random: LegacyRandom::new(0x5EED_B00C),
|
||||
}
|
||||
}
|
||||
/// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`).
|
||||
pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> {
|
||||
Some((
|
||||
self.models.get("standing_banner")?,
|
||||
self.models.get("standing_banner_flag")?,
|
||||
))
|
||||
}
|
||||
fn kind(&self, state: u32) -> &Kind {
|
||||
self.kinds.get(state as usize).unwrap_or(&Kind::None)
|
||||
}
|
||||
@@ -993,10 +1002,16 @@ impl BlockEntityRenderer {
|
||||
draw_part(main, "root", m, &none, paint, out);
|
||||
draw_part(flag, "root", m, &wave, paint, out);
|
||||
}
|
||||
// BannerRenderer.submitPatterns: the base pattern layer in the dye colour.
|
||||
// BannerRenderer.submitPatterns: the base pattern layer in the dye colour,
|
||||
// then up to 16 pattern layers in order.
|
||||
if let Some(paint) = paint("entity/banner/base", *color, packed) {
|
||||
draw_part(flag, "root", m, &wave, paint, out);
|
||||
}
|
||||
for (texture, tint) in (scene.banner)(pos).iter().take(16) {
|
||||
if let Some(paint) = paint(texture, *tint, packed) {
|
||||
draw_part(flag, "root", m, &wave, paint, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Skull {
|
||||
kind,
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Custom boss bars (`CustomBossEvents`): the `/bossbar` store, its saved
|
||||
//! form (`data/minecraft/custom_boss_events.dat`) and how a bar is shown.
|
||||
use crate::{
|
||||
scoreboard::{Comp, bracketed, comp_text, json_to_tag, literal, tag_to_json},
|
||||
text::{self, Style, Text},
|
||||
};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
pub const COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"];
|
||||
pub const STYLES: [&str; 5] = [
|
||||
"progress",
|
||||
"notched_6",
|
||||
"notched_10",
|
||||
"notched_12",
|
||||
"notched_20",
|
||||
];
|
||||
/// `BossBarColor.getFormatting`.
|
||||
pub fn color_rgb(color: &str) -> u32 {
|
||||
let name = match color {
|
||||
"pink" => "red",
|
||||
"red" => "dark_red",
|
||||
"purple" => "dark_purple",
|
||||
other => other,
|
||||
};
|
||||
text::named_color(name).unwrap_or(text::WHITE)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BossBar {
|
||||
pub id: String,
|
||||
pub name: Comp,
|
||||
pub color: String,
|
||||
pub style: String,
|
||||
pub value: i32,
|
||||
pub max: i32,
|
||||
pub visible: bool,
|
||||
/// Whether the (single) local player is in the bar's player set.
|
||||
pub player: bool,
|
||||
}
|
||||
impl BossBar {
|
||||
pub fn new(id: &str, name: Comp) -> Self {
|
||||
Self {
|
||||
id: id.to_owned(),
|
||||
name,
|
||||
color: "white".into(),
|
||||
style: "progress".into(),
|
||||
value: 0,
|
||||
max: 100,
|
||||
visible: false,
|
||||
player: false,
|
||||
}
|
||||
}
|
||||
/// `CustomBossEvent.getDisplayName`.
|
||||
pub fn display_name(&self) -> Text {
|
||||
let style = Style {
|
||||
color: Some(color_rgb(&self.color)),
|
||||
hover: Some(Box::new(Text::literal(self.id.clone()))),
|
||||
..Style::default()
|
||||
};
|
||||
bracketed(comp_text(&self.name).with_style(&style))
|
||||
}
|
||||
/// The filled fraction of the bar (`BossEvent.getProgress`).
|
||||
pub fn progress(&self) -> f32 {
|
||||
(self.value as f32 / self.max.max(1) as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BossBars {
|
||||
pub bars: Vec<BossBar>,
|
||||
}
|
||||
impl BossBars {
|
||||
pub fn get(&self, id: &str) -> Option<&BossBar> {
|
||||
self.bars.iter().find(|b| b.id == id)
|
||||
}
|
||||
pub fn get_mut(&mut self, id: &str) -> Option<&mut BossBar> {
|
||||
self.bars.iter_mut().find(|b| b.id == id)
|
||||
}
|
||||
pub fn add(&mut self, id: &str, name: Comp) -> bool {
|
||||
if self.get(id).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.bars.push(BossBar::new(id, name));
|
||||
true
|
||||
}
|
||||
pub fn remove(&mut self, id: &str) {
|
||||
self.bars.retain(|b| b.id != id);
|
||||
}
|
||||
pub fn ids(&self) -> Vec<String> {
|
||||
self.bars.iter().map(|b| b.id.clone()).collect()
|
||||
}
|
||||
/// The saved compound; the player's UUID stands for "the local player".
|
||||
pub fn pack(&self, player: Option<[i32; 4]>) -> Tag {
|
||||
let mut c = Compound::new();
|
||||
for b in &self.bars {
|
||||
let mut e = vec![
|
||||
("Name", json_to_tag(&b.name)),
|
||||
("Visible", Tag::Byte(i8::from(b.visible))),
|
||||
("Value", Tag::Int(b.value)),
|
||||
("Max", Tag::Int(b.max)),
|
||||
("Color", Tag::String(b.color.as_str().into())),
|
||||
("Overlay", Tag::String(b.style.as_str().into())),
|
||||
("DarkenScreen", Tag::Byte(0)),
|
||||
("PlayBossMusic", Tag::Byte(0)),
|
||||
("CreateWorldFog", Tag::Byte(0)),
|
||||
];
|
||||
let players = match (b.player, player) {
|
||||
(true, Some(u)) => vec![Tag::IntArray(u.to_vec())],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
e.push(("Players", Tag::List(players)));
|
||||
c.insert(b.id.as_str().into(), Tag::compound(e));
|
||||
}
|
||||
Tag::Compound(c)
|
||||
}
|
||||
pub fn unpack(data: &Tag, player: Option<[i32; 4]>) -> Self {
|
||||
let mut bars = Vec::new();
|
||||
if let Tag::Compound(c) = data {
|
||||
for (id, e) in c {
|
||||
let get = |k: &str| e.get(k);
|
||||
let text = |k: &str, d: &str| match get(k) {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => d.to_owned(),
|
||||
};
|
||||
let num = |k: &str, d: i32| match get(k) {
|
||||
Some(Tag::Int(v)) => *v,
|
||||
Some(Tag::Short(v)) => i32::from(*v),
|
||||
Some(Tag::Byte(v)) => i32::from(*v),
|
||||
_ => d,
|
||||
};
|
||||
let in_players = match (get("Players"), player) {
|
||||
(Some(Tag::List(l)), Some(u)) => l
|
||||
.iter()
|
||||
.any(|t| matches!(t, Tag::IntArray(a) if a.as_slice() == u)),
|
||||
_ => false,
|
||||
};
|
||||
bars.push(BossBar {
|
||||
id: id.to_string_lossy(),
|
||||
name: get("Name").map_or_else(|| literal(""), tag_to_json),
|
||||
color: text("Color", "white"),
|
||||
style: text("Overlay", "progress"),
|
||||
value: num("Value", 0),
|
||||
max: num("Max", 100),
|
||||
visible: num("Visible", 0) != 0,
|
||||
player: in_players,
|
||||
});
|
||||
}
|
||||
}
|
||||
Self { bars }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bars_round_trip_and_show() {
|
||||
let mut b = BossBars::default();
|
||||
assert!(b.add("test:x", literal("Hello")));
|
||||
assert!(!b.add("test:x", literal("Again")));
|
||||
let bar = b.get_mut("test:x").unwrap();
|
||||
bar.color = "pink".into();
|
||||
bar.style = "notched_10".into();
|
||||
bar.value = 25;
|
||||
bar.max = 50;
|
||||
bar.visible = true;
|
||||
bar.player = true;
|
||||
let uuid = Some([1, 2, 3, 4]);
|
||||
let back = BossBars::unpack(&b.pack(uuid), uuid);
|
||||
assert_eq!(back, b);
|
||||
// Another player's UUID does not include the local player.
|
||||
assert!(!BossBars::unpack(&b.pack(uuid), Some([9, 9, 9, 9])).bars[0].player);
|
||||
let bar = b.get("test:x").unwrap();
|
||||
assert_eq!(bar.progress(), 0.5);
|
||||
assert_eq!(bar.display_name().plain(), "chat.square_brackets");
|
||||
assert_eq!(color_rgb("pink"), text::RED);
|
||||
assert_eq!(color_rgb("purple"), 0xAA00AA);
|
||||
b.remove("test:x");
|
||||
assert!(b.bars.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,8 @@ pub struct Chunk {
|
||||
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
|
||||
pub heights: Arc<[i16; 256]>,
|
||||
pub lit: bool,
|
||||
/// Light read from a save with `isLightOn`: no light job is needed.
|
||||
pub light_loaded: bool,
|
||||
/// Newly generated (not loaded from a save): eligible for generation-time spawns.
|
||||
pub fresh: bool,
|
||||
/// Block entities read from a save, moved into the world on arrival.
|
||||
@@ -120,6 +122,7 @@ impl Chunk {
|
||||
biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]),
|
||||
heights: Arc::new([MIN_Y as i16; 256]),
|
||||
lit: false,
|
||||
light_loaded: false,
|
||||
fresh: false,
|
||||
block_entities: Vec::new(),
|
||||
structure_refs: Vec::new(),
|
||||
|
||||
@@ -1,24 +1,136 @@
|
||||
//! Fixed-rate development simulation driver. Rendering consumes elapsed time;
|
||||
//! a per-frame work cap retains its backlog instead of dropping simulation time.
|
||||
//! The rate, freezing, stepping and sprinting are what `/tick` controls
|
||||
//! (`ServerTickRateManager`).
|
||||
use std::time::Duration;
|
||||
|
||||
pub const TICK: Duration = Duration::from_millis(50);
|
||||
#[derive(Default)]
|
||||
/// Ticks one sprint frame may run.
|
||||
const SPRINT_PER_FRAME: u32 = 40;
|
||||
const SAMPLES: usize = 100;
|
||||
|
||||
pub struct FixedStep {
|
||||
pending: Duration,
|
||||
/// Ticks per second (`tickrate`).
|
||||
rate: f32,
|
||||
frozen: bool,
|
||||
/// Ticks the frozen world still runs (`/tick step`).
|
||||
step: u32,
|
||||
/// Ticks left in a sprint.
|
||||
sprint: u32,
|
||||
/// How long recent ticks took (nanoseconds), newest last.
|
||||
samples: Vec<u64>,
|
||||
}
|
||||
impl Default for FixedStep {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pending: Duration::ZERO,
|
||||
rate: 20.0,
|
||||
frozen: false,
|
||||
step: 0,
|
||||
sprint: 0,
|
||||
samples: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl FixedStep {
|
||||
/// The length of one tick at the current rate.
|
||||
pub fn tick_duration(&self) -> Duration {
|
||||
Duration::from_secs_f64(1.0 / f64::from(self.rate.max(0.01)))
|
||||
}
|
||||
pub fn advance(&mut self, elapsed: Duration) -> u32 {
|
||||
if self.sprint > 0 {
|
||||
let n = self.sprint.min(SPRINT_PER_FRAME);
|
||||
self.sprint -= n;
|
||||
self.pending = Duration::ZERO;
|
||||
return n;
|
||||
}
|
||||
self.pending += elapsed;
|
||||
let steps = (self.pending.as_nanos() / TICK.as_nanos()).min(10) as u32;
|
||||
self.pending -= TICK * steps;
|
||||
let tick = self.tick_duration();
|
||||
let steps = (self.pending.as_nanos() / tick.as_nanos().max(1)).min(10) as u32;
|
||||
self.pending -= tick * steps;
|
||||
steps
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.pending = Duration::ZERO;
|
||||
}
|
||||
pub fn fraction(&self) -> f64 {
|
||||
(self.pending.as_secs_f64() / TICK.as_secs_f64()).min(1.0)
|
||||
(self.pending.as_secs_f64() / self.tick_duration().as_secs_f64()).min(1.0)
|
||||
}
|
||||
/// Whether the world ticks this time (`ServerTickRateManager.runsNormally`
|
||||
/// or a pending step); called once per tick.
|
||||
pub fn world_runs(&mut self) -> bool {
|
||||
if !self.frozen {
|
||||
return true;
|
||||
}
|
||||
if self.step > 0 {
|
||||
self.step -= 1;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
pub fn rate(&self) -> f32 {
|
||||
self.rate
|
||||
}
|
||||
pub fn set_rate(&mut self, rate: f32) {
|
||||
self.rate = rate.clamp(1.0, 10000.0);
|
||||
}
|
||||
pub fn frozen(&self) -> bool {
|
||||
self.frozen
|
||||
}
|
||||
pub fn set_frozen(&mut self, frozen: bool) {
|
||||
self.frozen = frozen;
|
||||
if !frozen {
|
||||
self.step = 0;
|
||||
}
|
||||
}
|
||||
pub fn sprinting(&self) -> bool {
|
||||
self.sprint > 0
|
||||
}
|
||||
/// `requestGameToSprint`: true when a sprint was already running.
|
||||
pub fn start_sprint(&mut self, ticks: u32) -> bool {
|
||||
let was = self.sprint > 0;
|
||||
self.sprint = ticks;
|
||||
was
|
||||
}
|
||||
pub fn stop_sprint(&mut self) -> bool {
|
||||
let was = self.sprint > 0;
|
||||
self.sprint = 0;
|
||||
was
|
||||
}
|
||||
pub fn stepping(&self) -> bool {
|
||||
self.step > 0
|
||||
}
|
||||
/// `stepGameIfPaused`: only works while frozen.
|
||||
pub fn start_step(&mut self, ticks: u32) -> bool {
|
||||
if !self.frozen {
|
||||
return false;
|
||||
}
|
||||
self.step = ticks;
|
||||
true
|
||||
}
|
||||
pub fn stop_step(&mut self) -> bool {
|
||||
let was = self.step > 0;
|
||||
self.step = 0;
|
||||
was
|
||||
}
|
||||
pub fn record(&mut self, took: Duration) {
|
||||
if self.samples.len() == SAMPLES {
|
||||
self.samples.remove(0);
|
||||
}
|
||||
self.samples.push(took.as_nanos() as u64);
|
||||
}
|
||||
pub fn average_nanos(&self) -> u64 {
|
||||
if self.samples.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
self.samples.iter().sum::<u64>() / self.samples.len() as u64
|
||||
}
|
||||
/// The sorted tick times (p50, p95, p99 inputs) and their count.
|
||||
pub fn sorted_samples(&self) -> Vec<u64> {
|
||||
let mut v = self.samples.clone();
|
||||
v.sort_unstable();
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,4 +172,35 @@ mod tests {
|
||||
assert_eq!(clock.advance(Duration::from_millis(26)), 0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(24)), 1);
|
||||
}
|
||||
#[test]
|
||||
fn rate_changes_the_tick_length() {
|
||||
let mut clock = FixedStep::default();
|
||||
clock.set_rate(40.0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(100)), 4);
|
||||
clock.set_rate(5.0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(400)), 2);
|
||||
clock.set_rate(1.0e9);
|
||||
assert_eq!(clock.rate(), 10000.0);
|
||||
}
|
||||
#[test]
|
||||
fn freeze_step_and_sprint() {
|
||||
let mut clock = FixedStep::default();
|
||||
assert!(clock.world_runs());
|
||||
assert!(!clock.start_step(3), "stepping needs a frozen game");
|
||||
clock.set_frozen(true);
|
||||
assert!(!clock.world_runs());
|
||||
assert!(clock.start_step(2));
|
||||
assert!(clock.world_runs() && clock.world_runs() && !clock.world_runs());
|
||||
assert!(clock.start_step(5) && clock.stop_step() && !clock.stop_step());
|
||||
clock.set_frozen(false);
|
||||
assert!(!clock.start_sprint(100));
|
||||
assert!(clock.sprinting());
|
||||
assert_eq!(clock.advance(Duration::ZERO), SPRINT_PER_FRAME);
|
||||
assert!(clock.stop_sprint() && !clock.sprinting());
|
||||
for ns in [3, 1, 2] {
|
||||
clock.record(Duration::from_nanos(ns));
|
||||
}
|
||||
assert_eq!(clock.average_nanos(), 2);
|
||||
assert_eq!(clock.sorted_samples(), vec![1, 2, 3]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,28 @@ pub struct Registries {
|
||||
/// Game rule name -> integer-valued.
|
||||
pub game_rules: Vec<(String, bool)>,
|
||||
pub players: Vec<String>,
|
||||
/// Scoreboard objective names, team names and tracked score holders.
|
||||
pub objectives: Vec<String>,
|
||||
pub teams: Vec<String>,
|
||||
pub tracked: Vec<String>,
|
||||
/// Loaded datapack functions (`ns:path`) and function tags (`ns:path`).
|
||||
pub functions: Vec<String>,
|
||||
/// `/data ... storage` ids.
|
||||
pub storages: Vec<String>,
|
||||
/// Boss bar ids and datapack predicate ids.
|
||||
pub bossbars: Vec<String>,
|
||||
pub predicates: Vec<String>,
|
||||
pub schedules: Vec<String>,
|
||||
pub recipes: Vec<String>,
|
||||
pub sounds: Vec<String>,
|
||||
pub damage_types: Vec<String>,
|
||||
pub attributes: Vec<String>,
|
||||
pub loot_tables: Vec<String>,
|
||||
pub templates: Vec<String>,
|
||||
pub random_sequences: Vec<String>,
|
||||
pub datapacks_enabled: Vec<String>,
|
||||
pub datapacks_disabled: Vec<String>,
|
||||
pub function_tags: Vec<String>,
|
||||
/// The block the source is looking at (relevant coordinates).
|
||||
pub target_block: Option<[i32; 3]>,
|
||||
}
|
||||
@@ -116,7 +138,93 @@ pub enum ArgType {
|
||||
Component,
|
||||
/// CompoundTagArgument (kept as SNBT text).
|
||||
Nbt,
|
||||
/// ScoreHolderArgument.
|
||||
ScoreHolder {
|
||||
multiple: bool,
|
||||
},
|
||||
/// ObjectiveArgument (checked when the command runs).
|
||||
Objective,
|
||||
/// TeamArgument (checked when the command runs).
|
||||
Team,
|
||||
/// ObjectiveCriteriaArgument.
|
||||
Criteria,
|
||||
/// ScoreboardSlotArgument.
|
||||
ScoreboardSlot,
|
||||
/// OperationArgument.
|
||||
Operation,
|
||||
/// TeamColorArgument.
|
||||
TeamColor,
|
||||
/// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`).
|
||||
IntRange,
|
||||
/// NbtPathArgument (kept as text).
|
||||
NbtPath,
|
||||
/// NbtTagArgument: any SNBT value (kept as text).
|
||||
NbtTag,
|
||||
/// Vec2Argument: `x z` with `~` relative parts.
|
||||
Vec2,
|
||||
/// ColumnPosArgument: block `x z`.
|
||||
ColumnPos,
|
||||
/// ParticleArgument: a particle id and its options (kept as text).
|
||||
Particle,
|
||||
/// One of a fixed set of words.
|
||||
Enum(&'static [&'static str]),
|
||||
/// A (possibly quoted) name suggested from a registry list.
|
||||
Name(&'static str),
|
||||
/// FunctionArgument: `ns:path`, or `#ns:path` for a function tag.
|
||||
Function,
|
||||
/// SlotsArgument: a slot name or a wildcard group (`container.*`).
|
||||
Slots,
|
||||
/// SlotArgument: one slot (`container.5`, `weapon.mainhand`).
|
||||
Slot,
|
||||
}
|
||||
|
||||
/// Every slot name a command can address (`SlotRanges`), without wildcards.
|
||||
pub fn slot_names() -> Vec<String> {
|
||||
let mut v: Vec<String> = Vec::new();
|
||||
let mut range = |prefix: &str, n: usize| {
|
||||
for i in 0..n {
|
||||
v.push(format!("{prefix}.{i}"));
|
||||
}
|
||||
};
|
||||
range("container", 54);
|
||||
range("hotbar", 9);
|
||||
range("inventory", 27);
|
||||
range("enderchest", 27);
|
||||
range("villager", 8);
|
||||
range("horse", 15);
|
||||
range("player.crafting", 4);
|
||||
for name in [
|
||||
"weapon",
|
||||
"weapon.mainhand",
|
||||
"weapon.offhand",
|
||||
"armor.head",
|
||||
"armor.chest",
|
||||
"armor.legs",
|
||||
"armor.feet",
|
||||
"armor.body",
|
||||
"saddle",
|
||||
"horse.saddle",
|
||||
"horse.chest",
|
||||
"player.cursor",
|
||||
"contents",
|
||||
] {
|
||||
v.push(name.to_owned());
|
||||
}
|
||||
v
|
||||
}
|
||||
/// The wildcard groups of `slot_names` (`container.*`, `armor.*`, ...).
|
||||
pub const SLOT_GROUPS: [&str; 10] = [
|
||||
"container.*",
|
||||
"hotbar.*",
|
||||
"inventory.*",
|
||||
"enderchest.*",
|
||||
"villager.*",
|
||||
"horse.*",
|
||||
"player.crafting.*",
|
||||
"armor.*",
|
||||
"weapon.*",
|
||||
"player.*",
|
||||
];
|
||||
pub fn integer(min: i32) -> ArgType {
|
||||
ArgType::Integer { min, max: i32::MAX }
|
||||
}
|
||||
@@ -227,6 +335,29 @@ pub struct Selector {
|
||||
pub y_rotation: Option<DoubleRange>,
|
||||
pub pos: [Option<f64>; 3],
|
||||
pub delta: [Option<f64>; 3],
|
||||
/// `scores={objective=range,...}`.
|
||||
pub scores: Vec<(String, IntRange)>,
|
||||
/// `team=` (an empty name matches entities without a team).
|
||||
pub teams: Vec<(String, bool)>,
|
||||
/// `nbt=` compounds (SNBT text).
|
||||
pub nbt: Vec<(String, bool)>,
|
||||
/// `advancements={id=true|{criterion=true}}`.
|
||||
pub advancements: Vec<(String, AdvCondition)>,
|
||||
/// `predicate=` ids.
|
||||
pub predicates: Vec<(String, bool)>,
|
||||
}
|
||||
/// An `advancements=` entry: all done or not, or per-criterion states.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdvCondition {
|
||||
Done(bool),
|
||||
Criteria(Vec<(String, bool)>),
|
||||
}
|
||||
/// A `ScoreHolderArgument` value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ScoreHolderArg {
|
||||
Wildcard,
|
||||
Name(String),
|
||||
Selector(Selector),
|
||||
}
|
||||
impl Selector {
|
||||
pub fn is_self(&self) -> bool {
|
||||
@@ -293,6 +424,8 @@ pub enum Arg {
|
||||
GameMode(GameMode),
|
||||
/// `eyes` (true) or `feet`.
|
||||
Anchor(bool),
|
||||
ScoreHolder(ScoreHolderArg),
|
||||
IntRange(IntRange),
|
||||
}
|
||||
|
||||
fn is_id_char(c: char) -> bool {
|
||||
@@ -563,6 +696,7 @@ fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries) {
|
||||
}
|
||||
}
|
||||
|
||||
pub const OPERATIONS: [&str; 9] = ["=", "+=", "-=", "*=", "/=", "%=", "<", ">", "><"];
|
||||
const SELECTORS: [(&str, &str); 6] = [
|
||||
("@a", "argument.entity.selector.allPlayers"),
|
||||
("@e", "argument.entity.selector.allEntities"),
|
||||
@@ -571,7 +705,7 @@ const SELECTORS: [(&str, &str); 6] = [
|
||||
("@r", "argument.entity.selector.randomPlayer"),
|
||||
("@s", "argument.entity.selector.self"),
|
||||
];
|
||||
const OPTIONS: [&str; 16] = [
|
||||
const OPTIONS: [&str; 21] = [
|
||||
"name",
|
||||
"distance",
|
||||
"level",
|
||||
@@ -588,7 +722,22 @@ const OPTIONS: [&str; 16] = [
|
||||
"gamemode",
|
||||
"tag",
|
||||
"type",
|
||||
"scores",
|
||||
"team",
|
||||
"nbt",
|
||||
"advancements",
|
||||
"predicate",
|
||||
];
|
||||
/// StringReader.expect.
|
||||
fn expect_symbol(reader: &mut Reader, c: char) -> CmdResult<()> {
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() && reader.peek() == c {
|
||||
reader.skip();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CommandError::tr_at("parsing.expected", &[&c], reader))
|
||||
}
|
||||
}
|
||||
fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult<Selector> {
|
||||
let start = reader.cursor;
|
||||
if !(reader.can_read() && reader.peek() == '@') {
|
||||
@@ -791,6 +940,81 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult<Selector>
|
||||
let v = reader.read_unquoted_string().to_owned();
|
||||
s.tags.push((v, neg));
|
||||
}
|
||||
"team" => {
|
||||
let neg = negated(reader);
|
||||
let v = reader.read_unquoted_string().to_owned();
|
||||
s.teams.push((v, neg));
|
||||
}
|
||||
"nbt" => {
|
||||
let neg = negated(reader);
|
||||
if !reader.can_read() || reader.peek() != '{' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.nbt.expected.compound",
|
||||
&[],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
s.nbt.push((read_braced(reader, '{', '}')?, neg));
|
||||
}
|
||||
"predicate" => {
|
||||
let neg = negated(reader);
|
||||
s.predicates.push((read_id(reader)?, neg));
|
||||
}
|
||||
"scores" => {
|
||||
expect_symbol(reader, '{')?;
|
||||
reader.skip_whitespace();
|
||||
while reader.can_read() && reader.peek() != '}' {
|
||||
reader.skip_whitespace();
|
||||
let name = reader.read_unquoted_string().to_owned();
|
||||
expect_symbol(reader, '=')?;
|
||||
let range = range_int(reader)?;
|
||||
s.scores.push((name, range));
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() && reader.peek() == ',' {
|
||||
reader.skip();
|
||||
}
|
||||
reader.skip_whitespace();
|
||||
}
|
||||
expect_symbol(reader, '}')?;
|
||||
}
|
||||
"advancements" => {
|
||||
expect_symbol(reader, '{')?;
|
||||
reader.skip_whitespace();
|
||||
while reader.can_read() && reader.peek() != '}' {
|
||||
reader.skip_whitespace();
|
||||
let id = read_id(reader)?;
|
||||
expect_symbol(reader, '=')?;
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() && reader.peek() == '{' {
|
||||
reader.skip();
|
||||
reader.skip_whitespace();
|
||||
let mut criteria = Vec::new();
|
||||
while reader.can_read() && reader.peek() != '}' {
|
||||
reader.skip_whitespace();
|
||||
let c = reader.read_unquoted_string().to_owned();
|
||||
expect_symbol(reader, '=')?;
|
||||
criteria.push((c, reader.read_boolean()?));
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() && reader.peek() == ',' {
|
||||
reader.skip();
|
||||
}
|
||||
reader.skip_whitespace();
|
||||
}
|
||||
expect_symbol(reader, '}')?;
|
||||
s.advancements.push((id, AdvCondition::Criteria(criteria)));
|
||||
} else {
|
||||
s.advancements
|
||||
.push((id, AdvCondition::Done(reader.read_boolean()?)));
|
||||
}
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() && reader.peek() == ',' {
|
||||
reader.skip();
|
||||
}
|
||||
reader.skip_whitespace();
|
||||
}
|
||||
expect_symbol(reader, '}')?;
|
||||
s.include_entities = false;
|
||||
}
|
||||
"type" => {
|
||||
let neg = negated(reader);
|
||||
let at = reader.cursor;
|
||||
@@ -1410,7 +1634,11 @@ impl ArgType {
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(read_braced(reader, '{', '}')?)
|
||||
let text = read_braced(reader, '{', '}')?;
|
||||
if let Err(e) = horizon_world::nbt::parse_snbt(&text) {
|
||||
return Err(CommandError::at(crate::text::Text::literal(e), reader));
|
||||
}
|
||||
Arg::Str(text)
|
||||
}
|
||||
ArgType::Component => {
|
||||
let (value, used) =
|
||||
@@ -1436,6 +1664,205 @@ impl ArgType {
|
||||
}
|
||||
Arg::Str(axes)
|
||||
}
|
||||
ArgType::ScoreHolder { multiple } => {
|
||||
if reader.can_read() && reader.peek() == '@' {
|
||||
let sel = parse_selector(reader, reg)?;
|
||||
if !*multiple && sel.limit > 1 {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at("argument.entity.toomany", &[], reader));
|
||||
}
|
||||
Arg::ScoreHolder(ScoreHolderArg::Selector(sel))
|
||||
} else {
|
||||
while reader.can_read() && reader.peek() != ' ' {
|
||||
reader.skip();
|
||||
}
|
||||
let text = &reader.string[start..reader.cursor];
|
||||
if text == "*" {
|
||||
Arg::ScoreHolder(ScoreHolderArg::Wildcard)
|
||||
} else {
|
||||
Arg::ScoreHolder(ScoreHolderArg::Name(text.to_owned()))
|
||||
}
|
||||
}
|
||||
}
|
||||
ArgType::Objective | ArgType::Team => {
|
||||
Arg::Str(reader.read_unquoted_string().to_owned())
|
||||
}
|
||||
ArgType::Criteria => {
|
||||
while reader.can_read() && reader.peek() != ' ' {
|
||||
reader.skip();
|
||||
}
|
||||
let id = &reader.string[start..reader.cursor];
|
||||
if !crate::scoreboard::criteria_exists(id, reg) {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(id.to_owned())
|
||||
}
|
||||
ArgType::ScoreboardSlot => {
|
||||
let name = reader.read_unquoted_string();
|
||||
if !crate::scoreboard::display_slot_valid(name) {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.scoreboardDisplaySlot.invalid",
|
||||
&[&name],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(name.to_owned())
|
||||
}
|
||||
ArgType::Operation => {
|
||||
if !reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.operation.invalid",
|
||||
&[],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
while reader.can_read() && reader.peek() != ' ' {
|
||||
reader.skip();
|
||||
}
|
||||
let op = &reader.string[start..reader.cursor];
|
||||
if !OPERATIONS.contains(&op) {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.operation.invalid",
|
||||
&[],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(op.to_owned())
|
||||
}
|
||||
ArgType::TeamColor => {
|
||||
let name = reader.read_unquoted_string();
|
||||
if crate::scoreboard::team_color_rgb(name).is_none() {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.color.invalid",
|
||||
&[&name],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(name.to_owned())
|
||||
}
|
||||
ArgType::IntRange => Arg::IntRange(range_int(reader)?),
|
||||
ArgType::Name(_) => Arg::Str(reader.read_string()?),
|
||||
ArgType::Vec2 | ArgType::ColumnPos => {
|
||||
let block = matches!(self, ArgType::ColumnPos);
|
||||
let one = |reader: &mut Reader| {
|
||||
if block {
|
||||
parse_coord_int(reader)
|
||||
} else {
|
||||
parse_coord_double(reader, false)
|
||||
}
|
||||
};
|
||||
let x = one(reader)?;
|
||||
if !reader.can_read() || reader.peek() != ' ' {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.pos2d.incomplete",
|
||||
&[],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
reader.skip();
|
||||
let z = one(reader)?;
|
||||
Arg::Coords(Coordinates::World([
|
||||
x,
|
||||
Coord {
|
||||
relative: true,
|
||||
value: 0.0,
|
||||
},
|
||||
z,
|
||||
]))
|
||||
}
|
||||
ArgType::Particle => {
|
||||
let id = read_id(reader)?;
|
||||
let name = id.trim_start_matches("minecraft:").to_owned();
|
||||
if crate::particles::ParticleType::from_name(&id).is_none() {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at("particle.notFound", &[&id], reader));
|
||||
}
|
||||
let floats = |reader: &mut Reader, n: usize| -> CmdResult<()> {
|
||||
for _ in 0..n {
|
||||
reader.expect(' ')?;
|
||||
reader.read_float()?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
match name.as_str() {
|
||||
"dust" => floats(reader, 4)?,
|
||||
"dust_color_transition" => floats(reader, 7)?,
|
||||
"entity_effect" | "tinted_leaves" | "flash" => floats(reader, 4)?,
|
||||
"sculk_charge" => floats(reader, 1)?,
|
||||
"shriek" => {
|
||||
reader.expect(' ')?;
|
||||
reader.read_int()?;
|
||||
}
|
||||
"block" | "block_marker" | "falling_dust" | "dust_pillar" | "block_crumble" => {
|
||||
reader.expect(' ')?;
|
||||
parse_block(reader, reg, false)?;
|
||||
}
|
||||
"item" => {
|
||||
reader.expect(' ')?;
|
||||
parse_item(reader, reg, false)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Arg::Str(reader.string[start..reader.cursor].to_owned())
|
||||
}
|
||||
ArgType::Enum(words) => {
|
||||
let word = reader.read_unquoted_string();
|
||||
if !words.contains(&word) {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at("command.unknown.argument", &[], reader));
|
||||
}
|
||||
Arg::Str(word.to_owned())
|
||||
}
|
||||
ArgType::Function => {
|
||||
let tag = reader.can_read() && reader.peek() == '#';
|
||||
if tag {
|
||||
reader.skip();
|
||||
}
|
||||
let id = read_id(reader)?;
|
||||
Arg::Resource(if tag { format!("#{id}") } else { id })
|
||||
}
|
||||
ArgType::Slots | ArgType::Slot => {
|
||||
let mut end = reader.cursor;
|
||||
while reader.can_read() && reader.peek() != ' ' {
|
||||
reader.skip();
|
||||
end = reader.cursor;
|
||||
}
|
||||
let word = &reader.string[start..end];
|
||||
let known = slot_names().iter().any(|n| n == word)
|
||||
|| (matches!(self, ArgType::Slots) && SLOT_GROUPS.contains(&word));
|
||||
if !known {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at("slot.unknown", &[&word], reader));
|
||||
}
|
||||
Arg::Str(word.to_owned())
|
||||
}
|
||||
ArgType::NbtPath => {
|
||||
let (path, used) = crate::nbt_path::NbtPath::parse_prefix(reader.remaining())
|
||||
.map_err(|e| {
|
||||
reader.cursor += e.cursor.min(reader.remaining().len());
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
e.args.iter().map(|a| a as &dyn std::fmt::Display).collect();
|
||||
CommandError::tr_at(e.key, &args, reader)
|
||||
})?;
|
||||
reader.cursor += used;
|
||||
Arg::Str(path.as_str().to_owned())
|
||||
}
|
||||
ArgType::NbtTag => {
|
||||
let (_, used) = horizon_world::nbt::parse_snbt(reader.remaining())
|
||||
.map_err(|e| CommandError::at(crate::text::Text::literal(e), reader))?;
|
||||
let text = reader.remaining()[..used].to_owned();
|
||||
reader.cursor += used;
|
||||
Arg::Str(text)
|
||||
}
|
||||
ArgType::Anchor => {
|
||||
let name = reader.read_unquoted_string();
|
||||
match name {
|
||||
@@ -1492,6 +1919,17 @@ impl ArgType {
|
||||
}
|
||||
ArgType::Id(list) => {
|
||||
let values = match *list {
|
||||
"storages" => reg.storages.clone(),
|
||||
"bossbars" => reg.bossbars.clone(),
|
||||
"schedules" => reg.schedules.clone(),
|
||||
"recipes" => reg.recipes.clone(),
|
||||
"sounds" => reg.sounds.clone(),
|
||||
"damage_types" => reg.damage_types.clone(),
|
||||
"attributes" => reg.attributes.clone(),
|
||||
"loot_tables" => reg.loot_tables.clone(),
|
||||
"templates" => reg.templates.clone(),
|
||||
"random_sequences" => reg.random_sequences.clone(),
|
||||
"predicates" => reg.predicates.clone(),
|
||||
"time_markers" => reg.time_markers.clone(),
|
||||
"advancements" => reg.advancements.clone(),
|
||||
_ => Vec::new(),
|
||||
@@ -1511,6 +1949,79 @@ impl ArgType {
|
||||
}
|
||||
}
|
||||
ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)),
|
||||
ArgType::ScoreHolder { .. } => {
|
||||
suggest_selector(builder, reg);
|
||||
let names: Vec<String> = reg
|
||||
.players
|
||||
.iter()
|
||||
.chain(reg.tracked.iter())
|
||||
.cloned()
|
||||
.collect();
|
||||
builder.suggest_matching(names.iter().map(String::as_str));
|
||||
}
|
||||
ArgType::Objective => {
|
||||
builder.suggest_matching(reg.objectives.iter().map(String::as_str))
|
||||
}
|
||||
ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)),
|
||||
ArgType::Criteria => {
|
||||
let mut ids: Vec<String> = crate::scoreboard::CUSTOM_CRITERIA
|
||||
.iter()
|
||||
.map(|s| (*s).to_owned())
|
||||
.collect();
|
||||
for c in crate::scoreboard::team_colors() {
|
||||
ids.push(format!("teamkill.{c}"));
|
||||
ids.push(format!("killedByTeam.{c}"));
|
||||
}
|
||||
let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key);
|
||||
ids.extend(reg.blocks.keys().map(|b| stat("mined", b)));
|
||||
for ty in ["crafted", "used", "broken", "picked_up", "dropped"] {
|
||||
ids.extend(reg.items.iter().map(|i| stat(ty, i)));
|
||||
}
|
||||
for ty in ["killed", "killed_by"] {
|
||||
ids.extend(reg.entity_types.iter().map(|e| stat(ty, e)));
|
||||
}
|
||||
ids.extend(
|
||||
crate::scoreboard::CUSTOM_STATS
|
||||
.iter()
|
||||
.map(|c| stat("custom", &format!("minecraft:{c}"))),
|
||||
);
|
||||
builder.suggest_matching(ids.iter().map(String::as_str));
|
||||
}
|
||||
ArgType::ScoreboardSlot => {
|
||||
let slots = crate::scoreboard::display_slots();
|
||||
builder.suggest_matching(slots.iter().map(String::as_str));
|
||||
}
|
||||
ArgType::Operation => builder.suggest_matching(OPERATIONS),
|
||||
ArgType::Enum(words) => builder.suggest_matching(words.iter().copied()),
|
||||
ArgType::Particle => {
|
||||
let names: Vec<String> = crate::particles::ParticleType::ALL
|
||||
.iter()
|
||||
.map(|t| format!("minecraft:{}", t.name()))
|
||||
.collect();
|
||||
suggest_resources(builder, &names, "");
|
||||
}
|
||||
ArgType::Vec2 | ArgType::ColumnPos => builder.suggest_matching(["~", "~ ~"]),
|
||||
ArgType::Name(list) => {
|
||||
let names = match *list {
|
||||
"datapacks_enabled" => reg.datapacks_enabled.clone(),
|
||||
_ => reg.datapacks_disabled.clone(),
|
||||
};
|
||||
builder.suggest_matching(names.iter().map(String::as_str));
|
||||
}
|
||||
ArgType::Function => {
|
||||
let functions = reg.functions.clone();
|
||||
suggest_resources(builder, &functions, "");
|
||||
let tags = reg.function_tags.clone();
|
||||
suggest_resources(builder, &tags, "#");
|
||||
}
|
||||
ArgType::Slots | ArgType::Slot => {
|
||||
let mut names = slot_names();
|
||||
if matches!(self, ArgType::Slots) {
|
||||
names.extend(SLOT_GROUPS.iter().map(|s| (*s).to_owned()));
|
||||
}
|
||||
builder.suggest_matching(names.iter().map(String::as_str));
|
||||
}
|
||||
ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()),
|
||||
ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]),
|
||||
ArgType::Swizzle | ArgType::Component => {}
|
||||
ArgType::Message => {
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
//! usage text and the vanilla error messages. Argument types live in
|
||||
//! [`args`]; the vanilla command tree in [`vanilla`].
|
||||
pub mod args;
|
||||
pub mod tree_data;
|
||||
pub mod tree_execute;
|
||||
pub mod tree_misc;
|
||||
pub mod tree_scoreboard;
|
||||
pub mod tree_world;
|
||||
pub mod vanilla;
|
||||
|
||||
use crate::text::Text;
|
||||
|
||||
@@ -215,3 +215,262 @@ fn local_coordinates_follow_view() {
|
||||
]);
|
||||
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_and_tag_commands_parse() {
|
||||
let (id, args) = run("data get entity @s Pos 2.5").unwrap();
|
||||
assert_eq!(id, "data.get");
|
||||
assert_eq!(args, ["target", "path", "scale"]);
|
||||
assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get");
|
||||
assert_eq!(run("data get storage my:store").unwrap().0, "data.get");
|
||||
assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge");
|
||||
assert_eq!(
|
||||
run("data remove entity @s foo.bar[1]").unwrap().0,
|
||||
"data.remove"
|
||||
);
|
||||
let (id, args) = run("data modify storage a:b x.y insert 2 from entity @s Pos[0]").unwrap();
|
||||
assert_eq!(id, "data.modify");
|
||||
assert_eq!(
|
||||
args,
|
||||
["target", "targetPath", "index", "source", "sourcePath"]
|
||||
);
|
||||
assert_eq!(
|
||||
run("data modify block 1 2 3 Text1 set string storage a:b x 1 3")
|
||||
.unwrap()
|
||||
.0,
|
||||
"data.modify"
|
||||
);
|
||||
assert_eq!(
|
||||
run("data modify storage a:b l append value [1,2]")
|
||||
.unwrap()
|
||||
.0,
|
||||
"data.modify"
|
||||
);
|
||||
assert!(run("data modify storage a:b l explode value 1").is_err());
|
||||
assert!(run("data get storage a:b {broken").is_err());
|
||||
assert!(run("data merge storage a:b 5").is_err());
|
||||
assert_eq!(run("tag @e[tag=!x] add foo").unwrap().0, "tag.add");
|
||||
assert_eq!(run("tag @s list").unwrap().0, "tag.list");
|
||||
// Selector options added for scoreboards and NBT.
|
||||
assert!(run("kill @e[scores={a=1..},team=red,nbt={x:1b},tag=t]").is_ok());
|
||||
assert!(run("kill @e[scores={a=1..]").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoke_commands_parse() {
|
||||
for line in [
|
||||
"tag @s list",
|
||||
"random value 1..6",
|
||||
"team list",
|
||||
"data get storage a:b",
|
||||
"scoreboard objectives list",
|
||||
"function test:a",
|
||||
"execute store result score #r t run function test:a",
|
||||
"schedule function test:a 20t",
|
||||
"datapack list",
|
||||
"bossbar list",
|
||||
"item replace entity @s hotbar.0 with minecraft:stone 3",
|
||||
] {
|
||||
assert!(run(line).is_ok(), "{line}: {:?}", run(line).err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_tree_covers_vanilla_forms() {
|
||||
for line in [
|
||||
"execute as @a at @s run say hi",
|
||||
"execute store result score @s x run data get entity @s Health",
|
||||
"execute store success bossbar minecraft:b value run say hi",
|
||||
"execute store result storage a:b out int 1.5 run time query gametime",
|
||||
"execute store result entity @s Air short 1 run say hi",
|
||||
"execute if score @s a = @s b run say hi",
|
||||
"execute unless score @s a matches ..5 run say hi",
|
||||
"execute if block ~ ~ ~ minecraft:stone",
|
||||
"execute if blocks 0 0 0 1 1 1 5 5 5 masked run say hi",
|
||||
"execute if biome ~ ~ ~ minecraft:plains",
|
||||
"execute if loaded ~ ~ ~",
|
||||
"execute if dimension minecraft:overworld",
|
||||
"execute if data entity @s Inventory[0]",
|
||||
"execute unless data storage a:b x run say hi",
|
||||
"execute if predicate a:b",
|
||||
"execute if function a:b run say hi",
|
||||
"execute if items entity @s hotbar.* minecraft:stone",
|
||||
"execute if slots block 0 0 0 container.*",
|
||||
"execute positioned over world_surface run say hi",
|
||||
"execute summon minecraft:pig run say hi",
|
||||
"execute on vehicle run say hi",
|
||||
"execute on passengers as @s run say hi",
|
||||
"execute rotated as @s facing entity @s eyes align xyz anchored feet in minecraft:overworld run say hi",
|
||||
] {
|
||||
assert!(run(line).is_ok(), "{line}: {:?}", run(line).err());
|
||||
}
|
||||
assert!(run("execute positioned over nothing run say hi").is_err());
|
||||
assert!(run("execute on nobody run say hi").is_err());
|
||||
assert!(run("execute store result score @s").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_and_misc_trees() {
|
||||
assert_eq!(run("function a:b").unwrap().0, "function");
|
||||
assert_eq!(run("function #a:tag {x:1}").unwrap().0, "function");
|
||||
assert_eq!(
|
||||
run("function a:b with storage c:d path.x").unwrap().0,
|
||||
"function"
|
||||
);
|
||||
assert_eq!(run("return 5").unwrap().0, "return.value");
|
||||
assert_eq!(run("return fail").unwrap().0, "return.fail");
|
||||
assert_eq!(run("return run say hi").unwrap().0, "say");
|
||||
assert_eq!(
|
||||
run("schedule function a:b 5s append").unwrap().0,
|
||||
"schedule.function"
|
||||
);
|
||||
assert_eq!(run("schedule clear a:b").unwrap().0, "schedule.clear");
|
||||
assert_eq!(run("random roll 1..20").unwrap().0, "random.roll");
|
||||
assert_eq!(
|
||||
run("random reset * 5 true false").unwrap().0,
|
||||
"random.reset"
|
||||
);
|
||||
assert_eq!(run("teammsg hi there").unwrap().0, "teammsg");
|
||||
assert_eq!(run("tm hi").unwrap().0, "teammsg");
|
||||
assert_eq!(
|
||||
run("bossbar set a:b color pink").unwrap().0,
|
||||
"bossbar.set.color"
|
||||
);
|
||||
assert_eq!(
|
||||
run("bossbar set a:b players @a").unwrap().0,
|
||||
"bossbar.set.players"
|
||||
);
|
||||
assert_eq!(run("bossbar get a:b max").unwrap().0, "bossbar.get");
|
||||
assert_eq!(
|
||||
run("item fill block 1 2 3 container.* with minecraft:stone 5")
|
||||
.unwrap()
|
||||
.0,
|
||||
"item"
|
||||
);
|
||||
assert_eq!(
|
||||
run("item replace entity @s armor.head from block 0 0 0 container.3")
|
||||
.unwrap()
|
||||
.0,
|
||||
"item"
|
||||
);
|
||||
assert_eq!(run("tick rate 40").unwrap().0, "tick.rate");
|
||||
assert_eq!(run("tick step 1s").unwrap().0, "tick.step");
|
||||
assert_eq!(run("reload").unwrap().0, "reload");
|
||||
assert_eq!(
|
||||
run("datapack enable \"file/x\" after \"file/y\"")
|
||||
.unwrap()
|
||||
.0,
|
||||
"datapack.enable"
|
||||
);
|
||||
assert!(run("bossbar set a:b value -1").is_err());
|
||||
assert!(run("item replace entity @s nowhere.0 with minecraft:stone").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_command_trees() {
|
||||
for (line, id) in [
|
||||
("recipe give @s *", "recipe.give"),
|
||||
("recipe take @a minecraft:stick", "recipe.take"),
|
||||
("damage @e[limit=1] 5", "damage"),
|
||||
(
|
||||
"damage @s 3.5 minecraft:magic by @e[limit=1] from @s",
|
||||
"damage",
|
||||
),
|
||||
("damage @s 3 minecraft:fall at ~ ~ ~", "damage"),
|
||||
("rotate @s 90 0", "rotate"),
|
||||
("rotate @s facing entity @e[limit=1] eyes", "rotate"),
|
||||
("rotate @s facing 0 64 0", "rotate"),
|
||||
("swing", "swing"),
|
||||
("swing @e offhand whack 10", "swing"),
|
||||
("playsound minecraft:entity.cow.ambient", "playsound"),
|
||||
(
|
||||
"playsound minecraft:block.stone.break block @s ~ ~ ~ 1 1 0.5",
|
||||
"playsound",
|
||||
),
|
||||
("stopsound @s", "stopsound"),
|
||||
("stopsound @s * minecraft:ambient.cave", "stopsound"),
|
||||
("stopsound @s music minecraft:music.game", "stopsound"),
|
||||
("particle minecraft:smoke", "particle"),
|
||||
(
|
||||
"particle minecraft:dust 1 0 0 2 ~ ~ ~ 0.1 0.1 0.1 0 10 force @a",
|
||||
"particle",
|
||||
),
|
||||
("particle minecraft:block minecraft:stone ~ ~ ~", "particle"),
|
||||
("attribute @s minecraft:max_health get 2", "attribute.get"),
|
||||
(
|
||||
"attribute @s minecraft:max_health base set 40",
|
||||
"attribute.base.set",
|
||||
),
|
||||
(
|
||||
"attribute @s minecraft:scale modifier add a:b 1.5 add_multiplied_base",
|
||||
"attribute.modifier.add",
|
||||
),
|
||||
(
|
||||
"attribute @s minecraft:scale modifier remove a:b",
|
||||
"attribute.modifier.remove",
|
||||
),
|
||||
(
|
||||
"attribute @s minecraft:scale modifier value get a:b 2",
|
||||
"attribute.modifier.get",
|
||||
),
|
||||
("ride @s mount @e[limit=1]", "ride.mount"),
|
||||
("ride @s dismount", "ride.dismount"),
|
||||
("spreadplayers 0 0 5 20 false @a", "spreadplayers"),
|
||||
("spreadplayers ~ ~ 5 20 under 100 true @e", "spreadplayers"),
|
||||
("forceload add 0 0 100 100", "forceload.add"),
|
||||
("forceload remove all", "forceload.remove.all"),
|
||||
("forceload query", "forceload.query"),
|
||||
("forceload query ~ ~", "forceload.query"),
|
||||
(
|
||||
"fillbiome 0 0 0 10 10 10 minecraft:plains replace minecraft:desert",
|
||||
"fillbiome",
|
||||
),
|
||||
("worldborder set 100 5s", "worldborder.set"),
|
||||
("worldborder add -10", "worldborder.add"),
|
||||
("worldborder center 5 5", "worldborder.center"),
|
||||
("worldborder damage amount 1", "worldborder.damage.amount"),
|
||||
("worldborder warning time 10s", "worldborder.warning.time"),
|
||||
("worldborder get", "worldborder.get"),
|
||||
(
|
||||
"loot give @s loot minecraft:chests/simple_dungeon",
|
||||
"loot.loot",
|
||||
),
|
||||
("loot spawn ~ ~ ~ kill @e[limit=1]", "loot.kill"),
|
||||
("loot insert 0 0 0 mine 1 2 3 mainhand", "loot.mine"),
|
||||
(
|
||||
"loot replace entity @s hotbar.0 3 fish minecraft:gameplay/fishing 0 0 0",
|
||||
"loot.fish",
|
||||
),
|
||||
(
|
||||
"loot replace block 1 2 3 container.5 loot minecraft:chests/x",
|
||||
"loot.loot",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0,
|
||||
id,
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
assert!(run("playsound minecraft:x invalid_source").is_err());
|
||||
assert!(run("particle minecraft:not_a_particle").is_err());
|
||||
assert!(run("damage @s -1").is_err());
|
||||
assert!(run("spreadplayers 0 0 5 0 false @a").is_err());
|
||||
assert!(run("worldborder warning distance -1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn place_template_tree() {
|
||||
for line in [
|
||||
"place template minecraft:igloo/top",
|
||||
"place template minecraft:igloo/top ~ ~ ~",
|
||||
"place template minecraft:igloo/top 1 2 3 clockwise_90 left_right 0.5 12 strict",
|
||||
] {
|
||||
assert_eq!(
|
||||
run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0,
|
||||
"place"
|
||||
);
|
||||
}
|
||||
assert!(run("place template minecraft:x ~ ~ ~ sideways").is_err());
|
||||
assert!(run("place template minecraft:x ~ ~ ~ none none 2").is_err());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The `/data` and `/tag` command trees (DataCommands, TagCommand).
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITIES, GAMEMASTERS},
|
||||
};
|
||||
|
||||
const ENTITY: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
};
|
||||
|
||||
/// `ArgProvider.wrap` for each of entity, block and storage: calls `then`
|
||||
/// with the node holding the provider's argument.
|
||||
fn providers(
|
||||
d: &mut Dispatcher,
|
||||
parent: usize,
|
||||
role: &str,
|
||||
mut then: impl FnMut(&mut Dispatcher, usize),
|
||||
) {
|
||||
let e = d.literal(parent, "entity");
|
||||
let a = d.argument(e, role, ENTITY);
|
||||
then(d, a);
|
||||
let b = d.literal(parent, "block");
|
||||
let a = d.argument(b, &format!("{role}Pos"), ArgType::BlockPos);
|
||||
then(d, a);
|
||||
let s = d.literal(parent, "storage");
|
||||
let a = d.argument(s, role, ArgType::Id("storages"));
|
||||
then(d, a);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let data = d.literal(root, "data");
|
||||
d.requires(data, GAMEMASTERS);
|
||||
|
||||
let merge = d.literal(data, "merge");
|
||||
providers(d, merge, "target", |d, a| {
|
||||
let nbt = d.argument(a, "nbt", ArgType::Nbt);
|
||||
d.executes(nbt, "data.merge");
|
||||
});
|
||||
let get = d.literal(data, "get");
|
||||
providers(d, get, "target", |d, a| {
|
||||
d.executes(a, "data.get");
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "data.get");
|
||||
let scale = d.argument(
|
||||
path,
|
||||
"scale",
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(scale, "data.get");
|
||||
});
|
||||
let remove = d.literal(data, "remove");
|
||||
providers(d, remove, "target", |d, a| {
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "data.remove");
|
||||
});
|
||||
let modify = d.literal(data, "modify");
|
||||
providers(d, modify, "target", |d, a| {
|
||||
let target_path = d.argument(a, "targetPath", ArgType::NbtPath);
|
||||
// insert <index> | prepend | append | set | merge, then the source.
|
||||
let mut ops = Vec::new();
|
||||
let insert = d.literal(target_path, "insert");
|
||||
let index = d.argument(
|
||||
insert,
|
||||
"index",
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
);
|
||||
ops.push(index);
|
||||
for op in ["prepend", "append", "set", "merge"] {
|
||||
ops.push(d.literal(target_path, op));
|
||||
}
|
||||
for op in ops {
|
||||
let from = d.literal(op, "from");
|
||||
providers(d, from, "source", |d, s| {
|
||||
d.executes(s, "data.modify");
|
||||
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
|
||||
d.executes(sp, "data.modify");
|
||||
});
|
||||
let string = d.literal(op, "string");
|
||||
providers(d, string, "source", |d, s| {
|
||||
d.executes(s, "data.modify");
|
||||
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
|
||||
d.executes(sp, "data.modify");
|
||||
let int = || ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
};
|
||||
let start = d.argument(sp, "start", int());
|
||||
d.executes(start, "data.modify");
|
||||
let end = d.argument(start, "end", int());
|
||||
d.executes(end, "data.modify");
|
||||
});
|
||||
let value = d.literal(op, "value");
|
||||
let v = d.argument(value, "value", ArgType::NbtTag);
|
||||
d.executes(v, "data.modify");
|
||||
}
|
||||
});
|
||||
|
||||
// tag <targets> add|remove <name> | list
|
||||
let tag = d.literal(root, "tag");
|
||||
d.requires(tag, GAMEMASTERS);
|
||||
let targets = d.argument(tag, "targets", ENTITIES);
|
||||
for word in ["add", "remove"] {
|
||||
let w = d.literal(targets, word);
|
||||
let name = d.argument(w, "name", ArgType::Word);
|
||||
d.executes(
|
||||
name,
|
||||
if word == "add" {
|
||||
"tag.add"
|
||||
} else {
|
||||
"tag.remove"
|
||||
},
|
||||
);
|
||||
}
|
||||
let list = d.literal(targets, "list");
|
||||
d.executes(list, "tag.list");
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The `/execute` tree (ExecuteCommand): modifiers redirect back to
|
||||
//! `execute`, `run` to the root; conditions both execute (as a test) and
|
||||
//! continue the chain; `store` redirects with a result callback.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, Resource},
|
||||
vanilla::{ENTITIES, GAMEMASTERS},
|
||||
};
|
||||
|
||||
pub const HEIGHTMAPS: &[&str] = &[
|
||||
"world_surface",
|
||||
"motion_blocking",
|
||||
"motion_blocking_no_leaves",
|
||||
"ocean_floor",
|
||||
];
|
||||
pub const RELATIONS: [&str; 8] = [
|
||||
"owner",
|
||||
"leasher",
|
||||
"target",
|
||||
"attacker",
|
||||
"vehicle",
|
||||
"controller",
|
||||
"origin",
|
||||
"passengers",
|
||||
];
|
||||
|
||||
/// A conditional's end: it runs as a test and continues the chain.
|
||||
fn conditional(d: &mut Dispatcher, node: usize, ex: usize) {
|
||||
d.executes(node, "execute");
|
||||
d.redirect(node, ex);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let ex = d.literal(root, "execute");
|
||||
d.requires(ex, GAMEMASTERS);
|
||||
let run = d.literal(ex, "run");
|
||||
d.redirect(run, root);
|
||||
for name in ["as", "at"] {
|
||||
let l = d.literal(ex, name);
|
||||
let t = d.argument(l, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
}
|
||||
let positioned = d.literal(ex, "positioned");
|
||||
let pos = d.argument(positioned, "pos", ArgType::Vec3 { center: true });
|
||||
d.redirect(pos, ex);
|
||||
let as_ = d.literal(positioned, "as");
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let over = d.literal(positioned, "over");
|
||||
let hm = d.argument(over, "heightmap", ArgType::Enum(HEIGHTMAPS));
|
||||
d.redirect(hm, ex);
|
||||
let rotated = d.literal(ex, "rotated");
|
||||
let rot = d.argument(rotated, "rot", ArgType::Rotation);
|
||||
d.redirect(rot, ex);
|
||||
let as_ = d.literal(rotated, "as");
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let facing = d.literal(ex, "facing");
|
||||
let pos = d.argument(facing, "pos", ArgType::Vec3 { center: true });
|
||||
d.redirect(pos, ex);
|
||||
let entity = d.literal(facing, "entity");
|
||||
let t = d.argument(entity, "targets", ENTITIES);
|
||||
let anchor = d.argument(t, "anchor", ArgType::Anchor);
|
||||
d.redirect(anchor, ex);
|
||||
let align = d.literal(ex, "align");
|
||||
let axes = d.argument(align, "axes", ArgType::Swizzle);
|
||||
d.redirect(axes, ex);
|
||||
let anchored = d.literal(ex, "anchored");
|
||||
let anchor = d.argument(anchored, "anchor", ArgType::Anchor);
|
||||
d.redirect(anchor, ex);
|
||||
let in_ = d.literal(ex, "in");
|
||||
let dim = d.argument(in_, "dimension", ArgType::Dimension);
|
||||
d.redirect(dim, ex);
|
||||
let summon = d.literal(ex, "summon");
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.redirect(e, ex);
|
||||
let on = d.literal(ex, "on");
|
||||
for r in RELATIONS {
|
||||
let l = d.literal(on, r);
|
||||
d.redirect(l, ex);
|
||||
}
|
||||
store(d, ex);
|
||||
for mode in ["if", "unless"] {
|
||||
let m = d.literal(ex, mode);
|
||||
conditionals(d, m, ex);
|
||||
}
|
||||
}
|
||||
|
||||
fn store(d: &mut Dispatcher, ex: usize) {
|
||||
let store = d.literal(ex, "store");
|
||||
for kind in ["result", "success"] {
|
||||
let k = d.literal(store, kind);
|
||||
let score = d.literal(k, "score");
|
||||
let targets = d.argument(score, "targets", ArgType::ScoreHolder { multiple: true });
|
||||
let objective = d.argument(targets, "objective", ArgType::Objective);
|
||||
d.redirect(objective, ex);
|
||||
let bossbar = d.literal(k, "bossbar");
|
||||
let id = d.argument(bossbar, "id", ArgType::Id("bossbars"));
|
||||
for what in ["value", "max"] {
|
||||
let w = d.literal(id, what);
|
||||
d.redirect(w, ex);
|
||||
}
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
let p = d.literal(k, provider);
|
||||
let a = match provider {
|
||||
"entity" => d.argument(
|
||||
p,
|
||||
"target",
|
||||
ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
},
|
||||
),
|
||||
"block" => d.argument(p, "targetPos", ArgType::BlockPos),
|
||||
_ => d.argument(p, "target", ArgType::Id("storages")),
|
||||
};
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
for ty in ["int", "float", "short", "long", "double", "byte"] {
|
||||
let t = d.literal(path, ty);
|
||||
let scale = d.argument(
|
||||
t,
|
||||
"scale",
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
);
|
||||
d.redirect(scale, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
|
||||
let block = d.literal(m, "block");
|
||||
let pos = d.argument(block, "pos", ArgType::BlockPos);
|
||||
let predicate = d.argument(pos, "block", ArgType::BlockPredicate);
|
||||
conditional(d, predicate, ex);
|
||||
|
||||
let biome = d.literal(m, "biome");
|
||||
let pos = d.argument(biome, "pos", ArgType::BlockPos);
|
||||
let b = d.argument(pos, "biome", ArgType::Resource(Resource::Biome));
|
||||
conditional(d, b, ex);
|
||||
|
||||
let loaded = d.literal(m, "loaded");
|
||||
let pos = d.argument(loaded, "pos", ArgType::BlockPos);
|
||||
conditional(d, pos, ex);
|
||||
|
||||
let dimension = d.literal(m, "dimension");
|
||||
let dim = d.argument(dimension, "dimension", ArgType::Dimension);
|
||||
conditional(d, dim, ex);
|
||||
|
||||
let score = d.literal(m, "score");
|
||||
let target = d.argument(score, "target", ArgType::ScoreHolder { multiple: false });
|
||||
let objective = d.argument(target, "targetObjective", ArgType::Objective);
|
||||
for op in ["=", "<", "<=", ">", ">="] {
|
||||
let o = d.literal(objective, op);
|
||||
let source = d.argument(o, "source", ArgType::ScoreHolder { multiple: false });
|
||||
let so = d.argument(source, "sourceObjective", ArgType::Objective);
|
||||
conditional(d, so, ex);
|
||||
}
|
||||
let matches = d.literal(objective, "matches");
|
||||
let range = d.argument(matches, "range", ArgType::IntRange);
|
||||
conditional(d, range, ex);
|
||||
|
||||
let blocks = d.literal(m, "blocks");
|
||||
let start = d.argument(blocks, "start", ArgType::BlockPos);
|
||||
let end = d.argument(start, "end", ArgType::BlockPos);
|
||||
let dest = d.argument(end, "destination", ArgType::BlockPos);
|
||||
for mode in ["all", "masked"] {
|
||||
let l = d.literal(dest, mode);
|
||||
conditional(d, l, ex);
|
||||
}
|
||||
|
||||
let entity = d.literal(m, "entity");
|
||||
let targets = d.argument(entity, "entities", ENTITIES);
|
||||
conditional(d, targets, ex);
|
||||
|
||||
let predicate = d.literal(m, "predicate");
|
||||
let p = d.argument(predicate, "predicate", ArgType::Id("predicates"));
|
||||
conditional(d, p, ex);
|
||||
|
||||
let function = d.literal(m, "function");
|
||||
let name = d.argument(function, "name", ArgType::Function);
|
||||
conditional(d, name, ex);
|
||||
|
||||
let data = d.literal(m, "data");
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
let p = d.literal(data, provider);
|
||||
let a = match provider {
|
||||
"entity" => d.argument(
|
||||
p,
|
||||
"source",
|
||||
ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
},
|
||||
),
|
||||
"block" => d.argument(p, "sourcePos", ArgType::BlockPos),
|
||||
_ => d.argument(p, "source", ArgType::Id("storages")),
|
||||
};
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
conditional(d, path, ex);
|
||||
}
|
||||
|
||||
// items / slots (entity|block) <slots> [<predicate>]
|
||||
for kind in ["items", "slots"] {
|
||||
let k = d.literal(m, kind);
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(k, provider);
|
||||
let a = if provider == "entity" {
|
||||
d.argument(
|
||||
p,
|
||||
"source",
|
||||
ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
d.argument(p, "sourcePos", ArgType::BlockPos)
|
||||
};
|
||||
let slots = d.argument(a, "slots", ArgType::Slots);
|
||||
if kind == "items" {
|
||||
let item = d.argument(slots, "item_predicate", ArgType::ItemPredicate);
|
||||
conditional(d, item, ex);
|
||||
} else {
|
||||
conditional(d, slots, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! Smaller command trees: `/bossbar`, `/function`, `/return`, `/schedule`,
|
||||
//! `/random`, `/tick`, `/teammsg`, `/reload` and `/datapack`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITIES, GAMEMASTERS, PLAYERS},
|
||||
};
|
||||
|
||||
fn int() -> ArgType {
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
}
|
||||
}
|
||||
fn int_min(min: i32) -> ArgType {
|
||||
ArgType::Integer { min, max: i32::MAX }
|
||||
}
|
||||
pub const ADMINS: u8 = 3;
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
item(d, root);
|
||||
bossbar(d, root);
|
||||
function(d, root);
|
||||
|
||||
// return <value> | fail | run <command>
|
||||
let ret = d.literal(root, "return");
|
||||
d.requires(ret, GAMEMASTERS);
|
||||
let v = d.argument(ret, "value", int());
|
||||
d.executes(v, "return.value");
|
||||
let fail = d.literal(ret, "fail");
|
||||
d.executes(fail, "return.fail");
|
||||
let run = d.literal(ret, "run");
|
||||
d.redirect(run, root);
|
||||
|
||||
// schedule function <function> <time> [append|replace] | clear <function>
|
||||
let schedule = d.literal(root, "schedule");
|
||||
d.requires(schedule, GAMEMASTERS);
|
||||
let f = d.literal(schedule, "function");
|
||||
let name = d.argument(f, "function", ArgType::Function);
|
||||
let time = d.argument(name, "time", ArgType::Time { min: 0 });
|
||||
d.executes(time, "schedule.function");
|
||||
for mode in ["append", "replace"] {
|
||||
let m = d.literal(time, mode);
|
||||
d.executes(m, "schedule.function");
|
||||
}
|
||||
let clear = d.literal(schedule, "clear");
|
||||
let id = d.argument(clear, "function", ArgType::Id("schedules"));
|
||||
d.executes(id, "schedule.clear");
|
||||
|
||||
// random (value|roll) <range> [<sequence>] | reset (*|<sequence>) ...
|
||||
let random = d.literal(root, "random");
|
||||
for kind in ["value", "roll"] {
|
||||
let k = d.literal(random, kind);
|
||||
let range = d.argument(k, "range", ArgType::IntRange);
|
||||
let id = if kind == "value" {
|
||||
"random.value"
|
||||
} else {
|
||||
"random.roll"
|
||||
};
|
||||
d.executes(range, id);
|
||||
let seq = d.argument(range, "sequence", ArgType::Id("random_sequences"));
|
||||
d.requires(seq, GAMEMASTERS);
|
||||
d.executes(seq, id);
|
||||
}
|
||||
let reset = d.literal(random, "reset");
|
||||
d.requires(reset, GAMEMASTERS);
|
||||
let all = d.literal(reset, "*");
|
||||
d.executes(all, "random.reset");
|
||||
let seq = d.argument(reset, "sequence", ArgType::Id("random_sequences"));
|
||||
d.executes(seq, "random.reset");
|
||||
for parent in [all, seq] {
|
||||
let seed = d.argument(parent, "seed", int());
|
||||
d.executes(seed, "random.reset");
|
||||
let world = d.argument(seed, "includeWorldSeed", ArgType::Bool);
|
||||
d.executes(world, "random.reset");
|
||||
let seq_id = d.argument(world, "includeSequenceId", ArgType::Bool);
|
||||
d.executes(seq_id, "random.reset");
|
||||
}
|
||||
|
||||
// tick query | rate <rate> | step [stop|<time>] | sprint (stop|<time>) | freeze | unfreeze
|
||||
let tick = d.literal(root, "tick");
|
||||
d.requires(tick, ADMINS);
|
||||
let q = d.literal(tick, "query");
|
||||
d.executes(q, "tick.query");
|
||||
let rate = d.literal(tick, "rate");
|
||||
let r = d.argument(
|
||||
rate,
|
||||
"rate",
|
||||
ArgType::Float {
|
||||
min: 1.0,
|
||||
max: 10000.0,
|
||||
},
|
||||
);
|
||||
d.executes(r, "tick.rate");
|
||||
let step = d.literal(tick, "step");
|
||||
d.executes(step, "tick.step");
|
||||
let stop = d.literal(step, "stop");
|
||||
d.executes(stop, "tick.step.stop");
|
||||
let t = d.argument(step, "time", ArgType::Time { min: 1 });
|
||||
d.executes(t, "tick.step");
|
||||
let sprint = d.literal(tick, "sprint");
|
||||
let stop = d.literal(sprint, "stop");
|
||||
d.executes(stop, "tick.sprint.stop");
|
||||
let t = d.argument(sprint, "time", ArgType::Time { min: 1 });
|
||||
d.executes(t, "tick.sprint");
|
||||
let unfreeze = d.literal(tick, "unfreeze");
|
||||
d.executes(unfreeze, "tick.unfreeze");
|
||||
let freeze = d.literal(tick, "freeze");
|
||||
d.executes(freeze, "tick.freeze");
|
||||
|
||||
// teammsg / tm <message>
|
||||
let teammsg = d.literal(root, "teammsg");
|
||||
let m = d.argument(teammsg, "message", ArgType::Message);
|
||||
d.executes(m, "teammsg");
|
||||
let tm = d.literal(root, "tm");
|
||||
d.redirect(tm, teammsg);
|
||||
|
||||
// reload
|
||||
let reload = d.literal(root, "reload");
|
||||
d.requires(reload, GAMEMASTERS);
|
||||
d.executes(reload, "reload");
|
||||
|
||||
// datapack list [available|enabled] | enable|disable <name> ...
|
||||
let datapack = d.literal(root, "datapack");
|
||||
d.requires(datapack, GAMEMASTERS);
|
||||
let list = d.literal(datapack, "list");
|
||||
d.executes(list, "datapack.list");
|
||||
for w in ["available", "enabled"] {
|
||||
let l = d.literal(list, w);
|
||||
d.executes(l, "datapack.list");
|
||||
}
|
||||
let enable = d.literal(datapack, "enable");
|
||||
let name = d.argument(enable, "name", ArgType::Name("datapacks_disabled"));
|
||||
d.executes(name, "datapack.enable");
|
||||
for w in ["first", "last"] {
|
||||
let l = d.literal(name, w);
|
||||
d.executes(l, "datapack.enable");
|
||||
}
|
||||
for w in ["before", "after"] {
|
||||
let l = d.literal(name, w);
|
||||
let other = d.argument(l, "existing", ArgType::Name("datapacks_enabled"));
|
||||
d.executes(other, "datapack.enable");
|
||||
}
|
||||
let disable = d.literal(datapack, "disable");
|
||||
let name = d.argument(disable, "name", ArgType::Name("datapacks_enabled"));
|
||||
d.executes(name, "datapack.disable");
|
||||
}
|
||||
|
||||
/// `item (replace|fill|override) (entity|block) <target> <slots> (with <item> [<count>] | from ...)`.
|
||||
fn item(d: &mut Dispatcher, root: usize) {
|
||||
let item = d.literal(root, "item");
|
||||
d.requires(item, GAMEMASTERS);
|
||||
for mode in ["replace", "fill", "override"] {
|
||||
let m = d.literal(item, mode);
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(m, provider);
|
||||
let target = if provider == "entity" {
|
||||
d.argument(p, "target", ENTITIES)
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slots = d.argument(target, "slots", ArgType::Slots);
|
||||
let with = d.literal(slots, "with");
|
||||
let it = d.argument(with, "item", ArgType::Item);
|
||||
d.executes(it, "item");
|
||||
let count = d.argument(it, "count", ArgType::Integer { min: 1, max: 99 });
|
||||
d.executes(count, "item");
|
||||
let from = d.literal(slots, "from");
|
||||
for src in ["entity", "block"] {
|
||||
let s = d.literal(from, src);
|
||||
let source = if src == "entity" {
|
||||
d.argument(s, "source", ENTITIES)
|
||||
} else {
|
||||
d.argument(s, "sourcePos", ArgType::BlockPos)
|
||||
};
|
||||
let source_slots = d.argument(source, "sourceSlots", ArgType::Slots);
|
||||
d.executes(source_slots, "item");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bossbar(d: &mut Dispatcher, root: usize) {
|
||||
let b = d.literal(root, "bossbar");
|
||||
d.requires(b, GAMEMASTERS);
|
||||
let add = d.literal(b, "add");
|
||||
let id = d.argument(add, "id", ArgType::Id("bossbars_new"));
|
||||
let name = d.argument(id, "name", ArgType::Component);
|
||||
d.executes(name, "bossbar.add");
|
||||
let remove = d.literal(b, "remove");
|
||||
let id = d.argument(remove, "id", ArgType::Id("bossbars"));
|
||||
d.executes(id, "bossbar.remove");
|
||||
let list = d.literal(b, "list");
|
||||
d.executes(list, "bossbar.list");
|
||||
let set = d.literal(b, "set");
|
||||
let id = d.argument(set, "id", ArgType::Id("bossbars"));
|
||||
let name_l = d.literal(id, "name");
|
||||
let name = d.argument(name_l, "name", ArgType::Component);
|
||||
d.executes(name, "bossbar.set.name");
|
||||
let color = d.literal(id, "color");
|
||||
for c in crate::bossbar::COLORS {
|
||||
let l = d.literal(color, c);
|
||||
d.executes(l, "bossbar.set.color");
|
||||
}
|
||||
let style = d.literal(id, "style");
|
||||
for s in crate::bossbar::STYLES {
|
||||
let l = d.literal(style, s);
|
||||
d.executes(l, "bossbar.set.style");
|
||||
}
|
||||
let value = d.literal(id, "value");
|
||||
let v = d.argument(value, "value", int_min(0));
|
||||
d.executes(v, "bossbar.set.value");
|
||||
let max = d.literal(id, "max");
|
||||
let v = d.argument(max, "max", int_min(1));
|
||||
d.executes(v, "bossbar.set.max");
|
||||
let visible = d.literal(id, "visible");
|
||||
let v = d.argument(visible, "visible", ArgType::Bool);
|
||||
d.executes(v, "bossbar.set.visible");
|
||||
let players = d.literal(id, "players");
|
||||
d.executes(players, "bossbar.set.players");
|
||||
let t = d.argument(players, "targets", PLAYERS);
|
||||
d.executes(t, "bossbar.set.players");
|
||||
let get = d.literal(b, "get");
|
||||
let id = d.argument(get, "id", ArgType::Id("bossbars"));
|
||||
for w in ["value", "max", "visible", "players"] {
|
||||
let l = d.literal(id, w);
|
||||
d.executes(l, "bossbar.get");
|
||||
}
|
||||
}
|
||||
|
||||
fn function(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "function");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
let name = d.argument(f, "name", ArgType::Function);
|
||||
d.executes(name, "function");
|
||||
let args = d.argument(name, "arguments", ArgType::Nbt);
|
||||
d.executes(args, "function");
|
||||
let with = d.literal(name, "with");
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
let p = d.literal(with, provider);
|
||||
let a = match provider {
|
||||
"entity" => d.argument(
|
||||
p,
|
||||
"source",
|
||||
ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
},
|
||||
),
|
||||
"block" => d.argument(p, "sourcePos", ArgType::BlockPos),
|
||||
_ => d.argument(p, "source", ArgType::Id("storages")),
|
||||
};
|
||||
d.executes(a, "function");
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "function");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The `/scoreboard`, `/team` and `/trigger` command trees
|
||||
//! (ScoreboardCommand, TeamCommand, TriggerCommand).
|
||||
use super::{Dispatcher, args::ArgType, vanilla::GAMEMASTERS};
|
||||
|
||||
const HOLDERS: ArgType = ArgType::ScoreHolder { multiple: true };
|
||||
const HOLDER: ArgType = ArgType::ScoreHolder { multiple: false };
|
||||
|
||||
/// `addNumberFormats`: blank | fixed <contents> | styled <style>, and the
|
||||
/// node itself clears the format.
|
||||
fn number_formats(d: &mut Dispatcher, top: usize, id: &'static str) {
|
||||
d.executes(top, id);
|
||||
let blank = d.literal(top, "blank");
|
||||
d.executes(blank, id);
|
||||
let fixed = d.literal(top, "fixed");
|
||||
let contents = d.argument(fixed, "contents", ArgType::Component);
|
||||
d.executes(contents, id);
|
||||
let styled = d.literal(top, "styled");
|
||||
let style = d.argument(styled, "style", ArgType::Component);
|
||||
d.executes(style, id);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
scoreboard(d, root);
|
||||
team(d, root);
|
||||
|
||||
// trigger <objective> [add|set <value>]
|
||||
let trigger = d.literal(root, "trigger");
|
||||
let objective = d.argument(trigger, "objective", ArgType::Objective);
|
||||
d.executes(objective, "trigger");
|
||||
for mode in ["add", "set"] {
|
||||
let m = d.literal(objective, mode);
|
||||
let v = d.argument(
|
||||
m,
|
||||
"value",
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(
|
||||
v,
|
||||
if mode == "add" {
|
||||
"trigger.add"
|
||||
} else {
|
||||
"trigger.set"
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn scoreboard(d: &mut Dispatcher, root: usize) {
|
||||
let sb = d.literal(root, "scoreboard");
|
||||
d.requires(sb, GAMEMASTERS);
|
||||
|
||||
let objectives = d.literal(sb, "objectives");
|
||||
let list = d.literal(objectives, "list");
|
||||
d.executes(list, "scoreboard.objectives.list");
|
||||
let add = d.literal(objectives, "add");
|
||||
let name = d.argument(add, "objective", ArgType::Word);
|
||||
let criteria = d.argument(name, "criteria", ArgType::Criteria);
|
||||
d.executes(criteria, "scoreboard.objectives.add");
|
||||
let display = d.argument(criteria, "displayName", ArgType::Component);
|
||||
d.executes(display, "scoreboard.objectives.add");
|
||||
let modify = d.literal(objectives, "modify");
|
||||
let objective = d.argument(modify, "objective", ArgType::Objective);
|
||||
let dn = d.literal(objective, "displayname");
|
||||
let display = d.argument(dn, "displayName", ArgType::Component);
|
||||
d.executes(display, "scoreboard.objectives.modify.displayname");
|
||||
let rt = d.literal(objective, "rendertype");
|
||||
for kind in ["integer", "hearts"] {
|
||||
let k = d.literal(rt, kind);
|
||||
d.executes(k, "scoreboard.objectives.modify.rendertype");
|
||||
}
|
||||
let au = d.literal(objective, "displayautoupdate");
|
||||
let v = d.argument(au, "value", ArgType::Bool);
|
||||
d.executes(v, "scoreboard.objectives.modify.displayautoupdate");
|
||||
let nf = d.literal(objective, "numberformat");
|
||||
number_formats(d, nf, "scoreboard.objectives.modify.numberformat");
|
||||
let remove = d.literal(objectives, "remove");
|
||||
let objective = d.argument(remove, "objective", ArgType::Objective);
|
||||
d.executes(objective, "scoreboard.objectives.remove");
|
||||
let setdisplay = d.literal(objectives, "setdisplay");
|
||||
let slot = d.argument(setdisplay, "slot", ArgType::ScoreboardSlot);
|
||||
d.executes(slot, "scoreboard.objectives.setdisplay");
|
||||
let objective = d.argument(slot, "objective", ArgType::Objective);
|
||||
d.executes(objective, "scoreboard.objectives.setdisplay");
|
||||
|
||||
let players = d.literal(sb, "players");
|
||||
let list = d.literal(players, "list");
|
||||
d.executes(list, "scoreboard.players.list");
|
||||
let target = d.argument(list, "target", HOLDER);
|
||||
d.executes(target, "scoreboard.players.list");
|
||||
// set / add / remove <targets> <objective> <score>
|
||||
for (word, min, id) in [
|
||||
("set", i32::MIN, "scoreboard.players.set"),
|
||||
("add", 0, "scoreboard.players.add"),
|
||||
("remove", 0, "scoreboard.players.remove"),
|
||||
] {
|
||||
let w = d.literal(players, word);
|
||||
let t = d.argument(w, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
let s = d.argument(o, "score", ArgType::Integer { min, max: i32::MAX });
|
||||
d.executes(s, id);
|
||||
}
|
||||
let get = d.literal(players, "get");
|
||||
let t = d.argument(get, "target", HOLDER);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.get");
|
||||
let reset = d.literal(players, "reset");
|
||||
let t = d.argument(reset, "targets", HOLDERS);
|
||||
d.executes(t, "scoreboard.players.reset");
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.reset");
|
||||
let enable = d.literal(players, "enable");
|
||||
let t = d.argument(enable, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.enable");
|
||||
let display = d.literal(players, "display");
|
||||
let name = d.literal(display, "name");
|
||||
let t = d.argument(name, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.executes(o, "scoreboard.players.display.name");
|
||||
let n = d.argument(o, "name", ArgType::Component);
|
||||
d.executes(n, "scoreboard.players.display.name");
|
||||
let nf = d.literal(display, "numberformat");
|
||||
let t = d.argument(nf, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
number_formats(d, o, "scoreboard.players.display.numberformat");
|
||||
let operation = d.literal(players, "operation");
|
||||
let t = d.argument(operation, "targets", HOLDERS);
|
||||
let to = d.argument(t, "targetObjective", ArgType::Objective);
|
||||
let op = d.argument(to, "operation", ArgType::Operation);
|
||||
let source = d.argument(op, "source", HOLDERS);
|
||||
let so = d.argument(source, "sourceObjective", ArgType::Objective);
|
||||
d.executes(so, "scoreboard.players.operation");
|
||||
}
|
||||
|
||||
fn team(d: &mut Dispatcher, root: usize) {
|
||||
let team = d.literal(root, "team");
|
||||
d.requires(team, GAMEMASTERS);
|
||||
let list = d.literal(team, "list");
|
||||
d.executes(list, "team.list");
|
||||
let t = d.argument(list, "team", ArgType::Team);
|
||||
d.executes(t, "team.list");
|
||||
let add = d.literal(team, "add");
|
||||
let t = d.argument(add, "team", ArgType::Word);
|
||||
d.executes(t, "team.add");
|
||||
let dn = d.argument(t, "displayName", ArgType::Component);
|
||||
d.executes(dn, "team.add");
|
||||
let remove = d.literal(team, "remove");
|
||||
let t = d.argument(remove, "team", ArgType::Team);
|
||||
d.executes(t, "team.remove");
|
||||
let empty = d.literal(team, "empty");
|
||||
let t = d.argument(empty, "team", ArgType::Team);
|
||||
d.executes(t, "team.empty");
|
||||
let join = d.literal(team, "join");
|
||||
let t = d.argument(join, "team", ArgType::Team);
|
||||
d.executes(t, "team.join");
|
||||
let m = d.argument(t, "members", HOLDERS);
|
||||
d.executes(m, "team.join");
|
||||
let leave = d.literal(team, "leave");
|
||||
let m = d.argument(leave, "members", HOLDERS);
|
||||
d.executes(m, "team.leave");
|
||||
|
||||
let modify = d.literal(team, "modify");
|
||||
let t = d.argument(modify, "team", ArgType::Team);
|
||||
let dn = d.literal(t, "displayName");
|
||||
let v = d.argument(dn, "displayName", ArgType::Component);
|
||||
d.executes(v, "team.modify.displayname");
|
||||
let color = d.literal(t, "color");
|
||||
let reset = d.literal(color, "reset");
|
||||
d.executes(reset, "team.modify.color.reset");
|
||||
let v = d.argument(color, "value", ArgType::TeamColor);
|
||||
d.executes(v, "team.modify.color");
|
||||
for (word, id) in [
|
||||
("friendlyFire", "team.modify.friendlyfire"),
|
||||
("seeFriendlyInvisibles", "team.modify.seefriendlyinvisibles"),
|
||||
] {
|
||||
let w = d.literal(t, word);
|
||||
let v = d.argument(w, "allowed", ArgType::Bool);
|
||||
d.executes(v, id);
|
||||
}
|
||||
for (word, id, values) in [
|
||||
(
|
||||
"nametagVisibility",
|
||||
"team.modify.nametagvisibility",
|
||||
["never", "hideForOtherTeams", "hideForOwnTeam", "always"],
|
||||
),
|
||||
(
|
||||
"deathMessageVisibility",
|
||||
"team.modify.deathmessagevisibility",
|
||||
["never", "hideForOtherTeams", "hideForOwnTeam", "always"],
|
||||
),
|
||||
(
|
||||
"collisionRule",
|
||||
"team.modify.collisionrule",
|
||||
["never", "pushOwnTeam", "pushOtherTeams", "always"],
|
||||
),
|
||||
] {
|
||||
let w = d.literal(t, word);
|
||||
for value in values {
|
||||
let v = d.literal(w, value);
|
||||
d.executes(v, id);
|
||||
}
|
||||
}
|
||||
for (word, id) in [
|
||||
("prefix", "team.modify.prefix"),
|
||||
("suffix", "team.modify.suffix"),
|
||||
] {
|
||||
let w = d.literal(t, word);
|
||||
let v = d.argument(w, word, ArgType::Component);
|
||||
d.executes(v, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Command trees that act on entities and the world: `/recipe`, `/damage`,
|
||||
//! `/rotate`, `/swing`, `/playsound`, `/stopsound`, `/particle`,
|
||||
//! `/attribute`, `/ride`, `/spreadplayers`, `/loot`, `/forceload`,
|
||||
//! `/fillbiome`, `/worldborder`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, Resource, integer},
|
||||
vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS},
|
||||
};
|
||||
use crate::settings::SOUND_SOURCES;
|
||||
|
||||
fn float(min: f32) -> ArgType {
|
||||
ArgType::Float { min, max: f32::MAX }
|
||||
}
|
||||
fn double() -> ArgType {
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
recipe(d, root);
|
||||
damage(d, root);
|
||||
rotate_swing(d, root);
|
||||
sounds(d, root);
|
||||
particle(d, root);
|
||||
attribute(d, root);
|
||||
|
||||
// ride <target> (mount <vehicle> | dismount)
|
||||
let ride = d.literal(root, "ride");
|
||||
d.requires(ride, GAMEMASTERS);
|
||||
let target = d.argument(ride, "target", ENTITY);
|
||||
let mount = d.literal(target, "mount");
|
||||
let vehicle = d.argument(mount, "vehicle", ENTITY);
|
||||
d.executes(vehicle, "ride.mount");
|
||||
let dismount = d.literal(target, "dismount");
|
||||
d.executes(dismount, "ride.dismount");
|
||||
|
||||
// spreadplayers <center> <spreadDistance> <maxRange> [under <maxHeight>] <respectTeams> <targets>
|
||||
let spread = d.literal(root, "spreadplayers");
|
||||
d.requires(spread, GAMEMASTERS);
|
||||
let center = d.argument(spread, "center", ArgType::Vec2);
|
||||
let dist = d.argument(center, "spreadDistance", float(0.0));
|
||||
let range = d.argument(dist, "maxRange", float(1.0));
|
||||
let respect = d.argument(range, "respectTeams", ArgType::Bool);
|
||||
let targets = d.argument(respect, "targets", ENTITIES);
|
||||
d.executes(targets, "spreadplayers");
|
||||
let under = d.literal(range, "under");
|
||||
let height = d.argument(under, "maxHeight", integer(i32::MIN));
|
||||
let respect = d.argument(height, "respectTeams", ArgType::Bool);
|
||||
let targets = d.argument(respect, "targets", ENTITIES);
|
||||
d.executes(targets, "spreadplayers");
|
||||
|
||||
// place template <template> [<pos> [<rotation> [<mirror> [<integrity> [<seed> [strict]]]]]]
|
||||
let place = d.literal(root, "place");
|
||||
d.requires(place, GAMEMASTERS);
|
||||
let template = d.literal(place, "template");
|
||||
let id = d.argument(template, "template", ArgType::Id("templates"));
|
||||
d.executes(id, "place");
|
||||
let pos = d.argument(id, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "place");
|
||||
let rotation = d.argument(
|
||||
pos,
|
||||
"rotation",
|
||||
ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"]),
|
||||
);
|
||||
d.executes(rotation, "place");
|
||||
let mirror = d.argument(
|
||||
rotation,
|
||||
"mirror",
|
||||
ArgType::Enum(&["none", "left_right", "front_back"]),
|
||||
);
|
||||
d.executes(mirror, "place");
|
||||
let integrity = d.argument(mirror, "integrity", ArgType::Float { min: 0.0, max: 1.0 });
|
||||
d.executes(integrity, "place");
|
||||
let seed = d.argument(integrity, "seed", integer(i32::MIN));
|
||||
d.executes(seed, "place");
|
||||
let strict = d.literal(seed, "strict");
|
||||
d.executes(strict, "place");
|
||||
|
||||
forceload(d, root);
|
||||
fillbiome(d, root);
|
||||
worldborder(d, root);
|
||||
loot(d, root);
|
||||
}
|
||||
|
||||
fn recipe(d: &mut Dispatcher, root: usize) {
|
||||
let recipe = d.literal(root, "recipe");
|
||||
d.requires(recipe, GAMEMASTERS);
|
||||
for (word, id) in [("give", "recipe.give"), ("take", "recipe.take")] {
|
||||
let w = d.literal(recipe, word);
|
||||
let t = d.argument(w, "targets", PLAYERS);
|
||||
let r = d.argument(t, "recipe", ArgType::Id("recipes"));
|
||||
d.executes(r, id);
|
||||
let all = d.literal(t, "*");
|
||||
d.executes(all, id);
|
||||
}
|
||||
}
|
||||
|
||||
fn damage(d: &mut Dispatcher, root: usize) {
|
||||
let damage = d.literal(root, "damage");
|
||||
d.requires(damage, GAMEMASTERS);
|
||||
let target = d.argument(damage, "target", ENTITY);
|
||||
let amount = d.argument(target, "amount", float(0.0));
|
||||
d.executes(amount, "damage");
|
||||
let ty = d.argument(amount, "damageType", ArgType::Id("damage_types"));
|
||||
d.executes(ty, "damage");
|
||||
let at = d.literal(ty, "at");
|
||||
let loc = d.argument(at, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "damage");
|
||||
let by = d.literal(ty, "by");
|
||||
let entity = d.argument(by, "entity", ENTITY);
|
||||
d.executes(entity, "damage");
|
||||
let from = d.literal(entity, "from");
|
||||
let cause = d.argument(from, "cause", ENTITY);
|
||||
d.executes(cause, "damage");
|
||||
}
|
||||
|
||||
fn rotate_swing(d: &mut Dispatcher, root: usize) {
|
||||
let rotate = d.literal(root, "rotate");
|
||||
d.requires(rotate, GAMEMASTERS);
|
||||
let target = d.argument(rotate, "target", ENTITY);
|
||||
let rot = d.argument(target, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "rotate");
|
||||
let facing = d.literal(target, "facing");
|
||||
let entity = d.literal(facing, "entity");
|
||||
let fe = d.argument(entity, "facingEntity", ENTITY);
|
||||
d.executes(fe, "rotate");
|
||||
let anchor = d.argument(fe, "facingAnchor", ArgType::Anchor);
|
||||
d.executes(anchor, "rotate");
|
||||
let loc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "rotate");
|
||||
|
||||
let swing = d.literal(root, "swing");
|
||||
d.requires(swing, GAMEMASTERS);
|
||||
d.executes(swing, "swing");
|
||||
let targets = d.argument(swing, "targets", ENTITIES);
|
||||
d.executes(targets, "swing");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(targets, hand);
|
||||
d.executes(h, "swing");
|
||||
let animation = d.argument(h, "animation", ArgType::Enum(&["none", "whack", "stab"]));
|
||||
d.executes(animation, "swing");
|
||||
let duration = d.argument(animation, "duration", ArgType::Time { min: 1 });
|
||||
d.executes(duration, "swing");
|
||||
}
|
||||
}
|
||||
|
||||
fn sounds(d: &mut Dispatcher, root: usize) {
|
||||
let play = d.literal(root, "playsound");
|
||||
d.requires(play, GAMEMASTERS);
|
||||
let sound = d.argument(play, "sound", ArgType::Id("sounds"));
|
||||
d.executes(sound, "playsound");
|
||||
let stop = d.literal(root, "stopsound");
|
||||
d.requires(stop, GAMEMASTERS);
|
||||
let stop_targets = d.argument(stop, "targets", PLAYERS);
|
||||
d.executes(stop_targets, "stopsound");
|
||||
let any = d.literal(stop_targets, "*");
|
||||
let any_sound = d.argument(any, "sound", ArgType::Id("sounds"));
|
||||
d.executes(any_sound, "stopsound");
|
||||
for source in SOUND_SOURCES {
|
||||
let s = d.literal(sound, source);
|
||||
d.executes(s, "playsound");
|
||||
let targets = d.argument(s, "targets", PLAYERS);
|
||||
d.executes(targets, "playsound");
|
||||
let pos = d.argument(targets, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "playsound");
|
||||
let volume = d.argument(pos, "volume", float(0.0));
|
||||
d.executes(volume, "playsound");
|
||||
let pitch = d.argument(volume, "pitch", ArgType::Float { min: 0.0, max: 2.0 });
|
||||
d.executes(pitch, "playsound");
|
||||
let min = d.argument(pitch, "minVolume", ArgType::Float { min: 0.0, max: 1.0 });
|
||||
d.executes(min, "playsound");
|
||||
|
||||
let ls = d.literal(stop_targets, source);
|
||||
d.executes(ls, "stopsound");
|
||||
let lsound = d.argument(ls, "sound", ArgType::Id("sounds"));
|
||||
d.executes(lsound, "stopsound");
|
||||
}
|
||||
}
|
||||
|
||||
fn particle(d: &mut Dispatcher, root: usize) {
|
||||
let particle = d.literal(root, "particle");
|
||||
d.requires(particle, GAMEMASTERS);
|
||||
let name = d.argument(particle, "name", ArgType::Particle);
|
||||
d.executes(name, "particle");
|
||||
let pos = d.argument(name, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "particle");
|
||||
let delta = d.argument(pos, "delta", ArgType::Vec3 { center: false });
|
||||
let speed = d.argument(delta, "speed", float(0.0));
|
||||
let count = d.argument(speed, "count", integer(0));
|
||||
d.executes(count, "particle");
|
||||
for mode in ["force", "normal"] {
|
||||
let m = d.literal(count, mode);
|
||||
d.executes(m, "particle");
|
||||
let viewers = d.argument(m, "viewers", PLAYERS);
|
||||
d.executes(viewers, "particle");
|
||||
}
|
||||
}
|
||||
|
||||
fn attribute(d: &mut Dispatcher, root: usize) {
|
||||
let attribute = d.literal(root, "attribute");
|
||||
d.requires(attribute, GAMEMASTERS);
|
||||
let target = d.argument(attribute, "target", ENTITY);
|
||||
let attr = d.argument(target, "attribute", ArgType::Id("attributes"));
|
||||
let get = d.literal(attr, "get");
|
||||
d.executes(get, "attribute.get");
|
||||
let scale = d.argument(get, "scale", double());
|
||||
d.executes(scale, "attribute.get");
|
||||
let base = d.literal(attr, "base");
|
||||
let set = d.literal(base, "set");
|
||||
let value = d.argument(set, "value", double());
|
||||
d.executes(value, "attribute.base.set");
|
||||
let bget = d.literal(base, "get");
|
||||
d.executes(bget, "attribute.base.get");
|
||||
let bscale = d.argument(bget, "scale", double());
|
||||
d.executes(bscale, "attribute.base.get");
|
||||
let reset = d.literal(base, "reset");
|
||||
d.executes(reset, "attribute.base.reset");
|
||||
let modifier = d.literal(attr, "modifier");
|
||||
let add = d.literal(modifier, "add");
|
||||
let id = d.argument(add, "id", ArgType::Id("attribute_modifiers"));
|
||||
let value = d.argument(id, "value", double());
|
||||
for op in ["add_value", "add_multiplied_base", "add_multiplied_total"] {
|
||||
let o = d.literal(value, op);
|
||||
d.executes(o, "attribute.modifier.add");
|
||||
}
|
||||
let remove = d.literal(modifier, "remove");
|
||||
let rid = d.argument(remove, "id", ArgType::Id("attribute_modifiers"));
|
||||
d.executes(rid, "attribute.modifier.remove");
|
||||
let value_l = d.literal(modifier, "value");
|
||||
let vget = d.literal(value_l, "get");
|
||||
let vid = d.argument(vget, "id", ArgType::Id("attribute_modifiers"));
|
||||
d.executes(vid, "attribute.modifier.get");
|
||||
let vscale = d.argument(vid, "scale", double());
|
||||
d.executes(vscale, "attribute.modifier.get");
|
||||
}
|
||||
|
||||
fn forceload(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "forceload");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
for (word, id) in [("add", "forceload.add"), ("remove", "forceload.remove")] {
|
||||
let w = d.literal(f, word);
|
||||
let from = d.argument(w, "from", ArgType::ColumnPos);
|
||||
d.executes(from, id);
|
||||
let to = d.argument(from, "to", ArgType::ColumnPos);
|
||||
d.executes(to, id);
|
||||
if word == "remove" {
|
||||
let all = d.literal(w, "all");
|
||||
d.executes(all, "forceload.remove.all");
|
||||
}
|
||||
}
|
||||
let query = d.literal(f, "query");
|
||||
d.executes(query, "forceload.query");
|
||||
let pos = d.argument(query, "pos", ArgType::ColumnPos);
|
||||
d.executes(pos, "forceload.query");
|
||||
}
|
||||
|
||||
fn fillbiome(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "fillbiome");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
let from = d.argument(f, "from", ArgType::BlockPos);
|
||||
let to = d.argument(from, "to", ArgType::BlockPos);
|
||||
let biome = d.argument(to, "biome", ArgType::Resource(Resource::Biome));
|
||||
d.executes(biome, "fillbiome");
|
||||
let replace = d.literal(biome, "replace");
|
||||
let filter = d.argument(replace, "filter", ArgType::Resource(Resource::Biome));
|
||||
d.executes(filter, "fillbiome");
|
||||
}
|
||||
|
||||
fn worldborder(d: &mut Dispatcher, root: usize) {
|
||||
let w = d.literal(root, "worldborder");
|
||||
d.requires(w, GAMEMASTERS);
|
||||
let dist = || ArgType::Double {
|
||||
min: -5.999_997e7,
|
||||
max: 5.999_997e7,
|
||||
};
|
||||
for word in ["add", "set"] {
|
||||
let l = d.literal(w, word);
|
||||
let distance = d.argument(l, "distance", dist());
|
||||
let id = if word == "add" {
|
||||
"worldborder.add"
|
||||
} else {
|
||||
"worldborder.set"
|
||||
};
|
||||
d.executes(distance, id);
|
||||
let time = d.argument(distance, "time", ArgType::Time { min: 0 });
|
||||
d.executes(time, id);
|
||||
}
|
||||
let center = d.literal(w, "center");
|
||||
let pos = d.argument(center, "pos", ArgType::Vec2);
|
||||
d.executes(pos, "worldborder.center");
|
||||
let damage = d.literal(w, "damage");
|
||||
let amount = d.literal(damage, "amount");
|
||||
let per = d.argument(amount, "damagePerBlock", float(0.0));
|
||||
d.executes(per, "worldborder.damage.amount");
|
||||
let buffer = d.literal(damage, "buffer");
|
||||
let b = d.argument(buffer, "distance", float(0.0));
|
||||
d.executes(b, "worldborder.damage.buffer");
|
||||
let get = d.literal(w, "get");
|
||||
d.executes(get, "worldborder.get");
|
||||
let warning = d.literal(w, "warning");
|
||||
let wd = d.literal(warning, "distance");
|
||||
let v = d.argument(wd, "distance", integer(0));
|
||||
d.executes(v, "worldborder.warning.distance");
|
||||
let wt = d.literal(warning, "time");
|
||||
let v = d.argument(wt, "time", ArgType::Time { min: 0 });
|
||||
d.executes(v, "worldborder.warning.time");
|
||||
}
|
||||
|
||||
/// `loot (replace|insert|give|spawn) ... (fish|loot|kill|mine)`.
|
||||
fn loot(d: &mut Dispatcher, root: usize) {
|
||||
let loot = d.literal(root, "loot");
|
||||
d.requires(loot, GAMEMASTERS);
|
||||
// Targets.
|
||||
let mut targets = Vec::new();
|
||||
let replace = d.literal(loot, "replace");
|
||||
for provider in ["entity", "block"] {
|
||||
let p = d.literal(replace, provider);
|
||||
let a = if provider == "entity" {
|
||||
d.argument(p, "entities", ENTITIES)
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slot = d.argument(a, "slot", ArgType::Slot);
|
||||
targets.push(slot);
|
||||
let count = d.argument(slot, "count", integer(0));
|
||||
targets.push(count);
|
||||
}
|
||||
let insert = d.literal(loot, "insert");
|
||||
targets.push(d.argument(insert, "targetPos", ArgType::BlockPos));
|
||||
let give = d.literal(loot, "give");
|
||||
targets.push(d.argument(give, "players", PLAYERS));
|
||||
let spawn = d.literal(loot, "spawn");
|
||||
targets.push(d.argument(spawn, "targetPos", ArgType::Vec3 { center: true }));
|
||||
// Sources.
|
||||
for t in targets {
|
||||
let fish = d.literal(t, "fish");
|
||||
let table = d.argument(fish, "loot_table", ArgType::Id("loot_tables"));
|
||||
let pos = d.argument(table, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "loot.fish");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(pos, hand);
|
||||
d.executes(h, "loot.fish");
|
||||
}
|
||||
let tool = d.argument(pos, "tool", ArgType::ItemPredicate);
|
||||
d.executes(tool, "loot.fish");
|
||||
let l = d.literal(t, "loot");
|
||||
let lt = d.argument(l, "loot_table", ArgType::Id("loot_tables"));
|
||||
d.executes(lt, "loot.loot");
|
||||
let kill = d.literal(t, "kill");
|
||||
let target = d.argument(kill, "target", ENTITY);
|
||||
d.executes(target, "loot.kill");
|
||||
let mine = d.literal(t, "mine");
|
||||
let pos = d.argument(mine, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "loot.mine");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(pos, hand);
|
||||
d.executes(h, "loot.mine");
|
||||
}
|
||||
let tool = d.argument(pos, "tool", ArgType::ItemPredicate);
|
||||
d.executes(tool, "loot.mine");
|
||||
}
|
||||
}
|
||||
@@ -11,19 +11,19 @@ use crate::gamerules::{RULES, Value};
|
||||
pub const ALL: u8 = 0;
|
||||
pub const GAMEMASTERS: u8 = 2;
|
||||
|
||||
const PLAYERS: ArgType = ArgType::Entity {
|
||||
pub const PLAYERS: ArgType = ArgType::Entity {
|
||||
single: false,
|
||||
players: true,
|
||||
};
|
||||
const PLAYER: ArgType = ArgType::Entity {
|
||||
pub const PLAYER: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: true,
|
||||
};
|
||||
const ENTITIES: ArgType = ArgType::Entity {
|
||||
pub const ENTITIES: ArgType = ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
const ENTITY: ArgType = ArgType::Entity {
|
||||
pub const ENTITY: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
};
|
||||
@@ -111,6 +111,28 @@ pub fn build() -> Dispatcher {
|
||||
d.executes(dur, "weather");
|
||||
}
|
||||
|
||||
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
|
||||
let raid = d.literal(root, "raid");
|
||||
d.requires(raid, 3);
|
||||
let start = d.literal(raid, "start");
|
||||
let level = d.argument(start, "omenlvl", integer(0));
|
||||
d.executes(level, "raid.start");
|
||||
for (name, id) in [
|
||||
("stop", "raid.stop"),
|
||||
("check", "raid.check"),
|
||||
("spawnleader", "raid.spawnleader"),
|
||||
("glow", "raid.glow"),
|
||||
] {
|
||||
let n = d.literal(raid, name);
|
||||
d.executes(n, id);
|
||||
}
|
||||
let sound = d.literal(raid, "sound");
|
||||
let kind = d.argument(sound, "type", ArgType::Greedy);
|
||||
d.executes(kind, "raid.sound");
|
||||
let setomen = d.literal(raid, "setomen");
|
||||
let level = d.argument(setomen, "level", integer(0));
|
||||
d.executes(level, "raid.setomen");
|
||||
|
||||
// kill [<targets>]
|
||||
let kill = d.literal(root, "kill");
|
||||
d.requires(kill, GAMEMASTERS);
|
||||
@@ -295,6 +317,15 @@ pub fn build() -> Dispatcher {
|
||||
let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome));
|
||||
d.executes(a, "locate.biome");
|
||||
|
||||
// warden_spawn_tracker (clear | set <warning_level>)
|
||||
let tracker = d.literal(root, "warden_spawn_tracker");
|
||||
d.requires(tracker, GAMEMASTERS);
|
||||
let clear = d.literal(tracker, "clear");
|
||||
d.executes(clear, "warden_spawn_tracker.clear");
|
||||
let set = d.literal(tracker, "set");
|
||||
let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 });
|
||||
d.executes(level, "warden_spawn_tracker.set");
|
||||
|
||||
// say / me / msg / list
|
||||
let say = d.literal(root, "say");
|
||||
d.requires(say, GAMEMASTERS);
|
||||
@@ -342,69 +373,14 @@ pub fn build() -> Dispatcher {
|
||||
let fade_out = d.argument(stay, "fadeOut", ArgType::Time { min: 0 });
|
||||
d.executes(fade_out, "title");
|
||||
|
||||
execute(&mut d, root);
|
||||
super::tree_scoreboard::register(&mut d, root);
|
||||
super::tree_data::register(&mut d, root);
|
||||
super::tree_execute::register(&mut d, root);
|
||||
super::tree_misc::register(&mut d, root);
|
||||
super::tree_world::register(&mut d, root);
|
||||
d
|
||||
}
|
||||
|
||||
/// ExecuteCommand: modifiers redirect back to `execute`, `run` to the root;
|
||||
/// conditions both execute (as a test) and continue the chain. `store`,
|
||||
/// `summon`, `on` and score/data conditions are not implemented.
|
||||
fn execute(d: &mut Dispatcher, root: usize) {
|
||||
let ex = d.literal(root, "execute");
|
||||
d.requires(ex, GAMEMASTERS);
|
||||
let run = d.literal(ex, "run");
|
||||
d.redirect(run, root);
|
||||
for name in ["as", "at"] {
|
||||
let l = d.literal(ex, name);
|
||||
let t = d.argument(l, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
}
|
||||
let positioned = d.literal(ex, "positioned");
|
||||
let pos = d.argument(positioned, "pos", ArgType::Vec3 { center: true });
|
||||
d.redirect(pos, ex);
|
||||
let as_ = d.literal(positioned, "as");
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let rotated = d.literal(ex, "rotated");
|
||||
let rot = d.argument(rotated, "rot", ArgType::Rotation);
|
||||
d.redirect(rot, ex);
|
||||
let as_ = d.literal(rotated, "as");
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let facing = d.literal(ex, "facing");
|
||||
let pos = d.argument(facing, "pos", ArgType::Vec3 { center: true });
|
||||
d.redirect(pos, ex);
|
||||
let entity = d.literal(facing, "entity");
|
||||
let t = d.argument(entity, "targets", ENTITIES);
|
||||
let anchor = d.argument(t, "anchor", ArgType::Anchor);
|
||||
d.redirect(anchor, ex);
|
||||
let align = d.literal(ex, "align");
|
||||
let axes = d.argument(align, "axes", ArgType::Swizzle);
|
||||
d.redirect(axes, ex);
|
||||
let anchored = d.literal(ex, "anchored");
|
||||
let anchor = d.argument(anchored, "anchor", ArgType::Anchor);
|
||||
d.redirect(anchor, ex);
|
||||
let in_ = d.literal(ex, "in");
|
||||
let dim = d.argument(in_, "dimension", ArgType::Dimension);
|
||||
d.redirect(dim, ex);
|
||||
for mode in ["if", "unless"] {
|
||||
let m = d.literal(ex, mode);
|
||||
let block = d.literal(m, "block");
|
||||
let pos = d.argument(block, "pos", ArgType::BlockPos);
|
||||
let predicate = d.argument(pos, "block", ArgType::BlockPredicate);
|
||||
let entity = d.literal(m, "entity");
|
||||
let targets = d.argument(entity, "entities", ENTITIES);
|
||||
let loaded = d.literal(m, "loaded");
|
||||
let lpos = d.argument(loaded, "pos", ArgType::BlockPos);
|
||||
let dimension = d.literal(m, "dimension");
|
||||
let dim = d.argument(dimension, "dimension", ArgType::Dimension);
|
||||
for node in [predicate, targets, lpos, dim] {
|
||||
d.executes(node, "execute");
|
||||
d.redirect(node, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// AdvancementCommands: grant|revoke <targets> only|from|until|through
|
||||
/// <advancement> | everything; `only` takes an optional criterion.
|
||||
fn advancement(d: &mut Dispatcher, root: usize) {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! `CommandStorage`: named compounds for `/data ... storage <id>`, kept per
|
||||
//! namespace in `data/<namespace>/command_storage.dat`.
|
||||
use crate::save;
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CommandStorage {
|
||||
/// namespace -> path -> contents.
|
||||
namespaces: BTreeMap<String, BTreeMap<String, Tag>>,
|
||||
dirty: bool,
|
||||
}
|
||||
fn split_id(id: &str) -> (&str, &str) {
|
||||
id.split_once(':').unwrap_or(("minecraft", id))
|
||||
}
|
||||
fn file(root: &Path, namespace: &str) -> PathBuf {
|
||||
root.join("data")
|
||||
.join(namespace)
|
||||
.join("command_storage.dat")
|
||||
}
|
||||
impl CommandStorage {
|
||||
/// Read every `data/<namespace>/command_storage.dat` under a world.
|
||||
pub fn load(root: &Path) -> Self {
|
||||
let mut s = Self::default();
|
||||
let Ok(dirs) = std::fs::read_dir(root.join("data")) else {
|
||||
return s;
|
||||
};
|
||||
for dir in dirs.flatten() {
|
||||
let namespace = dir.file_name().to_string_lossy().into_owned();
|
||||
let Some(data) =
|
||||
save::read_dat(&file(root, &namespace)).and_then(|t| t.get("data").cloned())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Tag::Compound(contents)) = data.get("contents") {
|
||||
let map = contents
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string_lossy(), v.clone()))
|
||||
.collect();
|
||||
s.namespaces.insert(namespace, map);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
pub fn save(&mut self, root: &Path) {
|
||||
if !self.dirty {
|
||||
return;
|
||||
}
|
||||
self.dirty = false;
|
||||
for (namespace, map) in &self.namespaces {
|
||||
let contents: Compound = map
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str().into(), v.clone()))
|
||||
.collect();
|
||||
let _ = save::write_dat(
|
||||
&file(root, namespace),
|
||||
Tag::compound([
|
||||
(
|
||||
"data",
|
||||
Tag::compound([("contents", Tag::Compound(contents))]),
|
||||
),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `get`: an empty compound when unset.
|
||||
pub fn get(&self, id: &str) -> Tag {
|
||||
let (ns, path) = split_id(id);
|
||||
self.namespaces
|
||||
.get(ns)
|
||||
.and_then(|m| m.get(path))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Tag::Compound(Compound::new()))
|
||||
}
|
||||
/// `set`: empty contents remove the entry.
|
||||
pub fn set(&mut self, id: &str, contents: Tag) {
|
||||
let (ns, path) = split_id(id);
|
||||
let empty = matches!(&contents, Tag::Compound(c) if c.is_empty());
|
||||
let map = self.namespaces.entry(ns.to_owned()).or_default();
|
||||
if empty {
|
||||
map.remove(path);
|
||||
} else {
|
||||
map.insert(path.to_owned(), contents);
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
/// Every stored id (`keys`).
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
self.namespaces
|
||||
.iter()
|
||||
.flat_map(|(ns, m)| m.keys().map(move |k| format!("{ns}:{k}")))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
#[test]
|
||||
fn stores_per_namespace_and_persists() {
|
||||
let dir = std::env::temp_dir().join(format!("hz-storage-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut s = CommandStorage::default();
|
||||
assert_eq!(s.get("minecraft:x"), Tag::Compound(Compound::new()));
|
||||
s.set("minecraft:x", parse_snbt("{a:1}").unwrap().0);
|
||||
s.set("my:pack/y", parse_snbt("{b:[1,2]}").unwrap().0);
|
||||
s.save(&dir);
|
||||
let back = CommandStorage::load(&dir);
|
||||
assert_eq!(back.get("x"), parse_snbt("{a:1}").unwrap().0);
|
||||
assert_eq!(back.get("my:pack/y"), parse_snbt("{b:[1,2]}").unwrap().0);
|
||||
assert_eq!(back.keys(), vec!["minecraft:x", "my:pack/y"]);
|
||||
// Empty contents delete.
|
||||
let mut s = back;
|
||||
s.set("x", Tag::Compound(Compound::new()));
|
||||
assert_eq!(s.keys(), vec!["my:pack/y"]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,79 @@ pub enum BlockEntity {
|
||||
Beacon(Box<Beacon>),
|
||||
/// `LecternBlockEntity`: the book and the open page.
|
||||
Lectern(Lectern),
|
||||
/// Sculk sensors, shriekers and catalysts (`crate::sculk`).
|
||||
Sculk(Box<crate::sculk::SculkEntity>),
|
||||
/// `CreakingHeartBlockEntity`: its protector and the hurt emitter.
|
||||
CreakingHeart(Box<CreakingHeart>),
|
||||
/// `BannerBlockEntity`: the pattern layers.
|
||||
Banner(Banner),
|
||||
/// `CrafterBlockEntity`.
|
||||
Crafter(Crafter),
|
||||
}
|
||||
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
|
||||
/// and the ticks left in the crafting animation.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Crafter {
|
||||
pub items: [Option<ItemStack>; 9],
|
||||
pub disabled: [bool; 9],
|
||||
pub triggered: bool,
|
||||
pub crafting_ticks: i32,
|
||||
}
|
||||
impl Crafter {
|
||||
/// `slotCanBeDisabled`: only empty slots.
|
||||
pub fn slot_can_be_disabled(&self, slot: usize) -> bool {
|
||||
slot < 9 && self.items[slot].is_none()
|
||||
}
|
||||
/// `setSlotState`.
|
||||
pub fn set_slot_state(&mut self, slot: usize, enabled: bool) {
|
||||
if self.slot_can_be_disabled(slot) {
|
||||
self.disabled[slot] = !enabled;
|
||||
}
|
||||
}
|
||||
/// `getRedstoneSignal`: filled or disabled slots.
|
||||
pub fn redstone_signal(&self) -> i32 {
|
||||
(0..9)
|
||||
.filter(|&i| self.items[i].is_some() || self.disabled[i])
|
||||
.count() as i32
|
||||
}
|
||||
/// `canPlaceItem`: a hopper fills the smallest stacks first.
|
||||
pub fn can_place(&self, slot: usize, stack: &ItemStack, max_stack: u32) -> bool {
|
||||
if slot >= 9 || self.disabled[slot] {
|
||||
return false;
|
||||
}
|
||||
let Some(current) = &self.items[slot] else {
|
||||
return true;
|
||||
};
|
||||
if current.count >= max_stack {
|
||||
return false;
|
||||
}
|
||||
!(slot + 1..9).any(|i| {
|
||||
!self.disabled[i]
|
||||
&& match &self.items[i] {
|
||||
None => true,
|
||||
Some(other) => {
|
||||
other.count < current.count && other.same_item_same_components(stack)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Banner {
|
||||
pub layers: Vec<crate::banner::BannerLayer>,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CreakingHeart {
|
||||
/// The protector: its entity id once resolved, and its UUID (the saved form).
|
||||
pub creaking: Option<(Option<u32>, [i32; 4])>,
|
||||
pub ticks_existed: i64,
|
||||
pub ticker: i32,
|
||||
/// Ticks left of the hurt effect (`emitter`) and where it heads.
|
||||
pub emitter: i32,
|
||||
pub emitter_target: Option<[f64; 3]>,
|
||||
pub output_signal: i32,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Lectern {
|
||||
@@ -101,9 +174,21 @@ impl BlockEntity {
|
||||
speed: 1.0,
|
||||
}));
|
||||
}
|
||||
if name == "minecraft:creaking_heart" {
|
||||
return Some(Self::CreakingHeart(Box::default()));
|
||||
}
|
||||
if name == "minecraft:lectern" {
|
||||
return Some(Self::Lectern(Lectern::default()));
|
||||
}
|
||||
if let Some(sculk) = crate::sculk::SculkEntity::for_block(name) {
|
||||
return Some(Self::Sculk(Box::new(sculk)));
|
||||
}
|
||||
if name == "minecraft:crafter" {
|
||||
return Some(Self::Crafter(Crafter::default()));
|
||||
}
|
||||
if name.ends_with("_banner") {
|
||||
return Some(Self::Banner(Banner::default()));
|
||||
}
|
||||
if name == "minecraft:beacon" {
|
||||
return Some(Self::Beacon(Box::new(Beacon {
|
||||
last_check_y: i32::MIN / 2,
|
||||
@@ -135,6 +220,7 @@ impl BlockEntity {
|
||||
"minecraft:blast_furnace" => "minecraft:blast_furnace",
|
||||
"minecraft:smoker" => "minecraft:smoker",
|
||||
n if n.ends_with("shulker_box") => "minecraft:shulker_box",
|
||||
"minecraft:crafter" => "minecraft:crafter",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -155,6 +241,10 @@ impl BlockEntity {
|
||||
Self::Jukebox(_) => "minecraft:jukebox",
|
||||
Self::Beacon(_) => "minecraft:beacon",
|
||||
Self::Lectern(_) => "minecraft:lectern",
|
||||
Self::Sculk(s) => s.id(),
|
||||
Self::Banner(_) => "minecraft:banner",
|
||||
Self::Crafter(_) => "minecraft:crafter",
|
||||
Self::CreakingHeart(_) => "minecraft:creaking_heart",
|
||||
}
|
||||
}
|
||||
pub fn contents(&self) -> Vec<ItemStack> {
|
||||
@@ -164,8 +254,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(_) => Vec::new(),
|
||||
Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(),
|
||||
Self::Lectern(l) => l.book.iter().cloned().collect(),
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
|
||||
}
|
||||
}
|
||||
pub fn slots(&self) -> &[Option<ItemStack>] {
|
||||
@@ -173,7 +266,14 @@ impl BlockEntity {
|
||||
Self::Chest(items) => items,
|
||||
Self::Furnace(f) => &f.items,
|
||||
Self::Brewing(b) => &b.items,
|
||||
Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[],
|
||||
Self::Sign(_)
|
||||
| Self::Jukebox(_)
|
||||
| Self::Beacon(_)
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &[],
|
||||
Self::Crafter(c) => &c.items,
|
||||
Self::CreakingHeart(_) => &[],
|
||||
}
|
||||
}
|
||||
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
|
||||
@@ -181,7 +281,14 @@ impl BlockEntity {
|
||||
Self::Chest(items) => items,
|
||||
Self::Furnace(f) => &mut f.items,
|
||||
Self::Brewing(b) => &mut b.items,
|
||||
Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [],
|
||||
Self::Sign(_)
|
||||
| Self::Jukebox(_)
|
||||
| Self::Beacon(_)
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &mut [],
|
||||
Self::Crafter(c) => &mut c.items,
|
||||
Self::CreakingHeart(_) => &mut [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,9 +53,104 @@ pub enum Recipe {
|
||||
ingredients: Vec<Ingredient>,
|
||||
result: ItemStack,
|
||||
},
|
||||
/// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`.
|
||||
Special(Special),
|
||||
}
|
||||
/// The banner-copying custom recipes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Special {
|
||||
/// A patterned banner and a blank one of the same colour copy the patterns.
|
||||
BannerDuplicate { banner: Ingredient, result: String },
|
||||
/// A banner decorates an undecorated shield.
|
||||
ShieldDecoration {
|
||||
banner: Ingredient,
|
||||
target: Ingredient,
|
||||
result: String,
|
||||
},
|
||||
}
|
||||
impl Special {
|
||||
/// `matches` + `assemble` over the non-empty stacks of the grid.
|
||||
fn assemble(&self, stacks: &[&ItemStack]) -> Option<ItemStack> {
|
||||
use crate::banner;
|
||||
if stacks.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
match self {
|
||||
Self::BannerDuplicate {
|
||||
banner: ing,
|
||||
result,
|
||||
} => {
|
||||
let color = banner::banner_color(&stacks[0].item)?;
|
||||
let mut source = None;
|
||||
let mut target = false;
|
||||
for s in stacks {
|
||||
if !ing.test(s) || banner::banner_color(&s.item)? != color {
|
||||
return None;
|
||||
}
|
||||
let layers = banner::layers(s).len();
|
||||
if layers > banner::MAX_LAYERS {
|
||||
return None;
|
||||
}
|
||||
if layers > 0 {
|
||||
if source.is_some() {
|
||||
return None;
|
||||
}
|
||||
source = Some(*s);
|
||||
} else {
|
||||
if target {
|
||||
return None;
|
||||
}
|
||||
target = true;
|
||||
}
|
||||
}
|
||||
let source = source.filter(|_| target)?;
|
||||
// TransmuteRecipe.createWithOriginalComponents: the source's components.
|
||||
Some(ItemStack {
|
||||
item: Arc::from(result.as_str()),
|
||||
count: 1,
|
||||
..(*source).clone()
|
||||
})
|
||||
}
|
||||
Self::ShieldDecoration {
|
||||
banner: ing,
|
||||
target: tgt,
|
||||
result,
|
||||
} => {
|
||||
let (mut patterned, mut clear) = (None, None);
|
||||
for s in stacks {
|
||||
if ing.test(s) && banner::banner_color(&s.item).is_some() {
|
||||
if patterned.is_some() {
|
||||
return None;
|
||||
}
|
||||
patterned = Some(*s);
|
||||
} else {
|
||||
if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() {
|
||||
return None;
|
||||
}
|
||||
clear = Some(*s);
|
||||
}
|
||||
}
|
||||
let (banner_stack, shield) = (patterned?, clear?);
|
||||
let mut out = ItemStack {
|
||||
item: Arc::from(result.as_str()),
|
||||
count: 1,
|
||||
..shield.clone()
|
||||
};
|
||||
let data = out.data_mut();
|
||||
data.banner_patterns = banner::layers(banner_stack).to_vec();
|
||||
data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Cooking {
|
||||
/// The recipe's file name (its id without namespace).
|
||||
pub id: String,
|
||||
/// `category` (`food`, `blocks`, `misc`) and `group` of the recipe book.
|
||||
pub category: String,
|
||||
pub group: String,
|
||||
pub kind: String,
|
||||
pub ingredient: Ingredient,
|
||||
pub result: ItemStack,
|
||||
@@ -65,6 +160,8 @@ pub struct Cooking {
|
||||
pub struct Recipes {
|
||||
pub crafting: Vec<(String, Recipe)>,
|
||||
pub cooking: Vec<Cooking>,
|
||||
/// `category` and `group` of each crafting recipe, by file name.
|
||||
pub meta: std::collections::HashMap<String, (String, String)>,
|
||||
}
|
||||
fn result(v: &Value) -> Option<ItemStack> {
|
||||
Some(ItemStack {
|
||||
@@ -78,6 +175,7 @@ impl Recipes {
|
||||
pub fn load(root: &Path, items: &Items) -> Result<Self> {
|
||||
let mut crafting = Vec::new();
|
||||
let mut cooking = Vec::new();
|
||||
let mut meta = std::collections::HashMap::new();
|
||||
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
@@ -91,6 +189,8 @@ impl Recipes {
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let v: Value = serde_json::from_slice(&fs::read(&path)?)?;
|
||||
let text = |k: &str| v[k].as_str().unwrap_or("").to_owned();
|
||||
meta.insert(name.clone(), (text("category"), text("group")));
|
||||
match v["type"].as_str().unwrap_or("") {
|
||||
"minecraft:crafting_shaped" => {
|
||||
let pattern: Vec<Vec<char>> = v["pattern"]
|
||||
@@ -145,6 +245,36 @@ impl Recipes {
|
||||
));
|
||||
}
|
||||
}
|
||||
"minecraft:crafting_special_bannerduplicate" => {
|
||||
if let (Some(banner), Some(id)) = (
|
||||
Ingredient::parse(&v["banner"], items),
|
||||
v["result"]["id"].as_str(),
|
||||
) {
|
||||
crafting.push((
|
||||
name,
|
||||
Recipe::Special(Special::BannerDuplicate {
|
||||
banner,
|
||||
result: id.to_owned(),
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
"minecraft:crafting_special_shielddecoration" => {
|
||||
if let (Some(banner), Some(target), Some(id)) = (
|
||||
Ingredient::parse(&v["banner"], items),
|
||||
Ingredient::parse(&v["target"], items),
|
||||
v["result"]["id"].as_str(),
|
||||
) {
|
||||
crafting.push((
|
||||
name,
|
||||
Recipe::Special(Special::ShieldDecoration {
|
||||
banner,
|
||||
target,
|
||||
result: id.to_owned(),
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
kind @ ("minecraft:smelting"
|
||||
| "minecraft:blasting"
|
||||
| "minecraft:smoking"
|
||||
@@ -154,6 +284,9 @@ impl Recipes {
|
||||
result(&v["result"]),
|
||||
) {
|
||||
cooking.push(Cooking {
|
||||
id: name,
|
||||
category: text("category"),
|
||||
group: text("group"),
|
||||
kind: kind.to_owned(),
|
||||
ingredient,
|
||||
result,
|
||||
@@ -165,10 +298,18 @@ impl Recipes {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Self { crafting, cooking })
|
||||
Ok(Self {
|
||||
crafting,
|
||||
cooking,
|
||||
meta,
|
||||
})
|
||||
}
|
||||
/// Match a `size`x`size` grid (row-major) against the crafting recipes.
|
||||
pub fn craft(&self, grid: &[Option<ItemStack>], size: usize) -> Option<ItemStack> {
|
||||
self.find(grid, size).map(|(_, result)| result)
|
||||
}
|
||||
/// `craft` with the matched recipe's id (the file name without namespace).
|
||||
pub fn find(&self, grid: &[Option<ItemStack>], size: usize) -> Option<(&str, ItemStack)> {
|
||||
// Trim to the occupied bounding box.
|
||||
let occupied: Vec<(usize, usize)> = (0..size * size)
|
||||
.filter(|&i| grid[i].is_some())
|
||||
@@ -187,8 +328,14 @@ impl Recipes {
|
||||
);
|
||||
let (w, h) = (x1 - x0 + 1, y1 - y0 + 1);
|
||||
let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref();
|
||||
for (_, recipe) in &self.crafting {
|
||||
for (name, recipe) in &self.crafting {
|
||||
match recipe {
|
||||
Recipe::Special(special) => {
|
||||
let stacks: Vec<&ItemStack> = grid.iter().flatten().collect();
|
||||
if let Some(result) = special.assemble(&stacks) {
|
||||
return Some((name, result));
|
||||
}
|
||||
}
|
||||
Recipe::Shaped {
|
||||
width,
|
||||
height,
|
||||
@@ -211,7 +358,7 @@ impl Recipes {
|
||||
})
|
||||
};
|
||||
if matches(false) || matches(true) {
|
||||
return Some(result.clone());
|
||||
return Some((name, result.clone()));
|
||||
}
|
||||
}
|
||||
Recipe::Shapeless {
|
||||
@@ -235,16 +382,87 @@ impl Recipes {
|
||||
}
|
||||
});
|
||||
if ok {
|
||||
return Some(result.clone());
|
||||
return Some((name, result.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder
|
||||
/// (buckets, bottles), and the patterned banner a duplicate keeps.
|
||||
pub fn remainders(
|
||||
&self,
|
||||
items: &Items,
|
||||
grid: &[Option<ItemStack>],
|
||||
result: &ItemStack,
|
||||
) -> Vec<Option<ItemStack>> {
|
||||
grid.iter()
|
||||
.map(|cell| {
|
||||
let s = cell.as_ref()?;
|
||||
if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) {
|
||||
return Some(ItemStack::new(rem, 1));
|
||||
}
|
||||
(result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then(
|
||||
|| ItemStack {
|
||||
count: 1,
|
||||
..s.clone()
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
|
||||
self.cooking
|
||||
.iter()
|
||||
.find(|c| c.kind == kind && c.ingredient.test(input))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::banner::BannerLayer;
|
||||
|
||||
fn ingredient(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn patterned(item: &str) -> ItemStack {
|
||||
let mut s = ItemStack::new(item, 1);
|
||||
s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")];
|
||||
s
|
||||
}
|
||||
#[test]
|
||||
fn banner_duplicate_copies_the_patterns_of_the_same_colour() {
|
||||
let recipe = Special::BannerDuplicate {
|
||||
banner: ingredient(&["minecraft:white_banner"]),
|
||||
result: "minecraft:white_banner".into(),
|
||||
};
|
||||
let source = patterned("minecraft:white_banner");
|
||||
let blank = ItemStack::new("minecraft:white_banner", 1);
|
||||
let out = recipe.assemble(&[&source, &blank]).expect("copy");
|
||||
assert_eq!(out.data().unwrap().banner_patterns.len(), 1);
|
||||
// Two blanks, or two patterned banners, do not match.
|
||||
assert!(recipe.assemble(&[&blank, &blank]).is_none());
|
||||
assert!(recipe.assemble(&[&source, &source]).is_none());
|
||||
// Another colour is not in the recipe's ingredient.
|
||||
let other = ItemStack::new("minecraft:red_banner", 1);
|
||||
assert!(recipe.assemble(&[&source, &other]).is_none());
|
||||
}
|
||||
#[test]
|
||||
fn shield_decoration_needs_a_bare_shield() {
|
||||
let recipe = Special::ShieldDecoration {
|
||||
banner: ingredient(&["minecraft:red_banner"]),
|
||||
target: ingredient(&["minecraft:shield"]),
|
||||
result: "minecraft:shield".into(),
|
||||
};
|
||||
let banner = patterned("minecraft:red_banner");
|
||||
let shield = ItemStack::new("minecraft:shield", 1);
|
||||
let out = recipe.assemble(&[&banner, &shield]).expect("decorated");
|
||||
let data = out.data().unwrap();
|
||||
assert_eq!(data.base_color.as_deref(), Some("red"));
|
||||
assert_eq!(data.banner_patterns.len(), 1);
|
||||
// A shield that already has patterns cannot be decorated again.
|
||||
assert!(recipe.assemble(&[&banner, &out]).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! The pure parts of `/data` (DataCommands): merging compounds, the
|
||||
//! `modify` operations over an NBT path, string sources and the numeric
|
||||
//! result of `get`.
|
||||
use crate::{
|
||||
command::CommandError,
|
||||
nbt_path::{CollectionError, NbtPath, PathError, too_deep},
|
||||
snbt::to_snbt,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
/// `CompoundTag.merge`: compounds merge recursively, anything else replaces.
|
||||
pub fn merge_compound(target: &mut Compound, source: &Compound) {
|
||||
for (k, v) in source {
|
||||
match (target.get_mut(k), v) {
|
||||
(Some(Tag::Compound(t)), Tag::Compound(s)) => merge_compound(t, s),
|
||||
_ => {
|
||||
target.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `old.copy().merge(nbt)`.
|
||||
pub fn merged(old: &Tag, nbt: &Tag) -> Tag {
|
||||
let mut result = old.clone();
|
||||
if let (Tag::Compound(t), Tag::Compound(s)) = (&mut result, nbt) {
|
||||
merge_compound(t, s);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn path_error(e: PathError) -> CommandError {
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
e.args.iter().map(|a| a as &dyn std::fmt::Display).collect();
|
||||
CommandError::tr(e.key, &args)
|
||||
}
|
||||
pub fn collection_error(e: CollectionError) -> CommandError {
|
||||
match e {
|
||||
CollectionError::Path(p) => path_error(p),
|
||||
CollectionError::ExpectedList(t) => {
|
||||
CommandError::tr("commands.data.modify.expected_list", &[&t])
|
||||
}
|
||||
CollectionError::InvalidIndex(i) => {
|
||||
CommandError::tr("commands.data.modify.invalid_index", &[&i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `modify` operation words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Op {
|
||||
Insert(i32),
|
||||
Prepend,
|
||||
Append,
|
||||
Set,
|
||||
Merge,
|
||||
}
|
||||
/// Run a `modify` operation; the count is how many tags changed (0 = fail).
|
||||
pub fn modify(
|
||||
op: Op,
|
||||
target: &mut Tag,
|
||||
path: &NbtPath,
|
||||
sources: &[Tag],
|
||||
) -> Result<usize, CommandError> {
|
||||
match op {
|
||||
Op::Insert(i) => path.insert(i, target, sources).map_err(collection_error),
|
||||
Op::Prepend => path.insert(0, target, sources).map_err(collection_error),
|
||||
Op::Append => path.insert(-1, target, sources).map_err(collection_error),
|
||||
Op::Set => {
|
||||
let Some(last) = sources.last() else {
|
||||
return Ok(0);
|
||||
};
|
||||
path.set(target, last).map_err(path_error)
|
||||
}
|
||||
Op::Merge => {
|
||||
let mut combined = Compound::new();
|
||||
for s in sources {
|
||||
if too_deep(s, 0) {
|
||||
return Err(CommandError::tr("arguments.nbtpath.too_deep", &[]));
|
||||
}
|
||||
let Tag::Compound(c) = s else {
|
||||
return Err(CommandError::tr(
|
||||
"commands.data.modify.expected_object",
|
||||
&[&to_snbt(s)],
|
||||
));
|
||||
};
|
||||
merge_compound(&mut combined, c);
|
||||
}
|
||||
let mut changed = 0;
|
||||
let mut error = None;
|
||||
path.get_or_create(target, &|| Tag::Compound(Compound::new()), &mut |t| {
|
||||
if error.is_some() {
|
||||
return;
|
||||
}
|
||||
match t {
|
||||
Tag::Compound(c) => {
|
||||
let before = c.clone();
|
||||
merge_compound(c, &combined);
|
||||
changed += usize::from(before != *c);
|
||||
}
|
||||
other => {
|
||||
error = Some(CommandError::tr(
|
||||
"commands.data.modify.expected_object",
|
||||
&[&to_snbt(other)],
|
||||
));
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(path_error)?;
|
||||
match error {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(changed),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `getAsText`: strings and numbers as text, anything else is an error.
|
||||
pub fn as_text(tag: &Tag) -> Result<String, CommandError> {
|
||||
match tag {
|
||||
Tag::String(s) => Ok(s.to_string_lossy()),
|
||||
Tag::Byte(_)
|
||||
| Tag::Short(_)
|
||||
| Tag::Int(_)
|
||||
| Tag::Long(_)
|
||||
| Tag::Float(_)
|
||||
| Tag::Double(_) => {
|
||||
// PrimitiveTag.toString: the SNBT form (with its suffix).
|
||||
Ok(to_snbt(tag))
|
||||
}
|
||||
other => Err(CommandError::tr(
|
||||
"commands.data.modify.expected_value",
|
||||
&[&to_snbt(other)],
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// `substring(input, start[, end])` with negative offsets from the end.
|
||||
pub fn substring(input: &str, start: i32, end: Option<i32>) -> Result<String, CommandError> {
|
||||
let chars: Vec<u16> = input.encode_utf16().collect();
|
||||
let len = chars.len() as i32;
|
||||
let offset = |i: i32| if i >= 0 { i } else { len + i };
|
||||
let (s, e) = (offset(start), end.map_or(len, offset));
|
||||
if s >= 0 && e <= len && s <= e {
|
||||
Ok(String::from_utf16_lossy(&chars[s as usize..e as usize]))
|
||||
} else {
|
||||
Err(CommandError::tr(
|
||||
"commands.data.modify.invalid_substring",
|
||||
&[&s, &e],
|
||||
))
|
||||
}
|
||||
}
|
||||
/// `getSingleTag`: exactly one tag at the path.
|
||||
pub fn single_tag(path: &NbtPath, data: &Tag) -> Result<Tag, CommandError> {
|
||||
let mut tags = path.get(data).map_err(path_error)?;
|
||||
if tags.len() > 1 {
|
||||
return Err(CommandError::tr("commands.data.get.multiple", &[]));
|
||||
}
|
||||
Ok(tags.remove(0))
|
||||
}
|
||||
/// The value of a tag as a double (NumericTag.doubleValue).
|
||||
pub fn numeric(tag: &Tag) -> Option<f64> {
|
||||
Some(match tag {
|
||||
Tag::Byte(v) => f64::from(*v),
|
||||
Tag::Short(v) => f64::from(*v),
|
||||
Tag::Int(v) => f64::from(*v),
|
||||
Tag::Long(v) => *v as f64,
|
||||
Tag::Float(v) => f64::from(f32::from_bits(*v)),
|
||||
Tag::Double(v) => f64::from_bits(*v),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `data get <path>`'s return value: the number's floor, or a size.
|
||||
pub fn get_value(tag: &Tag, path: &NbtPath) -> Result<i32, CommandError> {
|
||||
Ok(match tag {
|
||||
Tag::List(l) => l.len() as i32,
|
||||
Tag::ByteArray(a) => a.len() as i32,
|
||||
Tag::IntArray(a) => a.len() as i32,
|
||||
Tag::LongArray(a) => a.len() as i32,
|
||||
Tag::Compound(c) => c.len() as i32,
|
||||
Tag::String(s) => s.0.len() as i32,
|
||||
Tag::End => {
|
||||
return Err(CommandError::tr(
|
||||
"commands.data.get.unknown",
|
||||
&[&path.as_str()],
|
||||
));
|
||||
}
|
||||
other => numeric(other).map_or(0, |v| v.floor() as i32),
|
||||
})
|
||||
}
|
||||
/// `Mth.floor(value * scale)` for `data get <path> <scale>`.
|
||||
pub fn scaled_value(tag: &Tag, path: &NbtPath, scale: f64) -> Result<i32, CommandError> {
|
||||
match numeric(tag) {
|
||||
Some(v) => Ok((v * scale).floor() as i32),
|
||||
None => Err(CommandError::tr(
|
||||
"commands.data.get.invalid",
|
||||
&[&path.as_str()],
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// The text `data get ... <scale>` prints for the scale (`%.2f`).
|
||||
pub fn scale_text(scale: f64) -> Text {
|
||||
Text::literal(format!("{scale:.2}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
fn tag(s: &str) -> Tag {
|
||||
parse_snbt(s).unwrap().0
|
||||
}
|
||||
fn path(s: &str) -> NbtPath {
|
||||
NbtPath::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_is_recursive() {
|
||||
let old = tag("{a:{b:1,c:2},d:[1]}");
|
||||
assert_eq!(
|
||||
to_snbt(&merged(&old, &tag("{a:{b:9},e:1}"))),
|
||||
"{a:{b:9,c:2},d:[1],e:1}"
|
||||
);
|
||||
assert_eq!(merged(&old, &tag("{}")), old);
|
||||
// Lists and scalars are replaced, not merged.
|
||||
assert_eq!(
|
||||
to_snbt(&merged(&old, &tag("{d:[2]}"))),
|
||||
"{a:{b:1,c:2},d:[2]}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modify_operations() {
|
||||
let mut t = tag("{l:[1,2],o:{a:1}}");
|
||||
assert_eq!(
|
||||
modify(Op::Append, &mut t, &path("l"), &[tag("3")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Prepend, &mut t, &path("l"), &[tag("0")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Insert(2), &mut t, &path("l"), &[tag("9")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(to_snbt(&t), "{l:[0,1,9,2,3],o:{a:1}}");
|
||||
assert_eq!(
|
||||
modify(Op::Set, &mut t, &path("o.a"), &[tag("1"), tag("2")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Set, &mut t, &path("o.a"), &[tag("2")]).unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Merge, &mut t, &path("o"), &[tag("{b:1}")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Merge, &mut t, &path("o"), &[tag("{b:1}")]).unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(to_snbt(&t), "{l:[0,1,9,2,3],o:{a:2,b:1}}");
|
||||
let e = modify(Op::Merge, &mut t, &path("o"), &[tag("3")]).unwrap_err();
|
||||
assert_eq!(e.message.plain(), "commands.data.modify.expected_object");
|
||||
let e = modify(Op::Append, &mut t, &path("o"), &[tag("3")]).unwrap_err();
|
||||
assert_eq!(e.message.plain(), "commands.data.modify.expected_list");
|
||||
// Merge creates the target compound when missing.
|
||||
assert_eq!(
|
||||
modify(Op::Merge, &mut t, &path("new.deep"), &[tag("{x:1}")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(single_tag(&path("new.deep.x"), &t).unwrap(), Tag::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_values() {
|
||||
assert_eq!(substring("abcdef", 1, Some(3)).unwrap(), "bc");
|
||||
assert_eq!(substring("abcdef", -2, None).unwrap(), "ef");
|
||||
assert_eq!(substring("abcdef", 0, Some(-1)).unwrap(), "abcde");
|
||||
assert!(substring("abc", 2, Some(1)).is_err());
|
||||
assert!(substring("abc", 0, Some(9)).is_err());
|
||||
assert_eq!(as_text(&tag("\"x\"")).unwrap(), "x");
|
||||
assert_eq!(as_text(&tag("5b")).unwrap(), "5b");
|
||||
assert!(as_text(&tag("[1]")).is_err());
|
||||
let data = tag("{n:2.7d,s:\"abcd\",l:[1,2,3],c:{a:1,b:2},m:[1,2]}");
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("n"), &data).unwrap(), &path("n")).unwrap(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("s"), &data).unwrap(), &path("s")).unwrap(),
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("l"), &data).unwrap(), &path("l")).unwrap(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("c"), &data).unwrap(), &path("c")).unwrap(),
|
||||
2
|
||||
);
|
||||
assert_eq!(scaled_value(&Tag::Int(7), &path("n"), 0.5).unwrap(), 3);
|
||||
assert_eq!(
|
||||
scaled_value(&Tag::Double((-0.5f64).to_bits()), &path("n"), 1.0).unwrap(),
|
||||
-1
|
||||
);
|
||||
assert!(scaled_value(&tag("\"x\""), &path("s"), 1.0).is_err());
|
||||
assert_eq!(
|
||||
single_tag(&path("m[]"), &data).unwrap_err().message.plain(),
|
||||
"commands.data.get.multiple"
|
||||
);
|
||||
assert_eq!(scale_text(1.0).plain(), "1.00");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
//! Data packs (`<world>/datapacks`: folders and zips with `pack.mcmeta`) and
|
||||
//! the parts of them commands use: `.mcfunction` functions (with macros and
|
||||
//! line continuation), function tags and predicates.
|
||||
use crate::zip::Zip;
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// A pack on disk.
|
||||
pub struct DataPack {
|
||||
/// `file/<name>` in `/datapack` and level.dat.
|
||||
pub id: String,
|
||||
source: Source,
|
||||
}
|
||||
enum Source {
|
||||
Dir(PathBuf),
|
||||
Zip(Box<Zip>),
|
||||
}
|
||||
impl DataPack {
|
||||
/// Every file path under `prefix` (relative to the pack root).
|
||||
fn list(&self, prefix: &str) -> Vec<String> {
|
||||
match &self.source {
|
||||
Source::Zip(z) => z
|
||||
.names()
|
||||
.filter(|n| n.starts_with(prefix) && !n.ends_with('/'))
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
Source::Dir(root) => {
|
||||
let mut out = Vec::new();
|
||||
walk(root, &root.join(prefix), &mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
match &self.source {
|
||||
Source::Zip(z) => z.read(path).ok(),
|
||||
Source::Dir(root) => std::fs::read(root.join(path)).ok(),
|
||||
}
|
||||
}
|
||||
/// The `description` of `pack.mcmeta`, as text.
|
||||
pub fn description(&self) -> String {
|
||||
let Some(bytes) = self.read("pack.mcmeta") else {
|
||||
return String::new();
|
||||
};
|
||||
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default();
|
||||
match &v["pack"]["description"] {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
other => other["text"].as_str().unwrap_or_default().to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(std::fs::DirEntry::file_name);
|
||||
for e in entries {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
walk(root, &p, out);
|
||||
} else if let Ok(rel) = p.strip_prefix(root) {
|
||||
out.push(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The packs in `<world>/datapacks`, sorted by name.
|
||||
pub fn discover(world: &Path) -> Vec<DataPack> {
|
||||
let Ok(entries) = std::fs::read_dir(world.join("datapacks")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut packs = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let path = e.path();
|
||||
if path.is_dir() && path.join("pack.mcmeta").exists() {
|
||||
packs.push(DataPack {
|
||||
id: format!("file/{name}"),
|
||||
source: Source::Dir(path),
|
||||
});
|
||||
} else if name.ends_with(".zip")
|
||||
&& let Ok(z) = Zip::open(&path)
|
||||
&& z.contains("pack.mcmeta")
|
||||
{
|
||||
packs.push(DataPack {
|
||||
id: format!("file/{name}"),
|
||||
source: Source::Zip(Box::new(z)),
|
||||
});
|
||||
}
|
||||
}
|
||||
packs.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
packs
|
||||
}
|
||||
|
||||
// ---- functions ---------------------------------------------------------------
|
||||
|
||||
/// A `.mcfunction`: plain command lines and macro lines.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Function {
|
||||
pub id: String,
|
||||
pub lines: Vec<FunctionLine>,
|
||||
/// Macro parameter names in order of first use.
|
||||
pub parameters: Vec<String>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum FunctionLine {
|
||||
Command(String),
|
||||
/// A `$` line: text with `$(name)` placeholders.
|
||||
Macro(String),
|
||||
}
|
||||
impl Function {
|
||||
pub fn is_macro(&self) -> bool {
|
||||
!self.parameters.is_empty()
|
||||
}
|
||||
/// `MacroFunction.instantiate`: the command lines with the arguments
|
||||
/// substituted. The error is the translation key and its arguments.
|
||||
pub fn instantiate(
|
||||
&self,
|
||||
arguments: Option<&Tag>,
|
||||
) -> Result<Vec<String>, (String, Vec<String>)> {
|
||||
let mut values: BTreeMap<&str, String> = BTreeMap::new();
|
||||
if self.is_macro() {
|
||||
let Some(args) = arguments else {
|
||||
return Err((
|
||||
"commands.function.error.missing_arguments".into(),
|
||||
vec![self.id.clone()],
|
||||
));
|
||||
};
|
||||
for p in &self.parameters {
|
||||
let Some(v) = args.get(p) else {
|
||||
return Err((
|
||||
"commands.function.error.missing_argument".into(),
|
||||
vec![self.id.clone(), p.clone()],
|
||||
));
|
||||
};
|
||||
values.insert(p, stringify(v));
|
||||
}
|
||||
}
|
||||
Ok(self
|
||||
.lines
|
||||
.iter()
|
||||
.map(|l| match l {
|
||||
FunctionLine::Command(c) => c.clone(),
|
||||
FunctionLine::Macro(t) => substitute(t, &values),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
/// `MacroFunction.stringify`.
|
||||
fn stringify(tag: &Tag) -> String {
|
||||
match tag {
|
||||
Tag::Float(v) => decimal(f64::from(f32::from_bits(*v))),
|
||||
Tag::Double(v) => decimal(f64::from_bits(*v)),
|
||||
Tag::Byte(v) => v.to_string(),
|
||||
Tag::Short(v) => v.to_string(),
|
||||
Tag::Long(v) => v.to_string(),
|
||||
Tag::String(s) => s.to_string_lossy(),
|
||||
other => crate::snbt::to_snbt(other),
|
||||
}
|
||||
}
|
||||
/// `DecimalFormat("#")` with up to 15 fraction digits.
|
||||
fn decimal(v: f64) -> String {
|
||||
if v.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
let s = format!("{v:.15}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() {
|
||||
"0".into()
|
||||
} else {
|
||||
s.to_owned()
|
||||
}
|
||||
}
|
||||
fn substitute(template: &str, values: &BTreeMap<&str, String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find("$(") {
|
||||
out.push_str(&rest[..i]);
|
||||
let after = &rest[i + 2..];
|
||||
match after.find(')') {
|
||||
Some(j) => {
|
||||
if let Some(v) = values.get(&after[..j]) {
|
||||
out.push_str(v);
|
||||
}
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push_str(&rest[i..]);
|
||||
rest = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
fn macro_parameters(line: &str) -> Result<Vec<String>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = line;
|
||||
while let Some(i) = rest.find("$(") {
|
||||
let after = &rest[i + 2..];
|
||||
let Some(j) = after.find(')') else {
|
||||
return Err(format!("Unterminated macro variable in '{line}'"));
|
||||
};
|
||||
let name = &after[..j];
|
||||
if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
|
||||
return Err(format!("Invalid macro variable name '{name}' in '{line}'"));
|
||||
}
|
||||
out.push(name.to_owned());
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// `CommandFunction.fromLines`: comments, blank lines, `\` continuation and
|
||||
/// `$` macro lines. Command syntax is checked by the caller.
|
||||
pub fn parse_function(id: &str, text: &str) -> Result<Function, String> {
|
||||
let raw: Vec<&str> = text.lines().collect();
|
||||
let mut lines = Vec::new();
|
||||
let mut parameters: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < raw.len() {
|
||||
let number = i + 1;
|
||||
let mut line = raw[i].trim().to_owned();
|
||||
if line.ends_with('\\') {
|
||||
loop {
|
||||
i += 1;
|
||||
if i == raw.len() {
|
||||
return Err("Line continuation at end of file".into());
|
||||
}
|
||||
line.pop();
|
||||
line.push_str(raw[i].trim());
|
||||
if !line.ends_with('\\') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('/') {
|
||||
let name: String = rest
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+'))
|
||||
.collect();
|
||||
return Err(if rest.starts_with('/') {
|
||||
format!(
|
||||
"Unknown or invalid command '{line}' on line {number} (if you intended to make a comment, use '#' not '//')"
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Unknown or invalid command '{line}' on line {number} (did you mean '{name}'? Do not use a preceding forwards slash.)"
|
||||
)
|
||||
});
|
||||
}
|
||||
if let Some(m) = line.strip_prefix('$') {
|
||||
for p in macro_parameters(m)? {
|
||||
if !parameters.contains(&p) {
|
||||
parameters.push(p);
|
||||
}
|
||||
}
|
||||
lines.push(FunctionLine::Macro(m.to_owned()));
|
||||
} else {
|
||||
lines.push(FunctionLine::Command(line));
|
||||
}
|
||||
}
|
||||
Ok(Function {
|
||||
id: id.to_owned(),
|
||||
lines,
|
||||
parameters,
|
||||
})
|
||||
}
|
||||
|
||||
/// The data of every enabled pack: functions, function tags, predicates.
|
||||
#[derive(Default)]
|
||||
pub struct DataStore {
|
||||
pub functions: BTreeMap<String, Function>,
|
||||
/// Function tag id -> entries (`ns:f`, `#ns:tag`), with `required` flags.
|
||||
pub function_tags: BTreeMap<String, Vec<(String, bool)>>,
|
||||
pub predicates: BTreeMap<String, serde_json::Value>,
|
||||
/// Functions that failed to parse (id, message), for logging.
|
||||
pub errors: Vec<(String, String)>,
|
||||
}
|
||||
/// `ns:path` for a file `data/<ns>/<kind>/<path>.<ext>`.
|
||||
fn resource_id(file: &str, kind: &str, ext: &str) -> Option<String> {
|
||||
let rest = file.strip_prefix("data/")?;
|
||||
let (ns, rest) = rest.split_once('/')?;
|
||||
let path = rest
|
||||
.strip_prefix(kind)?
|
||||
.strip_prefix('/')?
|
||||
.strip_suffix(ext)?;
|
||||
Some(format!("{ns}:{path}"))
|
||||
}
|
||||
impl DataStore {
|
||||
pub fn load(packs: &[&DataPack]) -> Self {
|
||||
let mut s = Self::default();
|
||||
for pack in packs {
|
||||
for f in pack.list("data/") {
|
||||
if let Some(id) = resource_id(&f, "function", ".mcfunction")
|
||||
&& let Some(bytes) = pack.read(&f)
|
||||
{
|
||||
match parse_function(&id, &String::from_utf8_lossy(&bytes)) {
|
||||
Ok(func) => {
|
||||
s.functions.insert(id, func);
|
||||
}
|
||||
Err(e) => s.errors.push((id, e)),
|
||||
}
|
||||
} else if let Some(id) = resource_id(&f, "tags/function", ".json")
|
||||
&& let Some(bytes) = pack.read(&f)
|
||||
&& let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes)
|
||||
{
|
||||
let entries = tag_entries(&v);
|
||||
let slot = s.function_tags.entry(id).or_default();
|
||||
if v["replace"].as_bool() == Some(true) {
|
||||
slot.clear();
|
||||
}
|
||||
slot.extend(entries);
|
||||
} else if let Some(id) = resource_id(&f, "predicate", ".json")
|
||||
&& let Some(bytes) = pack.read(&f)
|
||||
&& let Ok(v) = serde_json::from_slice(&bytes)
|
||||
{
|
||||
s.predicates.insert(id, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
/// `FunctionManager.getTag`: the functions a tag expands to (nested tags
|
||||
/// included, each function once).
|
||||
pub fn tag_functions(&self, id: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
self.expand(id, &mut out, 0);
|
||||
out
|
||||
}
|
||||
fn expand(&self, id: &str, out: &mut Vec<String>, depth: usize) {
|
||||
if depth > 16 {
|
||||
return;
|
||||
}
|
||||
let Some(entries) = self.function_tags.get(id) else {
|
||||
return;
|
||||
};
|
||||
for (e, required) in entries {
|
||||
match e.strip_prefix('#') {
|
||||
Some(inner) => self.expand(inner, out, depth + 1),
|
||||
None => {
|
||||
if (self.functions.contains_key(e) || *required) && !out.contains(e) {
|
||||
out.push(e.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn normalize(id: &str) -> String {
|
||||
if id.contains(':') {
|
||||
id.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
}
|
||||
}
|
||||
fn tag_entries(v: &serde_json::Value) -> Vec<(String, bool)> {
|
||||
v["values"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| match e {
|
||||
serde_json::Value::String(s) => Some((hash_normalize(s), true)),
|
||||
serde_json::Value::Object(o) => Some((
|
||||
hash_normalize(o.get("id")?.as_str()?),
|
||||
o.get("required")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(true),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn hash_normalize(s: &str) -> String {
|
||||
match s.strip_prefix('#') {
|
||||
Some(rest) => format!("#{}", normalize(rest)),
|
||||
None => normalize(s),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
#[test]
|
||||
fn parses_comments_continuations_and_macros() {
|
||||
let f = parse_function(
|
||||
"a:b",
|
||||
"# a comment\n\nsay hi\n say \\\n there \n$say $(who) is $(n)\n$tell $(who) $(who)\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
f.lines,
|
||||
vec![
|
||||
FunctionLine::Command("say hi".into()),
|
||||
FunctionLine::Command("say there".into()),
|
||||
FunctionLine::Macro("say $(who) is $(n)".into()),
|
||||
FunctionLine::Macro("tell $(who) $(who)".into()),
|
||||
]
|
||||
);
|
||||
assert_eq!(f.parameters, ["who", "n"]);
|
||||
assert!(
|
||||
parse_function("a:b", "/say hi")
|
||||
.unwrap_err()
|
||||
.contains("did you mean 'say'")
|
||||
);
|
||||
assert!(
|
||||
parse_function("a:b", "//x")
|
||||
.unwrap_err()
|
||||
.contains("use '#'")
|
||||
);
|
||||
assert!(parse_function("a:b", "say \\").is_err());
|
||||
assert!(parse_function("a:b", "$say $(bad name)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macros_substitute_vanilla_text() {
|
||||
let f = parse_function("a:b", "$say $(s) $(i) $(d) $(l) $(b) $(c)\nsay plain").unwrap();
|
||||
let args = parse_snbt("{s:\"hi\",i:5,d:1.5d,l:7L,b:1b,c:{x:1}}")
|
||||
.unwrap()
|
||||
.0;
|
||||
let out = f.instantiate(Some(&args)).unwrap();
|
||||
assert_eq!(out, ["say hi 5 1.5 7 1 {x:1}", "say plain"]);
|
||||
let args = parse_snbt("{s:\"x\",i:1,d:3.0d,l:1L,b:0b,c:{}}").unwrap().0;
|
||||
assert_eq!(f.instantiate(Some(&args)).unwrap()[0], "say x 1 3 1 0 {}");
|
||||
assert_eq!(
|
||||
f.instantiate(None).unwrap_err().0,
|
||||
"commands.function.error.missing_arguments"
|
||||
);
|
||||
let partial = parse_snbt("{s:\"x\"}").unwrap().0;
|
||||
assert_eq!(
|
||||
f.instantiate(Some(&partial)).unwrap_err().0,
|
||||
"commands.function.error.missing_argument"
|
||||
);
|
||||
// A plain function needs no arguments.
|
||||
let plain = parse_function("a:p", "say 1").unwrap();
|
||||
assert_eq!(plain.instantiate(None).unwrap(), ["say 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packs_provide_functions_and_tags() {
|
||||
let dir = std::env::temp_dir().join(format!("hz-datapack-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let pack = dir.join("datapacks/mypack");
|
||||
let write = |p: &str, t: &str| {
|
||||
let path = pack.join(p);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, t).unwrap();
|
||||
};
|
||||
write(
|
||||
"pack.mcmeta",
|
||||
"{\"pack\":{\"description\":\"Hello\",\"pack_format\":1}}",
|
||||
);
|
||||
write(
|
||||
"data/mine/function/a.mcfunction",
|
||||
"say a\nfunction mine:sub/b\n",
|
||||
);
|
||||
write("data/mine/function/sub/b.mcfunction", "say b");
|
||||
write(
|
||||
"data/minecraft/tags/function/tick.json",
|
||||
"{\"values\":[\"mine:a\",\"#mine:more\",{\"id\":\"mine:gone\",\"required\":false}]}",
|
||||
);
|
||||
write(
|
||||
"data/mine/tags/function/more.json",
|
||||
"{\"values\":[\"mine:sub/b\",\"mine:a\"]}",
|
||||
);
|
||||
write(
|
||||
"data/mine/predicate/p.json",
|
||||
"{\"condition\":\"minecraft:random_chance\",\"chance\":1}",
|
||||
);
|
||||
let packs = discover(&dir);
|
||||
assert_eq!(packs.len(), 1);
|
||||
assert_eq!(packs[0].id, "file/mypack");
|
||||
assert_eq!(packs[0].description(), "Hello");
|
||||
let store = DataStore::load(&[&packs[0]]);
|
||||
assert_eq!(store.functions.len(), 2);
|
||||
assert!(store.functions.contains_key("mine:sub/b"));
|
||||
assert_eq!(
|
||||
store.tag_functions("minecraft:tick"),
|
||||
["mine:a", "mine:sub/b"]
|
||||
);
|
||||
assert!(store.predicates.contains_key("mine:p"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,11 @@ impl Enchantments {
|
||||
|| k.starts_with("potion.")
|
||||
|| k.starts_with("container.")
|
||||
|| k.starts_with("merchant.")
|
||||
|| k.starts_with("entity.minecraft.villager")
|
||||
|| k.starts_with("entity.minecraft.")
|
||||
|| k.starts_with("gui.recipebook.")
|
||||
|| k.starts_with("gui.togglable_slot")
|
||||
|| k.starts_with("block.minecraft.banner.")
|
||||
|| k.starts_with("recipe.toast.")
|
||||
})
|
||||
.collect();
|
||||
let mut list = Vec::new();
|
||||
|
||||
@@ -121,10 +121,21 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let Tag::Compound(map) = &mut tag else {
|
||||
return tag;
|
||||
};
|
||||
for (key, on) in [
|
||||
("NoAI", m.no_ai),
|
||||
("Silent", m.silent),
|
||||
("Invulnerable", m.invulnerable_flag),
|
||||
] {
|
||||
if on {
|
||||
map.insert(key.into(), Tag::Byte(1));
|
||||
} else {
|
||||
map.remove(&horizon_world::nbt::JavaString::from(key));
|
||||
}
|
||||
}
|
||||
for (key, value) in [
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
("CanPickUpLoot", Tag::Byte(0)),
|
||||
("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))),
|
||||
("LeftHanded", Tag::Byte(0)),
|
||||
(
|
||||
"Brain",
|
||||
@@ -205,6 +216,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.insert("Variant".into(), Tag::Int(v));
|
||||
}
|
||||
map.insert("ChestedHorse".into(), Tag::Byte(i8::from(m.extra.chested)));
|
||||
if m.extra.chested && !m.extra.items.is_empty() {
|
||||
map.insert("Items".into(), crate::save::encode_items(&m.extra.items));
|
||||
} else {
|
||||
map.remove(&"Items".into());
|
||||
}
|
||||
let mut equipment = Vec::new();
|
||||
if m.extra.saddled {
|
||||
equipment.push((
|
||||
@@ -246,6 +262,14 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
map.insert("equipment".into(), Tag::Compound(equipment));
|
||||
}
|
||||
"minecraft:creaking" => {
|
||||
// home_pos: the heart it is bound to.
|
||||
if let Some(home) = m.extra.home {
|
||||
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
|
||||
} else {
|
||||
map.remove(&"home_pos".into());
|
||||
}
|
||||
}
|
||||
"minecraft:villager" => {
|
||||
use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
|
||||
let data = Tag::compound([
|
||||
@@ -272,6 +296,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.insert("RestocksToday".into(), Tag::Int(t.restocks_today));
|
||||
put_offers(map, m);
|
||||
put_memories(map, m);
|
||||
crate::mobs::villager::write_nbt(m, map);
|
||||
}
|
||||
"minecraft:wandering_trader" => put_offers(map, m),
|
||||
"minecraft:allay" => {
|
||||
@@ -314,6 +339,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
"minecraft:wither" => {
|
||||
map.insert("Invul".into(), Tag::Int(m.extra.counter));
|
||||
}
|
||||
"minecraft:warden" => {
|
||||
if let Some(st) = &m.extra.warden {
|
||||
map.insert("listener".into(), st.vibration.to_nbt());
|
||||
map.insert(
|
||||
"anger".into(),
|
||||
Tag::compound([("suspects", Tag::List(Vec::new()))]),
|
||||
);
|
||||
}
|
||||
}
|
||||
"minecraft:ravager" => {
|
||||
map.insert("AttackTick".into(), Tag::Int(m.extra.counter));
|
||||
map.insert("StunTick".into(), Tag::Int(m.extra.counter2));
|
||||
@@ -363,6 +397,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
crate::mobs::raider::write_nbt(m, map);
|
||||
// LivingEntity equipment: what the mob holds now.
|
||||
if !crate::mobs::equine::is_equine(m.species()) {
|
||||
let mut equipment = match map.get(&"equipment".into()) {
|
||||
@@ -383,7 +418,22 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
equipment.get(&slot.into()).and_then(|e| e.get("id")),
|
||||
Some(Tag::String(s)) if s.to_string_lossy() == **id
|
||||
);
|
||||
if !keep {
|
||||
if slot == "head"
|
||||
&& &**id == crate::mobs::raider::BANNER
|
||||
&& crate::mobs::raider::is_raider(m.species())
|
||||
{
|
||||
// The captain's ominous banner keeps its patterns.
|
||||
let has_patterns = equipment
|
||||
.get(&slot.into())
|
||||
.and_then(|e| e.get("components"))
|
||||
.is_some();
|
||||
if !has_patterns {
|
||||
equipment.insert(
|
||||
slot.into(),
|
||||
crate::save::item_to_nbt(&crate::mobs::raider::ominous_banner()),
|
||||
);
|
||||
}
|
||||
} else if !keep {
|
||||
equipment.insert(
|
||||
slot.into(),
|
||||
Tag::compound([
|
||||
@@ -446,12 +496,17 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
}
|
||||
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
|
||||
m.persistent = flag(tag, "PersistenceRequired");
|
||||
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
|
||||
m.custom_name = custom_name(tag);
|
||||
if m.kind.category == "creature" {
|
||||
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
|
||||
m.extra.age_locked = flag(tag, "AgeLocked");
|
||||
}
|
||||
m.name_visible = flag(tag, "CustomNameVisible");
|
||||
m.no_ai = flag(tag, "NoAI");
|
||||
m.silent = flag(tag, "Silent");
|
||||
m.invulnerable_flag = flag(tag, "Invulnerable");
|
||||
m.no_gravity = m.no_gravity || flag(tag, "NoGravity");
|
||||
if m.species() == crate::mobs::Species::Creeper {
|
||||
m.extra.charged = flag(tag, "powered");
|
||||
}
|
||||
@@ -479,6 +534,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.variant = (v & 0xFF).clamp(0, 6) as u8;
|
||||
m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8;
|
||||
m.extra.chested = flag(tag, "ChestedHorse");
|
||||
if m.extra.chested {
|
||||
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
|
||||
}
|
||||
let eq = tag.get("equipment");
|
||||
m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some();
|
||||
m.extra.head = eq
|
||||
@@ -562,9 +620,22 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.egg_time = -1 - 400;
|
||||
}
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Creaking
|
||||
&& let Some(Tag::IntArray(home)) = tag.get("home_pos")
|
||||
&& home.len() == 3
|
||||
{
|
||||
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Wither {
|
||||
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Warden {
|
||||
// The brain starts afresh: a minute before it digs back down.
|
||||
crate::mobs::warden::finalize(&mut m, false, &mut Vec::new());
|
||||
if let (Some(st), Some(listener)) = (m.extra.warden.as_mut(), tag.get("listener")) {
|
||||
st.vibration = crate::sculk::Data::from_nbt(listener);
|
||||
}
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Ravager {
|
||||
m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32;
|
||||
m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32;
|
||||
@@ -601,6 +672,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.health = health;
|
||||
m.extra.flag2 = flag(tag, "wasOnGround");
|
||||
}
|
||||
crate::mobs::raider::read_nbt(&mut m, tag);
|
||||
// A mob saved mid-death finishes dying; one saved dead is dropped.
|
||||
if m.health <= 0.0 && m.death_time == 0 {
|
||||
return None;
|
||||
@@ -1014,7 +1086,7 @@ fn put_offers(map: &mut Compound, m: &Mob) {
|
||||
}
|
||||
/// The villager brain's `job_site`, `home` and `meeting_point` memories.
|
||||
fn put_memories(map: &mut Compound, m: &Mob) {
|
||||
let memories: Vec<(&str, Tag)> = [
|
||||
let mut memories: Vec<(&str, Tag)> = [
|
||||
("minecraft:job_site", m.extra.home),
|
||||
("minecraft:home", m.extra.bed),
|
||||
("minecraft:meeting_point", m.extra.meeting),
|
||||
@@ -1028,6 +1100,7 @@ fn put_memories(map: &mut Compound, m: &Mob) {
|
||||
Some((key, Tag::compound([("value", pos)])))
|
||||
})
|
||||
.collect();
|
||||
crate::mobs::villager::write_memories(m, &mut memories);
|
||||
map.insert(
|
||||
"Brain".into(),
|
||||
Tag::compound([("memories", Tag::compound(memories))]),
|
||||
@@ -1061,6 +1134,9 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
|
||||
m.extra.home = memory("minecraft:job_site");
|
||||
m.extra.bed = memory("minecraft:home");
|
||||
m.extra.meeting = memory("minecraft:meeting_point");
|
||||
if m.species() == crate::mobs::Species::Villager {
|
||||
crate::mobs::villager::read_nbt(m, tag);
|
||||
}
|
||||
let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -185,6 +185,8 @@ pub struct FogInputs<'a> {
|
||||
pub skybox: bool,
|
||||
/// Blindness: (remaining duration ticks, infinite).
|
||||
pub blindness: Option<(i32, bool)>,
|
||||
/// The darkness effect's blend factor, while the effect is on.
|
||||
pub darkness: Option<f32>,
|
||||
}
|
||||
|
||||
/// `FogRenderer.setupFog` + `computeFogColor`.
|
||||
@@ -239,6 +241,9 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
} else if let Some(blend) = input.darkness {
|
||||
// DarknessFogEnvironment.getModifiedDarkness.
|
||||
darkness = darkness.max(blend);
|
||||
}
|
||||
if darkness > 0.0 && !matches!(input.fog_type, FogType::Lava | FogType::PowderSnow) {
|
||||
let brightness = (1.0 - darkness) * (1.0 - darkness);
|
||||
@@ -283,6 +288,15 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
|
||||
fog.sky_end = distance * 0.8;
|
||||
fog.cloud_end = distance * 0.8;
|
||||
}
|
||||
_ if input.darkness.is_some() => {
|
||||
// DarknessFogEnvironment.setupFog: closing in to 15 blocks.
|
||||
let blend = input.darkness.unwrap_or(0.0);
|
||||
let distance = rd + (15.0 - rd) * blend;
|
||||
fog.environmental_start = distance * 0.75;
|
||||
fog.environmental_end = distance;
|
||||
fog.sky_end = distance;
|
||||
fog.cloud_end = distance;
|
||||
}
|
||||
FogType::Water => {
|
||||
fog.environmental_start = -8.0;
|
||||
let factor = tables
|
||||
@@ -345,6 +359,7 @@ mod tests {
|
||||
thunder: 0.0,
|
||||
skybox: true,
|
||||
blindness: None,
|
||||
darkness: None,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
|
||||
+307
-118
@@ -4,17 +4,21 @@ mod advancements;
|
||||
mod advancements_screen;
|
||||
mod allays;
|
||||
mod armor_stands;
|
||||
mod banners;
|
||||
mod beacon;
|
||||
mod blockctl;
|
||||
mod boats;
|
||||
mod books;
|
||||
mod bossbars;
|
||||
mod cartography;
|
||||
mod chat;
|
||||
mod combat;
|
||||
mod commands;
|
||||
mod control;
|
||||
mod creaking;
|
||||
mod creatures;
|
||||
mod crossbow;
|
||||
mod dispenser;
|
||||
mod dragon;
|
||||
mod enchant_effects;
|
||||
mod end;
|
||||
@@ -24,15 +28,19 @@ mod fireworks;
|
||||
mod fishing;
|
||||
mod fov;
|
||||
mod frames;
|
||||
mod functions;
|
||||
mod game_mode;
|
||||
mod golems;
|
||||
mod growth;
|
||||
mod jukebox;
|
||||
mod lan;
|
||||
mod lan_screen;
|
||||
mod lightning;
|
||||
mod loom;
|
||||
mod machines;
|
||||
mod maps;
|
||||
mod minecarts;
|
||||
mod mount_menu;
|
||||
mod mounts;
|
||||
mod music;
|
||||
mod names;
|
||||
@@ -44,10 +52,14 @@ mod perspective;
|
||||
mod piglins;
|
||||
mod postprocess;
|
||||
mod potions;
|
||||
mod raids;
|
||||
mod recipe_book;
|
||||
mod remote;
|
||||
mod render_control;
|
||||
mod render_tick;
|
||||
mod scoreboard;
|
||||
mod screens;
|
||||
mod sculk;
|
||||
mod shield;
|
||||
mod sign_edit;
|
||||
mod station_control;
|
||||
@@ -56,11 +68,13 @@ mod stats;
|
||||
mod stats_screen;
|
||||
mod storage;
|
||||
mod structures;
|
||||
mod subtitle_hud;
|
||||
mod titles;
|
||||
mod tnt;
|
||||
mod totem;
|
||||
mod trading;
|
||||
mod trident;
|
||||
mod villagers;
|
||||
mod wither;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
@@ -303,12 +317,26 @@ impl LevelAccess for GameLevel<'_> {
|
||||
fn block_entity_analog_signal(
|
||||
&self,
|
||||
pos: BlockPos,
|
||||
_state: BlockStateId,
|
||||
state: BlockStateId,
|
||||
_direction: Direction,
|
||||
) -> i32 {
|
||||
if let Some(signal) = sculk::sensor_signal(self.world, self.behaviours, state, pos) {
|
||||
return signal;
|
||||
}
|
||||
if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) {
|
||||
return comparator;
|
||||
}
|
||||
if let Some(signal) = creaking::heart_signal(self.world, pos) {
|
||||
return if self.registry.state(state).is_some_and(|s| {
|
||||
s.properties
|
||||
.get("creaking_heart_state")
|
||||
.is_some_and(|v| v == "uprooted")
|
||||
}) {
|
||||
0
|
||||
} else {
|
||||
signal
|
||||
};
|
||||
}
|
||||
if let Some(signal) = books::lectern_signal(self.world, pos) {
|
||||
return signal;
|
||||
}
|
||||
@@ -521,6 +549,8 @@ struct Game<'a> {
|
||||
mobs: Vec<Mob>,
|
||||
arrows: Vec<Arrow>,
|
||||
creatures: creatures::Creatures,
|
||||
sculk: sculk::SculkState,
|
||||
raiding: raids::Raiding,
|
||||
attack_ticks: u32,
|
||||
last_hurt_by_player: HashSet<u32>,
|
||||
chest_open: HashMap<(i32, i32, i32), (f32, f32)>,
|
||||
@@ -611,10 +641,17 @@ struct Game<'a> {
|
||||
ender_open: Option<(i32, i32, i32)>,
|
||||
/// Contents of broken shulker boxes waiting for their dropped item.
|
||||
pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
|
||||
/// Layers of broken banners waiting for their dropped item.
|
||||
pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>,
|
||||
/// The recipe book of the open screen (game/recipe_book.rs).
|
||||
recipe_ui: recipe_book::RecipeUi,
|
||||
/// The horse inventory (game/mount_menu.rs).
|
||||
mount_menu: mount_menu::MountMenu,
|
||||
/// The player's fishing hook.
|
||||
hook: Option<fishing::Hook>,
|
||||
tridents: Vec<trident::ThrownTrident>,
|
||||
rockets: Vec<fireworks::Rocket>,
|
||||
creaking: creaking::CreakingState,
|
||||
trident_model: Option<horizon_client::mobs::Part>,
|
||||
tnts: Vec<tnt::PrimedTnt>,
|
||||
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
|
||||
@@ -636,6 +673,13 @@ struct Game<'a> {
|
||||
combat: combat::CombatTracker,
|
||||
mount: mounts::MountState,
|
||||
stats: stats::Stats,
|
||||
score: scoreboard::ScoreState,
|
||||
fns: functions::FnState,
|
||||
bosses: bossbars::BossState,
|
||||
exec: commands::execute::ExecState,
|
||||
rand_sequences: horizon_client::random_sequences::RandomSequences,
|
||||
border: horizon_client::worldborder::WorldBorder,
|
||||
subtitles: subtitle_hud::SubtitleState,
|
||||
adv: advancements::AdvState,
|
||||
stats_ui: stats_screen::StatsUi,
|
||||
adv_ui: advancements_screen::AdvUi,
|
||||
@@ -986,6 +1030,7 @@ impl Game<'_> {
|
||||
/// Block.popResource
|
||||
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
|
||||
self.attach_shulker_contents(pos, &mut stack);
|
||||
self.attach_banner_layers(pos, &mut stack);
|
||||
let r = &mut self.world.random;
|
||||
let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25;
|
||||
let p = [
|
||||
@@ -1235,6 +1280,12 @@ impl Game<'_> {
|
||||
sounds.pitch * 0.8,
|
||||
);
|
||||
}
|
||||
LevelEvent::LevelEvent {
|
||||
id: 3006,
|
||||
pos,
|
||||
data,
|
||||
} => self.sculk_charge_event(pos, data),
|
||||
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
|
||||
LevelEvent::LevelEvent { id, pos, .. } => {
|
||||
let c = Some([
|
||||
f64::from(pos.x) + 0.5,
|
||||
@@ -1384,10 +1435,17 @@ impl Game<'_> {
|
||||
},
|
||||
);
|
||||
}
|
||||
LevelEvent::GameEvent { pos, event, state } => {
|
||||
self.sculk_level_event(pos, event, state)
|
||||
}
|
||||
LevelEvent::BlockEvent {
|
||||
pos,
|
||||
state,
|
||||
kind: "shrieker_respond",
|
||||
} => self.shrieker_block_event(pos, state),
|
||||
LevelEvent::GrowTree { .. }
|
||||
| LevelEvent::PlaceFeature { .. }
|
||||
| LevelEvent::BlockEvent { .. }
|
||||
| LevelEvent::GameEvent { .. } => {}
|
||||
| LevelEvent::BlockEvent { .. } => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -1424,6 +1482,12 @@ impl Game<'_> {
|
||||
} else if let Some(entity) = BlockEntity::for_block(&name) {
|
||||
self.world.block_entities.entry(key).or_insert(entity);
|
||||
self.container = Some(key);
|
||||
self.post_block_game_event(
|
||||
"minecraft:container_open",
|
||||
[key.0, key.1, key.2],
|
||||
Some(horizon_client::mobs::Who::Player),
|
||||
None,
|
||||
);
|
||||
let stat = match &*name {
|
||||
"minecraft:chest" => "open_chest",
|
||||
"minecraft:trapped_chest" => "trigger_trapped_chest",
|
||||
@@ -1545,6 +1609,9 @@ impl Game<'_> {
|
||||
self.process_level_events()
|
||||
}
|
||||
fn break_block(&mut self, pos: [i32; 3]) -> Result<()> {
|
||||
self.with_player_actor(|game| game.break_block_as_player(pos))
|
||||
}
|
||||
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let facts = self.res.facts.get(state).clone();
|
||||
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
|
||||
@@ -1616,6 +1683,7 @@ impl Game<'_> {
|
||||
None
|
||||
}
|
||||
.unwrap_or(self.world.air);
|
||||
self.creaking_heart_broken(pos);
|
||||
if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) {
|
||||
// Containers.dropContents (shulker boxes keep theirs).
|
||||
let name = facts.name.clone();
|
||||
@@ -1641,6 +1709,9 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
fn use_item(&mut self) -> Result<()> {
|
||||
self.with_player_actor(|game| game.use_item_as_player())
|
||||
}
|
||||
fn use_item_as_player(&mut self) -> Result<()> {
|
||||
// Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass).
|
||||
if self.spectator() {
|
||||
return Ok(());
|
||||
@@ -1817,6 +1888,7 @@ impl Game<'_> {
|
||||
.block_entities
|
||||
.insert((target[0], target[1], target[2]), entity);
|
||||
self.fill_placed_box(target, &stack);
|
||||
self.fill_placed_banner(target, &stack);
|
||||
if sign {
|
||||
self.open_sign_editor((target[0], target[1], target[2]), true);
|
||||
}
|
||||
@@ -1839,6 +1911,7 @@ impl Game<'_> {
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
self.trigger_block("minecraft:placed_block", target, &stack);
|
||||
self.check_wither_spawn(target)?;
|
||||
self.check_golem_spawn(target)?;
|
||||
self.consume_held();
|
||||
Ok(())
|
||||
}
|
||||
@@ -1950,6 +2023,8 @@ impl Game<'_> {
|
||||
}
|
||||
if ticks >= duration {
|
||||
self.using = None;
|
||||
// Consumable.onConsume.
|
||||
self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player);
|
||||
if let Some((nutrition, saturation)) = info.food
|
||||
&& let Some(p) = self.player.as_mut()
|
||||
{
|
||||
@@ -2224,15 +2299,21 @@ impl Game<'_> {
|
||||
return self.tick_remote();
|
||||
}
|
||||
self.ticks += 1;
|
||||
self.world.game_time += 1;
|
||||
if self.ui.rules.bool("advance_weather") {
|
||||
self.world.weather.tick(&mut self.world.random);
|
||||
// `/tick freeze` stops the world but not the player.
|
||||
let running = self.clock.world_runs();
|
||||
if running {
|
||||
self.world.game_time += 1;
|
||||
if self.ui.rules.bool("advance_weather") {
|
||||
self.world.weather.tick(&mut self.world.random);
|
||||
}
|
||||
self.tick_weather_effects();
|
||||
}
|
||||
self.tick_weather_effects();
|
||||
if self.ticks.is_multiple_of(6000) {
|
||||
self.save_game()?;
|
||||
}
|
||||
self.advance_clock();
|
||||
if running {
|
||||
self.advance_clock();
|
||||
}
|
||||
if self.use_delay > 0 {
|
||||
self.use_delay -= 1;
|
||||
}
|
||||
@@ -2402,6 +2483,7 @@ impl Game<'_> {
|
||||
self.death_message();
|
||||
// ServerPlayer.die: deaths, and the time-since counters restart.
|
||||
self.stats.custom("deaths", 1);
|
||||
self.score_player_died();
|
||||
if let Some(kind) = killer {
|
||||
self.stats.add("killed_by", &kind, 1);
|
||||
let view = horizon_client::advancements::EntityView {
|
||||
@@ -2432,36 +2514,47 @@ impl Game<'_> {
|
||||
self.screen = Screen::Dead;
|
||||
self.capture(false);
|
||||
}
|
||||
self.tick_omens();
|
||||
self.tick_effects();
|
||||
self.tick_burning();
|
||||
self.tick_using();
|
||||
self.titles.tick();
|
||||
self.tick_paintings();
|
||||
self.tick_item_frames();
|
||||
self.tick_armor_stands();
|
||||
self.tick_boats();
|
||||
self.tick_carts();
|
||||
self.tick_thunder();
|
||||
self.tick_lecterns();
|
||||
self.tick_maps();
|
||||
self.tick_bolts();
|
||||
self.tick_fishing();
|
||||
self.tick_tridents();
|
||||
self.tick_rockets();
|
||||
if running {
|
||||
self.tick_paintings();
|
||||
self.tick_item_frames();
|
||||
self.tick_armor_stands();
|
||||
self.tick_boats();
|
||||
self.tick_carts();
|
||||
self.tick_thunder();
|
||||
self.tick_lecterns();
|
||||
self.tick_maps();
|
||||
self.tick_bolts();
|
||||
self.tick_fishing();
|
||||
self.tick_tridents();
|
||||
self.tick_rockets();
|
||||
}
|
||||
self.tick_mining()?;
|
||||
self.tick_items();
|
||||
if running {
|
||||
self.tick_items();
|
||||
}
|
||||
self.spawn_loaded_entities();
|
||||
self.tick_mobs()?;
|
||||
if running {
|
||||
self.tick_mobs()?;
|
||||
self.tick_experience();
|
||||
}
|
||||
self.tick_lan();
|
||||
self.tick_experience();
|
||||
self.tick_hand();
|
||||
self.tick_sleep();
|
||||
self.tick_portal()?;
|
||||
self.tick_end()?;
|
||||
if running {
|
||||
self.tick_end()?;
|
||||
}
|
||||
self.postprocess_chunks()?;
|
||||
self.tick_blocks()?;
|
||||
self.tick_falling()?;
|
||||
self.tick_tnt()?;
|
||||
if running {
|
||||
self.tick_blocks()?;
|
||||
self.tick_falling()?;
|
||||
self.tick_tnt()?;
|
||||
}
|
||||
if let Some(p) = &self.player {
|
||||
// Player.aiStep bob and Entity.walkDist (0.6 per block).
|
||||
let (dx, dz) = (
|
||||
@@ -2479,8 +2572,11 @@ impl Game<'_> {
|
||||
};
|
||||
self.bob.1 += (target - self.bob.1) * 0.4;
|
||||
}
|
||||
self.tick_block_entities()?;
|
||||
self.tick_brewing_stands()?;
|
||||
if running {
|
||||
self.tick_block_entities()?;
|
||||
self.tick_sculk()?;
|
||||
self.tick_brewing_stands()?;
|
||||
}
|
||||
if let Some(r) = &self.renderer {
|
||||
let eye = self.player.as_ref().map(|p| {
|
||||
[
|
||||
@@ -2663,13 +2759,18 @@ impl Game<'_> {
|
||||
.map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned()))
|
||||
}
|
||||
fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
|
||||
if &*stack.item == "minecraft:shield" {
|
||||
shield::draw_shield_icon(batch, &self.res.atlas, x, y);
|
||||
return;
|
||||
}
|
||||
let icon = self.icon(&stack.item);
|
||||
// Special-model items: the shield and banners draw their own 3D icon.
|
||||
let banner = if &*stack.item == "minecraft:shield" {
|
||||
let passes = shield::shield_passes(&self.res.stations.banners, stack);
|
||||
shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes);
|
||||
true
|
||||
} else {
|
||||
self.draw_banner_icon(batch, stack, x, y)
|
||||
};
|
||||
let icon = if banner { None } else { self.icon(&stack.item) };
|
||||
let atlas = &self.res.atlas;
|
||||
match icon {
|
||||
None if banner => {}
|
||||
Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX),
|
||||
Some(Icon::Cube {
|
||||
top,
|
||||
@@ -2828,7 +2929,10 @@ impl Game<'_> {
|
||||
self.draw_effect_icons(&mut batch);
|
||||
// Hud: the action bar and titles draw over the hotbar (nextStratum).
|
||||
self.draw_boss_bar(&mut batch);
|
||||
self.draw_custom_bossbars(&mut batch, 12.0 + 19.0 * self.builtin_bar_count() as f32);
|
||||
self.draw_titles(&mut batch);
|
||||
self.draw_scoreboard(&mut batch);
|
||||
self.draw_subtitles(&mut batch);
|
||||
// Gui.renderVehicleHealth / the jump bar while riding a mount.
|
||||
let mounted = !self.creative && !spectator && self.draw_mount_hud(&mut batch, w, h);
|
||||
let atlas = &self.res.atlas;
|
||||
@@ -3028,7 +3132,7 @@ impl Game<'_> {
|
||||
}
|
||||
fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) {
|
||||
(
|
||||
(batch.width - 176.0) / 2.0,
|
||||
(batch.width - 176.0) / 2.0 + self.recipe_book_shift(batch.width),
|
||||
(batch.height - self.screen_height()) / 2.0,
|
||||
)
|
||||
}
|
||||
@@ -3039,19 +3143,23 @@ impl Game<'_> {
|
||||
}
|
||||
/// 300.. are the open container's slots.
|
||||
fn slots(&self) -> Vec<usize> {
|
||||
if let Some(v) = self.station_slots() {
|
||||
if let Some(v) = self.station_slots().or_else(|| self.mount_slots()) {
|
||||
return v;
|
||||
}
|
||||
let mut v: Vec<usize> = (0..36).collect();
|
||||
match self.container_kind() {
|
||||
Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)),
|
||||
Some(BlockEntity::Chest(_)) => v.extend((0..self.container_size()).map(|i| 300 + i)),
|
||||
Some(BlockEntity::Furnace(_)) => v.extend(300..303),
|
||||
Some(BlockEntity::Brewing(_)) => v.extend(300..305),
|
||||
Some(BlockEntity::Crafter(_)) => v.extend(300..310),
|
||||
Some(
|
||||
BlockEntity::Sign(_)
|
||||
| BlockEntity::Jukebox(_)
|
||||
| BlockEntity::Beacon(_)
|
||||
| BlockEntity::Lectern(_),
|
||||
| BlockEntity::Lectern(_)
|
||||
| BlockEntity::Sculk(_)
|
||||
| BlockEntity::Banner(_)
|
||||
| BlockEntity::CreakingHeart(_),
|
||||
) => {}
|
||||
None => {
|
||||
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
|
||||
@@ -3068,15 +3176,18 @@ impl Game<'_> {
|
||||
if let Some(p) = self
|
||||
.station_slot_position(i)
|
||||
.or_else(|| self.machine_slot_position(i))
|
||||
.or_else(|| self.crafter_slot_position(i))
|
||||
.or_else(|| self.mount_slot_position(i))
|
||||
{
|
||||
return p;
|
||||
}
|
||||
let table = self.craft_size == 3;
|
||||
// ContainerScreen (3 rows) shifts the player inventory down by one pixel.
|
||||
let shift = if matches!(self.container_kind(), Some(BlockEntity::Chest(_))) {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
// ChestMenu: the inventory sits `18 * (rows - 3) + 1` lower than the
|
||||
// 3-row layout of the other menus.
|
||||
let shift = match self.chest_rows() {
|
||||
Some(rows) => 1.0 + (rows as f32 - 3.0) * 18.0,
|
||||
None => 0.0,
|
||||
};
|
||||
match i {
|
||||
0..9 => (8.0 + i as f32 * 18.0, 142.0 + shift),
|
||||
@@ -3122,6 +3233,9 @@ impl Game<'_> {
|
||||
})
|
||||
}
|
||||
fn slot_mut(&mut self, i: usize) -> &mut Option<ItemStack> {
|
||||
if i >= mount_menu::SADDLE {
|
||||
return self.mount_slot_mut(i);
|
||||
}
|
||||
if i >= stations::INPUT {
|
||||
return self.station_slot_mut(i);
|
||||
}
|
||||
@@ -3132,14 +3246,7 @@ impl Game<'_> {
|
||||
return &mut self.offhand;
|
||||
}
|
||||
if i >= 300 {
|
||||
let key = self.container;
|
||||
return match key.and_then(|k| self.world.block_entities.get_mut(&k)) {
|
||||
Some(e) => e
|
||||
.slots_mut()
|
||||
.get_mut(i - 300)
|
||||
.unwrap_or(&mut self.scratch_slot),
|
||||
None => &mut self.scratch_slot,
|
||||
};
|
||||
return self.container_slot_mut(i - 300);
|
||||
}
|
||||
if (100..109).contains(&i) {
|
||||
&mut self.craft_grid[i - 100]
|
||||
@@ -3147,6 +3254,14 @@ impl Game<'_> {
|
||||
&mut self.inventory[i]
|
||||
}
|
||||
}
|
||||
/// What a slot shows: the crafting result slots are computed.
|
||||
fn slot_view(&mut self, i: usize) -> Option<ItemStack> {
|
||||
match i {
|
||||
200 => self.craft_result(),
|
||||
309 => self.crafter_result(),
|
||||
_ => self.slot_mut(i).clone(),
|
||||
}
|
||||
}
|
||||
fn craft_result(&self) -> Option<ItemStack> {
|
||||
let n = self.craft_size;
|
||||
let grid: Vec<Option<ItemStack>> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect();
|
||||
@@ -3190,42 +3305,7 @@ impl Game<'_> {
|
||||
.and_then(|k| self.world.block_entities.get(&k))
|
||||
{
|
||||
Some(BlockEntity::Chest(_)) if self.draw_machine_screen(batch, ox, oy) => {}
|
||||
Some(BlockEntity::Chest(_)) => {
|
||||
// ContainerScreen with 3 rows: top 71px, then the player inventory from v=126.
|
||||
part(
|
||||
batch,
|
||||
"gui/container/generic_54",
|
||||
0.0,
|
||||
0.0,
|
||||
176.0,
|
||||
71.0,
|
||||
ox,
|
||||
oy,
|
||||
);
|
||||
part(
|
||||
batch,
|
||||
"gui/container/generic_54",
|
||||
0.0,
|
||||
126.0,
|
||||
176.0,
|
||||
96.0,
|
||||
ox,
|
||||
oy + 71.0,
|
||||
);
|
||||
let name = self
|
||||
.container
|
||||
.map(|k| self.world.block(k.0, k.1, k.2))
|
||||
.map(|s| self.res.facts.get(s).name.clone());
|
||||
let title = if self.open_cart_kind().is_some() {
|
||||
"Minecart with Chest"
|
||||
} else if name.as_deref() == Some("minecraft:barrel") {
|
||||
"Barrel"
|
||||
} else {
|
||||
"Chest"
|
||||
};
|
||||
batch.text(atlas, title, ox + 8.0, oy + 6.0, grey, false);
|
||||
batch.text(atlas, "Inventory", ox + 8.0, oy + 73.0, grey, false);
|
||||
}
|
||||
Some(BlockEntity::Chest(_)) => self.draw_chest_screen(batch, ox, oy),
|
||||
Some(BlockEntity::Furnace(f)) => {
|
||||
let (tex, title) = match f.kind {
|
||||
horizon_client::containers::FurnaceKind::Furnace => {
|
||||
@@ -3272,12 +3352,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Some(BlockEntity::Brewing(_)) => {}
|
||||
Some(BlockEntity::Crafter(_)) => self.draw_crafter_screen(batch, ox, oy),
|
||||
Some(
|
||||
BlockEntity::Sign(_)
|
||||
| BlockEntity::Jukebox(_)
|
||||
| BlockEntity::Beacon(_)
|
||||
| BlockEntity::Lectern(_),
|
||||
| BlockEntity::Lectern(_)
|
||||
| BlockEntity::Sculk(_)
|
||||
| BlockEntity::Banner(_)
|
||||
| BlockEntity::CreakingHeart(_),
|
||||
) => {}
|
||||
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
|
||||
None => {
|
||||
let texture = if self.craft_size == 3 {
|
||||
"gui/container/crafting_table"
|
||||
@@ -3304,7 +3389,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.container.is_none() && self.craft_size != 3 {
|
||||
if self.container.is_none() && self.craft_size != 3 && !self.mount_active() {
|
||||
self.draw_inventory_player(batch, ox, oy);
|
||||
}
|
||||
for i in self.slots() {
|
||||
@@ -3326,15 +3411,12 @@ impl Game<'_> {
|
||||
oy + sy,
|
||||
);
|
||||
}
|
||||
let stack = if i == 200 {
|
||||
self.craft_result()
|
||||
} else {
|
||||
self.slot_mut(i).clone()
|
||||
};
|
||||
let stack = self.slot_view(i);
|
||||
if let Some(stack) = stack {
|
||||
self.draw_item(batch, &stack, ox + sx, oy + sy);
|
||||
}
|
||||
}
|
||||
self.draw_recipe_book(batch);
|
||||
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
|
||||
let (sx, sy) = self.slot_position(slot);
|
||||
batch.fill(
|
||||
@@ -3353,6 +3435,8 @@ impl Game<'_> {
|
||||
}
|
||||
pub(super) fn close_container(&mut self) {
|
||||
self.close_station();
|
||||
self.mount_closed();
|
||||
self.recipe_ui.reset_screen();
|
||||
if self.remote.is_some() {
|
||||
return self.remote_close_container();
|
||||
}
|
||||
@@ -3367,6 +3451,12 @@ impl Game<'_> {
|
||||
}
|
||||
self.craft_size = 2;
|
||||
if let Some(key) = self.container.take() {
|
||||
self.post_block_game_event(
|
||||
"minecraft:container_close",
|
||||
[key.0, key.1, key.2],
|
||||
Some(horizon_client::mobs::Who::Player),
|
||||
None,
|
||||
);
|
||||
let name = self
|
||||
.res
|
||||
.facts
|
||||
@@ -3402,6 +3492,12 @@ impl Game<'_> {
|
||||
self.close_cart_container();
|
||||
}
|
||||
fn click_inventory(&mut self, right: bool) {
|
||||
if self.mount_click(right) {
|
||||
return;
|
||||
}
|
||||
if self.recipe_book_click(right) {
|
||||
return;
|
||||
}
|
||||
if self.station_click(right) {
|
||||
return;
|
||||
}
|
||||
@@ -3419,6 +3515,17 @@ impl Game<'_> {
|
||||
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
|
||||
return;
|
||||
};
|
||||
let held_shift =
|
||||
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
|
||||
if self.crafter_click(slot, held_shift) {
|
||||
return;
|
||||
}
|
||||
if held_shift && self.container.is_some() && self.container_quick_move(slot) {
|
||||
if let Some(key) = self.container {
|
||||
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(c) = &self.carried
|
||||
&& self.refuses(slot, c)
|
||||
{
|
||||
@@ -3464,6 +3571,12 @@ impl Game<'_> {
|
||||
let mut crafted = 0;
|
||||
while let Some(result) = self.craft_result() {
|
||||
let made = (result.item.clone(), result.count);
|
||||
let cells = self.craft_size * self.craft_size;
|
||||
let remainders = self.res.recipes.remainders(
|
||||
&self.res.items,
|
||||
&self.craft_grid[..cells],
|
||||
&result,
|
||||
);
|
||||
if shift {
|
||||
if self.give(result).is_some() {
|
||||
break;
|
||||
@@ -3488,6 +3601,14 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, rest) in remainders.into_iter().enumerate() {
|
||||
let Some(rest) = rest else { continue };
|
||||
match &mut self.craft_grid[i] {
|
||||
cell @ None => *cell = Some(rest),
|
||||
Some(c) if c.same_item_same_components(&rest) => c.count += rest.count,
|
||||
_ => self.give_or_drop(rest),
|
||||
}
|
||||
}
|
||||
crafted += 1;
|
||||
self.stats.add("crafted", &made.0, made.1 as i32);
|
||||
if !shift || crafted >= 64 {
|
||||
@@ -3879,6 +4000,7 @@ impl Game<'_> {
|
||||
Some(BlockEntity::Sign(sign)) => Some(sign),
|
||||
_ => None,
|
||||
},
|
||||
banner: &|p| self.banner_layers_at(p),
|
||||
glyph: &|c| self.res.atlas.glyph(c),
|
||||
};
|
||||
self.res
|
||||
@@ -4319,8 +4441,11 @@ impl Game<'_> {
|
||||
}
|
||||
fn tick_block_entities(&mut self) -> Result<()> {
|
||||
self.tick_hoppers()?;
|
||||
self.tick_crafters();
|
||||
self.tick_mount_menu();
|
||||
self.tick_jukeboxes();
|
||||
self.tick_beacons();
|
||||
self.tick_creaking_hearts()?;
|
||||
// ChestLidController: 0.1 per tick towards open/closed.
|
||||
if let Some(key) = self.container {
|
||||
self.chest_open.entry(key).or_insert((0.0, 0.0));
|
||||
@@ -4376,6 +4501,11 @@ impl Game<'_> {
|
||||
self.tick_creatures()?;
|
||||
self.position_rider();
|
||||
self.tick_stats();
|
||||
self.tick_scoreboard();
|
||||
self.load_bossbars();
|
||||
self.tick_functions();
|
||||
self.tick_worldborder();
|
||||
self.tick_subtitles();
|
||||
self.spawn_phantoms();
|
||||
self.tick_advancements();
|
||||
self.tick_player_model();
|
||||
@@ -4574,6 +4704,11 @@ impl Game<'_> {
|
||||
let save_root = std::env::current_dir()?.join("saves").join(folder);
|
||||
horizon_client::save::migrate_legacy(&save_root)?;
|
||||
self.persist = Default::default();
|
||||
self.score = Default::default();
|
||||
self.fns = Default::default();
|
||||
self.bosses = Default::default();
|
||||
self.rand_sequences = Default::default();
|
||||
self.border = Default::default();
|
||||
let level = Level::read(&save_root).unwrap_or_else(|| Level {
|
||||
name: name.unwrap_or(folder).to_owned(),
|
||||
// WorldOptions.randomSeed when no seed was given.
|
||||
@@ -5696,6 +5831,7 @@ impl Game<'_> {
|
||||
on_ground,
|
||||
);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
self.player_projectile_shot();
|
||||
let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5;
|
||||
self.audio
|
||||
.play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch);
|
||||
@@ -5772,6 +5908,10 @@ impl Game<'_> {
|
||||
}
|
||||
first(&d["model"])
|
||||
});
|
||||
if item.ends_with("_banner") {
|
||||
// The banner item model is a special renderer over this base model.
|
||||
current = Some("minecraft:item/template_banner".to_owned());
|
||||
}
|
||||
for _ in 0..16 {
|
||||
let Some(m) = current.take() else { break };
|
||||
let path = m.trim_start_matches("minecraft:").to_owned();
|
||||
@@ -5918,6 +6058,9 @@ impl Game<'_> {
|
||||
* glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2])))
|
||||
* glam::Mat4::from_scale(glam::Vec3::from(scale))
|
||||
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
|
||||
if self.held_banner_geometry(m, &stack, packed, &mut out) {
|
||||
return out;
|
||||
}
|
||||
let atlas = &self.res.atlas;
|
||||
let quad = |corners: [glam::Vec3; 4],
|
||||
name: &str,
|
||||
@@ -6495,23 +6638,8 @@ impl Game<'_> {
|
||||
self.carried = None;
|
||||
}
|
||||
}
|
||||
fn save_game(&mut self) -> Result<()> {
|
||||
if self.remote.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks: Vec<_> = keys
|
||||
.iter()
|
||||
.filter_map(|k| self.world.chunks.get(k))
|
||||
.map(|c| self.with_entities(c))
|
||||
.collect();
|
||||
self.save
|
||||
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
|
||||
self.save_entities()?;
|
||||
self.save_maps();
|
||||
self.save_fight();
|
||||
self.save_stats();
|
||||
self.save_advancements();
|
||||
/// Copy the live player and world state into the `Level` that gets saved.
|
||||
pub(super) fn sync_level(&mut self) {
|
||||
self.level.selected_slot = self.selected as i32;
|
||||
let mode = self.mode_id();
|
||||
let level = &mut self.level;
|
||||
@@ -6573,6 +6701,7 @@ impl Game<'_> {
|
||||
self.ender_items = items.clone();
|
||||
}
|
||||
level.ender_items = self.ender_items.clone();
|
||||
level.recipe_book.recipes = self.adv.recipes.iter().cloned().collect();
|
||||
level.active_effects = self
|
||||
.potions
|
||||
.effects
|
||||
@@ -6588,7 +6717,31 @@ impl Game<'_> {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
level.write(&self.world_root)?;
|
||||
}
|
||||
fn save_game(&mut self) -> Result<()> {
|
||||
if self.remote.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks: Vec<_> = keys
|
||||
.iter()
|
||||
.filter_map(|k| self.world.chunks.get(k))
|
||||
.map(|c| self.with_entities(c))
|
||||
.collect();
|
||||
self.save
|
||||
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
|
||||
self.save_entities()?;
|
||||
self.save_maps();
|
||||
self.save_raids();
|
||||
self.save_fight();
|
||||
self.save_stats();
|
||||
self.save_advancements();
|
||||
self.save_scoreboard();
|
||||
self.save_bossbars();
|
||||
self.save_schedule();
|
||||
self.save_warden_tracker();
|
||||
self.sync_level();
|
||||
self.level.write(&self.world_root)?;
|
||||
self.save_world_state();
|
||||
self.message = Some(("Saved the game".into(), Instant::now()));
|
||||
Ok(())
|
||||
@@ -6698,7 +6851,11 @@ impl Game<'_> {
|
||||
}
|
||||
let celestial = if title {
|
||||
self.panorama_geometry()
|
||||
} else if self.dim == Dim::Overworld {
|
||||
} else if self.dim == Dim::Overworld
|
||||
&& self.potions.effects.get("darkness").is_none()
|
||||
&& self.potions.effects.get("blindness").is_none()
|
||||
{
|
||||
// Camera.doesMobEffectBlockSky: no sun, moon or stars.
|
||||
self.celestial_geometry(&sky)
|
||||
} else if self.dim == Dim::End {
|
||||
self.end_sky_geometry()
|
||||
@@ -6777,6 +6934,7 @@ impl Game<'_> {
|
||||
screen: &screen,
|
||||
game_time: self.world.game_time as f32,
|
||||
ticks: self.ticks,
|
||||
darkness: self.darkness_lighting(alpha as f32),
|
||||
};
|
||||
self.renderer.as_mut().ok_or("renderer")?.render(&frame)
|
||||
}
|
||||
@@ -6808,6 +6966,7 @@ impl Game<'_> {
|
||||
Screen::WorldOptions => self.close_world_options(),
|
||||
Screen::Chat => self.close_chat(),
|
||||
},
|
||||
KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(),
|
||||
KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""),
|
||||
// key.advancements.
|
||||
KeyCode::KeyL if self.screen == Screen::Playing => self.open_advancements(false),
|
||||
@@ -6822,12 +6981,15 @@ impl Game<'_> {
|
||||
KeyCode::KeyE => match self.screen {
|
||||
Screen::Playing if self.spectator() => {}
|
||||
Screen::Playing => {
|
||||
self.screen = if self.creative {
|
||||
Screen::Creative
|
||||
} else {
|
||||
Screen::Inventory
|
||||
};
|
||||
self.capture(false);
|
||||
// key.inventory while riding a tamed mount opens its inventory.
|
||||
if !self.open_ridden_mount_menu() {
|
||||
self.screen = if self.creative {
|
||||
Screen::Creative
|
||||
} else {
|
||||
Screen::Inventory
|
||||
};
|
||||
self.capture(false);
|
||||
}
|
||||
}
|
||||
Screen::Creative => {
|
||||
if let Some(c) = self.carried.take() {
|
||||
@@ -7046,6 +7208,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
if self.screen == Screen::Advancements {
|
||||
self.advancements_drag();
|
||||
}
|
||||
if self.screen == Screen::Inventory {
|
||||
self.loom_drag();
|
||||
}
|
||||
if self.dragging && self.screen == Screen::Options {
|
||||
let _ = b;
|
||||
self.options_drag()?;
|
||||
@@ -7177,6 +7342,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.container_changed(key);
|
||||
}
|
||||
}
|
||||
Screen::Inventory => self.loom_release(),
|
||||
Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(),
|
||||
Screen::Creative if pressed => {
|
||||
self.click_creative(button == MouseButton::Right);
|
||||
@@ -7241,6 +7407,14 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
self.creative_screen.scroll = 0.0;
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.recipe_search_focused()
|
||||
&& event.state == ElementState::Pressed
|
||||
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
|
||||
{
|
||||
// The recipe book's search box takes every key but Escape.
|
||||
self.recipe_key(&event);
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.station_typing()
|
||||
&& event.state == ElementState::Pressed
|
||||
@@ -7323,12 +7497,14 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
let steps = self.clock.advance(elapsed);
|
||||
for _ in 0..steps {
|
||||
let started = Instant::now();
|
||||
if self.title.is_none() {
|
||||
self.tick()?;
|
||||
self.tick_ambience();
|
||||
self.tick_fov();
|
||||
}
|
||||
self.tick_music();
|
||||
self.clock.record(started.elapsed());
|
||||
}
|
||||
let rendered = self.render()?;
|
||||
let finished = self
|
||||
@@ -7616,6 +7792,8 @@ pub fn run() -> Result<()> {
|
||||
mobs: Vec::new(),
|
||||
arrows: Vec::new(),
|
||||
creatures: Default::default(),
|
||||
sculk: Default::default(),
|
||||
raiding: Default::default(),
|
||||
attack_ticks: 100,
|
||||
last_hurt_by_player: HashSet::new(),
|
||||
chest_open: HashMap::new(),
|
||||
@@ -7684,9 +7862,13 @@ pub fn run() -> Result<()> {
|
||||
ender_items: vec![None; 27],
|
||||
ender_open: None,
|
||||
pending_shulker: HashMap::new(),
|
||||
pending_banner: HashMap::new(),
|
||||
recipe_ui: Default::default(),
|
||||
mount_menu: Default::default(),
|
||||
hook: None,
|
||||
tridents: Vec::new(),
|
||||
rockets: Vec::new(),
|
||||
creaking: Default::default(),
|
||||
trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"),
|
||||
tnts: Vec::new(),
|
||||
hoppers: HashMap::new(),
|
||||
@@ -7704,6 +7886,13 @@ pub fn run() -> Result<()> {
|
||||
combat: Default::default(),
|
||||
mount: Default::default(),
|
||||
stats: Default::default(),
|
||||
score: Default::default(),
|
||||
fns: Default::default(),
|
||||
bosses: Default::default(),
|
||||
exec: Default::default(),
|
||||
rand_sequences: Default::default(),
|
||||
border: Default::default(),
|
||||
subtitles: Default::default(),
|
||||
adv: Default::default(),
|
||||
stats_ui: Default::default(),
|
||||
adv_ui: Default::default(),
|
||||
|
||||
@@ -20,6 +20,26 @@ pub(super) struct Toast {
|
||||
frame: Frame,
|
||||
title: Text,
|
||||
shown: Option<Instant>,
|
||||
/// A `RecipeToast`: the icon is a recipe result.
|
||||
recipe: bool,
|
||||
}
|
||||
impl Toast {
|
||||
pub(super) fn is_recipe(&self) -> bool {
|
||||
self.recipe
|
||||
}
|
||||
pub(super) fn was_shown(&self) -> bool {
|
||||
self.shown.is_some()
|
||||
}
|
||||
/// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result.
|
||||
pub(super) fn recipe(icon: &str) -> Self {
|
||||
Self {
|
||||
icon: icon.to_owned(),
|
||||
frame: Frame::Task,
|
||||
title: Text::literal(""),
|
||||
shown: None,
|
||||
recipe: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct AdvState {
|
||||
@@ -27,7 +47,7 @@ pub(super) struct AdvState {
|
||||
pub(super) progress: Progress,
|
||||
loaded: bool,
|
||||
pub(super) recipes: BTreeSet<String>,
|
||||
toasts: VecDeque<Toast>,
|
||||
pub(super) toasts: VecDeque<Toast>,
|
||||
/// Awards skip the toast (`/advancement grant ... everything`).
|
||||
pub(super) quiet: bool,
|
||||
/// The inventory last seen by `inventory_changed`.
|
||||
@@ -223,6 +243,42 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// The player as predicates see it.
|
||||
/// The predicate view of a command target.
|
||||
pub(super) fn entity_view_of(&self, t: super::commands::Target) -> EntityView {
|
||||
use super::commands::Target;
|
||||
match t {
|
||||
Target::Player => self.player_entity(),
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map(|m| self.mob_entity(m))
|
||||
.unwrap_or_default(),
|
||||
other => EntityView {
|
||||
kind: self.target_type(other),
|
||||
position: self.target_position(other).unwrap_or_default(),
|
||||
..EntityView::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
/// A `ContextAwarePredicate` for `this` at `origin`.
|
||||
pub(super) fn conditions_hold(
|
||||
&self,
|
||||
v: &Value,
|
||||
this: Option<&EntityView>,
|
||||
origin: [f64; 3],
|
||||
) -> bool {
|
||||
adv::conditions(
|
||||
v,
|
||||
&adv::Entities {
|
||||
this,
|
||||
origin,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
},
|
||||
&View(self),
|
||||
)
|
||||
}
|
||||
pub(super) fn player_entity(&self) -> EntityView {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return EntityView::default();
|
||||
@@ -261,12 +317,26 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
pub(super) fn mob_entity(&self, m: &horizon_client::mobs::Mob) -> EntityView {
|
||||
// mainhand, offhand, head, chest, legs, feet.
|
||||
let slot = |i: &Option<std::sync::Arc<str>>| {
|
||||
i.as_ref().map(|id| item_view(&ItemStack::new(id, 1)))
|
||||
};
|
||||
let mut equipment: [Option<ItemView>; 7] = Default::default();
|
||||
if !horizon_client::mobs::equine::is_equine(m.species()) {
|
||||
equipment[0] = slot(&m.extra.main_hand);
|
||||
equipment[1] = slot(&m.extra.off_hand);
|
||||
equipment[2] = slot(&m.extra.head);
|
||||
equipment[3] = slot(&m.extra.chest);
|
||||
equipment[4] = slot(&m.extra.legs);
|
||||
equipment[5] = slot(&m.extra.feet);
|
||||
}
|
||||
EntityView {
|
||||
kind: m.kind.id.clone(),
|
||||
position: [m.position.x, m.position.y, m.position.z],
|
||||
on_fire: m.fire_ticks > 0,
|
||||
baby: m.is_baby(),
|
||||
on_ground: m.on_ground,
|
||||
equipment,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -339,6 +409,7 @@ impl Game<'_> {
|
||||
frame: d.frame,
|
||||
title: text_of(&d.title),
|
||||
shown: None,
|
||||
recipe: false,
|
||||
});
|
||||
}
|
||||
if d.announce && self.ui.rules.bool("show_advancement_messages") {
|
||||
@@ -354,6 +425,7 @@ impl Game<'_> {
|
||||
));
|
||||
}
|
||||
}
|
||||
self.recipe_toast(&unlocked);
|
||||
for r in unlocked {
|
||||
self.trigger("minecraft:recipe_unlocked", |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
@@ -576,7 +648,20 @@ impl Game<'_> {
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone());
|
||||
let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe);
|
||||
if recipe {
|
||||
// RecipeToast: black description under a purple title.
|
||||
let atlas = &self.res.atlas;
|
||||
let x = batch.width - 160.0 * slide;
|
||||
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
|
||||
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
|
||||
let description = self.translate("recipe.toast.description", "Check your recipe book");
|
||||
let atlas = &self.res.atlas;
|
||||
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
|
||||
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
|
||||
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0);
|
||||
return;
|
||||
}
|
||||
if frame == Frame::Challenge && ms < 50.0 {
|
||||
self.audio
|
||||
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Placed banners (`BannerBlockEntity`): the pattern layers move from the
|
||||
//! banner item to the block when placed and back to the dropped item when
|
||||
//! broken (`copy_components` in the banner loot tables).
|
||||
use super::Game;
|
||||
use glam::{EulerRot, Mat4, Quat, Vec3};
|
||||
use horizon_client::{
|
||||
banner::{self, BannerLayer},
|
||||
block_entity_render::{Paint, draw_part},
|
||||
containers::{Banner, BlockEntity},
|
||||
hud::{HudBatch, rgba},
|
||||
items::ItemStack,
|
||||
mesher::Vertex,
|
||||
};
|
||||
|
||||
impl Game<'_> {
|
||||
/// The pattern textures and tints of the banner at `pos`, bottom first.
|
||||
pub(super) fn banner_layers_at(&self, pos: [i32; 3]) -> Vec<(String, u32)> {
|
||||
let Some(BlockEntity::Banner(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
layer_textures(&self.res.stations.banners, &b.layers)
|
||||
}
|
||||
/// A placed banner takes the item's layers and name.
|
||||
pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) {
|
||||
self.pending_banner.remove(&pos);
|
||||
if !stack.item.ends_with("_banner") {
|
||||
return;
|
||||
}
|
||||
if let Some(BlockEntity::Banner(b)) =
|
||||
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
|
||||
{
|
||||
b.layers = banner::layers(stack).to_vec();
|
||||
b.name = stack.custom_name().map(str::to_owned);
|
||||
}
|
||||
}
|
||||
/// A banner in a slot: `item/template_banner`'s `gui` transform on the
|
||||
/// banner model (pole, bar and flag with every layer), flat-lit and
|
||||
/// depth-sorted. False when the stack is not a banner.
|
||||
pub(super) fn draw_banner_icon(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
stack: &ItemStack,
|
||||
x: f32,
|
||||
y: f32,
|
||||
) -> bool {
|
||||
let Some(base) = banner::banner_color(&stack.item) else {
|
||||
return false;
|
||||
};
|
||||
let Some((main, flag)) = self.res.block_entity_render.banner_models() else {
|
||||
return true;
|
||||
};
|
||||
let banners = &self.res.stations.banners;
|
||||
let sprites = &self.res.atlas.sprites;
|
||||
// display.gui, then the item's special transformation (a banner is
|
||||
// modelled upside down and 2/3 size around the block centre).
|
||||
let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0))
|
||||
* Mat4::from_quat(Quat::from_euler(
|
||||
EulerRot::XYZ,
|
||||
30f32.to_radians(),
|
||||
20f32.to_radians(),
|
||||
0.0,
|
||||
))
|
||||
* Mat4::from_scale(Vec3::splat(0.5325))
|
||||
* Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0))
|
||||
* Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0));
|
||||
let wave = |name: &str, p: &mut [f32; 9]| {
|
||||
if name == "flag" {
|
||||
p[3] = (-0.0125 + 0.01) * std::f32::consts::PI;
|
||||
}
|
||||
};
|
||||
let none = |_: &str, _: &mut [f32; 9]| {};
|
||||
let mut passes: Vec<(&str, u32, bool, String)> = vec![
|
||||
("entity/banner/banner_base", 0xFFFFFF, true, String::new()),
|
||||
(
|
||||
"entity/banner/base",
|
||||
banner::dye_rgb(base),
|
||||
false,
|
||||
String::new(),
|
||||
),
|
||||
];
|
||||
for layer in banner::layers(stack).iter().take(16) {
|
||||
passes.push((
|
||||
"",
|
||||
banner::dye_rgb(&layer.color),
|
||||
false,
|
||||
banners.banner_texture(&layer.pattern),
|
||||
));
|
||||
}
|
||||
// (depth, pass, screen corners, uv, colour)
|
||||
let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
|
||||
for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() {
|
||||
let name = if fixed.is_empty() {
|
||||
dynamic.as_str()
|
||||
} else {
|
||||
fixed
|
||||
};
|
||||
let Some(sprite) = sprites.get(name).copied() else {
|
||||
continue;
|
||||
};
|
||||
let paint = Paint {
|
||||
sprite,
|
||||
tint: 0xFFFFFF,
|
||||
light: 0,
|
||||
lights: (Vec3::ZERO, Vec3::ZERO),
|
||||
};
|
||||
let mut verts: Vec<Vertex> = Vec::new();
|
||||
if *with_pole {
|
||||
draw_part(main, "root", m, &none, paint, &mut verts);
|
||||
}
|
||||
draw_part(flag, "root", m, &wave, paint, &mut verts);
|
||||
for quad in verts.as_chunks::<4>().0 {
|
||||
let p = |i: usize| Vec3::from(quad[i].pos);
|
||||
let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero();
|
||||
// Faces turned away from the viewer are culled.
|
||||
if normal.z <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let depth = (0..4).map(|i| p(i).z).sum::<f32>() / 4.0;
|
||||
let shade = (0.6 + 0.4 * normal.z).min(1.0);
|
||||
let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8;
|
||||
faces.push((
|
||||
depth,
|
||||
index,
|
||||
std::array::from_fn(|i| {
|
||||
[
|
||||
x + 8.0 + quad[i].pos[0] * 16.0,
|
||||
y + 8.0 - quad[i].pos[1] * 16.0,
|
||||
]
|
||||
}),
|
||||
std::array::from_fn(|i| quad[i].uv),
|
||||
rgba(c(16), c(8), c(0), 255),
|
||||
));
|
||||
}
|
||||
}
|
||||
faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
|
||||
for (_, _, corners, uv, color) in faces {
|
||||
batch.quad(corners, uv, color);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// A banner in the first-person hand: the standing banner model under the
|
||||
/// item's `firstperson_righthand` transform (`m`) and its special
|
||||
/// transformation. False when the stack is not a banner.
|
||||
pub(super) fn held_banner_geometry(
|
||||
&self,
|
||||
m: Mat4,
|
||||
stack: &ItemStack,
|
||||
packed: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) -> bool {
|
||||
let Some(base) = banner::banner_color(&stack.item) else {
|
||||
return false;
|
||||
};
|
||||
let Some((main, flag)) = self.res.block_entity_render.banner_models() else {
|
||||
return true;
|
||||
};
|
||||
let m = m
|
||||
* Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5))
|
||||
* Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0));
|
||||
let wave = |name: &str, p: &mut [f32; 9]| {
|
||||
if name == "flag" {
|
||||
p[3] = (-0.0125 + 0.01) * std::f32::consts::PI;
|
||||
}
|
||||
};
|
||||
let none = |_: &str, _: &mut [f32; 9]| {};
|
||||
let lights = horizon_client::block_entity_render::diffuse_lights(false);
|
||||
let sprites = &self.res.atlas.sprites;
|
||||
let paint = |name: &str, tint: u32| {
|
||||
sprites.get(name).map(|&sprite| Paint {
|
||||
sprite,
|
||||
tint,
|
||||
light: packed,
|
||||
lights,
|
||||
})
|
||||
};
|
||||
if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) {
|
||||
draw_part(main, "root", m, &none, p, out);
|
||||
draw_part(flag, "root", m, &wave, p, out);
|
||||
}
|
||||
if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) {
|
||||
draw_part(flag, "root", m, &wave, p, out);
|
||||
}
|
||||
for layer in banner::layers(stack).iter().take(16) {
|
||||
let texture = self.res.stations.banners.banner_texture(&layer.pattern);
|
||||
if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) {
|
||||
draw_part(flag, "root", m, &wave, p, out);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The layers a banner dropped at `pos` carries.
|
||||
pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if !stack.item.ends_with("_banner") {
|
||||
return;
|
||||
}
|
||||
if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) {
|
||||
let data = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
if name.is_some() {
|
||||
data.custom_name = name;
|
||||
}
|
||||
stack.tidy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture names and tints of banner layers (`Sheets.getBannerSprite`).
|
||||
pub(super) fn layer_textures(
|
||||
banners: &banner::Banners,
|
||||
layers: &[BannerLayer],
|
||||
) -> Vec<(String, u32)> {
|
||||
layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
(
|
||||
banners.banner_texture(&l.pattern),
|
||||
banner::dye_rgb(&l.color),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
//! `/bossbar` (BossBarCommands) and drawing the custom boss bars.
|
||||
use super::{
|
||||
Game,
|
||||
commands::{R, err},
|
||||
};
|
||||
use horizon_client::{
|
||||
bossbar::BossBars,
|
||||
command::{Arg, Context},
|
||||
hud::{HudBatch, rgba},
|
||||
save,
|
||||
scoreboard::{self as sb, Comp, comp_text},
|
||||
scoreboard_cmd::format_list,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BossState {
|
||||
pub bars: BossBars,
|
||||
loaded: bool,
|
||||
}
|
||||
|
||||
fn num(n: impl std::fmt::Display) -> Text {
|
||||
Text::literal(n.to_string())
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn bossbar_path(&self) -> std::path::PathBuf {
|
||||
self.world_root
|
||||
.join("data/minecraft/custom_boss_events.dat")
|
||||
}
|
||||
pub(super) fn load_bossbars(&mut self) {
|
||||
if self.bosses.loaded || self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
self.bosses.loaded = true;
|
||||
if let Some(root) = save::read_dat(&self.bossbar_path())
|
||||
&& let Some(data) = root.get("data")
|
||||
{
|
||||
self.bosses.bars = BossBars::unpack(data, self.level.player_uuid);
|
||||
}
|
||||
self.ui.registries.bossbars = self.bosses.bars.ids();
|
||||
}
|
||||
pub(super) fn save_bossbars(&self) {
|
||||
if !self.bosses.loaded || self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
if self.bosses.bars.bars.is_empty() && !self.bossbar_path().exists() {
|
||||
return;
|
||||
}
|
||||
let _ = save::write_dat(
|
||||
&self.bossbar_path(),
|
||||
Tag::compound([
|
||||
("data", self.bosses.bars.pack(self.level.player_uuid)),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
pub(in crate::game) fn bossbar_exists(&self, id: &str) -> bool {
|
||||
self.bosses.bars.get(id).is_some()
|
||||
}
|
||||
/// `execute store ... bossbar <id> value|max`.
|
||||
pub(in crate::game) fn set_bossbar_value(&mut self, id: &str, value: bool, v: i32) {
|
||||
if let Some(b) = self.bosses.bars.get_mut(id) {
|
||||
if value {
|
||||
b.value = v.clamp(0, b.max);
|
||||
} else {
|
||||
b.max = v.max(1);
|
||||
b.value = b.value.min(b.max);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bar_id(ctx: &Context) -> String {
|
||||
match ctx.get("id") {
|
||||
Some(Arg::Resource(id)) => id.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
fn bar_checked(&self, ctx: &Context) -> R<String> {
|
||||
let id = Self::bar_id(ctx);
|
||||
if self.bosses.bars.get(&id).is_none() {
|
||||
return Err(err("commands.bossbar.unknown", &[&id]));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
pub(super) fn cmd_bossbar(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
self.load_bossbars();
|
||||
let result = self.bossbar_command(id, ctx);
|
||||
self.ui.registries.bossbars = self.bosses.bars.ids();
|
||||
result
|
||||
}
|
||||
fn bossbar_command(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
match id {
|
||||
"bossbar.add" => {
|
||||
let bar = Self::bar_id(ctx);
|
||||
if self.bosses.bars.get(&bar).is_some() {
|
||||
return Err(err("commands.bossbar.create.failed", &[&bar]));
|
||||
}
|
||||
let name = self.component_json(ctx, "name")?;
|
||||
self.bosses.bars.add(&bar, name);
|
||||
let shown = self
|
||||
.bosses
|
||||
.bars
|
||||
.get(&bar)
|
||||
.map(|b| b.display_name())
|
||||
.unwrap_or_default();
|
||||
self.feedback(Text::translate("commands.bossbar.create.success", &[shown]));
|
||||
return Ok(self.bosses.bars.bars.len() as i32);
|
||||
}
|
||||
"bossbar.list" => {
|
||||
let names: Vec<Text> = self
|
||||
.bosses
|
||||
.bars
|
||||
.bars
|
||||
.iter()
|
||||
.map(horizon_client::bossbar::BossBar::display_name)
|
||||
.collect();
|
||||
let n = names.len();
|
||||
if n == 0 {
|
||||
self.feedback(Text::translate("commands.bossbar.list.bars.none", &[]));
|
||||
} else {
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.list.bars.some",
|
||||
&[num(n), format_list(names)],
|
||||
));
|
||||
}
|
||||
return Ok(n as i32);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let bar = self.bar_checked(ctx)?;
|
||||
let shown = |g: &Self| {
|
||||
g.bosses
|
||||
.bars
|
||||
.get(&bar)
|
||||
.map(|b| b.display_name())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let last = ctx.literals.last().cloned().unwrap_or_default();
|
||||
match id {
|
||||
"bossbar.remove" => {
|
||||
let s = shown(self);
|
||||
self.bosses.bars.remove(&bar);
|
||||
self.feedback(Text::translate("commands.bossbar.remove.success", &[s]));
|
||||
Ok(self.bosses.bars.bars.len() as i32)
|
||||
}
|
||||
"bossbar.get" => {
|
||||
let b = self.bosses.bars.get(&bar).cloned().unwrap_or_else(|| {
|
||||
horizon_client::bossbar::BossBar::new(&bar, sb::literal(&bar))
|
||||
});
|
||||
let s = b.display_name();
|
||||
Ok(match last.as_str() {
|
||||
"value" => {
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.get.value",
|
||||
&[s, num(b.value)],
|
||||
));
|
||||
b.value
|
||||
}
|
||||
"max" => {
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.get.max",
|
||||
&[s, num(b.max)],
|
||||
));
|
||||
b.max
|
||||
}
|
||||
"visible" => {
|
||||
let key = if b.visible {
|
||||
"commands.bossbar.get.visible.visible"
|
||||
} else {
|
||||
"commands.bossbar.get.visible.hidden"
|
||||
};
|
||||
self.feedback(Text::translate(key, &[s]));
|
||||
i32::from(b.visible)
|
||||
}
|
||||
_ => {
|
||||
if b.player {
|
||||
let name = self.target_name(super::commands::Target::Player);
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.get.players.some",
|
||||
&[s, num(1), format_list(vec![name])],
|
||||
));
|
||||
} else {
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.get.players.none",
|
||||
&[s],
|
||||
));
|
||||
}
|
||||
i32::from(b.player)
|
||||
}
|
||||
})
|
||||
}
|
||||
_ => self.bossbar_set(id, ctx, &bar, &last),
|
||||
}
|
||||
}
|
||||
fn bossbar_set(&mut self, id: &str, ctx: &Context, bar: &str, last: &str) -> R<i32> {
|
||||
let shown = |g: &Self| {
|
||||
g.bosses
|
||||
.bars
|
||||
.get(bar)
|
||||
.map(|b| b.display_name())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let int = |name: &str| match ctx.get(name) {
|
||||
Some(Arg::Int(v)) => *v,
|
||||
_ => 0,
|
||||
};
|
||||
match id {
|
||||
"bossbar.set.name" => {
|
||||
let name = self.component_json(ctx, "name")?;
|
||||
let b = self.bosses.bars.get_mut(bar).expect("checked");
|
||||
if b.name == name {
|
||||
return Err(err("commands.bossbar.set.name.unchanged", &[]));
|
||||
}
|
||||
b.name = name;
|
||||
let s = shown(self);
|
||||
self.feedback(Text::translate("commands.bossbar.set.name.success", &[s]));
|
||||
Ok(0)
|
||||
}
|
||||
"bossbar.set.color" | "bossbar.set.style" => {
|
||||
let color = id.ends_with("color");
|
||||
let b = self.bosses.bars.get_mut(bar).expect("checked");
|
||||
let slot = if color { &mut b.color } else { &mut b.style };
|
||||
if slot == last {
|
||||
return Err(err(
|
||||
if color {
|
||||
"commands.bossbar.set.color.unchanged"
|
||||
} else {
|
||||
"commands.bossbar.set.style.unchanged"
|
||||
},
|
||||
&[],
|
||||
));
|
||||
}
|
||||
*slot = last.to_owned();
|
||||
let s = shown(self);
|
||||
self.feedback(Text::translate(
|
||||
if color {
|
||||
"commands.bossbar.set.color.success"
|
||||
} else {
|
||||
"commands.bossbar.set.style.success"
|
||||
},
|
||||
&[s],
|
||||
));
|
||||
Ok(0)
|
||||
}
|
||||
"bossbar.set.value" | "bossbar.set.max" => {
|
||||
let is_value = id.ends_with("value");
|
||||
let v = int(if is_value { "value" } else { "max" });
|
||||
let b = self.bosses.bars.get_mut(bar).expect("checked");
|
||||
let slot = if is_value { &mut b.value } else { &mut b.max };
|
||||
if *slot == v {
|
||||
return Err(err(
|
||||
if is_value {
|
||||
"commands.bossbar.set.value.unchanged"
|
||||
} else {
|
||||
"commands.bossbar.set.max.unchanged"
|
||||
},
|
||||
&[],
|
||||
));
|
||||
}
|
||||
*slot = v;
|
||||
let s = shown(self);
|
||||
self.feedback(Text::translate(
|
||||
if is_value {
|
||||
"commands.bossbar.set.value.success"
|
||||
} else {
|
||||
"commands.bossbar.set.max.success"
|
||||
},
|
||||
&[s, num(v)],
|
||||
));
|
||||
Ok(v)
|
||||
}
|
||||
"bossbar.set.visible" => {
|
||||
let visible = matches!(ctx.get("visible"), Some(Arg::Bool(true)));
|
||||
let b = self.bosses.bars.get_mut(bar).expect("checked");
|
||||
if b.visible == visible {
|
||||
return Err(err(
|
||||
if visible {
|
||||
"commands.bossbar.set.visibility.unchanged.visible"
|
||||
} else {
|
||||
"commands.bossbar.set.visibility.unchanged.hidden"
|
||||
},
|
||||
&[],
|
||||
));
|
||||
}
|
||||
b.visible = visible;
|
||||
let s = shown(self);
|
||||
self.feedback(Text::translate(
|
||||
if visible {
|
||||
"commands.bossbar.set.visible.success.visible"
|
||||
} else {
|
||||
"commands.bossbar.set.visible.success.hidden"
|
||||
},
|
||||
&[s],
|
||||
));
|
||||
Ok(0)
|
||||
}
|
||||
_ => {
|
||||
// players [<targets>]
|
||||
let include = if ctx.get("targets").is_some() {
|
||||
!self.entities(ctx, "targets", true)?.is_empty()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let b = self.bosses.bars.get_mut(bar).expect("checked");
|
||||
if b.player == include {
|
||||
return Err(err("commands.bossbar.set.players.unchanged", &[]));
|
||||
}
|
||||
b.player = include;
|
||||
let s = shown(self);
|
||||
if include {
|
||||
let name = self.target_name(super::commands::Target::Player);
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.set.players.success.some",
|
||||
&[s, num(1), format_list(vec![name])],
|
||||
));
|
||||
} else {
|
||||
self.feedback(Text::translate(
|
||||
"commands.bossbar.set.players.success.none",
|
||||
&[s],
|
||||
));
|
||||
}
|
||||
Ok(i32::from(include))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A component argument as JSON with its selectors resolved.
|
||||
fn component_json(&mut self, ctx: &Context, name: &str) -> R<Comp> {
|
||||
let Some(Arg::Str(json)) = ctx.get(name) else {
|
||||
return Ok(sb::literal(""));
|
||||
};
|
||||
let value: Comp =
|
||||
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
|
||||
Ok(self.resolve_component(value))
|
||||
}
|
||||
|
||||
/// How many boss bars the dragon and withers already show.
|
||||
pub(super) fn builtin_bar_count(&self) -> usize {
|
||||
let dragon = usize::from(self.dragon.is_some() && self.dim == super::Dim::End);
|
||||
let withers = self.player.as_ref().map_or(0, |p| {
|
||||
self.mobs
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
m.species() == horizon_client::mobs::Species::Wither
|
||||
&& m.alive()
|
||||
&& m.position.distance_squared(p.position) <= 64.0 * 64.0
|
||||
})
|
||||
.count()
|
||||
});
|
||||
dragon + withers
|
||||
}
|
||||
// ---- drawing ------------------------------------------------------------------
|
||||
|
||||
/// `BossHealthOverlay`: the visible custom bars under the built-in ones.
|
||||
pub(super) fn draw_custom_bossbars(&self, batch: &mut HudBatch, mut y: f32) {
|
||||
let atlas = &self.res.atlas;
|
||||
for b in self
|
||||
.bosses
|
||||
.bars
|
||||
.bars
|
||||
.iter()
|
||||
.filter(|b| b.visible && b.player)
|
||||
{
|
||||
if y >= batch.height / 3.0 {
|
||||
break;
|
||||
}
|
||||
let x = (batch.width / 2.0 - 91.0).floor();
|
||||
let sprite = |kind: &str| format!("gui/sprites/boss_bar/{kind}");
|
||||
batch.sprite(atlas, &sprite(&format!("{}_background", b.color)), x, y);
|
||||
if b.progress() > 0.0 {
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
&sprite(&format!("{}_progress", b.color)),
|
||||
x,
|
||||
y,
|
||||
b.progress(),
|
||||
);
|
||||
}
|
||||
if b.style != "progress" {
|
||||
batch.sprite(atlas, &sprite(&format!("{}_background", b.style)), x, y);
|
||||
if b.progress() > 0.0 {
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
&sprite(&format!("{}_progress", b.style)),
|
||||
x,
|
||||
y,
|
||||
b.progress(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let name = comp_text(&b.name);
|
||||
let w = atlas.font.width_text(&name);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&name,
|
||||
(batch.width / 2.0 - w / 2.0).floor(),
|
||||
y - 9.0,
|
||||
rgba(255, 255, 255, 255),
|
||||
true,
|
||||
);
|
||||
y += 19.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,101 @@ impl Game<'_> {
|
||||
pub(super) fn build_registries(&mut self) {
|
||||
let reg = &mut self.ui.registries;
|
||||
reg.permission = 4;
|
||||
{
|
||||
let dir = |sub: &str| -> Vec<String> {
|
||||
let root = self.options.resources.join("data/minecraft").join(sub);
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![root.clone()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&d) else {
|
||||
continue;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else if p.extension().and_then(|x| x.to_str()) == Some("json")
|
||||
&& let Ok(rel) = p.strip_prefix(&root)
|
||||
{
|
||||
out.push(format!(
|
||||
"minecraft:{}",
|
||||
rel.with_extension("").to_string_lossy().replace('\\', "/")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
self.ui.registries.recipes = dir("recipe");
|
||||
self.ui.registries.damage_types = dir("damage_type");
|
||||
self.ui.registries.loot_tables = dir("loot_table");
|
||||
self.ui.registries.templates = {
|
||||
let root = self.options.resources.join("worldgen/structure/minecraft");
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![root.clone()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&d) else {
|
||||
continue;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else if p.extension().and_then(|x| x.to_str()) == Some("nbt")
|
||||
&& let Ok(rel) = p.strip_prefix(&root)
|
||||
{
|
||||
out.push(format!(
|
||||
"minecraft:{}",
|
||||
rel.with_extension("").to_string_lossy().replace('\\', "/")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
}
|
||||
self.ui.registries.sounds = self.audio.event_names();
|
||||
self.ui.registries.attributes = [
|
||||
"armor",
|
||||
"armor_toughness",
|
||||
"attack_damage",
|
||||
"attack_knockback",
|
||||
"attack_speed",
|
||||
"block_break_speed",
|
||||
"block_interaction_range",
|
||||
"burning_time",
|
||||
"camera_distance",
|
||||
"explosion_knockback_resistance",
|
||||
"entity_interaction_range",
|
||||
"fall_damage_multiplier",
|
||||
"flying_speed",
|
||||
"follow_range",
|
||||
"gravity",
|
||||
"jump_strength",
|
||||
"knockback_resistance",
|
||||
"luck",
|
||||
"max_absorption",
|
||||
"max_health",
|
||||
"mining_efficiency",
|
||||
"movement_efficiency",
|
||||
"movement_speed",
|
||||
"oxygen_bonus",
|
||||
"safe_fall_distance",
|
||||
"scale",
|
||||
"sneaking_speed",
|
||||
"spawn_reinforcements",
|
||||
"step_height",
|
||||
"submerged_mining_speed",
|
||||
"sweeping_damage_ratio",
|
||||
"tempt_range",
|
||||
"water_movement_efficiency",
|
||||
]
|
||||
.iter()
|
||||
.map(|a| format!("minecraft:{a}"))
|
||||
.collect();
|
||||
let reg = &mut self.ui.registries;
|
||||
let mut items: Vec<String> = self.res.items.order.iter().map(|s| s.to_string()).collect();
|
||||
items.sort();
|
||||
reg.items = items;
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
//! Command execution (the `execute` side of each vanilla command class):
|
||||
//! entity selectors resolved against the game, vanilla feedback and errors.
|
||||
mod data;
|
||||
mod effects;
|
||||
pub(super) mod execute;
|
||||
mod items;
|
||||
mod misc;
|
||||
mod place;
|
||||
mod raid;
|
||||
mod terrain_cmds;
|
||||
mod text_commands;
|
||||
mod world_cmds;
|
||||
|
||||
use super::{Dim, Game, Screen, chat::PLAYER_NAME};
|
||||
use horizon_client::{
|
||||
@@ -18,18 +25,23 @@ use horizon_client::{
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
|
||||
type R<T> = Result<T, CommandError>;
|
||||
pub(super) type R<T> = Result<T, CommandError>;
|
||||
|
||||
/// An entity a selector found.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(super) enum Target {
|
||||
Player,
|
||||
Mob(u32),
|
||||
Item(u32),
|
||||
Orb(usize),
|
||||
Arrow(usize),
|
||||
Stand(u32),
|
||||
Frame(u32),
|
||||
Painting(u32),
|
||||
Boat(u32),
|
||||
Cart(u32),
|
||||
}
|
||||
fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError {
|
||||
pub(super) fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError {
|
||||
CommandError::tr(key, args)
|
||||
}
|
||||
fn texts(args: &[Text]) -> Vec<Text> {
|
||||
@@ -58,19 +70,11 @@ impl Game<'_> {
|
||||
self.syntax_failure(&e, command);
|
||||
return;
|
||||
}
|
||||
Ok((ctx, id)) => {
|
||||
Ok((ctx, _)) => {
|
||||
let ctx = ctx.clone();
|
||||
if parse
|
||||
.context
|
||||
.literals
|
||||
.first()
|
||||
.is_some_and(|w| w == "execute")
|
||||
{
|
||||
let root = parse.context.clone();
|
||||
self.run_execute(&root)
|
||||
} else {
|
||||
self.execute_command(id, &ctx)
|
||||
}
|
||||
let root = parse.context.clone();
|
||||
self.exec = Default::default();
|
||||
self.run_chain(&root, &ctx)
|
||||
}
|
||||
};
|
||||
if let Err(e) = result {
|
||||
@@ -113,11 +117,17 @@ impl Game<'_> {
|
||||
self.command_failure(context.with_color(text::GRAY).with_style(&suggest));
|
||||
}
|
||||
/// CommandSourceStack.sendFailure: red text.
|
||||
fn command_failure(&mut self, message: Text) {
|
||||
pub(super) fn command_failure(&mut self, message: Text) {
|
||||
if self.command_source.is_some_and(|s| s.silent) {
|
||||
return;
|
||||
}
|
||||
self.system_message(message.with_color(text::RED));
|
||||
}
|
||||
/// sendSuccess honouring `send_command_feedback`.
|
||||
fn feedback(&mut self, message: Text) {
|
||||
pub(super) fn feedback(&mut self, message: Text) {
|
||||
if self.command_source.is_some_and(|s| s.silent) {
|
||||
return;
|
||||
}
|
||||
if self.ui.rules.bool("send_command_feedback") {
|
||||
self.system_message(message);
|
||||
}
|
||||
@@ -136,24 +146,24 @@ impl Game<'_> {
|
||||
.map_or([self.yaw, self.pitch], |s| s.rot)
|
||||
}
|
||||
/// LocalCoordinates use the anchored position; world coordinates the position.
|
||||
fn resolve_coords(&self, c: &Coordinates) -> [f64; 3] {
|
||||
pub(super) fn resolve_coords(&self, c: &Coordinates) -> [f64; 3] {
|
||||
let origin = match (c, &self.command_source) {
|
||||
(Coordinates::Local(_), Some(s)) => self.anchor_position(s),
|
||||
_ => self.source_position(),
|
||||
};
|
||||
c.position(origin, self.source_rotation())
|
||||
}
|
||||
fn coords(&self, ctx: &Context, name: &str) -> Option<Coordinates> {
|
||||
pub(super) fn coords(&self, ctx: &Context, name: &str) -> Option<Coordinates> {
|
||||
match ctx.get(name) {
|
||||
Some(Arg::Coords(c)) => Some(c.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn position_arg(&self, ctx: &Context, name: &str) -> Option<[f64; 3]> {
|
||||
pub(super) fn position_arg(&self, ctx: &Context, name: &str) -> Option<[f64; 3]> {
|
||||
self.coords(ctx, name).map(|c| self.resolve_coords(&c))
|
||||
}
|
||||
/// BlockPosArgument.getLoadedBlockPos.
|
||||
fn block_pos_arg(&self, ctx: &Context, name: &str) -> R<[i32; 3]> {
|
||||
pub(super) fn block_pos_arg(&self, ctx: &Context, name: &str) -> R<[i32; 3]> {
|
||||
let c = self
|
||||
.coords(ctx, name)
|
||||
.ok_or_else(|| err("argument.pos.missing.int", &[]))?;
|
||||
@@ -177,7 +187,7 @@ impl Game<'_> {
|
||||
}
|
||||
// ---- entities -------------------------------------------------------
|
||||
|
||||
fn target_position(&self, t: Target) -> Option<[f64; 3]> {
|
||||
pub(super) fn target_position(&self, t: Target) -> Option<[f64; 3]> {
|
||||
match t {
|
||||
Target::Player => self
|
||||
.player
|
||||
@@ -201,9 +211,40 @@ impl Game<'_> {
|
||||
.arrows
|
||||
.get(i)
|
||||
.map(|a| [a.position.x, a.position.y, a.position.z]),
|
||||
Target::Stand(id) => self
|
||||
.armor_stands
|
||||
.iter()
|
||||
.find(|a| a.id == id)
|
||||
.map(|a| [a.position.x, a.position.y, a.position.z]),
|
||||
Target::Frame(id) => self.item_frames.iter().find(|f| f.id == id).map(|f| {
|
||||
let (lo, hi) = f.bounds();
|
||||
[
|
||||
(lo[0] + hi[0]) / 2.0,
|
||||
(lo[1] + hi[1]) / 2.0,
|
||||
(lo[2] + hi[2]) / 2.0,
|
||||
]
|
||||
}),
|
||||
Target::Painting(id) => self.paintings.iter().find(|p| p.id == id).map(|p| {
|
||||
let (lo, hi) = p.bounds();
|
||||
[
|
||||
(lo[0] + hi[0]) / 2.0,
|
||||
(lo[1] + hi[1]) / 2.0,
|
||||
(lo[2] + hi[2]) / 2.0,
|
||||
]
|
||||
}),
|
||||
Target::Boat(id) => self
|
||||
.boats
|
||||
.iter()
|
||||
.find(|b| b.id == id)
|
||||
.map(|b| [b.position.x, b.position.y, b.position.z]),
|
||||
Target::Cart(id) => self
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map(|c| [c.position.x, c.position.y, c.position.z]),
|
||||
}
|
||||
}
|
||||
fn target_type(&self, t: Target) -> String {
|
||||
pub(super) fn target_type(&self, t: Target) -> String {
|
||||
match t {
|
||||
Target::Player => "minecraft:player".into(),
|
||||
Target::Mob(id) => self
|
||||
@@ -216,6 +257,27 @@ impl Game<'_> {
|
||||
Target::Item(_) => "minecraft:item".into(),
|
||||
Target::Orb(_) => "minecraft:experience_orb".into(),
|
||||
Target::Arrow(_) => "minecraft:arrow".into(),
|
||||
Target::Stand(_) => "minecraft:armor_stand".into(),
|
||||
Target::Frame(id) => {
|
||||
if self.item_frames.iter().any(|f| f.id == id && f.glow) {
|
||||
"minecraft:glow_item_frame".into()
|
||||
} else {
|
||||
"minecraft:item_frame".into()
|
||||
}
|
||||
}
|
||||
Target::Painting(_) => "minecraft:painting".into(),
|
||||
Target::Boat(id) => self.boats.iter().find(|b| b.id == id).map_or_else(
|
||||
|| "minecraft:oak_boat".into(),
|
||||
|b| {
|
||||
let kind = if &*b.wood == "bamboo" { "raft" } else { "boat" };
|
||||
format!("minecraft:{}_{kind}", b.wood)
|
||||
},
|
||||
),
|
||||
Target::Cart(id) => self
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map_or_else(|| "minecraft:minecart".into(), |c| c.kind.id().into()),
|
||||
}
|
||||
}
|
||||
/// Entity.getDisplayName.
|
||||
@@ -231,6 +293,19 @@ impl Game<'_> {
|
||||
.unwrap_or_default();
|
||||
Text::literal(self.res.names.item(&item))
|
||||
}
|
||||
Target::Mob(id)
|
||||
if self
|
||||
.mobs
|
||||
.iter()
|
||||
.any(|m| m.id == id && m.custom_name.is_some()) =>
|
||||
{
|
||||
let name = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.and_then(|m| m.custom_name.clone());
|
||||
Text::literal(name.unwrap_or_default())
|
||||
}
|
||||
other => {
|
||||
let ty = self.target_type(other);
|
||||
Text::translate(&format!("entity.{}", ty.replace(':', ".")), &[])
|
||||
@@ -238,7 +313,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// EntitySelector.findEntities.
|
||||
fn select(&mut self, s: &Selector) -> Vec<Target> {
|
||||
pub(super) fn select(&mut self, s: &Selector) -> Vec<Target> {
|
||||
if let Some(name) = &s.player_name {
|
||||
return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() {
|
||||
vec![Target::Player]
|
||||
@@ -271,9 +346,15 @@ impl Game<'_> {
|
||||
candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
|
||||
candidates.extend((0..self.orbs.len()).map(Target::Orb));
|
||||
candidates.extend((0..self.arrows.len()).map(Target::Arrow));
|
||||
candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
|
||||
candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
|
||||
candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
|
||||
candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id)));
|
||||
candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id)));
|
||||
}
|
||||
let level = self.experience.level;
|
||||
let creative = self.creative;
|
||||
let passing = self.selector_extra_filter(&candidates, s);
|
||||
let mut out: Vec<(Target, f64)> = candidates
|
||||
.into_iter()
|
||||
.filter_map(|t| {
|
||||
@@ -304,10 +385,8 @@ impl Game<'_> {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for (_, neg) in &s.tags {
|
||||
if !*neg {
|
||||
return None;
|
||||
}
|
||||
if !passing.contains(&t) {
|
||||
return None;
|
||||
}
|
||||
if let Some((lo, hi)) = s.level
|
||||
&& (t != Target::Player
|
||||
@@ -375,7 +454,7 @@ impl Game<'_> {
|
||||
})
|
||||
}
|
||||
/// EntityArgument.getEntities / getPlayers / getEntity / getPlayer.
|
||||
fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R<Vec<Target>> {
|
||||
pub(super) fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R<Vec<Target>> {
|
||||
let Some(Arg::Entity(s)) = ctx.get(name).cloned() else {
|
||||
return Ok(vec![Target::Player]);
|
||||
};
|
||||
@@ -424,6 +503,7 @@ impl Game<'_> {
|
||||
| "teleport.targets.location"
|
||||
| "teleport.targets.destination" => self.cmd_teleport(id, ctx),
|
||||
id if id.starts_with("time.") => self.cmd_time(id, ctx),
|
||||
id if id.starts_with("raid.") => self.cmd_raid(id, ctx),
|
||||
"weather" => self.cmd_weather(ctx),
|
||||
"kill" => self.cmd_kill(ctx),
|
||||
"summon" => self.cmd_summon(ctx),
|
||||
@@ -455,7 +535,45 @@ impl Game<'_> {
|
||||
"spawnpoint" => self.cmd_spawnpoint(ctx),
|
||||
"setworldspawn" => self.cmd_setworldspawn(ctx),
|
||||
"clear" => self.cmd_clear(ctx),
|
||||
"item" => self.cmd_item(ctx),
|
||||
"place" => self.cmd_place(ctx),
|
||||
"recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx),
|
||||
"damage" => self.cmd_damage(ctx),
|
||||
"rotate" => self.cmd_rotate(ctx),
|
||||
"swing" => self.cmd_swing(ctx),
|
||||
"playsound" => self.cmd_playsound(ctx),
|
||||
"stopsound" => self.cmd_stopsound(ctx),
|
||||
"particle" => self.cmd_particle(ctx),
|
||||
id if id.starts_with("attribute.") => self.cmd_attribute(id, ctx),
|
||||
"ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx),
|
||||
"spreadplayers" => self.cmd_spreadplayers(ctx),
|
||||
id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx),
|
||||
"fillbiome" => self.cmd_fillbiome(ctx),
|
||||
id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx),
|
||||
id if id.starts_with("loot.") => self.cmd_loot(id, ctx),
|
||||
"teammsg" => self.cmd_teammsg(ctx),
|
||||
id if id.starts_with("tick.") => self.cmd_tick(id, ctx),
|
||||
id if id.starts_with("random.") => self.cmd_random(id, ctx),
|
||||
"function" => self.cmd_function(ctx),
|
||||
"return.value" | "return.fail" => self.cmd_return(id, ctx),
|
||||
"schedule.function" | "schedule.clear" => self.cmd_schedule(id, ctx),
|
||||
"reload" => self.cmd_reload(),
|
||||
id if id.starts_with("datapack.") => self.cmd_datapack(id, ctx),
|
||||
id if id.starts_with("bossbar.") => self.cmd_bossbar(id, ctx),
|
||||
id if id.starts_with("data.") => self.cmd_data(id, ctx),
|
||||
id if id.starts_with("tag.") => self.cmd_tag(id, ctx),
|
||||
id if id.starts_with("scoreboard.")
|
||||
|| id.starts_with("team.")
|
||||
|| id.starts_with("trigger") =>
|
||||
{
|
||||
self.cmd_scoreboard(id, ctx)
|
||||
}
|
||||
"locate.structure" | "locate.biome" => self.cmd_locate(id, ctx),
|
||||
"warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => {
|
||||
let level = Self::int(ctx, "warning_level");
|
||||
self.cmd_warden_spawn_tracker(level);
|
||||
Ok(1)
|
||||
}
|
||||
"say" | "me" | "msg" => self.cmd_say(id, ctx),
|
||||
"list" => {
|
||||
let names = if ctx.has("uuids") {
|
||||
@@ -704,6 +822,34 @@ impl Game<'_> {
|
||||
a.previous = v;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => {
|
||||
if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) {
|
||||
a.position = v;
|
||||
if let Some([yaw, _]) = rotation {
|
||||
a.yaw = yaw;
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Boat(id) => {
|
||||
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
|
||||
b.position = v;
|
||||
b.previous = v;
|
||||
if let Some([yaw, _]) = rotation {
|
||||
b.yaw = yaw;
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Cart(id) => {
|
||||
if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) {
|
||||
c.position = v;
|
||||
c.previous = v;
|
||||
if let Some([yaw, _]) = rotation {
|
||||
c.yaw = yaw;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wall-mounted entities do not move.
|
||||
Target::Frame(_) | Target::Painting(_) => {}
|
||||
}
|
||||
}
|
||||
fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
@@ -1000,6 +1146,11 @@ impl Game<'_> {
|
||||
self.arrows[i].age = u32::MAX / 2;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => self.armor_stands.retain(|a| a.id != id),
|
||||
Target::Frame(id) => self.item_frames.retain(|f| f.id != id),
|
||||
Target::Painting(id) => self.paintings.retain(|p| p.id != id),
|
||||
Target::Boat(id) => self.boats.retain(|b| b.id != id),
|
||||
Target::Cart(id) => self.carts.retain(|c| c.id != id),
|
||||
}
|
||||
}
|
||||
fn cmd_kill(&mut self, ctx: &Context) -> R<i32> {
|
||||
@@ -1045,6 +1196,25 @@ impl Game<'_> {
|
||||
return Err(err("commands.summon.invalidPosition", &[]));
|
||||
}
|
||||
let short = kind.trim_start_matches("minecraft:").to_owned();
|
||||
if let Some(Arg::Str(nbt)) = ctx.get("nbt").cloned() {
|
||||
// With an NBT argument the entity is built from it, unfinalized.
|
||||
if self.ui.difficulty == 0
|
||||
&& self
|
||||
.res
|
||||
.mob_types
|
||||
.get(&format!("minecraft:{short}"))
|
||||
.is_some_and(|t| t.category == "monster")
|
||||
{
|
||||
return Err(err("commands.summon.failed.peaceful", &[]));
|
||||
}
|
||||
let Some(target) = self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)?
|
||||
else {
|
||||
return Err(err("commands.summon.failed", &[]));
|
||||
};
|
||||
let name = self.target_name(target);
|
||||
self.feedback(Text::translate("commands.summon.success", &[name]));
|
||||
return Ok(1);
|
||||
}
|
||||
let name;
|
||||
if let Some(t) = self
|
||||
.res
|
||||
@@ -1097,7 +1267,7 @@ impl Game<'_> {
|
||||
Ok(1)
|
||||
}
|
||||
/// BlockStateArgument -> registry state.
|
||||
fn block_state(&self, b: &BlockInput) -> R<BlockStateId> {
|
||||
pub(super) fn block_state(&self, b: &BlockInput) -> R<BlockStateId> {
|
||||
let state = horizon_world::chunk::BlockState {
|
||||
name: b.id.clone(),
|
||||
properties: b.properties.iter().cloned().collect(),
|
||||
@@ -1132,7 +1302,12 @@ impl Game<'_> {
|
||||
.all(|(k, v)| s.properties.get(k) == Some(v))
|
||||
}
|
||||
/// Place a state like BlockInput.place: false when nothing changed.
|
||||
fn place_state(&mut self, pos: [i32; 3], state: BlockStateId, strict: bool) -> R<bool> {
|
||||
pub(super) fn place_state(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
state: BlockStateId,
|
||||
strict: bool,
|
||||
) -> R<bool> {
|
||||
let previous = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if previous == state {
|
||||
return Ok(false);
|
||||
@@ -1958,7 +2133,7 @@ impl Game<'_> {
|
||||
Ok(1)
|
||||
}
|
||||
/// MessageArgument: `@p`-style selectors in a message become names.
|
||||
fn expand_selectors(&mut self, raw: &str) -> Text {
|
||||
pub(super) fn expand_selectors(&mut self, raw: &str) -> Text {
|
||||
let mut out = Text::empty();
|
||||
let mut rest = raw;
|
||||
while let Some(at) = rest.find('@') {
|
||||
|
||||
@@ -0,0 +1,676 @@
|
||||
//! `/data` (DataCommands), `/tag` (TagCommand) and `/summon` with NBT: entity,
|
||||
//! block entity and storage data accessors over the game state.
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use horizon_client::{
|
||||
data_cmd::{self, Op, path_error},
|
||||
entity_nbt,
|
||||
nbt_path::NbtPath,
|
||||
save::{self, random_uuid},
|
||||
scoreboard_cmd::{Holder, Tracker, format_list},
|
||||
snbt,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag, parse_snbt};
|
||||
|
||||
/// A `DataAccessor`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(in crate::game) enum DataRef {
|
||||
Entity(Target),
|
||||
Block([i32; 3]),
|
||||
Storage(String),
|
||||
}
|
||||
|
||||
fn empty() -> Tag {
|
||||
Tag::Compound(Compound::new())
|
||||
}
|
||||
fn set_key(tag: &mut Tag, key: &str, value: Tag) {
|
||||
if let Tag::Compound(c) = tag {
|
||||
c.insert(JavaString::from(key), value);
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
// ---- entity data ---------------------------------------------------
|
||||
|
||||
/// `NbtPredicate.getEntityTagToCompare`: the entity as saved.
|
||||
pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option<Tag> {
|
||||
let player_uuid = self.level.player_uuid;
|
||||
Some(match t {
|
||||
Target::Player => {
|
||||
self.player.as_ref()?;
|
||||
self.sync_level();
|
||||
let mut tag = self.level.player_tag();
|
||||
if let Some(u) = player_uuid {
|
||||
set_key(&mut tag, "UUID", Tag::IntArray(u.to_vec()));
|
||||
}
|
||||
tag
|
||||
}
|
||||
Target::Mob(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let m = self.mobs.iter().find(|m| m.id == id)?;
|
||||
entity_nbt::mob_to_nbt(m, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Item(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let e = self.dropped.iter().find(|e| e.id == id)?;
|
||||
entity_nbt::item_entity_to_nbt(e, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Stand(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let a = self.armor_stands.iter().find(|a| a.id == id)?;
|
||||
entity_nbt::armor_stand_to_nbt(a, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Frame(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let f = self.item_frames.iter().find(|f| f.id == id)?;
|
||||
entity_nbt::item_frame_to_nbt(f, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Painting(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let p = self.paintings.iter().find(|p| p.id == id)?;
|
||||
entity_nbt::painting_to_nbt(p, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Boat(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let b = self.boats.iter().find(|b| b.id == id)?;
|
||||
entity_nbt::boat_to_nbt(
|
||||
&b.wood,
|
||||
b.position,
|
||||
b.velocity,
|
||||
b.yaw,
|
||||
uuid,
|
||||
self.persist.raw.get(&id),
|
||||
)
|
||||
}
|
||||
Target::Cart(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let c = self.carts.iter().find(|c| c.id == id)?;
|
||||
c.to_nbt(uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
|
||||
Target::Arrow(i) => {
|
||||
let a = self.arrows.get(i)?;
|
||||
let owner = if a.from_player { player_uuid } else { None };
|
||||
entity_nbt::arrow_to_nbt(a, random_uuid(), owner)
|
||||
}
|
||||
})
|
||||
}
|
||||
/// `Entity.load` of new data (`EntityDataAccessor.setData`): the entity is
|
||||
/// rebuilt from its compound, keeping its id and UUID.
|
||||
fn apply_entity_nbt(&mut self, t: Target, mut tag: Tag) -> R<()> {
|
||||
let stale = || err("commands.data.merge.failed", &[]);
|
||||
match t {
|
||||
Target::Player => return Err(err("commands.data.entity.invalid", &[])),
|
||||
Target::Mob(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let kind = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map(|m| m.kind.id.clone());
|
||||
set_key(&mut tag, "UUID", Tag::IntArray(uuid.to_vec()));
|
||||
if let Some(k) = kind {
|
||||
set_key(&mut tag, "id", Tag::String(k.as_str().into()));
|
||||
}
|
||||
let new =
|
||||
entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, id).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
// Runtime-only state (AI, animation) carries over.
|
||||
let old = std::mem::replace(slot, new);
|
||||
slot.ai = old.ai;
|
||||
slot.age = old.age;
|
||||
slot.previous = slot.position;
|
||||
}
|
||||
}
|
||||
Target::Item(id) => {
|
||||
let new = entity_nbt::item_entity_from_nbt(&tag, id, 0.0).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.dropped.iter_mut().find(|e| e.id == id) {
|
||||
let bob = slot.bob_offset;
|
||||
*slot = new;
|
||||
slot.bob_offset = bob;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => {
|
||||
let new = entity_nbt::armor_stand_from_nbt(&tag, id).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.armor_stands.iter_mut().find(|a| a.id == id) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
Target::Frame(id) => {
|
||||
let new = entity_nbt::item_frame_from_nbt(&tag, id).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.item_frames.iter_mut().find(|f| f.id == id) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
_ => return Err(stale()),
|
||||
}
|
||||
if let Target::Mob(id) | Target::Item(id) | Target::Stand(id) | Target::Frame(id) = t {
|
||||
self.persist.raw.insert(id, tag);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::game) fn data_block_name(&self, p: [i32; 3]) -> String {
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
self.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.map_or_else(|| "minecraft:air".into(), |s| s.name.to_string())
|
||||
}
|
||||
fn raw_mut(&mut self, t: Target) -> Option<&mut Tag> {
|
||||
match t {
|
||||
Target::Player => Some(self.level.player_extra.get_or_insert_with(empty)),
|
||||
Target::Mob(id)
|
||||
| Target::Item(id)
|
||||
| Target::Stand(id)
|
||||
| Target::Frame(id)
|
||||
| Target::Painting(id)
|
||||
| Target::Boat(id)
|
||||
| Target::Cart(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn set_entity_tags(&mut self, t: Target, tags: &[String]) {
|
||||
if let Some(raw) = self.raw_mut(t) {
|
||||
let list = tags
|
||||
.iter()
|
||||
.map(|s| Tag::String(s.as_str().into()))
|
||||
.collect();
|
||||
set_key(raw, "Tags", Tag::List(list));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- accessors -----------------------------------------------------
|
||||
|
||||
/// The `role`th provider of the command (`entity`, `block` or `storage`).
|
||||
pub(in crate::game) fn data_ref(&mut self, ctx: &Context, role: usize) -> R<DataRef> {
|
||||
let prefix = if role == 0 { "target" } else { "source" };
|
||||
self.data_ref_named(ctx, role, prefix)
|
||||
}
|
||||
pub(in crate::game) fn data_ref_named(
|
||||
&mut self,
|
||||
ctx: &Context,
|
||||
role: usize,
|
||||
prefix: &str,
|
||||
) -> R<DataRef> {
|
||||
let kind = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.filter(|l| matches!(l.as_str(), "entity" | "block" | "storage"))
|
||||
.nth(role)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
match kind.as_str() {
|
||||
"entity" => {
|
||||
let Some(Arg::Entity(sel)) = ctx.get(prefix).cloned() else {
|
||||
return Err(err("argument.entity.notfound.entity", &[]));
|
||||
};
|
||||
let found = self.select(&sel);
|
||||
found
|
||||
.first()
|
||||
.map(|t| DataRef::Entity(*t))
|
||||
.ok_or_else(|| err("argument.entity.notfound.entity", &[]))
|
||||
}
|
||||
"block" => {
|
||||
let p = self.block_pos_arg(ctx, &format!("{prefix}Pos"))?;
|
||||
if !self.world.block_entities.contains_key(&(p[0], p[1], p[2])) {
|
||||
return Err(err("commands.data.block.invalid", &[]));
|
||||
}
|
||||
Ok(DataRef::Block(p))
|
||||
}
|
||||
_ => match ctx.get(prefix) {
|
||||
Some(Arg::Resource(id)) => Ok(DataRef::Storage(id.clone())),
|
||||
_ => Err(err("command.failed", &[])),
|
||||
},
|
||||
}
|
||||
}
|
||||
pub(in crate::game) fn data_of(&mut self, r: &DataRef) -> R<Tag> {
|
||||
match r {
|
||||
DataRef::Entity(t) => self
|
||||
.entity_nbt(*t)
|
||||
.ok_or_else(|| err("argument.entity.notfound.entity", &[])),
|
||||
DataRef::Block(p) => {
|
||||
let key = (p[0], p[1], p[2]);
|
||||
let name = self.data_block_name(*p);
|
||||
let e = self
|
||||
.world
|
||||
.block_entities
|
||||
.get(&key)
|
||||
.ok_or_else(|| err("commands.data.block.invalid", &[]))?;
|
||||
Ok(save::encode_block_entity(key, e, &name))
|
||||
}
|
||||
DataRef::Storage(id) => Ok(self.score.storage.get(id)),
|
||||
}
|
||||
}
|
||||
pub(in crate::game) fn set_data_of(&mut self, r: &DataRef, tag: Tag) -> R<()> {
|
||||
match r {
|
||||
DataRef::Entity(t) => self.apply_entity_nbt(*t, tag),
|
||||
DataRef::Block(p) => {
|
||||
let key = (p[0], p[1], p[2]);
|
||||
if let Some((_, new)) = save::decode_block_entity(&tag) {
|
||||
self.world.block_entities.insert(key, new);
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
// Redraw what shows the block entity (signs, banners).
|
||||
let _ = self.world.set(p[0], p[1], p[2], state);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
DataRef::Storage(id) => {
|
||||
self.score.storage.set(id, tag);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
fn data_name(&self, r: &DataRef) -> Text {
|
||||
match r {
|
||||
DataRef::Entity(t) => self.target_name(*t),
|
||||
DataRef::Block(p) => Text::literal(format!("{}, {}, {}", p[0], p[1], p[2])),
|
||||
DataRef::Storage(id) => Text::literal(id.clone()),
|
||||
}
|
||||
}
|
||||
fn modified_text(&self, r: &DataRef) -> Text {
|
||||
match r {
|
||||
DataRef::Entity(_) => {
|
||||
Text::translate("commands.data.entity.modified", &[self.data_name(r)])
|
||||
}
|
||||
DataRef::Block(p) => Text::translate(
|
||||
"commands.data.block.modified",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal(p[1].to_string()),
|
||||
Text::literal(p[2].to_string()),
|
||||
],
|
||||
),
|
||||
DataRef::Storage(id) => Text::translate(
|
||||
"commands.data.storage.modified",
|
||||
&[Text::literal(id.clone())],
|
||||
),
|
||||
}
|
||||
}
|
||||
fn query_text(&self, r: &DataRef, data: &Tag) -> Text {
|
||||
let pretty = snbt::pretty(data);
|
||||
match r {
|
||||
DataRef::Entity(_) => {
|
||||
Text::translate("commands.data.entity.query", &[self.data_name(r), pretty])
|
||||
}
|
||||
DataRef::Block(p) => Text::translate(
|
||||
"commands.data.block.query",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal(p[1].to_string()),
|
||||
Text::literal(p[2].to_string()),
|
||||
pretty,
|
||||
],
|
||||
),
|
||||
DataRef::Storage(id) => Text::translate(
|
||||
"commands.data.storage.query",
|
||||
&[Text::literal(id.clone()), pretty],
|
||||
),
|
||||
}
|
||||
}
|
||||
fn get_text(&self, r: &DataRef, path: &NbtPath, scale: f64, value: i32) -> Text {
|
||||
let p = Text::literal(path.as_str());
|
||||
let (s, v) = (
|
||||
data_cmd::scale_text(scale),
|
||||
Text::literal(value.to_string()),
|
||||
);
|
||||
match r {
|
||||
DataRef::Entity(_) => {
|
||||
Text::translate("commands.data.entity.get", &[p, self.data_name(r), s, v])
|
||||
}
|
||||
DataRef::Block(b) => Text::translate(
|
||||
"commands.data.block.get",
|
||||
&[
|
||||
p,
|
||||
Text::literal(b[0].to_string()),
|
||||
Text::literal(b[1].to_string()),
|
||||
Text::literal(b[2].to_string()),
|
||||
s,
|
||||
v,
|
||||
],
|
||||
),
|
||||
DataRef::Storage(id) => Text::translate(
|
||||
"commands.data.storage.get",
|
||||
&[p, Text::literal(id.clone()), s, v],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- /data -----------------------------------------------------------
|
||||
|
||||
fn path_arg(&self, ctx: &Context, name: &str) -> R<NbtPath> {
|
||||
let Some(Arg::Str(text)) = ctx.get(name) else {
|
||||
return Err(err("command.failed", &[]));
|
||||
};
|
||||
NbtPath::parse(text).map_err(path_error)
|
||||
}
|
||||
pub(super) fn cmd_data(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let target = self.data_ref(ctx, 0)?;
|
||||
match id {
|
||||
"data.merge" => {
|
||||
let Some(Arg::Str(nbt)) = ctx.get("nbt") else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (nbt, _) = parse_snbt(nbt).map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
let old = self.data_of(&target)?;
|
||||
if horizon_client::nbt_path::too_deep(&nbt, 0) {
|
||||
return Err(err("arguments.nbtpath.too_deep", &[]));
|
||||
}
|
||||
let result = data_cmd::merged(&old, &nbt);
|
||||
if old == result {
|
||||
return Err(err("commands.data.merge.failed", &[]));
|
||||
}
|
||||
self.set_data_of(&target, result)?;
|
||||
let message = self.modified_text(&target);
|
||||
self.feedback(message);
|
||||
Ok(1)
|
||||
}
|
||||
"data.get" => {
|
||||
let data = self.data_of(&target)?;
|
||||
if ctx.get("path").is_none() {
|
||||
let message = self.query_text(&target, &data);
|
||||
self.system_feedback(message);
|
||||
return Ok(1);
|
||||
}
|
||||
let path = self.path_arg(ctx, "path")?;
|
||||
let tag = data_cmd::single_tag(&path, &data)?;
|
||||
if let Some(Arg::Double(scale)) = ctx.get("scale") {
|
||||
let value = data_cmd::scaled_value(&tag, &path, *scale)?;
|
||||
let message = self.get_text(&target, &path, *scale, value);
|
||||
self.system_feedback(message);
|
||||
return Ok(value);
|
||||
}
|
||||
let value = data_cmd::get_value(&tag, &path)?;
|
||||
let message = self.query_text(&target, &tag);
|
||||
self.system_feedback(message);
|
||||
Ok(value)
|
||||
}
|
||||
"data.remove" => {
|
||||
let path = self.path_arg(ctx, "path")?;
|
||||
let mut data = self.data_of(&target)?;
|
||||
let count = path.remove(&mut data);
|
||||
if count == 0 {
|
||||
return Err(err("commands.data.merge.failed", &[]));
|
||||
}
|
||||
self.set_data_of(&target, data)?;
|
||||
let message = self.modified_text(&target);
|
||||
self.feedback(message);
|
||||
Ok(count as i32)
|
||||
}
|
||||
"data.modify" => self.cmd_data_modify(ctx, target),
|
||||
_ => Err(err("command.failed", &[])),
|
||||
}
|
||||
}
|
||||
/// A message sent without the feedback gamerule check (`sendSuccess(.., false)`).
|
||||
fn system_feedback(&mut self, message: Text) {
|
||||
self.feedback(message);
|
||||
}
|
||||
fn cmd_data_modify(&mut self, ctx: &Context, target: DataRef) -> R<i32> {
|
||||
let target_path = self.path_arg(ctx, "targetPath")?;
|
||||
let after_modify: Vec<&String> = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.skip_while(|l| l.as_str() != "modify")
|
||||
.collect();
|
||||
let op = after_modify
|
||||
.iter()
|
||||
.find_map(|l| match l.as_str() {
|
||||
"prepend" => Some(Op::Prepend),
|
||||
"append" => Some(Op::Append),
|
||||
"set" => Some(Op::Set),
|
||||
"merge" => Some(Op::Merge),
|
||||
"insert" => Some(Op::Insert(match ctx.get("index") {
|
||||
Some(Arg::Int(i)) => *i,
|
||||
_ => 0,
|
||||
})),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(Op::Set);
|
||||
let sources: Vec<Tag> = if ctx.has("value") {
|
||||
let Some(Arg::Str(text)) = ctx.get("value") else {
|
||||
return Ok(0);
|
||||
};
|
||||
vec![
|
||||
parse_snbt(text)
|
||||
.map_err(|e| err("argument.nbt.invalid", &[&e]))?
|
||||
.0,
|
||||
]
|
||||
} else {
|
||||
let source = self.data_ref(ctx, 1)?;
|
||||
let data = self.data_of(&source)?;
|
||||
let tags = if ctx.get("sourcePath").is_some() {
|
||||
self.path_arg(ctx, "sourcePath")?
|
||||
.get(&data)
|
||||
.map_err(path_error)?
|
||||
} else {
|
||||
vec![data]
|
||||
};
|
||||
if ctx.has("string") {
|
||||
let start = match ctx.get("start") {
|
||||
Some(Arg::Int(i)) => Some(*i),
|
||||
_ => None,
|
||||
};
|
||||
let end = match ctx.get("end") {
|
||||
Some(Arg::Int(i)) => Some(*i),
|
||||
_ => None,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for t in &tags {
|
||||
let text = data_cmd::as_text(t)?;
|
||||
let text = match start {
|
||||
Some(s) => data_cmd::substring(&text, s, end)?,
|
||||
None => text,
|
||||
};
|
||||
out.push(Tag::String(text.as_str().into()));
|
||||
}
|
||||
out
|
||||
} else {
|
||||
tags
|
||||
}
|
||||
};
|
||||
let mut data = self.data_of(&target)?;
|
||||
let changed = data_cmd::modify(op, &mut data, &target_path, &sources)?;
|
||||
if changed == 0 {
|
||||
return Err(err("commands.data.merge.failed", &[]));
|
||||
}
|
||||
self.set_data_of(&target, data)?;
|
||||
let message = self.modified_text(&target);
|
||||
self.feedback(message);
|
||||
Ok(changed as i32)
|
||||
}
|
||||
|
||||
// ---- /tag ------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_tag(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "targets", false)?;
|
||||
let name = match ctx.get("name") {
|
||||
Some(Arg::Str(n)) => n.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let mut tracker = Tracker::default();
|
||||
let holder = |g: &Self, t: Target| Holder {
|
||||
name: String::new(),
|
||||
text: g.target_name(t),
|
||||
display: None,
|
||||
};
|
||||
let mut all: Vec<String> = Vec::new();
|
||||
for &t in &targets {
|
||||
let mut tags = self.tags_of(t);
|
||||
let h = holder(self, t);
|
||||
match id {
|
||||
"tag.add" => {
|
||||
let added = tags.len() < 1024 && !tags.contains(&name);
|
||||
if added {
|
||||
tags.push(name.clone());
|
||||
self.set_entity_tags(t, &tags);
|
||||
}
|
||||
tracker.track(&h, i32::from(added));
|
||||
}
|
||||
"tag.remove" => {
|
||||
let before = tags.len();
|
||||
tags.retain(|x| x != &name);
|
||||
let removed = tags.len() != before;
|
||||
if removed {
|
||||
self.set_entity_tags(t, &tags);
|
||||
}
|
||||
tracker.track(&h, i32::from(removed));
|
||||
}
|
||||
_ => {
|
||||
tracker.track(&h, tags.len() as i32);
|
||||
for tag in tags {
|
||||
if !all.contains(&tag) {
|
||||
all.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let num = |n: usize| Text::literal(n.to_string());
|
||||
let n = name.clone();
|
||||
let (message, total) = match id {
|
||||
"tag.add" => tracker.message(
|
||||
false,
|
||||
Some(err("commands.tag.add.failed", &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.add.success.single",
|
||||
&[Text::literal(n.clone()), h.text.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.tag.add.success.multiple",
|
||||
&[Text::literal(n.clone()), num(c)],
|
||||
)
|
||||
},
|
||||
),
|
||||
"tag.remove" => tracker.message(
|
||||
false,
|
||||
Some(err("commands.tag.remove.failed", &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.remove.success.single",
|
||||
&[Text::literal(n.clone()), h.text.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.tag.remove.success.multiple",
|
||||
&[Text::literal(n.clone()), num(c)],
|
||||
)
|
||||
},
|
||||
),
|
||||
_ => {
|
||||
let count = all.len();
|
||||
let message = if all.is_empty() {
|
||||
tracker
|
||||
.message(
|
||||
false,
|
||||
None,
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.list.single.empty",
|
||||
std::slice::from_ref(&h.text),
|
||||
)
|
||||
},
|
||||
|c, _| Text::translate("commands.tag.list.multiple.empty", &[num(c)]),
|
||||
)?
|
||||
.0
|
||||
} else {
|
||||
let list = {
|
||||
let mut sorted = all.clone();
|
||||
sorted.sort();
|
||||
format_list(
|
||||
sorted
|
||||
.into_iter()
|
||||
.map(|s| Text::literal(s).with_color(horizon_client::text::GREEN))
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
tracker
|
||||
.message(
|
||||
true,
|
||||
None,
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.list.single.success",
|
||||
&[h.text.clone(), num(count), list.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.tag.list.multiple.success",
|
||||
&[num(c), num(count), list.clone()],
|
||||
)
|
||||
},
|
||||
)?
|
||||
.0
|
||||
};
|
||||
self.feedback(message);
|
||||
return Ok(count as i32);
|
||||
}
|
||||
}?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
// ---- /summon ---------------------------------------------------------
|
||||
|
||||
/// Spawn an entity from its compound (`EntityType.loadEntityRecursive`);
|
||||
/// returns what was created.
|
||||
pub(super) fn spawn_entity_from_nbt(&mut self, tag: Tag) -> Option<Target> {
|
||||
let before = self.next_entity;
|
||||
let key = {
|
||||
let p = entity_nbt::position(&tag)?;
|
||||
((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4)
|
||||
};
|
||||
self.world.loaded_entities.push((key, vec![tag]));
|
||||
self.spawn_loaded_entities();
|
||||
let id = self.next_entity;
|
||||
if id == before {
|
||||
return None;
|
||||
}
|
||||
if self.mobs.iter().any(|m| m.id == id) {
|
||||
Some(Target::Mob(id))
|
||||
} else if self.dropped.iter().any(|e| e.id == id) {
|
||||
Some(Target::Item(id))
|
||||
} else if self.armor_stands.iter().any(|a| a.id == id) {
|
||||
Some(Target::Stand(id))
|
||||
} else if self.item_frames.iter().any(|f| f.id == id) {
|
||||
Some(Target::Frame(id))
|
||||
} else if self.paintings.iter().any(|p| p.id == id) {
|
||||
Some(Target::Painting(id))
|
||||
} else if self.boats.iter().any(|b| b.id == id) {
|
||||
Some(Target::Boat(id))
|
||||
} else if self.carts.iter().any(|c| c.id == id) {
|
||||
Some(Target::Cart(id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// The `summon <entity> <pos> <nbt>` form.
|
||||
pub(super) fn summon_with_nbt(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
pos: [f64; 3],
|
||||
nbt: &str,
|
||||
) -> R<Option<Target>> {
|
||||
let (mut tag, _) = parse_snbt(nbt).map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
if !matches!(tag, Tag::Compound(_)) {
|
||||
return Err(err("argument.nbt.expected.compound", &[]));
|
||||
}
|
||||
set_key(&mut tag, "id", Tag::String(kind.into()));
|
||||
let p = pos.map(|v| Tag::Double(v.to_bits()));
|
||||
set_key(&mut tag, "Pos", Tag::List(p.to_vec()));
|
||||
if tag.get("Rotation").is_none() {
|
||||
set_key(
|
||||
&mut tag,
|
||||
"Rotation",
|
||||
Tag::List(vec![
|
||||
Tag::Float(0.0f32.to_bits()),
|
||||
Tag::Float(0.0f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
}
|
||||
Ok(self.spawn_entity_from_nbt(tag))
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
//! `/execute` (ExecuteCommand): walk the parsed redirect chain, forking and
|
||||
//! filtering command sources, then run the final command once per source.
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use horizon_client::text::Text;
|
||||
//! filtering command sources, then run the final command once per source,
|
||||
//! reporting each result to the `store` callbacks of its source.
|
||||
use super::{Arg, Context, Game, R, Target, data::DataRef, err};
|
||||
use horizon_client::{
|
||||
command::{CommandError, vanilla},
|
||||
nbt_path::NbtPath,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `CommandSourceStack` fields Horizon models: the executing entity (None for
|
||||
/// the server), position, rotation and anchor.
|
||||
/// the server), position, rotation, anchor, whether feedback is suppressed
|
||||
/// and the chain of `store` callbacks.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(in crate::game) struct Source {
|
||||
pub entity: Option<Target>,
|
||||
@@ -12,19 +19,71 @@ pub(in crate::game) struct Source {
|
||||
pub rot: [f32; 2],
|
||||
/// EntityAnchorArgument.Anchor: eyes (true) or feet.
|
||||
pub eyes: bool,
|
||||
/// `withSuppressedOutput`: functions do not print feedback.
|
||||
pub silent: bool,
|
||||
/// Index of the newest `store` in `ExecState::stores`.
|
||||
pub store: Option<u32>,
|
||||
}
|
||||
|
||||
/// Where `execute store` writes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(in crate::game) enum StoreTarget {
|
||||
Score(Vec<String>, String),
|
||||
Bossbar(String, bool),
|
||||
Data(DataRef, NbtPath, String, f64),
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub(in crate::game) struct StoreEntry {
|
||||
/// `store result` (true) or `store success`.
|
||||
result: bool,
|
||||
target: StoreTarget,
|
||||
parent: Option<u32>,
|
||||
}
|
||||
/// Command execution state shared across nested commands and functions.
|
||||
#[derive(Default)]
|
||||
pub(in crate::game) struct ExecState {
|
||||
stores: Vec<StoreEntry>,
|
||||
/// Commands run since the outermost one began.
|
||||
pub commands: u32,
|
||||
/// What the last leaf command reports to its `store` callbacks: None for
|
||||
/// the default, `Some(None)` for nothing (a function that did not
|
||||
/// `return`), `Some(Some((success, result)))` for an explicit value.
|
||||
pub callback: Option<Option<(bool, i32)>>,
|
||||
/// The innermost function frame's `return`.
|
||||
pub returned: Option<Option<i32>>,
|
||||
/// Depth of function calls.
|
||||
pub function_depth: u32,
|
||||
}
|
||||
|
||||
/// Java's `(int)`/`(short)`/`(byte)` narrowing of a double.
|
||||
fn java_int(v: f64) -> i32 {
|
||||
v as i32
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The source a command typed by the player starts from.
|
||||
pub(super) fn player_source(&self) -> Source {
|
||||
pub(in crate::game) fn player_source(&self) -> Source {
|
||||
Source {
|
||||
entity: Some(Target::Player),
|
||||
pos: self.source_position(),
|
||||
rot: self.source_rotation(),
|
||||
eyes: false,
|
||||
silent: false,
|
||||
store: None,
|
||||
}
|
||||
}
|
||||
fn target_rotation(&self, t: Target) -> [f32; 2] {
|
||||
/// The server as a source (function ticks and schedules): the world spawn.
|
||||
pub(in crate::game) fn server_source(&self) -> Source {
|
||||
Source {
|
||||
entity: None,
|
||||
pos: self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]),
|
||||
rot: [0.0, 0.0],
|
||||
eyes: false,
|
||||
silent: true,
|
||||
store: None,
|
||||
}
|
||||
}
|
||||
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
|
||||
match t {
|
||||
Target::Player => [self.yaw, self.pitch],
|
||||
Target::Mob(id) => self
|
||||
@@ -32,10 +91,25 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map_or([0.0; 2], |m| [m.yaw, m.head_pitch]),
|
||||
Target::Stand(id) => self
|
||||
.armor_stands
|
||||
.iter()
|
||||
.find(|a| a.id == id)
|
||||
.map_or([0.0; 2], |a| [a.yaw, 0.0]),
|
||||
Target::Boat(id) => self
|
||||
.boats
|
||||
.iter()
|
||||
.find(|b| b.id == id)
|
||||
.map_or([0.0; 2], |b| [b.yaw, 0.0]),
|
||||
Target::Cart(id) => self
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map_or([0.0; 2], |c| [c.yaw, 0.0]),
|
||||
_ => [0.0; 2],
|
||||
}
|
||||
}
|
||||
fn target_eye_height(&self, t: Target) -> f64 {
|
||||
pub(super) fn target_eye_height(&self, t: Target) -> f64 {
|
||||
match t {
|
||||
Target::Player => self
|
||||
.player
|
||||
@@ -57,14 +131,108 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Evaluate `f` with `source` as the command source.
|
||||
fn with_source<T>(&mut self, source: Source, f: impl FnOnce(&mut Self) -> T) -> T {
|
||||
pub(in crate::game) fn with_source<T>(
|
||||
&mut self,
|
||||
source: Source,
|
||||
f: impl FnOnce(&mut Self) -> T,
|
||||
) -> T {
|
||||
let previous = self.command_source.replace(source);
|
||||
let out = f(self);
|
||||
self.command_source = previous;
|
||||
out
|
||||
}
|
||||
|
||||
// ---- running commands -----------------------------------------------
|
||||
|
||||
/// Run one command line with `source` (no error reporting): the entry
|
||||
/// for functions and `execute run`.
|
||||
pub(in crate::game) fn execute_line(&mut self, line: &str, source: Source) -> R<i32> {
|
||||
let d = vanilla::dispatcher();
|
||||
let parse = d.parse(line, &self.ui.registries);
|
||||
let (ctx, _) = parse.executable()?;
|
||||
let ctx = ctx.clone();
|
||||
let root = parse.context.clone();
|
||||
self.with_source(source, |g| g.run_chain(&root, &ctx))
|
||||
}
|
||||
/// Run a parsed command (`root` is the first context; `ctx` the one with
|
||||
/// the executable node): `execute` and `return` walk their own chains.
|
||||
pub(in crate::game) fn run_chain(&mut self, root: &Context, ctx: &Context) -> R<i32> {
|
||||
self.exec.commands += 1;
|
||||
let limit = self.ui.rules.int("max_command_sequence_length").max(1) as u32;
|
||||
if self.exec.commands > limit {
|
||||
return Err(err("command.failed", &[]));
|
||||
}
|
||||
match root.literals.first().map(String::as_str) {
|
||||
Some("execute") => self.run_execute(root),
|
||||
Some("return") if root.child.is_some() => self.run_return_run(root),
|
||||
_ => {
|
||||
let id = ctx.command.unwrap_or("");
|
||||
self.run_leaf(id, ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Run a leaf command and report its outcome to the `store` callbacks.
|
||||
pub(in crate::game) fn run_leaf(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
self.exec.callback = None;
|
||||
let store = self.command_source.and_then(|s| s.store);
|
||||
let result = self.execute_command(id, ctx);
|
||||
let custom = self.exec.callback.take();
|
||||
let outcome = match (&result, custom) {
|
||||
(_, Some(c)) => c,
|
||||
(Ok(v), None) => Some((true, *v)),
|
||||
(Err(_), None) => Some((false, 0)),
|
||||
};
|
||||
if let Some((success, value)) = outcome {
|
||||
self.deliver(store, success, value);
|
||||
}
|
||||
result
|
||||
}
|
||||
/// `CommandResultCallback`s of a source's `store` chain, oldest first.
|
||||
fn deliver(&mut self, store: Option<u32>, success: bool, value: i32) {
|
||||
let mut chain = Vec::new();
|
||||
let mut at = store;
|
||||
while let Some(i) = at {
|
||||
let Some(e) = self.exec.stores.get(i as usize) else {
|
||||
break;
|
||||
};
|
||||
chain.push(e.clone());
|
||||
at = e.parent;
|
||||
}
|
||||
for e in chain.into_iter().rev() {
|
||||
let v = if e.result { value } else { i32::from(success) };
|
||||
self.store_value(&e.target, v);
|
||||
}
|
||||
}
|
||||
fn store_value(&mut self, target: &StoreTarget, value: i32) {
|
||||
match target {
|
||||
StoreTarget::Score(holders, objective) => {
|
||||
for h in holders {
|
||||
self.score.board.set(h, objective, value);
|
||||
}
|
||||
}
|
||||
StoreTarget::Bossbar(id, is_value) => self.set_bossbar_value(id, *is_value, value),
|
||||
StoreTarget::Data(r, path, kind, scale) => {
|
||||
let Ok(mut data) = self.data_of(r) else {
|
||||
return;
|
||||
};
|
||||
let v = f64::from(value) * scale;
|
||||
let tag = match kind.as_str() {
|
||||
"int" => Tag::Int(java_int(v)),
|
||||
"float" => Tag::Float((v as f32).to_bits()),
|
||||
"short" => Tag::Short(java_int(v) as i16),
|
||||
"long" => Tag::Long(v as i64),
|
||||
"double" => Tag::Double(v.to_bits()),
|
||||
_ => Tag::Byte(java_int(v) as i8),
|
||||
};
|
||||
if path.set(&mut data, &tag).is_ok() {
|
||||
let _ = self.set_data_of(r, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ExecuteCommand: `ctx` is the context holding the `execute` literal.
|
||||
pub(super) fn run_execute(&mut self, ctx: &Context) -> R<i32> {
|
||||
pub(in crate::game) fn run_execute(&mut self, ctx: &Context) -> R<i32> {
|
||||
let mut sources = vec![self.command_source.unwrap_or_else(|| self.player_source())];
|
||||
let mut c = ctx;
|
||||
loop {
|
||||
@@ -80,57 +248,41 @@ impl Game<'_> {
|
||||
return Err(err("command.unknown.command", &[]));
|
||||
};
|
||||
let last = command.last_child();
|
||||
let Some(id) = last.command else {
|
||||
if last.command.is_none() {
|
||||
return Err(err("command.unknown.command", &[]));
|
||||
};
|
||||
// A nested execute walks its own chain.
|
||||
let nested = command.literals.first().is_some_and(|w| w == "execute");
|
||||
}
|
||||
let mut total = 0;
|
||||
let many = sources.len() > 1;
|
||||
let mut failure = None;
|
||||
for s in sources {
|
||||
let result = self.with_source(s, |g| {
|
||||
if nested {
|
||||
g.run_execute(command)
|
||||
} else {
|
||||
g.execute_command(id, last)
|
||||
}
|
||||
});
|
||||
match result {
|
||||
match self.with_source(s, |g| g.run_chain(command, last)) {
|
||||
Ok(n) => total += n,
|
||||
// Forked executions report failures and carry on.
|
||||
Err(e) => self.command_failure(e.message),
|
||||
Err(e) if many => self.command_failure(e.message),
|
||||
Err(e) => failure = Some(e),
|
||||
}
|
||||
if self.exec.returned.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Ok(total);
|
||||
return match failure {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(total),
|
||||
};
|
||||
}
|
||||
"if" | "unless" => {
|
||||
let want = word == "if";
|
||||
if c.child.is_none() {
|
||||
return self.run_conditional_terminal(c, sources, want);
|
||||
}
|
||||
let mut kept = Vec::new();
|
||||
let mut count = 0;
|
||||
for s in sources {
|
||||
let n = self.with_source(s, |g| g.condition(c))?;
|
||||
if (n > 0) == want {
|
||||
let (keep, _) = self.with_source(s, |g| g.condition(c, want))?;
|
||||
if keep {
|
||||
kept.push(s);
|
||||
count += if want { n } else { 1 };
|
||||
}
|
||||
}
|
||||
sources = kept;
|
||||
if c.child.is_none() {
|
||||
// A condition ending the chain is a test.
|
||||
return if sources.is_empty() {
|
||||
Err(err("commands.execute.conditional.fail", &[]))
|
||||
} else {
|
||||
let entity = c.has("entity") && want;
|
||||
self.feedback(if entity {
|
||||
Text::translate(
|
||||
"commands.execute.conditional.pass_count",
|
||||
&[Text::literal(count.to_string())],
|
||||
)
|
||||
} else {
|
||||
Text::translate("commands.execute.conditional.pass", &[])
|
||||
});
|
||||
Ok(if entity { count } else { 1 })
|
||||
};
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let mut next = Vec::new();
|
||||
@@ -146,6 +298,89 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A conditional that ends the chain runs as a command: a test per source.
|
||||
fn run_conditional_terminal(
|
||||
&mut self,
|
||||
c: &Context,
|
||||
sources: Vec<Source>,
|
||||
want: bool,
|
||||
) -> R<i32> {
|
||||
let numeric = ["entity", "data", "blocks", "items", "slots"]
|
||||
.iter()
|
||||
.any(|k| c.has(k));
|
||||
let many = sources.len() > 1;
|
||||
let mut total = 0;
|
||||
let mut failure: Option<CommandError> = None;
|
||||
for s in sources {
|
||||
self.exec.callback = None;
|
||||
let (keep, count) = match self.with_source(s, |g| g.condition(c, want)) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
self.deliver(s.store, false, 0);
|
||||
if many {
|
||||
self.command_failure(e.message);
|
||||
} else {
|
||||
failure = Some(e);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if keep {
|
||||
let n = if want && numeric { count } else { 1 };
|
||||
let message = if want && numeric {
|
||||
Text::translate(
|
||||
"commands.execute.conditional.pass_count",
|
||||
&[Text::literal(count.to_string())],
|
||||
)
|
||||
} else {
|
||||
Text::translate("commands.execute.conditional.pass", &[])
|
||||
};
|
||||
self.with_source(s, |g| g.feedback(message));
|
||||
self.deliver(s.store, true, n);
|
||||
total += n;
|
||||
} else {
|
||||
self.deliver(s.store, false, 0);
|
||||
let e = if !want && numeric {
|
||||
err("commands.execute.conditional.fail_count", &[&count])
|
||||
} else {
|
||||
err("commands.execute.conditional.fail", &[])
|
||||
};
|
||||
if many {
|
||||
self.command_failure(e.message);
|
||||
} else {
|
||||
failure = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
match failure {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(total),
|
||||
}
|
||||
}
|
||||
/// `return run <command>`: run it and return its result from the frame.
|
||||
fn run_return_run(&mut self, root: &Context) -> R<i32> {
|
||||
let Some(command) = root.child.as_deref() else {
|
||||
return Err(err("command.unknown.command", &[]));
|
||||
};
|
||||
let last = command.last_child();
|
||||
let result = self.run_chain(command, last);
|
||||
// The command's own callbacks do not fire; the function frame gets
|
||||
// its result instead.
|
||||
match result {
|
||||
Ok(v) => self.finish_return(Some(v)),
|
||||
Err(e) => {
|
||||
self.finish_return(None);
|
||||
self.command_failure(e.message);
|
||||
}
|
||||
}
|
||||
self.exec.callback = Some(None);
|
||||
Ok(0)
|
||||
}
|
||||
/// `Frame.returnSuccess`/`returnFailure` then `discard`.
|
||||
pub(in crate::game) fn finish_return(&mut self, value: Option<i32>) {
|
||||
self.exec.returned = Some(value);
|
||||
}
|
||||
|
||||
/// The sources one modifier produces from `s`.
|
||||
fn modify(&mut self, word: &str, c: &Context, s: Source) -> R<Vec<Source>> {
|
||||
let targets = |g: &mut Self| -> R<Vec<Target>> {
|
||||
@@ -186,6 +421,20 @@ impl Game<'_> {
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
"positioned" if c.has("over") => {
|
||||
let Some(Arg::Str(kind)) = c.get("heightmap") else {
|
||||
return Ok(vec![s]);
|
||||
};
|
||||
let (x, z) = (s.pos[0].floor() as i32, s.pos[2].floor() as i32);
|
||||
if !self.world.chunks.contains_key(&(x >> 4, z >> 4)) {
|
||||
return Err(err("argument.pos.unloaded", &[]));
|
||||
}
|
||||
let y = self.heightmap_at(kind, x, z);
|
||||
vec![Source {
|
||||
pos: [s.pos[0], f64::from(y), s.pos[2]],
|
||||
..s
|
||||
}]
|
||||
}
|
||||
"positioned" => {
|
||||
let pos = self
|
||||
.position_arg(c, "pos")
|
||||
@@ -257,9 +506,183 @@ impl Game<'_> {
|
||||
}
|
||||
vec![s]
|
||||
}
|
||||
"summon" => {
|
||||
let Some(Arg::Resource(kind)) = c.get("entity").cloned() else {
|
||||
return Ok(vec![s]);
|
||||
};
|
||||
let target = self.summon_with_nbt(&kind, s.pos, "{}")?;
|
||||
let Some(t) = target else {
|
||||
return Err(err("commands.summon.failed", &[]));
|
||||
};
|
||||
vec![Source {
|
||||
entity: Some(t),
|
||||
..s
|
||||
}]
|
||||
}
|
||||
"on" => self.relation(c, s),
|
||||
"store" => vec![self.store_source(c, s)?],
|
||||
_ => return Err(err("command.unknown.command", &[])),
|
||||
})
|
||||
}
|
||||
/// The entities `on <relation>` reaches from the source entity.
|
||||
fn relation(&mut self, c: &Context, s: Source) -> Vec<Source> {
|
||||
let Some(entity) = s.entity else {
|
||||
return Vec::new();
|
||||
};
|
||||
let found: Vec<Target> = match c.literals.last().map(String::as_str) {
|
||||
Some("owner") => match entity {
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.and_then(|m| m.extra.owner)
|
||||
.and_then(|u| self.target_with_uuid(u))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
Some("vehicle") => match entity {
|
||||
Target::Player => self.riding.map(Target::Mob).into_iter().collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
Some("controller") | Some("passengers") => match entity {
|
||||
Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => {
|
||||
vec![Target::Player]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
},
|
||||
Some("target") | Some("attacker") => {
|
||||
let attacker = c.literals.last().is_some_and(|l| l == "attacker");
|
||||
match entity {
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.and_then(|m| {
|
||||
if attacker {
|
||||
m.ai.last_hurt_by
|
||||
} else {
|
||||
m.ai.target
|
||||
}
|
||||
})
|
||||
.map(|w| match w {
|
||||
horizon_client::mobs::Who::Player => Target::Player,
|
||||
horizon_client::mobs::Who::Mob(i) => Target::Mob(i),
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found
|
||||
.into_iter()
|
||||
.filter(|t| self.target_position(*t).is_some())
|
||||
.map(|t| Source {
|
||||
entity: Some(t),
|
||||
..s
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn target_with_uuid(&self, uuid: [i32; 4]) -> Option<Target> {
|
||||
if Some(uuid) == self.level.player_uuid {
|
||||
return Some(Target::Player);
|
||||
}
|
||||
let id = self
|
||||
.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.find(|(_, u)| **u == uuid)
|
||||
.map(|(id, _)| *id)?;
|
||||
self.mobs
|
||||
.iter()
|
||||
.any(|m| m.id == id)
|
||||
.then_some(Target::Mob(id))
|
||||
}
|
||||
/// The highest block of a heightmap type at a column (`Level.getHeight`).
|
||||
fn heightmap_at(&self, kind: &str, x: i32, z: i32) -> i32 {
|
||||
let top = horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT;
|
||||
for y in (horizon_client::chunk::MIN_Y..top).rev() {
|
||||
let state = self.world.block(x, y, z);
|
||||
if state == self.world.air {
|
||||
continue;
|
||||
}
|
||||
let facts = self.res.facts.get(state);
|
||||
let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None;
|
||||
let leaves = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.is_some_and(|s| s.name.ends_with("_leaves"));
|
||||
let found = match kind {
|
||||
"ocean_floor" => facts.legacy_solid,
|
||||
"motion_blocking" => blocks,
|
||||
"motion_blocking_no_leaves" => blocks && !leaves,
|
||||
_ => true,
|
||||
};
|
||||
if found {
|
||||
return y + 1;
|
||||
}
|
||||
}
|
||||
horizon_client::chunk::MIN_Y
|
||||
}
|
||||
/// A `store` modifier: a new callback in the source's chain.
|
||||
fn store_source(&mut self, c: &Context, s: Source) -> R<Source> {
|
||||
let result = c.has("result");
|
||||
let target = if c.has("score") {
|
||||
let holders = self.score_holder_names(c, "targets", true)?;
|
||||
let Some(Arg::Str(objective)) = c.get("objective") else {
|
||||
return Err(err("command.failed", &[]));
|
||||
};
|
||||
if self.score.board.objective(objective).is_none() {
|
||||
return Err(err("arguments.objective.notFound", &[objective]));
|
||||
}
|
||||
StoreTarget::Score(holders, objective.clone())
|
||||
} else if c.has("bossbar") {
|
||||
let Some(Arg::Resource(id)) = c.get("id") else {
|
||||
return Err(err("command.failed", &[]));
|
||||
};
|
||||
if !self.bossbar_exists(id) {
|
||||
return Err(err("commands.bossbar.unknown", &[id]));
|
||||
}
|
||||
StoreTarget::Bossbar(id.clone(), c.has("value"))
|
||||
} else {
|
||||
let r = self.data_ref(c, 0)?;
|
||||
let path = match c.get("path") {
|
||||
Some(Arg::Str(p)) => {
|
||||
NbtPath::parse(p).map_err(horizon_client::data_cmd::path_error)?
|
||||
}
|
||||
_ => return Err(err("command.failed", &[])),
|
||||
};
|
||||
let kind = c
|
||||
.literals
|
||||
.iter()
|
||||
.find(|l| {
|
||||
matches!(
|
||||
l.as_str(),
|
||||
"int" | "float" | "short" | "long" | "double" | "byte"
|
||||
)
|
||||
})
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "int".into());
|
||||
let scale = match c.get("scale") {
|
||||
Some(Arg::Double(v)) => *v,
|
||||
_ => 1.0,
|
||||
};
|
||||
StoreTarget::Data(r, path, kind, scale)
|
||||
};
|
||||
self.exec.stores.push(StoreEntry {
|
||||
result,
|
||||
target,
|
||||
parent: s.store,
|
||||
});
|
||||
Ok(Source {
|
||||
store: Some(self.exec.stores.len() as u32 - 1),
|
||||
..s
|
||||
})
|
||||
}
|
||||
/// CommandSourceStack.facing: rotation from the anchor point to `to`.
|
||||
fn facing(&self, s: Source, to: [f64; 3]) -> Source {
|
||||
let from = self.anchor_position(&s);
|
||||
@@ -272,35 +695,229 @@ impl Game<'_> {
|
||||
..s
|
||||
}
|
||||
}
|
||||
/// The count an if/unless condition yields (0 = false).
|
||||
fn condition(&mut self, c: &Context) -> R<i32> {
|
||||
|
||||
// ---- conditions ----------------------------------------------------------
|
||||
|
||||
/// Whether the source stays for `if`/`unless` (`want`), and the count the
|
||||
/// numeric conditions report.
|
||||
fn condition(&mut self, c: &Context, want: bool) -> R<(bool, i32)> {
|
||||
if c.has("function") {
|
||||
return self.condition_function(c, want);
|
||||
}
|
||||
let (matched, count) = self.condition_matches(c)?;
|
||||
Ok((matched == want, count))
|
||||
}
|
||||
/// `if function`/`unless function`: the source stays when a function
|
||||
/// returns a non-zero (`if`) or zero (`unless`) value; one that does not
|
||||
/// return leaves it out either way.
|
||||
fn condition_function(&mut self, c: &Context, want: bool) -> R<(bool, i32)> {
|
||||
let Some(Arg::Resource(name)) = c.get("name").cloned() else {
|
||||
return Ok((false, 0));
|
||||
};
|
||||
let results = self.call_function_ref(&name, None)?;
|
||||
let keep = results.iter().any(|r| r.is_some_and(|v| (v != 0) == want));
|
||||
Ok((keep, 0))
|
||||
}
|
||||
fn condition_matches(&mut self, c: &Context) -> R<(bool, i32)> {
|
||||
let flag = |b: bool| (b, i32::from(b));
|
||||
if c.has("data") {
|
||||
let r = self.data_ref_named(c, 0, "source")?;
|
||||
let data = self.data_of(&r)?;
|
||||
let Some(Arg::Str(p)) = c.get("path") else {
|
||||
return Ok((false, 0));
|
||||
};
|
||||
let path = NbtPath::parse(p).map_err(horizon_client::data_cmd::path_error)?;
|
||||
let n = path.count(&data) as i32;
|
||||
return Ok((n > 0, n));
|
||||
}
|
||||
if c.has("items") || c.has("slots") {
|
||||
return self.condition_items(c);
|
||||
}
|
||||
if c.has("entity") {
|
||||
let Some(Arg::Entity(sel)) = c.get("entities").cloned() else {
|
||||
return Ok(0);
|
||||
return Ok((false, 0));
|
||||
};
|
||||
return Ok(self.select(&sel).len() as i32);
|
||||
let n = self.select(&sel).len() as i32;
|
||||
return Ok((n > 0, n));
|
||||
}
|
||||
if c.has("loaded") {
|
||||
let p = self
|
||||
.coords(c, "pos")
|
||||
.map(|co| co.block(self.source_position(), self.source_rotation()));
|
||||
return Ok(
|
||||
p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))) as i32,
|
||||
);
|
||||
return Ok(flag(p.is_some_and(|p| {
|
||||
self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))
|
||||
})));
|
||||
}
|
||||
if c.has("dimension") {
|
||||
return Ok(
|
||||
matches!(c.get("dimension"), Some(Arg::Resource(d)) if d == self.dim.id()) as i32,
|
||||
);
|
||||
return Ok(flag(
|
||||
matches!(c.get("dimension"), Some(Arg::Resource(d)) if d == self.dim.id()),
|
||||
));
|
||||
}
|
||||
if c.has("block") {
|
||||
let p = self.block_pos_arg(c, "pos")?;
|
||||
let Some(Arg::Block(b)) = c.get("block").cloned() else {
|
||||
return Ok(0);
|
||||
return Ok((false, 0));
|
||||
};
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
return Ok(self.block_matches(&b, state) as i32);
|
||||
return Ok(flag(self.block_matches(&b, state)));
|
||||
}
|
||||
Ok(0)
|
||||
if c.has("biome") {
|
||||
let p = self.block_pos_arg(c, "pos")?;
|
||||
let Some(Arg::Resource(want_biome)) = c.get("biome").cloned() else {
|
||||
return Ok((false, 0));
|
||||
};
|
||||
let name = self.biome_name_at_block(p);
|
||||
return Ok(flag(
|
||||
name.is_some_and(|n| self.biome_matches(&want_biome, &n)),
|
||||
));
|
||||
}
|
||||
if c.has("score") {
|
||||
return self.condition_score(c).map(flag);
|
||||
}
|
||||
if c.has("blocks") {
|
||||
return self.condition_blocks(c);
|
||||
}
|
||||
if c.has("predicate") {
|
||||
let Some(Arg::Resource(id)) = c.get("predicate").cloned() else {
|
||||
return Ok((false, 0));
|
||||
};
|
||||
return Ok(flag(self.check_predicate(&id)?));
|
||||
}
|
||||
Ok((false, 0))
|
||||
}
|
||||
fn condition_score(&mut self, c: &Context) -> R<bool> {
|
||||
let target = self.score_holder_names(c, "target", false)?;
|
||||
let Some(Arg::Str(to)) = c.get("targetObjective").cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if self.score.board.objective(&to).is_none() {
|
||||
return Err(err("arguments.objective.notFound", &[&to]));
|
||||
}
|
||||
let Some(a) = target
|
||||
.first()
|
||||
.and_then(|t| self.score.board.score(t, &to))
|
||||
.map(|s| s.value)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if c.has("matches") {
|
||||
let Some(Arg::IntRange((lo, hi))) = c.get("range") else {
|
||||
return Ok(false);
|
||||
};
|
||||
return Ok(lo.is_none_or(|l| a >= l) && hi.is_none_or(|h| a <= h));
|
||||
}
|
||||
let source = self.score_holder_names(c, "source", false)?;
|
||||
let Some(Arg::Str(so)) = c.get("sourceObjective").cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if self.score.board.objective(&so).is_none() {
|
||||
return Err(err("arguments.objective.notFound", &[&so]));
|
||||
}
|
||||
let Some(b) = source
|
||||
.first()
|
||||
.and_then(|t| self.score.board.score(t, &so))
|
||||
.map(|s| s.value)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let op = c.literals.last().map_or("", String::as_str);
|
||||
Ok(match op {
|
||||
"=" => a == b,
|
||||
"<" => a < b,
|
||||
"<=" => a <= b,
|
||||
">" => a > b,
|
||||
">=" => a >= b,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
/// `if blocks`: the region at `start..end` equals the one at `destination`.
|
||||
fn condition_blocks(&mut self, c: &Context) -> R<(bool, i32)> {
|
||||
let (a, b, d) = (
|
||||
self.block_pos_arg(c, "start")?,
|
||||
self.block_pos_arg(c, "end")?,
|
||||
self.block_pos_arg(c, "destination")?,
|
||||
);
|
||||
let masked = c.has("masked");
|
||||
let lo = [a[0].min(b[0]), a[1].min(b[1]), a[2].min(b[2])];
|
||||
let hi = [a[0].max(b[0]), a[1].max(b[1]), a[2].max(b[2])];
|
||||
let area = i64::from(hi[0] - lo[0] + 1)
|
||||
* i64::from(hi[1] - lo[1] + 1)
|
||||
* i64::from(hi[2] - lo[2] + 1);
|
||||
if area > 32768 {
|
||||
return Err(err("commands.execute.blocks.toobig", &[&32768, &area]));
|
||||
}
|
||||
let offset = [d[0] - lo[0], d[1] - lo[1], d[2] - lo[2]];
|
||||
let mut count = 0;
|
||||
for z in lo[2]..=hi[2] {
|
||||
for y in lo[1]..=hi[1] {
|
||||
for x in lo[0]..=hi[0] {
|
||||
let src = self.world.block(x, y, z);
|
||||
if masked && src == self.world.air {
|
||||
continue;
|
||||
}
|
||||
let (dx, dy, dz) = (x + offset[0], y + offset[1], z + offset[2]);
|
||||
if src != self.world.block(dx, dy, dz) {
|
||||
return Ok((false, 0));
|
||||
}
|
||||
let (se, de) = (
|
||||
self.world.block_entities.get(&(x, y, z)),
|
||||
self.world.block_entities.get(&(dx, dy, dz)),
|
||||
);
|
||||
if let Some(se) = se {
|
||||
let name = self.data_block_name([x, y, z]);
|
||||
let Some(de) = de else {
|
||||
return Ok((false, 0));
|
||||
};
|
||||
let st = horizon_client::save::encode_block_entity((0, 0, 0), se, &name);
|
||||
let dt = horizon_client::save::encode_block_entity((0, 0, 0), de, &name);
|
||||
if st != dt {
|
||||
return Ok((false, 0));
|
||||
}
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((true, count))
|
||||
}
|
||||
/// The biome name at a block position.
|
||||
fn biome_name_at_block(&self, p: [i32; 3]) -> Option<String> {
|
||||
let chunk = self.world.chunks.get(&(p[0] >> 4, p[2] >> 4))?;
|
||||
Some(
|
||||
self.res
|
||||
.biomes
|
||||
.get(chunk.biome(p[0], p[1], p[2]))
|
||||
.name
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
/// A biome id or `#tag` matched against a biome name.
|
||||
pub(super) fn biome_matches(&self, wanted: &str, biome: &str) -> bool {
|
||||
match wanted.strip_prefix('#') {
|
||||
Some(tag) => self.biome_tag_has(tag, biome, 0),
|
||||
None => wanted == biome,
|
||||
}
|
||||
}
|
||||
fn biome_tag_has(&self, tag: &str, biome: &str, depth: u32) -> bool {
|
||||
if depth > 8 {
|
||||
return false;
|
||||
}
|
||||
let (ns, path) = tag.split_once(':').unwrap_or(("minecraft", tag));
|
||||
let file = self
|
||||
.options
|
||||
.resources
|
||||
.join(format!("data/{ns}/tags/worldgen/biome/{path}.json"));
|
||||
let Ok(bytes) = std::fs::read(file) else {
|
||||
return self.res.mob_data.biome_has(tag, biome);
|
||||
};
|
||||
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default();
|
||||
v["values"].as_array().is_some_and(|a| {
|
||||
a.iter()
|
||||
.filter_map(|e| e.as_str())
|
||||
.any(|e| match e.strip_prefix('#') {
|
||||
Some(inner) => self.biome_tag_has(inner, biome, depth + 1),
|
||||
None => e == biome,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
//! `/item` (ItemCommands) and `if items`/`if slots`: addressing the item
|
||||
//! slots of the player, mobs, armor stands, item frames and containers.
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use horizon_client::{
|
||||
command::{CommandError, args::ItemInput},
|
||||
items::ItemStack,
|
||||
scoreboard_cmd::{Holder, Tracker},
|
||||
text::Text,
|
||||
};
|
||||
|
||||
/// One addressable slot.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(in crate::game) enum Slot {
|
||||
/// `inventory[0..36]`: hotbar then the main rows.
|
||||
Inv(usize),
|
||||
/// `armor[0..4]` (head, chest, legs, feet).
|
||||
Armor(usize),
|
||||
Offhand,
|
||||
Ender(usize),
|
||||
/// A mob's equipment by name (`mainhand`, `offhand`, `head`, ...).
|
||||
Mob(u32, &'static str),
|
||||
/// An armor stand's equipment (`ArmorStand::SLOTS` index).
|
||||
Stand(u32, usize),
|
||||
Frame(u32),
|
||||
Block([i32; 3], usize),
|
||||
}
|
||||
/// Whose slots a command addresses.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(in crate::game) enum Owner {
|
||||
Entity(Target),
|
||||
Block([i32; 3]),
|
||||
}
|
||||
|
||||
/// The player's slot names and the inventory index each addresses.
|
||||
fn player_slot_names() -> Vec<(String, usize)> {
|
||||
let mut v = Vec::new();
|
||||
for i in 0..36 {
|
||||
v.push((format!("container.{i}"), i));
|
||||
}
|
||||
for i in 0..9 {
|
||||
v.push((format!("hotbar.{i}"), i));
|
||||
}
|
||||
for i in 0..27 {
|
||||
v.push((format!("inventory.{i}"), 9 + i));
|
||||
}
|
||||
v
|
||||
}
|
||||
/// `name` against a group: `container.*` matches every `container.N`.
|
||||
fn matches_name(pattern: &str, name: &str) -> bool {
|
||||
match pattern.strip_suffix(".*") {
|
||||
Some(prefix) => name.starts_with(&format!("{prefix}.")),
|
||||
None => pattern == name,
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn owner_of(&mut self, ctx: &Context, prefix: &str, many: bool) -> R<Vec<Owner>> {
|
||||
let kind = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.filter(|l| matches!(l.as_str(), "entity" | "block"))
|
||||
.nth(usize::from(prefix == "source" && ctx.has("from")))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if kind == "block" {
|
||||
let p = self.block_pos_arg(ctx, &format!("{prefix}Pos"))?;
|
||||
return Ok(vec![Owner::Block(p)]);
|
||||
}
|
||||
let targets = self.entities(ctx, prefix, false)?;
|
||||
let _ = many;
|
||||
Ok(targets.into_iter().map(Owner::Entity).collect())
|
||||
}
|
||||
/// The slots a name (or wildcard group) addresses on an owner.
|
||||
pub(in crate::game) fn slots_named(&mut self, owner: &Owner, name: &str) -> Vec<Slot> {
|
||||
let mut out = Vec::new();
|
||||
let mut add = |s: Slot| out.push(s);
|
||||
match owner {
|
||||
Owner::Block(p) => {
|
||||
let size = match self.world.block_entities.get(&(p[0], p[1], p[2])) {
|
||||
Some(horizon_client::containers::BlockEntity::Chest(items)) => items.len(),
|
||||
_ => 0,
|
||||
};
|
||||
for i in 0..size {
|
||||
if matches_name(name, &format!("container.{i}")) {
|
||||
add(Slot::Block(*p, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
Owner::Entity(Target::Player) => {
|
||||
for (n, i) in player_slot_names() {
|
||||
if matches_name(name, &n) {
|
||||
add(Slot::Inv(i));
|
||||
}
|
||||
}
|
||||
for (i, n) in ["armor.head", "armor.chest", "armor.legs", "armor.feet"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
if matches_name(name, n) {
|
||||
add(Slot::Armor(i));
|
||||
}
|
||||
}
|
||||
if matches_name(name, "weapon") || matches_name(name, "weapon.mainhand") {
|
||||
add(Slot::Inv(self.selected));
|
||||
}
|
||||
if matches_name(name, "weapon.offhand") {
|
||||
add(Slot::Offhand);
|
||||
}
|
||||
for i in 0..27 {
|
||||
if matches_name(name, &format!("enderchest.{i}")) {
|
||||
add(Slot::Ender(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
Owner::Entity(Target::Mob(id)) => {
|
||||
for (n, key) in [
|
||||
("weapon", "mainhand"),
|
||||
("weapon.mainhand", "mainhand"),
|
||||
("weapon.offhand", "offhand"),
|
||||
("armor.head", "head"),
|
||||
("armor.chest", "chest"),
|
||||
("armor.legs", "legs"),
|
||||
("armor.feet", "feet"),
|
||||
("armor.body", "body"),
|
||||
("saddle", "saddle"),
|
||||
] {
|
||||
if matches_name(name, n) {
|
||||
add(Slot::Mob(*id, key));
|
||||
}
|
||||
}
|
||||
}
|
||||
Owner::Entity(Target::Stand(id)) => {
|
||||
for (i, key) in horizon_client::entities::ArmorStand::SLOTS
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let aliases: &[&str] = match *key {
|
||||
"mainhand" => &["weapon", "weapon.mainhand"],
|
||||
"offhand" => &["weapon.offhand"],
|
||||
"feet" => &["armor.feet"],
|
||||
"legs" => &["armor.legs"],
|
||||
"chest" => &["armor.chest"],
|
||||
_ => &["armor.head"],
|
||||
};
|
||||
if aliases.iter().any(|a| matches_name(name, a)) {
|
||||
add(Slot::Stand(*id, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
Owner::Entity(Target::Frame(id)) => {
|
||||
if matches_name(name, "container.0") || matches_name(name, "contents") {
|
||||
add(Slot::Frame(*id));
|
||||
}
|
||||
}
|
||||
Owner::Entity(_) => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub(in crate::game) fn slot_get(&self, s: &Slot) -> Option<ItemStack> {
|
||||
match s {
|
||||
Slot::Inv(i) => self.inventory.get(*i).cloned().flatten(),
|
||||
Slot::Armor(i) => self.armor.get(*i).cloned().flatten(),
|
||||
Slot::Offhand => self.offhand.clone(),
|
||||
Slot::Ender(i) => self.ender_items.get(*i).cloned().flatten(),
|
||||
Slot::Mob(id, key) => {
|
||||
let m = self.mobs.iter().find(|m| m.id == *id)?;
|
||||
let item = match *key {
|
||||
"mainhand" => &m.extra.main_hand,
|
||||
"offhand" => &m.extra.off_hand,
|
||||
"head" | "body" => &m.extra.head,
|
||||
"chest" => &m.extra.chest,
|
||||
"legs" => &m.extra.legs,
|
||||
"feet" => &m.extra.feet,
|
||||
_ => return None,
|
||||
};
|
||||
item.as_ref().map(|i| ItemStack {
|
||||
item: i.clone(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
})
|
||||
}
|
||||
Slot::Stand(id, i) => self
|
||||
.armor_stands
|
||||
.iter()
|
||||
.find(|a| a.id == *id)?
|
||||
.equipment
|
||||
.get(*i)
|
||||
.cloned()
|
||||
.flatten(),
|
||||
Slot::Frame(id) => self.item_frames.iter().find(|f| f.id == *id)?.item.clone(),
|
||||
Slot::Block(p, i) => match self.world.block_entities.get(&(p[0], p[1], p[2])) {
|
||||
Some(horizon_client::containers::BlockEntity::Chest(items)) => {
|
||||
items.get(*i).cloned().flatten()
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
/// Put a stack (or nothing) in a slot; false when the slot cannot take it.
|
||||
pub(in crate::game) fn slot_set(&mut self, s: &Slot, stack: Option<ItemStack>) -> bool {
|
||||
match s {
|
||||
Slot::Inv(i) => match self.inventory.get_mut(*i) {
|
||||
Some(slot) => {
|
||||
*slot = stack;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Slot::Armor(i) => match self.armor.get_mut(*i) {
|
||||
Some(slot) => {
|
||||
*slot = stack;
|
||||
self.apply_equipment();
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Slot::Offhand => {
|
||||
self.offhand = stack;
|
||||
true
|
||||
}
|
||||
Slot::Ender(i) => match self.ender_items.get_mut(*i) {
|
||||
Some(slot) => {
|
||||
*slot = stack;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Slot::Mob(id, key) => {
|
||||
let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id) else {
|
||||
return false;
|
||||
};
|
||||
let item = stack.map(|s| s.item);
|
||||
match *key {
|
||||
"mainhand" => m.extra.main_hand = item,
|
||||
"offhand" => m.extra.off_hand = item,
|
||||
"head" | "body" => m.extra.head = item,
|
||||
"chest" => m.extra.chest = item,
|
||||
"legs" => m.extra.legs = item,
|
||||
"feet" => m.extra.feet = item,
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
Slot::Stand(id, i) => match self
|
||||
.armor_stands
|
||||
.iter_mut()
|
||||
.find(|a| a.id == *id)
|
||||
.and_then(|a| a.equipment.get_mut(*i))
|
||||
{
|
||||
Some(slot) => {
|
||||
*slot = stack;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Slot::Frame(id) => match self.item_frames.iter_mut().find(|f| f.id == *id) {
|
||||
Some(f) => {
|
||||
f.item = stack;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Slot::Block(p, i) => match self.world.block_entities.get_mut(&(p[0], p[1], p[2])) {
|
||||
Some(horizon_client::containers::BlockEntity::Chest(items)) => {
|
||||
match items.get_mut(*i) {
|
||||
Some(slot) => {
|
||||
*slot = stack;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
fn owner_holder(&self, o: &Owner) -> Holder {
|
||||
match o {
|
||||
Owner::Entity(t) => Holder {
|
||||
name: String::new(),
|
||||
text: self.target_name(*t),
|
||||
display: None,
|
||||
},
|
||||
Owner::Block(p) => Holder {
|
||||
name: String::new(),
|
||||
text: Text::literal(format!("{}, {}, {}", p[0], p[1], p[2])),
|
||||
display: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
fn stack_name(&self, s: &ItemStack) -> Text {
|
||||
self.item_display_name(&s.item)
|
||||
}
|
||||
fn item_from_input(&self, ctx: &Context) -> R<Option<ItemStack>> {
|
||||
let Some(Arg::Item(ItemInput { id, components, .. })) = ctx.get("item").cloned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (damage, extra) = match components
|
||||
.as_deref()
|
||||
.map(horizon_client::item_data::command_components)
|
||||
{
|
||||
Some(Ok(tag)) => horizon_client::item_data::decode_components(Some(&tag)),
|
||||
Some(Err(e)) => return Err(CommandError::new(Text::literal(e))),
|
||||
None => (0, None),
|
||||
};
|
||||
let count = Self::int(ctx, "count").unwrap_or(1).max(1) as u32;
|
||||
Ok(Some(ItemStack {
|
||||
item: id.as_str().into(),
|
||||
count,
|
||||
damage,
|
||||
extra,
|
||||
}))
|
||||
}
|
||||
/// `/item replace|fill|override <target> <slots> (with <item> [count] | from <source> <slots>)`.
|
||||
pub(super) fn cmd_item(&mut self, ctx: &Context) -> R<i32> {
|
||||
let mode = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.find(|l| matches!(l.as_str(), "replace" | "fill" | "override"))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let targets = self.owner_of(ctx, "target", true)?;
|
||||
let Some(Arg::Str(slot_name)) = ctx.get("slots").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
// The items to place.
|
||||
let (items, known): (Vec<Option<ItemStack>>, Option<ItemStack>) = if ctx.has("with") {
|
||||
let stack = self.item_from_input(ctx)?;
|
||||
(vec![stack.clone()], stack)
|
||||
} else {
|
||||
let sources = self.owner_of(ctx, "source", true)?;
|
||||
let Some(Arg::Str(source_slots)) = ctx.get("sourceSlots").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut found = Vec::new();
|
||||
for o in &sources {
|
||||
for s in self.slots_named(o, &source_slots) {
|
||||
found.push(self.slot_get(&s));
|
||||
}
|
||||
}
|
||||
if found.is_empty() {
|
||||
return Err(match &sources[..] {
|
||||
[Owner::Block(p)] => err(
|
||||
"commands.item.source.not_a_container",
|
||||
&[&p[0], &p[1], &p[2]],
|
||||
),
|
||||
_ => err("commands.item.source.no_such_slot", &[&source_slots]),
|
||||
});
|
||||
}
|
||||
// A source with nothing in the slot contributes air.
|
||||
(found, None)
|
||||
};
|
||||
let mut tracker = Tracker::default();
|
||||
let mut selected = 0;
|
||||
for o in &targets {
|
||||
let slots = self.slots_named(o, &slot_name);
|
||||
if slots.is_empty() {
|
||||
if let Owner::Block(p) = o
|
||||
&& !self.world.block_entities.contains_key(&(p[0], p[1], p[2]))
|
||||
{
|
||||
return Err(err(
|
||||
"commands.item.target.not_a_container",
|
||||
&[&p[0], &p[1], &p[2]],
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
selected += slots.len();
|
||||
let mut changed = 0;
|
||||
for (i, slot) in slots.iter().enumerate() {
|
||||
// `fill` cycles through the items; `replace` stops when they
|
||||
// run out; `override` empties the rest.
|
||||
let item = match mode.as_str() {
|
||||
"fill" => items.get(i % items.len()).cloned().flatten(),
|
||||
"override" => items.get(i).cloned().flatten(),
|
||||
_ => match items.get(i) {
|
||||
Some(x) => x.clone(),
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
if self.slot_get(slot) != item && self.slot_set(slot, item) {
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
let h = self.owner_holder(o);
|
||||
tracker.track(&h, changed);
|
||||
}
|
||||
if selected == 0 {
|
||||
return Err(err("commands.item.target.no_such_slot", &[&slot_name]));
|
||||
}
|
||||
let block = matches!(targets.first(), Some(Owner::Block(_)));
|
||||
let pos = match targets.first() {
|
||||
Some(Owner::Block(p)) => *p,
|
||||
_ => [0; 3],
|
||||
};
|
||||
let zero = match &known {
|
||||
Some(k) => err(
|
||||
"commands.item.target.failed.known_item",
|
||||
&[&k.item.to_string()],
|
||||
),
|
||||
None => err("commands.item.target.failed", &[]),
|
||||
};
|
||||
let name = known.as_ref().map(|k| self.stack_name(k));
|
||||
let (message, total) = tracker.message(
|
||||
false,
|
||||
Some(zero),
|
||||
|h, count| {
|
||||
let n = Text::literal(count.to_string());
|
||||
match (&name, block) {
|
||||
(Some(item), true) => Text::translate(
|
||||
"commands.item.block.replace.success.known_item",
|
||||
&[
|
||||
n,
|
||||
Text::literal(pos[0].to_string()),
|
||||
Text::literal(pos[1].to_string()),
|
||||
Text::literal(pos[2].to_string()),
|
||||
item.clone(),
|
||||
],
|
||||
),
|
||||
(None, true) => Text::translate(
|
||||
"commands.item.block.replace.success",
|
||||
&[
|
||||
n,
|
||||
Text::literal(pos[0].to_string()),
|
||||
Text::literal(pos[1].to_string()),
|
||||
Text::literal(pos[2].to_string()),
|
||||
],
|
||||
),
|
||||
(Some(item), false) => Text::translate(
|
||||
"commands.item.entity.replace.success.single.known_item",
|
||||
&[n, h.text.clone(), item.clone()],
|
||||
),
|
||||
(None, false) => Text::translate(
|
||||
"commands.item.entity.replace.success.single",
|
||||
&[n, h.text.clone()],
|
||||
),
|
||||
}
|
||||
},
|
||||
|c, _| match &name {
|
||||
Some(item) => Text::translate(
|
||||
"commands.item.entity.replace.success.multiple.known_item",
|
||||
&[Text::literal(c.to_string()), item.clone()],
|
||||
),
|
||||
None => Text::translate(
|
||||
"commands.item.entity.replace.success.multiple",
|
||||
&[Text::literal(c.to_string())],
|
||||
),
|
||||
},
|
||||
)?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
/// `if items` and `if slots`: how many items match / how many slots.
|
||||
pub(super) fn condition_items(&mut self, c: &Context) -> R<(bool, i32)> {
|
||||
let owners = self.owner_of(c, "source", true)?;
|
||||
let Some(Arg::Str(slot_name)) = c.get("slots").cloned() else {
|
||||
return Ok((false, 0));
|
||||
};
|
||||
let predicate = match c.get("item_predicate") {
|
||||
Some(Arg::Item(p)) => Some(p.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let mut count = 0;
|
||||
for o in owners {
|
||||
let slots = self.slots_named(&o, &slot_name);
|
||||
if predicate.is_none() {
|
||||
count += slots.len() as i32;
|
||||
continue;
|
||||
}
|
||||
for s in slots {
|
||||
if let Some(stack) = self.slot_get(&s)
|
||||
&& predicate
|
||||
.as_ref()
|
||||
.is_some_and(|p| self.item_matches(p, &stack.item))
|
||||
{
|
||||
count += stack.count as i32;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((count > 0, count))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//! `/random` (RandomCommand) and `/teammsg` (TeamMsgCommand).
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use crate::game::chat::PLAYER_NAME;
|
||||
use horizon_client::text::{self, Text};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
fn millis(nanos: u64) -> String {
|
||||
format!("{:.1}", nanos as f32 / 1_000_000.0)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `/tick` (TickCommand) over the game clock.
|
||||
pub(super) fn cmd_tick(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let t = |key: &str, args: &[Text]| Text::translate(key, args);
|
||||
let lit = |s: String| Text::literal(s);
|
||||
let time = match ctx.get("time") {
|
||||
Some(Arg::Int(v)) => *v,
|
||||
_ => 1,
|
||||
};
|
||||
match id {
|
||||
"tick.rate" => {
|
||||
let rate = match ctx.get("rate") {
|
||||
Some(Arg::Float(v)) => *v,
|
||||
_ => 20.0,
|
||||
};
|
||||
self.clock.set_rate(rate);
|
||||
self.feedback(t(
|
||||
"commands.tick.rate.success",
|
||||
&[lit(format!("{rate:.1}"))],
|
||||
));
|
||||
Ok(rate as i32)
|
||||
}
|
||||
"tick.query" => {
|
||||
let rate = self.clock.rate();
|
||||
let busy = millis(self.clock.average_nanos());
|
||||
let rate_text = format!("{rate:.1}");
|
||||
if self.clock.sprinting() {
|
||||
self.feedback(t("commands.tick.status.sprinting", &[]));
|
||||
self.feedback(t(
|
||||
"commands.tick.query.rate.sprinting",
|
||||
&[lit(rate_text), lit(busy)],
|
||||
));
|
||||
} else {
|
||||
let target = self.clock.tick_duration().as_nanos() as u64;
|
||||
let status = if self.clock.frozen() {
|
||||
"commands.tick.status.frozen"
|
||||
} else if target < self.clock.average_nanos() {
|
||||
"commands.tick.status.lagging"
|
||||
} else {
|
||||
"commands.tick.status.running"
|
||||
};
|
||||
self.feedback(t(status, &[]));
|
||||
self.feedback(t(
|
||||
"commands.tick.query.rate.running",
|
||||
&[lit(rate_text), lit(busy), lit(millis(target))],
|
||||
));
|
||||
}
|
||||
let samples = self.clock.sorted_samples();
|
||||
let at = |q: f32| {
|
||||
samples
|
||||
.get(
|
||||
((samples.len() as f32 * q) as usize)
|
||||
.min(samples.len().saturating_sub(1)),
|
||||
)
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
self.feedback(t(
|
||||
"commands.tick.query.percentiles",
|
||||
&[
|
||||
lit(millis(at(0.5))),
|
||||
lit(millis(at(0.95))),
|
||||
lit(millis(at(0.99))),
|
||||
lit(samples.len().to_string()),
|
||||
],
|
||||
));
|
||||
Ok(rate as i32)
|
||||
}
|
||||
"tick.sprint" => {
|
||||
if self.clock.start_sprint(time as u32) {
|
||||
self.feedback(t("commands.tick.sprint.stop.success", &[]));
|
||||
}
|
||||
self.feedback(t("commands.tick.status.sprinting", &[]));
|
||||
Ok(1)
|
||||
}
|
||||
"tick.sprint.stop" => {
|
||||
if !self.clock.stop_sprint() {
|
||||
return Err(err("commands.tick.sprint.stop.fail", &[]));
|
||||
}
|
||||
self.feedback(t("commands.tick.sprint.stop.success", &[]));
|
||||
Ok(1)
|
||||
}
|
||||
"tick.freeze" | "tick.unfreeze" => {
|
||||
let freeze = id == "tick.freeze";
|
||||
if freeze {
|
||||
self.clock.stop_sprint();
|
||||
self.clock.stop_step();
|
||||
}
|
||||
self.clock.set_frozen(freeze);
|
||||
self.feedback(t(
|
||||
if freeze {
|
||||
"commands.tick.status.frozen"
|
||||
} else {
|
||||
"commands.tick.status.running"
|
||||
},
|
||||
&[],
|
||||
));
|
||||
Ok(i32::from(freeze))
|
||||
}
|
||||
"tick.step" => {
|
||||
if !self.clock.start_step(time as u32) {
|
||||
return Err(err("commands.tick.step.fail", &[]));
|
||||
}
|
||||
self.feedback(t("commands.tick.step.success", &[lit(time.to_string())]));
|
||||
Ok(1)
|
||||
}
|
||||
_ => {
|
||||
if !self.clock.stop_step() {
|
||||
return Err(err("commands.tick.step.stop.fail", &[]));
|
||||
}
|
||||
self.feedback(t("commands.tick.step.stop.success", &[]));
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn cmd_random(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let seed = self.level.seed;
|
||||
if id == "random.reset" {
|
||||
let sequence = match ctx.get("sequence") {
|
||||
Some(Arg::Resource(s)) => Some(s.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let int = |name: &str| match ctx.get(name) {
|
||||
Some(Arg::Int(v)) => Some(*v),
|
||||
_ => None,
|
||||
};
|
||||
let flag = |name: &str| !matches!(ctx.get(name), Some(Arg::Bool(false)));
|
||||
let name_text = |s: &str| Text::literal(s.to_owned());
|
||||
return match (sequence, int("seed")) {
|
||||
(None, None) => {
|
||||
let n = self.rand_sequences.clear();
|
||||
self.feedback(Text::translate(
|
||||
"commands.random.reset.all.success",
|
||||
&[Text::literal(n.to_string())],
|
||||
));
|
||||
Ok(n as i32)
|
||||
}
|
||||
(None, Some(salt)) => {
|
||||
self.rand_sequences.set_defaults(
|
||||
salt,
|
||||
flag("includeWorldSeed"),
|
||||
flag("includeSequenceId"),
|
||||
);
|
||||
let n = self.rand_sequences.clear();
|
||||
self.feedback(Text::translate(
|
||||
"commands.random.reset.all.success",
|
||||
&[Text::literal(n.to_string())],
|
||||
));
|
||||
Ok(n as i32)
|
||||
}
|
||||
(Some(s), None) => {
|
||||
self.rand_sequences.reset(&s, seed);
|
||||
self.feedback(Text::translate(
|
||||
"commands.random.reset.success",
|
||||
&[name_text(&s)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
(Some(s), Some(salt)) => {
|
||||
self.rand_sequences.reset_with(
|
||||
&s,
|
||||
seed,
|
||||
salt,
|
||||
flag("includeWorldSeed"),
|
||||
flag("includeSequenceId"),
|
||||
);
|
||||
self.feedback(Text::translate(
|
||||
"commands.random.reset.success",
|
||||
&[name_text(&s)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
};
|
||||
}
|
||||
let Some(Arg::IntRange((lo, hi))) = ctx.get("range").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (min, max) = (lo.unwrap_or(i32::MIN), hi.unwrap_or(i32::MAX));
|
||||
let span = i64::from(max) - i64::from(min);
|
||||
if span == 0 {
|
||||
return Err(err("commands.random.error.range_too_small", &[]));
|
||||
}
|
||||
if span >= i64::from(i32::MAX) {
|
||||
return Err(err("commands.random.error.range_too_large", &[]));
|
||||
}
|
||||
let value = match ctx.get("sequence") {
|
||||
Some(Arg::Resource(s)) => {
|
||||
let s = s.clone();
|
||||
self.rand_sequences
|
||||
.get(&s, seed)
|
||||
.next_int_between_inclusive(min, max)
|
||||
}
|
||||
_ => self.world.random.next_int_between_inclusive(min, max),
|
||||
}
|
||||
.unwrap_or(min);
|
||||
if id == "random.roll" {
|
||||
let who = self.target_name(
|
||||
self.command_source
|
||||
.and_then(|s| s.entity)
|
||||
.unwrap_or(Target::Player),
|
||||
);
|
||||
self.system_message(Text::translate(
|
||||
"commands.random.roll",
|
||||
&[
|
||||
who,
|
||||
Text::literal(value.to_string()),
|
||||
Text::literal(min.to_string()),
|
||||
Text::literal(max.to_string()),
|
||||
],
|
||||
));
|
||||
} else {
|
||||
self.feedback(Text::translate(
|
||||
"commands.random.sample.success",
|
||||
&[Text::literal(value.to_string())],
|
||||
));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
/// `/teammsg`: the executor's team hears the message.
|
||||
pub(super) fn cmd_teammsg(&mut self, ctx: &Context) -> R<i32> {
|
||||
let entity = match self.command_source {
|
||||
Some(s) => s.entity,
|
||||
None => Some(Target::Player),
|
||||
};
|
||||
let Some(entity) = entity else {
|
||||
return Err(err("permissions.requires.entity", &[]));
|
||||
};
|
||||
let Some(holder) = self.holder_name(entity) else {
|
||||
return Err(err("permissions.requires.entity", &[]));
|
||||
};
|
||||
let Some(team) = self.score.board.players_team(&holder).cloned() else {
|
||||
return Err(err("commands.teammsg.failed.noteam", &[]));
|
||||
};
|
||||
// Only the local player can be on the receiving end.
|
||||
let player_name = PLAYER_NAME.to_owned();
|
||||
let player_in_team = self
|
||||
.score
|
||||
.board
|
||||
.players_team(&player_name)
|
||||
.is_some_and(|t| t.name == team.name);
|
||||
if !player_in_team {
|
||||
return Ok(0);
|
||||
}
|
||||
let raw = match ctx.get("message") {
|
||||
Some(Arg::Str(m)) => m.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let message = self.expand_selectors(&raw);
|
||||
let hover = text::Style {
|
||||
hover: Some(Box::new(Text::translate("chat.type.team.hover", &[]))),
|
||||
suggest: Some("/teammsg ".into()),
|
||||
..text::Style::default()
|
||||
};
|
||||
let team_name = team.formatted_display_name().with_style(&hover);
|
||||
let sender = self.target_name(entity);
|
||||
let key = if entity == Target::Player {
|
||||
"chat.type.team.sent"
|
||||
} else {
|
||||
"chat.type.team.text"
|
||||
};
|
||||
self.system_message(Text::translate(key, &[team_name, sender, message]));
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! `/place template` (PlaceCommand): a saved structure template placed with
|
||||
//! rotation, mirroring and integrity.
|
||||
use super::{Arg, Context, Game, R, err};
|
||||
use horizon_client::{save, text::Text};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use horizon_world::{
|
||||
compression::Compression,
|
||||
nbt::{self, Limits, Tag},
|
||||
worldgen::structure::{Mirror, Rotation, StateTransforms, StructureTemplate},
|
||||
};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
fn num(n: impl std::fmt::Display) -> Text {
|
||||
Text::literal(n.to_string())
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn state_transforms(&self) -> Option<&'static StateTransforms> {
|
||||
static TRANSFORMS: OnceLock<Option<StateTransforms>> = OnceLock::new();
|
||||
TRANSFORMS
|
||||
.get_or_init(|| {
|
||||
let json = std::fs::read_to_string(
|
||||
self.options
|
||||
.resources
|
||||
.join("worldgen/blocks/structure-blocks.json"),
|
||||
)
|
||||
.ok()?;
|
||||
StateTransforms::from_json(&json, self.res.assets.registry.len()).ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
/// A template by id: a structure block's save in the world, then the
|
||||
/// vanilla templates.
|
||||
fn load_template(&self, id: &str) -> Option<Arc<StructureTemplate>> {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
let candidates = [
|
||||
self.world_root
|
||||
.join("generated")
|
||||
.join(ns)
|
||||
.join("structures")
|
||||
.join(format!("{path}.nbt")),
|
||||
self.options
|
||||
.resources
|
||||
.join("worldgen/structure")
|
||||
.join(ns)
|
||||
.join(format!("{path}.nbt")),
|
||||
];
|
||||
let transforms = self.state_transforms()?;
|
||||
for file in candidates {
|
||||
let Ok(bytes) = std::fs::read(&file) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(raw) = Compression::Gzip.decode(&bytes, 1 << 28) else {
|
||||
continue;
|
||||
};
|
||||
let Ok((named, _)) = nbt::read_named(
|
||||
&raw,
|
||||
Limits {
|
||||
max_bytes: 1 << 28,
|
||||
..Limits::default()
|
||||
},
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
return Some(Arc::new(StructureTemplate::from_nbt(
|
||||
&named.tag,
|
||||
self.res.assets.registry,
|
||||
transforms,
|
||||
)));
|
||||
}
|
||||
None
|
||||
}
|
||||
pub(super) fn cmd_place(&mut self, ctx: &Context) -> R<i32> {
|
||||
let Some(Arg::Resource(id)) = ctx.get("template").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let pos = if ctx.get("pos").is_some() {
|
||||
self.block_pos_arg(ctx, "pos")?
|
||||
} else {
|
||||
let p = self.source_position();
|
||||
[
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
]
|
||||
};
|
||||
let rotation = match ctx.get("rotation") {
|
||||
Some(Arg::Str(r)) => Rotation::from_name(r).unwrap_or(Rotation::None),
|
||||
_ => Rotation::None,
|
||||
};
|
||||
let mirror = match ctx.get("mirror") {
|
||||
Some(Arg::Str(m)) => match m.as_str() {
|
||||
"left_right" => Mirror::LeftRight,
|
||||
"front_back" => Mirror::FrontBack,
|
||||
_ => Mirror::None,
|
||||
},
|
||||
_ => Mirror::None,
|
||||
};
|
||||
let integrity = match ctx.get("integrity") {
|
||||
Some(Arg::Float(f)) => *f,
|
||||
_ => 1.0,
|
||||
};
|
||||
let seed = match ctx.get("seed") {
|
||||
Some(Arg::Int(s)) => i64::from(*s),
|
||||
_ => 0,
|
||||
};
|
||||
let strict = ctx.has("strict");
|
||||
let template = self
|
||||
.load_template(&id)
|
||||
.filter(|t| !t.palettes().is_empty())
|
||||
.ok_or_else(|| err("commands.place.template.invalid", &[&id]))?;
|
||||
let transforms = self
|
||||
.state_transforms()
|
||||
.ok_or_else(|| err("commands.place.template.invalid", &[&id]))?;
|
||||
let mut random = LegacyRandom::new(if seed == 0 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(1, |d| d.as_millis() as i64)
|
||||
} else {
|
||||
seed
|
||||
});
|
||||
let palette = template.palette_index(&mut random);
|
||||
let blocks = template.palettes()[palette].blocks().to_vec();
|
||||
let mut placed = 0;
|
||||
for b in &blocks {
|
||||
if integrity < 1.0 && random.next_float() > integrity {
|
||||
continue;
|
||||
}
|
||||
let t = StructureTemplate::transform(b.pos, mirror, rotation, [0, 0, 0]);
|
||||
let at = [pos[0] + t[0], pos[1] + t[1], pos[2] + t[2]];
|
||||
if !self.world.chunks.contains_key(&(at[0] >> 4, at[2] >> 4)) {
|
||||
continue;
|
||||
}
|
||||
let state = transforms.rotate(transforms.mirror(b.state, mirror), rotation);
|
||||
if self.place_state(at, state, strict).is_ok() {
|
||||
placed += 1;
|
||||
}
|
||||
if let Some(data) = &b.nbt {
|
||||
let mut tag = Tag::Compound(data.clone());
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
c.insert("x".into(), Tag::Int(at[0]));
|
||||
c.insert("y".into(), Tag::Int(at[1]));
|
||||
c.insert("z".into(), Tag::Int(at[2]));
|
||||
}
|
||||
if let Some((_, entity)) = save::decode_block_entity(&tag) {
|
||||
self.world
|
||||
.block_entities
|
||||
.insert((at[0], at[1], at[2]), entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Entities saved with the template.
|
||||
for e in &template.entities {
|
||||
let p = StructureTemplate::transform_vec(e.pos, mirror, rotation, [0, 0, 0]);
|
||||
let at = [
|
||||
f64::from(pos[0]) + p[0],
|
||||
f64::from(pos[1]) + p[1],
|
||||
f64::from(pos[2]) + p[2],
|
||||
];
|
||||
let mut tag = Tag::Compound(e.nbt.clone());
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
c.insert(
|
||||
"Pos".into(),
|
||||
Tag::List(at.iter().map(|v| Tag::Double(v.to_bits())).collect()),
|
||||
);
|
||||
c.remove(&"UUID".into());
|
||||
}
|
||||
self.spawn_entity_from_nbt(tag);
|
||||
}
|
||||
if placed == 0 {
|
||||
return Err(err("commands.place.template.failed", &[]));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.place.template.success",
|
||||
&[Text::literal(id), num(pos[0]), num(pos[1]), num(pos[2])],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! `RaidCommand`: `/raid start|stop|check|spawnleader|setomen|glow|sound`.
|
||||
use super::{Game, R, Text, err};
|
||||
use horizon_client::{command::Context, mobs::raider};
|
||||
|
||||
impl Game<'_> {
|
||||
pub(in crate::game) fn cmd_raid(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let Some(player) = self.player.as_ref().map(|p| p.position) else {
|
||||
return Ok(0);
|
||||
};
|
||||
let at = [
|
||||
player.x.floor() as i32,
|
||||
player.y.floor() as i32,
|
||||
player.z.floor() as i32,
|
||||
];
|
||||
let fail = |game: &mut Self, message: &str| {
|
||||
game.command_failure(Text::literal(message));
|
||||
};
|
||||
match id {
|
||||
"raid.start" => {
|
||||
if self.raiding_nearby(at).is_some() {
|
||||
fail(self, "Raid already started close by");
|
||||
return Ok(-1);
|
||||
}
|
||||
let level = Self::int(ctx, "omenlvl").unwrap_or(0);
|
||||
match self.raid_command_create(at, level) {
|
||||
true => self.feedback(Text::literal("Created a raid in your local village")),
|
||||
false => fail(self, "Failed to create a raid in your local village"),
|
||||
}
|
||||
Ok(1)
|
||||
}
|
||||
"raid.stop" => match self.raiding_nearby(at) {
|
||||
Some(raid) => {
|
||||
self.raid_command_stop(raid);
|
||||
self.feedback(Text::literal("Stopped raid"));
|
||||
Ok(1)
|
||||
}
|
||||
None => {
|
||||
fail(self, "No raid here");
|
||||
Ok(-1)
|
||||
}
|
||||
},
|
||||
"raid.check" => match self.raiding_nearby(at).filter(|id| self.raid_started(*id)) {
|
||||
Some(raid) => {
|
||||
self.feedback(Text::literal("Found a started raid!"));
|
||||
let status = self.raid_status_text(raid);
|
||||
self.feedback(Text::literal(&status));
|
||||
Ok(1)
|
||||
}
|
||||
None => {
|
||||
fail(self, "Found no started raids");
|
||||
Ok(0)
|
||||
}
|
||||
},
|
||||
"raid.spawnleader" => {
|
||||
let kind = "minecraft:pillager";
|
||||
match self.spawn_mob_for(kind, [player.x, player.y, player.z], true, true) {
|
||||
Some(id) => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
raider::set_patrol_leader(m, true);
|
||||
raider::finalize(m, raider::Reason::Other);
|
||||
}
|
||||
self.feedback(Text::literal("Spawned a raid captain"));
|
||||
Ok(1)
|
||||
}
|
||||
None => {
|
||||
fail(self, "Pillager failed to spawn");
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
"raid.setomen" => {
|
||||
let level = Self::int(ctx, "level").unwrap_or(0);
|
||||
let Some(raid) = self.raiding_nearby(at) else {
|
||||
fail(self, "No raid found here");
|
||||
return Ok(1);
|
||||
};
|
||||
if level > horizon_client::raid::MAX_OMEN_LEVEL {
|
||||
fail(
|
||||
self,
|
||||
&format!(
|
||||
"Sorry, the max raid omen level you can set is {}",
|
||||
horizon_client::raid::MAX_OMEN_LEVEL
|
||||
),
|
||||
);
|
||||
} else {
|
||||
let before = self.raid_set_omen(raid, level);
|
||||
self.feedback(Text::literal(format!(
|
||||
"Changed village's raid omen level from {before} to {level}"
|
||||
)));
|
||||
}
|
||||
Ok(1)
|
||||
}
|
||||
"raid.glow" => {
|
||||
if let Some(raid) = self.raiding_nearby(at) {
|
||||
self.raid_glow(raid);
|
||||
}
|
||||
Ok(1)
|
||||
}
|
||||
"raid.sound" => {
|
||||
let at = [player.x + 5.0, player.y, player.z];
|
||||
self.audio
|
||||
.play("minecraft:event.raid.horn", Some(at), 1.0, 1.0);
|
||||
Ok(1)
|
||||
}
|
||||
_ => Err(err("commands.help.failed", &[])),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
//! `/forceload`, `/fillbiome`, `/worldborder` and `/loot`.
|
||||
use super::{Arg, Context, Game, R, Target, err, items::Owner};
|
||||
use horizon_client::{
|
||||
chunk::{HEIGHT, MIN_Y},
|
||||
items::ItemStack,
|
||||
scoreboard_cmd::{Holder, Tracker},
|
||||
text::Text,
|
||||
worldborder::MAX_SIZE,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
fn num(n: impl std::fmt::Display) -> Text {
|
||||
Text::literal(n.to_string())
|
||||
}
|
||||
fn chunk_text(x: i32, z: i32) -> Text {
|
||||
Text::literal(format!("[{x}, {z}]"))
|
||||
}
|
||||
fn holder(text: Text) -> Holder {
|
||||
Holder {
|
||||
name: String::new(),
|
||||
text,
|
||||
display: None,
|
||||
}
|
||||
}
|
||||
fn ticks_to_seconds(ticks: i64) -> String {
|
||||
format!("{:.2}", ticks as f64 / 20.0)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
// ---- /forceload ----------------------------------------------------------
|
||||
|
||||
fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
|
||||
let c = self
|
||||
.coords(ctx, name)
|
||||
.ok_or_else(|| err("argument.pos2d.incomplete", &[]))?;
|
||||
let p = self.resolve_coords(&c);
|
||||
Ok([p[0].floor() as i32, p[2].floor() as i32])
|
||||
}
|
||||
pub(super) fn cmd_forceload(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let dim = Text::literal(self.dim.id());
|
||||
match id {
|
||||
"forceload.query" if ctx.get("pos").is_none() => {
|
||||
let mut forced: Vec<(i32, i32)> = self.streaming.forced.iter().copied().collect();
|
||||
forced.sort_unstable();
|
||||
if forced.is_empty() {
|
||||
self.command_failure(Text::translate("commands.forceload.added.none", &[dim]));
|
||||
return Ok(0);
|
||||
}
|
||||
let list = forced
|
||||
.iter()
|
||||
.map(|(x, z)| format!("[{x}, {z}]"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let message = if forced.len() == 1 {
|
||||
Text::translate(
|
||||
"commands.forceload.list.single",
|
||||
&[dim, Text::literal(list)],
|
||||
)
|
||||
} else {
|
||||
Text::translate(
|
||||
"commands.forceload.list.multiple",
|
||||
&[num(forced.len()), dim, Text::literal(list)],
|
||||
)
|
||||
};
|
||||
self.feedback(message);
|
||||
Ok(forced.len() as i32)
|
||||
}
|
||||
"forceload.query" => {
|
||||
let [x, z] = self.column_arg(ctx, "pos")?;
|
||||
let key = (x >> 4, z >> 4);
|
||||
if self.streaming.forced.contains(&key) {
|
||||
self.feedback(Text::translate(
|
||||
"commands.forceload.query.success",
|
||||
&[chunk_text(key.0, key.1), dim],
|
||||
));
|
||||
Ok(1)
|
||||
} else {
|
||||
Err(err(
|
||||
"commands.forceload.query.failure",
|
||||
&[&chunk_text(key.0, key.1).plain(), &dim.plain()],
|
||||
))
|
||||
}
|
||||
}
|
||||
"forceload.remove.all" => {
|
||||
self.streaming.forced.clear();
|
||||
self.feedback(Text::translate("commands.forceload.removed.all", &[dim]));
|
||||
Ok(0)
|
||||
}
|
||||
_ => {
|
||||
let add = id == "forceload.add";
|
||||
let from = self.column_arg(ctx, "from")?;
|
||||
let to = if ctx.get("to").is_some() {
|
||||
self.column_arg(ctx, "to")?
|
||||
} else {
|
||||
from
|
||||
};
|
||||
let (min_x, max_x) = (from[0].min(to[0]), from[0].max(to[0]));
|
||||
let (min_z, max_z) = (from[1].min(to[1]), from[1].max(to[1]));
|
||||
if min_x < -30_000_000
|
||||
|| min_z < -30_000_000
|
||||
|| max_x >= 30_000_000
|
||||
|| max_z >= 30_000_000
|
||||
{
|
||||
return Err(err("argument.pos.outofworld", &[]));
|
||||
}
|
||||
let (cx0, cx1, cz0, cz1) = (min_x >> 4, max_x >> 4, min_z >> 4, max_z >> 4);
|
||||
let count = i64::from(cx1 - cx0 + 1) * i64::from(cz1 - cz0 + 1);
|
||||
if count > 256 {
|
||||
return Err(err("commands.forceload.toobig", &[&256, &count]));
|
||||
}
|
||||
let mut tracker = Tracker::default();
|
||||
for x in cx0..=cx1 {
|
||||
for z in cz0..=cz1 {
|
||||
let changed = if add {
|
||||
self.streaming.forced.insert((x, z))
|
||||
} else {
|
||||
self.streaming.forced.remove(&(x, z))
|
||||
};
|
||||
tracker.track(&holder(chunk_text(x, z)), i32::from(changed));
|
||||
}
|
||||
}
|
||||
let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1));
|
||||
let verb = if add { "added" } else { "removed" };
|
||||
let (message, total) = tracker.message(
|
||||
false,
|
||||
Some(err(&format!("commands.forceload.{verb}.failure"), &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
&format!("commands.forceload.{verb}.single"),
|
||||
&[h.text.clone(), dim.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
&format!("commands.forceload.{verb}.multiple"),
|
||||
&[num(c), dim.clone(), lo.clone(), hi.clone()],
|
||||
)
|
||||
},
|
||||
)?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- /fillbiome ----------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_fillbiome(&mut self, ctx: &Context) -> R<i32> {
|
||||
let (Some(Arg::Resource(biome)), from, to) = (
|
||||
ctx.get("biome").cloned(),
|
||||
self.coords(ctx, "from"),
|
||||
self.coords(ctx, "to"),
|
||||
) else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (Some(from), Some(to)) = (from, to) else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (src_pos, src_rot) = (self.source_position(), self.source_rotation());
|
||||
let (a, b) = (from.block(src_pos, src_rot), to.block(src_pos, src_rot));
|
||||
// Quantize to biome cells (`QuartPos`), then work with the box.
|
||||
let q = |v: i32| (v >> 2) << 2;
|
||||
let lo = [
|
||||
q(a[0]).min(q(b[0])),
|
||||
q(a[1]).min(q(b[1])),
|
||||
q(a[2]).min(q(b[2])),
|
||||
];
|
||||
let hi = [
|
||||
q(a[0]).max(q(b[0])),
|
||||
q(a[1]).max(q(b[1])),
|
||||
q(a[2]).max(q(b[2])),
|
||||
];
|
||||
let volume = i64::from(hi[0] - lo[0] + 1)
|
||||
* i64::from(hi[1] - lo[1] + 1)
|
||||
* i64::from(hi[2] - lo[2] + 1);
|
||||
let limit = self.ui.rules.int("max_block_modifications");
|
||||
if volume > i64::from(limit) {
|
||||
return Err(err("commands.fillbiome.toobig", &[&limit, &volume]));
|
||||
}
|
||||
let Some(target) = self.res.biomes.list.iter().position(|b| b.name == biome) else {
|
||||
return Err(err(
|
||||
"argument.resource.not_found",
|
||||
&[&biome, &"minecraft:worldgen/biome"],
|
||||
));
|
||||
};
|
||||
let filter = match ctx.get("filter") {
|
||||
Some(Arg::Resource(f)) => Some(f.clone()),
|
||||
_ => None,
|
||||
};
|
||||
for cz in (lo[2] >> 4)..=(hi[2] >> 4) {
|
||||
for cx in (lo[0] >> 4)..=(hi[0] >> 4) {
|
||||
if !self.world.chunks.contains_key(&(cx, cz)) {
|
||||
return Err(err("argument.pos.unloaded", &[]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut changed = 0;
|
||||
let mut touched = std::collections::HashSet::new();
|
||||
for z in (lo[2]..=hi[2]).step_by(4) {
|
||||
for y in (lo[1]..=hi[1]).step_by(4) {
|
||||
for x in (lo[0]..=hi[0]).step_by(4) {
|
||||
let key = (x >> 4, z >> 4);
|
||||
let Some(chunk) = self.world.chunks.get(&key) else {
|
||||
continue;
|
||||
};
|
||||
let current = chunk.biome(x, y, z);
|
||||
let current_name = &self.res.biomes.list[usize::from(current)].name;
|
||||
if let Some(f) = &filter
|
||||
&& !self.biome_matches(f, current_name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if usize::from(current) == target {
|
||||
continue;
|
||||
}
|
||||
let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1);
|
||||
let index = (qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize;
|
||||
if let Some(chunk) = self.world.chunks.get_mut(&key) {
|
||||
let chunk = std::sync::Arc::make_mut(chunk);
|
||||
std::sync::Arc::make_mut(&mut chunk.biomes)[index] = target as u16;
|
||||
}
|
||||
touched.insert(key);
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed == 0 {
|
||||
return Err(err("commands.fillbiome.no_changes", &[]));
|
||||
}
|
||||
for key in &touched {
|
||||
self.world.modified.insert(*key);
|
||||
for sy in 0..horizon_client::chunk::SECTIONS as i32 {
|
||||
self.world.dirty_sections.insert((key.0, sy, key.1));
|
||||
}
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.fillbiome.success.count",
|
||||
&[
|
||||
num(changed),
|
||||
num(lo[0]),
|
||||
num(lo[1]),
|
||||
num(lo[2]),
|
||||
num(hi[0]),
|
||||
num(hi[1]),
|
||||
num(hi[2]),
|
||||
],
|
||||
));
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
// ---- /worldborder -----------------------------------------------------------------------
|
||||
|
||||
/// Every tick: the size change, the wall the player cannot pass and
|
||||
/// damage outside the border.
|
||||
pub(in crate::game) fn tick_worldborder(&mut self) {
|
||||
self.border.tick();
|
||||
let Some((px, pz, half)) = self.player.as_ref().map(|p| {
|
||||
(
|
||||
p.position.x,
|
||||
p.position.z,
|
||||
f64::from(p.dimensions.width) / 2.0,
|
||||
)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let inside = self.border.contains(px - half, pz - half)
|
||||
&& self.border.contains(px + half, pz + half);
|
||||
if inside {
|
||||
return;
|
||||
}
|
||||
let dist = self.border.distance(px, pz) + self.border.safe_zone;
|
||||
if dist < 0.0 && self.border.damage_per_block > 0.0 && self.ticks.is_multiple_of(10) {
|
||||
let amount = (-dist * self.border.damage_per_block).floor().max(1.0) as f32;
|
||||
self.hurt_player_by("minecraft:outside_border", amount);
|
||||
}
|
||||
// From inside the border the wall stops movement.
|
||||
if self.border.distance(px, pz) >= 0.0 {
|
||||
let [x, z] = self.border.clamp(px, pz, half);
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
if x != px {
|
||||
p.velocity.x = 0.0;
|
||||
}
|
||||
if z != pz {
|
||||
p.velocity.z = 0.0;
|
||||
}
|
||||
p.position.x = x;
|
||||
p.position.z = z;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn cmd_worldborder(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let float2 = |v: f64| format!("{v:.2}");
|
||||
let double = match ctx.get("distance") {
|
||||
Some(Arg::Double(d)) => *d,
|
||||
_ => 0.0,
|
||||
};
|
||||
let time = match ctx.get("time") {
|
||||
Some(Arg::Int(t)) => i64::from(*t),
|
||||
_ => 0,
|
||||
};
|
||||
match id {
|
||||
"worldborder.get" => {
|
||||
let size = self.border.size();
|
||||
self.feedback(Text::translate(
|
||||
"commands.worldborder.get",
|
||||
&[Text::literal(format!("{size:.0}"))],
|
||||
));
|
||||
Ok((size + 0.5).floor() as i32)
|
||||
}
|
||||
"worldborder.set" | "worldborder.add" => {
|
||||
let current = self.border.size();
|
||||
let distance = if id == "worldborder.add" {
|
||||
current + double
|
||||
} else {
|
||||
double
|
||||
};
|
||||
if current == distance {
|
||||
return Err(err("commands.worldborder.set.failed.nochange", &[]));
|
||||
}
|
||||
if distance < 1.0 {
|
||||
return Err(err("commands.worldborder.set.failed.small", &[]));
|
||||
}
|
||||
if distance > MAX_SIZE {
|
||||
return Err(err("commands.worldborder.set.failed.big", &[&"5.999997E7"]));
|
||||
}
|
||||
let shown = Text::literal(format!("{distance:.1}"));
|
||||
if time > 0 {
|
||||
self.border.lerp_to(distance, time);
|
||||
let key = if distance > current {
|
||||
"commands.worldborder.set.grow"
|
||||
} else {
|
||||
"commands.worldborder.set.shrink"
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
key,
|
||||
&[shown, Text::literal(ticks_to_seconds(time))],
|
||||
));
|
||||
} else {
|
||||
self.border.set_size(distance);
|
||||
self.feedback(Text::translate(
|
||||
"commands.worldborder.set.immediate",
|
||||
&[shown],
|
||||
));
|
||||
}
|
||||
Ok((distance - current) as i32)
|
||||
}
|
||||
"worldborder.center" => {
|
||||
let p = self
|
||||
.position_arg(ctx, "pos")
|
||||
.unwrap_or_else(|| self.source_position());
|
||||
let (x, z) = (p[0], p[2]);
|
||||
if self.border.center == [x, z] {
|
||||
return Err(err("commands.worldborder.center.failed", &[]));
|
||||
}
|
||||
if x.abs() > 2.999_998_4e7 || z.abs() > 2.999_998_4e7 {
|
||||
return Err(err(
|
||||
"commands.worldborder.set.failed.far",
|
||||
&[&"2.9999984E7"],
|
||||
));
|
||||
}
|
||||
self.border.center = [x, z];
|
||||
self.feedback(Text::translate(
|
||||
"commands.worldborder.center.success",
|
||||
&[Text::literal(float2(x)), Text::literal(float2(z))],
|
||||
));
|
||||
Ok(0)
|
||||
}
|
||||
"worldborder.damage.amount" | "worldborder.damage.buffer" => {
|
||||
let amount = id.ends_with("amount");
|
||||
let value = match ctx.get(if amount { "damagePerBlock" } else { "distance" }) {
|
||||
Some(Arg::Float(v)) => f64::from(*v),
|
||||
_ => 0.0,
|
||||
};
|
||||
let slot = if amount {
|
||||
&mut self.border.damage_per_block
|
||||
} else {
|
||||
&mut self.border.safe_zone
|
||||
};
|
||||
if *slot == value {
|
||||
return Err(err(
|
||||
if amount {
|
||||
"commands.worldborder.damage.amount.failed"
|
||||
} else {
|
||||
"commands.worldborder.damage.buffer.failed"
|
||||
},
|
||||
&[],
|
||||
));
|
||||
}
|
||||
*slot = value;
|
||||
self.feedback(Text::translate(
|
||||
if amount {
|
||||
"commands.worldborder.damage.amount.success"
|
||||
} else {
|
||||
"commands.worldborder.damage.buffer.success"
|
||||
},
|
||||
&[Text::literal(float2(value))],
|
||||
));
|
||||
Ok(value as i32)
|
||||
}
|
||||
"worldborder.warning.distance" => {
|
||||
let d = match ctx.get("distance") {
|
||||
Some(Arg::Int(v)) => *v,
|
||||
_ => 0,
|
||||
};
|
||||
if self.border.warning_distance == d {
|
||||
return Err(err("commands.worldborder.warning.distance.failed", &[]));
|
||||
}
|
||||
self.border.warning_distance = d;
|
||||
self.feedback(Text::translate(
|
||||
"commands.worldborder.warning.distance.success",
|
||||
&[num(d)],
|
||||
));
|
||||
Ok(d)
|
||||
}
|
||||
_ => {
|
||||
let ticks = match ctx.get("time") {
|
||||
Some(Arg::Int(v)) => *v,
|
||||
_ => 0,
|
||||
};
|
||||
if self.border.warning_time == ticks {
|
||||
return Err(err("commands.worldborder.warning.time.failed", &[]));
|
||||
}
|
||||
self.border.warning_time = ticks;
|
||||
self.feedback(Text::translate(
|
||||
"commands.worldborder.warning.time.success",
|
||||
&[Text::literal(ticks_to_seconds(i64::from(ticks)))],
|
||||
));
|
||||
Ok(ticks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- /loot ---------------------------------------------------------------------------------
|
||||
|
||||
fn tool_stack(&mut self, ctx: &Context) -> R<Option<ItemStack>> {
|
||||
if let Some(Arg::Item(p)) = ctx.get("tool") {
|
||||
return Ok(Some(ItemStack {
|
||||
item: p.id.as_str().into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
}));
|
||||
}
|
||||
let entity = self
|
||||
.command_source
|
||||
.and_then(|s| s.entity)
|
||||
.unwrap_or(Target::Player);
|
||||
let slot = if ctx.has("offhand") {
|
||||
"weapon.offhand"
|
||||
} else {
|
||||
"weapon.mainhand"
|
||||
};
|
||||
Ok(self
|
||||
.slots_named(&Owner::Entity(entity), slot)
|
||||
.first()
|
||||
.and_then(|s| self.slot_get(s)))
|
||||
}
|
||||
pub(super) fn cmd_loot(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
// The drops.
|
||||
let (drops, table): (Vec<ItemStack>, Option<String>) = match id {
|
||||
"loot.loot" | "loot.fish" => {
|
||||
let Some(Arg::Resource(table)) = ctx.get("loot_table").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
if !self.res.items.has_loot_table(&table) {
|
||||
return Err(err("argument.resource_or_id.failed_to_parse", &[&table]));
|
||||
}
|
||||
let held = if id == "loot.fish" {
|
||||
self.tool_stack(ctx)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let drops =
|
||||
self.res
|
||||
.items
|
||||
.loot_table(&table, false, held.as_ref(), &mut self.world.random);
|
||||
(drops, None)
|
||||
}
|
||||
"loot.kill" => {
|
||||
let targets = self.entities(ctx, "target", false)?;
|
||||
let Some(t) = targets.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let ty = self.target_type(t);
|
||||
let table = format!("minecraft:entities/{}", ty.trim_start_matches("minecraft:"));
|
||||
if t == Target::Player || !self.res.items.has_loot_table(&table) {
|
||||
return Err(err(
|
||||
"commands.drop.no_loot_table.entity",
|
||||
&[&self.target_name(t).plain()],
|
||||
));
|
||||
}
|
||||
let by_player = matches!(
|
||||
self.command_source.map(|s| s.entity),
|
||||
None | Some(Some(Target::Player))
|
||||
);
|
||||
let held = self.slot_get(&super::items::Slot::Inv(self.selected));
|
||||
let drops = self.res.items.entity_drops(
|
||||
&ty,
|
||||
by_player,
|
||||
held.as_ref(),
|
||||
&mut self.world.random,
|
||||
);
|
||||
(drops, Some(table))
|
||||
}
|
||||
_ => {
|
||||
// loot mine
|
||||
let p = self.block_pos_arg(ctx, "pos")?;
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
let name = self.data_block_name(p);
|
||||
let table = format!("minecraft:blocks/{}", name.trim_start_matches("minecraft:"));
|
||||
if !self.res.items.has_loot_table(&table) {
|
||||
return Err(err("commands.drop.no_loot_table.block", &[&name]));
|
||||
}
|
||||
let tool = self.tool_stack(ctx)?;
|
||||
let drops = self.res.items.block_drops(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
tool.as_ref(),
|
||||
&mut self.world.random,
|
||||
);
|
||||
(drops, Some(table))
|
||||
}
|
||||
};
|
||||
let drops: Vec<ItemStack> = drops.into_iter().filter(|d| d.count > 0).collect();
|
||||
// Where they go.
|
||||
let mut used: Vec<ItemStack> = Vec::new();
|
||||
let literals = &ctx.literals;
|
||||
if literals.iter().any(|l| l == "give") {
|
||||
for d in &drops {
|
||||
for &t in &self.entities(ctx, "players", true)? {
|
||||
if t != Target::Player {
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = self.give(d.clone()) {
|
||||
let p = self.source_position();
|
||||
self.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0; 3], 0);
|
||||
}
|
||||
used.push(d.clone());
|
||||
}
|
||||
}
|
||||
} else if literals.iter().any(|l| l == "spawn") {
|
||||
let at = self
|
||||
.position_arg(ctx, "targetPos")
|
||||
.unwrap_or_else(|| self.source_position());
|
||||
for d in &drops {
|
||||
let r = &mut self.world.random;
|
||||
let v = [
|
||||
r.next_double() * 0.2 - 0.1,
|
||||
0.2,
|
||||
r.next_double() * 0.2 - 0.1,
|
||||
];
|
||||
self.spawn_item(d.clone(), at, v, 10);
|
||||
used.push(d.clone());
|
||||
}
|
||||
} else if literals.iter().any(|l| l == "insert") {
|
||||
let p = self.block_pos_arg(ctx, "targetPos")?;
|
||||
let owner = Owner::Block(p);
|
||||
let slots = self.slots_named(&owner, "container.*");
|
||||
if slots.is_empty() {
|
||||
return Err(err(
|
||||
"commands.item.target.not_a_container",
|
||||
&[&p[0], &p[1], &p[2]],
|
||||
));
|
||||
}
|
||||
for d in &drops {
|
||||
let mut left = d.clone();
|
||||
let mut placed = false;
|
||||
for s in &slots {
|
||||
match self.slot_get(s) {
|
||||
None => {
|
||||
self.slot_set(s, Some(left.clone()));
|
||||
placed = true;
|
||||
left.count = 0;
|
||||
break;
|
||||
}
|
||||
Some(mut cur)
|
||||
if cur.item == left.item
|
||||
&& cur.damage == left.damage
|
||||
&& cur.extra == left.extra =>
|
||||
{
|
||||
let max = self.res.items.get(&cur.item).map_or(64, |i| i.max_stack);
|
||||
let take = left.count.min(max.saturating_sub(cur.count));
|
||||
if take > 0 {
|
||||
cur.count += take;
|
||||
left.count -= take;
|
||||
self.slot_set(s, Some(cur));
|
||||
placed = true;
|
||||
}
|
||||
if left.count == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if placed {
|
||||
used.push(d.clone());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// replace entity|block <slot> [count]
|
||||
let block = literals.iter().any(|l| l == "block");
|
||||
let owners: Vec<Owner> = if block {
|
||||
vec![Owner::Block(self.block_pos_arg(ctx, "targetPos")?)]
|
||||
} else {
|
||||
self.entities(ctx, "entities", false)?
|
||||
.into_iter()
|
||||
.map(Owner::Entity)
|
||||
.collect()
|
||||
};
|
||||
let Some(Arg::Str(slot_name)) = ctx.get("slot").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let count = match ctx.get("count") {
|
||||
Some(Arg::Int(c)) => *c as usize,
|
||||
_ => drops.len(),
|
||||
};
|
||||
for o in owners {
|
||||
// `prefix.N` continues as `prefix.N+1`, ...
|
||||
let (prefix, start) = match slot_name.rsplit_once('.') {
|
||||
Some((p, n)) if n.parse::<usize>().is_ok() => {
|
||||
(Some(p.to_owned()), n.parse::<usize>().unwrap_or(0))
|
||||
}
|
||||
_ => (None, 0),
|
||||
};
|
||||
let first = self.slots_named(&o, &slot_name);
|
||||
if first.is_empty() {
|
||||
if let Owner::Block(p) = &o {
|
||||
return Err(err(
|
||||
"commands.item.target.not_a_container",
|
||||
&[&p[0], &p[1], &p[2]],
|
||||
));
|
||||
}
|
||||
return Err(err("commands.item.target.no_such_slot", &[&slot_name]));
|
||||
}
|
||||
for i in 0..count {
|
||||
let slot = match &prefix {
|
||||
Some(p) => self
|
||||
.slots_named(&o, &format!("{p}.{}", start + i))
|
||||
.first()
|
||||
.cloned(),
|
||||
None => first.first().cloned().filter(|_| i == 0),
|
||||
};
|
||||
let Some(slot) = slot else { continue };
|
||||
let item = drops.get(i).cloned();
|
||||
if self.slot_set(&slot, item.clone()) {
|
||||
used.push(item.unwrap_or(ItemStack {
|
||||
item: "minecraft:air".into(),
|
||||
count: 0,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut tracker = Tracker::default();
|
||||
for u in &used {
|
||||
let name = self.item_display_name(&u.item);
|
||||
tracker.track(&holder(name), u.count as i32);
|
||||
let _ = u;
|
||||
}
|
||||
let counts: Vec<u32> = used.iter().map(|u| u.count).collect();
|
||||
let (message, total) = tracker.message(
|
||||
false,
|
||||
None,
|
||||
|h, _| {
|
||||
let n = counts.iter().copied().find(|c| *c > 0).unwrap_or(1);
|
||||
match &table {
|
||||
Some(t) => Text::translate(
|
||||
"commands.drop.success.single_with_table",
|
||||
&[num(n), h.text.clone(), Text::literal(t.clone())],
|
||||
),
|
||||
None => {
|
||||
Text::translate("commands.drop.success.single", &[num(n), h.text.clone()])
|
||||
}
|
||||
}
|
||||
},
|
||||
|c, _| match &table {
|
||||
Some(t) => Text::translate(
|
||||
"commands.drop.success.multiple_with_table",
|
||||
&[num(c), Text::literal(t.clone())],
|
||||
),
|
||||
None => Text::translate("commands.drop.success.multiple", &[num(c)]),
|
||||
},
|
||||
)?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
//! `/recipe`, `/damage`, `/rotate`, `/swing`, `/playsound`, `/stopsound`,
|
||||
//! `/particle`, `/attribute`, `/ride` and `/spreadplayers`.
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use crate::game::chat::PLAYER_NAME;
|
||||
use horizon_client::{
|
||||
mobs::{Damage, DamageKind, Who},
|
||||
scoreboard_cmd::{Holder, Tracker},
|
||||
settings::SOUND_SOURCES,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::attribute_map::ValueKind;
|
||||
|
||||
fn num(n: impl std::fmt::Display) -> Text {
|
||||
Text::literal(n.to_string())
|
||||
}
|
||||
fn holder(text: Text) -> Holder {
|
||||
Holder {
|
||||
name: String::new(),
|
||||
text,
|
||||
display: None,
|
||||
}
|
||||
}
|
||||
/// `ChatFormatting`-free float text as `Component.translatable` prints a `double`.
|
||||
fn java_double_text(v: f64) -> Text {
|
||||
Text::literal(horizon_client::snbt::java_double(v))
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
// ---- /recipe -----------------------------------------------------------
|
||||
|
||||
/// Every `minecraft:` recipe that `/recipe` can give (non-special ones).
|
||||
pub(super) fn learnable_recipes(&self) -> Vec<String> {
|
||||
let dir = self.options.resources.join("data/minecraft/recipe");
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return out;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if path.extension().and_then(|x| x.to_str()) != Some("json") {
|
||||
continue;
|
||||
}
|
||||
let special = std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
.and_then(|v| v["type"].as_str().map(|t| t.contains("crafting_special_")))
|
||||
.unwrap_or(false);
|
||||
if !special {
|
||||
out.push(format!("minecraft:{stem}"));
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "targets", true)?;
|
||||
let give = id == "recipe.give";
|
||||
let recipes: Vec<String> = match ctx.get("recipe") {
|
||||
Some(Arg::Resource(r)) => {
|
||||
if !self.learnable_recipes().contains(r) {
|
||||
return Err(err("recipe.notFound", &[r]));
|
||||
}
|
||||
vec![r.clone()]
|
||||
}
|
||||
_ => self.learnable_recipes(),
|
||||
};
|
||||
let mut tracker = Tracker::default();
|
||||
for &t in &targets {
|
||||
let h = holder(self.target_name(t));
|
||||
let mut n = 0;
|
||||
for r in &recipes {
|
||||
let changed = if give {
|
||||
self.adv.recipes.insert(r.clone())
|
||||
} else {
|
||||
self.adv.recipes.remove(r)
|
||||
};
|
||||
n += i32::from(changed);
|
||||
}
|
||||
tracker.track(&h, n);
|
||||
}
|
||||
let verb = if give { "give" } else { "take" };
|
||||
let (message, total) = tracker.message(
|
||||
false,
|
||||
Some(err(&format!("commands.recipe.{verb}.failed"), &[])),
|
||||
|h, total| {
|
||||
Text::translate(
|
||||
&format!("commands.recipe.{verb}.success.single"),
|
||||
&[num(total), h.text.clone()],
|
||||
)
|
||||
},
|
||||
|count, total| {
|
||||
Text::translate(
|
||||
&format!("commands.recipe.{verb}.success.multiple"),
|
||||
&[num(total), num(count)],
|
||||
)
|
||||
},
|
||||
)?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
// ---- /damage ----------------------------------------------------------------
|
||||
|
||||
fn damage_kind(ty: &str) -> DamageKind {
|
||||
match ty.trim_start_matches("minecraft:") {
|
||||
"player_attack" => DamageKind::PlayerAttack,
|
||||
"mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
|
||||
"arrow" => DamageKind::Arrow,
|
||||
"thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
|
||||
"fireball" | "unattributed_fireball" | "wither_skull" => DamageKind::Fireball,
|
||||
"explosion" | "player_explosion" | "bad_respawn_point" => DamageKind::Explosion,
|
||||
"fall" | "ender_pearl" | "fly_into_wall" => DamageKind::Fall,
|
||||
"on_fire" => DamageKind::OnFire,
|
||||
"in_fire" | "campfire" | "hot_floor" => DamageKind::InFire,
|
||||
"lava" => DamageKind::Lava,
|
||||
"drown" => DamageKind::Drown,
|
||||
"magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic,
|
||||
"sting" => DamageKind::Sting,
|
||||
"cactus" | "sweet_berry_bush" => DamageKind::Cactus,
|
||||
"in_wall" => DamageKind::InWall,
|
||||
"thorns" => DamageKind::Thorns,
|
||||
_ => DamageKind::Generic,
|
||||
}
|
||||
}
|
||||
pub(super) fn cmd_damage(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "target", false)?;
|
||||
let Some(target) = targets.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let amount = match ctx.get("amount") {
|
||||
Some(Arg::Float(a)) => *a,
|
||||
_ => 0.0,
|
||||
};
|
||||
let ty = match ctx.get("damageType") {
|
||||
Some(Arg::Resource(t)) => t.clone(),
|
||||
_ => "minecraft:generic".into(),
|
||||
};
|
||||
let by = match ctx.get("entity") {
|
||||
Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(),
|
||||
_ => None,
|
||||
};
|
||||
let from = match ctx.get("location") {
|
||||
Some(Arg::Coords(_)) => self.position_arg(ctx, "location"),
|
||||
_ => by.and_then(|t| self.target_position(t)),
|
||||
};
|
||||
let hurt = match target {
|
||||
Target::Player => {
|
||||
if self.creative || self.spectator() {
|
||||
false
|
||||
} else if let Some(player) = self.player.as_mut() {
|
||||
match self.motion.health.damage.id(&ty) {
|
||||
Some(id) => player
|
||||
.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false),
|
||||
None => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Target::Mob(id) => {
|
||||
let attacker = by.and_then(|t| match t {
|
||||
Target::Player => Some(Who::Player),
|
||||
Target::Mob(i) => Some(Who::Mob(i)),
|
||||
_ => None,
|
||||
});
|
||||
let damage = Damage {
|
||||
kind: Self::damage_kind(&ty),
|
||||
attacker,
|
||||
from,
|
||||
};
|
||||
self.mobs
|
||||
.iter_mut()
|
||||
.find(|m| m.id == id)
|
||||
.is_some_and(|m| m.damage(amount, damage))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !hurt {
|
||||
return Err(err("commands.damage.invulnerable", &[]));
|
||||
}
|
||||
let name = self.target_name(target);
|
||||
self.feedback(Text::translate(
|
||||
"commands.damage.success",
|
||||
&[
|
||||
Text::literal(horizon_client::snbt::java_float(amount)),
|
||||
name,
|
||||
],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
|
||||
// ---- /rotate and /swing -----------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_rotate(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "target", false)?;
|
||||
let Some(t) = targets.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let Some(pos) = self.target_position(t) else {
|
||||
return Ok(0);
|
||||
};
|
||||
let current = self.target_rotation(t);
|
||||
let rot = if let Some(Arg::Coords(c)) = ctx.get("rotation") {
|
||||
// Relative parts are offsets from the entity's own rotation.
|
||||
c.rotation(current)
|
||||
} else {
|
||||
let to = if ctx.has("entity") {
|
||||
let faced = self.entities(ctx, "facingEntity", false)?;
|
||||
let Some(f) = faced.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut p = self.target_position(f).unwrap_or(pos);
|
||||
if matches!(ctx.get("facingAnchor"), Some(Arg::Anchor(true))) {
|
||||
p[1] += self.target_eye_height(f);
|
||||
}
|
||||
p
|
||||
} else {
|
||||
self.position_arg(ctx, "facingLocation").unwrap_or(pos)
|
||||
};
|
||||
let from = [pos[0], pos[1] + self.target_eye_height(t), pos[2]];
|
||||
look_at(from, to)
|
||||
};
|
||||
self.teleport_to(t, pos, Some(rot));
|
||||
if t == Target::Player {
|
||||
self.pitch = rot[1].clamp(-90.0, 90.0);
|
||||
}
|
||||
let name = self.target_name(t);
|
||||
self.feedback(Text::translate("commands.rotate.success", &[name]));
|
||||
Ok(1)
|
||||
}
|
||||
pub(super) fn cmd_swing(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = if ctx.get("targets").is_some() {
|
||||
self.entities(ctx, "targets", false)?
|
||||
} else {
|
||||
vec![
|
||||
self.command_source
|
||||
.and_then(|s| s.entity)
|
||||
.unwrap_or(Target::Player),
|
||||
]
|
||||
};
|
||||
let mut tracker = Tracker::default();
|
||||
for t in targets {
|
||||
match t {
|
||||
Target::Player => self.swing_arm(),
|
||||
Target::Mob(id) => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.ai.swinging = true;
|
||||
m.ai.swing_time = -1;
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let h = holder(self.target_name(t));
|
||||
tracker.mark(&h);
|
||||
}
|
||||
let (message, total) = tracker.message(
|
||||
false,
|
||||
Some(err("commands.swing.failed.notliving", &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.swing.success.single",
|
||||
std::slice::from_ref(&h.text),
|
||||
)
|
||||
},
|
||||
|c, _| Text::translate("commands.swing.success.multiple", &[num(c)]),
|
||||
)?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
// ---- sounds -----------------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_playsound(&mut self, ctx: &Context) -> R<i32> {
|
||||
let Some(Arg::Resource(sound)) = ctx.get("sound").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let source = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.find_map(|l| SOUND_SOURCES.iter().position(|s| s == l))
|
||||
.unwrap_or(0);
|
||||
let targets = if ctx.get("targets").is_some() {
|
||||
self.entities(ctx, "targets", true)?
|
||||
} else {
|
||||
vec![Target::Player]
|
||||
};
|
||||
let pos = self
|
||||
.position_arg(ctx, "pos")
|
||||
.unwrap_or_else(|| self.source_position());
|
||||
let float = |name: &str, default: f32| match ctx.get(name) {
|
||||
Some(Arg::Float(v)) => *v,
|
||||
_ => default,
|
||||
};
|
||||
let (volume, pitch, min_volume) = (
|
||||
float("volume", 1.0),
|
||||
float("pitch", 1.0),
|
||||
float("minVolume", 0.0),
|
||||
);
|
||||
let range = if volume > 1.0 { 16.0 * volume } else { 16.0 };
|
||||
let mut tracker = Tracker::default();
|
||||
for t in targets {
|
||||
if t != Target::Player {
|
||||
continue;
|
||||
}
|
||||
let Some(p) = self.target_position(t) else {
|
||||
continue;
|
||||
};
|
||||
let d = [pos[0] - p[0], pos[1] - p[1], pos[2] - p[2]];
|
||||
let dist2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
||||
let (at, v) = if dist2 > f64::from(range) * f64::from(range) {
|
||||
if min_volume <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let dist = dist2.sqrt();
|
||||
(
|
||||
[
|
||||
p[0] + d[0] / dist * 2.0,
|
||||
p[1] + d[1] / dist * 2.0,
|
||||
p[2] + d[2] / dist * 2.0,
|
||||
],
|
||||
min_volume,
|
||||
)
|
||||
} else {
|
||||
(pos, volume)
|
||||
};
|
||||
self.audio.play_on(source, &sound, Some(at), v, pitch);
|
||||
tracker.mark(&holder(Text::literal(PLAYER_NAME)));
|
||||
}
|
||||
let name = Text::literal(sound.clone());
|
||||
let (message, total) = tracker.message(
|
||||
true,
|
||||
Some(err("commands.playsound.failed", &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.playsound.success.single",
|
||||
&[name.clone(), h.text.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.playsound.success.multiple",
|
||||
&[name.clone(), num(c)],
|
||||
)
|
||||
},
|
||||
)?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
pub(super) fn cmd_stopsound(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "targets", true)?;
|
||||
let source = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.find_map(|l| SOUND_SOURCES.iter().position(|s| s == l));
|
||||
let sound = match ctx.get("sound") {
|
||||
Some(Arg::Resource(s)) => Some(s.clone()),
|
||||
_ => None,
|
||||
};
|
||||
self.audio.stop_sounds(sound.as_deref(), source);
|
||||
let key = match (source, &sound) {
|
||||
(Some(_), Some(_)) => "commands.stopsound.success.source.sound",
|
||||
(Some(_), None) => "commands.stopsound.success.source.any",
|
||||
(None, Some(_)) => "commands.stopsound.success.sourceless.sound",
|
||||
(None, None) => "commands.stopsound.success.sourceless.any",
|
||||
};
|
||||
let mut args = Vec::new();
|
||||
if let Some(s) = &sound {
|
||||
args.push(Text::literal(s.clone()));
|
||||
}
|
||||
if let Some(i) = source {
|
||||
args.push(Text::literal(SOUND_SOURCES[i]));
|
||||
}
|
||||
self.feedback(Text::translate(key, &args));
|
||||
Ok(targets.len() as i32)
|
||||
}
|
||||
|
||||
// ---- /particle ----------------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_particle(&mut self, ctx: &Context) -> R<i32> {
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
let Some(Arg::Str(spec)) = ctx.get("name").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut words = spec.split(' ');
|
||||
let name = words.next().unwrap_or("");
|
||||
let ty = ParticleType::from_name(name).ok_or_else(|| err("particle.notFound", &[&name]))?;
|
||||
let rest: Vec<&str> = words.collect();
|
||||
let float = |i: usize, d: f32| rest.get(i).and_then(|w| w.parse::<f32>().ok()).unwrap_or(d);
|
||||
let options = match ty {
|
||||
ParticleType::Dust => ParticleOptions::dust(
|
||||
[float(0, 1.0), float(1, 0.0), float(2, 0.0)],
|
||||
float(3, 1.0).clamp(0.01, 4.0),
|
||||
),
|
||||
ParticleType::Block | ParticleType::FallingDust | ParticleType::DustPillar => {
|
||||
let mut reader = horizon_client::command::Reader::new(rest.join(" ").leak());
|
||||
let block = horizon_client::command::args::ArgType::BlockState
|
||||
.parse(&mut reader, &self.ui.registries);
|
||||
match block {
|
||||
Ok(Arg::Block(b)) => {
|
||||
let state = self.block_state(&b)?;
|
||||
let (sprite, tint) = self
|
||||
.particle_sprite(state)
|
||||
.unwrap_or_else(|| ("block/stone".into(), 0xFFFFFF));
|
||||
ParticleOptions::block(ty, sprite, tint)
|
||||
}
|
||||
_ => ParticleOptions::simple(ty),
|
||||
}
|
||||
}
|
||||
_ => ParticleOptions::simple(ty),
|
||||
};
|
||||
let pos = self
|
||||
.position_arg(ctx, "pos")
|
||||
.unwrap_or_else(|| self.source_position());
|
||||
let delta = self.position_arg(ctx, "delta").map_or([0.0; 3], |d| {
|
||||
let s = self.source_position();
|
||||
[d[0] - s[0], d[1] - s[1], d[2] - s[2]]
|
||||
});
|
||||
let speed = match ctx.get("speed") {
|
||||
Some(Arg::Float(v)) => *v,
|
||||
_ => 0.0,
|
||||
};
|
||||
let count = match ctx.get("count") {
|
||||
Some(Arg::Int(c)) => *c,
|
||||
_ => 0,
|
||||
};
|
||||
// `ServerLevel.sendParticles`: no count means one particle with the delta as velocity.
|
||||
if count <= 0 {
|
||||
self.particles.create(&options, pos, delta);
|
||||
} else {
|
||||
for _ in 0..count {
|
||||
let r = self.particles.random();
|
||||
let p = [
|
||||
pos[0] + r.next_gaussian() * delta[0],
|
||||
pos[1] + r.next_gaussian() * delta[1],
|
||||
pos[2] + r.next_gaussian() * delta[2],
|
||||
];
|
||||
let v = [
|
||||
r.next_gaussian() * f64::from(speed),
|
||||
r.next_gaussian() * f64::from(speed),
|
||||
r.next_gaussian() * f64::from(speed),
|
||||
];
|
||||
self.particles.create(&options, p, v);
|
||||
}
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.particle.success",
|
||||
&[Text::literal(name.to_owned())],
|
||||
));
|
||||
Ok(count.max(1))
|
||||
}
|
||||
|
||||
// ---- /attribute ---------------------------------------------------------------------
|
||||
|
||||
/// The attribute id without `minecraft:`, as the attribute map names it.
|
||||
fn attribute_description(attribute: &str) -> Text {
|
||||
let short = attribute.trim_start_matches("minecraft:");
|
||||
Text::translate(&format!("attribute.name.{short}"), &[])
|
||||
}
|
||||
pub(super) fn cmd_attribute(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "target", false)?;
|
||||
let Some(target) = targets.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let Some(Arg::Resource(attribute)) = ctx.get("attribute").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let name = self.target_name(target);
|
||||
let description = Self::attribute_description(&attribute);
|
||||
let short = attribute.trim_start_matches("minecraft:").to_owned();
|
||||
let no_attribute = |name: &Text, d: &Text| {
|
||||
text_error(
|
||||
"commands.attribute.failed.no_attribute",
|
||||
&[name.clone(), d.clone()],
|
||||
)
|
||||
};
|
||||
let scale = match ctx.get("scale") {
|
||||
Some(Arg::Double(s)) => *s,
|
||||
_ => 1.0,
|
||||
};
|
||||
let value_arg = match ctx.get("value") {
|
||||
Some(Arg::Double(v)) => *v,
|
||||
_ => 0.0,
|
||||
};
|
||||
let modifier_id = match ctx.get("id") {
|
||||
Some(Arg::Resource(m)) => m.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
match target {
|
||||
Target::Player => {
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let Some(key) = player.attributes.key(&attribute) else {
|
||||
return Err(no_attribute(&name, &description));
|
||||
};
|
||||
let unavailable = |_| no_attribute(&name, &description);
|
||||
match id {
|
||||
"attribute.get" | "attribute.base.get" => {
|
||||
let kind = if id == "attribute.get" {
|
||||
ValueKind::Computed
|
||||
} else {
|
||||
ValueKind::Base
|
||||
};
|
||||
let v = player
|
||||
.attributes
|
||||
.value(Some(key), kind)
|
||||
.map_err(unavailable)?;
|
||||
let k = if id == "attribute.get" {
|
||||
"commands.attribute.value.get.success"
|
||||
} else {
|
||||
"commands.attribute.base_value.get.success"
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
k,
|
||||
&[description, name, java_double_text(v)],
|
||||
));
|
||||
Ok((v * scale) as i32)
|
||||
}
|
||||
"attribute.base.set" => {
|
||||
let handle = player
|
||||
.attributes
|
||||
.get_instance(Some(key))
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or_else(|| no_attribute(&name, &description))?;
|
||||
let _ = player.attributes.edit(&handle, |value, observer| {
|
||||
value.set_base_value(value_arg, observer)
|
||||
});
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.base_value.set.success",
|
||||
&[description, name, java_double_text(value_arg)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
"attribute.base.reset" => {
|
||||
if !player
|
||||
.attributes
|
||||
.reset_base(Some(key.clone()))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(no_attribute(&name, &description));
|
||||
}
|
||||
let v = player
|
||||
.attributes
|
||||
.value(Some(key.clone()), ValueKind::Base)
|
||||
.unwrap_or(0.0);
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.base_value.reset.success",
|
||||
&[description, name, java_double_text(v)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
"attribute.modifier.add" => {
|
||||
if player
|
||||
.attributes
|
||||
.has_modifier(Some(key), &modifier_id)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(err(
|
||||
"commands.attribute.failed.modifier_already_present",
|
||||
&[&modifier_id, &description.plain(), &name.plain()],
|
||||
));
|
||||
}
|
||||
let op = ctx
|
||||
.literals
|
||||
.last()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "add_value".into());
|
||||
player
|
||||
.set_modifier(&attribute, &modifier_id, value_arg, &op, true)
|
||||
.map_err(|_| no_attribute(&name, &description))?;
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.modifier.add.success",
|
||||
&[Text::literal(modifier_id), description, name],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
"attribute.modifier.remove" => {
|
||||
if !player
|
||||
.attributes
|
||||
.has_modifier(Some(key), &modifier_id)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(err(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[&description.plain(), &name.plain(), &modifier_id],
|
||||
));
|
||||
}
|
||||
let _ =
|
||||
player.set_modifier(&attribute, &modifier_id, 0.0, "add_value", false);
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.modifier.remove.success",
|
||||
&[Text::literal(modifier_id), description, name],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
_ => {
|
||||
let Some(handle) = player.attributes.get_instance(Some(key)).ok().flatten()
|
||||
else {
|
||||
return Err(no_attribute(&name, &description));
|
||||
};
|
||||
let found = player
|
||||
.attributes
|
||||
.edit(&handle, |value, _| {
|
||||
Ok(value
|
||||
.modifiers()
|
||||
.iter()
|
||||
.find(|m| m.id() == modifier_id)
|
||||
.map(|m| m.amount()))
|
||||
})
|
||||
.ok()
|
||||
.flatten();
|
||||
let Some(v) = found else {
|
||||
return Err(err(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[&description.plain(), &name.plain(), &modifier_id],
|
||||
));
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.modifier.value.get.success",
|
||||
&[
|
||||
Text::literal(modifier_id),
|
||||
description,
|
||||
name,
|
||||
java_double_text(v),
|
||||
],
|
||||
));
|
||||
Ok((v * scale) as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Mob(mob_id) => {
|
||||
let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) else {
|
||||
return Ok(0);
|
||||
};
|
||||
// Mobs keep three attributes as plain values.
|
||||
let slot: Option<f64> = match short.as_str() {
|
||||
"max_health" => Some(f64::from(m.attrs.max_health)),
|
||||
"movement_speed" => Some(m.attrs.speed),
|
||||
"attack_damage" => Some(f64::from(m.attrs.attack_damage)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(current) = slot else {
|
||||
return Err(no_attribute(&name, &description));
|
||||
};
|
||||
match id {
|
||||
"attribute.get" | "attribute.base.get" => {
|
||||
let k = if id == "attribute.get" {
|
||||
"commands.attribute.value.get.success"
|
||||
} else {
|
||||
"commands.attribute.base_value.get.success"
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
k,
|
||||
&[description, name, java_double_text(current)],
|
||||
));
|
||||
Ok((current * scale) as i32)
|
||||
}
|
||||
"attribute.base.set" => {
|
||||
match short.as_str() {
|
||||
"max_health" => {
|
||||
m.attrs.max_health = value_arg as f32;
|
||||
m.health = m.health.min(m.attrs.max_health);
|
||||
}
|
||||
"movement_speed" => m.attrs.speed = value_arg,
|
||||
_ => m.attrs.attack_damage = value_arg as f32,
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.base_value.set.success",
|
||||
&[description, name, java_double_text(value_arg)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
"attribute.base.reset" => {
|
||||
match short.as_str() {
|
||||
"max_health" => m.attrs.max_health = m.kind.max_health,
|
||||
"movement_speed" => m.attrs.speed = m.kind.speed,
|
||||
_ => m.attrs.attack_damage = m.kind.attack_damage,
|
||||
}
|
||||
let v = match short.as_str() {
|
||||
"max_health" => f64::from(m.attrs.max_health),
|
||||
"movement_speed" => m.attrs.speed,
|
||||
_ => f64::from(m.attrs.attack_damage),
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
"commands.attribute.base_value.reset.success",
|
||||
&[description, name, java_double_text(v)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
_ => Err(err(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[&description.plain(), &name.plain(), &modifier_id],
|
||||
)),
|
||||
}
|
||||
}
|
||||
_ => Err(err("commands.attribute.failed.entity", &[&name.plain()])),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- /ride ----------------------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_ride(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "target", false)?;
|
||||
let Some(target) = targets.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let name = self.target_name(target);
|
||||
if id == "ride.dismount" {
|
||||
let vehicle = match target {
|
||||
Target::Player => self.riding.map(Target::Mob),
|
||||
_ => None,
|
||||
};
|
||||
let Some(v) = vehicle else {
|
||||
return Err(err("commands.ride.not_riding", &[&name.plain()]));
|
||||
};
|
||||
let vehicle_name = self.target_name(v);
|
||||
self.dismount_mount();
|
||||
self.feedback(Text::translate(
|
||||
"commands.ride.dismount.success",
|
||||
&[name, vehicle_name],
|
||||
));
|
||||
return Ok(1);
|
||||
}
|
||||
let vehicles = self.entities(ctx, "vehicle", false)?;
|
||||
let Some(vehicle) = vehicles.first().copied() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let vehicle_name = self.target_name(vehicle);
|
||||
if target == Target::Player && self.riding.is_some() {
|
||||
let current = self
|
||||
.riding
|
||||
.map(Target::Mob)
|
||||
.map_or_else(Text::empty, |v| self.target_name(v));
|
||||
return Err(err(
|
||||
"commands.ride.already_riding",
|
||||
&[&name.plain(), ¤t.plain()],
|
||||
));
|
||||
}
|
||||
if vehicle == Target::Player {
|
||||
return Err(err("commands.ride.mount.failure.cant_ride_players", &[]));
|
||||
}
|
||||
if target == vehicle {
|
||||
return Err(err("commands.ride.mount.failure.loop", &[]));
|
||||
}
|
||||
// The player can ride mobs that carry a rider.
|
||||
let Target::Mob(mob_id) = vehicle else {
|
||||
return Err(err(
|
||||
"commands.ride.mount.failure.generic",
|
||||
&[&name.plain(), &vehicle_name.plain()],
|
||||
));
|
||||
};
|
||||
if target != Target::Player || !self.mobs.iter().any(|m| m.id == mob_id && m.alive()) {
|
||||
return Err(err(
|
||||
"commands.ride.mount.failure.generic",
|
||||
&[&name.plain(), &vehicle_name.plain()],
|
||||
));
|
||||
}
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) {
|
||||
m.extra.flag = false;
|
||||
m.extra.counter = 0;
|
||||
self.yaw = m.yaw;
|
||||
}
|
||||
self.riding = Some(mob_id);
|
||||
self.mount.jump_ticks = 0;
|
||||
self.mount.jump_scale = 0.0;
|
||||
self.feedback(Text::translate(
|
||||
"commands.ride.mount.success",
|
||||
&[name, vehicle_name],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
|
||||
// ---- /spreadplayers -----------------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_spreadplayers(&mut self, ctx: &Context) -> R<i32> {
|
||||
let centre = self
|
||||
.position_arg(ctx, "center")
|
||||
.unwrap_or_else(|| self.source_position());
|
||||
let float = |name: &str| match ctx.get(name) {
|
||||
Some(Arg::Float(v)) => f64::from(*v),
|
||||
_ => 0.0,
|
||||
};
|
||||
let (spread, range) = (float("spreadDistance"), float("maxRange"));
|
||||
let respect = matches!(ctx.get("respectTeams"), Some(Arg::Bool(true)));
|
||||
let max_y = match ctx.get("maxHeight") {
|
||||
Some(Arg::Int(h)) => *h,
|
||||
_ => horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT,
|
||||
};
|
||||
if max_y < horizon_client::chunk::MIN_Y {
|
||||
return Err(err(
|
||||
"commands.spreadplayers.failed.invalid.height",
|
||||
&[&max_y, &horizon_client::chunk::MIN_Y],
|
||||
));
|
||||
}
|
||||
let targets = self.entities(ctx, "targets", false)?;
|
||||
if targets.is_empty() {
|
||||
return Err(err("argument.entity.notfound.entity", &[]));
|
||||
}
|
||||
// Units: each entity, or each team together with `respectTeams`.
|
||||
let mut units: Vec<Vec<Target>> = Vec::new();
|
||||
let mut teams: Vec<(String, usize)> = Vec::new();
|
||||
for &t in &targets {
|
||||
let team = if respect {
|
||||
self.holder_name(t)
|
||||
.and_then(|h| self.score.board.players_team(&h).map(|x| x.name.clone()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match team {
|
||||
Some(name) => match teams.iter().find(|(n, _)| *n == name) {
|
||||
Some((_, i)) => units[*i].push(t),
|
||||
None => {
|
||||
teams.push((name, units.len()));
|
||||
units.push(vec![t]);
|
||||
}
|
||||
},
|
||||
None => units.push(vec![t]),
|
||||
}
|
||||
}
|
||||
let (min_x, max_x) = (centre[0] - range, centre[0] + range);
|
||||
let (min_z, max_z) = (centre[2] - range, centre[2] + range);
|
||||
let mut points: Vec<[f64; 2]> = units
|
||||
.iter()
|
||||
.map(|_| {
|
||||
let r = &mut self.world.random;
|
||||
[
|
||||
min_x + r.next_double() * (max_x - min_x),
|
||||
min_z + r.next_double() * (max_z - min_z),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let n = points.len();
|
||||
let mut ok = false;
|
||||
for _ in 0..10_000 {
|
||||
let mut moved = false;
|
||||
let mut crowded = 0;
|
||||
for i in 0..n {
|
||||
let mut push = [0.0, 0.0];
|
||||
let mut near = 0;
|
||||
for j in 0..n {
|
||||
if i == j {
|
||||
continue;
|
||||
}
|
||||
let (dx, dz) = (points[j][0] - points[i][0], points[j][1] - points[i][1]);
|
||||
let d = (dx * dx + dz * dz).sqrt();
|
||||
if d < spread {
|
||||
near += 1;
|
||||
if d > 1.0e-6 {
|
||||
push[0] -= dx / d;
|
||||
push[1] -= dz / d;
|
||||
} else {
|
||||
let r = &mut self.world.random;
|
||||
push[0] += r.next_double() - 0.5;
|
||||
push[1] += r.next_double() - 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
if near > 0 {
|
||||
crowded += 1;
|
||||
let len = (push[0] * push[0] + push[1] * push[1]).sqrt().max(1.0e-6);
|
||||
points[i][0] += push[0] / len;
|
||||
points[i][1] += push[1] / len;
|
||||
moved = true;
|
||||
}
|
||||
let before = points[i];
|
||||
points[i][0] = points[i][0].clamp(min_x, max_x);
|
||||
points[i][1] = points[i][1].clamp(min_z, max_z);
|
||||
moved |= before != points[i];
|
||||
}
|
||||
if !moved || crowded == 0 {
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
let key = if teams.is_empty() {
|
||||
"commands.spreadplayers.failed.entities"
|
||||
} else {
|
||||
"commands.spreadplayers.failed.teams"
|
||||
};
|
||||
return Err(err(
|
||||
key,
|
||||
&[
|
||||
&n,
|
||||
&format!("{:.2}", centre[0]),
|
||||
&format!("{:.2}", centre[2]),
|
||||
&format!("{:.2}", spread),
|
||||
],
|
||||
));
|
||||
}
|
||||
// Stand each unit on the ground under `max_y`.
|
||||
let mut total = 0.0;
|
||||
for (unit, p) in units.iter().zip(&points) {
|
||||
let (bx, bz) = (p[0].floor() as i32, p[1].floor() as i32);
|
||||
let mut y = None;
|
||||
for yy in (horizon_client::chunk::MIN_Y
|
||||
..max_y.min(horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT))
|
||||
.rev()
|
||||
{
|
||||
let solid = |dy: i32| {
|
||||
self.res
|
||||
.facts
|
||||
.get(self.world.block(bx, yy + dy, bz))
|
||||
.full_collision
|
||||
};
|
||||
if solid(-1) && !solid(0) && !solid(1) {
|
||||
y = Some(yy);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let y = y.unwrap_or(max_y);
|
||||
for &t in unit {
|
||||
self.teleport_to(
|
||||
t,
|
||||
[f64::from(bx) + 0.5, f64::from(y), f64::from(bz) + 0.5],
|
||||
None,
|
||||
);
|
||||
}
|
||||
let (dx, dz) = (p[0] - centre[0], p[1] - centre[2]);
|
||||
total += (dx * dx + dz * dz).sqrt();
|
||||
}
|
||||
let average = if n == 0 { 0.0 } else { total / n as f64 };
|
||||
let key = if teams.is_empty() {
|
||||
"commands.spreadplayers.success.entities"
|
||||
} else {
|
||||
"commands.spreadplayers.success.teams"
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
key,
|
||||
&[
|
||||
num(n),
|
||||
Text::literal(format!("{:.2}", centre[0])),
|
||||
Text::literal(format!("{:.2}", centre[2])),
|
||||
Text::literal(format!("{average:.2}")),
|
||||
],
|
||||
));
|
||||
Ok(n as i32)
|
||||
}
|
||||
}
|
||||
|
||||
/// A `CommandError` whose message is a translation with component arguments.
|
||||
fn text_error(key: &str, args: &[Text]) -> horizon_client::command::CommandError {
|
||||
horizon_client::command::CommandError::new(Text::translate(key, args))
|
||||
}
|
||||
|
||||
/// `Entity.lookAt`: yaw and pitch from `from` towards `to`.
|
||||
fn look_at(from: [f64; 3], to: [f64; 3]) -> [f32; 2] {
|
||||
let (dx, dy, dz) = (to[0] - from[0], to[1] - from[1], to[2] - from[2]);
|
||||
let horizontal = (dx * dx + dz * dz).sqrt();
|
||||
let pitch = (-(dy.atan2(horizontal).to_degrees())) as f32;
|
||||
let yaw = (dz.atan2(dx).to_degrees() - 90.0) as f32;
|
||||
[yaw.rem_euclid(360.0), pitch]
|
||||
}
|
||||
@@ -88,8 +88,10 @@ impl Game<'_> {
|
||||
.chain(super::blockctl::HELP)
|
||||
.chain(super::lan::HELP)
|
||||
.chain(super::render_control::HELP)
|
||||
.chain(super::sculk::HELP)
|
||||
.collect::<Vec<_>>() }))),
|
||||
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
|
||||
"sculk" => Ok(Some(self.sculk_command(&words)?)),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
@@ -297,6 +299,9 @@ impl Game<'_> {
|
||||
match self.screen {
|
||||
Screen::Chat => self.chat_type(text),
|
||||
Screen::Options => self.ui.options.type_text(text),
|
||||
Screen::Inventory if self.recipe_search_focused() => {
|
||||
self.recipe_text(Some(text), false)
|
||||
}
|
||||
_ => {
|
||||
return Err(
|
||||
"type needs the chat screen (key t tap) or the language search".into(),
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an
|
||||
//! awake heart in a pale oak trunk spawns a creaking that protects it,
|
||||
//! hurting the creaking makes the heart emit trails and spread resin over
|
||||
//! the logs, and breaking the heart tears the creaking down.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
containers::{BlockEntity, CreakingHeart},
|
||||
mobs::creaking,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
|
||||
type Pos = (i32, i32, i32);
|
||||
|
||||
/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`.
|
||||
const ORANGE: u32 = 16_545_810;
|
||||
const GRAY: u32 = 6_250_335;
|
||||
/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`.
|
||||
const TOO_FAR: f64 = 34.0;
|
||||
|
||||
/// `Direction.values()`: down, up, north, south, west, east.
|
||||
const DIRECTIONS: [[i32; 3]; 6] = [
|
||||
[0, -1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, -1],
|
||||
[0, 0, 1],
|
||||
[-1, 0, 0],
|
||||
[1, 0, 0],
|
||||
];
|
||||
const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
|
||||
|
||||
/// Comparator input of a heart (`getAnalogOutputSignal`).
|
||||
pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option<i32> {
|
||||
match world.block_entities.get(&(pos.x, pos.y, pos.z))? {
|
||||
BlockEntity::CreakingHeart(h) => Some(h.output_signal),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn heart_state_name(&self, state: BlockStateId) -> String {
|
||||
self.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
/// `Util.shuffledCopy(Direction.values(), random)`.
|
||||
fn shuffled_directions(&mut self) -> [usize; 6] {
|
||||
let mut order = [0, 1, 2, 3, 4, 5];
|
||||
for i in (2..=6).rev() {
|
||||
let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
|
||||
order.swap(i - 1, j);
|
||||
}
|
||||
order
|
||||
}
|
||||
fn is_pale_oak_log(&self, p: Pos) -> bool {
|
||||
let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name;
|
||||
self.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:pale_oak_logs")
|
||||
.is_some_and(|s| s.contains(&**name))
|
||||
}
|
||||
fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> {
|
||||
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
|
||||
Some((m.center(), m.bounds()))
|
||||
}
|
||||
/// The protector's entity, resolving a UUID read from a save.
|
||||
fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option<u32> {
|
||||
let (id, uuid) = heart.creaking?;
|
||||
if let Some(id) = id {
|
||||
if self.mobs.iter().any(|m| m.id == id && !m.removed) {
|
||||
return Some(id);
|
||||
}
|
||||
// The entity is gone: remember it by UUID until it reappears.
|
||||
heart.creaking = Some((None, uuid));
|
||||
}
|
||||
if let Some(id) = self.mob_id_for_uuid(uuid) {
|
||||
heart.creaking = Some((Some(id), uuid));
|
||||
return Some(id);
|
||||
}
|
||||
if heart.ticks_existed >= 30 {
|
||||
heart.creaking = None;
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart.
|
||||
fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) {
|
||||
let Some(id) = self.heart_protector(heart) else {
|
||||
return;
|
||||
};
|
||||
if by_player {
|
||||
// creakingDeathEffects: a twitching death.
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
creaking::set_tearing_down(m);
|
||||
m.health = 0.0;
|
||||
m.death_time = m.death_time.max(0);
|
||||
let at = m.center();
|
||||
self.audio
|
||||
.play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0);
|
||||
}
|
||||
} else if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
|
||||
let mut events = Vec::new();
|
||||
creaking::tear_down(&mut self.mobs[i], &mut events);
|
||||
let _ = self.handle_mob_events(events);
|
||||
}
|
||||
heart.creaking = None;
|
||||
}
|
||||
fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 {
|
||||
self.mob_center(id).map_or(0.0, |_| {
|
||||
let m = self.mobs.iter().find(|m| m.id == id).unwrap();
|
||||
let at = (
|
||||
f64::from(pos.0) + 0.5,
|
||||
f64::from(pos.1),
|
||||
f64::from(pos.2) + 0.5,
|
||||
);
|
||||
((m.position.x - at.0).powi(2)
|
||||
+ (m.position.y - at.1).powi(2)
|
||||
+ (m.position.z - at.2).powi(2))
|
||||
.sqrt()
|
||||
})
|
||||
}
|
||||
/// `emitParticles`: trails between the creaking and the heart.
|
||||
fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) {
|
||||
let Some(id) = self.heart_protector(heart) else {
|
||||
return;
|
||||
};
|
||||
let Some((_, b)) = self.mob_center(id) else {
|
||||
return;
|
||||
};
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
for _ in 0..count {
|
||||
let r = &mut self.world.random;
|
||||
let mut source = [
|
||||
lo.x + r.next_double() * (hi.x - lo.x),
|
||||
lo.y + r.next_double() * (hi.y - lo.y),
|
||||
lo.z + r.next_double() * (hi.z - lo.z),
|
||||
];
|
||||
let mut destination = [
|
||||
f64::from(pos.0) + r.next_double(),
|
||||
f64::from(pos.1) + r.next_double(),
|
||||
f64::from(pos.2) + r.next_double(),
|
||||
];
|
||||
if towards {
|
||||
std::mem::swap(&mut source, &mut destination);
|
||||
}
|
||||
let duration = r.next_int_bound(40).unwrap_or(0) + 10;
|
||||
let color = if towards { ORANGE } else { GRAY };
|
||||
self.particles.add(
|
||||
&ParticleOptions::trail(destination, color, duration),
|
||||
source,
|
||||
[0.0; 3],
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log
|
||||
/// face found within two steps of pale oak logs.
|
||||
fn heart_spread_resin(&mut self, pos: Pos) -> Option<Pos> {
|
||||
let mut visited: HashSet<Pos> = HashSet::new();
|
||||
let mut queue: VecDeque<(Pos, i32)> = VecDeque::new();
|
||||
queue.push_back((pos, 0));
|
||||
let mut count = 0;
|
||||
while let Some((current, depth)) = queue.pop_front() {
|
||||
if !visited.insert(current) {
|
||||
continue;
|
||||
}
|
||||
// The node processor.
|
||||
if self.is_pale_oak_log(current) {
|
||||
for d in self.shuffled_directions() {
|
||||
let n = (
|
||||
current.0 + DIRECTIONS[d][0],
|
||||
current.1 + DIRECTIONS[d][1],
|
||||
current.2 + DIRECTIONS[d][2],
|
||||
);
|
||||
let neighbour = self.world.block(n.0, n.1, n.2);
|
||||
let opposite = d ^ 1;
|
||||
let clump = self.resin_clump_for(neighbour);
|
||||
let Some(clump) = clump else { continue };
|
||||
if self.prop_is(clump, FACE_NAMES[opposite]) {
|
||||
continue;
|
||||
}
|
||||
let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else {
|
||||
continue;
|
||||
};
|
||||
let _ = self.level_set([n.0, n.1, n.2], placed);
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
count += 1;
|
||||
if count >= 64 {
|
||||
return None;
|
||||
}
|
||||
if depth < 2 {
|
||||
// The neighbour provider: adjacent pale oak logs.
|
||||
for d in self.shuffled_directions() {
|
||||
let n = (
|
||||
current.0 + DIRECTIONS[d][0],
|
||||
current.1 + DIRECTIONS[d][1],
|
||||
current.2 + DIRECTIONS[d][2],
|
||||
);
|
||||
if self.is_pale_oak_log(n) {
|
||||
queue.push_back((n, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// The state a face of resin can be added to: air, a source of water, or
|
||||
/// a clump already there.
|
||||
fn resin_clump_for(&self, neighbour: BlockStateId) -> Option<BlockStateId> {
|
||||
let registry = self.res.assets.registry;
|
||||
let clump = registry.default_state("minecraft:resin_clump")?;
|
||||
let facts = self.res.facts.get(neighbour);
|
||||
if self.res.facts.is_air(neighbour) {
|
||||
Some(clump)
|
||||
} else if &*facts.name == "minecraft:water"
|
||||
&& facts.fluid_level == 8
|
||||
&& !facts.fluid_falling
|
||||
{
|
||||
let mut s = registry.state(clump)?.clone();
|
||||
s.properties.insert("waterlogged".into(), "true".into());
|
||||
registry.resolve(&s).ok()
|
||||
} else if &*facts.name == "minecraft:resin_clump" {
|
||||
Some(neighbour)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn prop_is(&self, state: BlockStateId, key: &str) -> bool {
|
||||
self.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get(key))
|
||||
.is_some_and(|v| v == "true")
|
||||
}
|
||||
fn with_face(&self, state: BlockStateId, face: &str) -> Option<BlockStateId> {
|
||||
let mut s = self.res.assets.registry.state(state)?.clone();
|
||||
s.properties.insert(face.to_owned(), "true".to_owned());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
}
|
||||
/// A creaking bound to the heart at `home` was hurt (`creakingHurt`).
|
||||
pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) {
|
||||
if !by_player {
|
||||
return;
|
||||
}
|
||||
let key = (home[0], home[1], home[2]);
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 {
|
||||
self.heart_emit(&mut heart, key, 20, false);
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if self.heart_state_name(state) == "awake" {
|
||||
let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0);
|
||||
for _ in 0..clumps {
|
||||
if let Some(at) = self.heart_spread_resin(key) {
|
||||
self.audio.play(
|
||||
"minecraft:block.resin.place",
|
||||
Some([
|
||||
f64::from(at.0) + 0.5,
|
||||
f64::from(at.1) + 0.5,
|
||||
f64::from(at.2) + 0.5,
|
||||
]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
heart.emitter = 100;
|
||||
heart.emitter_target = self.mob_center(id).map(|(c, _)| c);
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
}
|
||||
/// `Creaking.tearDown`: the crumble particles.
|
||||
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
|
||||
let registry = self.res.assets.registry;
|
||||
let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| {
|
||||
let Some(mut state) = registry
|
||||
.default_state(name)
|
||||
.and_then(|s| registry.state(s).cloned())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for (k, v) in props {
|
||||
state.properties.insert((*k).to_owned(), (*v).to_owned());
|
||||
}
|
||||
let Ok(id) = registry.resolve(&state) else {
|
||||
return;
|
||||
};
|
||||
let Some((sprite, tint)) = this.particle_sprite(id) else {
|
||||
return;
|
||||
};
|
||||
for _ in 0..count {
|
||||
let r = &mut this.world.random;
|
||||
let p = [
|
||||
center[0] + r.next_gaussian() * spread[0],
|
||||
center[1] + r.next_gaussian() * spread[1],
|
||||
center[2] + r.next_gaussian() * spread[2],
|
||||
];
|
||||
this.particles.add(
|
||||
&ParticleOptions::block(ParticleType::BlockCrumble, sprite.clone(), tint),
|
||||
p,
|
||||
[0.0; 3],
|
||||
);
|
||||
}
|
||||
};
|
||||
crumble(self, "minecraft:pale_oak_wood", &[], 100);
|
||||
crumble(
|
||||
self,
|
||||
"minecraft:creaking_heart",
|
||||
&[("creaking_heart_state", "awake")],
|
||||
10,
|
||||
);
|
||||
}
|
||||
/// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to
|
||||
/// death and a natural heart drops experience.
|
||||
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.heart_remove_protector(&mut heart, true);
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if self.prop_is(state, "natural") && !self.creative && !self.spectator() {
|
||||
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
|
||||
self.spawn_orbs(
|
||||
[
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
],
|
||||
xp,
|
||||
);
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
}
|
||||
/// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`.
|
||||
fn spawn_protector(&mut self, pos: Pos) -> Option<u32> {
|
||||
let t = self.res.mob_types.get("minecraft:creaking").cloned()?;
|
||||
for _ in 0..5 {
|
||||
let r = &mut self.world.random;
|
||||
let dx = r.next_int_bound(33).unwrap_or(16) - 16;
|
||||
let dz = r.next_int_bound(33).unwrap_or(16) - 16;
|
||||
let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz);
|
||||
if !self.world.loaded(at.0, at.2) {
|
||||
continue;
|
||||
}
|
||||
// moveToPossibleSpawnPosition: scan down for a collider with room above.
|
||||
let mut above = self.world.block(at.0, at.1, at.2);
|
||||
let mut found = false;
|
||||
for _ in 0..=16 {
|
||||
at.1 -= 1;
|
||||
let current = self.world.block(at.0, at.1, at.2);
|
||||
let facts = self.res.facts.get(current);
|
||||
let leaves = self
|
||||
.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:leaves")
|
||||
.is_some_and(|s| s.contains(&*facts.name));
|
||||
let clear_above = self
|
||||
.res
|
||||
.behaviours
|
||||
.collision_shape(above)
|
||||
.map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty());
|
||||
if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 {
|
||||
at.1 += 1;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
above = current;
|
||||
}
|
||||
if !found {
|
||||
continue;
|
||||
}
|
||||
// noCollision(spawn box) and no liquid.
|
||||
let w = t.width / 2.0;
|
||||
let bounds = Aabb::new(
|
||||
horizon_core::geometry::Vec3::new(
|
||||
f64::from(at.0) + 0.5 - w,
|
||||
f64::from(at.1),
|
||||
f64::from(at.2) + 0.5 - w,
|
||||
),
|
||||
horizon_core::geometry::Vec3::new(
|
||||
f64::from(at.0) + 0.5 + w,
|
||||
f64::from(at.1) + t.height,
|
||||
f64::from(at.2) + 0.5 + w,
|
||||
),
|
||||
);
|
||||
let mut scene = horizon_client::collisions::SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let free = scene.unobstructed(bounds).unwrap_or(false);
|
||||
let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid
|
||||
!= horizon_client::blocks::Fluid::None;
|
||||
if !free || wet {
|
||||
continue;
|
||||
}
|
||||
let id = self.spawn_mob(
|
||||
"minecraft:creaking",
|
||||
[
|
||||
f64::from(at.0) + 0.5,
|
||||
f64::from(at.1),
|
||||
f64::from(at.2) + 0.5,
|
||||
],
|
||||
false,
|
||||
)?;
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
creaking::set_transient(m, [pos.0, pos.1, pos.2]);
|
||||
}
|
||||
return Some(id);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.computeAnalogOutputSignal`.
|
||||
fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 {
|
||||
if heart.creaking.is_none() {
|
||||
return 0;
|
||||
}
|
||||
let Some(id) = self.heart_protector(heart) else {
|
||||
return 0;
|
||||
};
|
||||
let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0;
|
||||
15 - (distance * 15.0).floor() as i32
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.serverTick` for every heart.
|
||||
pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> {
|
||||
let keys: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) =
|
||||
self.world.block_entities.remove(&key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
|
||||
// The block is gone: preRemoveSideEffects.
|
||||
self.heart_remove_protector(&mut heart, false);
|
||||
continue;
|
||||
}
|
||||
if self.heart_state_name(state) != "uprooted" {
|
||||
self.heart_tick(&mut heart, key, state)?;
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
}
|
||||
self.scan_for_hearts();
|
||||
Ok(())
|
||||
}
|
||||
fn heart_tick(
|
||||
&mut self,
|
||||
heart: &mut CreakingHeart,
|
||||
key: Pos,
|
||||
state: BlockStateId,
|
||||
) -> Result<()> {
|
||||
heart.ticks_existed += 1;
|
||||
let output = self.heart_output(heart, key);
|
||||
if output != heart.output_signal {
|
||||
heart.output_signal = output;
|
||||
self.container_changed(key);
|
||||
}
|
||||
if heart.emitter > 0 {
|
||||
if heart.emitter > 50 {
|
||||
self.heart_emit(heart, key, 1, true);
|
||||
self.heart_emit(heart, key, 1, false);
|
||||
}
|
||||
if heart.emitter % 10 == 0 && heart.emitter_target.is_some() {
|
||||
if let Some(id) = self.heart_protector(heart)
|
||||
&& let Some((c, _)) = self.mob_center(id)
|
||||
{
|
||||
heart.emitter_target = Some(c);
|
||||
}
|
||||
if let Some(target) = heart.emitter_target {
|
||||
let center = [
|
||||
f64::from(key.0) + 0.5,
|
||||
f64::from(key.1) + 0.5,
|
||||
f64::from(key.2) + 0.5,
|
||||
];
|
||||
let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0;
|
||||
let at = [
|
||||
(center[0] - target[0]) * progress + target[0],
|
||||
(center[1] - target[1]) * progress + target[1],
|
||||
(center[2] - target[2]) * progress + target[2],
|
||||
];
|
||||
let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5;
|
||||
self.audio
|
||||
.play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0);
|
||||
}
|
||||
}
|
||||
heart.emitter -= 1;
|
||||
}
|
||||
let ticker = heart.ticker;
|
||||
heart.ticker -= 1;
|
||||
if ticker >= 0 {
|
||||
return Ok(());
|
||||
}
|
||||
heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20;
|
||||
// updateCreakingState: logs gone and no creaking means uprooted.
|
||||
let active = self.creaking_active();
|
||||
let has_logs = self.with_level(|b, level, ticks| {
|
||||
b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state)
|
||||
});
|
||||
let wanted = if !has_logs && heart.creaking.is_none() {
|
||||
"uprooted"
|
||||
} else if active {
|
||||
"awake"
|
||||
} else {
|
||||
"dormant"
|
||||
};
|
||||
let mut current = self.heart_state_name(state);
|
||||
if wanted != current
|
||||
&& let Some(next) = self.heart_with_state(state, wanted)
|
||||
{
|
||||
self.level_set([key.0, key.1, key.2], next)?;
|
||||
current = wanted.to_owned();
|
||||
if wanted == "uprooted" {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if heart.creaking.is_none() {
|
||||
if current == "awake" && self.spawning_monsters() {
|
||||
let near = self.player.as_ref().is_some_and(|p| {
|
||||
let (dx, dy, dz) = (
|
||||
p.position.x - (f64::from(key.0) + 0.5),
|
||||
p.position.y - (f64::from(key.1) + 0.5),
|
||||
p.position.z - (f64::from(key.2) + 0.5),
|
||||
);
|
||||
dx * dx + dy * dy + dz * dz < 32.0 * 32.0
|
||||
}) && !self.spectator();
|
||||
if near && let Some(id) = self.spawn_protector(key) {
|
||||
let uuid = self.uuid_for(id);
|
||||
heart.creaking = Some((Some(id), uuid));
|
||||
heart.ticks_existed = 0;
|
||||
let at = self.mob_center(id).map(|(c, _)| c);
|
||||
self.audio
|
||||
.play("minecraft:entity.creaking.spawn", at, 1.0, 1.0);
|
||||
self.audio.play(
|
||||
"minecraft:block.creaking_heart.spawn",
|
||||
Some([
|
||||
f64::from(key.0) + 0.5,
|
||||
f64::from(key.1) + 0.5,
|
||||
f64::from(key.2) + 0.5,
|
||||
]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = self.heart_protector(heart) {
|
||||
let persistent = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.is_some_and(|m| m.persistent);
|
||||
let eye = self.player_view().map(|v| v.eye);
|
||||
let stuck = self
|
||||
.mobs
|
||||
.iter_mut()
|
||||
.find(|m| m.id == id)
|
||||
.is_some_and(|m| creaking::player_is_stuck(m, eye));
|
||||
if (!active && !persistent)
|
||||
|| self.heart_distance_to_creaking(id, key) > TOO_FAR
|
||||
|| stuck
|
||||
{
|
||||
self.heart_remove_protector(heart, false);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option<BlockStateId> {
|
||||
let mut s = self.res.assets.registry.state(state)?.clone();
|
||||
s.properties
|
||||
.insert("creaking_heart_state".to_owned(), wanted.to_owned());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
}
|
||||
/// `ServerLevel.isSpawningMonsters`.
|
||||
fn spawning_monsters(&self) -> bool {
|
||||
self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters")
|
||||
}
|
||||
/// `EnvironmentAttributes.CREAKING_ACTIVE`.
|
||||
pub(super) fn creaking_active(&mut self) -> bool {
|
||||
self.with_level(|b, level, ticks| b.creaking_active(level, ticks))
|
||||
}
|
||||
/// Hearts that came with generated or loaded chunks get their block
|
||||
/// entity (`newBlockEntity`) the first time their chunk is seen.
|
||||
fn scan_for_hearts(&mut self) {
|
||||
let Some(heart) = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.default_state("minecraft:creaking_heart")
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let keys: Vec<(i32, i32)> = self
|
||||
.world
|
||||
.chunks
|
||||
.iter()
|
||||
.filter(|(k, c)| c.lit && !self.creaking.scanned.contains(k))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
self.creaking.scanned.insert(key);
|
||||
let Some(chunk) = self.world.chunks.get(&key).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let name = |id: u16| &*self.res.facts.get(BlockStateId(u32::from(id))).name;
|
||||
let _ = heart;
|
||||
for (si, section) in chunk.sections.iter().enumerate() {
|
||||
if section.is_uniform(0) {
|
||||
continue;
|
||||
}
|
||||
for i in 0..4096 {
|
||||
let id = section.get(i);
|
||||
if name(id) != "minecraft:creaking_heart" {
|
||||
continue;
|
||||
}
|
||||
let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32);
|
||||
let pos = (
|
||||
key.0 * 16 + lx,
|
||||
horizon_client::chunk::MIN_Y + si as i32 * 16 + ly,
|
||||
key.1 * 16 + lz,
|
||||
);
|
||||
self.world
|
||||
.block_entities
|
||||
.entry(pos)
|
||||
.or_insert_with(|| BlockEntity::CreakingHeart(Box::default()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
|
||||
self.creaking.scanned.retain(|k| loaded.contains(k));
|
||||
}
|
||||
}
|
||||
|
||||
/// What the creaking code remembers between ticks.
|
||||
#[derive(Default)]
|
||||
pub(super) struct CreakingState {
|
||||
/// Chunks already scanned for heart blocks.
|
||||
scanned: HashSet<(i32, i32)>,
|
||||
}
|
||||
@@ -93,7 +93,8 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
|
||||
.full_collision
|
||||
}
|
||||
}
|
||||
fn seen(m: &Mob) -> Seen {
|
||||
fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
|
||||
let villager = m.species() == Species::Villager;
|
||||
Seen {
|
||||
id: m.id,
|
||||
species: m.species(),
|
||||
@@ -102,7 +103,12 @@ fn seen(m: &Mob) -> Seen {
|
||||
eye_y: m.eye_y(),
|
||||
alive: m.alive(),
|
||||
baby: m.is_baby(),
|
||||
in_love: m.extra.in_love > 0,
|
||||
// A villager is "in love" when it is willing to breed (`canBreed`).
|
||||
in_love: if villager {
|
||||
horizon_client::mobs::villager::can_breed(m)
|
||||
} else {
|
||||
m.extra.in_love > 0
|
||||
},
|
||||
tame: m.extra.tame,
|
||||
hostile: m.hostile(),
|
||||
target: m.ai.target,
|
||||
@@ -115,6 +121,13 @@ fn seen(m: &Mob) -> Seen {
|
||||
bed: (m.species() == Species::Villager)
|
||||
.then_some(m.extra.bed)
|
||||
.flatten(),
|
||||
active_raid: horizon_client::mobs::raider::has_active_raid(m),
|
||||
player_rep: match (villager, player) {
|
||||
(true, Some(uuid)) => {
|
||||
horizon_client::mobs::villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid))
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
@@ -150,6 +163,8 @@ impl Game<'_> {
|
||||
gold_armor: self.wearing_gold(),
|
||||
hurt_by: self.player_hurt_by(),
|
||||
last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)),
|
||||
hero: self.potions.effects.get("hero_of_the_village").is_some(),
|
||||
uuid: self.level.player_uuid.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
/// Biome facts at a position for finalizeSpawn and variant rules.
|
||||
@@ -191,6 +206,17 @@ impl Game<'_> {
|
||||
}
|
||||
/// Create a mob of `kind` at a position, finalized like a natural spawn.
|
||||
pub(super) fn spawn_mob(&mut self, kind: &str, at: [f64; 3], persistent: bool) -> Option<u32> {
|
||||
self.spawn_mob_for(kind, at, persistent, false)
|
||||
}
|
||||
/// `spawn_mob` for a patrol or raid (`EntitySpawnReason.PATROL` / `EVENT`),
|
||||
/// which never rolls a patrol leader.
|
||||
pub(super) fn spawn_mob_for(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
at: [f64; 3],
|
||||
persistent: bool,
|
||||
scripted: bool,
|
||||
) -> Option<u32> {
|
||||
let kind = if kind.contains(':') {
|
||||
kind.to_owned()
|
||||
} else {
|
||||
@@ -208,6 +234,14 @@ impl Game<'_> {
|
||||
);
|
||||
let difficulty = self.local_difficulty(at);
|
||||
spawning::finalize(&mut mob, &facts, &difficulty);
|
||||
if !scripted {
|
||||
let reason = if persistent {
|
||||
horizon_client::mobs::raider::Reason::Other
|
||||
} else {
|
||||
horizon_client::mobs::raider::Reason::Natural
|
||||
};
|
||||
horizon_client::mobs::raider::finalize(&mut mob, reason);
|
||||
}
|
||||
let id = mob.id;
|
||||
self.mobs.push(mob);
|
||||
Some(id)
|
||||
@@ -259,13 +293,29 @@ impl Game<'_> {
|
||||
"on_ground": m.on_ground,
|
||||
"variant": m.extra.variant,
|
||||
"color": m.extra.color,
|
||||
"warden": horizon_client::mobs::warden::describe(m),
|
||||
"villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({
|
||||
"food_level": e.food_level,
|
||||
"inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::<Vec<_>>(),
|
||||
"gossips": e.gossips.len(),
|
||||
"last_slept": e.last_slept,
|
||||
"raid": e.raid,
|
||||
})),
|
||||
"raider": horizon_client::mobs::raider::state(m).map(|s| serde_json::json!({
|
||||
"raid": s.raid_id,
|
||||
"wave": s.wave,
|
||||
"leader": s.patrol_leader,
|
||||
"patrolling": s.patrolling,
|
||||
"patrol_target": s.patrol_target,
|
||||
"vehicle": s.vehicle,
|
||||
})),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() })
|
||||
}
|
||||
/// Highest motion-blocking (no leaves) block + 1 (Heightmap MOTION_BLOCKING_NO_LEAVES).
|
||||
fn motion_top(&self, x: i32, z: i32) -> i32 {
|
||||
pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 {
|
||||
let top = if self.dim == Dim::Nether { 127 } else { 319 };
|
||||
for y in (horizon_client::chunk::MIN_Y..=top).rev() {
|
||||
let f = self.res.facts.get(self.world.block(x, y, z));
|
||||
@@ -602,7 +652,10 @@ impl Game<'_> {
|
||||
}
|
||||
self.tick_inhabited();
|
||||
self.spawn_natural();
|
||||
let snapshot: Vec<Seen> = self.mobs.iter().map(seen).collect();
|
||||
self.tick_patrol_spawner();
|
||||
self.tick_raids();
|
||||
let uuid = self.level.player_uuid;
|
||||
let snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
|
||||
let mut events = Vec::new();
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
let mut dead = Vec::new();
|
||||
@@ -625,6 +678,9 @@ impl Game<'_> {
|
||||
push_apart(&mut mobs);
|
||||
}
|
||||
self.mobs.append(&mut mobs);
|
||||
self.sync_riders();
|
||||
self.villager_reputation_tick();
|
||||
self.villager_pickups();
|
||||
for m in dead {
|
||||
self.mob_died(&m);
|
||||
}
|
||||
@@ -639,12 +695,27 @@ impl Game<'_> {
|
||||
/// LivingEntity.die / dropAllDeathLoot.
|
||||
fn mob_died(&mut self, m: &Mob) {
|
||||
let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0;
|
||||
// LivingEntity.die: the death is heard, and a sculk catalyst nearby
|
||||
// takes the experience.
|
||||
self.sculk_mob_died(m);
|
||||
let consumed =
|
||||
self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |game| {
|
||||
if by_player {
|
||||
experience_reward(m, &mut game.world.random)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
if by_player {
|
||||
self.stats.add("killed", &m.kind.id, 1);
|
||||
self.stats.custom("mob_kills", 1);
|
||||
self.score_player_killed(super::commands::Target::Mob(m.id));
|
||||
let view = self.mob_entity(m);
|
||||
self.trigger_entity("minecraft:player_killed_entity", "entity", &view);
|
||||
}
|
||||
self.score_entity_removed(m.id);
|
||||
self.raider_died(m, by_player);
|
||||
self.villager_murdered(m, by_player);
|
||||
let held = self.held().cloned();
|
||||
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
|
||||
if !m.is_baby() {
|
||||
@@ -688,6 +759,11 @@ impl Game<'_> {
|
||||
for item in gear {
|
||||
self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10);
|
||||
}
|
||||
// AbstractChestedHorse.dropEquipment: the chest contents.
|
||||
for stack in m.extra.items.clone().into_iter().flatten() {
|
||||
self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10);
|
||||
}
|
||||
self.raider_death_loot(m, pos);
|
||||
let worn = if horizon_client::mobs::equine::is_equine(m.species()) {
|
||||
[None, None, None, None]
|
||||
} else {
|
||||
@@ -703,6 +779,7 @@ impl Game<'_> {
|
||||
// Vexes never drop their sword.
|
||||
if let Some(item) = &item
|
||||
&& by_player
|
||||
&& &**item != horizon_client::mobs::raider::BANNER
|
||||
&& m.species() != Species::Vex
|
||||
&& self.world.random.next_float() < 0.085
|
||||
{
|
||||
@@ -720,7 +797,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if by_player {
|
||||
if by_player && !consumed {
|
||||
let xp = experience_reward(m, &mut self.world.random);
|
||||
if xp > 0 {
|
||||
self.spawn_orbs(pos, xp);
|
||||
@@ -863,7 +940,11 @@ impl Game<'_> {
|
||||
m.ai.target = Some(target);
|
||||
}
|
||||
}
|
||||
MobEvent::Projectile(p) => self.creatures.projectiles.push(p),
|
||||
MobEvent::Projectile(p) => {
|
||||
let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]);
|
||||
self.creatures.projectiles.push(p);
|
||||
self.projectile_event("minecraft:projectile_shoot", owner, at);
|
||||
}
|
||||
MobEvent::Spawn(mut m) => {
|
||||
self.next_entity += 1;
|
||||
m.id = self.next_entity;
|
||||
@@ -970,6 +1051,41 @@ impl Game<'_> {
|
||||
}
|
||||
},
|
||||
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
|
||||
MobEvent::Vibration { from, to, ticks } => {
|
||||
self.mob_vibration_particle(from, to, ticks)
|
||||
}
|
||||
MobEvent::DigParticles { at } => self.warden_dig_particles(at),
|
||||
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
|
||||
MobEvent::CreakingHurt {
|
||||
home,
|
||||
by_player,
|
||||
id,
|
||||
} => self.creaking_hurt(home, id, by_player),
|
||||
MobEvent::CreakingTearDown { center, spread } => {
|
||||
self.creaking_tear_down(center, spread)
|
||||
}
|
||||
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
|
||||
MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner),
|
||||
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
|
||||
MobEvent::Firework { at, color, flight } => {
|
||||
self.villager_firework(at, color, flight)
|
||||
}
|
||||
MobEvent::ThrowGift { table, from, to } => self.throw_gift(&table, from, to),
|
||||
MobEvent::PatrolTarget { mob, target } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
horizon_client::mobs::raider::set_patrol_target(m, target);
|
||||
}
|
||||
}
|
||||
MobEvent::RaiderTarget {
|
||||
mob,
|
||||
target,
|
||||
aggressive,
|
||||
} => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
m.ai.target = Some(target);
|
||||
m.ai.aggressive |= aggressive;
|
||||
}
|
||||
}
|
||||
MobEvent::GiftLoot { table, at } => {
|
||||
let drops =
|
||||
self.res
|
||||
@@ -1344,6 +1460,8 @@ impl Game<'_> {
|
||||
return Ok(());
|
||||
}
|
||||
let atp = [at.x, at.y, at.z];
|
||||
// Projectile.onHit: the landing is heard.
|
||||
self.projectile_event("minecraft:projectile_land", p.owner, atp);
|
||||
let source_kind = match p.kind {
|
||||
ProjectileKind::Arrow { .. } => DamageKind::Arrow,
|
||||
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => {
|
||||
@@ -1547,6 +1665,32 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A witch's healing potions reach the raiders around the splash.
|
||||
if matches!(
|
||||
*effect,
|
||||
"minecraft:instant_health" | "minecraft:regeneration"
|
||||
) {
|
||||
let center = at;
|
||||
for m in &mut self.mobs {
|
||||
let d2 = m.position.distance_squared(center);
|
||||
if !m.alive()
|
||||
|| d2 >= 16.0
|
||||
|| !horizon_client::mobs::raider::is_raider(m.species())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let scale = 1.0 - d2.sqrt() / 4.0;
|
||||
if *effect == "minecraft:instant_health" {
|
||||
let heal = (4 << *amplifier) as f64 * scale;
|
||||
m.health = (m.health + heal as f32).min(m.attrs.max_health);
|
||||
} else {
|
||||
let t = (f64::from(*ticks) * scale + 0.5) as i32;
|
||||
if t > 20 {
|
||||
m.add_effect(effect, t, *amplifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.audio.play(
|
||||
"minecraft:entity.splash_potion.break",
|
||||
Some(atp),
|
||||
@@ -2047,6 +2191,7 @@ impl Game<'_> {
|
||||
on_ground,
|
||||
);
|
||||
self.creatures.projectiles.push(proj);
|
||||
self.player_projectile_shot();
|
||||
let sound = match kind {
|
||||
ProjectileKind::Snowball => "minecraft:entity.snowball.throw",
|
||||
ProjectileKind::Egg => "minecraft:entity.egg.throw",
|
||||
|
||||
@@ -144,6 +144,7 @@ impl Game<'_> {
|
||||
);
|
||||
arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
self.player_projectile_shot();
|
||||
let pitch = if index == 0 {
|
||||
1.0
|
||||
} else {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1842,7 +1842,8 @@ impl Game<'_> {
|
||||
/// The boss bar (`BossHealthOverlay`): name and the pink progress bar.
|
||||
pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) {
|
||||
let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End);
|
||||
self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
|
||||
let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
|
||||
self.draw_raid_bar(batch, y);
|
||||
let Some(d) = dragon else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -326,6 +326,9 @@ impl Game<'_> {
|
||||
fire: bool,
|
||||
) -> Result<()> {
|
||||
let mut targets = self.exploded_positions(center, radius);
|
||||
// Explosion.explode: the blast is heard.
|
||||
let ctx = horizon_client::sculk::Context::default();
|
||||
self.post_game_event("minecraft:explode", center, ctx);
|
||||
self.explosion_hurt_entities(center, radius);
|
||||
if interaction != BlockInteraction::Keep {
|
||||
// Util.shuffle(list, level.random)
|
||||
|
||||
@@ -24,6 +24,9 @@ pub(super) struct Rocket {
|
||||
explosions: Vec<FireworkExplosion>,
|
||||
/// Boosting the player (attachedToEntity).
|
||||
attached: bool,
|
||||
/// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on
|
||||
/// the first block it hits.
|
||||
angled: bool,
|
||||
icon: Option<String>,
|
||||
}
|
||||
fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
|
||||
@@ -34,7 +37,7 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
|
||||
.unwrap_or((1, Vec::new()))
|
||||
}
|
||||
impl Game<'_> {
|
||||
fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
|
||||
pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
|
||||
let (flight, explosions) = fireworks_of(stack);
|
||||
let r = &mut self.world.random;
|
||||
let tri = |r: &mut horizon_core::random::LegacyRandom| {
|
||||
@@ -52,6 +55,7 @@ impl Game<'_> {
|
||||
lifetime,
|
||||
explosions,
|
||||
attached,
|
||||
angled: false,
|
||||
icon: Some("item/firework_rocket".into()),
|
||||
}
|
||||
}
|
||||
@@ -73,6 +77,13 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// `FireworkRocketItem.asProjectile` shot out of a dispenser.
|
||||
pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) {
|
||||
let mut rocket = self.new_rocket(at, stack, false);
|
||||
rocket.velocity = velocity;
|
||||
rocket.angled = true;
|
||||
self.rockets.push(rocket);
|
||||
}
|
||||
/// `FireworkRocketItem.use` while gliding: a rocket attached to the player.
|
||||
pub(super) fn boost_firework(&mut self, stack: &ItemStack) -> bool {
|
||||
if &*stack.item != "minecraft:firework_rocket"
|
||||
@@ -118,12 +129,23 @@ impl Game<'_> {
|
||||
Vec3::new(r.position.x - h, r.position.y, r.position.z - h),
|
||||
Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h),
|
||||
);
|
||||
let wanted = Vec3::new(
|
||||
r.velocity.x * 1.15,
|
||||
r.velocity.y + 0.04,
|
||||
r.velocity.z * 1.15,
|
||||
);
|
||||
let wanted = if r.angled {
|
||||
r.velocity
|
||||
} else {
|
||||
Vec3::new(
|
||||
r.velocity.x * 1.15,
|
||||
r.velocity.y + 0.04,
|
||||
r.velocity.z * 1.15,
|
||||
)
|
||||
};
|
||||
if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) {
|
||||
let blocked = (moved.x - wanted.x).abs() > 1e-7
|
||||
|| (moved.y - wanted.y).abs() > 1e-7
|
||||
|| (moved.z - wanted.z).abs() > 1e-7;
|
||||
if r.angled && blocked {
|
||||
// hitTargetOrDeflectSelf: explode on the block.
|
||||
r.life = r.lifetime;
|
||||
}
|
||||
let horizontal =
|
||||
(moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7;
|
||||
r.position = Vec3::new(
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
//! Data packs in the game: functions (`/function`, `/return`, tick and load
|
||||
//! tags, `/schedule`), predicates, `/reload` and `/datapack`.
|
||||
use super::{
|
||||
Game,
|
||||
commands::{
|
||||
R, err,
|
||||
execute::{ExecState, Source},
|
||||
},
|
||||
};
|
||||
use horizon_client::{
|
||||
command::{Arg, Context},
|
||||
datapack::{self, DataPack, DataStore, Function},
|
||||
save,
|
||||
scoreboard::bracketed,
|
||||
text::{self, Text},
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// A `TimerQueue` event.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct Scheduled {
|
||||
/// `ns:function`, or `#ns:tag` for a function tag.
|
||||
pub id: String,
|
||||
pub time: i64,
|
||||
pub seq: u64,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct FnState {
|
||||
pub store: DataStore,
|
||||
packs: Vec<DataPack>,
|
||||
/// Enabled pack ids, in load order (later overrides earlier).
|
||||
enabled: Vec<String>,
|
||||
loaded: bool,
|
||||
/// Run the `minecraft:load` tag on the next tick.
|
||||
load_pending: bool,
|
||||
pub schedule: Vec<Scheduled>,
|
||||
next_seq: u64,
|
||||
}
|
||||
/// What a function reported through `return`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Outcome {
|
||||
NoReturn,
|
||||
Value(i32),
|
||||
Fail,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
// ---- loading -----------------------------------------------------------
|
||||
|
||||
fn datapack_settings_path(&self) -> std::path::PathBuf {
|
||||
self.world_root.join("datapacks.json")
|
||||
}
|
||||
/// Discover and load the data packs of the world (once, or on `/reload`).
|
||||
pub(super) fn ensure_datapacks(&mut self) {
|
||||
if self.fns.loaded || self.world_root.as_os_str().is_empty() {
|
||||
return;
|
||||
}
|
||||
self.reload_datapacks(false);
|
||||
}
|
||||
pub(super) fn reload_datapacks(&mut self, run_load: bool) {
|
||||
self.fns.packs = datapack::discover(&self.world_root);
|
||||
let saved: Option<serde_json::Value> = std::fs::read(self.datapack_settings_path())
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok());
|
||||
let list = |key: &str| -> Vec<String> {
|
||||
saved
|
||||
.as_ref()
|
||||
.and_then(|v| v[key].as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|s| s.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let disabled: BTreeSet<String> = list("disabled").into_iter().collect();
|
||||
let mut enabled: Vec<String> = list("enabled")
|
||||
.into_iter()
|
||||
.filter(|id| self.fns.packs.iter().any(|p| &p.id == id))
|
||||
.collect();
|
||||
for p in &self.fns.packs {
|
||||
if !enabled.contains(&p.id) && !disabled.contains(&p.id) {
|
||||
enabled.push(p.id.clone());
|
||||
}
|
||||
}
|
||||
self.fns.enabled = enabled;
|
||||
self.rebuild_store();
|
||||
self.fns.loaded = true;
|
||||
self.fns.load_pending = true;
|
||||
let _ = run_load;
|
||||
if self.fns.schedule.is_empty() {
|
||||
self.load_schedule();
|
||||
}
|
||||
}
|
||||
fn rebuild_store(&mut self) {
|
||||
let packs: Vec<&DataPack> = self
|
||||
.fns
|
||||
.enabled
|
||||
.iter()
|
||||
.filter_map(|id| self.fns.packs.iter().find(|p| &p.id == id))
|
||||
.collect();
|
||||
let store = DataStore::load(&packs);
|
||||
for (id, e) in &store.errors {
|
||||
eprintln!("Horizon: failed to load function {id}: {e}");
|
||||
}
|
||||
self.fns.store = store;
|
||||
self.sync_function_registries();
|
||||
}
|
||||
fn save_datapack_settings(&self) {
|
||||
let disabled: Vec<&String> = self
|
||||
.fns
|
||||
.packs
|
||||
.iter()
|
||||
.map(|p| &p.id)
|
||||
.filter(|id| !self.fns.enabled.contains(id))
|
||||
.collect();
|
||||
let json = serde_json::json!({"enabled": self.fns.enabled, "disabled": disabled});
|
||||
let _ = std::fs::write(self.datapack_settings_path(), json.to_string());
|
||||
}
|
||||
pub(super) fn sync_function_registries(&mut self) {
|
||||
let reg = &mut self.ui.registries;
|
||||
reg.functions = self.fns.store.functions.keys().cloned().collect();
|
||||
reg.function_tags = self.fns.store.function_tags.keys().cloned().collect();
|
||||
reg.predicates = self.fns.store.predicates.keys().cloned().collect();
|
||||
reg.schedules = self.fns.schedule.iter().map(|s| s.id.clone()).collect();
|
||||
reg.datapacks_enabled = std::iter::once("vanilla".to_owned())
|
||||
.chain(self.fns.enabled.iter().cloned())
|
||||
.collect();
|
||||
reg.datapacks_disabled = self
|
||||
.fns
|
||||
.packs
|
||||
.iter()
|
||||
.map(|p| p.id.clone())
|
||||
.filter(|id| !self.fns.enabled.contains(id))
|
||||
.collect();
|
||||
}
|
||||
|
||||
// ---- scheduled events ------------------------------------------------------
|
||||
|
||||
fn schedule_path(&self) -> std::path::PathBuf {
|
||||
self.world_root.join("data/minecraft/scheduled_events.dat")
|
||||
}
|
||||
fn load_schedule(&mut self) {
|
||||
let Some(root) = save::read_dat(&self.schedule_path()) else {
|
||||
return;
|
||||
};
|
||||
let Some(Tag::List(events)) = root.get("data").and_then(|d| d.get("events")) else {
|
||||
return;
|
||||
};
|
||||
for e in events {
|
||||
let (Some(Tag::Long(time)), Some(Tag::String(id)), Some(cb)) =
|
||||
(e.get("trigger_time"), e.get("id"), e.get("callback"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let _ = cb;
|
||||
self.fns.next_seq += 1;
|
||||
self.fns.schedule.push(Scheduled {
|
||||
id: id.to_string_lossy(),
|
||||
time: *time,
|
||||
seq: self.fns.next_seq,
|
||||
});
|
||||
}
|
||||
}
|
||||
pub(super) fn save_schedule(&self) {
|
||||
if !self.fns.loaded || self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut events = self.fns.schedule.clone();
|
||||
events.sort_by_key(|e| (e.time, e.seq));
|
||||
let list = events
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let (kind, name) = match e.id.strip_prefix('#') {
|
||||
Some(tag) => ("minecraft:function_tag", tag),
|
||||
None => ("minecraft:function", e.id.as_str()),
|
||||
};
|
||||
Tag::compound([
|
||||
("trigger_time", Tag::Long(e.time)),
|
||||
("id", Tag::String(e.id.as_str().into())),
|
||||
(
|
||||
"callback",
|
||||
Tag::compound([
|
||||
("type", Tag::String(kind.into())),
|
||||
("id", Tag::String(name.into())),
|
||||
]),
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
if events.is_empty() && !self.schedule_path().exists() {
|
||||
return;
|
||||
}
|
||||
let _ = save::write_dat(
|
||||
&self.schedule_path(),
|
||||
Tag::compound([
|
||||
("data", Tag::compound([("events", Tag::List(list))])),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- ticking -----------------------------------------------------------------
|
||||
|
||||
/// `ServerFunctionManager.tick` and the scheduled events.
|
||||
pub(super) fn tick_functions(&mut self) {
|
||||
self.ensure_datapacks();
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
self.exec = ExecState::default();
|
||||
let source = self.server_source();
|
||||
if self.fns.load_pending {
|
||||
self.fns.load_pending = false;
|
||||
for f in self.fns.store.tag_functions("minecraft:load") {
|
||||
self.run_function_by_id(&f, None, source);
|
||||
}
|
||||
}
|
||||
let now = self.world.game_time;
|
||||
loop {
|
||||
let due = self
|
||||
.fns
|
||||
.schedule
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| e.time <= now)
|
||||
.min_by_key(|(_, e)| (e.time, e.seq))
|
||||
.map(|(i, _)| i);
|
||||
let Some(i) = due else { break };
|
||||
let event = self.fns.schedule.remove(i);
|
||||
match event.id.strip_prefix('#') {
|
||||
Some(tag) => {
|
||||
for f in self.fns.store.tag_functions(tag) {
|
||||
self.run_function_by_id(&f, None, source);
|
||||
}
|
||||
}
|
||||
None => self.run_function_by_id(&event.id, None, source),
|
||||
}
|
||||
}
|
||||
for f in self.fns.store.tag_functions("minecraft:tick") {
|
||||
self.run_function_by_id(&f, None, source);
|
||||
}
|
||||
}
|
||||
fn run_function_by_id(&mut self, id: &str, args: Option<&Tag>, source: Source) {
|
||||
self.exec.commands = 0;
|
||||
if let Some(f) = self.fns.store.functions.get(id).cloned() {
|
||||
let _ = self.run_function(&f, args, source);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- running -----------------------------------------------------------------
|
||||
|
||||
/// Run one function with `source`: its commands in order, until a `return`.
|
||||
pub(in crate::game) fn run_function(
|
||||
&mut self,
|
||||
f: &Function,
|
||||
args: Option<&Tag>,
|
||||
source: Source,
|
||||
) -> R<Outcome> {
|
||||
let lines = f.instantiate(args).map_err(|(key, a)| {
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
a.iter().map(|s| s as &dyn std::fmt::Display).collect();
|
||||
err(
|
||||
"commands.function.instantiationFailure",
|
||||
&[&f.id, &horizon_client::text::Text::tr(&key, &args).plain()],
|
||||
)
|
||||
})?;
|
||||
if self.exec.function_depth >= 128 {
|
||||
return Ok(Outcome::NoReturn);
|
||||
}
|
||||
self.exec.function_depth += 1;
|
||||
let outer = self.exec.returned.take();
|
||||
let inner = Source {
|
||||
silent: true,
|
||||
store: None,
|
||||
..source
|
||||
};
|
||||
for line in lines {
|
||||
let _ = self.execute_line(&line, inner);
|
||||
if self.exec.returned.is_some() {
|
||||
break;
|
||||
}
|
||||
if self.exec.commands > self.ui.rules.int("max_command_sequence_length").max(1) as u32 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let returned = std::mem::replace(&mut self.exec.returned, outer);
|
||||
self.exec.function_depth -= 1;
|
||||
Ok(match returned {
|
||||
None => Outcome::NoReturn,
|
||||
Some(Some(v)) => Outcome::Value(v),
|
||||
Some(None) => Outcome::Fail,
|
||||
})
|
||||
}
|
||||
/// The functions a `FunctionArgument` names: a function or a tag.
|
||||
pub(in crate::game) fn functions_named(&mut self, name: &str) -> R<Vec<Function>> {
|
||||
self.ensure_datapacks();
|
||||
match name.strip_prefix('#') {
|
||||
Some(tag) => {
|
||||
if !self.fns.store.function_tags.contains_key(tag) {
|
||||
return Err(err("arguments.function.tag.unknown", &[&tag]));
|
||||
}
|
||||
Ok(self
|
||||
.fns
|
||||
.store
|
||||
.tag_functions(tag)
|
||||
.iter()
|
||||
.filter_map(|id| self.fns.store.functions.get(id).cloned())
|
||||
.collect())
|
||||
}
|
||||
None => self
|
||||
.fns
|
||||
.store
|
||||
.functions
|
||||
.get(name)
|
||||
.cloned()
|
||||
.map(|f| vec![f])
|
||||
.ok_or_else(|| err("arguments.function.unknown", &[&name])),
|
||||
}
|
||||
}
|
||||
/// `if function`: what each function returns (None if it did not).
|
||||
pub(in crate::game) fn call_function_ref(
|
||||
&mut self,
|
||||
name: &str,
|
||||
args: Option<&Tag>,
|
||||
) -> R<Vec<Option<i32>>> {
|
||||
let functions = self.functions_named(name)?;
|
||||
let source = self.command_source.unwrap_or_else(|| self.player_source());
|
||||
let mut out = Vec::new();
|
||||
for f in functions {
|
||||
out.push(match self.run_function(&f, args, source)? {
|
||||
Outcome::NoReturn => None,
|
||||
Outcome::Value(v) => Some(v),
|
||||
Outcome::Fail => Some(0),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---- commands ------------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_function(&mut self, ctx: &Context) -> R<i32> {
|
||||
let Some(Arg::Resource(name)) = ctx.get("name").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let functions = self.functions_named(&name)?;
|
||||
if functions.is_empty() {
|
||||
return Err(err("commands.function.scheduled.no_functions", &[&name]));
|
||||
}
|
||||
let args = if ctx.has("with") {
|
||||
let r = self.data_ref_named(ctx, 0, "source")?;
|
||||
let data = self.data_of(&r)?;
|
||||
let tag = match ctx.get("path") {
|
||||
Some(Arg::Str(p)) => {
|
||||
let path = horizon_client::nbt_path::NbtPath::parse(p)
|
||||
.map_err(horizon_client::data_cmd::path_error)?;
|
||||
horizon_client::data_cmd::single_tag(&path, &data)?
|
||||
}
|
||||
_ => data,
|
||||
};
|
||||
if !matches!(tag, Tag::Compound(_)) {
|
||||
return Err(err(
|
||||
"commands.function.error.argument_not_compound",
|
||||
&[&"tag"],
|
||||
));
|
||||
}
|
||||
Some(tag)
|
||||
} else if let Some(Arg::Str(text)) = ctx.get("arguments") {
|
||||
Some(
|
||||
horizon_world::nbt::parse_snbt(text)
|
||||
.map_err(|e| err("argument.nbt.invalid", &[&e]))?
|
||||
.0,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let message = if functions.len() == 1 {
|
||||
Text::translate(
|
||||
"commands.function.scheduled.single",
|
||||
&[Text::literal(functions[0].id.clone())],
|
||||
)
|
||||
} else {
|
||||
Text::translate(
|
||||
"commands.function.scheduled.multiple",
|
||||
&[horizon_client::scoreboard_cmd::format_list(
|
||||
functions
|
||||
.iter()
|
||||
.map(|f| Text::literal(f.id.clone()))
|
||||
.collect(),
|
||||
)],
|
||||
)
|
||||
};
|
||||
self.feedback(message);
|
||||
let source = self.command_source.unwrap_or_else(|| self.player_source());
|
||||
let mut sum: i32 = 0;
|
||||
let mut any = false;
|
||||
let mut failed = false;
|
||||
for f in functions {
|
||||
match self.run_function(&f, args.as_ref(), source)? {
|
||||
Outcome::NoReturn => {}
|
||||
Outcome::Value(v) => {
|
||||
any = true;
|
||||
sum = sum.wrapping_add(v);
|
||||
let message = Text::translate(
|
||||
"commands.function.result",
|
||||
&[Text::literal(f.id.clone()), Text::literal(v.to_string())],
|
||||
);
|
||||
self.feedback(message);
|
||||
}
|
||||
Outcome::Fail => {
|
||||
any = true;
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.exec.callback = Some(if failed && sum == 0 {
|
||||
Some((false, 0))
|
||||
} else if any {
|
||||
Some((true, sum))
|
||||
} else {
|
||||
None
|
||||
});
|
||||
Ok(sum)
|
||||
}
|
||||
/// `return <value>` and `return fail` (`return run` is a chain).
|
||||
pub(super) fn cmd_return(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
if id == "return.fail" {
|
||||
self.finish_return(None);
|
||||
self.exec.callback = Some(Some((false, 0)));
|
||||
return Ok(0);
|
||||
}
|
||||
let value = match ctx.get("value") {
|
||||
Some(Arg::Int(v)) => *v,
|
||||
_ => 0,
|
||||
};
|
||||
self.finish_return(Some(value));
|
||||
Ok(value)
|
||||
}
|
||||
pub(super) fn cmd_schedule(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
self.ensure_datapacks();
|
||||
if id == "schedule.clear" {
|
||||
let Some(Arg::Resource(name)) = ctx.get("function").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let before = self.fns.schedule.len();
|
||||
self.fns.schedule.retain(|e| e.id != name);
|
||||
let count = before - self.fns.schedule.len();
|
||||
if count == 0 {
|
||||
return Err(err("commands.schedule.cleared.failure", &[&name]));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.schedule.cleared.success",
|
||||
&[Text::literal(count.to_string()), Text::literal(name)],
|
||||
));
|
||||
self.sync_function_registries();
|
||||
return Ok(count as i32);
|
||||
}
|
||||
let Some(Arg::Resource(name)) = ctx.get("function").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let time = match ctx.get("time") {
|
||||
Some(Arg::Int(t)) => *t,
|
||||
_ => 0,
|
||||
};
|
||||
if time == 0 {
|
||||
return Err(err("commands.schedule.same_tick", &[]));
|
||||
}
|
||||
let replace = !ctx.has("append");
|
||||
let tick_time = self.world.game_time + i64::from(time);
|
||||
let schedule_id = match name.strip_prefix('#') {
|
||||
Some(tag) => {
|
||||
if !self.fns.store.function_tags.contains_key(tag) {
|
||||
return Err(err("arguments.function.tag.unknown", &[&tag]));
|
||||
}
|
||||
name.clone()
|
||||
}
|
||||
None => {
|
||||
let Some(f) = self.fns.store.functions.get(&name) else {
|
||||
return Err(err("arguments.function.unknown", &[&name]));
|
||||
};
|
||||
if f.is_macro() {
|
||||
return Err(err("commands.schedule.macro", &[]));
|
||||
}
|
||||
name.clone()
|
||||
}
|
||||
};
|
||||
if replace {
|
||||
self.fns.schedule.retain(|e| e.id != schedule_id);
|
||||
}
|
||||
if !self
|
||||
.fns
|
||||
.schedule
|
||||
.iter()
|
||||
.any(|e| e.id == schedule_id && e.time == tick_time)
|
||||
{
|
||||
self.fns.next_seq += 1;
|
||||
let seq = self.fns.next_seq;
|
||||
self.fns.schedule.push(Scheduled {
|
||||
id: schedule_id,
|
||||
time: tick_time,
|
||||
seq,
|
||||
});
|
||||
}
|
||||
let key = if name.starts_with('#') {
|
||||
"commands.schedule.created.tag"
|
||||
} else {
|
||||
"commands.schedule.created.function"
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
key,
|
||||
&[
|
||||
Text::literal(name.trim_start_matches('#').to_owned()),
|
||||
Text::literal(time.to_string()),
|
||||
Text::literal(tick_time.to_string()),
|
||||
],
|
||||
));
|
||||
self.sync_function_registries();
|
||||
Ok((tick_time.rem_euclid(i64::from(i32::MAX))) as i32)
|
||||
}
|
||||
pub(super) fn cmd_reload(&mut self) -> R<i32> {
|
||||
self.reload_datapacks(true);
|
||||
self.feedback(Text::translate("commands.reload.success", &[]));
|
||||
Ok(1)
|
||||
}
|
||||
fn pack_link(&self, id: &str, enabled: bool) -> Text {
|
||||
let hint = if enabled { "disable" } else { "enable" };
|
||||
let style = text::Style {
|
||||
color: Some(if enabled { text::GREEN } else { text::RED }),
|
||||
suggest: Some(format!("/datapack {hint} \"{id}\"")),
|
||||
..text::Style::default()
|
||||
};
|
||||
let description = self
|
||||
.fns
|
||||
.packs
|
||||
.iter()
|
||||
.find(|p| p.id == id)
|
||||
.map_or_else(|| "Default data pack".to_owned(), DataPack::description);
|
||||
let style = text::Style {
|
||||
hover: Some(Box::new(Text::literal(format!("{id}\n{description}")))),
|
||||
..style
|
||||
};
|
||||
bracketed(Text::literal(id).with_style(&style))
|
||||
}
|
||||
pub(super) fn cmd_datapack(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
self.ensure_datapacks();
|
||||
let name = match ctx.get("name") {
|
||||
Some(Arg::Str(n)) => Some(n.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let enabled_ids: Vec<String> = std::iter::once("vanilla".to_owned())
|
||||
.chain(self.fns.enabled.iter().cloned())
|
||||
.collect();
|
||||
let available: Vec<String> = self
|
||||
.fns
|
||||
.packs
|
||||
.iter()
|
||||
.map(|p| p.id.clone())
|
||||
.filter(|p| !enabled_ids.contains(p))
|
||||
.collect();
|
||||
match id {
|
||||
"datapack.list" => {
|
||||
let want_enabled = ctx.has("enabled") || (!ctx.has("available"));
|
||||
let want_available = ctx.has("available") || (!ctx.has("enabled"));
|
||||
let mut total = 0;
|
||||
if want_enabled {
|
||||
let links: Vec<Text> = enabled_ids
|
||||
.iter()
|
||||
.map(|p| self.pack_link(p, true))
|
||||
.collect();
|
||||
total += links.len();
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.list.enabled.success",
|
||||
&[
|
||||
Text::literal(links.len().to_string()),
|
||||
horizon_client::scoreboard_cmd::format_list(links),
|
||||
],
|
||||
));
|
||||
}
|
||||
if want_available {
|
||||
if available.is_empty() {
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.list.available.none",
|
||||
&[],
|
||||
));
|
||||
} else {
|
||||
let links: Vec<Text> =
|
||||
available.iter().map(|p| self.pack_link(p, false)).collect();
|
||||
total += links.len();
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.list.available.success",
|
||||
&[
|
||||
Text::literal(links.len().to_string()),
|
||||
horizon_client::scoreboard_cmd::format_list(links),
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(total as i32)
|
||||
}
|
||||
"datapack.enable" => {
|
||||
let name = name.unwrap_or_default();
|
||||
if !self.fns.packs.iter().any(|p| p.id == name) && name != "vanilla" {
|
||||
return Err(err("commands.datapack.unknown", &[&name]));
|
||||
}
|
||||
if enabled_ids.contains(&name) {
|
||||
return Err(err("commands.datapack.enable.failed", &[&name]));
|
||||
}
|
||||
let existing = match ctx.get("existing") {
|
||||
Some(Arg::Str(e)) => Some(e.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let position = if ctx.has("first") {
|
||||
0
|
||||
} else if let Some(e) = &existing {
|
||||
let Some(i) = self.fns.enabled.iter().position(|p| p == e) else {
|
||||
return Err(err("commands.datapack.unknown", &[e]));
|
||||
};
|
||||
if ctx.has("before") { i } else { i + 1 }
|
||||
} else {
|
||||
self.fns.enabled.len()
|
||||
};
|
||||
self.fns.enabled.insert(position, name.clone());
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.modify.enable",
|
||||
&[self.pack_link(&name, true)],
|
||||
));
|
||||
self.apply_pack_change();
|
||||
Ok(self.fns.enabled.len() as i32)
|
||||
}
|
||||
_ => {
|
||||
let name = name.unwrap_or_default();
|
||||
if !self.fns.packs.iter().any(|p| p.id == name) && name != "vanilla" {
|
||||
return Err(err("commands.datapack.unknown", &[&name]));
|
||||
}
|
||||
let Some(i) = self.fns.enabled.iter().position(|p| p == &name) else {
|
||||
return Err(err("commands.datapack.disable.failed", &[&name]));
|
||||
};
|
||||
self.fns.enabled.remove(i);
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.modify.disable",
|
||||
&[self.pack_link(&name, false)],
|
||||
));
|
||||
self.apply_pack_change();
|
||||
Ok(self.fns.enabled.len() as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn apply_pack_change(&mut self) {
|
||||
self.save_datapack_settings();
|
||||
self.rebuild_store();
|
||||
self.fns.load_pending = true;
|
||||
self.feedback(Text::translate("commands.reload.success", &[]));
|
||||
}
|
||||
|
||||
// ---- predicates -------------------------------------------------------------------
|
||||
|
||||
/// `if predicate`: a datapack predicate tested for the source entity.
|
||||
pub(in crate::game) fn check_predicate(&mut self, id: &str) -> R<bool> {
|
||||
self.ensure_datapacks();
|
||||
let Some(json) = self.fns.store.predicates.get(id).cloned() else {
|
||||
return Err(err("argument.predicate.unknown", &[&id]));
|
||||
};
|
||||
let source = self.command_source.unwrap_or_else(|| self.player_source());
|
||||
let view = source.entity.map(|t| self.entity_view_of(t));
|
||||
Ok(self.conditions_hold(&json, view.as_ref(), source.pos))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Building golems from blocks (`CarvedPumpkinBlock.trySpawnGolem`): a carved
|
||||
//! pumpkin or jack o'lantern on two snow blocks makes a snow golem, and on a
|
||||
//! T of four iron blocks (arms along X or Z, nothing beside the legs) an iron
|
||||
//! golem. Players placing the pumpkin and dispensers share it.
|
||||
use super::Game;
|
||||
use horizon_client::Result;
|
||||
|
||||
impl Game<'_> {
|
||||
fn golem_block(&self, p: [i32; 3]) -> &str {
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
&self.res.facts.get(state).name
|
||||
}
|
||||
fn is_golem_head(&self, p: [i32; 3]) -> bool {
|
||||
matches!(
|
||||
self.golem_block(p),
|
||||
"minecraft:carved_pumpkin" | "minecraft:jack_o_lantern"
|
||||
)
|
||||
}
|
||||
/// The blocks of the golem whose head is at `head` and its spawn base
|
||||
/// (`BlockPattern.find`), snow golems first.
|
||||
fn find_golem(&self, head: [i32; 3]) -> Option<(&'static str, Vec<[i32; 3]>, [i32; 3])> {
|
||||
let below = |n: i32| [head[0], head[1] - n, head[2]];
|
||||
if self.golem_block(below(1)) == "minecraft:snow_block"
|
||||
&& self.golem_block(below(2)) == "minecraft:snow_block"
|
||||
{
|
||||
return Some((
|
||||
"minecraft:snow_golem",
|
||||
vec![head, below(1), below(2)],
|
||||
below(2),
|
||||
));
|
||||
}
|
||||
for (ax, az) in [(1, 0), (0, 1)] {
|
||||
let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s];
|
||||
let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block");
|
||||
let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2]));
|
||||
if arms
|
||||
&& self.golem_block(side(0, 2)) == "minecraft:iron_block"
|
||||
&& [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2)))
|
||||
{
|
||||
let mut blocks = vec![head];
|
||||
blocks.extend((-1..=1).map(|s| side(s, 1)));
|
||||
blocks.push(side(0, 2));
|
||||
return Some(("minecraft:iron_golem", blocks, side(0, 2)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CarvedPumpkinBlock.canSpawnGolem`.
|
||||
pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool {
|
||||
self.find_golem(head).is_some()
|
||||
}
|
||||
/// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed.
|
||||
pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> {
|
||||
if !self.is_golem_head(head) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some((kind, blocks, base)) = self.find_golem(head) else {
|
||||
return Ok(());
|
||||
};
|
||||
for p in blocks {
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
self.destroy_particles(p, state);
|
||||
self.level_set(p, self.world.air)?;
|
||||
}
|
||||
let at = [
|
||||
f64::from(base[0]) + 0.5,
|
||||
f64::from(base[1]) + 0.05,
|
||||
f64::from(base[2]) + 0.5,
|
||||
];
|
||||
if let Some(id) = self.spawn_mob(kind, at, false)
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
|
||||
{
|
||||
m.yaw = 0.0;
|
||||
m.body_yaw = 0.0;
|
||||
m.head_yaw = 0.0;
|
||||
m.previous_yaw = 0.0;
|
||||
m.previous_body_yaw = 0.0;
|
||||
m.previous_head_yaw = 0.0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,10 @@ impl Game<'_> {
|
||||
Some([x, top.y, z])
|
||||
}
|
||||
pub(super) fn spawn_bolt(&mut self, at: [f64; 3], visual_only: bool) {
|
||||
if !visual_only {
|
||||
let ctx = horizon_client::sculk::Context::default();
|
||||
self.post_game_event("minecraft:lightning_strike", at, ctx);
|
||||
}
|
||||
let r = &mut self.world.random;
|
||||
let seed = r.next_long();
|
||||
let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a
|
||||
//! banner with a dye (and a pattern item for the special patterns), the
|
||||
//! six-layer limit, the scrolling pattern list and the banner preview.
|
||||
use super::{
|
||||
Game,
|
||||
stations::{INPUT, Station},
|
||||
};
|
||||
use horizon_client::{
|
||||
banner::{self, BannerLayer},
|
||||
hud::{HudBatch, Rect, rgba},
|
||||
items::ItemStack,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Per-menu loom state: `selectablePatterns`, the selected index and the
|
||||
/// screen's scroller.
|
||||
#[derive(Default)]
|
||||
pub(super) struct LoomState {
|
||||
pub(super) patterns: Vec<Arc<str>>,
|
||||
pub(super) selected: Option<usize>,
|
||||
/// `displayPatterns`: the pattern buttons are shown.
|
||||
pub(super) display: bool,
|
||||
pub(super) has_max: bool,
|
||||
pub(super) scroll: f32,
|
||||
pub(super) start_row: usize,
|
||||
pub(super) scrolling: bool,
|
||||
}
|
||||
impl LoomState {
|
||||
fn total_rows(&self) -> usize {
|
||||
self.patterns.len().div_ceil(4)
|
||||
}
|
||||
fn offscreen_rows(&self) -> i32 {
|
||||
self.total_rows() as i32 - 4
|
||||
}
|
||||
fn scroll_active(&self) -> bool {
|
||||
self.display && self.patterns.len() > 16
|
||||
}
|
||||
/// `startRow` for a scroller position.
|
||||
fn row_for(&self, offs: f32) -> usize {
|
||||
((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize
|
||||
}
|
||||
}
|
||||
|
||||
const BUTTON: f32 = 14.0;
|
||||
|
||||
fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool {
|
||||
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
|
||||
}
|
||||
/// A sub-rectangle of a sprite given in texels.
|
||||
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
|
||||
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
|
||||
Rect {
|
||||
u0: r.u0 + x * du,
|
||||
v0: r.v0 + y * dv,
|
||||
u1: r.u0 + (x + w) * du,
|
||||
v1: r.v0 + (y + h) * dv,
|
||||
w: w as u32,
|
||||
h: h as u32,
|
||||
}
|
||||
}
|
||||
/// A dye's tint as a HUD vertex colour.
|
||||
pub(super) fn dye_color(name: &str) -> u32 {
|
||||
let c = banner::dye_rgb(name);
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `LoomMenu.slotsChanged` and the screen's `containerChanged`.
|
||||
pub(super) fn loom_changed(&self, s: &mut Station) {
|
||||
let banners = &self.res.stations.banners;
|
||||
let items = &self.res.items;
|
||||
let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref());
|
||||
let l = &mut s.loom;
|
||||
let mut result = None;
|
||||
if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) {
|
||||
let valid = l.selected.is_some_and(|i| i < l.patterns.len());
|
||||
let previous = std::mem::take(&mut l.patterns);
|
||||
l.patterns = banners.selectable(s.inputs[2].as_ref());
|
||||
let shown = if l.patterns.len() == 1 {
|
||||
l.selected = Some(0);
|
||||
Some(l.patterns[0].clone())
|
||||
} else if !valid {
|
||||
l.selected = None;
|
||||
None
|
||||
} else {
|
||||
let value = previous[l.selected.unwrap_or(0)].clone();
|
||||
match l.patterns.iter().position(|p| *p == value) {
|
||||
Some(i) => {
|
||||
l.selected = Some(i);
|
||||
Some(value)
|
||||
}
|
||||
None => {
|
||||
l.selected = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
l.has_max = banner::has_max_layers(banner_stack);
|
||||
if let Some(pattern) = shown {
|
||||
if l.has_max {
|
||||
l.selected = None;
|
||||
} else if let Some(dye) = banners.loom_dye(items, dye_stack) {
|
||||
result = Some(banner::loom_result(banner_stack, &dye, &pattern));
|
||||
}
|
||||
}
|
||||
l.display = !l.has_max && !l.patterns.is_empty();
|
||||
} else {
|
||||
l.patterns.clear();
|
||||
l.selected = None;
|
||||
l.has_max = banner_in.is_some_and(banner::has_max_layers);
|
||||
l.display = false;
|
||||
}
|
||||
if l.start_row >= l.total_rows() {
|
||||
l.start_row = 0;
|
||||
l.scroll = 0.0;
|
||||
}
|
||||
s.result = result;
|
||||
}
|
||||
/// The loom slots' `mayPlace`.
|
||||
pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) {
|
||||
let banners = &self.res.stations.banners;
|
||||
let ok = match input {
|
||||
0 => stack.item.ends_with("_banner"),
|
||||
1 => banners.loom_dye(&self.res.items, stack).is_some(),
|
||||
_ => banners.is_pattern_item(&self.res.items, stack),
|
||||
};
|
||||
(ok, 64)
|
||||
}
|
||||
/// The result slot's `onTake`: one banner and one dye are used up.
|
||||
pub(super) fn loom_taken(&mut self, s: &mut Station) {
|
||||
for slot in &mut s.inputs[..2] {
|
||||
if let Some(x) = slot.as_mut() {
|
||||
x.count -= 1;
|
||||
if x.count == 0 {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.inputs[0].is_none() || s.inputs[1].is_none() {
|
||||
s.loom.selected = None;
|
||||
}
|
||||
if s.last_sound != self.ticks {
|
||||
s.last_sound = self.ticks;
|
||||
let pos = s.pos;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.audio
|
||||
.play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
/// `LoomMenu.quickMoveStack` from an inventory slot.
|
||||
pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool {
|
||||
let banners = &self.res.stations.banners;
|
||||
let items = &self.res.items;
|
||||
let target = if stack.item.ends_with("_banner") {
|
||||
Some(INPUT)
|
||||
} else if banners.loom_dye(items, stack).is_some() {
|
||||
Some(INPUT + 1)
|
||||
} else if banners.is_pattern_item(items, stack) {
|
||||
Some(INPUT + 2)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match target {
|
||||
Some(t) => self.move_to(stack, &[t], false),
|
||||
None if (9..36).contains(&slot) => {
|
||||
let hotbar: Vec<usize> = (0..9).collect();
|
||||
self.move_to(stack, &hotbar, false)
|
||||
}
|
||||
None if slot < 9 => {
|
||||
let main: Vec<usize> = (9..36).collect();
|
||||
self.move_to(stack, &main, false)
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
/// A left click inside the loom's pattern grid or scroller.
|
||||
pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool {
|
||||
let Some(s) = self.station.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let l = &s.loom;
|
||||
if !l.display {
|
||||
return false;
|
||||
}
|
||||
for row in 0..4 {
|
||||
for column in 0..4 {
|
||||
let index = (row + l.start_row) * 4 + column;
|
||||
let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON);
|
||||
if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) {
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.loom.selected = Some(index);
|
||||
}
|
||||
self.audio
|
||||
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
|
||||
self.station_changed();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if inside(local, 119.0, 9.0, 12.0, 56.0)
|
||||
&& let Some(s) = self.station.as_mut()
|
||||
{
|
||||
s.loom.scrolling = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `LoomScreen.mouseDragged` on the scroller.
|
||||
pub(super) fn loom_drag(&mut self) {
|
||||
let Some(size) = self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.map(|r| [r.config.width, r.config.height])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (_, oy) = self.inventory_origin(&HudBatch::new(size));
|
||||
let cursor_y = self.cursor.1;
|
||||
let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else {
|
||||
return;
|
||||
};
|
||||
if l.scrolling && l.display && l.offscreen_rows() > 0 {
|
||||
let top = oy + 13.0;
|
||||
l.scroll = ((cursor_y - top - 7.5) / (56.0 - 15.0)).clamp(0.0, 1.0);
|
||||
l.start_row = l.row_for(l.scroll);
|
||||
}
|
||||
}
|
||||
pub(super) fn loom_release(&mut self) {
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.loom.scrolling = false;
|
||||
}
|
||||
}
|
||||
/// `LoomScreen.mouseScrolled`.
|
||||
pub(super) fn loom_scroll(&mut self, d: f32) {
|
||||
let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else {
|
||||
return;
|
||||
};
|
||||
let offscreen = l.offscreen_rows();
|
||||
if l.display && offscreen > 0 {
|
||||
l.scroll = (l.scroll - d / offscreen as f32).clamp(0.0, 1.0);
|
||||
l.start_row = l.row_for(l.scroll);
|
||||
}
|
||||
}
|
||||
/// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1))
|
||||
/// drawn flat: the cloth, the base colour and every layer.
|
||||
pub(super) fn draw_flag(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
rect: [f32; 4],
|
||||
base: &str,
|
||||
layers: &[BannerLayer],
|
||||
) {
|
||||
let banners = &self.res.stations.banners;
|
||||
let mut paint = |name: &str, color: u32| {
|
||||
if let Some(r) = self.res.atlas.sprites.get(name).copied() {
|
||||
let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]);
|
||||
batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color);
|
||||
}
|
||||
};
|
||||
paint("entity/banner/banner_base", u32::MAX);
|
||||
paint("entity/banner/base", dye_color(base));
|
||||
for layer in layers.iter().take(16) {
|
||||
paint(
|
||||
&banners.banner_texture(&layer.pattern),
|
||||
dye_color(&layer.color),
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `LoomScreen.extractBackground` after the background; returns the
|
||||
/// pattern name tooltip of the hovered button.
|
||||
pub(super) fn draw_loom(
|
||||
&mut self,
|
||||
batch: &mut HudBatch,
|
||||
ox: f32,
|
||||
oy: f32,
|
||||
local: (f32, f32),
|
||||
) -> Option<Vec<(String, u32)>> {
|
||||
let s = self.station.as_ref()?;
|
||||
let l = &s.loom;
|
||||
let atlas = &self.res.atlas;
|
||||
for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() {
|
||||
if s.inputs[i].is_none() {
|
||||
let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i];
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/slot/{icon}"),
|
||||
ox + pos.0,
|
||||
oy + pos.1,
|
||||
);
|
||||
}
|
||||
}
|
||||
let scroller = if l.scroll_active() {
|
||||
"scroller"
|
||||
} else {
|
||||
"scroller_disabled"
|
||||
};
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/loom/{scroller}"),
|
||||
ox + 119.0,
|
||||
oy + 13.0 + (41.0 * l.scroll).floor(),
|
||||
);
|
||||
let result = s.result.clone();
|
||||
let (display, has_max, start_row, selected) =
|
||||
(l.display, l.has_max, l.start_row, l.selected);
|
||||
let patterns = l.patterns.clone();
|
||||
let dye = s.inputs[1]
|
||||
.as_ref()
|
||||
.and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d))
|
||||
.unwrap_or_else(|| Arc::from("white"));
|
||||
if let Some(result) = result.filter(|_| !has_max)
|
||||
&& let Some(base) = banner::banner_color(&result.item)
|
||||
{
|
||||
self.draw_flag(
|
||||
batch,
|
||||
[ox + 141.0, oy + 8.0, 20.0, 40.0],
|
||||
base,
|
||||
banner::layers(&result),
|
||||
);
|
||||
} else if has_max {
|
||||
batch.sprite(
|
||||
&self.res.atlas,
|
||||
"gui/sprites/container/loom/error",
|
||||
ox + 138.0,
|
||||
oy + 52.0,
|
||||
);
|
||||
}
|
||||
let mut tooltip = None;
|
||||
if display {
|
||||
let atlas = &self.res.atlas;
|
||||
for row in 0..4 {
|
||||
for column in 0..4 {
|
||||
let index = (row + start_row) * 4 + column;
|
||||
let Some(pattern) = patterns.get(index) else {
|
||||
return tooltip;
|
||||
};
|
||||
let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON);
|
||||
let hover = inside(local, x, y, BUTTON, BUTTON);
|
||||
let sprite = if selected == Some(index) {
|
||||
"pattern_selected"
|
||||
} else if hover {
|
||||
let key = self
|
||||
.res
|
||||
.stations
|
||||
.banners
|
||||
.layer_key(&BannerLayer::new(pattern, &dye));
|
||||
tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]);
|
||||
"pattern_highlighted"
|
||||
} else {
|
||||
"pattern"
|
||||
};
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/loom/{sprite}"),
|
||||
ox + x,
|
||||
oy + y,
|
||||
);
|
||||
// extractBannerOnButton: a 5x10 grey cloth with the pattern.
|
||||
batch.fill(
|
||||
atlas,
|
||||
ox + x + 4.0,
|
||||
oy + y + 2.0,
|
||||
5.0,
|
||||
10.0,
|
||||
dye_color("gray"),
|
||||
);
|
||||
let texture = self.res.stations.banners.banner_texture(pattern);
|
||||
if let Some(r) = atlas.sprites.get(&texture).copied() {
|
||||
let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]);
|
||||
batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tooltip
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scroller_rows_follow_the_offset() {
|
||||
let l = LoomState {
|
||||
patterns: (0..40)
|
||||
.map(|i| Arc::from(format!("p{i}").as_str()))
|
||||
.collect(),
|
||||
display: true,
|
||||
..Default::default()
|
||||
};
|
||||
// 40 patterns = 10 rows, 6 off screen.
|
||||
assert_eq!(l.offscreen_rows(), 6);
|
||||
assert!(l.scroll_active());
|
||||
assert_eq!(l.row_for(0.0), 0);
|
||||
assert_eq!(l.row_for(1.0), 6);
|
||||
assert_eq!(l.row_for(0.5), 3);
|
||||
}
|
||||
#[test]
|
||||
fn few_patterns_do_not_scroll() {
|
||||
let l = LoomState {
|
||||
patterns: (0..16)
|
||||
.map(|i| Arc::from(format!("p{i}").as_str()))
|
||||
.collect(),
|
||||
display: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!l.scroll_active());
|
||||
assert_eq!(l.offscreen_rows(), 0);
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,15 @@
|
||||
//! the vanilla dispense behaviours Horizon has entities for, and container
|
||||
//! comparator signals (`AbstractContainerMenu.getRedstoneSignalFromContainer`).
|
||||
use super::Game;
|
||||
|
||||
mod crafter;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
containers::BlockEntity,
|
||||
entities::Arrow,
|
||||
items::{ItemStack, Items},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Direction, Vec3},
|
||||
position::BlockPos,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
|
||||
use horizon_world::{level::Behaviours, registry::BlockStateId};
|
||||
|
||||
type Pos = (i32, i32, i32);
|
||||
@@ -40,6 +37,8 @@ enum Kind {
|
||||
/// `AbstractFurnaceBlockEntity` (a `WorldlyContainer`).
|
||||
Furnace,
|
||||
Hopper,
|
||||
/// `CrafterBlockEntity`: disabled slots and the smallest-stack-first rule.
|
||||
Crafter,
|
||||
}
|
||||
|
||||
/// A container: one block entity, or a double chest (`CompoundContainer`).
|
||||
@@ -72,11 +71,6 @@ impl View {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Entity-owned randomness (projectile spread), separate from the level random.
|
||||
static ENTITY_RANDOM: std::cell::RefCell<LegacyRandom> = std::cell::RefCell::new(LegacyRandom::new(0x0d15_7e45));
|
||||
}
|
||||
|
||||
fn dir_from_name(name: &str) -> Option<Direction> {
|
||||
Some(match name {
|
||||
"down" => Direction::Down,
|
||||
@@ -145,6 +139,7 @@ impl Containers<'_> {
|
||||
let name = self.name(state);
|
||||
let kind = match (entity, name) {
|
||||
(BlockEntity::Furnace(_), _) => Kind::Furnace,
|
||||
(BlockEntity::Crafter(_), _) => Kind::Crafter,
|
||||
(_, "minecraft:hopper") => Kind::Hopper,
|
||||
_ => Kind::Generic,
|
||||
};
|
||||
@@ -212,6 +207,12 @@ impl Containers<'_> {
|
||||
}
|
||||
/// `Container.canPlaceItem` (+ `canPlaceItemThroughFace` for furnaces).
|
||||
fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool {
|
||||
if view.kind == Kind::Crafter {
|
||||
return match self.world.block_entities.get(&view.parts[0].0) {
|
||||
Some(BlockEntity::Crafter(c)) => c.can_place(slot, stack, self.max_stack(stack)),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
if view.kind != Kind::Furnace {
|
||||
return true;
|
||||
}
|
||||
@@ -246,6 +247,13 @@ impl Containers<'_> {
|
||||
}
|
||||
/// `AbstractContainerMenu.getRedstoneSignalFromContainer`.
|
||||
fn signal(&self, view: &View) -> i32 {
|
||||
if view.kind == Kind::Crafter {
|
||||
// CrafterBlockEntity.getRedstoneSignal: filled or disabled slots.
|
||||
return match self.world.block_entities.get(&view.parts[0].0) {
|
||||
Some(BlockEntity::Crafter(c)) => c.redstone_signal(),
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
let mut total = 0.0f32;
|
||||
for i in 0..view.len() {
|
||||
if let Some(s) = self.get(view, i) {
|
||||
@@ -304,10 +312,16 @@ impl Game<'_> {
|
||||
if pos.1 == super::minecarts::CART_KEY_Y {
|
||||
return;
|
||||
}
|
||||
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.container_changed(level, ticks, BlockPos::new(pos.0, pos.1, pos.2))
|
||||
});
|
||||
// A double chest's other half changes with it.
|
||||
let halves: Vec<Pos> = std::iter::once(pos)
|
||||
.chain(self.chest_other_half(pos))
|
||||
.collect();
|
||||
for pos in halves {
|
||||
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.container_changed(level, ticks, BlockPos::new(pos.0, pos.1, pos.2))
|
||||
});
|
||||
}
|
||||
}
|
||||
/// `HopperBlockEntity.tryMoveInItem`.
|
||||
fn try_move_in_item(
|
||||
@@ -567,6 +581,9 @@ impl Game<'_> {
|
||||
pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
if &*name == "minecraft:crafter" {
|
||||
return self.crafter_dispense(pos, state);
|
||||
}
|
||||
let dropper = &*name == "minecraft:dropper";
|
||||
if !dropper && &*name != "minecraft:dispenser" {
|
||||
return Ok(());
|
||||
@@ -585,14 +602,8 @@ impl Game<'_> {
|
||||
odds += 1;
|
||||
}
|
||||
}
|
||||
let center = [
|
||||
f64::from(pos.x) + 0.5,
|
||||
f64::from(pos.y) + 0.5,
|
||||
f64::from(pos.z) + 0.5,
|
||||
];
|
||||
let Some(slot) = slot else {
|
||||
self.audio
|
||||
.play("minecraft:block.dispenser.fail", Some(center), 1.0, 1.2);
|
||||
self.dispenser_event(1001, key, 0);
|
||||
return Ok(());
|
||||
};
|
||||
let Some(facing) = self
|
||||
@@ -608,7 +619,7 @@ impl Game<'_> {
|
||||
let target = offset(key, facing);
|
||||
let remaining = if dropper {
|
||||
match self.containers().view(target, false) {
|
||||
None => self.default_dispense(key, facing, stack),
|
||||
None => self.dispense_default(key, facing, stack),
|
||||
Some(into) => {
|
||||
let one = ItemStack {
|
||||
count: 1,
|
||||
@@ -630,7 +641,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.dispense_behaviour(key, facing, stack)?
|
||||
self.dispense_item(key, facing, stack)?
|
||||
};
|
||||
if let Some(entry) = self.slot_mut_at(&view, slot) {
|
||||
*entry = remaining;
|
||||
@@ -638,367 +649,6 @@ impl Game<'_> {
|
||||
self.container_changed(key);
|
||||
Ok(())
|
||||
}
|
||||
/// `DefaultDispenseItemBehavior.dispense`: drop one item, click and smoke.
|
||||
fn default_dispense(
|
||||
&mut self,
|
||||
pos: Pos,
|
||||
facing: Direction,
|
||||
mut stack: ItemStack,
|
||||
) -> Option<ItemStack> {
|
||||
let one = ItemStack {
|
||||
count: 1,
|
||||
..stack.clone()
|
||||
};
|
||||
stack.count -= 1;
|
||||
self.spawn_dispensed(pos, facing, one, 6);
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
|
||||
(stack.count > 0).then_some(stack)
|
||||
}
|
||||
fn dispenser_sound(&mut self, pos: Pos, sound: &str, pitch: f32) {
|
||||
let center = [
|
||||
f64::from(pos.0) + 0.5,
|
||||
f64::from(pos.1) + 0.5,
|
||||
f64::from(pos.2) + 0.5,
|
||||
];
|
||||
self.audio.play(sound, Some(center), 1.0, pitch);
|
||||
}
|
||||
/// `DefaultDispenseItemBehavior.spawnItem` at `DispenserBlock.getDispensePosition`.
|
||||
fn spawn_dispensed(&mut self, pos: Pos, facing: Direction, stack: ItemStack, accuracy: i32) {
|
||||
let s = step(facing);
|
||||
let mut at = [
|
||||
f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]),
|
||||
f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]),
|
||||
f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]),
|
||||
];
|
||||
at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 };
|
||||
let r = &mut self.world.random;
|
||||
// new ItemEntity(level, x, y, z, stack): its default motion draws first.
|
||||
let _ = (r.next_double(), r.next_double());
|
||||
let pow = r.next_double() * 0.1 + 0.2;
|
||||
let spread = 0.017_227_5 * f64::from(accuracy);
|
||||
let v = [
|
||||
r.triangle(f64::from(s[0]) * pow, spread),
|
||||
r.triangle(0.2, spread),
|
||||
r.triangle(f64::from(s[2]) * pow, spread),
|
||||
];
|
||||
self.spawn_item(stack, at, v, 0);
|
||||
}
|
||||
/// `DefaultDispenseItemBehavior.consumeWithRemainder`.
|
||||
fn consume_with_remainder(
|
||||
&mut self,
|
||||
pos: Pos,
|
||||
facing: Direction,
|
||||
mut stack: ItemStack,
|
||||
remainder: ItemStack,
|
||||
) -> Option<ItemStack> {
|
||||
stack.count -= 1;
|
||||
if stack.count == 0 {
|
||||
return Some(remainder);
|
||||
}
|
||||
// DispenserBlockEntity.insertItem, then drop what does not fit.
|
||||
let mut rest = remainder;
|
||||
if let Some(view) = self.containers().view(pos, false) {
|
||||
let max = self.containers().max_stack(&rest);
|
||||
for i in 0..view.len() {
|
||||
let Some(entry) = self.slot_mut_at(&view, i) else {
|
||||
continue;
|
||||
};
|
||||
match entry {
|
||||
None => {
|
||||
let n = rest.count.min(max);
|
||||
*entry = Some(ItemStack {
|
||||
count: n,
|
||||
..rest.clone()
|
||||
});
|
||||
rest.count -= n;
|
||||
}
|
||||
Some(e) if e.item == rest.item && e.damage == rest.damage => {
|
||||
let n = rest.count.min(max.saturating_sub(e.count));
|
||||
e.count += n;
|
||||
rest.count -= n;
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
if rest.count == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if rest.count > 0 {
|
||||
self.spawn_dispensed(pos, facing, rest, 6);
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
|
||||
}
|
||||
Some(stack)
|
||||
}
|
||||
/// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`.
|
||||
fn dispense_behaviour(
|
||||
&mut self,
|
||||
pos: Pos,
|
||||
facing: Direction,
|
||||
stack: ItemStack,
|
||||
) -> Result<Option<ItemStack>> {
|
||||
let target = offset(pos, facing);
|
||||
let target_pos = BlockPos::new(target.0, target.1, target.2);
|
||||
let item = stack.item.to_string();
|
||||
let result = match item.as_str() {
|
||||
"minecraft:bone_meal" => {
|
||||
let grown = self.with_level(|b, level, ticks| {
|
||||
b.grow_crop(level, ticks, target_pos)
|
||||
|| b.grow_water_plant(level, ticks, target_pos, None)
|
||||
});
|
||||
self.process_level_events()?;
|
||||
if grown {
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
|
||||
self.audio.play(
|
||||
"minecraft:item.bone_meal.use",
|
||||
Some([
|
||||
f64::from(target.0) + 0.5,
|
||||
f64::from(target.1) + 0.5,
|
||||
f64::from(target.2) + 0.5,
|
||||
]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
Some(ItemStack {
|
||||
count: stack.count - 1,
|
||||
..stack
|
||||
})
|
||||
.filter(|s| s.count > 0)
|
||||
} else {
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.fail", 1.2);
|
||||
Some(stack)
|
||||
}
|
||||
}
|
||||
"minecraft:tnt" => {
|
||||
self.spawn_primed_tnt(target_pos, false);
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
|
||||
Some(ItemStack {
|
||||
count: stack.count - 1,
|
||||
..stack
|
||||
})
|
||||
.filter(|s| s.count > 0)
|
||||
}
|
||||
"minecraft:flint_and_steel" => {
|
||||
let target_state = self.world.block(target.0, target.1, target.2);
|
||||
let target_name = self.res.facts.get(target_state).name.clone();
|
||||
let fire = self.res.assets.registry.default_state("minecraft:fire");
|
||||
let success = if self.res.facts.is_air(target_state)
|
||||
&& let Some(fire) = fire
|
||||
&& self
|
||||
.with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire))
|
||||
{
|
||||
self.level_set([target.0, target.1, target.2], fire)?;
|
||||
true
|
||||
} else if &*target_name == "minecraft:tnt" {
|
||||
self.spawn_primed_tnt(target_pos, false);
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.remove_block(level, ticks, target_pos, false)
|
||||
});
|
||||
self.process_level_events()?;
|
||||
true
|
||||
} else if self.containers().prop(target_state, "lit") == Some("false")
|
||||
&& (target_name.contains("campfire") || target_name.contains("candle"))
|
||||
&& self.containers().prop(target_state, "waterlogged") != Some("true")
|
||||
{
|
||||
let lit = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(target_state)
|
||||
.cloned()
|
||||
.and_then(|mut s| {
|
||||
s.properties.insert("lit".into(), "true".into());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
});
|
||||
if let Some(lit) = lit {
|
||||
self.level_set([target.0, target.1, target.2], lit)?;
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
self.dispenser_sound(
|
||||
pos,
|
||||
if success {
|
||||
"minecraft:block.dispenser.dispense"
|
||||
} else {
|
||||
"minecraft:block.dispenser.fail"
|
||||
},
|
||||
if success { 1.0 } else { 1.2 },
|
||||
);
|
||||
let mut stack = stack;
|
||||
if success {
|
||||
stack.damage += 1;
|
||||
let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
|
||||
if max > 0 && stack.damage >= max {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Some(stack)
|
||||
}
|
||||
"minecraft:water_bucket" | "minecraft:lava_bucket" => {
|
||||
let fluid = if item == "minecraft:water_bucket" {
|
||||
"minecraft:water"
|
||||
} else {
|
||||
"minecraft:lava"
|
||||
};
|
||||
let target_state = self.world.block(target.0, target.1, target.2);
|
||||
let f = self.res.facts.get(target_state).clone();
|
||||
let waterloggable = item == "minecraft:water_bucket"
|
||||
&& self.containers().prop(target_state, "waterlogged") == Some("false");
|
||||
if waterloggable {
|
||||
let wet = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(target_state)
|
||||
.cloned()
|
||||
.and_then(|mut s| {
|
||||
s.properties.insert("waterlogged".into(), "true".into());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
});
|
||||
if let Some(wet) = wet {
|
||||
self.level_set([target.0, target.1, target.2], wet)?;
|
||||
}
|
||||
self.consume_with_remainder(
|
||||
pos,
|
||||
facing,
|
||||
stack,
|
||||
ItemStack {
|
||||
item: "minecraft:bucket".into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
)
|
||||
} else if (self.res.facts.is_air(target_state) || f.replaceable)
|
||||
&& !(f.fluid_level == 8 && !f.fluid_falling && &*f.name == fluid)
|
||||
&& let Some(source) = self.res.assets.registry.default_state(fluid)
|
||||
{
|
||||
self.level_set([target.0, target.1, target.2], source)?;
|
||||
let sound = if fluid == "minecraft:water" {
|
||||
"minecraft:item.bucket.empty"
|
||||
} else {
|
||||
"minecraft:item.bucket.empty_lava"
|
||||
};
|
||||
self.audio.play(
|
||||
sound,
|
||||
Some([
|
||||
f64::from(target.0) + 0.5,
|
||||
f64::from(target.1) + 0.5,
|
||||
f64::from(target.2) + 0.5,
|
||||
]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
|
||||
self.consume_with_remainder(
|
||||
pos,
|
||||
facing,
|
||||
stack,
|
||||
ItemStack {
|
||||
item: "minecraft:bucket".into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
self.default_dispense(pos, facing, stack)
|
||||
}
|
||||
}
|
||||
"minecraft:bucket" => {
|
||||
let target_state = self.world.block(target.0, target.1, target.2);
|
||||
let f = self.res.facts.get(target_state).clone();
|
||||
let picked = if f.waterlogged
|
||||
&& self.containers().prop(target_state, "waterlogged") == Some("true")
|
||||
{
|
||||
let dry = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(target_state)
|
||||
.cloned()
|
||||
.and_then(|mut s| {
|
||||
s.properties.insert("waterlogged".into(), "false".into());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
});
|
||||
if let Some(dry) = dry {
|
||||
self.level_set([target.0, target.1, target.2], dry)?;
|
||||
}
|
||||
Some("minecraft:water_bucket")
|
||||
} else if f.fluid_level == 8
|
||||
&& !f.fluid_falling
|
||||
&& matches!(&*f.name, "minecraft:water" | "minecraft:lava")
|
||||
{
|
||||
self.level_set([target.0, target.1, target.2], self.world.air)?;
|
||||
Some(if &*f.name == "minecraft:water" {
|
||||
"minecraft:water_bucket"
|
||||
} else {
|
||||
"minecraft:lava_bucket"
|
||||
})
|
||||
} else if &*f.name == "minecraft:powder_snow" {
|
||||
self.level_set([target.0, target.1, target.2], self.world.air)?;
|
||||
Some("minecraft:powder_snow_bucket")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match picked {
|
||||
Some(filled) => {
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
|
||||
self.consume_with_remainder(
|
||||
pos,
|
||||
facing,
|
||||
stack,
|
||||
ItemStack {
|
||||
item: filled.into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
)
|
||||
}
|
||||
None => self.default_dispense(pos, facing, stack),
|
||||
}
|
||||
}
|
||||
"minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:tipped_arrow" => {
|
||||
// ProjectileDispenseBehavior: power 1.1, uncertainty 6, from 0.7 ahead and 0.1 up.
|
||||
let s = step(facing);
|
||||
let at = Vec3::new(
|
||||
f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]),
|
||||
f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]) + 0.1,
|
||||
f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]),
|
||||
);
|
||||
let spread = 0.017_227_5 * 6.0;
|
||||
let v = ENTITY_RANDOM.with(|r| {
|
||||
let r = &mut *r.borrow_mut();
|
||||
[
|
||||
(f64::from(s[0]) + r.triangle(0.0, spread)) * 1.1,
|
||||
(f64::from(s[1]) + r.triangle(0.0, spread)) * 1.1,
|
||||
(f64::from(s[2]) + r.triangle(0.0, spread)) * 1.1,
|
||||
]
|
||||
});
|
||||
self.arrows.push(Arrow {
|
||||
from_player: true,
|
||||
critical: false,
|
||||
position: at,
|
||||
previous: at,
|
||||
velocity: Vec3::new(v[0], v[1], v[2]),
|
||||
stuck: false,
|
||||
age: 0,
|
||||
base_damage: 2.0,
|
||||
});
|
||||
self.dispenser_sound(pos, "minecraft:block.dispenser.launch", 1.2);
|
||||
Some(ItemStack {
|
||||
count: stack.count - 1,
|
||||
..stack
|
||||
})
|
||||
.filter(|s| s.count > 0)
|
||||
}
|
||||
_ => self.default_dispense(pos, facing, stack),
|
||||
};
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- hopper, dispenser and dropper screens ----
|
||||
@@ -1035,6 +685,13 @@ impl Game<'_> {
|
||||
{
|
||||
return super::beacon::HEIGHT;
|
||||
}
|
||||
if let Some(rows) = self.chest_rows() {
|
||||
// ContainerScreen: 114 + 18 per row.
|
||||
return 114.0 + rows as f32 * 18.0;
|
||||
}
|
||||
if self.container_block_is_shulker() {
|
||||
return 167.0;
|
||||
}
|
||||
if self.machine_screen() == Some(Screen::Hopper) {
|
||||
133.0
|
||||
} else {
|
||||
@@ -1070,7 +727,13 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let key_is_cart = self
|
||||
.container
|
||||
.is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y);
|
||||
let (texture, height, title) = match screen {
|
||||
Screen::Hopper if key_is_cart => {
|
||||
("gui/container/hopper", 133.0, "Minecart with Hopper")
|
||||
}
|
||||
Screen::Hopper => ("gui/container/hopper", 133.0, "Item Hopper"),
|
||||
Screen::Dispenser => ("gui/container/dispenser", 166.0, "Dispenser"),
|
||||
Screen::Dropper => ("gui/container/dispenser", 166.0, "Dropper"),
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! The crafter (`CrafterBlock`, `CrafterBlockEntity`, `CrafterMenu`,
|
||||
//! `CrafterScreen`): redstone-triggered crafting of its 3x3 grid, ejecting
|
||||
//! the result and remainders into the container in front or as items, the
|
||||
//! crafting animation ticks, and the menu with its toggleable slots.
|
||||
use super::*;
|
||||
use horizon_client::{
|
||||
advancements as adv,
|
||||
containers::Crafter,
|
||||
hud::{HudBatch, rgba},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
/// `CrafterBlock`'s crafting animation length.
|
||||
const CRAFTING_TICKS: i32 = 6;
|
||||
const RESULT_SLOT: usize = 309;
|
||||
|
||||
fn center(pos: Pos) -> [f64; 3] {
|
||||
[
|
||||
f64::from(pos.0) + 0.5,
|
||||
f64::from(pos.1) + 0.5,
|
||||
f64::from(pos.2) + 0.5,
|
||||
]
|
||||
}
|
||||
/// Whether an advancement condition's `recipes` entry names the recipe.
|
||||
fn recipe_matches(condition: &Value, id: &str) -> bool {
|
||||
match condition {
|
||||
Value::String(s) => s == id,
|
||||
Value::Array(list) => list.iter().any(|v| v.as_str() == Some(id)),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Level.setBlock` of one boolean property of the block at `pos`.
|
||||
fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) {
|
||||
let registry = self.res.assets.registry;
|
||||
let old = self.world.block(pos.0, pos.1, pos.2);
|
||||
let Some(mut state) = registry.state(old).cloned() else {
|
||||
return;
|
||||
};
|
||||
if !state.properties.contains_key(key) {
|
||||
return;
|
||||
}
|
||||
state.properties.insert(key.to_owned(), value.to_string());
|
||||
let Ok(id) = registry.resolve(&state) else {
|
||||
return;
|
||||
};
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.set_block(level, ticks, BlockPos::new(pos.0, pos.1, pos.2), id, flags)
|
||||
});
|
||||
let _ = self.process_level_events();
|
||||
}
|
||||
fn crafter_at(&self, pos: Pos) -> Option<&Crafter> {
|
||||
match self.world.block_entities.get(&pos)? {
|
||||
BlockEntity::Crafter(c) => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `CrafterBlockEntity.serverTick` for every crafter, and the powered
|
||||
/// flag following the block state.
|
||||
pub(in crate::game) fn tick_crafters(&mut self) {
|
||||
let positions: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
for pos in positions {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let triggered = self.containers().prop(state, "triggered") == Some("true");
|
||||
let mut finished = false;
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) {
|
||||
c.triggered = triggered;
|
||||
let remaining = c.crafting_ticks - 1;
|
||||
if remaining >= 0 {
|
||||
c.crafting_ticks = remaining;
|
||||
finished = remaining == 0;
|
||||
}
|
||||
}
|
||||
if finished {
|
||||
self.set_bool_prop(
|
||||
pos,
|
||||
"crafting",
|
||||
false,
|
||||
horizon_world::level::flags::UPDATE_ALL,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse).
|
||||
pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
let Some(crafter) = self.crafter_at(key) else {
|
||||
return Ok(());
|
||||
};
|
||||
let grid: Vec<Option<ItemStack>> = crafter.items.to_vec();
|
||||
let found = self
|
||||
.res
|
||||
.recipes
|
||||
.find(&grid, 3)
|
||||
.map(|(name, result)| (name.to_owned(), result))
|
||||
.filter(|(_, result)| result.count > 0);
|
||||
let Some((recipe, result)) = found else {
|
||||
// LevelEvent 1050: CRAFTER_FAIL.
|
||||
self.audio
|
||||
.play("minecraft:block.crafter.fail", Some(center(key)), 1.0, 1.0);
|
||||
return Ok(());
|
||||
};
|
||||
let Some(facing) = self
|
||||
.containers()
|
||||
.prop(state, "orientation")
|
||||
.and_then(|o| o.split('_').next())
|
||||
.and_then(dir_from_name)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&key) {
|
||||
c.crafting_ticks = CRAFTING_TICKS;
|
||||
}
|
||||
self.set_bool_prop(
|
||||
key,
|
||||
"crafting",
|
||||
true,
|
||||
horizon_world::level::flags::UPDATE_CLIENTS,
|
||||
);
|
||||
let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result);
|
||||
self.crafter_eject(key, facing, result, &recipe);
|
||||
for rest in remainders.into_iter().flatten() {
|
||||
self.crafter_eject(key, facing, rest, &recipe);
|
||||
}
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&key) {
|
||||
for slot in c.items.iter_mut() {
|
||||
if let Some(s) = slot {
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.container_changed(key);
|
||||
Ok(())
|
||||
}
|
||||
/// `CrafterBlock.dispenseItem`: into the container in front, else out as an item.
|
||||
fn crafter_eject(&mut self, pos: Pos, facing: Direction, stack: ItemStack, recipe: &str) {
|
||||
let target = offset(pos, facing);
|
||||
let mut rest = stack;
|
||||
if let Some(into) = self.containers().view(target, false) {
|
||||
let one_by_one = self.crafter_at(target).is_some()
|
||||
|| rest.count > self.containers().max_stack(&rest);
|
||||
while rest.count > 0 {
|
||||
let before = rest.count;
|
||||
if one_by_one {
|
||||
let one = ItemStack {
|
||||
count: 1,
|
||||
..rest.clone()
|
||||
};
|
||||
if self
|
||||
.add_item(None, &into, one, Some(facing.opposite()))
|
||||
.is_some()
|
||||
{
|
||||
break;
|
||||
}
|
||||
rest.count -= 1;
|
||||
} else {
|
||||
match self.add_item(None, &into, rest.clone(), Some(facing.opposite())) {
|
||||
Some(left) => rest = left,
|
||||
None => rest.count = 0,
|
||||
}
|
||||
if rest.count == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if rest.count == 0 {
|
||||
return;
|
||||
}
|
||||
self.spawn_dispensed(pos, facing, rest, 6);
|
||||
// LevelEvent 1049 (CRAFTER_CRAFT) and 2010 (white smoke shot out the front).
|
||||
self.audio
|
||||
.play("minecraft:block.crafter.craft", Some(center(pos)), 1.0, 1.0);
|
||||
let s = step(facing);
|
||||
for _ in 0..10 {
|
||||
let r = &mut self.world.random;
|
||||
let pow = r.next_double() * 0.2 + 0.01;
|
||||
let at = [
|
||||
f64::from(pos.0)
|
||||
+ f64::from(s[0]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[0]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[2]) * 0.5,
|
||||
f64::from(pos.1)
|
||||
+ f64::from(s[1]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[1]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[1]) * 0.5,
|
||||
f64::from(pos.2)
|
||||
+ f64::from(s[2]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[2]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[0]) * 0.5,
|
||||
];
|
||||
let v = [
|
||||
f64::from(s[0]) * pow + r.next_gaussian() * 0.01,
|
||||
f64::from(s[1]) * pow + r.next_gaussian() * 0.01,
|
||||
f64::from(s[2]) * pow + r.next_gaussian() * 0.01,
|
||||
];
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ParticleType::WhiteSmoke), at, v);
|
||||
}
|
||||
// CrafterRecipeCraftedTrigger for players within the 17-block box.
|
||||
let near = self.eye_position().is_some_and(|e| {
|
||||
let c = center(pos);
|
||||
(0..3).all(|i| (e[i] - c[i]).abs() <= 8.5 + 1.0)
|
||||
});
|
||||
if near {
|
||||
let id = format!("minecraft:{recipe}");
|
||||
let me = self.player_entity();
|
||||
self.trigger("minecraft:crafter_recipe_crafted", move |c, w| {
|
||||
let ctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
adv::conditions(&c["player"], &ctx, w) && recipe_matches(&c["recipes"], &id)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the menu ----
|
||||
|
||||
/// The grid's current recipe result (`CrafterMenu.refreshRecipeResult`).
|
||||
pub(in crate::game) fn crafter_result(&self) -> Option<ItemStack> {
|
||||
let key = self.container?;
|
||||
let c = self.crafter_at(key)?;
|
||||
self.res.recipes.craft(&c.items, 3)
|
||||
}
|
||||
fn crafter_open(&self) -> bool {
|
||||
matches!(self.container_kind(), Some(BlockEntity::Crafter(_)))
|
||||
}
|
||||
/// `CrafterMenu` slot layout: the grid at (26, 17), the result at (134, 35).
|
||||
pub(in crate::game) fn crafter_slot_position(&self, i: usize) -> Option<(f32, f32)> {
|
||||
if !self.crafter_open() {
|
||||
return None;
|
||||
}
|
||||
match i {
|
||||
300..309 => Some((
|
||||
26.0 + ((i - 300) % 3) as f32 * 18.0,
|
||||
17.0 + ((i - 300) / 3) as f32 * 18.0,
|
||||
)),
|
||||
RESULT_SLOT => Some((134.0, 35.0)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `CrafterScreen`'s background, title, disabled slots and powered arrow.
|
||||
pub(in crate::game) fn draw_crafter_screen(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
|
||||
let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
"gui/container/crafter",
|
||||
[ox, oy, 176.0, 166.0],
|
||||
256.0,
|
||||
256.0,
|
||||
);
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
let title = self.translate("container.crafter", "Crafter");
|
||||
let tw = HudBatch::text_width(atlas, &title);
|
||||
batch.text(
|
||||
atlas,
|
||||
&title,
|
||||
ox + (176.0 - tw) / 2.0,
|
||||
oy + 6.0,
|
||||
grey,
|
||||
false,
|
||||
);
|
||||
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
|
||||
for slot in 0..9 {
|
||||
if c.disabled[slot] {
|
||||
let (x, y) = self.crafter_slot_position(300 + slot).unwrap_or_default();
|
||||
batch.sprite(
|
||||
atlas,
|
||||
"gui/sprites/container/crafter/disabled_slot",
|
||||
ox + x - 1.0,
|
||||
oy + y - 1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
let powered = self
|
||||
.container
|
||||
.map(|k| self.world.block(k.0, k.1, k.2))
|
||||
.is_some_and(|state| self.containers().prop(state, "triggered") == Some("true"));
|
||||
let arrow = if powered {
|
||||
"powered_redstone"
|
||||
} else {
|
||||
"unpowered_redstone"
|
||||
};
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/crafter/{arrow}"),
|
||||
ox + 97.0,
|
||||
oy + 35.0,
|
||||
);
|
||||
}
|
||||
/// `gui.togglable_slot` over an empty, enabled grid slot.
|
||||
pub(in crate::game) fn crafter_tooltip(&self, slot: usize) -> Option<String> {
|
||||
let c = self.container.and_then(|k| self.crafter_at(k))?;
|
||||
let i = slot.checked_sub(300).filter(|i| *i < 9)?;
|
||||
(self.carried.is_none() && c.items[i].is_none() && !c.disabled[i] && !self.spectator())
|
||||
.then(|| self.translate("gui.togglable_slot", "Click to disable slot"))
|
||||
}
|
||||
/// A click in the crafter menu before the generic handling; true when
|
||||
/// it was fully handled (the result, shift-clicks).
|
||||
pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool) -> bool {
|
||||
if !self.crafter_open() {
|
||||
return false;
|
||||
}
|
||||
if slot == RESULT_SLOT {
|
||||
return true;
|
||||
}
|
||||
if (300..309).contains(&slot) {
|
||||
// CrafterScreen.slotClicked: toggle an empty slot.
|
||||
let i = slot - 300;
|
||||
if !shift && !self.spectator() && self.slot_mut(slot).is_none() {
|
||||
let carried_empty = self.carried.is_none();
|
||||
let key = self.container;
|
||||
let mut toggled = None;
|
||||
if let Some(BlockEntity::Crafter(c)) =
|
||||
key.and_then(|k| self.world.block_entities.get_mut(&k))
|
||||
{
|
||||
if c.disabled[i] {
|
||||
c.set_slot_state(i, true);
|
||||
toggled = Some(true);
|
||||
} else if carried_empty {
|
||||
c.set_slot_state(i, false);
|
||||
toggled = Some(false);
|
||||
}
|
||||
}
|
||||
if let Some(enabled) = toggled {
|
||||
let pitch = if enabled { 1.0 } else { 0.75 };
|
||||
self.audio
|
||||
.play("minecraft:ui.button.click", None, 0.4, pitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
if shift {
|
||||
self.crafter_quick_move(slot);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `CrafterMenu.quickMoveStack`.
|
||||
fn crafter_quick_move(&mut self, slot: usize) {
|
||||
if slot >= 309 {
|
||||
return;
|
||||
}
|
||||
let Some(mut stack) = self.slot_mut(slot).take() else {
|
||||
return;
|
||||
};
|
||||
if slot >= 300 {
|
||||
let player: Vec<usize> = (9..36).chain(0..9).collect();
|
||||
self.move_to(&mut stack, &player, true);
|
||||
} else {
|
||||
let grid: Vec<usize> = (300..309).collect();
|
||||
self.move_to(&mut stack, &grid, false);
|
||||
}
|
||||
if stack.count > 0 {
|
||||
*self.slot_mut(slot) = Some(stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stack(item: &str, count: u32) -> Option<ItemStack> {
|
||||
Some(ItemStack::new(item, count))
|
||||
}
|
||||
#[test]
|
||||
fn signal_counts_filled_and_disabled_slots() {
|
||||
let mut c = Crafter::default();
|
||||
assert_eq!(c.redstone_signal(), 0);
|
||||
c.items[0] = stack("minecraft:stick", 3);
|
||||
c.set_slot_state(4, false);
|
||||
assert_eq!(c.redstone_signal(), 2);
|
||||
// A filled slot cannot be disabled.
|
||||
c.set_slot_state(0, false);
|
||||
assert!(!c.disabled[0]);
|
||||
c.set_slot_state(4, true);
|
||||
assert_eq!(c.redstone_signal(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn hoppers_fill_the_smaller_stacks_first() {
|
||||
let mut c = Crafter::default();
|
||||
let stick = ItemStack::new("minecraft:stick", 1);
|
||||
c.items[0] = stack("minecraft:stick", 2);
|
||||
c.items[1] = stack("minecraft:stick", 1);
|
||||
// A later empty slot counts as smaller: stacks level out front to back.
|
||||
assert!(!c.can_place(0, &stick, 64));
|
||||
assert!(!c.can_place(1, &stick, 64));
|
||||
assert!(c.can_place(2, &stick, 64));
|
||||
c.disabled[5] = true;
|
||||
assert!(!c.can_place(5, &stick, 64));
|
||||
// With every later slot at least as big, a slot accepts again.
|
||||
for i in 2..9 {
|
||||
c.items[i] = stack("minecraft:stick", 2);
|
||||
}
|
||||
assert!(c.can_place(1, &stick, 64));
|
||||
// A full stack accepts nothing.
|
||||
c.items[2] = stack("minecraft:stick", 64);
|
||||
assert!(!c.can_place(2, &stick, 64));
|
||||
}
|
||||
#[test]
|
||||
fn recipes_condition_accepts_a_name_or_a_list() {
|
||||
assert!(recipe_matches(
|
||||
&serde_json::json!("minecraft:crafter"),
|
||||
"minecraft:crafter"
|
||||
));
|
||||
assert!(!recipe_matches(
|
||||
&serde_json::json!(["minecraft:stick"]),
|
||||
"minecraft:crafter"
|
||||
));
|
||||
assert!(recipe_matches(&Value::Null, "minecraft:crafter"));
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ const SEAT: f64 = 0.1875 - 0.6;
|
||||
pub(super) const CART_KEY_Y: i32 = -100_000;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Shape {
|
||||
pub(super) enum Shape {
|
||||
NorthSouth,
|
||||
EastWest,
|
||||
AscendingEast,
|
||||
@@ -117,7 +117,7 @@ impl Shape {
|
||||
_ => Self::NorthSouth,
|
||||
}
|
||||
}
|
||||
fn is_slope(self) -> bool {
|
||||
pub(super) fn is_slope(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth
|
||||
@@ -141,9 +141,9 @@ impl Shape {
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Rail {
|
||||
pub(super) struct Rail {
|
||||
name: Arc<str>,
|
||||
shape: Shape,
|
||||
pub(super) shape: Shape,
|
||||
powered: bool,
|
||||
}
|
||||
impl Minecart {
|
||||
@@ -203,7 +203,7 @@ impl CartModels {
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
|
||||
pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
|
||||
let state = self.world.block(x, y, z);
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
if !matches!(
|
||||
@@ -1238,6 +1238,7 @@ impl Game<'_> {
|
||||
nether: self.dim == super::Dim::Nether,
|
||||
lid: &lid,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
glyph: &|c| self.res.atlas.glyph(c),
|
||||
};
|
||||
self.res
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The horse inventory (`HorseInventoryMenu`, `HorseInventoryScreen`): the
|
||||
//! saddle and body armour slots, the 3x5 chest of donkeys and mules and the
|
||||
//! mount drawn following the cursor. It opens with E while riding a tamed
|
||||
//! mount or with shift + use on a tamed one.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Species, equine},
|
||||
};
|
||||
|
||||
/// Menu slot ids: the saddle, the body armour and the chest from 710.
|
||||
pub(super) const SADDLE: usize = 700;
|
||||
pub(super) const ARMOR: usize = 701;
|
||||
pub(super) const CHEST: usize = 710;
|
||||
/// `AbstractChestedHorse.INV_CHEST_COUNT` and `getInventoryColumns`.
|
||||
const CHEST_SIZE: usize = 15;
|
||||
const COLUMNS: usize = 5;
|
||||
|
||||
/// The open mount menu: copies of the mount's slots, written back on every change.
|
||||
#[derive(Default)]
|
||||
pub(super) struct MountMenu {
|
||||
open: Option<Open>,
|
||||
}
|
||||
struct Open {
|
||||
mob: u32,
|
||||
species: Species,
|
||||
columns: usize,
|
||||
saddle: Option<ItemStack>,
|
||||
armor: Option<ItemStack>,
|
||||
items: Vec<Option<ItemStack>>,
|
||||
/// `shouldRenderSaddleSlot` / `shouldRenderArmorSlot`.
|
||||
show_saddle: bool,
|
||||
show_armor: bool,
|
||||
}
|
||||
|
||||
/// `EntityTypeTags.CAN_WEAR_HORSE_ARMOR`.
|
||||
fn can_wear_horse_armor(species: Species) -> bool {
|
||||
matches!(species, Species::Horse | Species::ZombieHorse)
|
||||
}
|
||||
/// Whether `item` fits the body slot of the species (`isEquippableInSlot`).
|
||||
fn body_armor_fits(species: Species, item: &str) -> bool {
|
||||
can_wear_horse_armor(species) && item.ends_with("_horse_armor")
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Whether the mount menu is the open screen.
|
||||
pub(super) fn mount_active(&self) -> bool {
|
||||
self.screen == Screen::Inventory && self.mount_menu.open.is_some()
|
||||
}
|
||||
fn mount_mob_index(&self, id: u32) -> Option<usize> {
|
||||
self.mobs.iter().position(|m| m.id == id)
|
||||
}
|
||||
/// `AbstractHorse.openCustomInventoryScreen` for a tamed adult mount.
|
||||
pub(super) fn open_mount_menu(&mut self, index: usize) {
|
||||
let m = &self.mobs[index];
|
||||
let species = m.species();
|
||||
if !equine::is_equine(species) {
|
||||
return;
|
||||
}
|
||||
let chested = m.extra.chested && matches!(species, Species::Donkey | Species::Mule);
|
||||
let columns = if chested { COLUMNS } else { 0 };
|
||||
let mut items = m.extra.items.clone();
|
||||
items.resize(CHEST_SIZE, None);
|
||||
let show_armor = can_wear_horse_armor(species);
|
||||
self.mount_menu.open = Some(Open {
|
||||
mob: m.id,
|
||||
species,
|
||||
columns,
|
||||
saddle: m
|
||||
.extra
|
||||
.saddled
|
||||
.then(|| ItemStack::new("minecraft:saddle", 1)),
|
||||
armor: m
|
||||
.extra
|
||||
.head
|
||||
.as_deref()
|
||||
.filter(|_| show_armor)
|
||||
.map(|i| ItemStack::new(i, 1)),
|
||||
items,
|
||||
show_saddle: true,
|
||||
show_armor,
|
||||
});
|
||||
self.carried = None;
|
||||
self.station = None;
|
||||
self.container = None;
|
||||
self.craft_size = 2;
|
||||
self.screen = Screen::Inventory;
|
||||
self.capture(false);
|
||||
}
|
||||
/// E while riding a tamed mount opens its inventory instead of the player's.
|
||||
pub(super) fn open_ridden_mount_menu(&mut self) -> bool {
|
||||
let Some(id) = self.riding else {
|
||||
return false;
|
||||
};
|
||||
let Some(index) = self.mount_mob_index(id) else {
|
||||
return false;
|
||||
};
|
||||
let m = &self.mobs[index];
|
||||
if !equine::is_equine(m.species()) || !m.extra.tame || !m.alive() {
|
||||
return false;
|
||||
}
|
||||
self.open_mount_menu(index);
|
||||
true
|
||||
}
|
||||
/// The menu ends when the mount dies or is more than 4 blocks away
|
||||
/// (`AbstractMountInventoryMenu.stillValid`).
|
||||
pub(super) fn tick_mount_menu(&mut self) {
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let valid = self.mount_mob_index(open.mob).is_some_and(|i| {
|
||||
let m = &self.mobs[i];
|
||||
let c = m.center();
|
||||
m.alive()
|
||||
&& self.eye_position().is_some_and(|e| {
|
||||
let d = (e[0] - c[0]).powi(2) + (e[1] - c[1]).powi(2) + (e[2] - c[2]).powi(2);
|
||||
d <= 16.0 + 4.0
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
self.close_container();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
/// Closing the screen keeps what is in the slots on the mount.
|
||||
pub(super) fn mount_closed(&mut self) {
|
||||
self.mount_sync();
|
||||
self.mount_menu.open = None;
|
||||
}
|
||||
/// Writes the menu slots to the mount, with the equip sounds.
|
||||
fn mount_sync(&mut self) {
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some(index) = self.mount_mob_index(open.mob) else {
|
||||
return;
|
||||
};
|
||||
let (saddle, armor) = (open.saddle.is_some(), open.armor.clone());
|
||||
let items = open.items.clone();
|
||||
let m = &mut self.mobs[index];
|
||||
let at = m.center();
|
||||
let sound = if saddle && !m.extra.saddled {
|
||||
Some("minecraft:entity.horse.saddle")
|
||||
} else if armor.is_some() && m.extra.head.is_none() {
|
||||
Some("minecraft:entity.horse.armor")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
m.extra.saddled = saddle;
|
||||
if open.show_armor {
|
||||
m.extra.head = armor.map(|a| a.item);
|
||||
}
|
||||
m.extra.items = items;
|
||||
let (x, z) = (at[0].floor() as i32 >> 4, at[2].floor() as i32 >> 4);
|
||||
self.world.modified.insert((x, z));
|
||||
if let Some(sound) = sound {
|
||||
self.audio.play(sound, Some(at), 0.5, 1.0);
|
||||
}
|
||||
}
|
||||
pub(super) fn mount_slots(&self) -> Option<Vec<usize>> {
|
||||
let open = self
|
||||
.mount_menu
|
||||
.open
|
||||
.as_ref()
|
||||
.filter(|_| self.mount_active())?;
|
||||
let mut v: Vec<usize> = (0..36).collect();
|
||||
if open.show_saddle {
|
||||
v.push(SADDLE);
|
||||
}
|
||||
if open.show_armor {
|
||||
v.push(ARMOR);
|
||||
}
|
||||
v.extend((0..open.columns * 3).map(|i| CHEST + i));
|
||||
Some(v)
|
||||
}
|
||||
pub(super) fn mount_slot_position(&self, i: usize) -> Option<(f32, f32)> {
|
||||
let open = self
|
||||
.mount_menu
|
||||
.open
|
||||
.as_ref()
|
||||
.filter(|_| self.mount_active())?;
|
||||
match i {
|
||||
SADDLE => Some((8.0, 18.0)),
|
||||
ARMOR => Some((8.0, 36.0)),
|
||||
_ if i >= CHEST => {
|
||||
let n = i - CHEST;
|
||||
(n < open.columns * 3).then(|| {
|
||||
(
|
||||
80.0 + (n % open.columns) as f32 * 18.0,
|
||||
18.0 + (n / open.columns) as f32 * 18.0,
|
||||
)
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(super) fn mount_slot_mut(&mut self, i: usize) -> &mut Option<ItemStack> {
|
||||
match self.mount_menu.open.as_mut() {
|
||||
Some(open) if i == SADDLE => &mut open.saddle,
|
||||
Some(open) if i == ARMOR => &mut open.armor,
|
||||
Some(open) if i >= CHEST && i - CHEST < CHEST_SIZE => &mut open.items[i - CHEST],
|
||||
_ => &mut self.scratch_slot,
|
||||
}
|
||||
}
|
||||
/// `ArmorSlot.mayPlace` and the stack limits of the mount's slots.
|
||||
pub(super) fn mount_slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return (false, 64);
|
||||
};
|
||||
match slot {
|
||||
SADDLE => (&*stack.item == "minecraft:saddle", 1),
|
||||
ARMOR => (body_armor_fits(open.species, &stack.item), 1),
|
||||
_ => (true, 64),
|
||||
}
|
||||
}
|
||||
/// A click in the mount menu before the generic handling.
|
||||
pub(super) fn mount_click(&mut self, right: bool) -> bool {
|
||||
if !self.mount_active() {
|
||||
return false;
|
||||
}
|
||||
let Some(r) = self.renderer.as_ref() else {
|
||||
return true;
|
||||
};
|
||||
let batch = HudBatch::new([r.config.width, r.config.height]);
|
||||
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
|
||||
return true;
|
||||
};
|
||||
let shift = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|
||||
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight);
|
||||
if shift {
|
||||
self.mount_quick_move(slot);
|
||||
} else if slot >= SADDLE {
|
||||
self.click_filtered(slot, right);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
self.mount_sync();
|
||||
true
|
||||
}
|
||||
/// The inventory slot ids in menu order.
|
||||
fn mount_player_slots() -> Vec<usize> {
|
||||
(9..36).chain(0..9).collect()
|
||||
}
|
||||
/// `AbstractMountInventoryMenu.quickMoveStack`.
|
||||
fn mount_quick_move(&mut self, slot: usize) {
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let (columns, show_saddle, show_armor) = (open.columns, open.show_saddle, open.show_armor);
|
||||
let Some(mut stack) = self.slot_mut(slot).take() else {
|
||||
return;
|
||||
};
|
||||
if slot >= SADDLE {
|
||||
let player = Self::mount_player_slots();
|
||||
self.move_to(&mut stack, &player, true);
|
||||
} else {
|
||||
let armor_free = self.mount_slot_mut(ARMOR).is_none();
|
||||
let saddle_free = self.mount_slot_mut(SADDLE).is_none();
|
||||
let armor_ok = show_armor && self.mount_slot_rules(ARMOR, &stack).0 && armor_free;
|
||||
let saddle_ok = show_saddle && self.mount_slot_rules(SADDLE, &stack).0 && saddle_free;
|
||||
if armor_ok {
|
||||
self.move_to(&mut stack, &[ARMOR], false);
|
||||
} else if saddle_ok {
|
||||
self.move_to(&mut stack, &[SADDLE], false);
|
||||
} else {
|
||||
let chest: Vec<usize> = (0..columns * 3).map(|i| CHEST + i).collect();
|
||||
let moved = columns > 0 && self.move_to(&mut stack, &chest, false);
|
||||
if !moved {
|
||||
// Between the hotbar and the main inventory.
|
||||
let other: Vec<usize> = if slot < 9 {
|
||||
(9..36).collect()
|
||||
} else {
|
||||
(0..9).collect()
|
||||
};
|
||||
self.move_to(&mut stack, &other, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
if stack.count > 0 {
|
||||
*self.slot_mut(slot) = Some(stack);
|
||||
}
|
||||
}
|
||||
/// `HorseInventoryScreen`'s background, slot frames and the mount.
|
||||
pub(super) fn draw_mount_background(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
"gui/container/horse",
|
||||
[ox, oy, 176.0, 166.0],
|
||||
256.0,
|
||||
256.0,
|
||||
);
|
||||
if open.columns > 0 {
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
"gui/sprites/container/horse/chest_slots",
|
||||
[ox + 79.0, oy + 17.0, open.columns as f32 * 18.0, 54.0],
|
||||
90.0,
|
||||
54.0,
|
||||
);
|
||||
}
|
||||
if open.show_saddle {
|
||||
batch.sprite(atlas, "gui/sprites/container/slot", ox + 7.0, oy + 17.0);
|
||||
if open.saddle.is_none() {
|
||||
batch.sprite(
|
||||
atlas,
|
||||
"gui/sprites/container/slot/saddle",
|
||||
ox + 8.0,
|
||||
oy + 18.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
if open.show_armor {
|
||||
batch.sprite(atlas, "gui/sprites/container/slot", ox + 7.0, oy + 35.0);
|
||||
if open.armor.is_none() {
|
||||
batch.sprite(
|
||||
atlas,
|
||||
"gui/sprites/container/slot/horse_armor",
|
||||
ox + 8.0,
|
||||
oy + 36.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
let title = match self.mobs.iter().find(|m| m.id == open.mob) {
|
||||
Some(m) => m.custom_name.clone().unwrap_or_else(|| {
|
||||
let key = format!(
|
||||
"entity.minecraft.{}",
|
||||
m.kind.id.trim_start_matches("minecraft:")
|
||||
);
|
||||
self.translate(&key, &key)
|
||||
}),
|
||||
None => String::new(),
|
||||
};
|
||||
batch.text(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
|
||||
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
|
||||
if let Some(m) = self.mobs.iter().find(|m| m.id == open.mob) {
|
||||
self.draw_mob_preview(
|
||||
batch,
|
||||
m,
|
||||
ox + 26.0,
|
||||
oy + 18.0,
|
||||
ox + 78.0,
|
||||
oy + 70.0,
|
||||
17.0,
|
||||
0.25,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `extractEntityInInventoryFollowsMouse` for a mob: depth-sorted,
|
||||
/// back-face-culled quads turned toward the cursor.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_mob_preview(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
mob: &Mob,
|
||||
x0: f32,
|
||||
y0: f32,
|
||||
x1: f32,
|
||||
y1: f32,
|
||||
size: f32,
|
||||
offset_y: f32,
|
||||
) {
|
||||
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
let x_angle = ((cx - self.cursor.0) / 40.0).atan();
|
||||
let y_angle = ((cy - self.cursor.1) / 40.0).atan();
|
||||
let mut m = mob.clone();
|
||||
m.previous = m.position;
|
||||
m.body_yaw = 180.0 + x_angle * 20.0;
|
||||
m.previous_body_yaw = m.body_yaw;
|
||||
m.head_yaw = m.body_yaw + x_angle * 20.0;
|
||||
m.previous_head_yaw = m.head_yaw;
|
||||
m.head_pitch = -y_angle * 20.0;
|
||||
m.previous_head_pitch = m.head_pitch;
|
||||
m.hurt_time = 0;
|
||||
m.death_time = 0;
|
||||
let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z);
|
||||
let atlas = &self.res.atlas;
|
||||
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
|
||||
let mut verts = Vec::new();
|
||||
horizon_client::mobs::render::render_with(
|
||||
&m,
|
||||
1.0,
|
||||
camera,
|
||||
&lookup,
|
||||
240 | 240 << 8,
|
||||
&self.res.mob_data,
|
||||
&[],
|
||||
&mut verts,
|
||||
);
|
||||
let height = m.kind.height as f32;
|
||||
let gui = glam::Mat4::from_translation(glam::Vec3::new(cx, cy, 0.0))
|
||||
* glam::Mat4::from_scale(glam::Vec3::new(size, size, -size))
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.0, height / 2.0 + offset_y, 0.0))
|
||||
* glam::Mat4::from_rotation_z(std::f32::consts::PI)
|
||||
* glam::Mat4::from_rotation_x((y_angle * 20.0).to_radians());
|
||||
let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
|
||||
for q in verts.as_chunks::<4>().0 {
|
||||
let p: [glam::Vec3; 4] =
|
||||
std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos)));
|
||||
let n = (p[1] - p[0]).cross(p[2] - p[0]);
|
||||
if n.z >= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let n = n.normalize_or_zero();
|
||||
let shade = (0.55 + 0.45 * -n.z - 0.15 * n.y).clamp(0.4, 1.0);
|
||||
let c = q[0].color;
|
||||
let ch = |s: u32| ((((c >> s) & 255) as f32 * shade) as u32) << s;
|
||||
let color = (c & 0xFF00_0000) | ch(0) | ch(8) | ch(16);
|
||||
let depth = p.iter().map(|v| v.z).sum::<f32>() / 4.0;
|
||||
quads.push((
|
||||
depth,
|
||||
p.map(|v| [v.x, v.y]),
|
||||
std::array::from_fn(|i| q[i].uv),
|
||||
color,
|
||||
));
|
||||
}
|
||||
quads.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let start = batch.vertices.len();
|
||||
for (_, p, uv, color) in quads {
|
||||
batch.quad(p, uv, color);
|
||||
}
|
||||
batch.clip_since(start, x0, y0, x1, y1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_horses_wear_horse_armour() {
|
||||
assert!(body_armor_fits(
|
||||
Species::Horse,
|
||||
"minecraft:iron_horse_armor"
|
||||
));
|
||||
assert!(body_armor_fits(
|
||||
Species::ZombieHorse,
|
||||
"minecraft:diamond_horse_armor"
|
||||
));
|
||||
assert!(!body_armor_fits(
|
||||
Species::Donkey,
|
||||
"minecraft:iron_horse_armor"
|
||||
));
|
||||
assert!(!body_armor_fits(
|
||||
Species::Horse,
|
||||
"minecraft:iron_chestplate"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ fn seat(s: Species) -> f64 {
|
||||
#[derive(Default)]
|
||||
pub(super) struct MountState {
|
||||
/// `jumpRidingTicks`: -10 cooling down after a jump, >= 0 charging.
|
||||
jump_ticks: i32,
|
||||
pub(super) jump_ticks: i32,
|
||||
/// `jumpRidingScale` (0..1).
|
||||
pub(super) jump_scale: f32,
|
||||
was_jumping: bool,
|
||||
@@ -99,6 +99,15 @@ impl Game<'_> {
|
||||
if !equine::is_equine(species) || !m.alive() || Some(m.id) == self.riding {
|
||||
return false;
|
||||
}
|
||||
// AbstractHorse.mobInteract: shift + use opens a tamed adult's inventory.
|
||||
if !m.is_baby()
|
||||
&& m.extra.tame
|
||||
&& (self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|
||||
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight))
|
||||
{
|
||||
self.open_mount_menu(index);
|
||||
return true;
|
||||
}
|
||||
if self.feed_mount(index, item) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ use std::{
|
||||
#[derive(Default)]
|
||||
pub struct EntityMemory {
|
||||
/// UUIDs of mobs and item entities by Horizon entity ID.
|
||||
uuids: HashMap<u32, [i32; 4]>,
|
||||
pub(super) uuids: HashMap<u32, [i32; 4]>,
|
||||
/// The compound each mob or item entity was loaded with.
|
||||
raw: HashMap<u32, Tag>,
|
||||
pub(super) raw: HashMap<u32, Tag>,
|
||||
/// Entities of types Horizon does not simulate, kept per chunk and
|
||||
/// written back unchanged.
|
||||
unknown: HashMap<(i32, i32), Vec<Tag>>,
|
||||
@@ -269,9 +269,17 @@ impl Game<'_> {
|
||||
}
|
||||
self.persist.raw.insert(id, tag);
|
||||
}
|
||||
fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
||||
pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
||||
*self.persist.uuids.entry(id).or_insert_with(random_uuid)
|
||||
}
|
||||
/// The loaded mob with a saved UUID.
|
||||
pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
|
||||
self.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed))
|
||||
.map(|(id, _)| *id)
|
||||
}
|
||||
/// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`).
|
||||
fn state_from_nbt(&self, tag: &Tag) -> Option<BlockStateId> {
|
||||
let registry = self.res.assets.registry;
|
||||
|
||||
@@ -19,6 +19,18 @@ pub(super) struct ThrownPotion {
|
||||
velocity: Vec3,
|
||||
age: u32,
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// A splash potion, lingering potion or experience bottle in flight (the
|
||||
/// player's throws and dispensers both end up here).
|
||||
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
|
||||
self.potions.thrown.push(ThrownPotion {
|
||||
stack,
|
||||
position,
|
||||
velocity,
|
||||
age: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
/// Effects, thrown potions and the attribute modifiers last applied.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PotionState {
|
||||
@@ -40,21 +52,25 @@ impl Game<'_> {
|
||||
/// Right-click with a potion, splash/lingering potion or glass bottle.
|
||||
pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result<bool> {
|
||||
match &*stack.item {
|
||||
"minecraft:potion" => {
|
||||
"minecraft:potion" | "minecraft:ominous_bottle" => {
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.selected, 0));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
"minecraft:splash_potion" | "minecraft:lingering_potion" => {
|
||||
"minecraft:splash_potion"
|
||||
| "minecraft:lingering_potion"
|
||||
| "minecraft:experience_bottle" => {
|
||||
let Some(eye) = self.eye_position() else {
|
||||
return Ok(true);
|
||||
};
|
||||
let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8);
|
||||
let sound = if &*stack.item == "minecraft:splash_potion" {
|
||||
"minecraft:entity.splash_potion.throw"
|
||||
} else {
|
||||
"minecraft:entity.lingering_potion.throw"
|
||||
let (sound, power) = match &*stack.item {
|
||||
"minecraft:splash_potion" => ("minecraft:entity.splash_potion.throw", 0.5),
|
||||
"minecraft:experience_bottle" => {
|
||||
("minecraft:entity.experience_bottle.throw", 0.7)
|
||||
}
|
||||
_ => ("minecraft:entity.lingering_potion.throw", 0.5),
|
||||
};
|
||||
self.audio.play(sound, Some(eye), 0.5, pitch);
|
||||
// Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0).
|
||||
@@ -74,9 +90,9 @@ impl Game<'_> {
|
||||
let r = &mut self.world.random;
|
||||
let mut jitter = || r.triangle(0.0, 0.0172275);
|
||||
let v = Vec3::new(
|
||||
(f64::from(dir[0]) / l + jitter()) * 0.5,
|
||||
(f64::from(dir[1]) / l + jitter()) * 0.5,
|
||||
(f64::from(dir[2]) / l + jitter()) * 0.5,
|
||||
(f64::from(dir[0]) / l + jitter()) * power,
|
||||
(f64::from(dir[1]) / l + jitter()) * power,
|
||||
(f64::from(dir[2]) / l + jitter()) * power,
|
||||
);
|
||||
let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity);
|
||||
let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground);
|
||||
@@ -85,15 +101,14 @@ impl Game<'_> {
|
||||
v.y + if on_ground { 0.0 } else { pv.y },
|
||||
v.z + pv.z,
|
||||
);
|
||||
self.potions.thrown.push(ThrownPotion {
|
||||
stack: ItemStack {
|
||||
self.launch_thrown(
|
||||
ItemStack {
|
||||
count: 1,
|
||||
..stack.clone()
|
||||
},
|
||||
position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
|
||||
velocity: v,
|
||||
age: 0,
|
||||
});
|
||||
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
|
||||
v,
|
||||
);
|
||||
self.swing_arm();
|
||||
self.consume_held();
|
||||
Ok(true)
|
||||
@@ -137,7 +152,8 @@ impl Game<'_> {
|
||||
}
|
||||
/// Drinking a potion while right-click is held; true when handled.
|
||||
pub(super) fn tick_drinking(&mut self, slot: usize, ticks: u32, stack: &ItemStack) -> bool {
|
||||
if &*stack.item != "minecraft:potion" {
|
||||
let ominous = &*stack.item == "minecraft:ominous_bottle";
|
||||
if &*stack.item != "minecraft:potion" && !ominous {
|
||||
return false;
|
||||
}
|
||||
let ticks = ticks + 1;
|
||||
@@ -154,6 +170,11 @@ impl Game<'_> {
|
||||
return true;
|
||||
}
|
||||
self.using = None;
|
||||
self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player);
|
||||
if ominous {
|
||||
self.drink_ominous_bottle(slot, stack);
|
||||
return true;
|
||||
}
|
||||
let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0);
|
||||
for e in lasting {
|
||||
self.potions.effects.add(e);
|
||||
@@ -326,19 +347,25 @@ impl Game<'_> {
|
||||
}
|
||||
t.position = next;
|
||||
// ThrowableItemProjectile: drag 0.99 then gravity 0.05.
|
||||
// ThrownExperienceBottle.getDefaultGravity is 0.07.
|
||||
let gravity = if &*t.stack.item == "minecraft:experience_bottle" {
|
||||
0.07
|
||||
} else {
|
||||
0.05
|
||||
};
|
||||
t.velocity = Vec3::new(
|
||||
t.velocity.x * 0.99,
|
||||
t.velocity.y * 0.99 - 0.05,
|
||||
t.velocity.y * 0.99 - gravity,
|
||||
t.velocity.z * 0.99,
|
||||
);
|
||||
t.age < 1200 && t.position.y > -128.0
|
||||
});
|
||||
// ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position.
|
||||
for t in &thrown {
|
||||
let sprite = if &*t.stack.item == "minecraft:lingering_potion" {
|
||||
"item/lingering_potion"
|
||||
} else {
|
||||
"item/splash_potion"
|
||||
let sprite = match &*t.stack.item {
|
||||
"minecraft:lingering_potion" => "item/lingering_potion",
|
||||
"minecraft:experience_bottle" => "item/experience_bottle",
|
||||
_ => "item/splash_potion",
|
||||
};
|
||||
let mut fixed = horizon_core::random::LegacyRandom::new(0);
|
||||
let mut p = horizon_client::particles::Particle::terrain(
|
||||
@@ -362,6 +389,36 @@ impl Game<'_> {
|
||||
}
|
||||
/// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash).
|
||||
fn splash(&mut self, stack: &ItemStack, at: Vec3) {
|
||||
if &*stack.item == "minecraft:experience_bottle" {
|
||||
// ThrownExperienceBottle.onHit: the water-coloured splash (level
|
||||
// event 2002) and 3 to 11 experience.
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio.play(
|
||||
"minecraft:entity.splash_potion.break",
|
||||
Some([at.x, at.y, at.z]),
|
||||
1.0,
|
||||
pitch,
|
||||
);
|
||||
for _ in 0..8 {
|
||||
let v = [
|
||||
f64::from(self.world.random.next_float() - 0.5) * 0.3,
|
||||
0.2,
|
||||
f64::from(self.world.random.next_float() - 0.5) * 0.3,
|
||||
];
|
||||
let p = horizon_client::particles::Particle::terrain(
|
||||
&mut self.world.random,
|
||||
[at.x, at.y, at.z],
|
||||
v,
|
||||
"item/splash_potion".into(),
|
||||
0x38_5DC6,
|
||||
);
|
||||
self.particles.push(p);
|
||||
}
|
||||
let r = &mut self.world.random;
|
||||
let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0);
|
||||
self.spawn_orbs([at.x, at.y, at.z], value as u32);
|
||||
return;
|
||||
}
|
||||
let lingering = &*stack.item == "minecraft:lingering_potion";
|
||||
let event = if lingering {
|
||||
"minecraft:entity.lingering_potion.break"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -88,6 +88,7 @@ impl Game<'_> {
|
||||
thunder,
|
||||
skybox: self.dim == Dim::Overworld,
|
||||
blindness: None,
|
||||
darkness: self.darkness_fog(),
|
||||
})
|
||||
}
|
||||
/// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water.
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
//! The scoreboard in the running game: saved data, criteria that follow the
|
||||
//! player (health, food, xp, deaths, kills, statistics), score holders for
|
||||
//! entities, the selector options `scores=`, `team=` and `tag=`, the
|
||||
//! commands' [`Env`] and the sidebar.
|
||||
use super::{Game, chat::PLAYER_NAME, commands::Target};
|
||||
use horizon_client::{
|
||||
command::{
|
||||
Context,
|
||||
args::{IntRange, Selector},
|
||||
},
|
||||
hud::{HudBatch, rgba},
|
||||
save::{self, uuid_from_text, uuid_text},
|
||||
scoreboard::{self as sb, Comp, NumberFormat, Scoreboard, literal},
|
||||
scoreboard_cmd::{self, Env, Holder},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// What `ServerPlayer` last recorded for the criteria that follow the player.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recorded {
|
||||
health: Option<i32>,
|
||||
food: Option<i32>,
|
||||
air: Option<i32>,
|
||||
armor: Option<i32>,
|
||||
xp: Option<i32>,
|
||||
level: Option<i32>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct ScoreState {
|
||||
pub board: Scoreboard,
|
||||
/// `/data ... storage`.
|
||||
pub storage: horizon_client::command_storage::CommandStorage,
|
||||
loaded: bool,
|
||||
recorded: Recorded,
|
||||
}
|
||||
|
||||
fn in_range(v: i32, (lo, hi): IntRange) -> bool {
|
||||
lo.is_none_or(|l| v >= l) && hi.is_none_or(|h| v <= h)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn scoreboard_path(&self) -> std::path::PathBuf {
|
||||
self.world_root.join("data/minecraft/scoreboard.dat")
|
||||
}
|
||||
/// `ScoreboardSaveData` read from `data/minecraft/scoreboard.dat`.
|
||||
pub(super) fn load_scoreboard(&mut self) {
|
||||
if self.score.loaded || self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
self.score.loaded = true;
|
||||
if let Some(root) = save::read_dat(&self.scoreboard_path())
|
||||
&& let Some(data) = root.get("data")
|
||||
{
|
||||
self.score.board = Scoreboard::unpack(data);
|
||||
}
|
||||
self.score.storage =
|
||||
horizon_client::command_storage::CommandStorage::load(&self.world_root);
|
||||
if let Some(root) = save::read_dat(&self.world_root.join("data/minecraft/world_border.dat"))
|
||||
&& let Some(data) = root.get("data")
|
||||
{
|
||||
self.border = horizon_client::worldborder::WorldBorder::unpack(data);
|
||||
}
|
||||
self.sync_score_registries();
|
||||
}
|
||||
pub(super) fn save_scoreboard(&mut self) {
|
||||
if !self.score.loaded || self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
self.score.storage.save(&self.world_root);
|
||||
if self.border != horizon_client::worldborder::WorldBorder::default() {
|
||||
let _ = save::write_dat(
|
||||
&self.world_root.join("data/minecraft/world_border.dat"),
|
||||
Tag::compound([
|
||||
("data", self.border.pack()),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
let path = self.scoreboard_path();
|
||||
let board = &self.score.board;
|
||||
if board == &Scoreboard::default() && !path.exists() {
|
||||
return;
|
||||
}
|
||||
let _ = save::write_dat(
|
||||
&path,
|
||||
Tag::compound([
|
||||
("data", board.pack()),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
/// The names commands complete: objectives, teams and tracked holders.
|
||||
pub(super) fn sync_score_registries(&mut self) {
|
||||
let board = &self.score.board;
|
||||
let reg = &mut self.ui.registries;
|
||||
reg.objectives = board.objectives.iter().map(|o| o.name.clone()).collect();
|
||||
reg.teams = board.teams.iter().map(|t| t.name.clone()).collect();
|
||||
reg.tracked = board.tracked();
|
||||
reg.storages = self.score.storage.keys();
|
||||
}
|
||||
|
||||
// ---- score holders ---------------------------------------------------
|
||||
|
||||
/// `ScoreHolder.getScoreboardName`: the player's name, an entity's UUID.
|
||||
pub(super) fn holder_name(&mut self, t: Target) -> Option<String> {
|
||||
match t {
|
||||
Target::Player => Some(PLAYER_NAME.to_owned()),
|
||||
Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn holder_for(&mut self, t: Target) -> Option<Holder> {
|
||||
let name = self.holder_name(t)?;
|
||||
let shown = self.target_name(t);
|
||||
Some(Holder {
|
||||
display: Some(literal(&shown.plain())),
|
||||
text: shown,
|
||||
name,
|
||||
})
|
||||
}
|
||||
/// The entity with the given scoreboard name.
|
||||
fn target_of_holder(&self, name: &str) -> Option<Target> {
|
||||
if name == PLAYER_NAME {
|
||||
return Some(Target::Player);
|
||||
}
|
||||
let uuid = uuid_from_text(name).filter(|_| name.len() == 36)?;
|
||||
if Some(uuid) == self.level.player_uuid {
|
||||
return Some(Target::Player);
|
||||
}
|
||||
let id = self
|
||||
.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.find(|(_, u)| **u == uuid)
|
||||
.map(|(id, _)| *id)?;
|
||||
if self.mobs.iter().any(|m| m.id == id) {
|
||||
Some(Target::Mob(id))
|
||||
} else if self.dropped.iter().any(|i| i.id == id) {
|
||||
Some(Target::Item(id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// `Entity.getTags` (the `Tags` list of the saved entity).
|
||||
pub(super) fn tags_of(&self, t: Target) -> Vec<String> {
|
||||
let raw = match t {
|
||||
Target::Mob(id) | Target::Item(id) => self.persist.raw.get(&id),
|
||||
Target::Player => self.level.player_extra.as_ref(),
|
||||
_ => None,
|
||||
};
|
||||
match raw.and_then(|r| r.get("Tags")) {
|
||||
Some(Tag::List(l)) => l
|
||||
.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
/// The selector options that need the scoreboard or entity data: which
|
||||
/// of `candidates` pass `scores=`, `team=` and `tag=`.
|
||||
pub(super) fn selector_extra_filter(
|
||||
&mut self,
|
||||
candidates: &[Target],
|
||||
s: &Selector,
|
||||
) -> HashSet<Target> {
|
||||
let mut pass = HashSet::new();
|
||||
let needs_holder = !s.scores.is_empty() || !s.teams.is_empty();
|
||||
for &t in candidates {
|
||||
let mut ok = true;
|
||||
if needs_holder {
|
||||
let holder = self.holder_name(t);
|
||||
for (objective, range) in &s.scores {
|
||||
let value = holder
|
||||
.as_deref()
|
||||
.and_then(|h| self.score.board.score(h, objective))
|
||||
.map(|score| score.value);
|
||||
if !value.is_some_and(|v| in_range(v, *range)) {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
let team = holder
|
||||
.as_deref()
|
||||
.and_then(|h| self.score.board.players_team(h))
|
||||
.map(|t| t.name.clone());
|
||||
for (want, negated) in &s.teams {
|
||||
let matches = match &team {
|
||||
Some(name) => name == want,
|
||||
None => want.is_empty(),
|
||||
};
|
||||
if matches == *negated {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !s.tags.is_empty() {
|
||||
let tags = self.tags_of(t);
|
||||
for (tag, negated) in &s.tags {
|
||||
let has = if tag.is_empty() {
|
||||
!tags.is_empty()
|
||||
} else {
|
||||
tags.contains(tag)
|
||||
};
|
||||
if has == *negated {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ok && !s.nbt.is_empty() {
|
||||
// NbtPredicate: the entity's saved data contains the pattern.
|
||||
let data = self.entity_nbt(t);
|
||||
for (pattern, negated) in &s.nbt {
|
||||
let matches = match (&data, horizon_world::nbt::parse_snbt(pattern)) {
|
||||
(Some(d), Ok((p, _))) => horizon_client::nbt_path::compare_nbt(&p, Some(d)),
|
||||
_ => false,
|
||||
};
|
||||
if matches == *negated {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ok && !s.advancements.is_empty() {
|
||||
ok = t == Target::Player && self.advancements_match(&s.advancements);
|
||||
}
|
||||
if ok {
|
||||
pass.insert(t);
|
||||
}
|
||||
}
|
||||
pass
|
||||
}
|
||||
|
||||
/// `advancements=` of a selector, against the player's progress.
|
||||
fn advancements_match(
|
||||
&self,
|
||||
wanted: &[(String, horizon_client::command::args::AdvCondition)],
|
||||
) -> bool {
|
||||
use horizon_client::command::args::AdvCondition;
|
||||
wanted.iter().all(|(id, cond)| {
|
||||
let Some(a) = self.adv.tree.get(id) else {
|
||||
return false;
|
||||
};
|
||||
match cond {
|
||||
AdvCondition::Done(want) => self.adv.progress.done(a) == *want,
|
||||
AdvCondition::Criteria(list) => list
|
||||
.iter()
|
||||
.all(|(c, want)| self.adv.progress.has(id, c) == *want),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---- criteria ----------------------------------------------------------
|
||||
|
||||
/// `ServerPlayer.doTick` score updates and the statistic criteria.
|
||||
pub(super) fn tick_scoreboard(&mut self) {
|
||||
self.load_scoreboard();
|
||||
let events = std::mem::take(&mut self.stats.events);
|
||||
let board = &mut self.score.board;
|
||||
if !board.objectives.is_empty() {
|
||||
for (ty, key, amount) in events {
|
||||
let criteria = sb::stat_criteria(&ty, &key);
|
||||
if board.has_objectives_for(&criteria) {
|
||||
board.for_all_objectives(&criteria, PLAYER_NAME, |v| {
|
||||
amount.map_or(0, |n| v.wrapping_add(n))
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
let health = (p.health.health() + p.health.absorption()).ceil() as i32;
|
||||
let food = p.health.food.food;
|
||||
let armor = p
|
||||
.attribute("minecraft:armor")
|
||||
.or_else(|_| p.attribute("armor"))
|
||||
.unwrap_or(0.0)
|
||||
.ceil() as i32;
|
||||
let rec = &mut self.score.recorded;
|
||||
let board = &mut self.score.board;
|
||||
for (criteria, last, value) in [
|
||||
(sb::CRITERIA_HEALTH, &mut rec.health, health),
|
||||
(sb::CRITERIA_FOOD, &mut rec.food, food),
|
||||
// The air supply is full unless the player is drowning.
|
||||
(sb::CRITERIA_AIR, &mut rec.air, 300),
|
||||
(sb::CRITERIA_ARMOR, &mut rec.armor, armor),
|
||||
(sb::CRITERIA_XP, &mut rec.xp, self.experience.total),
|
||||
(sb::CRITERIA_LEVEL, &mut rec.level, self.experience.level),
|
||||
] {
|
||||
if *last != Some(value) {
|
||||
*last = Some(value);
|
||||
board.for_all_objectives(criteria, PLAYER_NAME, |_| value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.ticks.is_multiple_of(20) {
|
||||
self.sync_score_registries();
|
||||
}
|
||||
}
|
||||
/// `ServerPlayer.die`: the death count.
|
||||
pub(super) fn score_player_died(&mut self) {
|
||||
let board = &mut self.score.board;
|
||||
board.for_all_objectives(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, |v| v + 1);
|
||||
// A respawned player has everything to record again.
|
||||
self.score.recorded = Recorded::default();
|
||||
}
|
||||
/// `ServerPlayer.awardKillScore`: total kills and the team kill counts.
|
||||
pub(super) fn score_player_killed(&mut self, victim: Target) {
|
||||
let victim_name = self.holder_name(victim);
|
||||
let board = &mut self.score.board;
|
||||
board.for_all_objectives(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, |v| v + 1);
|
||||
if victim == Target::Player {
|
||||
board.for_all_objectives(sb::CRITERIA_PLAYER_KILLS, PLAYER_NAME, |v| v + 1);
|
||||
}
|
||||
let color_of =
|
||||
|board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone());
|
||||
if let Some(victim_name) = victim_name {
|
||||
if let Some(color) = color_of(board, &victim_name) {
|
||||
let criteria = format!("teamkill.{color}");
|
||||
board.for_all_objectives(&criteria, PLAYER_NAME, |v| v + 1);
|
||||
}
|
||||
if let Some(color) = color_of(board, PLAYER_NAME) {
|
||||
let criteria = format!("killedByTeam.{color}");
|
||||
board.for_all_objectives(&criteria, &victim_name, |v| v + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Scoreboard.entityRemoved`: a dead non-player entity leaves the board.
|
||||
pub(super) fn score_entity_removed(&mut self, id: u32) {
|
||||
let Some(uuid) = self.persist.uuids.get(&id).copied() else {
|
||||
return;
|
||||
};
|
||||
let name = uuid_text(uuid);
|
||||
self.score.board.reset_all(&name);
|
||||
self.score.board.remove_from_team(&name);
|
||||
}
|
||||
|
||||
// ---- commands ------------------------------------------------------------
|
||||
|
||||
/// The scoreboard names a score holder argument resolves to.
|
||||
pub(super) fn score_holder_names(
|
||||
&mut self,
|
||||
ctx: &Context,
|
||||
name: &str,
|
||||
default_wildcard: bool,
|
||||
) -> super::commands::R<Vec<String>> {
|
||||
let mut env = GameEnv { g: self };
|
||||
Ok(
|
||||
scoreboard_cmd::holders(ctx, name, &mut env, default_wildcard)?
|
||||
.into_iter()
|
||||
.map(|h| h.name)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
pub(super) fn cmd_scoreboard(&mut self, id: &str, ctx: &Context) -> super::commands::R<i32> {
|
||||
let mut env = GameEnv { g: self };
|
||||
let result = scoreboard_cmd::execute(id, ctx, &mut env).unwrap_or_else(|| {
|
||||
Err(horizon_client::command::CommandError::tr(
|
||||
"command.failed",
|
||||
&[],
|
||||
))
|
||||
});
|
||||
self.sync_score_registries();
|
||||
result
|
||||
}
|
||||
/// ComponentUtils.updateForEntity for the pieces scoreboards store:
|
||||
/// `selector` and `score` components become their text.
|
||||
pub(super) fn resolve_component(&mut self, c: Comp) -> Comp {
|
||||
match c {
|
||||
Comp::Object(mut o) => {
|
||||
if let Some(sel) = o.get("selector").and_then(Comp::as_str).map(str::to_owned) {
|
||||
let text = self.resolve_selector_text(&sel);
|
||||
o.remove("selector");
|
||||
o.insert("text".into(), Comp::String(text));
|
||||
} else if let Some(score) = o.get("score").cloned() {
|
||||
let name = score.get("name").and_then(Comp::as_str).unwrap_or("");
|
||||
let objective = score.get("objective").and_then(Comp::as_str).unwrap_or("");
|
||||
let name = if name == "*" { PLAYER_NAME } else { name };
|
||||
let text = self
|
||||
.score
|
||||
.board
|
||||
.score(name, objective)
|
||||
.map_or_else(String::new, |s| s.value.to_string());
|
||||
o.remove("score");
|
||||
o.insert("text".into(), Comp::String(text));
|
||||
}
|
||||
for key in ["extra", "with"] {
|
||||
if let Some(Comp::Array(list)) = o.remove(key) {
|
||||
let list = list
|
||||
.into_iter()
|
||||
.map(|c| self.resolve_component(c))
|
||||
.collect();
|
||||
o.insert(key.into(), Comp::Array(list));
|
||||
}
|
||||
}
|
||||
Comp::Object(o)
|
||||
}
|
||||
Comp::Array(list) => Comp::Array(
|
||||
list.into_iter()
|
||||
.map(|c| self.resolve_component(c))
|
||||
.collect(),
|
||||
),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
fn resolve_selector_text(&mut self, raw: &str) -> String {
|
||||
let mut reader = horizon_client::command::Reader::new(raw);
|
||||
let ty = horizon_client::command::args::ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
let Ok(horizon_client::command::Arg::Entity(sel)) =
|
||||
ty.parse(&mut reader, &self.ui.registries)
|
||||
else {
|
||||
return raw.to_owned();
|
||||
};
|
||||
let names: Vec<String> = self
|
||||
.select(&sel)
|
||||
.into_iter()
|
||||
.map(|t| self.target_name(t).plain())
|
||||
.collect();
|
||||
names.join(", ")
|
||||
}
|
||||
|
||||
// ---- the sidebar -----------------------------------------------------------
|
||||
|
||||
/// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`.
|
||||
pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) {
|
||||
let board = &self.score.board;
|
||||
if board.display.is_empty() {
|
||||
return;
|
||||
}
|
||||
let team_slot = board
|
||||
.players_team(PLAYER_NAME)
|
||||
.and_then(|t| t.color.as_ref())
|
||||
.map(|c| format!("sidebar.team.{c}"))
|
||||
.and_then(|slot| board.display_objective(&slot));
|
||||
let Some(objective) = team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let default_format = NumberFormat::sidebar_default();
|
||||
let format = objective.format_or_default(default_format);
|
||||
let mut entries: Vec<_> = board
|
||||
.list_scores(&objective.name)
|
||||
.into_iter()
|
||||
.filter(|e| !e.is_hidden())
|
||||
.collect();
|
||||
// Highest score first, then names case-insensitively.
|
||||
entries.sort_by(|a, b| {
|
||||
b.value
|
||||
.cmp(&a.value)
|
||||
.then_with(|| a.owner.to_lowercase().cmp(&b.owner.to_lowercase()))
|
||||
});
|
||||
entries.truncate(15);
|
||||
let rows: Vec<(Text, Text, f32)> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let name = match board.players_team(&e.owner) {
|
||||
Some(t) => t.formatted_name(e.owner_name()),
|
||||
None => e.owner_name(),
|
||||
};
|
||||
let score = e.format_value(&format);
|
||||
let width = atlas.font.width_text(&score);
|
||||
(name, score, width)
|
||||
})
|
||||
.collect();
|
||||
let title = objective.display_text();
|
||||
let title_width = atlas.font.width_text(&title);
|
||||
let spacer = atlas.font.width(": ");
|
||||
let mut biggest = title_width;
|
||||
for (name, _, score_width) in &rows {
|
||||
let extra = if *score_width > 0.0 {
|
||||
spacer + score_width
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
biggest = biggest.max(atlas.font.width_text(name) + extra);
|
||||
}
|
||||
let count = rows.len() as f32;
|
||||
let height = count * 9.0;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let bottom = (h / 2.0).trunc() + (height / 3.0).trunc();
|
||||
let left = w - biggest - 3.0;
|
||||
let right = w - 3.0 + 2.0;
|
||||
let body = rgba(0, 0, 0, (0.3 * 255.0) as u8);
|
||||
let header = rgba(0, 0, 0, (0.4 * 255.0) as u8);
|
||||
let top = bottom - count * 9.0;
|
||||
batch.fill(
|
||||
atlas,
|
||||
left - 2.0,
|
||||
top - 9.0 - 1.0,
|
||||
right - (left - 2.0),
|
||||
9.0,
|
||||
header,
|
||||
);
|
||||
batch.fill(
|
||||
atlas,
|
||||
left - 2.0,
|
||||
top - 1.0,
|
||||
right - (left - 2.0),
|
||||
bottom - (top - 1.0),
|
||||
body,
|
||||
);
|
||||
let white = rgba(255, 255, 255, 255);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
left + (biggest / 2.0).trunc() - (title_width / 2.0).trunc(),
|
||||
top - 9.0,
|
||||
white,
|
||||
false,
|
||||
);
|
||||
for (i, (name, score, score_width)) in rows.iter().enumerate() {
|
||||
let y = bottom - (count - i as f32) * 9.0;
|
||||
batch.text_styled(atlas, name, left, y, white, false);
|
||||
batch.text_styled(atlas, score, right - score_width, y, white, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands' view of the game.
|
||||
struct GameEnv<'a, 'b> {
|
||||
g: &'a mut Game<'b>,
|
||||
}
|
||||
impl Env for GameEnv<'_, '_> {
|
||||
fn sb(&self) -> &Scoreboard {
|
||||
&self.g.score.board
|
||||
}
|
||||
fn sb_mut(&mut self) -> &mut Scoreboard {
|
||||
&mut self.g.score.board
|
||||
}
|
||||
fn select(&mut self, selector: &Selector) -> Vec<Holder> {
|
||||
let found = self.g.select(selector);
|
||||
found
|
||||
.into_iter()
|
||||
.filter_map(|t| self.g.holder_for(t))
|
||||
.collect()
|
||||
}
|
||||
fn named(&mut self, name: &str) -> Holder {
|
||||
if name.eq_ignore_ascii_case(PLAYER_NAME) && self.g.player.is_some() {
|
||||
return self
|
||||
.g
|
||||
.holder_for(Target::Player)
|
||||
.unwrap_or_else(|| Holder::named(name));
|
||||
}
|
||||
match self.g.target_of_holder(name) {
|
||||
Some(t) => self.g.holder_for(t).unwrap_or_else(|| Holder::named(name)),
|
||||
None => Holder::named(name),
|
||||
}
|
||||
}
|
||||
fn source(&mut self) -> Option<(Holder, bool)> {
|
||||
let entity = match self.g.command_source {
|
||||
Some(s) => s.entity,
|
||||
None => Some(Target::Player),
|
||||
}?;
|
||||
let name = match entity {
|
||||
Target::Player => PLAYER_NAME.to_owned(),
|
||||
Target::Mob(id) | Target::Item(id) => uuid_text(self.g.uuid_for(id)),
|
||||
_ => return None,
|
||||
};
|
||||
let text = self.g.target_name(entity);
|
||||
Some((
|
||||
Holder {
|
||||
display: Some(literal(&text.plain())),
|
||||
text,
|
||||
name,
|
||||
},
|
||||
entity == Target::Player,
|
||||
))
|
||||
}
|
||||
fn resolve(&mut self, c: Comp) -> Comp {
|
||||
self.g.resolve_component(c)
|
||||
}
|
||||
fn feedback(&mut self, message: Text) {
|
||||
self.g.feedback(message);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -252,14 +252,8 @@ pub(super) fn draw_shield_icon(
|
||||
atlas: &horizon_client::hud::HudAtlas,
|
||||
x: f32,
|
||||
y: f32,
|
||||
passes: &[(String, u32)],
|
||||
) {
|
||||
let Some(r) = atlas
|
||||
.sprites
|
||||
.get("entity/shield/shield_base_nopattern")
|
||||
.copied()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
// display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65.
|
||||
let (sx, cx) = 15f32.to_radians().sin_cos();
|
||||
let (sy, cy) = (-25f32).to_radians().sin_cos();
|
||||
@@ -282,15 +276,9 @@ pub(super) fn draw_shield_icon(
|
||||
qz,
|
||||
]
|
||||
};
|
||||
let tex = |u: f32, v: f32| {
|
||||
[
|
||||
r.u0 + (r.u1 - r.u0) * u / 64.0,
|
||||
r.v0 + (r.v1 - r.v0) * v / 64.0,
|
||||
]
|
||||
};
|
||||
// ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and
|
||||
// handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6).
|
||||
let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
|
||||
let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new();
|
||||
for (tu, tv, from, size) in [
|
||||
(0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]),
|
||||
(26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]),
|
||||
@@ -324,16 +312,64 @@ pub(super) fn draw_shield_icon(
|
||||
}
|
||||
let p = verts.map(place);
|
||||
let depth = p.iter().map(|q| q[2]).sum::<f32>() / 4.0;
|
||||
let uv = [tex(c, b), tex(a, b), tex(a, e), tex(c, e)];
|
||||
let texels = [[c, b], [a, b], [a, e], [c, e]];
|
||||
// Flat item lighting: faces toward the viewer are brightest.
|
||||
let shade = (0.6 + 0.4 * normal[2]).min(1.0);
|
||||
let s = (shade * 255.0) as u8;
|
||||
let color = horizon_client::hud::rgba(s, s, s, 255);
|
||||
faces.push((depth, p.map(|q| [q[0], q[1]]), uv, color));
|
||||
faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade));
|
||||
}
|
||||
}
|
||||
faces.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
for (_, p, uv, color) in faces {
|
||||
// Every pass redraws the same boxes; equal depths keep the pass order.
|
||||
let mut quads = Vec::new();
|
||||
for (index, (name, tint)) in passes.iter().enumerate() {
|
||||
let Some(r) = atlas.sprites.get(name).copied() else {
|
||||
continue;
|
||||
};
|
||||
for (depth, p, texels, shade) in &faces {
|
||||
let uv = texels.map(|[u, v]| {
|
||||
[
|
||||
r.u0 + (r.u1 - r.u0) * u / 64.0,
|
||||
r.v0 + (r.v1 - r.v0) * v / 64.0,
|
||||
]
|
||||
});
|
||||
let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8;
|
||||
quads.push((
|
||||
*depth,
|
||||
index,
|
||||
*p,
|
||||
uv,
|
||||
horizon_client::hud::rgba(c(16), c(8), c(0), 255),
|
||||
));
|
||||
}
|
||||
}
|
||||
quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
|
||||
for (_, _, p, uv, color) in quads {
|
||||
batch.quad(p, uv, color);
|
||||
}
|
||||
}
|
||||
/// The textures a shield draws: the plain or patterned base, then the
|
||||
/// banner layers (`ShieldSpecialRenderer.submit`).
|
||||
pub(super) fn shield_passes(
|
||||
banners: &horizon_client::banner::Banners,
|
||||
stack: &ItemStack,
|
||||
) -> Vec<(String, u32)> {
|
||||
let data = stack.data();
|
||||
let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]);
|
||||
let base = data.and_then(|d| d.base_color.as_deref());
|
||||
if layers.is_empty() && base.is_none() {
|
||||
return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)];
|
||||
}
|
||||
let mut passes = vec![
|
||||
("entity/shield/shield_base".into(), 0xFFFFFF),
|
||||
(
|
||||
"entity/shield/base".into(),
|
||||
horizon_client::banner::dye_rgb(base.unwrap_or("white")),
|
||||
),
|
||||
];
|
||||
for layer in layers.iter().take(16) {
|
||||
passes.push((
|
||||
banners.shield_texture(&layer.pattern),
|
||||
horizon_client::banner::dye_rgb(&layer.color),
|
||||
));
|
||||
}
|
||||
passes
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ pub(super) const HELP: &[&str] = &[
|
||||
"effect ID SECONDS [AMPLIFIER] give a status effect (effect clear removes all)",
|
||||
"effects list active status effects",
|
||||
"trade PROFESSION [LEVEL] [TYPE] open a villager trading menu (offers from the world's trade sequences)",
|
||||
"mount-menu [tame] [chest] open the inventory of the nearest horse, donkey or mule (tame, chest set those)",
|
||||
"close close the open menu",
|
||||
];
|
||||
fn id(name: &str) -> String {
|
||||
@@ -194,6 +195,29 @@ impl Game<'_> {
|
||||
"effects" => Ok(Some(
|
||||
json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }),
|
||||
)),
|
||||
"mount-menu" => {
|
||||
let eye = self.eye_position().ok_or("no player")?;
|
||||
let index = (0..self.mobs.len())
|
||||
.filter(|&i| horizon_client::mobs::equine::is_equine(self.mobs[i].species()))
|
||||
.min_by(|&a, &b| {
|
||||
let d = |i: usize| {
|
||||
let c = self.mobs[i].center();
|
||||
(c[0] - eye[0]).powi(2)
|
||||
+ (c[1] - eye[1]).powi(2)
|
||||
+ (c[2] - eye[2]).powi(2)
|
||||
};
|
||||
d(a).total_cmp(&d(b))
|
||||
})
|
||||
.ok_or("no horse around")?;
|
||||
if flag("tame") {
|
||||
self.mobs[index].extra.tame = true;
|
||||
}
|
||||
if flag("chest") {
|
||||
self.mobs[index].extra.chested = true;
|
||||
}
|
||||
self.open_mount_menu(index);
|
||||
ok()
|
||||
}
|
||||
"close" => {
|
||||
self.close_container();
|
||||
self.screen = Screen::Playing;
|
||||
|
||||
@@ -32,6 +32,8 @@ pub(super) enum Kind {
|
||||
Beacon,
|
||||
/// The cartography table (game/cartography.rs).
|
||||
Cartography,
|
||||
/// The loom (game/loom.rs).
|
||||
Loom,
|
||||
}
|
||||
impl Kind {
|
||||
fn from_block(name: &str) -> Option<Self> {
|
||||
@@ -45,12 +47,13 @@ impl Kind {
|
||||
"minecraft:stonecutter" => Self::Stonecutter,
|
||||
"minecraft:beacon" => Self::Beacon,
|
||||
"minecraft:cartography_table" => Self::Cartography,
|
||||
"minecraft:loom" => Self::Loom,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn inputs(self) -> usize {
|
||||
match self {
|
||||
Self::Smithing => 3,
|
||||
Self::Smithing | Self::Loom => 3,
|
||||
Self::Stonecutter | Self::Beacon => 1,
|
||||
_ => 2,
|
||||
}
|
||||
@@ -65,6 +68,7 @@ impl Kind {
|
||||
Self::Merchant => "gui/container/villager",
|
||||
Self::Beacon => "gui/container/beacon",
|
||||
Self::Cartography => "gui/container/cartography_table",
|
||||
Self::Loom => "gui/container/loom",
|
||||
}
|
||||
}
|
||||
fn title_key(self) -> &'static str {
|
||||
@@ -77,6 +81,7 @@ impl Kind {
|
||||
Self::Merchant => "merchant.trades",
|
||||
Self::Beacon => "container.beacon",
|
||||
Self::Cartography => "container.cartography_table",
|
||||
Self::Loom => "container.loom",
|
||||
}
|
||||
}
|
||||
/// (titleLabelX, titleLabelY).
|
||||
@@ -85,7 +90,7 @@ impl Kind {
|
||||
Self::Anvil => (60.0, 6.0),
|
||||
Self::Smithing => (44.0, 15.0),
|
||||
Self::Stonecutter => (8.0, 5.0),
|
||||
Self::Cartography => (8.0, 4.0),
|
||||
Self::Cartography | Self::Loom => (8.0, 4.0),
|
||||
_ => (8.0, 6.0),
|
||||
}
|
||||
}
|
||||
@@ -99,6 +104,7 @@ impl Kind {
|
||||
Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)],
|
||||
Self::Beacon => &[(109.0, 110.0)],
|
||||
Self::Cartography => &[(15.0, 15.0), (15.0, 52.0)],
|
||||
Self::Loom => &[(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)],
|
||||
};
|
||||
table[i.min(table.len() - 1)]
|
||||
}
|
||||
@@ -112,6 +118,7 @@ impl Kind {
|
||||
Self::Merchant => Some((170.0, 37.0)),
|
||||
Self::Beacon => None,
|
||||
Self::Cartography => Some((145.0, 39.0)),
|
||||
Self::Loom => Some((143.0, 57.0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,11 +140,13 @@ pub(super) struct Station {
|
||||
input_item: Option<Arc<str>>,
|
||||
/// Anvil: the input the rename box was last filled from.
|
||||
anvil_last: Option<ItemStack>,
|
||||
last_sound: u64,
|
||||
pub(super) last_sound: u64,
|
||||
/// Villager trading state.
|
||||
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
|
||||
/// Beacon menu: the selected primary and secondary power (EFFECTS index).
|
||||
pub(super) beacon: [Option<usize>; 2],
|
||||
/// The loom's patterns, selection and scroller (game/loom.rs).
|
||||
pub(super) loom: super::loom::LoomState,
|
||||
}
|
||||
impl Station {
|
||||
fn new(kind: Kind, pos: [i32; 3]) -> Self {
|
||||
@@ -158,6 +167,7 @@ impl Station {
|
||||
last_sound: 0,
|
||||
merchant: None,
|
||||
beacon: [None; 2],
|
||||
loom: Default::default(),
|
||||
}
|
||||
}
|
||||
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
|
||||
@@ -437,6 +447,7 @@ impl Game<'_> {
|
||||
Kind::Merchant => super::trading::update(&mut s, items),
|
||||
Kind::Beacon => {}
|
||||
Kind::Cartography => s.result = self.cartography_result(&s),
|
||||
Kind::Loom => self.loom_changed(&mut s),
|
||||
Kind::Stonecutter => {
|
||||
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
|
||||
if item != s.input_item {
|
||||
@@ -472,7 +483,20 @@ impl Game<'_> {
|
||||
/// `Slot.mayPlace` and `getMaxStackSize` for station and brewing slots.
|
||||
fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
|
||||
let data = self.data();
|
||||
if (300..305).contains(&slot) {
|
||||
if slot >= super::mount_menu::SADDLE {
|
||||
return self.mount_slot_rules(slot, stack);
|
||||
}
|
||||
if let Some(BlockEntity::Crafter(c)) = self.container_kind()
|
||||
&& (300..309).contains(&slot)
|
||||
{
|
||||
// CrafterSlot.mayPlace: not a disabled slot.
|
||||
return (!c.disabled[slot - 300], 64);
|
||||
}
|
||||
if (300..400).contains(&slot) && !self.brewing_open() && self.refuses(slot, stack) {
|
||||
// ShulkerBoxSlot.mayPlace.
|
||||
return (false, 64);
|
||||
}
|
||||
if self.brewing_open() && (300..305).contains(&slot) {
|
||||
return match slot - 300 {
|
||||
0..=2 => (data.brewing.is_bottle(stack), 1),
|
||||
3 => (data.brewing.is_reagent(stack), 64),
|
||||
@@ -498,6 +522,7 @@ impl Game<'_> {
|
||||
match s.kind {
|
||||
Kind::Enchanting if i == 0 => (true, 1),
|
||||
Kind::Beacon => (super::beacon::is_payment(&stack.item), 1),
|
||||
Kind::Loom => self.loom_slot_rules(i, stack),
|
||||
Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64),
|
||||
Kind::Cartography => (
|
||||
matches!(
|
||||
@@ -513,7 +538,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `AbstractContainerMenu.doClick` PICKUP on a filtered slot.
|
||||
fn click_filtered(&mut self, slot: usize, right: bool) {
|
||||
pub(super) fn click_filtered(&mut self, slot: usize, right: bool) {
|
||||
let carried = self.carried.take();
|
||||
let current = self.slot_mut(slot).take();
|
||||
let (new_slot, new_carried) = match (carried, current) {
|
||||
@@ -565,7 +590,12 @@ impl Game<'_> {
|
||||
self.carried = new_carried;
|
||||
}
|
||||
/// `moveItemStackTo` over `targets` (menu order), merging first, then empty slots.
|
||||
fn move_to(&mut self, stack: &mut ItemStack, targets: &[usize], reverse: bool) -> bool {
|
||||
pub(super) fn move_to(
|
||||
&mut self,
|
||||
stack: &mut ItemStack,
|
||||
targets: &[usize],
|
||||
reverse: bool,
|
||||
) -> bool {
|
||||
let order: Vec<usize> = if reverse {
|
||||
targets.iter().rev().copied().collect()
|
||||
} else {
|
||||
@@ -614,8 +644,12 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
let player = Self::player_slots();
|
||||
let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom);
|
||||
let moved = if (300..305).contains(&slot) || slot >= INPUT {
|
||||
self.move_to(&mut stack, &player, true)
|
||||
// LoomMenu moves into the inventory front to back, the others back to front.
|
||||
self.move_to(&mut stack, &player, !loom)
|
||||
} else if loom {
|
||||
self.loom_quick_move(slot, &mut stack)
|
||||
} else if self.brewing_open() {
|
||||
// BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half.
|
||||
let data = self.data();
|
||||
@@ -673,7 +707,7 @@ impl Game<'_> {
|
||||
moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false);
|
||||
}
|
||||
}
|
||||
Some(Kind::Merchant) => {}
|
||||
Some(Kind::Merchant | Kind::Loom) => {}
|
||||
Some(Kind::Beacon) => {
|
||||
// BeaconMenu.quickMoveStack: one payment item into the empty slot.
|
||||
if super::beacon::is_payment(&stack.item) {
|
||||
@@ -713,7 +747,7 @@ impl Game<'_> {
|
||||
];
|
||||
self.audio.play(sound, Some(at), volume, pitch);
|
||||
}
|
||||
fn give_or_drop(&mut self, stack: ItemStack) {
|
||||
pub(super) fn give_or_drop(&mut self, stack: ItemStack) {
|
||||
if let Some(rest) = self.give(stack)
|
||||
&& let Some(eye) = self.eye_position()
|
||||
{
|
||||
@@ -860,6 +894,7 @@ impl Game<'_> {
|
||||
self.cartography_taken(pos);
|
||||
}
|
||||
}
|
||||
Kind::Loom => self.loom_taken(&mut s),
|
||||
Kind::Enchanting => {}
|
||||
}
|
||||
self.station = Some(s);
|
||||
@@ -991,6 +1026,9 @@ impl Game<'_> {
|
||||
if kind == Kind::Merchant && !right && self.merchant_click(local) {
|
||||
return true;
|
||||
}
|
||||
if kind == Kind::Loom && !right && self.loom_click(local) {
|
||||
return true;
|
||||
}
|
||||
if kind == Kind::Beacon && !right && self.beacon_click(local) {
|
||||
return true;
|
||||
}
|
||||
@@ -1065,6 +1103,7 @@ impl Game<'_> {
|
||||
}
|
||||
pub(super) fn station_scroll(&mut self, d: f32) {
|
||||
self.merchant_scroll(d);
|
||||
self.loom_scroll(d);
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
@@ -1084,6 +1123,11 @@ impl Game<'_> {
|
||||
.is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some())
|
||||
}
|
||||
pub(super) fn station_text(&mut self, text: Option<&str>, backspace: bool) {
|
||||
// The recipe book's search box takes scripted typing too.
|
||||
if self.recipe_search_focused() {
|
||||
self.recipe_text(text, backspace);
|
||||
return;
|
||||
}
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
@@ -1308,6 +1352,9 @@ impl Game<'_> {
|
||||
if kind == Kind::Cartography {
|
||||
self.draw_cartography(batch, ox, oy);
|
||||
}
|
||||
if kind == Kind::Loom {
|
||||
tooltip = self.draw_loom(batch, ox, oy, local);
|
||||
}
|
||||
let atlas = &self.res.atlas;
|
||||
let s = self.station.as_ref().expect("open station");
|
||||
let has_input = s.inputs.iter().any(Option::is_some);
|
||||
@@ -1598,7 +1645,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Merchant | Kind::Beacon | Kind::Cartography => {}
|
||||
Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {}
|
||||
Kind::Stonecutter => {
|
||||
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
|
||||
let active = display && s.recipes.len() > 12;
|
||||
@@ -1725,6 +1772,10 @@ impl Game<'_> {
|
||||
let e: &Enchantments = &self.res.stations.enchantments;
|
||||
let props = e.props(&stack.item);
|
||||
let mut rarity = props.map_or("common", |p| p.rarity.as_str());
|
||||
// The ominous banner's rarity component.
|
||||
if stack.data().is_some_and(|d| d.ominous_banner) {
|
||||
rarity = "uncommon";
|
||||
}
|
||||
if !stack.enchantments().is_empty() {
|
||||
rarity = match rarity {
|
||||
"common" | "uncommon" => "rare",
|
||||
@@ -1740,6 +1791,9 @@ impl Game<'_> {
|
||||
};
|
||||
let name = if let Some(n) = stack.custom_name() {
|
||||
n.to_owned()
|
||||
} else if stack.data().is_some_and(|d| d.ominous_banner) {
|
||||
e.translate("block.minecraft.ominous_banner")
|
||||
.map_or_else(|| "Ominous Banner".to_owned(), str::to_owned)
|
||||
} else if stack.data().and_then(|d| d.potion.as_ref()).is_some()
|
||||
|| stack.item.ends_with("potion")
|
||||
|| &*stack.item == "minecraft:tipped_arrow"
|
||||
@@ -1799,6 +1853,11 @@ impl Game<'_> {
|
||||
},
|
||||
));
|
||||
}
|
||||
// BannerPatternLayers.addToTooltip: up to six layer names.
|
||||
for layer in horizon_client::banner::layers(stack).iter().take(6) {
|
||||
let key = self.res.stations.banners.layer_key(layer);
|
||||
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
|
||||
}
|
||||
if let Some(info) = self.res.items.get(&stack.item)
|
||||
&& info.max_damage > 0
|
||||
&& stack.damage > 0
|
||||
@@ -1918,14 +1977,12 @@ impl Game<'_> {
|
||||
let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) else {
|
||||
return;
|
||||
};
|
||||
let stack = if slot == 200 {
|
||||
self.craft_result()
|
||||
} else {
|
||||
self.slot_mut(slot).clone()
|
||||
};
|
||||
let stack = self.slot_view(slot);
|
||||
if let Some(stack) = stack {
|
||||
let lines = self.stack_tooltip(&stack);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
} else if let Some(text) = self.crafter_tooltip(slot) {
|
||||
self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1);
|
||||
}
|
||||
}
|
||||
/// Potion items: `layer0` tinted with the potion colour under the bottle
|
||||
|
||||
@@ -13,6 +13,9 @@ pub(super) struct Stats {
|
||||
loaded: bool,
|
||||
/// Ticks until the phantom spawner runs again.
|
||||
phantom_tick: i32,
|
||||
/// Statistic changes (type, key, amount; `None` = reset) for the
|
||||
/// scoreboard criteria to follow.
|
||||
pub(super) events: Vec<(String, String, Option<i32>)>,
|
||||
}
|
||||
impl Stats {
|
||||
pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) {
|
||||
@@ -23,6 +26,8 @@ impl Stats {
|
||||
.entry(key.to_owned())
|
||||
.or_insert(0);
|
||||
*v = v.saturating_add(n);
|
||||
self.events
|
||||
.push((format!("minecraft:{ty}"), key.to_owned(), Some(n)));
|
||||
}
|
||||
pub(super) fn get(&self, ty: &str, key: &str) -> i32 {
|
||||
self.values
|
||||
@@ -35,6 +40,8 @@ impl Stats {
|
||||
if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) {
|
||||
m.insert(key.to_owned(), 0);
|
||||
}
|
||||
self.events
|
||||
.push((format!("minecraft:{ty}"), key.to_owned(), None));
|
||||
}
|
||||
pub(super) fn custom(&mut self, key: &str, n: i32) {
|
||||
self.add("custom", &format!("minecraft:{key}"), n);
|
||||
|
||||
@@ -11,6 +11,10 @@ impl Game<'_> {
|
||||
/// Block-entity contents on removal: shulker boxes keep theirs for the
|
||||
/// dropped box (`copy_components`), other containers spill them.
|
||||
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
|
||||
if let BlockEntity::Banner(banner) = entity {
|
||||
self.pending_banner.insert(pos, banner);
|
||||
return;
|
||||
}
|
||||
if is_shulker_box(block) {
|
||||
if let BlockEntity::Chest(items) = entity {
|
||||
let kept = items
|
||||
@@ -79,3 +83,310 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- chest menus: double chests, titles and shift-click ----
|
||||
|
||||
/// `Direction.getClockWise` for horizontal facings.
|
||||
fn clockwise(facing: &str) -> &'static str {
|
||||
match facing {
|
||||
"north" => "east",
|
||||
"east" => "south",
|
||||
"south" => "west",
|
||||
_ => "north",
|
||||
}
|
||||
}
|
||||
fn counter_clockwise(facing: &str) -> &'static str {
|
||||
match clockwise(facing) {
|
||||
"east" => "west",
|
||||
"south" => "north",
|
||||
"west" => "east",
|
||||
_ => "south",
|
||||
}
|
||||
}
|
||||
fn facing_step(facing: &str) -> (i32, i32) {
|
||||
match facing {
|
||||
"north" => (0, -1),
|
||||
"south" => (0, 1),
|
||||
"west" => (-1, 0),
|
||||
_ => (1, 0),
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The other half of the open double chest and whether the open one is
|
||||
/// the right half (`ChestBlock.getConnectedDirection`).
|
||||
fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> {
|
||||
let registry = self.res.assets.registry;
|
||||
let state = registry.state(self.world.block(key.0, key.1, key.2))?;
|
||||
if !matches!(
|
||||
state.name.as_str(),
|
||||
"minecraft:chest" | "minecraft:trapped_chest"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let kind = state.properties.get("type")?.as_str();
|
||||
if kind == "single" {
|
||||
return None;
|
||||
}
|
||||
let facing = state.properties.get("facing")?.as_str();
|
||||
let dir = if kind == "left" {
|
||||
clockwise(facing)
|
||||
} else {
|
||||
counter_clockwise(facing)
|
||||
};
|
||||
let (dx, dz) = facing_step(dir);
|
||||
let other = (key.0 + dx, key.1, key.2 + dz);
|
||||
let other_state = registry.state(self.world.block(other.0, other.1, other.2))?;
|
||||
let other_kind = other_state.properties.get("type")?.as_str();
|
||||
let paired = other_state.name == state.name
|
||||
&& other_kind != "single"
|
||||
&& other_kind != kind
|
||||
&& matches!(
|
||||
self.world.block_entities.get(&other),
|
||||
Some(BlockEntity::Chest(items)) if items.len() == 27
|
||||
);
|
||||
paired.then_some((other, kind == "right"))
|
||||
}
|
||||
/// The other half of a double chest at `key`, for neighbour updates.
|
||||
pub(super) fn chest_other_half(&self, key: (i32, i32, i32)) -> Option<(i32, i32, i32)> {
|
||||
self.chest_partner(key).map(|p| p.0)
|
||||
}
|
||||
/// The block entities of the open container in menu order, with their
|
||||
/// sizes: a double chest is its right half then its left half.
|
||||
pub(super) fn container_parts(&self) -> Vec<((i32, i32, i32), usize)> {
|
||||
let Some(key) = self.container else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(entity) = self.world.block_entities.get(&key) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let own = (key, entity.slots().len());
|
||||
match self.chest_partner(key) {
|
||||
Some((other, true)) => vec![own, (other, 27)],
|
||||
Some((other, false)) => vec![(other, 27), own],
|
||||
None => vec![own],
|
||||
}
|
||||
}
|
||||
/// The number of slots of the open container.
|
||||
pub(super) fn container_size(&self) -> usize {
|
||||
self.container_parts().iter().map(|p| p.1).sum()
|
||||
}
|
||||
/// Container slot `n` (menu slot `300 + n`).
|
||||
pub(super) fn container_slot_mut(&mut self, mut n: usize) -> &mut Option<ItemStack> {
|
||||
let mut target = None;
|
||||
for (pos, size) in self.container_parts() {
|
||||
if n < size {
|
||||
target = Some((pos, n));
|
||||
break;
|
||||
}
|
||||
n -= size;
|
||||
}
|
||||
match target.and_then(|(pos, i)| {
|
||||
self.world
|
||||
.block_entities
|
||||
.get_mut(&pos)
|
||||
.and_then(|e| e.slots_mut().get_mut(i))
|
||||
}) {
|
||||
Some(slot) => slot,
|
||||
None => &mut self.scratch_slot,
|
||||
}
|
||||
}
|
||||
pub(super) fn container_block_is_shulker(&self) -> bool {
|
||||
self.container_block()
|
||||
.as_deref()
|
||||
.is_some_and(is_shulker_box)
|
||||
}
|
||||
fn container_block(&self) -> Option<std::sync::Arc<str>> {
|
||||
let k = self.container?;
|
||||
Some(
|
||||
self.res
|
||||
.facts
|
||||
.get(self.world.block(k.0, k.1, k.2))
|
||||
.name
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
/// Rows of the open generic 9-wide container (`ChestMenu`), or None for
|
||||
/// the other menus (hoppers, dispensers, shulker boxes, furnaces...).
|
||||
pub(super) fn chest_rows(&self) -> Option<usize> {
|
||||
if !matches!(self.container_kind()?, BlockEntity::Chest(_)) {
|
||||
return None;
|
||||
}
|
||||
let generic = match self.container_block().as_deref() {
|
||||
Some(
|
||||
"minecraft:chest"
|
||||
| "minecraft:trapped_chest"
|
||||
| "minecraft:barrel"
|
||||
| "minecraft:ender_chest",
|
||||
) => true,
|
||||
_ => self.open_cart_kind() == Some(super::minecarts::CartKind::Chest),
|
||||
};
|
||||
generic.then(|| self.container_size() / 9)
|
||||
}
|
||||
/// The title of the open chest-like menu.
|
||||
fn chest_title(&self, rows: usize) -> String {
|
||||
let (key, fallback) = match self.container_block().as_deref() {
|
||||
Some("minecraft:barrel") => ("container.barrel", "Barrel"),
|
||||
Some("minecraft:ender_chest") => ("container.enderchest", "Ender Chest"),
|
||||
_ if self.open_cart_kind().is_some() => {
|
||||
("entity.minecraft.chest_minecart", "Minecart with Chest")
|
||||
}
|
||||
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
|
||||
_ => ("container.chest", "Chest"),
|
||||
};
|
||||
self.translate(key, fallback)
|
||||
}
|
||||
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
|
||||
/// container rows, the title and the inventory label.
|
||||
pub(super) fn draw_chest_screen(
|
||||
&self,
|
||||
batch: &mut horizon_client::hud::HudBatch,
|
||||
ox: f32,
|
||||
oy: f32,
|
||||
) {
|
||||
use horizon_client::hud::rgba;
|
||||
let atlas = &self.res.atlas;
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
if self
|
||||
.container_block()
|
||||
.as_deref()
|
||||
.is_some_and(is_shulker_box)
|
||||
{
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
"gui/container/shulker_box",
|
||||
[ox, oy, 176.0, 167.0],
|
||||
256.0,
|
||||
256.0,
|
||||
);
|
||||
let title = self.translate("container.shulkerBox", "Shulker Box");
|
||||
batch.text(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
|
||||
batch.text(atlas, "Inventory", ox + 8.0, oy + 73.0, grey, false);
|
||||
return;
|
||||
}
|
||||
let rows = self.chest_rows().unwrap_or(3);
|
||||
let top = rows as f32 * 18.0 + 17.0;
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
"gui/container/generic_54",
|
||||
[ox, oy, 176.0, top],
|
||||
256.0,
|
||||
256.0,
|
||||
);
|
||||
// The player half of the texture starts at v = 126.
|
||||
if let Some(mut r) = atlas.sprites.get("gui/container/generic_54").copied() {
|
||||
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
|
||||
r.v0 += 126.0 * dv;
|
||||
r.v1 = r.v0 + 96.0 * dv;
|
||||
r.u1 = r.u0 + 176.0 * du;
|
||||
batch.rect_uv(ox, oy + top, 176.0, 96.0, r, u32::MAX);
|
||||
}
|
||||
batch.text(
|
||||
atlas,
|
||||
&self.chest_title(rows),
|
||||
ox + 8.0,
|
||||
oy + 6.0,
|
||||
grey,
|
||||
false,
|
||||
);
|
||||
batch.text(
|
||||
atlas,
|
||||
"Inventory",
|
||||
ox + 8.0,
|
||||
oy + 114.0 + rows as f32 * 18.0 - 94.0,
|
||||
grey,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace
|
||||
/// menu for a shift-click on `slot`; false when the menu has none.
|
||||
pub(super) fn container_quick_move(&mut self, slot: usize) -> bool {
|
||||
let size = self.container_size();
|
||||
let furnace = match self.container_kind() {
|
||||
Some(BlockEntity::Chest(_)) => None,
|
||||
Some(BlockEntity::Furnace(f)) => Some(f.kind),
|
||||
_ => return false,
|
||||
};
|
||||
if slot >= 300 + size.max(3) {
|
||||
return false;
|
||||
}
|
||||
let Some(mut stack) = self.slot_mut(slot).take() else {
|
||||
return true;
|
||||
};
|
||||
let player: Vec<usize> = (9..36).chain(0..9).collect();
|
||||
let hotbar_or_main = |slot: usize| -> Vec<usize> {
|
||||
if slot < 9 {
|
||||
(9..36).collect()
|
||||
} else {
|
||||
(0..9).collect()
|
||||
}
|
||||
};
|
||||
match furnace {
|
||||
None => {
|
||||
if slot >= 300 {
|
||||
self.move_to(&mut stack, &player, true);
|
||||
} else {
|
||||
let targets: Vec<usize> = (300..300 + size).collect();
|
||||
self.move_to(&mut stack, &targets, false);
|
||||
}
|
||||
}
|
||||
Some(kind) => {
|
||||
// AbstractFurnaceMenu.quickMoveStack.
|
||||
if slot >= 300 {
|
||||
self.move_to(&mut stack, &player, slot == 302);
|
||||
} else {
|
||||
let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some();
|
||||
let fuel = self
|
||||
.res
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.is_some_and(|i| i.fuel.is_some());
|
||||
let moved = if smeltable {
|
||||
self.move_to(&mut stack, &[300], false)
|
||||
} else if fuel {
|
||||
self.move_to(&mut stack, &[301], false)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !moved && !smeltable && !fuel {
|
||||
let other = hotbar_or_main(slot);
|
||||
self.move_to(&mut stack, &other, false);
|
||||
}
|
||||
if let Some(BlockEntity::Furnace(f)) = self
|
||||
.container
|
||||
.and_then(|k| self.world.block_entities.get_mut(&k))
|
||||
{
|
||||
f.cooking_timer = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if stack.count > 0 {
|
||||
*self.slot_mut(slot) = Some(stack);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn double_chest_halves_connect_around_the_facing() {
|
||||
// A left half facing north connects east, a right half west.
|
||||
assert_eq!(facing_step(clockwise("north")), (1, 0));
|
||||
assert_eq!(facing_step(counter_clockwise("north")), (-1, 0));
|
||||
assert_eq!(facing_step(clockwise("south")), (-1, 0));
|
||||
assert_eq!(facing_step(counter_clockwise("east")), (0, -1));
|
||||
}
|
||||
#[test]
|
||||
fn shulker_boxes_are_recognised_by_name() {
|
||||
assert!(is_shulker_box("minecraft:red_shulker_box"));
|
||||
assert!(is_shulker_box("minecraft:shulker_box"));
|
||||
assert!(!is_shulker_box("minecraft:chest"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The subtitle overlay in the game (`Hud` -> `SubtitleOverlay`): sounds the
|
||||
//! audio engine plays feed it, the HUD draws it.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
hud::HudBatch,
|
||||
subtitles::{self, SubtitleOverlay},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SubtitleState {
|
||||
overlay: SubtitleOverlay,
|
||||
listening: bool,
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// Feed the sounds played since the last tick to the overlay while the
|
||||
/// `showSubtitles` option is on.
|
||||
pub(super) fn tick_subtitles(&mut self) {
|
||||
let on = self.settings.show_subtitles;
|
||||
self.audio.record_heard = on;
|
||||
if !on {
|
||||
if self.subtitles.listening {
|
||||
self.subtitles.listening = false;
|
||||
self.subtitles.overlay.clear();
|
||||
}
|
||||
self.audio.take_heard();
|
||||
return;
|
||||
}
|
||||
self.subtitles.listening = true;
|
||||
let now = subtitles::now_ms();
|
||||
let listener = self.audio.listener;
|
||||
for heard in self.audio.take_heard() {
|
||||
self.subtitles.overlay.on_play(&heard, listener, now);
|
||||
}
|
||||
self.subtitles
|
||||
.overlay
|
||||
.purge(f64::from(self.settings.notification_display_time), now);
|
||||
}
|
||||
pub(super) fn draw_subtitles(&self, batch: &mut HudBatch) {
|
||||
if !self.settings.show_subtitles {
|
||||
return;
|
||||
}
|
||||
self.subtitles.overlay.draw(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
self.audio.listener,
|
||||
self.yaw,
|
||||
self.pitch,
|
||||
f64::from(self.settings.notification_display_time),
|
||||
subtitles::now_ms(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,9 @@ impl Game<'_> {
|
||||
/// `new PrimedTnt(level, x + 0.5, y, z + 0.5, owner)`; `short` applies
|
||||
/// `wasExploded`'s random short fuse. Plays `entity.tnt.primed` for primes.
|
||||
pub(super) fn spawn_primed_tnt(&mut self, pos: BlockPos, short: bool) {
|
||||
// PrimedTnt: the fuse is lit.
|
||||
let who = self.sculk_actor();
|
||||
self.post_block_game_event("minecraft:prime_fuse", [pos.x, pos.y, pos.z], who, None);
|
||||
let r = &mut self.world.random;
|
||||
let rot = r.next_double() * f64::from(std::f32::consts::TAU);
|
||||
let position = Vec3::new(
|
||||
|
||||
@@ -148,7 +148,13 @@ impl Game<'_> {
|
||||
}));
|
||||
}
|
||||
let m = &self.mobs[index];
|
||||
let trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
|
||||
let mut trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
|
||||
// Villager.updateSpecialPrices: reputation and Hero of the Village.
|
||||
if species == Species::Villager {
|
||||
let reputation = self.villager_reputation(m.id);
|
||||
merchant::update_special_prices(&mut trade.offers, reputation, self.hero_amplifier());
|
||||
}
|
||||
let m = &self.mobs[index];
|
||||
if trade.offers.is_empty() {
|
||||
let mut events = Vec::new();
|
||||
villager::set_unhappy(&mut self.mobs[index], &mut events);
|
||||
@@ -190,6 +196,10 @@ impl Game<'_> {
|
||||
let trade = m.extra.trade.get_or_insert_default();
|
||||
trade.xp = state.xp;
|
||||
trade.offers = state.offers.clone();
|
||||
// setTradingPlayer(null) resets the special prices.
|
||||
for offer in &mut trade.offers {
|
||||
offer.special_price_diff = 0;
|
||||
}
|
||||
}
|
||||
/// Opens a merchant menu for a villager (or a generated one for tests).
|
||||
pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) {
|
||||
@@ -244,6 +254,16 @@ impl Game<'_> {
|
||||
.map(|p| [p.position.x, p.position.y + 0.5, p.position.z]);
|
||||
self.audio
|
||||
.play("minecraft:entity.villager.yes", at, 1.0, 1.0);
|
||||
// Villager.notifyTrade: the villager remembers the trade.
|
||||
let villager = s
|
||||
.merchant
|
||||
.as_ref()
|
||||
.filter(|m| m.progress())
|
||||
.and_then(|m| m.mob);
|
||||
if let Some(mob) = villager {
|
||||
self.villager_traded(mob);
|
||||
}
|
||||
let Some(m) = s.merchant.as_mut() else { return };
|
||||
if level_up {
|
||||
let (profession, variant, level) =
|
||||
(m.profession.clone(), m.variant.clone(), m.level + 1);
|
||||
@@ -254,6 +274,14 @@ impl Game<'_> {
|
||||
}
|
||||
pop += 5;
|
||||
}
|
||||
// The prices follow the villager's new reputation.
|
||||
if let Some(mob) = villager {
|
||||
let reputation = self.villager_reputation(mob);
|
||||
let hero = self.hero_amplifier();
|
||||
if let Some(m) = s.merchant.as_mut() {
|
||||
merchant::update_special_prices(&mut m.offers, reputation, hero);
|
||||
}
|
||||
}
|
||||
if offer.reward_exp
|
||||
&& let Some(at) = at
|
||||
{
|
||||
|
||||
@@ -177,6 +177,7 @@ impl Game<'_> {
|
||||
returning: 0,
|
||||
creative_only: self.creative,
|
||||
});
|
||||
self.player_projectile_shot();
|
||||
self.audio
|
||||
.play("minecraft:item.trident.throw", at, 1.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
//! What villagers do with each other and with the player: gossip and
|
||||
//! reputation, sharing food and wares, picking up dropped items, making
|
||||
//! babies, calling iron golems and the prices they ask.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
gossip::{self, GossipType},
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Species, spawning, villager},
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn block_of(p: Vec3) -> [i32; 3] {
|
||||
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
|
||||
}
|
||||
/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`: what a golem will not land on.
|
||||
fn golem_floor_ok(name: &str) -> bool {
|
||||
!matches!(
|
||||
name,
|
||||
"minecraft:cobweb"
|
||||
| "minecraft:cactus"
|
||||
| "minecraft:glass_pane"
|
||||
| "minecraft:conduit"
|
||||
| "minecraft:ice"
|
||||
| "minecraft:tnt"
|
||||
| "minecraft:glowstone"
|
||||
| "minecraft:beacon"
|
||||
| "minecraft:sea_lantern"
|
||||
| "minecraft:frosted_ice"
|
||||
| "minecraft:tinted_glass"
|
||||
| "minecraft:glass"
|
||||
) && !name.ends_with("_stained_glass_pane")
|
||||
&& !name.ends_with("_stained_glass")
|
||||
&& !name.ends_with("leaves")
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn villager_index(&self, id: u32) -> Option<usize> {
|
||||
self.mobs
|
||||
.iter()
|
||||
.position(|m| m.id == id && m.species() == Species::Villager)
|
||||
}
|
||||
fn item_max_stack(&self, item: &str) -> u32 {
|
||||
self.res.items.get(item).map_or(64, |i| i.max_stack)
|
||||
}
|
||||
/// `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) {
|
||||
let at = [from.x, eye - 0.3, from.z];
|
||||
let d = Vec3::new(to.x - from.x, to.y - from.y, to.z - from.z).normalize();
|
||||
self.spawn_item(stack, at, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10);
|
||||
}
|
||||
|
||||
/// `TradeWithVillager.tick` for one pair: gossip (at most once in 1200
|
||||
/// ticks for both), then surplus food and wanted wares tossed over.
|
||||
pub(super) fn villager_meet(&mut self, a: u32, b: u32) {
|
||||
let (Some(ia), Some(ib)) = (self.villager_index(a), self.villager_index(b)) else {
|
||||
return;
|
||||
};
|
||||
let now = self.world.game_time;
|
||||
let items = &self.res.items;
|
||||
let max = |item: &str| items.get(item).map_or(64, |i| i.max_stack);
|
||||
// Villager.gossip: both must be past their cool-down.
|
||||
let ready = {
|
||||
let ea = villager::ext(&self.mobs[ia]);
|
||||
let eb = villager::ext(&self.mobs[ib]);
|
||||
ea.is_none_or(|e| e.can_gossip(now)) && eb.is_none_or(|e| e.can_gossip(now))
|
||||
};
|
||||
let mut golem = false;
|
||||
if ready {
|
||||
let source = villager::ext(&self.mobs[ib]).cloned().unwrap_or_default();
|
||||
let me = &mut self.mobs[ia];
|
||||
let mut random = me.random.clone();
|
||||
let e = villager::ext_mut(me);
|
||||
e.gossips.transfer_from(&source.gossips, &mut random, 10);
|
||||
e.last_gossip_time = now;
|
||||
me.random = random;
|
||||
villager::ext_mut(&mut self.mobs[ib]).last_gossip_time = now;
|
||||
golem = true;
|
||||
}
|
||||
// Surplus food goes to a hungry neighbour (farmers hand it to anyone).
|
||||
let farmer = villager::is_farmer(&self.mobs[ia]);
|
||||
let (from, eye, to) = (
|
||||
self.mobs[ia].position,
|
||||
self.mobs[ia].eye_y(),
|
||||
self.mobs[ib].position,
|
||||
);
|
||||
let wants_more = villager::ext(&self.mobs[ib]).is_none_or(|e| e.wants_more_food());
|
||||
let excess = villager::ext(&self.mobs[ia]).is_some_and(|e| e.has_excess_food());
|
||||
let mut thrown = Vec::new();
|
||||
if excess
|
||||
&& (farmer || wants_more)
|
||||
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
|
||||
.take_half_stack(|s| villager::food_points(&s.item) > 0, max)
|
||||
{
|
||||
thrown.push(s);
|
||||
}
|
||||
// A farmer's wheat.
|
||||
if farmer
|
||||
&& villager::ext(&self.mobs[ia]).is_some_and(|e| e.count_item("minecraft:wheat") > 32)
|
||||
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
|
||||
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
|
||||
{
|
||||
thrown.push(s);
|
||||
}
|
||||
// Wares the neighbour's profession asks for and ours does not.
|
||||
let theirs = villager::requested_items(&self.mobs[ib]);
|
||||
let mine = villager::requested_items(&self.mobs[ia]);
|
||||
let wanted: Vec<&str> = theirs
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|i| !mine.contains(i))
|
||||
.collect();
|
||||
if !wanted.is_empty()
|
||||
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
|
||||
.take_half_stack(|s| wanted.contains(&&*s.item), max)
|
||||
{
|
||||
thrown.push(s);
|
||||
}
|
||||
for stack in thrown {
|
||||
self.villager_throw(from, eye, to, stack);
|
||||
}
|
||||
if golem {
|
||||
self.villager_golem_check(a, 5);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Villager.spawnGolemIfNeeded`: when enough villagers nearby that
|
||||
/// slept recently and saw no golem agree, an iron golem appears.
|
||||
pub(super) fn villager_golem_check(&mut self, id: u32, needed: usize) {
|
||||
let Some(i) = self.villager_index(id) else {
|
||||
return;
|
||||
};
|
||||
let now = self.world.game_time;
|
||||
if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) {
|
||||
return;
|
||||
}
|
||||
let at = self.mobs[i].position;
|
||||
let nearby: Vec<usize> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| {
|
||||
m.species() == Species::Villager
|
||||
&& m.alive()
|
||||
&& (m.position.x - at.x).abs() <= 10.0
|
||||
&& (m.position.y - at.y).abs() <= 10.0
|
||||
&& (m.position.z - at.z).abs() <= 10.0
|
||||
})
|
||||
.map(|(j, _)| j)
|
||||
.collect();
|
||||
let wanting = nearby
|
||||
.iter()
|
||||
.filter(|j| villager::ext(&self.mobs[**j]).is_some_and(|e| e.wants_golem(now)))
|
||||
.take(5)
|
||||
.count();
|
||||
if wanting < needed {
|
||||
return;
|
||||
}
|
||||
if self.try_spawn_iron_golem(block_of(at)) {
|
||||
for j in nearby {
|
||||
villager::ext_mut(&mut self.mobs[j]).golem_until = now + 599;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up
|
||||
/// and down, LEGACY_IRON_GOLEM)`.
|
||||
fn try_spawn_iron_golem(&mut self, start: [i32; 3]) -> bool {
|
||||
for _ in 0..10 {
|
||||
let r = &mut self.world.random;
|
||||
let dx = r.next_int_bound(17).unwrap_or(8) - 8;
|
||||
let dz = r.next_int_bound(17).unwrap_or(8) - 8;
|
||||
let (x, z) = (start[0] + dx, start[2] + dz);
|
||||
let mut y = start[1] + 6;
|
||||
let mut above = self.world.block(x, y, z);
|
||||
let mut found = None;
|
||||
for _ in 0..=12 {
|
||||
y -= 1;
|
||||
let here = self.world.block(x, y, z);
|
||||
let f = self.res.facts.get(here);
|
||||
let above_f = self.res.facts.get(above);
|
||||
let air_or_liquid = self.res.facts.is_air(above)
|
||||
|| above_f.fluid != horizon_client::blocks::Fluid::None;
|
||||
let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID
|
||||
!= 0
|
||||
|| f.name.as_ref() == "minecraft:powder_snow";
|
||||
if golem_floor_ok(&f.name) && air_or_liquid && solid {
|
||||
found = Some(y + 1);
|
||||
break;
|
||||
}
|
||||
above = here;
|
||||
}
|
||||
let Some(y) = found else { continue };
|
||||
// IronGolem.checkSpawnRules: a floor and three free blocks.
|
||||
let free = |g: &Self, yy: i32| {
|
||||
g.res.mob_data.state(g.world.block(x, yy, z)).flags
|
||||
& horizon_client::mobs::data::VALID_EMPTY_SPAWN
|
||||
!= 0
|
||||
};
|
||||
if !(0..4).all(|k| free(self, y + k)) {
|
||||
continue;
|
||||
}
|
||||
let at = [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5];
|
||||
if let Some(id) = self.spawn_mob_for("minecraft:iron_golem", at, false, true)
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
|
||||
{
|
||||
let sound = m.kind.sounds[0];
|
||||
if !sound.is_empty() {
|
||||
let at = m.center();
|
||||
self.audio
|
||||
.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48
|
||||
/// blocks is taken for the child, who is a baby villager of one of
|
||||
/// three villager types.
|
||||
pub(super) fn villager_birth(&mut self, parent: u32, partner: u32) {
|
||||
let (Some(ia), Some(ib)) = (self.villager_index(parent), self.villager_index(partner))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
villager::ext_mut(&mut self.mobs[ia]).eat_and_digest();
|
||||
villager::ext_mut(&mut self.mobs[ib]).eat_and_digest();
|
||||
let from = self.mobs[ia].position;
|
||||
let angry = |g: &mut Self| {
|
||||
for i in [ia, ib] {
|
||||
let p = g.mobs[i].position;
|
||||
g.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
|
||||
}
|
||||
};
|
||||
let Some(bed) = self.take_vacant_bed(block_of(from)) else {
|
||||
angry(self);
|
||||
return;
|
||||
};
|
||||
// Villager.getBreedOffspring: half the biome's type, a quarter each parent's.
|
||||
let roll = self.mobs[ia].random.next_double();
|
||||
let kind_of = |m: &Mob| m.extra.variant;
|
||||
let facts = self.biome_facts(
|
||||
from.x.floor() as i32,
|
||||
from.y.floor() as i32,
|
||||
from.z.floor() as i32,
|
||||
);
|
||||
let variant = if roll < 0.5 {
|
||||
spawning::villager_type(&facts)
|
||||
} else if roll < 0.75 {
|
||||
kind_of(&self.mobs[ia])
|
||||
} else {
|
||||
kind_of(&self.mobs[ib])
|
||||
};
|
||||
let Some(id) =
|
||||
self.spawn_mob_for("minecraft:villager", [from.x, from.y, from.z], true, true)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.mobs[ia].extra.age = 6000;
|
||||
self.mobs[ib].extra.age = 6000;
|
||||
if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
child.extra.variant = variant;
|
||||
child.extra.variant2 = villager::NONE;
|
||||
child.extra.age = -24000;
|
||||
child.extra.bed = Some(bed);
|
||||
}
|
||||
self.particles_at("heart", [from.x, from.y + 1.8, from.z]);
|
||||
}
|
||||
/// `PoiManager.take(HOME, ..., 48)`: the nearest unclaimed bed head.
|
||||
fn take_vacant_bed(&self, from: [i32; 3]) -> Option<[i32; 3]> {
|
||||
let claimed: Vec<[i32; 3]> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| m.species() == Species::Villager)
|
||||
.filter_map(|m| m.extra.bed)
|
||||
.collect();
|
||||
let mut known: HashMap<u32, bool> = HashMap::new();
|
||||
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 state = self.world.block(x, y, z);
|
||||
if self.res.facts.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
let free_head = *known.entry(state.0).or_insert_with(|| {
|
||||
self.res.facts.get(state).name.ends_with("_bed")
|
||||
&& self.res.assets.registry.state(state).is_some_and(|s| {
|
||||
s.properties.get("part").map(String::as_str) == Some("head")
|
||||
&& s.properties.get("occupied").map(String::as_str)
|
||||
!= Some("true")
|
||||
})
|
||||
});
|
||||
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
|
||||
if free_head
|
||||
&& d <= 48 * 48
|
||||
&& !claimed.contains(&[x, y, z])
|
||||
&& best.is_none_or(|(b, _)| d < b)
|
||||
{
|
||||
best = Some((d, [x, y, z]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, p)| p)
|
||||
}
|
||||
fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) {
|
||||
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
|
||||
let options = horizon_client::particles::ParticleOptions::simple(ty);
|
||||
self.particles.add(&options, at, [0.0; 3]);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Mob.aiStep` item pickup for villagers (`InventoryCarrier`): food,
|
||||
/// seeds and what their profession wants, from within a block.
|
||||
pub(super) fn villager_pickups(&mut self) {
|
||||
if self.dropped.is_empty() || !self.ui.rules.bool("mob_griefing") {
|
||||
return;
|
||||
}
|
||||
let picks_up = self
|
||||
.res
|
||||
.items
|
||||
.item_tags
|
||||
.get("minecraft:villager_picks_up")
|
||||
.cloned();
|
||||
for i in 0..self.mobs.len() {
|
||||
let m = &self.mobs[i];
|
||||
if m.species() != Species::Villager || !m.alive() {
|
||||
continue;
|
||||
}
|
||||
let (pos, half) = (m.position, f64::from(m.width()) / 2.0 + 1.0);
|
||||
let top = f64::from(m.height());
|
||||
let requested = villager::requested_items(m);
|
||||
let mut j = 0;
|
||||
while j < self.dropped.len() {
|
||||
let e = &self.dropped[j];
|
||||
let near = (e.position.x - pos.x).abs() <= half
|
||||
&& (e.position.z - pos.z).abs() <= half
|
||||
&& e.position.y >= pos.y - 0.25
|
||||
&& e.position.y <= pos.y + top;
|
||||
let item = e.stack.item.clone();
|
||||
let wants = villager::food_points(&item) > 0
|
||||
|| picks_up.as_ref().is_some_and(|t| t.contains(&*item))
|
||||
|| requested.contains(&&*item);
|
||||
if !near || e.pickup_delay > 0 || !wants {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let max = self.item_max_stack(&item);
|
||||
let stack = self.dropped[j].stack.clone();
|
||||
if !villager::ext_mut(&mut self.mobs[i]).can_add(&stack, max) {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max);
|
||||
match rest {
|
||||
None => {
|
||||
self.dropped.remove(j);
|
||||
}
|
||||
Some(rest) => {
|
||||
self.dropped[j].stack.count = rest.count;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Villager.setLastHurtByMob` and `ServerLevel.onReputationEvent`: a hit
|
||||
/// from the player counts against it with the villager that was hit.
|
||||
pub(super) fn villager_reputation_tick(&mut self) {
|
||||
let Some(uuid) = self.level.player_uuid else {
|
||||
return;
|
||||
};
|
||||
let mut angry = Vec::new();
|
||||
for m in &mut self.mobs {
|
||||
if m.species() != Species::Villager
|
||||
|| m.ai.last_hurt_by != Some(horizon_client::mobs::Who::Player)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let time = m.ai.last_hurt_by_time;
|
||||
let alive = m.alive();
|
||||
let at = m.position;
|
||||
let e = villager::ext_mut(m);
|
||||
if e.hurt_seen != time {
|
||||
e.hurt_seen = time;
|
||||
e.gossips.add(
|
||||
uuid,
|
||||
GossipType::MinorNegative,
|
||||
gossip::REPUTATION_CHANGE_PER_EVENT,
|
||||
);
|
||||
if alive {
|
||||
angry.push(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
for at in angry {
|
||||
self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]);
|
||||
}
|
||||
}
|
||||
/// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a
|
||||
/// player kill one remember it as a major wrong.
|
||||
pub(super) fn villager_murdered(&mut self, victim: &Mob, by_player: bool) {
|
||||
if victim.species() != Species::Villager || !by_player {
|
||||
return;
|
||||
}
|
||||
let Some(uuid) = self.level.player_uuid else {
|
||||
return;
|
||||
};
|
||||
let eye = Vec3::new(victim.position.x, victim.eye_y(), victim.position.z);
|
||||
let witnesses: Vec<usize> = {
|
||||
let w = self.mob_world_base(&[]);
|
||||
self.mobs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| {
|
||||
m.id != victim.id
|
||||
&& m.species() == Species::Villager
|
||||
&& m.alive()
|
||||
&& (m.position.x - victim.position.x).abs() <= 16.0
|
||||
&& (m.position.y - victim.position.y).abs() <= 16.0
|
||||
&& (m.position.z - victim.position.z).abs() <= 16.0
|
||||
&& w.line_of_sight(eye, Vec3::new(m.position.x, m.eye_y(), m.position.z))
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect()
|
||||
};
|
||||
for i in witnesses {
|
||||
villager::ext_mut(&mut self.mobs[i]).gossips.add(
|
||||
uuid,
|
||||
GossipType::MajorNegative,
|
||||
gossip::REPUTATION_CHANGE_PER_EVENT,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `ReputationEventType.TRADE`: each trade earns a little trust.
|
||||
pub(super) fn villager_traded(&mut self, id: u32) {
|
||||
let Some(uuid) = self.level.player_uuid else {
|
||||
return;
|
||||
};
|
||||
let Some(i) = self.villager_index(id) else {
|
||||
return;
|
||||
};
|
||||
villager::ext_mut(&mut self.mobs[i]).gossips.add(
|
||||
uuid,
|
||||
GossipType::Trading,
|
||||
gossip::REPUTATION_CHANGE_PER_TRADE,
|
||||
);
|
||||
let p = self.mobs[i].position;
|
||||
self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]);
|
||||
}
|
||||
/// `Villager.getPlayerReputation` of the local player.
|
||||
pub(super) fn villager_reputation(&self, id: u32) -> i32 {
|
||||
let Some(uuid) = self.level.player_uuid else {
|
||||
return 0;
|
||||
};
|
||||
self.villager_index(id)
|
||||
.and_then(|i| villager::ext(&self.mobs[i]))
|
||||
.map_or(0, |e| e.gossips.reputation(uuid))
|
||||
}
|
||||
/// The Hero of the Village amplifier of the player, if any.
|
||||
pub(super) fn hero_amplifier(&self) -> Option<i32> {
|
||||
self.potions.effects.amplifier("hero_of_the_village")
|
||||
}
|
||||
}
|
||||
@@ -75,9 +75,9 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
/// The wither boss bars (purple, below the dragon's), within range.
|
||||
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) {
|
||||
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
return y;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
for m in self
|
||||
@@ -117,6 +117,7 @@ impl Game<'_> {
|
||||
);
|
||||
y += 19.0;
|
||||
}
|
||||
y
|
||||
}
|
||||
pub(super) fn wither_near(&self) -> bool {
|
||||
self.player.as_ref().is_some_and(|p| {
|
||||
|
||||
@@ -77,6 +77,9 @@ pub struct Frame<'a> {
|
||||
pub screen: &'a [crate::screen_effects::ScreenQuad],
|
||||
pub game_time: f32,
|
||||
pub ticks: u64,
|
||||
/// The darkness effect on the lightmap: the brightness it takes off the
|
||||
/// gamma option and the pulsing scale subtracted from the light.
|
||||
pub darkness: (f32, f32),
|
||||
}
|
||||
pub struct Renderer {
|
||||
instance: wgpu::Instance,
|
||||
@@ -1186,7 +1189,11 @@ impl Renderer {
|
||||
}
|
||||
};
|
||||
self.animate(frame.ticks);
|
||||
self.update_lightmap(&frame.sky, 0.0, self.gamma);
|
||||
self.update_lightmap(
|
||||
&frame.sky,
|
||||
frame.darkness.1,
|
||||
(self.gamma - frame.darkness.0).max(0.0),
|
||||
);
|
||||
let view_proj = self.view_projection(frame);
|
||||
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
|
||||
let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians());
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Villager gossip (`GossipContainer` and `GossipType`): what a villager
|
||||
//! remembers about each player, how it fades by the day, how it spreads from
|
||||
//! villager to villager and the reputation it adds up to.
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// `ReputationEventType` amounts.
|
||||
pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25;
|
||||
pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20;
|
||||
pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2;
|
||||
/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten.
|
||||
const DISCARD_THRESHOLD: i32 = 2;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum GossipType {
|
||||
MajorNegative,
|
||||
MinorNegative,
|
||||
MinorPositive,
|
||||
MajorPositive,
|
||||
Trading,
|
||||
}
|
||||
impl GossipType {
|
||||
pub const ALL: [Self; 5] = [
|
||||
Self::MajorNegative,
|
||||
Self::MinorNegative,
|
||||
Self::MinorPositive,
|
||||
Self::MajorPositive,
|
||||
Self::Trading,
|
||||
];
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::MajorNegative => "major_negative",
|
||||
Self::MinorNegative => "minor_negative",
|
||||
Self::MinorPositive => "minor_positive",
|
||||
Self::MajorPositive => "major_positive",
|
||||
Self::Trading => "trading",
|
||||
}
|
||||
}
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|t| t.id() == id)
|
||||
}
|
||||
fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
pub fn weight(self) -> i32 {
|
||||
match self {
|
||||
Self::MajorNegative => -5,
|
||||
Self::MinorNegative => -1,
|
||||
Self::MinorPositive => 1,
|
||||
Self::MajorPositive => 5,
|
||||
Self::Trading => 1,
|
||||
}
|
||||
}
|
||||
pub fn max(self) -> i32 {
|
||||
match self {
|
||||
Self::MajorNegative => 100,
|
||||
Self::MinorNegative => 200,
|
||||
Self::MinorPositive | Self::Trading => 25,
|
||||
Self::MajorPositive => 20,
|
||||
}
|
||||
}
|
||||
pub fn decay_per_day(self) -> i32 {
|
||||
match self {
|
||||
Self::MajorNegative => 10,
|
||||
Self::MinorNegative => 20,
|
||||
Self::MinorPositive => 1,
|
||||
Self::MajorPositive => 0,
|
||||
Self::Trading => 2,
|
||||
}
|
||||
}
|
||||
pub fn decay_per_transfer(self) -> i32 {
|
||||
match self {
|
||||
Self::MajorNegative => 10,
|
||||
Self::MinorNegative => 20,
|
||||
Self::MinorPositive => 5,
|
||||
Self::MajorPositive | Self::Trading => 20,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A UUID as four ints.
|
||||
pub type Target = [i32; 4];
|
||||
|
||||
/// One gossip entry (`GossipContainer.GossipEntry`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Entry {
|
||||
target: Target,
|
||||
kind: GossipType,
|
||||
value: i32,
|
||||
}
|
||||
impl Entry {
|
||||
fn weighted(self) -> i32 {
|
||||
self.value * self.kind.weight()
|
||||
}
|
||||
}
|
||||
|
||||
/// `GossipContainer`: per target, the value of each gossip type (0: none).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Gossips {
|
||||
map: BTreeMap<Target, [i32; 5]>,
|
||||
}
|
||||
impl Gossips {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.map.clear();
|
||||
}
|
||||
pub fn get(&self, target: Target, kind: GossipType) -> i32 {
|
||||
self.map.get(&target).map_or(0, |e| e[kind.index()])
|
||||
}
|
||||
/// `getReputation`: the weighted sum of every type for a target.
|
||||
pub fn reputation(&self, target: Target) -> i32 {
|
||||
self.map.get(&target).map_or(0, |e| {
|
||||
GossipType::ALL
|
||||
.into_iter()
|
||||
.map(|t| e[t.index()] * t.weight())
|
||||
.sum()
|
||||
})
|
||||
}
|
||||
/// How many targets have a gossip of `kind` whose weighted value passes `test`.
|
||||
pub fn count_for_type(&self, kind: GossipType, test: impl Fn(f64) -> bool) -> usize {
|
||||
self.map
|
||||
.values()
|
||||
.filter(|e| test(f64::from(e[kind.index()] * kind.weight())))
|
||||
.count()
|
||||
}
|
||||
/// `add`: sums up to the type's maximum and forgets values below 2.
|
||||
pub fn add(&mut self, target: Target, kind: GossipType, amount: i32) {
|
||||
let entries = self.map.entry(target).or_insert([0; 5]);
|
||||
let old = entries[kind.index()];
|
||||
entries[kind.index()] = if old == 0 {
|
||||
amount
|
||||
} else {
|
||||
let sum = old + amount;
|
||||
if sum > kind.max() {
|
||||
kind.max().max(old)
|
||||
} else {
|
||||
sum
|
||||
}
|
||||
};
|
||||
let value = entries[kind.index()];
|
||||
if value > kind.max() {
|
||||
entries[kind.index()] = kind.max();
|
||||
}
|
||||
if value < DISCARD_THRESHOLD {
|
||||
entries[kind.index()] = 0;
|
||||
}
|
||||
if entries.iter().all(|v| *v == 0) {
|
||||
self.map.remove(&target);
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, target: Target, kind: GossipType) {
|
||||
if let Some(e) = self.map.get_mut(&target) {
|
||||
e[kind.index()] = 0;
|
||||
if e.iter().all(|v| *v == 0) {
|
||||
self.map.remove(&target);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `decay` (once per day): every type loses its daily amount.
|
||||
pub fn decay(&mut self) {
|
||||
self.map.retain(|_, e| {
|
||||
for kind in GossipType::ALL {
|
||||
let v = e[kind.index()];
|
||||
if v == 0 {
|
||||
continue;
|
||||
}
|
||||
let next = v - kind.decay_per_day();
|
||||
e[kind.index()] = if next < DISCARD_THRESHOLD { 0 } else { next };
|
||||
}
|
||||
e.iter().any(|v| *v != 0)
|
||||
});
|
||||
}
|
||||
fn unpack(&self) -> Vec<Entry> {
|
||||
let mut out = Vec::new();
|
||||
for (target, e) in &self.map {
|
||||
for kind in GossipType::ALL {
|
||||
if e[kind.index()] != 0 {
|
||||
out.push(Entry {
|
||||
target: *target,
|
||||
kind,
|
||||
value: e[kind.index()],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `selectGossipsForTransfer`: `max_count` picks weighted by magnitude,
|
||||
/// duplicates counted once.
|
||||
fn select_for_transfer(&self, random: &mut LegacyRandom, max_count: usize) -> Vec<Entry> {
|
||||
let entries = self.unpack();
|
||||
if entries.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ends = Vec::with_capacity(entries.len());
|
||||
let mut total = 0;
|
||||
for e in &entries {
|
||||
total += e.weighted().abs();
|
||||
ends.push(total - 1);
|
||||
}
|
||||
let mut picked: Vec<usize> = Vec::new();
|
||||
for _ in 0..max_count {
|
||||
let choice = random.next_int_bound(total).unwrap_or(0);
|
||||
// Arrays.binarySearch on the strictly increasing range ends.
|
||||
let index = match ends.binary_search(&choice) {
|
||||
Ok(i) | Err(i) => i,
|
||||
};
|
||||
if !picked.contains(&index) {
|
||||
picked.push(index);
|
||||
}
|
||||
}
|
||||
picked.into_iter().map(|i| entries[i]).collect()
|
||||
}
|
||||
/// `transferFrom`: gossip heard from another villager, weakened by the
|
||||
/// retelling. Returns how many gossips were picked.
|
||||
pub fn transfer_from(
|
||||
&mut self,
|
||||
source: &Gossips,
|
||||
random: &mut LegacyRandom,
|
||||
max_count: usize,
|
||||
) -> usize {
|
||||
let picked = source.select_for_transfer(random, max_count);
|
||||
for g in &picked {
|
||||
let decayed = g.value - g.kind.decay_per_transfer();
|
||||
if decayed >= DISCARD_THRESHOLD {
|
||||
let e = self.map.entry(g.target).or_insert([0; 5]);
|
||||
let slot = &mut e[g.kind.index()];
|
||||
*slot = (*slot).max(decayed);
|
||||
}
|
||||
}
|
||||
picked.len()
|
||||
}
|
||||
|
||||
pub fn to_nbt(&self) -> Tag {
|
||||
Tag::List(
|
||||
self.unpack()
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
Tag::compound([
|
||||
("Target", Tag::IntArray(e.target.to_vec())),
|
||||
("Type", Tag::String(e.kind.id().into())),
|
||||
("Value", Tag::Int(e.value)),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
pub fn from_nbt(tag: &Tag) -> Self {
|
||||
let mut out = Self::default();
|
||||
let Tag::List(list) = tag else { return out };
|
||||
for g in list {
|
||||
let target = match g.get("Target") {
|
||||
Some(Tag::IntArray(v)) if v.len() == 4 => [v[0], v[1], v[2], v[3]],
|
||||
_ => continue,
|
||||
};
|
||||
let kind = match g.get("Type") {
|
||||
Some(Tag::String(s)) => GossipType::from_id(&s.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
let value = match g.get("Value") {
|
||||
Some(Tag::Int(v)) => *v,
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(kind) = kind
|
||||
&& value > 0
|
||||
{
|
||||
out.map.entry(target).or_insert([0; 5])[kind.index()] = value;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PLAYER: Target = [1, 2, 3, 4];
|
||||
const OTHER: Target = [5, 6, 7, 8];
|
||||
|
||||
#[test]
|
||||
fn reputation_adds_up_weighted() {
|
||||
let mut g = Gossips::default();
|
||||
g.add(PLAYER, GossipType::MinorPositive, 25);
|
||||
g.add(PLAYER, GossipType::MajorPositive, 20);
|
||||
g.add(PLAYER, GossipType::Trading, 2);
|
||||
// 25 + 20 * 5 + 2
|
||||
assert_eq!(g.reputation(PLAYER), 127);
|
||||
g.add(PLAYER, GossipType::MajorNegative, 25);
|
||||
assert_eq!(g.reputation(PLAYER), 127 - 125);
|
||||
assert_eq!(g.reputation(OTHER), 0);
|
||||
}
|
||||
#[test]
|
||||
fn values_stop_at_their_maximum() {
|
||||
let mut g = Gossips::default();
|
||||
for _ in 0..10 {
|
||||
g.add(PLAYER, GossipType::MajorNegative, 25);
|
||||
}
|
||||
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 100);
|
||||
// The minor negative cap is 200: eight hits of 25 fill it.
|
||||
for _ in 0..12 {
|
||||
g.add(PLAYER, GossipType::MinorNegative, 25);
|
||||
}
|
||||
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 200);
|
||||
assert_eq!(g.reputation(PLAYER), -500 - 200);
|
||||
}
|
||||
#[test]
|
||||
fn small_values_are_forgotten() {
|
||||
let mut g = Gossips::default();
|
||||
g.add(PLAYER, GossipType::Trading, 1);
|
||||
assert!(g.is_empty());
|
||||
g.add(PLAYER, GossipType::Trading, 2);
|
||||
assert_eq!(g.get(PLAYER, GossipType::Trading), 2);
|
||||
g.remove(PLAYER, GossipType::Trading);
|
||||
assert!(g.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn gossip_decays_by_the_day() {
|
||||
let mut g = Gossips::default();
|
||||
g.add(PLAYER, GossipType::MajorNegative, 25);
|
||||
g.add(PLAYER, GossipType::MinorNegative, 25);
|
||||
g.add(PLAYER, GossipType::MinorPositive, 3);
|
||||
g.add(PLAYER, GossipType::MajorPositive, 20);
|
||||
g.decay();
|
||||
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 15);
|
||||
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 5);
|
||||
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 2);
|
||||
// Major positive gossip never fades.
|
||||
assert_eq!(g.get(PLAYER, GossipType::MajorPositive), 20);
|
||||
g.decay();
|
||||
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 5);
|
||||
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 0);
|
||||
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 0);
|
||||
g.decay();
|
||||
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 0);
|
||||
assert_eq!(g.len(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn retold_gossip_is_weaker() {
|
||||
let mut source = Gossips::default();
|
||||
source.add(PLAYER, GossipType::MajorNegative, 25);
|
||||
source.add(OTHER, GossipType::Trading, 25);
|
||||
let mut heard = Gossips::default();
|
||||
let mut random = LegacyRandom::new(11);
|
||||
let n = heard.transfer_from(&source, &mut random, 50);
|
||||
assert!((1..=2).contains(&n));
|
||||
// 25 - 10 per transfer for major negative, 25 - 20 for trading.
|
||||
let major = heard.get(PLAYER, GossipType::MajorNegative);
|
||||
let trading = heard.get(OTHER, GossipType::Trading);
|
||||
assert!(major == 0 || major == 15);
|
||||
assert!(trading == 0 || trading == 5);
|
||||
assert!(major + trading > 0);
|
||||
// A second hearing keeps the stronger value.
|
||||
heard.transfer_from(&source, &mut random, 50);
|
||||
assert!(heard.get(PLAYER, GossipType::MajorNegative) <= 15);
|
||||
// Gossip too weak to survive retelling is dropped.
|
||||
let mut faint = Gossips::default();
|
||||
faint.add(PLAYER, GossipType::Trading, 5);
|
||||
let mut heard = Gossips::default();
|
||||
heard.transfer_from(&faint, &mut random, 10);
|
||||
assert!(heard.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn gossip_round_trips_through_nbt() {
|
||||
let mut g = Gossips::default();
|
||||
g.add(PLAYER, GossipType::MajorNegative, 25);
|
||||
g.add(PLAYER, GossipType::Trading, 2);
|
||||
g.add(OTHER, GossipType::MinorPositive, 25);
|
||||
assert_eq!(Gossips::from_nbt(&g.to_nbt()), g);
|
||||
}
|
||||
#[test]
|
||||
fn counts_by_type() {
|
||||
let mut g = Gossips::default();
|
||||
g.add(PLAYER, GossipType::MajorNegative, 25);
|
||||
g.add(OTHER, GossipType::MajorNegative, 25);
|
||||
g.add(OTHER, GossipType::Trading, 25);
|
||||
assert_eq!(g.count_for_type(GossipType::MajorNegative, |v| v < 0.0), 2);
|
||||
assert_eq!(g.count_for_type(GossipType::Trading, |v| v < 0.0), 0);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,27 @@ pub struct StackData {
|
||||
pub writable_pages: Vec<String>,
|
||||
/// `minecraft:written_book_content`.
|
||||
pub written: Option<WrittenBook>,
|
||||
/// `minecraft:banner_patterns` (banners and shields).
|
||||
pub banner_patterns: Vec<crate::banner::BannerLayer>,
|
||||
/// `minecraft:base_color` (a shield's dye).
|
||||
pub base_color: Option<Arc<str>>,
|
||||
/// The raid captain's banner: `minecraft:banner_patterns` with the
|
||||
/// ominous layers, its item name, rarity and hidden tooltip.
|
||||
pub ominous_banner: bool,
|
||||
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
|
||||
pub ominous_amplifier: Option<u8>,
|
||||
}
|
||||
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
|
||||
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
|
||||
("rhombus", "cyan"),
|
||||
("stripe_bottom", "light_gray"),
|
||||
("stripe_center", "gray"),
|
||||
("border", "light_gray"),
|
||||
("stripe_middle", "black"),
|
||||
("half_horizontal", "light_gray"),
|
||||
("circle", "light_gray"),
|
||||
("border", "black"),
|
||||
];
|
||||
/// `WrittenBookContent` with the pages as plain text.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct WrittenBook {
|
||||
@@ -267,6 +287,15 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
|
||||
if let Some(id) = d.map_id {
|
||||
entries.push(("minecraft:map_id", Tag::Int(id)));
|
||||
}
|
||||
if !d.banner_patterns.is_empty() {
|
||||
entries.push((
|
||||
"minecraft:banner_patterns",
|
||||
crate::banner::layers_to_nbt(&d.banner_patterns),
|
||||
));
|
||||
}
|
||||
if let Some(color) = &d.base_color {
|
||||
entries.push(("minecraft:base_color", Tag::String((&**color).into())));
|
||||
}
|
||||
// Filterable values are saved as {raw: ..}.
|
||||
let raw = |t: Tag| Tag::compound([("raw", t)]);
|
||||
if !d.writable_pages.is_empty() {
|
||||
@@ -330,6 +359,39 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
|
||||
Tag::List(d.charged.iter().map(crate::save::item_to_nbt).collect()),
|
||||
));
|
||||
}
|
||||
if d.ominous_banner {
|
||||
let layer = |pattern: &str, color: &str| {
|
||||
Tag::compound([
|
||||
(
|
||||
"pattern",
|
||||
Tag::String(format!("minecraft:{pattern}").as_str().into()),
|
||||
),
|
||||
("color", Tag::String(color.into())),
|
||||
])
|
||||
};
|
||||
entries.push((
|
||||
"minecraft:banner_patterns",
|
||||
Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()),
|
||||
));
|
||||
entries.push((
|
||||
"minecraft:tooltip_display",
|
||||
Tag::compound([(
|
||||
"hidden_components",
|
||||
Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]),
|
||||
)]),
|
||||
));
|
||||
entries.push((
|
||||
"minecraft:item_name",
|
||||
Tag::compound([(
|
||||
"translate",
|
||||
Tag::String("block.minecraft.ominous_banner".into()),
|
||||
)]),
|
||||
));
|
||||
entries.push(("minecraft:rarity", Tag::String("uncommon".into())));
|
||||
}
|
||||
if let Some(a) = d.ominous_amplifier {
|
||||
entries.push(("minecraft:ominous_bottle_amplifier", Tag::Int(i32::from(a))));
|
||||
}
|
||||
if !d.container.is_empty() {
|
||||
let slots = d
|
||||
.container
|
||||
@@ -371,6 +433,11 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
|
||||
custom_name: c.get("minecraft:custom_name").and_then(read_text),
|
||||
potion,
|
||||
map_id: c.get("minecraft:map_id").and_then(int).map(|v| v as i32),
|
||||
banner_patterns: crate::banner::layers_from_nbt(c.get("minecraft:banner_patterns")),
|
||||
base_color: c
|
||||
.get("minecraft:base_color")
|
||||
.and_then(string)
|
||||
.map(|s| Arc::from(s.as_str())),
|
||||
writable_pages: match c
|
||||
.get("minecraft:writable_book_content")
|
||||
.and_then(|b| b.get("pages"))
|
||||
@@ -435,6 +502,15 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
ominous_banner: matches!(
|
||||
c.get("minecraft:banner_patterns"),
|
||||
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
|
||||
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
|
||||
),
|
||||
ominous_amplifier: c
|
||||
.get("minecraft:ominous_bottle_amplifier")
|
||||
.and_then(int)
|
||||
.map(|v| v.clamp(0, 4) as u8),
|
||||
trim: c.get("minecraft:trim").and_then(|t| {
|
||||
Some((
|
||||
Arc::from(t.get("material").and_then(string)?.as_str()),
|
||||
@@ -499,6 +575,34 @@ mod tests {
|
||||
assert_eq!(back.custom_name(), Some("Blade"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn banner_layers_and_shield_base_round_trip() {
|
||||
let mut stack = ItemStack::new("minecraft:shield", 1);
|
||||
stack.data_mut().base_color = Some(Arc::from("red"));
|
||||
stack.data_mut().banner_patterns = vec![
|
||||
crate::banner::BannerLayer::new("minecraft:flower", "black"),
|
||||
crate::banner::BannerLayer::new("minecraft:border", "white"),
|
||||
];
|
||||
let tag = encode_components(&stack).expect("components");
|
||||
let (_, extra) = decode_components(Some(&tag));
|
||||
let extra = extra.expect("data");
|
||||
assert_eq!(extra.base_color.as_deref(), Some("red"));
|
||||
assert_eq!(extra.banner_patterns, stack.data().unwrap().banner_patterns);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ominous_items_round_trip() {
|
||||
let mut banner = ItemStack::new("minecraft:white_banner", 1);
|
||||
banner.data_mut().ominous_banner = true;
|
||||
let tag = encode_components(&banner).unwrap();
|
||||
assert!(tag.get("minecraft:banner_patterns").is_some());
|
||||
let (_, back) = decode_components(Some(&tag));
|
||||
assert!(back.unwrap().ominous_banner);
|
||||
let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1);
|
||||
bottle.data_mut().ominous_amplifier = Some(3);
|
||||
let (_, back) = decode_components(encode_components(&bottle).as_ref());
|
||||
assert_eq!(back.unwrap().ominous_amplifier, Some(3));
|
||||
}
|
||||
#[test]
|
||||
fn plain_stacks_have_no_components() {
|
||||
let stack = ItemStack::new("minecraft:stone", 64);
|
||||
|
||||
@@ -53,6 +53,10 @@ pub struct ItemInfo {
|
||||
pub glider: bool,
|
||||
/// `equippable.swappable` and `equip_sound`.
|
||||
pub swappable: bool,
|
||||
/// `equippable.dispensable` (dispensers may put it on an entity).
|
||||
pub equip_dispensable: bool,
|
||||
/// `equippable.allowed_entities` resolved to entity type ids; None allows all.
|
||||
pub equip_allowed: Option<HashSet<String>>,
|
||||
pub equip_sound: Option<String>,
|
||||
/// `jukebox_playable`: the jukebox song it plays.
|
||||
pub jukebox_song: Option<String>,
|
||||
@@ -251,6 +255,13 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
/// An entity type id or `#tag` as the set of entity type ids it names.
|
||||
fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<String> {
|
||||
match spec.strip_prefix('#') {
|
||||
Some(tag) => tags.get(tag).cloned().unwrap_or_default(),
|
||||
None => HashSet::from([spec.to_owned()]),
|
||||
}
|
||||
}
|
||||
impl Items {
|
||||
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
|
||||
let raw: BTreeMap<String, Value> =
|
||||
@@ -264,6 +275,7 @@ impl Items {
|
||||
.or_insert(BlockStateId(i as u32));
|
||||
}
|
||||
}
|
||||
let entity_tags = load_tags(root, "entity_type")?;
|
||||
let mut items = HashMap::new();
|
||||
let mut order = Vec::new();
|
||||
for (name, c) in &raw {
|
||||
@@ -323,6 +335,19 @@ impl Items {
|
||||
swappable: c["minecraft:equippable"]["swappable"]
|
||||
.as_bool()
|
||||
.unwrap_or(true),
|
||||
equip_dispensable: c["minecraft:equippable"]["dispensable"]
|
||||
.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(
|
||||
list.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.flat_map(|spec| entity_spec(&entity_tags, spec))
|
||||
.collect(),
|
||||
),
|
||||
_ => None,
|
||||
},
|
||||
equip_sound: c["minecraft:equippable"]["equip_sound"]
|
||||
.as_str()
|
||||
.map(str::to_owned),
|
||||
@@ -468,6 +493,10 @@ impl Items {
|
||||
}
|
||||
false
|
||||
}
|
||||
/// Whether a loot table (`minecraft:blocks/stone`, ...) exists.
|
||||
pub fn has_loot_table(&self, id: &str) -> bool {
|
||||
self.loot.contains_key(id)
|
||||
}
|
||||
/// Evaluate the block's loot table for a player break without explosions.
|
||||
pub fn block_drops(
|
||||
&self,
|
||||
|
||||
@@ -7,20 +7,25 @@ pub mod animate_tick;
|
||||
pub mod assets;
|
||||
pub mod attribute_updates;
|
||||
pub mod audio;
|
||||
pub mod banner;
|
||||
pub mod biome;
|
||||
pub mod block_entity_render;
|
||||
pub mod blocks;
|
||||
pub mod bossbar;
|
||||
pub mod brewing;
|
||||
pub mod chat;
|
||||
pub mod chunk;
|
||||
pub mod clock;
|
||||
pub mod collisions;
|
||||
pub mod command;
|
||||
pub mod command_storage;
|
||||
pub mod component;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
pub mod crafting;
|
||||
pub mod creative;
|
||||
pub mod data_cmd;
|
||||
pub mod datapack;
|
||||
pub mod effects;
|
||||
pub mod enchant;
|
||||
pub mod entities;
|
||||
@@ -30,6 +35,7 @@ pub mod fog;
|
||||
pub mod font;
|
||||
pub mod gamerules;
|
||||
pub mod gfx;
|
||||
pub mod gossip;
|
||||
pub mod health;
|
||||
pub mod hud;
|
||||
pub mod hunger;
|
||||
@@ -48,27 +54,37 @@ pub mod models;
|
||||
pub mod motion;
|
||||
pub mod multiplayer;
|
||||
pub mod music;
|
||||
pub mod nbt_path;
|
||||
pub mod net;
|
||||
pub mod options_ui;
|
||||
pub mod packs;
|
||||
pub mod particles;
|
||||
pub mod pose;
|
||||
pub mod projectiles;
|
||||
pub mod raid;
|
||||
pub mod random_sequences;
|
||||
pub mod recipe_book;
|
||||
pub mod save;
|
||||
pub mod scoreboard;
|
||||
pub mod scoreboard_cmd;
|
||||
pub mod screen_effects;
|
||||
pub mod sculk;
|
||||
pub mod settings;
|
||||
pub mod shadows;
|
||||
pub mod signs;
|
||||
pub mod snbt;
|
||||
pub mod sprint;
|
||||
pub mod sprites;
|
||||
pub mod stations;
|
||||
pub mod streaming;
|
||||
pub mod structure_blocks;
|
||||
pub mod subtitles;
|
||||
pub mod testgen;
|
||||
pub mod text;
|
||||
pub mod title;
|
||||
pub mod ui;
|
||||
pub mod vanillagen;
|
||||
pub mod world;
|
||||
pub mod worldborder;
|
||||
pub mod zip;
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
@@ -98,6 +98,23 @@ impl Trader {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Villager.updateSpecialPrices`: the reputation and Hero of the Village
|
||||
/// discounts of a player, from scratch.
|
||||
pub fn update_special_prices(offers: &mut [MerchantOffer], reputation: i32, hero: Option<i32>) {
|
||||
// 0.3F + 0.0625F * amplifier, widened from float.
|
||||
let hero_modifier = hero.map_or(0.0, |a| f64::from(0.3f32 + 0.0625f32 * a as f32));
|
||||
for offer in offers {
|
||||
offer.special_price_diff = 0;
|
||||
if reputation != 0 {
|
||||
offer.special_price_diff -= (reputation as f32 * offer.price_multiplier).floor() as i32;
|
||||
}
|
||||
if hero_modifier > 0.0 {
|
||||
let reduction =
|
||||
(hero_modifier * f64::from(offer.base_cost_a.stack.count)).floor() as i32;
|
||||
offer.special_price_diff -= reduction.max(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// An `ItemCost`: item and count (component predicates are not used by the
|
||||
/// 26.3 trade data except for one exact match, kept as the stack's data).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -708,6 +725,32 @@ mod tests {
|
||||
assert!(!can_level_up(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reputation_and_heroes_lower_prices() {
|
||||
let items = items();
|
||||
let mut offers = vec![offer(10, None), offer(1, None)];
|
||||
// Reputation 50 with a 0.2 multiplier: 10 off, floored per offer.
|
||||
update_special_prices(&mut offers, 50, None);
|
||||
assert_eq!(offers[0].special_price_diff, -10);
|
||||
assert_eq!(offers[0].cost_a_count(&items), 1);
|
||||
assert_eq!(offers[1].special_price_diff, -10);
|
||||
// Bad reputation raises the price (-30 * 0.2 = -6 floors to -6).
|
||||
update_special_prices(&mut offers, -30, None);
|
||||
assert_eq!(offers[0].special_price_diff, 6);
|
||||
assert_eq!(offers[0].cost_a_count(&items), 16);
|
||||
// Hero of the Village I: 0.3 * 10 = 3 off, at least 1.
|
||||
update_special_prices(&mut offers, 0, Some(0));
|
||||
assert_eq!(offers[0].special_price_diff, -3);
|
||||
assert_eq!(offers[1].special_price_diff, -1);
|
||||
// Level III: 0.3 + 0.125 = 0.425 -> 4 off a ten emerald price.
|
||||
update_special_prices(&mut offers, 0, Some(2));
|
||||
assert_eq!(offers[0].special_price_diff, -4);
|
||||
// Both stack, from scratch each time.
|
||||
update_special_prices(&mut offers, 25, Some(0));
|
||||
assert_eq!(offers[0].special_price_diff, -5 - 3);
|
||||
update_special_prices(&mut offers, 0, None);
|
||||
assert_eq!(offers[0].special_price_diff, 0);
|
||||
}
|
||||
#[test]
|
||||
fn offers_follow_the_trade_data() {
|
||||
let items = items();
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod anim;
|
||||
pub mod aquatic;
|
||||
pub mod camel;
|
||||
pub mod control;
|
||||
pub mod creaking;
|
||||
pub mod cube;
|
||||
pub mod data;
|
||||
pub mod enderman;
|
||||
@@ -28,6 +29,7 @@ pub mod nether;
|
||||
pub mod path;
|
||||
pub mod phantom;
|
||||
pub mod piglin;
|
||||
pub mod raider;
|
||||
pub mod ravager;
|
||||
pub mod render;
|
||||
pub mod shulker;
|
||||
@@ -37,6 +39,7 @@ pub mod tame;
|
||||
pub mod undead;
|
||||
pub mod vex;
|
||||
pub mod villager;
|
||||
pub mod warden;
|
||||
pub mod witch;
|
||||
pub mod wither;
|
||||
mod world;
|
||||
@@ -336,6 +339,7 @@ pub enum DamageKind {
|
||||
Generic,
|
||||
InWall,
|
||||
Thorns,
|
||||
SonicBoom,
|
||||
}
|
||||
/// A damage source: its type, the attacking entity and where it came from.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -390,6 +394,7 @@ impl Damage {
|
||||
| DamageKind::Magic
|
||||
| DamageKind::InWall
|
||||
| DamageKind::Generic
|
||||
| DamageKind::SonicBoom
|
||||
)
|
||||
}
|
||||
pub fn is_fire(&self) -> bool {
|
||||
@@ -433,8 +438,12 @@ pub struct Extra {
|
||||
/// Dye colour id (sheep wool, collars).
|
||||
pub color: u8,
|
||||
pub sheared: bool,
|
||||
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
|
||||
pub pick_up_loot: bool,
|
||||
pub saddled: bool,
|
||||
pub chested: bool,
|
||||
/// The chest contents of a donkey or mule (15 slots).
|
||||
pub items: Vec<Option<crate::items::ItemStack>>,
|
||||
pub tame: bool,
|
||||
pub sitting: bool,
|
||||
/// The owner's UUID (tamed animals).
|
||||
@@ -473,6 +482,12 @@ pub struct Extra {
|
||||
pub meeting: Option<[i32; 3]>,
|
||||
/// Villager and wandering trader offers and experience.
|
||||
pub trade: Option<Box<crate::merchant::Trader>>,
|
||||
/// A warden's brain, anger and vibrations.
|
||||
pub warden: Option<Box<warden::Warden>>,
|
||||
/// A raider's patrol and raid state.
|
||||
pub raider: Option<Box<raider::State>>,
|
||||
/// A villager's raid activity and gossip.
|
||||
pub villager: Option<Box<villager::Ext>>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Mob {
|
||||
@@ -515,6 +530,12 @@ pub struct Mob {
|
||||
pub extra: Extra,
|
||||
pub fluids: living::Fluids,
|
||||
pub no_gravity: bool,
|
||||
/// `NoAI`: no goals and no movement.
|
||||
pub no_ai: bool,
|
||||
/// `Silent`.
|
||||
pub silent: bool,
|
||||
/// `Invulnerable`: immune to damage (but not to `/kill`).
|
||||
pub invulnerable_flag: bool,
|
||||
pub climbing: bool,
|
||||
pub fire_ticks: i32,
|
||||
pub air: i32,
|
||||
@@ -657,11 +678,75 @@ pub enum MobEvent {
|
||||
kind: DamageKind,
|
||||
amount: f32,
|
||||
},
|
||||
/// Two villagers are close: swap gossip and share food and wares.
|
||||
VillagerMeet {
|
||||
mob: u32,
|
||||
other: u32,
|
||||
},
|
||||
/// Two villagers make a baby.
|
||||
VillagerBirth {
|
||||
parent: u32,
|
||||
partner: u32,
|
||||
},
|
||||
/// A villager asks whether enough neighbours want an iron golem.
|
||||
GolemCheck {
|
||||
mob: u32,
|
||||
needed: usize,
|
||||
},
|
||||
/// A villager launches a firework rocket (celebrating a won raid).
|
||||
Firework {
|
||||
at: [f64; 3],
|
||||
color: usize,
|
||||
flight: u8,
|
||||
},
|
||||
/// A villager throws a hero's gift (a loot table) toward the player.
|
||||
ThrowGift {
|
||||
table: String,
|
||||
from: [f64; 3],
|
||||
to: [f64; 3],
|
||||
},
|
||||
/// A patrol leader hands its patrol target to a companion.
|
||||
PatrolTarget {
|
||||
mob: u32,
|
||||
target: [i32; 3],
|
||||
},
|
||||
/// A raider is told to attack (`HoldGroundAttackGoal` shouting).
|
||||
RaiderTarget {
|
||||
mob: u32,
|
||||
target: Who,
|
||||
aggressive: bool,
|
||||
},
|
||||
/// Drop the loot of a gift table (chicken eggs, armadillo scutes).
|
||||
GiftLoot {
|
||||
table: &'static str,
|
||||
at: [f64; 3],
|
||||
},
|
||||
/// A vibration travelling to a listener (`VibrationParticleOption`).
|
||||
Vibration {
|
||||
from: [f64; 3],
|
||||
to: [f64; 3],
|
||||
ticks: i32,
|
||||
},
|
||||
/// The crumbs of the block under a digging or emerging warden.
|
||||
DigParticles {
|
||||
at: [f64; 3],
|
||||
},
|
||||
/// `Warden.applyDarknessAround`: darkness for survival players nearby.
|
||||
Darkness {
|
||||
at: [f64; 3],
|
||||
radius: f64,
|
||||
},
|
||||
/// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it).
|
||||
CreakingHurt {
|
||||
home: [i32; 3],
|
||||
by_player: bool,
|
||||
id: u32,
|
||||
},
|
||||
/// `Creaking.tearDown`: crumbling particles around the creaking.
|
||||
CreakingTearDown {
|
||||
center: [f64; 3],
|
||||
spread: [f64; 3],
|
||||
},
|
||||
}
|
||||
/// How a spawned-by-kind mob should be set up.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -701,6 +786,10 @@ pub struct Seen {
|
||||
/// A villager's claimed job site and bed.
|
||||
pub job: Option<[i32; 3]>,
|
||||
pub bed: Option<[i32; 3]>,
|
||||
/// A raider in an active raid.
|
||||
pub active_raid: bool,
|
||||
/// A villager's reputation of the player (`getPlayerReputation`).
|
||||
pub player_rep: i32,
|
||||
}
|
||||
/// The player as mobs see it.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -723,6 +812,10 @@ pub struct PlayerView {
|
||||
pub hurt_by: Option<(Who, i64)>,
|
||||
/// `getLastHurtMob` and when.
|
||||
pub last_hurt: Option<(Who, i64)>,
|
||||
/// The Hero of the Village effect.
|
||||
pub hero: bool,
|
||||
/// The player's UUID (villagers' gossip is keyed by it).
|
||||
pub uuid: [i32; 4],
|
||||
}
|
||||
pub struct MobWorld<'a> {
|
||||
pub world: &'a World,
|
||||
@@ -785,6 +878,9 @@ impl Mob {
|
||||
extra: Extra::default(),
|
||||
fluids: living::Fluids::default(),
|
||||
no_gravity: false,
|
||||
no_ai: false,
|
||||
silent: false,
|
||||
invulnerable_flag: false,
|
||||
climbing: false,
|
||||
fire_ticks: 0,
|
||||
air: 300,
|
||||
@@ -858,7 +954,7 @@ impl Mob {
|
||||
.fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
|
||||
}
|
||||
pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
|
||||
if !self.alive() || self.removed {
|
||||
if !self.alive() || self.removed || self.invulnerable_flag {
|
||||
return false;
|
||||
}
|
||||
if source.is_fire() && (self.kind.flags.fire_immune) {
|
||||
|
||||
@@ -87,6 +87,8 @@ pub enum Family {
|
||||
Wither,
|
||||
Allay,
|
||||
Villager,
|
||||
Warden,
|
||||
Creaking,
|
||||
}
|
||||
pub fn family(s: Species) -> Family {
|
||||
use Species as S;
|
||||
@@ -121,6 +123,7 @@ pub fn family(s: Species) -> Family {
|
||||
S::Ravager => Family::Ravager,
|
||||
S::Wither => Family::Wither,
|
||||
S::Allay => Family::Allay,
|
||||
S::Creaking => Family::Creaking,
|
||||
S::Villager => Family::Villager,
|
||||
S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin,
|
||||
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => {
|
||||
@@ -130,6 +133,7 @@ pub fn family(s: Species) -> Family {
|
||||
S::Enderman => Family::Enderman,
|
||||
S::Slime | S::MagmaCube => Family::Cube,
|
||||
S::Guardian | S::ElderGuardian => Family::Guardian,
|
||||
S::Warden => Family::Warden,
|
||||
S::Shulker => Family::Shulker,
|
||||
_ => Family::Generic,
|
||||
}
|
||||
@@ -169,7 +173,10 @@ pub fn register(m: &mut Mob) {
|
||||
Family::Wither => super::wither::register(m),
|
||||
Family::Allay => super::allay::register(m),
|
||||
Family::Villager => super::villager::register(m),
|
||||
Family::Warden => super::warden::register(m),
|
||||
Family::Creaking => super::creaking::register(m),
|
||||
}
|
||||
super::raider::register(m);
|
||||
}
|
||||
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
|
||||
fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
@@ -251,10 +258,16 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
return false;
|
||||
}
|
||||
base_tick(m, w, events);
|
||||
if m.death_time >= 20 {
|
||||
if m.death_time >= super::creaking::death_limit(m) {
|
||||
// Creaking.tickDeath: a heart's creaking crumbles away.
|
||||
if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) {
|
||||
super::creaking::tear_down(m, events);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
ai_step(m, w, events);
|
||||
if !m.no_ai {
|
||||
ai_step(m, w, events);
|
||||
}
|
||||
// Mob.tickHeadTurn -> BodyRotationControl.clientTick
|
||||
if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
@@ -371,6 +384,11 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let sound = match m.species() {
|
||||
// Warden.getAmbientSound: by anger, silent while roaring or digging.
|
||||
Species::Warden => match super::warden::ambient_sound(m) {
|
||||
Some(sound) => sound,
|
||||
None => return,
|
||||
},
|
||||
Species::Zombie | Species::Husk if m.is_baby() => m.kind.sounds[0],
|
||||
Species::Drowned if m.fluids.in_water => "entity.drowned.ambient_water",
|
||||
Species::Enderman if m.ai.target.is_some() => "entity.enderman.scream",
|
||||
@@ -391,6 +409,8 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air",
|
||||
Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return,
|
||||
Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item",
|
||||
// Creaking.getAmbientSound: silent while awake.
|
||||
Species::Creaking if m.extra.flag => return,
|
||||
// Shulker.playAmbientSound: silent while closed.
|
||||
Species::Shulker if m.extra.counter == 0 => return,
|
||||
Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry",
|
||||
@@ -405,6 +425,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
|
||||
fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if super::creaking::is_creaking(m) {
|
||||
super::creaking::update(m, w, events);
|
||||
}
|
||||
if m.ai.no_jump_delay > 0 {
|
||||
m.ai.no_jump_delay -= 1;
|
||||
}
|
||||
@@ -486,6 +509,10 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
/// Mob.serverAiStep
|
||||
fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.ai.no_action_time += 1;
|
||||
// A creaking looked at stands still.
|
||||
if super::creaking::is_creaking(m) && !super::creaking::can_move(m) {
|
||||
return;
|
||||
}
|
||||
// A saddled mount follows its rider instead of its goals.
|
||||
if super::equine::controlled(m) {
|
||||
super::equine::ridden_step(m);
|
||||
@@ -532,6 +559,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
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),
|
||||
Species::Warden => super::warden::server_ai_step(m, cx),
|
||||
// SpellcasterIllager.customServerAiStep.
|
||||
Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1,
|
||||
_ => {}
|
||||
@@ -559,6 +587,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
Species::Zoglin if m.extra.anim_ticks > 0 => m.extra.anim_ticks -= 1,
|
||||
s if super::equine::is_equine(s) => super::equine::ai_step(m, w, events),
|
||||
Species::Phantom => super::phantom::flap_sound(m, events),
|
||||
Species::Warden => super::warden::ai_step(m, events),
|
||||
Species::Guardian | Species::ElderGuardian => super::guardian::ai_step(m, w, events),
|
||||
Species::Vex => super::vex::ai_step(m, w),
|
||||
Species::Ravager => super::ravager::ai_step(m, w, events),
|
||||
@@ -581,12 +610,17 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
/// Mob.checkDespawn (players are the only despawn reference).
|
||||
fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
let creature = m.kind.category == "creature";
|
||||
if m.persistent || creature && m.kind.flags.animal {
|
||||
// Warden.removeWhenFarAway is false.
|
||||
if m.persistent || m.species() == Species::Warden || creature && m.kind.flags.animal {
|
||||
m.ai.no_action_time = 0;
|
||||
return true;
|
||||
}
|
||||
let Some(p) = &w.player else { return true };
|
||||
let d = m.distance_sqr(p.position);
|
||||
// Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`).
|
||||
if super::raider::keeps_alive(m, d) {
|
||||
return true;
|
||||
}
|
||||
let despawn = if m.kind.category == "water_ambient" {
|
||||
64.0
|
||||
} else {
|
||||
@@ -625,6 +659,7 @@ pub fn speed_bonus(m: &Mob) -> f64 {
|
||||
pub fn sound_volume(m: &Mob) -> f32 {
|
||||
match m.species() {
|
||||
Species::Ghast => 5.0,
|
||||
Species::Warden => 4.0,
|
||||
Species::Slime | Species::MagmaCube => 0.4 * m.extra.size.max(1) as f32,
|
||||
Species::Cod
|
||||
| Species::Salmon
|
||||
@@ -664,7 +699,9 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
|
||||
match m.species() {
|
||||
// Allay.hurtServer: its liked player cannot hurt it.
|
||||
Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false,
|
||||
Species::Creaking => super::creaking::accepts_damage(m, source),
|
||||
Species::Wither => super::wither::accepts(m, source.kind, source.attacker, false),
|
||||
Species::Warden => super::warden::accepts_damage(m, source),
|
||||
Species::Shulker => super::shulker::accepts(m, source),
|
||||
Species::Enderman => super::enderman::on_damage(m, source),
|
||||
Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider
|
||||
@@ -681,6 +718,7 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
|
||||
match m.species() {
|
||||
Species::Enderman => super::enderman::after_hurt(m, source),
|
||||
Species::Shulker => super::shulker::after_hurt(m),
|
||||
Species::Warden => super::warden::hurt(m, source),
|
||||
Species::Wolf => super::tame::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
|
||||
@@ -707,6 +745,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
|
||||
if m.species() == Species::Ravager {
|
||||
super::ravager::on_attack(m, cx.events);
|
||||
}
|
||||
if super::creaking::is_creaking(m) {
|
||||
super::creaking::on_attack(m, cx.events);
|
||||
}
|
||||
let mut amount = m.attrs.attack_damage;
|
||||
let from = [m.position.x, m.position.y, m.position.z];
|
||||
let source = Damage::mob(m.id, from);
|
||||
|
||||
@@ -8,7 +8,9 @@ use std::f32::consts::PI;
|
||||
/// The setupAnim implementation a model uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Anim {
|
||||
Warden,
|
||||
Allay,
|
||||
Creaking,
|
||||
Camel,
|
||||
Wither,
|
||||
Vex,
|
||||
@@ -345,7 +347,9 @@ pub fn setup(
|
||||
) {
|
||||
match m.kind.anim {
|
||||
Anim::Camel => super::camel::anim(m, s, p, w_anims),
|
||||
Anim::Warden => super::warden::anim(m, s, p, w_anims),
|
||||
Anim::Allay => super::allay::anim(m, s, p),
|
||||
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
|
||||
Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => {
|
||||
super::aquatic::anim(m, s, p)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at
|
||||
//! them, wake up when one looks from within 12 blocks, then hunt the nearest
|
||||
//! visible player and hit every 40 ticks. One bound to a creaking heart takes
|
||||
//! no damage (it only sways and hurts the heart's resin spreader), dies when
|
||||
//! the heart no longer protects it and falls apart with the heart.
|
||||
use super::{
|
||||
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
|
||||
anim::{Poses, State},
|
||||
goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone},
|
||||
keyframes::Animation,
|
||||
path::PathType,
|
||||
};
|
||||
use crate::containers::BlockEntity;
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// `Extra.ints` slots.
|
||||
const INVULNERABLE: usize = 0;
|
||||
const ATTACKING: usize = 1;
|
||||
const STUCK: usize = 2;
|
||||
const TEARING_DOWN: usize = 3;
|
||||
const EYES: usize = 4;
|
||||
const NEXT_FLICKER: usize = 5;
|
||||
/// `Extra.counter` bits: hurt while protected, and by a player.
|
||||
const HURT: i32 = 1;
|
||||
const HURT_BY_PLAYER: i32 = 2;
|
||||
|
||||
/// `Creaking.ACTIVATION_RANGE_SQ`.
|
||||
const ACTIVATION_RANGE_SQ: f64 = 144.0;
|
||||
/// `Creaking.INVULNERABILITY_ANIMATION_DURATION` and the attack animation.
|
||||
const INVULNERABILITY_TICKS: i32 = 8;
|
||||
const ATTACK_TICKS: i32 = 15;
|
||||
/// `Creaking.TWITCH_DEATH_DURATION`.
|
||||
const TWITCH_TICKS: i32 = 45;
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(2, MeleeAttack::new(1.0, false).interval(40));
|
||||
g.add(5, Stroll::avoiding_water(0.3));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
m.ai.targets.add(1, HuntPlayer);
|
||||
}
|
||||
/// Bound to a heart (`getHomePos() != null`).
|
||||
pub fn heart_bound(m: &Mob) -> bool {
|
||||
is_creaking(m) && m.extra.home.is_some()
|
||||
}
|
||||
pub fn tearing_down(m: &Mob) -> bool {
|
||||
is_creaking(m) && m.extra.ints[TEARING_DOWN] != 0
|
||||
}
|
||||
/// `Creaking.canMove`: false while a player looks at it.
|
||||
pub fn can_move(m: &Mob) -> bool {
|
||||
!m.extra.flag2
|
||||
}
|
||||
/// `Creaking.isActive`.
|
||||
pub fn is_active(m: &Mob) -> bool {
|
||||
m.extra.flag
|
||||
}
|
||||
/// `Creaking.setTransient`: bind to the heart at `pos` and avoid damage.
|
||||
pub fn set_transient(m: &mut Mob, pos: [i32; 3]) {
|
||||
m.extra.home = Some(pos);
|
||||
m.set_malus(PathType::Damaging, 8.0);
|
||||
m.set_malus(PathType::PowderSnow, 8.0);
|
||||
m.set_malus(PathType::Lava, 8.0);
|
||||
m.set_malus(PathType::Fire, 0.0);
|
||||
m.set_malus(PathType::FireInNeighbor, 0.0);
|
||||
}
|
||||
/// `Creaking.setTearingDown`: the heart was broken by someone.
|
||||
pub fn set_tearing_down(m: &mut Mob) {
|
||||
m.extra.ints[TEARING_DOWN] = 1;
|
||||
}
|
||||
/// `Creaking.hasGlowingEyes` / `isActive`: the eyes layer shows.
|
||||
pub fn eyes_glowing(m: &Mob) -> bool {
|
||||
if tearing_down(m) {
|
||||
m.extra.ints[EYES] != 0
|
||||
} else {
|
||||
is_active(m)
|
||||
}
|
||||
}
|
||||
/// Ticks of death animation before the mob is removed (`tickDeath`).
|
||||
pub fn death_limit(m: &Mob) -> i32 {
|
||||
if heart_bound(m) && tearing_down(m) {
|
||||
TWITCH_TICKS + 1
|
||||
} else {
|
||||
20
|
||||
}
|
||||
}
|
||||
/// `Creaking.tearDown`: crumbles away.
|
||||
pub fn tear_down(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
events.push(MobEvent::CreakingTearDown {
|
||||
center: [
|
||||
(lo.x + hi.x) / 2.0,
|
||||
(lo.y + hi.y) / 2.0,
|
||||
(lo.z + hi.z) / 2.0,
|
||||
],
|
||||
spread: [
|
||||
(hi.x - lo.x) * 0.3,
|
||||
(hi.y - lo.y) * 0.3,
|
||||
(hi.z - lo.z) * 0.3,
|
||||
],
|
||||
});
|
||||
m.voice("entity.creaking.death", events);
|
||||
m.removed = true;
|
||||
}
|
||||
/// `Creaking.hurtServer` for a heart-bound creaking: no damage, only the
|
||||
/// invulnerability animation and the heart's reaction. Returns whether the
|
||||
/// normal damage path should run.
|
||||
pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
|
||||
if !heart_bound(m) || source.kind == DamageKind::Generic {
|
||||
return true;
|
||||
}
|
||||
if source.is_fire() || !m.alive() || m.extra.ints[INVULNERABLE] > 0 {
|
||||
return false;
|
||||
}
|
||||
let by_player = source.attacker == Some(Who::Player);
|
||||
// The direct entity must be living or a projectile (or a player must be to blame).
|
||||
let direct = matches!(
|
||||
source.kind,
|
||||
DamageKind::PlayerAttack
|
||||
| DamageKind::MobAttack
|
||||
| DamageKind::Arrow
|
||||
| DamageKind::Thrown
|
||||
| DamageKind::Fireball
|
||||
| DamageKind::Thorns
|
||||
);
|
||||
if !direct && !by_player {
|
||||
return false;
|
||||
}
|
||||
m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS;
|
||||
m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 };
|
||||
false
|
||||
}
|
||||
/// `Creaking.doHurtTarget` extras: the attack animation and sound.
|
||||
pub fn on_attack(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.extra.ints[ATTACKING] = ATTACK_TICKS;
|
||||
m.voice("entity.creaking.attack", events);
|
||||
}
|
||||
/// The heart this creaking is bound to protects it (`isProtector`); a link
|
||||
/// read from a save is trusted until the heart resolves it.
|
||||
fn protected(m: &Mob, w: &MobWorld) -> bool {
|
||||
let Some(home) = m.extra.home else {
|
||||
return true;
|
||||
};
|
||||
match w.world.block_entities.get(&(home[0], home[1], home[2])) {
|
||||
Some(BlockEntity::CreakingHeart(h)) => match h.creaking {
|
||||
Some((Some(id), _)) => id == m.id,
|
||||
Some((None, _)) => true,
|
||||
None => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// `Creaking.tick` and the start of `aiStep`: protection, timers, freezing.
|
||||
pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
// Creaking.tick: without its heart's protection it dies.
|
||||
if heart_bound(m) && m.alive() && !protected(m, w) {
|
||||
m.health = 0.0;
|
||||
}
|
||||
for slot in [INVULNERABLE, ATTACKING] {
|
||||
if m.extra.ints[slot] > 0 {
|
||||
m.extra.ints[slot] -= 1;
|
||||
}
|
||||
}
|
||||
let age = m.age as f32;
|
||||
m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age);
|
||||
m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age);
|
||||
m.anim.states[2].animate_when(tearing_down(m), age);
|
||||
if m.extra.counter & HURT != 0 {
|
||||
// hurtServer: sway, and the heart reacts to a player's hit.
|
||||
if protected(m, w) {
|
||||
let by_player = m.extra.counter & HURT_BY_PLAYER != 0;
|
||||
if let Some(home) = m.extra.home {
|
||||
events.push(MobEvent::CreakingHurt {
|
||||
home,
|
||||
by_player,
|
||||
id: m.id,
|
||||
});
|
||||
}
|
||||
m.voice("entity.creaking.sway", events);
|
||||
}
|
||||
m.extra.counter &= !(HURT | HURT_BY_PLAYER);
|
||||
}
|
||||
// checkEyeBlink: the eyes of a creaking falling apart flicker.
|
||||
if m.death_time > m.extra.ints[NEXT_FLICKER] {
|
||||
let glowing = m.extra.ints[EYES] != 0;
|
||||
let (lo, hi) = if glowing {
|
||||
(2, 8)
|
||||
} else {
|
||||
(m.death_time / 4, m.death_time / 2)
|
||||
};
|
||||
let span = (hi - lo + 1).max(1);
|
||||
m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0);
|
||||
m.extra.ints[EYES] = i32::from(!glowing);
|
||||
}
|
||||
if !m.alive() {
|
||||
return;
|
||||
}
|
||||
let now = check_can_move(m, w, events);
|
||||
if now != can_move(m) {
|
||||
if now {
|
||||
m.voice("entity.creaking.unfreeze", events);
|
||||
} else {
|
||||
stop_in_place(m);
|
||||
m.voice("entity.creaking.freeze", events);
|
||||
}
|
||||
m.extra.flag2 = !now;
|
||||
}
|
||||
}
|
||||
/// `Mob.stopInPlace`.
|
||||
pub fn stop_in_place(m: &mut Mob) {
|
||||
m.nav_stop();
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.yya = 0.0;
|
||||
m.ai.zza = 0.0;
|
||||
m.ai.speed = 0.0;
|
||||
}
|
||||
fn activate(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.ai.target = Some(Who::Player);
|
||||
m.voice("entity.creaking.activate", events);
|
||||
m.extra.flag = true;
|
||||
}
|
||||
fn deactivate(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.ai.target = None;
|
||||
m.voice("entity.creaking.deactivate", events);
|
||||
m.extra.flag = false;
|
||||
}
|
||||
/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`.
|
||||
fn looked_at_by(m: &Mob, w: &MobWorld) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
let look = p.look;
|
||||
let eye = m.eye_y();
|
||||
[eye, m.position.y + 0.5, (eye + m.position.y) / 2.0]
|
||||
.into_iter()
|
||||
.any(|y| {
|
||||
let d = [
|
||||
m.position.x - p.position.x,
|
||||
y - p.eye[1],
|
||||
m.position.z - p.position.z,
|
||||
];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
if len < 1.0e-6 {
|
||||
return true;
|
||||
}
|
||||
let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len;
|
||||
dot > 0.5
|
||||
&& w.line_of_sight(
|
||||
Vec3::new(p.eye[0], p.eye[1], p.eye[2]),
|
||||
Vec3::new(m.position.x, y, m.position.z),
|
||||
)
|
||||
})
|
||||
}
|
||||
/// `Creaking.checkCanMove`: false while looked at; also wakes and calms it.
|
||||
fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
let active = is_active(m);
|
||||
// NEAREST_PLAYERS: players within the follow range.
|
||||
let near = w.player.as_ref().filter(|p| {
|
||||
let d = Vec3::new(p.position.x, p.position.y, p.position.z);
|
||||
m.distance_sqr(d) < 32.0 * 32.0
|
||||
});
|
||||
let Some(p) = near else {
|
||||
if active {
|
||||
deactivate(m, events);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// canAttack: alive and not creative or spectator.
|
||||
let attackable = p.alive && !p.creative;
|
||||
if attackable {
|
||||
// GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake.
|
||||
let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin");
|
||||
if (!active || !disguised) && looked_at_by(m, w) {
|
||||
if active {
|
||||
return false;
|
||||
}
|
||||
if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ {
|
||||
activate(m, events);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if active {
|
||||
deactivate(m, events);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `Creaking.playerIsStuckInYou`: the player's eyes inside it for more than 4 ticks.
|
||||
pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool {
|
||||
let Some(eye) = eye else {
|
||||
m.extra.ints[STUCK] = 0;
|
||||
return false;
|
||||
};
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let inside = eye[0] >= lo.x
|
||||
&& eye[0] <= hi.x
|
||||
&& eye[1] >= lo.y
|
||||
&& eye[1] <= hi.y
|
||||
&& eye[2] >= lo.z
|
||||
&& eye[2] <= hi.z;
|
||||
if inside {
|
||||
m.extra.ints[STUCK] += 1;
|
||||
m.extra.ints[STUCK] > 4
|
||||
} else {
|
||||
m.extra.ints[STUCK] = 0;
|
||||
false
|
||||
}
|
||||
}
|
||||
/// The nearest attackable player the creaking can see.
|
||||
fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else {
|
||||
return false;
|
||||
};
|
||||
let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2);
|
||||
p.alive && !p.creative && near && m.sees(cx.w, Who::Player)
|
||||
}
|
||||
/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the
|
||||
/// nearest visible player.
|
||||
#[derive(Clone, Debug)]
|
||||
struct HuntPlayer;
|
||||
impl Goal for HuntPlayer {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
TARGET
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !is_active(m) || !sees_attackable_player(m, cx) {
|
||||
return false;
|
||||
}
|
||||
m.ai.target = Some(Who::Player);
|
||||
true
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
if m.ai.target == Some(Who::Player) {
|
||||
m.ai.target = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `CreakingModel.setupAnim`.
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Animation>) {
|
||||
p.xrot("head", s.x_rot.to_radians());
|
||||
p.yrot("head", s.y_rot.to_radians());
|
||||
let get = |n: &str| animations.get(&format!("CreakingAnimation.CREAKING_{n}"));
|
||||
if can_move(m)
|
||||
&& let Some(walk) = get("WALK")
|
||||
{
|
||||
walk.apply_walk(s.pos, s.speed, 1.0, 1.0, p);
|
||||
}
|
||||
for (state, name) in [
|
||||
(&m.anim.states[0], "ATTACK"),
|
||||
(&m.anim.states[1], "INVULNERABLE"),
|
||||
(&m.anim.states[2], "DEATH"),
|
||||
] {
|
||||
if let (Some(ms), Some(a)) = (state.millis(s.age), get(name)) {
|
||||
a.apply(ms, 1.0, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The creaking species exists in the species table.
|
||||
pub fn is_creaking(m: &Mob) -> bool {
|
||||
m.species() == Species::Creaking
|
||||
}
|
||||
@@ -731,6 +731,8 @@ pub struct MeleeAttack {
|
||||
pub until_attack: i32,
|
||||
last_check: i64,
|
||||
raise_arm: i32,
|
||||
/// Ticks between attacks (20 unless set).
|
||||
pub interval: i32,
|
||||
}
|
||||
impl MeleeAttack {
|
||||
pub fn new(speed: f64, follow_unseen: bool) -> Self {
|
||||
@@ -743,12 +745,17 @@ impl MeleeAttack {
|
||||
until_attack: 0,
|
||||
last_check: i64::MIN / 2,
|
||||
raise_arm: 0,
|
||||
interval: 20,
|
||||
}
|
||||
}
|
||||
pub fn zombie(mut self) -> Self {
|
||||
self.zombie = true;
|
||||
self
|
||||
}
|
||||
pub fn interval(mut self, ticks: i32) -> Self {
|
||||
self.interval = ticks;
|
||||
self
|
||||
}
|
||||
}
|
||||
impl Goal for MeleeAttack {
|
||||
goal_clone!();
|
||||
@@ -834,7 +841,7 @@ impl Goal for MeleeAttack {
|
||||
}
|
||||
self.until_attack = (self.until_attack - 1).max(0);
|
||||
if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) {
|
||||
self.until_attack = adjusted(true, 20);
|
||||
self.until_attack = adjusted(true, self.interval);
|
||||
m.swing();
|
||||
super::ai::do_hurt_target(m, who, cx);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ pub fn register_iron(m: &mut Mob) {
|
||||
);
|
||||
g.add(7, LookAtPlayer::new(6.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
m.ai.targets.add(1, DefendVillage);
|
||||
m.ai.targets.add(2, HurtByTarget::new());
|
||||
m.ai.targets.add(
|
||||
3,
|
||||
@@ -48,6 +49,48 @@ pub fn register_iron(m: &mut Mob) {
|
||||
NearestTarget::new(Prey::Filter(golem_prey), false).interval(5),
|
||||
);
|
||||
}
|
||||
/// `DefendVillageTargetGoal`: a player that a villager nearby has no
|
||||
/// good word for (reputation of -100 or worse) is attacked on sight.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DefendVillage;
|
||||
impl Goal for DefendVillage {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
super::goals::TARGET
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
if !p.alive || p.creative || p.spectator {
|
||||
return false;
|
||||
}
|
||||
// The box around the golem: 10 across, 8 up and down.
|
||||
let b = m.bounds().inflate(Vec3::new(10.0, 8.0, 10.0));
|
||||
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
|
||||
return false;
|
||||
}
|
||||
let bad = cx.w.others.iter().any(|s| {
|
||||
s.species == Species::Villager
|
||||
&& s.alive
|
||||
&& s.player_rep <= -100
|
||||
&& b.contains(s.position)
|
||||
&& s.position.distance_squared(m.position) <= 64.0 * 64.0
|
||||
});
|
||||
bad && m.sees(cx.w, Who::Player)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
m.target_info(cx.w).is_some_and(|t| {
|
||||
t.alive
|
||||
&& !(t.is_player && t.creative)
|
||||
&& m.position.distance_squared(t.position) <= 64.0 * 64.0
|
||||
})
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.ai.target = Some(Who::Player);
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.ai.target = None;
|
||||
}
|
||||
}
|
||||
/// `MoveTowardsTargetGoal`: close in on a target within range.
|
||||
#[derive(Clone, Debug)]
|
||||
struct MoveTowardsTarget {
|
||||
|
||||
@@ -384,8 +384,10 @@ impl CrossbowAttack {
|
||||
pub fn crossbow_goal(speed: f64, radius: f64) -> impl Goal {
|
||||
CrossbowAttack::new(speed, radius)
|
||||
}
|
||||
/// `CrossbowItem.getChargeDuration` without Quick Charge.
|
||||
const CHARGE: i32 = 25;
|
||||
/// `CrossbowItem.getChargeDuration` (25 ticks, 5 fewer per level of Quick Charge).
|
||||
pub fn charge_ticks(m: &Mob) -> i32 {
|
||||
25 - 5 * i32::from(super::raider::state(m).map_or(0, |s| s.enchant))
|
||||
}
|
||||
fn holding_crossbow(m: &Mob) -> bool {
|
||||
m.extra.main_hand.as_deref() == Some("minecraft:crossbow")
|
||||
}
|
||||
@@ -469,7 +471,7 @@ impl Goal for CrossbowAttack {
|
||||
}
|
||||
Crossbow::Charging => {
|
||||
m.extra.using_item += 1;
|
||||
if m.extra.using_item >= CHARGE {
|
||||
if m.extra.using_item >= charge_ticks(m) {
|
||||
m.extra.using_item = 0;
|
||||
m.extra.flag = false;
|
||||
self.state = Crossbow::Charged;
|
||||
@@ -534,6 +536,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
|
||||
enum ArmPose {
|
||||
Spellcasting,
|
||||
Crossed,
|
||||
Celebrating,
|
||||
Neutral,
|
||||
Attacking,
|
||||
CrossbowHold,
|
||||
@@ -554,16 +557,22 @@ fn arm_pose(m: &Mob) -> ArmPose {
|
||||
}
|
||||
}
|
||||
Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting,
|
||||
Species::Evoker if celebrating(m) => ArmPose::Celebrating,
|
||||
Species::Evoker => ArmPose::Crossed,
|
||||
_ => {
|
||||
if m.ai.aggressive {
|
||||
ArmPose::Attacking
|
||||
} else if celebrating(m) {
|
||||
ArmPose::Celebrating
|
||||
} else {
|
||||
ArmPose::Crossed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn celebrating(m: &Mob) -> bool {
|
||||
super::raider::state(m).is_some_and(|s| s.celebrating)
|
||||
}
|
||||
/// Whether the held item shows (vindicators only draw their axe when angry).
|
||||
pub fn shows_item(m: &Mob) -> bool {
|
||||
m.species() != Species::Vindicator || m.ai.aggressive
|
||||
@@ -637,8 +646,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
ArmPose::CrossbowCharge => {
|
||||
p.yrot("right_arm", -0.8);
|
||||
p.xrot("right_arm", -0.970_796_35);
|
||||
let a =
|
||||
(m.extra.using_item as f32 + s.partial).clamp(0.0, CHARGE as f32) / CHARGE as f32;
|
||||
let charge = charge_ticks(m) as f32;
|
||||
let a = (m.extra.using_item as f32 + s.partial).clamp(0.0, charge) / charge;
|
||||
p.yrot("left_arm", 0.4 + (0.85 - 0.4) * a);
|
||||
p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a);
|
||||
}
|
||||
@@ -655,6 +664,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
v[5] = z_rot;
|
||||
}
|
||||
}
|
||||
ArmPose::Celebrating => {
|
||||
for (arm, x, z_rot) in [
|
||||
("right_arm", -5.0, 2.670_354),
|
||||
("left_arm", 5.0, -PI * 0.75),
|
||||
] {
|
||||
let v = p.get(arm);
|
||||
v[2] = 0.0;
|
||||
v[0] = x;
|
||||
v[3] = (s.age * 0.6662).cos() * 0.05;
|
||||
v[4] = 0.0;
|
||||
v[5] = z_rot;
|
||||
}
|
||||
}
|
||||
ArmPose::Crossed | ArmPose::Neutral => {}
|
||||
}
|
||||
if pose == ArmPose::Crossed {
|
||||
|
||||
@@ -99,6 +99,11 @@ impl Mob {
|
||||
super::species::Baby::None => {}
|
||||
}
|
||||
}
|
||||
// Warden.getDefaultDimensions: a metre tall while digging or emerging.
|
||||
if self.kind.species == super::Species::Warden && super::warden::digging_or_emerging(self) {
|
||||
h = 1.0;
|
||||
e = 0.85;
|
||||
}
|
||||
if self.kind.species == super::Species::Pufferfish {
|
||||
let s = super::aquatic::puff_scale(self.extra.size);
|
||||
(w, h, e) = (w * s, h * s, e * s);
|
||||
@@ -437,7 +442,12 @@ impl Mob {
|
||||
let distance = (dx * dx + dy * dy + dz * dz).sqrt() as f32;
|
||||
self.previous_limb_speed = self.limb_speed;
|
||||
if self.alive() {
|
||||
let target = (distance * 4.0).min(1.0);
|
||||
// Creaking.updateWalkAnimation walks the model faster.
|
||||
let target = if self.species() == super::Species::Creaking {
|
||||
(distance * 25.0).min(3.0)
|
||||
} else {
|
||||
(distance * 4.0).min(1.0)
|
||||
};
|
||||
self.limb_speed += (target - self.limb_speed) * 0.4;
|
||||
self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 };
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,678 @@
|
||||
//! Raiders (`PatrollingMonster` and `Raider`): the patrol state every
|
||||
//! pillager, vindicator, evoker, witch and ravager carries, the long
|
||||
//! distance patrol and hold-ground goals, the ominous banner a patrol leader
|
||||
//! wears, and the saved fields.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
goals::{Cx, Goal, LOOK, MOVE, goal_clone},
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// The ominous banner is a white banner with the raid patterns; raiders wear
|
||||
/// it as their head item.
|
||||
pub const BANNER: &str = "minecraft:white_banner";
|
||||
|
||||
/// `PatrollingMonster` and `Raider` state (saved as `patrol_target`,
|
||||
/// `PatrolLeader`, `Patrolling`, `Wave`, `CanJoinRaid`, `RaidId`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct State {
|
||||
pub patrol_leader: bool,
|
||||
pub patrolling: bool,
|
||||
pub patrol_target: Option<[i32; 3]>,
|
||||
/// Goal cooldown after a failed long distance path (game time).
|
||||
pub patrol_cooldown_until: i64,
|
||||
pub wave: i32,
|
||||
pub can_join_raid: bool,
|
||||
/// The raid this raider belongs to.
|
||||
pub raid_id: Option<i32>,
|
||||
pub ticks_outside_raid: i32,
|
||||
pub celebrating: bool,
|
||||
/// The raid is active (`hasActiveRaid`); set by the game every tick.
|
||||
pub active_raid: bool,
|
||||
/// The raid is won or lost (`Raid.isOver`), lost (`isLoss`).
|
||||
pub raid_over: bool,
|
||||
pub raid_loss: bool,
|
||||
pub raid_center: [i32; 3],
|
||||
/// Standing in or beside a village (`ServerLevel.isVillage`).
|
||||
pub in_village: bool,
|
||||
/// A dropped ominous banner this raider may fetch.
|
||||
pub banner_at: Option<[f64; 3]>,
|
||||
/// Beds around the raid's centre.
|
||||
pub homes: Option<std::sync::Arc<Vec<[i32; 3]>>>,
|
||||
/// The ravager this raider rides, and (for a ravager) that it carries one.
|
||||
pub vehicle: Option<u32>,
|
||||
pub rider: bool,
|
||||
/// Quick Charge (pillager crossbows) or Sharpness (vindicator axes) from
|
||||
/// the raid's enchanting.
|
||||
pub enchant: u8,
|
||||
}
|
||||
impl State {
|
||||
/// A ravager carrying a raider (`hasControllingPassenger`).
|
||||
pub fn has_rider(&self) -> bool {
|
||||
self.rider
|
||||
}
|
||||
}
|
||||
|
||||
/// The raider species (`EntityTypeTags.RAIDERS`).
|
||||
pub fn is_raider(s: Species) -> bool {
|
||||
matches!(
|
||||
s,
|
||||
Species::Pillager
|
||||
| Species::Vindicator
|
||||
| Species::Evoker
|
||||
| Species::Witch
|
||||
| Species::Ravager
|
||||
)
|
||||
}
|
||||
/// `canBeLeader`: witches and ravagers never lead.
|
||||
pub fn can_be_leader(s: Species) -> bool {
|
||||
is_raider(s) && !matches!(s, Species::Witch | Species::Ravager)
|
||||
}
|
||||
pub fn state(m: &Mob) -> Option<&State> {
|
||||
m.extra.raider.as_deref()
|
||||
}
|
||||
pub fn state_mut(m: &mut Mob) -> &mut State {
|
||||
m.extra.raider.get_or_insert_with(Box::default)
|
||||
}
|
||||
pub fn has_active_raid(m: &Mob) -> bool {
|
||||
state(m).is_some_and(|s| s.active_raid)
|
||||
}
|
||||
/// `Raider.isCaptain`: the banner on the head of a patrol leader.
|
||||
pub fn is_captain(m: &Mob) -> bool {
|
||||
m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader)
|
||||
}
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
if !is_raider(m.species()) {
|
||||
return;
|
||||
}
|
||||
m.extra.raider = Some(Box::default());
|
||||
let species = m.species();
|
||||
m.ai.goals.add(1, ObtainBanner);
|
||||
m.ai.goals.add(3, PathfindToRaid);
|
||||
m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0));
|
||||
m.ai.goals.add(5, Celebration);
|
||||
m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595));
|
||||
// The illagers hold their ground in a patrol (Witch and Ravager do not).
|
||||
if matches!(species, Species::Pillager | Species::Vindicator) {
|
||||
m.ai.goals.add(
|
||||
if species == Species::Pillager { 2 } else { 4 },
|
||||
HoldGroundAttack::new(10.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Raid.getOminousBannerInstance`.
|
||||
pub fn ominous_banner() -> crate::items::ItemStack {
|
||||
let mut stack = crate::items::ItemStack::new(BANNER, 1);
|
||||
stack.data_mut().ominous_banner = true;
|
||||
stack
|
||||
}
|
||||
|
||||
/// `PatrollingMonster.setPatrolLeader`.
|
||||
pub fn set_patrol_leader(m: &mut Mob, leader: bool) {
|
||||
let s = state_mut(m);
|
||||
s.patrol_leader = leader;
|
||||
s.patrolling = true;
|
||||
}
|
||||
/// `PatrollingMonster.setPatrolTarget`.
|
||||
pub fn set_patrol_target(m: &mut Mob, target: [i32; 3]) {
|
||||
let s = state_mut(m);
|
||||
s.patrol_target = Some(target);
|
||||
s.patrolling = true;
|
||||
}
|
||||
/// `PatrollingMonster.findPatrolTarget`: somewhere within 500 blocks.
|
||||
pub fn find_patrol_target(m: &mut Mob) {
|
||||
let at = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
find_patrol_target_from(m, at);
|
||||
}
|
||||
/// `findPatrolTarget` from a given block position.
|
||||
pub fn find_patrol_target_from(m: &mut Mob, [x, y, z]: [i32; 3]) {
|
||||
let dx = -500 + m.random.next_int_bound(1000).unwrap_or(0);
|
||||
let dz = -500 + m.random.next_int_bound(1000).unwrap_or(0);
|
||||
let s = state_mut(m);
|
||||
s.patrol_target = Some([x + dx, y, z + dz]);
|
||||
s.patrolling = true;
|
||||
}
|
||||
/// The leader's ominous banner and its drop chance of 2.0 (always dropped).
|
||||
pub fn wear_banner(m: &mut Mob) {
|
||||
m.extra.head = Some(BANNER.into());
|
||||
}
|
||||
/// Why a mob was spawned (`EntitySpawnReason`), as far as raiders care.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Reason {
|
||||
/// Natural spawning: one leader in 17, and witches stay out of raids.
|
||||
Natural,
|
||||
/// Commands, eggs and other spawns: one leader in 17.
|
||||
Other,
|
||||
Patrol,
|
||||
Event,
|
||||
}
|
||||
/// `PatrollingMonster.finalizeSpawn` and `Raider.finalizeSpawn`: a spawn
|
||||
/// other than a patrol, raid or structure leads one time in 17, a patrol
|
||||
/// leader wears the ominous banner, and every raider but a naturally spawned
|
||||
/// witch can join a raid.
|
||||
pub fn finalize(m: &mut Mob, reason: Reason) {
|
||||
if !is_raider(m.species()) {
|
||||
return;
|
||||
}
|
||||
let roll = matches!(reason, Reason::Natural | Reason::Other);
|
||||
if roll && m.random.next_float() < 0.06 && can_be_leader(m.species()) {
|
||||
state_mut(m).patrol_leader = true;
|
||||
}
|
||||
if state_mut(m).patrol_leader {
|
||||
wear_banner(m);
|
||||
}
|
||||
let witch = m.species() == Species::Witch;
|
||||
let s = state_mut(m);
|
||||
if reason == Reason::Patrol {
|
||||
s.patrolling = true;
|
||||
}
|
||||
s.can_join_raid = !witch || reason != Reason::Natural;
|
||||
}
|
||||
|
||||
/// `PatrollingMonster.removeWhenFarAway`: patrollers and raiders in a raid
|
||||
/// are only despawned beyond 128 blocks (never inside a raid).
|
||||
pub fn keeps_alive(m: &Mob, distance_squared: f64) -> bool {
|
||||
match state(m) {
|
||||
Some(s) => s.raid_id.is_some() || s.patrolling && distance_squared <= 16384.0,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` position above (x, z).
|
||||
pub fn heightmap_pos(w: &MobWorld, x: i32, z: i32) -> [i32; 3] {
|
||||
let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT;
|
||||
let y = (crate::chunk::MIN_Y..top)
|
||||
.rev()
|
||||
.find(|&y| {
|
||||
let f = w.facts.get(w.world.block(x, y, z));
|
||||
(f.full_collision || f.fluid != crate::blocks::Fluid::None)
|
||||
&& !f.name.ends_with("leaves")
|
||||
})
|
||||
.map_or(crate::chunk::MIN_Y, |y| y + 1);
|
||||
[x, y, z]
|
||||
}
|
||||
|
||||
/// `Vec3.yRot` (the angle is in radians, and the patrol goal passes 90).
|
||||
fn y_rot(v: Vec3, angle: f32) -> Vec3 {
|
||||
let (cos, sin) = (f64::from(angle.cos()), f64::from(angle.sin()));
|
||||
Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin)
|
||||
}
|
||||
|
||||
/// `PatrollingMonster.LongDistancePatrolGoal`: walk toward the patrol target
|
||||
/// in 10 block hops (curving around it), the leader dragging its companions.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LongDistancePatrol {
|
||||
speed: f64,
|
||||
leader_speed: f64,
|
||||
}
|
||||
impl LongDistancePatrol {
|
||||
pub fn new(speed: f64, leader_speed: f64) -> Self {
|
||||
Self {
|
||||
speed,
|
||||
leader_speed,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Patrol companions within 16 blocks that are not in a raid.
|
||||
fn companions(m: &Mob, w: &MobWorld) -> Vec<u32> {
|
||||
w.others
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
s.id != m.id
|
||||
&& s.alive
|
||||
&& is_raider(s.species)
|
||||
&& !s.active_raid
|
||||
&& (s.position.x - m.position.x).abs() <= 16.0 + f64::from(m.width())
|
||||
&& (s.position.y - m.position.y).abs() <= 16.0 + f64::from(m.height())
|
||||
&& (s.position.z - m.position.z).abs() <= 16.0 + f64::from(m.width())
|
||||
})
|
||||
.map(|s| s.id)
|
||||
.collect()
|
||||
}
|
||||
impl Goal for LongDistancePatrol {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(s) = state(m) else { return false };
|
||||
cx.w.game_time >= s.patrol_cooldown_until
|
||||
&& s.patrolling
|
||||
&& m.ai.target.is_none()
|
||||
&& s.patrol_target.is_some()
|
||||
&& !s.has_rider()
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if !m.ai.nav.is_done() {
|
||||
return;
|
||||
}
|
||||
let leader = state(m).is_some_and(|s| s.patrol_leader);
|
||||
let friends = companions(m, cx.w);
|
||||
let Some(target) = state(m).and_then(|s| s.patrol_target) else {
|
||||
return;
|
||||
};
|
||||
if state(m).is_some_and(|s| s.patrolling) && friends.is_empty() {
|
||||
state_mut(m).patrolling = false;
|
||||
} else if leader && close_to_center(target, m.position, 10.0) {
|
||||
find_patrol_target(m);
|
||||
} else {
|
||||
let to = Vec3::new(
|
||||
f64::from(target[0]) + 0.5,
|
||||
f64::from(target[1]),
|
||||
f64::from(target[2]) + 0.5,
|
||||
);
|
||||
let own = m.position;
|
||||
let distance = own.subtract(to);
|
||||
let to = y_rot(distance, 90.0).scale(0.4).add_vector(to);
|
||||
let hop = to.subtract(own).normalize().scale(10.0).add_vector(own);
|
||||
let at = heightmap_pos(cx.w, hop.x.floor() as i32, hop.z.floor() as i32);
|
||||
let speed = if leader {
|
||||
self.leader_speed
|
||||
} else {
|
||||
self.speed
|
||||
};
|
||||
let to = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])];
|
||||
if !m.nav_move_to(cx.w, to, speed) {
|
||||
self.move_randomly(m, cx);
|
||||
state_mut(m).patrol_cooldown_until = cx.w.game_time + 200;
|
||||
} else if leader {
|
||||
for id in friends {
|
||||
cx.events.push(MobEvent::PatrolTarget {
|
||||
mob: id,
|
||||
target: at,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl LongDistancePatrol {
|
||||
fn move_randomly(&self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let (x, z) = (
|
||||
m.position.x.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0),
|
||||
m.position.z.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0),
|
||||
);
|
||||
let at = heightmap_pos(cx.w, x, z);
|
||||
m.nav_move_to(
|
||||
cx.w,
|
||||
[f64::from(at[0]), f64::from(at[1]), f64::from(at[2])],
|
||||
self.speed,
|
||||
)
|
||||
}
|
||||
}
|
||||
/// `Vec3i.closerToCenterThan`.
|
||||
fn close_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
|
||||
}
|
||||
|
||||
/// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when
|
||||
/// the wave has no living leader (the game finds the banner and picks it up).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ObtainBanner;
|
||||
impl Goal for ObtainBanner {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
state(m).is_some_and(|s| s.banner_at.is_some())
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
!m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some())
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(at) = state(m).and_then(|s| s.banner_at) {
|
||||
m.nav_move_to(cx.w, at, 1.15);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `PathfindToRaidGoal`: outside the village, head for the raid's centre in
|
||||
/// hops of up to 15 blocks.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PathfindToRaid;
|
||||
impl PathfindToRaid {
|
||||
fn valid(s: &State) -> bool {
|
||||
s.active_raid && !s.raid_over && !s.in_village
|
||||
}
|
||||
}
|
||||
impl Goal for PathfindToRaid {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
m.ai.target.is_none() && state(m).is_some_and(|s| !s.has_rider() && Self::valid(s))
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
state(m).is_some_and(Self::valid)
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(c) = state(m).map(|s| s.raid_center) else {
|
||||
return;
|
||||
};
|
||||
if m.ai.nav.is_done() {
|
||||
let to = [
|
||||
f64::from(c[0]) + 0.5,
|
||||
f64::from(c[1]),
|
||||
f64::from(c[2]) + 0.5,
|
||||
];
|
||||
if let Some(at) =
|
||||
m.default_random_pos_towards(cx.w, 15, 4, to, std::f64::consts::FRAC_PI_2)
|
||||
{
|
||||
m.nav_move_to(cx.w, at, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Raider.RaiderMoveThroughVillageGoal`: walk to a bed of the village not
|
||||
/// visited lately, then onwards to the next one.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MoveThroughVillage {
|
||||
speed: f64,
|
||||
distance: f64,
|
||||
poi: Option<[i32; 3]>,
|
||||
visited: Vec<[i32; 3]>,
|
||||
stuck: bool,
|
||||
}
|
||||
impl MoveThroughVillage {
|
||||
pub fn new(speed: f64, distance: f64) -> Self {
|
||||
Self {
|
||||
speed,
|
||||
distance,
|
||||
poi: None,
|
||||
visited: Vec::new(),
|
||||
stuck: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for MoveThroughVillage {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
if self.visited.len() > 2 {
|
||||
self.visited.remove(0);
|
||||
}
|
||||
let Some(s) = state(m) else { return false };
|
||||
if !(s.active_raid && !s.raid_over) || m.ai.target.is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(homes) = s.homes.clone() else {
|
||||
return false;
|
||||
};
|
||||
let near: Vec<[i32; 3]> = homes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|p| !self.visited.contains(p) && close_to_center(*p, m.position, 48.0))
|
||||
.collect();
|
||||
if near.is_empty() {
|
||||
return false;
|
||||
}
|
||||
self.poi = Some(near[m.random.next_int_bound(near.len() as i32).unwrap_or(0) as usize]);
|
||||
true
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
let Some(p) = self.poi else { return false };
|
||||
!m.ai.nav.is_done()
|
||||
&& m.ai.target.is_none()
|
||||
&& !close_to_center(p, m.position, f64::from(m.width()) + self.distance)
|
||||
&& !self.stuck
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.ai.no_action_time = 0;
|
||||
if let Some(p) = self.poi {
|
||||
m.nav_move_to(
|
||||
cx.w,
|
||||
[f64::from(p[0]), f64::from(p[1]), f64::from(p[2])],
|
||||
self.speed,
|
||||
);
|
||||
}
|
||||
self.stuck = false;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
if let Some(p) = self.poi
|
||||
&& close_to_center(p, m.position, self.distance)
|
||||
{
|
||||
self.visited.push(p);
|
||||
}
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(p) = self.poi else { return };
|
||||
if !m.ai.nav.is_done() {
|
||||
return;
|
||||
}
|
||||
let to = [
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]),
|
||||
f64::from(p[2]) + 0.5,
|
||||
];
|
||||
let next = m
|
||||
.default_random_pos_towards(cx.w, 16, 7, 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));
|
||||
match next {
|
||||
Some(at) => {
|
||||
m.nav_move_to(cx.w, at, self.speed);
|
||||
}
|
||||
None => self.stuck = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Raider.RaiderCelebration`: after a lost village, cheer and jump.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Celebration;
|
||||
impl Goal for Celebration {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
m.alive()
|
||||
&& m.ai.target.is_none()
|
||||
&& state(m).is_some_and(|s| s.raid_loss && s.raid_id.is_some())
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
state_mut(m).celebrating = true;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
state_mut(m).celebrating = false;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if m.random
|
||||
.next_int_bound(super::goals::reduced(100))
|
||||
.unwrap_or(1)
|
||||
== 0
|
||||
{
|
||||
let sound = match m.species() {
|
||||
Species::Pillager => "entity.pillager.celebrate",
|
||||
Species::Vindicator => "entity.vindicator.celebrate",
|
||||
Species::Evoker => "entity.evoker.celebrate",
|
||||
Species::Ravager => "entity.ravager.celebrate",
|
||||
_ => "entity.witch.celebrate",
|
||||
};
|
||||
m.voice(sound, cx.events);
|
||||
}
|
||||
if m.random
|
||||
.next_int_bound(super::goals::reduced(50))
|
||||
.unwrap_or(1)
|
||||
== 0
|
||||
{
|
||||
m.ai.jumping = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Raider.HoldGroundAttackGoal`: while patrolling, stand still and let the
|
||||
/// patrol shout when something shows up; attack once it comes close.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HoldGroundAttack {
|
||||
hostile_radius_sqr: f64,
|
||||
}
|
||||
impl HoldGroundAttack {
|
||||
pub fn new(radius: f64) -> Self {
|
||||
Self {
|
||||
hostile_radius_sqr: radius * radius,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Raiders within 8 blocks, nearest first (`shoutTargeting`).
|
||||
fn shout_range(m: &Mob, w: &MobWorld) -> Vec<u32> {
|
||||
w.others
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
s.id != m.id
|
||||
&& s.alive
|
||||
&& is_raider(s.species)
|
||||
&& (s.position.x - m.position.x).abs() <= 8.0 + f64::from(m.width())
|
||||
&& (s.position.y - m.position.y).abs() <= 8.0 + f64::from(m.height())
|
||||
&& (s.position.z - m.position.z).abs() <= 8.0 + f64::from(m.width())
|
||||
&& s.position.distance_squared(m.position) <= 64.0
|
||||
})
|
||||
.map(|s| s.id)
|
||||
.collect()
|
||||
}
|
||||
impl Goal for HoldGroundAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
let Some(s) = state(m) else { return false };
|
||||
s.raid_id.is_none()
|
||||
&& s.patrolling
|
||||
&& m.ai.target.is_some()
|
||||
&& !m.ai.aggressive
|
||||
&& m.ai.last_hurt_by != Some(Who::Player)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.ai.nav.stop();
|
||||
if let Some(target) = m.ai.target {
|
||||
for id in shout_range(m, cx.w) {
|
||||
cx.events.push(MobEvent::RaiderTarget {
|
||||
mob: id,
|
||||
target,
|
||||
aggressive: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(target) = m.ai.target {
|
||||
for id in shout_range(m, cx.w) {
|
||||
cx.events.push(MobEvent::RaiderTarget {
|
||||
mob: id,
|
||||
target,
|
||||
aggressive: true,
|
||||
});
|
||||
}
|
||||
m.ai.aggressive = true;
|
||||
}
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(t) = m.target_info(cx.w) else { return };
|
||||
if m.distance_sqr(t.position) > self.hostile_radius_sqr {
|
||||
m.look_at([t.position.x, t.eye_y, t.position.z]);
|
||||
if m.random.next_int_bound(50).unwrap_or(1) == 0 {
|
||||
let sound = m.kind.sounds[0];
|
||||
if !sound.is_empty() {
|
||||
m.voice(sound, cx.events);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
m.ai.aggressive = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved fields (`PatrollingMonster` and `Raider.addAdditionalSaveData`).
|
||||
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
|
||||
let Some(s) = state(m) else { return };
|
||||
match s.patrol_target {
|
||||
Some(p) => {
|
||||
map.insert("patrol_target".into(), Tag::IntArray(p.to_vec()));
|
||||
}
|
||||
None => {
|
||||
map.remove(&"patrol_target".into());
|
||||
}
|
||||
}
|
||||
map.insert("PatrolLeader".into(), Tag::Byte(i8::from(s.patrol_leader)));
|
||||
map.insert("Patrolling".into(), Tag::Byte(i8::from(s.patrolling)));
|
||||
map.insert("Wave".into(), Tag::Int(s.wave));
|
||||
map.insert("CanJoinRaid".into(), Tag::Byte(i8::from(s.can_join_raid)));
|
||||
match s.raid_id {
|
||||
Some(id) => {
|
||||
map.insert("RaidId".into(), Tag::Int(id));
|
||||
}
|
||||
None => {
|
||||
map.remove(&"RaidId".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn read_nbt(m: &mut Mob, tag: &Tag) {
|
||||
if !is_raider(m.species()) {
|
||||
return;
|
||||
}
|
||||
let int = |t: Option<&Tag>| match t {
|
||||
Some(Tag::Int(v)) => Some(*v),
|
||||
Some(Tag::Byte(v)) => Some(i32::from(*v)),
|
||||
Some(Tag::Short(v)) => Some(i32::from(*v)),
|
||||
_ => None,
|
||||
};
|
||||
let flag = |t: Option<&Tag>| int(t).unwrap_or(0) != 0;
|
||||
let s = state_mut(m);
|
||||
s.patrol_target = match tag.get("patrol_target") {
|
||||
Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]),
|
||||
_ => None,
|
||||
};
|
||||
s.patrol_leader = flag(tag.get("PatrolLeader"));
|
||||
s.patrolling = flag(tag.get("Patrolling"));
|
||||
s.wave = int(tag.get("Wave")).unwrap_or(0);
|
||||
s.can_join_raid = flag(tag.get("CanJoinRaid"));
|
||||
s.raid_id = int(tag.get("RaidId"));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn raiders_and_leaders() {
|
||||
assert!(is_raider(Species::Ravager) && is_raider(Species::Witch));
|
||||
assert!(!is_raider(Species::Zombie));
|
||||
assert!(can_be_leader(Species::Pillager) && can_be_leader(Species::Evoker));
|
||||
assert!(!can_be_leader(Species::Witch) && !can_be_leader(Species::Ravager));
|
||||
}
|
||||
#[test]
|
||||
fn long_distance_patrol_turns_by_ninety_radians() {
|
||||
// PatrollingMonster passes 90.0F to Vec3.yRot (radians).
|
||||
let v = y_rot(Vec3::new(10.0, 3.0, 0.0), 90.0);
|
||||
let (c, s) = (90f64.cos(), 90f64.sin());
|
||||
assert!((v.x - 10.0 * c).abs() < 1e-4 && (v.z + 10.0 * s).abs() < 1e-4);
|
||||
assert_eq!(v.y, 3.0);
|
||||
}
|
||||
#[test]
|
||||
fn closer_to_center_uses_block_centres() {
|
||||
let at = Vec3::new(10.5, 64.5, 10.5);
|
||||
assert!(close_to_center([10, 64, 10], at, 1.0));
|
||||
assert!(!close_to_center([30, 64, 10], at, 10.0));
|
||||
}
|
||||
}
|
||||
@@ -403,6 +403,13 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
|
||||
);
|
||||
}
|
||||
}
|
||||
S::Creaking if super::creaking::eyes_glowing(m) => push(
|
||||
&mut v,
|
||||
"creaking#eyes",
|
||||
"entity/creaking/creaking_eyes",
|
||||
white,
|
||||
true,
|
||||
),
|
||||
S::Spider | S::CaveSpider => push(
|
||||
&mut v,
|
||||
&m.kind.model_key(),
|
||||
@@ -622,7 +629,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
|
||||
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
|
||||
};
|
||||
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
|
||||
if m.death_time > 0 {
|
||||
if m.death_time > 0 && !super::creaking::tearing_down(m) {
|
||||
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
|
||||
.sqrt()
|
||||
.min(1.0);
|
||||
@@ -740,7 +747,8 @@ pub fn render_with(
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let base = base_transform(m, alpha, camera);
|
||||
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
|
||||
let overlay =
|
||||
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
|
||||
let s = anim::state(m, alpha);
|
||||
let (model_key, texture) = body(m);
|
||||
let model = m
|
||||
@@ -766,7 +774,21 @@ pub fn render_with(
|
||||
draw(part, base, &poses, *uv, *color, light, overlay, out);
|
||||
}
|
||||
held_items(m, &model, base, &poses, atlas, light, out);
|
||||
for layer in layers(m) {
|
||||
let mut all_layers = layers(m);
|
||||
// WardenRenderer: the translucent emissive layers fade with the animations.
|
||||
if m.species() == Species::Warden {
|
||||
for (model, texture, a) in super::warden::emissive_layers(m, alpha) {
|
||||
if a > 0.0 {
|
||||
all_layers.push(Layer {
|
||||
model: model.into(),
|
||||
texture: texture.into(),
|
||||
color: ((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | 0x00FF_FFFF,
|
||||
full_bright: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for layer in all_layers {
|
||||
let Some(part) = m.kind.layer(&layer.model).cloned() else {
|
||||
continue;
|
||||
};
|
||||
@@ -793,7 +815,8 @@ pub fn render_single(
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let base = base_transform(m, alpha, camera);
|
||||
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
|
||||
let overlay =
|
||||
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
|
||||
let s = anim::state(m, alpha);
|
||||
let model = m.kind.model.clone();
|
||||
let mut poses = Poses::new(&model);
|
||||
|
||||
@@ -292,6 +292,8 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
|
||||
Climate::Cold => 2,
|
||||
};
|
||||
match m.species() {
|
||||
// Warden.finalizeSpawn: a minute before it digs back down.
|
||||
S::Warden => super::warden::finalize(m, false, &mut Vec::new()),
|
||||
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,
|
||||
@@ -299,7 +301,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
|
||||
S::Wolf => m.extra.variant = biome.wolf,
|
||||
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
|
||||
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => {
|
||||
// Zombie.finalizeSpawn: 5% babies (normal difficulty).
|
||||
// Zombie.finalizeSpawn: pick up loot 55% of the time (scaled by
|
||||
// difficulty), 5% babies (normal difficulty).
|
||||
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
|
||||
if m.random.next_float() < 0.05 {
|
||||
m.extra.age = i32::MIN / 2;
|
||||
}
|
||||
@@ -348,8 +352,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
|
||||
}
|
||||
// AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on
|
||||
// registration).
|
||||
S::Skeleton | S::Stray | S::Bogged | S::Parched => populate_armor(m, difficulty),
|
||||
S::Pillager => m.extra.main_hand = Some("minecraft:crossbow".into()),
|
||||
S::Skeleton | S::Stray | S::Bogged | S::Parched => {
|
||||
populate_armor(m, difficulty);
|
||||
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
|
||||
}
|
||||
S::Pillager => {
|
||||
m.extra.main_hand = Some("minecraft:crossbow".into());
|
||||
m.extra.pick_up_loot = true;
|
||||
}
|
||||
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => {
|
||||
super::equine::finalize(m)
|
||||
}
|
||||
@@ -358,6 +368,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
|
||||
// Piglin.createSpawnWeapon: half crossbows, half golden swords, and
|
||||
// each piece of golden armour one time in ten.
|
||||
S::Piglin if !m.is_baby() => {
|
||||
m.extra.pick_up_loot = true;
|
||||
for i in 0..4 {
|
||||
if m.random.next_float() < 0.1 {
|
||||
let (slot, piece) = match i {
|
||||
@@ -379,11 +390,16 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
S::PiglinBrute => m.extra.main_hand = Some("minecraft:golden_axe".into()),
|
||||
S::PiglinBrute => {
|
||||
m.extra.main_hand = Some("minecraft:golden_axe".into());
|
||||
m.extra.pick_up_loot = true;
|
||||
}
|
||||
S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()),
|
||||
S::Villager => {
|
||||
m.extra.variant = villager_type(biome);
|
||||
m.extra.pick_up_loot = true;
|
||||
}
|
||||
S::Fox | S::Panda | S::Dolphin => m.extra.pick_up_loot = true,
|
||||
S::TropicalFish => super::aquatic::finalize(m),
|
||||
S::Slime | S::MagmaCube => super::cube::finalize(m),
|
||||
_ => {}
|
||||
|
||||
@@ -83,6 +83,8 @@ pub enum Species {
|
||||
Wither,
|
||||
Camel,
|
||||
Allay,
|
||||
Warden,
|
||||
Creaking,
|
||||
}
|
||||
/// Baby bounding boxes (each class's BABY_DIMENSIONS).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -914,6 +916,20 @@ pub const ALL: &[Def] = &[
|
||||
None,
|
||||
Baby::None
|
||||
),
|
||||
def!(
|
||||
Creaking,
|
||||
"creaking",
|
||||
"creaking#main",
|
||||
"entity/creaking/creaking",
|
||||
A::Creaking,
|
||||
[
|
||||
"entity.creaking.ambient",
|
||||
"entity.generic.hurt",
|
||||
"entity.creaking.death"
|
||||
],
|
||||
Some("entity.creaking.step"),
|
||||
Baby::None
|
||||
),
|
||||
def!(
|
||||
Camel,
|
||||
"camel",
|
||||
@@ -1148,6 +1164,20 @@ pub const ALL: &[Def] = &[
|
||||
Some("entity.strider.step"),
|
||||
Baby::Abs(0.45, 0.85, 0.4375)
|
||||
),
|
||||
def!(
|
||||
Warden,
|
||||
"warden",
|
||||
"warden#main",
|
||||
"entity/warden/warden",
|
||||
A::Warden,
|
||||
[
|
||||
"entity.warden.ambient",
|
||||
"entity.warden.hurt",
|
||||
"entity.warden.death"
|
||||
],
|
||||
None,
|
||||
Baby::None
|
||||
),
|
||||
];
|
||||
pub fn def(s: Species) -> &'static Def {
|
||||
ALL.iter().find(|d| d.species == s).unwrap_or(&ALL[0])
|
||||
@@ -1356,6 +1386,7 @@ impl Def {
|
||||
| S::Vex
|
||||
| S::Ravager
|
||||
| S::Wither
|
||||
| S::Warden
|
||||
)
|
||||
}
|
||||
/// The item tag Animal.isFood tests.
|
||||
|
||||
@@ -5,13 +5,14 @@
|
||||
//! (work and restock at the job site, meet at the bell, sleep in the bed),
|
||||
//! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
anim::{Poses, State},
|
||||
goals::{
|
||||
Avoid, AvoidEntity, Cx, Float, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll,
|
||||
goal_clone,
|
||||
Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround,
|
||||
Stroll, goal_clone,
|
||||
},
|
||||
};
|
||||
use crate::items::ItemStack;
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::{collections::HashMap, f32::consts::PI};
|
||||
|
||||
@@ -74,6 +75,10 @@ pub fn register(m: &mut Mob) {
|
||||
AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75),
|
||||
);
|
||||
g.add(1, Panic::new(0.75));
|
||||
g.add(2, RaidBehavior::default());
|
||||
g.add(3, Social::default());
|
||||
g.add(0, GolemCall);
|
||||
g.add(3, GiftToHero::default());
|
||||
g.add(3, JobSite::default());
|
||||
g.add(3, AcquireHome::default());
|
||||
g.add(4, Schedule::default());
|
||||
@@ -456,6 +461,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
|
||||
_ => 4,
|
||||
};
|
||||
m.nav_stop();
|
||||
ext_mut(m).last_slept = Some(w.game_time);
|
||||
m.velocity = horizon_core::geometry::Vec3::ZERO;
|
||||
m.position = horizon_core::geometry::Vec3::new(
|
||||
f64::from(p[0]) + 0.5,
|
||||
@@ -516,6 +522,23 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
if m.extra.ints[0] > 0 {
|
||||
m.extra.ints[0] -= 1;
|
||||
}
|
||||
if m.species() == Species::Villager {
|
||||
let now = w.game_time;
|
||||
let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0
|
||||
&& w.others.iter().any(|s| {
|
||||
s.species == Species::IronGolem
|
||||
&& s.alive
|
||||
&& (s.position.x - m.position.x).abs() <= 16.0
|
||||
&& (s.position.y - m.position.y).abs() <= 16.0
|
||||
&& (s.position.z - m.position.z).abs() <= 16.0
|
||||
});
|
||||
let e = ext_mut(m);
|
||||
// Villager.maybeDecayGossip and the GolemSensor (every 200 ticks).
|
||||
e.maybe_decay(now);
|
||||
if seen_golem {
|
||||
e.golem_until = now + 599;
|
||||
}
|
||||
}
|
||||
// WakeUp / LivingEntity.hurt: morning, a hit or a missing bed.
|
||||
if sleeping(m) {
|
||||
let bed_gone = m
|
||||
@@ -594,3 +617,759 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
p.yrot("right_leg", 0.0);
|
||||
p.yrot("left_leg", 0.0);
|
||||
}
|
||||
|
||||
// ---- Raids: the raid activities and the gift for a hero.
|
||||
|
||||
pub const RAID_NONE: u8 = 0;
|
||||
/// A raid is near but no wave is on (`Activity.PRE_RAID`).
|
||||
pub const PRE_RAID: u8 = 1;
|
||||
/// A wave is on (`Activity.RAID`).
|
||||
pub const RAID: u8 = 2;
|
||||
/// The raid was won: the villagers celebrate.
|
||||
pub const RAID_VICTORY: u8 = 3;
|
||||
|
||||
/// Villager state beyond `Extra`'s scratch fields.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ext {
|
||||
/// Which raid package the villager follows.
|
||||
pub raid: u8,
|
||||
/// What the villager remembers of players (`gossips`).
|
||||
pub gossips: crate::gossip::Gossips,
|
||||
pub last_gossip_time: i64,
|
||||
pub last_gossip_decay: i64,
|
||||
/// `foodLevel`: eaten but not yet digested, in food points.
|
||||
pub food_level: i32,
|
||||
/// The eight-slot inventory (`InventoryCarrier`).
|
||||
pub inventory: Vec<ItemStack>,
|
||||
/// `LAST_SLEPT` memory.
|
||||
pub last_slept: Option<i64>,
|
||||
/// `GOLEM_DETECTED_RECENTLY` expires at this game time.
|
||||
pub golem_until: i64,
|
||||
/// The `last_hurt_by_time` of the player's hit already counted.
|
||||
pub hurt_seen: i32,
|
||||
}
|
||||
pub fn ext(m: &Mob) -> Option<&Ext> {
|
||||
m.extra.villager.as_deref()
|
||||
}
|
||||
pub fn ext_mut(m: &mut Mob) -> &mut Ext {
|
||||
m.extra.villager.get_or_insert_with(Box::default)
|
||||
}
|
||||
fn raid_status(m: &Mob) -> u8 {
|
||||
ext(m).map_or(RAID_NONE, |e| e.raid)
|
||||
}
|
||||
|
||||
/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at
|
||||
/// home (`LocateHidingPlace`), before one they gather at the bell and ring it
|
||||
/// (`RingBell`), and after a victory they look for the sky to celebrate
|
||||
/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct RaidBehavior {
|
||||
next_move: i32,
|
||||
}
|
||||
impl Goal for RaidBehavior {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
raid_status(m) != RAID_NONE && !sleeping(m)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.can_use(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
self.next_move = 0;
|
||||
m.nav_stop();
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.nav_stop();
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.next_move -= 1;
|
||||
let p = m.position;
|
||||
match raid_status(m) {
|
||||
RAID => {
|
||||
// LocateHidingPlace(24, 0.7, 1): back to the bed.
|
||||
let Some(home) = m.extra.bed else { return };
|
||||
if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
|
||||
if distance(m, home) <= 24.0 {
|
||||
m.nav_move_to(cx.w, center(home), 0.7);
|
||||
}
|
||||
self.next_move = 40;
|
||||
}
|
||||
}
|
||||
PRE_RAID => {
|
||||
// RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75).
|
||||
let Some(bell) = m.extra.meeting else { return };
|
||||
if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
|
||||
m.nav_move_to(cx.w, center(bell), 0.75);
|
||||
self.next_move = 40;
|
||||
}
|
||||
if distance(m, bell) < 3.0
|
||||
&& m.random.next_float() > 0.95
|
||||
&& cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell"
|
||||
{
|
||||
cx.events.push(MobEvent::SoundId(
|
||||
"minecraft:block.bell.use".into(),
|
||||
center(bell),
|
||||
2.0,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
}
|
||||
RAID_VICTORY => {
|
||||
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
|
||||
if cx.w.can_see_sky(x, y, z) {
|
||||
// CelebrateVillagersSurvivedRaid.tick.
|
||||
if m.random.next_int_bound(100).unwrap_or(1) == 0 {
|
||||
m.voice("entity.villager.celebrate", cx.events);
|
||||
}
|
||||
if m.random.next_int_bound(200).unwrap_or(1) == 0 {
|
||||
let color = m.random.next_int_bound(16).unwrap_or(0) as usize;
|
||||
let flight = m.random.next_int_bound(3).unwrap_or(0) as u8;
|
||||
cx.events.push(MobEvent::Firework {
|
||||
at: [p.x, m.eye_y(), p.z],
|
||||
color,
|
||||
flight,
|
||||
});
|
||||
}
|
||||
m.nav_stop();
|
||||
} else if self.next_move <= 0 || m.ai.nav.is_done() {
|
||||
// MoveToSkySeeingSpot: a random spot with a view of the sky.
|
||||
for _ in 0..5 {
|
||||
if let Some(at) = m.land_random_pos(cx.w, 15, 7)
|
||||
&& cx.w.can_see_sky(
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
at[2].floor() as i32,
|
||||
)
|
||||
{
|
||||
m.nav_move_to(cx.w, at, 0.5);
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.next_move = 40;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and
|
||||
/// throws a gift of its profession, every so often.
|
||||
#[derive(Clone, Debug)]
|
||||
struct GiftToHero {
|
||||
until_next: i32,
|
||||
started: i64,
|
||||
given: bool,
|
||||
}
|
||||
impl Default for GiftToHero {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
until_next: 600,
|
||||
started: 0,
|
||||
given: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`).
|
||||
fn gift_table(m: &Mob) -> String {
|
||||
if m.is_baby() {
|
||||
return "minecraft:gameplay/hero_of_the_village/baby_gift".into();
|
||||
}
|
||||
let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15];
|
||||
let name = match profession {
|
||||
"none" | "nitwit" => "unemployed",
|
||||
other => other,
|
||||
};
|
||||
format!("minecraft:gameplay/hero_of_the_village/{name}_gift")
|
||||
}
|
||||
fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
p.hero
|
||||
&& p.alive
|
||||
&& !p.spectator
|
||||
&& m.position.distance_squared(p.position) <= 16.0 * 16.0
|
||||
&& m.sees(cx.w, Who::Player)
|
||||
}
|
||||
impl Goal for GiftToHero {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !hero_in_view(m, cx) || sleeping(m) {
|
||||
return false;
|
||||
}
|
||||
if self.until_next > 0 {
|
||||
self.until_next -= 1;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
hero_in_view(m, cx) && !self.given
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.given = false;
|
||||
self.started = cx.w.game_time;
|
||||
if let Some(p) = &cx.w.player {
|
||||
m.look_at(p.eye);
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0);
|
||||
m.nav_stop();
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(p) = cx.w.player.clone() else { return };
|
||||
m.look_at(p.eye);
|
||||
let near = m.position.distance_squared(p.position) < 25.0;
|
||||
if near {
|
||||
if cx.w.game_time - self.started > 20 {
|
||||
cx.events.push(MobEvent::ThrowGift {
|
||||
table: gift_table(m),
|
||||
from: [m.position.x, m.eye_y() - 0.3, m.position.z],
|
||||
to: [p.position.x, p.position.y, p.position.z],
|
||||
});
|
||||
self.given = true;
|
||||
}
|
||||
m.nav_stop();
|
||||
} else if m.ai.nav.is_done() {
|
||||
m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Gossip, food, breeding and golems.
|
||||
|
||||
/// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`).
|
||||
pub fn food_points(item: &str) -> i32 {
|
||||
match item {
|
||||
"minecraft:bread" => 4,
|
||||
"minecraft:potato" | "minecraft:carrot" | "minecraft:beetroot" => 1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
/// The farmer's `requestedItems`.
|
||||
pub fn farmer_items() -> &'static [&'static str] {
|
||||
&[
|
||||
"minecraft:bread",
|
||||
"minecraft:potato",
|
||||
"minecraft:carrot",
|
||||
"minecraft:wheat",
|
||||
"minecraft:wheat_seeds",
|
||||
"minecraft:beetroot",
|
||||
"minecraft:beetroot_seeds",
|
||||
"minecraft:torchflower_seeds",
|
||||
"minecraft:pitcher_pod",
|
||||
]
|
||||
}
|
||||
/// A villager's `requestedItems` by profession.
|
||||
pub fn requested_items(m: &Mob) -> &'static [&'static str] {
|
||||
if super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer" {
|
||||
farmer_items()
|
||||
} else {
|
||||
&[]
|
||||
}
|
||||
}
|
||||
pub fn is_farmer(m: &Mob) -> bool {
|
||||
super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer"
|
||||
}
|
||||
/// `SimpleContainer(8)`: stacks the villager carries.
|
||||
const INVENTORY_SLOTS: usize = 8;
|
||||
|
||||
impl Ext {
|
||||
/// `countFoodPointsInInventory`.
|
||||
pub fn food_in_inventory(&self) -> i32 {
|
||||
self.inventory
|
||||
.iter()
|
||||
.map(|s| food_points(&s.item) * s.count as i32)
|
||||
.sum()
|
||||
}
|
||||
/// `hasExcessFood` and `wantsMoreFood`.
|
||||
pub fn has_excess_food(&self) -> bool {
|
||||
self.food_in_inventory() >= 24
|
||||
}
|
||||
pub fn wants_more_food(&self) -> bool {
|
||||
self.food_in_inventory() < 12
|
||||
}
|
||||
fn hungry(&self) -> bool {
|
||||
self.food_level < 12
|
||||
}
|
||||
/// `Villager.eatAndDigestFood`: eat until full, then digest 12 points.
|
||||
pub fn eat_and_digest(&mut self) {
|
||||
if self.hungry() {
|
||||
let mut slot = 0;
|
||||
while slot < self.inventory.len() && self.hungry() {
|
||||
let points = food_points(&self.inventory[slot].item);
|
||||
if points > 0 {
|
||||
while self.inventory[slot].count > 0 && self.hungry() {
|
||||
self.food_level += points;
|
||||
self.inventory[slot].count -= 1;
|
||||
}
|
||||
if self.inventory[slot].count == 0 {
|
||||
self.inventory.remove(slot);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
slot += 1;
|
||||
}
|
||||
}
|
||||
self.food_level -= 12;
|
||||
}
|
||||
/// Whether the stack fits (`SimpleContainer.canAddItem`).
|
||||
pub fn can_add(&self, stack: &ItemStack, max_stack: u32) -> bool {
|
||||
self.inventory.len() < INVENTORY_SLOTS
|
||||
|| self
|
||||
.inventory
|
||||
.iter()
|
||||
.any(|s| s.same_item_same_components(stack) && s.count < max_stack)
|
||||
}
|
||||
/// `SimpleContainer.addItem`: merge into stacks, then free slots; the
|
||||
/// part that did not fit is returned.
|
||||
pub fn add_item(&mut self, mut stack: ItemStack, max_stack: u32) -> Option<ItemStack> {
|
||||
for s in &mut self.inventory {
|
||||
if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max_stack {
|
||||
let n = (max_stack - s.count).min(stack.count);
|
||||
s.count += n;
|
||||
stack.count -= n;
|
||||
}
|
||||
}
|
||||
while stack.count > 0 && self.inventory.len() < INVENTORY_SLOTS {
|
||||
let n = stack.count.min(max_stack);
|
||||
self.inventory.push(ItemStack {
|
||||
count: n,
|
||||
..stack.clone()
|
||||
});
|
||||
stack.count -= n;
|
||||
}
|
||||
(stack.count > 0).then_some(stack)
|
||||
}
|
||||
pub fn count_item(&self, item: &str) -> u32 {
|
||||
self.inventory
|
||||
.iter()
|
||||
.filter(|s| &*s.item == item)
|
||||
.map(|s| s.count)
|
||||
.sum()
|
||||
}
|
||||
/// `TradeWithVillager.throwHalfStack`: the half of a big matching stack
|
||||
/// (or whatever is over 24) leaves the inventory.
|
||||
pub fn take_half_stack(
|
||||
&mut self,
|
||||
wanted: impl Fn(&ItemStack) -> bool,
|
||||
max_stack: impl Fn(&str) -> u32,
|
||||
) -> Option<ItemStack> {
|
||||
for i in 0..self.inventory.len() {
|
||||
let s = &self.inventory[i];
|
||||
if s.count == 0 || !wanted(s) {
|
||||
continue;
|
||||
}
|
||||
let count = if s.count > max_stack(&s.item) / 2 {
|
||||
s.count / 2
|
||||
} else if s.count > 24 {
|
||||
s.count - 24
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let taken = ItemStack { count, ..s.clone() };
|
||||
self.inventory[i].count -= count;
|
||||
if self.inventory[i].count == 0 {
|
||||
self.inventory.remove(i);
|
||||
}
|
||||
return Some(taken);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `Villager.wantsToSpawnGolem`: slept within the last day and no golem
|
||||
/// seen lately.
|
||||
pub fn wants_golem(&self, now: i64) -> bool {
|
||||
self.last_slept.is_some_and(|t| now - t < 24000) && now >= self.golem_until
|
||||
}
|
||||
/// `maybeDecayGossip`: once a day.
|
||||
pub fn maybe_decay(&mut self, now: i64) {
|
||||
if self.last_gossip_decay == 0 {
|
||||
self.last_gossip_decay = now;
|
||||
} else if now >= self.last_gossip_decay + 24000 {
|
||||
self.gossips.decay();
|
||||
self.last_gossip_decay = now;
|
||||
}
|
||||
}
|
||||
/// `Villager.gossip` timing: hearing again waits 1200 ticks.
|
||||
pub fn can_gossip(&self, now: i64) -> bool {
|
||||
now < self.last_gossip_time || now >= self.last_gossip_time + 1200
|
||||
}
|
||||
}
|
||||
/// `Villager.canBreed`: enough food, awake and an adult.
|
||||
pub fn can_breed(m: &Mob) -> bool {
|
||||
m.species() == Species::Villager
|
||||
&& m.extra.age == 0
|
||||
&& !sleeping(m)
|
||||
&& ext(m).map_or(0, |e| e.food_level + e.food_in_inventory()) >= 12
|
||||
}
|
||||
|
||||
/// The saved fields (`FoodLevel`, `Gossips`, `LastGossipDecay`, `Inventory`
|
||||
/// and the sleep and golem memories).
|
||||
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
|
||||
use horizon_world::nbt::Tag;
|
||||
let Some(e) = ext(m) else { return };
|
||||
map.insert(
|
||||
"FoodLevel".into(),
|
||||
Tag::Byte(e.food_level.clamp(-128, 127) as i8),
|
||||
);
|
||||
map.insert("Gossips".into(), e.gossips.to_nbt());
|
||||
map.insert("LastGossipDecay".into(), Tag::Long(e.last_gossip_decay));
|
||||
map.insert(
|
||||
"Inventory".into(),
|
||||
Tag::List(e.inventory.iter().map(crate::save::item_to_nbt).collect()),
|
||||
);
|
||||
}
|
||||
/// The memories of `Brain.memories` the villager keeps besides positions.
|
||||
pub fn write_memories(m: &Mob, memories: &mut Vec<(&'static str, horizon_world::nbt::Tag)>) {
|
||||
use horizon_world::nbt::Tag;
|
||||
let Some(e) = ext(m) else { return };
|
||||
if let Some(t) = e.last_slept {
|
||||
memories.push((
|
||||
"minecraft:last_slept",
|
||||
Tag::compound([("value", Tag::Long(t))]),
|
||||
));
|
||||
}
|
||||
}
|
||||
pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
|
||||
use horizon_world::nbt::Tag;
|
||||
let int = |t: Option<&Tag>| match t {
|
||||
Some(Tag::Int(v)) => Some(i64::from(*v)),
|
||||
Some(Tag::Byte(v)) => Some(i64::from(*v)),
|
||||
Some(Tag::Short(v)) => Some(i64::from(*v)),
|
||||
Some(Tag::Long(v)) => Some(*v),
|
||||
_ => None,
|
||||
};
|
||||
let last_slept = int(tag
|
||||
.get("Brain")
|
||||
.and_then(|b| b.get("memories"))
|
||||
.and_then(|b| b.get("minecraft:last_slept"))
|
||||
.and_then(|j| j.get("value")));
|
||||
let e = ext_mut(m);
|
||||
e.food_level = int(tag.get("FoodLevel")).unwrap_or(0) as i32;
|
||||
e.gossips = tag
|
||||
.get("Gossips")
|
||||
.map(crate::gossip::Gossips::from_nbt)
|
||||
.unwrap_or_default();
|
||||
e.last_gossip_decay = int(tag.get("LastGossipDecay")).unwrap_or(0);
|
||||
e.last_slept = last_slept;
|
||||
if let Some(Tag::List(items)) = tag.get("Inventory") {
|
||||
e.inventory = items
|
||||
.iter()
|
||||
.filter_map(crate::save::item_from_nbt)
|
||||
.take(INVENTORY_SLOTS)
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while
|
||||
/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap
|
||||
/// gossip and food, and make a baby with a willing partner.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Social {
|
||||
target: Option<u32>,
|
||||
breed: bool,
|
||||
ticks: i32,
|
||||
cooldown: i32,
|
||||
birth_at: i64,
|
||||
}
|
||||
impl Social {
|
||||
fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let breedable = can_breed(m);
|
||||
let id = m.id;
|
||||
let nearest =
|
||||
cx.w.nearby(m.position, 8.0, move |s| {
|
||||
s.species == Species::Villager && s.id != id
|
||||
})
|
||||
.filter(|s| m.position.distance_squared(s.position) <= 64.0)
|
||||
.map(|s| (s.id, s.in_love))
|
||||
.collect::<Vec<_>>();
|
||||
let visible: Vec<(u32, bool)> = nearest
|
||||
.into_iter()
|
||||
.filter(|(i, _)| m.sees(cx.w, Who::Mob(*i)))
|
||||
.collect();
|
||||
let Some(&(target, partner_willing)) = visible.first() else {
|
||||
return false;
|
||||
};
|
||||
// RunOne weights: interact 2, breed 1 (when both are willing).
|
||||
let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0;
|
||||
self.target = Some(target);
|
||||
self.breed = breed;
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Goal for Social {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE {
|
||||
return false;
|
||||
}
|
||||
if self.cooldown > 0 {
|
||||
self.cooldown -= 1;
|
||||
return false;
|
||||
}
|
||||
match activity(m, cx.w.day_time) {
|
||||
Activity::Idle => self.pick(m, cx),
|
||||
Activity::Meet => {
|
||||
// SocializeAtBell: one tick in a hundred, near the bell.
|
||||
let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0);
|
||||
near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && {
|
||||
let ok = self.pick(m, cx);
|
||||
self.breed = false;
|
||||
ok
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(t) = self.target else { return false };
|
||||
let Some(s) = cx.w.seen(t) else { return false };
|
||||
if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE {
|
||||
return false;
|
||||
}
|
||||
if self.breed {
|
||||
self.ticks < 350 && can_breed(m) && s.in_love
|
||||
} else {
|
||||
self.ticks < 60
|
||||
}
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks = 0;
|
||||
self.birth_at = 0;
|
||||
if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) {
|
||||
let at = [s.position.x, s.position.y, s.position.z];
|
||||
m.nav_move_to(cx.w, at, 0.5);
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.nav_stop();
|
||||
self.target = None;
|
||||
self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks += 1;
|
||||
let Some(t) = self.target else { return };
|
||||
let Some(s) = cx.w.seen(t) else { return };
|
||||
let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y);
|
||||
m.look_at([at[0], eye, at[2]]);
|
||||
if m.position.distance_squared(s.position) > 5.0 {
|
||||
if m.ai.nav.is_done() && self.ticks % 10 == 1 {
|
||||
m.nav_move_to(cx.w, at, 0.5);
|
||||
}
|
||||
return;
|
||||
}
|
||||
m.nav_stop();
|
||||
if !self.breed {
|
||||
cx.events.push(MobEvent::VillagerMeet {
|
||||
mob: m.id,
|
||||
other: t,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let now = cx.w.game_time;
|
||||
if self.birth_at == 0 {
|
||||
self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
|
||||
}
|
||||
if now >= self.birth_at {
|
||||
cx.events.push(MobEvent::VillagerBirth {
|
||||
parent: m.id,
|
||||
partner: t,
|
||||
});
|
||||
self.ticks = 1000;
|
||||
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
|
||||
for p in [m.position, s.position] {
|
||||
cx.events.push(MobEvent::Particles {
|
||||
kind: "heart",
|
||||
at: [p.x, p.y + 1.8, p.z],
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem
|
||||
/// every five seconds.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct GolemCall;
|
||||
/// `VillagerHostilesSensor`: how close each hostile must be to scare.
|
||||
fn hostile_range(s: Species) -> f64 {
|
||||
match s {
|
||||
Species::Drowned
|
||||
| Species::Husk
|
||||
| Species::Vex
|
||||
| Species::Zombie
|
||||
| Species::ZombieVillager => 8.0,
|
||||
Species::Evoker | Species::Ravager => 12.0,
|
||||
Species::Pillager => 15.0,
|
||||
Species::Vindicator | Species::Zoglin => 10.0,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
fn frightened(m: &Mob, cx: &Cx) -> bool {
|
||||
// HURT_BY lasts 100 ticks.
|
||||
let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100;
|
||||
hurt || cx.w.others.iter().any(|s| {
|
||||
s.alive && {
|
||||
let r = hostile_range(s.species);
|
||||
r > 0.0 && s.position.distance_squared(m.position) <= r * r
|
||||
}
|
||||
})
|
||||
}
|
||||
impl Goal for GolemCall {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
!m.is_baby() && frightened(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.can_use(m, cx)
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if cx.w.game_time % 100 == 0 {
|
||||
cx.events.push(MobEvent::GolemCheck {
|
||||
mob: m.id,
|
||||
needed: 3,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stack(item: &str, count: u32) -> ItemStack {
|
||||
ItemStack::new(item, count)
|
||||
}
|
||||
#[test]
|
||||
fn eating_fills_the_food_level_then_digests() {
|
||||
let mut e = Ext {
|
||||
inventory: vec![stack("minecraft:bread", 3), stack("minecraft:carrot", 5)],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(e.food_in_inventory(), 17);
|
||||
// Hungry below 12: three breads fill it exactly, then 12 digest away.
|
||||
e.eat_and_digest();
|
||||
assert_eq!(e.food_level, 0);
|
||||
assert_eq!(e.inventory.len(), 1);
|
||||
assert_eq!(e.inventory[0].count, 5);
|
||||
// Five carrots are not enough to be full again, and are all eaten.
|
||||
e.eat_and_digest();
|
||||
assert_eq!(e.food_level, 5 - 12);
|
||||
assert!(e.inventory.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn willingness_to_breed_needs_twelve_food_points() {
|
||||
let mut e = Ext::default();
|
||||
assert!(e.wants_more_food() && !e.has_excess_food());
|
||||
e.inventory.push(stack("minecraft:bread", 6));
|
||||
assert!(e.has_excess_food() && !e.wants_more_food());
|
||||
e.food_level = -5;
|
||||
assert_eq!(e.food_level + e.food_in_inventory(), 19);
|
||||
}
|
||||
#[test]
|
||||
fn the_inventory_has_eight_stacking_slots() {
|
||||
let mut e = Ext::default();
|
||||
assert!(e.add_item(stack("minecraft:bread", 100), 64).is_none());
|
||||
assert_eq!(e.inventory.len(), 2);
|
||||
assert_eq!(e.inventory[0].count, 64);
|
||||
for i in 0..6 {
|
||||
assert!(
|
||||
e.add_item(stack(&format!("minecraft:item_{i}"), 1), 64)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(e.inventory.len(), 8);
|
||||
// Full: another kind is refused, the same kind tops up the stack.
|
||||
assert!(!e.can_add(&stack("minecraft:stick", 1), 64));
|
||||
let left = e.add_item(stack("minecraft:bread", 40), 64).unwrap();
|
||||
assert_eq!(left.count, 40 - 28);
|
||||
}
|
||||
#[test]
|
||||
fn half_stacks_are_thrown() {
|
||||
let mut e = Ext {
|
||||
inventory: vec![
|
||||
stack("minecraft:bread", 10),
|
||||
stack("minecraft:wheat", 50),
|
||||
stack("minecraft:wheat", 20),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let max = |_: &str| 64;
|
||||
// Bread is under half a stack and under 24: nothing.
|
||||
assert!(
|
||||
e.take_half_stack(|s| &*s.item == "minecraft:bread", max)
|
||||
.is_none()
|
||||
);
|
||||
// 50 wheat is over half a stack: 25 go.
|
||||
let t = e
|
||||
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
|
||||
.unwrap();
|
||||
assert_eq!(t.count, 25);
|
||||
assert_eq!(e.count_item("minecraft:wheat"), 25 + 20);
|
||||
}
|
||||
#[test]
|
||||
fn golems_need_sleep_and_no_golem_nearby() {
|
||||
let mut e = Ext::default();
|
||||
assert!(!e.wants_golem(100));
|
||||
e.last_slept = Some(0);
|
||||
assert!(e.wants_golem(23_999));
|
||||
assert!(!e.wants_golem(24_000));
|
||||
e.last_slept = Some(1000);
|
||||
e.golem_until = 2000 + 599;
|
||||
assert!(!e.wants_golem(2500));
|
||||
assert!(e.wants_golem(2700));
|
||||
}
|
||||
#[test]
|
||||
fn gossip_decays_once_a_day_and_heard_gossip_waits() {
|
||||
let player = [1, 2, 3, 4];
|
||||
let mut e = Ext::default();
|
||||
e.gossips
|
||||
.add(player, crate::gossip::GossipType::MajorNegative, 25);
|
||||
e.maybe_decay(100);
|
||||
assert_eq!(e.last_gossip_decay, 100);
|
||||
e.maybe_decay(24_099);
|
||||
assert_eq!(
|
||||
e.gossips
|
||||
.get(player, crate::gossip::GossipType::MajorNegative),
|
||||
25
|
||||
);
|
||||
e.maybe_decay(24_100);
|
||||
assert_eq!(
|
||||
e.gossips
|
||||
.get(player, crate::gossip::GossipType::MajorNegative),
|
||||
15
|
||||
);
|
||||
e.last_gossip_time = 5000;
|
||||
assert!(!e.can_gossip(5100));
|
||||
assert!(e.can_gossip(6200));
|
||||
assert!(e.can_gossip(4000));
|
||||
}
|
||||
#[test]
|
||||
fn villager_food_values() {
|
||||
assert_eq!(food_points("minecraft:bread"), 4);
|
||||
assert_eq!(food_points("minecraft:beetroot"), 1);
|
||||
assert_eq!(food_points("minecraft:apple"), 0);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,6 +19,18 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(3, LookAtPlayer::new(8.0));
|
||||
g.add(3, RandomLookAround::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new());
|
||||
// NearestHealableRaiderTargetGoal: in a raid, go and heal the other raiders.
|
||||
m.ai.targets.add(
|
||||
2,
|
||||
NearestTarget::new(
|
||||
super::goals::Prey::Filter(|s| {
|
||||
super::raider::is_raider(s.species) && s.species != Species::Witch
|
||||
}),
|
||||
true,
|
||||
)
|
||||
.interval(1)
|
||||
.when(|m, _| super::raider::has_active_raid(m)),
|
||||
);
|
||||
m.ai.targets
|
||||
.add(3, NearestTarget::player(true).interval(10));
|
||||
}
|
||||
@@ -129,7 +141,23 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
})
|
||||
.map_or(20.0, |s| s.health)
|
||||
};
|
||||
let (effect, ticks, amplifier) = if dist >= 8.0 {
|
||||
// A raider target is healed instead: Healing when nearly dead, else
|
||||
// Regeneration, and the witch drops the target afterwards.
|
||||
let heals = match who {
|
||||
Who::Mob(id) => {
|
||||
cx.w.seen(id)
|
||||
.is_some_and(|s| super::raider::is_raider(s.species))
|
||||
}
|
||||
Who::Player => false,
|
||||
};
|
||||
let (effect, ticks, amplifier) = if heals {
|
||||
m.ai.target = None;
|
||||
if health <= 4.0 {
|
||||
("minecraft:instant_health", 1, 0)
|
||||
} else {
|
||||
("minecraft:regeneration", 900, 0)
|
||||
}
|
||||
} else if dist >= 8.0 {
|
||||
("minecraft:slowness", 1800, 0)
|
||||
} else if health >= 8.0 {
|
||||
("minecraft:poison", 900, 0)
|
||||
|
||||
@@ -0,0 +1,901 @@
|
||||
//! NBT paths (`NbtPathArgument`): `foo.bar[0]`, `[]`, `list[{id:1}]`,
|
||||
//! `{root:match}`, with get, set, insert and remove on a tag tree, and the
|
||||
//! partial NBT comparison (`NbtUtils.compareNbt`) selectors and conditions use.
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag, parse_snbt};
|
||||
|
||||
/// An error carrying the translation key and its arguments.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PathError {
|
||||
pub key: &'static str,
|
||||
pub args: Vec<String>,
|
||||
/// Byte offset in the path text (parse errors).
|
||||
pub cursor: usize,
|
||||
}
|
||||
impl PathError {
|
||||
fn new(key: &'static str, args: Vec<String>, cursor: usize) -> Self {
|
||||
Self { key, args, cursor }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Node {
|
||||
/// `name`
|
||||
Child(String),
|
||||
/// `name{pattern}`
|
||||
MatchChild(String, Tag),
|
||||
/// `[]`
|
||||
AllElements,
|
||||
/// `[n]`
|
||||
Index(i32),
|
||||
/// `[{pattern}]`
|
||||
MatchElement(Tag),
|
||||
/// `{pattern}` at the start.
|
||||
MatchRoot(Tag),
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NbtPath {
|
||||
original: String,
|
||||
nodes: Vec<Node>,
|
||||
/// Byte offset just after each node in `original`.
|
||||
ends: Vec<usize>,
|
||||
}
|
||||
|
||||
fn key(s: &str) -> JavaString {
|
||||
JavaString::from(s)
|
||||
}
|
||||
fn get_child<'a>(c: &'a Compound, name: &str) -> Option<&'a Tag> {
|
||||
c.get(&key(name))
|
||||
}
|
||||
|
||||
/// `NbtUtils.compareNbt(expected, actual, true)`.
|
||||
pub fn compare_nbt(expected: &Tag, actual: Option<&Tag>) -> bool {
|
||||
let Some(actual) = actual else { return false };
|
||||
if std::mem::discriminant(expected) != std::mem::discriminant(actual) {
|
||||
return false;
|
||||
}
|
||||
match (expected, actual) {
|
||||
(Tag::Compound(e), Tag::Compound(a)) => {
|
||||
a.len() >= e.len() && e.iter().all(|(k, v)| compare_nbt(v, a.get(k)))
|
||||
}
|
||||
(Tag::List(e), Tag::List(a)) => {
|
||||
if e.is_empty() {
|
||||
return a.is_empty();
|
||||
}
|
||||
a.len() >= e.len() && e.iter().all(|x| a.iter().any(|y| compare_nbt(x, Some(y))))
|
||||
}
|
||||
_ => expected == actual,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- list-like tags ----------------------------------------------------------
|
||||
|
||||
/// The elements of a list or array tag.
|
||||
fn elements(tag: &Tag) -> Option<Vec<Tag>> {
|
||||
Some(match tag {
|
||||
Tag::List(l) => l.clone(),
|
||||
Tag::ByteArray(a) => a.iter().map(|b| Tag::Byte(*b as i8)).collect(),
|
||||
Tag::IntArray(a) => a.iter().map(|v| Tag::Int(*v)).collect(),
|
||||
Tag::LongArray(a) => a.iter().map(|v| Tag::Long(*v)).collect(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn number(t: &Tag) -> Option<i64> {
|
||||
match t {
|
||||
Tag::Byte(v) => Some(i64::from(*v)),
|
||||
Tag::Short(v) => Some(i64::from(*v)),
|
||||
Tag::Int(v) => Some(i64::from(*v)),
|
||||
Tag::Long(v) => Some(*v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Run `f` over the elements of a list/array, writing array results back.
|
||||
/// None when `tag` is not list-like.
|
||||
fn with_elements<R>(tag: &mut Tag, f: impl FnOnce(&mut Vec<Tag>) -> R) -> Option<R> {
|
||||
match tag {
|
||||
Tag::List(l) => Some(f(l)),
|
||||
Tag::ByteArray(_) | Tag::IntArray(_) | Tag::LongArray(_) => {
|
||||
let mut v = elements(tag)?;
|
||||
let r = f(&mut v);
|
||||
let nums: Vec<i64> = v.iter().filter_map(number).collect();
|
||||
match tag {
|
||||
Tag::ByteArray(a) => *a = nums.iter().map(|n| *n as u8).collect(),
|
||||
Tag::IntArray(a) => *a = nums.iter().map(|n| *n as i32).collect(),
|
||||
Tag::LongArray(a) => *a = nums,
|
||||
_ => {}
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl NbtPath {
|
||||
/// `NbtPathArgument.parse` from the start of `text`; returns the path and
|
||||
/// the bytes consumed (it stops at a space).
|
||||
pub fn parse_prefix(text: &str) -> Result<(NbtPath, usize), PathError> {
|
||||
let b = text.as_bytes();
|
||||
let mut i = 0;
|
||||
let mut nodes = Vec::new();
|
||||
let mut ends = Vec::new();
|
||||
let mut first = true;
|
||||
while i < b.len() && b[i] != b' ' {
|
||||
let (node, next) = parse_node(text, i, first)?;
|
||||
nodes.push(node);
|
||||
i = next;
|
||||
ends.push(i);
|
||||
first = false;
|
||||
if i < b.len() && !matches!(b[i], b' ' | b'[' | b'{') {
|
||||
if b[i] != b'.' {
|
||||
return Err(PathError::new("parsing.expected", vec![".".into()], i));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok((
|
||||
NbtPath {
|
||||
original: text[..i].to_owned(),
|
||||
nodes,
|
||||
ends,
|
||||
},
|
||||
i,
|
||||
))
|
||||
}
|
||||
pub fn parse(text: &str) -> Result<NbtPath, PathError> {
|
||||
let (p, used) = Self::parse_prefix(text)?;
|
||||
if used != text.len() {
|
||||
return Err(PathError::new(
|
||||
"arguments.nbtpath.node.invalid",
|
||||
vec![],
|
||||
used,
|
||||
));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.original
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty()
|
||||
}
|
||||
fn not_found(&self, node: usize) -> PathError {
|
||||
let end = self.ends[node];
|
||||
PathError::new(
|
||||
"arguments.nbtpath.nothing_found",
|
||||
vec![self.original[..end.min(self.original.len())].to_owned()],
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
// ---- reading --------------------------------------------------------
|
||||
|
||||
fn step<'a>(node: &Node, parent: &'a Tag, out: &mut Vec<&'a Tag>) {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent
|
||||
&& let Some(t) = get_child(c, name)
|
||||
{
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent
|
||||
&& let Some(t) = get_child(c, name)
|
||||
&& compare_nbt(pattern, Some(t))
|
||||
{
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
Node::AllElements => {
|
||||
if let Tag::List(l) = parent {
|
||||
out.extend(l.iter());
|
||||
}
|
||||
}
|
||||
Node::Index(i) => {
|
||||
if let Tag::List(l) = parent {
|
||||
let n = l.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
out.push(&l[idx as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchElement(pattern) => {
|
||||
if let Tag::List(l) = parent {
|
||||
out.extend(l.iter().filter(|t| compare_nbt(pattern, Some(t))));
|
||||
}
|
||||
}
|
||||
Node::MatchRoot(pattern) => {
|
||||
if matches!(parent, Tag::Compound(_)) && compare_nbt(pattern, Some(parent)) {
|
||||
out.push(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Array tags read as lists of their elements.
|
||||
fn read_steps(&self, root: &Tag) -> Result<Vec<Tag>, PathError> {
|
||||
let mut current: Vec<Tag> = vec![root.clone()];
|
||||
for (i, node) in self.nodes.iter().enumerate() {
|
||||
let mut next = Vec::new();
|
||||
for parent in ¤t {
|
||||
// Arrays expose their elements to element nodes.
|
||||
let list;
|
||||
let p = if matches!(node, Node::AllElements | Node::Index(_)) {
|
||||
match elements(parent) {
|
||||
Some(l) if !matches!(parent, Tag::List(_)) => {
|
||||
list = Tag::List(l);
|
||||
&list
|
||||
}
|
||||
_ => parent,
|
||||
}
|
||||
} else {
|
||||
parent
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
Self::step(node, p, &mut out);
|
||||
next.extend(out.into_iter().cloned());
|
||||
}
|
||||
if next.is_empty() {
|
||||
return Err(self.not_found(i));
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
/// `get`: every matching tag (an error when nothing matches).
|
||||
pub fn get(&self, root: &Tag) -> Result<Vec<Tag>, PathError> {
|
||||
self.read_steps(root)
|
||||
}
|
||||
/// `countMatching`.
|
||||
pub fn count(&self, root: &Tag) -> usize {
|
||||
self.read_steps(root).map_or(0, |v| v.len())
|
||||
}
|
||||
|
||||
// ---- writing --------------------------------------------------------
|
||||
|
||||
/// The parents of the last node, creating the missing ones (`getOrCreateParents`).
|
||||
fn visit_parents(
|
||||
&self,
|
||||
root: &mut Tag,
|
||||
create: bool,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
self.descend(0, self.nodes.len().saturating_sub(1), root, create, None, f)
|
||||
}
|
||||
/// Walk `nodes[from..to]` from `tag`, calling `f` on every tag reached.
|
||||
fn descend(
|
||||
&self,
|
||||
from: usize,
|
||||
to: usize,
|
||||
tag: &mut Tag,
|
||||
create: bool,
|
||||
last_value: Option<&dyn Fn() -> Tag>,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
if from >= to {
|
||||
f(tag);
|
||||
return Ok(());
|
||||
}
|
||||
let node = &self.nodes[from];
|
||||
// What a created child should be: the next node's preferred parent,
|
||||
// or the caller's value for the last node.
|
||||
let default_child = || -> Tag {
|
||||
match (self.nodes.get(from + 1), last_value) {
|
||||
(Some(next), _) if from + 1 < to => preferred_parent(next),
|
||||
(_, Some(v)) => v(),
|
||||
(Some(next), None) => preferred_parent(next),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
}
|
||||
};
|
||||
let mut found = false;
|
||||
let mut error = None;
|
||||
let mut visit = |child: &mut Tag| {
|
||||
found = true;
|
||||
if error.is_none()
|
||||
&& let Err(e) = self.descend(from + 1, to, child, create, last_value, f)
|
||||
{
|
||||
error = Some(e);
|
||||
}
|
||||
};
|
||||
step_mut(
|
||||
node,
|
||||
tag,
|
||||
create.then_some(&default_child as &dyn Fn() -> Tag),
|
||||
&mut visit,
|
||||
);
|
||||
if let Some(e) = error {
|
||||
return Err(e);
|
||||
}
|
||||
if !found {
|
||||
return Err(self.not_found(from));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `getOrCreate`: the tags at the path, creating missing ones as
|
||||
/// `new_value` (used for the last node).
|
||||
pub fn get_or_create(
|
||||
&self,
|
||||
root: &mut Tag,
|
||||
new_value: &dyn Fn() -> Tag,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
self.descend(0, self.nodes.len(), root, true, Some(new_value), f)
|
||||
}
|
||||
/// `set`: returns how many tags changed.
|
||||
pub fn set(&self, root: &mut Tag, value: &Tag) -> Result<usize, PathError> {
|
||||
if too_deep(value, self.nodes.len()) {
|
||||
return Err(PathError::new("arguments.nbtpath.too_deep", vec![], 0));
|
||||
}
|
||||
let Some(last) = self.nodes.last() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut changed = 0;
|
||||
self.visit_parents(root, true, &mut |parent| {
|
||||
changed += set_tag(last, parent, value);
|
||||
})?;
|
||||
Ok(changed)
|
||||
}
|
||||
/// `remove`: returns how many tags were removed.
|
||||
pub fn remove(&self, root: &mut Tag) -> usize {
|
||||
let Some(last) = self.nodes.last() else {
|
||||
return 0;
|
||||
};
|
||||
let mut removed = 0;
|
||||
let _ = self.visit_parents(root, false, &mut |parent| {
|
||||
removed += remove_tag(last, parent);
|
||||
});
|
||||
removed
|
||||
}
|
||||
/// `insert` (also append and prepend): into every list the path reaches.
|
||||
pub fn insert(
|
||||
&self,
|
||||
index: i32,
|
||||
root: &mut Tag,
|
||||
values: &[Tag],
|
||||
) -> Result<usize, CollectionError> {
|
||||
for v in values {
|
||||
if too_deep(v, self.nodes.len()) {
|
||||
return Err(CollectionError::Path(PathError::new(
|
||||
"arguments.nbtpath.too_deep",
|
||||
vec![],
|
||||
0,
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut modified = 0;
|
||||
let mut error: Option<CollectionError> = None;
|
||||
self.get_or_create(root, &|| Tag::List(Vec::new()), &mut |target| {
|
||||
if error.is_some() {
|
||||
return;
|
||||
}
|
||||
let shown = crate::snbt::to_snbt(target);
|
||||
let result = with_elements(target, |list| {
|
||||
let start = if index < 0 {
|
||||
list.len() as i64 + i64::from(index) + 1
|
||||
} else {
|
||||
i64::from(index)
|
||||
};
|
||||
let mut any = false;
|
||||
for (n, v) in values.iter().enumerate() {
|
||||
let at = start + n as i64;
|
||||
if at < 0 || at as usize > list.len() {
|
||||
return Err(CollectionError::InvalidIndex(at as i32));
|
||||
}
|
||||
list.insert(at as usize, v.clone());
|
||||
any = true;
|
||||
}
|
||||
Ok(any)
|
||||
});
|
||||
match result {
|
||||
None => error = Some(CollectionError::ExpectedList(shown)),
|
||||
Some(Err(e)) => error = Some(e),
|
||||
Some(Ok(any)) => modified += usize::from(any),
|
||||
}
|
||||
})
|
||||
.map_err(CollectionError::Path)?;
|
||||
match error {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(modified),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum CollectionError {
|
||||
Path(PathError),
|
||||
/// `commands.data.modify.expected_list` with the offending tag.
|
||||
ExpectedList(String),
|
||||
/// `commands.data.modify.invalid_index`.
|
||||
InvalidIndex(i32),
|
||||
}
|
||||
|
||||
/// `isTooDeep`.
|
||||
pub fn too_deep(tag: &Tag, depth: usize) -> bool {
|
||||
if depth >= 512 {
|
||||
return true;
|
||||
}
|
||||
match tag {
|
||||
Tag::Compound(c) => c.values().any(|t| too_deep(t, depth + 1)),
|
||||
Tag::List(l) => l.iter().any(|t| too_deep(t, depth + 1)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn preferred_parent(node: &Node) -> Tag {
|
||||
match node {
|
||||
Node::AllElements | Node::Index(_) | Node::MatchElement(_) => Tag::List(Vec::new()),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
}
|
||||
}
|
||||
/// `getOrCreateTag` (or `getTag` without `create`): the children of `parent`.
|
||||
fn step_mut(
|
||||
node: &Node,
|
||||
parent: &mut Tag,
|
||||
create: Option<&dyn Fn() -> Tag>,
|
||||
out: &mut dyn FnMut(&mut Tag),
|
||||
) {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if !c.contains_key(&k) {
|
||||
let Some(make) = create else { return };
|
||||
c.insert(k.clone(), make());
|
||||
}
|
||||
if let Some(t) = c.get_mut(&k) {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if !c.contains_key(&k) {
|
||||
if create.is_none() {
|
||||
return;
|
||||
}
|
||||
c.insert(k.clone(), pattern.clone());
|
||||
if let Some(t) = c.get_mut(&k) {
|
||||
out(t);
|
||||
}
|
||||
} else if let Some(t) = c.get_mut(&k)
|
||||
&& compare_nbt(pattern, Some(t))
|
||||
{
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::AllElements => {
|
||||
let make = create;
|
||||
let _ = with_elements(parent, |list| {
|
||||
if list.is_empty() {
|
||||
if let Some(make) = make {
|
||||
list.push(make());
|
||||
out(&mut list[0]);
|
||||
}
|
||||
} else {
|
||||
for t in list.iter_mut() {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::Index(i) => {
|
||||
let _ = with_elements(parent, |list| {
|
||||
let n = list.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
out(&mut list[idx as usize]);
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::MatchElement(pattern) => {
|
||||
if let Tag::List(list) = parent {
|
||||
let mut any = false;
|
||||
for t in list.iter_mut() {
|
||||
if compare_nbt(pattern, Some(t)) {
|
||||
any = true;
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
if !any && create.is_some() {
|
||||
list.push(pattern.clone());
|
||||
if let Some(t) = list.last_mut() {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchRoot(pattern) => {
|
||||
if matches!(parent, Tag::Compound(_)) && compare_nbt(pattern, Some(parent)) {
|
||||
out(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Node.setTag`: replace the child(ren) of `parent` with `value`.
|
||||
fn set_tag(node: &Node, parent: &mut Tag, value: &Tag) -> usize {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let prev = c.insert(key(name), value.clone());
|
||||
return usize::from(prev.as_ref() != Some(value));
|
||||
}
|
||||
0
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if compare_nbt(pattern, c.get(&k)) && c.get(&k) != Some(value) {
|
||||
c.insert(k, value.clone());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Node::AllElements => with_elements(parent, |list| {
|
||||
if list.is_empty() {
|
||||
list.push(value.clone());
|
||||
return 1;
|
||||
}
|
||||
let changed = list.iter().filter(|t| *t != value).count();
|
||||
if changed == 0 {
|
||||
return 0;
|
||||
}
|
||||
for t in list.iter_mut() {
|
||||
*t = value.clone();
|
||||
}
|
||||
changed
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::Index(i) => with_elements(parent, |list| {
|
||||
let n = list.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) && list[idx as usize] != *value {
|
||||
list[idx as usize] = value.clone();
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::MatchElement(pattern) => {
|
||||
let Tag::List(list) = parent else { return 0 };
|
||||
if list.is_empty() {
|
||||
list.push(value.clone());
|
||||
return 1;
|
||||
}
|
||||
let mut changed = 0;
|
||||
for t in list.iter_mut() {
|
||||
if compare_nbt(pattern, Some(t)) && t != value {
|
||||
*t = value.clone();
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
Node::MatchRoot(_) => 0,
|
||||
}
|
||||
}
|
||||
fn remove_tag(node: &Node, parent: &mut Tag) -> usize {
|
||||
match node {
|
||||
Node::Child(name) => match parent {
|
||||
Tag::Compound(c) => usize::from(c.remove(&key(name)).is_some()),
|
||||
_ => 0,
|
||||
},
|
||||
Node::MatchChild(name, pattern) => match parent {
|
||||
Tag::Compound(c) => {
|
||||
let k = key(name);
|
||||
if compare_nbt(pattern, c.get(&k)) {
|
||||
usize::from(c.remove(&k).is_some())
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
Node::AllElements => with_elements(parent, |l| {
|
||||
let n = l.len();
|
||||
l.clear();
|
||||
n
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::Index(i) => with_elements(parent, |l| {
|
||||
let n = l.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
l.remove(idx as usize);
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::MatchElement(pattern) => match parent {
|
||||
Tag::List(l) => {
|
||||
let before = l.len();
|
||||
l.retain(|t| !compare_nbt(pattern, Some(t)));
|
||||
before - l.len()
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
Node::MatchRoot(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- parsing -------------------------------------------------------------------
|
||||
|
||||
fn parse_node(text: &str, i: usize, first: bool) -> Result<(Node, usize), PathError> {
|
||||
let b = text.as_bytes();
|
||||
let invalid = |at: usize| PathError::new("arguments.nbtpath.node.invalid", vec![], at);
|
||||
match b[i] {
|
||||
b'"' | b'\'' => {
|
||||
let (name, next) = read_quoted(text, i)?;
|
||||
read_object_node(text, name, next)
|
||||
}
|
||||
b'[' => {
|
||||
let mut j = i + 1;
|
||||
match b.get(j) {
|
||||
Some(b'{') => {
|
||||
let (pattern, next) = parse_compound(text, j)?;
|
||||
j = next;
|
||||
expect(text, j, b']')?;
|
||||
Ok((Node::MatchElement(pattern), j + 1))
|
||||
}
|
||||
Some(b']') => Ok((Node::AllElements, j + 1)),
|
||||
_ => {
|
||||
let start = j;
|
||||
if b.get(j) == Some(&b'-') {
|
||||
j += 1;
|
||||
}
|
||||
while b.get(j).is_some_and(u8::is_ascii_digit) {
|
||||
j += 1;
|
||||
}
|
||||
let n: i32 = text[start..j].parse().map_err(|_| {
|
||||
PathError::new(
|
||||
"parsing.int.invalid",
|
||||
vec![text[start..j].to_owned()],
|
||||
start,
|
||||
)
|
||||
})?;
|
||||
expect(text, j, b']')?;
|
||||
Ok((Node::Index(n), j + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
if !first {
|
||||
return Err(invalid(i));
|
||||
}
|
||||
let (pattern, next) = parse_compound(text, i)?;
|
||||
Ok((Node::MatchRoot(pattern), next))
|
||||
}
|
||||
_ => {
|
||||
let mut j = i;
|
||||
while j < b.len()
|
||||
&& !matches!(b[j], b' ' | b'"' | b'\'' | b'[' | b']' | b'.' | b'{' | b'}')
|
||||
{
|
||||
j += 1;
|
||||
}
|
||||
if j == i {
|
||||
return Err(invalid(i));
|
||||
}
|
||||
read_object_node(text, text[i..j].to_owned(), j)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_object_node(text: &str, name: String, i: usize) -> Result<(Node, usize), PathError> {
|
||||
if name.is_empty() {
|
||||
return Err(PathError::new("arguments.nbtpath.node.invalid", vec![], i));
|
||||
}
|
||||
if text.as_bytes().get(i) == Some(&b'{') {
|
||||
let (pattern, next) = parse_compound(text, i)?;
|
||||
return Ok((Node::MatchChild(name, pattern), next));
|
||||
}
|
||||
Ok((Node::Child(name), i))
|
||||
}
|
||||
fn expect(text: &str, i: usize, c: u8) -> Result<(), PathError> {
|
||||
if text.as_bytes().get(i) == Some(&c) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PathError::new(
|
||||
"parsing.expected",
|
||||
vec![(c as char).to_string()],
|
||||
i,
|
||||
))
|
||||
}
|
||||
}
|
||||
fn read_quoted(text: &str, i: usize) -> Result<(String, usize), PathError> {
|
||||
let quote = text.as_bytes()[i] as char;
|
||||
let mut out = String::new();
|
||||
let mut escaped = false;
|
||||
for (o, c) in text[i + 1..].char_indices() {
|
||||
if escaped {
|
||||
out.push(c);
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == quote {
|
||||
return Ok((out, i + 1 + o + c.len_utf8()));
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Err(PathError::new(
|
||||
"parsing.quote.expected.end",
|
||||
vec![],
|
||||
text.len(),
|
||||
))
|
||||
}
|
||||
fn parse_compound(text: &str, i: usize) -> Result<(Tag, usize), PathError> {
|
||||
// Find the balanced end of the braces, then parse the SNBT inside.
|
||||
let b = text.as_bytes();
|
||||
let mut depth = 0;
|
||||
let mut quote: Option<u8> = None;
|
||||
let mut j = i;
|
||||
while j < b.len() {
|
||||
let c = b[j];
|
||||
match quote {
|
||||
Some(_) if c == b'\\' => j += 1,
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if c == b'"' || c == b'\'' => quote = Some(c),
|
||||
None if c == b'{' || c == b'[' => depth += 1,
|
||||
None if c == b'}' || c == b']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
let (tag, _) = parse_snbt(&text[i..=j])
|
||||
.map_err(|e| PathError::new("argument.nbt.invalid", vec![e], i))?;
|
||||
return Ok((tag, j + 1));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
Err(PathError::new("argument.nbt.expected.compound", vec![], i))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tag(s: &str) -> Tag {
|
||||
parse_snbt(s).unwrap().0
|
||||
}
|
||||
fn path(s: &str) -> NbtPath {
|
||||
NbtPath::parse(s).unwrap_or_else(|e| panic!("{s}: {e:?}"))
|
||||
}
|
||||
fn show(v: &[Tag]) -> Vec<String> {
|
||||
v.iter().map(crate::snbt::to_snbt).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_follows_the_path() {
|
||||
let root = tag("{a:{b:[{id:1,n:\"x\"},{id:2,n:\"y\"},{id:3}]},c:5,\"d e\":7}");
|
||||
assert_eq!(show(&path("c").get(&root).unwrap()), ["5"]);
|
||||
assert_eq!(show(&path("\"d e\"").get(&root).unwrap()), ["7"]);
|
||||
assert_eq!(show(&path("a.b[0].n").get(&root).unwrap()), ["\"x\""]);
|
||||
assert_eq!(show(&path("a.b[-1]").get(&root).unwrap()), ["{id:3}"]);
|
||||
assert_eq!(show(&path("a.b[].id").get(&root).unwrap()), ["1", "2", "3"]);
|
||||
assert_eq!(show(&path("a.b[{id:2}].n").get(&root).unwrap()), ["\"y\""]);
|
||||
assert_eq!(
|
||||
show(&path("a{b:[{id:1}]}.b[0].id").get(&root).unwrap()),
|
||||
["1"]
|
||||
);
|
||||
assert_eq!(show(&path("{c:5}.c").get(&root).unwrap()), ["5"]);
|
||||
assert!(path("{c:6}.c").get(&root).is_err());
|
||||
let e = path("a.zzz.q").get(&root).unwrap_err();
|
||||
assert_eq!(e.key, "arguments.nbtpath.nothing_found");
|
||||
assert_eq!(e.args, ["a.zzz"]);
|
||||
assert_eq!(path("a.b[].id").count(&root), 3);
|
||||
assert_eq!(path("a.nope").count(&root), 0);
|
||||
// Arrays act like lists.
|
||||
let arr = tag("{v:[I;4,5,6]}");
|
||||
assert_eq!(show(&path("v[1]").get(&arr).unwrap()), ["5"]);
|
||||
assert_eq!(show(&path("v[]").get(&arr).unwrap()), ["4", "5", "6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_errors() {
|
||||
assert_eq!(
|
||||
NbtPath::parse("a..b").unwrap_err().key,
|
||||
"arguments.nbtpath.node.invalid"
|
||||
);
|
||||
assert_eq!(
|
||||
NbtPath::parse("a.{b:1}").unwrap_err().key,
|
||||
"arguments.nbtpath.node.invalid"
|
||||
);
|
||||
assert_eq!(NbtPath::parse("a[1").unwrap_err().key, "parsing.expected");
|
||||
assert_eq!(NbtPath::parse("a]").unwrap_err().key, "parsing.expected");
|
||||
let (p, used) = NbtPath::parse_prefix("a.b[0] rest").unwrap();
|
||||
assert_eq!((p.as_str(), used), ("a.b[0]", 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_creates_and_reports_changes() {
|
||||
let mut root = tag("{a:{x:1}}");
|
||||
assert_eq!(path("a.x").set(&mut root, &tag("2")).unwrap(), 1);
|
||||
assert_eq!(path("a.x").set(&mut root, &tag("2")).unwrap(), 0);
|
||||
assert_eq!(path("b.c.d").set(&mut root, &tag("\"deep\"")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{a:{x:2},b:{c:{d:\"deep\"}}}");
|
||||
let mut root = tag("{l:[1,2,3]}");
|
||||
assert_eq!(path("l[1]").set(&mut root, &tag("9")).unwrap(), 1);
|
||||
assert_eq!(path("l[7]").set(&mut root, &tag("9")).unwrap(), 0);
|
||||
assert_eq!(path("l[]").set(&mut root, &tag("0")).unwrap(), 3);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[0,0,0]}");
|
||||
let mut root = tag("{l:[{id:1,v:0},{id:2,v:0}]}");
|
||||
assert_eq!(path("l[{id:2}].v").set(&mut root, &tag("5")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[{id:1,v:0},{id:2,v:5}]}");
|
||||
// A missing match is created from the pattern.
|
||||
assert_eq!(path("l[{id:3}].v").set(&mut root, &tag("1")).unwrap(), 1);
|
||||
assert_eq!(path("l[{id:3}].v").count(&root), 1);
|
||||
// New lists come from index nodes.
|
||||
let mut root = tag("{}");
|
||||
assert_eq!(path("x[].y").set(&mut root, &tag("1")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{x:[{y:1}]}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_counts() {
|
||||
let mut root = tag("{a:1,l:[1,2,3,2],c:{d:1}}");
|
||||
assert_eq!(path("a").remove(&mut root), 1);
|
||||
assert_eq!(path("a").remove(&mut root), 0);
|
||||
assert_eq!(path("l[1]").remove(&mut root), 1);
|
||||
assert_eq!(path("c.d").remove(&mut root), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{c:{},l:[1,3,2]}");
|
||||
let mut root = tag("{l:[{k:1},{k:2},{k:1}]}");
|
||||
assert_eq!(path("l[{k:1}]").remove(&mut root), 2);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[{k:2}]}");
|
||||
assert_eq!(path("l[]").remove(&mut root), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_positions() {
|
||||
let mut root = tag("{l:[1,2]}");
|
||||
assert_eq!(path("l").insert(0, &mut root, &[tag("0")]).unwrap(), 1);
|
||||
assert_eq!(path("l").insert(-1, &mut root, &[tag("9")]).unwrap(), 1);
|
||||
assert_eq!(
|
||||
path("l")
|
||||
.insert(1, &mut root, &[tag("5"), tag("6")])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[0,5,6,1,2,9]}");
|
||||
assert_eq!(
|
||||
path("l").insert(99, &mut root, &[tag("1")]).unwrap_err(),
|
||||
CollectionError::InvalidIndex(99)
|
||||
);
|
||||
// A missing list is created.
|
||||
assert_eq!(path("n").insert(-1, &mut root, &[tag("1")]).unwrap(), 1);
|
||||
assert!(matches!(
|
||||
path("l[0]").insert(0, &mut root, &[tag("1")]).unwrap_err(),
|
||||
CollectionError::ExpectedList(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_comparison() {
|
||||
let actual = tag("{a:1,b:{c:[1,2,3],d:\"x\"},e:2}");
|
||||
assert!(compare_nbt(&tag("{b:{c:[2]}}"), Some(&actual)));
|
||||
assert!(compare_nbt(&tag("{a:1}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{a:2}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{a:1L}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{z:1}"), Some(&actual)));
|
||||
assert!(compare_nbt(&tag("{b:{c:[]}}"), Some(&tag("{b:{c:[]}}"))));
|
||||
assert!(!compare_nbt(&tag("{b:{c:[]}}"), Some(&actual)));
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,8 @@ pub enum Opt {
|
||||
AutoSuggestions,
|
||||
ReducedDebugInfo,
|
||||
HighContrast,
|
||||
ShowSubtitles,
|
||||
NotificationDisplayTime,
|
||||
ForceUnicode,
|
||||
JapaneseGlyphs,
|
||||
}
|
||||
@@ -147,6 +149,8 @@ impl Opt {
|
||||
Opt::AutoSuggestions => "options.autoSuggestCommands",
|
||||
Opt::ReducedDebugInfo => "options.reducedDebugInfo",
|
||||
Opt::HighContrast => "options.accessibility.high_contrast",
|
||||
Opt::ShowSubtitles => "options.showSubtitles",
|
||||
Opt::NotificationDisplayTime => "options.notifications.display_time",
|
||||
Opt::ForceUnicode => "options.forceUnicodeFont",
|
||||
Opt::JapaneseGlyphs => "options.japaneseGlyphVariants",
|
||||
}
|
||||
@@ -175,6 +179,7 @@ impl Opt {
|
||||
Opt::WeatherRadius => unit(s.weather_radius as f32, 3.0, 10.0),
|
||||
Opt::ChunkFade => unit(s.chunk_fade, 0.0, 2.0),
|
||||
Opt::MenuBlur => unit(s.menu_blur as f32, 0.0, 10.0),
|
||||
Opt::NotificationDisplayTime => unit(s.notification_display_time, 0.5, 10.0),
|
||||
Opt::ChatOpacity => Kind::Slider(s.chat_opacity),
|
||||
Opt::TextBackgroundOpacity => Kind::Slider(s.text_background_opacity),
|
||||
Opt::ChatScale => Kind::Slider(s.chat_scale),
|
||||
@@ -294,6 +299,13 @@ impl Opt {
|
||||
chat_px(c, (s.chat_height_unfocused * 160.0 + 20.0).floor())
|
||||
}
|
||||
Opt::ChatLineSpacing => percent(c, s.chat_line_spacing),
|
||||
Opt::NotificationDisplayTime => generic(
|
||||
c,
|
||||
Text::tr(
|
||||
"options.multiplier",
|
||||
&[&format!("{:.1}", s.notification_display_time)],
|
||||
),
|
||||
),
|
||||
_ => generic(c, self.value_text(s)),
|
||||
}
|
||||
}
|
||||
@@ -356,6 +368,7 @@ impl Opt {
|
||||
Opt::AutoSuggestions => on_off(s.auto_suggestions),
|
||||
Opt::ReducedDebugInfo => on_off(s.reduced_debug_info),
|
||||
Opt::HighContrast => on_off(s.high_contrast),
|
||||
Opt::ShowSubtitles => on_off(s.show_subtitles),
|
||||
Opt::ForceUnicode => on_off(s.force_unicode),
|
||||
Opt::JapaneseGlyphs => on_off(s.japanese_glyphs),
|
||||
_ => Text::empty(),
|
||||
@@ -383,6 +396,7 @@ impl Opt {
|
||||
Opt::WeatherRadius => s.weather_radius = step(3.0, 10.0) as i32,
|
||||
Opt::ChunkFade => s.chunk_fade = step(0.0, 40.0) / 20.0,
|
||||
Opt::MenuBlur => s.menu_blur = step(0.0, 10.0) as i32,
|
||||
Opt::NotificationDisplayTime => s.notification_display_time = step(5.0, 100.0) / 10.0,
|
||||
Opt::ChatOpacity => s.chat_opacity = v,
|
||||
Opt::TextBackgroundOpacity => s.text_background_opacity = v,
|
||||
Opt::ChatScale => s.chat_scale = v,
|
||||
@@ -460,6 +474,7 @@ impl Opt {
|
||||
Opt::AutoSuggestions => s.auto_suggestions = !s.auto_suggestions,
|
||||
Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info,
|
||||
Opt::HighContrast => s.high_contrast = !s.high_contrast,
|
||||
Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles,
|
||||
Opt::ForceUnicode => s.force_unicode = !s.force_unicode,
|
||||
Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs,
|
||||
_ => {}
|
||||
@@ -763,6 +778,7 @@ impl OptionsUi {
|
||||
let mut rows = vec![Row::Big(Opt::Volume(0))];
|
||||
let others: Vec<Opt> = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect();
|
||||
rows.extend(pairs(&others));
|
||||
rows.extend(pairs(&[Opt::ShowSubtitles]));
|
||||
rows
|
||||
}
|
||||
Page::Controls => {
|
||||
@@ -810,11 +826,13 @@ impl OptionsUi {
|
||||
Opt::ReducedDebugInfo,
|
||||
]),
|
||||
Page::Accessibility => pairs(&[
|
||||
Opt::ShowSubtitles,
|
||||
Opt::HighContrast,
|
||||
Opt::MenuBlur,
|
||||
Opt::TextBackgroundOpacity,
|
||||
Opt::ChatOpacity,
|
||||
Opt::ChatLineSpacing,
|
||||
Opt::NotificationDisplayTime,
|
||||
Opt::ViewBobbing,
|
||||
Opt::ToggleCrouch,
|
||||
Opt::ToggleSprint,
|
||||
|
||||
@@ -41,6 +41,7 @@ macro_rules! particle_types {
|
||||
particle_types! {
|
||||
Block = "block",
|
||||
BlockCrumble = "block_crumble",
|
||||
Trail = "trail",
|
||||
DustPillar = "dust_pillar",
|
||||
FallingDust = "falling_dust",
|
||||
Smoke = "smoke",
|
||||
@@ -119,6 +120,12 @@ particle_types! {
|
||||
Soul = "soul",
|
||||
SculkSoul = "sculk_soul",
|
||||
DragonBreath = "dragon_breath",
|
||||
DustColorTransition = "dust_color_transition",
|
||||
SculkCharge = "sculk_charge",
|
||||
SculkChargePop = "sculk_charge_pop",
|
||||
Shriek = "shriek",
|
||||
SonicBoom = "sonic_boom",
|
||||
Vibration = "vibration",
|
||||
}
|
||||
impl ParticleType {
|
||||
/// `ParticleType.getOverrideLimiter`: spawned regardless of distance.
|
||||
@@ -138,8 +145,13 @@ pub struct ParticleOptions {
|
||||
pub block: Option<(String, u32)>,
|
||||
/// RGB(A) for dust, spells, entity effects and tinted leaves.
|
||||
pub color: [f32; 4],
|
||||
/// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`.
|
||||
/// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`,
|
||||
/// `SculkChargeParticleOptions.roll`, `ShriekParticleOption.delay`.
|
||||
pub scale: f32,
|
||||
/// `DustColorTransitionOptions.toColor` (`color` is the from colour).
|
||||
pub to_color: [f32; 3],
|
||||
/// `TrailParticleOption`: the point it flies to and how many ticks it takes.
|
||||
pub trail: Option<([f64; 3], i32)>,
|
||||
}
|
||||
impl ParticleOptions {
|
||||
pub fn simple(ty: ParticleType) -> Self {
|
||||
@@ -148,6 +160,55 @@ impl ParticleOptions {
|
||||
block: None,
|
||||
color: [1.0; 4],
|
||||
scale: 1.0,
|
||||
to_color: [1.0, 0.0, 0.0],
|
||||
trail: None,
|
||||
}
|
||||
}
|
||||
/// `DustColorTransitionOptions`.
|
||||
pub fn dust_transition(from: [f32; 3], to: [f32; 3], scale: f32) -> Self {
|
||||
Self {
|
||||
color: [from[0], from[1], from[2], 1.0],
|
||||
to_color: to,
|
||||
scale: scale.clamp(0.01, 4.0),
|
||||
..Self::simple(ParticleType::DustColorTransition)
|
||||
}
|
||||
}
|
||||
/// `DustColorTransitionOptions.SCULK_TO_REDSTONE`.
|
||||
pub fn sculk_to_redstone() -> Self {
|
||||
let rgb = |c: u32| {
|
||||
[
|
||||
((c >> 16) & 255) as f32 / 255.0,
|
||||
((c >> 8) & 255) as f32 / 255.0,
|
||||
(c & 255) as f32 / 255.0,
|
||||
]
|
||||
};
|
||||
Self::dust_transition(rgb(3_790_560), rgb(16_711_680), 1.0)
|
||||
}
|
||||
/// `SculkChargeParticleOptions(roll)`.
|
||||
pub fn sculk_charge(roll: f32) -> Self {
|
||||
Self {
|
||||
scale: roll,
|
||||
..Self::simple(ParticleType::SculkCharge)
|
||||
}
|
||||
}
|
||||
/// `ShriekParticleOption(delay)`.
|
||||
pub fn shriek(delay: i32) -> Self {
|
||||
Self {
|
||||
scale: delay as f32,
|
||||
..Self::simple(ParticleType::Shriek)
|
||||
}
|
||||
}
|
||||
/// `TrailParticleOption(target, color, duration)`.
|
||||
pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self {
|
||||
Self {
|
||||
color: [
|
||||
((rgb >> 16) & 255) as f32 / 255.0,
|
||||
((rgb >> 8) & 255) as f32 / 255.0,
|
||||
(rgb & 255) as f32 / 255.0,
|
||||
1.0,
|
||||
],
|
||||
trail: Some((target, duration)),
|
||||
..Self::simple(ParticleType::Trail)
|
||||
}
|
||||
}
|
||||
pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self {
|
||||
@@ -188,6 +249,8 @@ enum Size {
|
||||
Lava,
|
||||
Portal,
|
||||
ReversePortal,
|
||||
/// `ShriekParticle.getQuadSize`.
|
||||
Shriek,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Light {
|
||||
@@ -261,6 +324,27 @@ enum Behaviour {
|
||||
DragonBreath {
|
||||
hit_ground: bool,
|
||||
},
|
||||
/// `ShriekParticle`: waits `delay` ticks, then rises.
|
||||
Shriek {
|
||||
delay: i32,
|
||||
},
|
||||
/// `VibrationSignalParticle`: flies to a listener.
|
||||
Vibration {
|
||||
dest: [f64; 3],
|
||||
rot: f32,
|
||||
rot_o: f32,
|
||||
pitch: f32,
|
||||
pitch_o: f32,
|
||||
},
|
||||
/// `DustColorTransitionParticle`: from one colour to the other.
|
||||
Transition {
|
||||
from: [f32; 3],
|
||||
to: [f32; 3],
|
||||
},
|
||||
/// `TrailParticle`: eases towards its target over its lifetime.
|
||||
Trail {
|
||||
target: [f64; 3],
|
||||
},
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum DripStage {
|
||||
@@ -511,6 +595,7 @@ impl Particle {
|
||||
Size::ReversePortal => {
|
||||
self.size * (1.0 - (self.age as f32 + a) / (self.lifetime as f32 * 1.5))
|
||||
}
|
||||
Size::Shriek => self.size * (t * 0.75).clamp(0.0, 1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -655,6 +740,27 @@ impl ParticleEngine {
|
||||
self.particles.clear();
|
||||
self.pending.clear();
|
||||
}
|
||||
/// A vibration signal flying from `from` to `to` in `ticks`
|
||||
/// (`VibrationParticleOption`).
|
||||
pub fn vibration(&mut self, from: [f64; 3], to: [f64; 3], ticks: i32) {
|
||||
let mut q = Particle::blank(ParticleType::Vibration, from);
|
||||
q.size = 0.3;
|
||||
q.lifetime = ticks;
|
||||
q.has_physics = false;
|
||||
q.light = Light::Block15;
|
||||
q.set = self.set_of(ParticleType::Vibration);
|
||||
let d = [from[0] - to[0], from[1] - to[1], from[2] - to[2]];
|
||||
let rot = d[0].atan2(d[2]) as f32;
|
||||
let pitch = d[1].atan2((d[0] * d[0] + d[2] * d[2]).sqrt()) as f32;
|
||||
q.behaviour = Behaviour::Vibration {
|
||||
dest: to,
|
||||
rot,
|
||||
rot_o: rot,
|
||||
pitch,
|
||||
pitch_o: pitch,
|
||||
};
|
||||
self.pending.push(q);
|
||||
}
|
||||
/// `ParticleEngine.add` (via `particlesToAdd`, applied on the next tick).
|
||||
pub fn push(&mut self, particle: Particle) {
|
||||
self.pending.push(particle);
|
||||
@@ -1411,12 +1517,17 @@ impl ParticleEngine {
|
||||
q.set = set;
|
||||
q
|
||||
}
|
||||
T::Explosion => {
|
||||
T::Explosion | T::SonicBoom => {
|
||||
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
|
||||
q.lifetime = 6 + r.next_int_bound(4).unwrap_or(0);
|
||||
let col = r.next_float() * 0.6 + 0.4;
|
||||
q.set_color(col, col, col);
|
||||
q.size = 2.0 * (1.0 - v[0] as f32 * 0.5);
|
||||
if ty == T::SonicBoom {
|
||||
// SonicBoomParticle.
|
||||
q.lifetime = 16;
|
||||
q.size = 1.5;
|
||||
}
|
||||
q.light = Light::FullBright;
|
||||
q.behaviour = Behaviour::HugeExplosion;
|
||||
q.set = set;
|
||||
@@ -1470,6 +1581,69 @@ impl ParticleEngine {
|
||||
q.size_curve = Size::GrowIn;
|
||||
q
|
||||
}
|
||||
T::DustColorTransition => {
|
||||
let mut q = Particle::moving(r, ty, p, v);
|
||||
q.friction = 0.96;
|
||||
q.speed_up_when_y_blocked = true;
|
||||
for c in &mut q.velocity {
|
||||
*c *= f64::from(0.1f32);
|
||||
}
|
||||
q.size *= 0.75 * o.scale;
|
||||
let base = (8.0 / (r.next_double() * 0.8 + 0.2)) as i32;
|
||||
q.lifetime = ((base as f32 * o.scale).max(1.0)) as i32;
|
||||
let factor = r.next_float() * 0.4 + 0.6;
|
||||
let mut randomize = |c: f32| (r.next_float() * 0.2 + 0.8) * c * factor;
|
||||
let from = [
|
||||
randomize(o.color[0]),
|
||||
randomize(o.color[1]),
|
||||
randomize(o.color[2]),
|
||||
];
|
||||
let to = [
|
||||
randomize(o.to_color[0]),
|
||||
randomize(o.to_color[1]),
|
||||
randomize(o.to_color[2]),
|
||||
];
|
||||
q.size_curve = Size::GrowIn;
|
||||
q.behaviour = Behaviour::Transition { from, to };
|
||||
q.set = set;
|
||||
q
|
||||
}
|
||||
// SculkChargeParticle / SculkChargePopParticle.
|
||||
T::SculkCharge | T::SculkChargePop => {
|
||||
let mut q = Particle::moving(r, ty, p, v);
|
||||
q.friction = 0.96;
|
||||
q.scale(if ty == T::SculkCharge { 1.5 } else { 1.0 });
|
||||
q.has_physics = false;
|
||||
q.velocity = v;
|
||||
q.light = Light::Block15;
|
||||
q.behaviour = Behaviour::Animated;
|
||||
q.set = set;
|
||||
if ty == T::SculkCharge {
|
||||
q.roll = o.scale;
|
||||
q.o_roll = o.scale;
|
||||
q.lifetime = r.next_int_bound(12).unwrap_or(0) + 8;
|
||||
} else {
|
||||
q.lifetime = r.next_int_bound(4).unwrap_or(0) + 6;
|
||||
}
|
||||
q
|
||||
}
|
||||
// Vibration signals are created by `vibration`, aimed at a listener.
|
||||
T::Vibration => return None,
|
||||
// ShriekParticle.
|
||||
T::Shriek => {
|
||||
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
|
||||
q.size = 0.85;
|
||||
q.lifetime = 30;
|
||||
q.gravity = 0.0;
|
||||
q.velocity = [0.0, 0.1, 0.0];
|
||||
q.light = Light::Block15;
|
||||
q.size_curve = Size::Shriek;
|
||||
q.behaviour = Behaviour::Shriek {
|
||||
delay: o.scale as i32,
|
||||
};
|
||||
q.set = set;
|
||||
q
|
||||
}
|
||||
T::Dust => {
|
||||
let mut q = Particle::moving(r, ty, p, v);
|
||||
q.friction = 0.96;
|
||||
@@ -1662,6 +1836,24 @@ impl ParticleEngine {
|
||||
q.set_power(o.scale);
|
||||
q
|
||||
}
|
||||
T::Trail => {
|
||||
let (target, duration) = o.trail?;
|
||||
let mut q = Particle::at(r, ty, p);
|
||||
let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25;
|
||||
let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r));
|
||||
q.set_color(
|
||||
(o.color[0] * jr).min(1.0),
|
||||
(o.color[1] * jg).min(1.0),
|
||||
(o.color[2] * jb).min(1.0),
|
||||
);
|
||||
q.size = 0.26;
|
||||
q.lifetime = duration;
|
||||
q.has_physics = false;
|
||||
q.free_move = true;
|
||||
q.light = Light::FullBright;
|
||||
q.behaviour = Behaviour::Trail { target };
|
||||
q
|
||||
}
|
||||
};
|
||||
if particle.set.is_some() {
|
||||
particle.sprite = self.first(ty);
|
||||
@@ -2146,6 +2338,62 @@ impl ParticleEngine {
|
||||
start[2] + p.velocity[2] * f64::from(pos),
|
||||
];
|
||||
}
|
||||
Behaviour::Transition { .. } => {
|
||||
p.base_tick(level);
|
||||
self.sprite_from_age(p);
|
||||
}
|
||||
Behaviour::Shriek { delay } => {
|
||||
if delay > 0 {
|
||||
p.behaviour = Behaviour::Shriek { delay: delay - 1 };
|
||||
} else {
|
||||
p.base_tick(level);
|
||||
self.sprite_from_age(p);
|
||||
}
|
||||
}
|
||||
Behaviour::Vibration {
|
||||
dest, rot, pitch, ..
|
||||
} => {
|
||||
p.previous = p.position;
|
||||
let age = p.age;
|
||||
p.age += 1;
|
||||
if age >= p.lifetime {
|
||||
p.removed = true;
|
||||
return;
|
||||
}
|
||||
let remaining = p.lifetime - p.age;
|
||||
if remaining > 0 {
|
||||
let alpha = 1.0 / f64::from(remaining);
|
||||
for i in 0..3 {
|
||||
p.position[i] += (dest[i] - p.position[i]) * alpha;
|
||||
}
|
||||
}
|
||||
let d = [
|
||||
p.position[0] - dest[0],
|
||||
p.position[1] - dest[1],
|
||||
p.position[2] - dest[2],
|
||||
];
|
||||
p.behaviour = Behaviour::Vibration {
|
||||
dest,
|
||||
rot: d[0].atan2(d[2]) as f32,
|
||||
rot_o: rot,
|
||||
pitch: d[1].atan2((d[0] * d[0] + d[2] * d[2]).sqrt()) as f32,
|
||||
pitch_o: pitch,
|
||||
};
|
||||
self.sprite_from_age(p);
|
||||
}
|
||||
Behaviour::Trail { target } => {
|
||||
p.previous = p.position;
|
||||
let age = p.age;
|
||||
p.age += 1;
|
||||
if age >= p.lifetime {
|
||||
p.removed = true;
|
||||
return;
|
||||
}
|
||||
let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1));
|
||||
for i in 0..3 {
|
||||
p.position[i] += (target[i] - p.position[i]) * alpha;
|
||||
}
|
||||
}
|
||||
Behaviour::HugeExplosion => {
|
||||
p.previous = p.position;
|
||||
let age = p.age;
|
||||
@@ -2403,6 +2651,58 @@ impl ParticleEngine {
|
||||
if let Behaviour::FlyTowards { alpha: la, .. } = p.behaviour {
|
||||
alpha = lifetime_alpha(la, p.age, p.lifetime, partial);
|
||||
}
|
||||
let mut rotations = [Some(rotation), None];
|
||||
let mut rgb = [p.rgba[0], p.rgba[1], p.rgba[2]];
|
||||
match p.behaviour {
|
||||
// ShriekParticle.extract: two tilted quads, fading out.
|
||||
Behaviour::Shriek { delay } => {
|
||||
if delay > 0 {
|
||||
continue;
|
||||
}
|
||||
alpha = 1.0 - ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0);
|
||||
rotations = [
|
||||
Some(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_3)),
|
||||
Some(Quat::from_euler(
|
||||
glam::EulerRot::YXZ,
|
||||
-std::f32::consts::PI,
|
||||
std::f32::consts::FRAC_PI_3,
|
||||
0.0,
|
||||
)),
|
||||
];
|
||||
}
|
||||
// VibrationSignalParticle.extract: two quads along the flight.
|
||||
Behaviour::Vibration {
|
||||
rot,
|
||||
rot_o,
|
||||
pitch,
|
||||
pitch_o,
|
||||
..
|
||||
} => {
|
||||
let sway =
|
||||
((p.age as f32 + partial - std::f32::consts::TAU) * 0.05).sin() * 2.0;
|
||||
let lerped_rot = rot_o + (rot - rot_o) * partial;
|
||||
let lerped_pitch =
|
||||
pitch_o + (pitch - pitch_o) * partial + std::f32::consts::FRAC_PI_2;
|
||||
rotations = [
|
||||
Some(
|
||||
Quat::from_rotation_y(lerped_rot)
|
||||
* Quat::from_rotation_x(-lerped_pitch)
|
||||
* Quat::from_rotation_y(sway),
|
||||
),
|
||||
Some(
|
||||
Quat::from_rotation_y(-std::f32::consts::PI + lerped_rot)
|
||||
* Quat::from_rotation_x(lerped_pitch)
|
||||
* Quat::from_rotation_y(sway),
|
||||
),
|
||||
];
|
||||
}
|
||||
// DustColorTransitionParticle.lerpColors.
|
||||
Behaviour::Transition { from, to } => {
|
||||
let t = (p.age as f32 + partial) / (p.lifetime as f32 + 1.0);
|
||||
rgb = std::array::from_fn(|i| from[i] + (to[i] - from[i]) * t);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let block = ParticleLevel::block_at(p.position);
|
||||
let packed = light_at(block);
|
||||
let (sky, mut block_light) = (u32::from(packed >> 4) * 16, u32::from(packed & 15) * 16);
|
||||
@@ -2424,7 +2724,7 @@ impl ParticleEngine {
|
||||
}
|
||||
let light = sky_light | block_light << 8;
|
||||
let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0) as u32;
|
||||
let color = c(alpha) << 24 | c(p.rgba[2]) << 16 | c(p.rgba[1]) << 8 | c(p.rgba[0]);
|
||||
let color = c(alpha) << 24 | c(rgb[2]) << 16 | c(rgb[1]) << 8 | c(rgb[0]);
|
||||
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
|
||||
let (u0, v0, u1, v1) = (
|
||||
r.u0 + du * p.uv[0],
|
||||
@@ -2432,20 +2732,22 @@ impl ParticleEngine {
|
||||
r.u0 + du * p.uv[2],
|
||||
r.v0 + dv * p.uv[3],
|
||||
);
|
||||
for (n, uv) in [
|
||||
((1.0, -1.0), [u1, v1]),
|
||||
((1.0, 1.0), [u1, v0]),
|
||||
((-1.0, 1.0), [u0, v0]),
|
||||
((-1.0, -1.0), [u0, v1]),
|
||||
] {
|
||||
let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size;
|
||||
out.push(Vertex {
|
||||
pos: v.to_array(),
|
||||
uv,
|
||||
layer: 0,
|
||||
color,
|
||||
light,
|
||||
});
|
||||
for rotation in rotations.into_iter().flatten() {
|
||||
for (n, uv) in [
|
||||
((1.0, -1.0), [u1, v1]),
|
||||
((1.0, 1.0), [u1, v0]),
|
||||
((-1.0, 1.0), [u0, v0]),
|
||||
((-1.0, -1.0), [u0, v1]),
|
||||
] {
|
||||
let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size;
|
||||
out.push(Vertex {
|
||||
pos: v.to_array(),
|
||||
uv,
|
||||
layer: 0,
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,107 @@
|
||||
//! `RandomSequences`: the named random streams `/random` draws from.
|
||||
use horizon_core::random::{XoroshiroRandom, mix_stafford13, seed_from_hash};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const GOLDEN_RATIO: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
const SILVER_RATIO: u64 = 0x6a09_e667_f3bc_c909;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RandomSequences {
|
||||
salt: i32,
|
||||
include_world_seed: bool,
|
||||
include_sequence_id: bool,
|
||||
sequences: BTreeMap<String, XoroshiroRandom>,
|
||||
}
|
||||
impl Default for RandomSequences {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
salt: 0,
|
||||
include_world_seed: true,
|
||||
include_sequence_id: true,
|
||||
sequences: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `RandomSequence.createSequence`.
|
||||
fn create(id: &str, world_seed: i64, salt: i32, world: bool, with_id: bool) -> XoroshiroRandom {
|
||||
let seed = (if world { world_seed } else { 0 }) ^ i64::from(salt);
|
||||
let mut lo = seed as u64 ^ SILVER_RATIO;
|
||||
let mut hi = lo.wrapping_add(GOLDEN_RATIO);
|
||||
if with_id {
|
||||
let [a, b] = seed_from_hash(id);
|
||||
lo ^= a;
|
||||
hi ^= b;
|
||||
}
|
||||
XoroshiroRandom::from_state(mix_stafford13(lo), mix_stafford13(hi))
|
||||
}
|
||||
impl RandomSequences {
|
||||
pub fn get(&mut self, id: &str, world_seed: i64) -> &mut XoroshiroRandom {
|
||||
let (salt, w, i) = (self.salt, self.include_world_seed, self.include_sequence_id);
|
||||
self.sequences
|
||||
.entry(id.to_owned())
|
||||
.or_insert_with(|| create(id, world_seed, salt, w, i))
|
||||
}
|
||||
pub fn ids(&self) -> Vec<String> {
|
||||
self.sequences.keys().cloned().collect()
|
||||
}
|
||||
pub fn clear(&mut self) -> usize {
|
||||
let n = self.sequences.len();
|
||||
self.sequences.clear();
|
||||
n
|
||||
}
|
||||
pub fn set_defaults(&mut self, salt: i32, include_world_seed: bool, include_sequence_id: bool) {
|
||||
self.salt = salt;
|
||||
self.include_world_seed = include_world_seed;
|
||||
self.include_sequence_id = include_sequence_id;
|
||||
}
|
||||
pub fn reset(&mut self, id: &str, world_seed: i64) {
|
||||
let (salt, w, i) = (self.salt, self.include_world_seed, self.include_sequence_id);
|
||||
self.sequences
|
||||
.insert(id.to_owned(), create(id, world_seed, salt, w, i));
|
||||
}
|
||||
pub fn reset_with(&mut self, id: &str, world_seed: i64, salt: i32, w: bool, i: bool) {
|
||||
self.sequences
|
||||
.insert(id.to_owned(), create(id, world_seed, salt, w, i));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
#[test]
|
||||
fn sequences_are_deterministic_and_resettable() {
|
||||
let mut a = RandomSequences::default();
|
||||
let first: Vec<i32> = (0..4)
|
||||
.map(|_| a.get("minecraft:x", 42).next_int_bound(100).unwrap())
|
||||
.collect();
|
||||
let mut b = RandomSequences::default();
|
||||
let again: Vec<i32> = (0..4)
|
||||
.map(|_| b.get("minecraft:x", 42).next_int_bound(100).unwrap())
|
||||
.collect();
|
||||
assert_eq!(first, again);
|
||||
// Another id or seed gives another stream.
|
||||
let other = RandomSequences::default()
|
||||
.get("minecraft:y", 42)
|
||||
.next_long();
|
||||
let same = RandomSequences::default()
|
||||
.get("minecraft:x", 42)
|
||||
.next_long();
|
||||
assert_ne!(other, same);
|
||||
// Reset restarts it.
|
||||
a.reset("minecraft:x", 42);
|
||||
assert_eq!(
|
||||
a.get("minecraft:x", 42).next_int_bound(100).unwrap(),
|
||||
first[0]
|
||||
);
|
||||
// Defaults change what new sequences start from.
|
||||
a.set_defaults(7, false, false);
|
||||
a.reset("minecraft:x", 42);
|
||||
let v = a.get("minecraft:x", 1).next_long();
|
||||
let mut c = RandomSequences::default();
|
||||
c.set_defaults(7, false, false);
|
||||
assert_eq!(c.get("minecraft:z", 999).next_long(), v);
|
||||
assert_eq!(a.clear(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,685 @@
|
||||
//! The recipe book: what the book shows for each menu (`RecipeBookType`
|
||||
//! tabs, `RecipeBookCategories`, groups), which recipes the player can craft
|
||||
//! with the items at hand (`StackedItemContents.canCraft` and the biggest
|
||||
//! craftable stack), where a recipe goes in a grid (`PlaceRecipeHelper`) and
|
||||
//! the book's saved settings.
|
||||
use crate::{
|
||||
crafting::{Ingredient, Recipe, Recipes},
|
||||
items::{ItemStack, Items},
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
/// `RecipeBookType`: the menus with a recipe book and their own settings.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub enum BookType {
|
||||
Crafting,
|
||||
Furnace,
|
||||
BlastFurnace,
|
||||
Smoker,
|
||||
}
|
||||
impl BookType {
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::Crafting,
|
||||
Self::Furnace,
|
||||
Self::BlastFurnace,
|
||||
Self::Smoker,
|
||||
];
|
||||
pub fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
/// `RecipeBookSettings` keys in the player's `recipeBook` compound.
|
||||
fn keys(self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
Self::Crafting => ("isGuiOpen", "isFilteringCraftable"),
|
||||
Self::Furnace => ("isFurnaceGuiOpen", "isFurnaceFilteringCraftable"),
|
||||
Self::BlastFurnace => (
|
||||
"isBlastingFurnaceGuiOpen",
|
||||
"isBlastingFurnaceFilteringCraftable",
|
||||
),
|
||||
Self::Smoker => ("isSmokerGuiOpen", "isSmokerFilteringCraftable"),
|
||||
}
|
||||
}
|
||||
/// The tab buttons of the book's screen, search first.
|
||||
pub fn tabs(self) -> Vec<Tab> {
|
||||
use Category::*;
|
||||
let categories: &[Category] = match self {
|
||||
Self::Crafting => &[
|
||||
CraftingEquipment,
|
||||
CraftingBuilding,
|
||||
CraftingMisc,
|
||||
CraftingRedstone,
|
||||
],
|
||||
Self::Furnace => &[FurnaceFood, FurnaceBlocks, FurnaceMisc],
|
||||
Self::BlastFurnace => &[BlastBlocks, BlastMisc],
|
||||
Self::Smoker => &[SmokerFood],
|
||||
};
|
||||
std::iter::once(Tab::Search)
|
||||
.chain(categories.iter().map(|c| Tab::Category(*c)))
|
||||
.collect()
|
||||
}
|
||||
/// The categories the search tab lists, in `SearchRecipeBookCategory` order.
|
||||
fn search_categories(self) -> &'static [Category] {
|
||||
use Category::*;
|
||||
match self {
|
||||
Self::Crafting => &[
|
||||
CraftingEquipment,
|
||||
CraftingBuilding,
|
||||
CraftingMisc,
|
||||
CraftingRedstone,
|
||||
],
|
||||
Self::Furnace => &[FurnaceFood, FurnaceBlocks, FurnaceMisc],
|
||||
Self::BlastFurnace => &[BlastBlocks, BlastMisc],
|
||||
Self::Smoker => &[SmokerFood],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeBookCategories` of the four menus' recipes.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub enum Category {
|
||||
CraftingBuilding,
|
||||
CraftingRedstone,
|
||||
CraftingEquipment,
|
||||
CraftingMisc,
|
||||
FurnaceFood,
|
||||
FurnaceBlocks,
|
||||
FurnaceMisc,
|
||||
BlastBlocks,
|
||||
BlastMisc,
|
||||
SmokerFood,
|
||||
}
|
||||
/// A tab button: the search tab or one category.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub enum Tab {
|
||||
Search,
|
||||
Category(Category),
|
||||
}
|
||||
impl Tab {
|
||||
/// The tab's icon items (`TabInfo`).
|
||||
pub fn icons(self) -> (&'static str, Option<&'static str>) {
|
||||
use Category::*;
|
||||
match self {
|
||||
Self::Search => ("minecraft:compass", None),
|
||||
Self::Category(c) => match c {
|
||||
CraftingEquipment => ("minecraft:iron_axe", Some("minecraft:golden_sword")),
|
||||
CraftingBuilding => ("minecraft:bricks", None),
|
||||
CraftingMisc => ("minecraft:lava_bucket", Some("minecraft:apple")),
|
||||
CraftingRedstone => ("minecraft:redstone", None),
|
||||
FurnaceFood | SmokerFood => ("minecraft:porkchop", None),
|
||||
FurnaceBlocks => ("minecraft:stone", None),
|
||||
FurnaceMisc => ("minecraft:lava_bucket", Some("minecraft:emerald")),
|
||||
BlastBlocks => ("minecraft:redstone_ore", None),
|
||||
BlastMisc => ("minecraft:iron_shovel", Some("minecraft:golden_leggings")),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeDisplay`: how a recipe is laid out.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Display {
|
||||
Shaped {
|
||||
width: usize,
|
||||
height: usize,
|
||||
cells: Vec<Option<Ingredient>>,
|
||||
},
|
||||
Shapeless(Vec<Ingredient>),
|
||||
/// A smelting-type recipe: its input; the fuel is any fuel.
|
||||
Furnace(Ingredient),
|
||||
}
|
||||
/// One recipe of the book (`RecipeDisplayEntry`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Entry {
|
||||
/// The recipe id, `minecraft:name`.
|
||||
pub id: String,
|
||||
pub category: Category,
|
||||
pub group: Option<String>,
|
||||
pub display: Display,
|
||||
pub result: ItemStack,
|
||||
}
|
||||
impl Entry {
|
||||
/// The ingredients that must be matched to craft it, in order.
|
||||
pub fn requirements(&self) -> Vec<&Ingredient> {
|
||||
match &self.display {
|
||||
Display::Shaped { cells, .. } => cells.iter().flatten().collect(),
|
||||
Display::Shapeless(list) => list.iter().collect(),
|
||||
Display::Furnace(i) => vec![i],
|
||||
}
|
||||
}
|
||||
/// `CraftingRecipeBookComponent.canDisplay` for a grid.
|
||||
pub fn fits(&self, grid_width: usize, grid_height: usize) -> bool {
|
||||
match &self.display {
|
||||
Display::Shaped { width, height, .. } => grid_width >= *width && grid_height >= *height,
|
||||
Display::Shapeless(list) => grid_width * grid_height >= list.len(),
|
||||
Display::Furnace(_) => true,
|
||||
}
|
||||
}
|
||||
/// The size the recipe takes in the grid (`PlaceRecipeHelper`).
|
||||
pub fn size_in(&self, grid_width: usize, grid_height: usize) -> (usize, usize) {
|
||||
match &self.display {
|
||||
Display::Shaped { width, height, .. } => (*width, *height),
|
||||
_ => (grid_width, grid_height),
|
||||
}
|
||||
}
|
||||
/// The ingredient of each grid cell the recipe fills, with its grid index
|
||||
/// (the ghost recipe and the placement use the same layout).
|
||||
pub fn grid_cells(&self, grid_width: usize, grid_height: usize) -> Vec<(Option<usize>, usize)> {
|
||||
let (w, h) = self.size_in(grid_width, grid_height);
|
||||
// One entry per recipe cell: the index of its ingredient, if any.
|
||||
let entries: Vec<Option<usize>> = match &self.display {
|
||||
Display::Shaped { cells, .. } => {
|
||||
let mut next = 0;
|
||||
cells
|
||||
.iter()
|
||||
.map(|c| {
|
||||
c.as_ref().map(|_| {
|
||||
next += 1;
|
||||
next - 1
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Display::Shapeless(list) => (0..list.len()).map(Some).collect(),
|
||||
Display::Furnace(_) => vec![Some(0)],
|
||||
};
|
||||
place_cells(grid_width, grid_height, w, h, &entries)
|
||||
}
|
||||
}
|
||||
|
||||
/// `PlaceRecipeHelper.placeRecipe`: the grid index each entry goes to; a
|
||||
/// recipe smaller than half the grid is centred.
|
||||
pub fn place_cells<T: Clone>(
|
||||
grid_width: usize,
|
||||
grid_height: usize,
|
||||
recipe_width: usize,
|
||||
recipe_height: usize,
|
||||
entries: &[T],
|
||||
) -> Vec<(T, usize)> {
|
||||
let mut out = Vec::new();
|
||||
let mut iter = entries.iter().peekable();
|
||||
let mut index = 0usize;
|
||||
let mut y = 0;
|
||||
while y < grid_height {
|
||||
let center_rows = (recipe_height as f32) < grid_height as f32 / 2.0;
|
||||
let start_row = (grid_height as f32 / 2.0 - recipe_height as f32 / 2.0).floor() as usize;
|
||||
if center_rows && start_row > y {
|
||||
index += grid_width;
|
||||
y += 1;
|
||||
}
|
||||
for x in 0..grid_width {
|
||||
if iter.peek().is_none() {
|
||||
return out;
|
||||
}
|
||||
let center_cols = (recipe_width as f32) < grid_width as f32 / 2.0;
|
||||
let start_col = (grid_width as f32 / 2.0 - recipe_width as f32 / 2.0).floor() as usize;
|
||||
let mut total = recipe_width;
|
||||
let mut add = x < recipe_width;
|
||||
if center_cols {
|
||||
total = start_col + recipe_width;
|
||||
add = start_col <= x && x < start_col + recipe_width;
|
||||
}
|
||||
if add {
|
||||
if let Some(item) = iter.next() {
|
||||
out.push((item.clone(), index));
|
||||
}
|
||||
} else if total == x {
|
||||
index += grid_width - x;
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
y += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A group of recipes shown as one button (`RecipeCollection`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Collection {
|
||||
/// Indices into `Book::entries`.
|
||||
pub entries: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Every recipe the menus' books can show.
|
||||
#[derive(Default)]
|
||||
pub struct Book {
|
||||
pub entries: Vec<Entry>,
|
||||
/// Item id -> registry position, to order ingredient choices.
|
||||
pub order: HashMap<String, usize>,
|
||||
}
|
||||
fn crafting_category(name: &str) -> Category {
|
||||
match name {
|
||||
"building" => Category::CraftingBuilding,
|
||||
"redstone" => Category::CraftingRedstone,
|
||||
"equipment" => Category::CraftingEquipment,
|
||||
_ => Category::CraftingMisc,
|
||||
}
|
||||
}
|
||||
impl Book {
|
||||
pub fn build(recipes: &Recipes, items: &Items) -> Self {
|
||||
let mut entries = Vec::new();
|
||||
let group = |s: &str| (!s.is_empty()).then(|| s.to_owned());
|
||||
for (name, recipe) in &recipes.crafting {
|
||||
let (category, grp) = recipes.meta.get(name).cloned().unwrap_or_default();
|
||||
let (display, result) = match recipe {
|
||||
Recipe::Shaped {
|
||||
width,
|
||||
height,
|
||||
cells,
|
||||
result,
|
||||
} => (
|
||||
Display::Shaped {
|
||||
width: *width,
|
||||
height: *height,
|
||||
cells: cells.clone(),
|
||||
},
|
||||
result,
|
||||
),
|
||||
Recipe::Shapeless {
|
||||
ingredients,
|
||||
result,
|
||||
} => (Display::Shapeless(ingredients.clone()), result),
|
||||
Recipe::Special(_) => continue,
|
||||
};
|
||||
entries.push(Entry {
|
||||
id: format!("minecraft:{name}"),
|
||||
category: crafting_category(&category),
|
||||
group: group(&grp),
|
||||
display,
|
||||
result: result.clone(),
|
||||
});
|
||||
}
|
||||
for c in &recipes.cooking {
|
||||
let category = match (c.kind.as_str(), c.category.as_str()) {
|
||||
("minecraft:smelting", "food") => Category::FurnaceFood,
|
||||
("minecraft:smelting", "blocks") => Category::FurnaceBlocks,
|
||||
("minecraft:smelting", _) => Category::FurnaceMisc,
|
||||
("minecraft:blasting", "blocks") => Category::BlastBlocks,
|
||||
("minecraft:blasting", _) => Category::BlastMisc,
|
||||
("minecraft:smoking", _) => Category::SmokerFood,
|
||||
_ => continue,
|
||||
};
|
||||
entries.push(Entry {
|
||||
id: format!("minecraft:{}", c.id),
|
||||
category,
|
||||
group: group(&c.group),
|
||||
display: Display::Furnace(c.ingredient.clone()),
|
||||
result: c.result.clone(),
|
||||
});
|
||||
}
|
||||
let order = items
|
||||
.order
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, id)| (id.to_string(), i))
|
||||
.collect();
|
||||
Self { entries, order }
|
||||
}
|
||||
/// The unlocked recipes of one tab as collections (`ClientRecipeBook.rebuildCollections`).
|
||||
pub fn collections(
|
||||
&self,
|
||||
unlocked: &BTreeSet<String>,
|
||||
book: BookType,
|
||||
tab: Tab,
|
||||
) -> Vec<Collection> {
|
||||
let categories: Vec<Category> = match tab {
|
||||
Tab::Search => book.search_categories().to_vec(),
|
||||
Tab::Category(c) => vec![c],
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for category in categories {
|
||||
let mut by_group: HashMap<&str, usize> = HashMap::new();
|
||||
let start = out.len();
|
||||
for (i, e) in self.entries.iter().enumerate() {
|
||||
if e.category != category || !unlocked.contains(&e.id) {
|
||||
continue;
|
||||
}
|
||||
match e.group.as_deref().and_then(|g| by_group.get(g).copied()) {
|
||||
Some(c) => {
|
||||
let c: usize = c;
|
||||
let collection: &mut Collection = &mut out[start + c];
|
||||
collection.entries.push(i);
|
||||
}
|
||||
None => {
|
||||
if let Some(g) = e.group.as_deref() {
|
||||
by_group.insert(g, out.len() - start);
|
||||
}
|
||||
out.push(Collection { entries: vec![i] });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Which book a recipe id belongs to.
|
||||
pub fn book_of(&self, id: &str) -> Option<BookType> {
|
||||
let e = self.entries.iter().find(|e| e.id == id)?;
|
||||
Some(match e.category {
|
||||
Category::CraftingBuilding
|
||||
| Category::CraftingRedstone
|
||||
| Category::CraftingEquipment
|
||||
| Category::CraftingMisc => BookType::Crafting,
|
||||
Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => {
|
||||
BookType::Furnace
|
||||
}
|
||||
Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace,
|
||||
Category::SmokerFood => BookType::Smoker,
|
||||
})
|
||||
}
|
||||
pub fn entry(&self, id: &str) -> Option<&Entry> {
|
||||
self.entries.iter().find(|e| e.id == id)
|
||||
}
|
||||
/// `ingredient`'s items in registry order (the cycling order of ghost slots).
|
||||
pub fn items_of(&self, ingredient: &Ingredient) -> Vec<String> {
|
||||
let mut items: Vec<String> = ingredient.0.iter().cloned().collect();
|
||||
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
|
||||
items
|
||||
}
|
||||
/// `RecipeCollection` search: the result's name or registry path, or
|
||||
/// `@namespace`.
|
||||
pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool {
|
||||
let query = query.to_lowercase();
|
||||
if let Some(ns) = query.strip_prefix('@') {
|
||||
return entry
|
||||
.result
|
||||
.item
|
||||
.split(':')
|
||||
.next()
|
||||
.is_some_and(|n| n.starts_with(ns));
|
||||
}
|
||||
name.to_lowercase().contains(&query)
|
||||
|| entry
|
||||
.result
|
||||
.item
|
||||
.trim_start_matches("minecraft:")
|
||||
.contains(&query)
|
||||
}
|
||||
}
|
||||
|
||||
/// `StackedItemContents`: simple stacks (undamaged, unenchanted, unnamed) by item.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Available {
|
||||
pub counts: HashMap<String, u32>,
|
||||
}
|
||||
impl Available {
|
||||
/// `accountSimpleStack`.
|
||||
pub fn add(&mut self, stack: &ItemStack) {
|
||||
if stack.count > 0
|
||||
&& stack.damage == 0
|
||||
&& stack.enchantments().is_empty()
|
||||
&& stack.custom_name().is_none()
|
||||
{
|
||||
*self.counts.entry(stack.item.to_string()).or_default() += stack.count;
|
||||
}
|
||||
}
|
||||
pub fn from_stacks<'a>(stacks: impl IntoIterator<Item = &'a ItemStack>) -> Self {
|
||||
let mut a = Self::default();
|
||||
for s in stacks {
|
||||
a.add(s);
|
||||
}
|
||||
a
|
||||
}
|
||||
/// `StackedItemContents.canCraft(ingredients, null)`.
|
||||
pub fn can_craft(&self, requirements: &[&Ingredient]) -> bool {
|
||||
!requirements.is_empty() && pick(requirements, &self.counts, 1, &HashMap::new()).is_some()
|
||||
}
|
||||
/// `canCraft(recipe, amount, output)`: the item each ingredient uses when
|
||||
/// `amount` sets can be made, preferring earlier registry items.
|
||||
pub fn pick(
|
||||
&self,
|
||||
requirements: &[&Ingredient],
|
||||
amount: u32,
|
||||
order: &HashMap<String, usize>,
|
||||
) -> Option<Vec<String>> {
|
||||
pick(requirements, &self.counts, amount, order)
|
||||
}
|
||||
/// `getBiggestCraftableStack`: how many sets can be made, up to 99.
|
||||
pub fn biggest_stack(&self, requirements: &[&Ingredient]) -> u32 {
|
||||
if !self.can_craft(requirements) {
|
||||
return 0;
|
||||
}
|
||||
let none = HashMap::new();
|
||||
let (mut lo, mut hi) = (1u32, 99u32);
|
||||
while lo < hi {
|
||||
let mid = (lo + hi).div_ceil(2);
|
||||
if pick(requirements, &self.counts, mid, &none).is_some() {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
lo
|
||||
}
|
||||
}
|
||||
/// Bipartite assignment of one item to each ingredient where an item can
|
||||
/// serve `count / amount` ingredients.
|
||||
fn pick(
|
||||
requirements: &[&Ingredient],
|
||||
counts: &HashMap<String, u32>,
|
||||
amount: u32,
|
||||
order: &HashMap<String, usize>,
|
||||
) -> Option<Vec<String>> {
|
||||
let amount = amount.max(1);
|
||||
let capacity = |item: &str| counts.get(item).copied().unwrap_or(0) / amount;
|
||||
let candidates: Vec<Vec<String>> = requirements
|
||||
.iter()
|
||||
.map(|ing| {
|
||||
let mut v: Vec<String> = ing.0.iter().filter(|i| capacity(i) > 0).cloned().collect();
|
||||
v.sort_by_key(|i| (order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let mut used: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
fn assign(
|
||||
i: usize,
|
||||
candidates: &[Vec<String>],
|
||||
used: &mut HashMap<String, Vec<usize>>,
|
||||
visited: &mut Vec<String>,
|
||||
capacity: &dyn Fn(&str) -> u32,
|
||||
) -> bool {
|
||||
for item in &candidates[i] {
|
||||
if visited.contains(item) {
|
||||
continue;
|
||||
}
|
||||
visited.push(item.clone());
|
||||
let holders = used.get(item).cloned().unwrap_or_default();
|
||||
if (holders.len() as u32) < capacity(item) {
|
||||
used.entry(item.clone()).or_default().push(i);
|
||||
return true;
|
||||
}
|
||||
for j in holders {
|
||||
if assign(j, candidates, used, visited, capacity) {
|
||||
// j moved elsewhere: drop it from this item and take its place.
|
||||
if let Some(list) = used.get_mut(item) {
|
||||
list.retain(|x| *x != j);
|
||||
list.push(i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
for i in 0..requirements.len() {
|
||||
let mut visited = Vec::new();
|
||||
if !assign(i, &candidates, &mut used, &mut visited, &capacity) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut result = vec![String::new(); requirements.len()];
|
||||
for (item, holders) in used {
|
||||
for i in holders {
|
||||
result[i] = item.clone();
|
||||
}
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
/// The recipe book's saved state: the `recipeBook` compound of the player.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Settings {
|
||||
/// `isGuiOpen`-style flags per `BookType`.
|
||||
pub open: [bool; 4],
|
||||
pub filtering: [bool; 4],
|
||||
/// Unlocked recipe ids (`recipes`).
|
||||
pub recipes: Vec<String>,
|
||||
}
|
||||
impl Settings {
|
||||
pub fn read(tag: Option<&Tag>) -> Self {
|
||||
let mut s = Self::default();
|
||||
let Some(tag) = tag else { return s };
|
||||
let flag = |k: &str| matches!(tag.get(k), Some(Tag::Byte(b)) if *b != 0);
|
||||
for b in BookType::ALL {
|
||||
let (open, filter) = b.keys();
|
||||
s.open[b.index()] = flag(open);
|
||||
s.filtering[b.index()] = flag(filter);
|
||||
}
|
||||
if let Some(Tag::List(list)) = tag.get("recipes") {
|
||||
s.recipes = list
|
||||
.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::String(id) => Some(id.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
s
|
||||
}
|
||||
/// The compound written to the player file; `toBeDisplayed` stays empty.
|
||||
pub fn write(&self) -> Tag {
|
||||
let mut entries: Vec<(&str, Tag)> = Vec::new();
|
||||
for b in BookType::ALL {
|
||||
let (open, filter) = b.keys();
|
||||
entries.push((open, Tag::Byte(i8::from(self.open[b.index()]))));
|
||||
entries.push((filter, Tag::Byte(i8::from(self.filtering[b.index()]))));
|
||||
}
|
||||
let list = |ids: &[String]| {
|
||||
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
|
||||
};
|
||||
entries.push(("recipes", list(&self.recipes)));
|
||||
entries.push(("toBeDisplayed", Tag::List(Vec::new())));
|
||||
Tag::compound(entries)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ing(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn have(items: &[(&str, u32)]) -> Available {
|
||||
Available {
|
||||
counts: items.iter().map(|(i, n)| ((*i).to_owned(), *n)).collect(),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn small_recipes_are_centred_in_the_grid() {
|
||||
// One ingredient in a 3x3 grid goes to the middle cell.
|
||||
assert_eq!(place_cells(3, 3, 1, 1, &['a']), vec![('a', 4)]);
|
||||
// A 2x2 recipe fills the top-left corner.
|
||||
let cells: Vec<usize> = place_cells(3, 3, 2, 2, &['a', 'b', 'c', 'd'])
|
||||
.into_iter()
|
||||
.map(|(_, i)| i)
|
||||
.collect();
|
||||
assert_eq!(cells, vec![0, 1, 3, 4]);
|
||||
// A one-row recipe sits on the middle row.
|
||||
let row: Vec<usize> = place_cells(3, 3, 3, 1, &['a', 'b', 'c'])
|
||||
.into_iter()
|
||||
.map(|(_, i)| i)
|
||||
.collect();
|
||||
assert_eq!(row, vec![3, 4, 5]);
|
||||
// The 2x2 grid is never centred.
|
||||
let small: Vec<usize> = place_cells(2, 2, 1, 1, &['a'])
|
||||
.into_iter()
|
||||
.map(|(_, i)| i)
|
||||
.collect();
|
||||
assert_eq!(small, vec![0]);
|
||||
}
|
||||
#[test]
|
||||
fn a_single_item_can_fill_several_ingredients() {
|
||||
let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]);
|
||||
let reqs = [&planks, &planks, &planks, &planks];
|
||||
let a = have(&[("minecraft:oak_planks", 2), ("minecraft:birch_planks", 2)]);
|
||||
assert!(a.can_craft(&reqs));
|
||||
let none = HashMap::new();
|
||||
// Two sets need 8 planks, but only 4 are there.
|
||||
assert!(a.pick(&reqs, 2, &none).is_none());
|
||||
assert!(a.pick(&reqs, 1, &none).is_some());
|
||||
assert_eq!(a.biggest_stack(&reqs), 1);
|
||||
assert_eq!(
|
||||
have(&[("minecraft:oak_planks", 64)]).biggest_stack(&reqs),
|
||||
16
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn the_matching_reassigns_flexible_ingredients() {
|
||||
// The first ingredient takes either item, the second only the stick:
|
||||
// one stick must not be wasted on the first.
|
||||
let any = ing(&["minecraft:stick", "minecraft:bone"]);
|
||||
let stick = ing(&["minecraft:stick"]);
|
||||
let a = have(&[("minecraft:stick", 1), ("minecraft:bone", 1)]);
|
||||
let mut order = HashMap::new();
|
||||
order.insert("minecraft:stick".to_owned(), 0);
|
||||
order.insert("minecraft:bone".to_owned(), 1);
|
||||
let picked = a.pick(&[&any, &stick], 1, &order).expect("matching");
|
||||
assert_eq!(picked, vec!["minecraft:bone", "minecraft:stick"]);
|
||||
assert!(!have(&[("minecraft:stick", 1)]).can_craft(&[&any, &stick]));
|
||||
}
|
||||
#[test]
|
||||
fn damaged_or_named_stacks_are_not_counted() {
|
||||
let mut named = ItemStack::new("minecraft:stick", 4);
|
||||
named.data_mut().custom_name = Some("x".into());
|
||||
let mut damaged = ItemStack::new("minecraft:iron_sword", 1);
|
||||
damaged.damage = 3;
|
||||
let a = Available::from_stacks([&named, &damaged, &ItemStack::new("minecraft:stick", 2)]);
|
||||
assert_eq!(a.counts.get("minecraft:stick"), Some(&2));
|
||||
assert!(!a.counts.contains_key("minecraft:iron_sword"));
|
||||
}
|
||||
#[test]
|
||||
fn collections_group_recipes_of_a_category() {
|
||||
let entry = |id: &str, group: Option<&str>, category| Entry {
|
||||
id: id.into(),
|
||||
category,
|
||||
group: group.map(str::to_owned),
|
||||
display: Display::Shapeless(vec![ing(&["minecraft:stick"])]),
|
||||
result: ItemStack::new("minecraft:stick", 1),
|
||||
};
|
||||
let book = Book {
|
||||
entries: vec![
|
||||
entry("minecraft:a", Some("planks"), Category::CraftingBuilding),
|
||||
entry("minecraft:b", Some("planks"), Category::CraftingBuilding),
|
||||
entry("minecraft:c", None, Category::CraftingBuilding),
|
||||
entry("minecraft:d", Some("planks"), Category::CraftingMisc),
|
||||
],
|
||||
order: HashMap::new(),
|
||||
};
|
||||
let unlocked: BTreeSet<String> = ["a", "b", "c", "d"]
|
||||
.iter()
|
||||
.map(|n| format!("minecraft:{n}"))
|
||||
.collect();
|
||||
let tab = Tab::Category(Category::CraftingBuilding);
|
||||
let c = book.collections(&unlocked, BookType::Crafting, tab);
|
||||
assert_eq!(c.len(), 2);
|
||||
assert_eq!(c[0].entries, vec![0, 1]);
|
||||
// The search tab lists every category; the same group in another category is separate.
|
||||
let all = book.collections(&unlocked, BookType::Crafting, Tab::Search);
|
||||
assert_eq!(all.len(), 3);
|
||||
// Locked recipes are hidden.
|
||||
let some: BTreeSet<String> = ["minecraft:c".to_owned()].into();
|
||||
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn settings_round_trip() {
|
||||
let mut s = Settings::default();
|
||||
s.open[BookType::Furnace.index()] = true;
|
||||
s.filtering[BookType::Crafting.index()] = true;
|
||||
s.recipes = vec!["minecraft:stick".into()];
|
||||
let back = Settings::read(Some(&s.write()));
|
||||
assert_eq!(back.open, s.open);
|
||||
assert_eq!(back.filtering, s.filtering);
|
||||
assert_eq!(back.recipes, s.recipes);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user