trurwsuieghfdskg

This commit is contained in:
2025-06-08 00:02:04 +09:00
commit 56c8ad5bc2
14172 changed files with 1139672 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
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;
private static volatile boolean isBootstrapped;
private static final Logger LOGGER = LogUtils.getLogger();
public static final AtomicLong bootstrapDuration = new AtomicLong(-1L);
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();
// Forge: Hacky fix to ensure that NetworkConstants is loaded before mods are constructed.
// Many older mods use network internals that shouldn't be used, yet are exposed so they get used anyways.
// This can cause class-loading issues with ForgeMod loading NetworkConstants and HandshakeResolver.
// To ensure that doesn't happen, we load it here and now. This is not an issue in 1.20.2 and newer.
net.minecraftforge.network.NetworkHooks.init();
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> p_135872_, Function<T, String> p_135873_, Set<String> p_135874_) {
Language language = Language.getInstance();
p_135872_.forEach((p_135883_) -> {
String s = p_135873_.apply(p_135883_);
if (!language.has(s)) {
p_135874_.add(s);
}
});
}
private static void checkGameruleTranslations(final Set<String> p_135878_) {
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())) {
p_135878_.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();
}
}
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 p_135876_) {
STDOUT.println(p_135876_);
}
}

View File

@@ -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 p_135909_) {
this.entries.get(0).addJsonKey(p_135909_);
}
public void setFilenameAndFlush(String p_135911_) {
(this.entries.get(0)).filename = p_135911_;
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 p_135907_) {
if (p_135907_ instanceof ChainedJsonException) {
return (ChainedJsonException)p_135907_;
} else {
String s = p_135907_.getMessage();
if (p_135907_ instanceof FileNotFoundException) {
s = "File not found";
}
return new ChainedJsonException(s, p_135907_);
}
}
public static class Entry {
@Nullable
String filename;
private final List<String> jsonKeys = Lists.newArrayList();
Entry() {
}
void addJsonKey(String p_135919_) {
this.jsonKeys.add(0, p_135919_);
}
@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();
}
}
}
}

View File

@@ -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 p_135931_, CommandSourceStack p_135932_) {
this.msg = p_135931_;
this.source = p_135932_;
}
}

View File

@@ -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 p_135937_) {
StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace();
StackTraceElement stacktraceelement = astacktraceelement[Math.min(3, astacktraceelement.length)];
LOGGER.info("[{}]@.({}:{}): {}", this.name, stacktraceelement.getFileName(), stacktraceelement.getLineNumber(), p_135937_);
}
}

View File

@@ -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 p_135943_) {
this.file = p_135943_;
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);
}
}
}
}

View File

@@ -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 p_135953_) {
LOGGER.info("[{}]: {}", this.name, p_135953_);
}
}

View File

@@ -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[] p_129699_) {
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(p_129699_);
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 p_270192_) {
try {
long i = ProcessHandle.current().pid();
Files.writeString(p_270192_, Long.toString(i));
} catch (IOException ioexception) {
throw new UncheckedIOException(ioexception);
}
}
private static WorldLoader.InitConfig loadOrCreateConfig(DedicatedServerProperties p_248563_, LevelStorageSource.LevelStorageAccess p_251359_, boolean p_249093_, PackRepository p_251069_) {
WorldDataConfiguration worlddataconfiguration = p_251359_.getDataConfiguration();
WorldDataConfiguration worlddataconfiguration1;
boolean flag;
if (worlddataconfiguration != null) {
flag = false;
worlddataconfiguration1 = worlddataconfiguration;
} else {
flag = true;
worlddataconfiguration1 = new WorldDataConfiguration(p_248563_.initialDataPackConfiguration, FeatureFlags.DEFAULT_FLAGS);
}
WorldLoader.PackConfig worldloader$packconfig = new WorldLoader.PackConfig(p_251069_, worlddataconfiguration1, p_249093_, flag);
return new WorldLoader.InitConfig(worldloader$packconfig, Commands.CommandSelection.DEDICATED, p_248563_.functionPermissionLevel);
}
private static void forceUpgrade(LevelStorageSource.LevelStorageAccess p_195489_, DataFixer p_195490_, boolean p_195491_, BooleanSupplier p_195492_, Registry<LevelStem> p_250443_) {
LOGGER.info("Forcing world upgrade!");
WorldUpgrader worldupgrader = new WorldUpgrader(p_195489_, p_195490_, p_250443_, p_195491_);
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 (!p_195492_.getAsBoolean()) {
worldupgrader.cancel();
} else {
try {
Thread.sleep(1000L);
} catch (InterruptedException interruptedexception) {
}
}
}
}
}

View File

@@ -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 p_265655_, PlayerList p_265703_, ServerAdvancementManager p_265166_, Path p_265268_, ServerPlayer p_265673_) {
this.dataFixer = p_265655_;
this.playerList = p_265703_;
this.playerSavePath = p_265268_;
this.player = p_265673_;
this.load(p_265166_);
}
public void setPlayer(ServerPlayer p_135980_) {
this.player = p_135980_;
}
public void stopListening() {
for(CriterionTrigger<?> criteriontrigger : CriteriaTriggers.all()) {
criteriontrigger.removePlayerListeners(this);
}
}
public void reload(ServerAdvancementManager p_135982_) {
this.stopListening();
this.progress.clear();
this.visible.clear();
this.rootsToUpdate.clear();
this.progressChanged.clear();
this.isFirstPacket = true;
this.lastSelectedTab = null;
this.load(p_135982_);
}
private void registerListeners(ServerAdvancementManager p_135995_) {
for(Advancement advancement : p_135995_.getAllAdvancements()) {
this.registerListeners(advancement);
}
}
private void checkForAutomaticTriggers(ServerAdvancementManager p_136003_) {
for(Advancement advancement : p_136003_.getAllAdvancements()) {
if (advancement.getCriteria().isEmpty()) {
this.award(advancement, "");
advancement.getRewards().grant(this.player);
}
}
}
private void load(ServerAdvancementManager p_136007_) {
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 = p_136007_.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(p_136007_);
this.registerListeners(p_136007_);
}
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 p_135989_, String p_135990_) {
// 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(p_135989_);
boolean flag1 = advancementprogress.isDone();
if (advancementprogress.grantProgress(p_135990_)) {
this.unregisterListeners(p_135989_);
this.progressChanged.add(p_135989_);
flag = true;
net.minecraftforge.event.ForgeEventFactory.onAdvancementProgressedEvent(this.player, p_135989_, advancementprogress, p_135990_, net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent.ProgressType.GRANT);
if (!flag1 && advancementprogress.isDone()) {
p_135989_.getRewards().grant(this.player);
if (p_135989_.getDisplay() != null && p_135989_.getDisplay().shouldAnnounceChat() && this.player.level().getGameRules().getBoolean(GameRules.RULE_ANNOUNCE_ADVANCEMENTS)) {
this.playerList.broadcastSystemMessage(Component.translatable("chat.type.advancement." + p_135989_.getDisplay().getFrame().getName(), this.player.getDisplayName(), p_135989_.getChatComponent()), false);
}
net.minecraftforge.event.ForgeEventFactory.onAdvancementEarnedEvent(this.player, p_135989_);
}
}
if (!flag1 && advancementprogress.isDone()) {
this.markForVisibilityUpdate(p_135989_);
}
return flag;
}
public boolean revoke(Advancement p_135999_, String p_136000_) {
boolean flag = false;
AdvancementProgress advancementprogress = this.getOrStartProgress(p_135999_);
boolean flag1 = advancementprogress.isDone();
if (advancementprogress.revokeProgress(p_136000_)) {
this.registerListeners(p_135999_);
this.progressChanged.add(p_135999_);
flag = true;
net.minecraftforge.event.ForgeEventFactory.onAdvancementProgressedEvent(this.player, p_135999_, advancementprogress, p_136000_, net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent.ProgressType.REVOKE);
}
if (flag1 && !advancementprogress.isDone()) {
this.markForVisibilityUpdate(p_135999_);
}
return flag;
}
private void markForVisibilityUpdate(Advancement p_265528_) {
this.rootsToUpdate.add(p_265528_.getRoot());
}
private void registerListeners(Advancement p_136005_) {
AdvancementProgress advancementprogress = this.getOrStartProgress(p_136005_);
if (!advancementprogress.isDone()) {
for(Map.Entry<String, Criterion> entry : p_136005_.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, p_136005_, entry.getKey()));
}
}
}
}
}
}
private void unregisterListeners(Advancement p_136009_) {
AdvancementProgress advancementprogress = this.getOrStartProgress(p_136009_);
for(Map.Entry<String, Criterion> entry : p_136009_.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, p_136009_, entry.getKey()));
}
}
}
}
}
public void flushDirty(ServerPlayer p_135993_) {
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()) {
p_135993_.connection.send(new ClientboundUpdateAdvancementsPacket(this.isFirstPacket, set, set1, map));
}
}
this.isFirstPacket = false;
}
public void setSelectedTab(@Nullable Advancement p_135984_) {
Advancement advancement = this.lastSelectedTab;
if (p_135984_ != null && p_135984_.getParent() == null && p_135984_.getDisplay() != null) {
this.lastSelectedTab = p_135984_;
} 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 p_135997_) {
AdvancementProgress advancementprogress = this.progress.get(p_135997_);
if (advancementprogress == null) {
advancementprogress = new AdvancementProgress();
this.startProgress(p_135997_, advancementprogress);
}
return advancementprogress;
}
private void startProgress(Advancement p_135986_, AdvancementProgress p_135987_) {
p_135987_.update(p_135986_.getCriteria(), p_135986_.getRequirements());
this.progress.put(p_135986_, p_135987_);
}
private void updateTreeVisibility(Advancement p_265158_, Set<Advancement> p_265206_, Set<ResourceLocation> p_265593_) {
AdvancementVisibilityEvaluator.evaluateVisibility(p_265158_, (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());
}
});
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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> p_136034_, ResourceManager p_136035_, ProfilerFiller p_136036_) {
Map<ResourceLocation, Advancement.Builder> map = Maps.newHashMap();
p_136034_.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 p_136042_) {
return this.advancements.get(p_136042_);
}
public Collection<Advancement> getAllAdvancements() {
return this.advancements.getAllAdvancements();
}
}

View File

@@ -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 p_136057_, ResourceManager p_136058_, ProfilerFiller p_136059_, ProfilerFiller p_136060_, Executor p_136061_, Executor p_136062_) {
CompletableFuture<Map<ResourceLocation, List<TagLoader.EntryWithSource>>> completablefuture = CompletableFuture.supplyAsync(() -> {
return this.tagsLoader.load(p_136058_);
}, p_136061_);
CompletableFuture<Map<ResourceLocation, CompletableFuture<CommandFunction>>> completablefuture1 = CompletableFuture.supplyAsync(() -> {
return LISTER.listMatchingResources(p_136058_);
}, p_136061_).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);
}, p_136061_));
}
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(p_136057_::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());
}, p_136062_);
}
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);
}
}
}

View File

@@ -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 p_136110_, ServerFunctionLibrary p_136111_) {
this.server = p_136110_;
this.library = p_136111_;
this.postReload(p_136111_);
}
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> p_136116_, ResourceLocation p_136117_) {
this.server.getProfiler().push(p_136117_::toString);
for(CommandFunction commandfunction : p_136116_) {
this.execute(commandfunction, this.getGameLoopSender());
}
this.server.getProfiler().pop();
}
public int execute(CommandFunction p_136113_, CommandSourceStack p_136114_) {
return this.execute(p_136113_, p_136114_, (ServerFunctionManager.TraceCallbacks)null);
}
public int execute(CommandFunction p_179961_, CommandSourceStack p_179962_, @Nullable ServerFunctionManager.TraceCallbacks p_179963_) {
if (this.context != null) {
if (p_179963_ != null) {
this.context.reportError(NO_RECURSIVE_TRACES.getString());
return 0;
} else {
this.context.delayFunctionCall(p_179961_, p_179962_);
return 0;
}
} else {
int i;
try {
this.context = new ServerFunctionManager.ExecutionContext(p_179963_);
i = this.context.runTopCommand(p_179961_, p_179962_);
} finally {
this.context = null;
}
return i;
}
}
public void replaceLibrary(ServerFunctionLibrary p_136121_) {
this.library = p_136121_;
this.postReload(p_136121_);
}
private void postReload(ServerFunctionLibrary p_136126_) {
this.ticking = ImmutableList.copyOf(p_136126_.getTag(TICK_FUNCTION_TAG));
this.postReload = true;
}
public CommandSourceStack getGameLoopSender() {
return this.server.createCommandSourceStack().withPermission(2).withSuppressedOutput();
}
public Optional<CommandFunction> get(ResourceLocation p_136119_) {
return this.library.getFunction(p_136119_);
}
public Collection<CommandFunction> getTag(ResourceLocation p_214332_) {
return this.library.getTag(p_214332_);
}
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 p_179971_) {
this.tracer = p_179971_;
}
void delayFunctionCall(CommandFunction p_179973_, CommandSourceStack p_179974_) {
int i = ServerFunctionManager.this.getCommandLimit();
CommandSourceStack commandsourcestack = this.wrapSender(p_179974_);
if (this.commandQueue.size() + this.nestedCalls.size() < i) {
this.nestedCalls.add(new ServerFunctionManager.QueuedCommand(commandsourcestack, this.depth, new CommandFunction.FunctionEntry(p_179973_)));
}
}
private CommandSourceStack wrapSender(CommandSourceStack p_282848_) {
IntConsumer intconsumer = p_282848_.getReturnValueConsumer();
return intconsumer instanceof ServerFunctionManager.ExecutionContext.AbortingReturnValueConsumer ? p_282848_ : p_282848_.withReturnValueConsumer(new ServerFunctionManager.ExecutionContext.AbortingReturnValueConsumer(intconsumer));
}
int runTopCommand(CommandFunction p_179978_, CommandSourceStack p_179979_) {
int i = ServerFunctionManager.this.getCommandLimit();
CommandSourceStack commandsourcestack = this.wrapSender(p_179979_);
int j = 0;
CommandFunction.Entry[] acommandfunction$entry = p_179978_.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 p_179976_) {
if (this.tracer != null) {
this.tracer.onError(this.depth, p_179976_);
}
}
class AbortingReturnValueConsumer implements IntConsumer {
private final IntConsumer wrapped;
AbortingReturnValueConsumer(IntConsumer p_281634_) {
this.wrapped = p_281634_;
}
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 p_179982_, int p_179983_, CommandFunction.Entry p_179984_) {
this.sender = p_179982_;
this.depth = p_179983_;
this.entry = p_179984_;
}
public void execute(ServerFunctionManager p_179986_, Deque<ServerFunctionManager.QueuedCommand> p_179987_, int p_179988_, @Nullable ServerFunctionManager.TraceCallbacks p_179989_) {
try {
this.entry.execute(p_179986_, this.sender, p_179987_, p_179988_, this.depth, p_179989_);
} catch (CommandSyntaxException commandsyntaxexception) {
if (p_179989_ != null) {
p_179989_.onError(this.depth, commandsyntaxexception.getRawMessage().getString());
}
} catch (Exception exception) {
if (p_179989_ != null) {
p_179989_.onError(this.depth, exception.getMessage());
}
}
}
public String toString() {
return this.entry.toString();
}
}
public interface TraceCallbacks {
void onCommand(int p_179990_, String p_179991_);
void onReturn(int p_179992_, String p_179993_, int p_179994_);
void onError(int p_179998_, String p_179999_);
void onCall(int p_179995_, ResourceLocation p_179996_, int p_179997_);
}
}

View File

@@ -0,0 +1,27 @@
package net.minecraft.server;
import net.minecraft.server.dedicated.DedicatedServerProperties;
public interface ServerInterface {
DedicatedServerProperties getProperties();
String getServerIp();
int getServerPort();
String getServerName();
String getServerVersion();
int getPlayerCount();
int getMaxPlayers();
String[] getPlayerNames();
String getLevelIdName();
String getPluginNames();
String runCommand(String p_136143_);
}

View File

@@ -0,0 +1,224 @@
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 p_136206_) {
super.onScoreChanged(p_136206_);
if (this.trackedObjectives.contains(p_136206_.getObjective())) {
this.server.getPlayerList().broadcastAll(new ClientboundSetScorePacket(ServerScoreboard.Method.CHANGE, p_136206_.getObjective().getName(), p_136206_.getOwner(), p_136206_.getScore()));
}
this.setDirty();
}
public void onPlayerRemoved(String p_136210_) {
super.onPlayerRemoved(p_136210_);
this.server.getPlayerList().broadcastAll(new ClientboundSetScorePacket(ServerScoreboard.Method.REMOVE, (String)null, p_136210_, 0));
this.setDirty();
}
public void onPlayerScoreRemoved(String p_136212_, Objective p_136213_) {
super.onPlayerScoreRemoved(p_136212_, p_136213_);
if (this.trackedObjectives.contains(p_136213_)) {
this.server.getPlayerList().broadcastAll(new ClientboundSetScorePacket(ServerScoreboard.Method.REMOVE, p_136213_.getName(), p_136212_, 0));
}
this.setDirty();
}
public void setDisplayObjective(int p_136199_, @Nullable Objective p_136200_) {
Objective objective = this.getDisplayObjective(p_136199_);
super.setDisplayObjective(p_136199_, p_136200_);
if (objective != p_136200_ && objective != null) {
if (this.getObjectiveDisplaySlotCount(objective) > 0) {
this.server.getPlayerList().broadcastAll(new ClientboundSetDisplayObjectivePacket(p_136199_, p_136200_));
} else {
this.stopTrackingObjective(objective);
}
}
if (p_136200_ != null) {
if (this.trackedObjectives.contains(p_136200_)) {
this.server.getPlayerList().broadcastAll(new ClientboundSetDisplayObjectivePacket(p_136199_, p_136200_));
} else {
this.startTrackingObjective(p_136200_);
}
}
this.setDirty();
}
public boolean addPlayerToTeam(String p_136215_, PlayerTeam p_136216_) {
if (super.addPlayerToTeam(p_136215_, p_136216_)) {
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createPlayerPacket(p_136216_, p_136215_, ClientboundSetPlayerTeamPacket.Action.ADD));
this.setDirty();
return true;
} else {
return false;
}
}
public void removePlayerFromTeam(String p_136223_, PlayerTeam p_136224_) {
super.removePlayerFromTeam(p_136223_, p_136224_);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createPlayerPacket(p_136224_, p_136223_, ClientboundSetPlayerTeamPacket.Action.REMOVE));
this.setDirty();
}
public void onObjectiveAdded(Objective p_136202_) {
super.onObjectiveAdded(p_136202_);
this.setDirty();
}
public void onObjectiveChanged(Objective p_136219_) {
super.onObjectiveChanged(p_136219_);
if (this.trackedObjectives.contains(p_136219_)) {
this.server.getPlayerList().broadcastAll(new ClientboundSetObjectivePacket(p_136219_, 2));
}
this.setDirty();
}
public void onObjectiveRemoved(Objective p_136226_) {
super.onObjectiveRemoved(p_136226_);
if (this.trackedObjectives.contains(p_136226_)) {
this.stopTrackingObjective(p_136226_);
}
this.setDirty();
}
public void onTeamAdded(PlayerTeam p_136204_) {
super.onTeamAdded(p_136204_);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(p_136204_, true));
this.setDirty();
}
public void onTeamChanged(PlayerTeam p_136221_) {
super.onTeamChanged(p_136221_);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(p_136221_, false));
this.setDirty();
}
public void onTeamRemoved(PlayerTeam p_136228_) {
super.onTeamRemoved(p_136228_);
this.server.getPlayerList().broadcastAll(ClientboundSetPlayerTeamPacket.createRemovePacket(p_136228_));
this.setDirty();
}
public void addDirtyListener(Runnable p_136208_) {
this.dirtyListeners.add(p_136208_);
}
protected void setDirty() {
for(Runnable runnable : this.dirtyListeners) {
runnable.run();
}
}
public List<Packet<?>> getStartTrackingPackets(Objective p_136230_) {
List<Packet<?>> list = Lists.newArrayList();
list.add(new ClientboundSetObjectivePacket(p_136230_, 0));
for(int i = 0; i < 19; ++i) {
if (this.getDisplayObjective(i) == p_136230_) {
list.add(new ClientboundSetDisplayObjectivePacket(i, p_136230_));
}
}
for(Score score : this.getPlayerScores(p_136230_)) {
list.add(new ClientboundSetScorePacket(ServerScoreboard.Method.CHANGE, score.getObjective().getName(), score.getOwner(), score.getScore()));
}
return list;
}
public void startTrackingObjective(Objective p_136232_) {
List<Packet<?>> list = this.getStartTrackingPackets(p_136232_);
for(ServerPlayer serverplayer : this.server.getPlayerList().getPlayers()) {
for(Packet<?> packet : list) {
serverplayer.connection.send(packet);
}
}
this.trackedObjectives.add(p_136232_);
}
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;
}
}

View File

@@ -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 p_214345_, File p_214346_) {
MinecraftSessionService minecraftsessionservice = p_214345_.createMinecraftSessionService();
GameProfileRepository gameprofilerepository = p_214345_.createProfileRepository();
GameProfileCache gameprofilecache = new GameProfileCache(gameprofilerepository, new File(p_214346_, "usercache.json"));
return new Services(minecraftsessionservice, p_214345_.getServicesKeySet(), gameprofilerepository, gameprofilecache);
}
@Nullable
public SignatureValidator profileKeySignatureValidator() {
return SignatureValidator.from(this.servicesKeySet, ServicesKeyType.PROFILE_KEY);
}
}

View File

@@ -0,0 +1,19 @@
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_;
}
public int getTick() {
return this.tick;
}
public void run() {
this.runnable.run();
}
}

View File

@@ -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 p_214363_, WorldLoader.WorldDataSupplier<D> p_214364_, WorldLoader.ResultFactory<D, R> p_214365_, Executor p_214366_, Executor p_214367_) {
try {
Pair<WorldDataConfiguration, CloseableResourceManager> pair = p_214363_.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(), p_214363_.commandSelection(), p_214363_.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 p_251529_, LayeredRegistryAccess<RegistryLayer> p_250737_, RegistryLayer p_250790_, List<RegistryDataLoader.RegistryData<?>> p_249516_) {
RegistryAccess.Frozen registryaccess$frozen = p_250737_.getAccessForLoading(p_250790_);
return RegistryDataLoader.load(p_251529_, registryaccess$frozen, p_249516_);
}
private static LayeredRegistryAccess<RegistryLayer> loadAndReplaceLayer(ResourceManager p_249913_, LayeredRegistryAccess<RegistryLayer> p_252077_, RegistryLayer p_250346_, List<RegistryDataLoader.RegistryData<?>> p_250589_) {
RegistryAccess.Frozen registryaccess$frozen = loadLayer(p_249913_, p_252077_, p_250346_, p_250589_);
return p_252077_.replaceFrom(p_250346_, 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_);
}
}

View File

@@ -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();
}
}

View File

@@ -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 p_265736_, boolean p_265426_) {
DisplayInfo displayinfo = p_265736_.getDisplay();
if (displayinfo == null) {
return AdvancementVisibilityEvaluator.VisibilityRule.HIDE;
} else if (p_265426_) {
return AdvancementVisibilityEvaluator.VisibilityRule.SHOW;
} else {
return displayinfo.isHidden() ? AdvancementVisibilityEvaluator.VisibilityRule.HIDE : AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE;
}
}
private static boolean evaluateVisiblityForUnfinishedNode(Stack<AdvancementVisibilityEvaluator.VisibilityRule> p_265343_) {
for(int i = 0; i <= 2; ++i) {
AdvancementVisibilityEvaluator.VisibilityRule advancementvisibilityevaluator$visibilityrule = p_265343_.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 p_265202_, Stack<AdvancementVisibilityEvaluator.VisibilityRule> p_265086_, Predicate<Advancement> p_265561_, AdvancementVisibilityEvaluator.Output p_265381_) {
boolean flag = p_265561_.test(p_265202_);
AdvancementVisibilityEvaluator.VisibilityRule advancementvisibilityevaluator$visibilityrule = evaluateVisibilityRule(p_265202_, flag);
boolean flag1 = flag;
p_265086_.push(advancementvisibilityevaluator$visibilityrule);
for(Advancement advancement : p_265202_.getChildren()) {
flag1 |= evaluateVisibility(advancement, p_265086_, p_265561_, p_265381_);
}
boolean flag2 = flag1 || evaluateVisiblityForUnfinishedNode(p_265086_);
p_265086_.pop();
p_265381_.accept(p_265202_, flag2);
return flag1;
}
public static void evaluateVisibility(Advancement p_265578_, Predicate<Advancement> p_265359_, AdvancementVisibilityEvaluator.Output p_265303_) {
Advancement advancement = p_265578_.getRoot();
Stack<AdvancementVisibilityEvaluator.VisibilityRule> stack = new ObjectArrayList<>();
for(int i = 0; i <= 2; ++i) {
stack.push(AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE);
}
evaluateVisibility(advancement, stack, p_265359_, p_265303_);
}
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, (p_265639_, p_265580_) -> {});
}
@FunctionalInterface
public interface Output {
void accept(Advancement p_265639_, boolean p_265580_);
}
static enum VisibilityRule {
SHOW,
HIDE,
NO_CHANGE;
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.server.advancements;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,180 @@
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 p_136261_, Component p_136262_) {
super(p_136262_, BossEvent.BossBarColor.WHITE, BossEvent.BossBarOverlay.PROGRESS);
this.id = p_136261_;
this.setProgress(0.0F);
}
public ResourceLocation getTextId() {
return this.id;
}
public void addPlayer(ServerPlayer p_136267_) {
super.addPlayer(p_136267_);
this.players.add(p_136267_.getUUID());
}
public void addOfflinePlayer(UUID p_136271_) {
this.players.add(p_136271_);
}
public void removePlayer(ServerPlayer p_136281_) {
super.removePlayer(p_136281_);
this.players.remove(p_136281_.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 p_136265_) {
this.value = p_136265_;
this.setProgress(Mth.clamp((float)p_136265_ / (float)this.max, 0.0F, 1.0F));
}
public void setMax(int p_136279_) {
this.max = p_136279_;
this.setProgress(Mth.clamp((float)this.value / (float)p_136279_, 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> p_136269_) {
Set<UUID> set = Sets.newHashSet();
Set<ServerPlayer> set1 = Sets.newHashSet();
for(UUID uuid : this.players) {
boolean flag = false;
for(ServerPlayer serverplayer : p_136269_) {
if (serverplayer.getUUID().equals(uuid)) {
flag = true;
break;
}
}
if (!flag) {
set.add(uuid);
}
}
for(ServerPlayer serverplayer1 : p_136269_) {
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 p_136273_, ResourceLocation p_136274_) {
CustomBossEvent custombossevent = new CustomBossEvent(p_136274_, Component.Serializer.fromJson(p_136273_.getString("Name")));
custombossevent.setVisible(p_136273_.getBoolean("Visible"));
custombossevent.setValue(p_136273_.getInt("Value"));
custombossevent.setMax(p_136273_.getInt("Max"));
custombossevent.setColor(BossEvent.BossBarColor.byName(p_136273_.getString("Color")));
custombossevent.setOverlay(BossEvent.BossBarOverlay.byName(p_136273_.getString("Overlay")));
custombossevent.setDarkenScreen(p_136273_.getBoolean("DarkenScreen"));
custombossevent.setPlayBossMusic(p_136273_.getBoolean("PlayBossMusic"));
custombossevent.setCreateWorldFog(p_136273_.getBoolean("CreateWorldFog"));
ListTag listtag = p_136273_.getList("Players", 11);
for(int i = 0; i < listtag.size(); ++i) {
custombossevent.addOfflinePlayer(NbtUtils.loadUUID(listtag.get(i)));
}
return custombossevent;
}
public void onPlayerConnect(ServerPlayer p_136284_) {
if (this.players.contains(p_136284_.getUUID())) {
this.addPlayer(p_136284_);
}
}
public void onPlayerDisconnect(ServerPlayer p_136287_) {
super.removePlayer(p_136287_);
}
}

View File

@@ -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 p_136298_) {
return this.events.get(p_136298_);
}
public CustomBossEvent create(ResourceLocation p_136300_, Component p_136301_) {
CustomBossEvent custombossevent = new CustomBossEvent(p_136300_, p_136301_);
this.events.put(p_136300_, custombossevent);
return custombossevent;
}
public void remove(CustomBossEvent p_136303_) {
this.events.remove(p_136303_.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 p_136294_) {
for(CustomBossEvent custombossevent : this.events.values()) {
custombossevent.onPlayerConnect(p_136294_);
}
}
public void onPlayerDisconnect(ServerPlayer p_136306_) {
for(CustomBossEvent custombossevent : this.events.values()) {
custombossevent.onPlayerDisconnect(p_136306_);
}
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.server.bossevents;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -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 p_195990_, int p_195991_, MinecraftServer p_195992_) {
this.serverHost = p_195990_;
this.serverPort = p_195991_;
this.server = p_195992_;
}
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 p_195995_) {
try (Scanner scanner = new Scanner(new StringReader(p_195995_))) {
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)p_195995_);
}
}
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) {
}
}

View File

@@ -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 p_196032_, int p_196033_, PlayerList p_196034_, int p_196035_) {
this.serverBindAddress = p_196032_;
this.serverPort = p_196033_;
this.playerList = p_196034_;
this.broadcastIntervalMs = p_196035_;
}
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);
}
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.server.chase;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,241 @@
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> p_136311_) {
p_136311_.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());
})))));
}
private static int perform(CommandSourceStack p_136320_, Collection<ServerPlayer> p_136321_, AdvancementCommands.Action p_136322_, Collection<Advancement> p_136323_) {
int i = 0;
for(ServerPlayer serverplayer : p_136321_) {
i += p_136322_.perform(serverplayer, p_136323_);
}
if (i == 0) {
if (p_136323_.size() == 1) {
if (p_136321_.size() == 1) {
throw new CommandRuntimeException(Component.translatable(p_136322_.getKey() + ".one.to.one.failure", p_136323_.iterator().next().getChatComponent(), p_136321_.iterator().next().getDisplayName()));
} else {
throw new CommandRuntimeException(Component.translatable(p_136322_.getKey() + ".one.to.many.failure", p_136323_.iterator().next().getChatComponent(), p_136321_.size()));
}
} else if (p_136321_.size() == 1) {
throw new CommandRuntimeException(Component.translatable(p_136322_.getKey() + ".many.to.one.failure", p_136323_.size(), p_136321_.iterator().next().getDisplayName()));
} else {
throw new CommandRuntimeException(Component.translatable(p_136322_.getKey() + ".many.to.many.failure", p_136323_.size(), p_136321_.size()));
}
} else {
if (p_136323_.size() == 1) {
if (p_136321_.size() == 1) {
p_136320_.sendSuccess(() -> {
return Component.translatable(p_136322_.getKey() + ".one.to.one.success", p_136323_.iterator().next().getChatComponent(), p_136321_.iterator().next().getDisplayName());
}, true);
} else {
p_136320_.sendSuccess(() -> {
return Component.translatable(p_136322_.getKey() + ".one.to.many.success", p_136323_.iterator().next().getChatComponent(), p_136321_.size());
}, true);
}
} else if (p_136321_.size() == 1) {
p_136320_.sendSuccess(() -> {
return Component.translatable(p_136322_.getKey() + ".many.to.one.success", p_136323_.size(), p_136321_.iterator().next().getDisplayName());
}, true);
} else {
p_136320_.sendSuccess(() -> {
return Component.translatable(p_136322_.getKey() + ".many.to.many.success", p_136323_.size(), p_136321_.size());
}, true);
}
return i;
}
}
private static int performCriterion(CommandSourceStack p_136325_, Collection<ServerPlayer> p_136326_, AdvancementCommands.Action p_136327_, Advancement p_136328_, String p_136329_) {
int i = 0;
if (!p_136328_.getCriteria().containsKey(p_136329_)) {
throw new CommandRuntimeException(Component.translatable("commands.advancement.criterionNotFound", p_136328_.getChatComponent(), p_136329_));
} else {
for(ServerPlayer serverplayer : p_136326_) {
if (p_136327_.performCriterion(serverplayer, p_136328_, p_136329_)) {
++i;
}
}
if (i == 0) {
if (p_136326_.size() == 1) {
throw new CommandRuntimeException(Component.translatable(p_136327_.getKey() + ".criterion.to.one.failure", p_136329_, p_136328_.getChatComponent(), p_136326_.iterator().next().getDisplayName()));
} else {
throw new CommandRuntimeException(Component.translatable(p_136327_.getKey() + ".criterion.to.many.failure", p_136329_, p_136328_.getChatComponent(), p_136326_.size()));
}
} else {
if (p_136326_.size() == 1) {
p_136325_.sendSuccess(() -> {
return Component.translatable(p_136327_.getKey() + ".criterion.to.one.success", p_136329_, p_136328_.getChatComponent(), p_136326_.iterator().next().getDisplayName());
}, true);
} else {
p_136325_.sendSuccess(() -> {
return Component.translatable(p_136327_.getKey() + ".criterion.to.many.success", p_136329_, p_136328_.getChatComponent(), p_136326_.size());
}, true);
}
return i;
}
}
}
private static List<Advancement> getAdvancements(Advancement p_136334_, AdvancementCommands.Mode p_136335_) {
List<Advancement> list = Lists.newArrayList();
if (p_136335_.parents) {
for(Advancement advancement = p_136334_.getParent(); advancement != null; advancement = advancement.getParent()) {
list.add(advancement);
}
}
list.add(p_136334_);
if (p_136335_.children) {
addChildren(p_136334_, list);
}
return list;
}
private static void addChildren(Advancement p_136331_, List<Advancement> p_136332_) {
for(Advancement advancement : p_136331_.getChildren()) {
p_136332_.add(advancement);
addChildren(advancement, p_136332_);
}
}
static enum Action {
GRANT("grant") {
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;
}
}
protected boolean performCriterion(ServerPlayer p_136398_, Advancement p_136399_, String p_136400_) {
return p_136398_.getAdvancements().award(p_136399_, p_136400_);
}
},
REVOKE("revoke") {
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;
}
}
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 p_136372_) {
this.key = "commands.advancement." + p_136372_;
}
public int perform(ServerPlayer p_136380_, Iterable<Advancement> p_136381_) {
int i = 0;
for(Advancement advancement : p_136381_) {
if (this.perform(p_136380_, advancement)) {
++i;
}
}
return i;
}
protected abstract boolean perform(ServerPlayer p_136382_, Advancement p_136383_);
protected abstract boolean performCriterion(ServerPlayer p_136384_, Advancement p_136385_, String p_136386_);
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 p_136424_, boolean p_136425_) {
this.parents = p_136424_;
this.children = p_136425_;
}
}
}

View File

@@ -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> p_251026_, CommandBuildContext p_250936_) {
p_251026_.register(Commands.literal("attribute").requires((p_212441_) -> {
return p_212441_.hasPermission(2);
}).then(Commands.argument("target", EntityArgument.entity()).then(Commands.argument("attribute", ResourceArgument.resource(p_250936_, 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 p_252177_, Holder<Attribute> p_249942_) throws CommandSyntaxException {
AttributeInstance attributeinstance = getLivingEntity(p_252177_).getAttributes().getInstance(p_249942_);
if (attributeinstance == null) {
throw ERROR_NO_SUCH_ATTRIBUTE.create(p_252177_.getName(), getAttributeDescription(p_249942_));
} else {
return attributeinstance;
}
}
private static LivingEntity getLivingEntity(Entity p_136440_) throws CommandSyntaxException {
if (!(p_136440_ instanceof LivingEntity)) {
throw ERROR_NOT_LIVING_ENTITY.create(p_136440_.getName());
} else {
return (LivingEntity)p_136440_;
}
}
private static LivingEntity getEntityWithAttribute(Entity p_252105_, Holder<Attribute> p_248921_) throws CommandSyntaxException {
LivingEntity livingentity = getLivingEntity(p_252105_);
if (!livingentity.getAttributes().hasAttribute(p_248921_)) {
throw ERROR_NO_SUCH_ATTRIBUTE.create(p_252105_.getName(), getAttributeDescription(p_248921_));
} else {
return livingentity;
}
}
private static int getAttributeValue(CommandSourceStack p_251776_, Entity p_249647_, Holder<Attribute> p_250986_, double p_251395_) throws CommandSyntaxException {
LivingEntity livingentity = getEntityWithAttribute(p_249647_, p_250986_);
double d0 = livingentity.getAttributeValue(p_250986_);
p_251776_.sendSuccess(() -> {
return Component.translatable("commands.attribute.value.get.success", getAttributeDescription(p_250986_), p_249647_.getName(), d0);
}, false);
return (int)(d0 * p_251395_);
}
private static int getAttributeBase(CommandSourceStack p_248780_, Entity p_251083_, Holder<Attribute> p_250388_, double p_250194_) throws CommandSyntaxException {
LivingEntity livingentity = getEntityWithAttribute(p_251083_, p_250388_);
double d0 = livingentity.getAttributeBaseValue(p_250388_);
p_248780_.sendSuccess(() -> {
return Component.translatable("commands.attribute.base_value.get.success", getAttributeDescription(p_250388_), p_251083_.getName(), d0);
}, false);
return (int)(d0 * p_250194_);
}
private static int getAttributeModifier(CommandSourceStack p_136464_, Entity p_136465_, Holder<Attribute> p_250680_, UUID p_136467_, double p_136468_) throws CommandSyntaxException {
LivingEntity livingentity = getEntityWithAttribute(p_136465_, p_250680_);
AttributeMap attributemap = livingentity.getAttributes();
if (!attributemap.hasModifier(p_250680_, p_136467_)) {
throw ERROR_NO_SUCH_MODIFIER.create(p_136465_.getName(), getAttributeDescription(p_250680_), p_136467_);
} else {
double d0 = attributemap.getModifierValue(p_250680_, p_136467_);
p_136464_.sendSuccess(() -> {
return Component.translatable("commands.attribute.modifier.value.get.success", p_136467_, getAttributeDescription(p_250680_), p_136465_.getName(), d0);
}, false);
return (int)(d0 * p_136468_);
}
}
private static int setAttributeBase(CommandSourceStack p_248556_, Entity p_248620_, Holder<Attribute> p_249456_, double p_252212_) throws CommandSyntaxException {
getAttributeInstance(p_248620_, p_249456_).setBaseValue(p_252212_);
p_248556_.sendSuccess(() -> {
return Component.translatable("commands.attribute.base_value.set.success", getAttributeDescription(p_249456_), p_248620_.getName(), p_252212_);
}, false);
return 1;
}
private static int addModifier(CommandSourceStack p_136470_, Entity p_136471_, Holder<Attribute> p_251636_, UUID p_136473_, String p_136474_, double p_136475_, AttributeModifier.Operation p_136476_) throws CommandSyntaxException {
AttributeInstance attributeinstance = getAttributeInstance(p_136471_, p_251636_);
AttributeModifier attributemodifier = new AttributeModifier(p_136473_, p_136474_, p_136475_, p_136476_);
if (attributeinstance.hasModifier(attributemodifier)) {
throw ERROR_MODIFIER_ALREADY_PRESENT.create(p_136471_.getName(), getAttributeDescription(p_251636_), p_136473_);
} else {
attributeinstance.addPermanentModifier(attributemodifier);
p_136470_.sendSuccess(() -> {
return Component.translatable("commands.attribute.modifier.add.success", p_136473_, getAttributeDescription(p_251636_), p_136471_.getName());
}, false);
return 1;
}
}
private static int removeModifier(CommandSourceStack p_136459_, Entity p_136460_, Holder<Attribute> p_250830_, UUID p_136462_) throws CommandSyntaxException {
AttributeInstance attributeinstance = getAttributeInstance(p_136460_, p_250830_);
if (attributeinstance.removePermanentModifier(p_136462_)) {
p_136459_.sendSuccess(() -> {
return Component.translatable("commands.attribute.modifier.remove.success", p_136462_, getAttributeDescription(p_250830_), p_136460_.getName());
}, false);
return 1;
} else {
throw ERROR_NO_SUCH_MODIFIER.create(p_136460_.getName(), getAttributeDescription(p_250830_), p_136462_);
}
}
private static Component getAttributeDescription(Holder<Attribute> p_250602_) {
return Component.translatable(p_250602_.value().getDescriptionId());
}
}

View File

@@ -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> p_136528_) {
p_136528_.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 p_136534_, String p_136535_, @Nullable Component p_136536_) throws CommandSyntaxException {
if (InetAddresses.isInetAddress(p_136535_)) {
return banIp(p_136534_, p_136535_, p_136536_);
} else {
ServerPlayer serverplayer = p_136534_.getServer().getPlayerList().getPlayerByName(p_136535_);
if (serverplayer != null) {
return banIp(p_136534_, serverplayer.getIpAddress(), p_136536_);
} else {
throw ERROR_INVALID_IP.create();
}
}
}
private static int banIp(CommandSourceStack p_136540_, String p_136541_, @Nullable Component p_136542_) throws CommandSyntaxException {
IpBanList ipbanlist = p_136540_.getServer().getPlayerList().getIpBans();
if (ipbanlist.isBanned(p_136541_)) {
throw ERROR_ALREADY_BANNED.create();
} else {
List<ServerPlayer> list = p_136540_.getServer().getPlayerList().getPlayersWithAddress(p_136541_);
IpBanListEntry ipbanlistentry = new IpBanListEntry(p_136541_, (Date)null, p_136540_.getTextName(), (Date)null, p_136542_ == null ? null : p_136542_.getString());
ipbanlist.add(ipbanlistentry);
p_136540_.sendSuccess(() -> {
return Component.translatable("commands.banip.success", p_136541_, ipbanlistentry.getReason());
}, true);
if (!list.isEmpty()) {
p_136540_.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();
}
}
}

View File

@@ -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> p_136544_) {
p_136544_.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 p_136550_, Collection<? extends BanListEntry<?>> p_136551_) {
if (p_136551_.isEmpty()) {
p_136550_.sendSuccess(() -> {
return Component.translatable("commands.banlist.none");
}, false);
} else {
p_136550_.sendSuccess(() -> {
return Component.translatable("commands.banlist.list", p_136551_.size());
}, false);
for(BanListEntry<?> banlistentry : p_136551_) {
p_136550_.sendSuccess(() -> {
return Component.translatable("commands.banlist.entry", banlistentry.getDisplayName(), banlistentry.getSource(), banlistentry.getReason());
}, false);
}
}
return p_136551_.size();
}
}

View File

@@ -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> p_136559_) {
p_136559_.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 p_136565_, Collection<GameProfile> p_136566_, @Nullable Component p_136567_) throws CommandSyntaxException {
UserBanList userbanlist = p_136565_.getServer().getPlayerList().getBans();
int i = 0;
for(GameProfile gameprofile : p_136566_) {
if (!userbanlist.isBanned(gameprofile)) {
UserBanListEntry userbanlistentry = new UserBanListEntry(gameprofile, (Date)null, p_136565_.getTextName(), (Date)null, p_136567_ == null ? null : p_136567_.getString());
userbanlist.add(userbanlistentry);
++i;
p_136565_.sendSuccess(() -> {
return Component.translatable("commands.ban.success", ComponentUtils.getDisplayName(gameprofile), userbanlistentry.getReason());
}, true);
ServerPlayer serverplayer = p_136565_.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;
}
}
}

View File

@@ -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> p_136583_) {
p_136583_.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 p_136596_, CustomBossEvent p_136597_) {
p_136596_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.value", p_136597_.getDisplayName(), p_136597_.getValue());
}, true);
return p_136597_.getValue();
}
private static int getMax(CommandSourceStack p_136629_, CustomBossEvent p_136630_) {
p_136629_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.max", p_136630_.getDisplayName(), p_136630_.getMax());
}, true);
return p_136630_.getMax();
}
private static int getVisible(CommandSourceStack p_136640_, CustomBossEvent p_136641_) {
if (p_136641_.isVisible()) {
p_136640_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.visible.visible", p_136641_.getDisplayName());
}, true);
return 1;
} else {
p_136640_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.visible.hidden", p_136641_.getDisplayName());
}, true);
return 0;
}
}
private static int getPlayers(CommandSourceStack p_136645_, CustomBossEvent p_136646_) {
if (p_136646_.getPlayers().isEmpty()) {
p_136645_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.players.none", p_136646_.getDisplayName());
}, true);
} else {
p_136645_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.get.players.some", p_136646_.getDisplayName(), p_136646_.getPlayers().size(), ComponentUtils.formatList(p_136646_.getPlayers(), Player::getDisplayName));
}, true);
}
return p_136646_.getPlayers().size();
}
private static int setVisible(CommandSourceStack p_136619_, CustomBossEvent p_136620_, boolean p_136621_) throws CommandSyntaxException {
if (p_136620_.isVisible() == p_136621_) {
if (p_136621_) {
throw ERROR_ALREADY_VISIBLE.create();
} else {
throw ERROR_ALREADY_HIDDEN.create();
}
} else {
p_136620_.setVisible(p_136621_);
if (p_136621_) {
p_136619_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.visible.success.visible", p_136620_.getDisplayName());
}, true);
} else {
p_136619_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.visible.success.hidden", p_136620_.getDisplayName());
}, true);
}
return 0;
}
}
private static int setValue(CommandSourceStack p_136599_, CustomBossEvent p_136600_, int p_136601_) throws CommandSyntaxException {
if (p_136600_.getValue() == p_136601_) {
throw ERROR_NO_VALUE_CHANGE.create();
} else {
p_136600_.setValue(p_136601_);
p_136599_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.value.success", p_136600_.getDisplayName(), p_136601_);
}, true);
return p_136601_;
}
}
private static int setMax(CommandSourceStack p_136632_, CustomBossEvent p_136633_, int p_136634_) throws CommandSyntaxException {
if (p_136633_.getMax() == p_136634_) {
throw ERROR_NO_MAX_CHANGE.create();
} else {
p_136633_.setMax(p_136634_);
p_136632_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.max.success", p_136633_.getDisplayName(), p_136634_);
}, true);
return p_136634_;
}
}
private static int setColor(CommandSourceStack p_136603_, CustomBossEvent p_136604_, BossEvent.BossBarColor p_136605_) throws CommandSyntaxException {
if (p_136604_.getColor().equals(p_136605_)) {
throw ERROR_NO_COLOR_CHANGE.create();
} else {
p_136604_.setColor(p_136605_);
p_136603_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.color.success", p_136604_.getDisplayName());
}, true);
return 0;
}
}
private static int setStyle(CommandSourceStack p_136607_, CustomBossEvent p_136608_, BossEvent.BossBarOverlay p_136609_) throws CommandSyntaxException {
if (p_136608_.getOverlay().equals(p_136609_)) {
throw ERROR_NO_STYLE_CHANGE.create();
} else {
p_136608_.setOverlay(p_136609_);
p_136607_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.style.success", p_136608_.getDisplayName());
}, true);
return 0;
}
}
private static int setName(CommandSourceStack p_136615_, CustomBossEvent p_136616_, Component p_136617_) throws CommandSyntaxException {
Component component = ComponentUtils.updateForEntity(p_136615_, p_136617_, (Entity)null, 0);
if (p_136616_.getName().equals(component)) {
throw ERROR_NO_NAME_CHANGE.create();
} else {
p_136616_.setName(component);
p_136615_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.name.success", p_136616_.getDisplayName());
}, true);
return 0;
}
}
private static int setPlayers(CommandSourceStack p_136611_, CustomBossEvent p_136612_, Collection<ServerPlayer> p_136613_) throws CommandSyntaxException {
boolean flag = p_136612_.setPlayers(p_136613_);
if (!flag) {
throw ERROR_NO_PLAYER_CHANGE.create();
} else {
if (p_136612_.getPlayers().isEmpty()) {
p_136611_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.players.success.none", p_136612_.getDisplayName());
}, true);
} else {
p_136611_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.set.players.success.some", p_136612_.getDisplayName(), p_136613_.size(), ComponentUtils.formatList(p_136613_, Player::getDisplayName));
}, true);
}
return p_136612_.getPlayers().size();
}
}
private static int listBars(CommandSourceStack p_136590_) {
Collection<CustomBossEvent> collection = p_136590_.getServer().getCustomBossEvents().getEvents();
if (collection.isEmpty()) {
p_136590_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.list.bars.none");
}, false);
} else {
p_136590_.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 p_136592_, ResourceLocation p_136593_, Component p_136594_) throws CommandSyntaxException {
CustomBossEvents custombossevents = p_136592_.getServer().getCustomBossEvents();
if (custombossevents.get(p_136593_) != null) {
throw ERROR_ALREADY_EXISTS.create(p_136593_.toString());
} else {
CustomBossEvent custombossevent = custombossevents.create(p_136593_, ComponentUtils.updateForEntity(p_136592_, p_136594_, (Entity)null, 0));
p_136592_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.create.success", custombossevent.getDisplayName());
}, true);
return custombossevents.getEvents().size();
}
}
private static int removeBar(CommandSourceStack p_136650_, CustomBossEvent p_136651_) {
CustomBossEvents custombossevents = p_136650_.getServer().getCustomBossEvents();
p_136651_.removeAllPlayers();
custombossevents.remove(p_136651_);
p_136650_.sendSuccess(() -> {
return Component.translatable("commands.bossbar.remove.success", p_136651_.getDisplayName());
}, true);
return custombossevents.getEvents().size();
}
public static CustomBossEvent getBossBar(CommandContext<CommandSourceStack> p_136585_) throws CommandSyntaxException {
ResourceLocation resourcelocation = ResourceLocationArgument.getId(p_136585_, "id");
CustomBossEvent custombossevent = p_136585_.getSource().getServer().getCustomBossEvents().get(resourcelocation);
if (custombossevent == null) {
throw ERROR_DOESNT_EXIST.create(resourcelocation.toString());
} else {
return custombossevent;
}
}
}

View File

@@ -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> p_196078_) {
p_196078_.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 p_196082_) {
if (chaseClient != null) {
chaseClient.stop();
p_196082_.sendSuccess(() -> {
return Component.literal("You have now stopped chasing");
}, false);
chaseClient = null;
}
if (chaseServer != null) {
chaseServer.stop();
p_196082_.sendSuccess(() -> {
return Component.literal("You are no longer being chased");
}, false);
chaseServer = null;
}
return 0;
}
private static boolean alreadyRunning(CommandSourceStack p_196090_) {
if (chaseServer != null) {
p_196090_.sendFailure(Component.literal("Chase server is already running. Stop it using /chase stop"));
return true;
} else if (chaseClient != null) {
p_196090_.sendFailure(Component.literal("You are already chasing someone. Stop it using /chase stop"));
return true;
} else {
return false;
}
}
private static int lead(CommandSourceStack p_196084_, String p_196085_, int p_196086_) {
if (alreadyRunning(p_196084_)) {
return 0;
} else {
chaseServer = new ChaseServer(p_196085_, p_196086_, p_196084_.getServer().getPlayerList(), 100);
try {
chaseServer.start();
p_196084_.sendSuccess(() -> {
return Component.literal("Chase server is now running on port " + p_196086_ + ". Clients can follow you using /chase follow <ip> <port>");
}, false);
} catch (IOException ioexception) {
ioexception.printStackTrace();
p_196084_.sendFailure(Component.literal("Failed to start chase server on port " + p_196086_));
chaseServer = null;
}
return 0;
}
}
private static int follow(CommandSourceStack p_196092_, String p_196093_, int p_196094_) {
if (alreadyRunning(p_196092_)) {
return 0;
} else {
chaseClient = new ChaseClient(p_196093_, p_196094_, p_196092_.getServer());
chaseClient.start();
p_196092_.sendSuccess(() -> {
return Component.literal("You are now chasing " + p_196093_ + ":" + p_196094_ + ". If that server does '/chase lead' then you will automatically go to the same position. Use '/chase stop' to stop chasing.");
}, false);
return 0;
}
}
}

View File

@@ -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> p_214421_, CommandBuildContext p_214422_) {
p_214421_.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(p_214422_)).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 p_136706_, Collection<ServerPlayer> p_136707_, Predicate<ItemStack> p_136708_, int p_136709_) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : p_136707_) {
i += serverplayer.getInventory().clearOrCountMatchingItems(p_136708_, p_136709_, serverplayer.inventoryMenu.getCraftSlots());
serverplayer.containerMenu.broadcastChanges();
serverplayer.inventoryMenu.slotsChanged(serverplayer.getInventory());
}
if (i == 0) {
if (p_136707_.size() == 1) {
throw ERROR_SINGLE.create(p_136707_.iterator().next().getName());
} else {
throw ERROR_MULTIPLE.create(p_136707_.size());
}
} else {
int j = i;
if (p_136709_ == 0) {
if (p_136707_.size() == 1) {
p_136706_.sendSuccess(() -> {
return Component.translatable("commands.clear.test.single", j, p_136707_.iterator().next().getDisplayName());
}, true);
} else {
p_136706_.sendSuccess(() -> {
return Component.translatable("commands.clear.test.multiple", j, p_136707_.size());
}, true);
}
} else if (p_136707_.size() == 1) {
p_136706_.sendSuccess(() -> {
return Component.translatable("commands.clear.success.single", j, p_136707_.iterator().next().getDisplayName());
}, true);
} else {
p_136706_.sendSuccess(() -> {
return Component.translatable("commands.clear.success.multiple", j, p_136707_.size());
}, true);
}
return i;
}
}
}

View File

@@ -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> p_214424_, CommandBuildContext p_214425_) {
p_214424_.register(Commands.literal("clone").requires((p_136734_) -> {
return p_136734_.hasPermission(2);
}).then(beginEndDestinationAndModeSuffix(p_214425_, (p_264757_) -> {
return p_264757_.getSource().getLevel();
})).then(Commands.literal("from").then(Commands.argument("sourceDimension", DimensionArgument.dimension()).then(beginEndDestinationAndModeSuffix(p_214425_, (p_264743_) -> {
return DimensionArgument.getDimension(p_264743_, "sourceDimension");
})))));
}
private static ArgumentBuilder<CommandSourceStack, ?> beginEndDestinationAndModeSuffix(CommandBuildContext p_265681_, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, ServerLevel> p_265514_) {
return Commands.argument("begin", BlockPosArgument.blockPos()).then(Commands.argument("end", BlockPosArgument.blockPos()).then(destinationAndModeSuffix(p_265681_, p_265514_, (p_264751_) -> {
return p_264751_.getSource().getLevel();
})).then(Commands.literal("to").then(Commands.argument("targetDimension", DimensionArgument.dimension()).then(destinationAndModeSuffix(p_265681_, p_265514_, (p_264756_) -> {
return DimensionArgument.getDimension(p_264756_, "targetDimension");
})))));
}
private static CloneCommands.DimensionAndPosition getLoadedDimensionAndPosition(CommandContext<CommandSourceStack> p_265513_, ServerLevel p_265183_, String p_265511_) throws CommandSyntaxException {
BlockPos blockpos = BlockPosArgument.getLoadedBlockPos(p_265513_, p_265183_, p_265511_);
return new CloneCommands.DimensionAndPosition(p_265183_, blockpos);
}
private static ArgumentBuilder<CommandSourceStack, ?> destinationAndModeSuffix(CommandBuildContext p_265238_, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, ServerLevel> p_265621_, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, ServerLevel> p_265296_) {
CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> commandfunction = (p_264737_) -> {
return getLoadedDimensionAndPosition(p_264737_, p_265621_.apply(p_264737_), "begin");
};
CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> commandfunction1 = (p_264735_) -> {
return getLoadedDimensionAndPosition(p_264735_, p_265621_.apply(p_264735_), "end");
};
CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> commandfunction2 = (p_264768_) -> {
return getLoadedDimensionAndPosition(p_264768_, p_265296_.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(p_265238_)).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> p_265374_, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> p_265134_, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, CloneCommands.DimensionAndPosition> p_265546_, CloneCommands.CommandFunction<CommandContext<CommandSourceStack>, Predicate<BlockInWorld>> p_265798_, ArgumentBuilder<CommandSourceStack, ?> p_265069_) {
return p_265069_.then(Commands.literal("force").executes((p_264773_) -> {
return clone(p_264773_.getSource(), p_265374_.apply(p_264773_), p_265134_.apply(p_264773_), p_265546_.apply(p_264773_), p_265798_.apply(p_264773_), CloneCommands.Mode.FORCE);
})).then(Commands.literal("move").executes((p_264766_) -> {
return clone(p_264766_.getSource(), p_265374_.apply(p_264766_), p_265134_.apply(p_264766_), p_265546_.apply(p_264766_), p_265798_.apply(p_264766_), CloneCommands.Mode.MOVE);
})).then(Commands.literal("normal").executes((p_264750_) -> {
return clone(p_264750_.getSource(), p_265374_.apply(p_264750_), p_265134_.apply(p_264750_), p_265546_.apply(p_264750_), p_265798_.apply(p_264750_), CloneCommands.Mode.NORMAL);
}));
}
private static int clone(CommandSourceStack p_265047_, CloneCommands.DimensionAndPosition p_265232_, CloneCommands.DimensionAndPosition p_265188_, CloneCommands.DimensionAndPosition p_265594_, Predicate<BlockInWorld> p_265585_, CloneCommands.Mode p_265530_) throws CommandSyntaxException {
BlockPos blockpos = p_265232_.position();
BlockPos blockpos1 = p_265188_.position();
BoundingBox boundingbox = BoundingBox.fromCorners(blockpos, blockpos1);
BlockPos blockpos2 = p_265594_.position();
BlockPos blockpos3 = blockpos2.offset(boundingbox.getLength());
BoundingBox boundingbox1 = BoundingBox.fromCorners(blockpos2, blockpos3);
ServerLevel serverlevel = p_265232_.dimension();
ServerLevel serverlevel1 = p_265594_.dimension();
if (!p_265530_.canOverlap() && serverlevel == serverlevel1 && boundingbox1.intersects(boundingbox)) {
throw ERROR_OVERLAP.create();
} else {
int i = boundingbox.getXSpan() * boundingbox.getYSpan() * boundingbox.getZSpan();
int j = p_265047_.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 (p_265585_.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 (p_265530_ == 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;
p_265047_.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 p_136783_, BlockState p_136784_, @Nullable CompoundTag p_136785_) {
this.pos = p_136783_;
this.state = p_136784_;
this.tag = p_136785_;
}
}
@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 p_136795_) {
this.canOverlap = p_136795_;
}
public boolean canOverlap() {
return this.canOverlap;
}
}
}

View File

@@ -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> p_270226_, CommandBuildContext p_270136_) {
p_270226_.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(p_270136_, 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 p_270409_, Entity p_270496_, float p_270836_, DamageSource p_270727_) throws CommandSyntaxException {
if (p_270496_.hurt(p_270727_, p_270836_)) {
p_270409_.sendSuccess(() -> {
return Component.translatable("commands.damage.success", p_270836_, p_270496_.getDisplayName());
}, true);
return 1;
} else {
throw ERROR_INVULNERABLE.create();
}
}
}

View File

@@ -0,0 +1,181 @@
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> p_136809_) {
p_136809_.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());
}))));
}
private static int enablePack(CommandSourceStack p_136829_, Pack p_136830_, DataPackCommand.Inserter p_136831_) throws CommandSyntaxException {
PackRepository packrepository = p_136829_.getServer().getPackRepository();
List<Pack> list = Lists.newArrayList(packrepository.getSelectedPacks());
p_136831_.apply(list, p_136830_);
p_136829_.sendSuccess(() -> {
return Component.translatable("commands.datapack.modify.enable", p_136830_.getChatLink(true));
}, true);
ReloadCommand.reloadPacks(list.stream().map(Pack::getId).collect(Collectors.toList()), p_136829_);
return list.size();
}
private static int disablePack(CommandSourceStack p_136826_, Pack p_136827_) {
PackRepository packrepository = p_136826_.getServer().getPackRepository();
List<Pack> list = Lists.newArrayList(packrepository.getSelectedPacks());
list.remove(p_136827_);
p_136826_.sendSuccess(() -> {
return Component.translatable("commands.datapack.modify.disable", p_136827_.getChatLink(true));
}, true);
ReloadCommand.reloadPacks(list.stream().map(Pack::getId).collect(Collectors.toList()), p_136826_);
return list.size();
}
private static int listPacks(CommandSourceStack p_136824_) {
return listEnabledPacks(p_136824_) + listAvailablePacks(p_136824_);
}
private static int listAvailablePacks(CommandSourceStack p_136855_) {
PackRepository packrepository = p_136855_.getServer().getPackRepository();
packrepository.reload();
Collection<Pack> collection = packrepository.getSelectedPacks();
Collection<Pack> collection1 = packrepository.getAvailablePacks();
FeatureFlagSet featureflagset = p_136855_.enabledFeatures();
List<Pack> list = collection1.stream().filter((p_248121_) -> {
return !collection.contains(p_248121_) && p_248121_.getRequestedFeatures().isSubsetOf(featureflagset);
}).toList();
if (list.isEmpty()) {
p_136855_.sendSuccess(() -> {
return Component.translatable("commands.datapack.list.available.none");
}, false);
} else {
p_136855_.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();
}
private static int listEnabledPacks(CommandSourceStack p_136866_) {
PackRepository packrepository = p_136866_.getServer().getPackRepository();
packrepository.reload();
Collection<? extends Pack> collection = packrepository.getSelectedPacks();
if (collection.isEmpty()) {
p_136866_.sendSuccess(() -> {
return Component.translatable("commands.datapack.list.enabled.none");
}, false);
} else {
p_136866_.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> p_136816_, String p_136817_, boolean p_136818_) throws CommandSyntaxException {
String s = StringArgumentType.getString(p_136816_, p_136817_);
PackRepository packrepository = p_136816_.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 (p_136818_ && flag) {
throw ERROR_PACK_ALREADY_ENABLED.create(s);
} else if (!p_136818_ && !flag) {
throw ERROR_PACK_ALREADY_DISABLED.create(s);
} else {
FeatureFlagSet featureflagset = p_136816_.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;
}
}

View File

@@ -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> p_136889_) {
p_136889_.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 p_136898_, Collection<GameProfile> p_136899_) throws CommandSyntaxException {
PlayerList playerlist = p_136898_.getServer().getPlayerList();
int i = 0;
for(GameProfile gameprofile : p_136899_) {
if (playerlist.isOp(gameprofile)) {
playerlist.deop(gameprofile);
++i;
p_136898_.sendSuccess(() -> {
return Component.translatable("commands.deop.success", p_136899_.iterator().next().getName());
}, true);
}
}
if (i == 0) {
throw ERROR_NOT_OP.create();
} else {
p_136898_.getServer().kickUnlistedPlayers(p_136898_);
return i;
}
}
}

View File

@@ -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> p_136906_) {
p_136906_.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 p_136910_) throws CommandSyntaxException {
MinecraftServer minecraftserver = p_136910_.getServer();
if (minecraftserver.isTimeProfilerRunning()) {
throw ERROR_ALREADY_RUNNING.create();
} else {
minecraftserver.startTimeProfiler();
p_136910_.sendSuccess(() -> {
return Component.translatable("commands.debug.started");
}, true);
return 0;
}
}
private static int stop(CommandSourceStack p_136916_) throws CommandSyntaxException {
MinecraftServer minecraftserver = p_136916_.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;
p_136916_.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 p_180066_, Collection<CommandFunction> p_180067_) {
int i = 0;
MinecraftServer minecraftserver = p_180066_.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 : p_180067_) {
printwriter.println((Object)commandfunction.getId());
DebugCommand.Tracer debugcommand$tracer = new DebugCommand.Tracer(printwriter);
i += p_180066_.getServer().getFunctions().execute(commandfunction, p_180066_.withSource(debugcommand$tracer).withMaximumPermission(2), debugcommand$tracer);
}
}
} catch (IOException | UncheckedIOException uncheckedioexception) {
LOGGER.warn("Tracing failed", (Throwable)uncheckedioexception);
p_180066_.sendFailure(Component.translatable("commands.debug.function.traceFailed"));
}
int j = i;
if (p_180067_.size() == 1) {
p_180066_.sendSuccess(() -> {
return Component.translatable("commands.debug.function.success.single", j, p_180067_.iterator().next().getId(), s);
}, true);
} else {
p_180066_.sendSuccess(() -> {
return Component.translatable("commands.debug.function.success.multiple", j, p_180067_.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 p_180079_) {
this.output = p_180079_;
}
private void indentAndSave(int p_180082_) {
this.printIndent(p_180082_);
this.lastIndent = p_180082_;
}
private void printIndent(int p_180098_) {
for(int i = 0; i < p_180098_ + 1; ++i) {
this.output.write(" ");
}
}
private void newLine() {
if (this.waitingForResult) {
this.output.println();
this.waitingForResult = false;
}
}
public void onCommand(int p_180084_, String p_180085_) {
this.newLine();
this.indentAndSave(p_180084_);
this.output.print("[C] ");
this.output.print(p_180085_);
this.waitingForResult = true;
}
public void onReturn(int p_180087_, String p_180088_, int p_180089_) {
if (this.waitingForResult) {
this.output.print(" -> ");
this.output.println(p_180089_);
this.waitingForResult = false;
} else {
this.indentAndSave(p_180087_);
this.output.print("[R = ");
this.output.print(p_180089_);
this.output.print("] ");
this.output.println(p_180088_);
}
}
public void onCall(int p_180091_, ResourceLocation p_180092_, int p_180093_) {
this.newLine();
this.indentAndSave(p_180091_);
this.output.print("[F] ");
this.output.print((Object)p_180092_);
this.output.print(" size=");
this.output.println(p_180093_);
}
public void onError(int p_180100_, String p_180101_) {
this.newLine();
this.indentAndSave(p_180100_ + 1);
this.output.print("[E] ");
this.output.print(p_180101_);
}
public void sendSystemMessage(Component p_214427_) {
this.newLine();
this.printIndent(this.lastIndent + 1);
this.output.print("[M] ");
this.output.println(p_214427_.getString());
}
public boolean acceptsSuccess() {
return true;
}
public boolean acceptsFailure() {
return true;
}
public boolean shouldInformAdmins() {
return false;
}
public boolean alwaysAccepts() {
return true;
}
}
}

View File

@@ -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> p_180111_) {
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"));
})));
}
p_180111_.register(literalargumentbuilder);
}
private static int spawnMobs(CommandSourceStack p_180115_, MobCategory p_180116_, BlockPos p_180117_) {
NaturalSpawner.spawnCategoryForPosition(p_180116_, p_180115_.getLevel(), p_180117_);
return 1;
}
}

View File

@@ -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> p_180124_) {
p_180124_.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 p_180130_, BlockPos p_180131_) throws CommandSyntaxException {
Entity entity = p_180130_.getEntity();
if (!(entity instanceof Mob mob)) {
throw ERROR_NOT_MOB.create();
} else {
PathNavigation pathnavigation = new GroundPathNavigation(mob, p_180130_.getLevel());
Path path = pathnavigation.createPath(p_180131_, 0);
DebugPackets.sendPathFindingPacket(p_180130_.getLevel(), mob, path, pathnavigation.getMaxDistanceToWaypoint());
if (path == null) {
throw ERROR_NO_PATH.create();
} else if (!path.canReach()) {
throw ERROR_NOT_COMPLETE.create();
} else {
p_180130_.sendSuccess(() -> {
return Component.literal("Made path");
}, true);
return 1;
}
}
}
}

View File

@@ -0,0 +1,39 @@
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> p_136927_) {
p_136927_.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"));
})));
}
private static int setMode(CommandSourceStack p_136931_, GameType p_136932_) {
int i = 0;
MinecraftServer minecraftserver = p_136931_.getServer();
minecraftserver.setDefaultGameType(p_136932_);
GameType gametype = minecraftserver.getForcedGameType();
if (gametype != null) {
for(ServerPlayer serverplayer : minecraftserver.getPlayerList().getPlayers()) {
if (serverplayer.setGameMode(gametype)) {
++i;
}
}
}
p_136931_.sendSuccess(() -> {
return Component.translatable("commands.defaultgamemode.success", p_136932_.getLongDisplayName());
}, true);
return i;
}
}

View File

@@ -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> p_136939_) {
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);
}));
}
p_136939_.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 p_136945_, Difficulty p_136946_) throws CommandSyntaxException {
MinecraftServer minecraftserver = p_136945_.getServer();
if (minecraftserver.getWorldData().getDifficulty() == p_136946_) {
throw ERROR_ALREADY_DIFFICULT.create(p_136946_.getKey());
} else {
minecraftserver.setDifficulty(p_136946_, true);
p_136945_.sendSuccess(() -> {
return Component.translatable("commands.difficulty.success", p_136946_.getDisplayName());
}, true);
return 0;
}
}
}

View File

@@ -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> p_136954_, CommandBuildContext p_251610_) {
p_136954_.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(p_251610_, 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(p_251610_, 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 p_250553_, Collection<? extends Entity> p_250411_, Holder<MobEffect> p_249495_, @Nullable Integer p_249652_, int p_251498_, boolean p_249944_) throws CommandSyntaxException {
MobEffect mobeffect = p_249495_.value();
int i = 0;
int j;
if (p_249652_ != null) {
if (mobeffect.isInstantenous()) {
j = p_249652_;
} else if (p_249652_ == -1) {
j = -1;
} else {
j = p_249652_ * 20;
}
} else if (mobeffect.isInstantenous()) {
j = 1;
} else {
j = 600;
}
for(Entity entity : p_250411_) {
if (entity instanceof LivingEntity) {
MobEffectInstance mobeffectinstance = new MobEffectInstance(mobeffect, j, p_251498_, false, p_249944_);
if (((LivingEntity)entity).addEffect(mobeffectinstance, p_250553_.getEntity())) {
++i;
}
}
}
if (i == 0) {
throw ERROR_GIVE_FAILED.create();
} else {
if (p_250411_.size() == 1) {
p_250553_.sendSuccess(() -> {
return Component.translatable("commands.effect.give.success.single", mobeffect.getDisplayName(), p_250411_.iterator().next().getDisplayName(), j / 20);
}, true);
} else {
p_250553_.sendSuccess(() -> {
return Component.translatable("commands.effect.give.success.multiple", mobeffect.getDisplayName(), p_250411_.size(), j / 20);
}, true);
}
return i;
}
}
private static int clearEffects(CommandSourceStack p_136960_, Collection<? extends Entity> p_136961_) throws CommandSyntaxException {
int i = 0;
for(Entity entity : p_136961_) {
if (entity instanceof LivingEntity && ((LivingEntity)entity).removeAllEffects()) {
++i;
}
}
if (i == 0) {
throw ERROR_CLEAR_EVERYTHING_FAILED.create();
} else {
if (p_136961_.size() == 1) {
p_136960_.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.everything.success.single", p_136961_.iterator().next().getDisplayName());
}, true);
} else {
p_136960_.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.everything.success.multiple", p_136961_.size());
}, true);
}
return i;
}
}
private static int clearEffect(CommandSourceStack p_250069_, Collection<? extends Entity> p_248561_, Holder<MobEffect> p_249198_) throws CommandSyntaxException {
MobEffect mobeffect = p_249198_.value();
int i = 0;
for(Entity entity : p_248561_) {
if (entity instanceof LivingEntity && ((LivingEntity)entity).removeEffect(mobeffect)) {
++i;
}
}
if (i == 0) {
throw ERROR_CLEAR_SPECIFIC_FAILED.create();
} else {
if (p_248561_.size() == 1) {
p_250069_.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.specific.success.single", mobeffect.getDisplayName(), p_248561_.iterator().next().getDisplayName());
}, true);
} else {
p_250069_.sendSuccess(() -> {
return Component.translatable("commands.effect.clear.specific.success.multiple", mobeffect.getDisplayName(), p_248561_.size());
}, true);
}
return i;
}
}
}

View File

@@ -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> p_136986_) {
p_136986_.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;
})));
}
}

View File

@@ -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> p_251241_, CommandBuildContext p_251038_) {
p_251241_.register(Commands.literal("enchant").requires((p_137013_) -> {
return p_137013_.hasPermission(2);
}).then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("enchantment", ResourceArgument.resource(p_251038_, 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 p_249815_, Collection<? extends Entity> p_248848_, Holder<Enchantment> p_251252_, int p_249941_) throws CommandSyntaxException {
Enchantment enchantment = p_251252_.value();
if (p_249941_ > enchantment.getMaxLevel()) {
throw ERROR_LEVEL_TOO_HIGH.create(p_249941_, enchantment.getMaxLevel());
} else {
int i = 0;
for(Entity entity : p_248848_) {
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, p_249941_);
++i;
} else if (p_248848_.size() == 1) {
throw ERROR_INCOMPATIBLE.create(itemstack.getItem().getName(itemstack).getString());
}
} else if (p_248848_.size() == 1) {
throw ERROR_NO_ITEM.create(livingentity.getName().getString());
}
} else if (p_248848_.size() == 1) {
throw ERROR_NOT_LIVING_ENTITY.create(entity.getName().getString());
}
}
if (i == 0) {
throw ERROR_NOTHING_HAPPENED.create();
} else {
if (p_248848_.size() == 1) {
p_249815_.sendSuccess(() -> {
return Component.translatable("commands.enchant.success.single", enchantment.getFullname(p_249941_), p_248848_.iterator().next().getDisplayName());
}, true);
} else {
p_249815_.sendSuccess(() -> {
return Component.translatable("commands.enchant.success.multiple", enchantment.getFullname(p_249941_), p_248848_.size());
}, true);
}
return i;
}
}
}
}

View File

@@ -0,0 +1,587 @@
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> p_214435_, CommandBuildContext p_214436_) {
LiteralCommandNode<CommandSourceStack> literalcommandnode = p_214435_.register(Commands.literal("execute").requires((p_137197_) -> {
return p_137197_.hasPermission(2);
}));
p_214435_.register(Commands.literal("execute").requires((p_137103_) -> {
return p_137103_.hasPermission(2);
}).then(Commands.literal("run").redirect(p_214435_.getRoot())).then(addConditionals(literalcommandnode, Commands.literal("if"), true, p_214436_)).then(addConditionals(literalcommandnode, Commands.literal("unless"), false, p_214436_)).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(p_214436_, 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> p_137094_, LiteralArgumentBuilder<CommandSourceStack> p_137095_, boolean p_137096_) {
p_137095_.then(Commands.literal("score").then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(Commands.argument("objective", ObjectiveArgument.objective()).redirect(p_137094_, (p_137271_) -> {
return storeValue(p_137271_.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(p_137271_, "targets"), ObjectiveArgument.getObjective(p_137271_, "objective"), p_137096_);
}))));
p_137095_.then(Commands.literal("bossbar").then(Commands.argument("id", ResourceLocationArgument.id()).suggests(BossBarCommands.SUGGEST_BOSS_BAR).then(Commands.literal("value").redirect(p_137094_, (p_137259_) -> {
return storeValue(p_137259_.getSource(), BossBarCommands.getBossBar(p_137259_), true, p_137096_);
})).then(Commands.literal("max").redirect(p_137094_, (p_137247_) -> {
return storeValue(p_137247_.getSource(), BossBarCommands.getBossBar(p_137247_), false, p_137096_);
}))));
for(DataCommands.DataProvider datacommands$dataprovider : DataCommands.TARGET_PROVIDERS) {
datacommands$dataprovider.wrap(p_137095_, (p_137101_) -> {
return p_137101_.then(Commands.argument("path", NbtPathArgument.nbtPath()).then(Commands.literal("int").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(p_137094_, (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")));
}, p_137096_);
}))).then(Commands.literal("float").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(p_137094_, (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")));
}, p_137096_);
}))).then(Commands.literal("short").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(p_137094_, (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"))));
}, p_137096_);
}))).then(Commands.literal("long").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(p_137094_, (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")));
}, p_137096_);
}))).then(Commands.literal("double").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(p_137094_, (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"));
}, p_137096_);
}))).then(Commands.literal("byte").then(Commands.argument("scale", DoubleArgumentType.doubleArg()).redirect(p_137094_, (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"))));
}, p_137096_);
}))));
});
}
return p_137095_;
}
private static CommandSourceStack storeValue(CommandSourceStack p_137108_, Collection<String> p_137109_, Objective p_137110_, boolean p_137111_) {
Scoreboard scoreboard = p_137108_.getServer().getScoreboard();
return p_137108_.withCallback((p_137136_, p_137137_, p_137138_) -> {
for(String s : p_137109_) {
Score score = scoreboard.getOrCreatePlayerScore(s, p_137110_);
int i = p_137111_ ? p_137138_ : (p_137137_ ? 1 : 0);
score.setScore(i);
}
}, CALLBACK_CHAINER);
}
private static CommandSourceStack storeValue(CommandSourceStack p_137113_, CustomBossEvent p_137114_, boolean p_137115_, boolean p_137116_) {
return p_137113_.withCallback((p_137185_, p_137186_, p_137187_) -> {
int i = p_137116_ ? p_137187_ : (p_137186_ ? 1 : 0);
if (p_137115_) {
p_137114_.setValue(i);
} else {
p_137114_.setMax(i);
}
}, CALLBACK_CHAINER);
}
private static CommandSourceStack storeData(CommandSourceStack p_137118_, DataAccessor p_137119_, NbtPathArgument.NbtPath p_137120_, IntFunction<Tag> p_137121_, boolean p_137122_) {
return p_137118_.withCallback((p_137153_, p_137154_, p_137155_) -> {
try {
CompoundTag compoundtag = p_137119_.getData();
int i = p_137122_ ? p_137155_ : (p_137154_ ? 1 : 0);
p_137120_.set(compoundtag, p_137121_.apply(i));
p_137119_.setData(compoundtag);
} catch (CommandSyntaxException commandsyntaxexception) {
}
}, CALLBACK_CHAINER);
}
private static boolean isChunkLoaded(ServerLevel p_265261_, BlockPos p_265260_) {
ChunkPos chunkpos = new ChunkPos(p_265260_);
LevelChunk levelchunk = p_265261_.getChunkSource().getChunkNow(chunkpos.x, chunkpos.z);
if (levelchunk == null) {
return false;
} else {
return levelchunk.getFullStatus() == FullChunkStatus.ENTITY_TICKING && p_265261_.areEntitiesLoaded(chunkpos.toLong());
}
}
private static ArgumentBuilder<CommandSourceStack, ?> addConditionals(CommandNode<CommandSourceStack> p_214438_, LiteralArgumentBuilder<CommandSourceStack> p_214439_, boolean p_214440_, CommandBuildContext p_214441_) {
p_214439_.then(Commands.literal("block").then(Commands.argument("pos", BlockPosArgument.blockPos()).then(addConditional(p_214438_, Commands.argument("block", BlockPredicateArgument.blockPredicate(p_214441_)), p_214440_, (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(p_214438_, Commands.argument("biome", ResourceOrTagArgument.resourceOrTag(p_214441_, Registries.BIOME)), p_214440_, (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(p_214438_, Commands.argument("pos", BlockPosArgument.blockPos()), p_214440_, (p_269757_) -> {
return isChunkLoaded(p_269757_.getSource().getLevel(), BlockPosArgument.getBlockPos(p_269757_, "pos"));
}))).then(Commands.literal("dimension").then(addConditional(p_214438_, Commands.argument("dimension", DimensionArgument.dimension()), p_214440_, (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(p_214438_, Commands.argument("sourceObjective", ObjectiveArgument.objective()), p_214440_, (p_137275_) -> {
return checkScore(p_137275_, Integer::equals);
})))).then(Commands.literal("<").then(Commands.argument("source", ScoreHolderArgument.scoreHolder()).suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS).then(addConditional(p_214438_, Commands.argument("sourceObjective", ObjectiveArgument.objective()), p_214440_, (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(p_214438_, Commands.argument("sourceObjective", ObjectiveArgument.objective()), p_214440_, (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(p_214438_, Commands.argument("sourceObjective", ObjectiveArgument.objective()), p_214440_, (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(p_214438_, Commands.argument("sourceObjective", ObjectiveArgument.objective()), p_214440_, (p_137234_) -> {
return checkScore(p_137234_, (p_180167_, p_180168_) -> {
return p_180167_ >= p_180168_;
});
})))).then(Commands.literal("matches").then(addConditional(p_214438_, Commands.argument("range", RangeArgument.intRange()), p_214440_, (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(p_214438_, Commands.literal("all"), p_214440_, false)).then(addIfBlocksConditional(p_214438_, Commands.literal("masked"), p_214440_, true)))))).then(Commands.literal("entity").then(Commands.argument("entities", EntityArgument.entities()).fork(p_214438_, (p_137232_) -> {
return expect(p_137232_, p_214440_, !EntityArgument.getOptionalEntities(p_137232_, "entities").isEmpty());
}).executes(createNumericConditionalHandler(p_214440_, (p_137189_) -> {
return EntityArgument.getOptionalEntities(p_137189_, "entities").size();
})))).then(Commands.literal("predicate").then(addConditional(p_214438_, Commands.argument("predicate", ResourceLocationArgument.id()).suggests(SUGGEST_PREDICATE), p_214440_, (p_137054_) -> {
return checkCustomPredicate(p_137054_.getSource(), ResourceLocationArgument.getPredicate(p_137054_, "predicate"));
})));
for(DataCommands.DataProvider datacommands$dataprovider : DataCommands.SOURCE_PROVIDERS) {
p_214439_.then(datacommands$dataprovider.wrap(Commands.literal("data"), (p_137092_) -> {
return p_137092_.then(Commands.argument("path", NbtPathArgument.nbtPath()).fork(p_214438_, (p_180175_) -> {
return expect(p_180175_, p_214440_, checkMatchingData(datacommands$dataprovider.access(p_180175_), NbtPathArgument.getPath(p_180175_, "path")) > 0);
}).executes(createNumericConditionalHandler(p_214440_, (p_180152_) -> {
return checkMatchingData(datacommands$dataprovider.access(p_180152_), NbtPathArgument.getPath(p_180152_, "path"));
})));
}));
}
return p_214439_;
}
private static Command<CommandSourceStack> createNumericConditionalHandler(boolean p_137167_, ExecuteCommand.CommandNumericPredicate p_137168_) {
return p_137167_ ? (p_288391_) -> {
int i = p_137168_.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 = p_137168_.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 p_137146_, NbtPathArgument.NbtPath p_137147_) throws CommandSyntaxException {
return p_137147_.countMatching(p_137146_.getData());
}
private static boolean checkScore(CommandContext<CommandSourceStack> p_137065_, BiPredicate<Integer, Integer> p_137066_) throws CommandSyntaxException {
String s = ScoreHolderArgument.getName(p_137065_, "target");
Objective objective = ObjectiveArgument.getObjective(p_137065_, "targetObjective");
String s1 = ScoreHolderArgument.getName(p_137065_, "source");
Objective objective1 = ObjectiveArgument.getObjective(p_137065_, "sourceObjective");
Scoreboard scoreboard = p_137065_.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 p_137066_.test(score.getScore(), score1.getScore());
} else {
return false;
}
}
private static boolean checkScore(CommandContext<CommandSourceStack> p_137059_, MinMaxBounds.Ints p_137060_) throws CommandSyntaxException {
String s = ScoreHolderArgument.getName(p_137059_, "target");
Objective objective = ObjectiveArgument.getObjective(p_137059_, "targetObjective");
Scoreboard scoreboard = p_137059_.getSource().getServer().getScoreboard();
return !scoreboard.hasPlayerScore(s, objective) ? false : p_137060_.matches(scoreboard.getOrCreatePlayerScore(s, objective).getScore());
}
private static boolean checkCustomPredicate(CommandSourceStack p_137105_, LootItemCondition p_137106_) {
ServerLevel serverlevel = p_137105_.getLevel();
LootParams lootparams = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, p_137105_.getPosition()).withOptionalParameter(LootContextParams.THIS_ENTITY, p_137105_.getEntity()).create(LootContextParamSets.COMMAND);
LootContext lootcontext = (new LootContext.Builder(lootparams)).create((ResourceLocation)null);
lootcontext.pushVisitedElement(LootContext.createVisitedEntry(p_137106_));
return p_137106_.test(lootcontext);
}
private static Collection<CommandSourceStack> expect(CommandContext<CommandSourceStack> p_137071_, boolean p_137072_, boolean p_137073_) {
return (Collection<CommandSourceStack>)(p_137073_ == p_137072_ ? Collections.singleton(p_137071_.getSource()) : Collections.emptyList());
}
private static ArgumentBuilder<CommandSourceStack, ?> addConditional(CommandNode<CommandSourceStack> p_137075_, ArgumentBuilder<CommandSourceStack, ?> p_137076_, boolean p_137077_, ExecuteCommand.CommandPredicate p_137078_) {
return p_137076_.fork(p_137075_, (p_137214_) -> {
return expect(p_137214_, p_137077_, p_137078_.test(p_137214_));
}).executes((p_288396_) -> {
if (p_137077_ == p_137078_.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> p_137080_, ArgumentBuilder<CommandSourceStack, ?> p_137081_, boolean p_137082_, boolean p_137083_) {
return p_137081_.fork(p_137080_, (p_137180_) -> {
return expect(p_137180_, p_137082_, checkRegions(p_137180_, p_137083_).isPresent());
}).executes(p_137082_ ? (p_137210_) -> {
return checkIfRegions(p_137210_, p_137083_);
} : (p_137165_) -> {
return checkUnlessRegions(p_137165_, p_137083_);
});
}
private static int checkIfRegions(CommandContext<CommandSourceStack> p_137068_, boolean p_137069_) throws CommandSyntaxException {
OptionalInt optionalint = checkRegions(p_137068_, p_137069_);
if (optionalint.isPresent()) {
p_137068_.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> p_137194_, boolean p_137195_) throws CommandSyntaxException {
OptionalInt optionalint = checkRegions(p_137194_, p_137195_);
if (optionalint.isPresent()) {
throw ERROR_CONDITIONAL_FAILED_COUNT.create(optionalint.getAsInt());
} else {
p_137194_.getSource().sendSuccess(() -> {
return Component.translatable("commands.execute.conditional.pass");
}, false);
return 1;
}
}
private static OptionalInt checkRegions(CommandContext<CommandSourceStack> p_137221_, boolean p_137222_) throws CommandSyntaxException {
return checkRegions(p_137221_.getSource().getLevel(), BlockPosArgument.getLoadedBlockPos(p_137221_, "start"), BlockPosArgument.getLoadedBlockPos(p_137221_, "end"), BlockPosArgument.getLoadedBlockPos(p_137221_, "destination"), p_137222_);
}
private static OptionalInt checkRegions(ServerLevel p_137037_, BlockPos p_137038_, BlockPos p_137039_, BlockPos p_137040_, boolean p_137041_) throws CommandSyntaxException {
BoundingBox boundingbox = BoundingBox.fromCorners(p_137038_, p_137039_);
BoundingBox boundingbox1 = BoundingBox.fromCorners(p_137040_, p_137040_.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 = p_137037_.getBlockState(blockpos1);
if (!p_137041_ || !blockstate.is(Blocks.AIR)) {
if (blockstate != p_137037_.getBlockState(blockpos2)) {
return OptionalInt.empty();
}
BlockEntity blockentity = p_137037_.getBlockEntity(blockpos1);
BlockEntity blockentity1 = p_137037_.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>> p_265114_) {
return (p_264786_) -> {
CommandSourceStack commandsourcestack = p_264786_.getSource();
Entity entity = commandsourcestack.getEntity();
return (Collection<CommandSourceStack>)(entity == null ? List.of() : p_265114_.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>> p_265496_) {
return (p_264780_) -> {
CommandSourceStack commandsourcestack = p_264780_.getSource();
Entity entity = commandsourcestack.getEntity();
return entity == null ? List.of() : p_265496_.apply(entity).filter((p_264784_) -> {
return !p_264784_.isRemoved();
}).map(commandsourcestack::withEntity).toList();
};
}
private static LiteralArgumentBuilder<CommandSourceStack> createRelationOperations(CommandNode<CommandSourceStack> p_265189_, LiteralArgumentBuilder<CommandSourceStack> p_265783_) {
return (LiteralArgumentBuilder<CommandSourceStack>)p_265783_.then(Commands.literal("owner").fork(p_265189_, 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(p_265189_, 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(p_265189_, 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(p_265189_, 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(p_265189_, expandOneToOneEntityRelation((p_264776_) -> {
return Optional.ofNullable(p_264776_.getVehicle());
}))).then(Commands.literal("controller").fork(p_265189_, expandOneToOneEntityRelation((p_274815_) -> {
return Optional.ofNullable(p_274815_.getControllingPassenger());
}))).then(Commands.literal("origin").fork(p_265189_, 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(p_265189_, 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> p_137301_) throws CommandSyntaxException;
}
@FunctionalInterface
interface CommandPredicate {
boolean test(CommandContext<CommandSourceStack> p_137303_) throws CommandSyntaxException;
}
}

View File

@@ -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> p_137307_) {
LiteralCommandNode<CommandSourceStack> literalcommandnode = p_137307_.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);
})))));
p_137307_.register(Commands.literal("xp").requires((p_137311_) -> {
return p_137311_.hasPermission(2);
}).redirect(literalcommandnode));
}
private static int queryExperience(CommandSourceStack p_137313_, ServerPlayer p_137314_, ExperienceCommand.Type p_137315_) {
int i = p_137315_.query.applyAsInt(p_137314_);
p_137313_.sendSuccess(() -> {
return Component.translatable("commands.experience.query." + p_137315_.name, p_137314_.getDisplayName(), i);
}, false);
return i;
}
private static int addExperience(CommandSourceStack p_137317_, Collection<? extends ServerPlayer> p_137318_, int p_137319_, ExperienceCommand.Type p_137320_) {
for(ServerPlayer serverplayer : p_137318_) {
p_137320_.add.accept(serverplayer, p_137319_);
}
if (p_137318_.size() == 1) {
p_137317_.sendSuccess(() -> {
return Component.translatable("commands.experience.add." + p_137320_.name + ".success.single", p_137319_, p_137318_.iterator().next().getDisplayName());
}, true);
} else {
p_137317_.sendSuccess(() -> {
return Component.translatable("commands.experience.add." + p_137320_.name + ".success.multiple", p_137319_, p_137318_.size());
}, true);
}
return p_137318_.size();
}
private static int setExperience(CommandSourceStack p_137326_, Collection<? extends ServerPlayer> p_137327_, int p_137328_, ExperienceCommand.Type p_137329_) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : p_137327_) {
if (p_137329_.set.test(serverplayer, p_137328_)) {
++i;
}
}
if (i == 0) {
throw ERROR_SET_POINTS_INVALID.create();
} else {
if (p_137327_.size() == 1) {
p_137326_.sendSuccess(() -> {
return Component.translatable("commands.experience.set." + p_137329_.name + ".success.single", p_137328_, p_137327_.iterator().next().getDisplayName());
}, true);
} else {
p_137326_.sendSuccess(() -> {
return Component.translatable("commands.experience.set." + p_137329_.name + ".success.multiple", p_137328_, p_137327_.size());
}, true);
}
return p_137327_.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 p_137353_, BiConsumer<ServerPlayer, Integer> p_137354_, BiPredicate<ServerPlayer, Integer> p_137355_, ToIntFunction<ServerPlayer> p_137356_) {
this.add = p_137354_;
this.name = p_137353_;
this.set = p_137355_;
this.query = p_137356_;
}
}
}

View File

@@ -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> p_261867_, CommandBuildContext p_262155_) {
p_261867_.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(p_262155_, 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(p_262155_, 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 p_261998_) {
return QuartPos.toBlock(QuartPos.fromBlock(p_261998_));
}
private static BlockPos quantize(BlockPos p_262148_) {
return new BlockPos(quantize(p_262148_.getX()), quantize(p_262148_.getY()), quantize(p_262148_.getZ()));
}
private static BiomeResolver makeResolver(MutableInt p_262615_, ChunkAccess p_262698_, BoundingBox p_262622_, Holder<Biome> p_262705_, Predicate<Holder<Biome>> p_262695_) {
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 = p_262698_.getNoiseBiome(p_262550_, p_262551_, p_262552_);
if (p_262622_.isInside(i, j, k) && p_262695_.test(holder)) {
p_262615_.increment();
return p_262705_;
} else {
return holder;
}
};
}
private static int fill(CommandSourceStack p_262664_, BlockPos p_262651_, BlockPos p_262678_, Holder.Reference<Biome> p_262612_, Predicate<Holder<Biome>> p_262697_) throws CommandSyntaxException {
BlockPos blockpos = quantize(p_262651_);
BlockPos blockpos1 = quantize(p_262678_);
BoundingBox boundingbox = BoundingBox.fromCorners(blockpos, blockpos1);
int i = boundingbox.getXSpan() * boundingbox.getYSpan() * boundingbox.getZSpan();
int j = p_262664_.getLevel().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT);
if (i > j) {
throw ERROR_VOLUME_TOO_LARGE.create(j, i);
} else {
ServerLevel serverlevel = p_262664_.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, p_262612_, p_262697_), serverlevel.getChunkSource().randomState().sampler());
chunkaccess1.setUnsaved(true);
}
serverlevel.getChunkSource().chunkMap.resendBiomesForChunks(list);
p_262664_.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();
}
}
}

View File

@@ -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> p_214443_, CommandBuildContext p_214444_) {
p_214443_.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(p_214444_)).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(p_214444_)).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 p_137386_, BoundingBox p_137387_, BlockInput p_137388_, FillCommand.Mode p_137389_, @Nullable Predicate<BlockInWorld> p_137390_) throws CommandSyntaxException {
int i = p_137387_.getXSpan() * p_137387_.getYSpan() * p_137387_.getZSpan();
int j = p_137386_.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 = p_137386_.getLevel();
int k = 0;
for(BlockPos blockpos : BlockPos.betweenClosed(p_137387_.minX(), p_137387_.minY(), p_137387_.minZ(), p_137387_.maxX(), p_137387_.maxY(), p_137387_.maxZ())) {
if (p_137390_ == null || p_137390_.test(new BlockInWorld(serverlevel, blockpos, true))) {
BlockInput blockinput = p_137389_.filter.filter(p_137387_, blockpos, p_137388_, 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;
p_137386_.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 p_137416_) {
this.filter = p_137416_;
}
}
}

View File

@@ -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> p_137677_) {
p_137677_.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 p_137683_, ColumnPos p_137684_) throws CommandSyntaxException {
ChunkPos chunkpos = p_137684_.toChunkPos();
ServerLevel serverlevel = p_137683_.getLevel();
ResourceKey<Level> resourcekey = serverlevel.dimension();
boolean flag = serverlevel.getForcedChunks().contains(chunkpos.toLong());
if (flag) {
p_137683_.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 p_137681_) {
ServerLevel serverlevel = p_137681_.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) {
p_137681_.sendSuccess(() -> {
return Component.translatable("commands.forceload.list.single", resourcekey.location(), s);
}, false);
} else {
p_137681_.sendSuccess(() -> {
return Component.translatable("commands.forceload.list.multiple", i, resourcekey.location(), s);
}, false);
}
} else {
p_137681_.sendFailure(Component.translatable("commands.forceload.added.none", resourcekey.location()));
}
return i;
}
private static int removeAll(CommandSourceStack p_137696_) {
ServerLevel serverlevel = p_137696_.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);
});
p_137696_.sendSuccess(() -> {
return Component.translatable("commands.forceload.removed.all", resourcekey.location());
}, true);
return 0;
}
private static int changeForceLoad(CommandSourceStack p_137686_, ColumnPos p_137687_, ColumnPos p_137688_, boolean p_137689_) throws CommandSyntaxException {
int i = Math.min(p_137687_.x(), p_137688_.x());
int j = Math.min(p_137687_.z(), p_137688_.z());
int k = Math.max(p_137687_.x(), p_137688_.x());
int l = Math.max(p_137687_.z(), p_137688_.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 = p_137686_.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, p_137689_);
if (flag) {
++j2;
if (chunkpos == null) {
chunkpos = new ChunkPos(k2, l2);
}
}
}
}
ChunkPos chunkpos1 = chunkpos;
if (j2 == 0) {
throw (p_137689_ ? ERROR_ALL_ADDED : ERROR_NONE_REMOVED).create();
} else {
if (j2 == 1) {
p_137686_.sendSuccess(() -> {
return Component.translatable("commands.forceload." + (p_137689_ ? "added" : "removed") + ".single", chunkpos1, resourcekey.location());
}, true);
} else {
ChunkPos chunkpos2 = new ChunkPos(i1, j1);
ChunkPos chunkpos3 = new ChunkPos(k1, l1);
p_137686_.sendSuccess(() -> {
return Component.translatable("commands.forceload." + (p_137689_ ? "added" : "removed") + ".multiple", chunkpos1, resourcekey.location(), chunkpos2, chunkpos3);
}, true);
}
return j2;
}
}
} else {
throw BlockPosArgument.ERROR_OUT_OF_WORLD.create();
}
}
}

View File

@@ -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> p_137715_) {
p_137715_.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 p_137724_, Collection<CommandFunction> p_137725_) {
int i = 0;
boolean flag = false;
for(CommandFunction commandfunction : p_137725_) {
MutableObject<OptionalInt> mutableobject = new MutableObject<>(OptionalInt.empty());
int j = p_137724_.getServer().getFunctions().execute(commandfunction, p_137724_.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 (p_137725_.size() == 1) {
if (flag) {
p_137724_.sendSuccess(() -> {
return Component.translatable("commands.function.success.single.result", k, p_137725_.iterator().next().getId());
}, true);
} else {
p_137724_.sendSuccess(() -> {
return Component.translatable("commands.function.success.single", k, p_137725_.iterator().next().getId());
}, true);
}
} else if (flag) {
p_137724_.sendSuccess(() -> {
return Component.translatable("commands.function.success.multiple.result", p_137725_.size());
}, true);
} else {
p_137724_.sendSuccess(() -> {
return Component.translatable("commands.function.success.multiple", k, p_137725_.size());
}, true);
}
return i;
}
}

View File

@@ -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> p_137730_) {
p_137730_.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 p_137738_, ServerPlayer p_137739_, GameType p_137740_) {
Component component = Component.translatable("gameMode." + p_137740_.getName());
if (p_137738_.getEntity() == p_137739_) {
p_137738_.sendSuccess(() -> {
return Component.translatable("commands.gamemode.success.self", component);
}, true);
} else {
if (p_137738_.getLevel().getGameRules().getBoolean(GameRules.RULE_SENDCOMMANDFEEDBACK)) {
p_137739_.sendSystemMessage(Component.translatable("gameMode.changed", component));
}
p_137738_.sendSuccess(() -> {
return Component.translatable("commands.gamemode.success.other", p_137739_.getDisplayName(), component);
}, true);
}
}
private static int setMode(CommandContext<CommandSourceStack> p_137732_, Collection<ServerPlayer> p_137733_, GameType p_137734_) {
int i = 0;
for(ServerPlayer serverplayer : p_137733_) {
if (serverplayer.setGameMode(p_137734_)) {
logGamemodeChange(p_137732_.getSource(), serverplayer, p_137734_);
++i;
}
}
return i;
}
}

View File

@@ -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> p_137745_) {
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_);
})));
}
});
p_137745_.register(literalargumentbuilder);
}
static <T extends GameRules.Value<T>> int setRule(CommandContext<CommandSourceStack> p_137755_, GameRules.Key<T> p_137756_) {
CommandSourceStack commandsourcestack = p_137755_.getSource();
T t = commandsourcestack.getServer().getGameRules().getRule(p_137756_);
t.setFromArgument(p_137755_, "value");
commandsourcestack.sendSuccess(() -> {
return Component.translatable("commands.gamerule.set", p_137756_.getId(), t.toString());
}, true);
return t.getCommandResult();
}
static <T extends GameRules.Value<T>> int queryRule(CommandSourceStack p_137758_, GameRules.Key<T> p_137759_) {
T t = p_137758_.getServer().getGameRules().getRule(p_137759_);
p_137758_.sendSuccess(() -> {
return Component.translatable("commands.gamerule.query", p_137759_.getId(), t.toString());
}, false);
return t.getCommandResult();
}
}

View File

@@ -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> p_214446_, CommandBuildContext p_214447_) {
p_214446_.register(Commands.literal("give").requires((p_137777_) -> {
return p_137777_.hasPermission(2);
}).then(Commands.argument("targets", EntityArgument.players()).then(Commands.argument("item", ItemArgument.item(p_214447_)).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 p_137779_, ItemInput p_137780_, Collection<ServerPlayer> p_137781_, int p_137782_) throws CommandSyntaxException {
int i = p_137780_.getItem().getMaxStackSize();
int j = i * 100;
ItemStack itemstack = p_137780_.createItemStack(p_137782_, false);
if (p_137782_ > j) {
p_137779_.sendFailure(Component.translatable("commands.give.failed.toomanyitems", j, itemstack.getDisplayName()));
return 0;
} else {
for(ServerPlayer serverplayer : p_137781_) {
int k = p_137782_;
while(k > 0) {
int l = Math.min(i, k);
k -= l;
ItemStack itemstack1 = p_137780_.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 (p_137781_.size() == 1) {
p_137779_.sendSuccess(() -> {
return Component.translatable("commands.give.success.single", p_137782_, itemstack.getDisplayName(), p_137781_.iterator().next().getDisplayName());
}, true);
} else {
p_137779_.sendSuccess(() -> {
return Component.translatable("commands.give.success.single", p_137782_, itemstack.getDisplayName(), p_137781_.size());
}, true);
}
return p_137781_.size();
}
}
}

View File

@@ -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> p_137788_) {
p_137788_.register(Commands.literal("help").executes((p_288460_) -> {
Map<CommandNode<CommandSourceStack>, String> map = p_137788_.getSmartUsage(p_137788_.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 = p_137788_.parse(StringArgumentType.getString(p_288458_, "command"), p_288458_.getSource());
if (parseresults.getContext().getNodes().isEmpty()) {
throw ERROR_FAILED.create();
} else {
Map<CommandNode<CommandSourceStack>, String> map = p_137788_.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();
}
})));
}
}

View File

@@ -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> p_214449_, CommandBuildContext p_214450_) {
p_214449_.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(p_214450_)).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(p_214450_)).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 p_180297_, BlockPos p_180298_, int p_180299_, LootItemFunction p_180300_) throws CommandSyntaxException {
Container container = getContainer(p_180297_, p_180298_, ERROR_TARGET_NOT_A_CONTAINER);
if (p_180299_ >= 0 && p_180299_ < container.getContainerSize()) {
ItemStack itemstack = applyModifier(p_180297_, p_180300_, container.getItem(p_180299_));
container.setItem(p_180299_, itemstack);
p_180297_.sendSuccess(() -> {
return Component.translatable("commands.item.block.set.success", p_180298_.getX(), p_180298_.getY(), p_180298_.getZ(), itemstack.getDisplayName());
}, true);
return 1;
} else {
throw ERROR_TARGET_INAPPLICABLE_SLOT.create(p_180299_);
}
}
private static int modifyEntityItem(CommandSourceStack p_180337_, Collection<? extends Entity> p_180338_, int p_180339_, LootItemFunction p_180340_) throws CommandSyntaxException {
Map<Entity, ItemStack> map = Maps.newHashMapWithExpectedSize(p_180338_.size());
for(Entity entity : p_180338_) {
SlotAccess slotaccess = entity.getSlot(p_180339_);
if (slotaccess != SlotAccess.NULL) {
ItemStack itemstack = applyModifier(p_180337_, p_180340_, 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(p_180339_);
} else {
if (map.size() == 1) {
Map.Entry<Entity, ItemStack> entry = map.entrySet().iterator().next();
p_180337_.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.single", entry.getKey().getDisplayName(), entry.getValue().getDisplayName());
}, true);
} else {
p_180337_.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.multiple", map.size());
}, true);
}
return map.size();
}
}
private static int setBlockItem(CommandSourceStack p_180292_, BlockPos p_180293_, int p_180294_, ItemStack p_180295_) throws CommandSyntaxException {
Container container = getContainer(p_180292_, p_180293_, ERROR_TARGET_NOT_A_CONTAINER);
if (p_180294_ >= 0 && p_180294_ < container.getContainerSize()) {
container.setItem(p_180294_, p_180295_);
p_180292_.sendSuccess(() -> {
return Component.translatable("commands.item.block.set.success", p_180293_.getX(), p_180293_.getY(), p_180293_.getZ(), p_180295_.getDisplayName());
}, true);
return 1;
} else {
throw ERROR_TARGET_INAPPLICABLE_SLOT.create(p_180294_);
}
}
private static Container getContainer(CommandSourceStack p_180328_, BlockPos p_180329_, Dynamic3CommandExceptionType p_180330_) throws CommandSyntaxException {
BlockEntity blockentity = p_180328_.getLevel().getBlockEntity(p_180329_);
if (!(blockentity instanceof Container)) {
throw p_180330_.create(p_180329_.getX(), p_180329_.getY(), p_180329_.getZ());
} else {
return (Container)blockentity;
}
}
private static int setEntityItem(CommandSourceStack p_180332_, Collection<? extends Entity> p_180333_, int p_180334_, ItemStack p_180335_) throws CommandSyntaxException {
List<Entity> list = Lists.newArrayListWithCapacity(p_180333_.size());
for(Entity entity : p_180333_) {
SlotAccess slotaccess = entity.getSlot(p_180334_);
if (slotaccess != SlotAccess.NULL && slotaccess.set(p_180335_.copy())) {
list.add(entity);
if (entity instanceof ServerPlayer) {
((ServerPlayer)entity).containerMenu.broadcastChanges();
}
}
}
if (list.isEmpty()) {
throw ERROR_TARGET_NO_CHANGES_KNOWN_ITEM.create(p_180335_.getDisplayName(), p_180334_);
} else {
if (list.size() == 1) {
p_180332_.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.single", list.iterator().next().getDisplayName(), p_180335_.getDisplayName());
}, true);
} else {
p_180332_.sendSuccess(() -> {
return Component.translatable("commands.item.entity.set.success.multiple", list.size(), p_180335_.getDisplayName());
}, true);
}
return list.size();
}
}
private static int blockToEntities(CommandSourceStack p_180315_, BlockPos p_180316_, int p_180317_, Collection<? extends Entity> p_180318_, int p_180319_) throws CommandSyntaxException {
return setEntityItem(p_180315_, p_180318_, p_180319_, getBlockItem(p_180315_, p_180316_, p_180317_));
}
private static int blockToEntities(CommandSourceStack p_180321_, BlockPos p_180322_, int p_180323_, Collection<? extends Entity> p_180324_, int p_180325_, LootItemFunction p_180326_) throws CommandSyntaxException {
return setEntityItem(p_180321_, p_180324_, p_180325_, applyModifier(p_180321_, p_180326_, getBlockItem(p_180321_, p_180322_, p_180323_)));
}
private static int blockToBlock(CommandSourceStack p_180302_, BlockPos p_180303_, int p_180304_, BlockPos p_180305_, int p_180306_) throws CommandSyntaxException {
return setBlockItem(p_180302_, p_180305_, p_180306_, getBlockItem(p_180302_, p_180303_, p_180304_));
}
private static int blockToBlock(CommandSourceStack p_180308_, BlockPos p_180309_, int p_180310_, BlockPos p_180311_, int p_180312_, LootItemFunction p_180313_) throws CommandSyntaxException {
return setBlockItem(p_180308_, p_180311_, p_180312_, applyModifier(p_180308_, p_180313_, getBlockItem(p_180308_, p_180309_, p_180310_)));
}
private static int entityToBlock(CommandSourceStack p_180258_, Entity p_180259_, int p_180260_, BlockPos p_180261_, int p_180262_) throws CommandSyntaxException {
return setBlockItem(p_180258_, p_180261_, p_180262_, getEntityItem(p_180259_, p_180260_));
}
private static int entityToBlock(CommandSourceStack p_180264_, Entity p_180265_, int p_180266_, BlockPos p_180267_, int p_180268_, LootItemFunction p_180269_) throws CommandSyntaxException {
return setBlockItem(p_180264_, p_180267_, p_180268_, applyModifier(p_180264_, p_180269_, getEntityItem(p_180265_, p_180266_)));
}
private static int entityToEntities(CommandSourceStack p_180271_, Entity p_180272_, int p_180273_, Collection<? extends Entity> p_180274_, int p_180275_) throws CommandSyntaxException {
return setEntityItem(p_180271_, p_180274_, p_180275_, getEntityItem(p_180272_, p_180273_));
}
private static int entityToEntities(CommandSourceStack p_180277_, Entity p_180278_, int p_180279_, Collection<? extends Entity> p_180280_, int p_180281_, LootItemFunction p_180282_) throws CommandSyntaxException {
return setEntityItem(p_180277_, p_180280_, p_180281_, applyModifier(p_180277_, p_180282_, getEntityItem(p_180278_, p_180279_)));
}
private static ItemStack applyModifier(CommandSourceStack p_180284_, LootItemFunction p_180285_, ItemStack p_180286_) {
ServerLevel serverlevel = p_180284_.getLevel();
LootParams lootparams = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, p_180284_.getPosition()).withOptionalParameter(LootContextParams.THIS_ENTITY, p_180284_.getEntity()).create(LootContextParamSets.COMMAND);
LootContext lootcontext = (new LootContext.Builder(lootparams)).create((ResourceLocation)null);
lootcontext.pushVisitedElement(LootContext.createVisitedEntry(p_180285_));
return p_180285_.apply(p_180286_, lootcontext);
}
private static ItemStack getEntityItem(Entity p_180246_, int p_180247_) throws CommandSyntaxException {
SlotAccess slotaccess = p_180246_.getSlot(p_180247_);
if (slotaccess == SlotAccess.NULL) {
throw ERROR_SOURCE_INAPPLICABLE_SLOT.create(p_180247_);
} else {
return slotaccess.get().copy();
}
}
private static ItemStack getBlockItem(CommandSourceStack p_180288_, BlockPos p_180289_, int p_180290_) throws CommandSyntaxException {
Container container = getContainer(p_180288_, p_180289_, ERROR_SOURCE_NOT_A_CONTAINER);
if (p_180290_ >= 0 && p_180290_ < container.getContainerSize()) {
return container.getItem(p_180290_).copy();
} else {
throw ERROR_SOURCE_INAPPLICABLE_SLOT.create(p_180290_);
}
}
}

View File

@@ -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> p_183646_) {
p_183646_.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 p_183650_) throws CommandSyntaxException {
Environment environment = Environment.from(p_183650_.getServer());
if (!JvmProfiler.INSTANCE.start(environment)) {
throw START_FAILED.create();
} else {
p_183650_.sendSuccess(() -> {
return Component.translatable("commands.jfr.started");
}, false);
return 1;
}
}
private static int stopJfr(CommandSourceStack p_183659_) throws CommandSyntaxException {
try {
Path path = Paths.get(".").relativize(JvmProfiler.INSTANCE.stop().normalize());
Path path1 = p_183659_.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")));
});
p_183659_.sendSuccess(() -> {
return Component.translatable("commands.jfr.stopped", component);
}, false);
return 1;
} catch (Throwable throwable) {
throw DUMP_FAILED.create(throwable.getMessage());
}
}
}

View File

@@ -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> p_137796_) {
p_137796_.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 p_137802_, Collection<ServerPlayer> p_137803_, Component p_137804_) {
for(ServerPlayer serverplayer : p_137803_) {
serverplayer.connection.disconnect(p_137804_);
p_137802_.sendSuccess(() -> {
return Component.translatable("commands.kick.success", serverplayer.getDisplayName(), p_137804_);
}, true);
}
return p_137803_.size();
}
}

View File

@@ -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> p_137808_) {
p_137808_.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 p_137814_, Collection<? extends Entity> p_137815_) {
for(Entity entity : p_137815_) {
entity.kill();
}
if (p_137815_.size() == 1) {
p_137814_.sendSuccess(() -> {
return Component.translatable("commands.kill.success.single", p_137815_.iterator().next().getDisplayName());
}, true);
} else {
p_137814_.sendSuccess(() -> {
return Component.translatable("commands.kill.success.multiple", p_137815_.size());
}, true);
}
return p_137815_.size();
}
}

View File

@@ -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> p_137821_) {
p_137821_.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 p_137825_) {
return format(p_137825_, Player::getDisplayName);
}
private static int listPlayersWithUuids(CommandSourceStack p_137832_) {
return format(p_137832_, (p_289283_) -> {
return Component.translatable("commands.list.nameAndId", p_289283_.getName(), p_289283_.getGameProfile().getId());
});
}
private static int format(CommandSourceStack p_137827_, Function<ServerPlayer, Component> p_137828_) {
PlayerList playerlist = p_137827_.getServer().getPlayerList();
List<ServerPlayer> list = playerlist.getPlayers();
Component component = ComponentUtils.formatList(list, p_137828_);
p_137827_.sendSuccess(() -> {
return Component.translatable("commands.list.players", list.size(), playerlist.getMaxPlayers(), component);
}, false);
return list.size();
}
}

View File

@@ -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> p_249870_, CommandBuildContext p_248936_) {
p_249870_.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(p_248936_, 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(p_248936_, 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> p_251212_, Registry<Structure> p_249691_) {
return p_251212_.unwrap().map((p_258231_) -> {
return p_249691_.getHolder(p_258231_).map((p_214491_) -> {
return HolderSet.direct(p_214491_);
});
}, p_249691_::getTag);
}
private static int locateStructure(CommandSourceStack p_214472_, ResourceOrTagKeyArgument.Result<Structure> p_249893_) throws CommandSyntaxException {
Registry<Structure> registry = p_214472_.getLevel().registryAccess().registryOrThrow(Registries.STRUCTURE);
HolderSet<Structure> holderset = getHolders(p_249893_, registry).orElseThrow(() -> {
return ERROR_STRUCTURE_INVALID.create(p_249893_.asPrintable());
});
BlockPos blockpos = BlockPos.containing(p_214472_.getPosition());
ServerLevel serverlevel = p_214472_.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(p_249893_.asPrintable());
} else {
return showLocateResult(p_214472_, p_249893_, blockpos, pair, "commands.locate.structure.success", false, stopwatch.elapsed());
}
}
private static int locateBiome(CommandSourceStack p_252062_, ResourceOrTagArgument.Result<Biome> p_249756_) throws CommandSyntaxException {
BlockPos blockpos = BlockPos.containing(p_252062_.getPosition());
Stopwatch stopwatch = Stopwatch.createStarted(Util.TICKER);
Pair<BlockPos, Holder<Biome>> pair = p_252062_.getLevel().findClosestBiome3d(p_249756_, blockpos, 6400, 32, 64);
stopwatch.stop();
if (pair == null) {
throw ERROR_BIOME_NOT_FOUND.create(p_249756_.asPrintable());
} else {
return showLocateResult(p_252062_, p_249756_, blockpos, pair, "commands.locate.biome.success", true, stopwatch.elapsed());
}
}
private static int locatePoi(CommandSourceStack p_252013_, ResourceOrTagArgument.Result<PoiType> p_249480_) throws CommandSyntaxException {
BlockPos blockpos = BlockPos.containing(p_252013_.getPosition());
ServerLevel serverlevel = p_252013_.getLevel();
Stopwatch stopwatch = Stopwatch.createStarted(Util.TICKER);
Optional<Pair<Holder<PoiType>, BlockPos>> optional = serverlevel.getPoiManager().findClosestWithType(p_249480_, blockpos, 256, PoiManager.Occupancy.ANY);
stopwatch.stop();
if (optional.isEmpty()) {
throw ERROR_POI_NOT_FOUND.create(p_249480_.asPrintable());
} else {
return showLocateResult(p_252013_, p_249480_, blockpos, optional.get().swap(), "commands.locate.poi.success", false, stopwatch.elapsed());
}
}
private static String getElementName(Pair<BlockPos, ? extends Holder<?>> p_249526_) {
return p_249526_.getSecond().unwrapKey().map((p_214498_) -> {
return p_214498_.location().toString();
}).orElse("[unregistered]");
}
public static int showLocateResult(CommandSourceStack p_263098_, ResourceOrTagArgument.Result<?> p_262956_, BlockPos p_262917_, Pair<BlockPos, ? extends Holder<?>> p_263074_, String p_262937_, boolean p_263051_, Duration p_263028_) {
String s = p_262956_.unwrap().map((p_248147_) -> {
return p_262956_.asPrintable();
}, (p_248143_) -> {
return p_262956_.asPrintable() + " (" + getElementName(p_263074_) + ")";
});
return showLocateResult(p_263098_, p_262917_, p_263074_, p_262937_, p_263051_, s, p_263028_);
}
public static int showLocateResult(CommandSourceStack p_263019_, ResourceOrTagKeyArgument.Result<?> p_263031_, BlockPos p_262989_, Pair<BlockPos, ? extends Holder<?>> p_262959_, String p_263045_, boolean p_262934_, Duration p_262960_) {
String s = p_263031_.unwrap().map((p_214463_) -> {
return p_214463_.location().toString();
}, (p_248145_) -> {
return "#" + p_248145_.location() + " (" + getElementName(p_262959_) + ")";
});
return showLocateResult(p_263019_, p_262989_, p_262959_, p_263045_, p_262934_, s, p_262960_);
}
private static int showLocateResult(CommandSourceStack p_262983_, BlockPos p_263016_, Pair<BlockPos, ? extends Holder<?>> p_262941_, String p_263083_, boolean p_263010_, String p_263048_, Duration p_263040_) {
BlockPos blockpos = p_262941_.getFirst();
int i = p_263010_ ? Mth.floor(Mth.sqrt((float)p_263016_.distSqr(blockpos))) : Mth.floor(dist(p_263016_.getX(), p_263016_.getZ(), blockpos.getX(), blockpos.getZ()));
String s = p_263010_ ? 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")));
});
p_262983_.sendSuccess(() -> {
return Component.translatable(p_263083_, p_263048_, component, i);
}, false);
LOGGER.info("Locating element " + p_263048_ + " took " + p_263040_.toMillis() + " ms");
return i;
}
private static float dist(int p_137854_, int p_137855_, int p_137856_, int p_137857_) {
int i = p_137856_ - p_137854_;
int j = p_137857_ - p_137855_;
return Mth.sqrt((float)(i * i + j * j));
}
}

View File

@@ -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> p_214516_, CommandBuildContext p_214517_) {
p_214516_.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(p_214517_)).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(p_214517_)).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 p_137951_, BlockPos p_137952_) throws CommandSyntaxException {
BlockEntity blockentity = p_137951_.getLevel().getBlockEntity(p_137952_);
if (!(blockentity instanceof Container)) {
throw ItemCommands.ERROR_TARGET_NOT_A_CONTAINER.create(p_137952_.getX(), p_137952_.getY(), p_137952_.getZ());
} else {
return (Container)blockentity;
}
}
private static int blockDistribute(CommandSourceStack p_137961_, BlockPos p_137962_, List<ItemStack> p_137963_, LootCommand.Callback p_137964_) throws CommandSyntaxException {
Container container = getContainer(p_137961_, p_137962_);
List<ItemStack> list = Lists.newArrayListWithCapacity(p_137963_.size());
for(ItemStack itemstack : p_137963_) {
if (distributeToContainer(container, itemstack.copy())) {
container.setChanged();
list.add(itemstack);
}
}
p_137964_.accept(list);
return list.size();
}
private static boolean distributeToContainer(Container p_137886_, ItemStack p_137887_) {
boolean flag = false;
for(int i = 0; i < p_137886_.getContainerSize() && !p_137887_.isEmpty(); ++i) {
ItemStack itemstack = p_137886_.getItem(i);
if (p_137886_.canPlaceItem(i, p_137887_)) {
if (itemstack.isEmpty()) {
p_137886_.setItem(i, p_137887_);
flag = true;
break;
}
if (canMergeItems(itemstack, p_137887_)) {
int j = p_137887_.getMaxStackSize() - itemstack.getCount();
int k = Math.min(p_137887_.getCount(), j);
p_137887_.shrink(k);
itemstack.grow(k);
flag = true;
}
}
}
return flag;
}
private static int blockReplace(CommandSourceStack p_137954_, BlockPos p_137955_, int p_137956_, int p_137957_, List<ItemStack> p_137958_, LootCommand.Callback p_137959_) throws CommandSyntaxException {
Container container = getContainer(p_137954_, p_137955_);
int i = container.getContainerSize();
if (p_137956_ >= 0 && p_137956_ < i) {
List<ItemStack> list = Lists.newArrayListWithCapacity(p_137958_.size());
for(int j = 0; j < p_137957_; ++j) {
int k = p_137956_ + j;
ItemStack itemstack = j < p_137958_.size() ? p_137958_.get(j) : ItemStack.EMPTY;
if (container.canPlaceItem(k, itemstack)) {
container.setItem(k, itemstack);
list.add(itemstack);
}
}
p_137959_.accept(list);
return list.size();
} else {
throw ItemCommands.ERROR_TARGET_INAPPLICABLE_SLOT.create(p_137956_);
}
}
private static boolean canMergeItems(ItemStack p_137895_, ItemStack p_137896_) {
return p_137895_.getCount() <= p_137895_.getMaxStackSize() && ItemStack.isSameItemSameTags(p_137895_, p_137896_);
}
private static int playerGive(Collection<ServerPlayer> p_137985_, List<ItemStack> p_137986_, LootCommand.Callback p_137987_) throws CommandSyntaxException {
List<ItemStack> list = Lists.newArrayListWithCapacity(p_137986_.size());
for(ItemStack itemstack : p_137986_) {
for(ServerPlayer serverplayer : p_137985_) {
if (serverplayer.getInventory().add(itemstack.copy())) {
list.add(itemstack);
}
}
}
p_137987_.accept(list);
return list.size();
}
private static void setSlots(Entity p_137889_, List<ItemStack> p_137890_, int p_137891_, int p_137892_, List<ItemStack> p_137893_) {
for(int i = 0; i < p_137892_; ++i) {
ItemStack itemstack = i < p_137890_.size() ? p_137890_.get(i) : ItemStack.EMPTY;
SlotAccess slotaccess = p_137889_.getSlot(p_137891_ + i);
if (slotaccess != SlotAccess.NULL && slotaccess.set(itemstack.copy())) {
p_137893_.add(itemstack);
}
}
}
private static int entityReplace(Collection<? extends Entity> p_137979_, int p_137980_, int p_137981_, List<ItemStack> p_137982_, LootCommand.Callback p_137983_) throws CommandSyntaxException {
List<ItemStack> list = Lists.newArrayListWithCapacity(p_137982_.size());
for(Entity entity : p_137979_) {
if (entity instanceof ServerPlayer serverplayer) {
setSlots(entity, p_137982_, p_137980_, p_137981_, list);
serverplayer.containerMenu.broadcastChanges();
} else {
setSlots(entity, p_137982_, p_137980_, p_137981_, list);
}
}
p_137983_.accept(list);
return list.size();
}
private static int dropInWorld(CommandSourceStack p_137946_, Vec3 p_137947_, List<ItemStack> p_137948_, LootCommand.Callback p_137949_) throws CommandSyntaxException {
ServerLevel serverlevel = p_137946_.getLevel();
p_137948_.forEach((p_137884_) -> {
ItemEntity itementity = new ItemEntity(serverlevel, p_137947_.x, p_137947_.y, p_137947_.z, p_137884_.copy());
itementity.setDefaultPickUpDelay();
serverlevel.addFreshEntity(itementity);
});
p_137949_.accept(p_137948_);
return p_137948_.size();
}
private static void callback(CommandSourceStack p_137966_, List<ItemStack> p_137967_) {
if (p_137967_.size() == 1) {
ItemStack itemstack = p_137967_.get(0);
p_137966_.sendSuccess(() -> {
return Component.translatable("commands.drop.success.single", itemstack.getCount(), itemstack.getDisplayName());
}, false);
} else {
p_137966_.sendSuccess(() -> {
return Component.translatable("commands.drop.success.multiple", p_137967_.size());
}, false);
}
}
private static void callback(CommandSourceStack p_137969_, List<ItemStack> p_137970_, ResourceLocation p_137971_) {
if (p_137970_.size() == 1) {
ItemStack itemstack = p_137970_.get(0);
p_137969_.sendSuccess(() -> {
return Component.translatable("commands.drop.success.single_with_table", itemstack.getCount(), itemstack.getDisplayName(), p_137971_);
}, false);
} else {
p_137969_.sendSuccess(() -> {
return Component.translatable("commands.drop.success.multiple_with_table", p_137970_.size(), p_137971_);
}, false);
}
}
private static ItemStack getSourceHandItem(CommandSourceStack p_137939_, EquipmentSlot p_137940_) throws CommandSyntaxException {
Entity entity = p_137939_.getEntityOrException();
if (entity instanceof LivingEntity) {
return ((LivingEntity)entity).getItemBySlot(p_137940_);
} else {
throw ERROR_NO_HELD_ITEMS.create(entity.getDisplayName());
}
}
private static int dropBlockLoot(CommandContext<CommandSourceStack> p_137913_, BlockPos p_137914_, ItemStack p_137915_, LootCommand.DropConsumer p_137916_) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = p_137913_.getSource();
ServerLevel serverlevel = commandsourcestack.getLevel();
BlockState blockstate = serverlevel.getBlockState(p_137914_);
BlockEntity blockentity = serverlevel.getBlockEntity(p_137914_);
LootParams.Builder lootparams$builder = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(p_137914_)).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 p_137916_.accept(p_137913_, list, (p_278915_) -> {
callback(commandsourcestack, p_278915_, blockstate.getBlock().getLootTable());
});
}
private static int dropKillLoot(CommandContext<CommandSourceStack> p_137906_, Entity p_137907_, LootCommand.DropConsumer p_137908_) throws CommandSyntaxException {
if (!(p_137907_ instanceof LivingEntity)) {
throw ERROR_NO_LOOT_TABLE.create(p_137907_.getDisplayName());
} else {
ResourceLocation resourcelocation = ((LivingEntity)p_137907_).getLootTable();
CommandSourceStack commandsourcestack = p_137906_.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, p_137907_.damageSources().magic());
lootparams$builder.withOptionalParameter(LootContextParams.DIRECT_KILLER_ENTITY, entity);
lootparams$builder.withOptionalParameter(LootContextParams.KILLER_ENTITY, entity);
lootparams$builder.withParameter(LootContextParams.THIS_ENTITY, p_137907_);
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 p_137908_.accept(p_137906_, list, (p_137975_) -> {
callback(commandsourcestack, p_137975_, resourcelocation);
});
}
}
private static int dropChestLoot(CommandContext<CommandSourceStack> p_137933_, ResourceLocation p_137934_, LootCommand.DropConsumer p_137935_) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = p_137933_.getSource();
LootParams lootparams = (new LootParams.Builder(commandsourcestack.getLevel())).withOptionalParameter(LootContextParams.THIS_ENTITY, commandsourcestack.getEntity()).withParameter(LootContextParams.ORIGIN, commandsourcestack.getPosition()).create(LootContextParamSets.CHEST);
return drop(p_137933_, p_137934_, lootparams, p_137935_);
}
private static int dropFishingLoot(CommandContext<CommandSourceStack> p_137927_, ResourceLocation p_137928_, BlockPos p_137929_, ItemStack p_137930_, LootCommand.DropConsumer p_137931_) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = p_137927_.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(p_137927_, p_137928_, lootparams, p_137931_);
}
private static int drop(CommandContext<CommandSourceStack> p_287721_, ResourceLocation p_287610_, LootParams p_287728_, LootCommand.DropConsumer p_287770_) throws CommandSyntaxException {
CommandSourceStack commandsourcestack = p_287721_.getSource();
LootTable loottable = commandsourcestack.getServer().getLootData().getLootTable(p_287610_);
List<ItemStack> list = loottable.getRandomItems(p_287728_);
return p_287770_.accept(p_287721_, list, (p_137997_) -> {
callback(commandsourcestack, p_137997_);
});
}
@FunctionalInterface
interface Callback {
void accept(List<ItemStack> p_138048_) throws CommandSyntaxException;
}
@FunctionalInterface
interface DropConsumer {
int accept(CommandContext<CommandSourceStack> p_138050_, List<ItemStack> p_138051_, LootCommand.Callback p_138052_) throws CommandSyntaxException;
}
@FunctionalInterface
interface TailProvider {
ArgumentBuilder<CommandSourceStack, ?> construct(ArgumentBuilder<CommandSourceStack, ?> p_138054_, LootCommand.DropConsumer p_138055_);
}
}

View File

@@ -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> p_138061_) {
LiteralCommandNode<CommandSourceStack> literalcommandnode = p_138061_.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();
}))));
p_138061_.register(Commands.literal("tell").redirect(literalcommandnode));
p_138061_.register(Commands.literal("w").redirect(literalcommandnode));
}
private static void sendMessage(CommandSourceStack p_250209_, Collection<ServerPlayer> p_252344_, PlayerChatMessage p_249416_) {
ChatType.Bound chattype$bound = ChatType.bind(ChatType.MSG_COMMAND_INCOMING, p_250209_);
OutgoingChatMessage outgoingchatmessage = OutgoingChatMessage.create(p_249416_);
boolean flag = false;
for(ServerPlayer serverplayer : p_252344_) {
ChatType.Bound chattype$bound1 = ChatType.bind(ChatType.MSG_COMMAND_OUTGOING, p_250209_).withTargetName(serverplayer.getDisplayName());
p_250209_.sendChatMessage(outgoingchatmessage, false, chattype$bound1);
boolean flag1 = p_250209_.shouldFilterMessageTo(serverplayer);
serverplayer.sendChatMessage(outgoingchatmessage, flag1, chattype$bound);
flag |= flag1 && p_249416_.isFullyFiltered();
}
if (flag) {
p_250209_.sendSystemMessage(PlayerList.CHAT_FILTERED_FULL);
}
}
}

View File

@@ -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> p_138080_) {
p_138080_.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 p_138089_, Collection<GameProfile> p_138090_) throws CommandSyntaxException {
PlayerList playerlist = p_138089_.getServer().getPlayerList();
int i = 0;
for(GameProfile gameprofile : p_138090_) {
if (!playerlist.isOp(gameprofile)) {
playerlist.op(gameprofile);
++i;
p_138089_.sendSuccess(() -> {
return Component.translatable("commands.op.success", p_138090_.iterator().next().getName());
}, true);
}
}
if (i == 0) {
throw ERROR_ALREADY_OP.create();
} else {
return i;
}
}
}

View File

@@ -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> p_138094_) {
p_138094_.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 p_138103_, Collection<GameProfile> p_138104_) throws CommandSyntaxException {
UserBanList userbanlist = p_138103_.getServer().getPlayerList().getBans();
int i = 0;
for(GameProfile gameprofile : p_138104_) {
if (userbanlist.isBanned(gameprofile)) {
userbanlist.remove(gameprofile);
++i;
p_138103_.sendSuccess(() -> {
return Component.translatable("commands.pardon.success", ComponentUtils.getDisplayName(gameprofile));
}, true);
}
}
if (i == 0) {
throw ERROR_NOT_BANNED.create();
} else {
return i;
}
}
}

View File

@@ -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> p_138109_) {
p_138109_.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 p_138118_, String p_138119_) throws CommandSyntaxException {
if (!InetAddresses.isInetAddress(p_138119_)) {
throw ERROR_INVALID.create();
} else {
IpBanList ipbanlist = p_138118_.getServer().getPlayerList().getIpBans();
if (!ipbanlist.isBanned(p_138119_)) {
throw ERROR_NOT_BANNED.create();
} else {
ipbanlist.remove(p_138119_);
p_138118_.sendSuccess(() -> {
return Component.translatable("commands.pardonip.success", p_138119_);
}, true);
return 1;
}
}
}
}

View File

@@ -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> p_138123_, CommandBuildContext p_248587_) {
p_138123_.register(Commands.literal("particle").requires((p_138127_) -> {
return p_138127_.hasPermission(2);
}).then(Commands.argument("name", ParticleArgument.particle(p_248587_)).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 p_138129_, ParticleOptions p_138130_, Vec3 p_138131_, Vec3 p_138132_, float p_138133_, int p_138134_, boolean p_138135_, Collection<ServerPlayer> p_138136_) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : p_138136_) {
if (p_138129_.getLevel().sendParticles(serverplayer, p_138130_, p_138135_, p_138131_.x, p_138131_.y, p_138131_.z, p_138134_, p_138132_.x, p_138132_.y, p_138132_.z, (double)p_138133_)) {
++i;
}
}
if (i == 0) {
throw ERROR_FAILED.create();
} else {
p_138129_.sendSuccess(() -> {
return Component.translatable("commands.particle.success", BuiltInRegistries.PARTICLE_TYPE.getKey(p_138130_.getType()).toString());
}, true);
return i;
}
}
}

View File

@@ -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> p_180438_) {
p_180438_.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 p_180442_) throws CommandSyntaxException {
MinecraftServer minecraftserver = p_180442_.getServer();
if (minecraftserver.isRecordingMetrics()) {
throw ERROR_ALREADY_RUNNING.create();
} else {
Consumer<ProfileResults> consumer = (p_180460_) -> {
whenStopped(p_180442_, p_180460_);
};
Consumer<Path> consumer1 = (p_180453_) -> {
saveResults(p_180442_, p_180453_, minecraftserver);
};
minecraftserver.startRecordingMetrics(consumer, consumer1);
p_180442_.sendSuccess(() -> {
return Component.translatable("commands.perf.started");
}, false);
return 0;
}
}
private static int stopProfilingDedicatedServer(CommandSourceStack p_180457_) throws CommandSyntaxException {
MinecraftServer minecraftserver = p_180457_.getServer();
if (!minecraftserver.isRecordingMetrics()) {
throw ERROR_NOT_RUNNING.create();
} else {
minecraftserver.finishRecordingMetrics();
return 0;
}
}
private static void saveResults(CommandSourceStack p_180447_, Path p_180448_, MinecraftServer p_180449_) {
String s = String.format(Locale.ROOT, "%s-%s-%s", Util.getFilenameFormattedDateTime(), p_180449_.getWorldData().getLevelName(), SharedConstants.getCurrentVersion().getId());
String s1;
try {
s1 = FileUtil.findAvailableName(MetricsPersister.PROFILING_RESULTS_DIR, s, ".zip");
} catch (IOException ioexception1) {
p_180447_.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"), p_180449_.fillSystemReport(new SystemReport()).toLineSeparatedString());
filezipper.add(p_180448_);
}
try {
FileUtils.forceDelete(p_180448_.toFile());
} catch (IOException ioexception) {
LOGGER.warn("Failed to delete temporary profiling file {}", p_180448_, ioexception);
}
p_180447_.sendSuccess(() -> {
return Component.translatable("commands.perf.reportSaved", s1);
}, false);
}
private static void whenStopped(CommandSourceStack p_180444_, ProfileResults p_180445_) {
if (p_180445_ != EmptyProfileResults.EMPTY) {
int i = p_180445_.getTickDuration();
double d0 = (double)p_180445_.getNanoDuration() / (double)TimeUtil.NANOSECONDS_PER_SECOND;
p_180444_.sendSuccess(() -> {
return Component.translatable("commands.perf.stopped", String.format(Locale.ROOT, "%.2f", d0), i, String.format(Locale.ROOT, "%.2f", (double)i / d0));
}, false);
}
}
}

View File

@@ -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> p_214548_) {
p_214548_.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 p_214576_, Holder.Reference<ConfiguredFeature<?, ?>> p_248822_, BlockPos p_214578_) throws CommandSyntaxException {
ServerLevel serverlevel = p_214576_.getLevel();
ConfiguredFeature<?, ?> configuredfeature = p_248822_.value();
ChunkPos chunkpos = new ChunkPos(p_214578_);
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(), p_214578_)) {
throw ERROR_FEATURE_FAILED.create();
} else {
String s = p_248822_.key().location().toString();
p_214576_.sendSuccess(() -> {
return Component.translatable("commands.place.feature.success", s, p_214578_.getX(), p_214578_.getY(), p_214578_.getZ());
}, true);
return 1;
}
}
public static int placeJigsaw(CommandSourceStack p_214570_, Holder<StructureTemplatePool> p_214571_, ResourceLocation p_214572_, int p_214573_, BlockPos p_214574_) throws CommandSyntaxException {
ServerLevel serverlevel = p_214570_.getLevel();
if (!JigsawPlacement.generateJigsaw(serverlevel, p_214571_, p_214572_, p_214573_, p_214574_, false)) {
throw ERROR_JIGSAW_FAILED.create();
} else {
p_214570_.sendSuccess(() -> {
return Component.translatable("commands.place.jigsaw.success", p_214574_.getX(), p_214574_.getY(), p_214574_.getZ());
}, true);
return 1;
}
}
public static int placeStructure(CommandSourceStack p_214588_, Holder.Reference<Structure> p_251799_, BlockPos p_214590_) throws CommandSyntaxException {
ServerLevel serverlevel = p_214588_.getLevel();
Structure structure = p_251799_.value();
ChunkGenerator chunkgenerator = serverlevel.getChunkSource().getGenerator();
StructureStart structurestart = structure.generate(p_214588_.registryAccess(), chunkgenerator, chunkgenerator.getBiomeSource(), serverlevel.getChunkSource().randomState(), serverlevel.getStructureManager(), serverlevel.getSeed(), new ChunkPos(p_214590_), 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 = p_251799_.key().location().toString();
p_214588_.sendSuccess(() -> {
return Component.translatable("commands.place.structure.success", s, p_214590_.getX(), p_214590_.getY(), p_214590_.getZ());
}, true);
return 1;
}
}
public static int placeTemplate(CommandSourceStack p_214562_, ResourceLocation p_214563_, BlockPos p_214564_, Rotation p_214565_, Mirror p_214566_, float p_214567_, int p_214568_) throws CommandSyntaxException {
ServerLevel serverlevel = p_214562_.getLevel();
StructureTemplateManager structuretemplatemanager = serverlevel.getStructureManager();
Optional<StructureTemplate> optional;
try {
optional = structuretemplatemanager.get(p_214563_);
} catch (ResourceLocationException resourcelocationexception) {
throw ERROR_TEMPLATE_INVALID.create(p_214563_);
}
if (optional.isEmpty()) {
throw ERROR_TEMPLATE_INVALID.create(p_214563_);
} else {
StructureTemplate structuretemplate = optional.get();
checkLoaded(serverlevel, new ChunkPos(p_214564_), new ChunkPos(p_214564_.offset(structuretemplate.getSize())));
StructurePlaceSettings structureplacesettings = (new StructurePlaceSettings()).setMirror(p_214566_).setRotation(p_214565_);
if (p_214567_ < 1.0F) {
structureplacesettings.clearProcessors().addProcessor(new BlockRotProcessor(p_214567_)).setRandom(StructureBlockEntity.createRandom((long)p_214568_));
}
boolean flag = structuretemplate.placeInWorld(serverlevel, p_214564_, p_214564_, structureplacesettings, StructureBlockEntity.createRandom((long)p_214568_), 2);
if (!flag) {
throw ERROR_TEMPLATE_FAILED.create();
} else {
p_214562_.sendSuccess(() -> {
return Component.translatable("commands.place.template.success", p_214563_, p_214564_.getX(), p_214564_.getY(), p_214564_.getZ());
}, true);
return 1;
}
}
}
private static void checkLoaded(ServerLevel p_214544_, ChunkPos p_214545_, ChunkPos p_214546_) throws CommandSyntaxException {
if (ChunkPos.rangeClosed(p_214545_, p_214546_).filter((p_214542_) -> {
return !p_214544_.isLoaded(p_214542_.getWorldPosition());
}).findAny().isPresent()) {
throw BlockPosArgument.ERROR_NOT_LOADED.create();
}
}
}

View File

@@ -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> p_138157_) {
RequiredArgumentBuilder<CommandSourceStack, ResourceLocation> requiredargumentbuilder = Commands.argument("sound", ResourceLocationArgument.id()).suggests(SuggestionProviders.AVAILABLE_SOUNDS);
for(SoundSource soundsource : SoundSource.values()) {
requiredargumentbuilder.then(source(soundsource));
}
p_138157_.register(Commands.literal("playsound").requires((p_138159_) -> {
return p_138159_.hasPermission(2);
}).then(requiredargumentbuilder));
}
private static LiteralArgumentBuilder<CommandSourceStack> source(SoundSource p_138152_) {
return Commands.literal(p_138152_.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"), p_138152_, 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"), p_138152_, 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"), p_138152_, 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"), p_138152_, 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"), p_138152_, 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 p_138161_, Collection<ServerPlayer> p_138162_, ResourceLocation p_138163_, SoundSource p_138164_, Vec3 p_138165_, float p_138166_, float p_138167_, float p_138168_) throws CommandSyntaxException {
Holder<SoundEvent> holder = Holder.direct(SoundEvent.createVariableRangeEvent(p_138163_));
double d0 = (double)Mth.square(holder.value().getRange(p_138166_));
int i = 0;
long j = p_138161_.getLevel().getRandom().nextLong();
for(ServerPlayer serverplayer : p_138162_) {
double d1 = p_138165_.x - serverplayer.getX();
double d2 = p_138165_.y - serverplayer.getY();
double d3 = p_138165_.z - serverplayer.getZ();
double d4 = d1 * d1 + d2 * d2 + d3 * d3;
Vec3 vec3 = p_138165_;
float f = p_138166_;
if (d4 > d0) {
if (p_138168_ <= 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 = p_138168_;
}
serverplayer.connection.send(new ClientboundSoundPacket(holder, p_138164_, vec3.x(), vec3.y(), vec3.z(), f, p_138167_, j));
++i;
}
if (i == 0) {
throw ERROR_TOO_FAR.create();
} else {
if (p_138162_.size() == 1) {
p_138161_.sendSuccess(() -> {
return Component.translatable("commands.playsound.success.single", p_138163_, p_138162_.iterator().next().getDisplayName());
}, true);
} else {
p_138161_.sendSuccess(() -> {
return Component.translatable("commands.playsound.success.multiple", p_138163_, p_138162_.size());
}, true);
}
return i;
}
}
}

View File

@@ -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> p_138185_) {
p_138185_.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 p_260117_, int p_259411_, boolean p_260137_, @Nullable GameType p_259145_) throws CommandSyntaxException {
if (p_260117_.getServer().isPublished()) {
throw ERROR_ALREADY_PUBLISHED.create(p_260117_.getServer().getPort());
} else if (!p_260117_.getServer().publishServer(p_259145_, p_260137_, p_259411_)) {
throw ERROR_FAILED.create();
} else {
p_260117_.sendSuccess(() -> {
return getSuccessMessage(p_259411_);
}, true);
return p_259411_;
}
}
public static MutableComponent getSuccessMessage(int p_259532_) {
Component component = ComponentUtils.copyOnClickText(String.valueOf(p_259532_));
return Component.translatable("commands.publish.started", component);
}
}

View File

@@ -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> p_180469_) {
p_180469_.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 p_180473_) throws CommandSyntaxException {
Raid raid = getRaid(p_180473_.getPlayerOrException());
if (raid != null) {
for(Raider raider : raid.getAllRaiders()) {
raider.addEffect(new MobEffectInstance(MobEffects.GLOWING, 1000, 1));
}
}
return 1;
}
private static int setBadOmenLevel(CommandSourceStack p_180475_, int p_180476_) throws CommandSyntaxException {
Raid raid = getRaid(p_180475_.getPlayerOrException());
if (raid != null) {
int i = raid.getMaxBadOmenLevel();
if (p_180476_ > i) {
p_180475_.sendFailure(Component.literal("Sorry, the max bad omen level you can set is " + i));
} else {
int j = raid.getBadOmenLevel();
raid.setBadOmenLevel(p_180476_);
p_180475_.sendSuccess(() -> {
return Component.literal("Changed village's bad omen level from " + j + " to " + p_180476_);
}, false);
}
} else {
p_180475_.sendFailure(Component.literal("No raid found here"));
}
return 1;
}
private static int spawnLeader(CommandSourceStack p_180483_) {
p_180483_.sendSuccess(() -> {
return Component.literal("Spawned a raid captain");
}, false);
Raider raider = EntityType.PILLAGER.create(p_180483_.getLevel());
if (raider == null) {
p_180483_.sendFailure(Component.literal("Pillager failed to spawn"));
return 0;
} else {
raider.setPatrolLeader(true);
raider.setItemSlot(EquipmentSlot.HEAD, Raid.getLeaderBannerInstance());
raider.setPos(p_180483_.getPosition().x, p_180483_.getPosition().y, p_180483_.getPosition().z);
raider.finalizeSpawn(p_180483_.getLevel(), p_180483_.getLevel().getCurrentDifficultyAt(BlockPos.containing(p_180483_.getPosition())), MobSpawnType.COMMAND, (SpawnGroupData)null, (CompoundTag)null);
p_180483_.getLevel().addFreshEntityWithPassengers(raider);
return 1;
}
}
private static int playSound(CommandSourceStack p_180478_, @Nullable Component p_180479_) {
if (p_180479_ != null && p_180479_.getString().equals("local")) {
ServerLevel serverlevel = p_180478_.getLevel();
Vec3 vec3 = p_180478_.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 p_180485_, int p_180486_) throws CommandSyntaxException {
ServerPlayer serverplayer = p_180485_.getPlayerOrException();
BlockPos blockpos = serverplayer.blockPosition();
if (serverplayer.serverLevel().isRaided(blockpos)) {
p_180485_.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(p_180486_);
raids.setDirty();
p_180485_.sendSuccess(() -> {
return Component.literal("Created a raid in your local village");
}, false);
} else {
p_180485_.sendFailure(Component.literal("Failed to create a raid in your local village"));
}
return 1;
}
}
private static int stop(CommandSourceStack p_180490_) throws CommandSyntaxException {
ServerPlayer serverplayer = p_180490_.getPlayerOrException();
BlockPos blockpos = serverplayer.blockPosition();
Raid raid = serverplayer.serverLevel().getRaidAt(blockpos);
if (raid != null) {
raid.stop();
p_180490_.sendSuccess(() -> {
return Component.literal("Stopped raid");
}, false);
return 1;
} else {
p_180490_.sendFailure(Component.literal("No raid here"));
return -1;
}
}
private static int check(CommandSourceStack p_180494_) throws CommandSyntaxException {
Raid raid = getRaid(p_180494_.getPlayerOrException());
if (raid != null) {
StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append("Found a started raid! ");
p_180494_.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());
p_180494_.sendSuccess(() -> {
return Component.literal(stringbuilder1.toString());
}, false);
return 1;
} else {
p_180494_.sendFailure(Component.literal("Found no started raids"));
return 0;
}
}
@Nullable
private static Raid getRaid(ServerPlayer p_180467_) {
return p_180467_.serverLevel().getRaidAt(p_180467_.blockPosition());
}
}

View File

@@ -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> p_138201_) {
p_138201_.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 p_138207_, Collection<ServerPlayer> p_138208_, Collection<Recipe<?>> p_138209_) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : p_138208_) {
i += serverplayer.awardRecipes(p_138209_);
}
if (i == 0) {
throw ERROR_GIVE_FAILED.create();
} else {
if (p_138208_.size() == 1) {
p_138207_.sendSuccess(() -> {
return Component.translatable("commands.recipe.give.success.single", p_138209_.size(), p_138208_.iterator().next().getDisplayName());
}, true);
} else {
p_138207_.sendSuccess(() -> {
return Component.translatable("commands.recipe.give.success.multiple", p_138209_.size(), p_138208_.size());
}, true);
}
return i;
}
}
private static int takeRecipes(CommandSourceStack p_138213_, Collection<ServerPlayer> p_138214_, Collection<Recipe<?>> p_138215_) throws CommandSyntaxException {
int i = 0;
for(ServerPlayer serverplayer : p_138214_) {
i += serverplayer.resetRecipes(p_138215_);
}
if (i == 0) {
throw ERROR_TAKE_FAILED.create();
} else {
if (p_138214_.size() == 1) {
p_138213_.sendSuccess(() -> {
return Component.translatable("commands.recipe.take.success.single", p_138215_.size(), p_138214_.iterator().next().getDisplayName());
}, true);
} else {
p_138213_.sendSuccess(() -> {
return Component.translatable("commands.recipe.take.success.multiple", p_138215_.size(), p_138214_.size());
}, true);
}
return i;
}
}
}

View File

@@ -0,0 +1,57 @@
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> p_138236_, CommandSourceStack p_138237_) {
p_138237_.getServer().reloadResources(p_138236_).exceptionally((p_138234_) -> {
LOGGER.warn("Failed to execute reload", p_138234_);
p_138237_.sendFailure(Component.translatable("commands.reload.failure"));
return null;
});
}
private static Collection<String> discoverNewPacks(PackRepository p_138223_, WorldData p_138224_, Collection<String> p_138225_) {
p_138223_.reload();
Collection<String> collection = Lists.newArrayList(p_138225_);
Collection<String> collection1 = p_138224_.getDataConfiguration().dataPacks().getDisabled();
for(String s : p_138223_.getAvailableIds()) {
if (!collection1.contains(s) && !collection.contains(s)) {
collection.add(s);
}
}
return collection;
}
public static void register(CommandDispatcher<CommandSourceStack> p_138227_) {
p_138227_.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;
}));
}
}

View File

@@ -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> p_183667_) {
p_183667_.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 p_183685_, int p_183686_, boolean p_183687_) {
ServerLevel serverlevel = p_183685_.getLevel();
ServerChunkCache serverchunkcache = serverlevel.getChunkSource();
serverchunkcache.chunkMap.debugReloadGenerator();
Vec3 vec3 = p_183685_.getPosition();
ChunkPos chunkpos = new ChunkPos(BlockPos.containing(vec3));
int i = chunkpos.z - p_183686_;
int j = chunkpos.z + p_183686_;
int k = chunkpos.x - p_183686_;
int l = chunkpos.x + p_183686_;
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 && (!p_183687_ || !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 = (p_183686_ * 2 + 1) * (p_183686_ * 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 - p_183686_; i2 <= chunkpos.z + p_183686_; ++i2) {
for(int j2 = chunkpos.x - p_183686_; j2 <= chunkpos.x + p_183686_; ++j2) {
ChunkPos chunkpos2 = new ChunkPos(j2, i2);
LevelChunk levelchunk1 = serverchunkcache.getChunk(j2, i2, false);
if (levelchunk1 != null && (!p_183687_ || !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);
}
}
}
p_183685_.getServer().managedBlock(completablefuture::isDone);
LOGGER.debug(chunkstatus + " took " + (System.currentTimeMillis() - k1) + " ms");
}
long l3 = System.currentTimeMillis();
for(int i4 = chunkpos.z - p_183686_; i4 <= chunkpos.z + p_183686_; ++i4) {
for(int l1 = chunkpos.x - p_183686_; l1 <= chunkpos.x + p_183686_; ++l1) {
ChunkPos chunkpos3 = new ChunkPos(l1, i4);
LevelChunk levelchunk2 = serverchunkcache.getChunk(l1, i4, false);
if (levelchunk2 != null && (!p_183687_ || !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;
p_183685_.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;
}
}

View File

@@ -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> p_282091_) {
p_282091_.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 p_281858_, int p_281623_) {
p_281858_.getReturnValueConsumer().accept(p_281623_);
return p_281623_;
}
}

View File

@@ -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> p_265201_) {
p_265201_.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 p_265285_, Entity p_265711_, Entity p_265339_) throws CommandSyntaxException {
Entity entity = p_265711_.getVehicle();
if (entity != null) {
throw ERROR_ALREADY_RIDING.create(p_265711_.getDisplayName(), entity.getDisplayName());
} else if (p_265339_.getType() == EntityType.PLAYER) {
throw ERROR_MOUNTING_PLAYER.create();
} else if (p_265711_.getSelfAndPassengers().anyMatch((p_265501_) -> {
return p_265501_ == p_265339_;
})) {
throw ERROR_MOUNTING_LOOP.create();
} else if (p_265711_.level() != p_265339_.level()) {
throw ERROR_WRONG_DIMENSION.create();
} else if (!p_265711_.startRiding(p_265339_, true)) {
throw ERROR_MOUNT_FAILED.create(p_265711_.getDisplayName(), p_265339_.getDisplayName());
} else {
p_265285_.sendSuccess(() -> {
return Component.translatable("commands.ride.mount.success", p_265711_.getDisplayName(), p_265339_.getDisplayName());
}, true);
return 1;
}
}
private static int dismount(CommandSourceStack p_265724_, Entity p_265678_) throws CommandSyntaxException {
Entity entity = p_265678_.getVehicle();
if (entity == null) {
throw ERROR_NOT_RIDING.create(p_265678_.getDisplayName());
} else {
p_265678_.stopRiding();
p_265724_.sendSuccess(() -> {
return Component.translatable("commands.ride.dismount.success", p_265678_.getDisplayName(), entity.getDisplayName());
}, true);
return 1;
}
}
}

View File

@@ -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> p_138272_) {
p_138272_.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 p_138278_, boolean p_138279_) throws CommandSyntaxException {
p_138278_.sendSuccess(() -> {
return Component.translatable("commands.save.saving");
}, false);
MinecraftServer minecraftserver = p_138278_.getServer();
boolean flag = minecraftserver.saveEverything(true, p_138279_, true);
if (!flag) {
throw ERROR_FAILED.create();
} else {
p_138278_.sendSuccess(() -> {
return Component.translatable("commands.save.success");
}, true);
return 1;
}
}
}

View File

@@ -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> p_138285_) {
p_138285_.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;
}
}));
}
}

View File

@@ -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> p_138293_) {
p_138293_.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;
}
}));
}
}

View File

@@ -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> p_138410_) {
p_138410_.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;
})));
}
}

View File

@@ -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> p_138420_) {
p_138420_.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 p_138429_, Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> p_138430_, int p_138431_, boolean p_138432_) throws CommandSyntaxException {
if (p_138431_ == 0) {
throw ERROR_SAME_TICK.create();
} else {
long i = p_138429_.getLevel().getGameTime() + (long)p_138431_;
ResourceLocation resourcelocation = p_138430_.getFirst();
TimerQueue<MinecraftServer> timerqueue = p_138429_.getServer().getWorldData().overworldData().getScheduledEvents();
p_138430_.getSecond().ifLeft((p_288541_) -> {
String s = resourcelocation.toString();
if (p_138432_) {
timerqueue.remove(s);
}
timerqueue.schedule(s, i, new FunctionCallback(resourcelocation));
p_138429_.sendSuccess(() -> {
return Component.translatable("commands.schedule.created.function", resourcelocation, p_138431_, i);
}, true);
}).ifRight((p_288548_) -> {
String s = "#" + resourcelocation;
if (p_138432_) {
timerqueue.remove(s);
}
timerqueue.schedule(s, i, new FunctionTagCallback(resourcelocation));
p_138429_.sendSuccess(() -> {
return Component.translatable("commands.schedule.created.tag", resourcelocation, p_138431_, i);
}, true);
});
return Math.floorMod(i, Integer.MAX_VALUE);
}
}
private static int remove(CommandSourceStack p_138434_, String p_138435_) throws CommandSyntaxException {
int i = p_138434_.getServer().getWorldData().overworldData().getScheduledEvents().remove(p_138435_);
if (i == 0) {
throw ERROR_CANT_REMOVE.create(p_138435_);
} else {
p_138434_.sendSuccess(() -> {
return Component.translatable("commands.schedule.cleared.success", i, p_138435_);
}, true);
return i;
}
}
}

View File

@@ -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> p_138469_) {
p_138469_.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 p_138511_, Collection<String> p_138512_, SuggestionsBuilder p_138513_) {
List<String> list = Lists.newArrayList();
Scoreboard scoreboard = p_138511_.getServer().getScoreboard();
for(Objective objective : scoreboard.getObjectives()) {
if (objective.getCriteria() == ObjectiveCriteria.TRIGGER) {
boolean flag = false;
for(String s : p_138512_) {
if (!scoreboard.hasPlayerScore(s, objective) || scoreboard.getOrCreatePlayerScore(s, objective).isLocked()) {
flag = true;
break;
}
}
if (flag) {
list.add(objective.getName());
}
}
}
return SharedSuggestionProvider.suggest(list, p_138513_);
}
private static int getScore(CommandSourceStack p_138499_, String p_138500_, Objective p_138501_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138499_.getServer().getScoreboard();
if (!scoreboard.hasPlayerScore(p_138500_, p_138501_)) {
throw ERROR_NO_VALUE.create(p_138501_.getName(), p_138500_);
} else {
Score score = scoreboard.getOrCreatePlayerScore(p_138500_, p_138501_);
p_138499_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.get.success", p_138500_, score.getScore(), p_138501_.getFormattedDisplayName());
}, false);
return score.getScore();
}
}
private static int performOperation(CommandSourceStack p_138524_, Collection<String> p_138525_, Objective p_138526_, OperationArgument.Operation p_138527_, Collection<String> p_138528_, Objective p_138529_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138524_.getServer().getScoreboard();
int i = 0;
for(String s : p_138525_) {
Score score = scoreboard.getOrCreatePlayerScore(s, p_138526_);
for(String s1 : p_138528_) {
Score score1 = scoreboard.getOrCreatePlayerScore(s1, p_138529_);
p_138527_.apply(score, score1);
}
i += score.getScore();
}
if (p_138525_.size() == 1) {
int j = i;
p_138524_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.operation.success.single", p_138526_.getFormattedDisplayName(), p_138525_.iterator().next(), j);
}, true);
} else {
p_138524_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.operation.success.multiple", p_138526_.getFormattedDisplayName(), p_138525_.size());
}, true);
}
return i;
}
private static int enableTrigger(CommandSourceStack p_138515_, Collection<String> p_138516_, Objective p_138517_) throws CommandSyntaxException {
if (p_138517_.getCriteria() != ObjectiveCriteria.TRIGGER) {
throw ERROR_NOT_TRIGGER.create();
} else {
Scoreboard scoreboard = p_138515_.getServer().getScoreboard();
int i = 0;
for(String s : p_138516_) {
Score score = scoreboard.getOrCreatePlayerScore(s, p_138517_);
if (score.isLocked()) {
score.setLocked(false);
++i;
}
}
if (i == 0) {
throw ERROR_TRIGGER_ALREADY_ENABLED.create();
} else {
if (p_138516_.size() == 1) {
p_138515_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.enable.success.single", p_138517_.getFormattedDisplayName(), p_138516_.iterator().next());
}, true);
} else {
p_138515_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.enable.success.multiple", p_138517_.getFormattedDisplayName(), p_138516_.size());
}, true);
}
return i;
}
}
}
private static int resetScores(CommandSourceStack p_138508_, Collection<String> p_138509_) {
Scoreboard scoreboard = p_138508_.getServer().getScoreboard();
for(String s : p_138509_) {
scoreboard.resetPlayerScore(s, (Objective)null);
}
if (p_138509_.size() == 1) {
p_138508_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.all.single", p_138509_.iterator().next());
}, true);
} else {
p_138508_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.all.multiple", p_138509_.size());
}, true);
}
return p_138509_.size();
}
private static int resetScore(CommandSourceStack p_138541_, Collection<String> p_138542_, Objective p_138543_) {
Scoreboard scoreboard = p_138541_.getServer().getScoreboard();
for(String s : p_138542_) {
scoreboard.resetPlayerScore(s, p_138543_);
}
if (p_138542_.size() == 1) {
p_138541_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.specific.single", p_138543_.getFormattedDisplayName(), p_138542_.iterator().next());
}, true);
} else {
p_138541_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.reset.specific.multiple", p_138543_.getFormattedDisplayName(), p_138542_.size());
}, true);
}
return p_138542_.size();
}
private static int setScore(CommandSourceStack p_138519_, Collection<String> p_138520_, Objective p_138521_, int p_138522_) {
Scoreboard scoreboard = p_138519_.getServer().getScoreboard();
for(String s : p_138520_) {
Score score = scoreboard.getOrCreatePlayerScore(s, p_138521_);
score.setScore(p_138522_);
}
if (p_138520_.size() == 1) {
p_138519_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.set.success.single", p_138521_.getFormattedDisplayName(), p_138520_.iterator().next(), p_138522_);
}, true);
} else {
p_138519_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.set.success.multiple", p_138521_.getFormattedDisplayName(), p_138520_.size(), p_138522_);
}, true);
}
return p_138522_ * p_138520_.size();
}
private static int addScore(CommandSourceStack p_138545_, Collection<String> p_138546_, Objective p_138547_, int p_138548_) {
Scoreboard scoreboard = p_138545_.getServer().getScoreboard();
int i = 0;
for(String s : p_138546_) {
Score score = scoreboard.getOrCreatePlayerScore(s, p_138547_);
score.setScore(score.getScore() + p_138548_);
i += score.getScore();
}
if (p_138546_.size() == 1) {
int j = i;
p_138545_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.add.success.single", p_138548_, p_138547_.getFormattedDisplayName(), p_138546_.iterator().next(), j);
}, true);
} else {
p_138545_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.add.success.multiple", p_138548_, p_138547_.getFormattedDisplayName(), p_138546_.size());
}, true);
}
return i;
}
private static int removeScore(CommandSourceStack p_138554_, Collection<String> p_138555_, Objective p_138556_, int p_138557_) {
Scoreboard scoreboard = p_138554_.getServer().getScoreboard();
int i = 0;
for(String s : p_138555_) {
Score score = scoreboard.getOrCreatePlayerScore(s, p_138556_);
score.setScore(score.getScore() - p_138557_);
i += score.getScore();
}
if (p_138555_.size() == 1) {
int j = i;
p_138554_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.remove.success.single", p_138557_, p_138556_.getFormattedDisplayName(), p_138555_.iterator().next(), j);
}, true);
} else {
p_138554_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.remove.success.multiple", p_138557_, p_138556_.getFormattedDisplayName(), p_138555_.size());
}, true);
}
return i;
}
private static int listTrackedPlayers(CommandSourceStack p_138476_) {
Collection<String> collection = p_138476_.getServer().getScoreboard().getTrackedPlayers();
if (collection.isEmpty()) {
p_138476_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.empty");
}, false);
} else {
p_138476_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.success", collection.size(), ComponentUtils.formatList(collection));
}, false);
}
return collection.size();
}
private static int listTrackedPlayerScores(CommandSourceStack p_138496_, String p_138497_) {
Map<Objective, Score> map = p_138496_.getServer().getScoreboard().getPlayerScores(p_138497_);
if (map.isEmpty()) {
p_138496_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.entity.empty", p_138497_);
}, false);
} else {
p_138496_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.players.list.entity.success", p_138497_, map.size());
}, false);
for(Map.Entry<Objective, Score> entry : map.entrySet()) {
p_138496_.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 p_138478_, int p_138479_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138478_.getServer().getScoreboard();
if (scoreboard.getDisplayObjective(p_138479_) == null) {
throw ERROR_DISPLAY_SLOT_ALREADY_EMPTY.create();
} else {
scoreboard.setDisplayObjective(p_138479_, (Objective)null);
p_138478_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.display.cleared", Scoreboard.getDisplaySlotNames()[p_138479_]);
}, true);
return 0;
}
}
private static int setDisplaySlot(CommandSourceStack p_138481_, int p_138482_, Objective p_138483_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138481_.getServer().getScoreboard();
if (scoreboard.getDisplayObjective(p_138482_) == p_138483_) {
throw ERROR_DISPLAY_SLOT_ALREADY_SET.create();
} else {
scoreboard.setDisplayObjective(p_138482_, p_138483_);
p_138481_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.display.set", Scoreboard.getDisplaySlotNames()[p_138482_], p_138483_.getDisplayName());
}, true);
return 0;
}
}
private static int setDisplayName(CommandSourceStack p_138492_, Objective p_138493_, Component p_138494_) {
if (!p_138493_.getDisplayName().equals(p_138494_)) {
p_138493_.setDisplayName(p_138494_);
p_138492_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.modify.displayname", p_138493_.getName(), p_138493_.getFormattedDisplayName());
}, true);
}
return 0;
}
private static int setRenderType(CommandSourceStack p_138488_, Objective p_138489_, ObjectiveCriteria.RenderType p_138490_) {
if (p_138489_.getRenderType() != p_138490_) {
p_138489_.setRenderType(p_138490_);
p_138488_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.modify.rendertype", p_138489_.getFormattedDisplayName());
}, true);
}
return 0;
}
private static int removeObjective(CommandSourceStack p_138485_, Objective p_138486_) {
Scoreboard scoreboard = p_138485_.getServer().getScoreboard();
scoreboard.removeObjective(p_138486_);
p_138485_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.remove.success", p_138486_.getFormattedDisplayName());
}, true);
return scoreboard.getObjectives().size();
}
private static int addObjective(CommandSourceStack p_138503_, String p_138504_, ObjectiveCriteria p_138505_, Component p_138506_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138503_.getServer().getScoreboard();
if (scoreboard.getObjective(p_138504_) != null) {
throw ERROR_OBJECTIVE_ALREADY_EXISTS.create();
} else {
scoreboard.addObjective(p_138504_, p_138505_, p_138506_, p_138505_.getDefaultRenderType());
Objective objective = scoreboard.getObjective(p_138504_);
p_138503_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.add.success", objective.getFormattedDisplayName());
}, true);
return scoreboard.getObjectives().size();
}
}
private static int listObjectives(CommandSourceStack p_138539_) {
Collection<Objective> collection = p_138539_.getServer().getScoreboard().getObjectives();
if (collection.isEmpty()) {
p_138539_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.list.empty");
}, false);
} else {
p_138539_.sendSuccess(() -> {
return Component.translatable("commands.scoreboard.objectives.list.success", collection.size(), ComponentUtils.formatList(collection, Objective::getFormattedDisplayName));
}, false);
}
return collection.size();
}
}

View File

@@ -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> p_138590_, boolean p_138591_) {
p_138590_.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;
}));
}
}

View File

@@ -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> p_214731_, CommandBuildContext p_214732_) {
p_214731_.register(Commands.literal("setblock").requires((p_138606_) -> {
return p_138606_.hasPermission(2);
}).then(Commands.argument("pos", BlockPosArgument.blockPos()).then(Commands.argument("block", BlockStateArgument.block(p_214732_)).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 p_138608_, BlockPos p_138609_, BlockInput p_138610_, SetBlockCommand.Mode p_138611_, @Nullable Predicate<BlockInWorld> p_138612_) throws CommandSyntaxException {
ServerLevel serverlevel = p_138608_.getLevel();
if (p_138612_ != null && !p_138612_.test(new BlockInWorld(serverlevel, p_138609_, true))) {
throw ERROR_FAILED.create();
} else {
boolean flag;
if (p_138611_ == SetBlockCommand.Mode.DESTROY) {
serverlevel.destroyBlock(p_138609_, true);
flag = !p_138610_.getState().isAir() || !serverlevel.getBlockState(p_138609_).isAir();
} else {
BlockEntity blockentity = serverlevel.getBlockEntity(p_138609_);
Clearable.tryClear(blockentity);
flag = true;
}
if (flag && !p_138610_.place(serverlevel, p_138609_, 2)) {
throw ERROR_FAILED.create();
} else {
serverlevel.blockUpdated(p_138609_, p_138610_.getState().getBlock());
p_138608_.sendSuccess(() -> {
return Component.translatable("commands.setblock.success", p_138609_.getX(), p_138609_.getY(), p_138609_.getZ());
}, true);
return 1;
}
}
}
public interface Filter {
@Nullable
BlockInput filter(BoundingBox p_138620_, BlockPos p_138621_, BlockInput p_138622_, ServerLevel p_138623_);
}
public static enum Mode {
REPLACE,
DESTROY;
}
}

View File

@@ -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> p_138635_) {
p_138635_.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 p_138641_, int p_138642_) {
p_138641_.getServer().setPlayerIdleTimeout(p_138642_);
p_138641_.sendSuccess(() -> {
return Component.translatable("commands.setidletimeout.success", p_138642_);
}, true);
return p_138642_;
}
}

View File

@@ -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> p_138644_) {
p_138644_.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 p_138650_, Collection<ServerPlayer> p_138651_, BlockPos p_138652_, float p_138653_) {
ResourceKey<Level> resourcekey = p_138650_.getLevel().dimension();
for(ServerPlayer serverplayer : p_138651_) {
serverplayer.setRespawnPosition(resourcekey, p_138652_, p_138653_, true, false);
}
String s = resourcekey.location().toString();
if (p_138651_.size() == 1) {
p_138650_.sendSuccess(() -> {
return Component.translatable("commands.spawnpoint.success.single", p_138652_.getX(), p_138652_.getY(), p_138652_.getZ(), p_138653_, s, p_138651_.iterator().next().getDisplayName());
}, true);
} else {
p_138650_.sendSuccess(() -> {
return Component.translatable("commands.spawnpoint.success.multiple", p_138652_.getX(), p_138652_.getY(), p_138652_.getZ(), p_138653_, s, p_138651_.size());
}, true);
}
return p_138651_.size();
}
}

View File

@@ -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> p_138661_) {
p_138661_.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 p_138667_, BlockPos p_138668_, float p_138669_) {
p_138667_.getLevel().setDefaultSpawnPos(p_138668_, p_138669_);
p_138667_.sendSuccess(() -> {
return Component.translatable("commands.setworldspawn.success", p_138668_.getX(), p_138668_.getY(), p_138668_.getZ(), p_138669_);
}, true);
return 1;
}
}

View File

@@ -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> p_266758_) {
p_266758_.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 p_266993_, Player p_266983_) {
Level level = p_266983_.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 = p_266983_.blockPosition().relative(p_266983_.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;
}
p_266993_.sendSuccess(() -> {
return Component.literal("Armorstands with trimmed armor spawned around you");
}, true);
return 1;
}
}

View File

@@ -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> p_138678_) {
p_138678_.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 p_138684_, @Nullable Entity p_138685_, ServerPlayer p_138686_) throws CommandSyntaxException {
if (p_138686_ == p_138685_) {
throw ERROR_SELF.create();
} else if (p_138686_.gameMode.getGameModeForPlayer() != GameType.SPECTATOR) {
throw ERROR_NOT_SPECTATOR.create(p_138686_.getDisplayName());
} else {
p_138686_.setCamera(p_138685_);
if (p_138685_ != null) {
p_138684_.sendSuccess(() -> {
return Component.translatable("commands.spectate.success.started", p_138685_.getDisplayName());
}, false);
} else {
p_138684_.sendSuccess(() -> {
return Component.translatable("commands.spectate.success.stopped");
}, false);
}
return 1;
}
}
}

View File

@@ -0,0 +1,283 @@
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> p_138697_) {
p_138697_.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 p_138703_, Vec2 p_138704_, float p_138705_, float p_138706_, int p_138707_, boolean p_138708_, Collection<? extends Entity> p_138709_) throws CommandSyntaxException {
ServerLevel serverlevel = p_138703_.getLevel();
int i = serverlevel.getMinBuildHeight();
if (p_138707_ < i) {
throw ERROR_INVALID_MAX_HEIGHT.create(p_138707_, i);
} else {
RandomSource randomsource = RandomSource.create();
double d0 = (double)(p_138704_.x - p_138706_);
double d1 = (double)(p_138704_.y - p_138706_);
double d2 = (double)(p_138704_.x + p_138706_);
double d3 = (double)(p_138704_.y + p_138706_);
SpreadPlayersCommand.Position[] aspreadplayerscommand$position = createInitialPositions(randomsource, p_138708_ ? getNumberOfTeams(p_138709_) : p_138709_.size(), d0, d1, d2, d3);
spreadPositions(p_138704_, (double)p_138705_, serverlevel, randomsource, d0, d1, d2, d3, p_138707_, aspreadplayerscommand$position, p_138708_);
double d4 = setPlayerPositions(p_138709_, serverlevel, aspreadplayerscommand$position, p_138707_, p_138708_);
p_138703_.sendSuccess(() -> {
return Component.translatable("commands.spreadplayers.success." + (p_138708_ ? "teams" : "entities"), aspreadplayerscommand$position.length, p_138704_.x, p_138704_.y, String.format(Locale.ROOT, "%.2f", d4));
}, true);
return aspreadplayerscommand$position.length;
}
}
private static int getNumberOfTeams(Collection<? extends Entity> p_138728_) {
Set<Team> set = Sets.newHashSet();
for(Entity entity : p_138728_) {
if (entity instanceof Player) {
set.add(entity.getTeam());
} else {
set.add((Team)null);
}
}
return set.size();
}
private static void spreadPositions(Vec2 p_214741_, double p_214742_, ServerLevel p_214743_, RandomSource p_214744_, double p_214745_, double p_214746_, double p_214747_, double p_214748_, int p_214749_, SpreadPlayersCommand.Position[] p_214750_, boolean p_214751_) 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 < p_214750_.length; ++j) {
SpreadPlayersCommand.Position spreadplayerscommand$position = p_214750_[j];
int k = 0;
SpreadPlayersCommand.Position spreadplayerscommand$position1 = new SpreadPlayersCommand.Position();
for(int l = 0; l < p_214750_.length; ++l) {
if (j != l) {
SpreadPlayersCommand.Position spreadplayerscommand$position2 = p_214750_[l];
double d1 = spreadplayerscommand$position.dist(spreadplayerscommand$position2);
d0 = Math.min(d1, d0);
if (d1 < p_214742_) {
++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(p_214744_, p_214745_, p_214746_, p_214747_, p_214748_);
}
flag = true;
}
if (spreadplayerscommand$position.clamp(p_214745_, p_214746_, p_214747_, p_214748_)) {
flag = true;
}
}
if (!flag) {
for(SpreadPlayersCommand.Position spreadplayerscommand$position3 : p_214750_) {
if (!spreadplayerscommand$position3.isSafe(p_214743_, p_214749_)) {
spreadplayerscommand$position3.randomize(p_214744_, p_214745_, p_214746_, p_214747_, p_214748_);
flag = true;
}
}
}
}
if (d0 == (double)Float.MAX_VALUE) {
d0 = 0.0D;
}
if (i >= 10000) {
if (p_214751_) {
throw ERROR_FAILED_TO_SPREAD_TEAMS.create(p_214750_.length, p_214741_.x, p_214741_.y, String.format(Locale.ROOT, "%.2f", d0));
} else {
throw ERROR_FAILED_TO_SPREAD_ENTITIES.create(p_214750_.length, p_214741_.x, p_214741_.y, String.format(Locale.ROOT, "%.2f", d0));
}
}
}
private static double setPlayerPositions(Collection<? extends Entity> p_138730_, ServerLevel p_138731_, SpreadPlayersCommand.Position[] p_138732_, int p_138733_, boolean p_138734_) {
double d0 = 0.0D;
int i = 0;
Map<Team, SpreadPlayersCommand.Position> map = Maps.newHashMap();
for(Entity entity : p_138730_) {
SpreadPlayersCommand.Position spreadplayerscommand$position;
if (p_138734_) {
Team team = entity instanceof Player ? entity.getTeam() : null;
if (!map.containsKey(team)) {
map.put(team, p_138732_[i++]);
}
spreadplayerscommand$position = map.get(team);
} else {
spreadplayerscommand$position = p_138732_[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(p_138731_, p_138733_), (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 : p_138732_) {
if (spreadplayerscommand$position != spreadplayerscommand$position1) {
double d1 = spreadplayerscommand$position.dist(spreadplayerscommand$position1);
d2 = Math.min(d1, d2);
}
}
d0 += d2;
}
return p_138730_.size() < 2 ? 0.0D : d0 / (double)p_138730_.size();
}
private static SpreadPlayersCommand.Position[] createInitialPositions(RandomSource p_214734_, int p_214735_, double p_214736_, double p_214737_, double p_214738_, double p_214739_) {
SpreadPlayersCommand.Position[] aspreadplayerscommand$position = new SpreadPlayersCommand.Position[p_214735_];
for(int i = 0; i < aspreadplayerscommand$position.length; ++i) {
SpreadPlayersCommand.Position spreadplayerscommand$position = new SpreadPlayersCommand.Position();
spreadplayerscommand$position.randomize(p_214734_, p_214736_, p_214737_, p_214738_, p_214739_);
aspreadplayerscommand$position[i] = spreadplayerscommand$position;
}
return aspreadplayerscommand$position;
}
static class Position {
double x;
double z;
double dist(SpreadPlayersCommand.Position p_138768_) {
double d0 = this.x - p_138768_.x;
double d1 = this.z - p_138768_.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 p_138777_) {
this.x -= p_138777_.x;
this.z -= p_138777_.z;
}
public boolean clamp(double p_138754_, double p_138755_, double p_138756_, double p_138757_) {
boolean flag = false;
if (this.x < p_138754_) {
this.x = p_138754_;
flag = true;
} else if (this.x > p_138756_) {
this.x = p_138756_;
flag = true;
}
if (this.z < p_138755_) {
this.z = p_138755_;
flag = true;
} else if (this.z > p_138757_) {
this.z = p_138757_;
flag = true;
}
return flag;
}
public int getSpawnY(BlockGetter p_138759_, int p_138760_) {
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(this.x, (double)(p_138760_ + 1), this.z);
boolean flag = p_138759_.getBlockState(blockpos$mutableblockpos).isAir();
blockpos$mutableblockpos.move(Direction.DOWN);
boolean flag2;
for(boolean flag1 = p_138759_.getBlockState(blockpos$mutableblockpos).isAir(); blockpos$mutableblockpos.getY() > p_138759_.getMinBuildHeight(); flag1 = flag2) {
blockpos$mutableblockpos.move(Direction.DOWN);
flag2 = p_138759_.getBlockState(blockpos$mutableblockpos).isAir();
if (!flag2 && flag1 && flag) {
return blockpos$mutableblockpos.getY() + 1;
}
flag = flag1;
}
return p_138760_ + 1;
}
public boolean isSafe(BlockGetter p_138774_, int p_138775_) {
BlockPos blockpos = BlockPos.containing(this.x, (double)(this.getSpawnY(p_138774_, p_138775_) - 1), this.z);
BlockState blockstate = p_138774_.getBlockState(blockpos);
return blockpos.getY() < p_138775_ && !blockstate.liquid() && !blockstate.is(BlockTags.FIRE);
}
public void randomize(RandomSource p_214753_, double p_214754_, double p_214755_, double p_214756_, double p_214757_) {
this.x = Mth.nextDouble(p_214753_, p_214754_, p_214756_);
this.z = Mth.nextDouble(p_214753_, p_214755_, p_214757_);
}
}
}

View File

@@ -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> p_138786_) {
p_138786_.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;
}));
}
}

View File

@@ -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> p_138795_) {
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"));
})));
}
p_138795_.register(Commands.literal("stopsound").requires((p_138799_) -> {
return p_138799_.hasPermission(2);
}).then(requiredargumentbuilder));
}
private static int stopSound(CommandSourceStack p_138801_, Collection<ServerPlayer> p_138802_, @Nullable SoundSource p_138803_, @Nullable ResourceLocation p_138804_) {
ClientboundStopSoundPacket clientboundstopsoundpacket = new ClientboundStopSoundPacket(p_138804_, p_138803_);
for(ServerPlayer serverplayer : p_138802_) {
serverplayer.connection.send(clientboundstopsoundpacket);
}
if (p_138803_ != null) {
if (p_138804_ != null) {
p_138801_.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.source.sound", p_138804_, p_138803_.getName());
}, true);
} else {
p_138801_.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.source.any", p_138803_.getName());
}, true);
}
} else if (p_138804_ != null) {
p_138801_.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.sourceless.sound", p_138804_);
}, true);
} else {
p_138801_.sendSuccess(() -> {
return Component.translatable("commands.stopsound.success.sourceless.any");
}, true);
}
return p_138802_.size();
}
}

View File

@@ -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> p_250343_, CommandBuildContext p_250122_) {
p_250343_.register(Commands.literal("summon").requires((p_138819_) -> {
return p_138819_.hasPermission(2);
}).then(Commands.argument("entity", ResourceArgument.resource(p_250122_, 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 p_270582_, Holder.Reference<EntityType<?>> p_270277_, Vec3 p_270366_, CompoundTag p_270197_, boolean p_270947_) throws CommandSyntaxException {
BlockPos blockpos = BlockPos.containing(p_270366_);
if (!Level.isInSpawnableBounds(blockpos)) {
throw INVALID_POSITION.create();
} else {
CompoundTag compoundtag = p_270197_.copy();
compoundtag.putString("id", p_270277_.key().location().toString());
ServerLevel serverlevel = p_270582_.getLevel();
Entity entity = EntityType.loadEntityRecursive(compoundtag, serverlevel, (p_138828_) -> {
p_138828_.moveTo(p_270366_.x, p_270366_.y, p_270366_.z, p_138828_.getYRot(), p_138828_.getXRot());
return p_138828_;
});
if (entity == null) {
throw ERROR_FAILED.create();
} else {
if (p_270947_ && entity instanceof Mob) {
((Mob)entity).finalizeSpawn(p_270582_.getLevel(), p_270582_.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 p_249752_, Holder.Reference<EntityType<?>> p_251948_, Vec3 p_251429_, CompoundTag p_250568_, boolean p_250229_) throws CommandSyntaxException {
Entity entity = createEntity(p_249752_, p_251948_, p_251429_, p_250568_, p_250229_);
p_249752_.sendSuccess(() -> {
return Component.translatable("commands.summon.success", entity.getDisplayName());
}, true);
return 1;
}
}

View File

@@ -0,0 +1,128 @@
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> p_138837_) {
p_138837_.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"));
}))));
}
private static Collection<String> getTags(Collection<? extends Entity> p_138853_) {
Set<String> set = Sets.newHashSet();
for(Entity entity : p_138853_) {
set.addAll(entity.getTags());
}
return set;
}
private static int addTag(CommandSourceStack p_138849_, Collection<? extends Entity> p_138850_, String p_138851_) throws CommandSyntaxException {
int i = 0;
for(Entity entity : p_138850_) {
if (entity.addTag(p_138851_)) {
++i;
}
}
if (i == 0) {
throw ERROR_ADD_FAILED.create();
} else {
if (p_138850_.size() == 1) {
p_138849_.sendSuccess(() -> {
return Component.translatable("commands.tag.add.success.single", p_138851_, p_138850_.iterator().next().getDisplayName());
}, true);
} else {
p_138849_.sendSuccess(() -> {
return Component.translatable("commands.tag.add.success.multiple", p_138851_, p_138850_.size());
}, true);
}
return i;
}
}
private static int removeTag(CommandSourceStack p_138857_, Collection<? extends Entity> p_138858_, String p_138859_) throws CommandSyntaxException {
int i = 0;
for(Entity entity : p_138858_) {
if (entity.removeTag(p_138859_)) {
++i;
}
}
if (i == 0) {
throw ERROR_REMOVE_FAILED.create();
} else {
if (p_138858_.size() == 1) {
p_138857_.sendSuccess(() -> {
return Component.translatable("commands.tag.remove.success.single", p_138859_, p_138858_.iterator().next().getDisplayName());
}, true);
} else {
p_138857_.sendSuccess(() -> {
return Component.translatable("commands.tag.remove.success.multiple", p_138859_, p_138858_.size());
}, true);
}
return i;
}
}
private static int listTags(CommandSourceStack p_138846_, Collection<? extends Entity> p_138847_) {
Set<String> set = Sets.newHashSet();
for(Entity entity : p_138847_) {
set.addAll(entity.getTags());
}
if (p_138847_.size() == 1) {
Entity entity1 = p_138847_.iterator().next();
if (set.isEmpty()) {
p_138846_.sendSuccess(() -> {
return Component.translatable("commands.tag.list.single.empty", entity1.getDisplayName());
}, false);
} else {
p_138846_.sendSuccess(() -> {
return Component.translatable("commands.tag.list.single.success", entity1.getDisplayName(), set.size(), ComponentUtils.formatList(set));
}, false);
}
} else if (set.isEmpty()) {
p_138846_.sendSuccess(() -> {
return Component.translatable("commands.tag.list.multiple.empty", p_138847_.size());
}, false);
} else {
p_138846_.sendSuccess(() -> {
return Component.translatable("commands.tag.list.multiple.success", p_138847_.size(), set.size(), ComponentUtils.formatList(set));
}, false);
}
return set.size();
}
}

View File

@@ -0,0 +1,318 @@
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> p_138878_) {
p_138878_.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"));
}))))));
}
private static int leaveTeam(CommandSourceStack p_138918_, Collection<String> p_138919_) {
Scoreboard scoreboard = p_138918_.getServer().getScoreboard();
for(String s : p_138919_) {
scoreboard.removePlayerFromTeam(s);
}
if (p_138919_.size() == 1) {
p_138918_.sendSuccess(() -> {
return Component.translatable("commands.team.leave.success.single", p_138919_.iterator().next());
}, true);
} else {
p_138918_.sendSuccess(() -> {
return Component.translatable("commands.team.leave.success.multiple", p_138919_.size());
}, true);
}
return p_138919_.size();
}
private static int joinTeam(CommandSourceStack p_138895_, PlayerTeam p_138896_, Collection<String> p_138897_) {
Scoreboard scoreboard = p_138895_.getServer().getScoreboard();
for(String s : p_138897_) {
scoreboard.addPlayerToTeam(s, p_138896_);
}
if (p_138897_.size() == 1) {
p_138895_.sendSuccess(() -> {
return Component.translatable("commands.team.join.success.single", p_138897_.iterator().next(), p_138896_.getFormattedDisplayName());
}, true);
} else {
p_138895_.sendSuccess(() -> {
return Component.translatable("commands.team.join.success.multiple", p_138897_.size(), p_138896_.getFormattedDisplayName());
}, true);
}
return p_138897_.size();
}
private static int setNametagVisibility(CommandSourceStack p_138891_, PlayerTeam p_138892_, Team.Visibility p_138893_) throws CommandSyntaxException {
if (p_138892_.getNameTagVisibility() == p_138893_) {
throw ERROR_TEAM_NAMETAG_VISIBLITY_UNCHANGED.create();
} else {
p_138892_.setNameTagVisibility(p_138893_);
p_138891_.sendSuccess(() -> {
return Component.translatable("commands.team.option.nametagVisibility.success", p_138892_.getFormattedDisplayName(), p_138893_.getDisplayName());
}, true);
return 0;
}
}
private static int setDeathMessageVisibility(CommandSourceStack p_138930_, PlayerTeam p_138931_, Team.Visibility p_138932_) throws CommandSyntaxException {
if (p_138931_.getDeathMessageVisibility() == p_138932_) {
throw ERROR_TEAM_DEATH_MESSAGE_VISIBLITY_UNCHANGED.create();
} else {
p_138931_.setDeathMessageVisibility(p_138932_);
p_138930_.sendSuccess(() -> {
return Component.translatable("commands.team.option.deathMessageVisibility.success", p_138931_.getFormattedDisplayName(), p_138932_.getDisplayName());
}, true);
return 0;
}
}
private static int setCollision(CommandSourceStack p_138887_, PlayerTeam p_138888_, Team.CollisionRule p_138889_) throws CommandSyntaxException {
if (p_138888_.getCollisionRule() == p_138889_) {
throw ERROR_TEAM_COLLISION_UNCHANGED.create();
} else {
p_138888_.setCollisionRule(p_138889_);
p_138887_.sendSuccess(() -> {
return Component.translatable("commands.team.option.collisionRule.success", p_138888_.getFormattedDisplayName(), p_138889_.getDisplayName());
}, true);
return 0;
}
}
private static int setFriendlySight(CommandSourceStack p_138907_, PlayerTeam p_138908_, boolean p_138909_) throws CommandSyntaxException {
if (p_138908_.canSeeFriendlyInvisibles() == p_138909_) {
if (p_138909_) {
throw ERROR_TEAM_ALREADY_FRIENDLYINVISIBLES_ENABLED.create();
} else {
throw ERROR_TEAM_ALREADY_FRIENDLYINVISIBLES_DISABLED.create();
}
} else {
p_138908_.setSeeFriendlyInvisibles(p_138909_);
p_138907_.sendSuccess(() -> {
return Component.translatable("commands.team.option.seeFriendlyInvisibles." + (p_138909_ ? "enabled" : "disabled"), p_138908_.getFormattedDisplayName());
}, true);
return 0;
}
}
private static int setFriendlyFire(CommandSourceStack p_138938_, PlayerTeam p_138939_, boolean p_138940_) throws CommandSyntaxException {
if (p_138939_.isAllowFriendlyFire() == p_138940_) {
if (p_138940_) {
throw ERROR_TEAM_ALREADY_FRIENDLYFIRE_ENABLED.create();
} else {
throw ERROR_TEAM_ALREADY_FRIENDLYFIRE_DISABLED.create();
}
} else {
p_138939_.setAllowFriendlyFire(p_138940_);
p_138938_.sendSuccess(() -> {
return Component.translatable("commands.team.option.friendlyfire." + (p_138940_ ? "enabled" : "disabled"), p_138939_.getFormattedDisplayName());
}, true);
return 0;
}
}
private static int setDisplayName(CommandSourceStack p_138903_, PlayerTeam p_138904_, Component p_138905_) throws CommandSyntaxException {
if (p_138904_.getDisplayName().equals(p_138905_)) {
throw ERROR_TEAM_ALREADY_NAME.create();
} else {
p_138904_.setDisplayName(p_138905_);
p_138903_.sendSuccess(() -> {
return Component.translatable("commands.team.option.name.success", p_138904_.getFormattedDisplayName());
}, true);
return 0;
}
}
private static int setColor(CommandSourceStack p_138899_, PlayerTeam p_138900_, ChatFormatting p_138901_) throws CommandSyntaxException {
if (p_138900_.getColor() == p_138901_) {
throw ERROR_TEAM_ALREADY_COLOR.create();
} else {
p_138900_.setColor(p_138901_);
p_138899_.sendSuccess(() -> {
return Component.translatable("commands.team.option.color.success", p_138900_.getFormattedDisplayName(), p_138901_.getName());
}, true);
return 0;
}
}
private static int emptyTeam(CommandSourceStack p_138884_, PlayerTeam p_138885_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138884_.getServer().getScoreboard();
Collection<String> collection = Lists.newArrayList(p_138885_.getPlayers());
if (collection.isEmpty()) {
throw ERROR_TEAM_ALREADY_EMPTY.create();
} else {
for(String s : collection) {
scoreboard.removePlayerFromTeam(s, p_138885_);
}
p_138884_.sendSuccess(() -> {
return Component.translatable("commands.team.empty.success", collection.size(), p_138885_.getFormattedDisplayName());
}, true);
return collection.size();
}
}
private static int deleteTeam(CommandSourceStack p_138927_, PlayerTeam p_138928_) {
Scoreboard scoreboard = p_138927_.getServer().getScoreboard();
scoreboard.removePlayerTeam(p_138928_);
p_138927_.sendSuccess(() -> {
return Component.translatable("commands.team.remove.success", p_138928_.getFormattedDisplayName());
}, true);
return scoreboard.getPlayerTeams().size();
}
private static int createTeam(CommandSourceStack p_138911_, String p_138912_) throws CommandSyntaxException {
return createTeam(p_138911_, p_138912_, Component.literal(p_138912_));
}
private static int createTeam(CommandSourceStack p_138914_, String p_138915_, Component p_138916_) throws CommandSyntaxException {
Scoreboard scoreboard = p_138914_.getServer().getScoreboard();
if (scoreboard.getPlayerTeam(p_138915_) != null) {
throw ERROR_TEAM_ALREADY_EXISTS.create();
} else {
PlayerTeam playerteam = scoreboard.addPlayerTeam(p_138915_);
playerteam.setDisplayName(p_138916_);
p_138914_.sendSuccess(() -> {
return Component.translatable("commands.team.add.success", playerteam.getFormattedDisplayName());
}, true);
return scoreboard.getPlayerTeams().size();
}
}
private static int listMembers(CommandSourceStack p_138944_, PlayerTeam p_138945_) {
Collection<String> collection = p_138945_.getPlayers();
if (collection.isEmpty()) {
p_138944_.sendSuccess(() -> {
return Component.translatable("commands.team.list.members.empty", p_138945_.getFormattedDisplayName());
}, false);
} else {
p_138944_.sendSuccess(() -> {
return Component.translatable("commands.team.list.members.success", p_138945_.getFormattedDisplayName(), collection.size(), ComponentUtils.formatList(collection));
}, false);
}
return collection.size();
}
private static int listTeams(CommandSourceStack p_138882_) {
Collection<PlayerTeam> collection = p_138882_.getServer().getScoreboard().getPlayerTeams();
if (collection.isEmpty()) {
p_138882_.sendSuccess(() -> {
return Component.translatable("commands.team.list.teams.empty");
}, false);
} else {
p_138882_.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 p_138934_, PlayerTeam p_138935_, Component p_138936_) {
p_138935_.setPlayerPrefix(p_138936_);
p_138934_.sendSuccess(() -> {
return Component.translatable("commands.team.option.prefix.success", p_138936_);
}, false);
return 1;
}
private static int setSuffix(CommandSourceStack p_138947_, PlayerTeam p_138948_, Component p_138949_) {
p_138948_.setPlayerSuffix(p_138949_);
p_138947_.sendSuccess(() -> {
return Component.translatable("commands.team.option.suffix.success", p_138949_);
}, false);
return 1;
}
}

Some files were not shown because too many files have changed in this diff Show More