refactor(commands): from async to sync Part 3
This commit is contained in:
1 parent
5d841d6d3b
commit
66a5f53408
222 files changed
+11699
-12920
No files matched your search
@@ -211,7 +211,7 @@ mod tests {
|
||||
let ec = EnderChestInventory::new();
|
||||
assert_eq!(ec.size(), 27);
|
||||
assert!(ec.is_empty().await);
|
||||
assert!(!ec.has_tracker().await);
|
||||
assert!(!ec.has_tracker());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -323,13 +323,9 @@ impl AnvilChunkData {
|
||||
|
||||
let compression = compression.unwrap_or_else(|| chunk_config.compression.algorithm.into());
|
||||
let level = chunk_config.compression.level;
|
||||
|
||||
// Offload CPU-heavy compression to blocking thread pool
|
||||
let compressed_data =
|
||||
tokio::task::spawn_blocking(move || compression.compress_data(&raw_bytes, level))
|
||||
.await
|
||||
.map_err(|err| ChunkWritingError::IoError(std::io::Error::other(err)))?
|
||||
.map_err(ChunkWritingError::Compression)?;
|
||||
let compressed_data = compression
|
||||
.compress_data(&raw_bytes, level)
|
||||
.map_err(ChunkWritingError::Compression)?;
|
||||
|
||||
Ok(Self {
|
||||
compression: Some(compression),
|
||||
@@ -793,17 +789,10 @@ impl<S: SingleChunkDataSerializer + 'static> ChunkSerializer for AnvilChunkFile<
|
||||
let is_ok = match &self.chunks_data[index] {
|
||||
None => stream.send(LoadedData::Missing(chunk)).await.is_ok(),
|
||||
Some(chunk_metadata) => {
|
||||
let chunk_data = chunk_metadata.serialized_data.clone();
|
||||
let result =
|
||||
match tokio::task::spawn_blocking(move || chunk_data.to_chunk(chunk)).await
|
||||
{
|
||||
Ok(Ok(chunk_res)) => LoadedData::Loaded(chunk_res),
|
||||
Ok(Err(err)) => LoadedData::Error((chunk, err)),
|
||||
Err(err) => LoadedData::Error((
|
||||
chunk,
|
||||
ChunkReadingError::IoError(std::io::Error::other(err)),
|
||||
)),
|
||||
};
|
||||
let result = match chunk_metadata.serialized_data.to_chunk(chunk) {
|
||||
Ok(chunk_res) => LoadedData::Loaded(chunk_res),
|
||||
Err(err) => LoadedData::Error((chunk, err)),
|
||||
};
|
||||
|
||||
stream.send(result).await.is_ok()
|
||||
}
|
||||
|
||||
@@ -407,26 +407,21 @@ impl<S: SingleChunkDataSerializer + 'static> ChunkSerializer for LinearV2File<S>
|
||||
let chunks_data = self.chunks_data.clone();
|
||||
let timestamps = self.timestamps;
|
||||
|
||||
let (bucket_entries, compressed_buckets) = tokio::task::spawn_blocking(move || {
|
||||
let mut compressed_buckets: Vec<Box<[u8]>> = Vec::with_capacity(bucket_count);
|
||||
let mut bucket_entries: Vec<BucketSizeEntry> = Vec::with_capacity(bucket_count);
|
||||
let mut compressed_buckets: Vec<Box<[u8]>> = Vec::with_capacity(bucket_count);
|
||||
let mut bucket_entries: Vec<BucketSizeEntry> = Vec::with_capacity(bucket_count);
|
||||
|
||||
for bucket_idx in 0..bucket_count {
|
||||
let raw = Self::serialise_bucket(&chunks_data, ×tamps, bucket_idx, grid_size);
|
||||
let compressed =
|
||||
compress_to_vec(raw.as_slice(), CompressionLevel::Fastest).into_boxed_slice();
|
||||
let hash = xxh64(&compressed, 0);
|
||||
bucket_entries.push(BucketSizeEntry {
|
||||
size: compressed.len() as u32,
|
||||
compression_level: 1,
|
||||
xxhash: hash,
|
||||
});
|
||||
compressed_buckets.push(compressed);
|
||||
}
|
||||
(bucket_entries, compressed_buckets)
|
||||
})
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
for bucket_idx in 0..bucket_count {
|
||||
let raw = Self::serialise_bucket(&chunks_data, ×tamps, bucket_idx, grid_size);
|
||||
let compressed =
|
||||
compress_to_vec(raw.as_slice(), CompressionLevel::Fastest).into_boxed_slice();
|
||||
let hash = xxh64(&compressed, 0);
|
||||
bucket_entries.push(BucketSizeEntry {
|
||||
size: compressed.len() as u32,
|
||||
compression_level: 1,
|
||||
xxhash: hash,
|
||||
});
|
||||
compressed_buckets.push(compressed);
|
||||
}
|
||||
|
||||
let newest_timestamp = self.timestamps.iter().copied().max().unwrap_or(0);
|
||||
|
||||
@@ -598,18 +593,9 @@ impl<S: SingleChunkDataSerializer + 'static> ChunkSerializer for LinearV2File<S>
|
||||
let is_ok = match &self.chunks_data[index] {
|
||||
None => stream.send(LoadedData::Missing(chunk)).await.is_ok(),
|
||||
Some(data) => {
|
||||
let data = data.clone();
|
||||
let result = match tokio::task::spawn_blocking(move || {
|
||||
S::from_bytes(&data, chunk)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(c)) => LoadedData::Loaded(c),
|
||||
Ok(Err(err)) => LoadedData::Error((chunk, err)),
|
||||
Err(err) => LoadedData::Error((
|
||||
chunk,
|
||||
ChunkReadingError::IoError(std::io::Error::other(err)),
|
||||
)),
|
||||
let result = match S::from_bytes(data, chunk) {
|
||||
Ok(c) => LoadedData::Loaded(c),
|
||||
Err(err) => LoadedData::Error((chunk, err)),
|
||||
};
|
||||
stream.send(result).await.is_ok()
|
||||
}
|
||||
|
||||
@@ -129,8 +129,7 @@ where
|
||||
let index = (rel_x + rel_z * 32) as usize;
|
||||
|
||||
if let Some(chunk_bytes) = self.data.chunks.get(&index.to_string()) {
|
||||
let chunk_bytes = chunk_bytes.clone();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let res = (|| {
|
||||
let mut decoder = StreamingDecoder::new(&chunk_bytes[..]).map_err(|e| {
|
||||
ChunkReadingError::IoError(std::io::Error::other(e.to_string()))
|
||||
})?;
|
||||
@@ -139,16 +138,11 @@ where
|
||||
.map_err(ChunkReadingError::IoError)?;
|
||||
let bytes = Bytes::from(decompressed);
|
||||
D::from_bytes(&bytes, pos)
|
||||
})
|
||||
.await;
|
||||
})();
|
||||
|
||||
let data_res = match res {
|
||||
Ok(Ok(data)) => LoadedData::Loaded(data),
|
||||
Ok(Err(e)) => LoadedData::Error((pos, e)),
|
||||
Err(e) => LoadedData::Error((
|
||||
pos,
|
||||
ChunkReadingError::IoError(std::io::Error::other(e)),
|
||||
)),
|
||||
Ok(data) => LoadedData::Loaded(data),
|
||||
Err(e) => LoadedData::Error((pos, e)),
|
||||
};
|
||||
|
||||
if stream.send(data_res).await.is_err() {
|
||||
|
||||
@@ -108,9 +108,7 @@ impl<S: ChunkSerializer<WriteBackend = PathBuf> + 'static> ChunkSerializerLazyLo
|
||||
);
|
||||
return Ok(S::default());
|
||||
}
|
||||
let value = tokio::task::spawn_blocking(move || S::read(bytes.into()))
|
||||
.await
|
||||
.map_err(|e| ChunkReadingError::IoError(std::io::Error::other(e)))??;
|
||||
let value = S::read(bytes.into())?;
|
||||
trace!("Successfully read file from disk: {}", self.path.display());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -56,6 +56,55 @@ fn needs_relighting(chunk: &crate::chunk::ChunkData, config: LightingEngineConfi
|
||||
!has_complex_light
|
||||
}
|
||||
|
||||
async fn load_proto_chunk(chunk: &Arc<crate::chunk::ChunkData>, level: &Level) -> ProtoChunk {
|
||||
if let Some(pool) = &level.gen_pool {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let world_gen = level.world_gen.load();
|
||||
let chunk_clone = chunk.clone();
|
||||
pool.spawn(move || {
|
||||
let p = ProtoChunk::from_chunk_data(&chunk_clone, &world_gen);
|
||||
let _ = tx.send(p);
|
||||
});
|
||||
rx.await
|
||||
.unwrap_or_else(|_| ProtoChunk::from_chunk_data(chunk, &level.world_gen.load()))
|
||||
} else {
|
||||
ProtoChunk::from_chunk_data(chunk, &level.world_gen.load())
|
||||
}
|
||||
}
|
||||
|
||||
async fn process_loaded_chunk(chunk: Arc<crate::chunk::ChunkData>, level: &Level) -> Chunk {
|
||||
let pos = ChunkPos::new(chunk.x, chunk.z);
|
||||
if chunk.status == ChunkStatus::Full {
|
||||
let needs_relight = needs_relighting(&chunk, level.lighting_config);
|
||||
if needs_relight {
|
||||
debug!(
|
||||
"Chunk {pos:?} has uniform lighting, downgrading to Features stage for relighting"
|
||||
);
|
||||
|
||||
let mut proto = load_proto_chunk(&chunk, level).await;
|
||||
|
||||
// Clear all lighting data
|
||||
let section_count = proto.light.sky_light.len();
|
||||
proto.light.sky_light = (0..section_count)
|
||||
.map(|_| LightContainer::new_empty(15))
|
||||
.collect();
|
||||
proto.light.block_light = (0..section_count)
|
||||
.map(|_| LightContainer::new_empty(0))
|
||||
.collect();
|
||||
|
||||
// Set stage to Features
|
||||
proto.stage = StagedChunkEnum::Features;
|
||||
|
||||
Chunk::Proto(Box::new(proto))
|
||||
} else {
|
||||
Chunk::Level(chunk)
|
||||
}
|
||||
} else {
|
||||
let proto = load_proto_chunk(&chunk, level).await;
|
||||
Chunk::Proto(Box::new(proto))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn io_read_work(
|
||||
recv: crossfire::compat::MAsyncRx<Vec<ChunkPos>>,
|
||||
send: crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
|
||||
@@ -102,54 +151,9 @@ pub async fn io_read_work(
|
||||
match data {
|
||||
Loaded(chunk) => {
|
||||
let pos = ChunkPos::new(chunk.x, chunk.z);
|
||||
if chunk.status == ChunkStatus::Full {
|
||||
// Relighting check
|
||||
let needs_relight = needs_relighting(&chunk, level.lighting_config);
|
||||
|
||||
if needs_relight {
|
||||
debug!(
|
||||
"Chunk {pos:?} has uniform lighting, downgrading to Features stage for relighting"
|
||||
);
|
||||
|
||||
// Create ProtoChunk using the async method
|
||||
let mut proto =
|
||||
ProtoChunk::from_chunk_data(&chunk, &level.world_gen.load());
|
||||
|
||||
// Clear all lighting data
|
||||
let section_count = proto.light.sky_light.len();
|
||||
proto.light.sky_light = (0..section_count)
|
||||
.map(|_| LightContainer::new_empty(15))
|
||||
.collect();
|
||||
proto.light.block_light = (0..section_count)
|
||||
.map(|_| LightContainer::new_empty(0))
|
||||
.collect();
|
||||
|
||||
// Set stage to Features
|
||||
proto.stage = StagedChunkEnum::Features;
|
||||
|
||||
if send
|
||||
.send((pos, RecvChunk::IO(Chunk::Proto(Box::new(proto)))))
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Send fully valid chunk
|
||||
if send
|
||||
.send((pos, RecvChunk::IO(Chunk::Level(chunk))))
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Standard ProtoChunk handling for non-full chunks
|
||||
let val = RecvChunk::IO(Chunk::Proto(Box::new(
|
||||
ProtoChunk::from_chunk_data(&chunk, &level.world_gen.load()),
|
||||
)));
|
||||
if send.send((pos, val)).is_err() {
|
||||
break;
|
||||
}
|
||||
let processed = process_loaded_chunk(chunk, &level).await;
|
||||
if send.send((pos, RecvChunk::IO(processed))).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
LoadedData::Missing(pos) | LoadedData::Error((pos, _)) => {
|
||||
|
||||
@@ -246,15 +246,13 @@ impl BedBlock {
|
||||
if world.get_block_state(&bed_head_pos.up()).is_solid()
|
||||
|| world.get_block_state(&bed_foot_pos.up()).is_solid()
|
||||
{
|
||||
player
|
||||
.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_OBSTRUCTED,
|
||||
translation::bedrock::TILE_BED_OBSTRUCTED
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
player.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_OBSTRUCTED,
|
||||
translation::bedrock::TILE_BED_OBSTRUCTED
|
||||
),
|
||||
true,
|
||||
);
|
||||
return BlockActionResult::SuccessServer;
|
||||
}
|
||||
|
||||
@@ -262,15 +260,13 @@ impl BedBlock {
|
||||
if bed_props.occupied {
|
||||
// TODO: Wake up villager
|
||||
|
||||
player
|
||||
.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_OCCUPIED,
|
||||
translation::bedrock::TILE_BED_OCCUPIED
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
player.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_OCCUPIED,
|
||||
translation::bedrock::TILE_BED_OCCUPIED
|
||||
),
|
||||
true,
|
||||
);
|
||||
return BlockActionResult::SuccessServer;
|
||||
}
|
||||
|
||||
@@ -282,48 +278,39 @@ impl BedBlock {
|
||||
.position()
|
||||
.is_within_bounds(bed_foot_pos.to_f64(), 3.0, 3.0, 3.0)
|
||||
{
|
||||
player
|
||||
.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_TOO_FAR_AWAY,
|
||||
translation::bedrock::TILE_BED_TOOFAR
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
player.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_TOO_FAR_AWAY,
|
||||
translation::bedrock::TILE_BED_TOOFAR
|
||||
),
|
||||
true,
|
||||
);
|
||||
return BlockActionResult::SuccessServer;
|
||||
}
|
||||
|
||||
// Set respawn point
|
||||
if player
|
||||
.set_respawn_point(
|
||||
world.dimension.clone(),
|
||||
bed_head_pos,
|
||||
player.get_entity().yaw.load(),
|
||||
player.get_entity().pitch.load(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
{
|
||||
player
|
||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
||||
translation::bedrock::TILE_BED_RESPAWNSET
|
||||
))
|
||||
.await;
|
||||
if player.set_respawn_point(
|
||||
world.dimension.clone(),
|
||||
bed_head_pos,
|
||||
player.get_entity().yaw.load(),
|
||||
player.get_entity().pitch.load(),
|
||||
false,
|
||||
) {
|
||||
player.send_system_message(&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
||||
translation::bedrock::TILE_BED_RESPAWNSET
|
||||
));
|
||||
}
|
||||
|
||||
// Make sure the time and weather allows sleep
|
||||
if !can_sleep(world) {
|
||||
player
|
||||
.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
||||
translation::bedrock::TILE_BED_NOSLEEP
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
player.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
||||
translation::bedrock::TILE_BED_NOSLEEP
|
||||
),
|
||||
true,
|
||||
);
|
||||
return BlockActionResult::SuccessServer;
|
||||
}
|
||||
|
||||
@@ -337,15 +324,13 @@ impl BedBlock {
|
||||
if pos.is_within_bounds(bed_head_pos.to_f64(), 8.0, 5.0, 8.0)
|
||||
|| pos.is_within_bounds(bed_foot_pos.to_f64(), 8.0, 5.0, 8.0)
|
||||
{
|
||||
player
|
||||
.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_NOT_SAFE,
|
||||
translation::bedrock::TILE_BED_NOTSAFE
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
player.send_system_message_raw(
|
||||
&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_NOT_SAFE,
|
||||
translation::bedrock::TILE_BED_NOTSAFE
|
||||
),
|
||||
true,
|
||||
);
|
||||
return BlockActionResult::SuccessServer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ impl CommandBlock {
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
fn execute(
|
||||
server: &Arc<Server>,
|
||||
world: Arc<World>,
|
||||
block_entity: Arc<dyn BlockEntity>,
|
||||
@@ -133,24 +133,16 @@ impl CommandBlock {
|
||||
if command.is_empty() {
|
||||
command_entity.success_count.store(0, Ordering::Release);
|
||||
} else {
|
||||
let source = CommandSender::CommandBlock(command_entity, world.clone())
|
||||
.into_source(server)
|
||||
.await;
|
||||
let source = CommandSender::CommandBlock(command_entity, world).into_source(server);
|
||||
|
||||
server
|
||||
.command_dispatcher
|
||||
.load()
|
||||
.handle_command(&source, command)
|
||||
.await;
|
||||
.handle_command(&source, command);
|
||||
}
|
||||
}
|
||||
|
||||
async fn chain_execute(
|
||||
server: &Arc<Server>,
|
||||
world: Arc<World>,
|
||||
start: BlockPos,
|
||||
direction: Facing,
|
||||
) {
|
||||
fn chain_execute(server: &Arc<Server>, world: &Arc<World>, start: BlockPos, direction: Facing) {
|
||||
let mut i = u16::MAX;
|
||||
let mut pos = start;
|
||||
|
||||
@@ -179,7 +171,7 @@ impl CommandBlock {
|
||||
let props = CommandBlockLikeProperties::from_state_id(state_id, block);
|
||||
|
||||
if powered || auto {
|
||||
let conditions_met = Self::conditions_met(&world, &pos, direction);
|
||||
let conditions_met = Self::conditions_met(world, &pos, direction);
|
||||
if conditions_met {
|
||||
let command = command_entity
|
||||
.command
|
||||
@@ -190,7 +182,7 @@ impl CommandBlock {
|
||||
warn!("Command block entity disappeared during execution");
|
||||
break;
|
||||
};
|
||||
Self::execute(server, world.clone(), entity, &command).await;
|
||||
Self::execute(server, world.clone(), entity, &command);
|
||||
} else if props.conditional {
|
||||
command_entity.success_count.store(0, Ordering::Release);
|
||||
}
|
||||
@@ -298,25 +290,20 @@ impl BlockBehaviour for CommandBlock {
|
||||
let entity_clone = block_entity.clone();
|
||||
let position = *args.position;
|
||||
let facing = props.facing;
|
||||
tokio::spawn(async move {
|
||||
let Some(command_entity) = entity_clone.as_any().downcast_ref::<CommandBlockEntity>()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Some(command_entity) = entity_clone.as_any().downcast_ref::<CommandBlockEntity>() {
|
||||
let command = command_entity
|
||||
.command
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
Self::execute(&server, world.clone(), entity_clone, &command).await;
|
||||
Self::execute(&server, world.clone(), entity_clone, &command);
|
||||
Self::chain_execute(
|
||||
&server,
|
||||
world,
|
||||
&world,
|
||||
position.offset(facing.to_block_direction().to_offset()),
|
||||
facing,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
let block = args.world.get_block(args.position);
|
||||
let is_auto = command_entity.auto.load(Ordering::Relaxed);
|
||||
|
||||
@@ -294,13 +294,13 @@ impl DispenserBlock {
|
||||
Self::dispense_empty_bucket(ctx, dispenser, item).await;
|
||||
} else if FilledBucketItem::ids().contains(&item.item.id) {
|
||||
// Filled buckets place their fluid in front of the dispenser
|
||||
Self::dispense_filled_bucket(ctx, item).await;
|
||||
Self::dispense_filled_bucket(ctx, item);
|
||||
} else if item.item.id == Item::FLINT_AND_STEEL.id {
|
||||
// Flint and steel light fires and prime TNT
|
||||
Self::dispense_flint_and_steel(ctx, item).await;
|
||||
Self::dispense_flint_and_steel(ctx, item);
|
||||
} else if item.item.id == Item::HONEYCOMB.id {
|
||||
// Honeycombs wax copper blocks
|
||||
Self::dispense_honeycomb(ctx, item).await;
|
||||
Self::dispense_honeycomb(ctx, item);
|
||||
} else if entity_from_egg(item.item.id).is_some() {
|
||||
// Spawn eggs
|
||||
Self::dispense_spawn_egg(ctx, item);
|
||||
@@ -703,7 +703,7 @@ impl DispenserBlock {
|
||||
Some(stack)
|
||||
}
|
||||
|
||||
async fn dispense_filled_bucket(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||
fn dispense_filled_bucket(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||
let front = Self::target_position(ctx);
|
||||
|
||||
// TODO: Spawn the stored entity for axolotl/fish/tadpole buckets, like the player path.
|
||||
@@ -727,7 +727,7 @@ impl DispenserBlock {
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispense_flint_and_steel(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||
fn dispense_flint_and_steel(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||
let front = Self::target_position(ctx);
|
||||
let front_block = ctx.world.get_block(&front);
|
||||
|
||||
@@ -755,7 +755,7 @@ impl DispenserBlock {
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispense_honeycomb(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||
fn dispense_honeycomb(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||
let front = Self::target_position(ctx);
|
||||
let front_block = ctx.world.get_block(&front);
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::block_properties::{BlockProperties, RespawnAnchorLikeProperties};
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
use pumpkin_data::item::Item;
|
||||
@@ -61,46 +59,35 @@ impl BlockBehaviour for RespawnAnchorBlock {
|
||||
}
|
||||
|
||||
if props.charges == 0 {
|
||||
let player = Arc::clone(args.player);
|
||||
tokio::spawn(async move {
|
||||
player
|
||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
||||
translation::bedrock::TILE_BED_NOSLEEP
|
||||
))
|
||||
.await;
|
||||
});
|
||||
args.player
|
||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
||||
translation::bedrock::TILE_BED_NOSLEEP
|
||||
));
|
||||
return BlockActionResult::SuccessServer;
|
||||
}
|
||||
|
||||
let player = Arc::clone(args.player);
|
||||
let world = Arc::clone(args.world);
|
||||
let player = args.player;
|
||||
let world = args.world;
|
||||
let pos = *args.position;
|
||||
tokio::spawn(async move {
|
||||
if player
|
||||
.set_respawn_point(
|
||||
world.dimension.clone(),
|
||||
pos,
|
||||
player.get_entity().yaw.load(),
|
||||
player.get_entity().pitch.load(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
{
|
||||
world.play_sound(
|
||||
Sound::BlockRespawnAnchorSetSpawn,
|
||||
SoundCategory::Blocks,
|
||||
&pos.to_f64(),
|
||||
);
|
||||
if player.set_respawn_point(
|
||||
world.dimension.clone(),
|
||||
pos,
|
||||
player.get_entity().yaw.load(),
|
||||
player.get_entity().pitch.load(),
|
||||
false,
|
||||
) {
|
||||
world.play_sound(
|
||||
Sound::BlockRespawnAnchorSetSpawn,
|
||||
SoundCategory::Blocks,
|
||||
&pos.to_f64(),
|
||||
);
|
||||
|
||||
player
|
||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
||||
translation::bedrock::TILE_BED_RESPAWNSET
|
||||
))
|
||||
.await;
|
||||
}
|
||||
});
|
||||
player.send_system_message(&pumpkin_macros::translate_cross!(
|
||||
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
||||
translation::bedrock::TILE_BED_RESPAWNSET
|
||||
));
|
||||
}
|
||||
|
||||
BlockActionResult::SuccessServer
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ impl SculkShriekerBlock {
|
||||
show_icon: true,
|
||||
blend: true,
|
||||
};
|
||||
player.send_effect(darkness.clone()).await;
|
||||
player.send_effect(&darkness);
|
||||
player.living_entity.add_effect(darkness);
|
||||
}
|
||||
|
||||
|
||||
@@ -566,19 +566,17 @@ impl BlockRegistry {
|
||||
}
|
||||
|
||||
if location.0.y + face.to_offset().y > world.get_top_y() {
|
||||
player
|
||||
.send_system_message_raw(
|
||||
&pumpkin_util::text::TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::BUILD_TOOHIGH,
|
||||
pumpkin_data::translation::bedrock::BUILD_TOOHIGH,
|
||||
vec![pumpkin_util::text::TextComponent::text(
|
||||
(world.get_top_y()).to_string(),
|
||||
)],
|
||||
)
|
||||
.color_named(pumpkin_util::text::color::NamedColor::Red),
|
||||
true,
|
||||
player.send_system_message_raw(
|
||||
&pumpkin_util::text::TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::BUILD_TOOHIGH,
|
||||
pumpkin_data::translation::bedrock::BUILD_TOOHIGH,
|
||||
vec![pumpkin_util::text::TextComponent::text(
|
||||
(world.get_top_y()).to_string(),
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
.color_named(pumpkin_util::text::color::NamedColor::Red),
|
||||
true,
|
||||
);
|
||||
return Err(BlockPlacingError::BlockOutOfWorld);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,11 +33,7 @@ impl ArgumentConsumer for BlockArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let block = args.pop().map(|arg| arg.value);
|
||||
match block {
|
||||
Some(s) => Box::pin(async move { Some(Arg::Block(s)) }),
|
||||
None => Box::pin(async move { None }),
|
||||
}
|
||||
args.pop().map(|arg| Arg::Block(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,11 +95,7 @@ impl ArgumentConsumer for BlockPredicateArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let block = args.pop().map(|arg| arg.value);
|
||||
match block {
|
||||
Some(s) => Box::pin(async move { Some(Arg::BlockPredicate(s)) }),
|
||||
None => Box::pin(async move { None }),
|
||||
}
|
||||
args.pop().map(|arg| Arg::BlockPredicate(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,24 +18,19 @@ impl GetClientSideArgParser for BoolArgConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for BoolArgConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt.map_or_else(
|
||||
|| None,
|
||||
|s| match s {
|
||||
"false" => Some(Arg::Bool(false)),
|
||||
"true" => Some(Arg::Bool(true)),
|
||||
_ => None,
|
||||
},
|
||||
);
|
||||
|
||||
Box::pin(async move { result })
|
||||
s_opt.and_then(|s| match s {
|
||||
"false" => Some(Arg::Bool(false)),
|
||||
"true" => Some(Arg::Bool(true)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,49 +23,35 @@ impl GetClientSideArgParser for BossbarColorArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for BossbarColorArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt.map_or_else(
|
||||
|| None,
|
||||
|s| {
|
||||
let color = match s {
|
||||
"blue" => Some(BossbarColor::Blue),
|
||||
"green" => Some(BossbarColor::Green),
|
||||
"pink" => Some(BossbarColor::Pink),
|
||||
"purple" => Some(BossbarColor::Purple),
|
||||
"red" => Some(BossbarColor::Red),
|
||||
"white" => Some(BossbarColor::White),
|
||||
"yellow" => Some(BossbarColor::Yellow),
|
||||
_ => None,
|
||||
};
|
||||
let color = match s_opt? {
|
||||
"blue" => Some(BossbarColor::Blue),
|
||||
"green" => Some(BossbarColor::Green),
|
||||
"pink" => Some(BossbarColor::Pink),
|
||||
"purple" => Some(BossbarColor::Purple),
|
||||
"red" => Some(BossbarColor::Red),
|
||||
"white" => Some(BossbarColor::White),
|
||||
"yellow" => Some(BossbarColor::Yellow),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
color.map(Arg::BossbarColor)
|
||||
},
|
||||
);
|
||||
|
||||
Box::pin(async move { result })
|
||||
color.map(Arg::BossbarColor)
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move {
|
||||
let colors = ["blue", "green", "pink", "purple", "red", "white", "yellow"];
|
||||
let suggestions: Vec<CommandSuggestion> = colors
|
||||
.iter()
|
||||
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
})
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||
let colors = ["blue", "green", "pink", "purple", "red", "white", "yellow"];
|
||||
let suggestions: Vec<CommandSuggestion> = colors
|
||||
.iter()
|
||||
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,53 +23,39 @@ impl GetClientSideArgParser for BossbarStyleArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for BossbarStyleArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt.map_or_else(
|
||||
|| None,
|
||||
|s| {
|
||||
let style = match s {
|
||||
"notched_10" => Some(BossbarDivisions::Notches10),
|
||||
"notched_12" => Some(BossbarDivisions::Notches12),
|
||||
"notched_20" => Some(BossbarDivisions::Notches20),
|
||||
"notched_6" => Some(BossbarDivisions::Notches6),
|
||||
"progress" => Some(BossbarDivisions::NoDivision),
|
||||
_ => None,
|
||||
};
|
||||
let style = match s_opt? {
|
||||
"notched_10" => Some(BossbarDivisions::Notches10),
|
||||
"notched_12" => Some(BossbarDivisions::Notches12),
|
||||
"notched_20" => Some(BossbarDivisions::Notches20),
|
||||
"notched_6" => Some(BossbarDivisions::Notches6),
|
||||
"progress" => Some(BossbarDivisions::NoDivision),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
style.map(Arg::BossbarStyle)
|
||||
},
|
||||
);
|
||||
|
||||
Box::pin(async move { result })
|
||||
style.map(Arg::BossbarStyle)
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move {
|
||||
let styles = [
|
||||
"notched_10",
|
||||
"notched_12",
|
||||
"notched_20",
|
||||
"notched_6",
|
||||
"progress",
|
||||
];
|
||||
let suggestions: Vec<CommandSuggestion> = styles
|
||||
.iter()
|
||||
.map(|style| CommandSuggestion::new((*style).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
})
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||
let styles = [
|
||||
"notched_10",
|
||||
"notched_12",
|
||||
"notched_20",
|
||||
"notched_6",
|
||||
"progress",
|
||||
];
|
||||
let suggestions: Vec<CommandSuggestion> = styles
|
||||
.iter()
|
||||
.map(|style| CommandSuggestion::new((*style).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,15 +25,15 @@ impl<T: ToFromNumber> ArgumentConsumer for BoundedNumArgumentConsumer<T>
|
||||
where
|
||||
Self: GetClientSideArgParser,
|
||||
{
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt
|
||||
s_opt
|
||||
// Replace args.pop()?.parse::<T>().ok()?
|
||||
.and_then(|s| s.parse::<T>().ok())
|
||||
.map(|x| {
|
||||
@@ -53,9 +53,7 @@ where
|
||||
|
||||
// Success case
|
||||
Arg::Num(Ok(x.to_number()))
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,50 +27,37 @@ impl GetClientSideArgParser for CommandTreeArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for CommandTreeArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
let s = args.pop().map(|arg| arg.value)?;
|
||||
|
||||
let Some(s) = s_opt else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let dispatcher = server.command_dispatcher.load();
|
||||
|
||||
Box::pin(async move {
|
||||
let dispatcher = server.command_dispatcher.load();
|
||||
|
||||
dispatcher
|
||||
.fallback_dispatcher
|
||||
.get_tree(s)
|
||||
.ok()
|
||||
.map(|tree| Arg::CommandTree(tree.clone()))
|
||||
})
|
||||
dispatcher
|
||||
.fallback_dispatcher
|
||||
.get_tree(s)
|
||||
.ok()
|
||||
.map(|tree| Arg::CommandTree(tree.clone()))
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
server: &'a Server,
|
||||
input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(input) = input.split_single_whitespace_including_empty_parts().last() else {
|
||||
return Ok(None);
|
||||
};
|
||||
fn suggest(&self, _sender: &CommandSender, server: &Server, input: &str) -> SuggestResult {
|
||||
let Some(input) = input.split_single_whitespace_including_empty_parts().last() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let dispatcher = server.command_dispatcher.load();
|
||||
let suggestions = dispatcher
|
||||
.fallback_dispatcher
|
||||
.commands
|
||||
.keys()
|
||||
.filter(|suggestion| suggestion.starts_with(input))
|
||||
.map(|suggestion| CommandSuggestion::new(suggestion.clone(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
})
|
||||
let dispatcher = server.command_dispatcher.load();
|
||||
let suggestions = dispatcher
|
||||
.fallback_dispatcher
|
||||
.commands
|
||||
.keys()
|
||||
.filter(|suggestion| suggestion.starts_with(input))
|
||||
.map(|suggestion| CommandSuggestion::new(suggestion.clone(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,26 +38,16 @@ impl ArgumentConsumer for DifficultyArgumentConsumer {
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> =
|
||||
s_opt.and_then(|s| Difficulty::from_str(s).map(Arg::Difficulty).ok());
|
||||
|
||||
Box::pin(async move { result })
|
||||
s_opt.and_then(|s| Difficulty::from_str(s).map(Arg::Difficulty).ok())
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move {
|
||||
let difficulties = ["easy", "normal", "hard", "peaceful"];
|
||||
let suggestions: Vec<CommandSuggestion> = difficulties
|
||||
.iter()
|
||||
.map(|difficulty| CommandSuggestion::new((*difficulty).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
})
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||
let difficulties = ["easy", "normal", "hard", "peaceful"];
|
||||
let suggestions: Vec<CommandSuggestion> = difficulties
|
||||
.iter()
|
||||
.map(|difficulty| CommandSuggestion::new((*difficulty).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -352,33 +352,26 @@ impl GetClientSideArgParser for EntitiesArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for EntitiesArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let Some(s) = s_opt else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let s = args.pop().map(|arg| arg.value)?;
|
||||
|
||||
let entity_selector = match s.parse::<TargetSelector>() {
|
||||
Ok(selector) => selector,
|
||||
Err(e) => {
|
||||
debug!("Failed to parse target selector '{s}': {e}");
|
||||
return Box::pin(async move { None }); // Return a Future resolving to None
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
Box::pin(async move {
|
||||
// todo: command context
|
||||
// This is the required asynchronous operation.
|
||||
let entities = server.select_entities(&entity_selector, Some(sender));
|
||||
// todo: command context
|
||||
let entities = server.select_entities(&entity_selector, Some(sender));
|
||||
|
||||
Some(Arg::Entities(entities))
|
||||
})
|
||||
Some(Arg::Entities(entities))
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -388,18 +381,12 @@ impl ArgumentConsumer for EntitiesArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let selector = match parse_target_selector_with_context(raw_arg) {
|
||||
Ok(selector) => selector,
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
|
||||
Box::pin(async move {
|
||||
let entities = server.select_entities(&selector, Some(sender));
|
||||
Ok(Some(Arg::Entities(entities)))
|
||||
})
|
||||
let selector = parse_target_selector_with_context(raw_arg)?;
|
||||
let entities = server.select_entities(&selector, Some(sender));
|
||||
Ok(Some(Arg::Entities(entities)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,37 +35,31 @@ impl GetClientSideArgParser for EntityArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for EntityArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let Some(s) = s_opt else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let s = args.pop().map(|arg| arg.value)?;
|
||||
|
||||
let entity_selector = match s.parse::<TargetSelector>() {
|
||||
Ok(selector) => selector,
|
||||
Err(e) => {
|
||||
debug!("Failed to parse target selector '{s}': {e}");
|
||||
return Box::pin(async move { None });
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
if entity_selector.get_limit() > 1 {
|
||||
debug!("Target selector '{s}' has limit > 1, expected single entity");
|
||||
return Box::pin(async move { None });
|
||||
return None;
|
||||
}
|
||||
|
||||
Box::pin(async move {
|
||||
// todo: command context
|
||||
let entities = server.select_entities(&entity_selector, Some(sender));
|
||||
// todo: command context
|
||||
let entities = server.select_entities(&entity_selector, Some(sender));
|
||||
|
||||
entities.into_iter().next().map(Arg::Entity)
|
||||
})
|
||||
entities.into_iter().next().map(Arg::Entity)
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -75,22 +69,17 @@ impl ArgumentConsumer for EntityArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let selector = match parse_target_selector_with_context(raw_arg) {
|
||||
Ok(selector) => selector,
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
let selector = parse_target_selector_with_context(raw_arg)?;
|
||||
|
||||
if selector.get_limit() > 1 {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Box::pin(async move {
|
||||
let entities = server.select_entities(&selector, Some(sender));
|
||||
Ok(entities.into_iter().next().map(Arg::Entity))
|
||||
})
|
||||
let entities = server.select_entities(&selector, Some(sender));
|
||||
Ok(entities.into_iter().next().map(Arg::Entity))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,17 +47,15 @@ impl ArgumentConsumer for EntityAnchorArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let Some(anchor_str) = args.pop().map(|arg| arg.value) else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let anchor_str = args.pop().map(|arg| arg.value)?;
|
||||
|
||||
let anchor = match anchor_str.to_lowercase().as_str() {
|
||||
"feet" => EntityAnchor::Feet,
|
||||
"eyes" => EntityAnchor::Eyes,
|
||||
_ => return Box::pin(async move { None }),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Box::pin(async move { Some(Arg::EntityAnchor(anchor)) })
|
||||
Some(Arg::EntityAnchor(anchor))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,15 +23,15 @@ impl GetClientSideArgParser for GamemodeArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for GamemodeArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt.and_then(|s| {
|
||||
s_opt.and_then(|s| {
|
||||
if let Ok(id) = s.parse::<i8>()
|
||||
&& let Ok(gamemode) = GameMode::try_from(id)
|
||||
{
|
||||
@@ -39,9 +39,7 @@ impl ArgumentConsumer for GamemodeArgumentConsumer {
|
||||
}
|
||||
|
||||
GameMode::from_str(s).map(Arg::GameMode).ok() // Convert Result to Option<T>
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,16 +76,11 @@ impl ArgumentConsumer for GameProfilesArgumentConsumer {
|
||||
server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { None });
|
||||
};
|
||||
let raw_arg = args.pop()?;
|
||||
|
||||
Box::pin(async move {
|
||||
resolve_profiles_from_token(sender, server, raw_arg)
|
||||
.await
|
||||
.ok()
|
||||
.map(Arg::GameProfiles)
|
||||
})
|
||||
resolve_profiles_from_token(sender, server, raw_arg)
|
||||
.ok()
|
||||
.map(Arg::GameProfiles)
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -95,78 +90,89 @@ impl ArgumentConsumer for GameProfilesArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
Box::pin(async move {
|
||||
let resolved = resolve_profiles_from_token(sender, server, raw_arg).await?;
|
||||
Ok(Some(Arg::GameProfiles(resolved)))
|
||||
})
|
||||
let resolved = resolve_profiles_from_token(sender, server, raw_arg)?;
|
||||
Ok(Some(Arg::GameProfiles(resolved)))
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut suggestions = Vec::new();
|
||||
if self.suggest_selectors {
|
||||
suggestions.extend(selector_suggestions());
|
||||
}
|
||||
fn suggest(&self, _sender: &CommandSender, server: &Server, _input: &str) -> SuggestResult {
|
||||
let mut suggestions = Vec::new();
|
||||
if self.suggest_selectors {
|
||||
suggestions.extend(selector_suggestions());
|
||||
}
|
||||
|
||||
let mut names = Vec::new();
|
||||
match self.suggestion_mode {
|
||||
GameProfileSuggestionMode::OnlinePlayers => {
|
||||
for player in server.get_all_players() {
|
||||
let mut names = Vec::new();
|
||||
match self.suggestion_mode {
|
||||
GameProfileSuggestionMode::OnlinePlayers => {
|
||||
for player in server.get_all_players() {
|
||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::NonOpOnlinePlayers => {
|
||||
let ops = server
|
||||
.data
|
||||
.operator_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for player in server.get_all_players() {
|
||||
if ops.ops.iter().all(|op| op.uuid != player.gameprofile.id) {
|
||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::NonOpOnlinePlayers => {
|
||||
let ops = server.data.operator_config.read().await;
|
||||
for player in server.get_all_players() {
|
||||
if ops.ops.iter().all(|op| op.uuid != player.gameprofile.id) {
|
||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::OpNames => {
|
||||
let ops = server
|
||||
.data
|
||||
.operator_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for op in &ops.ops {
|
||||
push_name_if_missing(&mut names, op.name.clone());
|
||||
}
|
||||
GameProfileSuggestionMode::OpNames => {
|
||||
let ops = server.data.operator_config.read().await;
|
||||
for op in &ops.ops {
|
||||
push_name_if_missing(&mut names, op.name.clone());
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::BannedNames => {
|
||||
let banned = server
|
||||
.data
|
||||
.banned_player_list
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for entry in &banned.banned_players {
|
||||
push_name_if_missing(&mut names, entry.name.clone());
|
||||
}
|
||||
GameProfileSuggestionMode::BannedNames => {
|
||||
let banned = server.data.banned_player_list.read().await;
|
||||
for entry in &banned.banned_players {
|
||||
push_name_if_missing(&mut names, entry.name.clone());
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::NonWhitelistedOnlinePlayers => {
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
for player in server.get_all_players() {
|
||||
if !whitelist.is_whitelisted(&player.gameprofile) {
|
||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::WhitelistedNames => {
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
for entry in &whitelist.whitelist {
|
||||
push_name_if_missing(&mut names, entry.name.clone());
|
||||
}
|
||||
GameProfileSuggestionMode::NonWhitelistedOnlinePlayers => {
|
||||
let whitelist = server
|
||||
.data
|
||||
.whitelist_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for player in server.get_all_players() {
|
||||
if !whitelist.is_whitelisted(&player.gameprofile) {
|
||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
GameProfileSuggestionMode::WhitelistedNames => {
|
||||
let whitelist = server
|
||||
.data
|
||||
.whitelist_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for entry in &whitelist.whitelist {
|
||||
push_name_if_missing(&mut names, entry.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suggestions.extend(
|
||||
names
|
||||
.into_iter()
|
||||
.map(|name| CommandSuggestion::new(name, None)),
|
||||
);
|
||||
suggestions.extend(
|
||||
names
|
||||
.into_iter()
|
||||
.map(|name| CommandSuggestion::new(name, None)),
|
||||
);
|
||||
|
||||
Ok(Some(suggestions))
|
||||
})
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +193,7 @@ impl<'a> FindArg<'a> for GameProfilesArgumentConsumer {
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_profiles_from_token(
|
||||
fn resolve_profiles_from_token(
|
||||
sender: &CommandSender,
|
||||
server: &Server,
|
||||
raw_arg: RawArg<'_>,
|
||||
@@ -212,12 +218,17 @@ async fn resolve_profiles_from_token(
|
||||
return Ok(vec![player.gameprofile.clone()]);
|
||||
}
|
||||
|
||||
let cached_entry = server.data.user_cache.write().await.get_by_uuid(uuid);
|
||||
let cached_entry = server
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get_by_uuid(uuid);
|
||||
if let Some(entry) = cached_entry {
|
||||
return Ok(vec![profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||
}
|
||||
|
||||
if let Some(profile) = resolve_known_profile_by_uuid(server, uuid).await {
|
||||
if let Some(profile) = resolve_known_profile_by_uuid(server, uuid) {
|
||||
return Ok(vec![profile]);
|
||||
}
|
||||
|
||||
@@ -232,13 +243,13 @@ async fn resolve_profiles_from_token(
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get_by_name(raw_arg.value);
|
||||
if let Some(entry) = cached_entry {
|
||||
return Ok(vec![profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||
}
|
||||
|
||||
if let Some(profile) = resolve_known_profile_by_name(server, raw_arg.value).await {
|
||||
if let Some(profile) = resolve_known_profile_by_name(server, raw_arg.value) {
|
||||
return Ok(vec![profile]);
|
||||
}
|
||||
|
||||
@@ -252,7 +263,7 @@ async fn resolve_profiles_from_token(
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.upsert(uuid, resolved_name.clone());
|
||||
return Ok(vec![profile_from_uuid_name(uuid, resolved_name)]);
|
||||
}
|
||||
@@ -266,7 +277,7 @@ async fn resolve_profiles_from_token(
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.upsert(profile.id, profile.name.clone());
|
||||
return Ok(vec![profile]);
|
||||
}
|
||||
@@ -274,16 +285,24 @@ async fn resolve_profiles_from_token(
|
||||
Err(syntax_player_unknown(raw_arg))
|
||||
}
|
||||
|
||||
async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
||||
fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
||||
{
|
||||
let ops = server.data.operator_config.read().await;
|
||||
let ops = server
|
||||
.data
|
||||
.operator_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(op) = ops.ops.iter().find(|op| op.name.eq_ignore_ascii_case(name)) {
|
||||
return Some(profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let banned_players = server.data.banned_player_list.read().await;
|
||||
let banned_players = server
|
||||
.data
|
||||
.banned_player_list
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = banned_players
|
||||
.banned_players
|
||||
.iter()
|
||||
@@ -294,7 +313,11 @@ async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<Ga
|
||||
}
|
||||
|
||||
{
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
let whitelist = server
|
||||
.data
|
||||
.whitelist_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = whitelist
|
||||
.whitelist
|
||||
.iter()
|
||||
@@ -307,16 +330,24 @@ async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<Ga
|
||||
None
|
||||
}
|
||||
|
||||
async fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
||||
fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
||||
{
|
||||
let ops = server.data.operator_config.read().await;
|
||||
let ops = server
|
||||
.data
|
||||
.operator_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(op) = ops.ops.iter().find(|op| op.uuid == uuid) {
|
||||
return Some(profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let banned_players = server.data.banned_player_list.read().await;
|
||||
let banned_players = server
|
||||
.data
|
||||
.banned_player_list
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = banned_players
|
||||
.banned_players
|
||||
.iter()
|
||||
@@ -327,7 +358,11 @@ async fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<Ga
|
||||
}
|
||||
|
||||
{
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
let whitelist = server
|
||||
.data
|
||||
.whitelist_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = whitelist.whitelist.iter().find(|entry| entry.uuid == uuid) {
|
||||
return Some(profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||
}
|
||||
|
||||
@@ -48,17 +48,15 @@ impl GetClientSideArgParser for HexColorArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for HexColorArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result = s_opt.and_then(|s| parse_hex_color(s).map(Arg::HexColor));
|
||||
|
||||
Box::pin(async move { result })
|
||||
s_opt.and_then(|s| parse_hex_color(s).map(Arg::HexColor))
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -68,31 +66,24 @@ impl ArgumentConsumer for HexColorArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let result = parse_hex_color(raw_arg.value)
|
||||
parse_hex_color(raw_arg.value)
|
||||
.map(|color| Some(Arg::HexColor(color)))
|
||||
.ok_or_else(|| {
|
||||
INVALID_HEX_ERROR_TYPE.create_without_context_args_slice(&[TextComponent::text(
|
||||
raw_arg.value.to_string(),
|
||||
)])
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
})
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||
let suggestions = vec![
|
||||
CommandSuggestion::new("F00".to_string(), None),
|
||||
CommandSuggestion::new("FF0000".to_string(), None),
|
||||
];
|
||||
Box::pin(async move { Ok(Some(suggestions)) })
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,19 +35,16 @@ impl ArgumentConsumer for MsgArgConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let first_word_opt = args.pop();
|
||||
let first_word = args.pop()?;
|
||||
|
||||
let mut msg = match first_word_opt {
|
||||
Some(word) => word.value.to_string(),
|
||||
None => return Box::pin(async { None }),
|
||||
};
|
||||
let mut msg = first_word.value.to_string();
|
||||
|
||||
while let Some(word) = args.pop() {
|
||||
msg.push(' ');
|
||||
msg.push_str(word.value);
|
||||
}
|
||||
|
||||
Box::pin(async move { Some(Arg::Msg(msg)) })
|
||||
Some(Arg::Msg(msg))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
use std::{collections::HashMap, hash::Hash, sync::Arc};
|
||||
|
||||
use bounded_num::{NotInBounds, Number};
|
||||
@@ -60,12 +59,10 @@ pub mod textcomponent;
|
||||
pub mod time;
|
||||
|
||||
/// see [`crate::command::tree::builder::argument`]
|
||||
pub type ConsumeResult<'a> = Pin<Box<dyn Future<Output = Option<Arg<'a>>> + Send + 'a>>;
|
||||
pub type ConsumeResultWithSyntax<'a> =
|
||||
Pin<Box<dyn Future<Output = Result<Option<Arg<'a>>, CommandSyntaxError>> + Send + 'a>>;
|
||||
pub type ConsumeResult<'a> = Option<Arg<'a>>;
|
||||
pub type ConsumeResultWithSyntax<'a> = Result<Option<Arg<'a>>, CommandSyntaxError>;
|
||||
|
||||
pub type SuggestResult<'a> =
|
||||
Pin<Box<dyn Future<Output = Result<Option<Vec<CommandSuggestion>>, CommandError>> + Send + 'a>>;
|
||||
pub type SuggestResult = Result<Option<Vec<CommandSuggestion>>, CommandError>;
|
||||
|
||||
pub trait ArgumentConsumer: Sync + Send + GetClientSideArgParser {
|
||||
fn consume<'a>(
|
||||
@@ -81,20 +78,14 @@ pub trait ArgumentConsumer: Sync + Send + GetClientSideArgParser {
|
||||
server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let future = self.consume(sender, server, args);
|
||||
Box::pin(async move { Ok(future.await) })
|
||||
Ok(self.consume(sender, server, args))
|
||||
}
|
||||
|
||||
/// Used for tab completion (but only if argument suggestion type is "`minecraft:ask_server`"!).
|
||||
///
|
||||
/// NOTE: This is called after this consumer's [`ArgumentConsumer::consume`] method returned None, so if args is used here, make sure [`ArgumentConsumer::consume`] never returns None after mutating args.
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move { Ok(None) })
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,17 +30,13 @@ impl GetClientSideArgParser for PlayersArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for PlayersArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let Some(s) = s_opt else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let s = args.pop().map(|arg| arg.value)?;
|
||||
|
||||
let sync_result: Option<Vec<Arc<Player>>> = match s {
|
||||
"@s" => match sender {
|
||||
@@ -57,20 +53,18 @@ impl ArgumentConsumer for PlayersArgumentConsumer {
|
||||
};
|
||||
|
||||
if let Some(players) = sync_result {
|
||||
return Box::pin(async move { Some(Arg::Players(players)) });
|
||||
return Some(Arg::Players(players));
|
||||
}
|
||||
|
||||
Box::pin(async move {
|
||||
let players = match s {
|
||||
"@r" => server
|
||||
.get_random_player()
|
||||
.map_or_else(|| Some(vec![]), |p| Some(vec![p])),
|
||||
"@a" | "@e" => Some(server.get_all_players()),
|
||||
name => server.get_player_by_name(name).map(|p| vec![p]),
|
||||
};
|
||||
let players = match s {
|
||||
"@r" => server
|
||||
.get_random_player()
|
||||
.map_or_else(|| Some(vec![]), |p| Some(vec![p])),
|
||||
"@a" | "@e" => Some(server.get_all_players()),
|
||||
name => server.get_player_by_name(name).map(|p| vec![p]),
|
||||
};
|
||||
|
||||
players.map(Arg::Players)
|
||||
})
|
||||
players.map(Arg::Players)
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -80,22 +74,14 @@ impl ArgumentConsumer for PlayersArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let selector = match parse_target_selector_with_context(raw_arg) {
|
||||
Ok(selector) => selector,
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
let selector = parse_target_selector_with_context(raw_arg)?;
|
||||
ensure_player_only_selector(&selector, raw_arg)?;
|
||||
|
||||
if let Err(error) = ensure_player_only_selector(&selector, raw_arg) {
|
||||
return Box::pin(async move { Err(error) });
|
||||
}
|
||||
|
||||
Box::pin(async move {
|
||||
let players = server.select_players(&selector, Some(sender));
|
||||
Ok(Some(Arg::Players(players)))
|
||||
})
|
||||
let players = server.select_players(&selector, Some(sender));
|
||||
Ok(Some(Arg::Players(players)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,24 +28,18 @@ impl GetClientSideArgParser for Position2DArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for Position2DArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let x_str_opt = args.pop().map(|arg| arg.value);
|
||||
let z_str_opt = args.pop().map(|arg| arg.value);
|
||||
let x_str = args.pop()?.value;
|
||||
let z_str = args.pop()?.value;
|
||||
|
||||
let (Some(x_str), Some(z_str)) = (x_str_opt, z_str_opt) else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
|
||||
let result: Option<Arg<'a>> = MaybeRelativePosition2D::try_new(x_str, z_str)
|
||||
MaybeRelativePosition2D::try_new(x_str, z_str)
|
||||
.and_then(|pos| pos.try_to_absolute(sender.position()))
|
||||
.map(Arg::Pos2D);
|
||||
|
||||
Box::pin(async move { result })
|
||||
.map(Arg::Pos2D)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,25 +25,19 @@ impl GetClientSideArgParser for Position3DArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for Position3DArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let x_str_opt = args.pop().map(|arg| arg.value);
|
||||
let y_str_opt = args.pop().map(|arg| arg.value);
|
||||
let z_str_opt = args.pop().map(|arg| arg.value);
|
||||
let x_str = args.pop()?.value;
|
||||
let y_str = args.pop()?.value;
|
||||
let z_str = args.pop()?.value;
|
||||
|
||||
let (Some(x_str), Some(y_str), Some(z_str)) = (x_str_opt, y_str_opt, z_str_opt) else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
|
||||
let result: Option<Arg<'a>> = MaybeRelativePosition3D::try_new(x_str, y_str, z_str)
|
||||
MaybeRelativePosition3D::try_new(x_str, y_str, z_str)
|
||||
.and_then(|pos| pos.try_to_absolute(sender.position()))
|
||||
.map(Arg::Pos3D);
|
||||
|
||||
Box::pin(async move { result })
|
||||
.map(Arg::Pos3D)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,25 +28,19 @@ impl GetClientSideArgParser for BlockPosArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for BlockPosArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let x_str_opt = args.pop().map(|arg| arg.value);
|
||||
let y_str_opt = args.pop().map(|arg| arg.value);
|
||||
let z_str_opt = args.pop().map(|arg| arg.value);
|
||||
let x_str = args.pop()?.value;
|
||||
let y_str = args.pop()?.value;
|
||||
let z_str = args.pop()?.value;
|
||||
|
||||
let (Some(x_str), Some(y_str), Some(z_str)) = (x_str_opt, y_str_opt, z_str_opt) else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
|
||||
let result: Option<Arg<'a>> = MaybeRelativeBlockPos::try_new(x_str, y_str, z_str)
|
||||
MaybeRelativeBlockPos::try_new(x_str, y_str, z_str)
|
||||
.and_then(|pos| pos.try_to_absolute(sender))
|
||||
.map(Arg::BlockPos);
|
||||
|
||||
Box::pin(async move { result })
|
||||
.map(Arg::BlockPos)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,23 +27,15 @@ impl GetClientSideArgParser for DamageTypeArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for DamageTypeArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let name_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = name_opt.map_or_else(
|
||||
|| None,
|
||||
|name| {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
DamageType::from_name(name).map(Arg::DamageType)
|
||||
},
|
||||
);
|
||||
|
||||
Box::pin(async move { result })
|
||||
let name = args.pop().map(|arg| arg.value)?;
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
DamageType::from_name(name).map(Arg::DamageType)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,22 +27,16 @@ impl GetClientSideArgParser for EffectTypeArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for EffectTypeArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let status_effect: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
match status_effect {
|
||||
Some(name) => Box::pin(async move {
|
||||
let status_effect =
|
||||
StatusEffect::from_name(name.strip_prefix("minecraft:").unwrap_or(name))?;
|
||||
Some(Arg::Effect(status_effect))
|
||||
}),
|
||||
None => Box::pin(async move { None }),
|
||||
}
|
||||
let name = args.pop().map(|arg| arg.value)?;
|
||||
let status_effect =
|
||||
StatusEffect::from_name(name.strip_prefix("minecraft:").unwrap_or(name))?;
|
||||
Some(Arg::Effect(status_effect))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,19 +27,14 @@ impl GetClientSideArgParser for EnchantmentArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for EnchantmentArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let name_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = name_opt.map_or_else(
|
||||
|| None,
|
||||
|name| Enchantment::from_name(name).map(Arg::Enchantment),
|
||||
);
|
||||
Box::pin(async move { result })
|
||||
let name = args.pop().map(|arg| arg.value)?;
|
||||
Enchantment::from_name(name).map(Arg::Enchantment)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,12 +37,7 @@ impl ArgumentConsumer for ItemArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let item = args.pop().map(|arg| arg.value);
|
||||
// TODO: When supporting data components in this argument, do it for ItemPredicateArgumentConsumer as well (both tags and items)
|
||||
match item {
|
||||
Some(s) => Box::pin(async move { Some(Arg::Item(s)) }),
|
||||
None => Box::pin(async move { None }),
|
||||
}
|
||||
args.pop().map(|arg| Arg::Item(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,11 +177,7 @@ impl ArgumentConsumer for ItemPredicateArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let item = args.pop().map(|arg| arg.value);
|
||||
match item {
|
||||
Some(s) => Box::pin(async move { Some(Arg::Item(s)) }),
|
||||
None => Box::pin(async move { None }),
|
||||
}
|
||||
args.pop().map(|arg| Arg::Item(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,23 +27,14 @@ impl GetClientSideArgParser for ParticleArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for ParticleArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let name_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = name_opt.map_or_else(
|
||||
|| None,
|
||||
|name| {
|
||||
Particle::from_name(name.strip_prefix("minecraft:").unwrap_or(name))
|
||||
.map(Arg::Particle)
|
||||
},
|
||||
);
|
||||
|
||||
Box::pin(async move { result })
|
||||
let name = args.pop().map(|arg| arg.value)?;
|
||||
Particle::from_name(name.strip_prefix("minecraft:").unwrap_or(name)).map(Arg::Particle)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ impl ArgumentConsumer for ResourceLocationArgumentConsumer {
|
||||
) -> ConsumeResult<'a> {
|
||||
let identifier = args.pop().and_then(|arg| Identifier::parse(arg.value).ok());
|
||||
|
||||
Box::pin(async move { identifier.map(Arg::ResourceLocation) })
|
||||
identifier.map(Arg::ResourceLocation)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,26 +45,19 @@ impl GetClientSideArgParser for RotationArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for RotationArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let yaw_str_opt = args.pop().map(|arg| arg.value);
|
||||
let pitch_str_opt = args.pop().map(|arg| arg.value);
|
||||
let yaw_str = args.pop()?.value;
|
||||
let pitch_str = args.pop()?.value;
|
||||
|
||||
let (Some(yaw_str), Some(pitch_str)) = (yaw_str_opt, pitch_str_opt) else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let (yaw, yaw_rel) = parse_rotation_component(yaw_str)?;
|
||||
let (pitch, pitch_rel) = parse_rotation_component(pitch_str)?;
|
||||
|
||||
let result: Option<Arg<'a>> =
|
||||
parse_rotation_component(yaw_str).and_then(|(yaw, yaw_rel)| {
|
||||
parse_rotation_component(pitch_str)
|
||||
.map(|(pitch, pitch_rel)| Arg::Rotation(yaw, yaw_rel, pitch, pitch_rel))
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
Some(Arg::Rotation(yaw, yaw_rel, pitch, pitch_rel))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,15 +29,13 @@ impl GetClientSideArgParser for SimpleArgConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for SimpleArgConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
Box::pin(async move { s_opt.map(Arg::Simple) })
|
||||
args.pop().map(|arg| Arg::Simple(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,18 +27,13 @@ impl ArgumentConsumer for SlotArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let slot = args.pop().map(|arg| arg.value);
|
||||
match slot {
|
||||
Some(s) => Box::pin(async move {
|
||||
if let Some(range) = get_slot_range(s)
|
||||
&& range.len() == 1
|
||||
{
|
||||
return Some(Arg::Slot(range[0], s.to_string()));
|
||||
}
|
||||
None
|
||||
}),
|
||||
None => Box::pin(async move { None }),
|
||||
let s = args.pop()?.value;
|
||||
if let Some(range) = get_slot_range(s)
|
||||
&& range.len() == 1
|
||||
{
|
||||
return Some(Arg::Slot(range[0], s.to_string()));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,16 +73,11 @@ impl ArgumentConsumer for SlotsArgumentConsumer {
|
||||
_server: &'a Server,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let slots = args.pop().map(|arg| arg.value);
|
||||
match slots {
|
||||
Some(s) => Box::pin(async move {
|
||||
if let Some(range) = get_slot_range(s) {
|
||||
return Some(Arg::Slots(range, s.to_string()));
|
||||
}
|
||||
None
|
||||
}),
|
||||
None => Box::pin(async move { None }),
|
||||
let s = args.pop()?.value;
|
||||
if let Some(range) = get_slot_range(s) {
|
||||
return Some(Arg::Slots(range, s.to_string()));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,15 +28,13 @@ impl GetClientSideArgParser for SoundArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for SoundArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
Box::pin(async move { s_opt.map(Arg::Block) })
|
||||
args.pop().map(|arg| Arg::Block(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,15 +25,15 @@ impl GetClientSideArgParser for SoundCategoryArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for SoundCategoryArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt.and_then(|s| {
|
||||
s_opt.and_then(|s| {
|
||||
let category = match s.to_lowercase().as_str() {
|
||||
"master" => Some(SoundCategory::Master),
|
||||
"music" => Some(SoundCategory::Music),
|
||||
@@ -50,28 +50,19 @@ impl ArgumentConsumer for SoundCategoryArgumentConsumer {
|
||||
};
|
||||
|
||||
category.map(Arg::SoundCategory)
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
})
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
_input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
Box::pin(async move {
|
||||
let categories = [
|
||||
"master", "music", "record", "weather", "block", "hostile", "neutral", "player",
|
||||
"ambient", "voice",
|
||||
];
|
||||
let suggestions: Vec<CommandSuggestion> = categories
|
||||
.iter()
|
||||
.map(|cat| CommandSuggestion::new((*cat).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
})
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||
let categories = [
|
||||
"master", "music", "record", "weather", "block", "hostile", "neutral", "player",
|
||||
"ambient", "voice",
|
||||
];
|
||||
let suggestions: Vec<CommandSuggestion> = categories
|
||||
.iter()
|
||||
.map(|cat| CommandSuggestion::new((*cat).to_string(), None))
|
||||
.collect();
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,15 +28,13 @@ impl GetClientSideArgParser for SummonableEntitiesArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for SummonableEntitiesArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
Box::pin(async move { s_opt.map(Arg::Block) })
|
||||
args.pop().map(|arg| Arg::Block(arg.value))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,17 +50,15 @@ impl GetClientSideArgParser for TeamColorArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for TeamColorArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result = s_opt.and_then(|s| NamedColor::try_from(s).ok().map(Arg::TeamColor));
|
||||
|
||||
Box::pin(async move { result })
|
||||
s_opt.and_then(|s| NamedColor::try_from(s).ok().map(Arg::TeamColor))
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -70,32 +68,25 @@ impl ArgumentConsumer for TeamColorArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let result = NamedColor::try_from(raw_arg.value)
|
||||
NamedColor::try_from(raw_arg.value)
|
||||
.map(|color| Some(Arg::TeamColor(color)))
|
||||
.map_err(|()| {
|
||||
INVALID_COLOR_ERROR_TYPE.create_without_context_args_slice(&[TextComponent::text(
|
||||
raw_arg.value.to_string(),
|
||||
)])
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
})
|
||||
}
|
||||
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_sender: &CommandSender,
|
||||
_server: &'a Server,
|
||||
input: &'a str,
|
||||
) -> SuggestResult<'a> {
|
||||
fn suggest(&self, _sender: &CommandSender, _server: &Server, input: &str) -> SuggestResult {
|
||||
let suggestions: Vec<CommandSuggestion> = TEAM_COLORS
|
||||
.iter()
|
||||
.filter(|color| color.starts_with(input))
|
||||
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
||||
.collect();
|
||||
Box::pin(async move { Ok(Some(suggestions)) })
|
||||
Ok(Some(suggestions))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,22 +20,18 @@ impl GetClientSideArgParser for TextComponentArgConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for TextComponentArgConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let Some(s) = s_opt else {
|
||||
return Box::pin(async move { None });
|
||||
};
|
||||
let s = args.pop().map(|arg| arg.value)?;
|
||||
|
||||
let text_component_opt = parse_text_component(s);
|
||||
|
||||
// TODO: Allow identifiers (starting with alphabetic or _, then alphanumeric+-_.) as display names
|
||||
let final_arg: Option<Arg<'a>> = text_component_opt.map_or_else(
|
||||
text_component_opt.map_or_else(
|
||||
|| {
|
||||
(s.starts_with('"') && s.ends_with('"')).then(|| {
|
||||
let s_owned = s.replace('"', "");
|
||||
@@ -43,9 +39,7 @@ impl ArgumentConsumer for TextComponentArgConsumer {
|
||||
})
|
||||
},
|
||||
|text_component| Some(Arg::TextComponent(text_component)),
|
||||
);
|
||||
|
||||
Box::pin(async move { final_arg })
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,21 +65,19 @@ impl GetClientSideArgParser for TimeArgumentConsumer {
|
||||
}
|
||||
|
||||
impl ArgumentConsumer for TimeArgumentConsumer {
|
||||
fn consume<'a, 'b>(
|
||||
fn consume<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a Server,
|
||||
args: &'b mut RawArgs<'a>,
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResult<'a> {
|
||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||
|
||||
let result: Option<Arg<'a>> = s_opt.and_then(|s| {
|
||||
s_opt.and_then(|s| {
|
||||
let mut reader = StringReader::new(s);
|
||||
let parser = TimeArgumentType::new(self.min);
|
||||
parser.parse(&mut reader).ok().map(Arg::Time)
|
||||
});
|
||||
|
||||
Box::pin(async move { result })
|
||||
})
|
||||
}
|
||||
|
||||
fn consume_with_syntax<'a>(
|
||||
@@ -89,17 +87,15 @@ impl ArgumentConsumer for TimeArgumentConsumer {
|
||||
args: &mut RawArgs<'a>,
|
||||
) -> ConsumeResultWithSyntax<'a> {
|
||||
let Some(raw_arg) = args.pop() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let mut reader = StringReader::new(raw_arg.value);
|
||||
let parser = TimeArgumentType::new(self.min);
|
||||
let result = parser
|
||||
parser
|
||||
.parse(&mut reader)
|
||||
.map(|ticks| Some(Arg::Time(ticks)))
|
||||
.map_err(|error| map_local_syntax_error(error, raw_arg));
|
||||
|
||||
Box::pin(async move { result })
|
||||
.map_err(|error| map_local_syntax_error(error, raw_arg))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,9 @@ use crate::command::{
|
||||
errors::command_syntax_error::CommandSyntaxError, string_reader::StringReader,
|
||||
};
|
||||
use std::any::Any;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub type JavaClientArgumentType = pumpkin_protocol::java::client::play::ArgumentType;
|
||||
pub type ParseWithSourceAnyResult<'a> = Pin<
|
||||
Box<dyn Future<Output = Result<Box<dyn Any + Send + Sync>, CommandSyntaxError>> + Send + 'a>,
|
||||
>;
|
||||
pub type ParseWithSourceAnyResult = Result<Box<dyn Any + Send + Sync>, CommandSyntaxError>;
|
||||
|
||||
/// Represents an argument type that parses a particular type `Item`.
|
||||
pub trait ArgumentType: Send + Sync {
|
||||
@@ -32,27 +29,27 @@ pub trait ArgumentType: Send + Sync {
|
||||
///
|
||||
/// Errors should be propagated using the `?` operator, which will
|
||||
/// replicate Brigadier's behavior of exceptions.
|
||||
fn parse_with_source<'a>(
|
||||
&'a self,
|
||||
reader: &'a mut StringReader,
|
||||
_source: &'a CommandSource,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self::Item, CommandSyntaxError>> + Send + 'a>> {
|
||||
Box::pin(async move { self.parse(reader) })
|
||||
fn parse_with_source(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
_source: &CommandSource,
|
||||
) -> Result<Self::Item, CommandSyntaxError> {
|
||||
self.parse(reader)
|
||||
}
|
||||
|
||||
/// Provides a list of suggestions from this argument type.
|
||||
#[must_use]
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
_builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { Suggestions::empty() })
|
||||
) -> Suggestions {
|
||||
Suggestions::empty()
|
||||
}
|
||||
|
||||
/// Returns the Java client-side parser used for this argument type.
|
||||
#[must_use]
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType;
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType;
|
||||
|
||||
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
||||
/// is returned.
|
||||
@@ -94,23 +91,23 @@ pub trait AnyArgumentType: Sealed + Send + Sync {
|
||||
///
|
||||
/// Errors should be propagated using the `?` operator, which will
|
||||
/// replicate Brigadier's behavior of exceptions.
|
||||
fn parse_with_source<'a>(
|
||||
&'a self,
|
||||
reader: &'a mut StringReader,
|
||||
source: &'a CommandSource,
|
||||
) -> ParseWithSourceAnyResult<'a>;
|
||||
fn parse_with_source(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
source: &CommandSource,
|
||||
) -> ParseWithSourceAnyResult;
|
||||
|
||||
/// Provides a list of suggestions from this argument type.
|
||||
#[must_use]
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>>;
|
||||
) -> Suggestions;
|
||||
|
||||
/// Returns the Java client-side parser used for this argument type.
|
||||
#[must_use]
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType;
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType;
|
||||
|
||||
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
||||
/// is returned.
|
||||
@@ -145,31 +142,29 @@ impl<U: ArgumentType<Item = T> + 'static, T: Send + Sync + 'static> AnyArgumentT
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_with_source<'a>(
|
||||
&'a self,
|
||||
reader: &'a mut StringReader,
|
||||
source: &'a CommandSource,
|
||||
) -> ParseWithSourceAnyResult<'a> {
|
||||
Box::pin(async move {
|
||||
match self.parse_with_source(reader, source).await {
|
||||
Ok(value) => {
|
||||
let value: Box<dyn Any + Send + Sync> = Box::new(value);
|
||||
Ok(value)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
fn parse_with_source(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
source: &CommandSource,
|
||||
) -> ParseWithSourceAnyResult {
|
||||
match self.parse_with_source(reader, source) {
|
||||
Ok(value) => {
|
||||
let value: Box<dyn Any + Send + Sync> = Box::new(value);
|
||||
Ok(value)
|
||||
}
|
||||
})
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
) -> Suggestions {
|
||||
self.list_suggestions(context, builder)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
self.client_side_parser()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::{
|
||||
argument_types::FromStringReader,
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
@@ -46,16 +44,14 @@ impl ArgumentType for AttributeArgumentType {
|
||||
}
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest_iter(Attributes::ALL.iter().map(|a| a.name))
|
||||
.build()
|
||||
})
|
||||
) -> Suggestions {
|
||||
builder
|
||||
.filter_and_suggest_iter(Attributes::ALL.iter().map(|a| a.name))
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::{
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
context::command_context::CommandContext,
|
||||
@@ -46,12 +44,12 @@ impl ArgumentType for BlockArgumentType {
|
||||
JavaClientArgumentType::BlockState
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { builder.build() })
|
||||
) -> Suggestions {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::command::argument_types::coordinates::Coordinates;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
@@ -56,23 +54,21 @@ impl ArgumentType for BlockPosArgumentType {
|
||||
examples!("1 3 5", "-3 ~24 ~-1", "80 80 80", "^ ^9 ^56")
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let remainder = builder.remaining();
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_3d_coordinates(suggested_coordinates, |value| {
|
||||
self.parse(&mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
builder.suggest_3d_coordinates(suggested_coordinates, |value| {
|
||||
self.parse(&mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::position::{BlockPos, ColumnPos};
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
@@ -48,23 +46,21 @@ impl ArgumentType for ColumnPosArgumentType {
|
||||
}
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let remainder = builder.remaining();
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_2d_coordinates(suggested_coordinates, |value| {
|
||||
self.parse(&mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
builder.suggest_2d_coordinates(suggested_coordinates, |value| {
|
||||
self.parse(&mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::command::argument_types::coordinates::Coordinates;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
@@ -60,23 +58,21 @@ impl ArgumentType for Vec3ArgumentType {
|
||||
examples!("1 1 1", "3 ~34 ~-2", "40 50 60", "^ ^4 ^3")
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let remainder = builder.remaining();
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggestioned_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
let suggestioned_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_3d_coordinates(suggestioned_coordinates, |value| {
|
||||
self.parse(&mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
builder.suggest_3d_coordinates(suggestioned_coordinates, |value| {
|
||||
self.parse(&mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::entity::player::Player;
|
||||
use pumpkin_data::translation;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A [`CommandErrorType`] to tell that no entities could be found.
|
||||
@@ -87,17 +86,12 @@ impl ArgumentType for EntityArgumentType {
|
||||
self.parse_with_allow_selectors(reader, true)
|
||||
}
|
||||
|
||||
fn parse_with_source<'a>(
|
||||
&'a self,
|
||||
reader: &'a mut StringReader,
|
||||
source: &'a CommandSource,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self::Item, CommandSyntaxError>> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
self.parse_with_allow_selectors(
|
||||
reader,
|
||||
source.has_permission(ENTITY_SELECTOR_PERMISSION).await,
|
||||
)
|
||||
})
|
||||
fn parse_with_source(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
source: &CommandSource,
|
||||
) -> Result<Self::Item, CommandSyntaxError> {
|
||||
self.parse_with_allow_selectors(reader, source.has_permission(ENTITY_SELECTOR_PERMISSION))
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
@@ -118,12 +112,12 @@ impl ArgumentType for EntityArgumentType {
|
||||
)
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
EntitySelectorParserSuggestions::list_suggestions(context, builder)
|
||||
) -> Suggestions {
|
||||
EntitySelectorParserSuggestions::list_suggestions(context, &builder)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,22 +150,21 @@ impl EntityArgumentType {
|
||||
}
|
||||
|
||||
/// Tries to get a single entity from a parsed argument of the provided [`CommandContext`].
|
||||
pub async fn get_entity(
|
||||
pub fn get_entity(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Arc<dyn EntityBase>, CommandSyntaxError> {
|
||||
context
|
||||
.get_argument::<EntitySelector>(name)?
|
||||
.find_single_entity(context.source.as_ref())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Tries to get at least 1 entity from a parsed argument of the provided [`CommandContext`].
|
||||
pub async fn get_entities(
|
||||
pub fn get_entities(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
||||
let entities = Self::get_optional_entities(context, name).await?;
|
||||
let entities = Self::get_optional_entities(context, name)?;
|
||||
if entities.is_empty() {
|
||||
Err(NO_ENTITIES_ERROR_TYPE.create_without_context())
|
||||
} else {
|
||||
@@ -180,33 +173,31 @@ impl EntityArgumentType {
|
||||
}
|
||||
|
||||
/// Tries to get any number of entities from a parsed argument of the provided [`CommandContext`].
|
||||
pub async fn get_optional_entities(
|
||||
pub fn get_optional_entities(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
||||
context
|
||||
.get_argument::<EntitySelector>(name)?
|
||||
.find_entities(context.source.as_ref())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Tries to get a single player from a parsed argument of the provided [`CommandContext`].
|
||||
pub async fn get_player(
|
||||
pub fn get_player(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Arc<Player>, CommandSyntaxError> {
|
||||
context
|
||||
.get_argument::<EntitySelector>(name)?
|
||||
.find_single_player(context.source.as_ref())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Tries to get at least 1 player from a parsed argument of the provided [`CommandContext`].
|
||||
pub async fn get_players(
|
||||
pub fn get_players(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
||||
let players = Self::get_optional_players(context, name).await?;
|
||||
let players = Self::get_optional_players(context, name)?;
|
||||
if players.is_empty() {
|
||||
Err(NO_PLAYERS_ERROR_TYPE.create_without_context())
|
||||
} else {
|
||||
@@ -215,13 +206,12 @@ impl EntityArgumentType {
|
||||
}
|
||||
|
||||
/// Tries to get any number of players from a parsed argument of the provided [`CommandContext`].
|
||||
pub async fn get_optional_players(
|
||||
pub fn get_optional_players(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
||||
context
|
||||
.get_argument::<EntitySelector>(name)?
|
||||
.find_players(context.source.as_ref())
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ use crate::entity::Entity;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ANCHOR_INVALID,
|
||||
@@ -37,12 +36,12 @@ impl ArgumentType for EntityAnchorArgumentType {
|
||||
JavaClientArgumentType::EntityAnchor
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { builder.filter_and_suggest(&["eyes", "feet"]).build() })
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&["eyes", "feet"]).build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -62,11 +62,8 @@ pub struct EntitySelector {
|
||||
impl EntitySelector {
|
||||
/// Returns an [`Err`] if a [`CommandSource`] does not have permission to use
|
||||
/// this entity selector.
|
||||
pub async fn check_permissions(
|
||||
&self,
|
||||
source: &CommandSource,
|
||||
) -> Result<(), CommandSyntaxError> {
|
||||
if self.uses_selector_variable && !source.has_permission(ENTITY_SELECTOR_PERMISSION).await {
|
||||
pub fn check_permissions(&self, source: &CommandSource) -> Result<(), CommandSyntaxError> {
|
||||
if self.uses_selector_variable && !source.has_permission(ENTITY_SELECTOR_PERMISSION) {
|
||||
Err(SELECTORS_NOT_ALLOWED_ERROR_TYPE.create_without_context())
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -82,11 +79,11 @@ impl EntitySelector {
|
||||
}
|
||||
|
||||
/// Tries to find a single entity represented by this selector.
|
||||
pub async fn find_single_entity(
|
||||
pub fn find_single_entity(
|
||||
&self,
|
||||
source: &CommandSource,
|
||||
) -> Result<Arc<dyn EntityBase>, CommandSyntaxError> {
|
||||
let list = self.find_entities(source).await?;
|
||||
let list = self.find_entities(source)?;
|
||||
match list.as_slice() {
|
||||
[] => Err(entity::NO_ENTITIES_ERROR_TYPE.create_without_context()),
|
||||
[entity] => Ok(entity.clone()),
|
||||
@@ -95,14 +92,13 @@ impl EntitySelector {
|
||||
}
|
||||
|
||||
/// Tries to find any entities represented by this selector. If none are found, an empty `Vec` will still be returned.
|
||||
pub async fn find_entities(
|
||||
pub fn find_entities(
|
||||
&self,
|
||||
source: &CommandSource,
|
||||
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
||||
self.check_permissions(source).await?;
|
||||
self.check_permissions(source)?;
|
||||
if !self.includes_entities {
|
||||
self.find_players(source)
|
||||
.await
|
||||
.map(|v| v.into_iter().map(|p| p as Arc<dyn EntityBase>).collect())
|
||||
} else if let Some(name) = self.player_name.as_ref() {
|
||||
// Try to get the player by name.
|
||||
@@ -160,11 +156,11 @@ impl EntitySelector {
|
||||
}
|
||||
|
||||
/// Tries to find a single player represented by this selector.
|
||||
pub async fn find_single_player(
|
||||
pub fn find_single_player(
|
||||
&self,
|
||||
source: &CommandSource,
|
||||
) -> Result<Arc<Player>, CommandSyntaxError> {
|
||||
let mut list = self.find_players(source).await?;
|
||||
let mut list = self.find_players(source)?;
|
||||
if list.len() == 1 {
|
||||
list.pop()
|
||||
.ok_or_else(|| entity::NO_PLAYERS_ERROR_TYPE.create_without_context())
|
||||
@@ -174,11 +170,11 @@ impl EntitySelector {
|
||||
}
|
||||
|
||||
/// Tries to find any players represented by this selector.
|
||||
pub async fn find_players(
|
||||
pub fn find_players(
|
||||
&self,
|
||||
source: &CommandSource,
|
||||
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
||||
self.check_permissions(source).await?;
|
||||
self.check_permissions(source)?;
|
||||
if let Some(name) = self.player_name.as_ref() {
|
||||
// Try to get the player by name.
|
||||
let player = source
|
||||
@@ -529,7 +525,10 @@ impl EntitySelectorPredicate {
|
||||
Self::Team(expected_team, invert) => {
|
||||
let actual_name = entity_actual_name(entity);
|
||||
let world = entity.get_entity().world.load();
|
||||
let scoreboard = world.scoreboard.blocking_lock();
|
||||
let scoreboard = world
|
||||
.scoreboard
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let has_team = scoreboard.get_teams().iter().any(|(name, team)| {
|
||||
name == expected_team && team.players.contains(&actual_name)
|
||||
});
|
||||
@@ -538,7 +537,10 @@ impl EntitySelectorPredicate {
|
||||
Self::Scores(scores_map) => {
|
||||
let actual_name = entity_actual_name(entity);
|
||||
let world = entity.get_entity().world.load();
|
||||
let scoreboard = world.scoreboard.blocking_lock();
|
||||
let scoreboard = world
|
||||
.scoreboard
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let entity_scores = scoreboard.get_scores().get(&actual_name);
|
||||
for (objective, bounds) in scores_map {
|
||||
let score_val = entity_scores
|
||||
|
||||
@@ -20,7 +20,6 @@ use pumpkin_util::math::bounds::{DoubleBounds, FloatDegreeBounds, IntBounds};
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::pin::Pin;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const INVALID_NAME_OR_UUID_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
@@ -593,31 +592,25 @@ impl EntitySelectorParserSuggestions {
|
||||
builder
|
||||
}
|
||||
|
||||
pub fn list_suggestions<'a>(
|
||||
context: &'a CommandContext<'_>,
|
||||
suggestions_builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let mut reader = StringReader::new(suggestions_builder.input.clone());
|
||||
reader.set_cursor(suggestions_builder.start);
|
||||
let mut parser = EntitySelectorParser::new(
|
||||
&mut reader,
|
||||
context
|
||||
.source
|
||||
.has_permission(ENTITY_SELECTOR_PERMISSION)
|
||||
.await,
|
||||
);
|
||||
pub fn list_suggestions(
|
||||
context: &CommandContext<'_>,
|
||||
suggestions_builder: &SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let mut reader = StringReader::new(suggestions_builder.input.clone());
|
||||
reader.set_cursor(suggestions_builder.start);
|
||||
let mut parser = EntitySelectorParser::new(
|
||||
&mut reader,
|
||||
context.source.has_permission(ENTITY_SELECTOR_PERMISSION),
|
||||
);
|
||||
|
||||
let _ = parser.parse();
|
||||
let _ = parser.parse();
|
||||
|
||||
parser.fill_suggestions(&suggestions_builder, |mut suggestions| {
|
||||
for player in context.server().get_all_players() {
|
||||
suggestions =
|
||||
suggestions.filter_and_suggest_one(player.gameprofile.name.clone());
|
||||
}
|
||||
// ONLY FOR EntityArgumentType: This is server-side, so no other entity will show up.
|
||||
suggestions
|
||||
})
|
||||
parser.fill_suggestions(suggestions_builder, |mut suggestions| {
|
||||
for player in context.server().get_all_players() {
|
||||
suggestions = suggestions.filter_and_suggest_one(player.gameprofile.name.clone());
|
||||
}
|
||||
// ONLY FOR EntityArgumentType: This is server-side, so no other entity will show up.
|
||||
suggestions
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ use crate::net::{GameProfile, offline_uuid};
|
||||
use crate::server::Server;
|
||||
use arc_swap::ArcSwap;
|
||||
use pumpkin_data::translation;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -49,24 +48,26 @@ impl GameProfileResult {
|
||||
/// - `server.data.whitelist_config`
|
||||
///
|
||||
/// Instead, call this method *before* using `write()`/`read()` on a lock.
|
||||
pub async fn resolve(
|
||||
&self,
|
||||
source: &CommandSource,
|
||||
) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
||||
pub fn resolve(&self, source: &CommandSource) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
||||
let players = match self {
|
||||
Self::Selector(selector) => selector.find_players(source).await,
|
||||
Self::Selector(selector) => selector.find_players(source),
|
||||
Self::Name(name) => {
|
||||
let server = source.server();
|
||||
if let Some(player) = server.get_player_by_name(name) {
|
||||
return Ok(vec![player.gameprofile.clone()]);
|
||||
}
|
||||
|
||||
let cached_entry = server.data.user_cache.write().await.get_by_name(name);
|
||||
let cached_entry = server
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get_by_name(name);
|
||||
if let Some(entry) = cached_entry {
|
||||
return Ok(vec![Self::profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||
}
|
||||
|
||||
if let Some(profile) = Self::resolve_known_profile_by_name(server, name).await {
|
||||
if let Some(profile) = Self::resolve_known_profile_by_name(server, name) {
|
||||
return Ok(vec![profile]);
|
||||
}
|
||||
|
||||
@@ -80,7 +81,7 @@ impl GameProfileResult {
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.upsert(uuid, resolved_name.clone());
|
||||
Ok(vec![Self::profile_from_uuid_name(uuid, resolved_name)])
|
||||
}
|
||||
@@ -92,7 +93,7 @@ impl GameProfileResult {
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.upsert(profile.id, profile.name.clone());
|
||||
return Ok(vec![profile]);
|
||||
}
|
||||
@@ -106,12 +107,17 @@ impl GameProfileResult {
|
||||
return Ok(vec![player.gameprofile.clone()]);
|
||||
}
|
||||
|
||||
let cached_entry = server.data.user_cache.write().await.get_by_uuid(*uuid);
|
||||
let cached_entry = server
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get_by_uuid(*uuid);
|
||||
if let Some(entry) = cached_entry {
|
||||
return Ok(vec![Self::profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||
}
|
||||
|
||||
if let Some(profile) = Self::resolve_known_profile_by_uuid(server, *uuid).await {
|
||||
if let Some(profile) = Self::resolve_known_profile_by_uuid(server, *uuid) {
|
||||
return Ok(vec![profile]);
|
||||
}
|
||||
|
||||
@@ -122,13 +128,21 @@ impl GameProfileResult {
|
||||
Ok(players.iter().map(|p| &p.gameprofile).cloned().collect())
|
||||
}
|
||||
|
||||
async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
||||
let ops = server.data.operator_config.read().await;
|
||||
fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
||||
let ops = server
|
||||
.data
|
||||
.operator_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(op) = ops.ops.iter().find(|op| op.name.eq_ignore_ascii_case(name)) {
|
||||
return Some(Self::profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||
}
|
||||
|
||||
let banned_players = server.data.banned_player_list.read().await;
|
||||
let banned_players = server
|
||||
.data
|
||||
.banned_player_list
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = banned_players
|
||||
.banned_players
|
||||
.iter()
|
||||
@@ -137,7 +151,11 @@ impl GameProfileResult {
|
||||
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||
}
|
||||
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
let whitelist = server
|
||||
.data
|
||||
.whitelist_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = whitelist
|
||||
.whitelist
|
||||
.iter()
|
||||
@@ -149,13 +167,21 @@ impl GameProfileResult {
|
||||
None
|
||||
}
|
||||
|
||||
async fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
||||
let ops = server.data.operator_config.read().await;
|
||||
fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
||||
let ops = server
|
||||
.data
|
||||
.operator_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(op) = ops.ops.iter().find(|op| op.uuid == uuid) {
|
||||
return Some(Self::profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||
}
|
||||
|
||||
let banned_players = server.data.banned_player_list.read().await;
|
||||
let banned_players = server
|
||||
.data
|
||||
.banned_player_list
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = banned_players
|
||||
.banned_players
|
||||
.iter()
|
||||
@@ -164,7 +190,11 @@ impl GameProfileResult {
|
||||
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||
}
|
||||
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
let whitelist = server
|
||||
.data
|
||||
.whitelist_config
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(entry) = whitelist.whitelist.iter().find(|entry| entry.uuid == uuid) {
|
||||
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||
}
|
||||
@@ -202,12 +232,12 @@ impl ArgumentType for GameProfileArgumentType {
|
||||
JavaClientArgumentType::GameProfile
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
EntitySelectorParserSuggestions::list_suggestions(context, builder)
|
||||
) -> Suggestions {
|
||||
EntitySelectorParserSuggestions::list_suggestions(context, &builder)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
@@ -255,13 +285,12 @@ impl GameProfileArgumentType {
|
||||
/// - `server.data.whitelist_config`
|
||||
///
|
||||
/// Instead, call this function *before* using `write()`/`read()` on a lock.
|
||||
pub async fn get(
|
||||
pub fn get(
|
||||
context: &CommandContext<'_>,
|
||||
name: &str,
|
||||
) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
||||
context
|
||||
.get_argument::<GameProfileResult>(name)?
|
||||
.resolve(context.source.as_ref())
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::GameMode;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::pin::Pin;
|
||||
use std::str::FromStr;
|
||||
|
||||
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
@@ -30,17 +29,15 @@ impl ArgumentType for GameModeArgumentType {
|
||||
JavaClientArgumentType::Gamemode
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
for gamemode in GameMode::VALUES {
|
||||
builder = builder.filter_and_suggest_one(gamemode.name());
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
) -> Suggestions {
|
||||
for gamemode in GameMode::VALUES {
|
||||
builder = builder.filter_and_suggest_one(gamemode.name());
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -7,7 +7,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation::java::ARGUMENT_HEXCOLOR_INVALID;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::RGBColor;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub const INVALID_HEX_ERROR_TYPE: CommandErrorType<1> =
|
||||
CommandErrorType::new(ARGUMENT_HEXCOLOR_INVALID, ARGUMENT_HEXCOLOR_INVALID);
|
||||
@@ -38,12 +37,12 @@ impl ArgumentType for HexColorArgumentType {
|
||||
JavaClientArgumentType::HexColor
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { builder.filter_and_suggest(&["F00", "FF0000"]).build() })
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&["F00", "FF0000"]).build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -26,12 +26,12 @@ impl ArgumentType for NbtTagArgumentType {
|
||||
JavaClientArgumentType::NbtTag
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> std::pin::Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { SnbtParser::parse_for_suggestions(builder) })
|
||||
) -> Suggestions {
|
||||
SnbtParser::parse_for_suggestions(builder)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::command::{
|
||||
string_reader::StringReader,
|
||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||
};
|
||||
use std::pin::Pin;
|
||||
|
||||
/// Represents an argument type parsing a scoreboard objective name.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -23,18 +22,20 @@ impl ArgumentType for ObjectiveArgumentType {
|
||||
JavaClientArgumentType::Objective
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let scoreboard = context.world().scoreboard.lock().await;
|
||||
for objective_name in scoreboard.get_objectives().keys() {
|
||||
builder = builder.filter_and_suggest_one(objective_name.as_str());
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
) -> Suggestions {
|
||||
let scoreboard = context
|
||||
.world()
|
||||
.scoreboard
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for objective_name in scoreboard.get_objectives().keys() {
|
||||
builder = builder.filter_and_suggest_one(objective_name.as_str());
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
@@ -19,17 +17,15 @@ impl ArgumentType for PlacedFeatureNameArgumentType {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::feature::placed_features::all_placed_feature_names();
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().copied())
|
||||
.build()
|
||||
})
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().copied())
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::argument_types::FromStringReader;
|
||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
@@ -18,17 +16,15 @@ impl ArgumentType for PoolNameArgumentType {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::structure::template::all_pool_names();
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||
.build()
|
||||
})
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
|
||||
@@ -12,7 +12,6 @@ use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::any::Any;
|
||||
use std::iter::Iterator;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub static ENTITY_TYPE_REGISTRY: &Identifier = &Identifier::vanilla_static("entity_type");
|
||||
static ERROR_UNKNOWN_RESOURCE: CommandErrorType<2> = CommandErrorType::new(
|
||||
@@ -59,18 +58,16 @@ impl ArgumentType for ResourceArgument {
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
suggestions_builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send>> {
|
||||
) -> Suggestions {
|
||||
if self.0 == ENTITY_TYPE_REGISTRY {
|
||||
Box::pin(async move {
|
||||
let entity_types = EntityType::ALL
|
||||
.iter()
|
||||
.map(|entity_type| format!("minecraft:{}", entity_type.resource_name));
|
||||
suggestions_builder
|
||||
.filter_and_suggest_iter(entity_types)
|
||||
.build()
|
||||
})
|
||||
let entity_types = EntityType::ALL
|
||||
.iter()
|
||||
.map(|entity_type| format!("minecraft:{}", entity_type.resource_name));
|
||||
suggestions_builder
|
||||
.filter_and_suggest_iter(entity_types)
|
||||
.build()
|
||||
} else {
|
||||
Box::pin(async move { Suggestions::empty() })
|
||||
Suggestions::empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ use pumpkin_data::{Advancement, translation};
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::resource::ResourceKey;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::pin::Pin;
|
||||
use std::string::ToString;
|
||||
|
||||
pub static ADVANCEMENT_REGISTRY: &Identifier = &Identifier::vanilla_static("advancement");
|
||||
@@ -55,23 +54,19 @@ impl ArgumentType for ResourceKeyArgument {
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
suggestions_builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send>> {
|
||||
) -> Suggestions {
|
||||
if self.0 == ADVANCEMENT_REGISTRY {
|
||||
let advancements = context.server().advancement_manager.get_advancements();
|
||||
Box::pin(async move {
|
||||
suggestions_builder
|
||||
.filter_and_suggest_iter(advancements.iter().map(ToString::to_string))
|
||||
.build()
|
||||
})
|
||||
suggestions_builder
|
||||
.filter_and_suggest_iter(advancements.iter().map(ToString::to_string))
|
||||
.build()
|
||||
} else if self.0 == BIOME_REGISTRY {
|
||||
Box::pin(async move {
|
||||
let biomes = pumpkin_data::biome::Biome::ALL
|
||||
.iter()
|
||||
.map(|biome| format!("minecraft:{}", biome.registry_id));
|
||||
suggestions_builder.filter_and_suggest_iter(biomes).build()
|
||||
})
|
||||
let biomes = pumpkin_data::biome::Biome::ALL
|
||||
.iter()
|
||||
.map(|biome| format!("minecraft:{}", biome.registry_id));
|
||||
suggestions_builder.filter_and_suggest_iter(biomes).build()
|
||||
} else {
|
||||
Box::pin(async move { Suggestions::empty() })
|
||||
Suggestions::empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::pin::Pin;
|
||||
|
||||
use pumpkin_data::structures::StructureSet;
|
||||
use pumpkin_data::tag::{self, RegistryKey};
|
||||
@@ -121,12 +120,12 @@ impl ArgumentType for ResourceOrTagKeyArgument {
|
||||
ResourceOrTag::from_string_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { suggest_for_registry(&self.0, builder) })
|
||||
) -> Suggestions {
|
||||
suggest_for_registry(&self.0, builder)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
@@ -190,12 +189,12 @@ impl ArgumentType for ResourceOrTagArgument {
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { suggest_for_registry(&self.0, builder) })
|
||||
) -> Suggestions {
|
||||
suggest_for_registry(&self.0, builder)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
|
||||
@@ -9,7 +9,6 @@ use pumpkin_data::slot_ranges::{
|
||||
};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub const UNKNOWN_SLOT_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SLOT_UNKNOWN,
|
||||
@@ -45,16 +44,14 @@ impl ArgumentType for SlotArgumentType {
|
||||
JavaClientArgumentType::ItemSlot
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest(&SLOT_RANGE_SINGLE_SLOT_NAMES)
|
||||
.build()
|
||||
})
|
||||
) -> Suggestions {
|
||||
builder
|
||||
.filter_and_suggest(&SLOT_RANGE_SINGLE_SLOT_NAMES)
|
||||
.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
@@ -84,12 +81,12 @@ impl ArgumentType for SlotsArgumentType {
|
||||
JavaClientArgumentType::ItemSlots
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move { builder.filter_and_suggest(&SLOT_RANGE_ALL_NAMES).build() })
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&SLOT_RANGE_ALL_NAMES).build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::argument_types::FromStringReader;
|
||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
@@ -18,17 +16,15 @@ impl ArgumentType for StructureNameArgumentType {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::structure::template::all_structure_names();
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().copied())
|
||||
.build()
|
||||
})
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().copied())
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::command::{
|
||||
string_reader::StringReader,
|
||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||
};
|
||||
use std::pin::Pin;
|
||||
|
||||
/// Represents an argument type parsing a team name.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -23,18 +22,20 @@ impl ArgumentType for TeamArgumentType {
|
||||
JavaClientArgumentType::Team
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let scoreboard = context.world().scoreboard.lock().await;
|
||||
for team_name in scoreboard.get_teams().keys() {
|
||||
builder = builder.filter_and_suggest_one(team_name.as_str());
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
) -> Suggestions {
|
||||
let scoreboard = context
|
||||
.world()
|
||||
.scoreboard
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for team_name in scoreboard.get_teams().keys() {
|
||||
builder = builder.filter_and_suggest_one(team_name.as_str());
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -7,7 +7,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation::java::ARGUMENT_COLOR_INVALID;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::NamedColor;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub const INVALID_VALUE_ERROR_TYPE: CommandErrorType<1> =
|
||||
CommandErrorType::new(ARGUMENT_COLOR_INVALID, ARGUMENT_COLOR_INVALID);
|
||||
@@ -30,33 +29,31 @@ impl ArgumentType for TeamColorArgumentType {
|
||||
JavaClientArgumentType::Color
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest(&[
|
||||
"black",
|
||||
"dark_blue",
|
||||
"dark_green",
|
||||
"dark_aqua",
|
||||
"dark_red",
|
||||
"dark_purple",
|
||||
"gold",
|
||||
"gray",
|
||||
"dark_gray",
|
||||
"blue",
|
||||
"green",
|
||||
"aqua",
|
||||
"red",
|
||||
"light_purple",
|
||||
"yellow",
|
||||
"white",
|
||||
])
|
||||
.build()
|
||||
})
|
||||
) -> Suggestions {
|
||||
builder
|
||||
.filter_and_suggest(&[
|
||||
"black",
|
||||
"dark_blue",
|
||||
"dark_green",
|
||||
"dark_aqua",
|
||||
"dark_red",
|
||||
"dark_purple",
|
||||
"gold",
|
||||
"gray",
|
||||
"dark_gray",
|
||||
"blue",
|
||||
"green",
|
||||
"aqua",
|
||||
"red",
|
||||
"light_purple",
|
||||
"yellow",
|
||||
"white",
|
||||
])
|
||||
.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::command::argument_types::FromStringReader;
|
||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
@@ -19,17 +17,15 @@ impl ArgumentType for TemplateNameArgumentType {
|
||||
Ok(identifier.path().to_string())
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::structure::template::all_template_names();
|
||||
Box::pin(async move {
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||
.build()
|
||||
})
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
|
||||
@@ -6,7 +6,6 @@ use crate::command::string_reader::StringReader;
|
||||
use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub const INVALID_UNIT_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_TIME_INVALID_UNIT,
|
||||
@@ -73,21 +72,19 @@ impl ArgumentType for TimeArgumentType {
|
||||
JavaClientArgumentType::Time { min: self.min }
|
||||
}
|
||||
|
||||
fn list_suggestions<'a>(
|
||||
&'a self,
|
||||
_context: &'a CommandContext,
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
suggestions_builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let mut reader = StringReader::new(suggestions_builder.remaining());
|
||||
if reader.read_float().is_err() {
|
||||
suggestions_builder.build()
|
||||
} else {
|
||||
suggestions_builder
|
||||
.filter_and_suggest(&["t", "s", "d"])
|
||||
.build()
|
||||
}
|
||||
})
|
||||
) -> Suggestions {
|
||||
let mut reader = StringReader::new(suggestions_builder.remaining());
|
||||
if reader.read_float().is_err() {
|
||||
suggestions_builder.build()
|
||||
} else {
|
||||
suggestions_builder
|
||||
.filter_and_suggest(&["t", "s", "d"])
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
|
||||
@@ -21,7 +21,7 @@ use pumpkin_protocol::bedrock::client::available_commands::{
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub async fn send_c_commands_packet(
|
||||
pub fn send_c_commands_packet(
|
||||
player: &Arc<Player>,
|
||||
server: &Server,
|
||||
dispatcher: &CommandDispatcher,
|
||||
@@ -50,7 +50,7 @@ pub async fn send_c_commands_packet(
|
||||
continue;
|
||||
};
|
||||
|
||||
if !cmd_src.has_permission(server, permission.as_str()).await {
|
||||
if !cmd_src.has_permission(server, permission.as_str()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ pub async fn send_c_commands_packet(
|
||||
}
|
||||
|
||||
let packet = CCommands::new(proto_nodes.into(), VarInt(root_node_index as i32));
|
||||
player.send_client_packet(&packet).await;
|
||||
player.try_send_client_packet(&packet);
|
||||
}
|
||||
|
||||
fn resolve_node_id(node_id: NodeId, node_id_offset: usize, root_node_index: usize) -> usize {
|
||||
@@ -319,7 +319,7 @@ struct BuilderContext<'a> {
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub async fn send_bedrock_commands_packet(
|
||||
pub fn send_bedrock_commands_packet(
|
||||
player: &Arc<Player>,
|
||||
server: &Server,
|
||||
dispatcher: &CommandDispatcher,
|
||||
@@ -348,7 +348,7 @@ pub async fn send_bedrock_commands_packet(
|
||||
continue;
|
||||
};
|
||||
|
||||
if !cmd_src.has_permission(server, permission.as_str()).await {
|
||||
if !cmd_src.has_permission(server, permission.as_str()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -441,8 +441,10 @@ pub async fn send_bedrock_commands_packet(
|
||||
constraints: Vec::new(),
|
||||
};
|
||||
|
||||
if let crate::net::ClientPlatform::Bedrock(bedrock_client) = player.client.as_ref() {
|
||||
bedrock_client.send_packet(&packet).await;
|
||||
if let crate::net::ClientPlatform::Bedrock(bedrock_client) = player.client.as_ref()
|
||||
&& let Ok(data) = bedrock_client.serialize_packet(&packet)
|
||||
{
|
||||
bedrock_client.try_enqueue_packet(data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ use crate::command::suggestion::suggestions::SuggestionsBuilder;
|
||||
use crate::entity::EntityBase;
|
||||
use crate::entity::player::Player;
|
||||
use crate::entity::player::advancement::PlayerAdvancement;
|
||||
use futures::future::join_all;
|
||||
use pumpkin_data::advancement_data::AdvancementNode;
|
||||
use pumpkin_data::{ADVANCEMENT_TREE, Advancement, translation};
|
||||
use pumpkin_util::PermissionLvl;
|
||||
@@ -141,13 +140,13 @@ impl Action {
|
||||
///
|
||||
/// Returns the number of advancements successfully modified. An advancement is counted as
|
||||
/// successful if [`perform_single_inner`] returns `true`
|
||||
async fn perform(
|
||||
&self,
|
||||
fn perform(
|
||||
self,
|
||||
player: &Arc<Player>,
|
||||
advancements: &[&'static Advancement],
|
||||
show_advancement: bool,
|
||||
) -> i32 {
|
||||
let mut guard = player.advancements.lock().await;
|
||||
let mut guard = player.advancements.blocking_lock();
|
||||
if !show_advancement {
|
||||
guard.flush_dirty(player, true);
|
||||
}
|
||||
@@ -161,13 +160,13 @@ impl Action {
|
||||
count
|
||||
}
|
||||
|
||||
async fn perform_criterion(
|
||||
&self,
|
||||
fn perform_criterion(
|
||||
self,
|
||||
player: &Arc<Player>,
|
||||
advancement: &'static Advancement,
|
||||
criterion: &str,
|
||||
) -> bool {
|
||||
let mut guard = player.advancements.lock().await;
|
||||
let mut guard = player.advancements.blocking_lock();
|
||||
match self {
|
||||
Self::Grant => guard.award(advancement, criterion),
|
||||
Self::Revoke => guard.revoke(advancement, criterion),
|
||||
@@ -261,41 +260,41 @@ fn add_children(parent: &AdvancementNode, output: &mut Vec<&Advancement>) {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn perform_and_show(
|
||||
context: Arc<CommandSource>,
|
||||
fn perform_and_show(
|
||||
context: &CommandSource,
|
||||
players: &[Arc<Player>],
|
||||
action: Action,
|
||||
advancements: &[&'static Advancement],
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
perform(context, players, action, advancements, true).await
|
||||
perform(context, players, action, advancements, true)
|
||||
}
|
||||
|
||||
/// Performs a batch action (grant or revoke) on multiple advancements for multiple players.
|
||||
///
|
||||
/// This function iterates through each player and applies the specified action to all provided
|
||||
/// advancements. It automatically handles error messaging based on the number of players and
|
||||
/// advancements involved, as well as the number of successful operations.
|
||||
/// advancements involved.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `context` - The command source context used to send feedback messages to the command executor
|
||||
/// * `targets` - Slice of players who will be affected by the action
|
||||
/// * `context` - The command source context for sending feedback
|
||||
/// * `targets` - The players to apply the action to
|
||||
/// * `action` - The action to perform on each advancement (Grant or Revoke)
|
||||
/// * `advancements` - Slice of advancements to apply the action to
|
||||
/// * `show_advancement` - Whether to show advancement notifications to players (currently unused)
|
||||
/// * `advancements` - A slice of advancements to apply the action to
|
||||
/// * `show_advancement` - Whether to show advancement notifications to players
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns `Ok(i)` with the total count of successful operations if at least one advancement
|
||||
/// was successfully modified for at least one player.
|
||||
/// Returns `Ok(count)` with the total number of advancements successfully granted/revoked across
|
||||
/// all players.
|
||||
///
|
||||
/// Returns `Err` with an appropriate localized error message if no operations succeeded. The
|
||||
/// error message varies based on:
|
||||
/// - Whether one or many players were targeted
|
||||
/// - Whether one or many advancements were involved
|
||||
/// - The type of action (Grant or Revoke)
|
||||
async fn perform(
|
||||
context: Arc<CommandSource>,
|
||||
fn perform(
|
||||
context: &CommandSource,
|
||||
targets: &[Arc<Player>],
|
||||
action: Action,
|
||||
advancements: &[&'static Advancement],
|
||||
@@ -303,7 +302,7 @@ async fn perform(
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
let mut i = 0;
|
||||
for player in targets {
|
||||
i += action.perform(player, advancements, show_advancement).await;
|
||||
i += action.perform(player, advancements, show_advancement);
|
||||
}
|
||||
if i == 0 {
|
||||
return if let [first_advancement] = advancements[..] {
|
||||
@@ -378,7 +377,7 @@ async fn perform(
|
||||
],
|
||||
)
|
||||
};
|
||||
context.send_feedback(translate, true).await;
|
||||
context.send_feedback(translate, true);
|
||||
Ok(i)
|
||||
}
|
||||
|
||||
@@ -402,23 +401,19 @@ async fn perform(
|
||||
/// Returns `Err` with an appropriate error message if:
|
||||
/// - The criterion doesn't exist in the advancement
|
||||
/// - No operations succeeded
|
||||
pub async fn perform_criterion(
|
||||
context: Arc<CommandSource>,
|
||||
pub fn perform_criterion(
|
||||
context: &CommandSource,
|
||||
targets: &[Arc<Player>],
|
||||
action: Action,
|
||||
advancement: &'static Advancement,
|
||||
criterion: &str,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
if advancement.criteria.contains(&criterion) {
|
||||
let count = join_all(
|
||||
targets
|
||||
.iter()
|
||||
.map(|player| action.perform_criterion(player, advancement, criterion)),
|
||||
)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|&success| success)
|
||||
.count() as i32;
|
||||
let count = targets
|
||||
.iter()
|
||||
.map(|player| action.perform_criterion(player, advancement, criterion))
|
||||
.filter(|&success| success)
|
||||
.count() as i32;
|
||||
if count == 0 {
|
||||
if let [first_player] = targets {
|
||||
Err(match action {
|
||||
@@ -461,14 +456,16 @@ pub async fn perform_criterion(
|
||||
],
|
||||
)
|
||||
};
|
||||
context.send_feedback(translate, true).await;
|
||||
context.send_feedback(translate, true);
|
||||
Ok(count)
|
||||
}
|
||||
} else {
|
||||
Err(ERROR_CRITERION_NOT_FOUND.create_without_context(
|
||||
advancement.name(),
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
))
|
||||
Err(
|
||||
ERROR_CRITERION_NOT_FOUND.create_without_context_args_slice(&[
|
||||
advancement.name(),
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
]),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,18 +475,15 @@ struct OnlyAdvancementCriterionExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for OnlyAdvancementCriterionExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let action = self.action;
|
||||
Box::pin(async move {
|
||||
perform_criterion(
|
||||
context.source.clone(),
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
||||
action,
|
||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||
StringArgumentType::get(context, ARG_CRITERION)?,
|
||||
)
|
||||
.await
|
||||
})
|
||||
perform_criterion(
|
||||
&context.source,
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS)?,
|
||||
action,
|
||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||
StringArgumentType::get(context, ARG_CRITERION)?,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,21 +494,18 @@ struct AdvancementExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for AdvancementExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let action = self.action;
|
||||
let mode = self.mode;
|
||||
Box::pin(async move {
|
||||
perform_and_show(
|
||||
context.source.clone(),
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
||||
action,
|
||||
&get_advancements(
|
||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||
mode,
|
||||
),
|
||||
)
|
||||
.await
|
||||
})
|
||||
perform_and_show(
|
||||
&context.source,
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS)?,
|
||||
action,
|
||||
&get_advancements(
|
||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||
mode,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,18 +513,18 @@ impl CommandExecutor for AdvancementExecutor {
|
||||
struct CriterionSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for CriterionSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn suggest(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult<'a> {
|
||||
) -> SuggestionProviderResult {
|
||||
let suggestion = ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)
|
||||
.ok()
|
||||
.map(|adv| adv.criteria)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(ToString::to_string);
|
||||
Box::pin(async move { builder.filter_and_suggest_iter(suggestion).build() })
|
||||
builder.filter_and_suggest_iter(suggestion).build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,18 +534,15 @@ struct EveryAdvancementExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for EveryAdvancementExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let action = self.action;
|
||||
Box::pin(async move {
|
||||
perform(
|
||||
context.source.clone(),
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
||||
action,
|
||||
&Advancement::get_advancements_list(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
})
|
||||
perform(
|
||||
&context.source,
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS)?,
|
||||
action,
|
||||
&Advancement::get_advancements_list(),
|
||||
false,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,180 +59,162 @@ struct GetExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for GetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let scale = if self.has_scale {
|
||||
DoubleArgumentType::get(context, ARG_SCALE)?
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let scale = if self.has_scale {
|
||||
DoubleArgumentType::get(context, ARG_SCALE)?
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
|
||||
if self.is_base {
|
||||
let base_value = living.get_attribute_base(&attribute);
|
||||
let scaled_value = base_value * scale;
|
||||
if self.is_base {
|
||||
let base_value = living.get_attribute_base(&attribute);
|
||||
let scaled_value = base_value * scale;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(base_value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(base_value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
Ok(scaled_value as i32)
|
||||
} else {
|
||||
let value = living.get_attribute_value(&attribute);
|
||||
let scaled_value = value * scale;
|
||||
Ok(scaled_value as i32)
|
||||
} else {
|
||||
let value = living.get_attribute_value(&attribute);
|
||||
let scaled_value = value * scale;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
Ok(scaled_value as i32)
|
||||
}
|
||||
})
|
||||
Ok(scaled_value as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BaseSetExecutor;
|
||||
|
||||
impl CommandExecutor for BaseSetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
|
||||
living.set_attribute_base(&attribute, value);
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_SET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_SET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
target.get_name(),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
living.set_attribute_base(&attribute, value);
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_SET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_SET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(value as i32)
|
||||
})
|
||||
Ok(value as i32)
|
||||
}
|
||||
}
|
||||
|
||||
struct BaseResetExecutor;
|
||||
|
||||
impl CommandExecutor for BaseResetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
|
||||
let default_val = attribute.default_value;
|
||||
living.set_attribute_base(&attribute, default_val);
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_RESET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_RESET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
target.get_name(),
|
||||
TextComponent::text(default_val.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
let default_val = attribute.default_value;
|
||||
living.set_attribute_base(&attribute, default_val);
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_RESET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_RESET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(default_val.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(default_val as i32)
|
||||
})
|
||||
Ok(default_val as i32)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,208 +223,193 @@ struct ModifierAddExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for ModifierAddExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
let _name = StringArgumentType::get(context, ARG_NAME)?;
|
||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
let _name = StringArgumentType::get(context, ARG_NAME)?;
|
||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||
|
||||
let modifier_id = uuid.to_string();
|
||||
let modifier_id = uuid.to_string();
|
||||
|
||||
let res = {
|
||||
let mut map = living
|
||||
.attributes
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
})?;
|
||||
|
||||
if inst.modifiers.iter().any(|m| m.id == modifier_id) {
|
||||
Err(MODIFIER_ALREADY_PRESENT_ERROR.create_without_context(
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
))
|
||||
} else {
|
||||
inst.modifiers.push(crate::entity::attributes::Modifier {
|
||||
id: modifier_id.clone(),
|
||||
amount: value,
|
||||
operation: self.operation,
|
||||
});
|
||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
res?;
|
||||
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_ADD_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_ADD_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
],
|
||||
),
|
||||
true,
|
||||
let res = {
|
||||
let mut map = living
|
||||
.attributes
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
.await;
|
||||
})?;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
if inst.modifiers.iter().any(|m| m.id == modifier_id) {
|
||||
Err(MODIFIER_ALREADY_PRESENT_ERROR.create_without_context(
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
))
|
||||
} else {
|
||||
inst.modifiers.push(crate::entity::attributes::Modifier {
|
||||
id: modifier_id.clone(),
|
||||
amount: value,
|
||||
operation: self.operation,
|
||||
});
|
||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
res?;
|
||||
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_ADD_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_ADD_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct ModifierRemoveExecutor;
|
||||
|
||||
impl CommandExecutor for ModifierRemoveExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
|
||||
let modifier_id = uuid.to_string();
|
||||
let modifier_id = uuid.to_string();
|
||||
|
||||
let res = {
|
||||
let mut map = living
|
||||
.attributes
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
let res = {
|
||||
let mut map = living
|
||||
.attributes
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
})?;
|
||||
|
||||
let index = inst
|
||||
.modifiers
|
||||
.iter()
|
||||
.position(|m| m.id == modifier_id)
|
||||
.ok_or_else(|| {
|
||||
NO_MODIFIER_ERROR.create_without_context(
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let index = inst
|
||||
.modifiers
|
||||
.iter()
|
||||
.position(|m| m.id == modifier_id)
|
||||
.ok_or_else(|| {
|
||||
NO_MODIFIER_ERROR.create_without_context(
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
)
|
||||
})?;
|
||||
inst.modifiers.remove(index);
|
||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
};
|
||||
res?;
|
||||
|
||||
inst.modifiers.remove(index);
|
||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
};
|
||||
res?;
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
);
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_REMOVE_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_REMOVE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_REMOVE_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_REMOVE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct ModifierGetExecutor;
|
||||
|
||||
impl CommandExecutor for ModifierGetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
|
||||
let modifier_id = uuid.to_string();
|
||||
let modifier_id = uuid.to_string();
|
||||
|
||||
let val = {
|
||||
let map = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let inst = map.get(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
let val = {
|
||||
let map = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let inst = map.get(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
})?;
|
||||
|
||||
let modifier = inst
|
||||
.modifiers
|
||||
.iter()
|
||||
.find(|m| m.id == modifier_id)
|
||||
.ok_or_else(|| {
|
||||
NO_MODIFIER_ERROR.create_without_context(
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let modifier = inst
|
||||
.modifiers
|
||||
.iter()
|
||||
.find(|m| m.id == modifier_id)
|
||||
.ok_or_else(|| {
|
||||
NO_MODIFIER_ERROR.create_without_context(
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
)
|
||||
})?;
|
||||
modifier.amount
|
||||
};
|
||||
|
||||
modifier.amount
|
||||
};
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(val as i32)
|
||||
})
|
||||
Ok(val as i32)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::command::CommandResult;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandSender,
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs,
|
||||
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
||||
@@ -25,47 +24,43 @@ const ARG_REASON: &str = "reason";
|
||||
struct NoReasonExecutor;
|
||||
|
||||
impl CommandExecutor for NoReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
ban_players(sender, server, targets.as_slice(), None).await
|
||||
})
|
||||
ban_players(sender, server, targets.as_slice(), None)
|
||||
}
|
||||
}
|
||||
|
||||
struct ReasonExecutor;
|
||||
|
||||
impl CommandExecutor for ReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||
};
|
||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||
};
|
||||
|
||||
ban_players(sender, server, targets.as_slice(), Some(reason)).await
|
||||
})
|
||||
ban_players(sender, server, targets.as_slice(), Some(reason))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of players successfully banned.
|
||||
async fn ban_players(
|
||||
fn ban_players(
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
targets: &[GameProfile],
|
||||
@@ -73,7 +68,7 @@ async fn ban_players(
|
||||
) -> Result<i32, CommandError> {
|
||||
let mut count: usize = 0;
|
||||
for target in targets {
|
||||
if ban_profile(sender, server, target, reason.cloned()).await {
|
||||
if ban_profile(sender, server, target, reason.cloned()) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
@@ -90,13 +85,13 @@ async fn ban_players(
|
||||
}
|
||||
|
||||
/// Returns `true` if the player was successfully banned.
|
||||
async fn ban_profile(
|
||||
fn ban_profile(
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
profile: &GameProfile,
|
||||
reason: Option<String>,
|
||||
) -> bool {
|
||||
let mut banned_players = server.data.banned_player_list.write().await;
|
||||
let mut banned_players = server.data.banned_player_list.write().unwrap();
|
||||
|
||||
let reason = reason.unwrap_or_else(|| "Banned by an operator.".to_string());
|
||||
|
||||
@@ -123,28 +118,22 @@ async fn ban_profile(
|
||||
drop(banned_players);
|
||||
|
||||
// Send messages
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BAN_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BAN_SUCCESS,
|
||||
[
|
||||
TextComponent::text(profile.name.clone()),
|
||||
TextComponent::text(reason),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BAN_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BAN_SUCCESS,
|
||||
[
|
||||
TextComponent::text(profile.name.clone()),
|
||||
TextComponent::text(reason),
|
||||
],
|
||||
));
|
||||
|
||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
||||
player
|
||||
.kick(
|
||||
DisconnectReason::Kicked,
|
||||
TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_BANNED,
|
||||
translation::bedrock::DISCONNECTIONSCREEN_TITLE_BANNEDBYHOST,
|
||||
[],
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let kick_msg = TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_BANNED,
|
||||
translation::bedrock::DISCONNECTIONSCREEN_TITLE_BANNEDBYHOST,
|
||||
[],
|
||||
);
|
||||
player.kick(DisconnectReason::Kicked, &kick_msg);
|
||||
}
|
||||
|
||||
true
|
||||
|
||||
@@ -30,46 +30,42 @@ fn parse_ip(target: &str, server: &Server) -> Option<IpAddr> {
|
||||
struct NoReasonExecutor;
|
||||
|
||||
impl CommandExecutor for NoReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
ban_ip(sender, server, target, None).await
|
||||
})
|
||||
ban_ip(sender, server, target, None)
|
||||
}
|
||||
}
|
||||
|
||||
struct ReasonExecutor;
|
||||
|
||||
impl CommandExecutor for ReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||
};
|
||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||
};
|
||||
|
||||
ban_ip(sender, server, target, Some(reason.clone())).await
|
||||
})
|
||||
ban_ip(sender, server, target, Some(reason.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn ban_ip(
|
||||
fn ban_ip(
|
||||
sender: &CommandSender,
|
||||
server: &Server,
|
||||
target: &str,
|
||||
@@ -85,7 +81,7 @@ async fn ban_ip(
|
||||
)));
|
||||
};
|
||||
|
||||
let mut banned_ips = server.data.banned_ip_list.write().await;
|
||||
let mut banned_ips = server.data.banned_ip_list.write().unwrap();
|
||||
|
||||
if banned_ips.get_entry(&target_ip).is_some() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
@@ -113,40 +109,32 @@ async fn ban_ip(
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BANIP_SUCCESS,
|
||||
[
|
||||
TextComponent::text(target_ip.to_string()),
|
||||
TextComponent::text(reason),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BANIP_SUCCESS,
|
||||
[
|
||||
TextComponent::text(target_ip.to_string()),
|
||||
TextComponent::text(reason),
|
||||
],
|
||||
));
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_INFO,
|
||||
translation::java::COMMANDS_BANIP_INFO,
|
||||
[
|
||||
TextComponent::text(affected.len().to_string()),
|
||||
TextComponent::text(names),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_INFO,
|
||||
translation::java::COMMANDS_BANIP_INFO,
|
||||
[
|
||||
TextComponent::text(affected.len().to_string()),
|
||||
TextComponent::text(names),
|
||||
],
|
||||
));
|
||||
|
||||
let count = affected.len();
|
||||
for target in affected {
|
||||
target
|
||||
.kick(
|
||||
DisconnectReason::Kicked,
|
||||
TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||
[],
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let kick_msg = TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||
[],
|
||||
);
|
||||
target.kick(DisconnectReason::Kicked, &kick_msg);
|
||||
}
|
||||
|
||||
Ok(count as i32)
|
||||
|
||||
@@ -23,86 +23,78 @@ struct BanListCommandExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for BanListCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut entries = Vec::new();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let mut entries = Vec::new();
|
||||
|
||||
let data = &context.server().data;
|
||||
let data = &context.server().data;
|
||||
|
||||
if self.players {
|
||||
let lock = data.banned_player_list.read().await;
|
||||
for entry in &lock.banned_players {
|
||||
entries.push(BanListEntry {
|
||||
name: entry.name.clone(),
|
||||
source: entry.source.clone(),
|
||||
reason: entry.reason.clone(),
|
||||
});
|
||||
}
|
||||
if self.players {
|
||||
let lock = data.banned_player_list.read().unwrap();
|
||||
for entry in &lock.banned_players {
|
||||
entries.push(BanListEntry {
|
||||
name: entry.name.clone(),
|
||||
source: entry.source.clone(),
|
||||
reason: entry.reason.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if self.ips {
|
||||
let lock = data.banned_ip_list.read().await;
|
||||
for entry in &lock.banned_ips {
|
||||
entries.push(BanListEntry {
|
||||
name: entry.ip.to_string(),
|
||||
source: entry.source.clone(),
|
||||
reason: entry.reason.clone(),
|
||||
});
|
||||
}
|
||||
if self.ips {
|
||||
let lock = data.banned_ip_list.read().unwrap();
|
||||
for entry in &lock.banned_ips {
|
||||
entries.push(BanListEntry {
|
||||
name: entry.ip.to_string(),
|
||||
source: entry.source.clone(),
|
||||
reason: entry.reason.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let entries_len = entries.len() as i32;
|
||||
let source = &context.source;
|
||||
let entries_len = entries.len() as i32;
|
||||
let source = &context.source;
|
||||
|
||||
if entries.is_empty() {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_NONE,
|
||||
translation::java::COMMANDS_BANLIST_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
if entries.is_empty() {
|
||||
source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_NONE,
|
||||
translation::java::COMMANDS_BANLIST_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
let bedrock_list_key = if self.ips && !self.players {
|
||||
translation::bedrock::COMMANDS_BANLIST_IPS
|
||||
} else {
|
||||
let bedrock_list_key = if self.ips && !self.players {
|
||||
translation::bedrock::COMMANDS_BANLIST_IPS
|
||||
} else {
|
||||
translation::bedrock::COMMANDS_BANLIST_PLAYERS
|
||||
};
|
||||
translation::bedrock::COMMANDS_BANLIST_PLAYERS
|
||||
};
|
||||
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_LIST,
|
||||
bedrock_list_key,
|
||||
[TextComponent::text(entries.len().to_string())],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_LIST,
|
||||
bedrock_list_key,
|
||||
[TextComponent::text(entries.len().to_string())],
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
for entry in entries {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||
[
|
||||
TextComponent::text(entry.name),
|
||||
TextComponent::text(entry.source),
|
||||
TextComponent::text(entry.reason),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for entry in entries {
|
||||
source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||
[
|
||||
TextComponent::text(entry.name),
|
||||
TextComponent::text(entry.source),
|
||||
TextComponent::text(entry.reason),
|
||||
],
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries_len)
|
||||
})
|
||||
Ok(entries_len)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,25 +35,23 @@ const fn autocomplete_consumer() -> ResourceLocationArgumentConsumer {
|
||||
struct BossbarSuggestionProvider;
|
||||
|
||||
impl CommandSuggestionProvider for BossbarSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
_src: &'a CommandSender,
|
||||
server: &'a Server,
|
||||
input: &'a str,
|
||||
fn suggest(
|
||||
&self,
|
||||
_src: &CommandSender,
|
||||
server: &Server,
|
||||
input: &str,
|
||||
start: usize,
|
||||
_end: usize,
|
||||
) -> CommandSuggestionResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut builder = SuggestionsBuilder::new(input, start);
|
||||
let bossbars = server.bossbars.lock().await;
|
||||
let remaining = builder.remaining_lowercase().to_string();
|
||||
for key in bossbars.custom_bossbars.keys() {
|
||||
if key.to_lowercase().starts_with(&remaining) {
|
||||
builder = builder.suggest(key.clone());
|
||||
}
|
||||
) -> CommandSuggestionResult {
|
||||
let mut builder = SuggestionsBuilder::new(input, start);
|
||||
let bossbars = server.bossbars.lock().unwrap();
|
||||
let remaining = builder.remaining_lowercase().to_string();
|
||||
for key in bossbars.custom_bossbars.keys() {
|
||||
if key.to_lowercase().starts_with(&remaining) {
|
||||
builder = builder.suggest(key.clone());
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,269 +75,229 @@ enum CommandValueSet {
|
||||
struct AddExecutor;
|
||||
|
||||
impl CommandExecutor for AddExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
|
||||
let text_component = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
let text_component = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
|
||||
if server.bossbars.lock().await.has_bossbar(&namespace) {
|
||||
return Result::Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_CREATE_FAILED,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_FAILURE_EXISTS,
|
||||
[TextComponent::text(namespace.clone())],
|
||||
)));
|
||||
}
|
||||
if server.bossbars.lock().unwrap().has_bossbar(&namespace) {
|
||||
return Result::Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_CREATE_FAILED,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_FAILURE_EXISTS,
|
||||
[TextComponent::text(namespace)],
|
||||
)));
|
||||
}
|
||||
|
||||
let bossbar = Bossbar::new(text_component);
|
||||
let mut bossbars = server.bossbars.lock().await;
|
||||
let bossbar = Bossbar::new(text_component);
|
||||
let mut bossbars = server.bossbars.lock().unwrap();
|
||||
|
||||
bossbars.create_bossbar(namespace.clone(), bossbar.clone());
|
||||
let new_size = bossbars.get_bossbars_len();
|
||||
drop(bossbars);
|
||||
bossbars.create_bossbar(namespace.clone(), bossbar.clone());
|
||||
let new_size = bossbars.get_bossbars_len();
|
||||
drop(bossbars);
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_CREATE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_SUCCESS,
|
||||
[bossbar_prefix(bossbar.title.clone(), namespace.clone())],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_CREATE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_SUCCESS,
|
||||
[bossbar_prefix(bossbar.title, namespace)],
|
||||
));
|
||||
|
||||
Ok(new_size as i32)
|
||||
})
|
||||
Ok(new_size as i32)
|
||||
}
|
||||
}
|
||||
|
||||
struct GetExecutor(CommandValueGet);
|
||||
|
||||
impl CommandExecutor for GetExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
|
||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace.clone()),
|
||||
let Some(bossbar) = server.bossbars.lock().unwrap().get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||
));
|
||||
};
|
||||
|
||||
match self.0 {
|
||||
CommandValueGet::Max => {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_MAX,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_MAX,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
||||
TextComponent::text(bossbar.max.to_string()),
|
||||
],
|
||||
));
|
||||
};
|
||||
|
||||
match self.0 {
|
||||
CommandValueGet::Max => {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_MAX,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_MAX,
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
),
|
||||
TextComponent::text(bossbar.max.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
Ok(bossbar.max)
|
||||
}
|
||||
CommandValueGet::Players => {
|
||||
let online_players: Vec<String> = server
|
||||
.get_all_players()
|
||||
.iter()
|
||||
.filter(|player| bossbar.players.contains(&player.gameprofile.id))
|
||||
.map(|player| player.gameprofile.name.clone())
|
||||
.collect();
|
||||
let count = online_players.len() as i32;
|
||||
|
||||
if count == 0 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_SOME,
|
||||
if count == 1 {
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_ONE
|
||||
} else {
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS
|
||||
},
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
),
|
||||
TextComponent::text(count.to_string()),
|
||||
TextComponent::text(online_players.join(", ")),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
CommandValueGet::Value => {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VALUE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VALUE,
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
),
|
||||
TextComponent::text(bossbar.value.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
Ok(bossbar.value)
|
||||
}
|
||||
CommandValueGet::Visible => {
|
||||
let (java_key, bedrock_key) = if bossbar.visible {
|
||||
(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_VISIBLE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_TRUE,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_HIDDEN,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_FALSE,
|
||||
)
|
||||
};
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
java_key,
|
||||
bedrock_key,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
Ok(bossbar.visible as i32)
|
||||
}
|
||||
Ok(bossbar.max)
|
||||
}
|
||||
})
|
||||
CommandValueGet::Players => {
|
||||
let online_players: Vec<String> = server
|
||||
.get_all_players()
|
||||
.iter()
|
||||
.filter(|player| bossbar.players.contains(&player.gameprofile.id))
|
||||
.map(|player| player.gameprofile.name.clone())
|
||||
.collect();
|
||||
let count = online_players.len() as i32;
|
||||
|
||||
if count == 0 {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
||||
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||
));
|
||||
} else {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_SOME,
|
||||
if count == 1 {
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_ONE
|
||||
} else {
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS
|
||||
},
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||
TextComponent::text(count.to_string()),
|
||||
TextComponent::text(online_players.join(", ")),
|
||||
],
|
||||
));
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
CommandValueGet::Value => {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VALUE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VALUE,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
||||
TextComponent::text(bossbar.value.to_string()),
|
||||
],
|
||||
));
|
||||
Ok(bossbar.value)
|
||||
}
|
||||
CommandValueGet::Visible => {
|
||||
let (java_key, bedrock_key) = if bossbar.visible {
|
||||
(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_VISIBLE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_TRUE,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_HIDDEN,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_FALSE,
|
||||
)
|
||||
};
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
java_key,
|
||||
bedrock_key,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace,
|
||||
)],
|
||||
));
|
||||
Ok(bossbar.visible as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ListExecutor;
|
||||
|
||||
impl CommandExecutor for ListExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let bossbars = server.bossbars.lock().await.get_all_bossbars();
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
_args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let bossbars = server.bossbars.lock().unwrap().get_all_bossbars();
|
||||
|
||||
if bossbars.is_empty() {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_NONE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_LIST_NONE,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
return Ok(0);
|
||||
}
|
||||
if bossbars.is_empty() {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_NONE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_LIST_NONE,
|
||||
[],
|
||||
));
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut bossbars_text = TextComponent::empty();
|
||||
for (i, bossbar) in bossbars.iter().enumerate() {
|
||||
if i == 0 {
|
||||
bossbars_text = bossbars_text.add_child(bossbar_prefix(
|
||||
let mut bossbars_text = TextComponent::empty();
|
||||
for (i, bossbar) in bossbars.iter().enumerate() {
|
||||
if i == 0 {
|
||||
bossbars_text = bossbars_text.add_child(bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
bossbar.namespace.clone(),
|
||||
));
|
||||
} else {
|
||||
bossbars_text =
|
||||
bossbars_text.add_child(TextComponent::text(", ").add_child(bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
bossbar.namespace.clone(),
|
||||
));
|
||||
} else {
|
||||
bossbars_text = bossbars_text.add_child(TextComponent::text(", ").add_child(
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
bossbar.namespace.clone(),
|
||||
),
|
||||
));
|
||||
}
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_SOME,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_LIST,
|
||||
[
|
||||
TextComponent::text(bossbars.len().to_string()),
|
||||
bossbars_text,
|
||||
],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_SOME,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_LIST,
|
||||
[
|
||||
TextComponent::text(bossbars.len().to_string()),
|
||||
bossbars_text,
|
||||
],
|
||||
));
|
||||
|
||||
Ok(bossbars.len() as i32)
|
||||
})
|
||||
Ok(bossbars.len() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
struct RemoveExecutor;
|
||||
|
||||
impl CommandExecutor for RemoveExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
|
||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||
));
|
||||
};
|
||||
let Some(bossbar) = server.bossbars.lock().unwrap().get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||
));
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_REMOVE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_REMOVE,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_REMOVE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_REMOVE,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title,
|
||||
namespace.clone(),
|
||||
)],
|
||||
));
|
||||
|
||||
let res = server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.remove_bossbar(server, namespace);
|
||||
match res {
|
||||
Ok(()) => Ok(server.bossbars.lock().await.get_bossbars_len() as i32),
|
||||
Err(error) => Err(handle_bossbar_error(error)),
|
||||
}
|
||||
})
|
||||
let res = server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.remove_bossbar(server, namespace);
|
||||
match res {
|
||||
Ok(()) => Ok(server.bossbars.lock().unwrap().get_bossbars_len() as i32),
|
||||
Err(error) => Err(handle_bossbar_error(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,231 +305,201 @@ struct SetExecutor(CommandValueSet);
|
||||
|
||||
impl CommandExecutor for SetExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
|
||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||
let Some(bossbar) = server.bossbars.lock().unwrap().get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||
));
|
||||
};
|
||||
|
||||
match self.0 {
|
||||
CommandValueSet::Color => {
|
||||
let color = BossbarColorArgumentConsumer.find_arg_default_name(args)?;
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_color(server, &namespace, *color)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
||||
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||
));
|
||||
};
|
||||
|
||||
match self.0 {
|
||||
CommandValueSet::Color => {
|
||||
let color = BossbarColorArgumentConsumer.find_arg_default_name(args)?;
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_color(server, &namespace, *color)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace,
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Max => {
|
||||
let Ok(max_value) = max_value_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"parsing.int.invalid",
|
||||
"parsing.int.invalid",
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_max(server, namespace.clone(), max_value)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
||||
TextComponent::text(max_value.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Name => {
|
||||
let name = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_name(server, &namespace, &name)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
||||
[bossbar_prefix(name.clone(), namespace)],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Players(has_players) => {
|
||||
if !has_players {
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.set_players(server, namespace.clone(), vec![])
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace,
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
let players: Vec<Uuid> =
|
||||
targets.iter().map(|player| player.gameprofile.id).collect();
|
||||
let count = players.len();
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.set_players(server, namespace.clone(), players)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
let player_names = targets
|
||||
.iter()
|
||||
.map(|p| p.gameprofile.name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
||||
TextComponent::text(count.to_string()),
|
||||
TextComponent::text(player_names),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(count as i32)
|
||||
}
|
||||
CommandValueSet::Style => {
|
||||
let style = BossbarStyleArgumentConsumer.find_arg_default_name(args)?;
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_style(server, &namespace, *style)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace,
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Value => {
|
||||
let Ok(value) = value_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"parsing.int.invalid",
|
||||
"parsing.int.invalid",
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_value(server, namespace.clone(), value)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(value)
|
||||
}
|
||||
CommandValueSet::Visible => {
|
||||
let visibility = BoolArgConsumer::find_arg(args, ARG_VISIBLE)?;
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_visibility(server, namespace.clone(), visibility)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
let state = if visibility {
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_VISIBLE
|
||||
} else {
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_HIDDEN
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
state,
|
||||
state,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace,
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
})
|
||||
CommandValueSet::Max => {
|
||||
let Ok(max_value) = max_value_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"parsing.int.invalid",
|
||||
"parsing.int.invalid",
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_max(server, namespace.clone(), max_value)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||
TextComponent::text(max_value.to_string()),
|
||||
],
|
||||
));
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Name => {
|
||||
let name = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_name(server, &namespace, &name)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
||||
[bossbar_prefix(name, namespace)],
|
||||
));
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Players(has_players) => {
|
||||
if !has_players {
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_players(server, namespace.clone(), vec![])
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
||||
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||
));
|
||||
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
let players: Vec<Uuid> =
|
||||
targets.iter().map(|player| player.gameprofile.id).collect();
|
||||
let count = players.len();
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_players(server, namespace.clone(), players)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
let player_names = targets
|
||||
.iter()
|
||||
.map(|p| p.gameprofile.name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||
TextComponent::text(count.to_string()),
|
||||
TextComponent::text(player_names),
|
||||
],
|
||||
));
|
||||
|
||||
Ok(count as i32)
|
||||
}
|
||||
CommandValueSet::Style => {
|
||||
let style = BossbarStyleArgumentConsumer.find_arg_default_name(args)?;
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_style(server, &namespace, *style)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
||||
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||
));
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Value => {
|
||||
let Ok(value) = value_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"parsing.int.invalid",
|
||||
"parsing.int.invalid",
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_value(server, namespace.clone(), value)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
||||
[
|
||||
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
));
|
||||
|
||||
Ok(value)
|
||||
}
|
||||
CommandValueSet::Visible => {
|
||||
let visibility = BoolArgConsumer::find_arg(args, ARG_VISIBLE)?;
|
||||
|
||||
server
|
||||
.bossbars
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_visibility(server, namespace.clone(), visibility)
|
||||
.map_err(handle_bossbar_error)?;
|
||||
|
||||
let state = if visibility {
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_VISIBLE
|
||||
} else {
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_HIDDEN
|
||||
};
|
||||
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
state,
|
||||
state,
|
||||
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||
));
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -106,22 +106,22 @@ fn test_and_clear(
|
||||
}
|
||||
}
|
||||
|
||||
async fn command_result(
|
||||
fn command_result(
|
||||
sender: &CommandSender,
|
||||
item_count: i32,
|
||||
max_count: i32,
|
||||
targets: &[Arc<Player>],
|
||||
) -> Result<i32, CommandError> {
|
||||
match clear_command_text_output(item_count, max_count, targets).await {
|
||||
match clear_command_text_output(item_count, max_count, targets) {
|
||||
Ok(success) => {
|
||||
sender.send_message(success).await;
|
||||
sender.send_message(success);
|
||||
Ok(item_count)
|
||||
}
|
||||
Err(failure) => Err(CommandError::CommandFailed(failure)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn clear_command_text_output(
|
||||
fn clear_command_text_output(
|
||||
item_count: i32,
|
||||
max_count: i32,
|
||||
targets: &[Arc<Player>],
|
||||
@@ -179,103 +179,94 @@ const fn count_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
struct SelfExecutor;
|
||||
|
||||
impl CommandExecutor for SelfExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = sender.as_player().ok_or(CommandError::InvalidRequirement)?;
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
_args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let target = sender.as_player().ok_or(CommandError::InvalidRequirement)?;
|
||||
|
||||
let items_cleared = clear_player(&target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
||||
let items_cleared = clear_player(&target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
||||
|
||||
command_result(sender, items_cleared, MAX_NO_UPPER_LIMIT, &[target]).await
|
||||
})
|
||||
command_result(sender, items_cleared, MAX_NO_UPPER_LIMIT, &[target])
|
||||
}
|
||||
}
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared +=
|
||||
clear_player(target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
||||
}
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
||||
}
|
||||
|
||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets).await
|
||||
})
|
||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets)
|
||||
}
|
||||
}
|
||||
|
||||
struct ItemExecutor;
|
||||
|
||||
impl CommandExecutor for ItemExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &item, MAX_NO_UPPER_LIMIT);
|
||||
}
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &item, MAX_NO_UPPER_LIMIT);
|
||||
}
|
||||
|
||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets).await
|
||||
})
|
||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets)
|
||||
}
|
||||
}
|
||||
|
||||
struct ItemCountExecutor;
|
||||
|
||||
impl CommandExecutor for ItemCountExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let Ok(max) = count_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let Ok(max) = count_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &item, max);
|
||||
}
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &item, max);
|
||||
}
|
||||
|
||||
command_result(sender, total_items_cleared, max, targets).await
|
||||
})
|
||||
command_result(sender, total_items_cleared, max, targets)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,187 +76,182 @@ struct ClonedBlock {
|
||||
|
||||
impl CommandExecutor for CloneExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let begin = BlockPosArgumentType::get_block_pos(context, ARG_BEGIN)?;
|
||||
let end = BlockPosArgumentType::get_block_pos(context, ARG_END)?;
|
||||
let dest = BlockPosArgumentType::get_block_pos(context, ARG_DEST)?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let begin = BlockPosArgumentType::get_block_pos(context, ARG_BEGIN)?;
|
||||
let end = BlockPosArgumentType::get_block_pos(context, ARG_END)?;
|
||||
let dest = BlockPosArgumentType::get_block_pos(context, ARG_DEST)?;
|
||||
|
||||
let filter_block = if self.has_filter {
|
||||
Some(BlockArgumentType::get(context, ARG_FILTER)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let filter_block = if self.has_filter {
|
||||
Some(BlockArgumentType::get(context, ARG_FILTER)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let min_x = begin.0.x.min(end.0.x);
|
||||
let max_x = begin.0.x.max(end.0.x);
|
||||
let min_y = begin.0.y.min(end.0.y);
|
||||
let max_y = begin.0.y.max(end.0.y);
|
||||
let min_z = begin.0.z.min(end.0.z);
|
||||
let max_z = begin.0.z.max(end.0.z);
|
||||
let min_x = begin.0.x.min(end.0.x);
|
||||
let max_x = begin.0.x.max(end.0.x);
|
||||
let min_y = begin.0.y.min(end.0.y);
|
||||
let max_y = begin.0.y.max(end.0.y);
|
||||
let min_z = begin.0.z.min(end.0.z);
|
||||
let max_z = begin.0.z.max(end.0.z);
|
||||
|
||||
let size_x = max_x - min_x + 1;
|
||||
let size_y = max_y - min_y + 1;
|
||||
let size_z = max_z - min_z + 1;
|
||||
let size_x = max_x - min_x + 1;
|
||||
let size_y = max_y - min_y + 1;
|
||||
let size_z = max_z - min_z + 1;
|
||||
|
||||
let volume = size_x * size_y * size_z;
|
||||
let volume = size_x * size_y * size_z;
|
||||
|
||||
if volume > 32768 {
|
||||
return Err(TOOBIG_ERROR.create_without_context_args_slice(&[
|
||||
TextComponent::text("32768"),
|
||||
TextComponent::text(volume.to_string()),
|
||||
]));
|
||||
}
|
||||
if volume > 32768 {
|
||||
return Err(TOOBIG_ERROR.create_without_context_args_slice(&[
|
||||
TextComponent::text("32768"),
|
||||
TextComponent::text(volume.to_string()),
|
||||
]));
|
||||
}
|
||||
|
||||
let dest_min_x = dest.0.x;
|
||||
let dest_min_y = dest.0.y;
|
||||
let dest_min_z = dest.0.z;
|
||||
let dest_max_x = dest_min_x + size_x - 1;
|
||||
let dest_max_y = dest_min_y + size_y - 1;
|
||||
let dest_max_z = dest_min_z + size_z - 1;
|
||||
let dest_min_x = dest.0.x;
|
||||
let dest_min_y = dest.0.y;
|
||||
let dest_min_z = dest.0.z;
|
||||
let dest_max_x = dest_min_x + size_x - 1;
|
||||
let dest_max_y = dest_min_y + size_y - 1;
|
||||
let dest_max_z = dest_min_z + size_z - 1;
|
||||
|
||||
let overlap = !(dest_max_x < min_x
|
||||
|| dest_min_x > max_x
|
||||
|| dest_max_y < min_y
|
||||
|| dest_min_y > max_y
|
||||
|| dest_max_z < min_z
|
||||
|| dest_min_z > max_z);
|
||||
let overlap = !(dest_max_x < min_x
|
||||
|| dest_min_x > max_x
|
||||
|| dest_max_y < min_y
|
||||
|| dest_min_y > max_y
|
||||
|| dest_max_z < min_z
|
||||
|| dest_min_z > max_z);
|
||||
|
||||
if overlap && self.clone_mode != CloneMode::Force {
|
||||
return Err(OVERLAP_ERROR.create_without_context());
|
||||
}
|
||||
if overlap && self.clone_mode != CloneMode::Force {
|
||||
return Err(OVERLAP_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let world = context.source.world();
|
||||
let world = context.source.world();
|
||||
|
||||
let limit_check_pos_1 = BlockPos::new(min_x, min_y, min_z);
|
||||
let limit_check_pos_2 = BlockPos::new(max_x, max_y, max_z);
|
||||
let limit_check_pos_3 = BlockPos::new(dest_min_x, dest_min_y, dest_min_z);
|
||||
let limit_check_pos_4 = BlockPos::new(dest_max_x, dest_max_y, dest_max_z);
|
||||
let limit_check_pos_1 = BlockPos::new(min_x, min_y, min_z);
|
||||
let limit_check_pos_2 = BlockPos::new(max_x, max_y, max_z);
|
||||
let limit_check_pos_3 = BlockPos::new(dest_min_x, dest_min_y, dest_min_z);
|
||||
let limit_check_pos_4 = BlockPos::new(dest_max_x, dest_max_y, dest_max_z);
|
||||
|
||||
if !world.is_in_build_limit(limit_check_pos_1)
|
||||
|| !world.is_in_build_limit(limit_check_pos_2)
|
||||
|| !world.is_in_build_limit(limit_check_pos_3)
|
||||
|| !world.is_in_build_limit(limit_check_pos_4)
|
||||
{
|
||||
return Err(OUT_OF_WORLD_ERROR.create_without_context());
|
||||
}
|
||||
if !world.is_in_build_limit(limit_check_pos_1)
|
||||
|| !world.is_in_build_limit(limit_check_pos_2)
|
||||
|| !world.is_in_build_limit(limit_check_pos_3)
|
||||
|| !world.is_in_build_limit(limit_check_pos_4)
|
||||
{
|
||||
return Err(OUT_OF_WORLD_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
for cx in (min_x >> 4)..=(max_x >> 4) {
|
||||
for cz in (min_z >> 4)..=(max_z >> 4) {
|
||||
let chunk_pos = Vector2::new(cx, cz);
|
||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||
}
|
||||
for cx in (min_x >> 4)..=(max_x >> 4) {
|
||||
for cz in (min_z >> 4)..=(max_z >> 4) {
|
||||
let chunk_pos = Vector2::new(cx, cz);
|
||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for cx in (dest_min_x >> 4)..=(dest_max_x >> 4) {
|
||||
for cz in (dest_min_z >> 4)..=(dest_max_z >> 4) {
|
||||
let chunk_pos = Vector2::new(cx, cz);
|
||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||
}
|
||||
for cx in (dest_min_x >> 4)..=(dest_max_x >> 4) {
|
||||
for cz in (dest_min_z >> 4)..=(dest_max_z >> 4) {
|
||||
let chunk_pos = Vector2::new(cx, cz);
|
||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut blocks_to_clone = Vec::new();
|
||||
let mut blocks_to_clone = Vec::new();
|
||||
|
||||
for x in 0..size_x {
|
||||
for y in 0..size_y {
|
||||
for z in 0..size_z {
|
||||
let src_pos = BlockPos::new(min_x + x, min_y + y, min_z + z);
|
||||
let dest_pos =
|
||||
BlockPos::new(dest_min_x + x, dest_min_y + y, dest_min_z + z);
|
||||
for x in 0..size_x {
|
||||
for y in 0..size_y {
|
||||
for z in 0..size_z {
|
||||
let src_pos = BlockPos::new(min_x + x, min_y + y, min_z + z);
|
||||
let dest_pos = BlockPos::new(dest_min_x + x, dest_min_y + y, dest_min_z + z);
|
||||
|
||||
let state_id = world.get_block_state_id(&src_pos);
|
||||
let state_id = world.get_block_state_id(&src_pos);
|
||||
|
||||
let should_clone = match self.mask_mode {
|
||||
MaskMode::Replace => true,
|
||||
MaskMode::Masked => !pumpkin_data::block_properties::is_air(state_id),
|
||||
MaskMode::Filtered => {
|
||||
let block = Block::from_state_id(state_id);
|
||||
filter_block.is_some_and(|f| block.id == f.id)
|
||||
}
|
||||
};
|
||||
|
||||
if should_clone {
|
||||
let block_entity_nbt =
|
||||
if let Some(be) = world.get_block_entity(&src_pos) {
|
||||
let mut nbt = NbtCompound::new();
|
||||
be.write_internal(&mut nbt).await;
|
||||
Some(nbt)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
blocks_to_clone.push(ClonedBlock {
|
||||
src_pos,
|
||||
dest_pos,
|
||||
state_id,
|
||||
block_entity_nbt,
|
||||
});
|
||||
let should_clone = match self.mask_mode {
|
||||
MaskMode::Replace => true,
|
||||
MaskMode::Masked => !pumpkin_data::block_properties::is_air(state_id),
|
||||
MaskMode::Filtered => {
|
||||
let block = Block::from_state_id(state_id);
|
||||
filter_block.is_some_and(|f| block.id == f.id)
|
||||
}
|
||||
};
|
||||
|
||||
if should_clone {
|
||||
let block_entity_nbt = world.get_block_entity(&src_pos).map(|be| {
|
||||
let mut nbt = NbtCompound::new();
|
||||
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||
tokio::task::block_in_place(|| {
|
||||
handle.block_on(be.write_internal(&mut nbt));
|
||||
});
|
||||
}
|
||||
nbt
|
||||
});
|
||||
|
||||
blocks_to_clone.push(ClonedBlock {
|
||||
src_pos,
|
||||
dest_pos,
|
||||
state_id,
|
||||
block_entity_nbt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut count = 0;
|
||||
let mut count = 0;
|
||||
for block in &blocks_to_clone {
|
||||
world.set_block_state(&block.dest_pos, block.state_id, BlockFlags::NOTIFY_ALL);
|
||||
|
||||
if let Some(nbt) = &block.block_entity_nbt {
|
||||
let mut new_nbt = nbt.clone();
|
||||
new_nbt.put_int("x", block.dest_pos.0.x);
|
||||
new_nbt.put_int("y", block.dest_pos.0.y);
|
||||
new_nbt.put_int("z", block.dest_pos.0.z);
|
||||
|
||||
if let Some(be) = crate::block::entities::block_entity_from_nbt(&new_nbt) {
|
||||
world.add_block_entity(be);
|
||||
}
|
||||
}
|
||||
|
||||
count += 1;
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
return Err(FAILED_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let is_dest_pos = |pos: &BlockPos| {
|
||||
pos.0.x >= dest_min_x
|
||||
&& pos.0.x <= dest_max_x
|
||||
&& pos.0.y >= dest_min_y
|
||||
&& pos.0.y <= dest_max_y
|
||||
&& pos.0.z >= dest_min_z
|
||||
&& pos.0.z <= dest_max_z
|
||||
};
|
||||
|
||||
if self.clone_mode == CloneMode::Move {
|
||||
for block in &blocks_to_clone {
|
||||
world.set_block_state(&block.dest_pos, block.state_id, BlockFlags::NOTIFY_ALL);
|
||||
|
||||
if let Some(nbt) = &block.block_entity_nbt {
|
||||
let mut new_nbt = nbt.clone();
|
||||
new_nbt.put_int("x", block.dest_pos.0.x);
|
||||
new_nbt.put_int("y", block.dest_pos.0.y);
|
||||
new_nbt.put_int("z", block.dest_pos.0.z);
|
||||
|
||||
if let Some(be) = crate::block::entities::block_entity_from_nbt(&new_nbt) {
|
||||
world.add_block_entity(be);
|
||||
}
|
||||
}
|
||||
|
||||
count += 1;
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
return Err(FAILED_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let is_dest_pos = |pos: &BlockPos| {
|
||||
pos.0.x >= dest_min_x
|
||||
&& pos.0.x <= dest_max_x
|
||||
&& pos.0.y >= dest_min_y
|
||||
&& pos.0.y <= dest_max_y
|
||||
&& pos.0.z >= dest_min_z
|
||||
&& pos.0.z <= dest_max_z
|
||||
};
|
||||
|
||||
if self.clone_mode == CloneMode::Move {
|
||||
for block in &blocks_to_clone {
|
||||
if !is_dest_pos(&block.src_pos) {
|
||||
world.set_block_state(
|
||||
&block.src_pos,
|
||||
BlockStateId::AIR,
|
||||
BlockFlags::NOTIFY_ALL,
|
||||
);
|
||||
}
|
||||
if !is_dest_pos(&block.src_pos) {
|
||||
world.set_block_state(
|
||||
&block.src_pos,
|
||||
BlockStateId::AIR,
|
||||
BlockFlags::NOTIFY_ALL,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLONE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_CLONE_SUCCESS,
|
||||
[TextComponent::text(count.to_string())],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLONE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_CLONE_SUCCESS,
|
||||
[TextComponent::text(count.to_string())],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
Ok(count)
|
||||
})
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ const fn amount_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
struct LocationExecutor;
|
||||
struct EntityExecutor(bool);
|
||||
|
||||
async fn send_damage_result(
|
||||
fn send_damage_result(
|
||||
sender: &CommandSender,
|
||||
success: bool,
|
||||
amount: f32,
|
||||
@@ -46,89 +46,77 @@ async fn send_damage_result(
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DAMAGE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_DAMAGE_SUCCESS,
|
||||
[TextComponent::text(amount.to_string()), target_name],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DAMAGE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_DAMAGE_SUCCESS,
|
||||
[TextComponent::text(amount.to_string()), target_name],
|
||||
));
|
||||
|
||||
Ok(1) // not arbitrary, this is what vanilla does
|
||||
}
|
||||
|
||||
impl CommandExecutor for LocationExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
|
||||
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
||||
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
||||
|
||||
let damage_type =
|
||||
args.get(ARG_DAMAGE_TYPE)
|
||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||
Arg::DamageType(dt) => *dt,
|
||||
_ => DamageType::GENERIC,
|
||||
});
|
||||
let damage_type = args
|
||||
.get(ARG_DAMAGE_TYPE)
|
||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||
Arg::DamageType(dt) => *dt,
|
||||
_ => DamageType::GENERIC,
|
||||
});
|
||||
|
||||
let location = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
let location = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
|
||||
let success = target.damage_with_context(
|
||||
&*target,
|
||||
amount,
|
||||
damage_type,
|
||||
Some(location),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let success =
|
||||
target.damage_with_context(&*target, amount, damage_type, Some(location), None, None);
|
||||
|
||||
send_damage_result(sender, success, amount, target.get_display_name()).await
|
||||
})
|
||||
send_damage_result(sender, success, amount, target.get_display_name())
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandExecutor for EntityExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
|
||||
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
||||
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
||||
|
||||
let damage_type =
|
||||
args.get(ARG_DAMAGE_TYPE)
|
||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||
Arg::DamageType(dt) => *dt,
|
||||
_ => DamageType::GENERIC,
|
||||
});
|
||||
let damage_type = args
|
||||
.get(ARG_DAMAGE_TYPE)
|
||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||
Arg::DamageType(dt) => *dt,
|
||||
_ => DamageType::GENERIC,
|
||||
});
|
||||
|
||||
let source = EntityArgumentConsumer::find_arg(args, ARG_ENTITY).ok();
|
||||
let cause = if self.0 {
|
||||
EntityArgumentConsumer::find_arg(args, ARG_CAUSE).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let source = EntityArgumentConsumer::find_arg(args, ARG_ENTITY).ok();
|
||||
let cause = if self.0 {
|
||||
EntityArgumentConsumer::find_arg(args, ARG_CAUSE).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let success = target.damage_with_context(
|
||||
&*target,
|
||||
amount,
|
||||
damage_type,
|
||||
None,
|
||||
source.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||
cause.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||
);
|
||||
let success = target.damage_with_context(
|
||||
&*target,
|
||||
amount,
|
||||
damage_type,
|
||||
None,
|
||||
source.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||
cause.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||
);
|
||||
|
||||
send_damage_result(sender, success, amount, target.get_display_name()).await
|
||||
})
|
||||
send_damage_result(sender, success, amount, target.get_display_name())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,18 +22,16 @@ const ARG_ENTITY: &str = "entity";
|
||||
struct GetEntityDataExecutor;
|
||||
|
||||
impl CommandExecutor for GetEntityDataExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Entity(entity)) = args.get(&ARG_ENTITY) else {
|
||||
return Err(InvalidConsumption(Some(ARG_ENTITY.into())));
|
||||
};
|
||||
display_data(entity.as_ref(), entity.get_display_name(), sender).await
|
||||
})
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Entity(entity)) = args.get(&ARG_ENTITY) else {
|
||||
return Err(InvalidConsumption(Some(ARG_ENTITY.into())));
|
||||
};
|
||||
display_data(entity.as_ref(), entity.get_display_name(), sender)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,7 +214,7 @@ pub fn snbt_colorful_display(tag: &NbtTag, depth: usize) -> Result<TextComponent
|
||||
}
|
||||
}
|
||||
|
||||
async fn display_data(
|
||||
fn display_data(
|
||||
entity: &dyn EntityBase,
|
||||
target_name: TextComponent,
|
||||
sender: &CommandSender,
|
||||
@@ -228,13 +226,11 @@ async fn display_data(
|
||||
let result = get_i32_result(&tag)?;
|
||||
let display = snbt_colorful_display(&tag, 0)
|
||||
.map_err(|string| CommandError::CommandFailed(TextComponent::text(string)))?;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||
[target_name, display],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||
[target_name, display],
|
||||
));
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -137,58 +137,54 @@ fn format_pack(name: &str) -> TextComponent {
|
||||
struct AvailablePackSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for AvailablePackSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn suggest(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
for pack in get_available_packs(server) {
|
||||
if pack.contains(' ') || pack.contains('/') {
|
||||
builder = builder.suggest(format!("\"{pack}\""));
|
||||
) -> SuggestionProviderResult {
|
||||
let server = context.server();
|
||||
for pack in get_available_packs(server) {
|
||||
if pack.contains(' ') || pack.contains('/') {
|
||||
builder = builder.suggest(format!("\"{pack}\""));
|
||||
} else {
|
||||
builder = builder.suggest(pack.clone());
|
||||
}
|
||||
if let Some(short) = pack.strip_prefix("file/") {
|
||||
if short.contains(' ') {
|
||||
builder = builder.suggest(format!("\"{short}\""));
|
||||
} else {
|
||||
builder = builder.suggest(pack.clone());
|
||||
}
|
||||
if let Some(short) = pack.strip_prefix("file/") {
|
||||
if short.contains(' ') {
|
||||
builder = builder.suggest(format!("\"{short}\""));
|
||||
} else {
|
||||
builder = builder.suggest(short.to_string());
|
||||
}
|
||||
builder = builder.suggest(short.to_string());
|
||||
}
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
struct EnabledPackSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for EnabledPackSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn suggest(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
for pack in get_enabled_packs(server) {
|
||||
if pack.contains(' ') || pack.contains('/') {
|
||||
builder = builder.suggest(format!("\"{pack}\""));
|
||||
) -> SuggestionProviderResult {
|
||||
let server = context.server();
|
||||
for pack in get_enabled_packs(server) {
|
||||
if pack.contains(' ') || pack.contains('/') {
|
||||
builder = builder.suggest(format!("\"{pack}\""));
|
||||
} else {
|
||||
builder = builder.suggest(pack.clone());
|
||||
}
|
||||
if let Some(short) = pack.strip_prefix("file/") {
|
||||
if short.contains(' ') {
|
||||
builder = builder.suggest(format!("\"{short}\""));
|
||||
} else {
|
||||
builder = builder.suggest(pack.clone());
|
||||
}
|
||||
if let Some(short) = pack.strip_prefix("file/") {
|
||||
if short.contains(' ') {
|
||||
builder = builder.suggest(format!("\"{short}\""));
|
||||
} else {
|
||||
builder = builder.suggest(short.to_string());
|
||||
}
|
||||
builder = builder.suggest(short.to_string());
|
||||
}
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,94 +198,80 @@ enum ListFilter {
|
||||
struct DatapackListExecutor(ListFilter);
|
||||
|
||||
impl CommandExecutor for DatapackListExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
let enabled = get_enabled_packs(server);
|
||||
let available = get_available_packs(server);
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let server = context.server();
|
||||
let enabled = get_enabled_packs(server);
|
||||
let available = get_available_packs(server);
|
||||
|
||||
match self.0 {
|
||||
ListFilter::All => {
|
||||
send_enabled_list(context, &enabled).await;
|
||||
send_available_list(context, &available).await;
|
||||
Ok(enabled.len() as i32)
|
||||
}
|
||||
ListFilter::Enabled => {
|
||||
send_enabled_list(context, &enabled).await;
|
||||
Ok(enabled.len() as i32)
|
||||
}
|
||||
ListFilter::Available => {
|
||||
send_available_list(context, &available).await;
|
||||
Ok(available.len() as i32)
|
||||
}
|
||||
match self.0 {
|
||||
ListFilter::All => {
|
||||
send_enabled_list(context, &enabled);
|
||||
send_available_list(context, &available);
|
||||
Ok(enabled.len() as i32)
|
||||
}
|
||||
})
|
||||
ListFilter::Enabled => {
|
||||
send_enabled_list(context, &enabled);
|
||||
Ok(enabled.len() as i32)
|
||||
}
|
||||
ListFilter::Available => {
|
||||
send_available_list(context, &available);
|
||||
Ok(available.len() as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_enabled_list(context: &CommandContext<'_>, enabled: &[String]) {
|
||||
fn send_enabled_list(context: &CommandContext<'_>, enabled: &[String]) {
|
||||
if enabled.is_empty() {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
let packs_component =
|
||||
TextComponent::join_with_comma(enabled.iter().map(|p| format_pack(p)).collect());
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
||||
[
|
||||
TextComponent::text(enabled.len().to_string()),
|
||||
packs_component,
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
||||
[
|
||||
TextComponent::text(enabled.len().to_string()),
|
||||
packs_component,
|
||||
],
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_available_list(context: &CommandContext<'_>, available: &[String]) {
|
||||
fn send_available_list(context: &CommandContext<'_>, available: &[String]) {
|
||||
if available.is_empty() {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
let packs_component =
|
||||
TextComponent::join_with_comma(available.iter().map(|p| format_pack(p)).collect());
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(available.len().to_string()),
|
||||
packs_component,
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(available.len().to_string()),
|
||||
packs_component,
|
||||
],
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,60 +284,55 @@ enum EnablePosition {
|
||||
struct DatapackEnableExecutor(EnablePosition);
|
||||
|
||||
impl CommandExecutor for DatapackEnableExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let server = context.server();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let server = context.server();
|
||||
|
||||
let Some(resolved_name) = find_pack_name(server, name_str) else {
|
||||
return Err(ERROR_UNKNOWN_DATAPACK
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
let Some(resolved_name) = find_pack_name(server, name_str) else {
|
||||
return Err(ERROR_UNKNOWN_DATAPACK
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
|
||||
let enabled = get_enabled_packs(server);
|
||||
if enabled.contains(&resolved_name) {
|
||||
return Err(
|
||||
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(resolved_name))
|
||||
);
|
||||
}
|
||||
let enabled = get_enabled_packs(server);
|
||||
if enabled.contains(&resolved_name) {
|
||||
return Err(
|
||||
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(resolved_name))
|
||||
);
|
||||
}
|
||||
|
||||
let target = resolved_name.clone();
|
||||
let pos = self.0;
|
||||
server.level_info.rcu(|level_info| {
|
||||
let mut new_info = (**level_info).clone();
|
||||
new_info.data_packs.disabled.retain(|p| p != &target);
|
||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||
match pos {
|
||||
EnablePosition::First => {
|
||||
new_info.data_packs.enabled.insert(0, target.clone());
|
||||
}
|
||||
EnablePosition::Last => {
|
||||
new_info.data_packs.enabled.push(target.clone());
|
||||
}
|
||||
let target = resolved_name.clone();
|
||||
let pos = self.0;
|
||||
server.level_info.rcu(|level_info| {
|
||||
let mut new_info = (**level_info).clone();
|
||||
new_info.data_packs.disabled.retain(|p| p != &target);
|
||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||
match pos {
|
||||
EnablePosition::First => {
|
||||
new_info.data_packs.enabled.insert(0, target.clone());
|
||||
}
|
||||
EnablePosition::Last => {
|
||||
new_info.data_packs.enabled.push(target.clone());
|
||||
}
|
||||
new_info
|
||||
});
|
||||
|
||||
if let Err(err) = server.save_world_info() {
|
||||
error!("Failed to save world info: {err}");
|
||||
}
|
||||
new_info
|
||||
});
|
||||
|
||||
server.reload_datapacks(server).await;
|
||||
if let Err(err) = server.save_world_info() {
|
||||
error!("Failed to save world info: {err}");
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
[format_pack(&resolved_name)],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
server.reload_datapacks(server);
|
||||
|
||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||
})
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
[format_pack(&resolved_name)],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,140 +345,130 @@ enum BeforeOrAfter {
|
||||
struct DatapackEnableExistingExecutor(BeforeOrAfter);
|
||||
|
||||
impl CommandExecutor for DatapackEnableExistingExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let existing_str = StringArgumentType::get(context, "existing")?;
|
||||
let server = context.server();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let existing_str = StringArgumentType::get(context, "existing")?;
|
||||
let server = context.server();
|
||||
|
||||
let Some(target_pack) = find_pack_name(server, name_str) else {
|
||||
return Err(ERROR_UNKNOWN_DATAPACK
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
let Some(target_pack) = find_pack_name(server, name_str) else {
|
||||
return Err(ERROR_UNKNOWN_DATAPACK
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
|
||||
let Some(existing_pack) = find_pack_name(server, existing_str) else {
|
||||
return Err(ERROR_UNKNOWN_DATAPACK
|
||||
.create_without_context(TextComponent::text(existing_str.to_string())));
|
||||
};
|
||||
let Some(existing_pack) = find_pack_name(server, existing_str) else {
|
||||
return Err(ERROR_UNKNOWN_DATAPACK
|
||||
.create_without_context(TextComponent::text(existing_str.to_string())));
|
||||
};
|
||||
|
||||
let enabled = get_enabled_packs(server);
|
||||
if enabled.contains(&target_pack) {
|
||||
return Err(
|
||||
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(target_pack))
|
||||
);
|
||||
}
|
||||
let enabled = get_enabled_packs(server);
|
||||
if enabled.contains(&target_pack) {
|
||||
return Err(
|
||||
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(target_pack))
|
||||
);
|
||||
}
|
||||
|
||||
if !enabled.contains(&existing_pack) {
|
||||
return Err(
|
||||
ERROR_DISABLE_FAILED.create_without_context(TextComponent::text(existing_pack))
|
||||
);
|
||||
}
|
||||
if !enabled.contains(&existing_pack) {
|
||||
return Err(
|
||||
ERROR_DISABLE_FAILED.create_without_context(TextComponent::text(existing_pack))
|
||||
);
|
||||
}
|
||||
|
||||
let target = target_pack.clone();
|
||||
let existing = existing_pack.clone();
|
||||
let before_or_after = self.0;
|
||||
server.level_info.rcu(|level_info| {
|
||||
let mut new_info = (**level_info).clone();
|
||||
new_info.data_packs.disabled.retain(|p| p != &target);
|
||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||
let target = target_pack.clone();
|
||||
let existing = existing_pack;
|
||||
let before_or_after = self.0;
|
||||
server.level_info.rcu(|level_info| {
|
||||
let mut new_info = (**level_info).clone();
|
||||
new_info.data_packs.disabled.retain(|p| p != &target);
|
||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||
|
||||
if let Some(idx) = new_info
|
||||
if let Some(idx) = new_info
|
||||
.data_packs
|
||||
.enabled
|
||||
.iter()
|
||||
.position(|p| p == &existing)
|
||||
{
|
||||
let insert_pos = match before_or_after {
|
||||
BeforeOrAfter::Before => idx,
|
||||
BeforeOrAfter::After => idx + 1,
|
||||
};
|
||||
new_info
|
||||
.data_packs
|
||||
.enabled
|
||||
.iter()
|
||||
.position(|p| p == &existing)
|
||||
{
|
||||
let insert_pos = match before_or_after {
|
||||
BeforeOrAfter::Before => idx,
|
||||
BeforeOrAfter::After => idx + 1,
|
||||
};
|
||||
new_info
|
||||
.data_packs
|
||||
.enabled
|
||||
.insert(insert_pos, target.clone());
|
||||
} else {
|
||||
new_info.data_packs.enabled.push(target.clone());
|
||||
}
|
||||
new_info
|
||||
});
|
||||
|
||||
if let Err(err) = server.save_world_info() {
|
||||
error!("Failed to save world info: {err}");
|
||||
.insert(insert_pos, target.clone());
|
||||
} else {
|
||||
new_info.data_packs.enabled.push(target.clone());
|
||||
}
|
||||
new_info
|
||||
});
|
||||
|
||||
server.reload_datapacks(server).await;
|
||||
if let Err(err) = server.save_world_info() {
|
||||
error!("Failed to save world info: {err}");
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
[format_pack(&target_pack)],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
server.reload_datapacks(server);
|
||||
|
||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||
})
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||
[format_pack(&target_pack)],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
struct DatapackDisableExecutor;
|
||||
|
||||
impl CommandExecutor for DatapackDisableExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let server = context.server();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let server = context.server();
|
||||
|
||||
let Some(target_pack) = find_pack_name(server, name_str) else {
|
||||
return Err(ERROR_DISABLE_FAILED
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
let Some(target_pack) = find_pack_name(server, name_str) else {
|
||||
return Err(ERROR_DISABLE_FAILED
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
|
||||
let enabled = get_enabled_packs(server);
|
||||
if !enabled.contains(&target_pack) {
|
||||
return Err(ERROR_DISABLE_FAILED
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
let enabled = get_enabled_packs(server);
|
||||
if !enabled.contains(&target_pack) {
|
||||
return Err(ERROR_DISABLE_FAILED
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
if target_pack == "vanilla" {
|
||||
return Err(ERROR_DISABLE_FAILED
|
||||
.create_without_context(TextComponent::text("vanilla".to_string())));
|
||||
}
|
||||
|
||||
let target = target_pack.clone();
|
||||
server.level_info.rcu(|level_info| {
|
||||
let mut new_info = (**level_info).clone();
|
||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||
if !new_info.data_packs.disabled.contains(&target) {
|
||||
new_info.data_packs.disabled.push(target.clone());
|
||||
}
|
||||
new_info
|
||||
});
|
||||
|
||||
if target_pack == "vanilla" {
|
||||
return Err(ERROR_DISABLE_FAILED
|
||||
.create_without_context(TextComponent::text("vanilla".to_string())));
|
||||
}
|
||||
if let Err(err) = server.save_world_info() {
|
||||
error!("Failed to save world info: {err}");
|
||||
}
|
||||
|
||||
let target = target_pack.clone();
|
||||
server.level_info.rcu(|level_info| {
|
||||
let mut new_info = (**level_info).clone();
|
||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||
if !new_info.data_packs.disabled.contains(&target) {
|
||||
new_info.data_packs.disabled.push(target.clone());
|
||||
}
|
||||
new_info
|
||||
});
|
||||
server.reload_datapacks(server);
|
||||
|
||||
if let Err(err) = server.save_world_info() {
|
||||
error!("Failed to save world info: {err}");
|
||||
}
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
||||
[format_pack(&target_pack)],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
server.reload_datapacks(server).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
||||
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
||||
[format_pack(&target_pack)],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||
})
|
||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,69 +485,64 @@ fn is_valid_pack_name(name: &str) -> bool {
|
||||
struct DatapackCreateExecutor;
|
||||
|
||||
impl CommandExecutor for DatapackCreateExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let description = StringArgumentType::get(context, "description").unwrap_or(name_str);
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let description = StringArgumentType::get(context, "description").unwrap_or(name_str);
|
||||
|
||||
if !is_valid_pack_name(name_str) {
|
||||
return Err(ERROR_CREATE_INVALID_NAME
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
if !is_valid_pack_name(name_str) {
|
||||
return Err(ERROR_CREATE_INVALID_NAME
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
let server = context.server();
|
||||
let datapacks_dir = server.basic_config.get_world_path().join("datapacks");
|
||||
let pack_dir = datapacks_dir.join(name_str);
|
||||
|
||||
if pack_dir.exists() {
|
||||
return Err(ERROR_CREATE_ALREADY_EXISTS
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
let data_dir = pack_dir.join("data");
|
||||
if let Err(err) = fs::create_dir_all(&data_dir) {
|
||||
error!("Failed to create datapack directory: {err}");
|
||||
return Err(ERROR_CREATE_IO_FAILURE
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
let mcmeta_content = serde_json::json!({
|
||||
"pack": {
|
||||
"pack_format": 61,
|
||||
"description": description
|
||||
}
|
||||
});
|
||||
|
||||
let server = context.server();
|
||||
let datapacks_dir = server.basic_config.get_world_path().join("datapacks");
|
||||
let pack_dir = datapacks_dir.join(name_str);
|
||||
|
||||
if pack_dir.exists() {
|
||||
return Err(ERROR_CREATE_ALREADY_EXISTS
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
let data_dir = pack_dir.join("data");
|
||||
if let Err(err) = fs::create_dir_all(&data_dir) {
|
||||
error!("Failed to create datapack directory: {err}");
|
||||
let mcmeta_path = pack_dir.join("pack.mcmeta");
|
||||
let mcmeta_str = match serde_json::to_string_pretty(&mcmeta_content) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
error!("Failed to serialize pack.mcmeta: {err}");
|
||||
return Err(ERROR_CREATE_IO_FAILURE
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
};
|
||||
|
||||
let mcmeta_content = serde_json::json!({
|
||||
"pack": {
|
||||
"pack_format": 61,
|
||||
"description": description
|
||||
}
|
||||
});
|
||||
if let Err(err) = fs::write(&mcmeta_path, mcmeta_str) {
|
||||
error!("Failed to write pack.mcmeta: {err}");
|
||||
return Err(ERROR_CREATE_IO_FAILURE
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
let mcmeta_path = pack_dir.join("pack.mcmeta");
|
||||
let mcmeta_str = match serde_json::to_string_pretty(&mcmeta_content) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
error!("Failed to serialize pack.mcmeta: {err}");
|
||||
return Err(ERROR_CREATE_IO_FAILURE
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
};
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
||||
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
||||
[TextComponent::text(name_str.to_string())],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
if let Err(err) = fs::write(&mcmeta_path, mcmeta_str) {
|
||||
error!("Failed to write pack.mcmeta: {err}");
|
||||
return Err(ERROR_CREATE_IO_FAILURE
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
||||
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
||||
[TextComponent::text(name_str.to_string())],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,70 +29,63 @@ const NOT_RUNNING_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
struct DebugStartExecutor;
|
||||
|
||||
impl CommandExecutor for DebugStartExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
||||
server.debug_profiler.start(current_tick).map_err(
|
||||
|StartDebugProfileError::AlreadyRunning| {
|
||||
ALREADY_RUNNING_ERROR_TYPE.create_without_context()
|
||||
},
|
||||
)?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let server = context.server();
|
||||
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
||||
server.debug_profiler.start(current_tick).map_err(
|
||||
|StartDebugProfileError::AlreadyRunning| {
|
||||
ALREADY_RUNNING_ERROR_TYPE.create_without_context()
|
||||
},
|
||||
)?;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DEBUG_STARTED,
|
||||
translation::bedrock::COMMANDS_DEBUG_START,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DEBUG_STARTED,
|
||||
translation::bedrock::COMMANDS_DEBUG_START,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct DebugStopExecutor;
|
||||
|
||||
impl CommandExecutor for DebugStopExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
||||
let result = server.debug_profiler.stop(current_tick).map_err(
|
||||
|StopDebugProfileError::NotRunning| NOT_RUNNING_ERROR_TYPE.create_without_context(),
|
||||
)?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let server = context.server();
|
||||
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
||||
let result = server.debug_profiler.stop(current_tick).map_err(
|
||||
|StopDebugProfileError::NotRunning| NOT_RUNNING_ERROR_TYPE.create_without_context(),
|
||||
)?;
|
||||
|
||||
let seconds = result.duration.as_secs_f64();
|
||||
let tps = result.ticks_per_second();
|
||||
let arguments = [
|
||||
TextComponent::text(format!("{seconds:.2}")),
|
||||
TextComponent::text(result.ticks.to_string()),
|
||||
TextComponent::text(format!("{tps:.2}")),
|
||||
];
|
||||
let feedback = if matches!(context.source.output, CommandSender::Player(_)) {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DEBUG_STOPPED,
|
||||
translation::bedrock::COMMANDS_DEBUG_STOP,
|
||||
arguments,
|
||||
)
|
||||
} else {
|
||||
// Bedrock's debug-stop translation uses printf-style placeholders that the
|
||||
// server-side console renderer cannot resolve. Non-player command sources need
|
||||
// an already-rendered message; players still receive their native translation.
|
||||
TextComponent::text(format!(
|
||||
"Stopped tick profiling after {seconds:.2} second(s) and {} tick(s) ({tps:.2} tick(s) per second)",
|
||||
result.ticks
|
||||
))
|
||||
};
|
||||
context.source.send_feedback(feedback, true).await;
|
||||
let seconds = result.duration.as_secs_f64();
|
||||
let tps = result.ticks_per_second();
|
||||
let arguments = [
|
||||
TextComponent::text(format!("{seconds:.2}")),
|
||||
TextComponent::text(result.ticks.to_string()),
|
||||
TextComponent::text(format!("{tps:.2}")),
|
||||
];
|
||||
let feedback = if matches!(context.source.output, CommandSender::Player(_)) {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DEBUG_STOPPED,
|
||||
translation::bedrock::COMMANDS_DEBUG_STOP,
|
||||
arguments,
|
||||
)
|
||||
} else {
|
||||
// Bedrock's debug-stop translation uses printf-style placeholders that the
|
||||
// server-side console renderer cannot resolve. Non-player command sources need
|
||||
// an already-rendered message; players still receive their native translation.
|
||||
TextComponent::text(format!(
|
||||
"Stopped tick profiling after {seconds:.2} second(s) and {} tick(s) ({tps:.2} tick(s) per second)",
|
||||
result.ticks
|
||||
))
|
||||
};
|
||||
context.source.send_feedback(feedback, true);
|
||||
|
||||
Ok(result.command_result())
|
||||
})
|
||||
Ok(result.command_result())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,46 +20,43 @@ pub struct DefaultGamemode {
|
||||
struct DefaultGamemodeExecutor;
|
||||
|
||||
impl CommandExecutor for DefaultGamemodeExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||
};
|
||||
|
||||
let mut successful_changes: i32 = 0;
|
||||
if server.basic_config.force_gamemode {
|
||||
for player in server.get_all_players() {
|
||||
if player.set_gamemode(gamemode).await {
|
||||
successful_changes += 1;
|
||||
}
|
||||
let mut successful_changes: i32 = 0;
|
||||
if server.basic_config.force_gamemode {
|
||||
for player in server.get_all_players() {
|
||||
if player.gamemode.load() != gamemode {
|
||||
player.set_gamemode(gamemode);
|
||||
successful_changes += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||
[TextComponent::translate_cross(
|
||||
gamemode_string.clone(),
|
||||
gamemode_string,
|
||||
[],
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||
[TextComponent::translate_cross(
|
||||
gamemode_string.clone(),
|
||||
gamemode_string,
|
||||
[],
|
||||
)],
|
||||
));
|
||||
|
||||
//Change the default gamemode (not in configuration.toml)
|
||||
server.defaultgamemode.lock().await.gamemode = gamemode;
|
||||
//Change the default gamemode (not in configuration.toml)
|
||||
server.defaultgamemode.lock().unwrap().gamemode = gamemode;
|
||||
|
||||
Ok(successful_changes)
|
||||
})
|
||||
Ok(successful_changes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,59 +21,57 @@ const ARG_TARGETS: &str = "targets";
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut config = server.data.operator_config.write().await;
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let mut config = server.data.operator_config.write().unwrap();
|
||||
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let mut succeeded_deops: i32 = 0;
|
||||
for profile in targets {
|
||||
if let Some(op_index) = config.ops.iter().position(|o| o.uuid == profile.id) {
|
||||
config.ops.remove(op_index);
|
||||
succeeded_deops += 1;
|
||||
let mut succeeded_deops: i32 = 0;
|
||||
for profile in targets {
|
||||
if let Some(op_index) = config.ops.iter().position(|o| o.uuid == profile.id) {
|
||||
config.ops.remove(op_index);
|
||||
succeeded_deops += 1;
|
||||
|
||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
||||
let command_dispatcher = server.command_dispatcher.load();
|
||||
player
|
||||
.set_permission_lvl(
|
||||
server,
|
||||
pumpkin_util::PermissionLvl::Zero,
|
||||
&command_dispatcher,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEOP_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_SUCCESS,
|
||||
[TextComponent::text(profile.name.clone())],
|
||||
if let Some(player) = server.get_player_by_uuid(profile.id)
|
||||
&& let Some(server_arc) = player.world().server.upgrade()
|
||||
{
|
||||
let command_dispatcher = server_arc.command_dispatcher.load();
|
||||
player.set_permission_lvl(
|
||||
&server_arc,
|
||||
pumpkin_util::PermissionLvl::Zero,
|
||||
&command_dispatcher,
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
}
|
||||
}
|
||||
|
||||
if succeeded_deops > 0 {
|
||||
config.save();
|
||||
let msg = TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEOP_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_SUCCESS,
|
||||
[TextComponent::text(profile.name.clone())],
|
||||
);
|
||||
sender.send_message(msg);
|
||||
}
|
||||
}
|
||||
|
||||
if succeeded_deops == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEOP_FAILED,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_FAILED,
|
||||
[],
|
||||
)))
|
||||
} else {
|
||||
Ok(succeeded_deops)
|
||||
}
|
||||
})
|
||||
if succeeded_deops > 0 {
|
||||
config.save();
|
||||
}
|
||||
|
||||
if succeeded_deops == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEOP_FAILED,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_FAILED,
|
||||
[],
|
||||
)))
|
||||
} else {
|
||||
Ok(succeeded_deops)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,28 +21,26 @@ const ARG_DIALOG: &str = "dialog";
|
||||
struct DialogClearExecutor;
|
||||
|
||||
impl CommandExecutor for DialogClearExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS)?;
|
||||
|
||||
let count = targets.len();
|
||||
let packet = CPlayClearDialog::new();
|
||||
for player in &targets {
|
||||
player.send_client_packet(&packet).await;
|
||||
}
|
||||
let count = targets.len();
|
||||
let packet = CPlayClearDialog::new();
|
||||
for player in &targets {
|
||||
player.try_send_client_packet(&packet);
|
||||
}
|
||||
|
||||
let msg = if count == 1 {
|
||||
TextComponent::text(format!(
|
||||
"Cleared dialog for {}",
|
||||
targets[0].gameprofile.name
|
||||
))
|
||||
} else {
|
||||
TextComponent::text(format!("Cleared dialogs for {count} players"))
|
||||
};
|
||||
context.source.send_feedback(msg, true).await;
|
||||
let msg = if count == 1 {
|
||||
TextComponent::text(format!(
|
||||
"Cleared dialog for {}",
|
||||
targets[0].gameprofile.name
|
||||
))
|
||||
} else {
|
||||
TextComponent::text(format!("Cleared dialogs for {count} players"))
|
||||
};
|
||||
context.source.send_feedback(msg, true);
|
||||
|
||||
Ok(count as i32)
|
||||
})
|
||||
Ok(count as i32)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,36 +51,31 @@ static REGISTRY_ERROR: LiteralCommandErrorType = LiteralCommandErrorType::new(
|
||||
struct DialogShowExecutor;
|
||||
|
||||
impl CommandExecutor for DialogShowExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
||||
let dialog_arg = DialogArgumentType::get(context, ARG_DIALOG)?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS)?;
|
||||
let dialog_arg = DialogArgumentType::get(context, ARG_DIALOG)?;
|
||||
|
||||
match dialog_arg {
|
||||
DialogArg::Nbt(compound) => {
|
||||
let count = targets.len();
|
||||
let dialog_nbt = DialogNBT::from_nbt(compound);
|
||||
let packet = CPlayShowDialog::new(IdOr::Value(dialog_nbt));
|
||||
match dialog_arg {
|
||||
DialogArg::Nbt(compound) => {
|
||||
let count = targets.len();
|
||||
let dialog_nbt = DialogNBT::from_nbt(compound);
|
||||
let packet = CPlayShowDialog::new(IdOr::Value(dialog_nbt));
|
||||
|
||||
for player in &targets {
|
||||
player.send_client_packet(&packet).await;
|
||||
}
|
||||
|
||||
let msg = if count == 1 {
|
||||
TextComponent::text(format!(
|
||||
"Showed dialog to {}",
|
||||
targets[0].gameprofile.name
|
||||
))
|
||||
} else {
|
||||
TextComponent::text(format!("Showed dialog to {count} players"))
|
||||
};
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(count as i32)
|
||||
for player in &targets {
|
||||
player.try_send_client_packet(&packet);
|
||||
}
|
||||
DialogArg::Id(_id) => Err(REGISTRY_ERROR.create_without_context()),
|
||||
|
||||
let msg = if count == 1 {
|
||||
TextComponent::text(format!("Showed dialog to {}", targets[0].gameprofile.name))
|
||||
} else {
|
||||
TextComponent::text(format!("Showed dialog to {count} players"))
|
||||
};
|
||||
context.source.send_feedback(msg, true);
|
||||
|
||||
Ok(count as i32)
|
||||
}
|
||||
})
|
||||
DialogArg::Id(_id) => Err(REGISTRY_ERROR.create_without_context()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,68 +17,58 @@ const FAILURE_ERROR_TYPE: CommandErrorType<1> =
|
||||
struct DifficultyQueryExecutor;
|
||||
|
||||
impl CommandExecutor for DifficultyQueryExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let difficulty = context.server().get_difficulty();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let difficulty = context.server().get_difficulty();
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
"commands.difficulty.query",
|
||||
"commands.difficulty.query",
|
||||
[TextComponent::translate_cross(
|
||||
difficulty.translation_key(),
|
||||
difficulty.translation_key(),
|
||||
[],
|
||||
)],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
"commands.difficulty.query",
|
||||
"commands.difficulty.query",
|
||||
[TextComponent::translate_cross(
|
||||
difficulty.translation_key(),
|
||||
difficulty.translation_key(),
|
||||
[],
|
||||
)],
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
Ok(difficulty as i32)
|
||||
})
|
||||
Ok(difficulty as i32)
|
||||
}
|
||||
}
|
||||
|
||||
struct DifficultySetExecutor(Difficulty);
|
||||
|
||||
impl CommandExecutor for DifficultySetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let difficulty = self.0;
|
||||
let server = context.server();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let difficulty = self.0;
|
||||
let server = context.server();
|
||||
|
||||
{
|
||||
let level_info = server.level_info.load();
|
||||
{
|
||||
let level_info = server.level_info.load();
|
||||
|
||||
if level_info.difficulty == difficulty {
|
||||
return Err(FAILURE_ERROR_TYPE
|
||||
.create_without_context(TextComponent::text(difficulty.name())));
|
||||
}
|
||||
if level_info.difficulty == difficulty {
|
||||
return Err(FAILURE_ERROR_TYPE
|
||||
.create_without_context(TextComponent::text(difficulty.name())));
|
||||
}
|
||||
}
|
||||
|
||||
server.set_difficulty(difficulty, true);
|
||||
server.set_difficulty(difficulty, true);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DIFFICULTY_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DIFFICULTY_SUCCESS,
|
||||
[TextComponent::translate_cross(
|
||||
difficulty.translation_key(),
|
||||
difficulty.translation_key(),
|
||||
[],
|
||||
)],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DIFFICULTY_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DIFFICULTY_SUCCESS,
|
||||
[TextComponent::translate_cross(
|
||||
difficulty.translation_key(),
|
||||
difficulty.translation_key(),
|
||||
[],
|
||||
)],
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
Ok(0)
|
||||
})
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,219 +38,210 @@ enum Amplifier {
|
||||
struct GiveExecutor(Time, Amplifier, bool);
|
||||
|
||||
impl CommandExecutor for GiveExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
let Some(Arg::Effect(effect)) = args.get(ARG_EFFECT) else {
|
||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
let Some(Arg::Effect(effect)) = args.get(ARG_EFFECT) else {
|
||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||
};
|
||||
|
||||
//duration is in tick, so * 20 (not for the infinite because -1*20 cause visual glitch)
|
||||
let second = match self.0 {
|
||||
Time::Base => 30 * 20,
|
||||
Time::Specified => {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("seconds")
|
||||
.min(1)
|
||||
.max(1_000_000)
|
||||
.find_arg_default_name(args)??
|
||||
* 20
|
||||
}
|
||||
Time::Infinite => -1,
|
||||
};
|
||||
|
||||
let amplifier: u8 = match self.1 {
|
||||
Amplifier::Base => 0,
|
||||
Amplifier::Specified => BoundedNumArgumentConsumer::<i32>::new()
|
||||
.name("amplifier")
|
||||
.min(0)
|
||||
.max(255)
|
||||
.find_arg_default_name(args)?? as u8,
|
||||
};
|
||||
|
||||
let mut hide_particles = self.2;
|
||||
//if false -> parameter is referred
|
||||
if !hide_particles {
|
||||
let Some(Arg::Bool(hide_particle)) = args.get(ARG_HIDE_PARTICLE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_HIDE_PARTICLE.into())));
|
||||
};
|
||||
|
||||
hide_particles = *hide_particle;
|
||||
//duration is in tick, so * 20 (not for the infinite because -1*20 cause visual glitch)
|
||||
let second = match self.0 {
|
||||
Time::Base => 30 * 20,
|
||||
Time::Specified => {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("seconds")
|
||||
.min(1)
|
||||
.max(1_000_000)
|
||||
.find_arg_default_name(args)??
|
||||
* 20
|
||||
}
|
||||
Time::Infinite => -1,
|
||||
};
|
||||
|
||||
let mut successes = 0;
|
||||
let amplifier: u8 = match self.1 {
|
||||
Amplifier::Base => 0,
|
||||
Amplifier::Specified => BoundedNumArgumentConsumer::<i32>::new()
|
||||
.name("amplifier")
|
||||
.min(0)
|
||||
.max(255)
|
||||
.find_arg_default_name(args)?? as u8,
|
||||
};
|
||||
|
||||
for target in targets {
|
||||
let should_skip = target
|
||||
.living_entity
|
||||
.get_effect(effect)
|
||||
.is_some_and(|existing| existing.amplifier >= amplifier);
|
||||
let mut hide_particles = self.2;
|
||||
//if false -> parameter is referred
|
||||
if !hide_particles {
|
||||
let Some(Arg::Bool(hide_particle)) = args.get(ARG_HIDE_PARTICLE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_HIDE_PARTICLE.into())));
|
||||
};
|
||||
|
||||
if !should_skip {
|
||||
target.add_effect(Effect {
|
||||
effect_type: effect,
|
||||
duration: second,
|
||||
amplifier,
|
||||
ambient: false, //this is not a beacon effect
|
||||
show_particles: !hide_particles,
|
||||
show_icon: true,
|
||||
blend: false,
|
||||
});
|
||||
successes += 1;
|
||||
}
|
||||
hide_particles = *hide_particle;
|
||||
}
|
||||
|
||||
let mut successes = 0;
|
||||
|
||||
for target in targets {
|
||||
let should_skip = target
|
||||
.living_entity
|
||||
.get_effect(effect)
|
||||
.is_some_and(|existing| existing.amplifier >= amplifier);
|
||||
|
||||
if !should_skip {
|
||||
target.add_effect(Effect {
|
||||
effect_type: effect,
|
||||
duration: second,
|
||||
amplifier,
|
||||
ambient: false, //this is not a beacon effect
|
||||
show_particles: !hide_particles,
|
||||
show_icon: true,
|
||||
blend: false,
|
||||
});
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let translation_name = TextComponent::translate_cross(
|
||||
effect.translation_key.to_string(),
|
||||
effect.translation_key.to_string(),
|
||||
let translation_name = TextComponent::translate_cross(
|
||||
effect.translation_key.to_string(),
|
||||
effect.translation_key.to_string(),
|
||||
[],
|
||||
);
|
||||
|
||||
if successes == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.give.failed",
|
||||
"commands.effect.give.failed",
|
||||
[],
|
||||
);
|
||||
)));
|
||||
} else if targets.len() == 1 {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.give.success.single",
|
||||
"commands.effect.give.success.single",
|
||||
[translation_name, targets[0].get_display_name()],
|
||||
));
|
||||
} else {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.give.success.multiple",
|
||||
"commands.effect.give.success.multiple",
|
||||
[
|
||||
translation_name,
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
));
|
||||
}
|
||||
|
||||
if successes == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.give.failed",
|
||||
"commands.effect.give.failed",
|
||||
[],
|
||||
)));
|
||||
} else if targets.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.give.success.single",
|
||||
"commands.effect.give.success.single",
|
||||
[translation_name, targets[0].get_display_name()],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.give.success.multiple",
|
||||
"commands.effect.give.success.multiple",
|
||||
[
|
||||
translation_name,
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(successes)
|
||||
})
|
||||
Ok(successes)
|
||||
}
|
||||
}
|
||||
|
||||
struct ClearExecutor(bool); //the param -> true = delete every effect, false = only one
|
||||
|
||||
impl CommandExecutor for ClearExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let effect;
|
||||
//Only one effect
|
||||
if self.0 {
|
||||
let mut succeeded_clears: i32 = 0;
|
||||
for target in targets {
|
||||
let has_effects = !target
|
||||
.living_entity
|
||||
.active_effects
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.is_empty();
|
||||
if has_effects {
|
||||
target.remove_all_effects();
|
||||
succeeded_clears += 1;
|
||||
}
|
||||
}
|
||||
|
||||
//if the player or everyplayer don't have any effect
|
||||
if succeeded_clears == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.failed",
|
||||
"commands.effect.clear.everything.failed",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
//a player have at least 1 effect
|
||||
else if targets.len() == 1 {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.success.single",
|
||||
"commands.effect.clear.everything.success.single",
|
||||
[targets[0].get_display_name()],
|
||||
));
|
||||
} else {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.success.multiple",
|
||||
"commands.effect.clear.everything.success.multiple",
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
));
|
||||
}
|
||||
Ok(succeeded_clears)
|
||||
} else {
|
||||
let Some(Arg::Effect(effect_type)) = args.get(ARG_EFFECT) else {
|
||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||
};
|
||||
|
||||
let effect;
|
||||
//Only one effect
|
||||
if self.0 {
|
||||
let mut succeeded_clears: i32 = 0;
|
||||
for target in targets {
|
||||
if target.remove_all_effects().await {
|
||||
succeeded_clears += 1;
|
||||
}
|
||||
}
|
||||
effect = *effect_type;
|
||||
|
||||
//if the player or everyplayer don't have any effect
|
||||
if succeeded_clears == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.failed",
|
||||
"commands.effect.clear.everything.failed",
|
||||
[],
|
||||
)));
|
||||
let mut succeeded_clears: i32 = 0;
|
||||
for target in targets {
|
||||
if target.living_entity.has_effect(effect) {
|
||||
target.remove_effect(effect);
|
||||
succeeded_clears += 1;
|
||||
}
|
||||
//a player have at least 1 effect
|
||||
else if targets.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.success.single",
|
||||
"commands.effect.clear.everything.success.single",
|
||||
[targets[0].get_display_name()],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.success.multiple",
|
||||
"commands.effect.clear.everything.success.multiple",
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
Ok(succeeded_clears)
|
||||
} else {
|
||||
let Some(Arg::Effect(effect_type)) = args.get(ARG_EFFECT) else {
|
||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||
};
|
||||
|
||||
effect = *effect_type;
|
||||
|
||||
let mut succeeded_clears: i32 = 0;
|
||||
for target in targets {
|
||||
if target.living_entity.has_effect(effect) {
|
||||
target.remove_effect(effect).await;
|
||||
succeeded_clears += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if succeeded_clears == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.failed",
|
||||
"commands.effect.clear.specific.failed",
|
||||
[],
|
||||
)));
|
||||
} else if targets.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.success.single",
|
||||
"commands.effect.clear.specific.success.single",
|
||||
[
|
||||
TextComponent::translate_cross(
|
||||
effect.translation_key,
|
||||
effect.translation_key,
|
||||
[],
|
||||
),
|
||||
targets[0].get_display_name(),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
[
|
||||
TextComponent::translate_cross(
|
||||
effect.translation_key,
|
||||
effect.translation_key,
|
||||
[],
|
||||
),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
Ok(succeeded_clears)
|
||||
}
|
||||
})
|
||||
|
||||
if succeeded_clears == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.failed",
|
||||
"commands.effect.clear.specific.failed",
|
||||
[],
|
||||
)));
|
||||
} else if targets.len() == 1 {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.success.single",
|
||||
"commands.effect.clear.specific.success.single",
|
||||
[
|
||||
TextComponent::translate_cross(
|
||||
effect.translation_key,
|
||||
effect.translation_key,
|
||||
[],
|
||||
),
|
||||
targets[0].get_display_name(),
|
||||
],
|
||||
));
|
||||
} else {
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
[
|
||||
TextComponent::translate_cross(
|
||||
effect.translation_key,
|
||||
effect.translation_key,
|
||||
[],
|
||||
),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
));
|
||||
}
|
||||
Ok(succeeded_clears)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,95 +18,93 @@ const DESCRIPTION: &str = "Adds an enchantment to a player's selected item, subj
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer.find_arg_default_name(args)?;
|
||||
let enchantment = EnchantmentArgumentConsumer.find_arg_default_name(args)?;
|
||||
let level = match enchantment_level_consumer().find_arg_default_name(args) {
|
||||
Err(_) => 1,
|
||||
Ok(Ok(level)) => level,
|
||||
Ok(Err(err)) => {
|
||||
let err_msg = match err {
|
||||
NotInBounds::LowerBound(val, min) => TextComponent::translate_cross(
|
||||
"argument.integer.low",
|
||||
"argument.integer.low",
|
||||
&[
|
||||
TextComponent::text(min.to_string()),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
NotInBounds::UpperBound(val, max) => TextComponent::translate_cross(
|
||||
"argument.integer.big",
|
||||
"argument.integer.big",
|
||||
&[
|
||||
TextComponent::text(max.to_string()),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
};
|
||||
|
||||
return Err(CommandError::CommandFailed(err_msg));
|
||||
}
|
||||
};
|
||||
|
||||
if level > enchantment.max_level {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_FAILED_LEVEL,
|
||||
translation::bedrock::COMMANDS_ENCHANT_INVALIDLEVEL,
|
||||
[
|
||||
TextComponent::text(level.to_string()),
|
||||
TextComponent::text(enchantment.max_level.to_string()),
|
||||
],
|
||||
);
|
||||
return Err(CommandError::CommandFailed(msg));
|
||||
}
|
||||
|
||||
let mut successful_targets = 0;
|
||||
|
||||
if targets.len() == 1 {
|
||||
return match enchant_target(&targets[0], enchantment, level).await {
|
||||
Ok(()) => {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
||||
[
|
||||
enchantment.get_fullname(level),
|
||||
targets[0].get_display_name(),
|
||||
],
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
Ok(1)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let targets = EntitiesArgumentConsumer.find_arg_default_name(args)?;
|
||||
let enchantment = EnchantmentArgumentConsumer.find_arg_default_name(args)?;
|
||||
let level = match enchantment_level_consumer().find_arg_default_name(args) {
|
||||
Err(_) => 1,
|
||||
Ok(Ok(level)) => level,
|
||||
Ok(Err(err)) => {
|
||||
let err_msg = match err {
|
||||
NotInBounds::LowerBound(val, min) => TextComponent::translate_cross(
|
||||
"argument.integer.low",
|
||||
"argument.integer.low",
|
||||
&[
|
||||
TextComponent::text(min.to_string()),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
NotInBounds::UpperBound(val, max) => TextComponent::translate_cross(
|
||||
"argument.integer.big",
|
||||
"argument.integer.big",
|
||||
&[
|
||||
TextComponent::text(max.to_string()),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
for target in targets {
|
||||
if enchant_target(target, enchantment, level).await.is_ok() {
|
||||
successful_targets += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successful_targets == 0 {
|
||||
return Err(commands_enchant_failed());
|
||||
return Err(CommandError::CommandFailed(err_msg));
|
||||
}
|
||||
};
|
||||
|
||||
if level > enchantment.max_level {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
||||
translation::java::COMMANDS_ENCHANT_FAILED_LEVEL,
|
||||
translation::bedrock::COMMANDS_ENCHANT_INVALIDLEVEL,
|
||||
[
|
||||
enchantment.get_fullname(level),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
TextComponent::text(level.to_string()),
|
||||
TextComponent::text(enchantment.max_level.to_string()),
|
||||
],
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
Ok(successful_targets)
|
||||
})
|
||||
return Err(CommandError::CommandFailed(msg));
|
||||
}
|
||||
|
||||
let mut successful_targets = 0;
|
||||
|
||||
if targets.len() == 1 {
|
||||
return match enchant_target(&targets[0], enchantment, level) {
|
||||
Ok(()) => {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
||||
[
|
||||
enchantment.get_fullname(level),
|
||||
targets[0].get_display_name(),
|
||||
],
|
||||
);
|
||||
sender.send_message(msg);
|
||||
Ok(1)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
}
|
||||
|
||||
for target in targets {
|
||||
if enchant_target(target, enchantment, level).is_ok() {
|
||||
successful_targets += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successful_targets == 0 {
|
||||
return Err(commands_enchant_failed());
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
||||
[
|
||||
enchantment.get_fullname(level),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
);
|
||||
sender.send_message(msg);
|
||||
Ok(successful_targets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,7 +124,7 @@ fn commands_enchant_failed() -> CommandError {
|
||||
CommandError::CommandFailed(msg)
|
||||
}
|
||||
|
||||
async fn enchant_target(
|
||||
fn enchant_target(
|
||||
target: &Arc<dyn EntityBase>,
|
||||
enchantment: &'static Enchantment,
|
||||
level: i32,
|
||||
|
||||
@@ -31,365 +31,316 @@ static ERROR_INVALID_DIMENSION: CommandErrorType<1> =
|
||||
|
||||
static DIMENSION_REGISTRY: &Identifier = &Identifier::vanilla_static("dimension");
|
||||
|
||||
fn execute_as_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
fn execute_as_modifier(context: &CommandContext) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
let display_name = target.get_display_name();
|
||||
let name = target.get_name().get_text();
|
||||
source.entity = Some(target.clone());
|
||||
source.name = name;
|
||||
source.display_name = display_name;
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn execute_at_modifier(context: &CommandContext) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let entity = target.get_entity();
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = entity.pos.load();
|
||||
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||
source.world = Some(entity.world.load().clone());
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn execute_in_modifier(context: &CommandContext) -> crate::command::node::RedirectModifierResult {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
let server = context.server();
|
||||
let worlds = server.worlds.load();
|
||||
let target_world = worlds
|
||||
.iter()
|
||||
.find(|w| w.dimension.minecraft_name == dimension_name);
|
||||
|
||||
target_world.map_or_else(
|
||||
|| Err(ERROR_INVALID_DIMENSION.create_without_context(TextComponent::text(dimension_name))),
|
||||
|target_world| {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
let display_name = target.get_display_name();
|
||||
let name = target.get_name().get_text();
|
||||
source.entity = Some(target.clone());
|
||||
source.name = name;
|
||||
source.display_name = display_name;
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
source.world = Some(target_world.clone());
|
||||
Ok(vec![Arc::new(source)])
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn execute_at_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let entity = target.get_entity();
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = entity.pos.load();
|
||||
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||
source.world = Some(entity.world.load().clone());
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
fn execute_positioned_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = pos;
|
||||
Ok(vec![Arc::new(source)])
|
||||
}
|
||||
|
||||
fn execute_in_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
let server = context.server();
|
||||
let worlds = server.worlds.load();
|
||||
let target_world = worlds
|
||||
.iter()
|
||||
.find(|w| w.dimension.minecraft_name == dimension_name);
|
||||
|
||||
target_world.map_or_else(
|
||||
|| {
|
||||
Err(ERROR_INVALID_DIMENSION
|
||||
.create_without_context(TextComponent::text(dimension_name)))
|
||||
},
|
||||
|target_world| {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.world = Some(target_world.clone());
|
||||
Ok(vec![Arc::new(source)])
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_positioned_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||
fn execute_positioned_as_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = pos;
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
source.position = target.get_entity().pos.load();
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn execute_positioned_as_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = target.get_entity().pos.load();
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
fn execute_rotated_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let rot_coords = RotationArgumentType::get(context, "rotation")?;
|
||||
let rot = rot_coords.rotation(&context.source);
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.rotation = rot;
|
||||
Ok(vec![Arc::new(source)])
|
||||
}
|
||||
|
||||
fn execute_rotated_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let rot_coords = RotationArgumentType::get(context, "rotation")?;
|
||||
let rot = rot_coords.rotation(&context.source);
|
||||
fn execute_rotated_as_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let entity = target.get_entity();
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.rotation = rot;
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn execute_rotated_as_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let entity = target.get_entity();
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
fn execute_if_entity_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
if targets.is_empty() {
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Ok(vec![context.source.clone()])
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_if_entity_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
if targets.is_empty() {
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Ok(vec![context.source.clone()])
|
||||
}
|
||||
})
|
||||
fn execute_unless_entity_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
if targets.is_empty() {
|
||||
Ok(vec![context.source.clone()])
|
||||
} else {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_unless_entity_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
if targets.is_empty() {
|
||||
Ok(vec![context.source.clone()])
|
||||
} else {
|
||||
Ok(vec![])
|
||||
}
|
||||
})
|
||||
fn execute_align_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let axes = StringArgumentType::get(context, "axes")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let has_x = axes.contains('x');
|
||||
let has_y = axes.contains('y');
|
||||
let has_z = axes.contains('z');
|
||||
|
||||
if has_x {
|
||||
source.position.x = source.position.x.floor();
|
||||
}
|
||||
if has_y {
|
||||
source.position.y = source.position.y.floor();
|
||||
}
|
||||
if has_z {
|
||||
source.position.z = source.position.z.floor();
|
||||
}
|
||||
|
||||
Ok(vec![Arc::new(source)])
|
||||
}
|
||||
|
||||
fn execute_align_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let axes = StringArgumentType::get(context, "axes")?;
|
||||
fn execute_anchored_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.entity_anchor = anchor;
|
||||
Ok(vec![Arc::new(source)])
|
||||
}
|
||||
|
||||
fn execute_facing_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let dx = pos.x - source.position.x;
|
||||
let dy = pos.y - source.position.y;
|
||||
let dz = pos.z - source.position.z;
|
||||
|
||||
let xz_dist = dx.hypot(dz);
|
||||
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
||||
|
||||
source.rotation = Vector2::new(yaw, pitch);
|
||||
Ok(vec![Arc::new(source)])
|
||||
}
|
||||
|
||||
fn execute_facing_entity_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||
let mut sources = Vec::new();
|
||||
|
||||
for target in targets {
|
||||
let target_pos = anchor.position_at_entity(target.get_entity());
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let has_x = axes.contains('x');
|
||||
let has_y = axes.contains('y');
|
||||
let has_z = axes.contains('z');
|
||||
|
||||
if has_x {
|
||||
source.position.x = source.position.x.floor();
|
||||
}
|
||||
if has_y {
|
||||
source.position.y = source.position.y.floor();
|
||||
}
|
||||
if has_z {
|
||||
source.position.z = source.position.z.floor();
|
||||
}
|
||||
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_anchored_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.entity_anchor = anchor;
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_facing_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let dx = pos.x - source.position.x;
|
||||
let dy = pos.y - source.position.y;
|
||||
let dz = pos.z - source.position.z;
|
||||
let dx = target_pos.x - source.position.x;
|
||||
let dy = target_pos.y - source.position.y;
|
||||
let dz = target_pos.z - source.position.z;
|
||||
|
||||
let xz_dist = dx.hypot(dz);
|
||||
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
||||
|
||||
source.rotation = Vector2::new(yaw, pitch);
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn execute_facing_entity_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||
let mut sources = Vec::new();
|
||||
fn execute_if_block_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||
|
||||
for target in targets {
|
||||
let target_pos = anchor.position_at_entity(target.get_entity());
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let dx = target_pos.x - source.position.x;
|
||||
let dy = target_pos.y - source.position.y;
|
||||
let dz = target_pos.z - source.position.z;
|
||||
|
||||
let xz_dist = dx.hypot(dz);
|
||||
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
||||
|
||||
source.rotation = Vector2::new(yaw, pitch);
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_if_block_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
let block = world.get_block(&pos);
|
||||
if block == expected_block {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_unless_block_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
let block = world.get_block(&pos);
|
||||
if block != expected_block {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
} else {
|
||||
if let Some(ref world) = context.source.world {
|
||||
let block = world.get_block(&pos);
|
||||
if block == expected_block {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
fn execute_if_loaded_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
fn execute_unless_block_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||
|
||||
if let Some(ref world) = context.source.world
|
||||
&& world.is_loaded(&pos)
|
||||
{
|
||||
if let Some(ref world) = context.source.world {
|
||||
let block = world.get_block(&pos);
|
||||
if block != expected_block {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
fn execute_unless_loaded_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
fn execute_if_loaded_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
if !world.is_loaded(&pos) {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
} else {
|
||||
if let Some(ref world) = context.source.world
|
||||
&& world.is_loaded(&pos)
|
||||
{
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
fn execute_unless_loaded_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
if !world.is_loaded(&pos) {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
fn execute_if_dimension_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
fn execute_if_dimension_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
|
||||
if let Some(ref world) = context.source.world
|
||||
&& world.dimension.minecraft_name == dimension_name
|
||||
{
|
||||
if let Some(ref world) = context.source.world
|
||||
&& world.dimension.minecraft_name == dimension_name
|
||||
{
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
fn execute_unless_dimension_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
if world.dimension.minecraft_name != dimension_name {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
fn execute_unless_dimension_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
if world.dimension.minecraft_name != dimension_name {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_summon_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let entity_type = ResourceArgument::get_summonable_entity_type(context, "entity_type")?;
|
||||
let entity = from_type(
|
||||
entity_type,
|
||||
context.source.position,
|
||||
context.source.world(),
|
||||
Uuid::new_v4(),
|
||||
);
|
||||
context.source.world().spawn_entity(entity.clone());
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.entity = Some(entity);
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
fn execute_summon_modifier(
|
||||
context: &CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult {
|
||||
let entity_type = ResourceArgument::get_summonable_entity_type(context, "entity_type")?;
|
||||
let entity = from_type(
|
||||
entity_type,
|
||||
context.source.position,
|
||||
context.source.world(),
|
||||
Uuid::new_v4(),
|
||||
);
|
||||
context.source.world().spawn_entity(entity.clone());
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.entity = Some(entity);
|
||||
Ok(vec![Arc::new(source)])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
|
||||
@@ -45,7 +45,7 @@ struct Executor {
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
async fn handle_query(&self, sender: &CommandSender, target: &Player) -> i32 {
|
||||
fn handle_query(&self, sender: &CommandSender, target: &Player) -> i32 {
|
||||
let (val, translation_key) = match self.exp_type {
|
||||
ExpType::Levels => (
|
||||
target.experience_level.load(Ordering::Relaxed),
|
||||
@@ -57,16 +57,14 @@ impl Executor {
|
||||
),
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation_key,
|
||||
translation_key,
|
||||
[
|
||||
target.get_display_name(),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation_key,
|
||||
translation_key,
|
||||
[
|
||||
target.get_display_name(),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
));
|
||||
|
||||
val
|
||||
}
|
||||
@@ -122,7 +120,7 @@ impl Executor {
|
||||
}
|
||||
|
||||
/// Returns `true` if successful. Otherwise, there was a problem setting the points of a player.
|
||||
async fn handle_modify(&self, target: &Arc<Player>, amount: i32) -> bool {
|
||||
fn handle_modify(&self, target: &Arc<Player>, amount: i32) -> bool {
|
||||
match self.exp_type {
|
||||
ExpType::Levels => {
|
||||
if self.mode == Mode::Add {
|
||||
@@ -148,59 +146,57 @@ impl Executor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
_server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let targets = PlayersArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
if self.mode == Mode::Query {
|
||||
let target = targets.first().ok_or_else(|| {
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"argument.player.unknown",
|
||||
"argument.player.unknown",
|
||||
[],
|
||||
))
|
||||
})?;
|
||||
if self.mode == Mode::Query {
|
||||
let target = targets.first().ok_or_else(|| {
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"argument.player.unknown",
|
||||
"argument.player.unknown",
|
||||
[],
|
||||
))
|
||||
})?;
|
||||
|
||||
if targets.len() > 1 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"argument.player.toomany",
|
||||
"argument.player.toomany",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
return Ok(self.handle_query(sender, target).await);
|
||||
}
|
||||
|
||||
// Handle Add/Set
|
||||
let amount = BoundedNumArgumentConsumer::<i32>::find_arg(args, ARG_AMOUNT)??;
|
||||
|
||||
let mut successes = 0;
|
||||
for target in targets {
|
||||
if self.handle_modify(target, amount).await {
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successes == 0 {
|
||||
if targets.len() > 1 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.experience.set.points.invalid",
|
||||
"commands.experience.set.points.invalid",
|
||||
"argument.player.toomany",
|
||||
"argument.player.toomany",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
return Ok(self.handle_query(sender, target));
|
||||
}
|
||||
|
||||
// Safe to access first() because successes > 0
|
||||
let first_name = targets[0].get_display_name();
|
||||
let msg = self.get_success_message(amount, targets, first_name);
|
||||
sender.send_message(msg).await;
|
||||
// Handle Add/Set
|
||||
let amount = BoundedNumArgumentConsumer::<i32>::find_arg(args, ARG_AMOUNT)??;
|
||||
|
||||
Ok(successes)
|
||||
})
|
||||
let mut successes = 0;
|
||||
for target in targets {
|
||||
if self.handle_modify(target, amount) {
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successes == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.experience.set.points.invalid",
|
||||
"commands.experience.set.points.invalid",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
// Safe to access first() because successes > 0
|
||||
let first_name = targets[0].get_display_name();
|
||||
let msg = self.get_success_message(amount, targets, first_name);
|
||||
sender.send_message(msg);
|
||||
|
||||
Ok(successes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ fn format_clickable_list(items: Vec<TextComponent>) -> TextComponent {
|
||||
root
|
||||
}
|
||||
|
||||
async fn report_resolved_profile(
|
||||
fn report_resolved_profile(
|
||||
source: &CommandSource,
|
||||
profile: &GameProfile,
|
||||
message_id: &'static str,
|
||||
@@ -139,7 +139,7 @@ async fn report_resolved_profile(
|
||||
|
||||
let msg = TextComponent::translate_cross(message_id, message_id, [argument, clickable]);
|
||||
|
||||
source.send_feedback(msg, false).await;
|
||||
source.send_feedback(msg, false);
|
||||
}
|
||||
|
||||
async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<GameProfile> {
|
||||
@@ -147,7 +147,7 @@ async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<Gam
|
||||
return Some(player.gameprofile.clone());
|
||||
}
|
||||
|
||||
let cached_entry = server.data.user_cache.write().await.get_by_name(name);
|
||||
let cached_entry = server.data.user_cache.write().unwrap().get_by_name(name);
|
||||
|
||||
let auth_config = server
|
||||
.advanced_config
|
||||
@@ -169,7 +169,7 @@ async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<Gam
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap()
|
||||
.upsert(uuid, resolved_name.clone());
|
||||
let auth_config_clone = server
|
||||
.advanced_config
|
||||
@@ -214,7 +214,7 @@ async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<Gam
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap()
|
||||
.upsert(uuid, name.to_string());
|
||||
return Some(profile);
|
||||
}
|
||||
@@ -244,12 +244,12 @@ async fn fetch_profile_by_id_helper(server: &Server, id: Uuid) -> Option<GamePro
|
||||
.data
|
||||
.user_cache
|
||||
.write()
|
||||
.await
|
||||
.unwrap()
|
||||
.upsert(profile.id, profile.name.clone());
|
||||
return Some(profile);
|
||||
}
|
||||
|
||||
let cached_entry = server.data.user_cache.write().await.get_by_uuid(id);
|
||||
let cached_entry = server.data.user_cache.write().unwrap().get_by_uuid(id);
|
||||
if let Some(entry) = cached_entry {
|
||||
return Some(GameProfile {
|
||||
id: entry.uuid,
|
||||
@@ -265,102 +265,84 @@ async fn fetch_profile_by_id_helper(server: &Server, id: Uuid) -> Option<GamePro
|
||||
struct ResolveNameExecutor;
|
||||
|
||||
impl CommandExecutor for ResolveNameExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let name = StringArgumentType::get(context, ARG_NAME)?;
|
||||
let server = context.server().clone();
|
||||
let source = context.source.clone();
|
||||
let name_owned = name.to_string();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let name = StringArgumentType::get(context, ARG_NAME)?;
|
||||
let server = context.server();
|
||||
let name_owned = name.to_string();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let name_component = TextComponent::text(name_owned.clone());
|
||||
let result = fetch_profile_by_name_helper(&server, &name_owned).await;
|
||||
match result {
|
||||
Some(profile) => {
|
||||
report_resolved_profile(
|
||||
&source,
|
||||
&profile,
|
||||
translation::java::COMMANDS_FETCHPROFILE_NAME_SUCCESS,
|
||||
name_component,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
None => {
|
||||
source
|
||||
.send_error(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
||||
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
||||
[name_component],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
});
|
||||
let name_component = TextComponent::text(name_owned.clone());
|
||||
let result = futures::executor::block_on(fetch_profile_by_name_helper(server, &name_owned));
|
||||
match result {
|
||||
Some(profile) => {
|
||||
report_resolved_profile(
|
||||
&context.source,
|
||||
&profile,
|
||||
translation::java::COMMANDS_FETCHPROFILE_NAME_SUCCESS,
|
||||
name_component,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
context.source.send_error(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
||||
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
||||
[name_component],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct ResolveIdExecutor;
|
||||
|
||||
impl CommandExecutor for ResolveIdExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let id = UuidArgumentType::get(context, ARG_ID)?;
|
||||
let server = context.server().clone();
|
||||
let source = context.source.clone();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let id = UuidArgumentType::get(context, ARG_ID)?;
|
||||
let server = context.server();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let id_component = TextComponent::text(id.to_string());
|
||||
let result = fetch_profile_by_id_helper(&server, id).await;
|
||||
match result {
|
||||
Some(profile) => {
|
||||
report_resolved_profile(
|
||||
&source,
|
||||
&profile,
|
||||
translation::java::COMMANDS_FETCHPROFILE_ID_SUCCESS,
|
||||
id_component,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
None => {
|
||||
source
|
||||
.send_error(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
||||
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
||||
[id_component],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
});
|
||||
let id_component = TextComponent::text(id.to_string());
|
||||
let result = futures::executor::block_on(fetch_profile_by_id_helper(server, id));
|
||||
match result {
|
||||
Some(profile) => {
|
||||
report_resolved_profile(
|
||||
&context.source,
|
||||
&profile,
|
||||
translation::java::COMMANDS_FETCHPROFILE_ID_SUCCESS,
|
||||
id_component,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
context.source.send_error(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
||||
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
||||
[id_component],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct PrintForEntityExecutor;
|
||||
|
||||
impl CommandExecutor for PrintForEntityExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let entity = EntityArgumentType::get_entity(context, ARG_ENTITY).await?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let entity = EntityArgumentType::get_entity(context, ARG_ENTITY)?;
|
||||
|
||||
if let Some(player) = entity.get_player() {
|
||||
entity.get_player().map_or_else(
|
||||
|| Err(NO_PROFILE_ERROR_TYPE.create_without_context(entity.get_display_name())),
|
||||
|player| {
|
||||
report_resolved_profile(
|
||||
&context.source,
|
||||
&player.gameprofile,
|
||||
translation::java::COMMANDS_FETCHPROFILE_ENTITY_SUCCESS,
|
||||
player.get_display_name(),
|
||||
)
|
||||
.await;
|
||||
);
|
||||
Ok(1)
|
||||
} else {
|
||||
Err(NO_PROFILE_ERROR_TYPE.create_without_context(entity.get_display_name()))
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -236,96 +236,92 @@ impl Filler for StrictFiller {
|
||||
}
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let block = BlockArgumentConsumer::find_arg(args, ARG_BLOCK)?;
|
||||
let block_state_id = block.default_state.id;
|
||||
let from = BlockPosArgumentConsumer::find_arg(args, ARG_FROM)?;
|
||||
let to = BlockPosArgumentConsumer::find_arg(args, ARG_TO)?;
|
||||
let mode = self.0;
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let block = BlockArgumentConsumer::find_arg(args, ARG_BLOCK)?;
|
||||
let block_state_id = block.default_state.id;
|
||||
let from = BlockPosArgumentConsumer::find_arg(args, ARG_FROM)?;
|
||||
let to = BlockPosArgumentConsumer::find_arg(args, ARG_TO)?;
|
||||
let mode = self.0;
|
||||
|
||||
let mut context = Context {
|
||||
block_state_id,
|
||||
option_filter: BlockPredicateArgumentConsumer::find_arg(args, ARG_FILTER)?,
|
||||
world: sender
|
||||
.world_or_first(server)
|
||||
.ok_or(CommandError::InvalidRequirement)?,
|
||||
placed_blocks: 0,
|
||||
to_update: Vec::new(),
|
||||
let mut context = Context {
|
||||
block_state_id,
|
||||
option_filter: BlockPredicateArgumentConsumer::find_arg(args, ARG_FILTER)?,
|
||||
world: sender
|
||||
.world_or_first(server)
|
||||
.ok_or(CommandError::InvalidRequirement)?,
|
||||
placed_blocks: 0,
|
||||
to_update: Vec::new(),
|
||||
|
||||
start_x: from.0.x.min(to.0.x),
|
||||
start_y: from.0.y.min(to.0.y),
|
||||
start_z: from.0.z.min(to.0.z),
|
||||
start_x: from.0.x.min(to.0.x),
|
||||
start_y: from.0.y.min(to.0.y),
|
||||
start_z: from.0.z.min(to.0.z),
|
||||
|
||||
end_x: from.0.x.max(to.0.x),
|
||||
end_y: from.0.y.max(to.0.y),
|
||||
end_z: from.0.z.max(to.0.z),
|
||||
};
|
||||
end_x: from.0.x.max(to.0.x),
|
||||
end_y: from.0.y.max(to.0.y),
|
||||
end_z: from.0.z.max(to.0.z),
|
||||
};
|
||||
|
||||
if !context.world.is_in_build_limit(from) || !context.world.is_in_build_limit(to) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
if !context.world.is_in_build_limit(from) || !context.world.is_in_build_limit(to) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let max_block_modifications = {
|
||||
let level_info = server.level_info.load();
|
||||
level_info.game_rules.max_block_modifications
|
||||
};
|
||||
let max_block_modifications = {
|
||||
let level_info = server.level_info.load();
|
||||
level_info.game_rules.max_block_modifications
|
||||
};
|
||||
|
||||
let total_blocks = (context.end_x - context.start_x + 1) as i64
|
||||
* (context.end_y - context.start_y + 1) as i64
|
||||
* (context.end_z - context.start_z + 1) as i64;
|
||||
let total_blocks = (context.end_x - context.start_x + 1) as i64
|
||||
* (context.end_y - context.start_y + 1) as i64
|
||||
* (context.end_z - context.start_z + 1) as i64;
|
||||
|
||||
if total_blocks > max_block_modifications {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_TOOBIG,
|
||||
translation::java::COMMANDS_FILL_TOOBIG,
|
||||
[
|
||||
TextComponent::text(max_block_modifications.to_string()),
|
||||
TextComponent::text(total_blocks.to_string()),
|
||||
],
|
||||
)));
|
||||
}
|
||||
if total_blocks > max_block_modifications {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_TOOBIG,
|
||||
translation::java::COMMANDS_FILL_TOOBIG,
|
||||
[
|
||||
TextComponent::text(max_block_modifications.to_string()),
|
||||
TextComponent::text(total_blocks.to_string()),
|
||||
],
|
||||
)));
|
||||
}
|
||||
|
||||
match mode {
|
||||
Mode::Destroy => DestroyFiller::execute_for_region(&mut context),
|
||||
Mode::Replace => ReplaceFiller::execute_for_region(&mut context),
|
||||
Mode::Keep => KeepFiller::execute_for_region(&mut context),
|
||||
Mode::Hollow => HollowFiller::execute_for_region(&mut context),
|
||||
Mode::Outline => OutlineFiller::execute_for_region(&mut context),
|
||||
Mode::Strict => StrictFiller::execute_for_region(&mut context),
|
||||
}
|
||||
match mode {
|
||||
Mode::Destroy => DestroyFiller::execute_for_region(&mut context),
|
||||
Mode::Replace => ReplaceFiller::execute_for_region(&mut context),
|
||||
Mode::Keep => KeepFiller::execute_for_region(&mut context),
|
||||
Mode::Hollow => HollowFiller::execute_for_region(&mut context),
|
||||
Mode::Outline => OutlineFiller::execute_for_region(&mut context),
|
||||
Mode::Strict => StrictFiller::execute_for_region(&mut context),
|
||||
}
|
||||
|
||||
for i in context.to_update {
|
||||
context.world.update_neighbors(&i, None);
|
||||
}
|
||||
for i in context.to_update {
|
||||
context.world.update_neighbors(&i, None);
|
||||
}
|
||||
|
||||
if context.placed_blocks == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_FAILED,
|
||||
translation::bedrock::COMMANDS_FILL_FAILED,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
if context.placed_blocks == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_FAILED,
|
||||
translation::bedrock::COMMANDS_FILL_FAILED,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_SUCCESS,
|
||||
translation::bedrock::COMMANDS_FILL_SUCCESS,
|
||||
[TextComponent::text(context.placed_blocks.to_string())],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_SUCCESS,
|
||||
translation::bedrock::COMMANDS_FILL_SUCCESS,
|
||||
[TextComponent::text(context.placed_blocks.to_string())],
|
||||
));
|
||||
|
||||
Ok(context.placed_blocks)
|
||||
})
|
||||
Ok(context.placed_blocks)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,96 +31,85 @@ struct FillBiomeExecutor {
|
||||
|
||||
impl CommandExecutor for FillBiomeExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let from_pos = BlockPosArgumentType::get_block_pos(context, "from")?;
|
||||
let to_pos = BlockPosArgumentType::get_block_pos(context, "to")?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let from_pos = BlockPosArgumentType::get_block_pos(context, "from")?;
|
||||
let to_pos = BlockPosArgumentType::get_block_pos(context, "to")?;
|
||||
|
||||
let world = context.world();
|
||||
if !world.is_in_build_limit(from_pos) || !world.is_in_build_limit(to_pos) {
|
||||
return Err(OUT_OF_BOUNDS_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
let world = context.world();
|
||||
if !world.is_in_build_limit(from_pos) || !world.is_in_build_limit(to_pos) {
|
||||
return Err(OUT_OF_BOUNDS_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
let min_x = from_pos.0.x.min(to_pos.0.x);
|
||||
let max_x = from_pos.0.x.max(to_pos.0.x);
|
||||
let min_y = from_pos.0.y.min(to_pos.0.y);
|
||||
let max_y = from_pos.0.y.max(to_pos.0.y);
|
||||
let min_z = from_pos.0.z.min(to_pos.0.z);
|
||||
let max_z = from_pos.0.z.max(to_pos.0.z);
|
||||
let min_x = from_pos.0.x.min(to_pos.0.x);
|
||||
let max_x = from_pos.0.x.max(to_pos.0.x);
|
||||
let min_y = from_pos.0.y.min(to_pos.0.y);
|
||||
let max_y = from_pos.0.y.max(to_pos.0.y);
|
||||
let min_z = from_pos.0.z.min(to_pos.0.z);
|
||||
let max_z = from_pos.0.z.max(to_pos.0.z);
|
||||
|
||||
let biome_min_x = min_x >> 2;
|
||||
let biome_max_x = max_x >> 2;
|
||||
let biome_min_y = min_y >> 2;
|
||||
let biome_max_y = max_y >> 2;
|
||||
let biome_min_z = min_z >> 2;
|
||||
let biome_max_z = max_z >> 2;
|
||||
let biome_min_x = min_x >> 2;
|
||||
let biome_max_x = max_x >> 2;
|
||||
let biome_min_y = min_y >> 2;
|
||||
let biome_max_y = max_y >> 2;
|
||||
let biome_min_z = min_z >> 2;
|
||||
let biome_max_z = max_z >> 2;
|
||||
|
||||
let volume = (biome_max_x - biome_min_x + 1) as i64
|
||||
* (biome_max_y - biome_min_y + 1) as i64
|
||||
* (biome_max_z - biome_min_z + 1) as i64;
|
||||
let volume = (biome_max_x - biome_min_x + 1) as i64
|
||||
* (biome_max_y - biome_min_y + 1) as i64
|
||||
* (biome_max_z - biome_min_z + 1) as i64;
|
||||
|
||||
if volume > MAX_BIOME_BLOCKS {
|
||||
return Err(ERROR_TOOBIG.create_without_context_args_slice(&[
|
||||
TextComponent::text(MAX_BIOME_BLOCKS.to_string()),
|
||||
TextComponent::text(volume.to_string()),
|
||||
]));
|
||||
}
|
||||
if volume > MAX_BIOME_BLOCKS {
|
||||
return Err(ERROR_TOOBIG.create_without_context_args_slice(&[
|
||||
TextComponent::text(MAX_BIOME_BLOCKS.to_string()),
|
||||
TextComponent::text(volume.to_string()),
|
||||
]));
|
||||
}
|
||||
|
||||
let target_biome = ResourceKeyArgument::get_biome(context, "biome")?;
|
||||
let target_biome = ResourceKeyArgument::get_biome(context, "biome")?;
|
||||
|
||||
let replace_biome = if self.has_replace {
|
||||
Some(ResourceKeyArgument::get_biome(context, "replace_biome")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let replace_biome = if self.has_replace {
|
||||
Some(ResourceKeyArgument::get_biome(context, "replace_biome")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut chunk_modifications: HashMap<Vector2<i32>, Vec<(usize, usize, usize)>> =
|
||||
HashMap::new();
|
||||
for y in biome_min_y..=biome_max_y {
|
||||
for z in biome_min_z..=biome_max_z {
|
||||
for x in biome_min_x..=biome_max_x {
|
||||
let chunk_pos = Vector2::new(x >> 2, z >> 2);
|
||||
let rel_x = (x & 3) as usize;
|
||||
let rel_z = (z & 3) as usize;
|
||||
let rel_y = (y - (world.min_y >> 2)) as usize;
|
||||
chunk_modifications
|
||||
.entry(chunk_pos)
|
||||
.or_default()
|
||||
.push((rel_x, rel_y, rel_z));
|
||||
}
|
||||
let mut chunk_modifications: HashMap<Vector2<i32>, Vec<(usize, usize, usize)>> =
|
||||
HashMap::new();
|
||||
for y in biome_min_y..=biome_max_y {
|
||||
for z in biome_min_z..=biome_max_z {
|
||||
for x in biome_min_x..=biome_max_x {
|
||||
let chunk_pos = Vector2::new(x >> 2, z >> 2);
|
||||
let rel_x = (x & 3) as usize;
|
||||
let rel_z = (z & 3) as usize;
|
||||
let rel_y = (y - (world.min_y >> 2)) as usize;
|
||||
chunk_modifications
|
||||
.entry(chunk_pos)
|
||||
.or_default()
|
||||
.push((rel_x, rel_y, rel_z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let target_biome_id = target_biome.id;
|
||||
let replace_biome_id = replace_biome.map(|b| b.id);
|
||||
let mut changed_count = 0;
|
||||
let target_biome_id = target_biome.id;
|
||||
let replace_biome_id = replace_biome.map(|b| b.id);
|
||||
let world = context.world().clone();
|
||||
|
||||
for (chunk_pos, mods) in chunk_modifications {
|
||||
let (has_replaced, count) = world
|
||||
.level
|
||||
.get_or_fetch_chunk(chunk_pos, |chunk| {
|
||||
let mut local_count = 0;
|
||||
let mut modified = false;
|
||||
for &(rel_x, rel_y, rel_z) in &mods {
|
||||
let section_index = rel_y / 4;
|
||||
let scale_y = rel_y % 4;
|
||||
if let Some(current_id) =
|
||||
chunk
|
||||
.section
|
||||
.get_noise_biome(section_index, rel_x, scale_y, rel_z)
|
||||
{
|
||||
if let Some(replace_id) = replace_biome_id {
|
||||
if current_id == replace_id {
|
||||
chunk.section.set_relative_biome(
|
||||
rel_x,
|
||||
rel_y,
|
||||
rel_z,
|
||||
target_biome_id,
|
||||
);
|
||||
local_count += 1;
|
||||
modified = true;
|
||||
}
|
||||
} else {
|
||||
let mut changed_count = 0;
|
||||
for (chunk_pos, mods) in chunk_modifications {
|
||||
let (has_replaced, count) =
|
||||
futures::executor::block_on(world.level.get_or_fetch_chunk(chunk_pos, |chunk| {
|
||||
let mut local_count = 0;
|
||||
let mut modified = false;
|
||||
for &(rel_x, rel_y, rel_z) in &mods {
|
||||
let section_index = rel_y / 4;
|
||||
let scale_y = rel_y % 4;
|
||||
if let Some(current_id) =
|
||||
chunk
|
||||
.section
|
||||
.get_noise_biome(section_index, rel_x, scale_y, rel_z)
|
||||
{
|
||||
if let Some(replace_id) = replace_biome_id {
|
||||
if current_id == replace_id {
|
||||
chunk.section.set_relative_biome(
|
||||
rel_x,
|
||||
rel_y,
|
||||
@@ -130,31 +119,40 @@ impl CommandExecutor for FillBiomeExecutor {
|
||||
local_count += 1;
|
||||
modified = true;
|
||||
}
|
||||
} else {
|
||||
chunk.section.set_relative_biome(
|
||||
rel_x,
|
||||
rel_y,
|
||||
rel_z,
|
||||
target_biome_id,
|
||||
);
|
||||
local_count += 1;
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
(modified, local_count)
|
||||
})
|
||||
.await;
|
||||
}
|
||||
(modified, local_count)
|
||||
}));
|
||||
|
||||
if has_replaced {
|
||||
changed_count += count;
|
||||
let chunk = world
|
||||
if has_replaced {
|
||||
changed_count += count;
|
||||
let chunk = futures::executor::block_on(
|
||||
world
|
||||
.level
|
||||
.get_or_fetch_chunk(chunk_pos, std::clone::Clone::clone)
|
||||
.await;
|
||||
world.broadcast_to_chunk_except(chunk_pos, &[], &CChunkData(&chunk));
|
||||
}
|
||||
.get_or_fetch_chunk(chunk_pos, std::clone::Clone::clone),
|
||||
);
|
||||
world.broadcast_to_chunk_except(chunk_pos, &[], &CChunkData(&chunk));
|
||||
}
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||
[TextComponent::text(changed_count.to_string())],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||
[TextComponent::text(changed_count.to_string())],
|
||||
);
|
||||
context.source.send_feedback(msg, true);
|
||||
|
||||
Ok(changed_count)
|
||||
})
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,315 +35,300 @@ static ERROR_TOO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
||||
struct ForceloadAddExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadAddExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||
|
||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||
} else {
|
||||
from_pos
|
||||
};
|
||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||
} else {
|
||||
from_pos
|
||||
};
|
||||
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_ADD.create_without_context())?;
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_ADD.create_without_context())?;
|
||||
|
||||
let chunk_x_start = from_pos.0.x >> 4;
|
||||
let chunk_z_start = from_pos.0.y >> 4;
|
||||
let chunk_x_start = from_pos.0.x >> 4;
|
||||
let chunk_z_start = from_pos.0.y >> 4;
|
||||
|
||||
let chunk_x_end = to_pos.0.x >> 4;
|
||||
let chunk_z_end = to_pos.0.y >> 4;
|
||||
let chunk_x_end = to_pos.0.x >> 4;
|
||||
let chunk_z_end = to_pos.0.y >> 4;
|
||||
|
||||
let min_x = chunk_x_start.min(chunk_x_end);
|
||||
let max_x = chunk_x_start.max(chunk_x_end);
|
||||
let min_z = chunk_z_start.min(chunk_z_end);
|
||||
let max_z = chunk_z_start.max(chunk_z_end);
|
||||
let min_x = chunk_x_start.min(chunk_x_end);
|
||||
let max_x = chunk_x_start.max(chunk_x_end);
|
||||
let min_z = chunk_z_start.min(chunk_z_end);
|
||||
let max_z = chunk_z_start.max(chunk_z_end);
|
||||
|
||||
let count_x = max_x - min_x + 1;
|
||||
let count_z = max_z - min_z + 1;
|
||||
let total_chunks = count_x * count_z;
|
||||
let count_x = max_x - min_x + 1;
|
||||
let count_z = max_z - min_z + 1;
|
||||
let total_chunks = count_x * count_z;
|
||||
|
||||
if total_chunks > 256 {
|
||||
return Err(ERROR_TOO_MANY.create_without_context(
|
||||
TextComponent::text("256"),
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
));
|
||||
}
|
||||
if total_chunks > 256 {
|
||||
return Err(ERROR_TOO_MANY.create_without_context(
|
||||
TextComponent::text("256"),
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
));
|
||||
}
|
||||
|
||||
{
|
||||
let mut forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for x in min_x..=max_x {
|
||||
for z in min_z..=max_z {
|
||||
forced.insert(Vector2::new(x, z));
|
||||
}
|
||||
{
|
||||
let mut forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for x in min_x..=max_x {
|
||||
for z in min_z..=max_z {
|
||||
forced.insert(Vector2::new(x, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
world.update_active_chunks();
|
||||
world.update_active_chunks();
|
||||
|
||||
let text = if total_chunks == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||
[
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
TextComponent::text(max_x.to_string()),
|
||||
TextComponent::text(max_z.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
let text = if total_chunks == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||
[
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
TextComponent::text(max_x.to_string()),
|
||||
TextComponent::text(max_z.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||
|
||||
Ok(total_chunks)
|
||||
})
|
||||
Ok(total_chunks)
|
||||
}
|
||||
}
|
||||
|
||||
struct ForceloadRemoveExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadRemoveExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||
|
||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||
} else {
|
||||
from_pos
|
||||
};
|
||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||
} else {
|
||||
from_pos
|
||||
};
|
||||
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||
|
||||
let chunk_x_start = from_pos.0.x >> 4;
|
||||
let chunk_z_start = from_pos.0.y >> 4;
|
||||
let chunk_x_start = from_pos.0.x >> 4;
|
||||
let chunk_z_start = from_pos.0.y >> 4;
|
||||
|
||||
let chunk_x_end = to_pos.0.x >> 4;
|
||||
let chunk_z_end = to_pos.0.y >> 4;
|
||||
let chunk_x_end = to_pos.0.x >> 4;
|
||||
let chunk_z_end = to_pos.0.y >> 4;
|
||||
|
||||
let min_x = chunk_x_start.min(chunk_x_end);
|
||||
let max_x = chunk_x_start.max(chunk_x_end);
|
||||
let min_z = chunk_z_start.min(chunk_z_end);
|
||||
let max_z = chunk_z_start.max(chunk_z_end);
|
||||
let min_x = chunk_x_start.min(chunk_x_end);
|
||||
let max_x = chunk_x_start.max(chunk_x_end);
|
||||
let min_z = chunk_z_start.min(chunk_z_end);
|
||||
let max_z = chunk_z_start.max(chunk_z_end);
|
||||
|
||||
let count_x = max_x - min_x + 1;
|
||||
let count_z = max_z - min_z + 1;
|
||||
let total_chunks = count_x * count_z;
|
||||
let count_x = max_x - min_x + 1;
|
||||
let count_z = max_z - min_z + 1;
|
||||
let total_chunks = count_x * count_z;
|
||||
|
||||
if total_chunks > 256 {
|
||||
return Err(ERROR_TOO_MANY.create_without_context(
|
||||
TextComponent::text("256"),
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
));
|
||||
}
|
||||
if total_chunks > 256 {
|
||||
return Err(ERROR_TOO_MANY.create_without_context(
|
||||
TextComponent::text("256"),
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
));
|
||||
}
|
||||
|
||||
{
|
||||
let mut forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for x in min_x..=max_x {
|
||||
for z in min_z..=max_z {
|
||||
forced.remove(&Vector2::new(x, z));
|
||||
}
|
||||
{
|
||||
let mut forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for x in min_x..=max_x {
|
||||
for z in min_z..=max_z {
|
||||
forced.remove(&Vector2::new(x, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
world.update_active_chunks();
|
||||
world.update_active_chunks();
|
||||
|
||||
let text = if total_chunks == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||
[
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
TextComponent::text(max_x.to_string()),
|
||||
TextComponent::text(max_z.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
let text = if total_chunks == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||
[
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
TextComponent::text(max_x.to_string()),
|
||||
TextComponent::text(max_z.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||
|
||||
Ok(total_chunks)
|
||||
})
|
||||
Ok(total_chunks)
|
||||
}
|
||||
}
|
||||
|
||||
struct ForceloadRemoveAllExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadRemoveAllExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||
|
||||
let removed_count = {
|
||||
let mut forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let count = forced.len();
|
||||
forced.clear();
|
||||
count
|
||||
};
|
||||
let removed_count = {
|
||||
let mut forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let count = forced.len();
|
||||
forced.clear();
|
||||
count
|
||||
};
|
||||
|
||||
world.update_active_chunks();
|
||||
world.update_active_chunks();
|
||||
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||
[],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||
[],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||
|
||||
Ok(removed_count as i32)
|
||||
})
|
||||
Ok(removed_count as i32)
|
||||
}
|
||||
}
|
||||
|
||||
struct ForceloadQueryExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadQueryExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let world = context
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_QUERY.create_without_context())?;
|
||||
|
||||
let chunk_pos = if context.get_argument::<Coordinates>("pos").is_ok() {
|
||||
let pos = ColumnPosArgumentType::get_column_pos(context, "pos")?;
|
||||
Vector2::new(pos.0.x >> 4, pos.0.y >> 4)
|
||||
} else {
|
||||
let block_x = context.source.position.x.floor() as i32;
|
||||
let block_z = context.source.position.z.floor() as i32;
|
||||
Vector2::new(block_x >> 4, block_z >> 4)
|
||||
};
|
||||
|
||||
let is_forced = {
|
||||
let forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
forced.contains(&chunk_pos)
|
||||
};
|
||||
|
||||
if is_forced {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_SUCCESS,
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_SUCCESS,
|
||||
[
|
||||
TextComponent::text(chunk_pos.x.to_string()),
|
||||
TextComponent::text(chunk_pos.y.to_string()),
|
||||
],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_QUERY.create_without_context())?;
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||
} else {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
[
|
||||
TextComponent::text(chunk_pos.x.to_string()),
|
||||
TextComponent::text(chunk_pos.y.to_string()),
|
||||
],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Red)), false);
|
||||
}
|
||||
|
||||
let chunk_pos = if context.get_argument::<Coordinates>("pos").is_ok() {
|
||||
let pos = ColumnPosArgumentType::get_column_pos(context, "pos")?;
|
||||
Vector2::new(pos.0.x >> 4, pos.0.y >> 4)
|
||||
let all_forced = {
|
||||
let forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
forced
|
||||
.iter()
|
||||
.map(|pos| format!("[{}, {}]", pos.x, pos.y))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if all_forced.is_empty() {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_NONE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_NONE,
|
||||
[],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false);
|
||||
} else {
|
||||
let list_str = all_forced.join(", ");
|
||||
let text = if all_forced.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_SINGLE,
|
||||
[TextComponent::text(list_str)],
|
||||
)
|
||||
} else {
|
||||
let block_x = context.source.position.x.floor() as i32;
|
||||
let block_z = context.source.position.z.floor() as i32;
|
||||
Vector2::new(block_x >> 4, block_z >> 4)
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||
[TextComponent::text(list_str)],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false);
|
||||
}
|
||||
|
||||
let is_forced = {
|
||||
let forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
forced.contains(&chunk_pos)
|
||||
};
|
||||
|
||||
if is_forced {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_SUCCESS,
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_SUCCESS,
|
||||
[
|
||||
TextComponent::text(chunk_pos.x.to_string()),
|
||||
TextComponent::text(chunk_pos.y.to_string()),
|
||||
],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
} else {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
[
|
||||
TextComponent::text(chunk_pos.x.to_string()),
|
||||
TextComponent::text(chunk_pos.y.to_string()),
|
||||
],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Red)), false)
|
||||
.await;
|
||||
}
|
||||
|
||||
let all_forced = {
|
||||
let forced = world
|
||||
.forced_chunks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
forced
|
||||
.iter()
|
||||
.map(|pos| format!("[{}, {}]", pos.x, pos.y))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if all_forced.is_empty() {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_NONE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_NONE,
|
||||
[],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false)
|
||||
.await;
|
||||
} else {
|
||||
let list_str = all_forced.join(", ");
|
||||
let text = if all_forced.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_SINGLE,
|
||||
[TextComponent::text(list_str)],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||
[TextComponent::text(list_str)],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(i32::from(is_forced))
|
||||
})
|
||||
Ok(i32::from(is_forced))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,73 +23,63 @@ static ERROR_UNKNOWN_FUNCTION: CommandErrorType<1> = CommandErrorType::new(
|
||||
struct FunctionSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for FunctionSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
fn suggest(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
let function_names = server.datapack_manager.get_function_names().await;
|
||||
for name in function_names {
|
||||
builder = builder.suggest(name);
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
) -> SuggestionProviderResult {
|
||||
let server = context.server();
|
||||
let function_names = server.datapack_manager.get_function_names();
|
||||
for name in function_names {
|
||||
builder = builder.suggest(name);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
struct FunctionExecutor;
|
||||
|
||||
impl CommandExecutor for FunctionExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let server = context.server();
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let name_str = StringArgumentType::get(context, "name")?;
|
||||
let server = context.server();
|
||||
|
||||
let Ok(executed_count) = server
|
||||
let Ok(executed_count) =
|
||||
server
|
||||
.datapack_manager
|
||||
.execute_function(server, &context.source, name_str)
|
||||
.await
|
||||
else {
|
||||
return Err(ERROR_UNKNOWN_FUNCTION
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
else {
|
||||
return Err(ERROR_UNKNOWN_FUNCTION
|
||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||
};
|
||||
|
||||
if name_str.starts_with('#') {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(executed_count.to_string()),
|
||||
TextComponent::text(name_str.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
||||
[
|
||||
TextComponent::text(executed_count.to_string()),
|
||||
TextComponent::text(name_str.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if name_str.starts_with('#') {
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(executed_count.to_string()),
|
||||
TextComponent::text(name_str.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
);
|
||||
} else {
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
||||
[
|
||||
TextComponent::text(executed_count.to_string()),
|
||||
TextComponent::text(name_str.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(executed_count as i32)
|
||||
})
|
||||
Ok(executed_count as i32)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,72 +25,65 @@ struct TargetExecutor {
|
||||
}
|
||||
|
||||
impl CommandExecutor for TargetExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||
};
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||
};
|
||||
|
||||
let targets = if self.is_self {
|
||||
let Some(player) = sender.as_player() else {
|
||||
return Err(InvalidRequirement);
|
||||
};
|
||||
&[player]
|
||||
} else {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
targets.as_slice()
|
||||
let targets = if self.is_self {
|
||||
let Some(player) = sender.as_player() else {
|
||||
return Err(InvalidRequirement);
|
||||
};
|
||||
&[player]
|
||||
} else {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
targets.as_slice()
|
||||
};
|
||||
|
||||
let mut succeeded: i32 = 0;
|
||||
for target in targets {
|
||||
if target.set_gamemode(gamemode).await {
|
||||
succeeded += 1;
|
||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||
// Checking if the target was the sender of this command.
|
||||
let gamemode_comp = TextComponent::translate_cross(
|
||||
gamemode_string.clone(),
|
||||
gamemode_string.clone(),
|
||||
[],
|
||||
);
|
||||
if sender.as_player().as_ref() == Some(target) {
|
||||
target
|
||||
.send_system_message(&TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||
[gamemode_comp],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
if server.level_info.load().game_rules.send_command_feedback {
|
||||
target
|
||||
.send_system_message(&TextComponent::translate_cross(
|
||||
translation::java::GAMEMODE_CHANGED,
|
||||
translation::bedrock::GAMEMODE_CHANGED,
|
||||
[gamemode_comp.clone()],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||
[target.get_display_name(), gamemode_comp],
|
||||
))
|
||||
.await;
|
||||
let mut succeeded: i32 = 0;
|
||||
for target in targets {
|
||||
if target.gamemode.load() != gamemode {
|
||||
target.set_gamemode(gamemode);
|
||||
succeeded += 1;
|
||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||
// Checking if the target was the sender of this command.
|
||||
let gamemode_comp = TextComponent::translate_cross(
|
||||
gamemode_string.clone(),
|
||||
gamemode_string.clone(),
|
||||
[],
|
||||
);
|
||||
if sender.as_player().as_ref() == Some(target) {
|
||||
target.send_system_message(&TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||
[gamemode_comp],
|
||||
));
|
||||
} else {
|
||||
if server.level_info.load().game_rules.send_command_feedback {
|
||||
target.send_system_message(&TextComponent::translate_cross(
|
||||
translation::java::GAMEMODE_CHANGED,
|
||||
translation::bedrock::GAMEMODE_CHANGED,
|
||||
[gamemode_comp.clone()],
|
||||
));
|
||||
}
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||
[target.get_display_name(), gamemode_comp],
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(succeeded)
|
||||
})
|
||||
Ok(succeeded)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,35 +20,29 @@ const ARG_NAME: &str = "value";
|
||||
struct QueryExecutor(GameRule);
|
||||
|
||||
impl CommandExecutor for QueryExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let key = TextComponent::text(self.0.to_string());
|
||||
let level_info = server.level_info.load();
|
||||
let game_rule = level_info.game_rules.get(&self.0);
|
||||
let game_rule_i32_value = match game_rule {
|
||||
GameRuleValue::Int(value) => {
|
||||
(*value).clamp(i32::MIN as i64, i32::MAX as i64) as i32
|
||||
}
|
||||
GameRuleValue::Bool(value) => *value as i32,
|
||||
};
|
||||
let value = TextComponent::text(game_rule.to_string());
|
||||
drop(level_info);
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
_args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let key = TextComponent::text(self.0.to_string());
|
||||
let level_info = server.level_info.load();
|
||||
let game_rule = level_info.game_rules.get(&self.0);
|
||||
let game_rule_i32_value = match game_rule {
|
||||
GameRuleValue::Int(value) => (*value).clamp(i32::MIN as i64, i32::MAX as i64) as i32,
|
||||
GameRuleValue::Bool(value) => *value as i32,
|
||||
};
|
||||
let value = TextComponent::text(game_rule.to_string());
|
||||
drop(level_info);
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.gamerule.query",
|
||||
"commands.gamerule.query",
|
||||
[key, value],
|
||||
))
|
||||
.await;
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.gamerule.query",
|
||||
"commands.gamerule.query",
|
||||
[key, value],
|
||||
));
|
||||
|
||||
Ok(game_rule_i32_value)
|
||||
})
|
||||
Ok(game_rule_i32_value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,53 +50,49 @@ struct SetExecutor(GameRule);
|
||||
|
||||
impl CommandExecutor for SetExecutor {
|
||||
#[expect(unused)]
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let key = TextComponent::text(self.0.to_string());
|
||||
let current_info = server.level_info.load();
|
||||
fn execute(
|
||||
&self,
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
args: &ConsumedArgs,
|
||||
) -> CommandResult {
|
||||
let key = TextComponent::text(self.0.to_string());
|
||||
let current_info = server.level_info.load();
|
||||
|
||||
let mut new_info = (**current_info).clone();
|
||||
let mut new_info = (**current_info).clone();
|
||||
|
||||
let mut output_value = String::new();
|
||||
let mut result_i32: i32;
|
||||
let mut output_value = String::new();
|
||||
let mut result_i32: i32;
|
||||
|
||||
let raw_value = new_info.game_rules.get_mut(&self.0);
|
||||
let raw_value = new_info.game_rules.get_mut(&self.0);
|
||||
|
||||
match raw_value {
|
||||
GameRuleValue::Int(value) => {
|
||||
let arg_value = BoundedNumArgumentConsumer::<i64>::find_arg(args, ARG_NAME)??;
|
||||
*value = arg_value;
|
||||
output_value = arg_value.to_string();
|
||||
// TODO: Should integer gamerule values be kept as a `i64` or should it be changed to an `i32`?
|
||||
// For now, we can cast it
|
||||
result_i32 = arg_value.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
|
||||
}
|
||||
GameRuleValue::Bool(value) => {
|
||||
let arg_value = BoolArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
*value = arg_value;
|
||||
output_value = arg_value.to_string();
|
||||
result_i32 = *value as i32;
|
||||
}
|
||||
match raw_value {
|
||||
GameRuleValue::Int(value) => {
|
||||
let arg_value = BoundedNumArgumentConsumer::<i64>::find_arg(args, ARG_NAME)??;
|
||||
*value = arg_value;
|
||||
output_value = arg_value.to_string();
|
||||
// TODO: Should integer gamerule values be kept as a `i64` or should it be changed to an `i32`?
|
||||
// For now, we can cast it
|
||||
result_i32 = arg_value.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
|
||||
}
|
||||
GameRuleValue::Bool(value) => {
|
||||
let arg_value = BoolArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
*value = arg_value;
|
||||
output_value = arg_value.to_string();
|
||||
result_i32 = *value as i32;
|
||||
}
|
||||
}
|
||||
|
||||
server.level_info.store(std::sync::Arc::new(new_info));
|
||||
server.level_info.store(std::sync::Arc::new(new_info));
|
||||
|
||||
let value_component = TextComponent::text(output_value);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.gamerule.set",
|
||||
"commands.gamerule.set",
|
||||
[key, value_component],
|
||||
))
|
||||
.await;
|
||||
let value_component = TextComponent::text(output_value);
|
||||
sender.send_message(TextComponent::translate_cross(
|
||||
"commands.gamerule.set",
|
||||
"commands.gamerule.set",
|
||||
[key, value_component],
|
||||
));
|
||||
|
||||
Ok(result_i32)
|
||||
})
|
||||
Ok(result_i32)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 222 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user