LootCommand .java

net.minecraft.server.commands.LootCommand (class): members: RESPONSE_WITHOUT_LOOT_TABLE, ERROR_NO_ENTITY_LOOT_TABLE, ERROR_NO_BLOCK_LOOT_TABLE, lootParams.

net.minecraft.server.commandsclass453 linesserver18.4 KB

API Surface (1)

void register(final CommandDispatcher<CommandSourceStack> dispatcher, final CommandBuildContext context)

Fields & Constants (16)

ERROR_NO_HELD_ITEMS
ERROR_NO_ENTITY_LOOT_TABLE
ERROR_NO_BLOCK_LOOT_TABLE
RESPONSE_WITHOUT_LOOT_TABLE
RESPONSE_WITH_LOOT_TABLE
drops
source
pos
startSlot
slotCount
count
entities
tool
context
lootTable
lootParams

String literals (27)

"commands.drop.no_held_items"
"commands.drop.no_loot_table.entity"
"commands.drop.no_loot_table.block"
"commands.drop.success.single"
"commands.drop.success.multiple"
"commands.drop.success.single_with_table"
"commands.drop.success.multiple_with_table"
"loot"
"fish"
"loot_table"
"tool"
"mainhand"
"offhand"
"kill"
"target"
"mine"
"replace"
"entity"
"entities"
"slot"
"count"
"block"
"targetPos"
"insert"

Full Source

LootCommand.java453 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.commands;
2
3
import com.mojang.brigadier.CommandDispatcher;
4
import com.mojang.brigadier.arguments.IntegerArgumentType;
5
import com.mojang.brigadier.builder.ArgumentBuilder;
6
import com.mojang.brigadier.context.CommandContext;
7
import com.mojang.brigadier.exceptions.CommandSyntaxException;
8
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
9
import java.util.Collection;
10
import java.util.List;
11
import java.util.Optional;
12
import net.minecraft.commands.CommandBuildContext;
13
import net.minecraft.commands.CommandSourceStack;
14
import net.minecraft.commands.Commands;
15
import net.minecraft.commands.arguments.EntityArgument;
16
import net.minecraft.commands.arguments.ResourceOrIdArgument;
17
import net.minecraft.commands.arguments.SlotArgument;
18
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
19
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
20
import net.minecraft.commands.arguments.item.ItemArgument;
21
import net.minecraft.core.BlockPos;
22
import net.minecraft.core.Holder;
23
import net.minecraft.network.chat.Component;
24
import net.minecraft.resources.ResourceKey;
25
import net.minecraft.server.commands.item.BlockItemAccessor;
26
import net.minecraft.server.commands.item.ItemCommands;
27
import net.minecraft.server.level.ServerLevel;
28
import net.minecraft.server.level.ServerPlayer;
29
import net.minecraft.world.Container;
30
import net.minecraft.world.entity.Entity;
31
import net.minecraft.world.entity.EquipmentSlot;
32
import net.minecraft.world.entity.LivingEntity;
33
import net.minecraft.world.entity.SlotAccess;
34
import net.minecraft.world.entity.item.ItemEntity;
35
import net.minecraft.world.entity.player.Player;
36
import net.minecraft.world.item.ItemInstance;
37
import net.minecraft.world.item.ItemStack;
38
import net.minecraft.world.level.block.entity.BlockEntity;
39
import net.minecraft.world.level.block.state.BlockState;
40
import net.minecraft.world.level.storage.loot.LootParams;
41
import net.minecraft.world.level.storage.loot.LootTable;
42
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
43
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
44
import net.minecraft.world.phys.Vec3;
45
46
public class LootCommand {
47
	private static final DynamicCommandExceptionType ERROR_NO_HELD_ITEMS = new DynamicCommandExceptionType(
48
		entity -> Component.translatableEscape("commands.drop.no_held_items", entity)
49
	);
50
	private static final DynamicCommandExceptionType ERROR_NO_ENTITY_LOOT_TABLE = new DynamicCommandExceptionType(
51
		entity -> Component.translatableEscape("commands.drop.no_loot_table.entity", entity)
52
	);
53
	private static final DynamicCommandExceptionType ERROR_NO_BLOCK_LOOT_TABLE = new DynamicCommandExceptionType(
54
		block -> Component.translatableEscape("commands.drop.no_loot_table.block", block)
55
	);
56
	private static final CommandResponseTracker.Messages<ItemStack> RESPONSE_WITHOUT_LOOT_TABLE = CommandResponseTracker.messages(
57
		(drop, var1) -> Component.translatable("commands.drop.success.single", drop.getCount(), drop.getDisplayName()),
58
		(dropCount, var1) -> Component.translatable("commands.drop.success.multiple", dropCount)
59
	);
60
	private static final CommandResponseTracker.MessagesWithArg<ItemStack, ResourceKey<LootTable>> RESPONSE_WITH_LOOT_TABLE = CommandResponseTracker.messages(
61
		(drop, var1, key) -> Component.translatable(
62
			"commands.drop.success.single_with_table", drop.getCount(), drop.getDisplayName(), Component.translationArg(key.identifier())
63
		),
64
		(dropCount, var1, key) -> Component.translatable("commands.drop.success.multiple_with_table", dropCount, Component.translationArg(key.identifier()))
65
	);
66
67
	public static void register(final CommandDispatcher<CommandSourceStack> dispatcher, final CommandBuildContext context) {
68
		dispatcher.register(
69
			addTargets(
70
				Commands.literal("loot").requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS)),
71
				(target, output) -> target.then(
72
						Commands.literal("fish")
73
							.then(
74
								Commands.argument("loot_table", ResourceOrIdArgument.lootTable(context))
75
									.then(
76
										Commands.argument("pos", BlockPosArgument.blockPos())
77
											.executes(
78
												c -> dropFishingLoot(c, ResourceOrIdArgument.getLootTable(c, "loot_table"), BlockPosArgument.getLoadedBlockPos(c, "pos"), ItemStack.EMPTY, output)
79
											)
80
											.then(
81
												Commands.argument("tool", ItemArgument.item(context))
82
													.executes(
83
														c -> dropFishingLoot(
84
															c,
85
															ResourceOrIdArgument.getLootTable(c, "loot_table"),
86
															BlockPosArgument.getLoadedBlockPos(c, "pos"),
87
															ItemArgument.getItem(c, "tool").createItemStack(1),
88
															output
89
														)
90
													)
91
											)
92
											.then(
93
												Commands.literal("mainhand")
94
													.executes(
95
														c -> dropFishingLoot(
96
															c,
97
															ResourceOrIdArgument.getLootTable(c, "loot_table"),
98
															BlockPosArgument.getLoadedBlockPos(c, "pos"),
99
															getSourceHandItem(c.getSource(), EquipmentSlot.MAINHAND),
100
															output
101
														)
102
													)
103
											)
104
											.then(
105
												Commands.literal("offhand")
106
													.executes(
107
														c -> dropFishingLoot(
108
															c,
109
															ResourceOrIdArgument.getLootTable(c, "loot_table"),
110
															BlockPosArgument.getLoadedBlockPos(c, "pos"),
111
															getSourceHandItem(c.getSource(), EquipmentSlot.OFFHAND),
112
															output
113
														)
114
													)
115
											)
116
									)
117
							)
118
					)
119
					.then(
120
						Commands.literal("loot")
121
							.then(
122
								Commands.argument("loot_table", ResourceOrIdArgument.lootTable(context))
123
									.executes(c -> dropChestLoot(c, ResourceOrIdArgument.getLootTable(c, "loot_table"), output))
124
							)
125
					)
126
					.then(
127
						Commands.literal("kill")
128
							.then(Commands.argument("target", EntityArgument.entity()).executes(c -> dropKillLoot(c, EntityArgument.getEntity(c, "target"), output)))
129
					)
130
					.then(
131
						Commands.literal("mine")
132
							.then(
133
								Commands.argument("pos", BlockPosArgument.blockPos())
134
									.executes(c -> dropBlockLoot(c, BlockPosArgument.getLoadedBlockPos(c, "pos"), ItemStack.EMPTY, output))
135
									.then(
136
										Commands.argument("tool", ItemArgument.item(context))
137
											.executes(c -> dropBlockLoot(c, BlockPosArgument.getLoadedBlockPos(c, "pos"), ItemArgument.getItem(c, "tool").createItemStack(1), output))
138
									)
139
									.then(
140
										Commands.literal("mainhand")
141
											.executes(c -> dropBlockLoot(c, BlockPosArgument.getLoadedBlockPos(c, "pos"), getSourceHandItem(c.getSource(), EquipmentSlot.MAINHAND), output))
142
									)
143
									.then(
144
										Commands.literal("offhand")
145
											.executes(c -> dropBlockLoot(c, BlockPosArgument.getLoadedBlockPos(c, "pos"), getSourceHandItem(c.getSource(), EquipmentSlot.OFFHAND), output))
146
									)
147
							)
148
					)
149
			)
150
		);
151
	}
152
153
	private static <T extends ArgumentBuilder<CommandSourceStack, T>> T addTargets(final T root, final LootCommand.TailProvider tail) {
154
		return root.then(
155
				Commands.literal("replace")
156
					.then(
157
						Commands.literal("entity")
158
							.then(
159
								Commands.argument("entities", EntityArgument.entities())
160
									.then(
161
										tail.construct(
162
												Commands.argument("slot", SlotArgument.slot()),
163
												(c, drops, usedItems) -> entityReplace(EntityArgument.getEntities(c, "entities"), SlotArgument.getSlot(c, "slot"), drops.size(), drops, usedItems)
164
											)
165
											.then(
166
												tail.construct(
167
													Commands.argument("count", IntegerArgumentType.integer(0)),
168
													(c, drops, usedItems) -> entityReplace(
169
														EntityArgument.getEntities(c, "entities"), SlotArgument.getSlot(c, "slot"), IntegerArgumentType.getInteger(c, "count"), drops, usedItems
170
													)
171
												)
172
											)
173
									)
174
							)
175
					)
176
					.then(
177
						Commands.literal("block")
178
							.then(
179
								Commands.argument("targetPos", BlockPosArgument.blockPos())
180
									.then(
181
										tail.construct(
182
												Commands.argument("slot", SlotArgument.slot()),
183
												(c, drops, usedItems) -> blockReplace(
184
													c.getSource(), BlockPosArgument.getLoadedBlockPos(c, "targetPos"), SlotArgument.getSlot(c, "slot"), drops.size(), drops, usedItems
185
												)
186
											)
187
											.then(
188
												tail.construct(
189
													Commands.argument("count", IntegerArgumentType.integer(0)),
190
													(c, drops, usedItems) -> blockReplace(
191
														c.getSource(),
192
														BlockPosArgument.getLoadedBlockPos(c, "targetPos"),
193
														IntegerArgumentType.getInteger(c, "slot"),
194
														IntegerArgumentType.getInteger(c, "count"),
195
														drops,
196
														usedItems
197
													)
198
												)
199
											)
200
									)
201
							)
202
					)
203
			)
204
			.then(
205
				Commands.literal("insert")
206
					.then(
207
						tail.construct(
208
							Commands.argument("targetPos", BlockPosArgument.blockPos()),
209
							(c, drops, usedItems) -> blockDistribute(c.getSource(), BlockPosArgument.getLoadedBlockPos(c, "targetPos"), drops, usedItems)
210
						)
211
					)
212
			)
213
			.then(
214
				Commands.literal("give")
215
					.then(
216
						tail.construct(
217
							Commands.argument("players", EntityArgument.players()), (c, drops, usedItems) -> playerGive(EntityArgument.getPlayers(c, "players"), drops, usedItems)
218
						)
219
					)
220
			)
221
			.then(
222
				Commands.literal("spawn")
223
					.then(
224
						tail.construct(
225
							Commands.argument("targetPos", Vec3Argument.vec3()),
226
							(c, drops, usedItems) -> dropInWorld(c.getSource(), Vec3Argument.getVec3(c, "targetPos"), drops, usedItems)
227
						)
228
					)
229
			);
230
	}
231
232
	private static void blockDistribute(
233
		final CommandSourceStack source, final BlockPos pos, final List<ItemStack> drops, final CommandResponseTracker<ItemStack> usedItems
234
	) throws CommandSyntaxException {
235
		Container container = BlockItemAccessor.getContainer(source, pos, ItemCommands.ERROR_TARGET_NOT_A_CONTAINER);
236
237
		for (ItemStack drop : drops) {
238
			if (distributeToContainer(container, drop.copy())) {
239
				container.setChanged();
240
				usedItems.track(drop);
241
			}
242
		}
243
	}
244
245
	private static boolean distributeToContainer(final Container container, final ItemStack itemStack) {
246
		boolean changed = false;
247
248
		for (int slot = 0; slot < container.getContainerSize() && !itemStack.isEmpty(); slot++) {
249
			ItemStack current = container.getItem(slot);
250
			if (container.canPlaceItem(slot, itemStack)) {
251
				if (current.isEmpty()) {
252
					container.setItem(slot, itemStack);
253
					changed = true;
254
					break;
255
				}
256
257
				if (canMergeItems(current, itemStack)) {
258
					int space = itemStack.getMaxStackSize() - current.getCount();
259
					int count = Math.min(itemStack.getCount(), space);
260
					itemStack.shrink(count);
261
					current.grow(count);
262
					changed = true;
263
				}
264
			}
265
		}
266
267
		return changed;
268
	}
269
270
	private static void blockReplace(
271
		final CommandSourceStack source,
272
		final BlockPos pos,
273
		final int startSlot,
274
		final int slotCount,
275
		final List<ItemStack> drops,
276
		final CommandResponseTracker<ItemStack> usedItems
277
	) throws CommandSyntaxException {
278
		Container container = BlockItemAccessor.getContainer(source, pos, ItemCommands.ERROR_TARGET_NOT_A_CONTAINER);
279
		int maxSlot = container.getContainerSize();
280
		if (startSlot >= 0 && startSlot < maxSlot) {
281
			for (int i = 0; i < slotCount; i++) {
282
				int slot = startSlot + i;
283
				ItemStack toAdd = i < drops.size() ? drops.get(i) : ItemStack.EMPTY;
284
				if (container.canPlaceItem(slot, toAdd)) {
285
					container.setItem(slot, toAdd);
286
					usedItems.track(toAdd);
287
				}
288
			}
289
		} else {
290
			throw ItemCommands.ERROR_TARGET_INAPPLICABLE_SLOT.create(startSlot);
291
		}
292
	}
293
294
	private static boolean canMergeItems(final ItemStack a, final ItemStack b) {
295
		return a.getCount() <= a.getMaxStackSize() && ItemStack.isSameItemSameComponents(a, b);
296
	}
297
298
	private static void playerGive(final Collection<ServerPlayer> players, final List<ItemStack> drops, final CommandResponseTracker<ItemStack> usedItems) {
299
		for (ItemStack drop : drops) {
300
			for (ServerPlayer player : players) {
301
				if (player.getInventory().add(drop.copy())) {
302
					usedItems.track(drop);
303
				}
304
			}
305
		}
306
	}
307
308
	private static void setSlots(
309
		final Entity entity, final List<ItemStack> itemsToSet, final int startSlot, final int count, final CommandResponseTracker<ItemStack> usedItems
310
	) {
311
		for (int i = 0; i < count; i++) {
312
			ItemStack item = i < itemsToSet.size() ? itemsToSet.get(i) : ItemStack.EMPTY;
313
			SlotAccess slotAccess = entity.getSlot(startSlot + i);
314
			if (slotAccess != null && slotAccess.set(item.copy())) {
315
				usedItems.track(item);
316
			}
317
		}
318
	}
319
320
	private static void entityReplace(
321
		final Collection<? extends Entity> entities,
322
		final int startSlot,
323
		final int count,
324
		final List<ItemStack> drops,
325
		final CommandResponseTracker<ItemStack> usedItems
326
	) {
327
		for (Entity entity : entities) {
328
			if (entity instanceof ServerPlayer player) {
329
				setSlots(entity, drops, startSlot, count, usedItems);
330
				player.containerMenu.broadcastChanges();
331
			} else {
332
				setSlots(entity, drops, startSlot, count, usedItems);
333
			}
334
		}
335
	}
336
337
	private static void dropInWorld(
338
		final CommandSourceStack source, final Vec3 pos, final List<ItemStack> drops, final CommandResponseTracker<ItemStack> usedItems
339
	) {
340
		ServerLevel level = source.getLevel();
341
		drops.forEach(drop -> {
342
			ItemEntity entity = new ItemEntity(level, pos.x, pos.y, pos.z, drop.copy());
343
			entity.setDefaultPickUpDelay();
344
			level.addFreshEntity(entity);
345
			usedItems.track(drop);
346
		});
347
	}
348
349
	private static ItemStack getSourceHandItem(final CommandSourceStack source, final EquipmentSlot slot) throws CommandSyntaxException {
350
		Entity entity = source.getEntityOrException();
351
		if (entity instanceof LivingEntity livingEntity) {
352
			return livingEntity.getItemBySlot(slot);
353
		} else {
354
			throw ERROR_NO_HELD_ITEMS.create(entity.getDisplayName());
355
		}
356
	}
357
358
	private static int dropBlockLoot(
359
		final CommandContext<CommandSourceStack> context, final BlockPos pos, final ItemInstance tool, final LootCommand.DropConsumer output
360
	) throws CommandSyntaxException {
361
		CommandSourceStack source = context.getSource();
362
		ServerLevel level = source.getLevel();
363
		BlockState blockState = level.getBlockState(pos);
364
		BlockEntity blockEntity = level.getBlockEntity(pos);
365
		Optional<ResourceKey<LootTable>> lootTable = blockState.getBlock().getLootTable();
366
		if (lootTable.isEmpty()) {
367
			throw ERROR_NO_BLOCK_LOOT_TABLE.create(blockState.getBlock().getName());
368
		}
369
370
		LootParams.Builder lootParams = new LootParams.Builder(level)
371
			.withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos))
372
			.withParameter(LootContextParams.BLOCK_STATE, blockState)
373
			.withOptionalParameter(LootContextParams.BLOCK_ENTITY, blockEntity)
374
			.withOptionalParameter(LootContextParams.THIS_ENTITY, source.getEntity())
375
			.withParameter(LootContextParams.TOOL, tool);
376
		List<ItemStack> drops = blockState.getDrops(lootParams);
377
		CommandResponseTracker<ItemStack> usedItems = CommandResponseTracker.create();
378
		output.accept(context, drops, usedItems);
379
		return usedItems.sendFeedback(source, false, RESPONSE_WITH_LOOT_TABLE, lootTable.get());
380
	}
381
382
	private static int dropKillLoot(final CommandContext<CommandSourceStack> context, final Entity target, final LootCommand.DropConsumer output) throws CommandSyntaxException {
383
		Optional<ResourceKey<LootTable>> lootTableId = target.getLootTable();
384
		if (lootTableId.isEmpty()) {
385
			throw ERROR_NO_ENTITY_LOOT_TABLE.create(target.getDisplayName());
386
		}
387
388
		CommandSourceStack source = context.getSource();
389
		LootParams.Builder builder = new LootParams.Builder(source.getLevel());
390
		Entity killer = source.getEntity();
391
		if (killer instanceof Player player) {
392
			builder.withParameter(LootContextParams.LAST_DAMAGE_PLAYER, player);
393
		}
394
395
		builder.withParameter(LootContextParams.DAMAGE_SOURCE, target.damageSources().magic());
396
		builder.withOptionalParameter(LootContextParams.DIRECT_ATTACKING_ENTITY, killer);
397
		builder.withOptionalParameter(LootContextParams.ATTACKING_ENTITY, killer);
398
		builder.withParameter(LootContextParams.THIS_ENTITY, target);
399
		builder.withParameter(LootContextParams.ORIGIN, source.getPosition());
400
		LootParams lootParams = builder.create(LootContextParamSets.ENTITY);
401
		LootTable lootTable = source.getServer().reloadableRegistries().getLootTable(lootTableId.get());
402
		List<ItemStack> drops = lootTable.getRandomItems(lootParams);
403
		CommandResponseTracker<ItemStack> usedItems = CommandResponseTracker.create();
404
		output.accept(context, drops, usedItems);
405
		return usedItems.sendFeedback(source, false, RESPONSE_WITH_LOOT_TABLE, lootTableId.get());
406
	}
407
408
	private static int dropChestLoot(final CommandContext<CommandSourceStack> context, final Holder<LootTable> lootTable, final LootCommand.DropConsumer output) throws CommandSyntaxException {
409
		CommandSourceStack source = context.getSource();
410
		LootParams lootParams = new LootParams.Builder(source.getLevel())
411
			.withOptionalParameter(LootContextParams.THIS_ENTITY, source.getEntity())
412
			.withParameter(LootContextParams.ORIGIN, source.getPosition())
413
			.create(LootContextParamSets.CHEST);
414
		return drop(context, lootTable, lootParams, output);
415
	}
416
417
	private static int dropFishingLoot(
418
		final CommandContext<CommandSourceStack> context,
419
		final Holder<LootTable> lootTable,
420
		final BlockPos pos,
421
		final ItemInstance tool,
422
		final LootCommand.DropConsumer output
423
	) throws CommandSyntaxException {
424
		CommandSourceStack source = context.getSource();
425
		LootParams lootParams = new LootParams.Builder(source.getLevel())
426
			.withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos))
427
			.withParameter(LootContextParams.TOOL, tool)
428
			.withOptionalParameter(LootContextParams.THIS_ENTITY, source.getEntity())
429
			.create(LootContextParamSets.FISHING);
430
		return drop(context, lootTable, lootParams, output);
431
	}
432
433
	private static int drop(
434
		final CommandContext<CommandSourceStack> context, final Holder<LootTable> lootTable, final LootParams lootParams, final LootCommand.DropConsumer output
435
	) throws CommandSyntaxException {
436
		CommandSourceStack source = context.getSource();
437
		List<ItemStack> drops = lootTable.value().getRandomItems(lootParams);
438
		CommandResponseTracker<ItemStack> usedItems = CommandResponseTracker.create();
439
		output.accept(context, drops, usedItems);
440
		return usedItems.sendFeedback(source, false, RESPONSE_WITHOUT_LOOT_TABLE);
441
	}
442
443
	@FunctionalInterface
444
	private interface DropConsumer {
445
		void accept(CommandContext<CommandSourceStack> context, List<ItemStack> drops, CommandResponseTracker<ItemStack> response) throws CommandSyntaxException;
446
	}
447
448
	@FunctionalInterface
449
	private interface TailProvider {
450
		ArgumentBuilder<CommandSourceStack, ?> construct(final ArgumentBuilder<CommandSourceStack, ?> root, LootCommand.DropConsumer consumer);
451
	}
452
}
453

Decompiled Minecraft 26.3 source of LootCommand (net/minecraft/server/commands/LootCommand.java) with Mojang official mappings, stored verbatim on the site.