Add /execute

ExecuteCommand's tree with redirects: as, at, positioned (as), rotated
(as), facing (entity), align, anchored, in, and if/unless block, entity,
loaded and dimension, as conditions or tests. Commands run with a real
command source (entity, position, rotation, anchor): @s, coordinates,
local coordinates from the anchor and /say and /me names follow it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 00:58:47 +02:00
parent 2030284a0f
commit a5db4eb8e3
5 changed files with 429 additions and 12 deletions
+19
View File
@@ -109,6 +109,8 @@ pub enum ArgType {
Message,
Dimension,
Anchor,
/// SwizzleArgument: a set of `x`, `y` and `z` (kept as text).
Swizzle,
/// CompoundTagArgument (kept as SNBT text).
Nbt,
}
@@ -1400,6 +1402,22 @@ impl ArgType {
}
Arg::Str(read_braced(reader, '{', '}')?)
}
ArgType::Swizzle => {
let mut axes = String::new();
while reader.can_read() && reader.peek() != ' ' {
let c = reader.read();
if !matches!(c, 'x' | 'y' | 'z') || axes.contains(c) {
reader.cursor = start;
return Err(CommandError::tr_at(
"arguments.swizzle.invalid",
&[],
reader,
));
}
axes.push(c);
}
Arg::Str(axes)
}
ArgType::Anchor => {
let name = reader.read_unquoted_string();
match name {
@@ -1475,6 +1493,7 @@ impl ArgType {
}
ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)),
ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]),
ArgType::Swizzle => {}
ArgType::Message => {
// MessageArgument suggests selectors and names for the last word.
let rem = builder.remaining();
@@ -314,9 +314,69 @@ pub fn build() -> Dispatcher {
let uuids = d.literal(list, "uuids");
d.executes(uuids, "list");
execute(&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);
}
}
}
/// TimeCommand.addClockNodes.
fn clock_nodes(d: &mut Dispatcher, node: usize) {
let set = d.literal(node, "set");
+3
View File
@@ -477,6 +477,8 @@ struct Game<'a> {
offhand: Option<ItemStack>,
/// The shield's item cooldown after an axe disabled it (ticks).
shield_cooldown: u32,
/// The source of a command run through /execute (the player otherwise).
command_source: Option<commands::execute::Source>,
applied_modifiers: Vec<(String, String)>,
experience: Experience,
orbs: Vec<ExperienceOrb>,
@@ -6946,6 +6948,7 @@ pub fn run() -> Result<()> {
armor: [None, None, None, None],
offhand: None,
shield_cooldown: 0,
command_source: None,
applied_modifiers: Vec::new(),
experience: Experience::default(),
orbs: Vec::new(),
+41 -12
View File
@@ -1,6 +1,7 @@
//! Command execution (the `execute` side of each vanilla command class):
//! entity selectors resolved against the game, vanilla feedback and errors.
mod effects;
pub(super) mod execute;
use super::{Dim, Game, Screen, chat::PLAYER_NAME};
use horizon_client::{
@@ -58,7 +59,17 @@ impl Game<'_> {
}
Ok((ctx, id)) => {
let ctx = ctx.clone();
self.execute_command(id, &ctx)
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)
}
}
};
if let Err(e) = result {
@@ -111,13 +122,25 @@ impl Game<'_> {
}
}
fn source_position(&self) -> [f64; 3] {
if let Some(s) = &self.command_source {
return s.pos;
}
match &self.player {
Some(p) => [p.position.x, p.position.y, p.position.z],
None => self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]),
}
}
fn source_rotation(&self) -> [f32; 2] {
[self.yaw, self.pitch]
self.command_source
.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] {
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> {
match ctx.get(name) {
@@ -126,15 +149,15 @@ impl Game<'_> {
}
}
fn position_arg(&self, ctx: &Context, name: &str) -> Option<[f64; 3]> {
self.coords(ctx, name)
.map(|c| c.position(self.source_position(), self.source_rotation()))
self.coords(ctx, name).map(|c| self.resolve_coords(&c))
}
/// BlockPosArgument.getLoadedBlockPos.
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", &[]))?;
let p = c.block(self.source_position(), self.source_rotation());
// 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)) {
return Err(err("argument.pos.unloaded", &[]));
}
@@ -231,8 +254,11 @@ impl Game<'_> {
]
};
let mut candidates: Vec<Target> = Vec::new();
if self.player.is_some() {
candidates.push(Target::Player);
match (s.kind, self.command_source) {
// @s: the executing entity (none for a server source).
('s', Some(source)) => candidates.extend(source.entity),
_ if self.player.is_some() => candidates.push(Target::Player),
_ => {}
}
if s.kind != 's' {
candidates.extend(
@@ -1666,12 +1692,15 @@ impl Game<'_> {
_ => String::new(),
};
let message = self.expand_selectors(&raw);
// CommandSourceStack.getDisplayName: the executing entity's name.
let name = match self.command_source.map(|s| s.entity) {
Some(Some(t)) => self.target_name(t),
Some(None) => Text::literal("Server"),
None => Text::literal(PLAYER_NAME),
};
let line = match id {
"say" => Text::translate(
"chat.type.announcement",
&[Text::literal(PLAYER_NAME), message],
),
"me" => Text::translate("chat.type.emote", &[Text::literal(PLAYER_NAME), message]),
"say" => Text::translate("chat.type.announcement", &[name, message]),
"me" => Text::translate("chat.type.emote", &[name, message]),
_ => {
let _ = self.entities(ctx, "targets", true)?;
// Whispering to yourself: the incoming and outgoing lines.
@@ -0,0 +1,306 @@
//! `/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;
/// `CommandSourceStack` fields Horizon models: the executing entity (None for
/// the server), position, rotation and anchor.
#[derive(Clone, Copy, Debug)]
pub(in crate::game) struct Source {
pub entity: Option<Target>,
pub pos: [f64; 3],
pub rot: [f32; 2],
/// EntityAnchorArgument.Anchor: eyes (true) or feet.
pub eyes: bool,
}
impl Game<'_> {
/// The source a command typed by the player starts from.
pub(super) fn player_source(&self) -> Source {
Source {
entity: Some(Target::Player),
pos: self.source_position(),
rot: self.source_rotation(),
eyes: false,
}
}
fn target_rotation(&self, t: Target) -> [f32; 2] {
match t {
Target::Player => [self.yaw, self.pitch],
Target::Mob(id) => self
.mobs
.iter()
.find(|m| m.id == id)
.map_or([0.0; 2], |m| [m.yaw, m.head_pitch]),
_ => [0.0; 2],
}
}
fn target_eye_height(&self, t: Target) -> f64 {
match t {
Target::Player => self
.player
.as_ref()
.map_or(1.62, |p| f64::from(p.dimensions.eye_height)),
Target::Mob(id) => self
.mobs
.iter()
.find(|m| m.id == id)
.map_or(0.0, |m| m.eye_y() - m.position.y),
_ => 0.0,
}
}
/// EntityAnchorArgument.Anchor.apply.
pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] {
match s.entity {
Some(t) if s.eyes => [s.pos[0], s.pos[1] + self.target_eye_height(t), s.pos[2]],
_ => s.pos,
}
}
/// Evaluate `f` with `source` as the command source.
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
}
/// ExecuteCommand: `ctx` is the context holding the `execute` literal.
pub(super) 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 {
let word = c
.literals
.iter()
.map(String::as_str)
.find(|w| *w != "execute")
.unwrap_or("");
match word {
"run" => {
let Some(command) = c.child.as_deref() else {
return Err(err("command.unknown.command", &[]));
};
let last = command.last_child();
let Some(id) = last.command else {
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;
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 {
Ok(n) => total += n,
// Forked executions report failures and carry on.
Err(e) => self.command_failure(e.message),
}
}
return Ok(total);
}
"if" | "unless" => {
let want = word == "if";
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 {
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();
for s in sources {
next.extend(self.with_source(s, |g| g.modify(word, c, s))?);
}
sources = next;
}
}
match c.child.as_deref() {
Some(child) => c = child,
None => return Err(err("command.unknown.command", &[])),
}
}
}
/// 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>> {
// An empty selection forks to nothing rather than failing.
match c.get("targets") {
Some(Arg::Entity(sel)) => {
let sel = sel.clone();
Ok(g.select(&sel))
}
_ => Ok(Vec::new()),
}
};
Ok(match word {
"as" => targets(self)?
.into_iter()
.map(|t| Source {
entity: Some(t),
..s
})
.collect(),
"at" => targets(self)?
.into_iter()
.filter_map(|t| {
Some(Source {
pos: self.target_position(t)?,
rot: self.target_rotation(t),
..s
})
})
.collect(),
"positioned" if c.has("as") => targets(self)?
.into_iter()
.filter_map(|t| {
Some(Source {
pos: self.target_position(t)?,
eyes: false,
..s
})
})
.collect(),
"positioned" => {
let pos = self
.position_arg(c, "pos")
.ok_or_else(|| err("argument.pos.missing.double", &[]))?;
vec![Source {
pos,
eyes: false,
..s
}]
}
"rotated" if c.has("as") => targets(self)?
.into_iter()
.map(|t| Source {
rot: self.target_rotation(t),
..s
})
.collect(),
"rotated" => {
let rot = match c.get("rot") {
Some(Arg::Coords(r)) => r.rotation(s.rot),
_ => s.rot,
};
vec![Source { rot, ..s }]
}
"facing" if c.has("entity") => {
let eyes = matches!(c.get("anchor"), Some(Arg::Anchor(true)));
targets(self)?
.into_iter()
.filter_map(|t| {
let p = self.target_position(t)?;
let y = if eyes {
p[1] + self.target_eye_height(t)
} else {
p[1]
};
Some(self.facing(s, [p[0], y, p[2]]))
})
.collect()
}
"facing" => {
let to = self
.position_arg(c, "pos")
.ok_or_else(|| err("argument.pos.missing.double", &[]))?;
vec![self.facing(s, to)]
}
"align" => {
let Some(Arg::Str(axes)) = c.get("axes") else {
return Ok(vec![s]);
};
let mut pos = s.pos;
for (i, axis) in ['x', 'y', 'z'].into_iter().enumerate() {
if axes.contains(axis) {
pos[i] = pos[i].floor();
}
}
vec![Source { pos, ..s }]
}
"anchored" => vec![Source {
eyes: matches!(c.get("anchor"), Some(Arg::Anchor(true))),
..s
}],
"in" => {
// Horizon keeps one dimension loaded; others cannot be a source.
let Some(Arg::Resource(dim)) = c.get("dimension") else {
return Ok(vec![s]);
};
if dim != self.dim.id() {
return Err(err("argument.dimension.invalid", &[dim]));
}
vec![s]
}
_ => return Err(err("command.unknown.command", &[])),
})
}
/// CommandSourceStack.facing: rotation from the anchor point to `to`.
fn facing(&self, s: Source, to: [f64; 3]) -> Source {
let from = self.anchor_position(&s);
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;
Source {
rot: [yaw.rem_euclid(360.0), pitch],
..s
}
}
/// The count an if/unless condition yields (0 = false).
fn condition(&mut self, c: &Context) -> R<i32> {
if c.has("entity") {
let Some(Arg::Entity(sel)) = c.get("entities").cloned() else {
return Ok(0);
};
return Ok(self.select(&sel).len() as i32);
}
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,
);
}
if c.has("dimension") {
return Ok(
matches!(c.get("dimension"), Some(Arg::Resource(d)) if d == self.dim.id()) as i32,
);
}
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);
};
let state = self.world.block(p[0], p[1], p[2]);
return Ok(self.block_matches(&b, state) as i32);
}
Ok(0)
}
}