Resolve nbt text components, other dimensions and vanilla's own data as vanilla
/tellraw resolves nbt components; execute in another dimension sees its chunks unloaded; the built-in pack's predicates load; holders stay tracked after their objective is removed; new worlds use the offline profile id of the player. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -155,6 +155,14 @@ impl Parser<'_> {
|
||||
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
|
||||
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
|
||||
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
to_text_with(v, resolve, &mut |_| None)
|
||||
}
|
||||
/// `to_text` with a hook resolving other contents (`nbt`) from the object.
|
||||
pub fn to_text_with(
|
||||
v: &Value,
|
||||
resolve: &mut dyn FnMut(&str) -> Text,
|
||||
contents: &mut dyn FnMut(&serde_json::Map<String, Value>) -> Option<Text>,
|
||||
) -> Text {
|
||||
match v {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
Value::Number(n) => Text::literal(n.to_string()),
|
||||
@@ -164,14 +172,14 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
let Some((first, rest)) = list.split_first() else {
|
||||
return Text::empty();
|
||||
};
|
||||
let mut base = to_text(first, resolve);
|
||||
let mut base = to_text_with(first, resolve, contents);
|
||||
let style = base
|
||||
.spans
|
||||
.first()
|
||||
.map(|s| s.style.clone())
|
||||
.unwrap_or_default();
|
||||
for sibling in rest {
|
||||
base.push(to_text(sibling, resolve).with_style(&style));
|
||||
base.push(to_text_with(sibling, resolve, contents).with_style(&style));
|
||||
}
|
||||
base
|
||||
}
|
||||
@@ -189,7 +197,9 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
style.underlined = flag("underlined");
|
||||
style.strikethrough = flag("strikethrough");
|
||||
style.obfuscated = flag("obfuscated");
|
||||
let content = if let Some(t) = o.get("text") {
|
||||
let content = if let Some(t) = contents(o) {
|
||||
t
|
||||
} else if let Some(t) = o.get("text") {
|
||||
match t {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
other => Text::literal(other.to_string()),
|
||||
@@ -198,7 +208,7 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
let args: Vec<Text> = o
|
||||
.get("with")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().map(|x| to_text(x, resolve)).collect())
|
||||
.map(|a| a.iter().map(|x| to_text_with(x, resolve, contents)).collect())
|
||||
.unwrap_or_default();
|
||||
let translated = Text::translate(key, &args);
|
||||
match o.get("fallback").and_then(Value::as_str) {
|
||||
@@ -219,7 +229,7 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
out.push(to_text(extra, resolve).with_style(&style));
|
||||
out.push(to_text_with(extra, resolve, contents).with_style(&style));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -67,6 +67,15 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl DataPack {
|
||||
/// The built-in `vanilla` pack: the game's own data directory.
|
||||
pub fn builtin(root: &Path) -> Self {
|
||||
DataPack {
|
||||
id: "vanilla".into(),
|
||||
source: Source::Dir(root.to_path_buf()),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// 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 {
|
||||
|
||||
@@ -286,7 +286,11 @@ impl Game<'_> {
|
||||
reg.structures = list("data/minecraft/worldgen/structure");
|
||||
reg.biomes = list("data/minecraft/worldgen/biome");
|
||||
reg.clocks = list("data/minecraft/world_clock");
|
||||
reg.dimensions = vec!["minecraft:overworld".into(), "minecraft:the_nether".into()];
|
||||
reg.dimensions = vec![
|
||||
"minecraft:overworld".into(),
|
||||
"minecraft:the_nether".into(),
|
||||
"minecraft:the_end".into(),
|
||||
];
|
||||
reg.players = vec![PLAYER_NAME.into()];
|
||||
// Timelines of the overworld clock and their time markers.
|
||||
self.ui.markers.clear();
|
||||
|
||||
@@ -183,7 +183,8 @@ impl Game<'_> {
|
||||
.ok_or_else(|| err("argument.pos.missing.int", &[]))?;
|
||||
// BlockPos.containing(getPosition)
|
||||
let p = self.resolve_coords(&c).map(|v| v.floor() as i32);
|
||||
if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
|
||||
let elsewhere = self.command_source.is_some_and(|s| s.elsewhere);
|
||||
if elsewhere || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
|
||||
return Err(err("argument.pos.unloaded", &[]));
|
||||
}
|
||||
if p[1] < horizon_client::chunk::MIN_Y
|
||||
|
||||
@@ -23,6 +23,9 @@ pub(in crate::game) struct Source {
|
||||
pub silent: bool,
|
||||
/// Index of the newest `store` in `ExecState::stores`.
|
||||
pub store: Option<u32>,
|
||||
/// `execute in` another dimension than the one Horizon has loaded: none
|
||||
/// of its chunks are loaded.
|
||||
pub elsewhere: bool,
|
||||
}
|
||||
|
||||
/// Where `execute store` writes.
|
||||
@@ -70,6 +73,7 @@ impl Game<'_> {
|
||||
eyes: false,
|
||||
silent: false,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
}
|
||||
}
|
||||
/// The server as a source (function ticks and schedules): the world spawn.
|
||||
@@ -81,6 +85,7 @@ impl Game<'_> {
|
||||
eyes: false,
|
||||
silent: true,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
}
|
||||
}
|
||||
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
|
||||
@@ -418,6 +423,7 @@ impl Game<'_> {
|
||||
Some(Source {
|
||||
pos: self.target_position(t)?,
|
||||
rot: self.target_rotation(t),
|
||||
elsewhere: false,
|
||||
..s
|
||||
})
|
||||
})
|
||||
@@ -508,14 +514,21 @@ impl Game<'_> {
|
||||
..s
|
||||
}],
|
||||
"in" => {
|
||||
// Horizon keeps one dimension loaded; others cannot be a source.
|
||||
// Horizon keeps one dimension loaded: in another one, no
|
||||
// chunk is loaded (as in vanilla without a player there).
|
||||
let Some(Arg::Resource(dim)) = c.get("dimension") else {
|
||||
return Ok(vec![s]);
|
||||
};
|
||||
if dim != self.dim.id() {
|
||||
if !matches!(
|
||||
dim.as_str(),
|
||||
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
|
||||
) {
|
||||
return Err(err("argument.dimension.invalid", &[dim]));
|
||||
}
|
||||
vec![s]
|
||||
vec![Source {
|
||||
elsewhere: dim != self.dim.id(),
|
||||
..s
|
||||
}]
|
||||
}
|
||||
"summon" => {
|
||||
let Some(Arg::Resource(kind)) = c.get("entity").cloned() else {
|
||||
|
||||
@@ -11,6 +11,34 @@ impl Game<'_> {
|
||||
};
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
|
||||
// NbtContents.resolve: the path's values in the entity, block or
|
||||
// storage data, rich-styled (or plain, or interpreted), ", "-joined.
|
||||
let nbt_values = std::cell::RefCell::new(Vec::new());
|
||||
{
|
||||
let mut collect = |o: &serde_json::Map<String, serde_json::Value>| {
|
||||
if o.contains_key("nbt") {
|
||||
nbt_values.borrow_mut().push(o.clone());
|
||||
}
|
||||
};
|
||||
fn walk(v: &serde_json::Value, f: &mut dyn FnMut(&serde_json::Map<String, serde_json::Value>)) {
|
||||
match v {
|
||||
serde_json::Value::Object(o) => {
|
||||
f(o);
|
||||
for (_, x) in o {
|
||||
walk(x, f);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(a) => a.iter().for_each(|x| walk(x, f)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
walk(&value, &mut collect);
|
||||
}
|
||||
let mut resolved: Vec<(serde_json::Map<String, serde_json::Value>, Text)> = Vec::new();
|
||||
for o in nbt_values.into_inner() {
|
||||
let t = self.resolve_nbt_component(&o);
|
||||
resolved.push((o, t));
|
||||
}
|
||||
let mut resolve = |raw: &str| -> Text {
|
||||
let mut reader = horizon_client::command::Reader::new(raw);
|
||||
let entities = horizon_client::command::args::ArgType::Entity {
|
||||
@@ -30,7 +58,77 @@ impl Game<'_> {
|
||||
}
|
||||
out
|
||||
};
|
||||
Ok(horizon_client::component::to_text(&value, &mut resolve))
|
||||
Ok(horizon_client::component::to_text_with(
|
||||
&value,
|
||||
&mut resolve,
|
||||
&mut |o| {
|
||||
resolved
|
||||
.iter()
|
||||
.find(|(k, _)| k == o)
|
||||
.map(|(_, t)| t.clone())
|
||||
},
|
||||
))
|
||||
}
|
||||
/// The text of an `nbt` component.
|
||||
fn resolve_nbt_component(&mut self, o: &serde_json::Map<String, serde_json::Value>) -> Text {
|
||||
use horizon_world::nbt::Tag;
|
||||
let path = o.get("nbt").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let mut sources: Vec<Tag> = Vec::new();
|
||||
if let Some(sel) = o.get("entity").and_then(|v| v.as_str()) {
|
||||
let mut reader = horizon_client::command::Reader::new(sel);
|
||||
let ty = horizon_client::command::args::ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
if let Ok(Arg::Entity(s)) = ty.parse(&mut reader, &self.ui.registries) {
|
||||
for t in self.select(&s) {
|
||||
if let Ok(tag) = self.data_of(&super::data::DataRef::Entity(t)) {
|
||||
sources.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = o.get("storage").and_then(|v| v.as_str()) {
|
||||
let id = if id.contains(':') {
|
||||
id.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
sources.push(self.score.storage.get(&id));
|
||||
} else if let Some(pos) = o.get("block").and_then(|v| v.as_str()) {
|
||||
let p: Vec<i32> = pos
|
||||
.split_whitespace()
|
||||
.filter_map(|v| v.parse().ok())
|
||||
.collect();
|
||||
if let [x, y, z] = p[..]
|
||||
&& let Ok(tag) = self.data_of(&super::data::DataRef::Block([x, y, z]))
|
||||
{
|
||||
sources.push(tag);
|
||||
}
|
||||
}
|
||||
let Ok(compiled) = horizon_client::nbt_path::NbtPath::parse(path) else {
|
||||
return Text::empty();
|
||||
};
|
||||
let plain = o.get("plain").and_then(|v| v.as_bool()) == Some(true);
|
||||
let interpret = o.get("interpret").and_then(|v| v.as_bool()) == Some(true);
|
||||
let mut out = Text::empty();
|
||||
let mut first = true;
|
||||
for data in &sources {
|
||||
for tag in compiled.get(data).unwrap_or_default() {
|
||||
if !first {
|
||||
out.push(Text::literal(", "));
|
||||
}
|
||||
first = false;
|
||||
let piece = if interpret {
|
||||
horizon_client::scoreboard::comp_text(&horizon_client::scoreboard::tag_to_json(&tag))
|
||||
} else if plain {
|
||||
Text::literal(horizon_client::snbt::pretty(&tag).plain())
|
||||
} else {
|
||||
horizon_client::snbt::pretty(&tag)
|
||||
};
|
||||
out.push(piece);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn player_targets(&mut self, ctx: &Context) -> R<usize> {
|
||||
// Only the local player can receive messages and titles.
|
||||
|
||||
@@ -94,11 +94,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
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))
|
||||
// The built-in pack first (lowest priority), unless disabled.
|
||||
let vanilla = DataPack::builtin(&self.options.resources);
|
||||
let packs: Vec<&DataPack> = (!self.cmds.vanilla_disabled)
|
||||
.then_some(&vanilla)
|
||||
.into_iter()
|
||||
.chain(
|
||||
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 {
|
||||
|
||||
@@ -1934,7 +1934,17 @@ impl Level {
|
||||
map.remove(&JavaString::from(key));
|
||||
}
|
||||
}
|
||||
let uuid = *self.player_uuid.get_or_insert_with(random_uuid);
|
||||
// A new world's player has the offline profile id of its name
|
||||
// (UUIDUtil.createOfflinePlayerUUID), as in an offline single-player game.
|
||||
let uuid = *self.player_uuid.get_or_insert_with(|| {
|
||||
let u = horizon_protocol::crypto::offline_uuid("Player");
|
||||
[
|
||||
(u >> 96) as u32 as i32,
|
||||
(u >> 64) as u32 as i32,
|
||||
(u >> 32) as u32 as i32,
|
||||
u as u32 as i32,
|
||||
]
|
||||
});
|
||||
// A new world's first spawn point is its world spawn.
|
||||
if self.world_spawn.is_none() {
|
||||
self.world_spawn = self.spawn.map(|s| {
|
||||
|
||||
@@ -647,10 +647,10 @@ impl Scoreboard {
|
||||
order.remove(name);
|
||||
}
|
||||
self.display.retain(|_, o| o != name);
|
||||
// Scoreboard.removeObjective: holders left without scores stay tracked.
|
||||
for s in self.scores.values_mut() {
|
||||
s.remove(name);
|
||||
}
|
||||
self.scores.retain(|_, s| !s.is_empty());
|
||||
}
|
||||
pub fn display_objective(&self, slot: &str) -> Option<&Objective> {
|
||||
self.objective(self.display.get(slot)?)
|
||||
|
||||
@@ -346,6 +346,9 @@ def execute():
|
||||
cmd('/execute facing 0 230 0 run tp @s ~ ~ ~ ~ ~'),
|
||||
cmd('/execute facing entity @e[tag=ex,limit=1] feet run tp @s ~ ~ ~ ~ ~'),
|
||||
cmd('/execute in minecraft:the_nether run setblock 0 200 0 minecraft:stone'),
|
||||
cmd('/execute in minecraft:the_end if block 0 64 0 minecraft:air'),
|
||||
cmd('/execute in minecraft:the_end run say elsewhere'),
|
||||
cmd('/execute in minecraft:nowhere run say nowhere'),
|
||||
cmd('/execute in minecraft:overworld run setblock 5 210 5 minecraft:dirt'),
|
||||
cmd('/execute if dimension minecraft:overworld'),
|
||||
cmd('/execute if dimension minecraft:the_end'),
|
||||
@@ -820,7 +823,9 @@ def social():
|
||||
cmd('/tellraw @s {"selector":"@s"}'),
|
||||
cmd('/tellraw @s {"score":{"name":"@s","objective":"trig"}}'),
|
||||
cmd('/tellraw @s {"nbt":"SelectedItemSlot","entity":"@s"}'),
|
||||
cmd('/tellraw @s {"keybind":"key.jump"}'),
|
||||
cmd('/tellraw @s {"nbt":"Inventory","entity":"@s","plain":true}'),
|
||||
cmd('/tellraw @s {"nbt":"value","storage":"harness:s","color":"red"}'),
|
||||
cmd('/tellraw @s {"nbt":"nothing","entity":"@s"}'),
|
||||
cmd('/tellraw @s {"text":"click","click_event":{"action":"run_command","command":"/say x"},"underlined":true}'),
|
||||
cmd('/title @s title {"selector":"@s"}'),
|
||||
cmd('/list uuids'),
|
||||
|
||||
Reference in New Issue
Block a user