Initial Commit

This commit is contained in:
richard committed 2026-11-13 22:25:04 +01:00
1 parent 377b32db6e
commit 2d9a5eecba
14134 files changed
+1160982

No files matched your search

@@ -0,0 +1,155 @@
package net.minecraft.server;
import com.mojang.logging.LogUtils;
import java.io.PrintStream;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.function.Supplier;
import net.minecraft.SharedConstants;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.selector.options.EntitySelectorOptions;
import net.minecraft.core.cauldron.CauldronInteraction;
import net.minecraft.core.dispenser.DispenseItemBehavior;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.locale.Language;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
import net.minecraft.world.item.CreativeModeTabs;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.alchemy.PotionBrewing;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ComposterBlock;
import net.minecraft.world.level.block.FireBlock;
import org.slf4j.Logger;
public class Bootstrap {
public static final PrintStream STDOUT = System.out;
/** Whether the blocks, items, etc have already been registered */
private static volatile boolean isBootstrapped;
private static final Logger LOGGER = LogUtils.getLogger();
public static final AtomicLong bootstrapDuration = new AtomicLong(-1L);
/**
* Registers blocks, items, stats, etc.
*/
public static void bootStrap() {
if (!isBootstrapped) {
isBootstrapped = true;
Instant instant = Instant.now();
if (BuiltInRegistries.REGISTRY.keySet().isEmpty()) {
throw new IllegalStateException("Unable to load registries");
} else {
FireBlock.bootStrap();
ComposterBlock.bootStrap();
if (EntityType.getKey(EntityType.PLAYER) == null) {
throw new IllegalStateException("Failed loading EntityTypes");
} else {
PotionBrewing.bootStrap();
EntitySelectorOptions.bootStrap();
DispenseItemBehavior.bootStrap();
CauldronInteraction.bootStrap();
BuiltInRegistries.bootStrap();
CreativeModeTabs.validate();
net.minecraftforge.registries.GameData.vanillaSnapshot();
if (false) // skip redirectOutputToLog, Forge already redirects stdout and stderr output to log so that they print with more context
wrapStreams();
bootstrapDuration.set(Duration.between(instant, Instant.now()).toMillis());
}
}
}
}
private static <T> void checkTranslations(Iterable<T> pObjects, Function<T, String> pObjectToKeyFunction, Set<String> pTranslationSet) {
Language language = Language.getInstance();
pObjects.forEach((p_135883_) -> {
String s = pObjectToKeyFunction.apply(p_135883_);
if (!language.has(s)) {
pTranslationSet.add(s);
}
});
}
private static void checkGameruleTranslations(final Set<String> pTranslations) {
final Language language = Language.getInstance();
GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() {
public <T extends GameRules.Value<T>> void visit(GameRules.Key<T> p_135897_, GameRules.Type<T> p_135898_) {
if (!language.has(p_135897_.getDescriptionId())) {
pTranslations.add(p_135897_.getId());
}
}
});
}
public static Set<String> getMissingTranslations() {
Set<String> set = new TreeSet<>();
checkTranslations(BuiltInRegistries.ATTRIBUTE, Attribute::getDescriptionId, set);
checkTranslations(BuiltInRegistries.ENTITY_TYPE, EntityType::getDescriptionId, set);
checkTranslations(BuiltInRegistries.MOB_EFFECT, MobEffect::getDescriptionId, set);
checkTranslations(BuiltInRegistries.ITEM, Item::getDescriptionId, set);
checkTranslations(BuiltInRegistries.ENCHANTMENT, Enchantment::getDescriptionId, set);
checkTranslations(BuiltInRegistries.BLOCK, Block::getDescriptionId, set);
checkTranslations(BuiltInRegistries.CUSTOM_STAT, (p_135885_) -> {
return "stat." + p_135885_.toString().replace(':', '.');
}, set);
checkGameruleTranslations(set);
return set;
}
public static void checkBootstrapCalled(Supplier<String> p_179913_) {
if (!isBootstrapped) {
throw createBootstrapException(p_179913_);
}
}
private static RuntimeException createBootstrapException(Supplier<String> p_179917_) {
try {
String s = p_179917_.get();
return new IllegalArgumentException("Not bootstrapped (called from " + s + ")");
} catch (Exception exception) {
RuntimeException runtimeexception = new IllegalArgumentException("Not bootstrapped (failed to resolve location)");
runtimeexception.addSuppressed(exception);
return runtimeexception;
}
}
public static void validate() {
checkBootstrapCalled(() -> {
return "validate";
});
if (SharedConstants.IS_RUNNING_IN_IDE) {
getMissingTranslations().forEach((p_179915_) -> {
LOGGER.error("Missing translations: {}", (Object)p_179915_);
});
Commands.validate();
}
}
/**
* Redirect standard streams to logger.
*/
private static void wrapStreams() {
if (LOGGER.isDebugEnabled()) {
System.setErr(new DebugLoggedPrintStream("STDERR", System.err));
System.setOut(new DebugLoggedPrintStream("STDOUT", STDOUT));
} else {
System.setErr(new LoggedPrintStream("STDERR", System.err));
System.setOut(new LoggedPrintStream("STDOUT", STDOUT));
}
}
public static void realStdoutPrintln(String pMessage) {
STDOUT.println(pMessage);
}
}
@@ -0,0 +1,80 @@
package net.minecraft.server;
import com.google.common.collect.Lists;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
public class ChainedJsonException extends IOException {
private final List<ChainedJsonException.Entry> entries = Lists.newArrayList();
private final String message;
public ChainedJsonException(String p_135902_) {
this.entries.add(new ChainedJsonException.Entry());
this.message = p_135902_;
}
public ChainedJsonException(String p_135904_, Throwable p_135905_) {
super(p_135905_);
this.entries.add(new ChainedJsonException.Entry());
this.message = p_135904_;
}
public void prependJsonKey(String pKey) {
this.entries.get(0).addJsonKey(pKey);
}
public void setFilenameAndFlush(String pFilename) {
(this.entries.get(0)).filename = pFilename;
this.entries.add(0, new ChainedJsonException.Entry());
}
public String getMessage() {
return "Invalid " + this.entries.get(this.entries.size() - 1) + ": " + this.message;
}
public static ChainedJsonException forException(Exception pException) {
if (pException instanceof ChainedJsonException) {
return (ChainedJsonException)pException;
} else {
String s = pException.getMessage();
if (pException instanceof FileNotFoundException) {
s = "File not found";
}
return new ChainedJsonException(s, pException);
}
}
public static class Entry {
@Nullable
String filename;
private final List<String> jsonKeys = Lists.newArrayList();
Entry() {
}
void addJsonKey(String pKey) {
this.jsonKeys.add(0, pKey);
}
@Nullable
public String getFilename() {
return this.filename;
}
public String getJsonKeys() {
return StringUtils.join(this.jsonKeys, "->");
}
public String toString() {
if (this.filename != null) {
return this.jsonKeys.isEmpty() ? this.filename : this.filename + " " + this.getJsonKeys();
} else {
return this.jsonKeys.isEmpty() ? "(Unknown file)" : "(Unknown file) " + this.getJsonKeys();
}
}
}
}
@@ -0,0 +1,13 @@
package net.minecraft.server;
import net.minecraft.commands.CommandSourceStack;
public class ConsoleInput {
public final String msg;
public final CommandSourceStack source;
public ConsoleInput(String pMsg, CommandSourceStack pSource) {
this.msg = pMsg;
this.source = pSource;
}
}
@@ -0,0 +1,19 @@
package net.minecraft.server;
import com.mojang.logging.LogUtils;
import java.io.OutputStream;
import org.slf4j.Logger;
public class DebugLoggedPrintStream extends LoggedPrintStream {
private static final Logger LOGGER = LogUtils.getLogger();
public DebugLoggedPrintStream(String p_135934_, OutputStream p_135935_) {
super(p_135934_, p_135935_);
}
protected void logLine(String pString) {
StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace();
StackTraceElement stacktraceelement = astacktraceelement[Math.min(3, astacktraceelement.length)];
LOGGER.info("[{}]@.({}:{}): {}", this.name, stacktraceelement.getFileName(), stacktraceelement.getLineNumber(), pString);
}
}
@@ -0,0 +1,50 @@
package net.minecraft.server;
import com.mojang.logging.LogUtils;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import net.minecraft.SharedConstants;
import org.slf4j.Logger;
public class Eula {
private static final Logger LOGGER = LogUtils.getLogger();
private final Path file;
private final boolean agreed;
public Eula(Path pFile) {
this.file = pFile;
this.agreed = SharedConstants.IS_RUNNING_IN_IDE || net.minecraftforge.gametest.ForgeGameTestHooks.isGametestServer() || this.readFile(); // Forge: Automatically agree to EULA for gametest servers to aid CI
}
private boolean readFile() {
try (InputStream inputstream = Files.newInputStream(this.file)) {
Properties properties = new Properties();
properties.load(inputstream);
return Boolean.parseBoolean(properties.getProperty("eula", "false"));
} catch (Exception exception) {
LOGGER.warn("Failed to load {}", (Object)this.file);
this.saveDefaults();
return false;
}
}
public boolean hasAgreedToEULA() {
return this.agreed;
}
private void saveDefaults() {
if (!SharedConstants.IS_RUNNING_IN_IDE) {
try (OutputStream outputstream = Files.newOutputStream(this.file)) {
Properties properties = new Properties();
properties.setProperty("eula", "false");
properties.store(outputstream, "By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA).");
} catch (Exception exception) {
LOGGER.warn("Failed to save {}", this.file, exception);
}
}
}
}
@@ -0,0 +1,29 @@
package net.minecraft.server;
import com.mojang.logging.LogUtils;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.annotation.Nullable;
import org.slf4j.Logger;
public class LoggedPrintStream extends PrintStream {
private static final Logger LOGGER = LogUtils.getLogger();
protected final String name;
public LoggedPrintStream(String p_135951_, OutputStream p_135952_) {
super(p_135952_);
this.name = p_135951_;
}
public void println(@Nullable String p_135957_) {
this.logLine(p_135957_);
}
public void println(Object p_135955_) {
this.logLine(String.valueOf(p_135955_));
}
protected void logLine(@Nullable String pString) {
LOGGER.info("[{}]: {}", this.name, pString);
}
}
@@ -0,0 +1,301 @@
package net.minecraft.server;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.datafixers.DataFixer;
import com.mojang.datafixers.util.Pair;
import com.mojang.logging.LogUtils;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.Lifecycle;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BooleanSupplier;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import joptsimple.util.PathConverter;
import net.minecraft.CrashReport;
import net.minecraft.DefaultUncaughtExceptionHandler;
import net.minecraft.SharedConstants;
import net.minecraft.Util;
import net.minecraft.commands.Commands;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.obfuscate.DontObfuscate;
import net.minecraft.resources.RegistryOps;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.dedicated.DedicatedServerProperties;
import net.minecraft.server.dedicated.DedicatedServerSettings;
import net.minecraft.server.level.progress.LoggerChunkProgressListener;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.util.Mth;
import net.minecraft.util.datafix.DataFixers;
import net.minecraft.util.profiling.jfr.Environment;
import net.minecraft.util.profiling.jfr.JvmProfiler;
import net.minecraft.util.worldupdate.WorldUpgrader;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.WorldDataConfiguration;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.WorldDimensions;
import net.minecraft.world.level.levelgen.WorldOptions;
import net.minecraft.world.level.levelgen.presets.WorldPresets;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.LevelSummary;
import net.minecraft.world.level.storage.PrimaryLevelData;
import net.minecraft.world.level.storage.WorldData;
import org.slf4j.Logger;
public class Main {
private static final Logger LOGGER = LogUtils.getLogger();
@DontObfuscate
public static void main(String[] pArgs) {
SharedConstants.tryDetectVersion();
OptionParser optionparser = new OptionParser();
OptionSpec<Void> optionspec = optionparser.accepts("nogui");
OptionSpec<Void> optionspec1 = optionparser.accepts("initSettings", "Initializes 'server.properties' and 'eula.txt', then quits");
OptionSpec<Void> optionspec2 = optionparser.accepts("demo");
OptionSpec<Void> optionspec3 = optionparser.accepts("bonusChest");
OptionSpec<Void> optionspec4 = optionparser.accepts("forceUpgrade");
OptionSpec<Void> optionspec5 = optionparser.accepts("eraseCache");
OptionSpec<Void> optionspec6 = optionparser.accepts("safeMode", "Loads level with vanilla datapack only");
OptionSpec<Void> optionspec7 = optionparser.accepts("help").forHelp();
OptionSpec<String> optionspec8 = optionparser.accepts("singleplayer").withRequiredArg();
OptionSpec<String> optionspec9 = optionparser.accepts("universe").withRequiredArg().defaultsTo(".");
OptionSpec<String> optionspec10 = optionparser.accepts("world").withRequiredArg();
OptionSpec<Integer> optionspec11 = optionparser.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1);
OptionSpec<String> optionspec12 = optionparser.accepts("serverId").withRequiredArg();
OptionSpec<Void> optionspec13 = optionparser.accepts("jfrProfile");
OptionSpec<Path> optionspec14 = optionparser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter());
OptionSpec<String> optionspec15 = optionparser.nonOptions();
optionparser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed
optionparser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side.
final OptionSpec<net.minecraft.core.BlockPos> spawnPosOpt;
boolean gametestEnabled = Boolean.getBoolean("forge.gameTestServer");
if (gametestEnabled) {
spawnPosOpt = optionparser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0));
} else {
spawnPosOpt = null;
}
try {
OptionSet optionset = optionparser.parse(pArgs);
if (optionset.has(optionspec7)) {
optionparser.printHelpOn(System.err);
return;
}
Path path2 = Paths.get("eula.txt");
Eula eula = new Eula(path2);
if (!eula.hasAgreedToEULA()) {
LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info.");
return;
}
Path path = optionset.valueOf(optionspec14);
if (path != null) {
writePidFile(path);
}
CrashReport.preload();
if (optionset.has(optionspec13)) {
JvmProfiler.INSTANCE.start(Environment.SERVER);
}
Bootstrap.bootStrap();
Bootstrap.validate();
Util.startTimerHackThread();
Path path1 = Paths.get("server.properties");
if (!optionset.has(optionspec1)) net.minecraftforge.server.loading.ServerModLoader.load(); // Load mods before we load almost anything else anymore. Single spot now. Only loads if they haven't passed the initserver param
DedicatedServerSettings dedicatedserversettings = new DedicatedServerSettings(path1);
dedicatedserversettings.forceSave();
if (optionset.has(optionspec1)) {
LOGGER.info("Initialized '{}' and '{}'", path1.toAbsolutePath(), path2.toAbsolutePath());
return;
}
File file1 = new File(optionset.valueOf(optionspec9));
Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), file1);
String s = Optional.ofNullable(optionset.valueOf(optionspec10)).orElse(dedicatedserversettings.getProperties().levelName);
if (s == null || s.isEmpty() || new File(file1, s).getAbsolutePath().equals(new File(s).getAbsolutePath())) {
LOGGER.error("Invalid world directory specified, must not be null, empty or the same directory as your universe! " + s);
return;
}
LevelStorageSource levelstoragesource = LevelStorageSource.createDefault(file1.toPath());
LevelStorageSource.LevelStorageAccess levelstoragesource$levelstorageaccess = levelstoragesource.validateAndCreateAccess(s);
levelstoragesource$levelstorageaccess.readAdditionalLevelSaveData();
LevelSummary levelsummary = levelstoragesource$levelstorageaccess.getSummary();
if (levelsummary != null) {
if (levelsummary.requiresManualConversion()) {
LOGGER.info("This world must be opened in an older version (like 1.6.4) to be safely converted");
return;
}
if (!levelsummary.isCompatible()) {
LOGGER.info("This world was created by an incompatible version.");
return;
}
}
boolean flag = optionset.has(optionspec6);
if (flag) {
LOGGER.warn("Safe mode active, only vanilla datapack will be loaded");
}
PackRepository packrepository = ServerPacksSource.createPackRepository(levelstoragesource$levelstorageaccess.getLevelPath(LevelResource.DATAPACK_DIR));
WorldStem worldstem;
try {
WorldLoader.InitConfig worldloader$initconfig = loadOrCreateConfig(dedicatedserversettings.getProperties(), levelstoragesource$levelstorageaccess, flag, packrepository);
worldstem = Util.blockUntilDone((p_248086_) -> {
return WorldLoader.load(worldloader$initconfig, (p_248079_) -> {
Registry<LevelStem> registry = p_248079_.datapackDimensions().registryOrThrow(Registries.LEVEL_STEM);
DynamicOps<Tag> dynamicops = RegistryOps.create(NbtOps.INSTANCE, p_248079_.datapackWorldgen());
Pair<WorldData, WorldDimensions.Complete> pair = levelstoragesource$levelstorageaccess.getDataTag(dynamicops, p_248079_.dataConfiguration(), registry, p_248079_.datapackWorldgen().allRegistriesLifecycle());
if (pair != null) {
return new WorldLoader.DataLoadOutput<>(pair.getFirst(), pair.getSecond().dimensionsRegistryAccess());
} else {
LevelSettings levelsettings;
WorldOptions worldoptions;
WorldDimensions worlddimensions;
if (optionset.has(optionspec2)) {
levelsettings = MinecraftServer.DEMO_SETTINGS;
worldoptions = WorldOptions.DEMO_OPTIONS;
worlddimensions = WorldPresets.createNormalWorldDimensions(p_248079_.datapackWorldgen());
} else {
DedicatedServerProperties dedicatedserverproperties = dedicatedserversettings.getProperties();
levelsettings = new LevelSettings(dedicatedserverproperties.levelName, dedicatedserverproperties.gamemode, dedicatedserverproperties.hardcore, dedicatedserverproperties.difficulty, false, new GameRules(), p_248079_.dataConfiguration());
worldoptions = optionset.has(optionspec3) ? dedicatedserverproperties.worldOptions.withBonusChest(true) : dedicatedserverproperties.worldOptions;
worlddimensions = dedicatedserverproperties.createDimensions(p_248079_.datapackWorldgen());
}
//Forge: Do a write-read-cycle to inject modded dimensions on first start of a dedicated server into its generated world dimensions list.
worlddimensions = WorldDimensions.CODEC.encoder().encodeStart(dynamicops, worlddimensions).flatMap((writtenPayloadWithModdedDimensions) -> WorldDimensions.CODEC.decoder().parse(dynamicops, writtenPayloadWithModdedDimensions)).resultOrPartial(LOGGER::error).orElse(worlddimensions);
WorldDimensions.Complete worlddimensions$complete = worlddimensions.bake(registry);
Lifecycle lifecycle = worlddimensions$complete.lifecycle().add(p_248079_.datapackWorldgen().allRegistriesLifecycle());
return new WorldLoader.DataLoadOutput<>(new PrimaryLevelData(levelsettings, worldoptions, worlddimensions$complete.specialWorldProperty(), lifecycle), worlddimensions$complete.dimensionsRegistryAccess());
}
}, WorldStem::new, Util.backgroundExecutor(), p_248086_);
}).get();
} catch (Exception exception) {
LOGGER.warn("Failed to load datapacks, can't proceed with server load. You can either fix your datapacks or reset to vanilla with --safeMode", (Throwable)exception);
return;
}
RegistryAccess.Frozen registryaccess$frozen = worldstem.registries().compositeAccess();
if (optionset.has(optionspec4)) {
forceUpgrade(levelstoragesource$levelstorageaccess, DataFixers.getDataFixer(), optionset.has(optionspec5), () -> {
return true;
}, registryaccess$frozen.registryOrThrow(Registries.LEVEL_STEM));
}
WorldData worlddata = worldstem.worldData();
levelstoragesource$levelstorageaccess.saveDataTag(registryaccess$frozen, worlddata);
final MinecraftServer dedicatedserver = MinecraftServer.spin((p_129697_) -> {
MinecraftServer dedicatedserver1;
if (gametestEnabled) {
net.minecraftforge.gametest.ForgeGameTestHooks.registerGametests();
java.util.Collection<net.minecraft.gametest.framework.GameTestBatch> testBatches = net.minecraft.gametest.framework.GameTestRunner.groupTestsIntoBatches(net.minecraft.gametest.framework.GameTestRegistry.getAllTestFunctions());
net.minecraft.core.BlockPos spawnPos = optionset.valueOf(spawnPosOpt);
dedicatedserver1 = new net.minecraft.gametest.framework.GameTestServer(p_129697_, levelstoragesource$levelstorageaccess, packrepository, worldstem, testBatches, spawnPos);
} else {
dedicatedserver1 = new DedicatedServer(p_129697_, levelstoragesource$levelstorageaccess, packrepository, worldstem, dedicatedserversettings, DataFixers.getDataFixer(), services, LoggerChunkProgressListener::new);
}
dedicatedserver1.setSingleplayerProfile(optionset.has(optionspec8) ? new GameProfile((UUID)null, optionset.valueOf(optionspec8)) : null);
dedicatedserver1.setPort(optionset.valueOf(optionspec11));
dedicatedserver1.setDemo(optionset.has(optionspec2));
dedicatedserver1.setId(optionset.valueOf(optionspec12));
boolean flag1 = !optionset.has(optionspec) && !optionset.valuesOf(optionspec15).contains("nogui");
if (dedicatedserver1 instanceof DedicatedServer dedicatedServer && flag1 && !GraphicsEnvironment.isHeadless()) {
dedicatedServer.showGui();
}
return dedicatedserver1;
});
Thread thread = new Thread("Server Shutdown Thread") {
public void run() {
// FORGE: Halting as GameTestServer will cause issues as it always calls System#exit on both crash and normal exit, so skip it
if (!(dedicatedserver instanceof net.minecraft.gametest.framework.GameTestServer))
dedicatedserver.halt(true);
org.apache.logging.log4j.LogManager.shutdown(); // we're manually managing the logging shutdown on the server. Make sure we do it here at the end.
}
};
thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
Runtime.getRuntime().addShutdownHook(thread);
} catch (Exception exception1) {
LOGGER.error(LogUtils.FATAL_MARKER, "Failed to start the minecraft server", (Throwable)exception1);
}
}
private static void writePidFile(Path pPath) {
try {
long i = ProcessHandle.current().pid();
Files.writeString(pPath, Long.toString(i));
} catch (IOException ioexception) {
throw new UncheckedIOException(ioexception);
}
}
private static WorldLoader.InitConfig loadOrCreateConfig(DedicatedServerProperties pServerProperties, LevelStorageSource.LevelStorageAccess pLevelStorage, boolean pSafeMode, PackRepository pPackRepository) {
WorldDataConfiguration worlddataconfiguration = pLevelStorage.getDataConfiguration();
WorldDataConfiguration worlddataconfiguration1;
boolean flag;
if (worlddataconfiguration != null) {
flag = false;
worlddataconfiguration1 = worlddataconfiguration;
} else {
flag = true;
worlddataconfiguration1 = new WorldDataConfiguration(pServerProperties.initialDataPackConfiguration, FeatureFlags.DEFAULT_FLAGS);
}
WorldLoader.PackConfig worldloader$packconfig = new WorldLoader.PackConfig(pPackRepository, worlddataconfiguration1, pSafeMode, flag);
return new WorldLoader.InitConfig(worldloader$packconfig, Commands.CommandSelection.DEDICATED, pServerProperties.functionPermissionLevel);
}
private static void forceUpgrade(LevelStorageSource.LevelStorageAccess pLevelStorage, DataFixer pDataFixer, boolean pEraseCache, BooleanSupplier pUpgradeWorld, Registry<LevelStem> pDimesions) {
LOGGER.info("Forcing world upgrade!");
WorldUpgrader worldupgrader = new WorldUpgrader(pLevelStorage, pDataFixer, pDimesions, pEraseCache);
Component component = null;
while(!worldupgrader.isFinished()) {
Component component1 = worldupgrader.getStatus();
if (component != component1) {
component = component1;
LOGGER.info(worldupgrader.getStatus().getString());
}
int i = worldupgrader.getTotalChunks();
if (i > 0) {
int j = worldupgrader.getConverted() + worldupgrader.getSkipped();
LOGGER.info("{}% completed ({} / {} chunks)...", Mth.floor((float)j / (float)i * 100.0F), j, i);
}
if (!pUpgradeWorld.getAsBoolean()) {
worldupgrader.cancel();
} else {
try {
Thread.sleep(1000L);
} catch (InterruptedException interruptedexception) {
}
}
}
}
}
@@ -0,0 +1,328 @@
package net.minecraft.server;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.mojang.datafixers.DataFixer;
import com.mojang.logging.LogUtils;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.JsonOps;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import net.minecraft.FileUtil;
import net.minecraft.SharedConstants;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.advancements.Criterion;
import net.minecraft.advancements.CriterionProgress;
import net.minecraft.advancements.CriterionTrigger;
import net.minecraft.advancements.CriterionTriggerInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundSelectAdvancementsTabPacket;
import net.minecraft.network.protocol.game.ClientboundUpdateAdvancementsPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.advancements.AdvancementVisibilityEvaluator;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.util.datafix.DataFixTypes;
import net.minecraft.world.level.GameRules;
import org.slf4j.Logger;
public class PlayerAdvancements {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Gson GSON = (new GsonBuilder()).registerTypeAdapter(AdvancementProgress.class, new AdvancementProgress.Serializer()).registerTypeAdapter(ResourceLocation.class, new ResourceLocation.Serializer()).setPrettyPrinting().create();
private static final TypeToken<Map<ResourceLocation, AdvancementProgress>> TYPE_TOKEN = new TypeToken<Map<ResourceLocation, AdvancementProgress>>() {
};
private final DataFixer dataFixer;
private final PlayerList playerList;
private final Path playerSavePath;
private final Map<Advancement, AdvancementProgress> progress = new LinkedHashMap<>();
private final Set<Advancement> visible = new HashSet<>();
private final Set<Advancement> progressChanged = new HashSet<>();
private final Set<Advancement> rootsToUpdate = new HashSet<>();
private ServerPlayer player;
@Nullable
private Advancement lastSelectedTab;
private boolean isFirstPacket = true;
public PlayerAdvancements(DataFixer pDataFixer, PlayerList pPlayerList, ServerAdvancementManager pManager, Path pPlayerSavePath, ServerPlayer pPlayer) {
this.dataFixer = pDataFixer;
this.playerList = pPlayerList;
this.playerSavePath = pPlayerSavePath;
this.player = pPlayer;
this.load(pManager);
}
public void setPlayer(ServerPlayer pPlayer) {
this.player = pPlayer;
}
public void stopListening() {
for(CriterionTrigger<?> criteriontrigger : CriteriaTriggers.all()) {
criteriontrigger.removePlayerListeners(this);
}
}
public void reload(ServerAdvancementManager pManager) {
this.stopListening();
this.progress.clear();
this.visible.clear();
this.rootsToUpdate.clear();
this.progressChanged.clear();
this.isFirstPacket = true;
this.lastSelectedTab = null;
this.load(pManager);
}
private void registerListeners(ServerAdvancementManager pManager) {
for(Advancement advancement : pManager.getAllAdvancements()) {
this.registerListeners(advancement);
}
}
private void checkForAutomaticTriggers(ServerAdvancementManager pManager) {
for(Advancement advancement : pManager.getAllAdvancements()) {
if (advancement.getCriteria().isEmpty()) {
this.award(advancement, "");
advancement.getRewards().grant(this.player);
}
}
}
private void load(ServerAdvancementManager pManager) {
if (Files.isRegularFile(this.playerSavePath)) {
try (JsonReader jsonreader = new JsonReader(Files.newBufferedReader(this.playerSavePath, StandardCharsets.UTF_8))) {
jsonreader.setLenient(false);
Dynamic<JsonElement> dynamic = new Dynamic<>(JsonOps.INSTANCE, Streams.parse(jsonreader));
int i = dynamic.get("DataVersion").asInt(1343);
dynamic = dynamic.remove("DataVersion");
dynamic = DataFixTypes.ADVANCEMENTS.updateToCurrentVersion(this.dataFixer, dynamic, i);
Map<ResourceLocation, AdvancementProgress> map = GSON.getAdapter(TYPE_TOKEN).fromJsonTree(dynamic.getValue());
if (map == null) {
throw new JsonParseException("Found null for advancements");
}
map.entrySet().stream().sorted(Entry.comparingByValue()).forEach((p_265663_) -> {
Advancement advancement = pManager.getAdvancement(p_265663_.getKey());
if (advancement == null) {
LOGGER.warn("Ignored advancement '{}' in progress file {} - it doesn't exist anymore?", p_265663_.getKey(), this.playerSavePath);
} else {
this.startProgress(advancement, p_265663_.getValue());
this.progressChanged.add(advancement);
this.markForVisibilityUpdate(advancement);
}
});
} catch (JsonParseException jsonparseexception) {
LOGGER.error("Couldn't parse player advancements in {}", this.playerSavePath, jsonparseexception);
} catch (IOException ioexception) {
LOGGER.error("Couldn't access player advancements in {}", this.playerSavePath, ioexception);
}
}
this.checkForAutomaticTriggers(pManager);
this.registerListeners(pManager);
}
public void save() {
Map<ResourceLocation, AdvancementProgress> map = new LinkedHashMap<>();
for(Map.Entry<Advancement, AdvancementProgress> entry : this.progress.entrySet()) {
AdvancementProgress advancementprogress = entry.getValue();
if (advancementprogress.hasProgress()) {
map.put(entry.getKey().getId(), advancementprogress);
}
}
JsonElement jsonelement = GSON.toJsonTree(map);
jsonelement.getAsJsonObject().addProperty("DataVersion", SharedConstants.getCurrentVersion().getDataVersion().getVersion());
try {
FileUtil.createDirectoriesSafe(this.playerSavePath.getParent());
try (Writer writer = Files.newBufferedWriter(this.playerSavePath, StandardCharsets.UTF_8)) {
GSON.toJson(jsonelement, writer);
}
} catch (IOException ioexception) {
LOGGER.error("Couldn't save player advancements to {}", this.playerSavePath, ioexception);
}
}
public boolean award(Advancement pAdvancement, String pCriterionKey) {
// Forge: don't grant advancements for fake players
if (this.player instanceof net.minecraftforge.common.util.FakePlayer) return false;
boolean flag = false;
AdvancementProgress advancementprogress = this.getOrStartProgress(pAdvancement);
boolean flag1 = advancementprogress.isDone();
if (advancementprogress.grantProgress(pCriterionKey)) {
this.unregisterListeners(pAdvancement);
this.progressChanged.add(pAdvancement);
flag = true;
net.minecraftforge.event.ForgeEventFactory.onAdvancementProgressedEvent(this.player, pAdvancement, advancementprogress, pCriterionKey, net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent.ProgressType.GRANT);
if (!flag1 && advancementprogress.isDone()) {
pAdvancement.getRewards().grant(this.player);
if (pAdvancement.getDisplay() != null && pAdvancement.getDisplay().shouldAnnounceChat() && this.player.level().getGameRules().getBoolean(GameRules.RULE_ANNOUNCE_ADVANCEMENTS)) {
this.playerList.broadcastSystemMessage(Component.translatable("chat.type.advancement." + pAdvancement.getDisplay().getFrame().getName(), this.player.getDisplayName(), pAdvancement.getChatComponent()), false);
}
net.minecraftforge.event.ForgeEventFactory.onAdvancementEarnedEvent(this.player, pAdvancement);
}
}
if (!flag1 && advancementprogress.isDone()) {
this.markForVisibilityUpdate(pAdvancement);
}
return flag;
}
public boolean revoke(Advancement pAdvancement, String pCriterionKey) {
boolean flag = false;
AdvancementProgress advancementprogress = this.getOrStartProgress(pAdvancement);
boolean flag1 = advancementprogress.isDone();
if (advancementprogress.revokeProgress(pCriterionKey)) {
this.registerListeners(pAdvancement);
this.progressChanged.add(pAdvancement);
flag = true;
net.minecraftforge.event.ForgeEventFactory.onAdvancementProgressedEvent(this.player, pAdvancement, advancementprogress, pCriterionKey, net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent.ProgressType.REVOKE);
}
if (flag1 && !advancementprogress.isDone()) {
this.markForVisibilityUpdate(pAdvancement);
}
return flag;
}
private void markForVisibilityUpdate(Advancement pAdvancement) {
this.rootsToUpdate.add(pAdvancement.getRoot());
}
private void registerListeners(Advancement pAdvancement) {
AdvancementProgress advancementprogress = this.getOrStartProgress(pAdvancement);
if (!advancementprogress.isDone()) {
for(Map.Entry<String, Criterion> entry : pAdvancement.getCriteria().entrySet()) {
CriterionProgress criterionprogress = advancementprogress.getCriterion(entry.getKey());
if (criterionprogress != null && !criterionprogress.isDone()) {
CriterionTriggerInstance criteriontriggerinstance = entry.getValue().getTrigger();
if (criteriontriggerinstance != null) {
CriterionTrigger<CriterionTriggerInstance> criteriontrigger = CriteriaTriggers.getCriterion(criteriontriggerinstance.getCriterion());
if (criteriontrigger != null) {
criteriontrigger.addPlayerListener(this, new CriterionTrigger.Listener<>(criteriontriggerinstance, pAdvancement, entry.getKey()));
}
}
}
}
}
}
private void unregisterListeners(Advancement pAdvancement) {
AdvancementProgress advancementprogress = this.getOrStartProgress(pAdvancement);
for(Map.Entry<String, Criterion> entry : pAdvancement.getCriteria().entrySet()) {
CriterionProgress criterionprogress = advancementprogress.getCriterion(entry.getKey());
if (criterionprogress != null && (criterionprogress.isDone() || advancementprogress.isDone())) {
CriterionTriggerInstance criteriontriggerinstance = entry.getValue().getTrigger();
if (criteriontriggerinstance != null) {
CriterionTrigger<CriterionTriggerInstance> criteriontrigger = CriteriaTriggers.getCriterion(criteriontriggerinstance.getCriterion());
if (criteriontrigger != null) {
criteriontrigger.removePlayerListener(this, new CriterionTrigger.Listener<>(criteriontriggerinstance, pAdvancement, entry.getKey()));
}
}
}
}
}
public void flushDirty(ServerPlayer pServerPlayer) {
if (this.isFirstPacket || !this.rootsToUpdate.isEmpty() || !this.progressChanged.isEmpty()) {
Map<ResourceLocation, AdvancementProgress> map = new HashMap<>();
Set<Advancement> set = new HashSet<>();
Set<ResourceLocation> set1 = new HashSet<>();
for(Advancement advancement : this.rootsToUpdate) {
this.updateTreeVisibility(advancement, set, set1);
}
this.rootsToUpdate.clear();
for(Advancement advancement1 : this.progressChanged) {
if (this.visible.contains(advancement1)) {
map.put(advancement1.getId(), this.progress.get(advancement1));
}
}
this.progressChanged.clear();
if (!map.isEmpty() || !set.isEmpty() || !set1.isEmpty()) {
pServerPlayer.connection.send(new ClientboundUpdateAdvancementsPacket(this.isFirstPacket, set, set1, map));
}
}
this.isFirstPacket = false;
}
public void setSelectedTab(@Nullable Advancement pAdvancement) {
Advancement advancement = this.lastSelectedTab;
if (pAdvancement != null && pAdvancement.getParent() == null && pAdvancement.getDisplay() != null) {
this.lastSelectedTab = pAdvancement;
} else {
this.lastSelectedTab = null;
}
if (advancement != this.lastSelectedTab) {
this.player.connection.send(new ClientboundSelectAdvancementsTabPacket(this.lastSelectedTab == null ? null : this.lastSelectedTab.getId()));
}
}
public AdvancementProgress getOrStartProgress(Advancement pAdvancement) {
AdvancementProgress advancementprogress = this.progress.get(pAdvancement);
if (advancementprogress == null) {
advancementprogress = new AdvancementProgress();
this.startProgress(pAdvancement, advancementprogress);
}
return advancementprogress;
}
private void startProgress(Advancement pAdvancement, AdvancementProgress pProgress) {
pProgress.update(pAdvancement.getCriteria(), pAdvancement.getRequirements());
this.progress.put(pAdvancement, pProgress);
}
private void updateTreeVisibility(Advancement pAdvancement, Set<Advancement> p_265206_, Set<ResourceLocation> p_265593_) {
AdvancementVisibilityEvaluator.evaluateVisibility(pAdvancement, (p_265787_) -> {
return this.getOrStartProgress(p_265787_).isDone();
}, (p_265247_, p_265330_) -> {
if (p_265330_) {
if (this.visible.add(p_265247_)) {
p_265206_.add(p_265247_);
if (this.progress.containsKey(p_265247_)) {
this.progressChanged.add(p_265247_);
}
}
} else if (this.visible.remove(p_265247_)) {
p_265593_.add(p_265247_.getId());
}
});
}
}
@@ -0,0 +1,20 @@
package net.minecraft.server;
import java.util.List;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries;
public enum RegistryLayer {
STATIC,
WORLDGEN,
DIMENSIONS,
RELOADABLE;
private static final List<RegistryLayer> VALUES = List.of(values());
private static final RegistryAccess.Frozen STATIC_ACCESS = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY);
public static LayeredRegistryAccess<RegistryLayer> createRegistryAccess() {
return (new LayeredRegistryAccess<>(VALUES)).replaceFrom(STATIC, STATIC_ACCESS);
}
}
@@ -0,0 +1,113 @@
package net.minecraft.server;
import com.mojang.logging.LogUtils;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.Commands;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleReloadInstance;
import net.minecraft.tags.TagKey;
import net.minecraft.tags.TagManager;
import net.minecraft.util.Unit;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.storage.loot.LootDataManager;
import org.slf4j.Logger;
public class ReloadableServerResources {
private static final Logger LOGGER = LogUtils.getLogger();
private static final CompletableFuture<Unit> DATA_RELOAD_INITIAL_TASK = CompletableFuture.completedFuture(Unit.INSTANCE);
private final CommandBuildContext.Configurable commandBuildContext;
private final Commands commands;
private final RecipeManager recipes;
private final TagManager tagManager;
private final LootDataManager lootData = new LootDataManager();
private final ServerAdvancementManager advancements;
private final ServerFunctionLibrary functionLibrary;
public ReloadableServerResources(RegistryAccess.Frozen p_206857_, FeatureFlagSet p_250695_, Commands.CommandSelection p_206858_, int p_206859_) {
this.tagManager = new TagManager(p_206857_);
this.commandBuildContext = CommandBuildContext.configurable(p_206857_, p_250695_);
this.commands = new Commands(p_206858_, this.commandBuildContext);
this.commandBuildContext.missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy.CREATE_NEW);
this.functionLibrary = new ServerFunctionLibrary(p_206859_, this.commands.getDispatcher());
// Forge: Create context object and pass it to the recipe manager.
this.context = new net.minecraftforge.common.crafting.conditions.ConditionContext(this.tagManager);
this.recipes = new RecipeManager(context);
this.advancements = new ServerAdvancementManager(this.lootData, context);
}
public ServerFunctionLibrary getFunctionLibrary() {
return this.functionLibrary;
}
public LootDataManager getLootData() {
return this.lootData;
}
public RecipeManager getRecipeManager() {
return this.recipes;
}
public Commands getCommands() {
return this.commands;
}
public ServerAdvancementManager getAdvancements() {
return this.advancements;
}
public List<PreparableReloadListener> listeners() {
return List.of(this.tagManager, this.lootData, this.recipes, this.functionLibrary, this.advancements);
}
public static CompletableFuture<ReloadableServerResources> loadResources(ResourceManager p_248588_, RegistryAccess.Frozen p_251163_, FeatureFlagSet p_250212_, Commands.CommandSelection p_249301_, int p_251126_, Executor p_249136_, Executor p_249601_) {
ReloadableServerResources reloadableserverresources = new ReloadableServerResources(p_251163_, p_250212_, p_249301_, p_251126_);
List<PreparableReloadListener> listeners = new java.util.ArrayList<>(reloadableserverresources.listeners());
listeners.addAll(net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, p_251163_));
return SimpleReloadInstance.create(p_248588_, listeners, p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled()).done().whenComplete((p_214309_, p_214310_) -> {
reloadableserverresources.commandBuildContext.missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy.FAIL);
}).thenApply((p_214306_) -> {
return reloadableserverresources;
});
}
public void updateRegistryTags(RegistryAccess p_206869_) {
this.tagManager.getResult().forEach((p_214315_) -> {
updateRegistryTags(p_206869_, p_214315_);
});
Blocks.rebuildCache();
net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.TagsUpdatedEvent(p_206869_, false, false));
}
private static <T> void updateRegistryTags(RegistryAccess p_206871_, TagManager.LoadResult<T> p_206872_) {
ResourceKey<? extends Registry<T>> resourcekey = p_206872_.key();
Map<TagKey<T>, List<Holder<T>>> map = p_206872_.tags().entrySet().stream().collect(Collectors.toUnmodifiableMap((p_214303_) -> {
return TagKey.create(resourcekey, p_214303_.getKey());
}, (p_214312_) -> {
return List.copyOf(p_214312_.getValue());
}));
p_206871_.registryOrThrow(resourcekey).bindTags(map);
}
private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context;
/**
* Exposes the current condition context for usage in other reload listeners.<br>
* This is not useful outside the reloading stage.
* @return The condition context for the currently active reload.
*/
public net.minecraftforge.common.crafting.conditions.ICondition.IContext getConditionContext() {
return this.context;
}
}
@@ -0,0 +1,14 @@
package net.minecraft.server;
public final class RunningOnDifferentThreadException extends RuntimeException {
public static final RunningOnDifferentThreadException RUNNING_ON_DIFFERENT_THREAD = new RunningOnDifferentThreadException();
private RunningOnDifferentThreadException() {
this.setStackTrace(new StackTraceElement[0]);
}
public synchronized Throwable fillInStackTrace() {
this.setStackTrace(new StackTraceElement[0]);
return this;
}
}
@@ -0,0 +1,79 @@
package net.minecraft.server;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.logging.LogUtils;
import java.util.Collection;
import java.util.Map;
import javax.annotation.Nullable;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementList;
import net.minecraft.advancements.TreeNodePosition;
import net.minecraft.advancements.critereon.DeserializationContext;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.level.storage.loot.LootDataManager;
import org.slf4j.Logger;
public class ServerAdvancementManager extends SimpleJsonResourceReloadListener {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Gson GSON = (new GsonBuilder()).create();
private AdvancementList advancements = new AdvancementList();
private final LootDataManager lootData;
private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; //Forge: add context
/** @deprecated Forge: use {@linkplain ServerAdvancementManager#ServerAdvancementManager(LootDataManager, net.minecraftforge.common.crafting.conditions.ICondition.IContext) constructor with context}. */
@Deprecated
public ServerAdvancementManager(LootDataManager p_279237_) {
this(p_279237_, net.minecraftforge.common.crafting.conditions.ICondition.IContext.EMPTY);
}
public ServerAdvancementManager(LootDataManager p_279237_, net.minecraftforge.common.crafting.conditions.ICondition.IContext context) {
super(GSON, "advancements");
this.lootData = p_279237_;
this.context = context;
}
protected void apply(Map<ResourceLocation, JsonElement> pObject, ResourceManager pResourceManager, ProfilerFiller pProfiler) {
Map<ResourceLocation, Advancement.Builder> map = Maps.newHashMap();
pObject.forEach((p_278903_, p_278904_) -> {
try {
JsonObject jsonobject = GsonHelper.convertToJsonObject(p_278904_, "advancement");
Advancement.Builder advancement$builder = Advancement.Builder.fromJson(jsonobject, new DeserializationContext(p_278903_, this.lootData), this.context);
if (advancement$builder == null) {
LOGGER.debug("Skipping loading advancement {} as its conditions were not met", p_278903_);
return;
}
map.put(p_278903_, advancement$builder);
} catch (Exception exception) {
LOGGER.error("Parsing error loading custom advancement {}: {}", p_278903_, exception.getMessage());
}
});
AdvancementList advancementlist = new AdvancementList();
advancementlist.add(map);
for(Advancement advancement : advancementlist.getRoots()) {
if (advancement.getDisplay() != null) {
TreeNodePosition.run(advancement);
}
}
this.advancements = advancementlist;
}
@Nullable
public Advancement getAdvancement(ResourceLocation pId) {
return this.advancements.get(pId);
}
public Collection<Advancement> getAllAdvancements() {
return this.advancements.getAllAdvancements();
}
}
@@ -0,0 +1,114 @@
package net.minecraft.server;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.datafixers.util.Pair;
import com.mojang.logging.LogUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import net.minecraft.commands.CommandFunction;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.resources.FileToIdConverter;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import org.slf4j.Logger;
public class ServerFunctionLibrary implements PreparableReloadListener {
private static final Logger LOGGER = LogUtils.getLogger();
private static final FileToIdConverter LISTER = new FileToIdConverter("functions", ".mcfunction");
private volatile Map<ResourceLocation, CommandFunction> functions = ImmutableMap.of();
private final TagLoader<CommandFunction> tagsLoader = new TagLoader<>(this::getFunction, "tags/functions");
private volatile Map<ResourceLocation, Collection<CommandFunction>> tags = Map.of();
private final int functionCompilationLevel;
private final CommandDispatcher<CommandSourceStack> dispatcher;
public Optional<CommandFunction> getFunction(ResourceLocation p_136090_) {
return Optional.ofNullable(this.functions.get(p_136090_));
}
public Map<ResourceLocation, CommandFunction> getFunctions() {
return this.functions;
}
public Collection<CommandFunction> getTag(ResourceLocation p_214328_) {
return this.tags.getOrDefault(p_214328_, List.of());
}
public Iterable<ResourceLocation> getAvailableTags() {
return this.tags.keySet();
}
public ServerFunctionLibrary(int p_136053_, CommandDispatcher<CommandSourceStack> p_136054_) {
this.functionCompilationLevel = p_136053_;
this.dispatcher = p_136054_;
}
public CompletableFuture<Void> reload(PreparableReloadListener.PreparationBarrier pStage, ResourceManager pResourceManager, ProfilerFiller pPreparationsProfiler, ProfilerFiller pReloadProfiler, Executor pBackgroundExecutor, Executor pGameExecutor) {
CompletableFuture<Map<ResourceLocation, List<TagLoader.EntryWithSource>>> completablefuture = CompletableFuture.supplyAsync(() -> {
return this.tagsLoader.load(pResourceManager);
}, pBackgroundExecutor);
CompletableFuture<Map<ResourceLocation, CompletableFuture<CommandFunction>>> completablefuture1 = CompletableFuture.supplyAsync(() -> {
return LISTER.listMatchingResources(pResourceManager);
}, pBackgroundExecutor).thenCompose((p_248095_) -> {
Map<ResourceLocation, CompletableFuture<CommandFunction>> map = Maps.newHashMap();
CommandSourceStack commandsourcestack = new CommandSourceStack(CommandSource.NULL, Vec3.ZERO, Vec2.ZERO, (ServerLevel)null, this.functionCompilationLevel, "", CommonComponents.EMPTY, (MinecraftServer)null, (Entity)null);
for(Map.Entry<ResourceLocation, Resource> entry : p_248095_.entrySet()) {
ResourceLocation resourcelocation = entry.getKey();
ResourceLocation resourcelocation1 = LISTER.fileToId(resourcelocation);
map.put(resourcelocation1, CompletableFuture.supplyAsync(() -> {
List<String> list = readLines(entry.getValue());
return CommandFunction.fromLines(resourcelocation1, this.dispatcher, commandsourcestack, list);
}, pBackgroundExecutor));
}
CompletableFuture<?>[] completablefuture2 = map.values().toArray(new CompletableFuture[0]);
return CompletableFuture.allOf(completablefuture2).handle((p_179949_, p_179950_) -> {
return map;
});
});
return completablefuture.thenCombine(completablefuture1, Pair::of).thenCompose(pStage::wait).thenAcceptAsync((p_179944_) -> {
Map<ResourceLocation, CompletableFuture<CommandFunction>> map = (Map)p_179944_.getSecond();
ImmutableMap.Builder<ResourceLocation, CommandFunction> builder = ImmutableMap.builder();
map.forEach((p_179941_, p_179942_) -> {
p_179942_.handle((p_179954_, p_179955_) -> {
if (p_179955_ != null) {
LOGGER.error("Failed to load function {}", p_179941_, p_179955_);
} else {
builder.put(p_179941_, p_179954_);
}
return null;
}).join();
});
this.functions = builder.build();
this.tags = this.tagsLoader.build((Map)p_179944_.getFirst());
}, pGameExecutor);
}
private static List<String> readLines(Resource p_214317_) {
try (BufferedReader bufferedreader = p_214317_.openAsReader()) {
return bufferedreader.lines().toList();
} catch (IOException ioexception) {
throw new CompletionException(ioexception);
}
}
}
@@ -0,0 +1,250 @@
package net.minecraft.server;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.function.IntConsumer;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandFunction;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.GameRules;
public class ServerFunctionManager {
private static final Component NO_RECURSIVE_TRACES = Component.translatable("commands.debug.function.noRecursion");
private static final ResourceLocation TICK_FUNCTION_TAG = new ResourceLocation("tick");
private static final ResourceLocation LOAD_FUNCTION_TAG = new ResourceLocation("load");
final MinecraftServer server;
@Nullable
private ServerFunctionManager.ExecutionContext context;
private List<CommandFunction> ticking = ImmutableList.of();
private boolean postReload;
private ServerFunctionLibrary library;
public ServerFunctionManager(MinecraftServer pServer, ServerFunctionLibrary pLibrary) {
this.server = pServer;
this.library = pLibrary;
this.postReload(pLibrary);
}
public int getCommandLimit() {
return this.server.getGameRules().getInt(GameRules.RULE_MAX_COMMAND_CHAIN_LENGTH);
}
public CommandDispatcher<CommandSourceStack> getDispatcher() {
return this.server.getCommands().getDispatcher();
}
public void tick() {
if (this.postReload) {
this.postReload = false;
Collection<CommandFunction> collection = this.library.getTag(LOAD_FUNCTION_TAG);
this.executeTagFunctions(collection, LOAD_FUNCTION_TAG);
}
this.executeTagFunctions(this.ticking, TICK_FUNCTION_TAG);
}
private void executeTagFunctions(Collection<CommandFunction> pFunctionObjects, ResourceLocation pIdentifier) {
this.server.getProfiler().push(pIdentifier::toString);
for(CommandFunction commandfunction : pFunctionObjects) {
this.execute(commandfunction, this.getGameLoopSender());
}
this.server.getProfiler().pop();
}
public int execute(CommandFunction pFunctionObject, CommandSourceStack pSource) {
return this.execute(pFunctionObject, pSource, (ServerFunctionManager.TraceCallbacks)null);
}
public int execute(CommandFunction pFunctionObject, CommandSourceStack pSource, @Nullable ServerFunctionManager.TraceCallbacks pTracer) {
if (this.context != null) {
if (pTracer != null) {
this.context.reportError(NO_RECURSIVE_TRACES.getString());
return 0;
} else {
this.context.delayFunctionCall(pFunctionObject, pSource);
return 0;
}
} else {
int i;
try {
this.context = new ServerFunctionManager.ExecutionContext(pTracer);
i = this.context.runTopCommand(pFunctionObject, pSource);
} finally {
this.context = null;
}
return i;
}
}
public void replaceLibrary(ServerFunctionLibrary pReloader) {
this.library = pReloader;
this.postReload(pReloader);
}
private void postReload(ServerFunctionLibrary pReloader) {
this.ticking = ImmutableList.copyOf(pReloader.getTag(TICK_FUNCTION_TAG));
this.postReload = true;
}
public CommandSourceStack getGameLoopSender() {
return this.server.createCommandSourceStack().withPermission(2).withSuppressedOutput();
}
public Optional<CommandFunction> get(ResourceLocation pFunctionIdentifier) {
return this.library.getFunction(pFunctionIdentifier);
}
public Collection<CommandFunction> getTag(ResourceLocation pFunctionTagIdentifier) {
return this.library.getTag(pFunctionTagIdentifier);
}
public Iterable<ResourceLocation> getFunctionNames() {
return this.library.getFunctions().keySet();
}
public Iterable<ResourceLocation> getTagNames() {
return this.library.getAvailableTags();
}
class ExecutionContext {
private int depth;
@Nullable
private final ServerFunctionManager.TraceCallbacks tracer;
private final Deque<ServerFunctionManager.QueuedCommand> commandQueue = Queues.newArrayDeque();
private final List<ServerFunctionManager.QueuedCommand> nestedCalls = Lists.newArrayList();
boolean abortCurrentDepth = false;
ExecutionContext(@Nullable ServerFunctionManager.TraceCallbacks pTracer) {
this.tracer = pTracer;
}
void delayFunctionCall(CommandFunction pFunction, CommandSourceStack pSender) {
int i = ServerFunctionManager.this.getCommandLimit();
CommandSourceStack commandsourcestack = this.wrapSender(pSender);
if (this.commandQueue.size() + this.nestedCalls.size() < i) {
this.nestedCalls.add(new ServerFunctionManager.QueuedCommand(commandsourcestack, this.depth, new CommandFunction.FunctionEntry(pFunction)));
}
}
private CommandSourceStack wrapSender(CommandSourceStack pSender) {
IntConsumer intconsumer = pSender.getReturnValueConsumer();
return intconsumer instanceof ServerFunctionManager.ExecutionContext.AbortingReturnValueConsumer ? pSender : pSender.withReturnValueConsumer(new ServerFunctionManager.ExecutionContext.AbortingReturnValueConsumer(intconsumer));
}
int runTopCommand(CommandFunction pFunction, CommandSourceStack pSource) {
int i = ServerFunctionManager.this.getCommandLimit();
CommandSourceStack commandsourcestack = this.wrapSender(pSource);
int j = 0;
CommandFunction.Entry[] acommandfunction$entry = pFunction.getEntries();
for(int k = acommandfunction$entry.length - 1; k >= 0; --k) {
this.commandQueue.push(new ServerFunctionManager.QueuedCommand(commandsourcestack, 0, acommandfunction$entry[k]));
}
while(!this.commandQueue.isEmpty()) {
try {
ServerFunctionManager.QueuedCommand serverfunctionmanager$queuedcommand = this.commandQueue.removeFirst();
ServerFunctionManager.this.server.getProfiler().push(serverfunctionmanager$queuedcommand::toString);
this.depth = serverfunctionmanager$queuedcommand.depth;
serverfunctionmanager$queuedcommand.execute(ServerFunctionManager.this, this.commandQueue, i, this.tracer);
if (!this.abortCurrentDepth) {
if (!this.nestedCalls.isEmpty()) {
Lists.reverse(this.nestedCalls).forEach(this.commandQueue::addFirst);
}
} else {
while(!this.commandQueue.isEmpty() && (this.commandQueue.peek()).depth >= this.depth) {
this.commandQueue.removeFirst();
}
this.abortCurrentDepth = false;
}
this.nestedCalls.clear();
} finally {
ServerFunctionManager.this.server.getProfiler().pop();
}
++j;
if (j >= i) {
return j;
}
}
return j;
}
public void reportError(String pError) {
if (this.tracer != null) {
this.tracer.onError(this.depth, pError);
}
}
class AbortingReturnValueConsumer implements IntConsumer {
private final IntConsumer wrapped;
AbortingReturnValueConsumer(IntConsumer pWrapped) {
this.wrapped = pWrapped;
}
public void accept(int p_281286_) {
this.wrapped.accept(p_281286_);
ExecutionContext.this.abortCurrentDepth = true;
}
}
}
public static class QueuedCommand {
private final CommandSourceStack sender;
final int depth;
private final CommandFunction.Entry entry;
public QueuedCommand(CommandSourceStack pSender, int pDepth, CommandFunction.Entry pEntry) {
this.sender = pSender;
this.depth = pDepth;
this.entry = pEntry;
}
public void execute(ServerFunctionManager pServerFunctionManager, Deque<ServerFunctionManager.QueuedCommand> pQueuedCommands, int pCommandLimit, @Nullable ServerFunctionManager.TraceCallbacks pTracer) {
try {
this.entry.execute(pServerFunctionManager, this.sender, pQueuedCommands, pCommandLimit, this.depth, pTracer);
} catch (CommandSyntaxException commandsyntaxexception) {
if (pTracer != null) {
pTracer.onError(this.depth, commandsyntaxexception.getRawMessage().getString());
}
} catch (Exception exception) {
if (pTracer != null) {
pTracer.onError(this.depth, exception.getMessage());
}
}
}
public String toString() {
return this.entry.toString();
}
}
public interface TraceCallbacks {
void onCommand(int pIndent, String pCommand);
void onReturn(int pIndent, String pReturnValue, int pCommand);
void onError(int pIndent, String pCommand);
void onCall(int pIndent, ResourceLocation pCommand, int pSize);
}
}
@@ -0,0 +1,54 @@
package net.minecraft.server;
import net.minecraft.server.dedicated.DedicatedServerProperties;
public interface ServerInterface {
DedicatedServerProperties getProperties();
/**
* Returns the server's hostname.
*/
String getServerIp();
/**
* Never used, but "getServerPort" is already taken.
*/
int getServerPort();
/**
* Returns the server message of the day
*/
String getServerName();
/**
* Returns the server's Minecraft version as string.
*/
String getServerVersion();
/**
* Returns the number of players currently on the server.
*/
int getPlayerCount();
/**
* Returns the maximum number of players allowed on the server.
*/
int getMaxPlayers();
/**
* Returns an array of the usernames of all the connected players.
*/
String[] getPlayerNames();
String getLevelIdName();
/**
* Used by RCon's Query in the form of "MajorServerMod 1.2.3: MyPlugin 1.3" AnotherPlugin 2.1" AndSoForth 1.0".
*/
String getPluginNames();
/**
* Handle a command received by an RCon instance
*/
String runCommand(String pCommand);
}
@@ -0,0 +1,231 @@
package net.minecraft.server;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientboundSetDisplayObjectivePacket;
import net.minecraft.network.protocol.game.ClientboundSetObjectivePacket;
import net.minecraft.network.protocol.game.ClientboundSetPlayerTeamPacket;
import net.minecraft.network.protocol.game.ClientboundSetScorePacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.PlayerTeam;
import net.minecraft.world.scores.Score;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.ScoreboardSaveData;
public class ServerScoreboard extends Scoreboard {
private final MinecraftServer server;
private final Set<Objective> trackedObjectives = Sets.newHashSet();
private final List<Runnable> dirtyListeners = Lists.newArrayList();
public ServerScoreboard(MinecraftServer p_136197_) {
this.server = p_136197_;
}
public void onScoreChanged(Score pScore) {
super.onScoreChanged(pScore);
if (this.trackedObjectives.contains(pScore.getObjective())) {
this.server.getPlayerList().broadcastAll(new ClientboundSetScorePacket(ServerScoreboard.Method.CHANGE, pScore.getObjective().getName(), pScore.getOwner(), pScore.getScore()));
}
this.setDirty();
}
public void onPlayerRemoved(String pScoreName) {
super.onPlayerRemoved(pScoreName);
this.server.getPlayerList().broadcastAll(new ClientboundSetScorePacket(ServerScoreboard.Method.REMOVE, (String)null, pScoreName, 0));
this.setDirty();
}
public void onPlayerScoreRemoved(String pScoreName, Objective pObjective) {
super.onPlayerScoreRemoved(pScoreName, pObjective);
if (this.trackedObjectives.contains(pObjective)) {
this.server.getPlayerList().broadcastAll(new ClientboundSetScorePacket(ServerScoreboard.Method.REMOVE, pObjective.getName(), pScoreName, 0));
}
this.setDirty();
}
/**
* 0 is tab menu, 1 is sidebar, 2 is below name
*/
public void setDisplayObjective(int pObjectiveSlot, @Nullable Objective pObjective) {
Objective objective = this.getDisplayObjective(pObjectiveSlot);
super.setDisplayObjective(pObjectiveSlot, pObjective);
if (objective != pObjective && objective != null) {
if (this.getObjectiveDisplaySlotCount(objective) > 0) {
this.server.getPlayerList().broadcastAll(new ClientboundSetDisplayObjectivePacket(pObjectiveSlot, pObjective));
} else {
this.stopTrackingObjective(objective);
}
}
if (pObjective != null) {
if (this.trackedObjectives.contains(pObjective)) {
this.server.getPlayerList().broadcastAll(new ClientboundSetDisplayObjectivePacket(pObjectiveSlot, pObjective));
} else {
this.startTrackingObjective(pObjective);
}
}
this.setDirty();
}
public boolean addPlayerToTeam(String pPlayerName, PlayerTeam pTeam) {
if (super.addPlayerToTeam(pPlayerName, pTeam)) {
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createPlayerPacket(pTeam, pPlayerName, ClientboundSetPlayerTeamPacket.Action.ADD));
this.setDirty();
return true;
} else {
return false;
}
}
/**
* Removes the given username from the given ScorePlayerTeam. If the player is not on the team then an
* IllegalStateException is thrown.
*/
public void removePlayerFromTeam(String pUsername, PlayerTeam pPlayerTeam) {
super.removePlayerFromTeam(pUsername, pPlayerTeam);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createPlayerPacket(pPlayerTeam, pUsername, ClientboundSetPlayerTeamPacket.Action.REMOVE));
this.setDirty();
}
public void onObjectiveAdded(Objective pObjective) {
super.onObjectiveAdded(pObjective);
this.setDirty();
}
public void onObjectiveChanged(Objective pObjective) {
super.onObjectiveChanged(pObjective);
if (this.trackedObjectives.contains(pObjective)) {
this.server.getPlayerList().broadcastAll(new ClientboundSetObjectivePacket(pObjective, 2));
}
this.setDirty();
}
public void onObjectiveRemoved(Objective pObjective) {
super.onObjectiveRemoved(pObjective);
if (this.trackedObjectives.contains(pObjective)) {
this.stopTrackingObjective(pObjective);
}
this.setDirty();
}
public void onTeamAdded(PlayerTeam pPlayerTeam) {
super.onTeamAdded(pPlayerTeam);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(pPlayerTeam, true));
this.setDirty();
}
public void onTeamChanged(PlayerTeam pPlayerTeam) {
super.onTeamChanged(pPlayerTeam);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(pPlayerTeam, false));
this.setDirty();
}
public void onTeamRemoved(PlayerTeam pPlayerTeam) {
super.onTeamRemoved(pPlayerTeam);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createRemovePacket(pPlayerTeam));
this.setDirty();
}
public void addDirtyListener(Runnable pRunnable) {
this.dirtyListeners.add(pRunnable);
}
protected void setDirty() {
for(Runnable runnable : this.dirtyListeners) {
runnable.run();
}
}
public List<Packet<?>> getStartTrackingPackets(Objective pObjective) {
List<Packet<?>> list = Lists.newArrayList();
list.add(new ClientboundSetObjectivePacket(pObjective, 0));
for(int i = 0; i < 19; ++i) {
if (this.getDisplayObjective(i) == pObjective) {
list.add(new ClientboundSetDisplayObjectivePacket(i, pObjective));
}
}
for(Score score : this.getPlayerScores(pObjective)) {
list.add(new ClientboundSetScorePacket(ServerScoreboard.Method.CHANGE, score.getObjective().getName(), score.getOwner(), score.getScore()));
}
return list;
}
public void startTrackingObjective(Objective pObjective) {
List<Packet<?>> list = this.getStartTrackingPackets(pObjective);
for(ServerPlayer serverplayer : this.server.getPlayerList().getPlayers()) {
for(Packet<?> packet : list) {
serverplayer.connection.send(packet);
}
}
this.trackedObjectives.add(pObjective);
}
public List<Packet<?>> getStopTrackingPackets(Objective p_136234_) {
List<Packet<?>> list = Lists.newArrayList();
list.add(new ClientboundSetObjectivePacket(p_136234_, 1));
for(int i = 0; i < 19; ++i) {
if (this.getDisplayObjective(i) == p_136234_) {
list.add(new ClientboundSetDisplayObjectivePacket(i, p_136234_));
}
}
return list;
}
public void stopTrackingObjective(Objective p_136236_) {
List<Packet<?>> list = this.getStopTrackingPackets(p_136236_);
for(ServerPlayer serverplayer : this.server.getPlayerList().getPlayers()) {
for(Packet<?> packet : list) {
serverplayer.connection.send(packet);
}
}
this.trackedObjectives.remove(p_136236_);
}
public int getObjectiveDisplaySlotCount(Objective p_136238_) {
int i = 0;
for(int j = 0; j < 19; ++j) {
if (this.getDisplayObjective(j) == p_136238_) {
++i;
}
}
return i;
}
public ScoreboardSaveData createData() {
ScoreboardSaveData scoreboardsavedata = new ScoreboardSaveData(this);
this.addDirtyListener(scoreboardsavedata::setDirty);
return scoreboardsavedata;
}
public ScoreboardSaveData createData(CompoundTag p_180014_) {
return this.createData().load(p_180014_);
}
public static enum Method {
CHANGE,
REMOVE;
}
}
@@ -0,0 +1,27 @@
package net.minecraft.server;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.yggdrasil.ServicesKeySet;
import com.mojang.authlib.yggdrasil.ServicesKeyType;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import java.io.File;
import javax.annotation.Nullable;
import net.minecraft.server.players.GameProfileCache;
import net.minecraft.util.SignatureValidator;
public record Services(MinecraftSessionService sessionService, ServicesKeySet servicesKeySet, GameProfileRepository profileRepository, GameProfileCache profileCache) {
private static final String USERID_CACHE_FILE = "usercache.json";
public static Services create(YggdrasilAuthenticationService pAuthenticationService, File pProfileRepository) {
MinecraftSessionService minecraftsessionservice = pAuthenticationService.createMinecraftSessionService();
GameProfileRepository gameprofilerepository = pAuthenticationService.createProfileRepository();
GameProfileCache gameprofilecache = new GameProfileCache(gameprofilerepository, new File(pProfileRepository, "usercache.json"));
return new Services(minecraftsessionservice, pAuthenticationService.getServicesKeySet(), gameprofilerepository, gameprofilecache);
}
@Nullable
public SignatureValidator profileKeySignatureValidator() {
return SignatureValidator.from(this.servicesKeySet, ServicesKeyType.PROFILE_KEY);
}
}
@@ -0,0 +1,22 @@
package net.minecraft.server;
public class TickTask implements Runnable {
private final int tick;
private final Runnable runnable;
public TickTask(int p_136252_, Runnable p_136253_) {
this.tick = p_136252_;
this.runnable = p_136253_;
}
/**
* Get the server time when this task was scheduled
*/
public int getTick() {
return this.tick;
}
public void run() {
this.runnable.run();
}
}
@@ -0,0 +1,94 @@
package net.minecraft.server;
import com.mojang.datafixers.util.Pair;
import com.mojang.logging.LogUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import net.minecraft.commands.Commands;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.resources.CloseableResourceManager;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.WorldDataConfiguration;
import org.slf4j.Logger;
public class WorldLoader {
private static final Logger LOGGER = LogUtils.getLogger();
public static <D, R> CompletableFuture<R> load(WorldLoader.InitConfig pInitConfig, WorldLoader.WorldDataSupplier<D> p_214364_, WorldLoader.ResultFactory<D, R> p_214365_, Executor p_214366_, Executor p_214367_) {
try {
Pair<WorldDataConfiguration, CloseableResourceManager> pair = pInitConfig.packConfig.createResourceManager();
CloseableResourceManager closeableresourcemanager = pair.getSecond();
LayeredRegistryAccess<RegistryLayer> layeredregistryaccess = RegistryLayer.createRegistryAccess();
LayeredRegistryAccess<RegistryLayer> layeredregistryaccess1 = loadAndReplaceLayer(closeableresourcemanager, layeredregistryaccess, RegistryLayer.WORLDGEN, net.minecraftforge.registries.DataPackRegistriesHooks.getDataPackRegistries());
RegistryAccess.Frozen registryaccess$frozen = layeredregistryaccess1.getAccessForLoading(RegistryLayer.DIMENSIONS);
RegistryAccess.Frozen registryaccess$frozen1 = RegistryDataLoader.load(closeableresourcemanager, registryaccess$frozen, RegistryDataLoader.DIMENSION_REGISTRIES);
WorldDataConfiguration worlddataconfiguration = pair.getFirst();
WorldLoader.DataLoadOutput<D> dataloadoutput = p_214364_.get(new WorldLoader.DataLoadContext(closeableresourcemanager, worlddataconfiguration, registryaccess$frozen, registryaccess$frozen1));
LayeredRegistryAccess<RegistryLayer> layeredregistryaccess2 = layeredregistryaccess1.replaceFrom(RegistryLayer.DIMENSIONS, dataloadoutput.finalDimensions);
RegistryAccess.Frozen registryaccess$frozen2 = layeredregistryaccess2.getAccessForLoading(RegistryLayer.RELOADABLE);
return ReloadableServerResources.loadResources(closeableresourcemanager, registryaccess$frozen2, worlddataconfiguration.enabledFeatures(), pInitConfig.commandSelection(), pInitConfig.functionCompilationLevel(), p_214366_, p_214367_).whenComplete((p_214370_, p_214371_) -> {
if (p_214371_ != null) {
closeableresourcemanager.close();
}
}).thenApplyAsync((p_248101_) -> {
p_248101_.updateRegistryTags(registryaccess$frozen2);
return p_214365_.create(closeableresourcemanager, p_248101_, layeredregistryaccess2, dataloadoutput.cookie);
}, p_214367_);
} catch (Exception exception) {
return CompletableFuture.failedFuture(exception);
}
}
private static RegistryAccess.Frozen loadLayer(ResourceManager pResourceManager, LayeredRegistryAccess<RegistryLayer> pRegistryAccess, RegistryLayer pRegistryLayer, List<RegistryDataLoader.RegistryData<?>> pRegistryData) {
RegistryAccess.Frozen registryaccess$frozen = pRegistryAccess.getAccessForLoading(pRegistryLayer);
return RegistryDataLoader.load(pResourceManager, registryaccess$frozen, pRegistryData);
}
private static LayeredRegistryAccess<RegistryLayer> loadAndReplaceLayer(ResourceManager pResourceManager, LayeredRegistryAccess<RegistryLayer> pRegistryAccess, RegistryLayer pRegistryLayer, List<RegistryDataLoader.RegistryData<?>> pRegistryData) {
RegistryAccess.Frozen registryaccess$frozen = loadLayer(pResourceManager, pRegistryAccess, pRegistryLayer, pRegistryData);
return pRegistryAccess.replaceFrom(pRegistryLayer, registryaccess$frozen);
}
public static record DataLoadContext(ResourceManager resources, WorldDataConfiguration dataConfiguration, RegistryAccess.Frozen datapackWorldgen, RegistryAccess.Frozen datapackDimensions) {
}
public static record DataLoadOutput<D>(D cookie, RegistryAccess.Frozen finalDimensions) {
}
public static record InitConfig(WorldLoader.PackConfig packConfig, Commands.CommandSelection commandSelection, int functionCompilationLevel) {
}
public static record PackConfig(PackRepository packRepository, WorldDataConfiguration initialDataConfig, boolean safeMode, boolean initMode) {
public Pair<WorldDataConfiguration, CloseableResourceManager> createResourceManager() {
FeatureFlagSet featureflagset = this.initMode ? FeatureFlags.REGISTRY.allFlags() : this.initialDataConfig.enabledFeatures();
WorldDataConfiguration worlddataconfiguration = MinecraftServer.configurePackRepository(this.packRepository, this.initialDataConfig.dataPacks(), this.safeMode, featureflagset);
if (!this.initMode) {
worlddataconfiguration = worlddataconfiguration.expandFeatures(this.initialDataConfig.enabledFeatures());
}
List<PackResources> list = this.packRepository.openAllSelected();
CloseableResourceManager closeableresourcemanager = new MultiPackResourceManager(PackType.SERVER_DATA, list);
return Pair.of(worlddataconfiguration, closeableresourcemanager);
}
}
@FunctionalInterface
public interface ResultFactory<D, R> {
R create(CloseableResourceManager p_214408_, ReloadableServerResources p_214409_, LayeredRegistryAccess<RegistryLayer> p_248844_, D p_214411_);
}
@FunctionalInterface
public interface WorldDataSupplier<D> {
WorldLoader.DataLoadOutput<D> get(WorldLoader.DataLoadContext p_251042_);
}
}
@@ -0,0 +1,11 @@
package net.minecraft.server;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.server.packs.resources.CloseableResourceManager;
import net.minecraft.world.level.storage.WorldData;
public record WorldStem(CloseableResourceManager resourceManager, ReloadableServerResources dataPackResources, LayeredRegistryAccess<RegistryLayer> registries, WorldData worldData) implements AutoCloseable {
public void close() {
this.resourceManager.close();
}
}
@@ -0,0 +1,84 @@
package net.minecraft.server.advancements;
import it.unimi.dsi.fastutil.Stack;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.function.Predicate;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.DisplayInfo;
public class AdvancementVisibilityEvaluator {
private static final int VISIBILITY_DEPTH = 2;
private static AdvancementVisibilityEvaluator.VisibilityRule evaluateVisibilityRule(Advancement pAdvancement, boolean pAlwaysShow) {
DisplayInfo displayinfo = pAdvancement.getDisplay();
if (displayinfo == null) {
return AdvancementVisibilityEvaluator.VisibilityRule.HIDE;
} else if (pAlwaysShow) {
return AdvancementVisibilityEvaluator.VisibilityRule.SHOW;
} else {
return displayinfo.isHidden() ? AdvancementVisibilityEvaluator.VisibilityRule.HIDE : AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE;
}
}
private static boolean evaluateVisiblityForUnfinishedNode(Stack<AdvancementVisibilityEvaluator.VisibilityRule> pVisibilityRules) {
for(int i = 0; i <= 2; ++i) {
AdvancementVisibilityEvaluator.VisibilityRule advancementvisibilityevaluator$visibilityrule = pVisibilityRules.peek(i);
if (advancementvisibilityevaluator$visibilityrule == AdvancementVisibilityEvaluator.VisibilityRule.SHOW) {
return true;
}
if (advancementvisibilityevaluator$visibilityrule == AdvancementVisibilityEvaluator.VisibilityRule.HIDE) {
return false;
}
}
return false;
}
private static boolean evaluateVisibility(Advancement pAdvancement, Stack<AdvancementVisibilityEvaluator.VisibilityRule> pVisibilityRules, Predicate<Advancement> pPredicate, AdvancementVisibilityEvaluator.Output pOutput) {
boolean flag = pPredicate.test(pAdvancement);
AdvancementVisibilityEvaluator.VisibilityRule advancementvisibilityevaluator$visibilityrule = evaluateVisibilityRule(pAdvancement, flag);
boolean flag1 = flag;
pVisibilityRules.push(advancementvisibilityevaluator$visibilityrule);
for(Advancement advancement : pAdvancement.getChildren()) {
flag1 |= evaluateVisibility(advancement, pVisibilityRules, pPredicate, pOutput);
}
boolean flag2 = flag1 || evaluateVisiblityForUnfinishedNode(pVisibilityRules);
pVisibilityRules.pop();
pOutput.accept(pAdvancement, flag2);
return flag1;
}
public static void evaluateVisibility(Advancement pAdvancement, Predicate<Advancement> pPredicate, AdvancementVisibilityEvaluator.Output pOutput) {
Advancement advancement = pAdvancement.getRoot();
Stack<AdvancementVisibilityEvaluator.VisibilityRule> stack = new ObjectArrayList<>();
for(int i = 0; i <= 2; ++i) {
stack.push(AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE);
}
evaluateVisibility(advancement, stack, pPredicate, pOutput);
}
public static boolean isVisible(Advancement advancement, Predicate<Advancement> test) {
Stack<AdvancementVisibilityEvaluator.VisibilityRule> stack = new ObjectArrayList<>();
for(int i = 0; i <= 2; ++i) {
stack.push(AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE);
}
return evaluateVisibility(advancement.getRoot(), stack, test, (pAdvancement, pVisible) -> {});
}
@FunctionalInterface
public interface Output {
void accept(Advancement pAdvancement, boolean pVisible);
}
static enum VisibilityRule {
SHOW,
HIDE,
NO_CHANGE;
}
}
@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.server.advancements;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
@@ -0,0 +1,186 @@
package net.minecraft.server.bossevents;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
import java.util.UUID;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerBossEvent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.BossEvent;
public class CustomBossEvent extends ServerBossEvent {
private final ResourceLocation id;
private final Set<UUID> players = Sets.newHashSet();
private int value;
private int max = 100;
public CustomBossEvent(ResourceLocation pId, Component pName) {
super(pName, BossEvent.BossBarColor.WHITE, BossEvent.BossBarOverlay.PROGRESS);
this.id = pId;
this.setProgress(0.0F);
}
public ResourceLocation getTextId() {
return this.id;
}
/**
* Makes the boss visible to the given player.
*/
public void addPlayer(ServerPlayer pPlayer) {
super.addPlayer(pPlayer);
this.players.add(pPlayer.getUUID());
}
public void addOfflinePlayer(UUID pPlayer) {
this.players.add(pPlayer);
}
/**
* Makes the boss non-visible to the given player.
*/
public void removePlayer(ServerPlayer pPlayer) {
super.removePlayer(pPlayer);
this.players.remove(pPlayer.getUUID());
}
public void removeAllPlayers() {
super.removeAllPlayers();
this.players.clear();
}
public int getValue() {
return this.value;
}
public int getMax() {
return this.max;
}
public void setValue(int pValue) {
this.value = pValue;
this.setProgress(Mth.clamp((float)pValue / (float)this.max, 0.0F, 1.0F));
}
public void setMax(int pMax) {
this.max = pMax;
this.setProgress(Mth.clamp((float)this.value / (float)pMax, 0.0F, 1.0F));
}
public final Component getDisplayName() {
return ComponentUtils.wrapInSquareBrackets(this.getName()).withStyle((p_136276_) -> {
return p_136276_.withColor(this.getColor().getFormatting()).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(this.getTextId().toString()))).withInsertion(this.getTextId().toString());
});
}
public boolean setPlayers(Collection<ServerPlayer> pServerPlayerList) {
Set<UUID> set = Sets.newHashSet();
Set<ServerPlayer> set1 = Sets.newHashSet();
for(UUID uuid : this.players) {
boolean flag = false;
for(ServerPlayer serverplayer : pServerPlayerList) {
if (serverplayer.getUUID().equals(uuid)) {
flag = true;
break;
}
}
if (!flag) {
set.add(uuid);
}
}
for(ServerPlayer serverplayer1 : pServerPlayerList) {
boolean flag1 = false;
for(UUID uuid2 : this.players) {
if (serverplayer1.getUUID().equals(uuid2)) {
flag1 = true;
break;
}
}
if (!flag1) {
set1.add(serverplayer1);
}
}
for(UUID uuid1 : set) {
for(ServerPlayer serverplayer3 : this.getPlayers()) {
if (serverplayer3.getUUID().equals(uuid1)) {
this.removePlayer(serverplayer3);
break;
}
}
this.players.remove(uuid1);
}
for(ServerPlayer serverplayer2 : set1) {
this.addPlayer(serverplayer2);
}
return !set.isEmpty() || !set1.isEmpty();
}
public CompoundTag save() {
CompoundTag compoundtag = new CompoundTag();
compoundtag.putString("Name", Component.Serializer.toJson(this.name));
compoundtag.putBoolean("Visible", this.isVisible());
compoundtag.putInt("Value", this.value);
compoundtag.putInt("Max", this.max);
compoundtag.putString("Color", this.getColor().getName());
compoundtag.putString("Overlay", this.getOverlay().getName());
compoundtag.putBoolean("DarkenScreen", this.shouldDarkenScreen());
compoundtag.putBoolean("PlayBossMusic", this.shouldPlayBossMusic());
compoundtag.putBoolean("CreateWorldFog", this.shouldCreateWorldFog());
ListTag listtag = new ListTag();
for(UUID uuid : this.players) {
listtag.add(NbtUtils.createUUID(uuid));
}
compoundtag.put("Players", listtag);
return compoundtag;
}
public static CustomBossEvent load(CompoundTag pNbt, ResourceLocation pId) {
CustomBossEvent custombossevent = new CustomBossEvent(pId, Component.Serializer.fromJson(pNbt.getString("Name")));
custombossevent.setVisible(pNbt.getBoolean("Visible"));
custombossevent.setValue(pNbt.getInt("Value"));
custombossevent.setMax(pNbt.getInt("Max"));
custombossevent.setColor(BossEvent.BossBarColor.byName(pNbt.getString("Color")));
custombossevent.setOverlay(BossEvent.BossBarOverlay.byName(pNbt.getString("Overlay")));
custombossevent.setDarkenScreen(pNbt.getBoolean("DarkenScreen"));
custombossevent.setPlayBossMusic(pNbt.getBoolean("PlayBossMusic"));
custombossevent.setCreateWorldFog(pNbt.getBoolean("CreateWorldFog"));
ListTag listtag = pNbt.getList("Players", 11);
for(int i = 0; i < listtag.size(); ++i) {
custombossevent.addOfflinePlayer(NbtUtils.loadUUID(listtag.get(i)));
}
return custombossevent;
}
public void onPlayerConnect(ServerPlayer pPlayer) {
if (this.players.contains(pPlayer.getUUID())) {
this.addPlayer(pPlayer);
}
}
public void onPlayerDisconnect(ServerPlayer pPlayer) {
super.removePlayer(pPlayer);
}
}
@@ -0,0 +1,69 @@
package net.minecraft.server.bossevents;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.Map;
import javax.annotation.Nullable;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
public class CustomBossEvents {
private final Map<ResourceLocation, CustomBossEvent> events = Maps.newHashMap();
@Nullable
public CustomBossEvent get(ResourceLocation pId) {
return this.events.get(pId);
}
public CustomBossEvent create(ResourceLocation pId, Component pName) {
CustomBossEvent custombossevent = new CustomBossEvent(pId, pName);
this.events.put(pId, custombossevent);
return custombossevent;
}
public void remove(CustomBossEvent pBossbar) {
this.events.remove(pBossbar.getTextId());
}
public Collection<ResourceLocation> getIds() {
return this.events.keySet();
}
public Collection<CustomBossEvent> getEvents() {
return this.events.values();
}
public CompoundTag save() {
CompoundTag compoundtag = new CompoundTag();
for(CustomBossEvent custombossevent : this.events.values()) {
compoundtag.put(custombossevent.getTextId().toString(), custombossevent.save());
}
return compoundtag;
}
public void load(CompoundTag p_136296_) {
for(String s : p_136296_.getAllKeys()) {
ResourceLocation resourcelocation = new ResourceLocation(s);
this.events.put(resourcelocation, CustomBossEvent.load(p_136296_.getCompound(s), resourcelocation));
}
}
public void onPlayerConnect(ServerPlayer pPlayer) {
for(CustomBossEvent custombossevent : this.events.values()) {
custombossevent.onPlayerConnect(pPlayer);
}
}
public void onPlayerDisconnect(ServerPlayer pPlayer) {
for(CustomBossEvent custombossevent : this.events.values()) {
custombossevent.onPlayerDisconnect(pPlayer);
}
}
}
@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.server.bossevents;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
@@ -0,0 +1,152 @@
package net.minecraft.server.chase;
import com.google.common.base.Charsets;
import com.mojang.logging.LogUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.Socket;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Scanner;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.commands.ChaseCommand;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
public class ChaseClient {
private static final Logger LOGGER = LogUtils.getLogger();
private static final int RECONNECT_INTERVAL_SECONDS = 5;
private final String serverHost;
private final int serverPort;
private final MinecraftServer server;
private volatile boolean wantsToRun;
@Nullable
private Socket socket;
@Nullable
private Thread thread;
public ChaseClient(String pServerHost, int pServerPort, MinecraftServer pServer) {
this.serverHost = pServerHost;
this.serverPort = pServerPort;
this.server = pServer;
}
public void start() {
if (this.thread != null && this.thread.isAlive()) {
LOGGER.warn("Remote control client was asked to start, but it is already running. Will ignore.");
}
this.wantsToRun = true;
this.thread = new Thread(this::run, "chase-client");
this.thread.setDaemon(true);
this.thread.start();
}
public void stop() {
this.wantsToRun = false;
IOUtils.closeQuietly(this.socket);
this.socket = null;
this.thread = null;
}
public void run() {
String s = this.serverHost + ":" + this.serverPort;
while(this.wantsToRun) {
try {
LOGGER.info("Connecting to remote control server {}", (Object)s);
this.socket = new Socket(this.serverHost, this.serverPort);
LOGGER.info("Connected to remote control server! Will continuously execute the command broadcasted by that server.");
try (BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), Charsets.US_ASCII))) {
while(this.wantsToRun) {
String s1 = bufferedreader.readLine();
if (s1 == null) {
LOGGER.warn("Lost connection to remote control server {}. Will retry in {}s.", s, 5);
break;
}
this.handleMessage(s1);
}
} catch (IOException ioexception) {
LOGGER.warn("Lost connection to remote control server {}. Will retry in {}s.", s, 5);
}
} catch (IOException ioexception1) {
LOGGER.warn("Failed to connect to remote control server {}. Will retry in {}s.", s, 5);
}
if (this.wantsToRun) {
try {
Thread.sleep(5000L);
} catch (InterruptedException interruptedexception) {
}
}
}
}
private void handleMessage(String pMessage) {
try (Scanner scanner = new Scanner(new StringReader(pMessage))) {
scanner.useLocale(Locale.ROOT);
String s = scanner.next();
if ("t".equals(s)) {
this.handleTeleport(scanner);
} else {
LOGGER.warn("Unknown message type '{}'", (Object)s);
}
} catch (NoSuchElementException nosuchelementexception) {
LOGGER.warn("Could not parse message '{}', ignoring", (Object)pMessage);
}
}
private void handleTeleport(Scanner p_195997_) {
this.parseTarget(p_195997_).ifPresent((p_195999_) -> {
this.executeCommand(String.format(Locale.ROOT, "execute in %s run tp @s %.3f %.3f %.3f %.3f %.3f", p_195999_.level.location(), p_195999_.pos.x, p_195999_.pos.y, p_195999_.pos.z, p_195999_.rot.y, p_195999_.rot.x));
});
}
private Optional<ChaseClient.TeleportTarget> parseTarget(Scanner p_196004_) {
ResourceKey<Level> resourcekey = ChaseCommand.DIMENSION_NAMES.get(p_196004_.next());
if (resourcekey == null) {
return Optional.empty();
} else {
float f = p_196004_.nextFloat();
float f1 = p_196004_.nextFloat();
float f2 = p_196004_.nextFloat();
float f3 = p_196004_.nextFloat();
float f4 = p_196004_.nextFloat();
return Optional.of(new ChaseClient.TeleportTarget(resourcekey, new Vec3((double)f, (double)f1, (double)f2), new Vec2(f4, f3)));
}
}
private void executeCommand(String p_196002_) {
this.server.execute(() -> {
List<ServerPlayer> list = this.server.getPlayerList().getPlayers();
if (!list.isEmpty()) {
ServerPlayer serverplayer = list.get(0);
ServerLevel serverlevel = this.server.overworld();
CommandSourceStack commandsourcestack = new CommandSourceStack(serverplayer, Vec3.atLowerCornerOf(serverlevel.getSharedSpawnPos()), Vec2.ZERO, serverlevel, 4, "", CommonComponents.EMPTY, this.server, serverplayer);
Commands commands = this.server.getCommands();
commands.performPrefixedCommand(commandsourcestack, p_196002_);
}
});
}
static record TeleportTarget(ResourceKey<Level> level, Vec3 pos, Vec2 rot) {
}
}
@@ -0,0 +1,146 @@
package net.minecraft.server.chase;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ClosedByInterruptException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.Util;
import net.minecraft.server.commands.ChaseCommand;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
public class ChaseServer {
private static final Logger LOGGER = LogUtils.getLogger();
private final String serverBindAddress;
private final int serverPort;
private final PlayerList playerList;
private final int broadcastIntervalMs;
private volatile boolean wantsToRun;
@Nullable
private ServerSocket serverSocket;
private final CopyOnWriteArrayList<Socket> clientSockets = new CopyOnWriteArrayList<>();
public ChaseServer(String pServerBindAddress, int pServerPort, PlayerList pPlayerList, int pBroadcastIntervalMs) {
this.serverBindAddress = pServerBindAddress;
this.serverPort = pServerPort;
this.playerList = pPlayerList;
this.broadcastIntervalMs = pBroadcastIntervalMs;
}
public void start() throws IOException {
if (this.serverSocket != null && !this.serverSocket.isClosed()) {
LOGGER.warn("Remote control server was asked to start, but it is already running. Will ignore.");
} else {
this.wantsToRun = true;
this.serverSocket = new ServerSocket(this.serverPort, 50, InetAddress.getByName(this.serverBindAddress));
Thread thread = new Thread(this::runAcceptor, "chase-server-acceptor");
thread.setDaemon(true);
thread.start();
Thread thread1 = new Thread(this::runSender, "chase-server-sender");
thread1.setDaemon(true);
thread1.start();
}
}
private void runSender() {
ChaseServer.PlayerPosition chaseserver$playerposition = null;
while(this.wantsToRun) {
if (!this.clientSockets.isEmpty()) {
ChaseServer.PlayerPosition chaseserver$playerposition1 = this.getPlayerPosition();
if (chaseserver$playerposition1 != null && !chaseserver$playerposition1.equals(chaseserver$playerposition)) {
chaseserver$playerposition = chaseserver$playerposition1;
byte[] abyte = chaseserver$playerposition1.format().getBytes(StandardCharsets.US_ASCII);
for(Socket socket : this.clientSockets) {
if (!socket.isClosed()) {
Util.ioPool().submit(() -> {
try {
OutputStream outputstream = socket.getOutputStream();
outputstream.write(abyte);
outputstream.flush();
} catch (IOException ioexception) {
LOGGER.info("Remote control client socket got an IO exception and will be closed", (Throwable)ioexception);
IOUtils.closeQuietly(socket);
}
});
}
}
}
List<Socket> list = this.clientSockets.stream().filter(Socket::isClosed).collect(Collectors.toList());
this.clientSockets.removeAll(list);
}
if (this.wantsToRun) {
try {
Thread.sleep((long)this.broadcastIntervalMs);
} catch (InterruptedException interruptedexception) {
}
}
}
}
public void stop() {
this.wantsToRun = false;
IOUtils.closeQuietly(this.serverSocket);
this.serverSocket = null;
}
private void runAcceptor() {
try {
while(this.wantsToRun) {
if (this.serverSocket != null) {
LOGGER.info("Remote control server is listening for connections on port {}", (int)this.serverPort);
Socket socket = this.serverSocket.accept();
LOGGER.info("Remote control server received client connection on port {}", (int)socket.getPort());
this.clientSockets.add(socket);
}
}
} catch (ClosedByInterruptException closedbyinterruptexception) {
if (this.wantsToRun) {
LOGGER.info("Remote control server closed by interrupt");
}
} catch (IOException ioexception) {
if (this.wantsToRun) {
LOGGER.error("Remote control server closed because of an IO exception", (Throwable)ioexception);
}
} finally {
IOUtils.closeQuietly(this.serverSocket);
}
LOGGER.info("Remote control server is now stopped");
this.wantsToRun = false;
}
@Nullable
private ChaseServer.PlayerPosition getPlayerPosition() {
List<ServerPlayer> list = this.playerList.getPlayers();
if (list.isEmpty()) {
return null;
} else {
ServerPlayer serverplayer = list.get(0);
String s = ChaseCommand.DIMENSION_NAMES.inverse().get(serverplayer.level().dimension());
return s == null ? null : new ChaseServer.PlayerPosition(s, serverplayer.getX(), serverplayer.getY(), serverplayer.getZ(), serverplayer.getYRot(), serverplayer.getXRot());
}
}
static record PlayerPosition(String dimensionName, double x, double y, double z, float yRot, float xRot) {
String format() {
return String.format(Locale.ROOT, "t %s %.2f %.2f %.2f %.2f %.2f\n", this.dimensionName, this.x, this.y, this.z, this.yRot, this.xRot);
}
}
}
@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.server.chase;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
@@ -0,0 +1,293 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Collection;
import java.util.List;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.commands.CommandRuntimeException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
public class AdvancementCommands {
private static final SuggestionProvider<CommandSourceStack> SUGGEST_ADVANCEMENTS = (p_136344_, p_136345_) -> {
Collection<Advancement> collection = p_136344_.getSource().getServer().getAdvancements().getAllAdvancements();
return SharedSuggestionProvider.suggestResource(collection.stream().map(Advancement::getId), p_136345_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("advancement").requires((p_136318_) -> {
return p_136318_.hasPermission(2);
}).then(Commands.literal("grant").then(Commands.argument("targets", EntityArgument.players()).then(Commands.literal("only").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136363_) -> {
return perform(p_136363_.getSource(), EntityArgument.getPlayers(p_136363_, "targets"), AdvancementCommands.Action.GRANT, getAdvancements(ResourceLocationArgument.getAdvancement(p_136363_, "advancement"), AdvancementCommands.Mode.ONLY));
}).then(Commands.argument("criterion", StringArgumentType.greedyString()).suggests((p_136339_, p_136340_) -> {
return SharedSuggestionProvider.suggest(ResourceLocationArgument.getAdvancement(p_136339_, "advancement").getCriteria().keySet(), p_136340_);
}).executes((p_136361_) -> {
return performCriterion(p_136361_.getSource(), EntityArgument.getPlayers(p_136361_, "targets"), AdvancementCommands.Action.GRANT, ResourceLocationArgument.getAdvancement(p_136361_, "advancement"), StringArgumentType.getString(p_136361_, "criterion"));
})))).then(Commands.literal("from").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136359_) -> {
return perform(p_136359_.getSource(), EntityArgument.getPlayers(p_136359_, "targets"), AdvancementCommands.Action.GRANT, getAdvancements(ResourceLocationArgument.getAdvancement(p_136359_, "advancement"), AdvancementCommands.Mode.FROM));
}))).then(Commands.literal("until").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136357_) -> {
return perform(p_136357_.getSource(), EntityArgument.getPlayers(p_136357_, "targets"), AdvancementCommands.Action.GRANT, getAdvancements(ResourceLocationArgument.getAdvancement(p_136357_, "advancement"), AdvancementCommands.Mode.UNTIL));
}))).then(Commands.literal("through").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136355_) -> {
return perform(p_136355_.getSource(), EntityArgument.getPlayers(p_136355_, "targets"), AdvancementCommands.Action.GRANT, getAdvancements(ResourceLocationArgument.getAdvancement(p_136355_, "advancement"), AdvancementCommands.Mode.THROUGH));
}))).then(Commands.literal("everything").executes((p_136353_) -> {
return perform(p_136353_.getSource(), EntityArgument.getPlayers(p_136353_, "targets"), AdvancementCommands.Action.GRANT, p_136353_.getSource().getServer().getAdvancements().getAllAdvancements());
})))).then(Commands.literal("revoke").then(Commands.argument("targets", EntityArgument.players()).then(Commands.literal("only").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136351_) -> {
return perform(p_136351_.getSource(), EntityArgument.getPlayers(p_136351_, "targets"), AdvancementCommands.Action.REVOKE, getAdvancements(ResourceLocationArgument.getAdvancement(p_136351_, "advancement"), AdvancementCommands.Mode.ONLY));
}).then(Commands.argument("criterion", StringArgumentType.greedyString()).suggests((p_136315_, p_136316_) -> {
return SharedSuggestionProvider.suggest(ResourceLocationArgument.getAdvancement(p_136315_, "advancement").getCriteria().keySet(), p_136316_);
}).executes((p_136349_) -> {
return performCriterion(p_136349_.getSource(), EntityArgument.getPlayers(p_136349_, "targets"), AdvancementCommands.Action.REVOKE, ResourceLocationArgument.getAdvancement(p_136349_, "advancement"), StringArgumentType.getString(p_136349_, "criterion"));
})))).then(Commands.literal("from").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136347_) -> {
return perform(p_136347_.getSource(), EntityArgument.getPlayers(p_136347_, "targets"), AdvancementCommands.Action.REVOKE, getAdvancements(ResourceLocationArgument.getAdvancement(p_136347_, "advancement"), AdvancementCommands.Mode.FROM));
}))).then(Commands.literal("until").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136342_) -> {
return perform(p_136342_.getSource(), EntityArgument.getPlayers(p_136342_, "targets"), AdvancementCommands.Action.REVOKE, getAdvancements(ResourceLocationArgument.getAdvancement(p_136342_, "advancement"), AdvancementCommands.Mode.UNTIL));
}))).then(Commands.literal("through").then(Commands.argument("advancement", ResourceLocationArgument.id()).suggests(SUGGEST_ADVANCEMENTS).executes((p_136337_) -> {
return perform(p_136337_.getSource(), EntityArgument.getPlayers(p_136337_, "targets"), AdvancementCommands.Action.REVOKE, getAdvancements(ResourceLocationArgument.getAdvancement(p_136337_, "advancement"), AdvancementCommands.Mode.THROUGH));
}))).then(Commands.literal("everything").executes((p_136313_) -> {
return perform(p_136313_.getSource(), EntityArgument.getPlayers(p_136313_, "targets"), AdvancementCommands.Action.REVOKE, p_136313_.getSource().getServer().getAdvancements().getAllAdvancements());
})))));
}
/**
* Performs the given action on each advancement in the list, for each player.
*
* @return The number of affected advancements across all players.
*/
private static int perform(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, AdvancementCommands.Action pAction, Collection<Advancement> pAdvancements) {
int i = 0;
for(ServerPlayer serverplayer : pTargets) {
i += pAction.perform(serverplayer, pAdvancements);
}
if (i == 0) {
if (pAdvancements.size() == 1) {
if (pTargets.size() == 1) {
throw new CommandRuntimeException(Component.translatable(pAction.getKey() + ".one.to.one.failure", pAdvancements.iterator().next().getChatComponent(), pTargets.iterator().next().getDisplayName()));
} else {
throw new CommandRuntimeException(Component.translatable(pAction.getKey() + ".one.to.many.failure", pAdvancements.iterator().next().getChatComponent(), pTargets.size()));
}
} else if (pTargets.size() == 1) {
throw new CommandRuntimeException(Component.translatable(pAction.getKey() + ".many.to.one.failure", pAdvancements.size(), pTargets.iterator().next().getDisplayName()));
} else {
throw new CommandRuntimeException(Component.translatable(pAction.getKey() + ".many.to.many.failure", pAdvancements.size(), pTargets.size()));
}
} else {
if (pAdvancements.size() == 1) {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable(pAction.getKey() + ".one.to.one.success", pAdvancements.iterator().next().getChatComponent(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable(pAction.getKey() + ".one.to.many.success", pAdvancements.iterator().next().getChatComponent(), pTargets.size());
}, true);
}
} else if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable(pAction.getKey() + ".many.to.one.success", pAdvancements.size(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable(pAction.getKey() + ".many.to.many.success", pAdvancements.size(), pTargets.size());
}, true);
}
return i;
}
}
/**
* Updates a single criterion based on the given action.
*
* @return The number of affected criteria across all players.
*/
private static int performCriterion(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, AdvancementCommands.Action pAction, Advancement pAdvancement, String pCriterionName) {
int i = 0;
if (!pAdvancement.getCriteria().containsKey(pCriterionName)) {
throw new CommandRuntimeException(Component.translatable("commands.advancement.criterionNotFound", pAdvancement.getChatComponent(), pCriterionName));
} else {
for(ServerPlayer serverplayer : pTargets) {
if (pAction.performCriterion(serverplayer, pAdvancement, pCriterionName)) {
++i;
}
}
if (i == 0) {
if (pTargets.size() == 1) {
throw new CommandRuntimeException(Component.translatable(pAction.getKey() + ".criterion.to.one.failure", pCriterionName, pAdvancement.getChatComponent(), pTargets.iterator().next().getDisplayName()));
} else {
throw new CommandRuntimeException(Component.translatable(pAction.getKey() + ".criterion.to.many.failure", pCriterionName, pAdvancement.getChatComponent(), pTargets.size()));
}
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable(pAction.getKey() + ".criterion.to.one.success", pCriterionName, pAdvancement.getChatComponent(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable(pAction.getKey() + ".criterion.to.many.success", pCriterionName, pAdvancement.getChatComponent(), pTargets.size());
}, true);
}
return i;
}
}
}
/**
* Gets all advancements that match the given mode.
*/
private static List<Advancement> getAdvancements(Advancement pAdvancement, AdvancementCommands.Mode pMode) {
List<Advancement> list = Lists.newArrayList();
if (pMode.parents) {
for(Advancement advancement = pAdvancement.getParent(); advancement != null; advancement = advancement.getParent()) {
list.add(advancement);
}
}
list.add(pAdvancement);
if (pMode.children) {
addChildren(pAdvancement, list);
}
return list;
}
/**
* Recursively adds all children of the given advancement to the given list. Does not add the advancement itself to
* the list.
*/
private static void addChildren(Advancement pAdvancement, List<Advancement> pList) {
for(Advancement advancement : pAdvancement.getChildren()) {
pList.add(advancement);
addChildren(advancement, pList);
}
}
static enum Action {
GRANT("grant") {
/**
* Applies this action to the given advancement.
*
* @return True if the player was affected.
*/
protected boolean perform(ServerPlayer p_136395_, Advancement p_136396_) {
AdvancementProgress advancementprogress = p_136395_.getAdvancements().getOrStartProgress(p_136396_);
if (advancementprogress.isDone()) {
return false;
} else {
for(String s : advancementprogress.getRemainingCriteria()) {
p_136395_.getAdvancements().award(p_136396_, s);
}
return true;
}
}
/**
* Applies this action to the given criterion.
*
* @return True if the player was affected.
*/
protected boolean performCriterion(ServerPlayer p_136398_, Advancement p_136399_, String p_136400_) {
return p_136398_.getAdvancements().award(p_136399_, p_136400_);
}
},
REVOKE("revoke") {
/**
* Applies this action to the given advancement.
*
* @return True if the player was affected.
*/
protected boolean perform(ServerPlayer p_136406_, Advancement p_136407_) {
AdvancementProgress advancementprogress = p_136406_.getAdvancements().getOrStartProgress(p_136407_);
if (!advancementprogress.hasProgress()) {
return false;
} else {
for(String s : advancementprogress.getCompletedCriteria()) {
p_136406_.getAdvancements().revoke(p_136407_, s);
}
return true;
}
}
/**
* Applies this action to the given criterion.
*
* @return True if the player was affected.
*/
protected boolean performCriterion(ServerPlayer p_136409_, Advancement p_136410_, String p_136411_) {
return p_136409_.getAdvancements().revoke(p_136410_, p_136411_);
}
};
private final String key;
Action(String pKey) {
this.key = "commands.advancement." + pKey;
}
/**
* Applies this action to all the given advancements.
*
* @return The number of players affected.
*/
public int perform(ServerPlayer pPlayer, Iterable<Advancement> pAdvancements) {
int i = 0;
for(Advancement advancement : pAdvancements) {
if (this.perform(pPlayer, advancement)) {
++i;
}
}
return i;
}
/**
* Applies this action to the given advancement.
*
* @return True if the player was affected.
*/
protected abstract boolean perform(ServerPlayer pPlayer, Advancement pAdvancement);
/**
* Applies this action to the given criterion.
*
* @return True if the player was affected.
*/
protected abstract boolean performCriterion(ServerPlayer pPlayer, Advancement pAdvancement, String pCriterionName);
protected String getKey() {
return this.key;
}
}
static enum Mode {
ONLY(false, false),
THROUGH(true, true),
FROM(false, true),
UNTIL(true, false),
EVERYTHING(true, true);
final boolean parents;
final boolean children;
private Mode(boolean pParents, boolean pChildren) {
this.parents = pParents;
this.children = pChildren;
}
}
}
@@ -0,0 +1,164 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import java.util.UUID;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.commands.arguments.UuidArgument;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeMap;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
public class AttributeCommand {
private static final DynamicCommandExceptionType ERROR_NOT_LIVING_ENTITY = new DynamicCommandExceptionType((p_212443_) -> {
return Component.translatable("commands.attribute.failed.entity", p_212443_);
});
private static final Dynamic2CommandExceptionType ERROR_NO_SUCH_ATTRIBUTE = new Dynamic2CommandExceptionType((p_212445_, p_212446_) -> {
return Component.translatable("commands.attribute.failed.no_attribute", p_212445_, p_212446_);
});
private static final Dynamic3CommandExceptionType ERROR_NO_SUCH_MODIFIER = new Dynamic3CommandExceptionType((p_212448_, p_212449_, p_212450_) -> {
return Component.translatable("commands.attribute.failed.no_modifier", p_212449_, p_212448_, p_212450_);
});
private static final Dynamic3CommandExceptionType ERROR_MODIFIER_ALREADY_PRESENT = new Dynamic3CommandExceptionType((p_136497_, p_136498_, p_136499_) -> {
return Component.translatable("commands.attribute.failed.modifier_already_present", p_136499_, p_136498_, p_136497_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("attribute").requires((p_212441_) -> {
return p_212441_.hasPermission(2);
}).then(Commands.argument("target", EntityArgument.entity()).then(Commands.argument("attribute", ResourceArgument.resource(pContext, Registries.ATTRIBUTE)).then(Commands.literal("get").executes((p_248109_) -> {
return getAttributeValue(p_248109_.getSource(), EntityArgument.getEntity(p_248109_, "target"), ResourceArgument.getAttribute(p_248109_, "attribute"), 1.0D);
}).then(Commands.argument("scale", DoubleArgumentType.doubleArg()).executes((p_248104_) -> {
return getAttributeValue(p_248104_.getSource(), EntityArgument.getEntity(p_248104_, "target"), ResourceArgument.getAttribute(p_248104_, "attribute"), DoubleArgumentType.getDouble(p_248104_, "scale"));
}))).then(Commands.literal("base").then(Commands.literal("set").then(Commands.argument("value", DoubleArgumentType.doubleArg()).executes((p_248102_) -> {
return setAttributeBase(p_248102_.getSource(), EntityArgument.getEntity(p_248102_, "target"), ResourceArgument.getAttribute(p_248102_, "attribute"), DoubleArgumentType.getDouble(p_248102_, "value"));
}))).then(Commands.literal("get").executes((p_248112_) -> {
return getAttributeBase(p_248112_.getSource(), EntityArgument.getEntity(p_248112_, "target"), ResourceArgument.getAttribute(p_248112_, "attribute"), 1.0D);
}).then(Commands.argument("scale", DoubleArgumentType.doubleArg()).executes((p_248106_) -> {
return getAttributeBase(p_248106_.getSource(), EntityArgument.getEntity(p_248106_, "target"), ResourceArgument.getAttribute(p_248106_, "attribute"), DoubleArgumentType.getDouble(p_248106_, "scale"));
})))).then(Commands.literal("modifier").then(Commands.literal("add").then(Commands.argument("uuid", UuidArgument.uuid()).then(Commands.argument("name", StringArgumentType.string()).then(Commands.argument("value", DoubleArgumentType.doubleArg()).then(Commands.literal("add").executes((p_248105_) -> {
return addModifier(p_248105_.getSource(), EntityArgument.getEntity(p_248105_, "target"), ResourceArgument.getAttribute(p_248105_, "attribute"), UuidArgument.getUuid(p_248105_, "uuid"), StringArgumentType.getString(p_248105_, "name"), DoubleArgumentType.getDouble(p_248105_, "value"), AttributeModifier.Operation.ADDITION);
})).then(Commands.literal("multiply").executes((p_248107_) -> {
return addModifier(p_248107_.getSource(), EntityArgument.getEntity(p_248107_, "target"), ResourceArgument.getAttribute(p_248107_, "attribute"), UuidArgument.getUuid(p_248107_, "uuid"), StringArgumentType.getString(p_248107_, "name"), DoubleArgumentType.getDouble(p_248107_, "value"), AttributeModifier.Operation.MULTIPLY_TOTAL);
})).then(Commands.literal("multiply_base").executes((p_248108_) -> {
return addModifier(p_248108_.getSource(), EntityArgument.getEntity(p_248108_, "target"), ResourceArgument.getAttribute(p_248108_, "attribute"), UuidArgument.getUuid(p_248108_, "uuid"), StringArgumentType.getString(p_248108_, "name"), DoubleArgumentType.getDouble(p_248108_, "value"), AttributeModifier.Operation.MULTIPLY_BASE);
})))))).then(Commands.literal("remove").then(Commands.argument("uuid", UuidArgument.uuid()).executes((p_248103_) -> {
return removeModifier(p_248103_.getSource(), EntityArgument.getEntity(p_248103_, "target"), ResourceArgument.getAttribute(p_248103_, "attribute"), UuidArgument.getUuid(p_248103_, "uuid"));
}))).then(Commands.literal("value").then(Commands.literal("get").then(Commands.argument("uuid", UuidArgument.uuid()).executes((p_248110_) -> {
return getAttributeModifier(p_248110_.getSource(), EntityArgument.getEntity(p_248110_, "target"), ResourceArgument.getAttribute(p_248110_, "attribute"), UuidArgument.getUuid(p_248110_, "uuid"), 1.0D);
}).then(Commands.argument("scale", DoubleArgumentType.doubleArg()).executes((p_248111_) -> {
return getAttributeModifier(p_248111_.getSource(), EntityArgument.getEntity(p_248111_, "target"), ResourceArgument.getAttribute(p_248111_, "attribute"), UuidArgument.getUuid(p_248111_, "uuid"), DoubleArgumentType.getDouble(p_248111_, "scale"));
})))))))));
}
private static AttributeInstance getAttributeInstance(Entity pEntity, Holder<Attribute> pAttribute) throws CommandSyntaxException {
AttributeInstance attributeinstance = getLivingEntity(pEntity).getAttributes().getInstance(pAttribute);
if (attributeinstance == null) {
throw ERROR_NO_SUCH_ATTRIBUTE.create(pEntity.getName(), getAttributeDescription(pAttribute));
} else {
return attributeinstance;
}
}
private static LivingEntity getLivingEntity(Entity pTarget) throws CommandSyntaxException {
if (!(pTarget instanceof LivingEntity)) {
throw ERROR_NOT_LIVING_ENTITY.create(pTarget.getName());
} else {
return (LivingEntity)pTarget;
}
}
private static LivingEntity getEntityWithAttribute(Entity pEntity, Holder<Attribute> pAttribute) throws CommandSyntaxException {
LivingEntity livingentity = getLivingEntity(pEntity);
if (!livingentity.getAttributes().hasAttribute(pAttribute)) {
throw ERROR_NO_SUCH_ATTRIBUTE.create(pEntity.getName(), getAttributeDescription(pAttribute));
} else {
return livingentity;
}
}
private static int getAttributeValue(CommandSourceStack pSource, Entity pEntity, Holder<Attribute> pAttribute, double pScale) throws CommandSyntaxException {
LivingEntity livingentity = getEntityWithAttribute(pEntity, pAttribute);
double d0 = livingentity.getAttributeValue(pAttribute);
pSource.sendSuccess(() -> {
return Component.translatable("commands.attribute.value.get.success", getAttributeDescription(pAttribute), pEntity.getName(), d0);
}, false);
return (int)(d0 * pScale);
}
private static int getAttributeBase(CommandSourceStack pSource, Entity pEntity, Holder<Attribute> pAttribute, double pScale) throws CommandSyntaxException {
LivingEntity livingentity = getEntityWithAttribute(pEntity, pAttribute);
double d0 = livingentity.getAttributeBaseValue(pAttribute);
pSource.sendSuccess(() -> {
return Component.translatable("commands.attribute.base_value.get.success", getAttributeDescription(pAttribute), pEntity.getName(), d0);
}, false);
return (int)(d0 * pScale);
}
private static int getAttributeModifier(CommandSourceStack pSource, Entity pEntity, Holder<Attribute> pAttribute, UUID pUuid, double pScale) throws CommandSyntaxException {
LivingEntity livingentity = getEntityWithAttribute(pEntity, pAttribute);
AttributeMap attributemap = livingentity.getAttributes();
if (!attributemap.hasModifier(pAttribute, pUuid)) {
throw ERROR_NO_SUCH_MODIFIER.create(pEntity.getName(), getAttributeDescription(pAttribute), pUuid);
} else {
double d0 = attributemap.getModifierValue(pAttribute, pUuid);
pSource.sendSuccess(() -> {
return Component.translatable("commands.attribute.modifier.value.get.success", pUuid, getAttributeDescription(pAttribute), pEntity.getName(), d0);
}, false);
return (int)(d0 * pScale);
}
}
private static int setAttributeBase(CommandSourceStack pSource, Entity pEntity, Holder<Attribute> pAttribute, double pValue) throws CommandSyntaxException {
getAttributeInstance(pEntity, pAttribute).setBaseValue(pValue);
pSource.sendSuccess(() -> {
return Component.translatable("commands.attribute.base_value.set.success", getAttributeDescription(pAttribute), pEntity.getName(), pValue);
}, false);
return 1;
}
private static int addModifier(CommandSourceStack pSource, Entity pEntity, Holder<Attribute> pAttribute, UUID pUuid, String pName, double pAmount, AttributeModifier.Operation pOperation) throws CommandSyntaxException {
AttributeInstance attributeinstance = getAttributeInstance(pEntity, pAttribute);
AttributeModifier attributemodifier = new AttributeModifier(pUuid, pName, pAmount, pOperation);
if (attributeinstance.hasModifier(attributemodifier)) {
throw ERROR_MODIFIER_ALREADY_PRESENT.create(pEntity.getName(), getAttributeDescription(pAttribute), pUuid);
} else {
attributeinstance.addPermanentModifier(attributemodifier);
pSource.sendSuccess(() -> {
return Component.translatable("commands.attribute.modifier.add.success", pUuid, getAttributeDescription(pAttribute), pEntity.getName());
}, false);
return 1;
}
}
private static int removeModifier(CommandSourceStack pSource, Entity pEntity, Holder<Attribute> pAttribute, UUID pUuid) throws CommandSyntaxException {
AttributeInstance attributeinstance = getAttributeInstance(pEntity, pAttribute);
if (attributeinstance.removePermanentModifier(pUuid)) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.attribute.modifier.remove.success", pUuid, getAttributeDescription(pAttribute), pEntity.getName());
}, false);
return 1;
} else {
throw ERROR_NO_SUCH_MODIFIER.create(pEntity.getName(), getAttributeDescription(pAttribute), pUuid);
}
}
private static Component getAttributeDescription(Holder<Attribute> pAttribute) {
return Component.translatable(pAttribute.value().getDescriptionId());
}
}
@@ -0,0 +1,71 @@
package net.minecraft.server.commands;
import com.google.common.net.InetAddresses;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Date;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.IpBanList;
import net.minecraft.server.players.IpBanListEntry;
public class BanIpCommands {
private static final SimpleCommandExceptionType ERROR_INVALID_IP = new SimpleCommandExceptionType(Component.translatable("commands.banip.invalid"));
private static final SimpleCommandExceptionType ERROR_ALREADY_BANNED = new SimpleCommandExceptionType(Component.translatable("commands.banip.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("ban-ip").requires((p_136532_) -> {
return p_136532_.hasPermission(3);
}).then(Commands.argument("target", StringArgumentType.word()).executes((p_136538_) -> {
return banIpOrName(p_136538_.getSource(), StringArgumentType.getString(p_136538_, "target"), (Component)null);
}).then(Commands.argument("reason", MessageArgument.message()).executes((p_136530_) -> {
return banIpOrName(p_136530_.getSource(), StringArgumentType.getString(p_136530_, "target"), MessageArgument.getMessage(p_136530_, "reason"));
}))));
}
private static int banIpOrName(CommandSourceStack pSource, String pUsername, @Nullable Component pReason) throws CommandSyntaxException {
if (InetAddresses.isInetAddress(pUsername)) {
return banIp(pSource, pUsername, pReason);
} else {
ServerPlayer serverplayer = pSource.getServer().getPlayerList().getPlayerByName(pUsername);
if (serverplayer != null) {
return banIp(pSource, serverplayer.getIpAddress(), pReason);
} else {
throw ERROR_INVALID_IP.create();
}
}
}
private static int banIp(CommandSourceStack pSource, String pIp, @Nullable Component pReason) throws CommandSyntaxException {
IpBanList ipbanlist = pSource.getServer().getPlayerList().getIpBans();
if (ipbanlist.isBanned(pIp)) {
throw ERROR_ALREADY_BANNED.create();
} else {
List<ServerPlayer> list = pSource.getServer().getPlayerList().getPlayersWithAddress(pIp);
IpBanListEntry ipbanlistentry = new IpBanListEntry(pIp, (Date)null, pSource.getTextName(), (Date)null, pReason == null ? null : pReason.getString());
ipbanlist.add(ipbanlistentry);
pSource.sendSuccess(() -> {
return Component.translatable("commands.banip.success", pIp, ipbanlistentry.getReason());
}, true);
if (!list.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.banip.info", list.size(), EntitySelector.joinNames(list));
}, true);
}
for(ServerPlayer serverplayer : list) {
serverplayer.connection.disconnect(Component.translatable("multiplayer.disconnect.ip_banned"));
}
return list.size();
}
}
}
@@ -0,0 +1,46 @@
package net.minecraft.server.commands;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.players.BanListEntry;
import net.minecraft.server.players.PlayerList;
public class BanListCommands {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("banlist").requires((p_136548_) -> {
return p_136548_.hasPermission(3);
}).executes((p_136555_) -> {
PlayerList playerlist = p_136555_.getSource().getServer().getPlayerList();
return showList(p_136555_.getSource(), Lists.newArrayList(Iterables.concat(playerlist.getBans().getEntries(), playerlist.getIpBans().getEntries())));
}).then(Commands.literal("ips").executes((p_136553_) -> {
return showList(p_136553_.getSource(), p_136553_.getSource().getServer().getPlayerList().getIpBans().getEntries());
})).then(Commands.literal("players").executes((p_136546_) -> {
return showList(p_136546_.getSource(), p_136546_.getSource().getServer().getPlayerList().getBans().getEntries());
})));
}
private static int showList(CommandSourceStack pSource, Collection<? extends BanListEntry<?>> pBannedPlayerList) {
if (pBannedPlayerList.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.banlist.none");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.banlist.list", pBannedPlayerList.size());
}, false);
for(BanListEntry<?> banlistentry : pBannedPlayerList) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.banlist.entry", banlistentry.getDisplayName(), banlistentry.getSource(), banlistentry.getReason());
}, false);
}
}
return pBannedPlayerList.size();
}
}
@@ -0,0 +1,58 @@
package net.minecraft.server.commands;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import java.util.Date;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.GameProfileArgument;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.UserBanList;
import net.minecraft.server.players.UserBanListEntry;
public class BanPlayerCommands {
private static final SimpleCommandExceptionType ERROR_ALREADY_BANNED = new SimpleCommandExceptionType(Component.translatable("commands.ban.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("ban").requires((p_136563_) -> {
return p_136563_.hasPermission(3);
}).then(Commands.argument("targets", GameProfileArgument.gameProfile()).executes((p_136569_) -> {
return banPlayers(p_136569_.getSource(), GameProfileArgument.getGameProfiles(p_136569_, "targets"), (Component)null);
}).then(Commands.argument("reason", MessageArgument.message()).executes((p_136561_) -> {
return banPlayers(p_136561_.getSource(), GameProfileArgument.getGameProfiles(p_136561_, "targets"), MessageArgument.getMessage(p_136561_, "reason"));
}))));
}
private static int banPlayers(CommandSourceStack pSource, Collection<GameProfile> pGameProfiles, @Nullable Component pReason) throws CommandSyntaxException {
UserBanList userbanlist = pSource.getServer().getPlayerList().getBans();
int i = 0;
for(GameProfile gameprofile : pGameProfiles) {
if (!userbanlist.isBanned(gameprofile)) {
UserBanListEntry userbanlistentry = new UserBanListEntry(gameprofile, (Date)null, pSource.getTextName(), (Date)null, pReason == null ? null : pReason.getString());
userbanlist.add(userbanlistentry);
++i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.ban.success", ComponentUtils.getDisplayName(gameprofile), userbanlistentry.getReason());
}, true);
ServerPlayer serverplayer = pSource.getServer().getPlayerList().getPlayer(gameprofile.getId());
if (serverplayer != null) {
serverplayer.connection.disconnect(Component.translatable("multiplayer.disconnect.banned"));
}
}
}
if (i == 0) {
throw ERROR_ALREADY_BANNED.create();
} else {
return i;
}
}
}
@@ -0,0 +1,296 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Collection;
import java.util.Collections;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.ComponentArgument;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.bossevents.CustomBossEvent;
import net.minecraft.server.bossevents.CustomBossEvents;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.BossEvent;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
public class BossBarCommands {
private static final DynamicCommandExceptionType ERROR_ALREADY_EXISTS = new DynamicCommandExceptionType((p_136636_) -> {
return Component.translatable("commands.bossbar.create.failed", p_136636_);
});
private static final DynamicCommandExceptionType ERROR_DOESNT_EXIST = new DynamicCommandExceptionType((p_136623_) -> {
return Component.translatable("commands.bossbar.unknown", p_136623_);
});
private static final SimpleCommandExceptionType ERROR_NO_PLAYER_CHANGE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.players.unchanged"));
private static final SimpleCommandExceptionType ERROR_NO_NAME_CHANGE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.name.unchanged"));
private static final SimpleCommandExceptionType ERROR_NO_COLOR_CHANGE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.color.unchanged"));
private static final SimpleCommandExceptionType ERROR_NO_STYLE_CHANGE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.style.unchanged"));
private static final SimpleCommandExceptionType ERROR_NO_VALUE_CHANGE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.value.unchanged"));
private static final SimpleCommandExceptionType ERROR_NO_MAX_CHANGE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.max.unchanged"));
private static final SimpleCommandExceptionType ERROR_ALREADY_HIDDEN = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.visibility.unchanged.hidden"));
private static final SimpleCommandExceptionType ERROR_ALREADY_VISIBLE = new SimpleCommandExceptionType(Component.translatable("commands.bossbar.set.visibility.unchanged.visible"));
public static final SuggestionProvider<CommandSourceStack> SUGGEST_BOSS_BAR = (p_136587_, p_136588_) -> {
return SharedSuggestionProvider.suggestResource(p_136587_.getSource().getServer().getCustomBossEvents().getIds(), p_136588_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("bossbar").requires((p_136627_) -> {
return p_136627_.hasPermission(2);
}).then(Commands.literal("add").then(Commands.argument("id", ResourceLocationArgument.id()).then(Commands.argument("name", ComponentArgument.textComponent()).executes((p_136693_) -> {
return createBar(p_136693_.getSource(), ResourceLocationArgument.getId(p_136693_, "id"), ComponentArgument.getComponent(p_136693_, "name"));
})))).then(Commands.literal("remove").then(Commands.argument("id", ResourceLocationArgument.id()).suggests(SUGGEST_BOSS_BAR).executes((p_136691_) -> {
return removeBar(p_136691_.getSource(), getBossBar(p_136691_));
}))).then(Commands.literal("list").executes((p_136689_) -> {
return listBars(p_136689_.getSource());
})).then(Commands.literal("set").then(Commands.argument("id", ResourceLocationArgument.id()).suggests(SUGGEST_BOSS_BAR).then(Commands.literal("name").then(Commands.argument("name", ComponentArgument.textComponent()).executes((p_136687_) -> {
return setName(p_136687_.getSource(), getBossBar(p_136687_), ComponentArgument.getComponent(p_136687_, "name"));
}))).then(Commands.literal("color").then(Commands.literal("pink").executes((p_136685_) -> {
return setColor(p_136685_.getSource(), getBossBar(p_136685_), BossEvent.BossBarColor.PINK);
})).then(Commands.literal("blue").executes((p_136683_) -> {
return setColor(p_136683_.getSource(), getBossBar(p_136683_), BossEvent.BossBarColor.BLUE);
})).then(Commands.literal("red").executes((p_136681_) -> {
return setColor(p_136681_.getSource(), getBossBar(p_136681_), BossEvent.BossBarColor.RED);
})).then(Commands.literal("green").executes((p_136679_) -> {
return setColor(p_136679_.getSource(), getBossBar(p_136679_), BossEvent.BossBarColor.GREEN);
})).then(Commands.literal("yellow").executes((p_136677_) -> {
return setColor(p_136677_.getSource(), getBossBar(p_136677_), BossEvent.BossBarColor.YELLOW);
})).then(Commands.literal("purple").executes((p_136675_) -> {
return setColor(p_136675_.getSource(), getBossBar(p_136675_), BossEvent.BossBarColor.PURPLE);
})).then(Commands.literal("white").executes((p_136673_) -> {
return setColor(p_136673_.getSource(), getBossBar(p_136673_), BossEvent.BossBarColor.WHITE);
}))).then(Commands.literal("style").then(Commands.literal("progress").executes((p_136671_) -> {
return setStyle(p_136671_.getSource(), getBossBar(p_136671_), BossEvent.BossBarOverlay.PROGRESS);
})).then(Commands.literal("notched_6").executes((p_136669_) -> {
return setStyle(p_136669_.getSource(), getBossBar(p_136669_), BossEvent.BossBarOverlay.NOTCHED_6);
})).then(Commands.literal("notched_10").executes((p_136667_) -> {
return setStyle(p_136667_.getSource(), getBossBar(p_136667_), BossEvent.BossBarOverlay.NOTCHED_10);
})).then(Commands.literal("notched_12").executes((p_136665_) -> {
return setStyle(p_136665_.getSource(), getBossBar(p_136665_), BossEvent.BossBarOverlay.NOTCHED_12);
})).then(Commands.literal("notched_20").executes((p_136663_) -> {
return setStyle(p_136663_.getSource(), getBossBar(p_136663_), BossEvent.BossBarOverlay.NOTCHED_20);
}))).then(Commands.literal("value").then(Commands.argument("value", IntegerArgumentType.integer(0)).executes((p_136661_) -> {
return setValue(p_136661_.getSource(), getBossBar(p_136661_), IntegerArgumentType.getInteger(p_136661_, "value"));
}))).then(Commands.literal("max").then(Commands.argument("max", IntegerArgumentType.integer(1)).executes((p_136659_) -> {
return setMax(p_136659_.getSource(), getBossBar(p_136659_), IntegerArgumentType.getInteger(p_136659_, "max"));
}))).then(Commands.literal("visible").then(Commands.argument("visible", BoolArgumentType.bool()).executes((p_136657_) -> {
return setVisible(p_136657_.getSource(), getBossBar(p_136657_), BoolArgumentType.getBool(p_136657_, "visible"));
}))).then(Commands.literal("players").executes((p_136655_) -> {
return setPlayers(p_136655_.getSource(), getBossBar(p_136655_), Collections.emptyList());
}).then(Commands.argument("targets", EntityArgument.players()).executes((p_136653_) -> {
return setPlayers(p_136653_.getSource(), getBossBar(p_136653_), EntityArgument.getOptionalPlayers(p_136653_, "targets"));
}))))).then(Commands.literal("get").then(Commands.argument("id", ResourceLocationArgument.id()).suggests(SUGGEST_BOSS_BAR).then(Commands.literal("value").executes((p_136648_) -> {
return getValue(p_136648_.getSource(), getBossBar(p_136648_));
})).then(Commands.literal("max").executes((p_136643_) -> {
return getMax(p_136643_.getSource(), getBossBar(p_136643_));
})).then(Commands.literal("visible").executes((p_136638_) -> {
return getVisible(p_136638_.getSource(), getBossBar(p_136638_));
})).then(Commands.literal("players").executes((p_136625_) -> {
return getPlayers(p_136625_.getSource(), getBossBar(p_136625_));
})))));
}
private static int getValue(CommandSourceStack pSource, CustomBossEvent pBossbar) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.value", pBossbar.getDisplayName(), pBossbar.getValue());
}, true);
return pBossbar.getValue();
}
private static int getMax(CommandSourceStack pSource, CustomBossEvent pBossbar) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.max", pBossbar.getDisplayName(), pBossbar.getMax());
}, true);
return pBossbar.getMax();
}
private static int getVisible(CommandSourceStack pSource, CustomBossEvent pBossbar) {
if (pBossbar.isVisible()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.visible.visible", pBossbar.getDisplayName());
}, true);
return 1;
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.visible.hidden", pBossbar.getDisplayName());
}, true);
return 0;
}
}
private static int getPlayers(CommandSourceStack pSource, CustomBossEvent pBossbar) {
if (pBossbar.getPlayers().isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.players.none", pBossbar.getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.players.some", pBossbar.getDisplayName(), pBossbar.getPlayers().size(), ComponentUtils.formatList(pBossbar.getPlayers(), Player::getDisplayName));
}, true);
}
return pBossbar.getPlayers().size();
}
private static int setVisible(CommandSourceStack pSource, CustomBossEvent pBossbar, boolean pVisible) throws CommandSyntaxException {
if (pBossbar.isVisible() == pVisible) {
if (pVisible) {
throw ERROR_ALREADY_VISIBLE.create();
} else {
throw ERROR_ALREADY_HIDDEN.create();
}
} else {
pBossbar.setVisible(pVisible);
if (pVisible) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.visible.success.visible", pBossbar.getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.visible.success.hidden", pBossbar.getDisplayName());
}, true);
}
return 0;
}
}
private static int setValue(CommandSourceStack pSource, CustomBossEvent pBossbar, int pValue) throws CommandSyntaxException {
if (pBossbar.getValue() == pValue) {
throw ERROR_NO_VALUE_CHANGE.create();
} else {
pBossbar.setValue(pValue);
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.value.success", pBossbar.getDisplayName(), pValue);
}, true);
return pValue;
}
}
private static int setMax(CommandSourceStack pSource, CustomBossEvent pBossbar, int pMax) throws CommandSyntaxException {
if (pBossbar.getMax() == pMax) {
throw ERROR_NO_MAX_CHANGE.create();
} else {
pBossbar.setMax(pMax);
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.max.success", pBossbar.getDisplayName(), pMax);
}, true);
return pMax;
}
}
private static int setColor(CommandSourceStack pSource, CustomBossEvent pBossbar, BossEvent.BossBarColor pColor) throws CommandSyntaxException {
if (pBossbar.getColor().equals(pColor)) {
throw ERROR_NO_COLOR_CHANGE.create();
} else {
pBossbar.setColor(pColor);
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.color.success", pBossbar.getDisplayName());
}, true);
return 0;
}
}
private static int setStyle(CommandSourceStack pSource, CustomBossEvent pBossbar, BossEvent.BossBarOverlay pStyle) throws CommandSyntaxException {
if (pBossbar.getOverlay().equals(pStyle)) {
throw ERROR_NO_STYLE_CHANGE.create();
} else {
pBossbar.setOverlay(pStyle);
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.style.success", pBossbar.getDisplayName());
}, true);
return 0;
}
}
private static int setName(CommandSourceStack pSource, CustomBossEvent pBossbar, Component pName) throws CommandSyntaxException {
Component component = ComponentUtils.updateForEntity(pSource, pName, (Entity)null, 0);
if (pBossbar.getName().equals(component)) {
throw ERROR_NO_NAME_CHANGE.create();
} else {
pBossbar.setName(component);
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.name.success", pBossbar.getDisplayName());
}, true);
return 0;
}
}
private static int setPlayers(CommandSourceStack pSource, CustomBossEvent pBossbar, Collection<ServerPlayer> pPlayers) throws CommandSyntaxException {
boolean flag = pBossbar.setPlayers(pPlayers);
if (!flag) {
throw ERROR_NO_PLAYER_CHANGE.create();
} else {
if (pBossbar.getPlayers().isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.players.success.none", pBossbar.getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.players.success.some", pBossbar.getDisplayName(), pPlayers.size(), ComponentUtils.formatList(pPlayers, Player::getDisplayName));
}, true);
}
return pBossbar.getPlayers().size();
}
}
private static int listBars(CommandSourceStack pSource) {
Collection<CustomBossEvent> collection = pSource.getServer().getCustomBossEvents().getEvents();
if (collection.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.list.bars.none");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.list.bars.some", collection.size(), ComponentUtils.formatList(collection, CustomBossEvent::getDisplayName));
}, false);
}
return collection.size();
}
private static int createBar(CommandSourceStack pSource, ResourceLocation pId, Component pDisplayName) throws CommandSyntaxException {
CustomBossEvents custombossevents = pSource.getServer().getCustomBossEvents();
if (custombossevents.get(pId) != null) {
throw ERROR_ALREADY_EXISTS.create(pId.toString());
} else {
CustomBossEvent custombossevent = custombossevents.create(pId, ComponentUtils.updateForEntity(pSource, pDisplayName, (Entity)null, 0));
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.create.success", custombossevent.getDisplayName());
}, true);
return custombossevents.getEvents().size();
}
}
private static int removeBar(CommandSourceStack pSource, CustomBossEvent pBossbar) {
CustomBossEvents custombossevents = pSource.getServer().getCustomBossEvents();
pBossbar.removeAllPlayers();
custombossevents.remove(pBossbar);
pSource.sendSuccess(() -> {
return Component.translatable("commands.bossbar.remove.success", pBossbar.getDisplayName());
}, true);
return custombossevents.getEvents().size();
}
public static CustomBossEvent getBossBar(CommandContext<CommandSourceStack> pSource) throws CommandSyntaxException {
ResourceLocation resourcelocation = ResourceLocationArgument.getId(pSource, "id");
CustomBossEvent custombossevent = pSource.getSource().getServer().getCustomBossEvents().get(resourcelocation);
if (custombossevent == null) {
throw ERROR_DOESNT_EXIST.create(resourcelocation.toString());
} else {
return custombossevent;
}
}
}
@@ -0,0 +1,112 @@
package net.minecraft.server.commands;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import java.io.IOException;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.chase.ChaseClient;
import net.minecraft.server.chase.ChaseServer;
import net.minecraft.world.level.Level;
public class ChaseCommand {
private static final String DEFAULT_CONNECT_HOST = "localhost";
private static final String DEFAULT_BIND_ADDRESS = "0.0.0.0";
private static final int DEFAULT_PORT = 10000;
private static final int BROADCAST_INTERVAL_MS = 100;
public static BiMap<String, ResourceKey<Level>> DIMENSION_NAMES = ImmutableBiMap.of("o", Level.OVERWORLD, "n", Level.NETHER, "e", Level.END);
@Nullable
private static ChaseServer chaseServer;
@Nullable
private static ChaseClient chaseClient;
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("chase").then(Commands.literal("follow").then(Commands.argument("host", StringArgumentType.string()).executes((p_196104_) -> {
return follow(p_196104_.getSource(), StringArgumentType.getString(p_196104_, "host"), 10000);
}).then(Commands.argument("port", IntegerArgumentType.integer(1, 65535)).executes((p_196102_) -> {
return follow(p_196102_.getSource(), StringArgumentType.getString(p_196102_, "host"), IntegerArgumentType.getInteger(p_196102_, "port"));
}))).executes((p_196100_) -> {
return follow(p_196100_.getSource(), "localhost", 10000);
})).then(Commands.literal("lead").then(Commands.argument("bind_address", StringArgumentType.string()).executes((p_196098_) -> {
return lead(p_196098_.getSource(), StringArgumentType.getString(p_196098_, "bind_address"), 10000);
}).then(Commands.argument("port", IntegerArgumentType.integer(1024, 65535)).executes((p_196096_) -> {
return lead(p_196096_.getSource(), StringArgumentType.getString(p_196096_, "bind_address"), IntegerArgumentType.getInteger(p_196096_, "port"));
}))).executes((p_196088_) -> {
return lead(p_196088_.getSource(), "0.0.0.0", 10000);
})).then(Commands.literal("stop").executes((p_196080_) -> {
return stop(p_196080_.getSource());
})));
}
private static int stop(CommandSourceStack pSource) {
if (chaseClient != null) {
chaseClient.stop();
pSource.sendSuccess(() -> {
return Component.literal("You have now stopped chasing");
}, false);
chaseClient = null;
}
if (chaseServer != null) {
chaseServer.stop();
pSource.sendSuccess(() -> {
return Component.literal("You are no longer being chased");
}, false);
chaseServer = null;
}
return 0;
}
private static boolean alreadyRunning(CommandSourceStack pSource) {
if (chaseServer != null) {
pSource.sendFailure(Component.literal("Chase server is already running. Stop it using /chase stop"));
return true;
} else if (chaseClient != null) {
pSource.sendFailure(Component.literal("You are already chasing someone. Stop it using /chase stop"));
return true;
} else {
return false;
}
}
private static int lead(CommandSourceStack pSource, String pBindAddress, int pPort) {
if (alreadyRunning(pSource)) {
return 0;
} else {
chaseServer = new ChaseServer(pBindAddress, pPort, pSource.getServer().getPlayerList(), 100);
try {
chaseServer.start();
pSource.sendSuccess(() -> {
return Component.literal("Chase server is now running on port " + pPort + ". Clients can follow you using /chase follow <ip> <port>");
}, false);
} catch (IOException ioexception) {
ioexception.printStackTrace();
pSource.sendFailure(Component.literal("Failed to start chase server on port " + pPort));
chaseServer = null;
}
return 0;
}
}
private static int follow(CommandSourceStack pSource, String pHost, int pPort) {
if (alreadyRunning(pSource)) {
return 0;
} else {
chaseClient = new ChaseClient(pHost, pPort, pSource.getServer());
chaseClient.start();
pSource.sendSuccess(() -> {
return Component.literal("You are now chasing " + pHost + ":" + pPort + ". If that server does '/chase lead' then you will automatically go to the same position. Use '/chase stop' to stop chasing.");
}, false);
return 0;
}
}
}
@@ -0,0 +1,85 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import java.util.Collection;
import java.util.Collections;
import java.util.function.Predicate;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.item.ItemPredicateArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
public class ClearInventoryCommands {
private static final DynamicCommandExceptionType ERROR_SINGLE = new DynamicCommandExceptionType((p_136717_) -> {
return Component.translatable("clear.failed.single", p_136717_);
});
private static final DynamicCommandExceptionType ERROR_MULTIPLE = new DynamicCommandExceptionType((p_136711_) -> {
return Component.translatable("clear.failed.multiple", p_136711_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("clear").requires((p_136704_) -> {
return p_136704_.hasPermission(2);
}).executes((p_136721_) -> {
return clearInventory(p_136721_.getSource(), Collections.singleton(p_136721_.getSource().getPlayerOrException()), (p_180029_) -> {
return true;
}, -1);
}).then(Commands.argument("targets", EntityArgument.players()).executes((p_136719_) -> {
return clearInventory(p_136719_.getSource(), EntityArgument.getPlayers(p_136719_, "targets"), (p_180027_) -> {
return true;
}, -1);
}).then(Commands.argument("item", ItemPredicateArgument.itemPredicate(pContext)).executes((p_136715_) -> {
return clearInventory(p_136715_.getSource(), EntityArgument.getPlayers(p_136715_, "targets"), ItemPredicateArgument.getItemPredicate(p_136715_, "item"), -1);
}).then(Commands.argument("maxCount", IntegerArgumentType.integer(0)).executes((p_136702_) -> {
return clearInventory(p_136702_.getSource(), EntityArgument.getPlayers(p_136702_, "targets"), ItemPredicateArgument.getItemPredicate(p_136702_, "item"), IntegerArgumentType.getInteger(p_136702_, "maxCount"));
})))));
}
private static int clearInventory(CommandSourceStack pSource, Collection<ServerPlayer> pTargetPlayers, Predicate<ItemStack> pItemPredicate, int pMaxCount) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : pTargetPlayers) {
i += serverplayer.getInventory().clearOrCountMatchingItems(pItemPredicate, pMaxCount, serverplayer.inventoryMenu.getCraftSlots());
serverplayer.containerMenu.broadcastChanges();
serverplayer.inventoryMenu.slotsChanged(serverplayer.getInventory());
}
if (i == 0) {
if (pTargetPlayers.size() == 1) {
throw ERROR_SINGLE.create(pTargetPlayers.iterator().next().getName());
} else {
throw ERROR_MULTIPLE.create(pTargetPlayers.size());
}
} else {
int j = i;
if (pMaxCount == 0) {
if (pTargetPlayers.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.clear.test.single", j, pTargetPlayers.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.clear.test.multiple", j, pTargetPlayers.size());
}, true);
}
} else if (pTargetPlayers.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.clear.success.single", j, pTargetPlayers.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.clear.success.multiple", j, pTargetPlayers.size());
}, true);
}
return i;
}
}
}
@@ -0,0 +1,254 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Deque;
import java.util.List;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.DimensionArgument;
import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Clearable;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
public class CloneCommands {
private static final SimpleCommandExceptionType ERROR_OVERLAP = new SimpleCommandExceptionType(Component.translatable("commands.clone.overlap"));
private static final Dynamic2CommandExceptionType ERROR_AREA_TOO_LARGE = new Dynamic2CommandExceptionType((p_136743_, p_136744_) -> {
return Component.translatable("commands.clone.toobig", p_136743_, p_136744_);
});
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.clone.failed"));
public static final Predicate<BlockInWorld> FILTER_AIR = (p_284652_) -> {
return !p_284652_.getState().isAir();
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("clone").requires((p_136734_) -> {
return p_136734_.hasPermission(2);
}).then(beginEndDestinationAndModeSuffix(pContext, (p_264757_) -> {
return p_264757_.getSource().getLevel();
})).then(Commands.literal("from").then(Commands.argument("sourceDimension", DimensionArgument.dimension()).then(beginEndDestinationAndModeSuffix(pContext, (p_264743_) -> {
return DimensionArgument.getDimension(p_264743_, "sourceDimension");
})))));
}
private static ArgumentBuilder<CommandSourceStack, ?> beginEndDestinationAndModeSuffix(CommandBuildContext pBuildContext, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, ServerLevel> pLevelGetter) {
return Commands.argument("begin", BlockPosArgument.blockPos()).then(Commands.argument("end", BlockPosArgument.blockPos()).then(destinationAndModeSuffix(pBuildContext, pLevelGetter, (p_264751_) -> {
return p_264751_.getSource().getLevel();
})).then(Commands.literal("to").then(Commands.argument("targetDimension", DimensionArgument.dimension()).then(destinationAndModeSuffix(pBuildContext, pLevelGetter, (p_264756_) -> {
return DimensionArgument.getDimension(p_264756_, "targetDimension");
})))));
}
private static CloneCommands.DimensionAndPosition getLoadedDimensionAndPosition(CommandContext<CommandSourceStack> pContext, ServerLevel pLevel, String pName) throws CommandSyntaxException {
BlockPos blockpos = BlockPosArgument.getLoadedBlockPos(pContext, pLevel, pName);
return new CloneCommands.DimensionAndPosition(pLevel, blockpos);
}
private static ArgumentBuilder<CommandSourceStack, ?> destinationAndModeSuffix(CommandBuildContext pBuildContext, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, ServerLevel> pSourceLevelGetter, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, ServerLevel> pDestinationLevelGetter) {
CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> commandfunction = (p_264737_) -> {
return getLoadedDimensionAndPosition(p_264737_, pSourceLevelGetter.apply(p_264737_), "begin");
};
CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> commandfunction1 = (p_264735_) -> {
return getLoadedDimensionAndPosition(p_264735_, pSourceLevelGetter.apply(p_264735_), "end");
};
CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> commandfunction2 = (p_264768_) -> {
return getLoadedDimensionAndPosition(p_264768_, pDestinationLevelGetter.apply(p_264768_), "destination");
};
return Commands.argument("destination", BlockPosArgument.blockPos()).executes((p_264761_) -> {
return clone(p_264761_.getSource(), commandfunction.apply(p_264761_), commandfunction1.apply(p_264761_), commandfunction2.apply(p_264761_), (p_180033_) -> {
return true;
}, CloneCommands.Mode.NORMAL);
}).then(wrapWithCloneMode(commandfunction, commandfunction1, commandfunction2, (p_264738_) -> {
return (p_180041_) -> {
return true;
};
}, Commands.literal("replace").executes((p_264755_) -> {
return clone(p_264755_.getSource(), commandfunction.apply(p_264755_), commandfunction1.apply(p_264755_), commandfunction2.apply(p_264755_), (p_180039_) -> {
return true;
}, CloneCommands.Mode.NORMAL);
}))).then(wrapWithCloneMode(commandfunction, commandfunction1, commandfunction2, (p_264744_) -> {
return FILTER_AIR;
}, Commands.literal("masked").executes((p_264742_) -> {
return clone(p_264742_.getSource(), commandfunction.apply(p_264742_), commandfunction1.apply(p_264742_), commandfunction2.apply(p_264742_), FILTER_AIR, CloneCommands.Mode.NORMAL);
}))).then(Commands.literal("filtered").then(wrapWithCloneMode(commandfunction, commandfunction1, commandfunction2, (p_264745_) -> {
return BlockPredicateArgument.getBlockPredicate(p_264745_, "filter");
}, Commands.argument("filter", BlockPredicateArgument.blockPredicate(pBuildContext)).executes((p_264733_) -> {
return clone(p_264733_.getSource(), commandfunction.apply(p_264733_), commandfunction1.apply(p_264733_), commandfunction2.apply(p_264733_), BlockPredicateArgument.getBlockPredicate(p_264733_, "filter"), CloneCommands.Mode.NORMAL);
}))));
}
private static ArgumentBuilder<CommandSourceStack, ?> wrapWithCloneMode(CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> pBeginGetter, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> pEndGetter, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> pTargetGetter, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, Predicate<BlockInWorld>> pFilterGetter, ArgumentBuilder<CommandSourceStack, ?> pArgumentBuilder) {
return pArgumentBuilder.then(Commands.literal("force").executes((p_264773_) -> {
return clone(p_264773_.getSource(), pBeginGetter.apply(p_264773_), pEndGetter.apply(p_264773_), pTargetGetter.apply(p_264773_), pFilterGetter.apply(p_264773_), CloneCommands.Mode.FORCE);
})).then(Commands.literal("move").executes((p_264766_) -> {
return clone(p_264766_.getSource(), pBeginGetter.apply(p_264766_), pEndGetter.apply(p_264766_), pTargetGetter.apply(p_264766_), pFilterGetter.apply(p_264766_), CloneCommands.Mode.MOVE);
})).then(Commands.literal("normal").executes((p_264750_) -> {
return clone(p_264750_.getSource(), pBeginGetter.apply(p_264750_), pEndGetter.apply(p_264750_), pTargetGetter.apply(p_264750_), pFilterGetter.apply(p_264750_), CloneCommands.Mode.NORMAL);
}));
}
private static int clone(CommandSourceStack pSource, CloneCommands.DimensionAndPosition pBegin, CloneCommands.DimensionAndPosition pEnd, CloneCommands.DimensionAndPosition pTarget, Predicate<BlockInWorld> pFilter, CloneCommands.Mode pMode) throws CommandSyntaxException {
BlockPos blockpos = pBegin.position();
BlockPos blockpos1 = pEnd.position();
BoundingBox boundingbox = BoundingBox.fromCorners(blockpos, blockpos1);
BlockPos blockpos2 = pTarget.position();
BlockPos blockpos3 = blockpos2.offset(boundingbox.getLength());
BoundingBox boundingbox1 = BoundingBox.fromCorners(blockpos2, blockpos3);
ServerLevel serverlevel = pBegin.dimension();
ServerLevel serverlevel1 = pTarget.dimension();
if (!pMode.canOverlap() && serverlevel == serverlevel1 && boundingbox1.intersects(boundingbox)) {
throw ERROR_OVERLAP.create();
} else {
int i = boundingbox.getXSpan() * boundingbox.getYSpan() * boundingbox.getZSpan();
int j = pSource.getLevel().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT);
if (i > j) {
throw ERROR_AREA_TOO_LARGE.create(j, i);
} else if (serverlevel.hasChunksAt(blockpos, blockpos1) && serverlevel1.hasChunksAt(blockpos2, blockpos3)) {
List<CloneCommands.CloneBlockInfo> list = Lists.newArrayList();
List<CloneCommands.CloneBlockInfo> list1 = Lists.newArrayList();
List<CloneCommands.CloneBlockInfo> list2 = Lists.newArrayList();
Deque<BlockPos> deque = Lists.newLinkedList();
BlockPos blockpos4 = new BlockPos(boundingbox1.minX() - boundingbox.minX(), boundingbox1.minY() - boundingbox.minY(), boundingbox1.minZ() - boundingbox.minZ());
for(int k = boundingbox.minZ(); k <= boundingbox.maxZ(); ++k) {
for(int l = boundingbox.minY(); l <= boundingbox.maxY(); ++l) {
for(int i1 = boundingbox.minX(); i1 <= boundingbox.maxX(); ++i1) {
BlockPos blockpos5 = new BlockPos(i1, l, k);
BlockPos blockpos6 = blockpos5.offset(blockpos4);
BlockInWorld blockinworld = new BlockInWorld(serverlevel, blockpos5, false);
BlockState blockstate = blockinworld.getState();
if (pFilter.test(blockinworld)) {
BlockEntity blockentity = serverlevel.getBlockEntity(blockpos5);
if (blockentity != null) {
CompoundTag compoundtag = blockentity.saveWithoutMetadata();
list1.add(new CloneCommands.CloneBlockInfo(blockpos6, blockstate, compoundtag));
deque.addLast(blockpos5);
} else if (!blockstate.isSolidRender(serverlevel, blockpos5) && !blockstate.isCollisionShapeFullBlock(serverlevel, blockpos5)) {
list2.add(new CloneCommands.CloneBlockInfo(blockpos6, blockstate, (CompoundTag)null));
deque.addFirst(blockpos5);
} else {
list.add(new CloneCommands.CloneBlockInfo(blockpos6, blockstate, (CompoundTag)null));
deque.addLast(blockpos5);
}
}
}
}
}
if (pMode == CloneCommands.Mode.MOVE) {
for(BlockPos blockpos7 : deque) {
BlockEntity blockentity1 = serverlevel.getBlockEntity(blockpos7);
Clearable.tryClear(blockentity1);
serverlevel.setBlock(blockpos7, Blocks.BARRIER.defaultBlockState(), 2);
}
for(BlockPos blockpos8 : deque) {
serverlevel.setBlock(blockpos8, Blocks.AIR.defaultBlockState(), 3);
}
}
List<CloneCommands.CloneBlockInfo> list3 = Lists.newArrayList();
list3.addAll(list);
list3.addAll(list1);
list3.addAll(list2);
List<CloneCommands.CloneBlockInfo> list4 = Lists.reverse(list3);
for(CloneCommands.CloneBlockInfo clonecommands$cloneblockinfo : list4) {
BlockEntity blockentity2 = serverlevel1.getBlockEntity(clonecommands$cloneblockinfo.pos);
Clearable.tryClear(blockentity2);
serverlevel1.setBlock(clonecommands$cloneblockinfo.pos, Blocks.BARRIER.defaultBlockState(), 2);
}
int j1 = 0;
for(CloneCommands.CloneBlockInfo clonecommands$cloneblockinfo1 : list3) {
if (serverlevel1.setBlock(clonecommands$cloneblockinfo1.pos, clonecommands$cloneblockinfo1.state, 2)) {
++j1;
}
}
for(CloneCommands.CloneBlockInfo clonecommands$cloneblockinfo2 : list1) {
BlockEntity blockentity3 = serverlevel1.getBlockEntity(clonecommands$cloneblockinfo2.pos);
if (clonecommands$cloneblockinfo2.tag != null && blockentity3 != null) {
blockentity3.load(clonecommands$cloneblockinfo2.tag);
blockentity3.setChanged();
}
serverlevel1.setBlock(clonecommands$cloneblockinfo2.pos, clonecommands$cloneblockinfo2.state, 2);
}
for(CloneCommands.CloneBlockInfo clonecommands$cloneblockinfo3 : list4) {
serverlevel1.blockUpdated(clonecommands$cloneblockinfo3.pos, clonecommands$cloneblockinfo3.state.getBlock());
}
serverlevel1.getBlockTicks().copyAreaFrom(serverlevel.getBlockTicks(), boundingbox, blockpos4);
if (j1 == 0) {
throw ERROR_FAILED.create();
} else {
int k1 = j1;
pSource.sendSuccess(() -> {
return Component.translatable("commands.clone.success", k1);
}, true);
return j1;
}
} else {
throw BlockPosArgument.ERROR_NOT_LOADED.create();
}
}
}
static class CloneBlockInfo {
public final BlockPos pos;
public final BlockState state;
@Nullable
public final CompoundTag tag;
public CloneBlockInfo(BlockPos pPos, BlockState pState, @Nullable CompoundTag pTag) {
this.pos = pPos;
this.state = pState;
this.tag = pTag;
}
}
@FunctionalInterface
interface CommandFunction<T, R> {
R apply(T p_265571_) throws CommandSyntaxException;
}
static record DimensionAndPosition(ServerLevel dimension, BlockPos position) {
}
static enum Mode {
FORCE(true),
MOVE(true),
NORMAL(false);
private final boolean canOverlap;
private Mode(boolean pCanOverlap) {
this.canOverlap = pCanOverlap;
}
public boolean canOverlap() {
return this.canOverlap;
}
}
}
@@ -0,0 +1,47 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
public class DamageCommand {
private static final SimpleCommandExceptionType ERROR_INVULNERABLE = new SimpleCommandExceptionType(Component.translatable("commands.damage.invulnerable"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("damage").requires((p_270872_) -> {
return p_270872_.hasPermission(2);
}).then(Commands.argument("target", EntityArgument.entity()).then(Commands.argument("amount", FloatArgumentType.floatArg(0.0F)).executes((p_288351_) -> {
return damage(p_288351_.getSource(), EntityArgument.getEntity(p_288351_, "target"), FloatArgumentType.getFloat(p_288351_, "amount"), p_288351_.getSource().getLevel().damageSources().generic());
}).then(Commands.argument("damageType", ResourceArgument.resource(pContext, Registries.DAMAGE_TYPE)).executes((p_270840_) -> {
return damage(p_270840_.getSource(), EntityArgument.getEntity(p_270840_, "target"), FloatArgumentType.getFloat(p_270840_, "amount"), new DamageSource(ResourceArgument.getResource(p_270840_, "damageType", Registries.DAMAGE_TYPE)));
}).then(Commands.literal("at").then(Commands.argument("location", Vec3Argument.vec3()).executes((p_270444_) -> {
return damage(p_270444_.getSource(), EntityArgument.getEntity(p_270444_, "target"), FloatArgumentType.getFloat(p_270444_, "amount"), new DamageSource(ResourceArgument.getResource(p_270444_, "damageType", Registries.DAMAGE_TYPE), Vec3Argument.getVec3(p_270444_, "location")));
}))).then(Commands.literal("by").then(Commands.argument("entity", EntityArgument.entity()).executes((p_270329_) -> {
return damage(p_270329_.getSource(), EntityArgument.getEntity(p_270329_, "target"), FloatArgumentType.getFloat(p_270329_, "amount"), new DamageSource(ResourceArgument.getResource(p_270329_, "damageType", Registries.DAMAGE_TYPE), EntityArgument.getEntity(p_270329_, "entity")));
}).then(Commands.literal("from").then(Commands.argument("cause", EntityArgument.entity()).executes((p_270848_) -> {
return damage(p_270848_.getSource(), EntityArgument.getEntity(p_270848_, "target"), FloatArgumentType.getFloat(p_270848_, "amount"), new DamageSource(ResourceArgument.getResource(p_270848_, "damageType", Registries.DAMAGE_TYPE), EntityArgument.getEntity(p_270848_, "entity"), EntityArgument.getEntity(p_270848_, "cause")));
})))))))));
}
private static int damage(CommandSourceStack pSource, Entity pTarget, float pAmount, DamageSource pDamageType) throws CommandSyntaxException {
if (pTarget.hurt(pDamageType, pAmount)) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.damage.success", pAmount, pTarget.getDisplayName());
}, true);
return 1;
} else {
throw ERROR_INVULNERABLE.create();
}
}
}
@@ -0,0 +1,206 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.flag.FeatureFlags;
public class DataPackCommand {
private static final DynamicCommandExceptionType ERROR_UNKNOWN_PACK = new DynamicCommandExceptionType((p_136868_) -> {
return Component.translatable("commands.datapack.unknown", p_136868_);
});
private static final DynamicCommandExceptionType ERROR_PACK_ALREADY_ENABLED = new DynamicCommandExceptionType((p_136857_) -> {
return Component.translatable("commands.datapack.enable.failed", p_136857_);
});
private static final DynamicCommandExceptionType ERROR_PACK_ALREADY_DISABLED = new DynamicCommandExceptionType((p_136833_) -> {
return Component.translatable("commands.datapack.disable.failed", p_136833_);
});
private static final Dynamic2CommandExceptionType ERROR_PACK_FEATURES_NOT_ENABLED = new Dynamic2CommandExceptionType((p_248117_, p_248118_) -> {
return Component.translatable("commands.datapack.enable.failed.no_flags", p_248117_, p_248118_);
});
private static final SuggestionProvider<CommandSourceStack> SELECTED_PACKS = (p_136848_, p_136849_) -> {
return SharedSuggestionProvider.suggest(p_136848_.getSource().getServer().getPackRepository().getSelectedIds().stream().map(StringArgumentType::escapeIfRequired), p_136849_);
};
private static final SuggestionProvider<CommandSourceStack> UNSELECTED_PACKS = (p_248113_, p_248114_) -> {
PackRepository packrepository = p_248113_.getSource().getServer().getPackRepository();
Collection<String> collection = packrepository.getSelectedIds();
FeatureFlagSet featureflagset = p_248113_.getSource().enabledFeatures();
return SharedSuggestionProvider.suggest(packrepository.getAvailablePacks().stream().filter((p_248116_) -> {
return p_248116_.getRequestedFeatures().isSubsetOf(featureflagset);
}).map(Pack::getId).filter((p_250072_) -> {
return !collection.contains(p_250072_);
}).map(StringArgumentType::escapeIfRequired), p_248114_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("datapack").requires((p_136872_) -> {
return p_136872_.hasPermission(2);
}).then(Commands.literal("enable").then(Commands.argument("name", StringArgumentType.string()).suggests(UNSELECTED_PACKS).executes((p_136876_) -> {
return enablePack(p_136876_.getSource(), getPack(p_136876_, "name", true), (p_180059_, p_180060_) -> {
p_180060_.getDefaultPosition().insert(p_180059_, p_180060_, (p_180062_) -> {
return p_180062_;
}, false);
});
}).then(Commands.literal("after").then(Commands.argument("existing", StringArgumentType.string()).suggests(SELECTED_PACKS).executes((p_136880_) -> {
return enablePack(p_136880_.getSource(), getPack(p_136880_, "name", true), (p_180056_, p_180057_) -> {
p_180056_.add(p_180056_.indexOf(getPack(p_136880_, "existing", false)) + 1, p_180057_);
});
}))).then(Commands.literal("before").then(Commands.argument("existing", StringArgumentType.string()).suggests(SELECTED_PACKS).executes((p_136878_) -> {
return enablePack(p_136878_.getSource(), getPack(p_136878_, "name", true), (p_180046_, p_180047_) -> {
p_180046_.add(p_180046_.indexOf(getPack(p_136878_, "existing", false)), p_180047_);
});
}))).then(Commands.literal("last").executes((p_136874_) -> {
return enablePack(p_136874_.getSource(), getPack(p_136874_, "name", true), List::add);
})).then(Commands.literal("first").executes((p_136882_) -> {
return enablePack(p_136882_.getSource(), getPack(p_136882_, "name", true), (p_180052_, p_180053_) -> {
p_180052_.add(0, p_180053_);
});
})))).then(Commands.literal("disable").then(Commands.argument("name", StringArgumentType.string()).suggests(SELECTED_PACKS).executes((p_136870_) -> {
return disablePack(p_136870_.getSource(), getPack(p_136870_, "name", false));
}))).then(Commands.literal("list").executes((p_136864_) -> {
return listPacks(p_136864_.getSource());
}).then(Commands.literal("available").executes((p_136846_) -> {
return listAvailablePacks(p_136846_.getSource());
})).then(Commands.literal("enabled").executes((p_136811_) -> {
return listEnabledPacks(p_136811_.getSource());
}))));
}
/**
* Enables the given pack.
*
* @return The number of packs that are loaded after this operation.
*/
private static int enablePack(CommandSourceStack pSource, Pack pPack, DataPackCommand.Inserter pPriorityCallback) throws CommandSyntaxException {
PackRepository packrepository = pSource.getServer().getPackRepository();
List<Pack> list = Lists.newArrayList(packrepository.getSelectedPacks());
pPriorityCallback.apply(list, pPack);
pSource.sendSuccess(() -> {
return Component.translatable("commands.datapack.modify.enable", pPack.getChatLink(true));
}, true);
ReloadCommand.reloadPacks(list.stream().map(Pack::getId).collect(Collectors.toList()), pSource);
return list.size();
}
/**
* Disables the given pack.
*
* @return The number of packs that are loaded after this operation.
*/
private static int disablePack(CommandSourceStack pSource, Pack pPack) {
PackRepository packrepository = pSource.getServer().getPackRepository();
List<Pack> list = Lists.newArrayList(packrepository.getSelectedPacks());
list.remove(pPack);
pSource.sendSuccess(() -> {
return Component.translatable("commands.datapack.modify.disable", pPack.getChatLink(true));
}, true);
ReloadCommand.reloadPacks(list.stream().map(Pack::getId).collect(Collectors.toList()), pSource);
return list.size();
}
/**
* Sends a list of both enabled and available packs to the user.
*
* @return The total number of packs.
*/
private static int listPacks(CommandSourceStack pSource) {
return listEnabledPacks(pSource) + listAvailablePacks(pSource);
}
/**
* Sends a list of available packs to the user.
*
* @return The number of available packs.
*/
private static int listAvailablePacks(CommandSourceStack pSource) {
PackRepository packrepository = pSource.getServer().getPackRepository();
packrepository.reload();
Collection<Pack> collection = packrepository.getSelectedPacks();
Collection<Pack> collection1 = packrepository.getAvailablePacks();
FeatureFlagSet featureflagset = pSource.enabledFeatures();
List<Pack> list = collection1.stream().filter((p_248121_) -> {
return !collection.contains(p_248121_) && p_248121_.getRequestedFeatures().isSubsetOf(featureflagset);
}).toList();
if (list.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.datapack.list.available.none");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.datapack.list.available.success", list.size(), ComponentUtils.formatList(list, (p_136844_) -> {
return p_136844_.getChatLink(false);
}));
}, false);
}
return list.size();
}
/**
* Sends a list of enabled packs to the user.
*
* @return The number of enabled packs.
*/
private static int listEnabledPacks(CommandSourceStack pSource) {
PackRepository packrepository = pSource.getServer().getPackRepository();
packrepository.reload();
Collection<? extends Pack> collection = packrepository.getSelectedPacks();
if (collection.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.datapack.list.enabled.none");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.datapack.list.enabled.success", collection.size(), ComponentUtils.formatList(collection, (p_136807_) -> {
return p_136807_.getChatLink(true);
}));
}, false);
}
return collection.size();
}
private static Pack getPack(CommandContext<CommandSourceStack> pContext, String pName, boolean pEnabling) throws CommandSyntaxException {
String s = StringArgumentType.getString(pContext, pName);
PackRepository packrepository = pContext.getSource().getServer().getPackRepository();
Pack pack = packrepository.getPack(s);
if (pack == null) {
throw ERROR_UNKNOWN_PACK.create(s);
} else {
boolean flag = packrepository.getSelectedPacks().contains(pack);
if (pEnabling && flag) {
throw ERROR_PACK_ALREADY_ENABLED.create(s);
} else if (!pEnabling && !flag) {
throw ERROR_PACK_ALREADY_DISABLED.create(s);
} else {
FeatureFlagSet featureflagset = pContext.getSource().enabledFeatures();
FeatureFlagSet featureflagset1 = pack.getRequestedFeatures();
if (!featureflagset1.isSubsetOf(featureflagset)) {
throw ERROR_PACK_FEATURES_NOT_ENABLED.create(s, FeatureFlags.printMissingFlags(featureflagset, featureflagset1));
} else {
return pack;
}
}
}
}
interface Inserter {
void apply(List<Pack> p_136884_, Pack p_136885_) throws CommandSyntaxException;
}
}
@@ -0,0 +1,49 @@
package net.minecraft.server.commands;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.GameProfileArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.players.PlayerList;
public class DeOpCommands {
private static final SimpleCommandExceptionType ERROR_NOT_OP = new SimpleCommandExceptionType(Component.translatable("commands.deop.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("deop").requires((p_136896_) -> {
return p_136896_.hasPermission(3);
}).then(Commands.argument("targets", GameProfileArgument.gameProfile()).suggests((p_136893_, p_136894_) -> {
return SharedSuggestionProvider.suggest(p_136893_.getSource().getServer().getPlayerList().getOpNames(), p_136894_);
}).executes((p_136891_) -> {
return deopPlayers(p_136891_.getSource(), GameProfileArgument.getGameProfiles(p_136891_, "targets"));
})));
}
private static int deopPlayers(CommandSourceStack pSource, Collection<GameProfile> pPlayers) throws CommandSyntaxException {
PlayerList playerlist = pSource.getServer().getPlayerList();
int i = 0;
for(GameProfile gameprofile : pPlayers) {
if (playerlist.isOp(gameprofile)) {
playerlist.deop(gameprofile);
++i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.deop.success", pPlayers.iterator().next().getName());
}, true);
}
}
if (i == 0) {
throw ERROR_NOT_OP.create();
} else {
pSource.getServer().kickUnlistedPlayers(pSource);
return i;
}
}
}
@@ -0,0 +1,206 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Locale;
import net.minecraft.Util;
import net.minecraft.commands.CommandFunction;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.item.FunctionArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ServerFunctionManager;
import net.minecraft.util.TimeUtil;
import net.minecraft.util.profiling.ProfileResults;
import org.slf4j.Logger;
public class DebugCommand {
private static final Logger LOGGER = LogUtils.getLogger();
private static final SimpleCommandExceptionType ERROR_NOT_RUNNING = new SimpleCommandExceptionType(Component.translatable("commands.debug.notRunning"));
private static final SimpleCommandExceptionType ERROR_ALREADY_RUNNING = new SimpleCommandExceptionType(Component.translatable("commands.debug.alreadyRunning"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("debug").requires((p_180073_) -> {
return p_180073_.hasPermission(3);
}).then(Commands.literal("start").executes((p_180069_) -> {
return start(p_180069_.getSource());
})).then(Commands.literal("stop").executes((p_136918_) -> {
return stop(p_136918_.getSource());
})).then(Commands.literal("function").requires((p_180071_) -> {
return p_180071_.hasPermission(3);
}).then(Commands.argument("name", FunctionArgument.functions()).suggests(FunctionCommand.SUGGEST_FUNCTION).executes((p_136908_) -> {
return traceFunction(p_136908_.getSource(), FunctionArgument.getFunctions(p_136908_, "name"));
}))));
}
private static int start(CommandSourceStack pSource) throws CommandSyntaxException {
MinecraftServer minecraftserver = pSource.getServer();
if (minecraftserver.isTimeProfilerRunning()) {
throw ERROR_ALREADY_RUNNING.create();
} else {
minecraftserver.startTimeProfiler();
pSource.sendSuccess(() -> {
return Component.translatable("commands.debug.started");
}, true);
return 0;
}
}
private static int stop(CommandSourceStack pSource) throws CommandSyntaxException {
MinecraftServer minecraftserver = pSource.getServer();
if (!minecraftserver.isTimeProfilerRunning()) {
throw ERROR_NOT_RUNNING.create();
} else {
ProfileResults profileresults = minecraftserver.stopTimeProfiler();
double d0 = (double)profileresults.getNanoDuration() / (double)TimeUtil.NANOSECONDS_PER_SECOND;
double d1 = (double)profileresults.getTickDuration() / d0;
pSource.sendSuccess(() -> {
return Component.translatable("commands.debug.stopped", String.format(Locale.ROOT, "%.2f", d0), profileresults.getTickDuration(), String.format(Locale.ROOT, "%.2f", d1));
}, true);
return (int)d1;
}
}
private static int traceFunction(CommandSourceStack pSource, Collection<CommandFunction> pFunctions) {
int i = 0;
MinecraftServer minecraftserver = pSource.getServer();
String s = "debug-trace-" + Util.getFilenameFormattedDateTime() + ".txt";
try {
Path path = minecraftserver.getFile("debug").toPath();
Files.createDirectories(path);
try (Writer writer = Files.newBufferedWriter(path.resolve(s), StandardCharsets.UTF_8)) {
PrintWriter printwriter = new PrintWriter(writer);
for(CommandFunction commandfunction : pFunctions) {
printwriter.println((Object)commandfunction.getId());
DebugCommand.Tracer debugcommand$tracer = new DebugCommand.Tracer(printwriter);
i += pSource.getServer().getFunctions().execute(commandfunction, pSource.withSource(debugcommand$tracer).withMaximumPermission(2), debugcommand$tracer);
}
}
} catch (IOException | UncheckedIOException uncheckedioexception) {
LOGGER.warn("Tracing failed", (Throwable)uncheckedioexception);
pSource.sendFailure(Component.translatable("commands.debug.function.traceFailed"));
}
int j = i;
if (pFunctions.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.debug.function.success.single", j, pFunctions.iterator().next().getId(), s);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.debug.function.success.multiple", j, pFunctions.size(), s);
}, true);
}
return i;
}
static class Tracer implements ServerFunctionManager.TraceCallbacks, CommandSource {
public static final int INDENT_OFFSET = 1;
private final PrintWriter output;
private int lastIndent;
private boolean waitingForResult;
Tracer(PrintWriter pOutput) {
this.output = pOutput;
}
private void indentAndSave(int pIndent) {
this.printIndent(pIndent);
this.lastIndent = pIndent;
}
private void printIndent(int pIndent) {
for(int i = 0; i < pIndent + 1; ++i) {
this.output.write(" ");
}
}
private void newLine() {
if (this.waitingForResult) {
this.output.println();
this.waitingForResult = false;
}
}
public void onCommand(int pIndent, String pCommand) {
this.newLine();
this.indentAndSave(pIndent);
this.output.print("[C] ");
this.output.print(pCommand);
this.waitingForResult = true;
}
public void onReturn(int pIndent, String pReturnValue, int pCommand) {
if (this.waitingForResult) {
this.output.print(" -> ");
this.output.println(pCommand);
this.waitingForResult = false;
} else {
this.indentAndSave(pIndent);
this.output.print("[R = ");
this.output.print(pCommand);
this.output.print("] ");
this.output.println(pReturnValue);
}
}
public void onCall(int pIndent, ResourceLocation pCommand, int pSize) {
this.newLine();
this.indentAndSave(pIndent);
this.output.print("[F] ");
this.output.print((Object)pCommand);
this.output.print(" size=");
this.output.println(pSize);
}
public void onError(int pIndent, String pCommand) {
this.newLine();
this.indentAndSave(pIndent + 1);
this.output.print("[E] ");
this.output.print(pCommand);
}
public void sendSystemMessage(Component pComponent) {
this.newLine();
this.printIndent(this.lastIndent + 1);
this.output.print("[M] ");
this.output.println(pComponent.getString());
}
public boolean acceptsSuccess() {
return true;
}
public boolean acceptsFailure() {
return true;
}
public boolean shouldInformAdmins() {
return false;
}
public boolean alwaysAccepts() {
return true;
}
}
}
@@ -0,0 +1,31 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.NaturalSpawner;
public class DebugMobSpawningCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = Commands.literal("debugmobspawning").requires((p_180113_) -> {
return p_180113_.hasPermission(2);
});
for(MobCategory mobcategory : MobCategory.values()) {
literalargumentbuilder.then(Commands.literal(mobcategory.getName()).then(Commands.argument("at", BlockPosArgument.blockPos()).executes((p_180109_) -> {
return spawnMobs(p_180109_.getSource(), mobcategory, BlockPosArgument.getLoadedBlockPos(p_180109_, "at"));
})));
}
pDispatcher.register(literalargumentbuilder);
}
private static int spawnMobs(CommandSourceStack pSource, MobCategory pMobCategory, BlockPos pPos) {
NaturalSpawner.spawnCategoryForPosition(pMobCategory, pSource.getLevel(), pPos);
return 1;
}
}
@@ -0,0 +1,51 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.DebugPackets;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.navigation.GroundPathNavigation;
import net.minecraft.world.entity.ai.navigation.PathNavigation;
import net.minecraft.world.level.pathfinder.Path;
public class DebugPathCommand {
private static final SimpleCommandExceptionType ERROR_NOT_MOB = new SimpleCommandExceptionType(Component.literal("Source is not a mob"));
private static final SimpleCommandExceptionType ERROR_NO_PATH = new SimpleCommandExceptionType(Component.literal("Path not found"));
private static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.literal("Target not reached"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("debugpath").requires((p_180128_) -> {
return p_180128_.hasPermission(2);
}).then(Commands.argument("to", BlockPosArgument.blockPos()).executes((p_180126_) -> {
return fillBlocks(p_180126_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180126_, "to"));
})));
}
private static int fillBlocks(CommandSourceStack pStack, BlockPos pPos) throws CommandSyntaxException {
Entity entity = pStack.getEntity();
if (!(entity instanceof Mob mob)) {
throw ERROR_NOT_MOB.create();
} else {
PathNavigation pathnavigation = new GroundPathNavigation(mob, pStack.getLevel());
Path path = pathnavigation.createPath(pPos, 0);
DebugPackets.sendPathFindingPacket(pStack.getLevel(), mob, path, pathnavigation.getMaxDistanceToWaypoint());
if (path == null) {
throw ERROR_NO_PATH.create();
} else if (!path.canReach()) {
throw ERROR_NOT_COMPLETE.create();
} else {
pStack.sendSuccess(() -> {
return Component.literal("Made path");
}, true);
return 1;
}
}
}
}
@@ -0,0 +1,42 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.GameModeArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.GameType;
public class DefaultGameModeCommands {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("defaultgamemode").requires((p_136929_) -> {
return p_136929_.hasPermission(2);
}).then(Commands.argument("gamemode", GameModeArgument.gameMode()).executes((p_258227_) -> {
return setMode(p_258227_.getSource(), GameModeArgument.getGameMode(p_258227_, "gamemode"));
})));
}
/**
* Sets the {@link net.minecraft.world.level.GameType} of the player who ran the command.
*/
private static int setMode(CommandSourceStack pCommandSource, GameType pGamemode) {
int i = 0;
MinecraftServer minecraftserver = pCommandSource.getServer();
minecraftserver.setDefaultGameType(pGamemode);
GameType gametype = minecraftserver.getForcedGameType();
if (gametype != null) {
for(ServerPlayer serverplayer : minecraftserver.getPlayerList().getPlayers()) {
if (serverplayer.setGameMode(gametype)) {
++i;
}
}
}
pCommandSource.sendSuccess(() -> {
return Component.translatable("commands.defaultgamemode.success", pGamemode.getLongDisplayName());
}, true);
return i;
}
}
@@ -0,0 +1,50 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.Difficulty;
public class DifficultyCommand {
private static final DynamicCommandExceptionType ERROR_ALREADY_DIFFICULT = new DynamicCommandExceptionType((p_136948_) -> {
return Component.translatable("commands.difficulty.failure", p_136948_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = Commands.literal("difficulty");
for(Difficulty difficulty : Difficulty.values()) {
literalargumentbuilder.then(Commands.literal(difficulty.getKey()).executes((p_136937_) -> {
return setDifficulty(p_136937_.getSource(), difficulty);
}));
}
pDispatcher.register(literalargumentbuilder.requires((p_136943_) -> {
return p_136943_.hasPermission(2);
}).executes((p_288367_) -> {
Difficulty difficulty1 = p_288367_.getSource().getLevel().getDifficulty();
p_288367_.getSource().sendSuccess(() -> {
return Component.translatable("commands.difficulty.query", difficulty1.getDisplayName());
}, false);
return difficulty1.getId();
}));
}
public static int setDifficulty(CommandSourceStack pSource, Difficulty pDifficulty) throws CommandSyntaxException {
MinecraftServer minecraftserver = pSource.getServer();
if (minecraftserver.getWorldData().getDifficulty() == pDifficulty) {
throw ERROR_ALREADY_DIFFICULT.create(pDifficulty.getKey());
} else {
minecraftserver.setDifficulty(pDifficulty, true);
pSource.sendSuccess(() -> {
return Component.translatable("commands.difficulty.success", pDifficulty.getDisplayName());
}, true);
return 0;
}
}
}
@@ -0,0 +1,151 @@
package net.minecraft.server.commands;
import com.google.common.collect.ImmutableList;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
public class EffectCommands {
private static final SimpleCommandExceptionType ERROR_GIVE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.effect.give.failed"));
private static final SimpleCommandExceptionType ERROR_CLEAR_EVERYTHING_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.effect.clear.everything.failed"));
private static final SimpleCommandExceptionType ERROR_CLEAR_SPECIFIC_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.effect.clear.specific.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("effect").requires((p_136958_) -> {
return p_136958_.hasPermission(2);
}).then(Commands.literal("clear").executes((p_136984_) -> {
return clearEffects(p_136984_.getSource(), ImmutableList.of(p_136984_.getSource().getEntityOrException()));
}).then(Commands.argument("targets", EntityArgument.entities()).executes((p_136982_) -> {
return clearEffects(p_136982_.getSource(), EntityArgument.getEntities(p_136982_, "targets"));
}).then(Commands.argument("effect", ResourceArgument.resource(pContext, Registries.MOB_EFFECT)).executes((p_248126_) -> {
return clearEffect(p_248126_.getSource(), EntityArgument.getEntities(p_248126_, "targets"), ResourceArgument.getMobEffect(p_248126_, "effect"));
})))).then(Commands.literal("give").then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("effect", ResourceArgument.resource(pContext, Registries.MOB_EFFECT)).executes((p_248127_) -> {
return giveEffect(p_248127_.getSource(), EntityArgument.getEntities(p_248127_, "targets"), ResourceArgument.getMobEffect(p_248127_, "effect"), (Integer)null, 0, true);
}).then(Commands.argument("seconds", IntegerArgumentType.integer(1, 1000000)).executes((p_248124_) -> {
return giveEffect(p_248124_.getSource(), EntityArgument.getEntities(p_248124_, "targets"), ResourceArgument.getMobEffect(p_248124_, "effect"), IntegerArgumentType.getInteger(p_248124_, "seconds"), 0, true);
}).then(Commands.argument("amplifier", IntegerArgumentType.integer(0, 255)).executes((p_248123_) -> {
return giveEffect(p_248123_.getSource(), EntityArgument.getEntities(p_248123_, "targets"), ResourceArgument.getMobEffect(p_248123_, "effect"), IntegerArgumentType.getInteger(p_248123_, "seconds"), IntegerArgumentType.getInteger(p_248123_, "amplifier"), true);
}).then(Commands.argument("hideParticles", BoolArgumentType.bool()).executes((p_248125_) -> {
return giveEffect(p_248125_.getSource(), EntityArgument.getEntities(p_248125_, "targets"), ResourceArgument.getMobEffect(p_248125_, "effect"), IntegerArgumentType.getInteger(p_248125_, "seconds"), IntegerArgumentType.getInteger(p_248125_, "amplifier"), !BoolArgumentType.getBool(p_248125_, "hideParticles"));
})))).then(Commands.literal("infinite").executes((p_267907_) -> {
return giveEffect(p_267907_.getSource(), EntityArgument.getEntities(p_267907_, "targets"), ResourceArgument.getMobEffect(p_267907_, "effect"), -1, 0, true);
}).then(Commands.argument("amplifier", IntegerArgumentType.integer(0, 255)).executes((p_267908_) -> {
return giveEffect(p_267908_.getSource(), EntityArgument.getEntities(p_267908_, "targets"), ResourceArgument.getMobEffect(p_267908_, "effect"), -1, IntegerArgumentType.getInteger(p_267908_, "amplifier"), true);
}).then(Commands.argument("hideParticles", BoolArgumentType.bool()).executes((p_267909_) -> {
return giveEffect(p_267909_.getSource(), EntityArgument.getEntities(p_267909_, "targets"), ResourceArgument.getMobEffect(p_267909_, "effect"), -1, IntegerArgumentType.getInteger(p_267909_, "amplifier"), !BoolArgumentType.getBool(p_267909_, "hideParticles"));
}))))))));
}
private static int giveEffect(CommandSourceStack pSource, Collection<? extends Entity> pTargets, Holder<MobEffect> pEffect, @Nullable Integer pSeconds, int pAmplifier, boolean pShowParticles) throws CommandSyntaxException {
MobEffect mobeffect = pEffect.value();
int i = 0;
int j;
if (pSeconds != null) {
if (mobeffect.isInstantenous()) {
j = pSeconds;
} else if (pSeconds == -1) {
j = -1;
} else {
j = pSeconds * 20;
}
} else if (mobeffect.isInstantenous()) {
j = 1;
} else {
j = 600;
}
for(Entity entity : pTargets) {
if (entity instanceof LivingEntity) {
MobEffectInstance mobeffectinstance = new MobEffectInstance(mobeffect, j, pAmplifier, false, pShowParticles);
if (((LivingEntity)entity).addEffect(mobeffectinstance, pSource.getEntity())) {
++i;
}
}
}
if (i == 0) {
throw ERROR_GIVE_FAILED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.effect.give.success.single", mobeffect.getDisplayName(), pTargets.iterator().next().getDisplayName(), j / 20);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.effect.give.success.multiple", mobeffect.getDisplayName(), pTargets.size(), j / 20);
}, true);
}
return i;
}
}
private static int clearEffects(CommandSourceStack pSource, Collection<? extends Entity> pTargets) throws CommandSyntaxException {
int i = 0;
for(Entity entity : pTargets) {
if (entity instanceof LivingEntity && ((LivingEntity)entity).removeAllEffects()) {
++i;
}
}
if (i == 0) {
throw ERROR_CLEAR_EVERYTHING_FAILED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.everything.success.single", pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.everything.success.multiple", pTargets.size());
}, true);
}
return i;
}
}
private static int clearEffect(CommandSourceStack pSource, Collection<? extends Entity> pTargets, Holder<MobEffect> pEffect) throws CommandSyntaxException {
MobEffect mobeffect = pEffect.value();
int i = 0;
for(Entity entity : pTargets) {
if (entity instanceof LivingEntity && ((LivingEntity)entity).removeEffect(mobeffect)) {
++i;
}
}
if (i == 0) {
throw ERROR_CLEAR_SPECIFIC_FAILED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.specific.success.single", mobeffect.getDisplayName(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.specific.success.multiple", mobeffect.getDisplayName(), pTargets.size());
}, true);
}
return i;
}
}
}
@@ -0,0 +1,21 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.network.chat.ChatType;
import net.minecraft.server.players.PlayerList;
public class EmoteCommands {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("me").then(Commands.argument("action", MessageArgument.message()).executes((p_248130_) -> {
MessageArgument.resolveChatMessage(p_248130_, "action", (p_248129_) -> {
CommandSourceStack commandsourcestack = p_248130_.getSource();
PlayerList playerlist = commandsourcestack.getServer().getPlayerList();
playerlist.broadcastChatMessage(p_248129_, commandsourcestack, ChatType.bind(ChatType.EMOTE_COMMAND, commandsourcestack));
});
return 1;
})));
}
}
@@ -0,0 +1,92 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
public class EnchantCommand {
private static final DynamicCommandExceptionType ERROR_NOT_LIVING_ENTITY = new DynamicCommandExceptionType((p_137029_) -> {
return Component.translatable("commands.enchant.failed.entity", p_137029_);
});
private static final DynamicCommandExceptionType ERROR_NO_ITEM = new DynamicCommandExceptionType((p_137027_) -> {
return Component.translatable("commands.enchant.failed.itemless", p_137027_);
});
private static final DynamicCommandExceptionType ERROR_INCOMPATIBLE = new DynamicCommandExceptionType((p_137020_) -> {
return Component.translatable("commands.enchant.failed.incompatible", p_137020_);
});
private static final Dynamic2CommandExceptionType ERROR_LEVEL_TOO_HIGH = new Dynamic2CommandExceptionType((p_137022_, p_137023_) -> {
return Component.translatable("commands.enchant.failed.level", p_137022_, p_137023_);
});
private static final SimpleCommandExceptionType ERROR_NOTHING_HAPPENED = new SimpleCommandExceptionType(Component.translatable("commands.enchant.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("enchant").requires((p_137013_) -> {
return p_137013_.hasPermission(2);
}).then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("enchantment", ResourceArgument.resource(pContext, Registries.ENCHANTMENT)).executes((p_248131_) -> {
return enchant(p_248131_.getSource(), EntityArgument.getEntities(p_248131_, "targets"), ResourceArgument.getEnchantment(p_248131_, "enchantment"), 1);
}).then(Commands.argument("level", IntegerArgumentType.integer(0)).executes((p_248132_) -> {
return enchant(p_248132_.getSource(), EntityArgument.getEntities(p_248132_, "targets"), ResourceArgument.getEnchantment(p_248132_, "enchantment"), IntegerArgumentType.getInteger(p_248132_, "level"));
})))));
}
private static int enchant(CommandSourceStack pSource, Collection<? extends Entity> pTargets, Holder<Enchantment> pEnchantment, int pLevel) throws CommandSyntaxException {
Enchantment enchantment = pEnchantment.value();
if (pLevel > enchantment.getMaxLevel()) {
throw ERROR_LEVEL_TOO_HIGH.create(pLevel, enchantment.getMaxLevel());
} else {
int i = 0;
for(Entity entity : pTargets) {
if (entity instanceof LivingEntity) {
LivingEntity livingentity = (LivingEntity)entity;
ItemStack itemstack = livingentity.getMainHandItem();
if (!itemstack.isEmpty()) {
if (enchantment.canEnchant(itemstack) && EnchantmentHelper.isEnchantmentCompatible(EnchantmentHelper.getEnchantments(itemstack).keySet(), enchantment)) {
itemstack.enchant(enchantment, pLevel);
++i;
} else if (pTargets.size() == 1) {
throw ERROR_INCOMPATIBLE.create(itemstack.getItem().getName(itemstack).getString());
}
} else if (pTargets.size() == 1) {
throw ERROR_NO_ITEM.create(livingentity.getName().getString());
}
} else if (pTargets.size() == 1) {
throw ERROR_NOT_LIVING_ENTITY.create(entity.getName().getString());
}
}
if (i == 0) {
throw ERROR_NOTHING_HAPPENED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.enchant.success.single", enchantment.getFullname(pLevel), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.enchant.success.multiple", enchantment.getFullname(pLevel), pTargets.size());
}, true);
}
return i;
}
}
}
}
@@ -0,0 +1,590 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.ResultConsumer;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Stream;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.DimensionArgument;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.HeightmapTypeArgument;
import net.minecraft.commands.arguments.NbtPathArgument;
import net.minecraft.commands.arguments.ObjectiveArgument;
import net.minecraft.commands.arguments.RangeArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.ResourceOrTagArgument;
import net.minecraft.commands.arguments.ScoreHolderArgument;
import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.commands.arguments.coordinates.RotationArgument;
import net.minecraft.commands.arguments.coordinates.SwizzleArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.SectionPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.ByteTag;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.DoubleTag;
import net.minecraft.nbt.FloatTag;
import net.minecraft.nbt.IntTag;
import net.minecraft.nbt.LongTag;
import net.minecraft.nbt.ShortTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.bossevents.CustomBossEvent;
import net.minecraft.server.commands.data.DataAccessor;
import net.minecraft.server.commands.data.DataCommands;
import net.minecraft.server.level.FullChunkStatus;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Attackable;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.OwnableEntity;
import net.minecraft.world.entity.Targeting;
import net.minecraft.world.entity.TraceableEntity;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.storage.loot.LootDataType;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.Score;
import net.minecraft.world.scores.Scoreboard;
public class ExecuteCommand {
private static final int MAX_TEST_AREA = 32768;
private static final Dynamic2CommandExceptionType ERROR_AREA_TOO_LARGE = new Dynamic2CommandExceptionType((p_137129_, p_137130_) -> {
return Component.translatable("commands.execute.blocks.toobig", p_137129_, p_137130_);
});
private static final SimpleCommandExceptionType ERROR_CONDITIONAL_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.execute.conditional.fail"));
private static final DynamicCommandExceptionType ERROR_CONDITIONAL_FAILED_COUNT = new DynamicCommandExceptionType((p_137127_) -> {
return Component.translatable("commands.execute.conditional.fail_count", p_137127_);
});
private static final BinaryOperator<ResultConsumer<CommandSourceStack>> CALLBACK_CHAINER = (p_137045_, p_137046_) -> {
return (p_180160_, p_180161_, p_180162_) -> {
p_137045_.onCommandComplete(p_180160_, p_180161_, p_180162_);
p_137046_.onCommandComplete(p_180160_, p_180161_, p_180162_);
};
};
private static final SuggestionProvider<CommandSourceStack> SUGGEST_PREDICATE = (p_278905_, p_278906_) -> {
LootDataManager lootdatamanager = p_278905_.getSource().getServer().getLootData();
return SharedSuggestionProvider.suggestResource(lootdatamanager.getKeys(LootDataType.PREDICATE), p_278906_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
LiteralCommandNode<CommandSourceStack> literalcommandnode = pDispatcher.register(Commands.literal("execute").requires((p_137197_) -> {
return p_137197_.hasPermission(2);
}));
pDispatcher.register(Commands.literal("execute").requires((p_137103_) -> {
return p_137103_.hasPermission(2);
}).then(Commands.literal("run").redirect(pDispatcher.getRoot())).then(addConditionals(literalcommandnode, Commands.literal("if"), true, pContext)).then(addConditionals(literalcommandnode, Commands.literal("unless"), false, pContext)).then(Commands.literal("as").then(Commands.argument("targets", EntityArgument.entities()).fork(literalcommandnode, (p_137299_) -> {
List<CommandSourceStack> list = Lists.newArrayList();
for(Entity entity : EntityArgument.getOptionalEntities(p_137299_, "targets")) {
list.add(p_137299_.getSource().withEntity(entity));
}
return list;
}))).then(Commands.literal("at").then(Commands.argument("targets", EntityArgument.entities()).fork(literalcommandnode, (p_284653_) -> {
List<CommandSourceStack> list = Lists.newArrayList();
for(Entity entity : EntityArgument.getOptionalEntities(p_284653_, "targets")) {
list.add(p_284653_.getSource().withLevel((ServerLevel)entity.level()).withPosition(entity.position()).withRotation(entity.getRotationVector()));
}
return list;
}))).then(Commands.literal("store").then(wrapStores(literalcommandnode, Commands.literal("result"), true)).then(wrapStores(literalcommandnode, Commands.literal("success"), false))).then(Commands.literal("positioned").then(Commands.argument("pos", Vec3Argument.vec3()).redirect(literalcommandnode, (p_137295_) -> {
return p_137295_.getSource().withPosition(Vec3Argument.getVec3(p_137295_, "pos")).withAnchor(EntityAnchorArgument.Anchor.FEET);
})).then(Commands.literal("as").then(Commands.argument("targets", EntityArgument.entities()).fork(literalcommandnode, (p_137293_) -> {
List<CommandSourceStack> list = Lists.newArrayList();
for(Entity entity : EntityArgument.getOptionalEntities(p_137293_, "targets")) {
list.add(p_137293_.getSource().withPosition(entity.position()));
}
return list;
}))).then(Commands.literal("over").then(Commands.argument("heightmap", HeightmapTypeArgument.heightmap()).redirect(literalcommandnode, (p_274814_) -> {
Vec3 vec3 = p_274814_.getSource().getPosition();
ServerLevel serverlevel = p_274814_.getSource().getLevel();
double d0 = vec3.x();
double d1 = vec3.z();
if (!serverlevel.hasChunk(SectionPos.blockToSectionCoord(d0), SectionPos.blockToSectionCoord(d1))) {
throw BlockPosArgument.ERROR_NOT_LOADED.create();
} else {
int i = serverlevel.getHeight(HeightmapTypeArgument.getHeightmap(p_274814_, "heightmap"), Mth.floor(d0), Mth.floor(d1));
return p_274814_.getSource().withPosition(new Vec3(d0, (double)i, d1));
}
})))).then(Commands.literal("rotated").then(Commands.argument("rot", RotationArgument.rotation()).redirect(literalcommandnode, (p_137291_) -> {
return p_137291_.getSource().withRotation(RotationArgument.getRotation(p_137291_, "rot").getRotation(p_137291_.getSource()));
})).then(Commands.literal("as").then(Commands.argument("targets", EntityArgument.entities()).fork(literalcommandnode, (p_137289_) -> {
List<CommandSourceStack> list = Lists.newArrayList();
for(Entity entity : EntityArgument.getOptionalEntities(p_137289_, "targets")) {
list.add(p_137289_.getSource().withRotation(entity.getRotationVector()));
}
return list;
})))).then(Commands.literal("facing").then(Commands.literal("entity").then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("anchor", EntityAnchorArgument.anchor()).fork(literalcommandnode, (p_137287_) -> {
List<CommandSourceStack> list = Lists.newArrayList();
EntityAnchorArgument.Anchor entityanchorargument$anchor = EntityAnchorArgument.getAnchor(p_137287_, "anchor");
for(Entity entity : EntityArgument.getOptionalEntities(p_137287_, "targets")) {
list.add(p_137287_.getSource().facing(entity, entityanchorargument$anchor));
}
return list;
})))).then(Commands.argument("pos", Vec3Argument.vec3()).redirect(literalcommandnode, (p_137285_) -> {
return p_137285_.getSource().facing(Vec3Argument.getVec3(p_137285_, "pos"));
}))).then(Commands.literal("align").then(Commands.argument("axes", SwizzleArgument.swizzle()).redirect(literalcommandnode, (p_137283_) -> {
return p_137283_.getSource().withPosition(p_137283_.getSource().getPosition().align(SwizzleArgument.getSwizzle(p_137283_, "axes")));
}))).then(Commands.literal("anchored").then(Commands.argument("anchor", EntityAnchorArgument.anchor()).redirect(literalcommandnode, (p_137281_) -> {
return p_137281_.getSource().withAnchor(EntityAnchorArgument.getAnchor(p_137281_, "anchor"));
}))).then(Commands.literal("in").then(Commands.argument("dimension", DimensionArgument.dimension()).redirect(literalcommandnode, (p_137279_) -> {
return p_137279_.getSource().withLevel(DimensionArgument.getDimension(p_137279_, "dimension"));
}))).then(Commands.literal("summon").then(Commands.argument("entity", ResourceArgument.resource(pContext, Registries.ENTITY_TYPE)).suggests(SuggestionProviders.SUMMONABLE_ENTITIES).redirect(literalcommandnode, (p_269759_) -> {
return spawnEntityAndRedirect(p_269759_.getSource(), ResourceArgument.getSummonableEntityType(p_269759_, "entity"));
}))).then(createRelationOperations(literalcommandnode, Commands.literal("on"))));
}
private static ArgumentBuilder<CommandSourceStack, ?> wrapStores(LiteralCommandNode<CommandSourceStack> pParent, LiteralArgumentBuilder<CommandSourceStack> pLiteral, boolean pStoringResult) {
pLiteral.then(Commands.literal("score").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).redirect(pParent, (p_137271_) -> {
return storeValue(p_137271_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_137271_, "targets"), ObjectiveArgument.getObjective(p_137271_, "objective"), pStoringResult);
}))));
pLiteral.then(Commands.literal("bossbar").then(Commands.argument("id", ResourceLocationArgument.id()).suggests(BossBarCommands.SUGGEST_BOSS_BAR).then(Commands.literal("value").redirect(pParent, (p_137259_) -> {
return storeValue(p_137259_.getSource(), BossBarCommands.getBossBar(p_137259_), true, pStoringResult);
})).then(Commands.literal("max").redirect(pParent, (p_137247_) -> {
return storeValue(p_137247_.getSource(), BossBarCommands.getBossBar(p_137247_), false, pStoringResult);
}))));
for(DataCommands.DataProvider datacommands$dataprovider : DataCommands.TARGET_PROVIDERS) {
datacommands$dataprovider.wrap(pLiteral, (p_137101_) -> {
return p_137101_.then(Commands.argument("path", NbtPathArgument.nbtPath()).then(Commands.literal("int").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(pParent, (p_180216_) -> {
return storeData(p_180216_.getSource(), datacommands$dataprovider.access(p_180216_), NbtPathArgument.getPath(p_180216_, "path"), (p_180219_) -> {
return IntTag.valueOf((int)((double)p_180219_ * DoubleArgumentType.getDouble(p_180216_, "scale")));
}, pStoringResult);
}))).then(Commands.literal("float").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(pParent, (p_180209_) -> {
return storeData(p_180209_.getSource(), datacommands$dataprovider.access(p_180209_), NbtPathArgument.getPath(p_180209_, "path"), (p_180212_) -> {
return FloatTag.valueOf((float)((double)p_180212_ * DoubleArgumentType.getDouble(p_180209_, "scale")));
}, pStoringResult);
}))).then(Commands.literal("short").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(pParent, (p_180199_) -> {
return storeData(p_180199_.getSource(), datacommands$dataprovider.access(p_180199_), NbtPathArgument.getPath(p_180199_, "path"), (p_180202_) -> {
return ShortTag.valueOf((short)((int)((double)p_180202_ * DoubleArgumentType.getDouble(p_180199_, "scale"))));
}, pStoringResult);
}))).then(Commands.literal("long").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(pParent, (p_180189_) -> {
return storeData(p_180189_.getSource(), datacommands$dataprovider.access(p_180189_), NbtPathArgument.getPath(p_180189_, "path"), (p_180192_) -> {
return LongTag.valueOf((long)((double)p_180192_ * DoubleArgumentType.getDouble(p_180189_, "scale")));
}, pStoringResult);
}))).then(Commands.literal("double").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(pParent, (p_180179_) -> {
return storeData(p_180179_.getSource(), datacommands$dataprovider.access(p_180179_), NbtPathArgument.getPath(p_180179_, "path"), (p_180182_) -> {
return DoubleTag.valueOf((double)p_180182_ * DoubleArgumentType.getDouble(p_180179_, "scale"));
}, pStoringResult);
}))).then(Commands.literal("byte").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(pParent, (p_180156_) -> {
return storeData(p_180156_.getSource(), datacommands$dataprovider.access(p_180156_), NbtPathArgument.getPath(p_180156_, "path"), (p_180165_) -> {
return ByteTag.valueOf((byte)((int)((double)p_180165_ * DoubleArgumentType.getDouble(p_180156_, "scale"))));
}, pStoringResult);
}))));
});
}
return pLiteral;
}
private static CommandSourceStack storeValue(CommandSourceStack pSource, Collection<String> pTargets, Objective pObjective, boolean pStoringResult) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
return pSource.withCallback((p_137136_, p_137137_, p_137138_) -> {
for(String s : pTargets) {
Score score = scoreboard.getOrCreatePlayerScore(s, pObjective);
int i = pStoringResult ? p_137138_ : (p_137137_ ? 1 : 0);
score.setScore(i);
}
}, CALLBACK_CHAINER);
}
private static CommandSourceStack storeValue(CommandSourceStack pSource, CustomBossEvent pBar, boolean pStoringValue, boolean pStoringResult) {
return pSource.withCallback((p_137185_, p_137186_, p_137187_) -> {
int i = pStoringResult ? p_137187_ : (p_137186_ ? 1 : 0);
if (pStoringValue) {
pBar.setValue(i);
} else {
pBar.setMax(i);
}
}, CALLBACK_CHAINER);
}
private static CommandSourceStack storeData(CommandSourceStack pSource, DataAccessor pAccessor, NbtPathArgument.NbtPath pPath, IntFunction<Tag> pTagConverter, boolean pStoringResult) {
return pSource.withCallback((p_137153_, p_137154_, p_137155_) -> {
try {
CompoundTag compoundtag = pAccessor.getData();
int i = pStoringResult ? p_137155_ : (p_137154_ ? 1 : 0);
pPath.set(compoundtag, pTagConverter.apply(i));
pAccessor.setData(compoundtag);
} catch (CommandSyntaxException commandsyntaxexception) {
}
}, CALLBACK_CHAINER);
}
private static boolean isChunkLoaded(ServerLevel pLevel, BlockPos pPos) {
ChunkPos chunkpos = new ChunkPos(pPos);
LevelChunk levelchunk = pLevel.getChunkSource().getChunkNow(chunkpos.x, chunkpos.z);
if (levelchunk == null) {
return false;
} else {
return levelchunk.getFullStatus() == FullChunkStatus.ENTITY_TICKING && pLevel.areEntitiesLoaded(chunkpos.toLong());
}
}
private static ArgumentBuilder<CommandSourceStack, ?> addConditionals(CommandNode<CommandSourceStack> pParent, LiteralArgumentBuilder<CommandSourceStack> pLiteral, boolean pIsIf, CommandBuildContext pContext) {
pLiteral.then(Commands.literal("block").then(Commands.argument("pos", BlockPosArgument.blockPos()).then(addConditional(pParent, Commands.argument("block", BlockPredicateArgument.blockPredicate(pContext)), pIsIf, (p_137277_) -> {
return BlockPredicateArgument.getBlockPredicate(p_137277_, "block").test(new BlockInWorld(p_137277_.getSource().getLevel(), BlockPosArgument.getLoadedBlockPos(p_137277_, "pos"), true));
})))).then(Commands.literal("biome").then(Commands.argument("pos", BlockPosArgument.blockPos()).then(addConditional(pParent, Commands.argument("biome", ResourceOrTagArgument.resourceOrTag(pContext, Registries.BIOME)), pIsIf, (p_277265_) -> {
return ResourceOrTagArgument.getResourceOrTag(p_277265_, "biome", Registries.BIOME).test(p_277265_.getSource().getLevel().getBiome(BlockPosArgument.getLoadedBlockPos(p_277265_, "pos")));
})))).then(Commands.literal("loaded").then(addConditional(pParent, Commands.argument("pos", BlockPosArgument.blockPos()), pIsIf, (p_269757_) -> {
return isChunkLoaded(p_269757_.getSource().getLevel(), BlockPosArgument.getBlockPos(p_269757_, "pos"));
}))).then(Commands.literal("dimension").then(addConditional(pParent, Commands.argument("dimension", DimensionArgument.dimension()), pIsIf, (p_264789_) -> {
return DimensionArgument.getDimension(p_264789_, "dimension") == p_264789_.getSource().getLevel();
}))).then(Commands.literal("score").then(Commands.argument("target", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("targetObjective", ObjectiveArgument.objective()).then(Commands.literal("=").then(Commands.argument("source", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(addConditional(pParent, Commands.argument("sourceObjective", ObjectiveArgument.objective()), pIsIf, (p_137275_) -> {
return checkScore(p_137275_, Integer::equals);
})))).then(Commands.literal("<").then(Commands.argument("source", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(addConditional(pParent, Commands.argument("sourceObjective", ObjectiveArgument.objective()), pIsIf, (p_137273_) -> {
return checkScore(p_137273_, (p_180204_, p_180205_) -> {
return p_180204_ < p_180205_;
});
})))).then(Commands.literal("<=").then(Commands.argument("source", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(addConditional(pParent, Commands.argument("sourceObjective", ObjectiveArgument.objective()), pIsIf, (p_137261_) -> {
return checkScore(p_137261_, (p_180194_, p_180195_) -> {
return p_180194_ <= p_180195_;
});
})))).then(Commands.literal(">").then(Commands.argument("source", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(addConditional(pParent, Commands.argument("sourceObjective", ObjectiveArgument.objective()), pIsIf, (p_137249_) -> {
return checkScore(p_137249_, (p_180184_, p_180185_) -> {
return p_180184_ > p_180185_;
});
})))).then(Commands.literal(">=").then(Commands.argument("source", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(addConditional(pParent, Commands.argument("sourceObjective", ObjectiveArgument.objective()), pIsIf, (p_137234_) -> {
return checkScore(p_137234_, (p_180167_, p_180168_) -> {
return p_180167_ >= p_180168_;
});
})))).then(Commands.literal("matches").then(addConditional(pParent, Commands.argument("range", RangeArgument.intRange()), pIsIf, (p_137216_) -> {
return checkScore(p_137216_, RangeArgument.Ints.getRange(p_137216_, "range"));
})))))).then(Commands.literal("blocks").then(Commands.argument("start", BlockPosArgument.blockPos()).then(Commands.argument("end", BlockPosArgument.blockPos()).then(Commands.argument("destination", BlockPosArgument.blockPos()).then(addIfBlocksConditional(pParent, Commands.literal("all"), pIsIf, false)).then(addIfBlocksConditional(pParent, Commands.literal("masked"), pIsIf, true)))))).then(Commands.literal("entity").then(Commands.argument("entities", EntityArgument.entities()).fork(pParent, (p_137232_) -> {
return expect(p_137232_, pIsIf, !EntityArgument.getOptionalEntities(p_137232_, "entities").isEmpty());
}).executes(createNumericConditionalHandler(pIsIf, (p_137189_) -> {
return EntityArgument.getOptionalEntities(p_137189_, "entities").size();
})))).then(Commands.literal("predicate").then(addConditional(pParent, Commands.argument("predicate", ResourceLocationArgument.id()).suggests(SUGGEST_PREDICATE), pIsIf, (p_137054_) -> {
return checkCustomPredicate(p_137054_.getSource(), ResourceLocationArgument.getPredicate(p_137054_, "predicate"));
})));
for(DataCommands.DataProvider datacommands$dataprovider : DataCommands.SOURCE_PROVIDERS) {
pLiteral.then(datacommands$dataprovider.wrap(Commands.literal("data"), (p_137092_) -> {
return p_137092_.then(Commands.argument("path", NbtPathArgument.nbtPath()).fork(pParent, (p_180175_) -> {
return expect(p_180175_, pIsIf, checkMatchingData(datacommands$dataprovider.access(p_180175_), NbtPathArgument.getPath(p_180175_, "path")) > 0);
}).executes(createNumericConditionalHandler(pIsIf, (p_180152_) -> {
return checkMatchingData(datacommands$dataprovider.access(p_180152_), NbtPathArgument.getPath(p_180152_, "path"));
})));
}));
}
return pLiteral;
}
private static Command<CommandSourceStack> createNumericConditionalHandler(boolean p_137167_, ExecuteCommand.CommandNumericPredicate pPredicate) {
return p_137167_ ? (p_288391_) -> {
int i = pPredicate.test(p_288391_);
if (i > 0) {
p_288391_.getSource().sendSuccess(() -> {
return Component.translatable("commands.execute.conditional.pass_count", i);
}, false);
return i;
} else {
throw ERROR_CONDITIONAL_FAILED.create();
}
} : (p_288393_) -> {
int i = pPredicate.test(p_288393_);
if (i == 0) {
p_288393_.getSource().sendSuccess(() -> {
return Component.translatable("commands.execute.conditional.pass");
}, false);
return 1;
} else {
throw ERROR_CONDITIONAL_FAILED_COUNT.create(i);
}
};
}
private static int checkMatchingData(DataAccessor pAccessor, NbtPathArgument.NbtPath pPath) throws CommandSyntaxException {
return pPath.countMatching(pAccessor.getData());
}
private static boolean checkScore(CommandContext<CommandSourceStack> pContext, BiPredicate<Integer, Integer> pComparison) throws CommandSyntaxException {
String s = ScoreHolderArgument.getName(pContext, "target");
Objective objective = ObjectiveArgument.getObjective(pContext, "targetObjective");
String s1 = ScoreHolderArgument.getName(pContext, "source");
Objective objective1 = ObjectiveArgument.getObjective(pContext, "sourceObjective");
Scoreboard scoreboard = pContext.getSource().getServer().getScoreboard();
if (scoreboard.hasPlayerScore(s, objective) && scoreboard.hasPlayerScore(s1, objective1)) {
Score score = scoreboard.getOrCreatePlayerScore(s, objective);
Score score1 = scoreboard.getOrCreatePlayerScore(s1, objective1);
return pComparison.test(score.getScore(), score1.getScore());
} else {
return false;
}
}
private static boolean checkScore(CommandContext<CommandSourceStack> pContext, MinMaxBounds.Ints pBounds) throws CommandSyntaxException {
String s = ScoreHolderArgument.getName(pContext, "target");
Objective objective = ObjectiveArgument.getObjective(pContext, "targetObjective");
Scoreboard scoreboard = pContext.getSource().getServer().getScoreboard();
return !scoreboard.hasPlayerScore(s, objective) ? false : pBounds.matches(scoreboard.getOrCreatePlayerScore(s, objective).getScore());
}
private static boolean checkCustomPredicate(CommandSourceStack pSource, LootItemCondition pPredicate) {
ServerLevel serverlevel = pSource.getLevel();
LootParams lootparams = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, pSource.getPosition()).withOptionalParameter(LootContextParams.THIS_ENTITY, pSource.getEntity()).create(LootContextParamSets.COMMAND);
LootContext lootcontext = (new LootContext.Builder(lootparams)).create((ResourceLocation)null);
lootcontext.pushVisitedElement(LootContext.createVisitedEntry(pPredicate));
return pPredicate.test(lootcontext);
}
/**
* If actual and expected match, returns a collection containing only the source player.
*/
private static Collection<CommandSourceStack> expect(CommandContext<CommandSourceStack> pContext, boolean pActual, boolean pExpected) {
return (Collection<CommandSourceStack>)(pExpected == pActual ? Collections.singleton(pContext.getSource()) : Collections.emptyList());
}
private static ArgumentBuilder<CommandSourceStack, ?> addConditional(CommandNode<CommandSourceStack> pContext, ArgumentBuilder<CommandSourceStack, ?> pBuilder, boolean pValue, ExecuteCommand.CommandPredicate pTest) {
return pBuilder.fork(pContext, (p_137214_) -> {
return expect(p_137214_, pValue, pTest.test(p_137214_));
}).executes((p_288396_) -> {
if (pValue == pTest.test(p_288396_)) {
p_288396_.getSource().sendSuccess(() -> {
return Component.translatable("commands.execute.conditional.pass");
}, false);
return 1;
} else {
throw ERROR_CONDITIONAL_FAILED.create();
}
});
}
private static ArgumentBuilder<CommandSourceStack, ?> addIfBlocksConditional(CommandNode<CommandSourceStack> pParent, ArgumentBuilder<CommandSourceStack, ?> pLiteral, boolean pIsIf, boolean pIsMasked) {
return pLiteral.fork(pParent, (p_137180_) -> {
return expect(p_137180_, pIsIf, checkRegions(p_137180_, pIsMasked).isPresent());
}).executes(pIsIf ? (p_137210_) -> {
return checkIfRegions(p_137210_, pIsMasked);
} : (p_137165_) -> {
return checkUnlessRegions(p_137165_, pIsMasked);
});
}
private static int checkIfRegions(CommandContext<CommandSourceStack> pContext, boolean pIsMasked) throws CommandSyntaxException {
OptionalInt optionalint = checkRegions(pContext, pIsMasked);
if (optionalint.isPresent()) {
pContext.getSource().sendSuccess(() -> {
return Component.translatable("commands.execute.conditional.pass_count", optionalint.getAsInt());
}, false);
return optionalint.getAsInt();
} else {
throw ERROR_CONDITIONAL_FAILED.create();
}
}
private static int checkUnlessRegions(CommandContext<CommandSourceStack> pContext, boolean pIsMasked) throws CommandSyntaxException {
OptionalInt optionalint = checkRegions(pContext, pIsMasked);
if (optionalint.isPresent()) {
throw ERROR_CONDITIONAL_FAILED_COUNT.create(optionalint.getAsInt());
} else {
pContext.getSource().sendSuccess(() -> {
return Component.translatable("commands.execute.conditional.pass");
}, false);
return 1;
}
}
private static OptionalInt checkRegions(CommandContext<CommandSourceStack> pContext, boolean pIsMasked) throws CommandSyntaxException {
return checkRegions(pContext.getSource().getLevel(), BlockPosArgument.getLoadedBlockPos(pContext, "start"), BlockPosArgument.getLoadedBlockPos(pContext, "end"), BlockPosArgument.getLoadedBlockPos(pContext, "destination"), pIsMasked);
}
private static OptionalInt checkRegions(ServerLevel pLevel, BlockPos pBegin, BlockPos pEnd, BlockPos pDestination, boolean pIsMasked) throws CommandSyntaxException {
BoundingBox boundingbox = BoundingBox.fromCorners(pBegin, pEnd);
BoundingBox boundingbox1 = BoundingBox.fromCorners(pDestination, pDestination.offset(boundingbox.getLength()));
BlockPos blockpos = new BlockPos(boundingbox1.minX() - boundingbox.minX(), boundingbox1.minY() - boundingbox.minY(), boundingbox1.minZ() - boundingbox.minZ());
int i = boundingbox.getXSpan() * boundingbox.getYSpan() * boundingbox.getZSpan();
if (i > 32768) {
throw ERROR_AREA_TOO_LARGE.create(32768, i);
} else {
int j = 0;
for(int k = boundingbox.minZ(); k <= boundingbox.maxZ(); ++k) {
for(int l = boundingbox.minY(); l <= boundingbox.maxY(); ++l) {
for(int i1 = boundingbox.minX(); i1 <= boundingbox.maxX(); ++i1) {
BlockPos blockpos1 = new BlockPos(i1, l, k);
BlockPos blockpos2 = blockpos1.offset(blockpos);
BlockState blockstate = pLevel.getBlockState(blockpos1);
if (!pIsMasked || !blockstate.is(Blocks.AIR)) {
if (blockstate != pLevel.getBlockState(blockpos2)) {
return OptionalInt.empty();
}
BlockEntity blockentity = pLevel.getBlockEntity(blockpos1);
BlockEntity blockentity1 = pLevel.getBlockEntity(blockpos2);
if (blockentity != null) {
if (blockentity1 == null) {
return OptionalInt.empty();
}
if (blockentity1.getType() != blockentity.getType()) {
return OptionalInt.empty();
}
CompoundTag compoundtag = blockentity.saveWithoutMetadata();
CompoundTag compoundtag1 = blockentity1.saveWithoutMetadata();
if (!compoundtag.equals(compoundtag1)) {
return OptionalInt.empty();
}
}
++j;
}
}
}
}
return OptionalInt.of(j);
}
}
private static RedirectModifier<CommandSourceStack> expandOneToOneEntityRelation(Function<Entity, Optional<Entity>> pRelation) {
return (p_264786_) -> {
CommandSourceStack commandsourcestack = p_264786_.getSource();
Entity entity = commandsourcestack.getEntity();
return (Collection<CommandSourceStack>)(entity == null ? List.of() : pRelation.apply(entity).filter((p_264783_) -> {
return !p_264783_.isRemoved();
}).map((p_264775_) -> {
return List.of(commandsourcestack.withEntity(p_264775_));
}).orElse(List.of()));
};
}
private static RedirectModifier<CommandSourceStack> expandOneToManyEntityRelation(Function<Entity, Stream<Entity>> pRelation) {
return (p_264780_) -> {
CommandSourceStack commandsourcestack = p_264780_.getSource();
Entity entity = commandsourcestack.getEntity();
return entity == null ? List.of() : pRelation.apply(entity).filter((p_264784_) -> {
return !p_264784_.isRemoved();
}).map(commandsourcestack::withEntity).toList();
};
}
private static LiteralArgumentBuilder<CommandSourceStack> createRelationOperations(CommandNode<CommandSourceStack> pNode, LiteralArgumentBuilder<CommandSourceStack> pArgumentBuilder) {
return (LiteralArgumentBuilder<CommandSourceStack>)pArgumentBuilder.then(Commands.literal("owner").fork(pNode, expandOneToOneEntityRelation((p_269758_) -> {
Optional optional;
if (p_269758_ instanceof OwnableEntity ownableentity) {
optional = Optional.ofNullable(ownableentity.getOwner());
} else {
optional = Optional.empty();
}
return optional;
}))).then(Commands.literal("leasher").fork(pNode, expandOneToOneEntityRelation((p_264782_) -> {
Optional optional;
if (p_264782_ instanceof Mob mob) {
optional = Optional.ofNullable(mob.getLeashHolder());
} else {
optional = Optional.empty();
}
return optional;
}))).then(Commands.literal("target").fork(pNode, expandOneToOneEntityRelation((p_272389_) -> {
Optional optional;
if (p_272389_ instanceof Targeting targeting) {
optional = Optional.ofNullable(targeting.getTarget());
} else {
optional = Optional.empty();
}
return optional;
}))).then(Commands.literal("attacker").fork(pNode, expandOneToOneEntityRelation((p_272388_) -> {
Optional optional;
if (p_272388_ instanceof Attackable attackable) {
optional = Optional.ofNullable(attackable.getLastAttacker());
} else {
optional = Optional.empty();
}
return optional;
}))).then(Commands.literal("vehicle").fork(pNode, expandOneToOneEntityRelation((p_264776_) -> {
return Optional.ofNullable(p_264776_.getVehicle());
}))).then(Commands.literal("controller").fork(pNode, expandOneToOneEntityRelation((p_274815_) -> {
return Optional.ofNullable(p_274815_.getControllingPassenger());
}))).then(Commands.literal("origin").fork(pNode, expandOneToOneEntityRelation((p_266631_) -> {
Optional optional;
if (p_266631_ instanceof TraceableEntity traceableentity) {
optional = Optional.ofNullable(traceableentity.getOwner());
} else {
optional = Optional.empty();
}
return optional;
}))).then(Commands.literal("passengers").fork(pNode, expandOneToManyEntityRelation((p_264777_) -> {
return p_264777_.getPassengers().stream();
})));
}
private static CommandSourceStack spawnEntityAndRedirect(CommandSourceStack p_270320_, Holder.Reference<EntityType<?>> p_270344_) throws CommandSyntaxException {
Entity entity = SummonCommand.createEntity(p_270320_, p_270344_, p_270320_.getPosition(), new CompoundTag(), true);
return p_270320_.withEntity(entity);
}
@FunctionalInterface
interface CommandNumericPredicate {
int test(CommandContext<CommandSourceStack> pContext) throws CommandSyntaxException;
}
@FunctionalInterface
interface CommandPredicate {
boolean test(CommandContext<CommandSourceStack> pContext) throws CommandSyntaxException;
}
}
@@ -0,0 +1,130 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.tree.LiteralCommandNode;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.ToIntFunction;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Player;
public class ExperienceCommand {
private static final SimpleCommandExceptionType ERROR_SET_POINTS_INVALID = new SimpleCommandExceptionType(Component.translatable("commands.experience.set.points.invalid"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
LiteralCommandNode<CommandSourceStack> literalcommandnode = pDispatcher.register(Commands.literal("experience").requires((p_137324_) -> {
return p_137324_.hasPermission(2);
}).then(Commands.literal("add").then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("amount", IntegerArgumentType.integer()).executes((p_137341_) -> {
return addExperience(p_137341_.getSource(), EntityArgument.getPlayers(p_137341_, "targets"), IntegerArgumentType.getInteger(p_137341_, "amount"), ExperienceCommand.Type.POINTS);
}).then(Commands.literal("points").executes((p_137339_) -> {
return addExperience(p_137339_.getSource(), EntityArgument.getPlayers(p_137339_, "targets"), IntegerArgumentType.getInteger(p_137339_, "amount"), ExperienceCommand.Type.POINTS);
})).then(Commands.literal("levels").executes((p_137337_) -> {
return addExperience(p_137337_.getSource(), EntityArgument.getPlayers(p_137337_, "targets"), IntegerArgumentType.getInteger(p_137337_, "amount"), ExperienceCommand.Type.LEVELS);
}))))).then(Commands.literal("set").then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("amount", IntegerArgumentType.integer(0)).executes((p_137335_) -> {
return setExperience(p_137335_.getSource(), EntityArgument.getPlayers(p_137335_, "targets"), IntegerArgumentType.getInteger(p_137335_, "amount"), ExperienceCommand.Type.POINTS);
}).then(Commands.literal("points").executes((p_137333_) -> {
return setExperience(p_137333_.getSource(), EntityArgument.getPlayers(p_137333_, "targets"), IntegerArgumentType.getInteger(p_137333_, "amount"), ExperienceCommand.Type.POINTS);
})).then(Commands.literal("levels").executes((p_137331_) -> {
return setExperience(p_137331_.getSource(), EntityArgument.getPlayers(p_137331_, "targets"), IntegerArgumentType.getInteger(p_137331_, "amount"), ExperienceCommand.Type.LEVELS);
}))))).then(Commands.literal("query").then(Commands.argument("targets", EntityArgument.player()).then(Commands.literal("points").executes((p_137322_) -> {
return queryExperience(p_137322_.getSource(), EntityArgument.getPlayer(p_137322_, "targets"), ExperienceCommand.Type.POINTS);
})).then(Commands.literal("levels").executes((p_137309_) -> {
return queryExperience(p_137309_.getSource(), EntityArgument.getPlayer(p_137309_, "targets"), ExperienceCommand.Type.LEVELS);
})))));
pDispatcher.register(Commands.literal("xp").requires((p_137311_) -> {
return p_137311_.hasPermission(2);
}).redirect(literalcommandnode));
}
private static int queryExperience(CommandSourceStack pSource, ServerPlayer pPlayer, ExperienceCommand.Type pType) {
int i = pType.query.applyAsInt(pPlayer);
pSource.sendSuccess(() -> {
return Component.translatable("commands.experience.query." + pType.name, pPlayer.getDisplayName(), i);
}, false);
return i;
}
private static int addExperience(CommandSourceStack pSource, Collection<? extends ServerPlayer> pTargets, int pAmount, ExperienceCommand.Type pType) {
for(ServerPlayer serverplayer : pTargets) {
pType.add.accept(serverplayer, pAmount);
}
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.experience.add." + pType.name + ".success.single", pAmount, pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.experience.add." + pType.name + ".success.multiple", pAmount, pTargets.size());
}, true);
}
return pTargets.size();
}
private static int setExperience(CommandSourceStack pSource, Collection<? extends ServerPlayer> pTargets, int pAmount, ExperienceCommand.Type pType) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : pTargets) {
if (pType.set.test(serverplayer, pAmount)) {
++i;
}
}
if (i == 0) {
throw ERROR_SET_POINTS_INVALID.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.experience.set." + pType.name + ".success.single", pAmount, pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.experience.set." + pType.name + ".success.multiple", pAmount, pTargets.size());
}, true);
}
return pTargets.size();
}
}
static enum Type {
POINTS("points", Player::giveExperiencePoints, (p_289274_, p_289275_) -> {
if (p_289275_ >= p_289274_.getXpNeededForNextLevel()) {
return false;
} else {
p_289274_.setExperiencePoints(p_289275_);
return true;
}
}, (p_289273_) -> {
return Mth.floor(p_289273_.experienceProgress * (float)p_289273_.getXpNeededForNextLevel());
}),
LEVELS("levels", ServerPlayer::giveExperienceLevels, (p_137360_, p_137361_) -> {
p_137360_.setExperienceLevels(p_137361_);
return true;
}, (p_287335_) -> {
return p_287335_.experienceLevel;
});
public final BiConsumer<ServerPlayer, Integer> add;
public final BiPredicate<ServerPlayer, Integer> set;
public final String name;
final ToIntFunction<ServerPlayer> query;
private Type(String pName, BiConsumer<ServerPlayer, Integer> pAdd, BiPredicate<ServerPlayer, Integer> pSet, ToIntFunction<ServerPlayer> pQuery) {
this.add = pAdd;
this.name = pName;
this.set = pSet;
this.query = pQuery;
}
}
}
@@ -0,0 +1,109 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.commands.arguments.ResourceOrTagArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.QuartPos;
import net.minecraft.core.SectionPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeResolver;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import org.apache.commons.lang3.mutable.MutableInt;
public class FillBiomeCommand {
public static final SimpleCommandExceptionType ERROR_NOT_LOADED = new SimpleCommandExceptionType(Component.translatable("argument.pos.unloaded"));
private static final Dynamic2CommandExceptionType ERROR_VOLUME_TOO_LARGE = new Dynamic2CommandExceptionType((p_262025_, p_261647_) -> {
return Component.translatable("commands.fillbiome.toobig", p_262025_, p_261647_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("fillbiome").requires((p_261890_) -> {
return p_261890_.hasPermission(2);
}).then(Commands.argument("from", BlockPosArgument.blockPos()).then(Commands.argument("to", BlockPosArgument.blockPos()).then(Commands.argument("biome", ResourceArgument.resource(pContext, Registries.BIOME)).executes((p_262554_) -> {
return fill(p_262554_.getSource(), BlockPosArgument.getLoadedBlockPos(p_262554_, "from"), BlockPosArgument.getLoadedBlockPos(p_262554_, "to"), ResourceArgument.getResource(p_262554_, "biome", Registries.BIOME), (p_262543_) -> {
return true;
});
}).then(Commands.literal("replace").then(Commands.argument("filter", ResourceOrTagArgument.resourceOrTag(pContext, Registries.BIOME)).executes((p_262544_) -> {
return fill(p_262544_.getSource(), BlockPosArgument.getLoadedBlockPos(p_262544_, "from"), BlockPosArgument.getLoadedBlockPos(p_262544_, "to"), ResourceArgument.getResource(p_262544_, "biome", Registries.BIOME), ResourceOrTagArgument.getResourceOrTag(p_262544_, "filter", Registries.BIOME)::test);
})))))));
}
private static int quantize(int pValue) {
return QuartPos.toBlock(QuartPos.fromBlock(pValue));
}
private static BlockPos quantize(BlockPos pPos) {
return new BlockPos(quantize(pPos.getX()), quantize(pPos.getY()), quantize(pPos.getZ()));
}
private static BiomeResolver makeResolver(MutableInt pBiomeEntries, ChunkAccess pChunk, BoundingBox pTargetRegion, Holder<Biome> pReplacementBiome, Predicate<Holder<Biome>> pFilter) {
return (p_262550_, p_262551_, p_262552_, p_262553_) -> {
int i = QuartPos.toBlock(p_262550_);
int j = QuartPos.toBlock(p_262551_);
int k = QuartPos.toBlock(p_262552_);
Holder<Biome> holder = pChunk.getNoiseBiome(p_262550_, p_262551_, p_262552_);
if (pTargetRegion.isInside(i, j, k) && pFilter.test(holder)) {
pBiomeEntries.increment();
return pReplacementBiome;
} else {
return holder;
}
};
}
private static int fill(CommandSourceStack pSource, BlockPos pFrom, BlockPos pTo, Holder.Reference<Biome> pBiome, Predicate<Holder<Biome>> pFilter) throws CommandSyntaxException {
BlockPos blockpos = quantize(pFrom);
BlockPos blockpos1 = quantize(pTo);
BoundingBox boundingbox = BoundingBox.fromCorners(blockpos, blockpos1);
int i = boundingbox.getXSpan() * boundingbox.getYSpan() * boundingbox.getZSpan();
int j = pSource.getLevel().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT);
if (i > j) {
throw ERROR_VOLUME_TOO_LARGE.create(j, i);
} else {
ServerLevel serverlevel = pSource.getLevel();
List<ChunkAccess> list = new ArrayList<>();
for(int k = SectionPos.blockToSectionCoord(boundingbox.minZ()); k <= SectionPos.blockToSectionCoord(boundingbox.maxZ()); ++k) {
for(int l = SectionPos.blockToSectionCoord(boundingbox.minX()); l <= SectionPos.blockToSectionCoord(boundingbox.maxX()); ++l) {
ChunkAccess chunkaccess = serverlevel.getChunk(l, k, ChunkStatus.FULL, false);
if (chunkaccess == null) {
throw ERROR_NOT_LOADED.create();
}
list.add(chunkaccess);
}
}
MutableInt mutableint = new MutableInt(0);
for(ChunkAccess chunkaccess1 : list) {
chunkaccess1.fillBiomesFromNoise(makeResolver(mutableint, chunkaccess1, boundingbox, pBiome, pFilter), serverlevel.getChunkSource().randomState().sampler());
chunkaccess1.setUnsaved(true);
}
serverlevel.getChunkSource().chunkMap.resendBiomesForChunks(list);
pSource.sendSuccess(() -> {
return Component.translatable("commands.fillbiome.success.count", mutableint.getValue(), boundingbox.minX(), boundingbox.minY(), boundingbox.minZ(), boundingbox.maxX(), boundingbox.maxY(), boundingbox.maxZ());
}, true);
return mutableint.getValue();
}
}
}
@@ -0,0 +1,122 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.blocks.BlockInput;
import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
import net.minecraft.commands.arguments.blocks.BlockStateArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Clearable;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
public class FillCommand {
private static final Dynamic2CommandExceptionType ERROR_AREA_TOO_LARGE = new Dynamic2CommandExceptionType((p_137392_, p_137393_) -> {
return Component.translatable("commands.fill.toobig", p_137392_, p_137393_);
});
static final BlockInput HOLLOW_CORE = new BlockInput(Blocks.AIR.defaultBlockState(), Collections.emptySet(), (CompoundTag)null);
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.fill.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("fill").requires((p_137384_) -> {
return p_137384_.hasPermission(2);
}).then(Commands.argument("from", BlockPosArgument.blockPos()).then(Commands.argument("to", BlockPosArgument.blockPos()).then(Commands.argument("block", BlockStateArgument.block(pContext)).executes((p_137405_) -> {
return fillBlocks(p_137405_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137405_, "from"), BlockPosArgument.getLoadedBlockPos(p_137405_, "to")), BlockStateArgument.getBlock(p_137405_, "block"), FillCommand.Mode.REPLACE, (Predicate<BlockInWorld>)null);
}).then(Commands.literal("replace").executes((p_137403_) -> {
return fillBlocks(p_137403_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137403_, "from"), BlockPosArgument.getLoadedBlockPos(p_137403_, "to")), BlockStateArgument.getBlock(p_137403_, "block"), FillCommand.Mode.REPLACE, (Predicate<BlockInWorld>)null);
}).then(Commands.argument("filter", BlockPredicateArgument.blockPredicate(pContext)).executes((p_137401_) -> {
return fillBlocks(p_137401_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137401_, "from"), BlockPosArgument.getLoadedBlockPos(p_137401_, "to")), BlockStateArgument.getBlock(p_137401_, "block"), FillCommand.Mode.REPLACE, BlockPredicateArgument.getBlockPredicate(p_137401_, "filter"));
}))).then(Commands.literal("keep").executes((p_137399_) -> {
return fillBlocks(p_137399_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137399_, "from"), BlockPosArgument.getLoadedBlockPos(p_137399_, "to")), BlockStateArgument.getBlock(p_137399_, "block"), FillCommand.Mode.REPLACE, (p_180225_) -> {
return p_180225_.getLevel().isEmptyBlock(p_180225_.getPos());
});
})).then(Commands.literal("outline").executes((p_137397_) -> {
return fillBlocks(p_137397_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137397_, "from"), BlockPosArgument.getLoadedBlockPos(p_137397_, "to")), BlockStateArgument.getBlock(p_137397_, "block"), FillCommand.Mode.OUTLINE, (Predicate<BlockInWorld>)null);
})).then(Commands.literal("hollow").executes((p_137395_) -> {
return fillBlocks(p_137395_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137395_, "from"), BlockPosArgument.getLoadedBlockPos(p_137395_, "to")), BlockStateArgument.getBlock(p_137395_, "block"), FillCommand.Mode.HOLLOW, (Predicate<BlockInWorld>)null);
})).then(Commands.literal("destroy").executes((p_137382_) -> {
return fillBlocks(p_137382_.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(p_137382_, "from"), BlockPosArgument.getLoadedBlockPos(p_137382_, "to")), BlockStateArgument.getBlock(p_137382_, "block"), FillCommand.Mode.DESTROY, (Predicate<BlockInWorld>)null);
}))))));
}
private static int fillBlocks(CommandSourceStack pSource, BoundingBox pArea, BlockInput pNewBlock, FillCommand.Mode pMode, @Nullable Predicate<BlockInWorld> pReplacingPredicate) throws CommandSyntaxException {
int i = pArea.getXSpan() * pArea.getYSpan() * pArea.getZSpan();
int j = pSource.getLevel().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT);
if (i > j) {
throw ERROR_AREA_TOO_LARGE.create(j, i);
} else {
List<BlockPos> list = Lists.newArrayList();
ServerLevel serverlevel = pSource.getLevel();
int k = 0;
for(BlockPos blockpos : BlockPos.betweenClosed(pArea.minX(), pArea.minY(), pArea.minZ(), pArea.maxX(), pArea.maxY(), pArea.maxZ())) {
if (pReplacingPredicate == null || pReplacingPredicate.test(new BlockInWorld(serverlevel, blockpos, true))) {
BlockInput blockinput = pMode.filter.filter(pArea, blockpos, pNewBlock, serverlevel);
if (blockinput != null) {
BlockEntity blockentity = serverlevel.getBlockEntity(blockpos);
Clearable.tryClear(blockentity);
if (blockinput.place(serverlevel, blockpos, 2)) {
list.add(blockpos.immutable());
++k;
}
}
}
}
for(BlockPos blockpos1 : list) {
Block block = serverlevel.getBlockState(blockpos1).getBlock();
serverlevel.blockUpdated(blockpos1, block);
}
if (k == 0) {
throw ERROR_FAILED.create();
} else {
int l = k;
pSource.sendSuccess(() -> {
return Component.translatable("commands.fill.success", l);
}, true);
return k;
}
}
}
static enum Mode {
REPLACE((p_137433_, p_137434_, p_137435_, p_137436_) -> {
return p_137435_;
}),
OUTLINE((p_137428_, p_137429_, p_137430_, p_137431_) -> {
return p_137429_.getX() != p_137428_.minX() && p_137429_.getX() != p_137428_.maxX() && p_137429_.getY() != p_137428_.minY() && p_137429_.getY() != p_137428_.maxY() && p_137429_.getZ() != p_137428_.minZ() && p_137429_.getZ() != p_137428_.maxZ() ? null : p_137430_;
}),
HOLLOW((p_137423_, p_137424_, p_137425_, p_137426_) -> {
return p_137424_.getX() != p_137423_.minX() && p_137424_.getX() != p_137423_.maxX() && p_137424_.getY() != p_137423_.minY() && p_137424_.getY() != p_137423_.maxY() && p_137424_.getZ() != p_137423_.minZ() && p_137424_.getZ() != p_137423_.maxZ() ? FillCommand.HOLLOW_CORE : p_137425_;
}),
DESTROY((p_137418_, p_137419_, p_137420_, p_137421_) -> {
p_137421_.destroyBlock(p_137419_, true);
return p_137420_;
});
public final SetBlockCommand.Filter filter;
private Mode(SetBlockCommand.Filter pFilter) {
this.filter = pFilter;
}
}
}
@@ -0,0 +1,157 @@
package net.minecraft.server.commands;
import com.google.common.base.Joiner;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.commands.arguments.coordinates.ColumnPosArgument;
import net.minecraft.core.SectionPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ColumnPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
public class ForceLoadCommand {
private static final int MAX_CHUNK_LIMIT = 256;
private static final Dynamic2CommandExceptionType ERROR_TOO_MANY_CHUNKS = new Dynamic2CommandExceptionType((p_137698_, p_137699_) -> {
return Component.translatable("commands.forceload.toobig", p_137698_, p_137699_);
});
private static final Dynamic2CommandExceptionType ERROR_NOT_TICKING = new Dynamic2CommandExceptionType((p_137691_, p_137692_) -> {
return Component.translatable("commands.forceload.query.failure", p_137691_, p_137692_);
});
private static final SimpleCommandExceptionType ERROR_ALL_ADDED = new SimpleCommandExceptionType(Component.translatable("commands.forceload.added.failure"));
private static final SimpleCommandExceptionType ERROR_NONE_REMOVED = new SimpleCommandExceptionType(Component.translatable("commands.forceload.removed.failure"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("forceload").requires((p_137703_) -> {
return p_137703_.hasPermission(2);
}).then(Commands.literal("add").then(Commands.argument("from", ColumnPosArgument.columnPos()).executes((p_137711_) -> {
return changeForceLoad(p_137711_.getSource(), ColumnPosArgument.getColumnPos(p_137711_, "from"), ColumnPosArgument.getColumnPos(p_137711_, "from"), true);
}).then(Commands.argument("to", ColumnPosArgument.columnPos()).executes((p_137709_) -> {
return changeForceLoad(p_137709_.getSource(), ColumnPosArgument.getColumnPos(p_137709_, "from"), ColumnPosArgument.getColumnPos(p_137709_, "to"), true);
})))).then(Commands.literal("remove").then(Commands.argument("from", ColumnPosArgument.columnPos()).executes((p_137707_) -> {
return changeForceLoad(p_137707_.getSource(), ColumnPosArgument.getColumnPos(p_137707_, "from"), ColumnPosArgument.getColumnPos(p_137707_, "from"), false);
}).then(Commands.argument("to", ColumnPosArgument.columnPos()).executes((p_137705_) -> {
return changeForceLoad(p_137705_.getSource(), ColumnPosArgument.getColumnPos(p_137705_, "from"), ColumnPosArgument.getColumnPos(p_137705_, "to"), false);
}))).then(Commands.literal("all").executes((p_137701_) -> {
return removeAll(p_137701_.getSource());
}))).then(Commands.literal("query").executes((p_137694_) -> {
return listForceLoad(p_137694_.getSource());
}).then(Commands.argument("pos", ColumnPosArgument.columnPos()).executes((p_137679_) -> {
return queryForceLoad(p_137679_.getSource(), ColumnPosArgument.getColumnPos(p_137679_, "pos"));
}))));
}
private static int queryForceLoad(CommandSourceStack pSource, ColumnPos pPos) throws CommandSyntaxException {
ChunkPos chunkpos = pPos.toChunkPos();
ServerLevel serverlevel = pSource.getLevel();
ResourceKey<Level> resourcekey = serverlevel.dimension();
boolean flag = serverlevel.getForcedChunks().contains(chunkpos.toLong());
if (flag) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.forceload.query.success", chunkpos, resourcekey.location());
}, false);
return 1;
} else {
throw ERROR_NOT_TICKING.create(chunkpos, resourcekey.location());
}
}
private static int listForceLoad(CommandSourceStack pSource) {
ServerLevel serverlevel = pSource.getLevel();
ResourceKey<Level> resourcekey = serverlevel.dimension();
LongSet longset = serverlevel.getForcedChunks();
int i = longset.size();
if (i > 0) {
String s = Joiner.on(", ").join(longset.stream().sorted().map(ChunkPos::new).map(ChunkPos::toString).iterator());
if (i == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.forceload.list.single", resourcekey.location(), s);
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.forceload.list.multiple", i, resourcekey.location(), s);
}, false);
}
} else {
pSource.sendFailure(Component.translatable("commands.forceload.added.none", resourcekey.location()));
}
return i;
}
private static int removeAll(CommandSourceStack pSource) {
ServerLevel serverlevel = pSource.getLevel();
ResourceKey<Level> resourcekey = serverlevel.dimension();
LongSet longset = serverlevel.getForcedChunks();
longset.forEach((p_137675_) -> {
serverlevel.setChunkForced(ChunkPos.getX(p_137675_), ChunkPos.getZ(p_137675_), false);
});
pSource.sendSuccess(() -> {
return Component.translatable("commands.forceload.removed.all", resourcekey.location());
}, true);
return 0;
}
private static int changeForceLoad(CommandSourceStack pSource, ColumnPos pFrom, ColumnPos pTo, boolean pAdd) throws CommandSyntaxException {
int i = Math.min(pFrom.x(), pTo.x());
int j = Math.min(pFrom.z(), pTo.z());
int k = Math.max(pFrom.x(), pTo.x());
int l = Math.max(pFrom.z(), pTo.z());
if (i >= -30000000 && j >= -30000000 && k < 30000000 && l < 30000000) {
int i1 = SectionPos.blockToSectionCoord(i);
int j1 = SectionPos.blockToSectionCoord(j);
int k1 = SectionPos.blockToSectionCoord(k);
int l1 = SectionPos.blockToSectionCoord(l);
long i2 = ((long)(k1 - i1) + 1L) * ((long)(l1 - j1) + 1L);
if (i2 > 256L) {
throw ERROR_TOO_MANY_CHUNKS.create(256, i2);
} else {
ServerLevel serverlevel = pSource.getLevel();
ResourceKey<Level> resourcekey = serverlevel.dimension();
ChunkPos chunkpos = null;
int j2 = 0;
for(int k2 = i1; k2 <= k1; ++k2) {
for(int l2 = j1; l2 <= l1; ++l2) {
boolean flag = serverlevel.setChunkForced(k2, l2, pAdd);
if (flag) {
++j2;
if (chunkpos == null) {
chunkpos = new ChunkPos(k2, l2);
}
}
}
}
ChunkPos chunkpos1 = chunkpos;
if (j2 == 0) {
throw (pAdd ? ERROR_ALL_ADDED : ERROR_NONE_REMOVED).create();
} else {
if (j2 == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.forceload." + (pAdd ? "added" : "removed") + ".single", chunkpos1, resourcekey.location());
}, true);
} else {
ChunkPos chunkpos2 = new ChunkPos(i1, j1);
ChunkPos chunkpos3 = new ChunkPos(k1, l1);
pSource.sendSuccess(() -> {
return Component.translatable("commands.forceload." + (pAdd ? "added" : "removed") + ".multiple", chunkpos1, resourcekey.location(), chunkpos2, chunkpos3);
}, true);
}
return j2;
}
}
} else {
throw BlockPosArgument.ERROR_OUT_OF_WORLD.create();
}
}
}
@@ -0,0 +1,68 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Collection;
import java.util.OptionalInt;
import net.minecraft.commands.CommandFunction;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.item.FunctionArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.ServerFunctionManager;
import org.apache.commons.lang3.mutable.MutableObject;
public class FunctionCommand {
public static final SuggestionProvider<CommandSourceStack> SUGGEST_FUNCTION = (p_137719_, p_137720_) -> {
ServerFunctionManager serverfunctionmanager = p_137719_.getSource().getServer().getFunctions();
SharedSuggestionProvider.suggestResource(serverfunctionmanager.getTagNames(), p_137720_, "#");
return SharedSuggestionProvider.suggestResource(serverfunctionmanager.getFunctionNames(), p_137720_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("function").requires((p_137722_) -> {
return p_137722_.hasPermission(2);
}).then(Commands.argument("name", FunctionArgument.functions()).suggests(SUGGEST_FUNCTION).executes((p_137717_) -> {
return runFunction(p_137717_.getSource(), FunctionArgument.getFunctions(p_137717_, "name"));
})));
}
private static int runFunction(CommandSourceStack pSource, Collection<CommandFunction> pFunctions) {
int i = 0;
boolean flag = false;
for(CommandFunction commandfunction : pFunctions) {
MutableObject<OptionalInt> mutableobject = new MutableObject<>(OptionalInt.empty());
int j = pSource.getServer().getFunctions().execute(commandfunction, pSource.withSuppressedOutput().withMaximumPermission(2).withReturnValueConsumer((p_280947_) -> {
mutableobject.setValue(OptionalInt.of(p_280947_));
}));
OptionalInt optionalint = mutableobject.getValue();
i += optionalint.orElse(j);
flag |= optionalint.isPresent();
}
int k = i;
if (pFunctions.size() == 1) {
if (flag) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.function.success.single.result", k, pFunctions.iterator().next().getId());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.function.success.single", k, pFunctions.iterator().next().getId());
}, true);
}
} else if (flag) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.function.success.multiple.result", pFunctions.size());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.function.success.multiple", k, pFunctions.size());
}, true);
}
return i;
}
}
@@ -0,0 +1,59 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import java.util.Collection;
import java.util.Collections;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.GameModeArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.GameType;
public class GameModeCommand {
public static final int PERMISSION_LEVEL = 2;
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("gamemode").requires((p_137736_) -> {
return p_137736_.hasPermission(2);
}).then(Commands.argument("gamemode", GameModeArgument.gameMode()).executes((p_258228_) -> {
return setMode(p_258228_, Collections.singleton(p_258228_.getSource().getPlayerOrException()), GameModeArgument.getGameMode(p_258228_, "gamemode"));
}).then(Commands.argument("target", EntityArgument.players()).executes((p_258229_) -> {
return setMode(p_258229_, EntityArgument.getPlayers(p_258229_, "target"), GameModeArgument.getGameMode(p_258229_, "gamemode"));
}))));
}
private static void logGamemodeChange(CommandSourceStack pSource, ServerPlayer pPlayer, GameType pGameType) {
Component component = Component.translatable("gameMode." + pGameType.getName());
if (pSource.getEntity() == pPlayer) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.gamemode.success.self", component);
}, true);
} else {
if (pSource.getLevel().getGameRules().getBoolean(GameRules.RULE_SENDCOMMANDFEEDBACK)) {
pPlayer.sendSystemMessage(Component.translatable("gameMode.changed", component));
}
pSource.sendSuccess(() -> {
return Component.translatable("commands.gamemode.success.other", pPlayer.getDisplayName(), component);
}, true);
}
}
private static int setMode(CommandContext<CommandSourceStack> pSource, Collection<ServerPlayer> pPlayers, GameType pGameType) {
int i = 0;
for(ServerPlayer serverplayer : pPlayers) {
if (serverplayer.setGameMode(pGameType)) {
logGamemodeChange(pSource.getSource(), serverplayer, pGameType);
++i;
}
}
return i;
}
}
@@ -0,0 +1,45 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.GameRules;
public class GameRuleCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
final LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = Commands.literal("gamerule").requires((p_137750_) -> {
return p_137750_.hasPermission(2);
});
GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() {
public <T extends GameRules.Value<T>> void visit(GameRules.Key<T> p_137764_, GameRules.Type<T> p_137765_) {
literalargumentbuilder.then(Commands.literal(p_137764_.getId()).executes((p_137771_) -> {
return GameRuleCommand.queryRule(p_137771_.getSource(), p_137764_);
}).then(p_137765_.createArgument("value").executes((p_137768_) -> {
return GameRuleCommand.setRule(p_137768_, p_137764_);
})));
}
});
pDispatcher.register(literalargumentbuilder);
}
static <T extends GameRules.Value<T>> int setRule(CommandContext<CommandSourceStack> pSource, GameRules.Key<T> pGameRule) {
CommandSourceStack commandsourcestack = pSource.getSource();
T t = commandsourcestack.getServer().getGameRules().getRule(pGameRule);
t.setFromArgument(pSource, "value");
commandsourcestack.sendSuccess(() -> {
return Component.translatable("commands.gamerule.set", pGameRule.getId(), t.toString());
}, true);
return t.getCommandResult();
}
static <T extends GameRules.Value<T>> int queryRule(CommandSourceStack pSource, GameRules.Key<T> pGameRule) {
T t = pSource.getServer().getGameRules().getRule(pGameRule);
pSource.sendSuccess(() -> {
return Component.translatable("commands.gamerule.query", pGameRule.getId(), t.toString());
}, false);
return t.getCommandResult();
}
}
@@ -0,0 +1,82 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Collection;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.item.ItemArgument;
import net.minecraft.commands.arguments.item.ItemInput;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
public class GiveCommand {
public static final int MAX_ALLOWED_ITEMSTACKS = 100;
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("give").requires((p_137777_) -> {
return p_137777_.hasPermission(2);
}).then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("item", ItemArgument.item(pContext)).executes((p_137784_) -> {
return giveItem(p_137784_.getSource(), ItemArgument.getItem(p_137784_, "item"), EntityArgument.getPlayers(p_137784_, "targets"), 1);
}).then(Commands.argument("count", IntegerArgumentType.integer(1)).executes((p_137775_) -> {
return giveItem(p_137775_.getSource(), ItemArgument.getItem(p_137775_, "item"), EntityArgument.getPlayers(p_137775_, "targets"), IntegerArgumentType.getInteger(p_137775_, "count"));
})))));
}
private static int giveItem(CommandSourceStack pSource, ItemInput pItem, Collection<ServerPlayer> pTargets, int pCount) throws CommandSyntaxException {
int i = pItem.getItem().getMaxStackSize();
int j = i * 100;
ItemStack itemstack = pItem.createItemStack(pCount, false);
if (pCount > j) {
pSource.sendFailure(Component.translatable("commands.give.failed.toomanyitems", j, itemstack.getDisplayName()));
return 0;
} else {
for(ServerPlayer serverplayer : pTargets) {
int k = pCount;
while(k > 0) {
int l = Math.min(i, k);
k -= l;
ItemStack itemstack1 = pItem.createItemStack(l, false);
boolean flag = serverplayer.getInventory().add(itemstack1);
if (flag && itemstack1.isEmpty()) {
itemstack1.setCount(1);
ItemEntity itementity1 = serverplayer.drop(itemstack1, false);
if (itementity1 != null) {
itementity1.makeFakeItem();
}
serverplayer.level().playSound((Player)null, serverplayer.getX(), serverplayer.getY(), serverplayer.getZ(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 0.2F, ((serverplayer.getRandom().nextFloat() - serverplayer.getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F);
serverplayer.containerMenu.broadcastChanges();
} else {
ItemEntity itementity = serverplayer.drop(itemstack1, false);
if (itementity != null) {
itementity.setNoPickUpDelay();
itementity.setTarget(serverplayer.getUUID());
}
}
}
}
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.give.success.single", pCount, itemstack.getDisplayName(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.give.success.single", pCount, itemstack.getDisplayName(), pTargets.size());
}, true);
}
return pTargets.size();
}
}
}
@@ -0,0 +1,45 @@
package net.minecraft.server.commands;
import com.google.common.collect.Iterables;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.tree.CommandNode;
import java.util.Map;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
public class HelpCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.help.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("help").executes((p_288460_) -> {
Map<CommandNode<CommandSourceStack>, String> map = pDispatcher.getSmartUsage(pDispatcher.getRoot(), p_288460_.getSource());
for(String s : map.values()) {
p_288460_.getSource().sendSuccess(() -> {
return Component.literal("/" + s);
}, false);
}
return map.size();
}).then(Commands.argument("command", StringArgumentType.greedyString()).executes((p_288458_) -> {
ParseResults<CommandSourceStack> parseresults = pDispatcher.parse(StringArgumentType.getString(p_288458_, "command"), p_288458_.getSource());
if (parseresults.getContext().getNodes().isEmpty()) {
throw ERROR_FAILED.create();
} else {
Map<CommandNode<CommandSourceStack>, String> map = pDispatcher.getSmartUsage(Iterables.getLast(parseresults.getContext().getNodes()).getNode(), p_288458_.getSource());
for(String s : map.values()) {
p_288458_.getSource().sendSuccess(() -> {
return Component.literal("/" + parseresults.getReader().getString() + " " + s);
}, false);
}
return map.size();
}
})));
}
}
@@ -0,0 +1,257 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.SlotArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.commands.arguments.item.ItemArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.Container;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.SlotAccess;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.storage.loot.LootDataType;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.functions.LootItemFunction;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
public class ItemCommands {
static final Dynamic3CommandExceptionType ERROR_TARGET_NOT_A_CONTAINER = new Dynamic3CommandExceptionType((p_180355_, p_180356_, p_180357_) -> {
return Component.translatable("commands.item.target.not_a_container", p_180355_, p_180356_, p_180357_);
});
private static final Dynamic3CommandExceptionType ERROR_SOURCE_NOT_A_CONTAINER = new Dynamic3CommandExceptionType((p_180347_, p_180348_, p_180349_) -> {
return Component.translatable("commands.item.source.not_a_container", p_180347_, p_180348_, p_180349_);
});
static final DynamicCommandExceptionType ERROR_TARGET_INAPPLICABLE_SLOT = new DynamicCommandExceptionType((p_180361_) -> {
return Component.translatable("commands.item.target.no_such_slot", p_180361_);
});
private static final DynamicCommandExceptionType ERROR_SOURCE_INAPPLICABLE_SLOT = new DynamicCommandExceptionType((p_180353_) -> {
return Component.translatable("commands.item.source.no_such_slot", p_180353_);
});
private static final DynamicCommandExceptionType ERROR_TARGET_NO_CHANGES = new DynamicCommandExceptionType((p_180342_) -> {
return Component.translatable("commands.item.target.no_changes", p_180342_);
});
private static final Dynamic2CommandExceptionType ERROR_TARGET_NO_CHANGES_KNOWN_ITEM = new Dynamic2CommandExceptionType((p_180344_, p_180345_) -> {
return Component.translatable("commands.item.target.no_changed.known_item", p_180344_, p_180345_);
});
private static final SuggestionProvider<CommandSourceStack> SUGGEST_MODIFIER = (p_278910_, p_278911_) -> {
LootDataManager lootdatamanager = p_278910_.getSource().getServer().getLootData();
return SharedSuggestionProvider.suggestResource(lootdatamanager.getKeys(LootDataType.MODIFIER), p_278911_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("item").requires((p_180256_) -> {
return p_180256_.hasPermission(2);
}).then(Commands.literal("replace").then(Commands.literal("block").then(Commands.argument("pos", BlockPosArgument.blockPos()).then(Commands.argument("slot", SlotArgument.slot()).then(Commands.literal("with").then(Commands.argument("item", ItemArgument.item(pContext)).executes((p_180383_) -> {
return setBlockItem(p_180383_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180383_, "pos"), SlotArgument.getSlot(p_180383_, "slot"), ItemArgument.getItem(p_180383_, "item").createItemStack(1, false));
}).then(Commands.argument("count", IntegerArgumentType.integer(1, 64)).executes((p_180381_) -> {
return setBlockItem(p_180381_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180381_, "pos"), SlotArgument.getSlot(p_180381_, "slot"), ItemArgument.getItem(p_180381_, "item").createItemStack(IntegerArgumentType.getInteger(p_180381_, "count"), true));
})))).then(Commands.literal("from").then(Commands.literal("block").then(Commands.argument("source", BlockPosArgument.blockPos()).then(Commands.argument("sourceSlot", SlotArgument.slot()).executes((p_180379_) -> {
return blockToBlock(p_180379_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180379_, "source"), SlotArgument.getSlot(p_180379_, "sourceSlot"), BlockPosArgument.getLoadedBlockPos(p_180379_, "pos"), SlotArgument.getSlot(p_180379_, "slot"));
}).then(Commands.argument("modifier", ResourceLocationArgument.id()).suggests(SUGGEST_MODIFIER).executes((p_180377_) -> {
return blockToBlock(p_180377_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180377_, "source"), SlotArgument.getSlot(p_180377_, "sourceSlot"), BlockPosArgument.getLoadedBlockPos(p_180377_, "pos"), SlotArgument.getSlot(p_180377_, "slot"), ResourceLocationArgument.getItemModifier(p_180377_, "modifier"));
}))))).then(Commands.literal("entity").then(Commands.argument("source", EntityArgument.entity()).then(Commands.argument("sourceSlot", SlotArgument.slot()).executes((p_180375_) -> {
return entityToBlock(p_180375_.getSource(), EntityArgument.getEntity(p_180375_, "source"), SlotArgument.getSlot(p_180375_, "sourceSlot"), BlockPosArgument.getLoadedBlockPos(p_180375_, "pos"), SlotArgument.getSlot(p_180375_, "slot"));
}).then(Commands.argument("modifier", ResourceLocationArgument.id()).suggests(SUGGEST_MODIFIER).executes((p_180373_) -> {
return entityToBlock(p_180373_.getSource(), EntityArgument.getEntity(p_180373_, "source"), SlotArgument.getSlot(p_180373_, "sourceSlot"), BlockPosArgument.getLoadedBlockPos(p_180373_, "pos"), SlotArgument.getSlot(p_180373_, "slot"), ResourceLocationArgument.getItemModifier(p_180373_, "modifier"));
}))))))))).then(Commands.literal("entity").then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("slot", SlotArgument.slot()).then(Commands.literal("with").then(Commands.argument("item", ItemArgument.item(pContext)).executes((p_180371_) -> {
return setEntityItem(p_180371_.getSource(), EntityArgument.getEntities(p_180371_, "targets"), SlotArgument.getSlot(p_180371_, "slot"), ItemArgument.getItem(p_180371_, "item").createItemStack(1, false));
}).then(Commands.argument("count", IntegerArgumentType.integer(1, 64)).executes((p_180369_) -> {
return setEntityItem(p_180369_.getSource(), EntityArgument.getEntities(p_180369_, "targets"), SlotArgument.getSlot(p_180369_, "slot"), ItemArgument.getItem(p_180369_, "item").createItemStack(IntegerArgumentType.getInteger(p_180369_, "count"), true));
})))).then(Commands.literal("from").then(Commands.literal("block").then(Commands.argument("source", BlockPosArgument.blockPos()).then(Commands.argument("sourceSlot", SlotArgument.slot()).executes((p_180367_) -> {
return blockToEntities(p_180367_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180367_, "source"), SlotArgument.getSlot(p_180367_, "sourceSlot"), EntityArgument.getEntities(p_180367_, "targets"), SlotArgument.getSlot(p_180367_, "slot"));
}).then(Commands.argument("modifier", ResourceLocationArgument.id()).suggests(SUGGEST_MODIFIER).executes((p_180365_) -> {
return blockToEntities(p_180365_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180365_, "source"), SlotArgument.getSlot(p_180365_, "sourceSlot"), EntityArgument.getEntities(p_180365_, "targets"), SlotArgument.getSlot(p_180365_, "slot"), ResourceLocationArgument.getItemModifier(p_180365_, "modifier"));
}))))).then(Commands.literal("entity").then(Commands.argument("source", EntityArgument.entity()).then(Commands.argument("sourceSlot", SlotArgument.slot()).executes((p_180363_) -> {
return entityToEntities(p_180363_.getSource(), EntityArgument.getEntity(p_180363_, "source"), SlotArgument.getSlot(p_180363_, "sourceSlot"), EntityArgument.getEntities(p_180363_, "targets"), SlotArgument.getSlot(p_180363_, "slot"));
}).then(Commands.argument("modifier", ResourceLocationArgument.id()).suggests(SUGGEST_MODIFIER).executes((p_180359_) -> {
return entityToEntities(p_180359_.getSource(), EntityArgument.getEntity(p_180359_, "source"), SlotArgument.getSlot(p_180359_, "sourceSlot"), EntityArgument.getEntities(p_180359_, "targets"), SlotArgument.getSlot(p_180359_, "slot"), ResourceLocationArgument.getItemModifier(p_180359_, "modifier"));
})))))))))).then(Commands.literal("modify").then(Commands.literal("block").then(Commands.argument("pos", BlockPosArgument.blockPos()).then(Commands.argument("slot", SlotArgument.slot()).then(Commands.argument("modifier", ResourceLocationArgument.id()).suggests(SUGGEST_MODIFIER).executes((p_180351_) -> {
return modifyBlockItem(p_180351_.getSource(), BlockPosArgument.getLoadedBlockPos(p_180351_, "pos"), SlotArgument.getSlot(p_180351_, "slot"), ResourceLocationArgument.getItemModifier(p_180351_, "modifier"));
}))))).then(Commands.literal("entity").then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("slot", SlotArgument.slot()).then(Commands.argument("modifier", ResourceLocationArgument.id()).suggests(SUGGEST_MODIFIER).executes((p_180251_) -> {
return modifyEntityItem(p_180251_.getSource(), EntityArgument.getEntities(p_180251_, "targets"), SlotArgument.getSlot(p_180251_, "slot"), ResourceLocationArgument.getItemModifier(p_180251_, "modifier"));
})))))));
}
private static int modifyBlockItem(CommandSourceStack pSource, BlockPos pPos, int pSlot, LootItemFunction pModifier) throws CommandSyntaxException {
Container container = getContainer(pSource, pPos, ERROR_TARGET_NOT_A_CONTAINER);
if (pSlot >= 0 && pSlot < container.getContainerSize()) {
ItemStack itemstack = applyModifier(pSource, pModifier, container.getItem(pSlot));
container.setItem(pSlot, itemstack);
pSource.sendSuccess(() -> {
return Component.translatable("commands.item.block.set.success", pPos.getX(), pPos.getY(), pPos.getZ(), itemstack.getDisplayName());
}, true);
return 1;
} else {
throw ERROR_TARGET_INAPPLICABLE_SLOT.create(pSlot);
}
}
private static int modifyEntityItem(CommandSourceStack pSource, Collection<? extends Entity> pTargets, int pSlot, LootItemFunction pModifier) throws CommandSyntaxException {
Map<Entity, ItemStack> map = Maps.newHashMapWithExpectedSize(pTargets.size());
for(Entity entity : pTargets) {
SlotAccess slotaccess = entity.getSlot(pSlot);
if (slotaccess != SlotAccess.NULL) {
ItemStack itemstack = applyModifier(pSource, pModifier, slotaccess.get().copy());
if (slotaccess.set(itemstack)) {
map.put(entity, itemstack);
if (entity instanceof ServerPlayer) {
((ServerPlayer)entity).containerMenu.broadcastChanges();
}
}
}
}
if (map.isEmpty()) {
throw ERROR_TARGET_NO_CHANGES.create(pSlot);
} else {
if (map.size() == 1) {
Map.Entry<Entity, ItemStack> entry = map.entrySet().iterator().next();
pSource.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.single", entry.getKey().getDisplayName(), entry.getValue().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.multiple", map.size());
}, true);
}
return map.size();
}
}
private static int setBlockItem(CommandSourceStack pSource, BlockPos pPos, int pSlot, ItemStack pItem) throws CommandSyntaxException {
Container container = getContainer(pSource, pPos, ERROR_TARGET_NOT_A_CONTAINER);
if (pSlot >= 0 && pSlot < container.getContainerSize()) {
container.setItem(pSlot, pItem);
pSource.sendSuccess(() -> {
return Component.translatable("commands.item.block.set.success", pPos.getX(), pPos.getY(), pPos.getZ(), pItem.getDisplayName());
}, true);
return 1;
} else {
throw ERROR_TARGET_INAPPLICABLE_SLOT.create(pSlot);
}
}
private static Container getContainer(CommandSourceStack pSource, BlockPos pPos, Dynamic3CommandExceptionType p_180330_) throws CommandSyntaxException {
BlockEntity blockentity = pSource.getLevel().getBlockEntity(pPos);
if (!(blockentity instanceof Container)) {
throw p_180330_.create(pPos.getX(), pPos.getY(), pPos.getZ());
} else {
return (Container)blockentity;
}
}
private static int setEntityItem(CommandSourceStack pSource, Collection<? extends Entity> pTargets, int pSlot, ItemStack pItem) throws CommandSyntaxException {
List<Entity> list = Lists.newArrayListWithCapacity(pTargets.size());
for(Entity entity : pTargets) {
SlotAccess slotaccess = entity.getSlot(pSlot);
if (slotaccess != SlotAccess.NULL && slotaccess.set(pItem.copy())) {
list.add(entity);
if (entity instanceof ServerPlayer) {
((ServerPlayer)entity).containerMenu.broadcastChanges();
}
}
}
if (list.isEmpty()) {
throw ERROR_TARGET_NO_CHANGES_KNOWN_ITEM.create(pItem.getDisplayName(), pSlot);
} else {
if (list.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.single", list.iterator().next().getDisplayName(), pItem.getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.multiple", list.size(), pItem.getDisplayName());
}, true);
}
return list.size();
}
}
private static int blockToEntities(CommandSourceStack pSource, BlockPos pPos, int pSourceSlot, Collection<? extends Entity> pTargets, int pSlot) throws CommandSyntaxException {
return setEntityItem(pSource, pTargets, pSlot, getBlockItem(pSource, pPos, pSourceSlot));
}
private static int blockToEntities(CommandSourceStack pSource, BlockPos pPos, int pSourceSlot, Collection<? extends Entity> pTargets, int pSlot, LootItemFunction pModifier) throws CommandSyntaxException {
return setEntityItem(pSource, pTargets, pSlot, applyModifier(pSource, pModifier, getBlockItem(pSource, pPos, pSourceSlot)));
}
private static int blockToBlock(CommandSourceStack pSource, BlockPos pSourcePos, int pSourceSlot, BlockPos pPos, int pSlot) throws CommandSyntaxException {
return setBlockItem(pSource, pPos, pSlot, getBlockItem(pSource, pSourcePos, pSourceSlot));
}
private static int blockToBlock(CommandSourceStack pSource, BlockPos pSourcePos, int pSourceSlot, BlockPos pPos, int pSlot, LootItemFunction pModifier) throws CommandSyntaxException {
return setBlockItem(pSource, pPos, pSlot, applyModifier(pSource, pModifier, getBlockItem(pSource, pSourcePos, pSourceSlot)));
}
private static int entityToBlock(CommandSourceStack pSource, Entity pSourceEntity, int pSourceSlot, BlockPos pPos, int pSlot) throws CommandSyntaxException {
return setBlockItem(pSource, pPos, pSlot, getEntityItem(pSourceEntity, pSourceSlot));
}
private static int entityToBlock(CommandSourceStack pSource, Entity pSourceEntity, int pSourceSlot, BlockPos pPos, int pSlot, LootItemFunction pModifier) throws CommandSyntaxException {
return setBlockItem(pSource, pPos, pSlot, applyModifier(pSource, pModifier, getEntityItem(pSourceEntity, pSourceSlot)));
}
private static int entityToEntities(CommandSourceStack pSource, Entity pSourceEntity, int pSourceSlot, Collection<? extends Entity> pTargets, int pSlot) throws CommandSyntaxException {
return setEntityItem(pSource, pTargets, pSlot, getEntityItem(pSourceEntity, pSourceSlot));
}
private static int entityToEntities(CommandSourceStack pSource, Entity pSourceEntity, int pSourceSlot, Collection<? extends Entity> pTargets, int pSlot, LootItemFunction pModifier) throws CommandSyntaxException {
return setEntityItem(pSource, pTargets, pSlot, applyModifier(pSource, pModifier, getEntityItem(pSourceEntity, pSourceSlot)));
}
private static ItemStack applyModifier(CommandSourceStack pSource, LootItemFunction pModifier, ItemStack pItem) {
ServerLevel serverlevel = pSource.getLevel();
LootParams lootparams = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, pSource.getPosition()).withOptionalParameter(LootContextParams.THIS_ENTITY, pSource.getEntity()).create(LootContextParamSets.COMMAND);
LootContext lootcontext = (new LootContext.Builder(lootparams)).create((ResourceLocation)null);
lootcontext.pushVisitedElement(LootContext.createVisitedEntry(pModifier));
return pModifier.apply(pItem, lootcontext);
}
private static ItemStack getEntityItem(Entity pEntity, int pSlot) throws CommandSyntaxException {
SlotAccess slotaccess = pEntity.getSlot(pSlot);
if (slotaccess == SlotAccess.NULL) {
throw ERROR_SOURCE_INAPPLICABLE_SLOT.create(pSlot);
} else {
return slotaccess.get().copy();
}
}
private static ItemStack getBlockItem(CommandSourceStack pSource, BlockPos pPos, int pSlot) throws CommandSyntaxException {
Container container = getContainer(pSource, pPos, ERROR_SOURCE_NOT_A_CONTAINER);
if (pSlot >= 0 && pSlot < container.getContainerSize()) {
return container.getItem(pSlot).copy();
} else {
throw ERROR_SOURCE_INAPPLICABLE_SLOT.create(pSlot);
}
}
}
@@ -0,0 +1,65 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.nio.file.Path;
import java.nio.file.Paths;
import net.minecraft.ChatFormatting;
import net.minecraft.SharedConstants;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.util.profiling.jfr.Environment;
import net.minecraft.util.profiling.jfr.JvmProfiler;
public class JfrCommand {
private static final SimpleCommandExceptionType START_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.jfr.start.failed"));
private static final DynamicCommandExceptionType DUMP_FAILED = new DynamicCommandExceptionType((p_183652_) -> {
return Component.translatable("commands.jfr.dump.failed", p_183652_);
});
private JfrCommand() {
}
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("jfr").requires((p_183661_) -> {
return p_183661_.hasPermission(4);
}).then(Commands.literal("start").executes((p_183657_) -> {
return startJfr(p_183657_.getSource());
})).then(Commands.literal("stop").executes((p_183648_) -> {
return stopJfr(p_183648_.getSource());
})));
}
private static int startJfr(CommandSourceStack pSource) throws CommandSyntaxException {
Environment environment = Environment.from(pSource.getServer());
if (!JvmProfiler.INSTANCE.start(environment)) {
throw START_FAILED.create();
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.jfr.started");
}, false);
return 1;
}
}
private static int stopJfr(CommandSourceStack pSource) throws CommandSyntaxException {
try {
Path path = Paths.get(".").relativize(JvmProfiler.INSTANCE.stop().normalize());
Path path1 = pSource.getServer().isPublished() && !SharedConstants.IS_RUNNING_IN_IDE ? path : path.toAbsolutePath();
Component component = Component.literal(path.toString()).withStyle(ChatFormatting.UNDERLINE).withStyle((p_183655_) -> {
return p_183655_.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, path1.toString())).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("chat.copy.click")));
});
pSource.sendSuccess(() -> {
return Component.translatable("commands.jfr.stopped", component);
}, false);
return 1;
} catch (Throwable throwable) {
throw DUMP_FAILED.create(throwable.getMessage());
}
}
}
@@ -0,0 +1,33 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
public class KickCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("kick").requires((p_137800_) -> {
return p_137800_.hasPermission(3);
}).then(Commands.argument("targets", EntityArgument.players()).executes((p_137806_) -> {
return kickPlayers(p_137806_.getSource(), EntityArgument.getPlayers(p_137806_, "targets"), Component.translatable("multiplayer.disconnect.kicked"));
}).then(Commands.argument("reason", MessageArgument.message()).executes((p_137798_) -> {
return kickPlayers(p_137798_.getSource(), EntityArgument.getPlayers(p_137798_, "targets"), MessageArgument.getMessage(p_137798_, "reason"));
}))));
}
private static int kickPlayers(CommandSourceStack pSource, Collection<ServerPlayer> pPlayers, Component pReason) {
for(ServerPlayer serverplayer : pPlayers) {
serverplayer.connection.disconnect(pReason);
pSource.sendSuccess(() -> {
return Component.translatable("commands.kick.success", serverplayer.getDisplayName(), pReason);
}, true);
}
return pPlayers.size();
}
}
@@ -0,0 +1,40 @@
package net.minecraft.server.commands;
import com.google.common.collect.ImmutableList;
import com.mojang.brigadier.CommandDispatcher;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
public class KillCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("kill").requires((p_137812_) -> {
return p_137812_.hasPermission(2);
}).executes((p_137817_) -> {
return kill(p_137817_.getSource(), ImmutableList.of(p_137817_.getSource().getEntityOrException()));
}).then(Commands.argument("targets", EntityArgument.entities()).executes((p_137810_) -> {
return kill(p_137810_.getSource(), EntityArgument.getEntities(p_137810_, "targets"));
})));
}
private static int kill(CommandSourceStack pSource, Collection<? extends Entity> pTargets) {
for(Entity entity : pTargets) {
entity.kill();
}
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.kill.success.single", pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.kill.success.multiple", pTargets.size());
}, true);
}
return pTargets.size();
}
}
@@ -0,0 +1,42 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import java.util.List;
import java.util.function.Function;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.entity.player.Player;
public class ListPlayersCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("list").executes((p_137830_) -> {
return listPlayers(p_137830_.getSource());
}).then(Commands.literal("uuids").executes((p_137823_) -> {
return listPlayersWithUuids(p_137823_.getSource());
})));
}
private static int listPlayers(CommandSourceStack pSource) {
return format(pSource, Player::getDisplayName);
}
private static int listPlayersWithUuids(CommandSourceStack pSource) {
return format(pSource, (p_289283_) -> {
return Component.translatable("commands.list.nameAndId", p_289283_.getName(), p_289283_.getGameProfile().getId());
});
}
private static int format(CommandSourceStack pSource, Function<ServerPlayer, Component> pNameExtractor) {
PlayerList playerlist = pSource.getServer().getPlayerList();
List<ServerPlayer> list = playerlist.getPlayers();
Component component = ComponentUtils.formatList(list, pNameExtractor);
pSource.sendSuccess(() -> {
return Component.translatable("commands.list.players", list.size(), playerlist.getMaxPlayers(), component);
}, false);
return list.size();
}
}
@@ -0,0 +1,160 @@
package net.minecraft.server.commands;
import com.google.common.base.Stopwatch;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.datafixers.util.Pair;
import com.mojang.logging.LogUtils;
import java.time.Duration;
import java.util.Optional;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.ResourceOrTagArgument;
import net.minecraft.commands.arguments.ResourceOrTagKeyArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.ai.village.poi.PoiManager;
import net.minecraft.world.entity.ai.village.poi.PoiType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.levelgen.structure.Structure;
import org.slf4j.Logger;
public class LocateCommand {
private static final Logger LOGGER = LogUtils.getLogger();
private static final DynamicCommandExceptionType ERROR_STRUCTURE_NOT_FOUND = new DynamicCommandExceptionType((p_201831_) -> {
return Component.translatable("commands.locate.structure.not_found", p_201831_);
});
private static final DynamicCommandExceptionType ERROR_STRUCTURE_INVALID = new DynamicCommandExceptionType((p_207534_) -> {
return Component.translatable("commands.locate.structure.invalid", p_207534_);
});
private static final DynamicCommandExceptionType ERROR_BIOME_NOT_FOUND = new DynamicCommandExceptionType((p_214514_) -> {
return Component.translatable("commands.locate.biome.not_found", p_214514_);
});
private static final DynamicCommandExceptionType ERROR_POI_NOT_FOUND = new DynamicCommandExceptionType((p_214512_) -> {
return Component.translatable("commands.locate.poi.not_found", p_214512_);
});
private static final int MAX_STRUCTURE_SEARCH_RADIUS = 100;
private static final int MAX_BIOME_SEARCH_RADIUS = 6400;
private static final int BIOME_SAMPLE_RESOLUTION_HORIZONTAL = 32;
private static final int BIOME_SAMPLE_RESOLUTION_VERTICAL = 64;
private static final int POI_SEARCH_RADIUS = 256;
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("locate").requires((p_214470_) -> {
return p_214470_.hasPermission(2);
}).then(Commands.literal("structure").then(Commands.argument("structure", ResourceOrTagKeyArgument.resourceOrTagKey(Registries.STRUCTURE)).executes((p_258233_) -> {
return locateStructure(p_258233_.getSource(), ResourceOrTagKeyArgument.getResourceOrTagKey(p_258233_, "structure", Registries.STRUCTURE, ERROR_STRUCTURE_INVALID));
}))).then(Commands.literal("biome").then(Commands.argument("biome", ResourceOrTagArgument.resourceOrTag(pContext, Registries.BIOME)).executes((p_258232_) -> {
return locateBiome(p_258232_.getSource(), ResourceOrTagArgument.getResourceOrTag(p_258232_, "biome", Registries.BIOME));
}))).then(Commands.literal("poi").then(Commands.argument("poi", ResourceOrTagArgument.resourceOrTag(pContext, Registries.POINT_OF_INTEREST_TYPE)).executes((p_258234_) -> {
return locatePoi(p_258234_.getSource(), ResourceOrTagArgument.getResourceOrTag(p_258234_, "poi", Registries.POINT_OF_INTEREST_TYPE));
}))));
}
private static Optional<? extends HolderSet.ListBacked<Structure>> getHolders(ResourceOrTagKeyArgument.Result<Structure> pStructure, Registry<Structure> pStructureRegistry) {
return pStructure.unwrap().map((p_258231_) -> {
return pStructureRegistry.getHolder(p_258231_).map((p_214491_) -> {
return HolderSet.direct(p_214491_);
});
}, pStructureRegistry::getTag);
}
private static int locateStructure(CommandSourceStack pSource, ResourceOrTagKeyArgument.Result<Structure> pStructure) throws CommandSyntaxException {
Registry<Structure> registry = pSource.getLevel().registryAccess().registryOrThrow(Registries.STRUCTURE);
HolderSet<Structure> holderset = getHolders(pStructure, registry).orElseThrow(() -> {
return ERROR_STRUCTURE_INVALID.create(pStructure.asPrintable());
});
BlockPos blockpos = BlockPos.containing(pSource.getPosition());
ServerLevel serverlevel = pSource.getLevel();
Stopwatch stopwatch = Stopwatch.createStarted(Util.TICKER);
Pair<BlockPos, Holder<Structure>> pair = serverlevel.getChunkSource().getGenerator().findNearestMapStructure(serverlevel, holderset, blockpos, 100, false);
stopwatch.stop();
if (pair == null) {
throw ERROR_STRUCTURE_NOT_FOUND.create(pStructure.asPrintable());
} else {
return showLocateResult(pSource, pStructure, blockpos, pair, "commands.locate.structure.success", false, stopwatch.elapsed());
}
}
private static int locateBiome(CommandSourceStack pSource, ResourceOrTagArgument.Result<Biome> pBiome) throws CommandSyntaxException {
BlockPos blockpos = BlockPos.containing(pSource.getPosition());
Stopwatch stopwatch = Stopwatch.createStarted(Util.TICKER);
Pair<BlockPos, Holder<Biome>> pair = pSource.getLevel().findClosestBiome3d(pBiome, blockpos, 6400, 32, 64);
stopwatch.stop();
if (pair == null) {
throw ERROR_BIOME_NOT_FOUND.create(pBiome.asPrintable());
} else {
return showLocateResult(pSource, pBiome, blockpos, pair, "commands.locate.biome.success", true, stopwatch.elapsed());
}
}
private static int locatePoi(CommandSourceStack pSource, ResourceOrTagArgument.Result<PoiType> pPoiType) throws CommandSyntaxException {
BlockPos blockpos = BlockPos.containing(pSource.getPosition());
ServerLevel serverlevel = pSource.getLevel();
Stopwatch stopwatch = Stopwatch.createStarted(Util.TICKER);
Optional<Pair<Holder<PoiType>, BlockPos>> optional = serverlevel.getPoiManager().findClosestWithType(pPoiType, blockpos, 256, PoiManager.Occupancy.ANY);
stopwatch.stop();
if (optional.isEmpty()) {
throw ERROR_POI_NOT_FOUND.create(pPoiType.asPrintable());
} else {
return showLocateResult(pSource, pPoiType, blockpos, optional.get().swap(), "commands.locate.poi.success", false, stopwatch.elapsed());
}
}
private static String getElementName(Pair<BlockPos, ? extends Holder<?>> pResultWithPosition) {
return pResultWithPosition.getSecond().unwrapKey().map((p_214498_) -> {
return p_214498_.location().toString();
}).orElse("[unregistered]");
}
public static int showLocateResult(CommandSourceStack pSource, ResourceOrTagArgument.Result<?> pResult, BlockPos pSourcePosition, Pair<BlockPos, ? extends Holder<?>> pResultWithPosition, String pTranslationKey, boolean pAbsoluteY, Duration pDuration) {
String s = pResult.unwrap().map((p_248147_) -> {
return pResult.asPrintable();
}, (p_248143_) -> {
return pResult.asPrintable() + " (" + getElementName(pResultWithPosition) + ")";
});
return showLocateResult(pSource, pSourcePosition, pResultWithPosition, pTranslationKey, pAbsoluteY, s, pDuration);
}
public static int showLocateResult(CommandSourceStack pSource, ResourceOrTagKeyArgument.Result<?> pResult, BlockPos pSourcePosition, Pair<BlockPos, ? extends Holder<?>> pResultWithPosition, String pTranslationKey, boolean pAbsoluteY, Duration pDuration) {
String s = pResult.unwrap().map((p_214463_) -> {
return p_214463_.location().toString();
}, (p_248145_) -> {
return "#" + p_248145_.location() + " (" + getElementName(pResultWithPosition) + ")";
});
return showLocateResult(pSource, pSourcePosition, pResultWithPosition, pTranslationKey, pAbsoluteY, s, pDuration);
}
private static int showLocateResult(CommandSourceStack pSource, BlockPos pSourcePosition, Pair<BlockPos, ? extends Holder<?>> pResultWithoutPosition, String pTranslationKey, boolean pAbsoluteY, String pElementName, Duration pDuration) {
BlockPos blockpos = pResultWithoutPosition.getFirst();
int i = pAbsoluteY ? Mth.floor(Mth.sqrt((float)pSourcePosition.distSqr(blockpos))) : Mth.floor(dist(pSourcePosition.getX(), pSourcePosition.getZ(), blockpos.getX(), blockpos.getZ()));
String s = pAbsoluteY ? String.valueOf(blockpos.getY()) : "~";
Component component = ComponentUtils.wrapInSquareBrackets(Component.translatable("chat.coordinates", blockpos.getX(), s, blockpos.getZ())).withStyle((p_214489_) -> {
return p_214489_.withColor(ChatFormatting.GREEN).withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/tp @s " + blockpos.getX() + " " + s + " " + blockpos.getZ())).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("chat.coordinates.tooltip")));
});
pSource.sendSuccess(() -> {
return Component.translatable(pTranslationKey, pElementName, component, i);
}, false);
LOGGER.info("Locating element " + pElementName + " took " + pDuration.toMillis() + " ms");
return i;
}
private static float dist(int pX1, int pZ1, int pX2, int pZ2) {
int i = pX2 - pX1;
int j = pZ2 - pZ1;
return Mth.sqrt((float)(i * i + j * j));
}
}
@@ -0,0 +1,343 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Collection;
import java.util.List;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.SlotArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.commands.arguments.item.ItemArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.Container;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.SlotAccess;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.storage.loot.LootDataType;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.Vec3;
public class LootCommand {
public static final SuggestionProvider<CommandSourceStack> SUGGEST_LOOT_TABLE = (p_278916_, p_278917_) -> {
LootDataManager lootdatamanager = p_278916_.getSource().getServer().getLootData();
return SharedSuggestionProvider.suggestResource(lootdatamanager.getKeys(LootDataType.TABLE), p_278917_);
};
private static final DynamicCommandExceptionType ERROR_NO_HELD_ITEMS = new DynamicCommandExceptionType((p_137999_) -> {
return Component.translatable("commands.drop.no_held_items", p_137999_);
});
private static final DynamicCommandExceptionType ERROR_NO_LOOT_TABLE = new DynamicCommandExceptionType((p_137977_) -> {
return Component.translatable("commands.drop.no_loot_table", p_137977_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(addTargets(Commands.literal("loot").requires((p_137937_) -> {
return p_137937_.hasPermission(2);
}), (p_214520_, p_214521_) -> {
return p_214520_.then(Commands.literal("fish").then(Commands.argument("loot_table", ResourceLocationArgument.id()).suggests(SUGGEST_LOOT_TABLE).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_180421_) -> {
return dropFishingLoot(p_180421_, ResourceLocationArgument.getId(p_180421_, "loot_table"), BlockPosArgument.getLoadedBlockPos(p_180421_, "pos"), ItemStack.EMPTY, p_214521_);
}).then(Commands.argument("tool", ItemArgument.item(pContext)).executes((p_180418_) -> {
return dropFishingLoot(p_180418_, ResourceLocationArgument.getId(p_180418_, "loot_table"), BlockPosArgument.getLoadedBlockPos(p_180418_, "pos"), ItemArgument.getItem(p_180418_, "tool").createItemStack(1, false), p_214521_);
})).then(Commands.literal("mainhand").executes((p_180415_) -> {
return dropFishingLoot(p_180415_, ResourceLocationArgument.getId(p_180415_, "loot_table"), BlockPosArgument.getLoadedBlockPos(p_180415_, "pos"), getSourceHandItem(p_180415_.getSource(), EquipmentSlot.MAINHAND), p_214521_);
})).then(Commands.literal("offhand").executes((p_180412_) -> {
return dropFishingLoot(p_180412_, ResourceLocationArgument.getId(p_180412_, "loot_table"), BlockPosArgument.getLoadedBlockPos(p_180412_, "pos"), getSourceHandItem(p_180412_.getSource(), EquipmentSlot.OFFHAND), p_214521_);
}))))).then(Commands.literal("loot").then(Commands.argument("loot_table", ResourceLocationArgument.id()).suggests(SUGGEST_LOOT_TABLE).executes((p_180409_) -> {
return dropChestLoot(p_180409_, ResourceLocationArgument.getId(p_180409_, "loot_table"), p_214521_);
}))).then(Commands.literal("kill").then(Commands.argument("target", EntityArgument.entity()).executes((p_180406_) -> {
return dropKillLoot(p_180406_, EntityArgument.getEntity(p_180406_, "target"), p_214521_);
}))).then(Commands.literal("mine").then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_180403_) -> {
return dropBlockLoot(p_180403_, BlockPosArgument.getLoadedBlockPos(p_180403_, "pos"), ItemStack.EMPTY, p_214521_);
}).then(Commands.argument("tool", ItemArgument.item(pContext)).executes((p_180400_) -> {
return dropBlockLoot(p_180400_, BlockPosArgument.getLoadedBlockPos(p_180400_, "pos"), ItemArgument.getItem(p_180400_, "tool").createItemStack(1, false), p_214521_);
})).then(Commands.literal("mainhand").executes((p_180397_) -> {
return dropBlockLoot(p_180397_, BlockPosArgument.getLoadedBlockPos(p_180397_, "pos"), getSourceHandItem(p_180397_.getSource(), EquipmentSlot.MAINHAND), p_214521_);
})).then(Commands.literal("offhand").executes((p_180394_) -> {
return dropBlockLoot(p_180394_, BlockPosArgument.getLoadedBlockPos(p_180394_, "pos"), getSourceHandItem(p_180394_.getSource(), EquipmentSlot.OFFHAND), p_214521_);
}))));
}));
}
private static <T extends ArgumentBuilder<CommandSourceStack, T>> T addTargets(T p_137903_, LootCommand.TailProvider p_137904_) {
return p_137903_.then(Commands.literal("replace").then(Commands.literal("entity").then(Commands.argument("entities", EntityArgument.entities()).then(p_137904_.construct(Commands.argument("slot", SlotArgument.slot()), (p_138032_, p_138033_, p_138034_) -> {
return entityReplace(EntityArgument.getEntities(p_138032_, "entities"), SlotArgument.getSlot(p_138032_, "slot"), p_138033_.size(), p_138033_, p_138034_);
}).then(p_137904_.construct(Commands.argument("count", IntegerArgumentType.integer(0)), (p_138025_, p_138026_, p_138027_) -> {
return entityReplace(EntityArgument.getEntities(p_138025_, "entities"), SlotArgument.getSlot(p_138025_, "slot"), IntegerArgumentType.getInteger(p_138025_, "count"), p_138026_, p_138027_);
}))))).then(Commands.literal("block").then(Commands.argument("targetPos", BlockPosArgument.blockPos()).then(p_137904_.construct(Commands.argument("slot", SlotArgument.slot()), (p_138018_, p_138019_, p_138020_) -> {
return blockReplace(p_138018_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138018_, "targetPos"), SlotArgument.getSlot(p_138018_, "slot"), p_138019_.size(), p_138019_, p_138020_);
}).then(p_137904_.construct(Commands.argument("count", IntegerArgumentType.integer(0)), (p_138011_, p_138012_, p_138013_) -> {
return blockReplace(p_138011_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138011_, "targetPos"), IntegerArgumentType.getInteger(p_138011_, "slot"), IntegerArgumentType.getInteger(p_138011_, "count"), p_138012_, p_138013_);
})))))).then(Commands.literal("insert").then(p_137904_.construct(Commands.argument("targetPos", BlockPosArgument.blockPos()), (p_138004_, p_138005_, p_138006_) -> {
return blockDistribute(p_138004_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138004_, "targetPos"), p_138005_, p_138006_);
}))).then(Commands.literal("give").then(p_137904_.construct(Commands.argument("players", EntityArgument.players()), (p_137992_, p_137993_, p_137994_) -> {
return playerGive(EntityArgument.getPlayers(p_137992_, "players"), p_137993_, p_137994_);
}))).then(Commands.literal("spawn").then(p_137904_.construct(Commands.argument("targetPos", Vec3Argument.vec3()), (p_137918_, p_137919_, p_137920_) -> {
return dropInWorld(p_137918_.getSource(), Vec3Argument.getVec3(p_137918_, "targetPos"), p_137919_, p_137920_);
})));
}
private static Container getContainer(CommandSourceStack pSource, BlockPos pPos) throws CommandSyntaxException {
BlockEntity blockentity = pSource.getLevel().getBlockEntity(pPos);
if (!(blockentity instanceof Container)) {
throw ItemCommands.ERROR_TARGET_NOT_A_CONTAINER.create(pPos.getX(), pPos.getY(), pPos.getZ());
} else {
return (Container)blockentity;
}
}
private static int blockDistribute(CommandSourceStack pSource, BlockPos pPos, List<ItemStack> pItems, LootCommand.Callback pCallback) throws CommandSyntaxException {
Container container = getContainer(pSource, pPos);
List<ItemStack> list = Lists.newArrayListWithCapacity(pItems.size());
for(ItemStack itemstack : pItems) {
if (distributeToContainer(container, itemstack.copy())) {
container.setChanged();
list.add(itemstack);
}
}
pCallback.accept(list);
return list.size();
}
private static boolean distributeToContainer(Container pContainer, ItemStack pItem) {
boolean flag = false;
for(int i = 0; i < pContainer.getContainerSize() && !pItem.isEmpty(); ++i) {
ItemStack itemstack = pContainer.getItem(i);
if (pContainer.canPlaceItem(i, pItem)) {
if (itemstack.isEmpty()) {
pContainer.setItem(i, pItem);
flag = true;
break;
}
if (canMergeItems(itemstack, pItem)) {
int j = pItem.getMaxStackSize() - itemstack.getCount();
int k = Math.min(pItem.getCount(), j);
pItem.shrink(k);
itemstack.grow(k);
flag = true;
}
}
}
return flag;
}
private static int blockReplace(CommandSourceStack pSource, BlockPos pPos, int pSlot, int p_137957_, List<ItemStack> pItems, LootCommand.Callback pCallback) throws CommandSyntaxException {
Container container = getContainer(pSource, pPos);
int i = container.getContainerSize();
if (pSlot >= 0 && pSlot < i) {
List<ItemStack> list = Lists.newArrayListWithCapacity(pItems.size());
for(int j = 0; j < p_137957_; ++j) {
int k = pSlot + j;
ItemStack itemstack = j < pItems.size() ? pItems.get(j) : ItemStack.EMPTY;
if (container.canPlaceItem(k, itemstack)) {
container.setItem(k, itemstack);
list.add(itemstack);
}
}
pCallback.accept(list);
return list.size();
} else {
throw ItemCommands.ERROR_TARGET_INAPPLICABLE_SLOT.create(pSlot);
}
}
private static boolean canMergeItems(ItemStack pFirst, ItemStack pSecond) {
return pFirst.getCount() <= pFirst.getMaxStackSize() && ItemStack.isSameItemSameTags(pFirst, pSecond);
}
private static int playerGive(Collection<ServerPlayer> pTargets, List<ItemStack> pItems, LootCommand.Callback pCallback) throws CommandSyntaxException {
List<ItemStack> list = Lists.newArrayListWithCapacity(pItems.size());
for(ItemStack itemstack : pItems) {
for(ServerPlayer serverplayer : pTargets) {
if (serverplayer.getInventory().add(itemstack.copy())) {
list.add(itemstack);
}
}
}
pCallback.accept(list);
return list.size();
}
private static void setSlots(Entity pTarget, List<ItemStack> pItems, int pStartSlot, int p_137892_, List<ItemStack> p_137893_) {
for(int i = 0; i < p_137892_; ++i) {
ItemStack itemstack = i < pItems.size() ? pItems.get(i) : ItemStack.EMPTY;
SlotAccess slotaccess = pTarget.getSlot(pStartSlot + i);
if (slotaccess != SlotAccess.NULL && slotaccess.set(itemstack.copy())) {
p_137893_.add(itemstack);
}
}
}
private static int entityReplace(Collection<? extends Entity> pTargets, int pStartSlot, int p_137981_, List<ItemStack> pItems, LootCommand.Callback pCallback) throws CommandSyntaxException {
List<ItemStack> list = Lists.newArrayListWithCapacity(pItems.size());
for(Entity entity : pTargets) {
if (entity instanceof ServerPlayer serverplayer) {
setSlots(entity, pItems, pStartSlot, p_137981_, list);
serverplayer.containerMenu.broadcastChanges();
} else {
setSlots(entity, pItems, pStartSlot, p_137981_, list);
}
}
pCallback.accept(list);
return list.size();
}
private static int dropInWorld(CommandSourceStack pSource, Vec3 pPos, List<ItemStack> pItems, LootCommand.Callback pCallback) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
pItems.forEach((p_137884_) -> {
ItemEntity itementity = new ItemEntity(serverlevel, pPos.x, pPos.y, pPos.z, p_137884_.copy());
itementity.setDefaultPickUpDelay();
serverlevel.addFreshEntity(itementity);
});
pCallback.accept(pItems);
return pItems.size();
}
private static void callback(CommandSourceStack pSource, List<ItemStack> pItems) {
if (pItems.size() == 1) {
ItemStack itemstack = pItems.get(0);
pSource.sendSuccess(() -> {
return Component.translatable("commands.drop.success.single", itemstack.getCount(), itemstack.getDisplayName());
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.drop.success.multiple", pItems.size());
}, false);
}
}
private static void callback(CommandSourceStack pSource, List<ItemStack> pItems, ResourceLocation pLootTable) {
if (pItems.size() == 1) {
ItemStack itemstack = pItems.get(0);
pSource.sendSuccess(() -> {
return Component.translatable("commands.drop.success.single_with_table", itemstack.getCount(), itemstack.getDisplayName(), pLootTable);
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.drop.success.multiple_with_table", pItems.size(), pLootTable);
}, false);
}
}
private static ItemStack getSourceHandItem(CommandSourceStack pSource, EquipmentSlot pSlot) throws CommandSyntaxException {
Entity entity = pSource.getEntityOrException();
if (entity instanceof LivingEntity) {
return ((LivingEntity)entity).getItemBySlot(pSlot);
} else {
throw ERROR_NO_HELD_ITEMS.create(entity.getDisplayName());
}
}
private static int dropBlockLoot(CommandContext<CommandSourceStack> pContext, BlockPos pPos, ItemStack p_137915_, LootCommand.DropConsumer pDropConsumer) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = pContext.getSource();
ServerLevel serverlevel = commandsourcestack.getLevel();
BlockState blockstate = serverlevel.getBlockState(pPos);
BlockEntity blockentity = serverlevel.getBlockEntity(pPos);
LootParams.Builder lootparams$builder = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pPos)).withParameter(LootContextParams.BLOCK_STATE, blockstate).withOptionalParameter(LootContextParams.BLOCK_ENTITY, blockentity).withOptionalParameter(LootContextParams.THIS_ENTITY, commandsourcestack.getEntity()).withParameter(LootContextParams.TOOL, p_137915_);
List<ItemStack> list = blockstate.getDrops(lootparams$builder);
return pDropConsumer.accept(pContext, list, (p_278915_) -> {
callback(commandsourcestack, p_278915_, blockstate.getBlock().getLootTable());
});
}
private static int dropKillLoot(CommandContext<CommandSourceStack> pContext, Entity pEntity, LootCommand.DropConsumer pDropConsumer) throws CommandSyntaxException {
if (!(pEntity instanceof LivingEntity)) {
throw ERROR_NO_LOOT_TABLE.create(pEntity.getDisplayName());
} else {
ResourceLocation resourcelocation = ((LivingEntity)pEntity).getLootTable();
CommandSourceStack commandsourcestack = pContext.getSource();
LootParams.Builder lootparams$builder = new LootParams.Builder(commandsourcestack.getLevel());
Entity entity = commandsourcestack.getEntity();
if (entity instanceof Player) {
Player player = (Player)entity;
lootparams$builder.withParameter(LootContextParams.LAST_DAMAGE_PLAYER, player);
}
lootparams$builder.withParameter(LootContextParams.DAMAGE_SOURCE, pEntity.damageSources().magic());
lootparams$builder.withOptionalParameter(LootContextParams.DIRECT_KILLER_ENTITY, entity);
lootparams$builder.withOptionalParameter(LootContextParams.KILLER_ENTITY, entity);
lootparams$builder.withParameter(LootContextParams.THIS_ENTITY, pEntity);
lootparams$builder.withParameter(LootContextParams.ORIGIN, commandsourcestack.getPosition());
LootParams lootparams = lootparams$builder.create(LootContextParamSets.ENTITY);
LootTable loottable = commandsourcestack.getServer().getLootData().getLootTable(resourcelocation);
List<ItemStack> list = loottable.getRandomItems(lootparams);
return pDropConsumer.accept(pContext, list, (p_137975_) -> {
callback(commandsourcestack, p_137975_, resourcelocation);
});
}
}
private static int dropChestLoot(CommandContext<CommandSourceStack> pContext, ResourceLocation pLootTable, LootCommand.DropConsumer pDropConsumer) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = pContext.getSource();
LootParams lootparams = (new LootParams.Builder(commandsourcestack.getLevel())).withOptionalParameter(LootContextParams.THIS_ENTITY, commandsourcestack.getEntity()).withParameter(LootContextParams.ORIGIN, commandsourcestack.getPosition()).create(LootContextParamSets.CHEST);
return drop(pContext, pLootTable, lootparams, pDropConsumer);
}
private static int dropFishingLoot(CommandContext<CommandSourceStack> pContext, ResourceLocation pLootTable, BlockPos p_137929_, ItemStack p_137930_, LootCommand.DropConsumer pDropConsumer) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = pContext.getSource();
LootParams lootparams = (new LootParams.Builder(commandsourcestack.getLevel())).withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(p_137929_)).withParameter(LootContextParams.TOOL, p_137930_).withOptionalParameter(LootContextParams.THIS_ENTITY, commandsourcestack.getEntity()).create(LootContextParamSets.FISHING);
return drop(pContext, pLootTable, lootparams, pDropConsumer);
}
private static int drop(CommandContext<CommandSourceStack> pContext, ResourceLocation pLootTable, LootParams pParams, LootCommand.DropConsumer pDropConsumer) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = pContext.getSource();
LootTable loottable = commandsourcestack.getServer().getLootData().getLootTable(pLootTable);
List<ItemStack> list = loottable.getRandomItems(pParams);
return pDropConsumer.accept(pContext, list, (p_137997_) -> {
callback(commandsourcestack, p_137997_);
});
}
@FunctionalInterface
interface Callback {
void accept(List<ItemStack> pItems) throws CommandSyntaxException;
}
@FunctionalInterface
interface DropConsumer {
int accept(CommandContext<CommandSourceStack> pContext, List<ItemStack> pItems, LootCommand.Callback pCallback) throws CommandSyntaxException;
}
@FunctionalInterface
interface TailProvider {
ArgumentBuilder<CommandSourceStack, ?> construct(ArgumentBuilder<CommandSourceStack, ?> p_138054_, LootCommand.DropConsumer pDropConsumer);
}
}
@@ -0,0 +1,50 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.LiteralCommandNode;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.OutgoingChatMessage;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
public class MsgCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
LiteralCommandNode<CommandSourceStack> literalcommandnode = pDispatcher.register(Commands.literal("msg").then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("message", MessageArgument.message()).executes((p_248155_) -> {
Collection<ServerPlayer> collection = EntityArgument.getPlayers(p_248155_, "targets");
if (!collection.isEmpty()) {
MessageArgument.resolveChatMessage(p_248155_, "message", (p_248154_) -> {
sendMessage(p_248155_.getSource(), collection, p_248154_);
});
}
return collection.size();
}))));
pDispatcher.register(Commands.literal("tell").redirect(literalcommandnode));
pDispatcher.register(Commands.literal("w").redirect(literalcommandnode));
}
private static void sendMessage(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, PlayerChatMessage pMessage) {
ChatType.Bound chattype$bound = ChatType.bind(ChatType.MSG_COMMAND_INCOMING, pSource);
OutgoingChatMessage outgoingchatmessage = OutgoingChatMessage.create(pMessage);
boolean flag = false;
for(ServerPlayer serverplayer : pTargets) {
ChatType.Bound chattype$bound1 = ChatType.bind(ChatType.MSG_COMMAND_OUTGOING, pSource).withTargetName(serverplayer.getDisplayName());
pSource.sendChatMessage(outgoingchatmessage, false, chattype$bound1);
boolean flag1 = pSource.shouldFilterMessageTo(serverplayer);
serverplayer.sendChatMessage(outgoingchatmessage, flag1, chattype$bound);
flag |= flag1 && pMessage.isFullyFiltered();
}
if (flag) {
pSource.sendSystemMessage(PlayerList.CHAT_FILTERED_FULL);
}
}
}
@@ -0,0 +1,53 @@
package net.minecraft.server.commands;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.GameProfileArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.players.PlayerList;
public class OpCommand {
private static final SimpleCommandExceptionType ERROR_ALREADY_OP = new SimpleCommandExceptionType(Component.translatable("commands.op.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("op").requires((p_138087_) -> {
return p_138087_.hasPermission(3);
}).then(Commands.argument("targets", GameProfileArgument.gameProfile()).suggests((p_138084_, p_138085_) -> {
PlayerList playerlist = p_138084_.getSource().getServer().getPlayerList();
return SharedSuggestionProvider.suggest(playerlist.getPlayers().stream().filter((p_289286_) -> {
return !playerlist.isOp(p_289286_.getGameProfile());
}).map((p_289284_) -> {
return p_289284_.getGameProfile().getName();
}), p_138085_);
}).executes((p_138082_) -> {
return opPlayers(p_138082_.getSource(), GameProfileArgument.getGameProfiles(p_138082_, "targets"));
})));
}
private static int opPlayers(CommandSourceStack pSource, Collection<GameProfile> pGameProfiles) throws CommandSyntaxException {
PlayerList playerlist = pSource.getServer().getPlayerList();
int i = 0;
for(GameProfile gameprofile : pGameProfiles) {
if (!playerlist.isOp(gameprofile)) {
playerlist.op(gameprofile);
++i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.op.success", pGameProfiles.iterator().next().getName());
}, true);
}
}
if (i == 0) {
throw ERROR_ALREADY_OP.create();
} else {
return i;
}
}
}
@@ -0,0 +1,49 @@
package net.minecraft.server.commands;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.GameProfileArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.server.players.UserBanList;
public class PardonCommand {
private static final SimpleCommandExceptionType ERROR_NOT_BANNED = new SimpleCommandExceptionType(Component.translatable("commands.pardon.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("pardon").requires((p_138101_) -> {
return p_138101_.hasPermission(3);
}).then(Commands.argument("targets", GameProfileArgument.gameProfile()).suggests((p_138098_, p_138099_) -> {
return SharedSuggestionProvider.suggest(p_138098_.getSource().getServer().getPlayerList().getBans().getUserList(), p_138099_);
}).executes((p_138096_) -> {
return pardonPlayers(p_138096_.getSource(), GameProfileArgument.getGameProfiles(p_138096_, "targets"));
})));
}
private static int pardonPlayers(CommandSourceStack pSource, Collection<GameProfile> pGameProfiles) throws CommandSyntaxException {
UserBanList userbanlist = pSource.getServer().getPlayerList().getBans();
int i = 0;
for(GameProfile gameprofile : pGameProfiles) {
if (userbanlist.isBanned(gameprofile)) {
userbanlist.remove(gameprofile);
++i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.pardon.success", ComponentUtils.getDisplayName(gameprofile));
}, true);
}
}
if (i == 0) {
throw ERROR_NOT_BANNED.create();
} else {
return i;
}
}
}
@@ -0,0 +1,44 @@
package net.minecraft.server.commands;
import com.google.common.net.InetAddresses;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.server.players.IpBanList;
public class PardonIpCommand {
private static final SimpleCommandExceptionType ERROR_INVALID = new SimpleCommandExceptionType(Component.translatable("commands.pardonip.invalid"));
private static final SimpleCommandExceptionType ERROR_NOT_BANNED = new SimpleCommandExceptionType(Component.translatable("commands.pardonip.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("pardon-ip").requires((p_138116_) -> {
return p_138116_.hasPermission(3);
}).then(Commands.argument("target", StringArgumentType.word()).suggests((p_138113_, p_138114_) -> {
return SharedSuggestionProvider.suggest(p_138113_.getSource().getServer().getPlayerList().getIpBans().getUserList(), p_138114_);
}).executes((p_138111_) -> {
return unban(p_138111_.getSource(), StringArgumentType.getString(p_138111_, "target"));
})));
}
private static int unban(CommandSourceStack pSource, String pIpAddress) throws CommandSyntaxException {
if (!InetAddresses.isInetAddress(pIpAddress)) {
throw ERROR_INVALID.create();
} else {
IpBanList ipbanlist = pSource.getServer().getPlayerList().getIpBans();
if (!ipbanlist.isBanned(pIpAddress)) {
throw ERROR_NOT_BANNED.create();
} else {
ipbanlist.remove(pIpAddress);
pSource.sendSuccess(() -> {
return Component.translatable("commands.pardonip.success", pIpAddress);
}, true);
return 1;
}
}
}
}
@@ -0,0 +1,62 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ParticleArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.phys.Vec3;
public class ParticleCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.particle.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("particle").requires((p_138127_) -> {
return p_138127_.hasPermission(2);
}).then(Commands.argument("name", ParticleArgument.particle(pContext)).executes((p_138148_) -> {
return sendParticles(p_138148_.getSource(), ParticleArgument.getParticle(p_138148_, "name"), p_138148_.getSource().getPosition(), Vec3.ZERO, 0.0F, 0, false, p_138148_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("pos", Vec3Argument.vec3()).executes((p_138146_) -> {
return sendParticles(p_138146_.getSource(), ParticleArgument.getParticle(p_138146_, "name"), Vec3Argument.getVec3(p_138146_, "pos"), Vec3.ZERO, 0.0F, 0, false, p_138146_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("delta", Vec3Argument.vec3(false)).then(Commands.argument("speed", FloatArgumentType.floatArg(0.0F)).then(Commands.argument("count", IntegerArgumentType.integer(0)).executes((p_138144_) -> {
return sendParticles(p_138144_.getSource(), ParticleArgument.getParticle(p_138144_, "name"), Vec3Argument.getVec3(p_138144_, "pos"), Vec3Argument.getVec3(p_138144_, "delta"), FloatArgumentType.getFloat(p_138144_, "speed"), IntegerArgumentType.getInteger(p_138144_, "count"), false, p_138144_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.literal("force").executes((p_138142_) -> {
return sendParticles(p_138142_.getSource(), ParticleArgument.getParticle(p_138142_, "name"), Vec3Argument.getVec3(p_138142_, "pos"), Vec3Argument.getVec3(p_138142_, "delta"), FloatArgumentType.getFloat(p_138142_, "speed"), IntegerArgumentType.getInteger(p_138142_, "count"), true, p_138142_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("viewers", EntityArgument.players()).executes((p_138140_) -> {
return sendParticles(p_138140_.getSource(), ParticleArgument.getParticle(p_138140_, "name"), Vec3Argument.getVec3(p_138140_, "pos"), Vec3Argument.getVec3(p_138140_, "delta"), FloatArgumentType.getFloat(p_138140_, "speed"), IntegerArgumentType.getInteger(p_138140_, "count"), true, EntityArgument.getPlayers(p_138140_, "viewers"));
}))).then(Commands.literal("normal").executes((p_138138_) -> {
return sendParticles(p_138138_.getSource(), ParticleArgument.getParticle(p_138138_, "name"), Vec3Argument.getVec3(p_138138_, "pos"), Vec3Argument.getVec3(p_138138_, "delta"), FloatArgumentType.getFloat(p_138138_, "speed"), IntegerArgumentType.getInteger(p_138138_, "count"), false, p_138138_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("viewers", EntityArgument.players()).executes((p_138125_) -> {
return sendParticles(p_138125_.getSource(), ParticleArgument.getParticle(p_138125_, "name"), Vec3Argument.getVec3(p_138125_, "pos"), Vec3Argument.getVec3(p_138125_, "delta"), FloatArgumentType.getFloat(p_138125_, "speed"), IntegerArgumentType.getInteger(p_138125_, "count"), false, EntityArgument.getPlayers(p_138125_, "viewers"));
})))))))));
}
private static int sendParticles(CommandSourceStack pSource, ParticleOptions pParticleData, Vec3 pPos, Vec3 pDelta, float pSpeed, int pCount, boolean pForce, Collection<ServerPlayer> pViewers) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : pViewers) {
if (pSource.getLevel().sendParticles(serverplayer, pParticleData, pForce, pPos.x, pPos.y, pPos.z, pCount, pDelta.x, pDelta.y, pDelta.z, (double)pSpeed)) {
++i;
}
}
if (i == 0) {
throw ERROR_FAILED.create();
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.particle.success", BuiltInRegistries.PARTICLE_TYPE.getKey(pParticleData.getType()).toString());
}, true);
return i;
}
}
}
@@ -0,0 +1,109 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.function.Consumer;
import net.minecraft.FileUtil;
import net.minecraft.SharedConstants;
import net.minecraft.SystemReport;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.FileZipper;
import net.minecraft.util.TimeUtil;
import net.minecraft.util.profiling.EmptyProfileResults;
import net.minecraft.util.profiling.ProfileResults;
import net.minecraft.util.profiling.metrics.storage.MetricsPersister;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
public class PerfCommand {
private static final Logger LOGGER = LogUtils.getLogger();
private static final SimpleCommandExceptionType ERROR_NOT_RUNNING = new SimpleCommandExceptionType(Component.translatable("commands.perf.notRunning"));
private static final SimpleCommandExceptionType ERROR_ALREADY_RUNNING = new SimpleCommandExceptionType(Component.translatable("commands.perf.alreadyRunning"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("perf").requires((p_180462_) -> {
return p_180462_.hasPermission(4);
}).then(Commands.literal("start").executes((p_180455_) -> {
return startProfilingDedicatedServer(p_180455_.getSource());
})).then(Commands.literal("stop").executes((p_180440_) -> {
return stopProfilingDedicatedServer(p_180440_.getSource());
})));
}
private static int startProfilingDedicatedServer(CommandSourceStack pSource) throws CommandSyntaxException {
MinecraftServer minecraftserver = pSource.getServer();
if (minecraftserver.isRecordingMetrics()) {
throw ERROR_ALREADY_RUNNING.create();
} else {
Consumer<ProfileResults> consumer = (p_180460_) -> {
whenStopped(pSource, p_180460_);
};
Consumer<Path> consumer1 = (p_180453_) -> {
saveResults(pSource, p_180453_, minecraftserver);
};
minecraftserver.startRecordingMetrics(consumer, consumer1);
pSource.sendSuccess(() -> {
return Component.translatable("commands.perf.started");
}, false);
return 0;
}
}
private static int stopProfilingDedicatedServer(CommandSourceStack pSource) throws CommandSyntaxException {
MinecraftServer minecraftserver = pSource.getServer();
if (!minecraftserver.isRecordingMetrics()) {
throw ERROR_NOT_RUNNING.create();
} else {
minecraftserver.finishRecordingMetrics();
return 0;
}
}
private static void saveResults(CommandSourceStack pSource, Path pPath, MinecraftServer pServer) {
String s = String.format(Locale.ROOT, "%s-%s-%s", Util.getFilenameFormattedDateTime(), pServer.getWorldData().getLevelName(), SharedConstants.getCurrentVersion().getId());
String s1;
try {
s1 = FileUtil.findAvailableName(MetricsPersister.PROFILING_RESULTS_DIR, s, ".zip");
} catch (IOException ioexception1) {
pSource.sendFailure(Component.translatable("commands.perf.reportFailed"));
LOGGER.error("Failed to create report name", (Throwable)ioexception1);
return;
}
try (FileZipper filezipper = new FileZipper(MetricsPersister.PROFILING_RESULTS_DIR.resolve(s1))) {
filezipper.add(Paths.get("system.txt"), pServer.fillSystemReport(new SystemReport()).toLineSeparatedString());
filezipper.add(pPath);
}
try {
FileUtils.forceDelete(pPath.toFile());
} catch (IOException ioexception) {
LOGGER.warn("Failed to delete temporary profiling file {}", pPath, ioexception);
}
pSource.sendSuccess(() -> {
return Component.translatable("commands.perf.reportSaved", s1);
}, false);
}
private static void whenStopped(CommandSourceStack pSource, ProfileResults pResults) {
if (pResults != EmptyProfileResults.EMPTY) {
int i = pResults.getTickDuration();
double d0 = (double)pResults.getNanoDuration() / (double)TimeUtil.NANOSECONDS_PER_SECOND;
pSource.sendSuccess(() -> {
return Component.translatable("commands.perf.stopped", String.format(Locale.ROOT, "%.2f", d0), i, String.format(Locale.ROOT, "%.2f", (double)i / d0));
}, false);
}
}
}
@@ -0,0 +1,179 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Optional;
import net.minecraft.ResourceLocationException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.ResourceKeyArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.TemplateMirrorArgument;
import net.minecraft.commands.arguments.TemplateRotationArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.SectionPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.entity.StructureBlockEntity;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.pools.JigsawPlacement;
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
import net.minecraft.world.level.levelgen.structure.templatesystem.BlockRotProcessor;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
public class PlaceCommand {
private static final SimpleCommandExceptionType ERROR_FEATURE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.place.feature.failed"));
private static final SimpleCommandExceptionType ERROR_JIGSAW_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.place.jigsaw.failed"));
private static final SimpleCommandExceptionType ERROR_STRUCTURE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.place.structure.failed"));
private static final DynamicCommandExceptionType ERROR_TEMPLATE_INVALID = new DynamicCommandExceptionType((p_214582_) -> {
return Component.translatable("commands.place.template.invalid", p_214582_);
});
private static final SimpleCommandExceptionType ERROR_TEMPLATE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.place.template.failed"));
private static final SuggestionProvider<CommandSourceStack> SUGGEST_TEMPLATES = (p_214552_, p_214553_) -> {
StructureTemplateManager structuretemplatemanager = p_214552_.getSource().getLevel().getStructureManager();
return SharedSuggestionProvider.suggestResource(structuretemplatemanager.listTemplates(), p_214553_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("place").requires((p_214560_) -> {
return p_214560_.hasPermission(2);
}).then(Commands.literal("feature").then(Commands.argument("feature", ResourceKeyArgument.key(Registries.CONFIGURED_FEATURE)).executes((p_274824_) -> {
return placeFeature(p_274824_.getSource(), ResourceKeyArgument.getConfiguredFeature(p_274824_, "feature"), BlockPos.containing(p_274824_.getSource().getPosition()));
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_248163_) -> {
return placeFeature(p_248163_.getSource(), ResourceKeyArgument.getConfiguredFeature(p_248163_, "feature"), BlockPosArgument.getLoadedBlockPos(p_248163_, "pos"));
})))).then(Commands.literal("jigsaw").then(Commands.argument("pool", ResourceKeyArgument.key(Registries.TEMPLATE_POOL)).then(Commands.argument("target", ResourceLocationArgument.id()).then(Commands.argument("max_depth", IntegerArgumentType.integer(1, 7)).executes((p_274825_) -> {
return placeJigsaw(p_274825_.getSource(), ResourceKeyArgument.getStructureTemplatePool(p_274825_, "pool"), ResourceLocationArgument.getId(p_274825_, "target"), IntegerArgumentType.getInteger(p_274825_, "max_depth"), BlockPos.containing(p_274825_.getSource().getPosition()));
}).then(Commands.argument("position", BlockPosArgument.blockPos()).executes((p_248167_) -> {
return placeJigsaw(p_248167_.getSource(), ResourceKeyArgument.getStructureTemplatePool(p_248167_, "pool"), ResourceLocationArgument.getId(p_248167_, "target"), IntegerArgumentType.getInteger(p_248167_, "max_depth"), BlockPosArgument.getLoadedBlockPos(p_248167_, "position"));
})))))).then(Commands.literal("structure").then(Commands.argument("structure", ResourceKeyArgument.key(Registries.STRUCTURE)).executes((p_274826_) -> {
return placeStructure(p_274826_.getSource(), ResourceKeyArgument.getStructure(p_274826_, "structure"), BlockPos.containing(p_274826_.getSource().getPosition()));
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_248168_) -> {
return placeStructure(p_248168_.getSource(), ResourceKeyArgument.getStructure(p_248168_, "structure"), BlockPosArgument.getLoadedBlockPos(p_248168_, "pos"));
})))).then(Commands.literal("template").then(Commands.argument("template", ResourceLocationArgument.id()).suggests(SUGGEST_TEMPLATES).executes((p_274827_) -> {
return placeTemplate(p_274827_.getSource(), ResourceLocationArgument.getId(p_274827_, "template"), BlockPos.containing(p_274827_.getSource().getPosition()), Rotation.NONE, Mirror.NONE, 1.0F, 0);
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_214596_) -> {
return placeTemplate(p_214596_.getSource(), ResourceLocationArgument.getId(p_214596_, "template"), BlockPosArgument.getLoadedBlockPos(p_214596_, "pos"), Rotation.NONE, Mirror.NONE, 1.0F, 0);
}).then(Commands.argument("rotation", TemplateRotationArgument.templateRotation()).executes((p_214594_) -> {
return placeTemplate(p_214594_.getSource(), ResourceLocationArgument.getId(p_214594_, "template"), BlockPosArgument.getLoadedBlockPos(p_214594_, "pos"), TemplateRotationArgument.getRotation(p_214594_, "rotation"), Mirror.NONE, 1.0F, 0);
}).then(Commands.argument("mirror", TemplateMirrorArgument.templateMirror()).executes((p_214592_) -> {
return placeTemplate(p_214592_.getSource(), ResourceLocationArgument.getId(p_214592_, "template"), BlockPosArgument.getLoadedBlockPos(p_214592_, "pos"), TemplateRotationArgument.getRotation(p_214592_, "rotation"), TemplateMirrorArgument.getMirror(p_214592_, "mirror"), 1.0F, 0);
}).then(Commands.argument("integrity", FloatArgumentType.floatArg(0.0F, 1.0F)).executes((p_214586_) -> {
return placeTemplate(p_214586_.getSource(), ResourceLocationArgument.getId(p_214586_, "template"), BlockPosArgument.getLoadedBlockPos(p_214586_, "pos"), TemplateRotationArgument.getRotation(p_214586_, "rotation"), TemplateMirrorArgument.getMirror(p_214586_, "mirror"), FloatArgumentType.getFloat(p_214586_, "integrity"), 0);
}).then(Commands.argument("seed", IntegerArgumentType.integer()).executes((p_214550_) -> {
return placeTemplate(p_214550_.getSource(), ResourceLocationArgument.getId(p_214550_, "template"), BlockPosArgument.getLoadedBlockPos(p_214550_, "pos"), TemplateRotationArgument.getRotation(p_214550_, "rotation"), TemplateMirrorArgument.getMirror(p_214550_, "mirror"), FloatArgumentType.getFloat(p_214550_, "integrity"), IntegerArgumentType.getInteger(p_214550_, "seed"));
})))))))));
}
public static int placeFeature(CommandSourceStack pSource, Holder.Reference<ConfiguredFeature<?, ?>> pFeature, BlockPos pPos) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
ConfiguredFeature<?, ?> configuredfeature = pFeature.value();
ChunkPos chunkpos = new ChunkPos(pPos);
checkLoaded(serverlevel, new ChunkPos(chunkpos.x - 1, chunkpos.z - 1), new ChunkPos(chunkpos.x + 1, chunkpos.z + 1));
if (!configuredfeature.place(serverlevel, serverlevel.getChunkSource().getGenerator(), serverlevel.getRandom(), pPos)) {
throw ERROR_FEATURE_FAILED.create();
} else {
String s = pFeature.key().location().toString();
pSource.sendSuccess(() -> {
return Component.translatable("commands.place.feature.success", s, pPos.getX(), pPos.getY(), pPos.getZ());
}, true);
return 1;
}
}
public static int placeJigsaw(CommandSourceStack pSource, Holder<StructureTemplatePool> pTemplatePool, ResourceLocation pTarget, int pMaxDepth, BlockPos pPos) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
if (!JigsawPlacement.generateJigsaw(serverlevel, pTemplatePool, pTarget, pMaxDepth, pPos, false)) {
throw ERROR_JIGSAW_FAILED.create();
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.place.jigsaw.success", pPos.getX(), pPos.getY(), pPos.getZ());
}, true);
return 1;
}
}
public static int placeStructure(CommandSourceStack pSource, Holder.Reference<Structure> pStructure, BlockPos pPos) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
Structure structure = pStructure.value();
ChunkGenerator chunkgenerator = serverlevel.getChunkSource().getGenerator();
StructureStart structurestart = structure.generate(pSource.registryAccess(), chunkgenerator, chunkgenerator.getBiomeSource(), serverlevel.getChunkSource().randomState(), serverlevel.getStructureManager(), serverlevel.getSeed(), new ChunkPos(pPos), 0, serverlevel, (p_214580_) -> {
return true;
});
if (!structurestart.isValid()) {
throw ERROR_STRUCTURE_FAILED.create();
} else {
BoundingBox boundingbox = structurestart.getBoundingBox();
ChunkPos chunkpos = new ChunkPos(SectionPos.blockToSectionCoord(boundingbox.minX()), SectionPos.blockToSectionCoord(boundingbox.minZ()));
ChunkPos chunkpos1 = new ChunkPos(SectionPos.blockToSectionCoord(boundingbox.maxX()), SectionPos.blockToSectionCoord(boundingbox.maxZ()));
checkLoaded(serverlevel, chunkpos, chunkpos1);
ChunkPos.rangeClosed(chunkpos, chunkpos1).forEach((p_289290_) -> {
structurestart.placeInChunk(serverlevel, serverlevel.structureManager(), chunkgenerator, serverlevel.getRandom(), new BoundingBox(p_289290_.getMinBlockX(), serverlevel.getMinBuildHeight(), p_289290_.getMinBlockZ(), p_289290_.getMaxBlockX(), serverlevel.getMaxBuildHeight(), p_289290_.getMaxBlockZ()), p_289290_);
});
String s = pStructure.key().location().toString();
pSource.sendSuccess(() -> {
return Component.translatable("commands.place.structure.success", s, pPos.getX(), pPos.getY(), pPos.getZ());
}, true);
return 1;
}
}
public static int placeTemplate(CommandSourceStack pSource, ResourceLocation pTemplate, BlockPos pPos, Rotation pRotation, Mirror pMirror, float pIntegrity, int pSeed) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
StructureTemplateManager structuretemplatemanager = serverlevel.getStructureManager();
Optional<StructureTemplate> optional;
try {
optional = structuretemplatemanager.get(pTemplate);
} catch (ResourceLocationException resourcelocationexception) {
throw ERROR_TEMPLATE_INVALID.create(pTemplate);
}
if (optional.isEmpty()) {
throw ERROR_TEMPLATE_INVALID.create(pTemplate);
} else {
StructureTemplate structuretemplate = optional.get();
checkLoaded(serverlevel, new ChunkPos(pPos), new ChunkPos(pPos.offset(structuretemplate.getSize())));
StructurePlaceSettings structureplacesettings = (new StructurePlaceSettings()).setMirror(pMirror).setRotation(pRotation);
if (pIntegrity < 1.0F) {
structureplacesettings.clearProcessors().addProcessor(new BlockRotProcessor(pIntegrity)).setRandom(StructureBlockEntity.createRandom((long)pSeed));
}
boolean flag = structuretemplate.placeInWorld(serverlevel, pPos, pPos, structureplacesettings, StructureBlockEntity.createRandom((long)pSeed), 2);
if (!flag) {
throw ERROR_TEMPLATE_FAILED.create();
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.place.template.success", pTemplate, pPos.getX(), pPos.getY(), pPos.getZ());
}, true);
return 1;
}
}
}
private static void checkLoaded(ServerLevel pLevel, ChunkPos pStart, ChunkPos pEnd) throws CommandSyntaxException {
if (ChunkPos.rangeClosed(pStart, pEnd).filter((p_214542_) -> {
return !pLevel.isLoaded(p_214542_.getWorldPosition());
}).findAny().isPresent()) {
throw BlockPosArgument.ERROR_NOT_LOADED.create();
}
}
}
@@ -0,0 +1,98 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.core.Holder;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
public class PlaySoundCommand {
private static final SimpleCommandExceptionType ERROR_TOO_FAR = new SimpleCommandExceptionType(Component.translatable("commands.playsound.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
RequiredArgumentBuilder<CommandSourceStack, ResourceLocation> requiredargumentbuilder = Commands.argument("sound", ResourceLocationArgument.id()).suggests(SuggestionProviders.AVAILABLE_SOUNDS);
for(SoundSource soundsource : SoundSource.values()) {
requiredargumentbuilder.then(source(soundsource));
}
pDispatcher.register(Commands.literal("playsound").requires((p_138159_) -> {
return p_138159_.hasPermission(2);
}).then(requiredargumentbuilder));
}
private static LiteralArgumentBuilder<CommandSourceStack> source(SoundSource pCategory) {
return Commands.literal(pCategory.getName()).then(Commands.argument("targets", EntityArgument.players()).executes((p_138180_) -> {
return playSound(p_138180_.getSource(), EntityArgument.getPlayers(p_138180_, "targets"), ResourceLocationArgument.getId(p_138180_, "sound"), pCategory, p_138180_.getSource().getPosition(), 1.0F, 1.0F, 0.0F);
}).then(Commands.argument("pos", Vec3Argument.vec3()).executes((p_138177_) -> {
return playSound(p_138177_.getSource(), EntityArgument.getPlayers(p_138177_, "targets"), ResourceLocationArgument.getId(p_138177_, "sound"), pCategory, Vec3Argument.getVec3(p_138177_, "pos"), 1.0F, 1.0F, 0.0F);
}).then(Commands.argument("volume", FloatArgumentType.floatArg(0.0F)).executes((p_138174_) -> {
return playSound(p_138174_.getSource(), EntityArgument.getPlayers(p_138174_, "targets"), ResourceLocationArgument.getId(p_138174_, "sound"), pCategory, Vec3Argument.getVec3(p_138174_, "pos"), p_138174_.getArgument("volume", Float.class), 1.0F, 0.0F);
}).then(Commands.argument("pitch", FloatArgumentType.floatArg(0.0F, 2.0F)).executes((p_138171_) -> {
return playSound(p_138171_.getSource(), EntityArgument.getPlayers(p_138171_, "targets"), ResourceLocationArgument.getId(p_138171_, "sound"), pCategory, Vec3Argument.getVec3(p_138171_, "pos"), p_138171_.getArgument("volume", Float.class), p_138171_.getArgument("pitch", Float.class), 0.0F);
}).then(Commands.argument("minVolume", FloatArgumentType.floatArg(0.0F, 1.0F)).executes((p_138155_) -> {
return playSound(p_138155_.getSource(), EntityArgument.getPlayers(p_138155_, "targets"), ResourceLocationArgument.getId(p_138155_, "sound"), pCategory, Vec3Argument.getVec3(p_138155_, "pos"), p_138155_.getArgument("volume", Float.class), p_138155_.getArgument("pitch", Float.class), p_138155_.getArgument("minVolume", Float.class));
}))))));
}
private static int playSound(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, ResourceLocation pSound, SoundSource pCategory, Vec3 pPos, float pVolume, float pPitch, float pMinVolume) throws CommandSyntaxException {
Holder<SoundEvent> holder = Holder.direct(SoundEvent.createVariableRangeEvent(pSound));
double d0 = (double)Mth.square(holder.value().getRange(pVolume));
int i = 0;
long j = pSource.getLevel().getRandom().nextLong();
for(ServerPlayer serverplayer : pTargets) {
double d1 = pPos.x - serverplayer.getX();
double d2 = pPos.y - serverplayer.getY();
double d3 = pPos.z - serverplayer.getZ();
double d4 = d1 * d1 + d2 * d2 + d3 * d3;
Vec3 vec3 = pPos;
float f = pVolume;
if (d4 > d0) {
if (pMinVolume <= 0.0F) {
continue;
}
double d5 = Math.sqrt(d4);
vec3 = new Vec3(serverplayer.getX() + d1 / d5 * 2.0D, serverplayer.getY() + d2 / d5 * 2.0D, serverplayer.getZ() + d3 / d5 * 2.0D);
f = pMinVolume;
}
serverplayer.connection.send(new ClientboundSoundPacket(holder, pCategory, vec3.x(), vec3.y(), vec3.z(), f, pPitch, j));
++i;
}
if (i == 0) {
throw ERROR_TOO_FAR.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.playsound.success.single", pSound, pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.playsound.success.multiple", pSound, pTargets.size());
}, true);
}
return i;
}
}
}
@@ -0,0 +1,56 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.GameModeArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.util.HttpUtil;
import net.minecraft.world.level.GameType;
public class PublishCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.publish.failed"));
private static final DynamicCommandExceptionType ERROR_ALREADY_PUBLISHED = new DynamicCommandExceptionType((p_138194_) -> {
return Component.translatable("commands.publish.alreadyPublished", p_138194_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("publish").requires((p_138189_) -> {
return p_138189_.hasPermission(4);
}).executes((p_258235_) -> {
return publish(p_258235_.getSource(), HttpUtil.getAvailablePort(), false, (GameType)null);
}).then(Commands.argument("allowCommands", BoolArgumentType.bool()).executes((p_258236_) -> {
return publish(p_258236_.getSource(), HttpUtil.getAvailablePort(), BoolArgumentType.getBool(p_258236_, "allowCommands"), (GameType)null);
}).then(Commands.argument("gamemode", GameModeArgument.gameMode()).executes((p_258237_) -> {
return publish(p_258237_.getSource(), HttpUtil.getAvailablePort(), BoolArgumentType.getBool(p_258237_, "allowCommands"), GameModeArgument.getGameMode(p_258237_, "gamemode"));
}).then(Commands.argument("port", IntegerArgumentType.integer(0, 65535)).executes((p_258238_) -> {
return publish(p_258238_.getSource(), IntegerArgumentType.getInteger(p_258238_, "port"), BoolArgumentType.getBool(p_258238_, "allowCommands"), GameModeArgument.getGameMode(p_258238_, "gamemode"));
})))));
}
private static int publish(CommandSourceStack pSource, int pPort, boolean pCheats, @Nullable GameType pGameMode) throws CommandSyntaxException {
if (pSource.getServer().isPublished()) {
throw ERROR_ALREADY_PUBLISHED.create(pSource.getServer().getPort());
} else if (!pSource.getServer().publishServer(pGameMode, pCheats, pPort)) {
throw ERROR_FAILED.create();
} else {
pSource.sendSuccess(() -> {
return getSuccessMessage(pPort);
}, true);
return pPort;
}
}
public static MutableComponent getSuccessMessage(int pPort) {
Component component = ComponentUtils.copyOnClickText(String.valueOf(pPort));
return Component.translatable("commands.publish.started", component);
}
}
@@ -0,0 +1,181 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.ComponentArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.entity.SpawnGroupData;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.raid.Raid;
import net.minecraft.world.entity.raid.Raider;
import net.minecraft.world.entity.raid.Raids;
import net.minecraft.world.phys.Vec3;
public class RaidCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("raid").requires((p_180498_) -> {
return p_180498_.hasPermission(3);
}).then(Commands.literal("start").then(Commands.argument("omenlvl", IntegerArgumentType.integer(0)).executes((p_180502_) -> {
return start(p_180502_.getSource(), IntegerArgumentType.getInteger(p_180502_, "omenlvl"));
}))).then(Commands.literal("stop").executes((p_180500_) -> {
return stop(p_180500_.getSource());
})).then(Commands.literal("check").executes((p_180496_) -> {
return check(p_180496_.getSource());
})).then(Commands.literal("sound").then(Commands.argument("type", ComponentArgument.textComponent()).executes((p_180492_) -> {
return playSound(p_180492_.getSource(), ComponentArgument.getComponent(p_180492_, "type"));
}))).then(Commands.literal("spawnleader").executes((p_180488_) -> {
return spawnLeader(p_180488_.getSource());
})).then(Commands.literal("setomen").then(Commands.argument("level", IntegerArgumentType.integer(0)).executes((p_180481_) -> {
return setBadOmenLevel(p_180481_.getSource(), IntegerArgumentType.getInteger(p_180481_, "level"));
}))).then(Commands.literal("glow").executes((p_180471_) -> {
return glow(p_180471_.getSource());
})));
}
private static int glow(CommandSourceStack pSource) throws CommandSyntaxException {
Raid raid = getRaid(pSource.getPlayerOrException());
if (raid != null) {
for(Raider raider : raid.getAllRaiders()) {
raider.addEffect(new MobEffectInstance(MobEffects.GLOWING, 1000, 1));
}
}
return 1;
}
private static int setBadOmenLevel(CommandSourceStack pSource, int pLevel) throws CommandSyntaxException {
Raid raid = getRaid(pSource.getPlayerOrException());
if (raid != null) {
int i = raid.getMaxBadOmenLevel();
if (pLevel > i) {
pSource.sendFailure(Component.literal("Sorry, the max bad omen level you can set is " + i));
} else {
int j = raid.getBadOmenLevel();
raid.setBadOmenLevel(pLevel);
pSource.sendSuccess(() -> {
return Component.literal("Changed village's bad omen level from " + j + " to " + pLevel);
}, false);
}
} else {
pSource.sendFailure(Component.literal("No raid found here"));
}
return 1;
}
private static int spawnLeader(CommandSourceStack pSource) {
pSource.sendSuccess(() -> {
return Component.literal("Spawned a raid captain");
}, false);
Raider raider = EntityType.PILLAGER.create(pSource.getLevel());
if (raider == null) {
pSource.sendFailure(Component.literal("Pillager failed to spawn"));
return 0;
} else {
raider.setPatrolLeader(true);
raider.setItemSlot(EquipmentSlot.HEAD, Raid.getLeaderBannerInstance());
raider.setPos(pSource.getPosition().x, pSource.getPosition().y, pSource.getPosition().z);
raider.finalizeSpawn(pSource.getLevel(), pSource.getLevel().getCurrentDifficultyAt(BlockPos.containing(pSource.getPosition())), MobSpawnType.COMMAND, (SpawnGroupData)null, (CompoundTag)null);
pSource.getLevel().addFreshEntityWithPassengers(raider);
return 1;
}
}
private static int playSound(CommandSourceStack pSource, @Nullable Component p_180479_) {
if (p_180479_ != null && p_180479_.getString().equals("local")) {
ServerLevel serverlevel = pSource.getLevel();
Vec3 vec3 = pSource.getPosition().add(5.0D, 0.0D, 0.0D);
serverlevel.playSeededSound((Player)null, vec3.x, vec3.y, vec3.z, SoundEvents.RAID_HORN, SoundSource.NEUTRAL, 2.0F, 1.0F, serverlevel.random.nextLong());
}
return 1;
}
private static int start(CommandSourceStack pSource, int pBadOmenLevel) throws CommandSyntaxException {
ServerPlayer serverplayer = pSource.getPlayerOrException();
BlockPos blockpos = serverplayer.blockPosition();
if (serverplayer.serverLevel().isRaided(blockpos)) {
pSource.sendFailure(Component.literal("Raid already started close by"));
return -1;
} else {
Raids raids = serverplayer.serverLevel().getRaids();
Raid raid = raids.createOrExtendRaid(serverplayer);
if (raid != null) {
raid.setBadOmenLevel(pBadOmenLevel);
raids.setDirty();
pSource.sendSuccess(() -> {
return Component.literal("Created a raid in your local village");
}, false);
} else {
pSource.sendFailure(Component.literal("Failed to create a raid in your local village"));
}
return 1;
}
}
private static int stop(CommandSourceStack pSource) throws CommandSyntaxException {
ServerPlayer serverplayer = pSource.getPlayerOrException();
BlockPos blockpos = serverplayer.blockPosition();
Raid raid = serverplayer.serverLevel().getRaidAt(blockpos);
if (raid != null) {
raid.stop();
pSource.sendSuccess(() -> {
return Component.literal("Stopped raid");
}, false);
return 1;
} else {
pSource.sendFailure(Component.literal("No raid here"));
return -1;
}
}
private static int check(CommandSourceStack pSource) throws CommandSyntaxException {
Raid raid = getRaid(pSource.getPlayerOrException());
if (raid != null) {
StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append("Found a started raid! ");
pSource.sendSuccess(() -> {
return Component.literal(stringbuilder.toString());
}, false);
StringBuilder stringbuilder1 = new StringBuilder();
stringbuilder1.append("Num groups spawned: ");
stringbuilder1.append(raid.getGroupsSpawned());
stringbuilder1.append(" Bad omen level: ");
stringbuilder1.append(raid.getBadOmenLevel());
stringbuilder1.append(" Num mobs: ");
stringbuilder1.append(raid.getTotalRaidersAlive());
stringbuilder1.append(" Raid health: ");
stringbuilder1.append(raid.getHealthOfLivingRaiders());
stringbuilder1.append(" / ");
stringbuilder1.append(raid.getTotalHealth());
pSource.sendSuccess(() -> {
return Component.literal(stringbuilder1.toString());
}, false);
return 1;
} else {
pSource.sendFailure(Component.literal("Found no started raids"));
return 0;
}
}
@Nullable
private static Raid getRaid(ServerPlayer pPlayer) {
return pPlayer.serverLevel().getRaidAt(pPlayer.blockPosition());
}
}
@@ -0,0 +1,82 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import java.util.Collections;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.crafting.Recipe;
public class RecipeCommand {
private static final SimpleCommandExceptionType ERROR_GIVE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.recipe.give.failed"));
private static final SimpleCommandExceptionType ERROR_TAKE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.recipe.take.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("recipe").requires((p_138205_) -> {
return p_138205_.hasPermission(2);
}).then(Commands.literal("give").then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("recipe", ResourceLocationArgument.id()).suggests(SuggestionProviders.ALL_RECIPES).executes((p_138219_) -> {
return giveRecipes(p_138219_.getSource(), EntityArgument.getPlayers(p_138219_, "targets"), Collections.singleton(ResourceLocationArgument.getRecipe(p_138219_, "recipe")));
})).then(Commands.literal("*").executes((p_138217_) -> {
return giveRecipes(p_138217_.getSource(), EntityArgument.getPlayers(p_138217_, "targets"), p_138217_.getSource().getServer().getRecipeManager().getRecipes());
})))).then(Commands.literal("take").then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("recipe", ResourceLocationArgument.id()).suggests(SuggestionProviders.ALL_RECIPES).executes((p_138211_) -> {
return takeRecipes(p_138211_.getSource(), EntityArgument.getPlayers(p_138211_, "targets"), Collections.singleton(ResourceLocationArgument.getRecipe(p_138211_, "recipe")));
})).then(Commands.literal("*").executes((p_138203_) -> {
return takeRecipes(p_138203_.getSource(), EntityArgument.getPlayers(p_138203_, "targets"), p_138203_.getSource().getServer().getRecipeManager().getRecipes());
})))));
}
private static int giveRecipes(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, Collection<Recipe<?>> pRecipes) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : pTargets) {
i += serverplayer.awardRecipes(pRecipes);
}
if (i == 0) {
throw ERROR_GIVE_FAILED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.recipe.give.success.single", pRecipes.size(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.recipe.give.success.multiple", pRecipes.size(), pTargets.size());
}, true);
}
return i;
}
}
private static int takeRecipes(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, Collection<Recipe<?>> pRecipes) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : pTargets) {
i += serverplayer.resetRecipes(pRecipes);
}
if (i == 0) {
throw ERROR_TAKE_FAILED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.recipe.take.success.single", pRecipes.size(), pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.recipe.take.success.multiple", pRecipes.size(), pTargets.size());
}, true);
}
return i;
}
}
}
@@ -0,0 +1,60 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.logging.LogUtils;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.storage.WorldData;
import org.slf4j.Logger;
public class ReloadCommand {
private static final Logger LOGGER = LogUtils.getLogger();
public static void reloadPacks(Collection<String> pSelectedIds, CommandSourceStack pSource) {
pSource.getServer().reloadResources(pSelectedIds).exceptionally((p_138234_) -> {
LOGGER.warn("Failed to execute reload", p_138234_);
pSource.sendFailure(Component.translatable("commands.reload.failure"));
return null;
});
}
/**
* Gets a list of IDs for the selected packs as well as all packs not disabled by the world config.
*/
private static Collection<String> discoverNewPacks(PackRepository pPackRepository, WorldData pWorldData, Collection<String> pSelectedIds) {
pPackRepository.reload();
Collection<String> collection = Lists.newArrayList(pSelectedIds);
Collection<String> collection1 = pWorldData.getDataConfiguration().dataPacks().getDisabled();
for(String s : pPackRepository.getAvailableIds()) {
if (!collection1.contains(s) && !collection.contains(s)) {
collection.add(s);
}
}
return collection;
}
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("reload").requires((p_138231_) -> {
return p_138231_.hasPermission(2);
}).executes((p_288528_) -> {
CommandSourceStack commandsourcestack = p_288528_.getSource();
MinecraftServer minecraftserver = commandsourcestack.getServer();
PackRepository packrepository = minecraftserver.getPackRepository();
WorldData worlddata = minecraftserver.getWorldData();
Collection<String> collection = packrepository.getSelectedIds();
Collection<String> collection1 = discoverNewPacks(packrepository, worlddata, collection);
commandsourcestack.sendSuccess(() -> {
return Component.translatable("commands.reload.success");
}, true);
reloadPacks(collection1, commandsourcestack);
return 0;
}));
}
}
@@ -0,0 +1,145 @@
package net.minecraft.server.commands;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.datafixers.util.Unit;
import com.mojang.logging.LogUtils;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.thread.ProcessorMailbox;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.phys.Vec3;
import org.slf4j.Logger;
public class ResetChunksCommand {
private static final Logger LOGGER = LogUtils.getLogger();
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("resetchunks").requires((p_183683_) -> {
return p_183683_.hasPermission(2);
}).executes((p_183693_) -> {
return resetChunks(p_183693_.getSource(), 0, true);
}).then(Commands.argument("range", IntegerArgumentType.integer(0, 5)).executes((p_183689_) -> {
return resetChunks(p_183689_.getSource(), IntegerArgumentType.getInteger(p_183689_, "range"), true);
}).then(Commands.argument("skipOldChunks", BoolArgumentType.bool()).executes((p_183669_) -> {
return resetChunks(p_183669_.getSource(), IntegerArgumentType.getInteger(p_183669_, "range"), BoolArgumentType.getBool(p_183669_, "skipOldChunks"));
}))));
}
private static int resetChunks(CommandSourceStack pSource, int pRange, boolean pSkipOldChunks) {
ServerLevel serverlevel = pSource.getLevel();
ServerChunkCache serverchunkcache = serverlevel.getChunkSource();
serverchunkcache.chunkMap.debugReloadGenerator();
Vec3 vec3 = pSource.getPosition();
ChunkPos chunkpos = new ChunkPos(BlockPos.containing(vec3));
int i = chunkpos.z - pRange;
int j = chunkpos.z + pRange;
int k = chunkpos.x - pRange;
int l = chunkpos.x + pRange;
for(int i1 = i; i1 <= j; ++i1) {
for(int j1 = k; j1 <= l; ++j1) {
ChunkPos chunkpos1 = new ChunkPos(j1, i1);
LevelChunk levelchunk = serverchunkcache.getChunk(j1, i1, false);
if (levelchunk != null && (!pSkipOldChunks || !levelchunk.isOldNoiseGeneration())) {
for(BlockPos blockpos : BlockPos.betweenClosed(chunkpos1.getMinBlockX(), serverlevel.getMinBuildHeight(), chunkpos1.getMinBlockZ(), chunkpos1.getMaxBlockX(), serverlevel.getMaxBuildHeight() - 1, chunkpos1.getMaxBlockZ())) {
serverlevel.setBlock(blockpos, Blocks.AIR.defaultBlockState(), 16);
}
}
}
}
ProcessorMailbox<Runnable> processormailbox = ProcessorMailbox.create(Util.backgroundExecutor(), "worldgen-resetchunks");
long j3 = System.currentTimeMillis();
int k3 = (pRange * 2 + 1) * (pRange * 2 + 1);
for(ChunkStatus chunkstatus : ImmutableList.of(ChunkStatus.BIOMES, ChunkStatus.NOISE, ChunkStatus.SURFACE, ChunkStatus.CARVERS, ChunkStatus.FEATURES, ChunkStatus.INITIALIZE_LIGHT)) {
long k1 = System.currentTimeMillis();
CompletableFuture<Unit> completablefuture = CompletableFuture.supplyAsync(() -> {
return Unit.INSTANCE;
}, processormailbox::tell);
for(int i2 = chunkpos.z - pRange; i2 <= chunkpos.z + pRange; ++i2) {
for(int j2 = chunkpos.x - pRange; j2 <= chunkpos.x + pRange; ++j2) {
ChunkPos chunkpos2 = new ChunkPos(j2, i2);
LevelChunk levelchunk1 = serverchunkcache.getChunk(j2, i2, false);
if (levelchunk1 != null && (!pSkipOldChunks || !levelchunk1.isOldNoiseGeneration())) {
List<ChunkAccess> list = Lists.newArrayList();
int k2 = Math.max(1, chunkstatus.getRange());
for(int l2 = chunkpos2.z - k2; l2 <= chunkpos2.z + k2; ++l2) {
for(int i3 = chunkpos2.x - k2; i3 <= chunkpos2.x + k2; ++i3) {
ChunkAccess chunkaccess = serverchunkcache.getChunk(i3, l2, chunkstatus.getParent(), true);
ChunkAccess chunkaccess1;
if (chunkaccess instanceof ImposterProtoChunk) {
chunkaccess1 = new ImposterProtoChunk(((ImposterProtoChunk)chunkaccess).getWrapped(), true);
} else if (chunkaccess instanceof LevelChunk) {
chunkaccess1 = new ImposterProtoChunk((LevelChunk)chunkaccess, true);
} else {
chunkaccess1 = chunkaccess;
}
list.add(chunkaccess1);
}
}
completablefuture = completablefuture.thenComposeAsync((p_280957_) -> {
return chunkstatus.generate(processormailbox::tell, serverlevel, serverchunkcache.getGenerator(), serverlevel.getStructureManager(), serverchunkcache.getLightEngine(), (p_183691_) -> {
throw new UnsupportedOperationException("Not creating full chunks here");
}, list).thenApply((p_183681_) -> {
if (chunkstatus == ChunkStatus.NOISE) {
p_183681_.left().ifPresent((p_183671_) -> {
Heightmap.primeHeightmaps(p_183671_, ChunkStatus.POST_FEATURES);
});
}
return Unit.INSTANCE;
});
}, processormailbox::tell);
}
}
}
pSource.getServer().managedBlock(completablefuture::isDone);
LOGGER.debug(chunkstatus + " took " + (System.currentTimeMillis() - k1) + " ms");
}
long l3 = System.currentTimeMillis();
for(int i4 = chunkpos.z - pRange; i4 <= chunkpos.z + pRange; ++i4) {
for(int l1 = chunkpos.x - pRange; l1 <= chunkpos.x + pRange; ++l1) {
ChunkPos chunkpos3 = new ChunkPos(l1, i4);
LevelChunk levelchunk2 = serverchunkcache.getChunk(l1, i4, false);
if (levelchunk2 != null && (!pSkipOldChunks || !levelchunk2.isOldNoiseGeneration())) {
for(BlockPos blockpos1 : BlockPos.betweenClosed(chunkpos3.getMinBlockX(), serverlevel.getMinBuildHeight(), chunkpos3.getMinBlockZ(), chunkpos3.getMaxBlockX(), serverlevel.getMaxBuildHeight() - 1, chunkpos3.getMaxBlockZ())) {
serverchunkcache.blockChanged(blockpos1);
}
}
}
}
LOGGER.debug("blockChanged took " + (System.currentTimeMillis() - l3) + " ms");
long j4 = System.currentTimeMillis() - j3;
pSource.sendSuccess(() -> {
return Component.literal(String.format(Locale.ROOT, "%d chunks have been reset. This took %d ms for %d chunks, or %02f ms per chunk", k3, j4, k3, (float)j4 / (float)k3));
}, true);
return 1;
}
}
@@ -0,0 +1,21 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
public class ReturnCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("return").requires((p_281281_) -> {
return p_281281_.hasPermission(2);
}).then(Commands.argument("value", IntegerArgumentType.integer()).executes((p_281464_) -> {
return setReturn(p_281464_.getSource(), IntegerArgumentType.getInteger(p_281464_, "value"));
})));
}
private static int setReturn(CommandSourceStack pSource, int pValue) {
pSource.getReturnValueConsumer().accept(pValue);
return pValue;
}
}
@@ -0,0 +1,73 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
public class RideCommand {
private static final DynamicCommandExceptionType ERROR_NOT_RIDING = new DynamicCommandExceptionType((p_265076_) -> {
return Component.translatable("commands.ride.not_riding", p_265076_);
});
private static final Dynamic2CommandExceptionType ERROR_ALREADY_RIDING = new Dynamic2CommandExceptionType((p_265488_, p_265072_) -> {
return Component.translatable("commands.ride.already_riding", p_265488_, p_265072_);
});
private static final Dynamic2CommandExceptionType ERROR_MOUNT_FAILED = new Dynamic2CommandExceptionType((p_265321_, p_265603_) -> {
return Component.translatable("commands.ride.mount.failure.generic", p_265321_, p_265603_);
});
private static final SimpleCommandExceptionType ERROR_MOUNTING_PLAYER = new SimpleCommandExceptionType(Component.translatable("commands.ride.mount.failure.cant_ride_players"));
private static final SimpleCommandExceptionType ERROR_MOUNTING_LOOP = new SimpleCommandExceptionType(Component.translatable("commands.ride.mount.failure.loop"));
private static final SimpleCommandExceptionType ERROR_WRONG_DIMENSION = new SimpleCommandExceptionType(Component.translatable("commands.ride.mount.failure.wrong_dimension"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("ride").requires((p_265326_) -> {
return p_265326_.hasPermission(2);
}).then(Commands.argument("target", EntityArgument.entity()).then(Commands.literal("mount").then(Commands.argument("vehicle", EntityArgument.entity()).executes((p_265139_) -> {
return mount(p_265139_.getSource(), EntityArgument.getEntity(p_265139_, "target"), EntityArgument.getEntity(p_265139_, "vehicle"));
}))).then(Commands.literal("dismount").executes((p_265418_) -> {
return dismount(p_265418_.getSource(), EntityArgument.getEntity(p_265418_, "target"));
}))));
}
private static int mount(CommandSourceStack pSource, Entity pTarget, Entity pVehicle) throws CommandSyntaxException {
Entity entity = pTarget.getVehicle();
if (entity != null) {
throw ERROR_ALREADY_RIDING.create(pTarget.getDisplayName(), entity.getDisplayName());
} else if (pVehicle.getType() == EntityType.PLAYER) {
throw ERROR_MOUNTING_PLAYER.create();
} else if (pTarget.getSelfAndPassengers().anyMatch((p_265501_) -> {
return p_265501_ == pVehicle;
})) {
throw ERROR_MOUNTING_LOOP.create();
} else if (pTarget.level() != pVehicle.level()) {
throw ERROR_WRONG_DIMENSION.create();
} else if (!pTarget.startRiding(pVehicle, true)) {
throw ERROR_MOUNT_FAILED.create(pTarget.getDisplayName(), pVehicle.getDisplayName());
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.ride.mount.success", pTarget.getDisplayName(), pVehicle.getDisplayName());
}, true);
return 1;
}
}
private static int dismount(CommandSourceStack pSource, Entity pTarget) throws CommandSyntaxException {
Entity entity = pTarget.getVehicle();
if (entity == null) {
throw ERROR_NOT_RIDING.create(pTarget.getDisplayName());
} else {
pTarget.stopRiding();
pSource.sendSuccess(() -> {
return Component.translatable("commands.ride.dismount.success", pTarget.getDisplayName(), entity.getDisplayName());
}, true);
return 1;
}
}
}
@@ -0,0 +1,39 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
public class SaveAllCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.save.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("save-all").requires((p_138276_) -> {
return p_138276_.hasPermission(4);
}).executes((p_138281_) -> {
return saveAll(p_138281_.getSource(), false);
}).then(Commands.literal("flush").executes((p_138274_) -> {
return saveAll(p_138274_.getSource(), true);
})));
}
private static int saveAll(CommandSourceStack pSource, boolean pFlush) throws CommandSyntaxException {
pSource.sendSuccess(() -> {
return Component.translatable("commands.save.saving");
}, false);
MinecraftServer minecraftserver = pSource.getServer();
boolean flag = minecraftserver.saveEverything(true, pFlush, true);
if (!flag) {
throw ERROR_FAILED.create();
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.save.success");
}, true);
return 1;
}
}
}
@@ -0,0 +1,37 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
public class SaveOffCommand {
private static final SimpleCommandExceptionType ERROR_ALREADY_OFF = new SimpleCommandExceptionType(Component.translatable("commands.save.alreadyOff"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("save-off").requires((p_138289_) -> {
return p_138289_.hasPermission(4);
}).executes((p_138287_) -> {
CommandSourceStack commandsourcestack = p_138287_.getSource();
boolean flag = false;
for(ServerLevel serverlevel : commandsourcestack.getServer().getAllLevels()) {
if (serverlevel != null && !serverlevel.noSave) {
serverlevel.noSave = true;
flag = true;
}
}
if (!flag) {
throw ERROR_ALREADY_OFF.create();
} else {
commandsourcestack.sendSuccess(() -> {
return Component.translatable("commands.save.disabled");
}, true);
return 1;
}
}));
}
}
@@ -0,0 +1,37 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
public class SaveOnCommand {
private static final SimpleCommandExceptionType ERROR_ALREADY_ON = new SimpleCommandExceptionType(Component.translatable("commands.save.alreadyOn"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("save-on").requires((p_138297_) -> {
return p_138297_.hasPermission(4);
}).executes((p_138295_) -> {
CommandSourceStack commandsourcestack = p_138295_.getSource();
boolean flag = false;
for(ServerLevel serverlevel : commandsourcestack.getServer().getAllLevels()) {
if (serverlevel != null && serverlevel.noSave) {
serverlevel.noSave = false;
flag = true;
}
}
if (!flag) {
throw ERROR_ALREADY_ON.create();
} else {
commandsourcestack.sendSuccess(() -> {
return Component.translatable("commands.save.enabled");
}, true);
return 1;
}
}));
}
}
@@ -0,0 +1,23 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.network.chat.ChatType;
import net.minecraft.server.players.PlayerList;
public class SayCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("say").requires((p_138414_) -> {
return p_138414_.hasPermission(2);
}).then(Commands.argument("message", MessageArgument.message()).executes((p_248171_) -> {
MessageArgument.resolveChatMessage(p_248171_, "message", (p_248170_) -> {
CommandSourceStack commandsourcestack = p_248171_.getSource();
PlayerList playerlist = commandsourcestack.getServer().getPlayerList();
playerlist.broadcastChatMessage(p_248170_, commandsourcestack, ChatType.bind(ChatType.SAY_COMMAND, commandsourcestack));
});
return 1;
})));
}
}
@@ -0,0 +1,92 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.datafixers.util.Either;
import com.mojang.datafixers.util.Pair;
import java.util.Collection;
import net.minecraft.commands.CommandFunction;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.TimeArgument;
import net.minecraft.commands.arguments.item.FunctionArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.timers.FunctionCallback;
import net.minecraft.world.level.timers.FunctionTagCallback;
import net.minecraft.world.level.timers.TimerQueue;
public class ScheduleCommand {
private static final SimpleCommandExceptionType ERROR_SAME_TICK = new SimpleCommandExceptionType(Component.translatable("commands.schedule.same_tick"));
private static final DynamicCommandExceptionType ERROR_CANT_REMOVE = new DynamicCommandExceptionType((p_138437_) -> {
return Component.translatable("commands.schedule.cleared.failure", p_138437_);
});
private static final SuggestionProvider<CommandSourceStack> SUGGEST_SCHEDULE = (p_138424_, p_138425_) -> {
return SharedSuggestionProvider.suggest(p_138424_.getSource().getServer().getWorldData().overworldData().getScheduledEvents().getEventsIds(), p_138425_);
};
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("schedule").requires((p_138427_) -> {
return p_138427_.hasPermission(2);
}).then(Commands.literal("function").then(Commands.argument("function", FunctionArgument.functions()).suggests(FunctionCommand.SUGGEST_FUNCTION).then(Commands.argument("time", TimeArgument.time()).executes((p_138459_) -> {
return schedule(p_138459_.getSource(), FunctionArgument.getFunctionOrTag(p_138459_, "function"), IntegerArgumentType.getInteger(p_138459_, "time"), true);
}).then(Commands.literal("append").executes((p_138457_) -> {
return schedule(p_138457_.getSource(), FunctionArgument.getFunctionOrTag(p_138457_, "function"), IntegerArgumentType.getInteger(p_138457_, "time"), false);
})).then(Commands.literal("replace").executes((p_138455_) -> {
return schedule(p_138455_.getSource(), FunctionArgument.getFunctionOrTag(p_138455_, "function"), IntegerArgumentType.getInteger(p_138455_, "time"), true);
}))))).then(Commands.literal("clear").then(Commands.argument("function", StringArgumentType.greedyString()).suggests(SUGGEST_SCHEDULE).executes((p_138422_) -> {
return remove(p_138422_.getSource(), StringArgumentType.getString(p_138422_, "function"));
}))));
}
private static int schedule(CommandSourceStack pSource, Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> pFunction, int pTime, boolean pAppend) throws CommandSyntaxException {
if (pTime == 0) {
throw ERROR_SAME_TICK.create();
} else {
long i = pSource.getLevel().getGameTime() + (long)pTime;
ResourceLocation resourcelocation = pFunction.getFirst();
TimerQueue<MinecraftServer> timerqueue = pSource.getServer().getWorldData().overworldData().getScheduledEvents();
pFunction.getSecond().ifLeft((p_288541_) -> {
String s = resourcelocation.toString();
if (pAppend) {
timerqueue.remove(s);
}
timerqueue.schedule(s, i, new FunctionCallback(resourcelocation));
pSource.sendSuccess(() -> {
return Component.translatable("commands.schedule.created.function", resourcelocation, pTime, i);
}, true);
}).ifRight((p_288548_) -> {
String s = "#" + resourcelocation;
if (pAppend) {
timerqueue.remove(s);
}
timerqueue.schedule(s, i, new FunctionTagCallback(resourcelocation));
pSource.sendSuccess(() -> {
return Component.translatable("commands.schedule.created.tag", resourcelocation, pTime, i);
}, true);
});
return Math.floorMod(i, Integer.MAX_VALUE);
}
}
private static int remove(CommandSourceStack pSource, String pFunction) throws CommandSyntaxException {
int i = pSource.getServer().getWorldData().overworldData().getScheduledEvents().remove(pFunction);
if (i == 0) {
throw ERROR_CANT_REMOVE.create(pFunction);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.schedule.cleared.success", i, pFunction);
}, true);
return i;
}
}
}
@@ -0,0 +1,426 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.ComponentArgument;
import net.minecraft.commands.arguments.ObjectiveArgument;
import net.minecraft.commands.arguments.ObjectiveCriteriaArgument;
import net.minecraft.commands.arguments.OperationArgument;
import net.minecraft.commands.arguments.ScoreHolderArgument;
import net.minecraft.commands.arguments.ScoreboardSlotArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.Score;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
public class ScoreboardCommand {
private static final SimpleCommandExceptionType ERROR_OBJECTIVE_ALREADY_EXISTS = new SimpleCommandExceptionType(Component.translatable("commands.scoreboard.objectives.add.duplicate"));
private static final SimpleCommandExceptionType ERROR_DISPLAY_SLOT_ALREADY_EMPTY = new SimpleCommandExceptionType(Component.translatable("commands.scoreboard.objectives.display.alreadyEmpty"));
private static final SimpleCommandExceptionType ERROR_DISPLAY_SLOT_ALREADY_SET = new SimpleCommandExceptionType(Component.translatable("commands.scoreboard.objectives.display.alreadySet"));
private static final SimpleCommandExceptionType ERROR_TRIGGER_ALREADY_ENABLED = new SimpleCommandExceptionType(Component.translatable("commands.scoreboard.players.enable.failed"));
private static final SimpleCommandExceptionType ERROR_NOT_TRIGGER = new SimpleCommandExceptionType(Component.translatable("commands.scoreboard.players.enable.invalid"));
private static final Dynamic2CommandExceptionType ERROR_NO_VALUE = new Dynamic2CommandExceptionType((p_138534_, p_138535_) -> {
return Component.translatable("commands.scoreboard.players.get.null", p_138534_, p_138535_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("scoreboard").requires((p_138552_) -> {
return p_138552_.hasPermission(2);
}).then(Commands.literal("objectives").then(Commands.literal("list").executes((p_138585_) -> {
return listObjectives(p_138585_.getSource());
})).then(Commands.literal("add").then(Commands.argument("objective", StringArgumentType.word()).then(Commands.argument("criteria", ObjectiveCriteriaArgument.criteria()).executes((p_138583_) -> {
return addObjective(p_138583_.getSource(), StringArgumentType.getString(p_138583_, "objective"), ObjectiveCriteriaArgument.getCriteria(p_138583_, "criteria"), Component.literal(StringArgumentType.getString(p_138583_, "objective")));
}).then(Commands.argument("displayName", ComponentArgument.textComponent()).executes((p_138581_) -> {
return addObjective(p_138581_.getSource(), StringArgumentType.getString(p_138581_, "objective"), ObjectiveCriteriaArgument.getCriteria(p_138581_, "criteria"), ComponentArgument.getComponent(p_138581_, "displayName"));
}))))).then(Commands.literal("modify").then(Commands.argument("objective", ObjectiveArgument.objective()).then(Commands.literal("displayname").then(Commands.argument("displayName", ComponentArgument.textComponent()).executes((p_138579_) -> {
return setDisplayName(p_138579_.getSource(), ObjectiveArgument.getObjective(p_138579_, "objective"), ComponentArgument.getComponent(p_138579_, "displayName"));
}))).then(createRenderTypeModify()))).then(Commands.literal("remove").then(Commands.argument("objective", ObjectiveArgument.objective()).executes((p_138577_) -> {
return removeObjective(p_138577_.getSource(), ObjectiveArgument.getObjective(p_138577_, "objective"));
}))).then(Commands.literal("setdisplay").then(Commands.argument("slot", ScoreboardSlotArgument.displaySlot()).executes((p_138575_) -> {
return clearDisplaySlot(p_138575_.getSource(), ScoreboardSlotArgument.getDisplaySlot(p_138575_, "slot"));
}).then(Commands.argument("objective", ObjectiveArgument.objective()).executes((p_138573_) -> {
return setDisplaySlot(p_138573_.getSource(), ScoreboardSlotArgument.getDisplaySlot(p_138573_, "slot"), ObjectiveArgument.getObjective(p_138573_, "objective"));
}))))).then(Commands.literal("players").then(Commands.literal("list").executes((p_138571_) -> {
return listTrackedPlayers(p_138571_.getSource());
}).then(Commands.argument("target", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).executes((p_138569_) -> {
return listTrackedPlayerScores(p_138569_.getSource(), ScoreHolderArgument.getName(p_138569_, "target"));
}))).then(Commands.literal("set").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).then(Commands.argument("score", IntegerArgumentType.integer()).executes((p_138567_) -> {
return setScore(p_138567_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138567_, "targets"), ObjectiveArgument.getWritableObjective(p_138567_, "objective"), IntegerArgumentType.getInteger(p_138567_, "score"));
}))))).then(Commands.literal("get").then(Commands.argument("target", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).executes((p_138565_) -> {
return getScore(p_138565_.getSource(), ScoreHolderArgument.getName(p_138565_, "target"), ObjectiveArgument.getObjective(p_138565_, "objective"));
})))).then(Commands.literal("add").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).then(Commands.argument("score", IntegerArgumentType.integer(0)).executes((p_138563_) -> {
return addScore(p_138563_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138563_, "targets"), ObjectiveArgument.getWritableObjective(p_138563_, "objective"), IntegerArgumentType.getInteger(p_138563_, "score"));
}))))).then(Commands.literal("remove").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).then(Commands.argument("score", IntegerArgumentType.integer(0)).executes((p_138561_) -> {
return removeScore(p_138561_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138561_, "targets"), ObjectiveArgument.getWritableObjective(p_138561_, "objective"), IntegerArgumentType.getInteger(p_138561_, "score"));
}))))).then(Commands.literal("reset").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).executes((p_138559_) -> {
return resetScores(p_138559_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138559_, "targets"));
}).then(Commands.argument("objective", ObjectiveArgument.objective()).executes((p_138550_) -> {
return resetScore(p_138550_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138550_, "targets"), ObjectiveArgument.getObjective(p_138550_, "objective"));
})))).then(Commands.literal("enable").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).suggests((p_138473_, p_138474_) -> {
return suggestTriggers(p_138473_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138473_, "targets"), p_138474_);
}).executes((p_138537_) -> {
return enableTrigger(p_138537_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138537_, "targets"), ObjectiveArgument.getObjective(p_138537_, "objective"));
})))).then(Commands.literal("operation").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("targetObjective", ObjectiveArgument.objective()).then(Commands.argument("operation", OperationArgument.operation()).then(Commands.argument("source", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("sourceObjective", ObjectiveArgument.objective()).executes((p_138471_) -> {
return performOperation(p_138471_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138471_, "targets"), ObjectiveArgument.getWritableObjective(p_138471_, "targetObjective"), OperationArgument.getOperation(p_138471_, "operation"), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138471_, "source"), ObjectiveArgument.getObjective(p_138471_, "sourceObjective"));
})))))))));
}
private static LiteralArgumentBuilder<CommandSourceStack> createRenderTypeModify() {
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = Commands.literal("rendertype");
for(ObjectiveCriteria.RenderType objectivecriteria$rendertype : ObjectiveCriteria.RenderType.values()) {
literalargumentbuilder.then(Commands.literal(objectivecriteria$rendertype.getId()).executes((p_138532_) -> {
return setRenderType(p_138532_.getSource(), ObjectiveArgument.getObjective(p_138532_, "objective"), objectivecriteria$rendertype);
}));
}
return literalargumentbuilder;
}
private static CompletableFuture<Suggestions> suggestTriggers(CommandSourceStack pSource, Collection<String> pTargets, SuggestionsBuilder pSuggestions) {
List<String> list = Lists.newArrayList();
Scoreboard scoreboard = pSource.getServer().getScoreboard();
for(Objective objective : scoreboard.getObjectives()) {
if (objective.getCriteria() == ObjectiveCriteria.TRIGGER) {
boolean flag = false;
for(String s : pTargets) {
if (!scoreboard.hasPlayerScore(s, objective) || scoreboard.getOrCreatePlayerScore(s, objective).isLocked()) {
flag = true;
break;
}
}
if (flag) {
list.add(objective.getName());
}
}
}
return SharedSuggestionProvider.suggest(list, pSuggestions);
}
private static int getScore(CommandSourceStack pSource, String pPlayer, Objective pObjective) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
if (!scoreboard.hasPlayerScore(pPlayer, pObjective)) {
throw ERROR_NO_VALUE.create(pObjective.getName(), pPlayer);
} else {
Score score = scoreboard.getOrCreatePlayerScore(pPlayer, pObjective);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.get.success", pPlayer, score.getScore(), pObjective.getFormattedDisplayName());
}, false);
return score.getScore();
}
}
private static int performOperation(CommandSourceStack pSource, Collection<String> pTargetEntities, Objective pTargetObjectives, OperationArgument.Operation pOperation, Collection<String> pSourceEntities, Objective pSourceObjective) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
int i = 0;
for(String s : pTargetEntities) {
Score score = scoreboard.getOrCreatePlayerScore(s, pTargetObjectives);
for(String s1 : pSourceEntities) {
Score score1 = scoreboard.getOrCreatePlayerScore(s1, pSourceObjective);
pOperation.apply(score, score1);
}
i += score.getScore();
}
if (pTargetEntities.size() == 1) {
int j = i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.operation.success.single", pTargetObjectives.getFormattedDisplayName(), pTargetEntities.iterator().next(), j);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.operation.success.multiple", pTargetObjectives.getFormattedDisplayName(), pTargetEntities.size());
}, true);
}
return i;
}
private static int enableTrigger(CommandSourceStack pSource, Collection<String> pTargets, Objective pObjective) throws CommandSyntaxException {
if (pObjective.getCriteria() != ObjectiveCriteria.TRIGGER) {
throw ERROR_NOT_TRIGGER.create();
} else {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
int i = 0;
for(String s : pTargets) {
Score score = scoreboard.getOrCreatePlayerScore(s, pObjective);
if (score.isLocked()) {
score.setLocked(false);
++i;
}
}
if (i == 0) {
throw ERROR_TRIGGER_ALREADY_ENABLED.create();
} else {
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.enable.success.single", pObjective.getFormattedDisplayName(), pTargets.iterator().next());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.enable.success.multiple", pObjective.getFormattedDisplayName(), pTargets.size());
}, true);
}
return i;
}
}
}
private static int resetScores(CommandSourceStack pSource, Collection<String> pTargets) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
for(String s : pTargets) {
scoreboard.resetPlayerScore(s, (Objective)null);
}
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.all.single", pTargets.iterator().next());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.all.multiple", pTargets.size());
}, true);
}
return pTargets.size();
}
private static int resetScore(CommandSourceStack pSource, Collection<String> pTargets, Objective pObjective) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
for(String s : pTargets) {
scoreboard.resetPlayerScore(s, pObjective);
}
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.specific.single", pObjective.getFormattedDisplayName(), pTargets.iterator().next());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.specific.multiple", pObjective.getFormattedDisplayName(), pTargets.size());
}, true);
}
return pTargets.size();
}
private static int setScore(CommandSourceStack pSource, Collection<String> pTargets, Objective pObjective, int pNewValue) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
for(String s : pTargets) {
Score score = scoreboard.getOrCreatePlayerScore(s, pObjective);
score.setScore(pNewValue);
}
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.set.success.single", pObjective.getFormattedDisplayName(), pTargets.iterator().next(), pNewValue);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.set.success.multiple", pObjective.getFormattedDisplayName(), pTargets.size(), pNewValue);
}, true);
}
return pNewValue * pTargets.size();
}
private static int addScore(CommandSourceStack pSource, Collection<String> pTargets, Objective pObjective, int pAmount) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
int i = 0;
for(String s : pTargets) {
Score score = scoreboard.getOrCreatePlayerScore(s, pObjective);
score.setScore(score.getScore() + pAmount);
i += score.getScore();
}
if (pTargets.size() == 1) {
int j = i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.add.success.single", pAmount, pObjective.getFormattedDisplayName(), pTargets.iterator().next(), j);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.add.success.multiple", pAmount, pObjective.getFormattedDisplayName(), pTargets.size());
}, true);
}
return i;
}
private static int removeScore(CommandSourceStack pSource, Collection<String> pTargets, Objective pObjective, int pAmount) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
int i = 0;
for(String s : pTargets) {
Score score = scoreboard.getOrCreatePlayerScore(s, pObjective);
score.setScore(score.getScore() - pAmount);
i += score.getScore();
}
if (pTargets.size() == 1) {
int j = i;
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.remove.success.single", pAmount, pObjective.getFormattedDisplayName(), pTargets.iterator().next(), j);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.remove.success.multiple", pAmount, pObjective.getFormattedDisplayName(), pTargets.size());
}, true);
}
return i;
}
private static int listTrackedPlayers(CommandSourceStack pSource) {
Collection<String> collection = pSource.getServer().getScoreboard().getTrackedPlayers();
if (collection.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.empty");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.success", collection.size(), ComponentUtils.formatList(collection));
}, false);
}
return collection.size();
}
private static int listTrackedPlayerScores(CommandSourceStack pSource, String pPlayer) {
Map<Objective, Score> map = pSource.getServer().getScoreboard().getPlayerScores(pPlayer);
if (map.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.entity.empty", pPlayer);
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.entity.success", pPlayer, map.size());
}, false);
for(Map.Entry<Objective, Score> entry : map.entrySet()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.entity.entry", entry.getKey().getFormattedDisplayName(), entry.getValue().getScore());
}, false);
}
}
return map.size();
}
private static int clearDisplaySlot(CommandSourceStack pSource, int pSlotId) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
if (scoreboard.getDisplayObjective(pSlotId) == null) {
throw ERROR_DISPLAY_SLOT_ALREADY_EMPTY.create();
} else {
scoreboard.setDisplayObjective(pSlotId, (Objective)null);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.display.cleared", Scoreboard.getDisplaySlotNames()[pSlotId]);
}, true);
return 0;
}
}
private static int setDisplaySlot(CommandSourceStack pSource, int pSlotId, Objective pObjective) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
if (scoreboard.getDisplayObjective(pSlotId) == pObjective) {
throw ERROR_DISPLAY_SLOT_ALREADY_SET.create();
} else {
scoreboard.setDisplayObjective(pSlotId, pObjective);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.display.set", Scoreboard.getDisplaySlotNames()[pSlotId], pObjective.getDisplayName());
}, true);
return 0;
}
}
private static int setDisplayName(CommandSourceStack pSource, Objective pObjective, Component pDisplayName) {
if (!pObjective.getDisplayName().equals(pDisplayName)) {
pObjective.setDisplayName(pDisplayName);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.modify.displayname", pObjective.getName(), pObjective.getFormattedDisplayName());
}, true);
}
return 0;
}
private static int setRenderType(CommandSourceStack pSource, Objective pObjective, ObjectiveCriteria.RenderType pRenderType) {
if (pObjective.getRenderType() != pRenderType) {
pObjective.setRenderType(pRenderType);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.modify.rendertype", pObjective.getFormattedDisplayName());
}, true);
}
return 0;
}
private static int removeObjective(CommandSourceStack pSource, Objective pObjective) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
scoreboard.removeObjective(pObjective);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.remove.success", pObjective.getFormattedDisplayName());
}, true);
return scoreboard.getObjectives().size();
}
private static int addObjective(CommandSourceStack pSource, String pName, ObjectiveCriteria pCriteria, Component pDisplayName) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
if (scoreboard.getObjective(pName) != null) {
throw ERROR_OBJECTIVE_ALREADY_EXISTS.create();
} else {
scoreboard.addObjective(pName, pCriteria, pDisplayName, pCriteria.getDefaultRenderType());
Objective objective = scoreboard.getObjective(pName);
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.add.success", objective.getFormattedDisplayName());
}, true);
return scoreboard.getObjectives().size();
}
}
private static int listObjectives(CommandSourceStack pSource) {
Collection<Objective> collection = pSource.getServer().getScoreboard().getObjectives();
if (collection.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.list.empty");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.list.success", collection.size(), ComponentUtils.formatList(collection, Objective::getFormattedDisplayName));
}, false);
}
return collection.size();
}
}
@@ -0,0 +1,22 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
public class SeedCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, boolean p_138591_) {
pDispatcher.register(Commands.literal("seed").requires((p_138596_) -> {
return !p_138591_ || p_138596_.hasPermission(2);
}).executes((p_288608_) -> {
long i = p_288608_.getSource().getLevel().getSeed();
Component component = ComponentUtils.copyOnClickText(String.valueOf(i));
p_288608_.getSource().sendSuccess(() -> {
return Component.translatable("commands.seed.success", component);
}, false);
return (int)i;
}));
}
}
@@ -0,0 +1,77 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.blocks.BlockInput;
import net.minecraft.commands.arguments.blocks.BlockStateArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Clearable;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
public class SetBlockCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.setblock.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("setblock").requires((p_138606_) -> {
return p_138606_.hasPermission(2);
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).then(Commands.argument("block", BlockStateArgument.block(pContext)).executes((p_138618_) -> {
return setBlock(p_138618_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138618_, "pos"), BlockStateArgument.getBlock(p_138618_, "block"), SetBlockCommand.Mode.REPLACE, (Predicate<BlockInWorld>)null);
}).then(Commands.literal("destroy").executes((p_138616_) -> {
return setBlock(p_138616_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138616_, "pos"), BlockStateArgument.getBlock(p_138616_, "block"), SetBlockCommand.Mode.DESTROY, (Predicate<BlockInWorld>)null);
})).then(Commands.literal("keep").executes((p_138614_) -> {
return setBlock(p_138614_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138614_, "pos"), BlockStateArgument.getBlock(p_138614_, "block"), SetBlockCommand.Mode.REPLACE, (p_180517_) -> {
return p_180517_.getLevel().isEmptyBlock(p_180517_.getPos());
});
})).then(Commands.literal("replace").executes((p_138604_) -> {
return setBlock(p_138604_.getSource(), BlockPosArgument.getLoadedBlockPos(p_138604_, "pos"), BlockStateArgument.getBlock(p_138604_, "block"), SetBlockCommand.Mode.REPLACE, (Predicate<BlockInWorld>)null);
})))));
}
private static int setBlock(CommandSourceStack pSource, BlockPos pPos, BlockInput pState, SetBlockCommand.Mode pMode, @Nullable Predicate<BlockInWorld> pPredicate) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
if (pPredicate != null && !pPredicate.test(new BlockInWorld(serverlevel, pPos, true))) {
throw ERROR_FAILED.create();
} else {
boolean flag;
if (pMode == SetBlockCommand.Mode.DESTROY) {
serverlevel.destroyBlock(pPos, true);
flag = !pState.getState().isAir() || !serverlevel.getBlockState(pPos).isAir();
} else {
BlockEntity blockentity = serverlevel.getBlockEntity(pPos);
Clearable.tryClear(blockentity);
flag = true;
}
if (flag && !pState.place(serverlevel, pPos, 2)) {
throw ERROR_FAILED.create();
} else {
serverlevel.blockUpdated(pPos, pState.getState().getBlock());
pSource.sendSuccess(() -> {
return Component.translatable("commands.setblock.success", pPos.getX(), pPos.getY(), pPos.getZ());
}, true);
return 1;
}
}
}
public interface Filter {
@Nullable
BlockInput filter(BoundingBox pBoundingBox, BlockPos pPos, BlockInput pBlockInput, ServerLevel pLevel);
}
public static enum Mode {
REPLACE,
DESTROY;
}
}
@@ -0,0 +1,25 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
public class SetPlayerIdleTimeoutCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("setidletimeout").requires((p_138639_) -> {
return p_138639_.hasPermission(3);
}).then(Commands.argument("minutes", IntegerArgumentType.integer(0)).executes((p_138637_) -> {
return setIdleTimeout(p_138637_.getSource(), IntegerArgumentType.getInteger(p_138637_, "minutes"));
})));
}
private static int setIdleTimeout(CommandSourceStack pSource, int pIdleTimeout) {
pSource.getServer().setPlayerIdleTimeout(pIdleTimeout);
pSource.sendSuccess(() -> {
return Component.translatable("commands.setidletimeout.success", pIdleTimeout);
}, true);
return pIdleTimeout;
}
}
@@ -0,0 +1,52 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import java.util.Collection;
import java.util.Collections;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.AngleArgument;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
public class SetSpawnCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("spawnpoint").requires((p_138648_) -> {
return p_138648_.hasPermission(2);
}).executes((p_274828_) -> {
return setSpawn(p_274828_.getSource(), Collections.singleton(p_274828_.getSource().getPlayerOrException()), BlockPos.containing(p_274828_.getSource().getPosition()), 0.0F);
}).then(Commands.argument("targets", EntityArgument.players()).executes((p_274829_) -> {
return setSpawn(p_274829_.getSource(), EntityArgument.getPlayers(p_274829_, "targets"), BlockPos.containing(p_274829_.getSource().getPosition()), 0.0F);
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_138655_) -> {
return setSpawn(p_138655_.getSource(), EntityArgument.getPlayers(p_138655_, "targets"), BlockPosArgument.getSpawnablePos(p_138655_, "pos"), 0.0F);
}).then(Commands.argument("angle", AngleArgument.angle()).executes((p_138646_) -> {
return setSpawn(p_138646_.getSource(), EntityArgument.getPlayers(p_138646_, "targets"), BlockPosArgument.getSpawnablePos(p_138646_, "pos"), AngleArgument.getAngle(p_138646_, "angle"));
})))));
}
private static int setSpawn(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, BlockPos pPos, float pAngle) {
ResourceKey<Level> resourcekey = pSource.getLevel().dimension();
for(ServerPlayer serverplayer : pTargets) {
serverplayer.setRespawnPosition(resourcekey, pPos, pAngle, true, false);
}
String s = resourcekey.location().toString();
if (pTargets.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.spawnpoint.success.single", pPos.getX(), pPos.getY(), pPos.getZ(), pAngle, s, pTargets.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.spawnpoint.success.multiple", pPos.getX(), pPos.getY(), pPos.getZ(), pAngle, s, pTargets.size());
}, true);
}
return pTargets.size();
}
}
@@ -0,0 +1,31 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.AngleArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
public class SetWorldSpawnCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("setworldspawn").requires((p_138665_) -> {
return p_138665_.hasPermission(2);
}).executes((p_274830_) -> {
return setSpawn(p_274830_.getSource(), BlockPos.containing(p_274830_.getSource().getPosition()), 0.0F);
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_138671_) -> {
return setSpawn(p_138671_.getSource(), BlockPosArgument.getSpawnablePos(p_138671_, "pos"), 0.0F);
}).then(Commands.argument("angle", AngleArgument.angle()).executes((p_138663_) -> {
return setSpawn(p_138663_.getSource(), BlockPosArgument.getSpawnablePos(p_138663_, "pos"), AngleArgument.getAngle(p_138663_, "angle"));
}))));
}
private static int setSpawn(CommandSourceStack pSource, BlockPos pPos, float pAngle) {
pSource.getLevel().setDefaultSpawnPos(pPos, pAngle);
pSource.sendSuccess(() -> {
return Component.translatable("commands.setworldspawn.success", pPos.getX(), pPos.getY(), pPos.getZ(), pAngle);
}, true);
return 1;
}
}
@@ -0,0 +1,134 @@
package net.minecraft.server.commands;
import com.google.common.collect.Maps;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.datafixers.util.Pair;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.ToIntFunction;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.decoration.ArmorStand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.ArmorMaterial;
import net.minecraft.world.item.ArmorMaterials;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.armortrim.ArmorTrim;
import net.minecraft.world.item.armortrim.TrimMaterial;
import net.minecraft.world.item.armortrim.TrimMaterials;
import net.minecraft.world.item.armortrim.TrimPattern;
import net.minecraft.world.item.armortrim.TrimPatterns;
import net.minecraft.world.level.Level;
public class SpawnArmorTrimsCommand {
private static final Map<Pair<ArmorMaterial, EquipmentSlot>, Item> MATERIAL_AND_SLOT_TO_ITEM = Util.make(Maps.newHashMap(), (p_266706_) -> {
p_266706_.put(Pair.of(ArmorMaterials.CHAIN, EquipmentSlot.HEAD), Items.CHAINMAIL_HELMET);
p_266706_.put(Pair.of(ArmorMaterials.CHAIN, EquipmentSlot.CHEST), Items.CHAINMAIL_CHESTPLATE);
p_266706_.put(Pair.of(ArmorMaterials.CHAIN, EquipmentSlot.LEGS), Items.CHAINMAIL_LEGGINGS);
p_266706_.put(Pair.of(ArmorMaterials.CHAIN, EquipmentSlot.FEET), Items.CHAINMAIL_BOOTS);
p_266706_.put(Pair.of(ArmorMaterials.IRON, EquipmentSlot.HEAD), Items.IRON_HELMET);
p_266706_.put(Pair.of(ArmorMaterials.IRON, EquipmentSlot.CHEST), Items.IRON_CHESTPLATE);
p_266706_.put(Pair.of(ArmorMaterials.IRON, EquipmentSlot.LEGS), Items.IRON_LEGGINGS);
p_266706_.put(Pair.of(ArmorMaterials.IRON, EquipmentSlot.FEET), Items.IRON_BOOTS);
p_266706_.put(Pair.of(ArmorMaterials.GOLD, EquipmentSlot.HEAD), Items.GOLDEN_HELMET);
p_266706_.put(Pair.of(ArmorMaterials.GOLD, EquipmentSlot.CHEST), Items.GOLDEN_CHESTPLATE);
p_266706_.put(Pair.of(ArmorMaterials.GOLD, EquipmentSlot.LEGS), Items.GOLDEN_LEGGINGS);
p_266706_.put(Pair.of(ArmorMaterials.GOLD, EquipmentSlot.FEET), Items.GOLDEN_BOOTS);
p_266706_.put(Pair.of(ArmorMaterials.NETHERITE, EquipmentSlot.HEAD), Items.NETHERITE_HELMET);
p_266706_.put(Pair.of(ArmorMaterials.NETHERITE, EquipmentSlot.CHEST), Items.NETHERITE_CHESTPLATE);
p_266706_.put(Pair.of(ArmorMaterials.NETHERITE, EquipmentSlot.LEGS), Items.NETHERITE_LEGGINGS);
p_266706_.put(Pair.of(ArmorMaterials.NETHERITE, EquipmentSlot.FEET), Items.NETHERITE_BOOTS);
p_266706_.put(Pair.of(ArmorMaterials.DIAMOND, EquipmentSlot.HEAD), Items.DIAMOND_HELMET);
p_266706_.put(Pair.of(ArmorMaterials.DIAMOND, EquipmentSlot.CHEST), Items.DIAMOND_CHESTPLATE);
p_266706_.put(Pair.of(ArmorMaterials.DIAMOND, EquipmentSlot.LEGS), Items.DIAMOND_LEGGINGS);
p_266706_.put(Pair.of(ArmorMaterials.DIAMOND, EquipmentSlot.FEET), Items.DIAMOND_BOOTS);
p_266706_.put(Pair.of(ArmorMaterials.TURTLE, EquipmentSlot.HEAD), Items.TURTLE_HELMET);
});
private static final List<ResourceKey<TrimPattern>> VANILLA_TRIM_PATTERNS = List.of(TrimPatterns.SENTRY, TrimPatterns.DUNE, TrimPatterns.COAST, TrimPatterns.WILD, TrimPatterns.WARD, TrimPatterns.EYE, TrimPatterns.VEX, TrimPatterns.TIDE, TrimPatterns.SNOUT, TrimPatterns.RIB, TrimPatterns.SPIRE, TrimPatterns.WAYFINDER, TrimPatterns.SHAPER, TrimPatterns.SILENCE, TrimPatterns.RAISER, TrimPatterns.HOST);
private static final List<ResourceKey<TrimMaterial>> VANILLA_TRIM_MATERIALS = List.of(TrimMaterials.QUARTZ, TrimMaterials.IRON, TrimMaterials.NETHERITE, TrimMaterials.REDSTONE, TrimMaterials.COPPER, TrimMaterials.GOLD, TrimMaterials.EMERALD, TrimMaterials.DIAMOND, TrimMaterials.LAPIS, TrimMaterials.AMETHYST);
private static final ToIntFunction<ResourceKey<TrimPattern>> TRIM_PATTERN_ORDER = Util.createIndexLookup(VANILLA_TRIM_PATTERNS);
private static final ToIntFunction<ResourceKey<TrimMaterial>> TRIM_MATERIAL_ORDER = Util.createIndexLookup(VANILLA_TRIM_MATERIALS);
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("spawn_armor_trims").requires((p_277270_) -> {
return p_277270_.hasPermission(2);
}).executes((p_267005_) -> {
return spawnArmorTrims(p_267005_.getSource(), p_267005_.getSource().getPlayerOrException());
}));
}
private static int spawnArmorTrims(CommandSourceStack pSource, Player pPlayer) {
Level level = pPlayer.level();
NonNullList<ArmorTrim> nonnulllist = NonNullList.create();
Registry<TrimPattern> registry = level.registryAccess().registryOrThrow(Registries.TRIM_PATTERN);
Registry<TrimMaterial> registry1 = level.registryAccess().registryOrThrow(Registries.TRIM_MATERIAL);
registry.stream().sorted(Comparator.comparing((p_266941_) -> {
return TRIM_PATTERN_ORDER.applyAsInt(registry.getResourceKey(p_266941_).orElse((ResourceKey<TrimPattern>)null));
})).forEachOrdered((p_266759_) -> {
registry1.stream().sorted(Comparator.comparing((p_267239_) -> {
return TRIM_MATERIAL_ORDER.applyAsInt(registry1.getResourceKey(p_267239_).orElse((ResourceKey<TrimMaterial>)null));
})).forEachOrdered((p_267162_) -> {
nonnulllist.add(new ArmorTrim(registry1.wrapAsHolder(p_267162_), registry.wrapAsHolder(p_266759_)));
});
});
BlockPos blockpos = pPlayer.blockPosition().relative(pPlayer.getDirection(), 5);
int i = ArmorMaterials.values().length - 1;
double d0 = 3.0D;
int j = 0;
int k = 0;
for(ArmorTrim armortrim : nonnulllist) {
for(ArmorMaterial armormaterial : ArmorMaterials.values()) {
if (armormaterial != ArmorMaterials.LEATHER) {
double d1 = (double)blockpos.getX() + 0.5D - (double)(j % registry1.size()) * 3.0D;
double d2 = (double)blockpos.getY() + 0.5D + (double)(k % i) * 3.0D;
double d3 = (double)blockpos.getZ() + 0.5D + (double)(j / registry1.size() * 10);
ArmorStand armorstand = new ArmorStand(level, d1, d2, d3);
armorstand.setYRot(180.0F);
armorstand.setNoGravity(true);
for(EquipmentSlot equipmentslot : EquipmentSlot.values()) {
Item item = MATERIAL_AND_SLOT_TO_ITEM.get(Pair.of(armormaterial, equipmentslot));
if (item != null) {
ItemStack itemstack = new ItemStack(item);
ArmorTrim.setTrim(level.registryAccess(), itemstack, armortrim);
armorstand.setItemSlot(equipmentslot, itemstack);
if (item instanceof ArmorItem) {
ArmorItem armoritem = (ArmorItem)item;
if (armoritem.getMaterial() == ArmorMaterials.TURTLE) {
armorstand.setCustomName(armortrim.pattern().value().copyWithStyle(armortrim.material()).copy().append(" ").append(armortrim.material().value().description()));
armorstand.setCustomNameVisible(true);
continue;
}
}
armorstand.setInvisible(true);
}
}
level.addFreshEntity(armorstand);
++k;
}
}
++j;
}
pSource.sendSuccess(() -> {
return Component.literal("Armorstands with trimmed armor spawned around you");
}, true);
return 1;
}
}
@@ -0,0 +1,54 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.GameType;
public class SpectateCommand {
private static final SimpleCommandExceptionType ERROR_SELF = new SimpleCommandExceptionType(Component.translatable("commands.spectate.self"));
private static final DynamicCommandExceptionType ERROR_NOT_SPECTATOR = new DynamicCommandExceptionType((p_138688_) -> {
return Component.translatable("commands.spectate.not_spectator", p_138688_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("spectate").requires((p_138682_) -> {
return p_138682_.hasPermission(2);
}).executes((p_138692_) -> {
return spectate(p_138692_.getSource(), (Entity)null, p_138692_.getSource().getPlayerOrException());
}).then(Commands.argument("target", EntityArgument.entity()).executes((p_138690_) -> {
return spectate(p_138690_.getSource(), EntityArgument.getEntity(p_138690_, "target"), p_138690_.getSource().getPlayerOrException());
}).then(Commands.argument("player", EntityArgument.player()).executes((p_138680_) -> {
return spectate(p_138680_.getSource(), EntityArgument.getEntity(p_138680_, "target"), EntityArgument.getPlayer(p_138680_, "player"));
}))));
}
private static int spectate(CommandSourceStack pSource, @Nullable Entity pTarget, ServerPlayer pPlayer) throws CommandSyntaxException {
if (pPlayer == pTarget) {
throw ERROR_SELF.create();
} else if (pPlayer.gameMode.getGameModeForPlayer() != GameType.SPECTATOR) {
throw ERROR_NOT_SPECTATOR.create(pPlayer.getDisplayName());
} else {
pPlayer.setCamera(pTarget);
if (pTarget != null) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.spectate.success.started", pTarget.getDisplayName());
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.spectate.success.stopped");
}, false);
}
return 1;
}
}
}
@@ -0,0 +1,286 @@
package net.minecraft.server.commands;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.Dynamic4CommandExceptionType;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.coordinates.Vec2Argument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.BlockTags;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.scores.Team;
public class SpreadPlayersCommand {
private static final int MAX_ITERATION_COUNT = 10000;
private static final Dynamic4CommandExceptionType ERROR_FAILED_TO_SPREAD_TEAMS = new Dynamic4CommandExceptionType((p_138745_, p_138746_, p_138747_, p_138748_) -> {
return Component.translatable("commands.spreadplayers.failed.teams", p_138745_, p_138746_, p_138747_, p_138748_);
});
private static final Dynamic4CommandExceptionType ERROR_FAILED_TO_SPREAD_ENTITIES = new Dynamic4CommandExceptionType((p_138723_, p_138724_, p_138725_, p_138726_) -> {
return Component.translatable("commands.spreadplayers.failed.entities", p_138723_, p_138724_, p_138725_, p_138726_);
});
private static final Dynamic2CommandExceptionType ERROR_INVALID_MAX_HEIGHT = new Dynamic2CommandExceptionType((p_201854_, p_201855_) -> {
return Component.translatable("commands.spreadplayers.failed.invalid.height", p_201854_, p_201855_);
});
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("spreadplayers").requires((p_201852_) -> {
return p_201852_.hasPermission(2);
}).then(Commands.argument("center", Vec2Argument.vec2()).then(Commands.argument("spreadDistance", FloatArgumentType.floatArg(0.0F)).then(Commands.argument("maxRange", FloatArgumentType.floatArg(1.0F)).then(Commands.argument("respectTeams", BoolArgumentType.bool()).then(Commands.argument("targets", EntityArgument.entities()).executes((p_288627_) -> {
return spreadPlayers(p_288627_.getSource(), Vec2Argument.getVec2(p_288627_, "center"), FloatArgumentType.getFloat(p_288627_, "spreadDistance"), FloatArgumentType.getFloat(p_288627_, "maxRange"), p_288627_.getSource().getLevel().getMaxBuildHeight(), BoolArgumentType.getBool(p_288627_, "respectTeams"), EntityArgument.getEntities(p_288627_, "targets"));
}))).then(Commands.literal("under").then(Commands.argument("maxHeight", IntegerArgumentType.integer()).then(Commands.argument("respectTeams", BoolArgumentType.bool()).then(Commands.argument("targets", EntityArgument.entities()).executes((p_201850_) -> {
return spreadPlayers(p_201850_.getSource(), Vec2Argument.getVec2(p_201850_, "center"), FloatArgumentType.getFloat(p_201850_, "spreadDistance"), FloatArgumentType.getFloat(p_201850_, "maxRange"), IntegerArgumentType.getInteger(p_201850_, "maxHeight"), BoolArgumentType.getBool(p_201850_, "respectTeams"), EntityArgument.getEntities(p_201850_, "targets"));
})))))))));
}
private static int spreadPlayers(CommandSourceStack pSource, Vec2 pCenter, float pSpreadDistance, float pMaxRange, int pMaxHeight, boolean pRespectTeams, Collection<? extends Entity> pTargets) throws CommandSyntaxException {
ServerLevel serverlevel = pSource.getLevel();
int i = serverlevel.getMinBuildHeight();
if (pMaxHeight < i) {
throw ERROR_INVALID_MAX_HEIGHT.create(pMaxHeight, i);
} else {
RandomSource randomsource = RandomSource.create();
double d0 = (double)(pCenter.x - pMaxRange);
double d1 = (double)(pCenter.y - pMaxRange);
double d2 = (double)(pCenter.x + pMaxRange);
double d3 = (double)(pCenter.y + pMaxRange);
SpreadPlayersCommand.Position[] aspreadplayerscommand$position = createInitialPositions(randomsource, pRespectTeams ? getNumberOfTeams(pTargets) : pTargets.size(), d0, d1, d2, d3);
spreadPositions(pCenter, (double)pSpreadDistance, serverlevel, randomsource, d0, d1, d2, d3, pMaxHeight, aspreadplayerscommand$position, pRespectTeams);
double d4 = setPlayerPositions(pTargets, serverlevel, aspreadplayerscommand$position, pMaxHeight, pRespectTeams);
pSource.sendSuccess(() -> {
return Component.translatable("commands.spreadplayers.success." + (pRespectTeams ? "teams" : "entities"), aspreadplayerscommand$position.length, pCenter.x, pCenter.y, String.format(Locale.ROOT, "%.2f", d4));
}, true);
return aspreadplayerscommand$position.length;
}
}
/**
* Gets the number of unique teams for the given list of entities.
*/
private static int getNumberOfTeams(Collection<? extends Entity> pEntities) {
Set<Team> set = Sets.newHashSet();
for(Entity entity : pEntities) {
if (entity instanceof Player) {
set.add(entity.getTeam());
} else {
set.add((Team)null);
}
}
return set.size();
}
private static void spreadPositions(Vec2 pCenter, double pSpreadDistance, ServerLevel pLevel, RandomSource pRandom, double pMinX, double pMinZ, double pMaxX, double pMaxZ, int pMaxHeight, SpreadPlayersCommand.Position[] pPositions, boolean pRespectTeams) throws CommandSyntaxException {
boolean flag = true;
double d0 = (double)Float.MAX_VALUE;
int i;
for(i = 0; i < 10000 && flag; ++i) {
flag = false;
d0 = (double)Float.MAX_VALUE;
for(int j = 0; j < pPositions.length; ++j) {
SpreadPlayersCommand.Position spreadplayerscommand$position = pPositions[j];
int k = 0;
SpreadPlayersCommand.Position spreadplayerscommand$position1 = new SpreadPlayersCommand.Position();
for(int l = 0; l < pPositions.length; ++l) {
if (j != l) {
SpreadPlayersCommand.Position spreadplayerscommand$position2 = pPositions[l];
double d1 = spreadplayerscommand$position.dist(spreadplayerscommand$position2);
d0 = Math.min(d1, d0);
if (d1 < pSpreadDistance) {
++k;
spreadplayerscommand$position1.x += spreadplayerscommand$position2.x - spreadplayerscommand$position.x;
spreadplayerscommand$position1.z += spreadplayerscommand$position2.z - spreadplayerscommand$position.z;
}
}
}
if (k > 0) {
spreadplayerscommand$position1.x /= (double)k;
spreadplayerscommand$position1.z /= (double)k;
double d2 = spreadplayerscommand$position1.getLength();
if (d2 > 0.0D) {
spreadplayerscommand$position1.normalize();
spreadplayerscommand$position.moveAway(spreadplayerscommand$position1);
} else {
spreadplayerscommand$position.randomize(pRandom, pMinX, pMinZ, pMaxX, pMaxZ);
}
flag = true;
}
if (spreadplayerscommand$position.clamp(pMinX, pMinZ, pMaxX, pMaxZ)) {
flag = true;
}
}
if (!flag) {
for(SpreadPlayersCommand.Position spreadplayerscommand$position3 : pPositions) {
if (!spreadplayerscommand$position3.isSafe(pLevel, pMaxHeight)) {
spreadplayerscommand$position3.randomize(pRandom, pMinX, pMinZ, pMaxX, pMaxZ);
flag = true;
}
}
}
}
if (d0 == (double)Float.MAX_VALUE) {
d0 = 0.0D;
}
if (i >= 10000) {
if (pRespectTeams) {
throw ERROR_FAILED_TO_SPREAD_TEAMS.create(pPositions.length, pCenter.x, pCenter.y, String.format(Locale.ROOT, "%.2f", d0));
} else {
throw ERROR_FAILED_TO_SPREAD_ENTITIES.create(pPositions.length, pCenter.x, pCenter.y, String.format(Locale.ROOT, "%.2f", d0));
}
}
}
private static double setPlayerPositions(Collection<? extends Entity> pTargets, ServerLevel pLevel, SpreadPlayersCommand.Position[] pPositions, int pMaxHeight, boolean pRespectTeams) {
double d0 = 0.0D;
int i = 0;
Map<Team, SpreadPlayersCommand.Position> map = Maps.newHashMap();
for(Entity entity : pTargets) {
SpreadPlayersCommand.Position spreadplayerscommand$position;
if (pRespectTeams) {
Team team = entity instanceof Player ? entity.getTeam() : null;
if (!map.containsKey(team)) {
map.put(team, pPositions[i++]);
}
spreadplayerscommand$position = map.get(team);
} else {
spreadplayerscommand$position = pPositions[i++];
}
net.minecraftforge.event.entity.EntityTeleportEvent.SpreadPlayersCommand event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportSpreadPlayersCommand(entity, (double)Mth.floor(spreadplayerscommand$position.x) + 0.5D, (double)spreadplayerscommand$position.getSpawnY(pLevel, pMaxHeight), (double)Mth.floor(spreadplayerscommand$position.z) + 0.5D);
if (!event.isCanceled()) entity.teleportToWithTicket(event.getTargetX(), event.getTargetY(), event.getTargetZ());
double d2 = Double.MAX_VALUE;
for(SpreadPlayersCommand.Position spreadplayerscommand$position1 : pPositions) {
if (spreadplayerscommand$position != spreadplayerscommand$position1) {
double d1 = spreadplayerscommand$position.dist(spreadplayerscommand$position1);
d2 = Math.min(d1, d2);
}
}
d0 += d2;
}
return pTargets.size() < 2 ? 0.0D : d0 / (double)pTargets.size();
}
private static SpreadPlayersCommand.Position[] createInitialPositions(RandomSource pRandom, int pCount, double pMinX, double pMinZ, double pMaxX, double pMaxZ) {
SpreadPlayersCommand.Position[] aspreadplayerscommand$position = new SpreadPlayersCommand.Position[pCount];
for(int i = 0; i < aspreadplayerscommand$position.length; ++i) {
SpreadPlayersCommand.Position spreadplayerscommand$position = new SpreadPlayersCommand.Position();
spreadplayerscommand$position.randomize(pRandom, pMinX, pMinZ, pMaxX, pMaxZ);
aspreadplayerscommand$position[i] = spreadplayerscommand$position;
}
return aspreadplayerscommand$position;
}
static class Position {
double x;
double z;
double dist(SpreadPlayersCommand.Position pOther) {
double d0 = this.x - pOther.x;
double d1 = this.z - pOther.z;
return Math.sqrt(d0 * d0 + d1 * d1);
}
void normalize() {
double d0 = this.getLength();
this.x /= d0;
this.z /= d0;
}
double getLength() {
return Math.sqrt(this.x * this.x + this.z * this.z);
}
public void moveAway(SpreadPlayersCommand.Position pOther) {
this.x -= pOther.x;
this.z -= pOther.z;
}
public boolean clamp(double pMinX, double pMinZ, double pMaxX, double pMaxZ) {
boolean flag = false;
if (this.x < pMinX) {
this.x = pMinX;
flag = true;
} else if (this.x > pMaxX) {
this.x = pMaxX;
flag = true;
}
if (this.z < pMinZ) {
this.z = pMinZ;
flag = true;
} else if (this.z > pMaxZ) {
this.z = pMaxZ;
flag = true;
}
return flag;
}
public int getSpawnY(BlockGetter pLevel, int pY) {
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(this.x, (double)(pY + 1), this.z);
boolean flag = pLevel.getBlockState(blockpos$mutableblockpos).isAir();
blockpos$mutableblockpos.move(Direction.DOWN);
boolean flag2;
for(boolean flag1 = pLevel.getBlockState(blockpos$mutableblockpos).isAir(); blockpos$mutableblockpos.getY() > pLevel.getMinBuildHeight(); flag1 = flag2) {
blockpos$mutableblockpos.move(Direction.DOWN);
flag2 = pLevel.getBlockState(blockpos$mutableblockpos).isAir();
if (!flag2 && flag1 && flag) {
return blockpos$mutableblockpos.getY() + 1;
}
flag = flag1;
}
return pY + 1;
}
public boolean isSafe(BlockGetter pLevel, int pY) {
BlockPos blockpos = BlockPos.containing(this.x, (double)(this.getSpawnY(pLevel, pY) - 1), this.z);
BlockState blockstate = pLevel.getBlockState(blockpos);
return blockpos.getY() < pY && !blockstate.liquid() && !blockstate.is(BlockTags.FIRE);
}
public void randomize(RandomSource pRandom, double pMinX, double pMinZ, double pMaxX, double pMaxZ) {
this.x = Mth.nextDouble(pRandom, pMinX, pMaxX);
this.z = Mth.nextDouble(pRandom, pMinZ, pMaxZ);
}
}
}
@@ -0,0 +1,20 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
public class StopCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("stop").requires((p_138790_) -> {
return p_138790_.hasPermission(4);
}).executes((p_288628_) -> {
p_288628_.getSource().sendSuccess(() -> {
return Component.translatable("commands.stop.stopping");
}, true);
p_288628_.getSource().getServer().halt(false);
return 1;
}));
}
}
@@ -0,0 +1,69 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import java.util.Collection;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundStopSoundPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundSource;
public class StopSoundCommand {
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
RequiredArgumentBuilder<CommandSourceStack, EntitySelector> requiredargumentbuilder = Commands.argument("targets", EntityArgument.players()).executes((p_138809_) -> {
return stopSound(p_138809_.getSource(), EntityArgument.getPlayers(p_138809_, "targets"), (SoundSource)null, (ResourceLocation)null);
}).then(Commands.literal("*").then(Commands.argument("sound", ResourceLocationArgument.id()).suggests(SuggestionProviders.AVAILABLE_SOUNDS).executes((p_138797_) -> {
return stopSound(p_138797_.getSource(), EntityArgument.getPlayers(p_138797_, "targets"), (SoundSource)null, ResourceLocationArgument.getId(p_138797_, "sound"));
})));
for(SoundSource soundsource : SoundSource.values()) {
requiredargumentbuilder.then(Commands.literal(soundsource.getName()).executes((p_138807_) -> {
return stopSound(p_138807_.getSource(), EntityArgument.getPlayers(p_138807_, "targets"), soundsource, (ResourceLocation)null);
}).then(Commands.argument("sound", ResourceLocationArgument.id()).suggests(SuggestionProviders.AVAILABLE_SOUNDS).executes((p_138793_) -> {
return stopSound(p_138793_.getSource(), EntityArgument.getPlayers(p_138793_, "targets"), soundsource, ResourceLocationArgument.getId(p_138793_, "sound"));
})));
}
pDispatcher.register(Commands.literal("stopsound").requires((p_138799_) -> {
return p_138799_.hasPermission(2);
}).then(requiredargumentbuilder));
}
private static int stopSound(CommandSourceStack pSource, Collection<ServerPlayer> pTargets, @Nullable SoundSource pCategory, @Nullable ResourceLocation pSound) {
ClientboundStopSoundPacket clientboundstopsoundpacket = new ClientboundStopSoundPacket(pSound, pCategory);
for(ServerPlayer serverplayer : pTargets) {
serverplayer.connection.send(clientboundstopsoundpacket);
}
if (pCategory != null) {
if (pSound != null) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.source.sound", pSound, pCategory.getName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.source.any", pCategory.getName());
}, true);
}
} else if (pSound != null) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.sourceless.sound", pSound);
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.sourceless.any");
}, true);
}
return pTargets.size();
}
}
@@ -0,0 +1,79 @@
package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.CompoundTagArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.entity.SpawnGroupData;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
public class SummonCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.summon.failed"));
private static final SimpleCommandExceptionType ERROR_DUPLICATE_UUID = new SimpleCommandExceptionType(Component.translatable("commands.summon.failed.uuid"));
private static final SimpleCommandExceptionType INVALID_POSITION = new SimpleCommandExceptionType(Component.translatable("commands.summon.invalidPosition"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher, CommandBuildContext pContext) {
pDispatcher.register(Commands.literal("summon").requires((p_138819_) -> {
return p_138819_.hasPermission(2);
}).then(Commands.argument("entity", ResourceArgument.resource(pContext, Registries.ENTITY_TYPE)).suggests(SuggestionProviders.SUMMONABLE_ENTITIES).executes((p_248175_) -> {
return spawnEntity(p_248175_.getSource(), ResourceArgument.getSummonableEntityType(p_248175_, "entity"), p_248175_.getSource().getPosition(), new CompoundTag(), true);
}).then(Commands.argument("pos", Vec3Argument.vec3()).executes((p_248173_) -> {
return spawnEntity(p_248173_.getSource(), ResourceArgument.getSummonableEntityType(p_248173_, "entity"), Vec3Argument.getVec3(p_248173_, "pos"), new CompoundTag(), true);
}).then(Commands.argument("nbt", CompoundTagArgument.compoundTag()).executes((p_248174_) -> {
return spawnEntity(p_248174_.getSource(), ResourceArgument.getSummonableEntityType(p_248174_, "entity"), Vec3Argument.getVec3(p_248174_, "pos"), CompoundTagArgument.getCompoundTag(p_248174_, "nbt"), false);
})))));
}
public static Entity createEntity(CommandSourceStack pSource, Holder.Reference<EntityType<?>> pType, Vec3 pPos, CompoundTag pTag, boolean pRandomizeProperties) throws CommandSyntaxException {
BlockPos blockpos = BlockPos.containing(pPos);
if (!Level.isInSpawnableBounds(blockpos)) {
throw INVALID_POSITION.create();
} else {
CompoundTag compoundtag = pTag.copy();
compoundtag.putString("id", pType.key().location().toString());
ServerLevel serverlevel = pSource.getLevel();
Entity entity = EntityType.loadEntityRecursive(compoundtag, serverlevel, (p_138828_) -> {
p_138828_.moveTo(pPos.x, pPos.y, pPos.z, p_138828_.getYRot(), p_138828_.getXRot());
return p_138828_;
});
if (entity == null) {
throw ERROR_FAILED.create();
} else {
if (pRandomizeProperties && entity instanceof Mob) {
((Mob)entity).finalizeSpawn(pSource.getLevel(), pSource.getLevel().getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.COMMAND, (SpawnGroupData)null, (CompoundTag)null);
}
if (!serverlevel.tryAddFreshEntityWithPassengers(entity)) {
throw ERROR_DUPLICATE_UUID.create();
} else {
return entity;
}
}
}
}
private static int spawnEntity(CommandSourceStack pSource, Holder.Reference<EntityType<?>> pType, Vec3 pPos, CompoundTag pTag, boolean pRandomizeProperties) throws CommandSyntaxException {
Entity entity = createEntity(pSource, pType, pPos, pTag, pRandomizeProperties);
pSource.sendSuccess(() -> {
return Component.translatable("commands.summon.success", entity.getDisplayName());
}, true);
return 1;
}
}
@@ -0,0 +1,131 @@
package net.minecraft.server.commands;
import com.google.common.collect.Sets;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import java.util.Set;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.world.entity.Entity;
public class TagCommand {
private static final SimpleCommandExceptionType ERROR_ADD_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.tag.add.failed"));
private static final SimpleCommandExceptionType ERROR_REMOVE_FAILED = new SimpleCommandExceptionType(Component.translatable("commands.tag.remove.failed"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("tag").requires((p_138844_) -> {
return p_138844_.hasPermission(2);
}).then(Commands.argument("targets", EntityArgument.entities()).then(Commands.literal("add").then(Commands.argument("name", StringArgumentType.word()).executes((p_138861_) -> {
return addTag(p_138861_.getSource(), EntityArgument.getEntities(p_138861_, "targets"), StringArgumentType.getString(p_138861_, "name"));
}))).then(Commands.literal("remove").then(Commands.argument("name", StringArgumentType.word()).suggests((p_138841_, p_138842_) -> {
return SharedSuggestionProvider.suggest(getTags(EntityArgument.getEntities(p_138841_, "targets")), p_138842_);
}).executes((p_138855_) -> {
return removeTag(p_138855_.getSource(), EntityArgument.getEntities(p_138855_, "targets"), StringArgumentType.getString(p_138855_, "name"));
}))).then(Commands.literal("list").executes((p_138839_) -> {
return listTags(p_138839_.getSource(), EntityArgument.getEntities(p_138839_, "targets"));
}))));
}
/**
* Gets all tags that are present on at least one of the given entities.
*/
private static Collection<String> getTags(Collection<? extends Entity> pEntities) {
Set<String> set = Sets.newHashSet();
for(Entity entity : pEntities) {
set.addAll(entity.getTags());
}
return set;
}
private static int addTag(CommandSourceStack pSource, Collection<? extends Entity> pEntities, String pTagName) throws CommandSyntaxException {
int i = 0;
for(Entity entity : pEntities) {
if (entity.addTag(pTagName)) {
++i;
}
}
if (i == 0) {
throw ERROR_ADD_FAILED.create();
} else {
if (pEntities.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.add.success.single", pTagName, pEntities.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.add.success.multiple", pTagName, pEntities.size());
}, true);
}
return i;
}
}
private static int removeTag(CommandSourceStack pSource, Collection<? extends Entity> pEntities, String pTagName) throws CommandSyntaxException {
int i = 0;
for(Entity entity : pEntities) {
if (entity.removeTag(pTagName)) {
++i;
}
}
if (i == 0) {
throw ERROR_REMOVE_FAILED.create();
} else {
if (pEntities.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.remove.success.single", pTagName, pEntities.iterator().next().getDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.remove.success.multiple", pTagName, pEntities.size());
}, true);
}
return i;
}
}
private static int listTags(CommandSourceStack pSource, Collection<? extends Entity> pEntities) {
Set<String> set = Sets.newHashSet();
for(Entity entity : pEntities) {
set.addAll(entity.getTags());
}
if (pEntities.size() == 1) {
Entity entity1 = pEntities.iterator().next();
if (set.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.list.single.empty", entity1.getDisplayName());
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.list.single.success", entity1.getDisplayName(), set.size(), ComponentUtils.formatList(set));
}, false);
}
} else if (set.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.list.multiple.empty", pEntities.size());
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.tag.list.multiple.success", pEntities.size(), set.size(), ComponentUtils.formatList(set));
}, false);
}
return set.size();
}
}
@@ -0,0 +1,321 @@
package net.minecraft.server.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import java.util.Collections;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.ColorArgument;
import net.minecraft.commands.arguments.ComponentArgument;
import net.minecraft.commands.arguments.ScoreHolderArgument;
import net.minecraft.commands.arguments.TeamArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.world.scores.PlayerTeam;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.Team;
public class TeamCommand {
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_EXISTS = new SimpleCommandExceptionType(Component.translatable("commands.team.add.duplicate"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_EMPTY = new SimpleCommandExceptionType(Component.translatable("commands.team.empty.unchanged"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_NAME = new SimpleCommandExceptionType(Component.translatable("commands.team.option.name.unchanged"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_COLOR = new SimpleCommandExceptionType(Component.translatable("commands.team.option.color.unchanged"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_FRIENDLYFIRE_ENABLED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.friendlyfire.alreadyEnabled"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_FRIENDLYFIRE_DISABLED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.friendlyfire.alreadyDisabled"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_FRIENDLYINVISIBLES_ENABLED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.seeFriendlyInvisibles.alreadyEnabled"));
private static final SimpleCommandExceptionType ERROR_TEAM_ALREADY_FRIENDLYINVISIBLES_DISABLED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.seeFriendlyInvisibles.alreadyDisabled"));
private static final SimpleCommandExceptionType ERROR_TEAM_NAMETAG_VISIBLITY_UNCHANGED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.nametagVisibility.unchanged"));
private static final SimpleCommandExceptionType ERROR_TEAM_DEATH_MESSAGE_VISIBLITY_UNCHANGED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.deathMessageVisibility.unchanged"));
private static final SimpleCommandExceptionType ERROR_TEAM_COLLISION_UNCHANGED = new SimpleCommandExceptionType(Component.translatable("commands.team.option.collisionRule.unchanged"));
public static void register(CommandDispatcher<CommandSourceStack> pDispatcher) {
pDispatcher.register(Commands.literal("team").requires((p_183713_) -> {
return p_183713_.hasPermission(2);
}).then(Commands.literal("list").executes((p_183711_) -> {
return listTeams(p_183711_.getSource());
}).then(Commands.argument("team", TeamArgument.team()).executes((p_138876_) -> {
return listMembers(p_138876_.getSource(), TeamArgument.getTeam(p_138876_, "team"));
}))).then(Commands.literal("add").then(Commands.argument("team", StringArgumentType.word()).executes((p_138995_) -> {
return createTeam(p_138995_.getSource(), StringArgumentType.getString(p_138995_, "team"));
}).then(Commands.argument("displayName", ComponentArgument.textComponent()).executes((p_138993_) -> {
return createTeam(p_138993_.getSource(), StringArgumentType.getString(p_138993_, "team"), ComponentArgument.getComponent(p_138993_, "displayName"));
})))).then(Commands.literal("remove").then(Commands.argument("team", TeamArgument.team()).executes((p_138991_) -> {
return deleteTeam(p_138991_.getSource(), TeamArgument.getTeam(p_138991_, "team"));
}))).then(Commands.literal("empty").then(Commands.argument("team", TeamArgument.team()).executes((p_138989_) -> {
return emptyTeam(p_138989_.getSource(), TeamArgument.getTeam(p_138989_, "team"));
}))).then(Commands.literal("join").then(Commands.argument("team", TeamArgument.team()).executes((p_138987_) -> {
return joinTeam(p_138987_.getSource(), TeamArgument.getTeam(p_138987_, "team"), Collections.singleton(p_138987_.getSource().getEntityOrException().getScoreboardName()));
}).then(Commands.argument("members", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).executes((p_138985_) -> {
return joinTeam(p_138985_.getSource(), TeamArgument.getTeam(p_138985_, "team"), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138985_, "members"));
})))).then(Commands.literal("leave").then(Commands.argument("members", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).executes((p_138983_) -> {
return leaveTeam(p_138983_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_138983_, "members"));
}))).then(Commands.literal("modify").then(Commands.argument("team", TeamArgument.team()).then(Commands.literal("displayName").then(Commands.argument("displayName", ComponentArgument.textComponent()).executes((p_138981_) -> {
return setDisplayName(p_138981_.getSource(), TeamArgument.getTeam(p_138981_, "team"), ComponentArgument.getComponent(p_138981_, "displayName"));
}))).then(Commands.literal("color").then(Commands.argument("value", ColorArgument.color()).executes((p_138979_) -> {
return setColor(p_138979_.getSource(), TeamArgument.getTeam(p_138979_, "team"), ColorArgument.getColor(p_138979_, "value"));
}))).then(Commands.literal("friendlyFire").then(Commands.argument("allowed", BoolArgumentType.bool()).executes((p_138977_) -> {
return setFriendlyFire(p_138977_.getSource(), TeamArgument.getTeam(p_138977_, "team"), BoolArgumentType.getBool(p_138977_, "allowed"));
}))).then(Commands.literal("seeFriendlyInvisibles").then(Commands.argument("allowed", BoolArgumentType.bool()).executes((p_138975_) -> {
return setFriendlySight(p_138975_.getSource(), TeamArgument.getTeam(p_138975_, "team"), BoolArgumentType.getBool(p_138975_, "allowed"));
}))).then(Commands.literal("nametagVisibility").then(Commands.literal("never").executes((p_138973_) -> {
return setNametagVisibility(p_138973_.getSource(), TeamArgument.getTeam(p_138973_, "team"), Team.Visibility.NEVER);
})).then(Commands.literal("hideForOtherTeams").executes((p_138971_) -> {
return setNametagVisibility(p_138971_.getSource(), TeamArgument.getTeam(p_138971_, "team"), Team.Visibility.HIDE_FOR_OTHER_TEAMS);
})).then(Commands.literal("hideForOwnTeam").executes((p_138969_) -> {
return setNametagVisibility(p_138969_.getSource(), TeamArgument.getTeam(p_138969_, "team"), Team.Visibility.HIDE_FOR_OWN_TEAM);
})).then(Commands.literal("always").executes((p_138967_) -> {
return setNametagVisibility(p_138967_.getSource(), TeamArgument.getTeam(p_138967_, "team"), Team.Visibility.ALWAYS);
}))).then(Commands.literal("deathMessageVisibility").then(Commands.literal("never").executes((p_138965_) -> {
return setDeathMessageVisibility(p_138965_.getSource(), TeamArgument.getTeam(p_138965_, "team"), Team.Visibility.NEVER);
})).then(Commands.literal("hideForOtherTeams").executes((p_138963_) -> {
return setDeathMessageVisibility(p_138963_.getSource(), TeamArgument.getTeam(p_138963_, "team"), Team.Visibility.HIDE_FOR_OTHER_TEAMS);
})).then(Commands.literal("hideForOwnTeam").executes((p_138961_) -> {
return setDeathMessageVisibility(p_138961_.getSource(), TeamArgument.getTeam(p_138961_, "team"), Team.Visibility.HIDE_FOR_OWN_TEAM);
})).then(Commands.literal("always").executes((p_138959_) -> {
return setDeathMessageVisibility(p_138959_.getSource(), TeamArgument.getTeam(p_138959_, "team"), Team.Visibility.ALWAYS);
}))).then(Commands.literal("collisionRule").then(Commands.literal("never").executes((p_138957_) -> {
return setCollision(p_138957_.getSource(), TeamArgument.getTeam(p_138957_, "team"), Team.CollisionRule.NEVER);
})).then(Commands.literal("pushOwnTeam").executes((p_138955_) -> {
return setCollision(p_138955_.getSource(), TeamArgument.getTeam(p_138955_, "team"), Team.CollisionRule.PUSH_OWN_TEAM);
})).then(Commands.literal("pushOtherTeams").executes((p_138953_) -> {
return setCollision(p_138953_.getSource(), TeamArgument.getTeam(p_138953_, "team"), Team.CollisionRule.PUSH_OTHER_TEAMS);
})).then(Commands.literal("always").executes((p_138951_) -> {
return setCollision(p_138951_.getSource(), TeamArgument.getTeam(p_138951_, "team"), Team.CollisionRule.ALWAYS);
}))).then(Commands.literal("prefix").then(Commands.argument("prefix", ComponentArgument.textComponent()).executes((p_138942_) -> {
return setPrefix(p_138942_.getSource(), TeamArgument.getTeam(p_138942_, "team"), ComponentArgument.getComponent(p_138942_, "prefix"));
}))).then(Commands.literal("suffix").then(Commands.argument("suffix", ComponentArgument.textComponent()).executes((p_138923_) -> {
return setSuffix(p_138923_.getSource(), TeamArgument.getTeam(p_138923_, "team"), ComponentArgument.getComponent(p_138923_, "suffix"));
}))))));
}
/**
* Removes the listed players from their teams.
*/
private static int leaveTeam(CommandSourceStack pSource, Collection<String> pPlayers) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
for(String s : pPlayers) {
scoreboard.removePlayerFromTeam(s);
}
if (pPlayers.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.leave.success.single", pPlayers.iterator().next());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.leave.success.multiple", pPlayers.size());
}, true);
}
return pPlayers.size();
}
private static int joinTeam(CommandSourceStack pSource, PlayerTeam pTeam, Collection<String> pPlayers) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
for(String s : pPlayers) {
scoreboard.addPlayerToTeam(s, pTeam);
}
if (pPlayers.size() == 1) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.join.success.single", pPlayers.iterator().next(), pTeam.getFormattedDisplayName());
}, true);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.join.success.multiple", pPlayers.size(), pTeam.getFormattedDisplayName());
}, true);
}
return pPlayers.size();
}
private static int setNametagVisibility(CommandSourceStack pSource, PlayerTeam pTeam, Team.Visibility pVisibility) throws CommandSyntaxException {
if (pTeam.getNameTagVisibility() == pVisibility) {
throw ERROR_TEAM_NAMETAG_VISIBLITY_UNCHANGED.create();
} else {
pTeam.setNameTagVisibility(pVisibility);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.nametagVisibility.success", pTeam.getFormattedDisplayName(), pVisibility.getDisplayName());
}, true);
return 0;
}
}
private static int setDeathMessageVisibility(CommandSourceStack pSource, PlayerTeam pTeam, Team.Visibility pVisibility) throws CommandSyntaxException {
if (pTeam.getDeathMessageVisibility() == pVisibility) {
throw ERROR_TEAM_DEATH_MESSAGE_VISIBLITY_UNCHANGED.create();
} else {
pTeam.setDeathMessageVisibility(pVisibility);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.deathMessageVisibility.success", pTeam.getFormattedDisplayName(), pVisibility.getDisplayName());
}, true);
return 0;
}
}
private static int setCollision(CommandSourceStack pSource, PlayerTeam pTeam, Team.CollisionRule pRule) throws CommandSyntaxException {
if (pTeam.getCollisionRule() == pRule) {
throw ERROR_TEAM_COLLISION_UNCHANGED.create();
} else {
pTeam.setCollisionRule(pRule);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.collisionRule.success", pTeam.getFormattedDisplayName(), pRule.getDisplayName());
}, true);
return 0;
}
}
private static int setFriendlySight(CommandSourceStack pSource, PlayerTeam pTeam, boolean pValue) throws CommandSyntaxException {
if (pTeam.canSeeFriendlyInvisibles() == pValue) {
if (pValue) {
throw ERROR_TEAM_ALREADY_FRIENDLYINVISIBLES_ENABLED.create();
} else {
throw ERROR_TEAM_ALREADY_FRIENDLYINVISIBLES_DISABLED.create();
}
} else {
pTeam.setSeeFriendlyInvisibles(pValue);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.seeFriendlyInvisibles." + (pValue ? "enabled" : "disabled"), pTeam.getFormattedDisplayName());
}, true);
return 0;
}
}
private static int setFriendlyFire(CommandSourceStack pSource, PlayerTeam pTeam, boolean pValue) throws CommandSyntaxException {
if (pTeam.isAllowFriendlyFire() == pValue) {
if (pValue) {
throw ERROR_TEAM_ALREADY_FRIENDLYFIRE_ENABLED.create();
} else {
throw ERROR_TEAM_ALREADY_FRIENDLYFIRE_DISABLED.create();
}
} else {
pTeam.setAllowFriendlyFire(pValue);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.friendlyfire." + (pValue ? "enabled" : "disabled"), pTeam.getFormattedDisplayName());
}, true);
return 0;
}
}
private static int setDisplayName(CommandSourceStack pSource, PlayerTeam pTeam, Component pValue) throws CommandSyntaxException {
if (pTeam.getDisplayName().equals(pValue)) {
throw ERROR_TEAM_ALREADY_NAME.create();
} else {
pTeam.setDisplayName(pValue);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.name.success", pTeam.getFormattedDisplayName());
}, true);
return 0;
}
}
private static int setColor(CommandSourceStack pSource, PlayerTeam pTeam, ChatFormatting pValue) throws CommandSyntaxException {
if (pTeam.getColor() == pValue) {
throw ERROR_TEAM_ALREADY_COLOR.create();
} else {
pTeam.setColor(pValue);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.color.success", pTeam.getFormattedDisplayName(), pValue.getName());
}, true);
return 0;
}
}
private static int emptyTeam(CommandSourceStack pSource, PlayerTeam pTeam) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
Collection<String> collection = Lists.newArrayList(pTeam.getPlayers());
if (collection.isEmpty()) {
throw ERROR_TEAM_ALREADY_EMPTY.create();
} else {
for(String s : collection) {
scoreboard.removePlayerFromTeam(s, pTeam);
}
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.empty.success", collection.size(), pTeam.getFormattedDisplayName());
}, true);
return collection.size();
}
}
private static int deleteTeam(CommandSourceStack pSource, PlayerTeam pTeam) {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
scoreboard.removePlayerTeam(pTeam);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.remove.success", pTeam.getFormattedDisplayName());
}, true);
return scoreboard.getPlayerTeams().size();
}
private static int createTeam(CommandSourceStack pSource, String pName) throws CommandSyntaxException {
return createTeam(pSource, pName, Component.literal(pName));
}
private static int createTeam(CommandSourceStack pSource, String pName, Component pDisplayName) throws CommandSyntaxException {
Scoreboard scoreboard = pSource.getServer().getScoreboard();
if (scoreboard.getPlayerTeam(pName) != null) {
throw ERROR_TEAM_ALREADY_EXISTS.create();
} else {
PlayerTeam playerteam = scoreboard.addPlayerTeam(pName);
playerteam.setDisplayName(pDisplayName);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.add.success", playerteam.getFormattedDisplayName());
}, true);
return scoreboard.getPlayerTeams().size();
}
}
private static int listMembers(CommandSourceStack pSource, PlayerTeam pTeam) {
Collection<String> collection = pTeam.getPlayers();
if (collection.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.list.members.empty", pTeam.getFormattedDisplayName());
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.list.members.success", pTeam.getFormattedDisplayName(), collection.size(), ComponentUtils.formatList(collection));
}, false);
}
return collection.size();
}
private static int listTeams(CommandSourceStack pSource) {
Collection<PlayerTeam> collection = pSource.getServer().getScoreboard().getPlayerTeams();
if (collection.isEmpty()) {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.list.teams.empty");
}, false);
} else {
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.list.teams.success", collection.size(), ComponentUtils.formatList(collection, PlayerTeam::getFormattedDisplayName));
}, false);
}
return collection.size();
}
private static int setPrefix(CommandSourceStack pSource, PlayerTeam pTeam, Component pPrefix) {
pTeam.setPlayerPrefix(pPrefix);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.prefix.success", pPrefix);
}, false);
return 1;
}
private static int setSuffix(CommandSourceStack pSource, PlayerTeam pTeam, Component pSuffix) {
pTeam.setPlayerSuffix(pSuffix);
pSource.sendSuccess(() -> {
return Component.translatable("commands.team.option.suffix.success", pSuffix);
}, false);
return 1;
}
}
Loaded 100 of 14134 files, more files were not shown because too many files have changed in this diff. Show more