Command blocks: placing, the edit screen, and running commands
A creative player with game master commands (Player.canUseGameMasterBlocks) places command, chain and repeating command blocks and opens CommandBlockEditScreen on them: the command, its previous output with the O/X tracking toggle, Impulse/Chain/Repeat, Conditional and Needs Redstone/Always Active, applied as handleSetCommandBlock does. The block entity (CommandBlockEntity with BaseCommandBlock) saves and loads its vanilla fields. CommandBlock.tick runs impulse blocks on a rising signal, repeating blocks every tick while powered or always active, and the chain in front (executeChain), honouring conditional blocks, command_blocks_work and max_command_sequence_length. Commands run through the command system as the block (position, facing, game master level); their feedback becomes the block's last output and the [@: ...] broadcast under command_block_output. Comparators read the success count. Fixes #444 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,256 @@
|
||||
//! `CommandBlockEntity` with its `BaseCommandBlock`: the command, the success
|
||||
//! count comparators read, the output it keeps, and the powered, automatic
|
||||
//! and condition flags `CommandBlock.tick` runs on.
|
||||
use crate::{
|
||||
save::{number, text},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `CommandBlockEntity.Mode`, in declaration order (the edit screen's mode
|
||||
/// button cycles through it).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Sequence,
|
||||
Auto,
|
||||
Redstone,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// `CommandBlockEntity.getMode`: the block the entity sits in.
|
||||
pub fn of_block(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
"minecraft:command_block" => Some(Self::Redstone),
|
||||
"minecraft:repeating_command_block" => Some(Self::Auto),
|
||||
"minecraft:chain_command_block" => Some(Self::Sequence),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The block `ServerGamePacketListenerImpl.handleSetCommandBlock` puts
|
||||
/// down for a mode.
|
||||
pub fn block(self) -> &'static str {
|
||||
match self {
|
||||
Self::Sequence => "minecraft:chain_command_block",
|
||||
Self::Auto => "minecraft:repeating_command_block",
|
||||
Self::Redstone => "minecraft:command_block",
|
||||
}
|
||||
}
|
||||
/// `CycleButton`: the next value, wrapping round.
|
||||
pub fn next(self) -> Self {
|
||||
match self {
|
||||
Self::Sequence => Self::Auto,
|
||||
Self::Auto => Self::Redstone,
|
||||
Self::Redstone => Self::Sequence,
|
||||
}
|
||||
}
|
||||
/// `CommandBlockEditScreen`'s label for the mode.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Sequence => "advMode.mode.sequence",
|
||||
Self::Auto => "advMode.mode.auto",
|
||||
Self::Redstone => "advMode.mode.redstone",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `automatic` flag `CommandBlock` gives its entity: chain command blocks
|
||||
/// are always active when placed.
|
||||
pub fn automatic_block(name: &str) -> bool {
|
||||
name == "minecraft:chain_command_block"
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CommandBlock {
|
||||
pub command: String,
|
||||
pub success_count: i32,
|
||||
/// `CustomName` as saved (a text component).
|
||||
pub custom_name: Option<Tag>,
|
||||
pub track_output: bool,
|
||||
pub last_output: Option<Text>,
|
||||
pub update_last_execution: bool,
|
||||
/// The game time of the last run, -1 for none.
|
||||
pub last_execution: i64,
|
||||
pub powered: bool,
|
||||
pub auto: bool,
|
||||
pub condition_met: bool,
|
||||
}
|
||||
|
||||
impl Default for CommandBlock {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
command: String::new(),
|
||||
success_count: 0,
|
||||
custom_name: None,
|
||||
track_output: true,
|
||||
last_output: None,
|
||||
update_last_execution: true,
|
||||
last_execution: -1,
|
||||
powered: false,
|
||||
auto: false,
|
||||
condition_met: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandBlock {
|
||||
/// `CommandBlockEntity.loadAdditional` with `BaseCommandBlock.load`.
|
||||
pub fn load(tag: &Tag) -> Self {
|
||||
let flag = |key: &str, default: bool| number(tag.get(key)).map_or(default, |v| v != 0);
|
||||
let track_output = flag("TrackOutput", true);
|
||||
let update_last_execution = flag("UpdateLastExecution", true);
|
||||
Self {
|
||||
command: text(tag.get("Command")).unwrap_or_default(),
|
||||
success_count: number(tag.get("SuccessCount")).unwrap_or(0) as i32,
|
||||
custom_name: tag.get("CustomName").cloned(),
|
||||
track_output,
|
||||
last_output: track_output
|
||||
.then(|| tag.get("LastOutput"))
|
||||
.flatten()
|
||||
.map(|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))),
|
||||
update_last_execution,
|
||||
last_execution: if update_last_execution {
|
||||
number(tag.get("LastExecution")).unwrap_or(-1)
|
||||
} else {
|
||||
-1
|
||||
},
|
||||
powered: flag("powered", false),
|
||||
auto: flag("auto", false),
|
||||
condition_met: flag("conditionMet", false),
|
||||
}
|
||||
}
|
||||
/// `CommandBlockEntity.saveAdditional`. The last output is written as a
|
||||
/// plain string component.
|
||||
pub fn save(&self) -> Vec<(&'static str, Tag)> {
|
||||
let mut out = vec![
|
||||
("Command", Tag::String(self.command.as_str().into())),
|
||||
("SuccessCount", Tag::Int(self.success_count)),
|
||||
];
|
||||
if let Some(name) = &self.custom_name {
|
||||
out.push(("CustomName", name.clone()));
|
||||
}
|
||||
out.push(("TrackOutput", Tag::Byte(i8::from(self.track_output))));
|
||||
if self.track_output
|
||||
&& let Some(last) = &self.last_output
|
||||
{
|
||||
out.push(("LastOutput", Tag::String(last.plain().as_str().into())));
|
||||
}
|
||||
out.push((
|
||||
"UpdateLastExecution",
|
||||
Tag::Byte(i8::from(self.update_last_execution)),
|
||||
));
|
||||
if self.update_last_execution && self.last_execution != -1 {
|
||||
out.push(("LastExecution", Tag::Long(self.last_execution)));
|
||||
}
|
||||
out.push(("powered", Tag::Byte(i8::from(self.powered))));
|
||||
out.push(("conditionMet", Tag::Byte(i8::from(self.condition_met))));
|
||||
out.push(("auto", Tag::Byte(i8::from(self.auto))));
|
||||
out
|
||||
}
|
||||
/// `BaseCommandBlock.setCommand`: a new command starts at no successes.
|
||||
pub fn set_command(&mut self, command: &str) {
|
||||
self.command = command.to_owned();
|
||||
self.success_count = 0;
|
||||
}
|
||||
/// `getLastOutput().getString()`: what the edit screen shows.
|
||||
pub fn last_output_string(&self) -> String {
|
||||
self.last_output
|
||||
.as_ref()
|
||||
.map(Text::plain)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
/// `getName`: the custom name, else `@`.
|
||||
pub fn name(&self) -> Text {
|
||||
self.custom_name.as_ref().map_or_else(
|
||||
|| Text::literal("@"),
|
||||
|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// What `CommandBlock.tick` does with a block of `mode` whose condition was
|
||||
/// `met` when last checked: run its command (`Some(true)`), clear the success
|
||||
/// count of a conditional block (`Some(false)`), or nothing. Chain blocks
|
||||
/// only run from the block before them (`executeChain`).
|
||||
pub fn tick_action(mode: Mode, met: bool, conditional: bool) -> Option<bool> {
|
||||
match mode {
|
||||
Mode::Sequence => None,
|
||||
_ if met => Some(true),
|
||||
_ if conditional => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `CommandBlock.tick`: a repeating block ticks again next tick while powered
|
||||
/// or always active.
|
||||
pub fn repeats(mode: Mode, powered: bool, auto: bool) -> bool {
|
||||
mode == Mode::Auto && (powered || auto)
|
||||
}
|
||||
|
||||
/// `CommandBlock.setPoweredAndUpdate`: a rising signal schedules the impulse
|
||||
/// or repeating block's tick unless it is always active anyway.
|
||||
pub fn power_schedules(mode: Mode, was_powered: bool, powered: bool, auto: bool) -> bool {
|
||||
powered && !was_powered && !auto && mode != Mode::Sequence
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn modes_cycle_and_map_to_blocks() {
|
||||
for mode in [Mode::Sequence, Mode::Auto, Mode::Redstone] {
|
||||
assert_eq!(Mode::of_block(mode.block()), Some(mode));
|
||||
}
|
||||
assert_eq!(Mode::Redstone.next(), Mode::Sequence);
|
||||
assert_eq!(Mode::Sequence.next(), Mode::Auto);
|
||||
assert!(automatic_block("minecraft:chain_command_block"));
|
||||
assert!(!automatic_block("minecraft:repeating_command_block"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_follows_the_condition() {
|
||||
assert_eq!(tick_action(Mode::Redstone, true, false), Some(true));
|
||||
assert_eq!(tick_action(Mode::Redstone, false, true), Some(false));
|
||||
assert_eq!(tick_action(Mode::Auto, false, false), None);
|
||||
assert_eq!(tick_action(Mode::Sequence, true, false), None);
|
||||
assert!(repeats(Mode::Auto, false, true));
|
||||
assert!(!repeats(Mode::Auto, false, false));
|
||||
assert!(!repeats(Mode::Redstone, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_rising_edge_schedules() {
|
||||
assert!(power_schedules(Mode::Redstone, false, true, false));
|
||||
assert!(!power_schedules(Mode::Redstone, true, true, false));
|
||||
assert!(!power_schedules(Mode::Redstone, false, true, true));
|
||||
assert!(!power_schedules(Mode::Sequence, false, true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saves_like_base_command_block() {
|
||||
let block = CommandBlock {
|
||||
command: "say hi".into(),
|
||||
success_count: 1,
|
||||
last_output: Some(Text::literal("[12:00:00] hi")),
|
||||
last_execution: 42,
|
||||
powered: true,
|
||||
..CommandBlock::default()
|
||||
};
|
||||
let tag = Tag::compound(block.save());
|
||||
let back = CommandBlock::load(&tag);
|
||||
assert_eq!(back.command, "say hi");
|
||||
assert_eq!(back.success_count, 1);
|
||||
assert_eq!(back.last_output_string(), "[12:00:00] hi");
|
||||
assert_eq!(back.last_execution, 42);
|
||||
assert!(back.powered && !back.auto && back.track_output);
|
||||
// Not tracking output drops it, and no execution time is kept at -1.
|
||||
let quiet = CommandBlock {
|
||||
track_output: false,
|
||||
last_output: Some(Text::literal("x")),
|
||||
..CommandBlock::default()
|
||||
};
|
||||
let tag = Tag::compound(quiet.save());
|
||||
assert!(tag.get("LastOutput").is_none() && tag.get("LastExecution").is_none());
|
||||
assert_eq!(CommandBlock::load(&tag).last_output, None);
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,8 @@ pub enum BlockEntity {
|
||||
Vault(Box<crate::vault::Vault>),
|
||||
/// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`).
|
||||
Beehive(Box<crate::beehive::Beehive>),
|
||||
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
|
||||
CommandBlock(Box<crate::command_block::CommandBlock>),
|
||||
}
|
||||
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
|
||||
/// and the ticks left in the crafting animation.
|
||||
@@ -203,6 +205,15 @@ impl BlockEntity {
|
||||
if name == "minecraft:lectern" {
|
||||
return Some(Self::Lectern(Lectern::default()));
|
||||
}
|
||||
if crate::command_block::Mode::of_block(name).is_some() {
|
||||
// CommandBlock.newBlockEntity: setAutomatic(this.automatic).
|
||||
return Some(Self::CommandBlock(Box::new(
|
||||
crate::command_block::CommandBlock {
|
||||
auto: crate::command_block::automatic_block(name),
|
||||
..Default::default()
|
||||
},
|
||||
)));
|
||||
}
|
||||
if let Some(sculk) = crate::sculk::SculkEntity::for_block(name) {
|
||||
return Some(Self::Sculk(Box::new(sculk)));
|
||||
}
|
||||
@@ -279,6 +290,7 @@ impl BlockEntity {
|
||||
Self::TrialSpawner(_) => "minecraft:trial_spawner",
|
||||
Self::Vault(_) => "minecraft:vault",
|
||||
Self::Beehive(_) => "minecraft:beehive",
|
||||
Self::CommandBlock(_) => "minecraft:command_block",
|
||||
}
|
||||
}
|
||||
pub fn contents(&self) -> Vec<ItemStack> {
|
||||
@@ -293,7 +305,8 @@ impl BlockEntity {
|
||||
| Self::Spawner(_)
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_) => Vec::new(),
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => Vec::new(),
|
||||
Self::Lectern(l) => l.book.iter().cloned().collect(),
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
@@ -316,7 +329,8 @@ impl BlockEntity {
|
||||
| Self::Spawner(_)
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_) => &[],
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => &[],
|
||||
}
|
||||
}
|
||||
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
|
||||
@@ -335,7 +349,8 @@ impl BlockEntity {
|
||||
| Self::Spawner(_)
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_) => &mut [],
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => &mut [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ mod cartography;
|
||||
mod chat;
|
||||
mod clipboard;
|
||||
mod combat;
|
||||
mod command_blocks;
|
||||
mod command_harness;
|
||||
mod commands;
|
||||
mod composter;
|
||||
@@ -396,6 +397,8 @@ enum Screen {
|
||||
Advancements,
|
||||
/// WorldOptionsScreen (game/lan_screen.rs).
|
||||
WorldOptions,
|
||||
/// CommandBlockEditScreen (game/command_blocks.rs).
|
||||
CommandBlock,
|
||||
}
|
||||
struct Mining {
|
||||
pos: [i32; 3],
|
||||
@@ -446,6 +449,9 @@ impl LevelAccess for GameLevel<'_> {
|
||||
state: BlockStateId,
|
||||
_direction: Direction,
|
||||
) -> i32 {
|
||||
if let Some(signal) = command_blocks::analog_signal(self.world, (pos.x, pos.y, pos.z)) {
|
||||
return signal;
|
||||
}
|
||||
if let Some(signal) = sculk::sensor_signal(self.world, self.behaviours, state, pos) {
|
||||
return signal;
|
||||
}
|
||||
@@ -603,6 +609,9 @@ impl LevelAccess for GameLevel<'_> {
|
||||
fn remove_block_entity(&mut self, pos: BlockPos, old: BlockStateId, side_effects: bool) -> u8 {
|
||||
self.remove_entity(pos, old, side_effects)
|
||||
}
|
||||
fn set_command_block_powered(&mut self, pos: BlockPos, powered: bool) -> Option<(bool, bool)> {
|
||||
command_blocks::set_powered(self.world, self.registry, (pos.x, pos.y, pos.z), powered)
|
||||
}
|
||||
}
|
||||
/// FallingBlockEntity carrying a block state.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -995,6 +1004,7 @@ struct Game<'a> {
|
||||
/// The open world is shared behind an invite code (game/friends.rs).
|
||||
friends: Option<friends::Sharing>,
|
||||
world_options: Option<lan_screen::WorldOptions>,
|
||||
command_block_screen: Option<command_blocks::CommandBlockScreen>,
|
||||
/// KeyboardHandler's debug key state (game/debug_keys.rs), the physical
|
||||
/// keys held, and the debug renderers F3+B and F3+G switch on.
|
||||
debug_keys: horizon_client::debug_keys::DebugKeys,
|
||||
@@ -1933,6 +1943,11 @@ impl Game<'_> {
|
||||
state,
|
||||
kind: "dispense",
|
||||
} => self.dispense_from(pos, state)?,
|
||||
LevelEvent::BlockEvent {
|
||||
pos,
|
||||
kind: "command_block",
|
||||
..
|
||||
} => self.command_block_tick(pos),
|
||||
LevelEvent::BlockEvent {
|
||||
pos, kind: "hatch", ..
|
||||
} => {
|
||||
@@ -2006,6 +2021,10 @@ impl Game<'_> {
|
||||
self.open_lectern(pos);
|
||||
return;
|
||||
}
|
||||
if horizon_client::command_block::Mode::of_block(&name).is_some() {
|
||||
self.open_command_block(key);
|
||||
return;
|
||||
}
|
||||
if &*name == "minecraft:crafting_table" {
|
||||
self.craft_size = 3;
|
||||
} else if &*name == "minecraft:ender_chest" {
|
||||
@@ -2411,7 +2430,7 @@ impl Game<'_> {
|
||||
.player
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.health.food.food < 20),
|
||||
game_master: false,
|
||||
game_master: self.can_use_game_master_blocks(),
|
||||
};
|
||||
let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
|
||||
let item = held.as_ref().map(|s| s.item.to_string());
|
||||
@@ -2534,7 +2553,7 @@ impl Game<'_> {
|
||||
pitch: self.pitch,
|
||||
sneaking: self.keys.contains(&KeyCode::ShiftLeft),
|
||||
item: stack.item.to_string(),
|
||||
can_use_game_master_blocks: false,
|
||||
can_use_game_master_blocks: self.can_use_game_master_blocks(),
|
||||
};
|
||||
let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx));
|
||||
let PlaceOutcome::Placed { pos, state } = outcome else {
|
||||
@@ -2549,9 +2568,13 @@ impl Game<'_> {
|
||||
let target = [pos.x, pos.y, pos.z];
|
||||
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
|
||||
let sign = matches!(entity, BlockEntity::Sign(_));
|
||||
let command_block = matches!(entity, BlockEntity::CommandBlock(_));
|
||||
self.world
|
||||
.block_entities
|
||||
.insert((target[0], target[1], target[2]), entity);
|
||||
if command_block {
|
||||
self.command_block_placed((target[0], target[1], target[2]));
|
||||
}
|
||||
self.fill_placed_box(target, &stack);
|
||||
self.name_placed_container(target, &stack);
|
||||
self.fill_placed_banner(target, &stack);
|
||||
@@ -3498,6 +3521,7 @@ impl Game<'_> {
|
||||
| Screen::Stats
|
||||
| Screen::Advancements
|
||||
| Screen::WorldOptions
|
||||
| Screen::CommandBlock
|
||||
) || self.book.is_some())
|
||||
}
|
||||
fn capture(&mut self, capture: bool) {
|
||||
@@ -3853,6 +3877,7 @@ impl Game<'_> {
|
||||
Screen::Stats => self.draw_stats(&mut batch),
|
||||
Screen::Advancements => self.draw_advancements(&mut batch),
|
||||
Screen::WorldOptions => self.draw_world_options(&mut batch),
|
||||
Screen::CommandBlock => self.draw_command_block(&mut batch),
|
||||
Screen::Inventory => {
|
||||
self.draw_inventory(&mut batch);
|
||||
}
|
||||
@@ -3915,7 +3940,8 @@ impl Game<'_> {
|
||||
| BlockEntity::Spawner(_)
|
||||
| BlockEntity::TrialSpawner(_)
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_),
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_),
|
||||
) => {}
|
||||
None => {
|
||||
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
|
||||
@@ -4171,7 +4197,8 @@ impl Game<'_> {
|
||||
| BlockEntity::Spawner(_)
|
||||
| BlockEntity::TrialSpawner(_)
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_),
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_),
|
||||
) => {}
|
||||
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
|
||||
None => {
|
||||
@@ -8687,6 +8714,7 @@ impl Game<'_> {
|
||||
Screen::Stats => self.screen = Screen::Paused,
|
||||
Screen::Advancements => self.close_advancements(),
|
||||
Screen::WorldOptions => self.close_world_options(),
|
||||
Screen::CommandBlock => self.close_command_block(),
|
||||
Screen::Chat => self.close_chat(),
|
||||
},
|
||||
KeyCode::Digit1
|
||||
@@ -9274,6 +9302,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
Screen::WorldOptions if pressed && button == MouseButton::Left => {
|
||||
self.world_options_click()
|
||||
}
|
||||
Screen::CommandBlock if pressed && button == MouseButton::Left => {
|
||||
self.command_block_click()
|
||||
}
|
||||
Screen::Dead if pressed && button == MouseButton::Left => {
|
||||
self.death_click()?
|
||||
}
|
||||
@@ -9355,6 +9386,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
{
|
||||
self.world_options_key(&event)
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::CommandBlock => {
|
||||
self.command_block_key(&event)
|
||||
}
|
||||
// Options consumes presses; releases still reach the bound
|
||||
// gameplay mapping below, including sneak/sprint toggles.
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
@@ -10052,6 +10086,7 @@ pub fn run() -> Result<()> {
|
||||
remote: None,
|
||||
lan: None,
|
||||
world_options: None,
|
||||
command_block_screen: None,
|
||||
friends: None,
|
||||
debug_keys: Default::default(),
|
||||
debug_charts: Default::default(),
|
||||
|
||||
@@ -389,6 +389,7 @@ impl Game<'_> {
|
||||
Screen::Stats => "stats",
|
||||
Screen::Advancements => "advancements",
|
||||
Screen::WorldOptions => "world-options",
|
||||
Screen::CommandBlock => "command-block",
|
||||
}
|
||||
}
|
||||
pub(super) fn inventory_counts(&self) -> BTreeMap<String, i64> {
|
||||
|
||||
@@ -0,0 +1,637 @@
|
||||
//! Command blocks: `CommandBlock`'s placement (`setPlacedBy`), its scheduled
|
||||
//! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand`
|
||||
//! through the command system with the block's output, and
|
||||
//! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it.
|
||||
use super::{Game, Screen, commands::execute::Source};
|
||||
use horizon_client::{
|
||||
command_block::{self, CommandBlock, Mode},
|
||||
containers::BlockEntity,
|
||||
hud::{HudBatch, rgba},
|
||||
text::{self, Text},
|
||||
ui::{self, EditBox},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_world::{
|
||||
chunk::BlockState,
|
||||
level::flags,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
};
|
||||
use winit::{
|
||||
event::{ElementState, KeyEvent},
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
};
|
||||
|
||||
type Pos = (i32, i32, i32);
|
||||
|
||||
/// The open `CommandBlockEditScreen`.
|
||||
pub(super) struct CommandBlockScreen {
|
||||
pos: Pos,
|
||||
command: EditBox,
|
||||
previous: EditBox,
|
||||
track_output: bool,
|
||||
mode: Mode,
|
||||
conditional: bool,
|
||||
auto: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Button {
|
||||
Output,
|
||||
Mode,
|
||||
Conditional,
|
||||
Auto,
|
||||
Done,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// `EditBox.textColorUneditable`.
|
||||
const UNEDITABLE: u32 = 0xFF70_7070;
|
||||
|
||||
impl CommandBlockScreen {
|
||||
/// `AbstractCommandBlockEditScreen.init` and `CommandBlockEditScreen`'s
|
||||
/// buttons, in GUI pixels of a `w`×`h` screen.
|
||||
fn buttons(w: f32, h: f32) -> [(Button, f32, f32, f32); 6] {
|
||||
let mid = (w / 2.0).floor();
|
||||
let low = (h / 4.0).floor() + 132.0;
|
||||
[
|
||||
(Button::Output, mid + 130.0, 135.0, 20.0),
|
||||
(Button::Mode, mid - 154.0, 165.0, 100.0),
|
||||
(Button::Conditional, mid - 50.0, 165.0, 100.0),
|
||||
(Button::Auto, mid + 54.0, 165.0, 100.0),
|
||||
(Button::Done, mid - 154.0, low, 150.0),
|
||||
(Button::Cancel, mid + 4.0, low, 150.0),
|
||||
]
|
||||
}
|
||||
fn label(&self, b: Button) -> Text {
|
||||
let tr = |key: &str| Text::translate(key, &[]);
|
||||
match b {
|
||||
Button::Output => Text::literal(if self.track_output { "O" } else { "X" }),
|
||||
Button::Mode => tr(self.mode.label()),
|
||||
Button::Conditional => tr(if self.conditional {
|
||||
"advMode.mode.conditional"
|
||||
} else {
|
||||
"advMode.mode.unconditional"
|
||||
}),
|
||||
Button::Auto => tr(if self.auto {
|
||||
"advMode.mode.autoexec.bat"
|
||||
} else {
|
||||
"advMode.mode.redstoneTriggered"
|
||||
}),
|
||||
Button::Done => tr("gui.done"),
|
||||
Button::Cancel => tr("gui.cancel"),
|
||||
}
|
||||
}
|
||||
/// `updatePreviousOutput`.
|
||||
fn show_previous(&mut self, block: &CommandBlock) {
|
||||
let shown = if self.track_output {
|
||||
block.last_output_string()
|
||||
} else {
|
||||
"-".to_owned()
|
||||
};
|
||||
self.previous.set_value(&shown);
|
||||
}
|
||||
}
|
||||
|
||||
fn state_of(registry: &BlockRegistry, state: BlockStateId) -> Option<&BlockState> {
|
||||
registry.state(state)
|
||||
}
|
||||
fn facing_step(state: &BlockState) -> [i32; 3] {
|
||||
match state.properties.get("facing").map(String::as_str) {
|
||||
Some("down") => [0, -1, 0],
|
||||
Some("up") => [0, 1, 0],
|
||||
Some("south") => [0, 0, 1],
|
||||
Some("west") => [-1, 0, 0],
|
||||
Some("east") => [1, 0, 0],
|
||||
_ => [0, 0, -1],
|
||||
}
|
||||
}
|
||||
/// `Direction.toYRot`: south 0, west 90, north 180, east (and up/down) 270.
|
||||
fn facing_yaw(state: &BlockState) -> f32 {
|
||||
match state.properties.get("facing").map(String::as_str) {
|
||||
Some("south") => 0.0,
|
||||
Some("west") => 90.0,
|
||||
Some("north") => 180.0,
|
||||
_ => 270.0,
|
||||
}
|
||||
}
|
||||
fn conditional(state: &BlockState) -> bool {
|
||||
state
|
||||
.properties
|
||||
.get("conditional")
|
||||
.is_some_and(|c| c == "true")
|
||||
}
|
||||
fn offset(pos: Pos, step: [i32; 3]) -> Pos {
|
||||
(pos.0 + step[0], pos.1 + step[1], pos.2 + step[2])
|
||||
}
|
||||
fn command_block_mut(world: &mut World, pos: Pos) -> Option<&mut CommandBlock> {
|
||||
match world.block_entities.get_mut(&pos)? {
|
||||
BlockEntity::CommandBlock(c) => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `CommandBlockEntity.markConditionMet`: a conditional block needs the
|
||||
/// command block behind it to have succeeded.
|
||||
pub(super) fn mark_condition_met(world: &mut World, registry: &BlockRegistry, pos: Pos) -> bool {
|
||||
let Some(state) = state_of(registry, world.block(pos.0, pos.1, pos.2)) else {
|
||||
return false;
|
||||
};
|
||||
let mut met = true;
|
||||
if conditional(state) {
|
||||
let back = facing_step(state).map(|v| -v);
|
||||
let behind = offset(pos, back);
|
||||
let behind_block = state_of(registry, world.block(behind.0, behind.1, behind.2))
|
||||
.is_some_and(|s| Mode::of_block(&s.name).is_some());
|
||||
met = behind_block
|
||||
&& matches!(world.block_entities.get(&behind),
|
||||
Some(BlockEntity::CommandBlock(c)) if c.success_count > 0);
|
||||
}
|
||||
if let Some(c) = command_block_mut(world, pos) {
|
||||
c.condition_met = met;
|
||||
}
|
||||
met
|
||||
}
|
||||
|
||||
/// `CommandBlockEntity.setPowered` from `CommandBlock.setPoweredAndUpdate`
|
||||
/// (the level's neighbour hook): the previous flag and `isAutomatic`; a
|
||||
/// rising signal that will tick the block checks its condition.
|
||||
pub(super) fn set_powered(
|
||||
world: &mut World,
|
||||
registry: &BlockRegistry,
|
||||
pos: Pos,
|
||||
powered: bool,
|
||||
) -> Option<(bool, bool)> {
|
||||
let mode = state_of(registry, world.block(pos.0, pos.1, pos.2))
|
||||
.and_then(|s| Mode::of_block(&s.name))?;
|
||||
let c = command_block_mut(world, pos)?;
|
||||
let (was, auto) = (c.powered, c.auto);
|
||||
c.powered = powered;
|
||||
if command_block::power_schedules(mode, was, powered, auto) {
|
||||
mark_condition_met(world, registry, pos);
|
||||
}
|
||||
Some((was, auto))
|
||||
}
|
||||
|
||||
/// `getAnalogOutputSignal`: the success count.
|
||||
pub(super) fn analog_signal(world: &World, pos: Pos) -> Option<i32> {
|
||||
match world.block_entities.get(&pos)? {
|
||||
BlockEntity::CommandBlock(c) => Some(c.success_count),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Player.canUseGameMasterBlocks`: creative with game master commands.
|
||||
pub(super) fn can_use_game_master_blocks(&self) -> bool {
|
||||
self.creative && self.ui.registries.permission >= 2
|
||||
}
|
||||
fn command_block(&self, pos: Pos) -> Option<&CommandBlock> {
|
||||
match self.world.block_entities.get(&pos)? {
|
||||
BlockEntity::CommandBlock(c) => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn block_state_at(&self, pos: Pos) -> Option<&'static BlockState> {
|
||||
let registry = self.res.assets.registry;
|
||||
state_of(registry, self.world.block(pos.0, pos.1, pos.2))
|
||||
}
|
||||
fn schedule_command_block(&mut self, pos: Pos) {
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
self.with_level(|b, level, ticks| b.schedule_tick(level, ticks, at, 1));
|
||||
}
|
||||
/// `CommandBlockEntity.scheduleTick`.
|
||||
fn schedule_command_block_tick(&mut self, pos: Pos) {
|
||||
mark_condition_met(&mut self.world, self.res.assets.registry, pos);
|
||||
self.schedule_command_block(pos);
|
||||
}
|
||||
fn update_output_signal(&mut self, pos: Pos) {
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
self.with_level(|b, level, ticks| b.update_neighbour_for_output_signal(level, ticks, at));
|
||||
}
|
||||
|
||||
/// `CommandBlock.setPlacedBy`: output tracking follows
|
||||
/// `send_command_feedback`, then the block takes the signal around it.
|
||||
pub(super) fn command_block_placed(&mut self, pos: Pos) {
|
||||
let feedback = self.ui.rules.bool("send_command_feedback");
|
||||
let Some(name) = self.block_state_at(pos).map(|s| s.name.as_str()) else {
|
||||
return;
|
||||
};
|
||||
let auto = command_block::automatic_block(name);
|
||||
if let Some(c) = command_block_mut(&mut self.world, pos) {
|
||||
c.track_output = feedback;
|
||||
c.auto = auto;
|
||||
}
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
let signal = self.with_level(|b, level, ticks| b.has_neighbor_signal(level, ticks, at));
|
||||
let registry = self.res.assets.registry;
|
||||
if let Some((was, auto)) = set_powered(&mut self.world, registry, pos, signal)
|
||||
&& signal
|
||||
&& !was
|
||||
&& !auto
|
||||
&& !command_block::automatic_block(name)
|
||||
{
|
||||
self.schedule_command_block(pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// `CommandBlock.tick`.
|
||||
pub(super) fn command_block_tick(&mut self, pos: BlockPos) {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
let Some(state) = self.block_state_at(key) else {
|
||||
return;
|
||||
};
|
||||
let Some(mode) = Mode::of_block(&state.name) else {
|
||||
return;
|
||||
};
|
||||
let Some(was_met) = self.command_block(key).map(|c| c.condition_met) else {
|
||||
return;
|
||||
};
|
||||
if mode == Mode::Auto {
|
||||
mark_condition_met(&mut self.world, self.res.assets.registry, key);
|
||||
}
|
||||
match command_block::tick_action(mode, was_met, conditional(state)) {
|
||||
Some(true) => self.command_block_execute(key, state),
|
||||
Some(false) => {
|
||||
if let Some(c) = command_block_mut(&mut self.world, key) {
|
||||
c.success_count = 0;
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(c) = self.command_block(key)
|
||||
&& command_block::repeats(mode, c.powered, c.auto)
|
||||
{
|
||||
self.schedule_command_block(key);
|
||||
}
|
||||
self.update_output_signal(key);
|
||||
}
|
||||
/// `CommandBlock.execute`: the command (or no successes without one),
|
||||
/// then the chain in front.
|
||||
fn command_block_execute(&mut self, pos: Pos, state: &BlockState) {
|
||||
let has_command = self
|
||||
.command_block(pos)
|
||||
.is_some_and(|c| !c.command.is_empty());
|
||||
if has_command {
|
||||
self.perform_command_block(pos);
|
||||
} else if let Some(c) = command_block_mut(&mut self.world, pos) {
|
||||
c.success_count = 0;
|
||||
}
|
||||
self.execute_chain(pos, facing_step(state));
|
||||
}
|
||||
/// `CommandBlock.executeChain`: the chain command blocks in front, each
|
||||
/// facing on to the next, up to `max_command_sequence_length`.
|
||||
fn execute_chain(&mut self, start: Pos, mut step: [i32; 3]) {
|
||||
let registry = self.res.assets.registry;
|
||||
let limit = self.ui.rules.int("max_command_sequence_length");
|
||||
let mut remaining = limit;
|
||||
let mut pos = start;
|
||||
while remaining > 0 {
|
||||
remaining -= 1;
|
||||
pos = offset(pos, step);
|
||||
let Some(state) = self.block_state_at(pos) else {
|
||||
break;
|
||||
};
|
||||
if Mode::of_block(&state.name) != Some(Mode::Sequence) {
|
||||
break;
|
||||
}
|
||||
let Some(c) = self.command_block(pos) else {
|
||||
break;
|
||||
};
|
||||
if c.powered || c.auto {
|
||||
if mark_condition_met(&mut self.world, registry, pos) {
|
||||
if !self.perform_command_block(pos) {
|
||||
break;
|
||||
}
|
||||
self.update_output_signal(pos);
|
||||
} else if conditional(state)
|
||||
&& let Some(c) = command_block_mut(&mut self.world, pos)
|
||||
{
|
||||
c.success_count = 0;
|
||||
}
|
||||
}
|
||||
step = facing_step(state);
|
||||
}
|
||||
if remaining <= 0 {
|
||||
log::warn!(
|
||||
"Command Block chain tried to execute more than {} steps!",
|
||||
limit.max(0)
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `BaseCommandBlock.performCommand`: runs the command as the block, at
|
||||
/// game master level, counting the successful results. False when it
|
||||
/// already ran this game tick.
|
||||
fn perform_command_block(&mut self, pos: Pos) -> bool {
|
||||
let game_time = self.world.game_time;
|
||||
let Some(c) = command_block_mut(&mut self.world, pos) else {
|
||||
return false;
|
||||
};
|
||||
if c.last_execution == game_time {
|
||||
return false;
|
||||
}
|
||||
if c.command.eq_ignore_ascii_case("Searge") {
|
||||
c.last_output = Some(Text::literal("#itzlipofutzli"));
|
||||
c.success_count = 1;
|
||||
return true;
|
||||
}
|
||||
c.success_count = 0;
|
||||
let command = c.command.clone();
|
||||
if self.ui.rules.bool("command_blocks_work") && !command.is_empty() {
|
||||
if let Some(c) = command_block_mut(&mut self.world, pos) {
|
||||
c.last_output = None;
|
||||
}
|
||||
let Some(state) = self.block_state_at(pos) else {
|
||||
return false;
|
||||
};
|
||||
let source = Source {
|
||||
entity: None,
|
||||
pos: [
|
||||
f64::from(pos.0) + 0.5,
|
||||
f64::from(pos.1) + 0.5,
|
||||
f64::from(pos.2) + 0.5,
|
||||
],
|
||||
rot: [facing_yaw(state), 0.0],
|
||||
eyes: false,
|
||||
silent: false,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
block: Some(pos),
|
||||
};
|
||||
// performPrefixedCommand: a leading slash is allowed.
|
||||
let line = command.strip_prefix('/').unwrap_or(&command).to_owned();
|
||||
let outer = self.cmds.results.replace(Vec::new());
|
||||
let level = std::mem::replace(&mut self.ui.registries.permission, 2);
|
||||
self.with_source(source, |g| g.run_command(&line));
|
||||
self.ui.registries.permission = level;
|
||||
let results = std::mem::replace(&mut self.cmds.results, outer).unwrap_or_default();
|
||||
let successes = results.iter().filter(|(success, _)| *success).count();
|
||||
if let Some(c) = command_block_mut(&mut self.world, pos) {
|
||||
c.success_count = successes as i32;
|
||||
}
|
||||
}
|
||||
if let Some(c) = command_block_mut(&mut self.world, pos) {
|
||||
c.last_execution = if c.update_last_execution {
|
||||
game_time
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `CloseableCommandBlockSource.sendSystemMessage`: the block's last
|
||||
/// output, stamped with the time. Nothing when it doesn't track output
|
||||
/// (`CommandSource.NULL`).
|
||||
pub(super) fn command_block_output(&mut self, pos: Pos, message: Text) {
|
||||
if let Some(c) = command_block_mut(&mut self.world, pos)
|
||||
&& c.track_output
|
||||
{
|
||||
let time = chrono::Local::now().format("[%H:%M:%S] ").to_string();
|
||||
c.last_output = Some(Text::literal(time).append(message));
|
||||
}
|
||||
}
|
||||
/// `CommandSourceStack.sendSuccess` from a command block: its output when
|
||||
/// `send_command_feedback`, and `broadcastToAdmins` when
|
||||
/// `command_block_output`.
|
||||
pub(super) fn command_block_success(&mut self, pos: Pos, message: Text) {
|
||||
let Some(name) = self
|
||||
.command_block(pos)
|
||||
.filter(|c| c.track_output)
|
||||
.map(CommandBlock::name)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let feedback = self.ui.rules.bool("send_command_feedback");
|
||||
if feedback {
|
||||
self.command_block_output(pos, message.clone());
|
||||
}
|
||||
if feedback && self.ui.rules.bool("command_block_output") {
|
||||
let broadcast = Text::translate("chat.type.admin", &[name, message])
|
||||
.with_color(text::GRAY)
|
||||
.italic();
|
||||
self.system_message(broadcast);
|
||||
}
|
||||
}
|
||||
|
||||
/// `LocalPlayer.openCommandBlock`.
|
||||
pub(super) fn open_command_block(&mut self, pos: Pos) {
|
||||
let Some(block) = self.command_block(pos).cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(state) = self.block_state_at(pos) else {
|
||||
return;
|
||||
};
|
||||
let mut command = EditBox::new(0.0, 50.0, 300.0, 20.0);
|
||||
command.max_length = 32500;
|
||||
command.set_value(&block.command);
|
||||
command.focused = true;
|
||||
let mut previous = EditBox::new(0.0, 135.0, 276.0, 20.0);
|
||||
previous.max_length = 32500;
|
||||
previous.text_color = UNEDITABLE;
|
||||
previous.focused = false;
|
||||
let mut screen = CommandBlockScreen {
|
||||
pos,
|
||||
command,
|
||||
previous,
|
||||
track_output: block.track_output,
|
||||
mode: Mode::of_block(&state.name).unwrap_or(Mode::Redstone),
|
||||
conditional: conditional(state),
|
||||
auto: block.auto,
|
||||
};
|
||||
screen.show_previous(&block);
|
||||
self.command_block_screen = Some(screen);
|
||||
self.screen = Screen::CommandBlock;
|
||||
self.capture(false);
|
||||
}
|
||||
pub(super) fn close_command_block(&mut self) {
|
||||
self.command_block_screen = None;
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
pub(super) fn draw_command_block(&mut self, batch: &mut HudBatch) {
|
||||
let Some(mut s) = self.command_block_screen.take() else {
|
||||
return;
|
||||
};
|
||||
// AbstractCommandBlockEditScreen.tick: the block is gone.
|
||||
if self.command_block(s.pos).is_none() {
|
||||
self.close_command_block();
|
||||
return;
|
||||
}
|
||||
let atlas = &self.res.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let mid = (w / 2.0).floor();
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
|
||||
let title = Text::translate("advMode.setCommand", &[]);
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
(mid - tw / 2.0).floor(),
|
||||
20.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
let grey = rgba(160, 160, 160, 255);
|
||||
let label = Text::translate("advMode.command", &[]);
|
||||
batch.text_styled(atlas, &label, mid - 149.0, 40.0, grey, true);
|
||||
s.command.x = mid - 150.0;
|
||||
s.command.draw(batch, atlas, None);
|
||||
if !s.previous.value.is_empty() {
|
||||
let label = Text::translate("advMode.previousOutput", &[]);
|
||||
batch.text_styled(atlas, &label, mid - 149.0, 125.0, grey, true);
|
||||
s.previous.x = mid - 150.0;
|
||||
s.previous.draw(batch, atlas, None);
|
||||
}
|
||||
for (b, x, y, bw) in CommandBlockScreen::buttons(w, h) {
|
||||
let hover = ui::hovered(self.cursor, x, y, bw, 20.0);
|
||||
ui::button(batch, atlas, x, y, bw, 20.0, &s.label(b), true, hover);
|
||||
}
|
||||
self.command_block_screen = Some(s);
|
||||
}
|
||||
pub(super) fn command_block_click(&mut self) {
|
||||
let Some(mut s) = self.command_block_screen.take() else {
|
||||
return;
|
||||
};
|
||||
let size = self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.map_or([1, 1], |r| [r.config.width, r.config.height]);
|
||||
let b = HudBatch::new(size);
|
||||
let hit = CommandBlockScreen::buttons(b.width, b.height)
|
||||
.into_iter()
|
||||
.find(|(_, x, y, bw)| ui::hovered(self.cursor, *x, *y, *bw, 20.0))
|
||||
.map(|b| b.0);
|
||||
if hit.is_some() {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
match hit {
|
||||
Some(Button::Output) => {
|
||||
s.track_output = !s.track_output;
|
||||
if let Some(block) = self.command_block(s.pos) {
|
||||
s.show_previous(block);
|
||||
}
|
||||
}
|
||||
Some(Button::Mode) => s.mode = s.mode.next(),
|
||||
Some(Button::Conditional) => s.conditional = !s.conditional,
|
||||
Some(Button::Auto) => s.auto = !s.auto,
|
||||
Some(Button::Done) => {
|
||||
self.set_command_block(&s);
|
||||
self.close_command_block();
|
||||
return;
|
||||
}
|
||||
Some(Button::Cancel) => {
|
||||
self.close_command_block();
|
||||
return;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
self.command_block_screen = Some(s);
|
||||
}
|
||||
/// `AbstractCommandBlockEditScreen.keyPressed`: Enter is Done, Escape
|
||||
/// cancels, the rest edits the command.
|
||||
pub(super) fn command_block_key(&mut self, event: &KeyEvent) {
|
||||
if event.state != ElementState::Pressed {
|
||||
return;
|
||||
}
|
||||
let PhysicalKey::Code(key) = event.physical_key else {
|
||||
return;
|
||||
};
|
||||
match key {
|
||||
KeyCode::Escape => return self.close_command_block(),
|
||||
KeyCode::Enter | KeyCode::NumpadEnter => {
|
||||
if let Some(s) = self.command_block_screen.take() {
|
||||
self.set_command_block(&s);
|
||||
}
|
||||
return self.close_command_block();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let ctrl = self.keys.contains(&KeyCode::ControlLeft);
|
||||
let shift = self.keys.contains(&KeyCode::ShiftLeft);
|
||||
let shortcut = self.edit_shortcut(event);
|
||||
let Some(s) = self.command_block_screen.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if let Some(shortcut) = shortcut {
|
||||
s.command.shortcut(shortcut, &mut self.clipboard);
|
||||
} else if !s.command.key(key, ctrl, shift) && !ctrl {
|
||||
self.command_block_type(event.text.as_deref().unwrap_or(""));
|
||||
}
|
||||
}
|
||||
/// Characters typed into the command box (`StringUtil.isAllowedChatCharacter`).
|
||||
pub(super) fn command_block_type(&mut self, typed: &str) {
|
||||
let allowed: String = typed
|
||||
.chars()
|
||||
.filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}')
|
||||
.collect();
|
||||
if let Some(s) = self.command_block_screen.as_mut()
|
||||
&& !allowed.is_empty()
|
||||
{
|
||||
s.command.insert_text(&allowed);
|
||||
}
|
||||
}
|
||||
/// `ServerGamePacketListenerImpl.handleSetCommandBlock`.
|
||||
fn set_command_block(&mut self, s: &CommandBlockScreen) {
|
||||
if !self.can_use_game_master_blocks() {
|
||||
self.system_message(Text::translate("advMode.notAllowed", &[]));
|
||||
return;
|
||||
}
|
||||
let pos = s.pos;
|
||||
let registry = self.res.assets.registry;
|
||||
let Some(current) = self.block_state_at(pos) else {
|
||||
return;
|
||||
};
|
||||
let Some(old_mode) = Mode::of_block(¤t.name) else {
|
||||
return;
|
||||
};
|
||||
if self.command_block(pos).is_none() {
|
||||
return;
|
||||
}
|
||||
// The mode is the block, the conditional flag its state; the block
|
||||
// entity stays.
|
||||
let mut wanted = current.clone();
|
||||
wanted.name = s.mode.block().to_owned();
|
||||
wanted
|
||||
.properties
|
||||
.insert("conditional".into(), s.conditional.to_string());
|
||||
if let Ok(id) = registry.resolve(&wanted)
|
||||
&& wanted != *current
|
||||
{
|
||||
let entity = self.world.block_entities.remove(&pos);
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS)
|
||||
});
|
||||
if let Some(entity) = entity {
|
||||
self.world.block_entities.insert(pos, entity);
|
||||
}
|
||||
let _ = self.process_level_events();
|
||||
}
|
||||
let command = s.command.value.clone();
|
||||
let Some(c) = command_block_mut(&mut self.world, pos) else {
|
||||
return;
|
||||
};
|
||||
c.set_command(&command);
|
||||
c.track_output = s.track_output;
|
||||
if !s.track_output {
|
||||
c.last_output = None;
|
||||
}
|
||||
// CommandBlockEntity.setAutomatic, then onModeSwitch.
|
||||
let (was_auto, powered) = (c.auto, c.powered);
|
||||
c.auto = s.auto;
|
||||
if !was_auto && s.auto && !powered && s.mode != Mode::Sequence {
|
||||
self.schedule_command_block_tick(pos);
|
||||
}
|
||||
if old_mode != s.mode && s.mode == Mode::Auto && (powered || s.auto) {
|
||||
self.schedule_command_block_tick(pos);
|
||||
}
|
||||
if !command.is_empty() {
|
||||
let key = if self.ui.rules.bool("command_blocks_work") {
|
||||
"advMode.setCommand.success"
|
||||
} else {
|
||||
"advMode.setCommand.disabled"
|
||||
};
|
||||
self.system_message(Text::translate(key, &[Text::literal(command)]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,13 +143,22 @@ impl Game<'_> {
|
||||
if self.command_source.is_some_and(|s| s.silent) {
|
||||
return;
|
||||
}
|
||||
self.system_message(Text::empty().append(message).with_color(text::RED));
|
||||
let message = Text::empty().append(message).with_color(text::RED);
|
||||
if let Some(block) = self.command_source.and_then(|s| s.block) {
|
||||
self.command_block_output(block, message);
|
||||
return;
|
||||
}
|
||||
self.system_message(message);
|
||||
}
|
||||
/// sendSuccess honouring `send_command_feedback`.
|
||||
pub(super) fn feedback(&mut self, message: Text) {
|
||||
if self.command_source.is_some_and(|s| s.silent) {
|
||||
return;
|
||||
}
|
||||
if let Some(block) = self.command_source.and_then(|s| s.block) {
|
||||
self.command_block_success(block, message);
|
||||
return;
|
||||
}
|
||||
if self.ui.rules.bool("send_command_feedback") {
|
||||
self.system_message(message);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,9 @@ pub(in crate::game) struct Source {
|
||||
/// `execute in` another dimension than the one Horizon has loaded: none
|
||||
/// of its chunks are loaded.
|
||||
pub elsewhere: bool,
|
||||
/// The command block whose output this source is
|
||||
/// (`BaseCommandBlock.CloseableCommandBlockSource`).
|
||||
pub block: Option<(i32, i32, i32)>,
|
||||
}
|
||||
|
||||
/// Where `execute store` writes.
|
||||
@@ -74,6 +77,7 @@ impl Game<'_> {
|
||||
silent: false,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
block: None,
|
||||
}
|
||||
}
|
||||
/// The server as a source (function ticks and schedules): the world spawn.
|
||||
@@ -86,6 +90,7 @@ impl Game<'_> {
|
||||
silent: true,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
block: None,
|
||||
}
|
||||
}
|
||||
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
|
||||
|
||||
@@ -420,6 +420,7 @@ impl Game<'_> {
|
||||
}
|
||||
match self.screen {
|
||||
Screen::Chat => self.chat_type(text),
|
||||
Screen::CommandBlock => self.command_block_type(text),
|
||||
Screen::Options => self.ui.options.type_text(&self.res.atlas, text),
|
||||
Screen::Inventory if self.recipe_search_focused() => {
|
||||
self.recipe_text(Some(text), false)
|
||||
@@ -609,6 +610,7 @@ impl Game<'_> {
|
||||
Screen::Stats => "stats",
|
||||
Screen::Advancements => "advancements",
|
||||
Screen::WorldOptions => "world-options",
|
||||
Screen::CommandBlock => "command-block",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ impl Game<'_> {
|
||||
// (EditBox.keyPressed); releases still reach KeyboardHandler.
|
||||
let typing = matches!(
|
||||
self.screen,
|
||||
Screen::Chat | Screen::Options | Screen::WorldOptions
|
||||
Screen::Chat | Screen::Options | Screen::WorldOptions | Screen::CommandBlock
|
||||
) || self.sign_edit.is_some()
|
||||
|| self.book.is_some()
|
||||
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
|
||||
|
||||
@@ -35,6 +35,7 @@ pub mod clock;
|
||||
pub mod clouds;
|
||||
pub mod collisions;
|
||||
pub mod command;
|
||||
pub mod command_block;
|
||||
pub mod command_storage;
|
||||
pub mod component;
|
||||
pub mod container_screen;
|
||||
|
||||
@@ -530,6 +530,7 @@ pub fn encode_block_entity(
|
||||
BlockEntity::TrialSpawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::Vault(v) => entries.extend(v.save()),
|
||||
BlockEntity::Beehive(h) => entries.extend(h.to_nbt()),
|
||||
BlockEntity::CommandBlock(c) => entries.extend(c.save()),
|
||||
}
|
||||
Tag::compound(entries)
|
||||
}
|
||||
@@ -661,6 +662,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag),
|
||||
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag),
|
||||
BlockEntity::Beehive(h) => **h = crate::beehive::Beehive::from_nbt(tag),
|
||||
BlockEntity::CommandBlock(c) => **c = crate::command_block::CommandBlock::load(tag),
|
||||
}
|
||||
Some((pos, entity))
|
||||
}
|
||||
|
||||
@@ -426,8 +426,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
// A fresh shrieker has warning level 0 and so never responds,
|
||||
// and no player is near enough for a portal to spawn a piglin.
|
||||
// A fresh command block has no command and is neither powered
|
||||
// nor always active: `CommandBlock.tick` changes nothing.
|
||||
LevelEvent::BlockEvent {
|
||||
kind: "shrieker_respond" | "portal_spawn",
|
||||
kind: "shrieker_respond" | "portal_spawn" | "command_block",
|
||||
..
|
||||
} => {}
|
||||
LevelEvent::BlockEvent { kind, .. } => {
|
||||
|
||||
@@ -656,6 +656,31 @@ impl Behaviours {
|
||||
) {
|
||||
self.sim(level, ticks).update_neighbors_at(pos, block);
|
||||
}
|
||||
/// `Level.updateNeighbourForOutputSignal(pos, block)` for the block at
|
||||
/// `pos`: comparators beside it (or behind a conductor there) read their
|
||||
/// input again.
|
||||
pub fn update_neighbour_for_output_signal<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let block = self.block(sim.state(pos));
|
||||
sim.update_neighbour_for_output_signal(pos, block);
|
||||
}
|
||||
/// `Level.scheduleTick(pos, block, delay)` for the block at `pos`.
|
||||
pub fn schedule_tick<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
delay: i32,
|
||||
) {
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let block = self.block(sim.state(pos));
|
||||
sim.schedule_tick(pos, block, delay);
|
||||
}
|
||||
/// `BlockState.handleNeighborChanged(level, pos, changedBlock, orientation, movedByPiston)`
|
||||
/// for the state currently at `pos`.
|
||||
pub fn handle_neighbor_changed<L: LevelAccess + ?Sized>(
|
||||
|
||||
@@ -117,6 +117,14 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
kind: "dispense",
|
||||
});
|
||||
}
|
||||
// CommandBlock.tick runs commands: the caller does it.
|
||||
Class::Command => {
|
||||
self.emit(LevelEvent::BlockEvent {
|
||||
pos,
|
||||
state,
|
||||
kind: "command_block",
|
||||
});
|
||||
}
|
||||
Class::FallingBlock => self.falling_block_tick(pos, state),
|
||||
Class::Brushable => {
|
||||
if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() {
|
||||
|
||||
Reference in New Issue
Block a user