Migrate the Carpet codebase to Mojang Mappings

This commit is contained in:
altrisi committed 2022-01-24 20:33:16 +01:00
1 parent a1a2488bc3
commit 06af9ce8b1
346 files changed
+8353 -8492

No files matched your search

+7 -8
View File
@@ -3,10 +3,9 @@ package carpet;
import carpet.script.CarpetExpression;
import carpet.settings.SettingsManager;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import java.util.Map;
public interface CarpetExtension
@@ -50,7 +49,7 @@ public interface CarpetExtension
* where you should register your commands
*
*/
default void registerCommands(CommandDispatcher<ServerCommandSource> dispatcher) {}
default void registerCommands(CommandDispatcher<CommandSourceStack> dispatcher) {}
/**
* Provide your own custom settings manager managed in the same way as base /carpet
@@ -64,18 +63,18 @@ public interface CarpetExtension
/**
* Event that gets called when a player logs in
*
* @param player The {@link ServerPlayerEntity} that logged in
* @param player The {@link ServerPlayer} that logged in
*
*/
default void onPlayerLoggedIn(ServerPlayerEntity player) {}
default void onPlayerLoggedIn(ServerPlayer player) {}
/**
* Event that gets called when a player logs out
*
* @param player The {@link ServerPlayerEntity} that logged out
* @param player The {@link ServerPlayer} that logged out
*
*/
default void onPlayerLoggedOut(ServerPlayerEntity player) {}
default void onPlayerLoggedOut(ServerPlayer player) {}
/**
* Event that gets called when the server closes.
+14 -10
View File
@@ -1,5 +1,6 @@
package carpet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -27,16 +28,19 @@ import carpet.logging.HUDController;
import carpet.utils.FabricAPIHooks;
import carpet.utils.MobAI;
import carpet.utils.SpawnReporter;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import com.mojang.brigadier.CommandDispatcher;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.dedicated.command.PerfCommand;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.commands.PerfCommand;
import net.minecraft.server.level.ServerPlayer;
public class CarpetServer // static for now - easier to handle all around the code, its one anyways
{
@@ -45,7 +49,7 @@ public class CarpetServer // static for now - easier to handle all around the co
public static final Random rand = new Random();
public static MinecraftServer minecraft_server;
private static CommandDispatcher<ServerCommandSource> currentCommandDispatcher;
private static CommandDispatcher<CommandSourceStack> currentCommandDispatcher;
public static CarpetScriptServer scriptServer;
public static SettingsManager settingsManager;
public static final List<CarpetExtension> extensions = new ArrayList<>();
@@ -116,10 +120,10 @@ public class CarpetServer // static for now - easier to handle all around the co
}
@Deprecated
public static void registerCarpetCommands(CommandDispatcher<ServerCommandSource> dispatcher) {
public static void registerCarpetCommands(CommandDispatcher<CommandSourceStack> dispatcher) {
}
public static void registerCarpetCommands(CommandDispatcher<ServerCommandSource> dispatcher, CommandManager.RegistrationEnvironment environment)
public static void registerCarpetCommands(CommandDispatcher<CommandSourceStack> dispatcher, Commands.CommandSelection environment)
{
settingsManager.registerCommand(dispatcher);
extensions.forEach(e -> {
@@ -144,7 +148,7 @@ public class CarpetServer // static for now - easier to handle all around the co
extensions.forEach(e -> e.registerCommands(dispatcher));
currentCommandDispatcher = dispatcher;
if (environment != CommandManager.RegistrationEnvironment.DEDICATED)
if (environment != Commands.CommandSelection.DEDICATED)
PerfCommand.register(dispatcher);
if (FabricLoader.getInstance().isDevelopmentEnvironment())
@@ -152,7 +156,7 @@ public class CarpetServer // static for now - easier to handle all around the co
// todo 1.16 - re-registerer apps if that's a reload operation.
}
public static void onPlayerLoggedIn(ServerPlayerEntity player)
public static void onPlayerLoggedIn(ServerPlayer player)
{
ServerNetworkHandler.onPlayerJoin(player);
LoggerRegistry.playerConnected(player);
@@ -161,7 +165,7 @@ public class CarpetServer // static for now - easier to handle all around the co
}
public static void onPlayerLoggedOut(ServerPlayerEntity player)
public static void onPlayerLoggedOut(ServerPlayer player)
{
ServerNetworkHandler.onPlayerLoggedOut(player);
LoggerRegistry.playerDisconnected(player);
+46 -46
View File
@@ -8,19 +8,19 @@ import carpet.settings.Validator;
import carpet.utils.Translations;
import carpet.utils.Messenger;
import carpet.utils.SpawnChunks;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import net.minecraft.server.ServerInterface;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -55,7 +55,7 @@ public class CarpetSettings
public static int updateSuppressionBlockSetting = -1;
private static class LanguageValidator extends Validator<String> {
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string) {
@Override public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string) {
if (currentRule.get().equals(newValue) || source == null)
{
return newValue;
@@ -128,8 +128,8 @@ public class CarpetSettings
*/
private static class CarpetPermissionLevel extends Validator<String> {
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string) {
if (source == null || source.hasPermissionLevel(4))
@Override public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string) {
if (source == null || source.hasPermission(4))
return newValue;
return null;
}
@@ -173,7 +173,7 @@ public class CarpetSettings
private static class OneHourMaxDelayLimit extends Validator<Integer> {
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
return (newValue > 0 && newValue <= 72000) ? newValue : null;
}
@Override
@@ -208,7 +208,7 @@ public class CarpetSettings
public static class StackableShulkerBoxValidator extends Validator<String>
{
@Override
public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string)
public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string)
{
if (newValue.matches("^[0-9]+$")) {
int value = Integer.parseInt(newValue);
@@ -258,7 +258,7 @@ public class CarpetSettings
private static class CheckOptimizedTntEnabledValidator<T> extends Validator<T>
{
@Override
public T validate(ServerCommandSource source, ParsedRule<T> currentRule, T newValue, String string) {
public T validate(CommandSourceStack source, ParsedRule<T> currentRule, T newValue, String string) {
return optimizedTNT || currentRule.defaultValue.equals(newValue) ? newValue : null;
}
@@ -274,7 +274,7 @@ public class CarpetSettings
private static class TNTRandomRangeValidator extends Validator<Double> {
@Override
public Double validate(ServerCommandSource source, ParsedRule<Double> currentRule, Double newValue, String string) {
public Double validate(CommandSourceStack source, ParsedRule<Double> currentRule, Double newValue, String string) {
return newValue == -1 || newValue >= 0 ? newValue : null;
}
@@ -290,7 +290,7 @@ public class CarpetSettings
private static class TNTAngleValidator extends Validator<Double> {
@Override
public Double validate(ServerCommandSource source, ParsedRule<Double> currentRule, Double newValue, String string) {
public Double validate(CommandSourceStack source, ParsedRule<Double> currentRule, Double newValue, String string) {
return (newValue >= 0 && newValue < Math.PI * 2) || newValue == -1 ? newValue : null;
}
@@ -384,7 +384,7 @@ public class CarpetSettings
private static class ChainStoneSetting extends Validator<String> {
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string) {
@Override public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string) {
CarpetSettings.doChainStone = !newValue.toLowerCase(Locale.ROOT).equals("false");
CarpetSettings.chainStoneStickToAll = newValue.toLowerCase(Locale.ROOT).equals("stick_to_all");
@@ -481,9 +481,9 @@ public class CarpetSettings
public static String commandScript = "true";
private static class ModulePermissionLevel extends Validator<String> {
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string) {
@Override public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string) {
int permissionLevel = SettingsManager.getCommandLevel(newValue);
if (source != null && !source.hasPermissionLevel(permissionLevel))
if (source != null && !source.hasPermission(permissionLevel))
return null;
CarpetSettings.runPermissionLevel = permissionLevel;
CarpetServer.settingsManager.notifyPlayersCommandsChanged();
@@ -581,7 +581,7 @@ public class CarpetSettings
//public static boolean miningGhostBlockFix = false;
private static class PushLimitLimits extends Validator<Integer> {
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
return (newValue>0 && newValue <= 1024) ? newValue : null;
}
@Override
@@ -606,7 +606,7 @@ public class CarpetSettings
public static int railPowerLimit = 9;
private static class FillLimitLimits extends Validator<Integer> {
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
return (newValue>0 && newValue <= 20000000) ? newValue : null;
}
@Override
@@ -676,7 +676,7 @@ public class CarpetSettings
private static class ViewDistanceValidator extends Validator<Integer>
{
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string)
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string)
{
if (currentRule.get().equals(newValue) || source == null)
{
@@ -689,11 +689,11 @@ public class CarpetSettings
}
MinecraftServer server = source.getServer();
if (server.isDedicated())
if (server.isDedicatedServer())
{
int vd = (newValue >= 2)?newValue:((DedicatedServer) server).getProperties().viewDistance;
if (vd != server.getPlayerManager().getViewDistance())
server.getPlayerManager().setViewDistance(vd);
int vd = (newValue >= 2)?newValue:((ServerInterface) server).getProperties().viewDistance;
if (vd != server.getPlayerList().getViewDistance())
server.getPlayerList().setViewDistance(vd);
return newValue;
}
else
@@ -718,17 +718,17 @@ public class CarpetSettings
public static class ChangeSpawnChunksValidator extends Validator<Integer> {
public static void changeSpawnSize(int size)
{
ServerWorld overworld = CarpetServer.minecraft_server.getWorld(World.OVERWORLD); // OW
ServerLevel overworld = CarpetServer.minecraft_server.getLevel(Level.OVERWORLD); // OW
if (overworld != null) {
ChunkPos centerChunk = new ChunkPos(new BlockPos(
overworld.getLevelProperties().getSpawnX(),
overworld.getLevelProperties().getSpawnY(),
overworld.getLevelProperties().getSpawnZ()
overworld.getLevelData().getXSpawn(),
overworld.getLevelData().getYSpawn(),
overworld.getLevelData().getZSpawn()
));
SpawnChunks.changeSpawnChunks(overworld.getChunkManager(), centerChunk, size);
SpawnChunks.changeSpawnChunks(overworld.getChunkSource(), centerChunk, size);
}
}
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
if (source == null) return newValue;
if (newValue < 0 || newValue > 32)
{
@@ -741,7 +741,7 @@ public class CarpetSettings
return newValue;
}
if (CarpetServer.minecraft_server == null) return newValue;
ServerWorld currentOverworld = CarpetServer.minecraft_server.getWorld(World.OVERWORLD); // OW
ServerLevel currentOverworld = CarpetServer.minecraft_server.getLevel(Level.OVERWORLD); // OW
if (currentOverworld != null)
{
changeSpawnSize(newValue);
@@ -762,15 +762,15 @@ public class CarpetSettings
public static class LightBatchValidator extends Validator<Integer> {
public static void applyLightBatchSizes()
{
Iterator<ServerWorld> iterator = CarpetServer.minecraft_server.getWorlds().iterator();
Iterator<ServerLevel> iterator = CarpetServer.minecraft_server.getAllLevels().iterator();
while (iterator.hasNext())
{
ServerWorld serverWorld = iterator.next();
serverWorld.getChunkManager().getLightingProvider().setTaskBatchSize(lightEngineMaxBatchSize);
ServerLevel serverWorld = iterator.next();
serverWorld.getChunkSource().getLightEngine().setTaskPerBatch(lightEngineMaxBatchSize);
}
}
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
if (source == null) return newValue;
if (newValue < 0)
{
@@ -893,7 +893,7 @@ public class CarpetSettings
public static boolean isCreativeFlying(Entity entity)
{
// #todo replace after merger to 1.17
return CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying;
return CarpetSettings.creativeNoClip && entity instanceof Player && (((Player) entity).isCreative()) && ((Player) entity).getAbilities().flying;
}
@@ -938,7 +938,7 @@ public class CarpetSettings
public static class StructureBlockLimitValidator extends Validator<Integer> {
@Override public Integer validate(ServerCommandSource source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
@Override public Integer validate(CommandSourceStack source, ParsedRule<Integer> currentRule, Integer newValue, String string) {
return (newValue >= vanillaStructureBlockLimit) ? newValue : null;
}
@@ -965,8 +965,8 @@ public class CarpetSettings
public static class StructureBlockIgnoredValidator extends Validator<String> {
@Override
public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string) {
Optional<Block> ignoredBlock = Registry.BLOCK.getOrEmpty(Identifier.tryParse(newValue));
public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string) {
Optional<Block> ignoredBlock = Registry.BLOCK.getOptional(ResourceLocation.tryParse(newValue));
if (!ignoredBlock.isPresent()) {
Messenger.m(source, "r Unknown block '" + newValue + "'.");
return null;
@@ -1027,7 +1027,7 @@ public class CarpetSettings
private static class updateSuppressionBlockModes extends Validator<String> {
@Override
public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string) {
public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string) {
if (!currentRule.get().equals(newValue)) {
if (newValue.equalsIgnoreCase("false")) {
updateSuppressionBlockSetting = -1;
@@ -5,11 +5,11 @@ import carpet.helpers.HopperCounter;
import carpet.utils.Messenger;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.command.CommandException;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.command.CommandManager;
import net.minecraft.util.DyeColor;
import net.minecraft.text.BaseText;
import net.minecraft.commands.CommandRuntimeException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.world.item.DyeColor;
/**
* Class for the /counter command which allows to use hoppers pointing into wool
@@ -20,25 +20,25 @@ public class CounterCommand
/**
* The method used to register the command and make it available for the players to use.
*/
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> literalargumentbuilder = CommandManager.literal("counter").executes((context)
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = Commands.literal("counter").executes((context)
-> listAllCounters(context.getSource(), false)).requires((player) ->
CarpetSettings.hopperCounters);
literalargumentbuilder.
then((CommandManager.literal("reset").executes( (p_198489_1_)->
then((Commands.literal("reset").executes( (p_198489_1_)->
resetCounter(p_198489_1_.getSource(), null))));
for (DyeColor enumDyeColor: DyeColor.values())
{
String color = enumDyeColor.toString();
literalargumentbuilder.
then((CommandManager.literal(color).executes( (p_198489_1_)-> displayCounter(p_198489_1_.getSource(), color, false))));
literalargumentbuilder.then(CommandManager.literal(color).
then(CommandManager.literal("reset").executes((context) ->
then((Commands.literal(color).executes( (p_198489_1_)-> displayCounter(p_198489_1_.getSource(), color, false))));
literalargumentbuilder.then(Commands.literal(color).
then(Commands.literal("reset").executes((context) ->
resetCounter(context.getSource(), color))));
literalargumentbuilder.then(CommandManager.literal(color).
then(CommandManager.literal("realtime").executes((context) ->
literalargumentbuilder.then(Commands.literal(color).
then(Commands.literal("realtime").executes((context) ->
displayCounter(context.getSource(), color, true))));
}
dispatcher.register(literalargumentbuilder);
@@ -51,14 +51,14 @@ public class CounterCommand
* would make it slower than IRL
*/
private static int displayCounter(ServerCommandSource source, String color, boolean realtime)
private static int displayCounter(CommandSourceStack source, String color, boolean realtime)
{
HopperCounter counter = HopperCounter.getCounter(color);
if (counter == null) throw new CommandException(Messenger.s("Unknown wool color: "+color));
if (counter == null) throw new CommandRuntimeException(Messenger.s("Unknown wool color: "+color));
for (BaseText message: counter.format(source.getServer(), realtime, false))
for (BaseComponent message: counter.format(source.getServer(), realtime, false))
{
source.sendFeedback(message, false);
source.sendSuccess(message, false);
}
return 1;
}
@@ -68,7 +68,7 @@ public class CounterCommand
* it will reset all counters.
* @param color The counter whose contents we want to reset
*/
private static int resetCounter(ServerCommandSource source, String color)
private static int resetCounter(CommandSourceStack source, String color)
{
if (color == null)
{
@@ -78,7 +78,7 @@ public class CounterCommand
else
{
HopperCounter counter = HopperCounter.getCounter(color);
if (counter == null) throw new CommandException(Messenger.s("Unknown wool color"));
if (counter == null) throw new CommandRuntimeException(Messenger.s("Unknown wool color"));
counter.reset(source.getServer());
Messenger.m(source, "w Restarted "+color+" counter");
}
@@ -90,11 +90,11 @@ public class CounterCommand
* @param realtime Whether or not to display it as in-game time or IRL time, which accounts for less than 20TPS which
* would make it slower than IRL
*/
private static int listAllCounters(ServerCommandSource source, boolean realtime)
private static int listAllCounters(CommandSourceStack source, boolean realtime)
{
for (BaseText message: HopperCounter.formatAll(source.getServer(), realtime))
for (BaseComponent message: HopperCounter.formatAll(source.getServer(), realtime))
{
source.sendFeedback(message, false);
source.sendSuccess(message, false);
}
return 1;
}
@@ -5,39 +5,39 @@ import carpet.settings.SettingsManager;
import carpet.utils.DistanceCalculator;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.command.argument.Vec3ArgumentType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
public class DistanceCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> command = literal("distance").
LiteralArgumentBuilder<CommandSourceStack> command = literal("distance").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandDistance)).
then(literal("from").
executes( (c) -> DistanceCalculator.setStart(c.getSource(), c.getSource().getPosition())).
then(argument("from", Vec3ArgumentType.vec3()).
then(argument("from", Vec3Argument.vec3()).
executes( (c) -> DistanceCalculator.setStart(
c.getSource(),
Vec3ArgumentType.getVec3(c, "from"))).
Vec3Argument.getVec3(c, "from"))).
then(literal("to").
executes((c) -> DistanceCalculator.distance(
c.getSource(),
Vec3ArgumentType.getVec3(c, "from"),
Vec3Argument.getVec3(c, "from"),
c.getSource().getPosition())).
then(argument("to", Vec3ArgumentType.vec3()).
then(argument("to", Vec3Argument.vec3()).
executes( (c) -> DistanceCalculator.distance(
c.getSource(),
Vec3ArgumentType.getVec3(c, "from"),
Vec3ArgumentType.getVec3(c, "to")
Vec3Argument.getVec3(c, "from"),
Vec3Argument.getVec3(c, "to")
)))))).
then(literal("to").
executes( (c) -> DistanceCalculator.setEnd(c.getSource(), c.getSource().getPosition()) ).
then(argument("to", Vec3ArgumentType.vec3()).
executes( (c) -> DistanceCalculator.setEnd(c.getSource(), Vec3ArgumentType.getVec3(c, "to")))));
then(argument("to", Vec3Argument.vec3()).
executes( (c) -> DistanceCalculator.setEnd(c.getSource(), Vec3Argument.getVec3(c, "to")))));
dispatcher.register(command);
}
}
+87 -88
View File
@@ -12,70 +12,69 @@ import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.block.Block;
import net.minecraft.block.pattern.CachedBlockPosition;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.command.argument.BlockPredicateArgumentType;
import net.minecraft.command.argument.BlockStateArgument;
import net.minecraft.command.argument.BlockStateArgumentType;
import net.minecraft.inventory.Inventory;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.MathHelper;
import java.util.List;
import java.util.function.Predicate;
import net.minecraft.commands.CommandSourceStack;
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.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.Container;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import java.lang.Math;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class DrawCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> command = literal("draw").
LiteralArgumentBuilder<CommandSourceStack> command = literal("draw").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandDraw)).
then(literal("sphere").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(drawShape(c -> DrawCommand.drawSphere(c, false)))))).
then(literal("ball").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(drawShape(c -> DrawCommand.drawSphere(c, true)))))).
then(literal("diamond").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(drawShape(c -> DrawCommand.drawDiamond(c, true)))))).
then(literal("pyramid").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(argument("height",IntegerArgumentType.integer(1)).
then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"up","down"},b)).
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b)).
then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"up","down"},b)).
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b)).
then(drawShape(c -> DrawCommand.drawPyramid(c, "square", true))))))))).
then(literal("cone").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(argument("height",IntegerArgumentType.integer(1)).
then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"up","down"},b)).
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b))
then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"up","down"},b)).
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b))
.then(drawShape(c -> DrawCommand.drawPyramid(c, "circle", true))))))))).
then(literal("cylinder").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(argument("height",IntegerArgumentType.integer(1)).
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b))
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b))
.then(drawShape(c -> DrawCommand.drawPrism(c, "circle")))))))).
then(literal("cuboid").
then(argument("center", BlockPosArgumentType.blockPos()).
then(argument("center", BlockPosArgument.blockPos()).
then(argument("radius", IntegerArgumentType.integer(1)).
then(argument("height",IntegerArgumentType.integer(1)).
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b))
then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b))
.then(drawShape(c -> DrawCommand.drawPrism(c, "square"))))))));
dispatcher.register(command);
}
@@ -83,33 +82,33 @@ public class DrawCommand
@FunctionalInterface
private interface OptionalBlockSelector
{
Integer apply(final CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException;
Integer apply(final CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException;
}
@FunctionalInterface
private interface ArgumentExtractor<T>
{
T apply(final CommandContext<ServerCommandSource> ctx, final String argName) throws CommandSyntaxException;
T apply(final CommandContext<CommandSourceStack> ctx, final String argName) throws CommandSyntaxException;
}
private static RequiredArgumentBuilder<ServerCommandSource, BlockStateArgument>
private static RequiredArgumentBuilder<CommandSourceStack, BlockInput>
drawShape(OptionalBlockSelector drawer)
{
return argument("block", BlockStateArgumentType.blockState()).
return argument("block", BlockStateArgument.block()).
executes(drawer::apply)
.then(literal("replace")
.then(argument("filter", BlockPredicateArgumentType.blockPredicate())
.then(argument("filter", BlockPredicateArgument.blockPredicate())
.executes(drawer::apply)));
}
private static class ErrorHandled extends RuntimeException {}
private static <T> T getArg(CommandContext<ServerCommandSource> ctx, ArgumentExtractor<T> extract, String hwat) throws CommandSyntaxException
private static <T> T getArg(CommandContext<CommandSourceStack> ctx, ArgumentExtractor<T> extract, String hwat) throws CommandSyntaxException
{
return getArg(ctx, extract, hwat, false);
}
private static <T> T getArg(CommandContext<ServerCommandSource> ctx, ArgumentExtractor<T> extract, String hwat, boolean optional) throws CommandSyntaxException
private static <T> T getArg(CommandContext<CommandSourceStack> ctx, ArgumentExtractor<T> extract, String hwat, boolean optional) throws CommandSyntaxException
{
T arg = null;
try
@@ -131,23 +130,23 @@ public class DrawCommand
}
private static int setBlock(
ServerWorld world, BlockPos.Mutable mbpos, int x, int y, int z,
BlockStateArgument block, Predicate<CachedBlockPosition> replacement,
ServerLevel world, BlockPos.MutableBlockPos mbpos, int x, int y, int z,
BlockInput block, Predicate<BlockInWorld> replacement,
List<BlockPos> list
)
{
mbpos.set(x, y, z);
int success=0;
if (replacement == null || replacement.test(new CachedBlockPosition(world, mbpos, true)))
if (replacement == null || replacement.test(new BlockInWorld(world, mbpos, true)))
{
BlockEntity tileentity = world.getBlockEntity(mbpos);
if (tileentity instanceof Inventory)
if (tileentity instanceof Container)
{
((Inventory) tileentity).clear();
((Container) tileentity).clearContent();
}
if (block.setBlockState(world, mbpos, 2))
if (block.place(world, mbpos, 2))
{
list.add(mbpos.toImmutable());
list.add(mbpos.immutable());
++success;
}
}
@@ -155,23 +154,23 @@ public class DrawCommand
return success;
}
private static int drawSphere(CommandContext<ServerCommandSource> ctx, boolean solid) throws CommandSyntaxException
private static int drawSphere(CommandContext<CommandSourceStack> ctx, boolean solid) throws CommandSyntaxException
{
BlockPos pos;
int radius;
BlockStateArgument block;
Predicate<CachedBlockPosition> replacement;
BlockInput block;
Predicate<BlockInWorld> replacement;
try
{
pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center");
pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center");
radius = getArg(ctx, IntegerArgumentType::getInteger, "radius");
block = getArg(ctx, BlockStateArgumentType::getBlockState, "block");
replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true);
block = getArg(ctx, BlockStateArgument::getBlock, "block");
replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true);
}
catch (ErrorHandled ignored) { return 0; }
int affected = 0;
ServerWorld world = ctx.getSource().getWorld();
ServerLevel world = ctx.getSource().getLevel();
double radiusX = radius+0.5;
double radiusY = radius+0.5;
@@ -185,7 +184,7 @@ public class DrawCommand
final int ceilRadiusY = (int) Math.ceil(radiusY);
final int ceilRadiusZ = (int) Math.ceil(radiusZ);
BlockPos.Mutable mbpos = pos.mutableCopy();
BlockPos.MutableBlockPos mbpos = pos.mutable();
List<BlockPos> list = Lists.newArrayList();
double nextXn = 0;
@@ -244,35 +243,35 @@ public class DrawCommand
}
if (CarpetSettings.fillUpdates)
{
list.forEach(blockpos1 -> world.updateNeighbors(blockpos1, world.getBlockState(blockpos1).getBlock()));
list.forEach(blockpos1 -> world.blockUpdated(blockpos1, world.getBlockState(blockpos1).getBlock()));
}
Messenger.m(ctx.getSource(), "gi Filled " + affected + " blocks");
return affected;
}
private static int drawDiamond(CommandContext<ServerCommandSource> ctx, boolean solid) throws CommandSyntaxException
private static int drawDiamond(CommandContext<CommandSourceStack> ctx, boolean solid) throws CommandSyntaxException
{
BlockPos pos;
int radius;
BlockStateArgument block;
Predicate<CachedBlockPosition> replacement;
BlockInput block;
Predicate<BlockInWorld> replacement;
try
{
pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center");
pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center");
radius = getArg(ctx, IntegerArgumentType::getInteger, "radius");
block = getArg(ctx, BlockStateArgumentType::getBlockState, "block");
replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true);
block = getArg(ctx, BlockStateArgument::getBlock, "block");
replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true);
}
catch (ErrorHandled ignored) { return 0; }
ServerCommandSource source = ctx.getSource();
CommandSourceStack source = ctx.getSource();
int affected=0;
BlockPos.Mutable mbpos = pos.mutableCopy();
BlockPos.MutableBlockPos mbpos = pos.mutable();
List<BlockPos> list = Lists.newArrayList();
ServerWorld world = source.getWorld();
ServerLevel world = source.getLevel();
CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates);
@@ -294,7 +293,7 @@ public class DrawCommand
if (CarpetSettings.fillUpdates)
{
list.forEach(p -> world.updateNeighbors(p, world.getBlockState(p).getBlock()));
list.forEach(p -> world.blockUpdated(p, world.getBlockState(p).getBlock()));
}
Messenger.m(source, "gi Filled " + affected + " blocks");
@@ -303,13 +302,13 @@ public class DrawCommand
}
private static int fillFlat(
ServerWorld world, BlockPos pos, int offset, double dr, boolean rectangle, String orientation,
BlockStateArgument block, Predicate<CachedBlockPosition> replacement,
List<BlockPos> list, BlockPos.Mutable mbpos
ServerLevel world, BlockPos pos, int offset, double dr, boolean rectangle, String orientation,
BlockInput block, Predicate<BlockInWorld> replacement,
List<BlockPos> list, BlockPos.MutableBlockPos mbpos
)
{
int successes=0;
int r = MathHelper.floor(dr);
int r = Mth.floor(dr);
double drsq = dr*dr;
if (orientation.equalsIgnoreCase("x"))
{
@@ -347,35 +346,35 @@ public class DrawCommand
return 0;
}
private static int drawPyramid(CommandContext<ServerCommandSource> ctx, String base, boolean solid) throws CommandSyntaxException
private static int drawPyramid(CommandContext<CommandSourceStack> ctx, String base, boolean solid) throws CommandSyntaxException
{
BlockPos pos;
double radius;
int height;
boolean pointup;
String orientation;
BlockStateArgument block;
Predicate<CachedBlockPosition> replacement;
BlockInput block;
Predicate<BlockInWorld> replacement;
try
{
pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center");
pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center");
radius = getArg(ctx, IntegerArgumentType::getInteger, "radius")+0.5D;
height = getArg(ctx, IntegerArgumentType::getInteger, "height");
pointup = getArg(ctx, StringArgumentType::getString, "pointing").equalsIgnoreCase("up");
orientation = getArg(ctx, StringArgumentType::getString,"orientation");
block = getArg(ctx, BlockStateArgumentType::getBlockState, "block");
replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true);
block = getArg(ctx, BlockStateArgument::getBlock, "block");
replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true);
}
catch (ErrorHandled ignored) { return 0; }
ServerCommandSource source = ctx.getSource();
CommandSourceStack source = ctx.getSource();
int affected = 0;
BlockPos.Mutable mbpos = pos.mutableCopy();
BlockPos.MutableBlockPos mbpos = pos.mutable();
List<BlockPos> list = Lists.newArrayList();
ServerWorld world = source.getWorld();
ServerLevel world = source.getLevel();
CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates);
@@ -393,7 +392,7 @@ public class DrawCommand
for (BlockPos blockpos1 : list) {
Block blokc = world.getBlockState(blockpos1).getBlock();
world.updateNeighbors(blockpos1, blokc);
world.blockUpdated(blockpos1, blokc);
}
}
@@ -402,32 +401,32 @@ public class DrawCommand
return affected;
}
private static int drawPrism(CommandContext<ServerCommandSource> ctx, String base){
private static int drawPrism(CommandContext<CommandSourceStack> ctx, String base){
BlockPos pos;
double radius;
int height;
String orientation;
BlockStateArgument block;
Predicate<CachedBlockPosition> replacement;
BlockInput block;
Predicate<BlockInWorld> replacement;
try
{
pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center");
pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center");
radius = getArg(ctx, IntegerArgumentType::getInteger, "radius")+0.5D;
height = getArg(ctx, IntegerArgumentType::getInteger, "height");
orientation = getArg(ctx, StringArgumentType::getString,"orientation");
block = getArg(ctx, BlockStateArgumentType::getBlockState, "block");
replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true);
block = getArg(ctx, BlockStateArgument::getBlock, "block");
replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true);
}
catch (ErrorHandled | CommandSyntaxException ignored) { return 0; }
ServerCommandSource source = ctx.getSource();
CommandSourceStack source = ctx.getSource();
int affected = 0;
BlockPos.Mutable mbpos = pos.mutableCopy();
BlockPos.MutableBlockPos mbpos = pos.mutable();
List<BlockPos> list = Lists.newArrayList();
ServerWorld world = source.getWorld();
ServerLevel world = source.getLevel();
CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates);
@@ -444,7 +443,7 @@ public class DrawCommand
for (BlockPos blockpos1 : list) {
Block blokc = world.getBlockState(blockpos1).getBlock();
world.updateNeighbors(blockpos1, blokc);
world.blockUpdated(blockpos1, blokc);
}
}
+15 -16
View File
@@ -6,42 +6,41 @@ import carpet.utils.BlockInfo;
import carpet.utils.Messenger;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.text.BaseText;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.util.math.BlockPos;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.BaseComponent;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
public class InfoCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> command = literal("info").
LiteralArgumentBuilder<CommandSourceStack> command = literal("info").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandInfo)).
then(literal("block").
then(argument("block position", BlockPosArgumentType.blockPos()).
then(argument("block position", BlockPosArgument.blockPos()).
executes( (c) -> infoBlock(
c.getSource(),
BlockPosArgumentType.getBlockPos(c, "block position"), null)).
BlockPosArgument.getSpawnablePos(c, "block position"), null)).
then(literal("grep").
then(argument("regexp",greedyString()).
executes( (c) -> infoBlock(
c.getSource(),
BlockPosArgumentType.getBlockPos(c, "block position"),
BlockPosArgument.getSpawnablePos(c, "block position"),
getString(c, "regexp")))))));
dispatcher.register(command);
}
public static void printBlock(List<BaseText> messages, ServerCommandSource source, String grep)
public static void printBlock(List<BaseComponent> messages, CommandSourceStack source, String grep)
{
Messenger.m(source, "");
if (grep != null)
@@ -50,7 +49,7 @@ public class InfoCommand
Messenger.m(source, messages.get(0));
for (int i = 1; i<messages.size(); i++)
{
BaseText line = messages.get(i);
BaseComponent line = messages.get(i);
Matcher m = p.matcher(line.getString());
if (m.find())
{
@@ -64,9 +63,9 @@ public class InfoCommand
}
}
private static int infoBlock(ServerCommandSource source, BlockPos pos, String grep)
private static int infoBlock(CommandSourceStack source, BlockPos pos, String grep)
{
printBlock(BlockInfo.blockInfo(pos, source.getWorld()),source, grep);
printBlock(BlockInfo.blockInfo(pos, source.getLevel()),source, grep);
return 1;
}
+32 -33
View File
@@ -9,54 +9,53 @@ import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.command.CommandManager;
import net.minecraft.entity.player.PlayerEntity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.world.entity.player.Player;
import java.util.Arrays;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class LogCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> literalargumentbuilder = CommandManager.literal("log").
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = Commands.literal("log").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandLog)).
executes((context) -> listLogs(context.getSource())).
then(CommandManager.literal("clear").
executes( (c) -> unsubFromAll(c.getSource(), c.getSource().getName())).
then(CommandManager.argument("player", StringArgumentType.word()).
suggests( (c, b)-> suggestMatching(c.getSource().getPlayerNames(),b)).
then(Commands.literal("clear").
executes( (c) -> unsubFromAll(c.getSource(), c.getSource().getTextName())).
then(Commands.argument("player", StringArgumentType.word()).
suggests( (c, b)-> suggest(c.getSource().getOnlinePlayerNames(),b)).
executes( (c) -> unsubFromAll(c.getSource(), getString(c, "player")))));
literalargumentbuilder.then(CommandManager.argument("log name",StringArgumentType.word()).
suggests( (c, b)-> suggestMatching(LoggerRegistry.getLoggerNames(),b)).
executes( (c)-> toggleSubscription(c.getSource(), c.getSource().getName(), getString(c, "log name"))).
then(CommandManager.literal("clear").
literalargumentbuilder.then(Commands.argument("log name",StringArgumentType.word()).
suggests( (c, b)-> suggest(LoggerRegistry.getLoggerNames(),b)).
executes( (c)-> toggleSubscription(c.getSource(), c.getSource().getTextName(), getString(c, "log name"))).
then(Commands.literal("clear").
executes( (c) -> unsubFromLogger(
c.getSource(),
c.getSource().getName(),
c.getSource().getTextName(),
getString(c, "log name")))).
then(CommandManager.argument("option", StringArgumentType.string()).
suggests( (c, b) -> suggestMatching(
then(Commands.argument("option", StringArgumentType.string()).
suggests( (c, b) -> suggest(
(LoggerRegistry.getLogger(getString(c, "log name"))==null
?new String[]{}
:LoggerRegistry.getLogger(getString(c, "log name")).getOptions()),
b)).
executes( (c) -> subscribePlayer(
c.getSource(),
c.getSource().getName(),
c.getSource().getTextName(),
getString(c, "log name"),
getString(c, "option"))).
then(CommandManager.argument("player", StringArgumentType.word()).
suggests( (c, b) -> suggestMatching(c.getSource().getPlayerNames(),b)).
then(Commands.argument("player", StringArgumentType.word()).
suggests( (c, b) -> suggest(c.getSource().getOnlinePlayerNames(),b)).
executes( (c) -> subscribePlayer(
c.getSource(),
getString(c, "player"),
@@ -65,19 +64,19 @@ public class LogCommand
dispatcher.register(literalargumentbuilder);
}
private static int listLogs(ServerCommandSource source)
private static int listLogs(CommandSourceStack source)
{
PlayerEntity player;
Player player;
try
{
player = source.getPlayer();
player = source.getPlayerOrException();
}
catch (CommandSyntaxException e)
{
Messenger.m(source, "For players only");
return 0;
}
Map<String,String> subs = LoggerRegistry.getPlayerSubscriptions(source.getName());
Map<String,String> subs = LoggerRegistry.getPlayerSubscriptions(source.getTextName());
if (subs == null)
{
subs = new HashMap<>();
@@ -132,9 +131,9 @@ public class LogCommand
}
return 1;
}
private static int unsubFromAll(ServerCommandSource source, String player_name)
private static int unsubFromAll(CommandSourceStack source, String player_name)
{
PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name);
Player player = source.getServer().getPlayerList().getPlayerByName(player_name);
if (player == null)
{
Messenger.m(source, "r No player specified");
@@ -147,9 +146,9 @@ public class LogCommand
Messenger.m(source, "gi Unsubscribed from all logs");
return 1;
}
private static int unsubFromLogger(ServerCommandSource source, String player_name, String logname)
private static int unsubFromLogger(CommandSourceStack source, String player_name, String logname)
{
PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name);
Player player = source.getServer().getPlayerList().getPlayerByName(player_name);
if (player == null)
{
Messenger.m(source, "r No player specified");
@@ -165,9 +164,9 @@ public class LogCommand
return 1;
}
private static int toggleSubscription(ServerCommandSource source, String player_name, String logName)
private static int toggleSubscription(CommandSourceStack source, String player_name, String logName)
{
PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name);
Player player = source.getServer().getPlayerList().getPlayerByName(player_name);
if (player == null)
{
Messenger.m(source, "r No player specified");
@@ -189,9 +188,9 @@ public class LogCommand
}
return 1;
}
private static int subscribePlayer(ServerCommandSource source, String player_name, String logname, String option)
private static int subscribePlayer(CommandSourceStack source, String player_name, String logname, String option)
{
PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name);
Player player = source.getServer().getPlayerList().getPlayerByName(player_name);
if (player == null)
{
Messenger.m(source, "r No player specified");
+13 -13
View File
@@ -6,34 +6,34 @@ import carpet.utils.MobAI;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.command.argument.EntitySummonArgumentType;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.registry.Registry;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.EntitySummonArgument;
import net.minecraft.core.Registry;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class MobAICommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> command = literal("track").
LiteralArgumentBuilder<CommandSourceStack> command = literal("track").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandTrackAI)).
then(argument("entity type", EntitySummonArgumentType.entitySummon()).
then(argument("entity type", EntitySummonArgument.id()).
suggests( (c, b) -> suggestMatching(MobAI.availbleTypes(), b)).
suggests( (c, b) -> suggest(MobAI.availbleTypes(), b)).
then(literal("clear").executes( (c) ->
{
MobAI.clearTracking(Registry.ENTITY_TYPE.get(EntitySummonArgumentType.getEntitySummon(c, "entity type")));
MobAI.clearTracking(Registry.ENTITY_TYPE.get(EntitySummonArgument.getSummonableEntity(c, "entity type")));
return 1;
}
)).
then(argument("aspect", StringArgumentType.word()).
suggests( (c, b) -> suggestMatching(MobAI.availableFor(Registry.ENTITY_TYPE.get(EntitySummonArgumentType.getEntitySummon(c, "entity type"))),b)).
suggests( (c, b) -> suggest(MobAI.availableFor(Registry.ENTITY_TYPE.get(EntitySummonArgument.getSummonableEntity(c, "entity type"))),b)).
executes( (c) -> {
MobAI.startTracking(
Registry.ENTITY_TYPE.get(EntitySummonArgumentType.getEntitySummon(c, "entity type")),
Registry.ENTITY_TYPE.get(EntitySummonArgument.getSummonableEntity(c, "entity type")),
MobAI.TrackingType.byName(StringArgumentType.getString(c, "aspect"))
);
return 1;
@@ -6,64 +6,64 @@ import carpet.utils.Messenger;
import carpet.utils.PerimeterDiagnostics;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.command.suggestion.SuggestionProviders;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.command.argument.EntitySummonArgumentType;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.EntitySummonArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
public class PerimeterInfoCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> command = literal("perimeterinfo").
LiteralArgumentBuilder<CommandSourceStack> command = literal("perimeterinfo").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandPerimeterInfo)).
executes( (c) -> perimeterDiagnose(
c.getSource(),
new BlockPos(c.getSource().getPosition()),
null)).
then(argument("center position", BlockPosArgumentType.blockPos()).
then(argument("center position", BlockPosArgument.blockPos()).
executes( (c) -> perimeterDiagnose(
c.getSource(),
BlockPosArgumentType.getBlockPos(c, "center position"),
BlockPosArgument.getSpawnablePos(c, "center position"),
null)).
then(argument("mob",EntitySummonArgumentType.entitySummon()).
then(argument("mob",EntitySummonArgument.id()).
suggests(SuggestionProviders.SUMMONABLE_ENTITIES).
executes( (c) -> perimeterDiagnose(
c.getSource(),
BlockPosArgumentType.getBlockPos(c, "center position"),
EntitySummonArgumentType.getEntitySummon(c, "mob").toString()
BlockPosArgument.getSpawnablePos(c, "center position"),
EntitySummonArgument.getSummonableEntity(c, "mob").toString()
))));
dispatcher.register(command);
}
private static int perimeterDiagnose(ServerCommandSource source, BlockPos pos, String mobId)
private static int perimeterDiagnose(CommandSourceStack source, BlockPos pos, String mobId)
{
NbtCompound nbttagcompound = new NbtCompound();
MobEntity entityliving = null;
CompoundTag nbttagcompound = new CompoundTag();
Mob entityliving = null;
if (mobId != null)
{
nbttagcompound.putString("id", mobId);
Entity baseEntity = EntityType.loadEntityWithPassengers(nbttagcompound, source.getWorld(), (entity_1x) -> {
entity_1x.refreshPositionAndAngles(new BlockPos(pos.getX(), source.getWorld().getBottomY()-10, pos.getZ()), entity_1x.getYaw(), entity_1x. getPitch());
return !source.getWorld().tryLoadEntity(entity_1x) ? null : entity_1x;
Entity baseEntity = EntityType.loadEntityRecursive(nbttagcompound, source.getLevel(), (entity_1x) -> {
entity_1x.moveTo(new BlockPos(pos.getX(), source.getLevel().getMinBuildHeight()-10, pos.getZ()), entity_1x.getYRot(), entity_1x. getXRot());
return !source.getLevel().addWithUUID(entity_1x) ? null : entity_1x;
});
if (!(baseEntity instanceof MobEntity))
if (!(baseEntity instanceof Mob))
{
Messenger.m(source, "r /perimeterinfo requires a mob entity to test agains.");
if (baseEntity != null) baseEntity.discard();
return 0;
}
entityliving = (MobEntity) baseEntity;
entityliving = (Mob) baseEntity;
}
PerimeterDiagnostics.Result res = PerimeterDiagnostics.countSpots(source.getWorld(), pos, entityliving);
PerimeterDiagnostics.Result res = PerimeterDiagnostics.countSpots(source.getLevel(), pos, entityliving);
Messenger.m(source, "w Spawning spaces around ",Messenger.tp("c",pos), "w :");
Messenger.m(source, "w potential in-liquid: ","wb "+res.liquid);
@@ -15,46 +15,45 @@ import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.argument.DimensionArgumentType;
import net.minecraft.command.argument.RotationArgumentType;
import net.minecraft.command.argument.Vec3ArgumentType;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.DimensionArgument;
import net.minecraft.commands.arguments.coordinates.RotationArgument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec2f;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.GameMode;
import net.minecraft.world.World;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class PlayerCommand
{
// TODO: allow any order like execute
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
final String[] gamemodeStrings = Arrays.stream(GameMode.values())
.map(GameMode::getName)
final String[] gamemodeStrings = Arrays.stream(GameType.values())
.map(GameType::getName)
.collect(Collectors.toList())
.toArray(new String[]{});
LiteralArgumentBuilder<ServerCommandSource> literalargumentbuilder = literal("player")
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = literal("player")
.requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandPlayer))
.then(argument("player", StringArgumentType.word())
.suggests( (c, b) -> suggestMatching(getPlayers(c.getSource()), b))
.suggests( (c, b) -> suggest(getPlayers(c.getSource()), b))
.then(literal("stop").executes(PlayerCommand::stop))
.then(makeActionCommand("use", EntityPlayerActionPack.ActionType.USE))
.then(makeActionCommand("jump", EntityPlayerActionPack.ActionType.JUMP))
@@ -83,30 +82,30 @@ public class PlayerCommand
.then(literal("west").executes(manipulation(ap -> ap.look(Direction.WEST))))
.then(literal("up").executes(manipulation(ap -> ap.look(Direction.UP))))
.then(literal("down").executes(manipulation(ap -> ap.look(Direction.DOWN))))
.then(literal("at").then(argument("position", Vec3ArgumentType.vec3()).executes(PlayerCommand::lookAt)))
.then(argument("direction", RotationArgumentType.rotation())
.executes(c -> manipulate(c, ap -> ap.look(RotationArgumentType.getRotation(c, "direction").toAbsoluteRotation(c.getSource())))))
.then(literal("at").then(argument("position", Vec3Argument.vec3()).executes(PlayerCommand::lookAt)))
.then(argument("direction", RotationArgument.rotation())
.executes(c -> manipulate(c, ap -> ap.look(RotationArgument.getRotation(c, "direction").getRotation(c.getSource())))))
).then(literal("turn")
.then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(-90, 0))))
.then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(90, 0))))
.then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(180, 0))))
.then(argument("rotation", RotationArgumentType.rotation())
.executes(c -> manipulate(c, ap -> ap.turn(RotationArgumentType.getRotation(c, "rotation").toAbsoluteRotation(c.getSource())))))
.then(argument("rotation", RotationArgument.rotation())
.executes(c -> manipulate(c, ap -> ap.turn(RotationArgument.getRotation(c, "rotation").getRotation(c.getSource())))))
).then(literal("move").executes(c -> manipulate(c, EntityPlayerActionPack::stopMovement))
.then(literal("forward").executes(c -> manipulate(c, ap -> ap.setForward(1))))
.then(literal("backward").executes(c -> manipulate(c, ap -> ap.setForward(-1))))
.then(literal("left").executes(c -> manipulate(c, ap -> ap.setStrafing(1))))
.then(literal("right").executes(c -> manipulate(c, ap -> ap.setStrafing(-1))))
).then(literal("spawn").executes(PlayerCommand::spawn)
.then(literal("in").requires((player) -> player.hasPermissionLevel(2))
.then(literal("in").requires((player) -> player.hasPermission(2))
.then(argument("gamemode", StringArgumentType.word())
.suggests( (c, b) -> suggestMatching(gamemodeStrings, b))
.suggests( (c, b) -> suggest(gamemodeStrings, b))
.executes(PlayerCommand::spawn)))
.then(literal("at").then(argument("position", Vec3ArgumentType.vec3()).executes(PlayerCommand::spawn)
.then(literal("facing").then(argument("direction", RotationArgumentType.rotation()).executes(PlayerCommand::spawn)
.then(literal("in").then(argument("dimension", DimensionArgumentType.dimension()).executes(PlayerCommand::spawn)
.then(literal("in").requires((player) -> player.hasPermissionLevel(2))
.then(argument("gamemode", StringArgumentType.word()).suggests( (c, b) -> suggestMatching(gamemodeStrings, b))
.then(literal("at").then(argument("position", Vec3Argument.vec3()).executes(PlayerCommand::spawn)
.then(literal("facing").then(argument("direction", RotationArgument.rotation()).executes(PlayerCommand::spawn)
.then(literal("in").then(argument("dimension", DimensionArgument.dimension()).executes(PlayerCommand::spawn)
.then(literal("in").requires((player) -> player.hasPermission(2))
.then(argument("gamemode", StringArgumentType.word()).suggests( (c, b) -> suggest(gamemodeStrings, b))
.executes(PlayerCommand::spawn)
)))
)))
@@ -116,7 +115,7 @@ public class PlayerCommand
dispatcher.register(literalargumentbuilder);
}
private static LiteralArgumentBuilder<ServerCommandSource> makeActionCommand(String actionName, EntityPlayerActionPack.ActionType type)
private static LiteralArgumentBuilder<CommandSourceStack> makeActionCommand(String actionName, EntityPlayerActionPack.ActionType type)
{
return literal(actionName)
.executes(c -> action(c, type, EntityPlayerActionPack.Action.once()))
@@ -126,7 +125,7 @@ public class PlayerCommand
.executes(c -> action(c, type, EntityPlayerActionPack.Action.interval(IntegerArgumentType.getInteger(c, "ticks"))))));
}
private static LiteralArgumentBuilder<ServerCommandSource> makeDropCommand(String actionName, boolean dropAll)
private static LiteralArgumentBuilder<CommandSourceStack> makeDropCommand(String actionName, boolean dropAll)
{
return literal(actionName)
.then(literal("all").executes(c ->manipulate(c, ap -> ap.drop(-2,dropAll))))
@@ -139,39 +138,39 @@ public class PlayerCommand
))));
}
private static Collection<String> getPlayers(ServerCommandSource source)
private static Collection<String> getPlayers(CommandSourceStack source)
{
Set<String> players = Sets.newLinkedHashSet(Arrays.asList("Steve", "Alex"));
players.addAll(source.getPlayerNames());
players.addAll(source.getOnlinePlayerNames());
return players;
}
private static ServerPlayerEntity getPlayer(CommandContext<ServerCommandSource> context)
private static ServerPlayer getPlayer(CommandContext<CommandSourceStack> context)
{
String playerName = StringArgumentType.getString(context, "player");
MinecraftServer server = context.getSource().getServer();
return server.getPlayerManager().getPlayer(playerName);
return server.getPlayerList().getPlayerByName(playerName);
}
private static boolean cantManipulate(CommandContext<ServerCommandSource> context)
private static boolean cantManipulate(CommandContext<CommandSourceStack> context)
{
PlayerEntity player = getPlayer(context);
Player player = getPlayer(context);
if (player == null)
{
Messenger.m(context.getSource(), "r Can only manipulate existing players");
return true;
}
PlayerEntity sendingPlayer;
Player sendingPlayer;
try
{
sendingPlayer = context.getSource().getPlayer();
sendingPlayer = context.getSource().getPlayerOrException();
}
catch (CommandSyntaxException e)
{
return false;
}
if (!context.getSource().getServer().getPlayerManager().isOperator(sendingPlayer.getGameProfile()))
if (!context.getSource().getServer().getPlayerList().isOp(sendingPlayer.getGameProfile()))
{
if (sendingPlayer != player && !(player instanceof EntityPlayerMPFake))
{
@@ -182,27 +181,27 @@ public class PlayerCommand
return false;
}
private static boolean cantReMove(CommandContext<ServerCommandSource> context)
private static boolean cantReMove(CommandContext<CommandSourceStack> context)
{
if (cantManipulate(context)) return true;
PlayerEntity player = getPlayer(context);
Player player = getPlayer(context);
if (player instanceof EntityPlayerMPFake) return false;
Messenger.m(context.getSource(), "r Only fake players can be moved or killed");
return true;
}
private static boolean cantSpawn(CommandContext<ServerCommandSource> context)
private static boolean cantSpawn(CommandContext<CommandSourceStack> context)
{
String playerName = StringArgumentType.getString(context, "player");
MinecraftServer server = context.getSource().getServer();
PlayerManager manager = server.getPlayerManager();
PlayerEntity player = manager.getPlayer(playerName);
PlayerList manager = server.getPlayerList();
Player player = manager.getPlayerByName(playerName);
if (player != null)
{
Messenger.m(context.getSource(), "r Player ", "rb " + playerName, "r is already logged on");
return true;
}
GameProfile profile = server.getUserCache().findByName(playerName).orElse(null);
GameProfile profile = server.getProfileCache().get(playerName).orElse(null);
if (profile == null)
{
if (!CarpetSettings.allowSpawningOfflinePlayers)
@@ -211,15 +210,15 @@ public class PlayerCommand
"Banned players can only be summoned in Singleplayer and in servers in off-line mode.");
return true;
} else {
profile = new GameProfile(PlayerEntity.getOfflinePlayerUuid(playerName), playerName);
profile = new GameProfile(Player.createPlayerUUID(playerName), playerName);
}
}
if (manager.getUserBanList().contains(profile))
if (manager.getBans().isBanned(profile))
{
Messenger.m(context.getSource(), "r Player ", "rb " + playerName, "r is banned on this server");
return true;
}
if (manager.isWhitelistEnabled() && manager.isWhitelisted(profile) && !context.getSource().hasPermissionLevel(2))
if (manager.isUsingWhitelist() && manager.isWhiteListed(profile) && !context.getSource().hasPermission(2))
{
Messenger.m(context.getSource(), "r Whitelisted players can only be spawned by operators");
return true;
@@ -227,18 +226,18 @@ public class PlayerCommand
return false;
}
private static int kill(CommandContext<ServerCommandSource> context)
private static int kill(CommandContext<CommandSourceStack> context)
{
if (cantReMove(context)) return 0;
getPlayer(context).kill();
return 1;
}
private static int lookAt(CommandContext<ServerCommandSource> context)
private static int lookAt(CommandContext<CommandSourceStack> context)
{
return manipulate(context, ap -> {
//try {
ap.lookAt(Vec3ArgumentType.getVec3(context, "position"));
ap.lookAt(Vec3Argument.getVec3(context, "position"));
//} catch (CommandSyntaxException ignored) {}
});
}
@@ -261,45 +260,45 @@ public class PlayerCommand
}
}
private static int spawn(CommandContext<ServerCommandSource> context) throws CommandSyntaxException
private static int spawn(CommandContext<CommandSourceStack> context) throws CommandSyntaxException
{
if (cantSpawn(context)) return 0;
ServerCommandSource source = context.getSource();
Vec3d pos = tryGetArg(
() -> Vec3ArgumentType.getVec3(context, "position"),
CommandSourceStack source = context.getSource();
Vec3 pos = tryGetArg(
() -> Vec3Argument.getVec3(context, "position"),
source::getPosition
);
Vec2f facing = tryGetArg(
() -> RotationArgumentType.getRotation(context, "direction").toAbsoluteRotation(context.getSource()),
Vec2 facing = tryGetArg(
() -> RotationArgument.getRotation(context, "direction").getRotation(context.getSource()),
source::getRotation
);
RegistryKey<World> dimType = tryGetArg(
() -> DimensionArgumentType.getDimensionArgument(context, "dimension").getRegistryKey(),
() -> source.getWorld().getRegistryKey() // dimension.getType()
ResourceKey<Level> dimType = tryGetArg(
() -> DimensionArgument.getDimension(context, "dimension").dimension(),
() -> source.getLevel().dimension() // dimension.getType()
);
GameMode mode = GameMode.CREATIVE;
GameType mode = GameType.CREATIVE;
boolean flying = false;
try
{
ServerPlayerEntity player = context.getSource().getPlayer();
mode = player.interactionManager.getGameMode();
ServerPlayer player = context.getSource().getPlayerOrException();
mode = player.gameMode.getGameModeForPlayer();
flying = player.getAbilities().flying;
}
catch (CommandSyntaxException ignored) {}
try {
String opGameMode = StringArgumentType.getString(context, "gamemode");
mode = GameMode.byName(opGameMode, null);
mode = GameType.byName(opGameMode, null);
if(mode == null)
{
Messenger.m(context.getSource(), "rb Invalid game mode: "+opGameMode+".");
return 0;
}
} catch (IllegalArgumentException ignored) {}
if(mode == GameMode.SPECTATOR)
if(mode == GameType.SPECTATOR)
{
// Force override flying to true for spectator players, or they will fell out of the world.
flying = true;
} else if(mode.isSurvivalLike()){
} else if(mode.isSurvival()){
// Force override flying to false for survival-like players, or they will fly too
flying = false;
}
@@ -311,12 +310,12 @@ public class PlayerCommand
}
MinecraftServer server = source.getServer();
if (!World.isValid(new BlockPos(pos.x, pos.y, pos.z)))
if (!Level.isInSpawnableBounds(new BlockPos(pos.x, pos.y, pos.z)))
{
Messenger.m(context.getSource(), "rb Player "+playerName+" cannot be placed outside of the world");
return 0;
}
PlayerEntity player = EntityPlayerMPFake.createFake(playerName, server, pos.x, pos.y, pos.z, facing.y, facing.x, dimType, mode, flying);
Player player = EntityPlayerMPFake.createFake(playerName, server, pos.x, pos.y, pos.z, facing.y, facing.x, dimType, mode, flying);
if (player == null)
{
Messenger.m(context.getSource(), "rb Player " + StringArgumentType.getString(context, "player") + " doesn't exist " +
@@ -328,47 +327,47 @@ public class PlayerCommand
private static int maxPlayerLength(MinecraftServer server)
{
return server.getServerPort() >= 0 ? 16 : 40;
return server.getPort() >= 0 ? 16 : 40;
}
private static int stop(CommandContext<ServerCommandSource> context)
private static int stop(CommandContext<CommandSourceStack> context)
{
if (cantManipulate(context)) return 0;
ServerPlayerEntity player = getPlayer(context);
ServerPlayer player = getPlayer(context);
((ServerPlayerEntityInterface) player).getActionPack().stopAll();
return 1;
}
private static int manipulate(CommandContext<ServerCommandSource> context, Consumer<EntityPlayerActionPack> action)
private static int manipulate(CommandContext<CommandSourceStack> context, Consumer<EntityPlayerActionPack> action)
{
if (cantManipulate(context)) return 0;
ServerPlayerEntity player = getPlayer(context);
ServerPlayer player = getPlayer(context);
action.accept(((ServerPlayerEntityInterface) player).getActionPack());
return 1;
}
private static Command<ServerCommandSource> manipulation(Consumer<EntityPlayerActionPack> action)
private static Command<CommandSourceStack> manipulation(Consumer<EntityPlayerActionPack> action)
{
return c -> manipulate(c, action);
}
private static int action(CommandContext<ServerCommandSource> context, EntityPlayerActionPack.ActionType type, EntityPlayerActionPack.Action action)
private static int action(CommandContext<CommandSourceStack> context, EntityPlayerActionPack.ActionType type, EntityPlayerActionPack.Action action)
{
return manipulate(context, ap -> ap.start(type, action));
}
private static int shadow(CommandContext<ServerCommandSource> context)
private static int shadow(CommandContext<CommandSourceStack> context)
{
ServerPlayerEntity player = getPlayer(context);
ServerPlayer player = getPlayer(context);
if (player instanceof EntityPlayerMPFake)
{
Messenger.m(context.getSource(), "r Cannot shadow fake players");
return 0;
}
ServerPlayerEntity sendingPlayer = null;
ServerPlayer sendingPlayer = null;
try
{
sendingPlayer = context.getSource().getPlayer();
sendingPlayer = context.getSource().getPlayerOrException();
}
catch (CommandSyntaxException ignored) { }
@@ -4,20 +4,20 @@ import carpet.CarpetSettings;
import carpet.settings.SettingsManager;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import static carpet.commands.TickCommand.healthEntities;
import static carpet.commands.TickCommand.healthReport;
import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
public class ProfileCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> literalargumentbuilder = literal("profile").
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = literal("profile").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandProfile)).
executes( (c) -> healthReport(c.getSource(), 100)).
then(literal("health").
+129 -129
View File
@@ -23,18 +23,6 @@ import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.block.Block;
import net.minecraft.block.pattern.CachedBlockPosition;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.command.argument.BlockPredicateArgumentType;
import net.minecraft.command.argument.BlockStateArgument;
import net.minecraft.command.argument.BlockStateArgumentType;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.util.Clearable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockBox;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
@@ -49,10 +37,22 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.commands.CommandSourceStack;
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.server.level.ServerLevel;
import net.minecraft.world.Clearable;
import net.minecraft.world.level.block.Block;
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;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class ScriptCommand
{
@@ -86,7 +86,7 @@ public class ScriptCommand
}
private static CompletableFuture<Suggestions> suggestCode(
CommandContext<ServerCommandSource> context,
CommandContext<CommandSourceStack> context,
SuggestionsBuilder suggestionsBuilder
) throws CommandSyntaxException
{
@@ -112,7 +112,7 @@ public class ScriptCommand
* variable.
*/
private static CompletableFuture<Suggestions> suggestDownloadableApps(
CommandContext<ServerCommandSource> context,
CommandContext<CommandSourceStack> context,
SuggestionsBuilder suggestionsBuilder
) throws CommandSyntaxException {
@@ -129,23 +129,23 @@ public class ScriptCommand
});
}
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> b = literal("globals").
LiteralArgumentBuilder<CommandSourceStack> b = literal("globals").
executes(context -> listGlobals(context, false)).
then(literal("all").executes(context -> listGlobals(context, true)));
LiteralArgumentBuilder<ServerCommandSource> o = literal("stop").
LiteralArgumentBuilder<CommandSourceStack> o = literal("stop").
executes( (cc) -> { CarpetServer.scriptServer.stopAll = true; return 1;});
LiteralArgumentBuilder<ServerCommandSource> u = literal("resume").
LiteralArgumentBuilder<CommandSourceStack> u = literal("resume").
executes( (cc) -> { CarpetServer.scriptServer.stopAll = false; return 1;});
LiteralArgumentBuilder<ServerCommandSource> l = literal("run").
LiteralArgumentBuilder<CommandSourceStack> l = literal("run").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE)).
then(argument("expr", StringArgumentType.greedyString()).suggests(ScriptCommand::suggestCode).
executes((cc) -> compute(
cc,
StringArgumentType.getString(cc, "expr"))));
LiteralArgumentBuilder<ServerCommandSource> s = literal("invoke").
then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggestMatching(suggestFunctionCalls(cc),bb)).
LiteralArgumentBuilder<CommandSourceStack> s = literal("invoke").
then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)).
executes( (cc) -> invoke(
cc,
StringArgumentType.getString(cc, "call"),
@@ -161,13 +161,13 @@ public class ScriptCommand
null,
StringArgumentType.getString(cc, "arguments")
))));
LiteralArgumentBuilder<ServerCommandSource> c = literal("invokepoint").
then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggestMatching(suggestFunctionCalls(cc),bb)).
then(argument("origin", BlockPosArgumentType.blockPos()).
LiteralArgumentBuilder<CommandSourceStack> c = literal("invokepoint").
then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)).
then(argument("origin", BlockPosArgument.blockPos()).
executes( (cc) -> invoke(
cc,
StringArgumentType.getString(cc, "call"),
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
null,
""
)).
@@ -175,99 +175,99 @@ public class ScriptCommand
executes( (cc) -> invoke(
cc,
StringArgumentType.getString(cc, "call"),
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
null,
StringArgumentType.getString(cc, "arguments")
)))));
LiteralArgumentBuilder<ServerCommandSource> h = literal("invokearea").
then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggestMatching(suggestFunctionCalls(cc),bb)).
then(argument("from", BlockPosArgumentType.blockPos()).
then(argument("to", BlockPosArgumentType.blockPos()).
LiteralArgumentBuilder<CommandSourceStack> h = literal("invokearea").
then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)).
then(argument("from", BlockPosArgument.blockPos()).
then(argument("to", BlockPosArgument.blockPos()).
executes( (cc) -> invoke(
cc,
StringArgumentType.getString(cc, "call"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
""
)).
then(argument("arguments", StringArgumentType.greedyString()).
executes( (cc) -> invoke(
cc,
StringArgumentType.getString(cc, "call"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
StringArgumentType.getString(cc, "arguments")
))))));
LiteralArgumentBuilder<ServerCommandSource> i = literal("scan").requires((player) -> player.hasPermissionLevel(2)).
then(argument("origin", BlockPosArgumentType.blockPos()).
then(argument("from", BlockPosArgumentType.blockPos()).
then(argument("to", BlockPosArgumentType.blockPos()).
LiteralArgumentBuilder<CommandSourceStack> i = literal("scan").requires((player) -> player.hasPermission(2)).
then(argument("origin", BlockPosArgument.blockPos()).
then(argument("from", BlockPosArgument.blockPos()).
then(argument("to", BlockPosArgument.blockPos()).
then(argument("expr", StringArgumentType.greedyString()).
suggests(ScriptCommand::suggestCode).
executes( (cc) -> scriptScan(
cc,
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
StringArgumentType.getString(cc, "expr")
))))));
LiteralArgumentBuilder<ServerCommandSource> e = literal("fill").requires((player) -> player.hasPermissionLevel(2)).
then(argument("origin", BlockPosArgumentType.blockPos()).
then(argument("from", BlockPosArgumentType.blockPos()).
then(argument("to", BlockPosArgumentType.blockPos()).
LiteralArgumentBuilder<CommandSourceStack> e = literal("fill").requires((player) -> player.hasPermission(2)).
then(argument("origin", BlockPosArgument.blockPos()).
then(argument("from", BlockPosArgument.blockPos()).
then(argument("to", BlockPosArgument.blockPos()).
then(argument("expr", StringArgumentType.string()).
then(argument("block", BlockStateArgumentType.blockState()).
then(argument("block", BlockStateArgument.block()).
executes((cc) -> scriptFill(
cc,
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
StringArgumentType.getString(cc, "expr"),
BlockStateArgumentType.getBlockState(cc, "block"),
BlockStateArgument.getBlock(cc, "block"),
null, "solid"
)).
then(literal("replace").
then(argument("filter", BlockPredicateArgumentType.blockPredicate())
then(argument("filter", BlockPredicateArgument.blockPredicate())
.executes((cc) -> scriptFill(
cc,
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
StringArgumentType.getString(cc, "expr"),
BlockStateArgumentType.getBlockState(cc, "block"),
BlockPredicateArgumentType.getBlockPredicate(cc, "filter"),
BlockStateArgument.getBlock(cc, "block"),
BlockPredicateArgument.getBlockPredicate(cc, "filter"),
"solid"
)))))))));
LiteralArgumentBuilder<ServerCommandSource> t = literal("outline").requires((player) -> player.hasPermissionLevel(2)).
then(argument("origin", BlockPosArgumentType.blockPos()).
then(argument("from", BlockPosArgumentType.blockPos()).
then(argument("to", BlockPosArgumentType.blockPos()).
LiteralArgumentBuilder<CommandSourceStack> t = literal("outline").requires((player) -> player.hasPermission(2)).
then(argument("origin", BlockPosArgument.blockPos()).
then(argument("from", BlockPosArgument.blockPos()).
then(argument("to", BlockPosArgument.blockPos()).
then(argument("expr", StringArgumentType.string()).
then(argument("block", BlockStateArgumentType.blockState()).
then(argument("block", BlockStateArgument.block()).
executes((cc) -> scriptFill(
cc,
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
StringArgumentType.getString(cc, "expr"),
BlockStateArgumentType.getBlockState(cc, "block"),
BlockStateArgument.getBlock(cc, "block"),
null, "outline"
)).
then(literal("replace").
then(argument("filter", BlockPredicateArgumentType.blockPredicate())
then(argument("filter", BlockPredicateArgument.blockPredicate())
.executes((cc) -> scriptFill(
cc,
BlockPosArgumentType.getBlockPos(cc, "origin"),
BlockPosArgumentType.getBlockPos(cc, "from"),
BlockPosArgumentType.getBlockPos(cc, "to"),
BlockPosArgument.getSpawnablePos(cc, "origin"),
BlockPosArgument.getSpawnablePos(cc, "from"),
BlockPosArgument.getSpawnablePos(cc, "to"),
StringArgumentType.getString(cc, "expr"),
BlockStateArgumentType.getBlockState(cc, "block"),
BlockPredicateArgumentType.getBlockPredicate(cc, "filter"),
BlockStateArgument.getBlock(cc, "block"),
BlockPredicateArgument.getBlockPredicate(cc, "filter"),
"outline"
)))))))));
LiteralArgumentBuilder<ServerCommandSource> a = literal("load").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
LiteralArgumentBuilder<CommandSourceStack> a = literal("load").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
then(argument("app", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.listAvailableModules(true),bb)).
suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.listAvailableModules(true),bb)).
executes((cc) ->
{
boolean success = CarpetServer.scriptServer.addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, true, false, false, null);
@@ -282,22 +282,22 @@ public class ScriptCommand
)
)
);
LiteralArgumentBuilder<ServerCommandSource> f = literal("unload").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
LiteralArgumentBuilder<CommandSourceStack> f = literal("unload").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
then(argument("app", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.unloadableModules,bb)).
suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.unloadableModules,bb)).
executes((cc) ->
{
boolean success =CarpetServer.scriptServer.removeScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), true, false);
return success?1:0;
}));
LiteralArgumentBuilder<ServerCommandSource> q = literal("event").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
LiteralArgumentBuilder<CommandSourceStack> q = literal("event").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
executes( (cc) -> listEvents(cc.getSource())).
then(literal("add_to").
then(argument("event", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().map(ev -> ev.name).collect(Collectors.toList()),bb)).
suggests( (cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().map(ev -> ev.name).collect(Collectors.toList()),bb)).
then(argument("call", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(suggestFunctionCalls(cc), bb)).
suggests( (cc, bb) -> suggest(suggestFunctionCalls(cc), bb)).
executes( (cc) -> CarpetServer.scriptServer.events.addEventFromCommand(
cc.getSource(),
StringArgumentType.getString(cc, "event"),
@@ -306,9 +306,9 @@ public class ScriptCommand
)?1:0)).
then(literal("from").
then(argument("app", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.modules.keySet(), bb)).
suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.modules.keySet(), bb)).
then(argument("call", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(suggestFunctionCalls(cc), bb)).
suggests( (cc, bb) -> suggest(suggestFunctionCalls(cc), bb)).
executes( (cc) -> CarpetServer.scriptServer.events.addEventFromCommand(
cc.getSource(),
StringArgumentType.getString(cc, "event"),
@@ -317,22 +317,22 @@ public class ScriptCommand
)?1:0)))))).
then(literal("remove_from").
then(argument("event", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().filter(CarpetEventServer.Event::isNeeded).map(ev -> ev.name).collect(Collectors.toList()) ,bb)).
suggests( (cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().filter(CarpetEventServer.Event::isNeeded).map(ev -> ev.name).collect(Collectors.toList()) ,bb)).
then(argument("call", StringArgumentType.greedyString()).
suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.getEvent(StringArgumentType.getString(cc, "event"), CarpetServer.scriptServer).handler.inspectCurrentCalls().stream().map(CarpetEventServer.Callback::toString), bb)).
suggests( (cc, bb) -> suggest(CarpetEventServer.Event.getEvent(StringArgumentType.getString(cc, "event"), CarpetServer.scriptServer).handler.inspectCurrentCalls().stream().map(CarpetEventServer.Callback::toString), bb)).
executes( (cc) -> CarpetServer.scriptServer.events.removeEventFromCommand(
cc.getSource(),
StringArgumentType.getString(cc, "event"),
StringArgumentType.getString(cc, "call")
)?1:0))));
LiteralArgumentBuilder<ServerCommandSource> d = literal("download").requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE)).
LiteralArgumentBuilder<CommandSourceStack> d = literal("download").requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE)).
then(argument("path", StringArgumentType.greedyString()).
suggests(ScriptCommand::suggestDownloadableApps).
executes(cc-> AppStoreManager.downloadScript(cc.getSource(), StringArgumentType.getString(cc,"path"))));
LiteralArgumentBuilder<ServerCommandSource> r = literal("remove").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
LiteralArgumentBuilder<CommandSourceStack> r = literal("remove").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ).
then(argument("app", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.unloadableModules,bb)).
suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.unloadableModules,bb)).
executes((cc) ->
{
boolean success =CarpetServer.scriptServer.uninstallApp(cc.getSource(), StringArgumentType.getString(cc, "app"));
@@ -346,10 +346,10 @@ public class ScriptCommand
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScript)).
then(literal("in").
then(argument("app", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.modules.keySet(), bb)).
suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.modules.keySet(), bb)).
then(b).then(u).then(o).then(l).then(s).then(c).then(h).then(i).then(e).then(t))));
}
private static CarpetScriptHost getHost(CommandContext<ServerCommandSource> context) throws CommandSyntaxException
private static CarpetScriptHost getHost(CommandContext<CommandSourceStack> context) throws CommandSyntaxException
{
CarpetScriptHost host;
try
@@ -365,12 +365,12 @@ public class ScriptCommand
host.setChatErrorSnooper(context.getSource());
return host;
}
private static Collection<String> suggestFunctionCalls(CommandContext<ServerCommandSource> c) throws CommandSyntaxException
private static Collection<String> suggestFunctionCalls(CommandContext<CommandSourceStack> c) throws CommandSyntaxException
{
CarpetScriptHost host = getHost(c);
return host.globalFunctionNames(host.main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList());
}
private static int listEvents(ServerCommandSource source)
private static int listEvents(CommandSourceStack source)
{
Messenger.m(source, "w Lists ALL event handlers:");
for (CarpetEventServer.Event event: CarpetEventServer.Event.getAllEvents(CarpetServer.scriptServer, null))
@@ -388,10 +388,10 @@ public class ScriptCommand
}
return 1;
}
private static int listGlobals(CommandContext<ServerCommandSource> context, boolean all) throws CommandSyntaxException
private static int listGlobals(CommandContext<CommandSourceStack> context, boolean all) throws CommandSyntaxException
{
CarpetScriptHost host = getHost(context);
ServerCommandSource source = context.getSource();
CommandSourceStack source = context.getSource();
Messenger.m(source, "lb Stored functions"+((host == CarpetServer.scriptServer.globalHost)?":":" in "+host.getName()+":"));
host.globalFunctionNames(host.main, (str) -> all || !str.startsWith("__")).sorted().forEach( (s) -> {
@@ -429,7 +429,7 @@ public class ScriptCommand
return 1;
}
public static int handleCall(ServerCommandSource source, CarpetScriptHost host, Supplier<Value> call)
public static int handleCall(CommandSourceStack source, CarpetScriptHost host, Supplier<Value> call)
{
try
{
@@ -470,9 +470,9 @@ public class ScriptCommand
//host.resetErrorSnooper(); // lets say no need to reset the snooper in case something happens on the way
}
private static int invoke(CommandContext<ServerCommandSource> context, String call, BlockPos pos1, BlockPos pos2, String args) throws CommandSyntaxException
private static int invoke(CommandContext<CommandSourceStack> context, String call, BlockPos pos1, BlockPos pos2, String args) throws CommandSyntaxException
{
ServerCommandSource source = context.getSource();
CommandSourceStack source = context.getSource();
CarpetScriptHost host = getHost(context);
if (call.startsWith("__"))
{
@@ -498,9 +498,9 @@ public class ScriptCommand
}
private static int compute(CommandContext<ServerCommandSource> context, String expr) throws CommandSyntaxException
private static int compute(CommandContext<CommandSourceStack> context, String expr) throws CommandSyntaxException
{
ServerCommandSource source = context.getSource();
CommandSourceStack source = context.getSource();
CarpetScriptHost host = getHost(context);
return handleCall(source, host, () -> {
CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0));
@@ -508,13 +508,13 @@ public class ScriptCommand
});
}
private static int scriptScan(CommandContext<ServerCommandSource> context, BlockPos origin, BlockPos a, BlockPos b, String expr) throws CommandSyntaxException
private static int scriptScan(CommandContext<CommandSourceStack> context, BlockPos origin, BlockPos a, BlockPos b, String expr) throws CommandSyntaxException
{
ServerCommandSource source = context.getSource();
CommandSourceStack source = context.getSource();
CarpetScriptHost host = getHost(context);
BlockBox area = BlockBox.create(a, b);
BoundingBox area = BoundingBox.fromCorners(a, b);
CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); // X Y Z
int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z
if (int_1 > CarpetSettings.fillLimit)
{
Messenger.m(source, "r too many blocks to evaluate: " + int_1);
@@ -524,11 +524,11 @@ public class ScriptCommand
CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates);
try
{
for (int x = area.getMinX(); x <= area.getMaxX(); x++)
for (int x = area.minX(); x <= area.maxX(); x++)
{
for (int y = area.getMinY(); y <= area.getMaxY(); y++)
for (int y = area.minY(); y <= area.maxY(); y++)
{
for (int z = area.getMinZ(); z <= area.getMaxZ(); z++)
for (int z = area.minZ(); z <= area.maxZ(); z++)
{
try
{
@@ -556,36 +556,36 @@ public class ScriptCommand
}
private static int scriptFill(CommandContext<ServerCommandSource> context, BlockPos origin, BlockPos a, BlockPos b, String expr,
BlockStateArgument block, Predicate<CachedBlockPosition> replacement, String mode) throws CommandSyntaxException
private static int scriptFill(CommandContext<CommandSourceStack> context, BlockPos origin, BlockPos a, BlockPos b, String expr,
BlockInput block, Predicate<BlockInWorld> replacement, String mode) throws CommandSyntaxException
{
ServerCommandSource source = context.getSource();
CommandSourceStack source = context.getSource();
CarpetScriptHost host = getHost(context);
BlockBox area = BlockBox.create(a, b);
BoundingBox area = BoundingBox.fromCorners(a, b);
CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ();
int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan();
if (int_1 > CarpetSettings.fillLimit)
{
Messenger.m(source, "r too many blocks to evaluate: "+ int_1);
return 1;
}
boolean[][][] volume = new boolean[area.getBlockCountX()][area.getBlockCountY()][area.getBlockCountZ()]; //X then Y then Z got messedup
boolean[][][] volume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; //X then Y then Z got messedup
BlockPos.Mutable mbpos = origin.mutableCopy();
ServerWorld world = source.getWorld();
BlockPos.MutableBlockPos mbpos = origin.mutable();
ServerLevel world = source.getLevel();
for (int x = area.getMinX(); x <= area.getMaxX(); x++)
for (int x = area.minX(); x <= area.maxX(); x++)
{
for (int y = area.getMinY(); y <= area.getMaxY(); y++)
for (int y = area.minY(); y <= area.maxY(); y++)
{
for (int z = area.getMinZ(); z <= area.getMaxZ(); z++)
for (int z = area.minZ(); z <= area.maxZ(); z++)
{
try
{
if (cexpr.fillAndScanCommand(host, x, y, z))
{
volume[x-area.getMinX()][y-area.getMinY()][z-area.getMinZ()]=true;
volume[x-area.minX()][y-area.minY()][z-area.minZ()]=true;
}
}
catch (CarpetExpressionException e)
@@ -599,12 +599,12 @@ public class ScriptCommand
}
}
}
final int maxx = area.getBlockCountX()-1;
final int maxy = area.getBlockCountY()-1;
final int maxz = area.getBlockCountZ()-1;
final int maxx = area.getXSpan()-1;
final int maxy = area.getYSpan()-1;
final int maxz = area.getZSpan()-1;
if ("outline".equalsIgnoreCase(mode))
{
boolean[][][] newVolume = new boolean[area.getBlockCountX()][area.getBlockCountY()][area.getBlockCountZ()];
boolean[][][] newVolume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()];
for (int x = 0; x <= maxx; x++)
{
for (int y = 0; y <= maxy; y++)
@@ -640,14 +640,14 @@ public class ScriptCommand
{
if (volume[x][y][z])
{
mbpos.set(x+area.getMinX(), y+area.getMinY(), z+area.getMinZ());
mbpos.set(x+area.minX(), y+area.minY(), z+area.minZ());
if (replacement == null || replacement.test(
new CachedBlockPosition( world, mbpos, true)))
new BlockInWorld( world, mbpos, true)))
{
BlockEntity tileentity = world.getBlockEntity(mbpos);
Clearable.clear(tileentity);
Clearable.tryClear(tileentity);
if (block.setBlockState(world, mbpos,2))
if (block.place(world, mbpos,2))
{
++affected;
}
@@ -668,15 +668,15 @@ public class ScriptCommand
{
if (volume[x][y][z])
{
mbpos.set(x+area.getMinX(), y+area.getMinY(), z+area.getMinZ());
mbpos.set(x+area.minX(), y+area.minY(), z+area.minZ());
Block blokc = world.getBlockState(mbpos).getBlock();
world.updateNeighbors(mbpos, blokc);
world.blockUpdated(mbpos, blokc);
}
}
}
}
}
Messenger.m(source, "gi Affected "+affected+" blocks in "+area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ()+" block volume");
Messenger.m(source, "gi Affected "+affected+" blocks in "+area.getXSpan() * area.getYSpan() * area.getZSpan()+" block volume");
return 1;
}
}
+59 -60
View File
@@ -12,54 +12,53 @@ import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.command.argument.DimensionArgumentType;
import net.minecraft.entity.SpawnGroup;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.DyeColor;
import net.minecraft.util.math.BlockPos;
import java.util.Arrays;
import java.util.Locale;
import java.util.stream.Collectors;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.DimensionArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.item.DyeColor;
import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.string;
import static com.mojang.brigadier.arguments.StringArgumentType.word;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class SpawnCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> literalargumentbuilder = literal("spawn").
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = literal("spawn").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandSpawn));
literalargumentbuilder.
then(literal("list").
then(argument("pos", BlockPosArgumentType.blockPos()).
executes( (c) -> listSpawns(c.getSource(), BlockPosArgumentType.getBlockPos(c, "pos"))))).
then(argument("pos", BlockPosArgument.blockPos()).
executes( (c) -> listSpawns(c.getSource(), BlockPosArgument.getSpawnablePos(c, "pos"))))).
then(literal("tracking").
executes( (c) -> printTrackingReport(c.getSource())).
then(literal("start").
executes( (c) -> startTracking(c.getSource(), null, null)).
then(argument("from", BlockPosArgumentType.blockPos()).
then(argument("to", BlockPosArgumentType.blockPos()).
then(argument("from", BlockPosArgument.blockPos()).
then(argument("to", BlockPosArgument.blockPos()).
executes( (c) -> startTracking(
c.getSource(),
BlockPosArgumentType.getBlockPos(c, "from"),
BlockPosArgumentType.getBlockPos(c, "to")))))).
BlockPosArgument.getSpawnablePos(c, "from"),
BlockPosArgument.getSpawnablePos(c, "to")))))).
then(literal("stop").
executes( (c) -> stopTracking(c.getSource()))).
then(argument("type", word()).
suggests( (c, b) -> suggestMatching(Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName),b)).
suggests( (c, b) -> suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName),b)).
executes( (c) -> recentSpawnsForType(c.getSource(), getString(c, "type"))))).
then(literal("test").
executes( (c)-> runTest(c.getSource(), 72000, null)).
@@ -69,7 +68,7 @@ public class SpawnCommand
getInteger(c, "ticks"),
null)).
then(argument("counter", word()).
suggests( (c, b) -> suggestMatching(Arrays.stream(DyeColor.values()).map(DyeColor::toString),b)).
suggests( (c, b) -> suggest(Arrays.stream(DyeColor.values()).map(DyeColor::toString),b)).
executes((c)-> runTest(
c.getSource(),
getInteger(c, "ticks"),
@@ -82,9 +81,9 @@ public class SpawnCommand
then(literal("reset").
executes( (c) -> resetSpawnRates(c.getSource()))).
then(argument("type", word()).
suggests( (c, b) -> suggestMatching(Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName),b)).
suggests( (c, b) -> suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName),b)).
then(argument("rounds", integer(0)).
suggests( (c, b) -> suggestMatching(new String[]{"1"},b)).
suggests( (c, b) -> suggest(new String[]{"1"},b)).
executes( (c) -> setSpawnRates(
c.getSource(),
getString(c, "type"),
@@ -94,41 +93,41 @@ public class SpawnCommand
then(literal("set").
then(argument("cap (hostile)", integer(1,1400)).
executes( (c) -> setMobcaps(c.getSource(), getInteger(c, "cap (hostile)"))))).
then(argument("dimension", DimensionArgumentType.dimension()).
executes( (c)-> mobcapsForDimension(c.getSource(), DimensionArgumentType.getDimensionArgument(c, "dimension"))))).
then(argument("dimension", DimensionArgument.dimension()).
executes( (c)-> mobcapsForDimension(c.getSource(), DimensionArgument.getDimension(c, "dimension"))))).
then(literal("entities").
executes( (c) -> generalMobcaps(c.getSource()) ).
then(argument("type", string()).
suggests( (c, b)->suggestMatching(Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName), b)).
suggests( (c, b)->suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName), b)).
executes( (c) -> listEntitiesOfType(c.getSource(), getString(c, "type"), false)).
then(literal("all").executes( (c) -> listEntitiesOfType(c.getSource(), getString(c, "type"), true)))));
dispatcher.register(literalargumentbuilder);
}
private static SpawnGroup getCategory(String string) throws CommandSyntaxException
private static MobCategory getCategory(String string) throws CommandSyntaxException
{
if (!Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName).collect(Collectors.toSet()).contains(string))
if (!Arrays.stream(MobCategory.values()).map(MobCategory::getName).collect(Collectors.toSet()).contains(string))
{
throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName).collect(Collectors.joining(", ")))).create();
throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(MobCategory.values()).map(MobCategory::getName).collect(Collectors.joining(", ")))).create();
}
return SpawnGroup.byName(string.toLowerCase(Locale.ROOT));
return MobCategory.byName(string.toLowerCase(Locale.ROOT));
}
private static int listSpawns(ServerCommandSource source, BlockPos pos)
private static int listSpawns(CommandSourceStack source, BlockPos pos)
{
Messenger.send(source, SpawnReporter.report(pos, source.getWorld()));
Messenger.send(source, SpawnReporter.report(pos, source.getLevel()));
return 1;
}
private static int printTrackingReport(ServerCommandSource source)
private static int printTrackingReport(CommandSourceStack source)
{
Messenger.send(source, SpawnReporter.tracking_report(source.getWorld()));
Messenger.send(source, SpawnReporter.tracking_report(source.getLevel()));
return 1;
}
private static int startTracking(ServerCommandSource source, BlockPos a, BlockPos b)
private static int startTracking(CommandSourceStack source, BlockPos a, BlockPos b)
{
if (SpawnReporter.track_spawns != 0L)
{
@@ -149,16 +148,16 @@ public class SpawnCommand
Math.max(a.getZ(), b.getZ()) );
}
SpawnReporter.reset_spawn_stats(source.getServer(), false);
SpawnReporter.track_spawns = (long) source.getServer().getTicks();
SpawnReporter.track_spawns = (long) source.getServer().getTickCount();
SpawnReporter.lower_spawning_limit = lsl;
SpawnReporter.upper_spawning_limit = usl;
Messenger.m(source, "gi Spawning tracking started.");
return 1;
}
private static int stopTracking(ServerCommandSource source)
private static int stopTracking(CommandSourceStack source)
{
Messenger.send(source, SpawnReporter.tracking_report(source.getWorld()));
Messenger.send(source, SpawnReporter.tracking_report(source.getLevel()));
SpawnReporter.reset_spawn_stats(source.getServer(),false);
SpawnReporter.track_spawns = 0L;
SpawnReporter.lower_spawning_limit = null;
@@ -167,19 +166,19 @@ public class SpawnCommand
return 1;
}
private static int recentSpawnsForType(ServerCommandSource source, String mob_type) throws CommandSyntaxException
private static int recentSpawnsForType(CommandSourceStack source, String mob_type) throws CommandSyntaxException
{
SpawnGroup cat = getCategory(mob_type);
Messenger.send(source, SpawnReporter.recent_spawns(source.getWorld(), cat));
MobCategory cat = getCategory(mob_type);
Messenger.send(source, SpawnReporter.recent_spawns(source.getLevel(), cat));
return 1;
}
private static int runTest(ServerCommandSource source, int ticks, String counter)
private static int runTest(CommandSourceStack source, int ticks, String counter)
{
//stop tracking
SpawnReporter.reset_spawn_stats(source.getServer(),false);
//start tracking
SpawnReporter.track_spawns = (long) source.getServer().getTicks();
SpawnReporter.track_spawns = (long) source.getServer().getTickCount();
//counter reset
if (counter == null)
{
@@ -196,11 +195,11 @@ public class SpawnCommand
// tick warp 0
TickSpeed.tickrate_advance(null, 0, null, null);
// tick warp given player
ServerCommandSource csource = null;
ServerPlayerEntity player = null;
CommandSourceStack csource = null;
ServerPlayer player = null;
try
{
player = source.getPlayer();
player = source.getPlayerOrException();
csource = source;
}
catch (CommandSyntaxException ignored)
@@ -211,7 +210,7 @@ public class SpawnCommand
return 1;
}
private static int toggleMocking(ServerCommandSource source, boolean domock)
private static int toggleMocking(CommandSourceStack source, boolean domock)
{
if (domock)
{
@@ -226,15 +225,15 @@ public class SpawnCommand
return 1;
}
private static int generalMobcaps(ServerCommandSource source)
private static int generalMobcaps(CommandSourceStack source)
{
Messenger.send(source, SpawnReporter.printMobcapsForDimension(source.getWorld(), true));
Messenger.send(source, SpawnReporter.printMobcapsForDimension(source.getLevel(), true));
return 1;
}
private static int resetSpawnRates(ServerCommandSource source)
private static int resetSpawnRates(CommandSourceStack source)
{
for (SpawnGroup s: SpawnReporter.spawn_tries.keySet())
for (MobCategory s: SpawnReporter.spawn_tries.keySet())
{
SpawnReporter.spawn_tries.put(s,1);
}
@@ -243,32 +242,32 @@ public class SpawnCommand
return 1;
}
private static int setSpawnRates(ServerCommandSource source, String mobtype, int rounds) throws CommandSyntaxException
private static int setSpawnRates(CommandSourceStack source, String mobtype, int rounds) throws CommandSyntaxException
{
SpawnGroup cat = getCategory(mobtype);
MobCategory cat = getCategory(mobtype);
SpawnReporter.spawn_tries.put(cat, rounds);
Messenger.m(source, "gi "+mobtype+" mobs will now spawn "+rounds+" times per tick");
return 1;
}
private static int setMobcaps(ServerCommandSource source, int hostile_cap)
private static int setMobcaps(CommandSourceStack source, int hostile_cap)
{
double desired_ratio = (double)hostile_cap/ ((SpawnGroupInterface)(Object)SpawnGroup.MONSTER).getInitialSpawnCap();
double desired_ratio = (double)hostile_cap/ ((SpawnGroupInterface)(Object)MobCategory.MONSTER).getInitialSpawnCap();
SpawnReporter.mobcap_exponent = 4.0*Math.log(desired_ratio)/Math.log(2.0);
Messenger.m(source, String.format("gi Mobcaps for hostile mobs changed to %d, other groups will follow", hostile_cap));
return 1;
}
private static int mobcapsForDimension(ServerCommandSource source, ServerWorld world)
private static int mobcapsForDimension(CommandSourceStack source, ServerLevel world)
{
Messenger.send(source, SpawnReporter.printMobcapsForDimension(world, true));
return 1;
}
private static int listEntitiesOfType(ServerCommandSource source, String mobtype, boolean all) throws CommandSyntaxException
private static int listEntitiesOfType(CommandSourceStack source, String mobtype, boolean all) throws CommandSyntaxException
{
SpawnGroup cat = getCategory(mobtype);
Messenger.send(source, SpawnReporter.printEntitiesByType(cat, source.getWorld(), all));
MobCategory cat = getCategory(mobtype);
Messenger.send(source, SpawnReporter.printEntitiesByType(cat, source.getLevel(), all));
return 1;
}
}
@@ -4,16 +4,16 @@ import carpet.CarpetServer;
import carpet.utils.Messenger;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.word;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
public class TestCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
dispatcher.register(literal("testcarpet").
then(literal("dump").
@@ -26,7 +26,7 @@ public class TestCommand
executes( (c)-> test(c, getString(c, "second")+" 2"))));
}
private static int test(CommandContext<ServerCommandSource> c, String term)
private static int test(CommandContext<CommandSourceStack> c, String term)
{
Messenger.m(c.getSource(),term.substring(0,1)+" "+term+": how did you get here?");
return 1;
+25 -25
View File
@@ -9,9 +9,9 @@ import carpet.utils.Messenger;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.BaseText;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.server.level.ServerPlayer;
import static com.mojang.brigadier.arguments.FloatArgumentType.floatArg;
import static com.mojang.brigadier.arguments.FloatArgumentType.getFloat;
@@ -19,25 +19,25 @@ import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.CommandSource.suggestMatching;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
import static net.minecraft.commands.SharedSuggestionProvider.suggest;
public class TickCommand
{
public static void register(CommandDispatcher<ServerCommandSource> dispatcher)
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
LiteralArgumentBuilder<ServerCommandSource> literalargumentbuilder = literal("tick").
LiteralArgumentBuilder<CommandSourceStack> literalargumentbuilder = literal("tick").
requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandTick)).
then(literal("rate").
executes((c) -> queryTps(c.getSource())).
then(argument("rate", floatArg(0.1F, 500.0F)).
suggests( (c, b) -> suggestMatching(new String[]{"20.0"},b)).
suggests( (c, b) -> suggest(new String[]{"20.0"},b)).
executes((c) -> setTps(c.getSource(), getFloat(c, "rate"))))).
then(literal("warp").
executes( (c)-> setWarp(c.getSource(), 0, null)).
then(argument("ticks", integer(0)).
suggests( (c, b) -> suggestMatching(new String[]{"3600","72000"},b)).
suggests( (c, b) -> suggest(new String[]{"3600","72000"},b)).
executes((c) -> setWarp(c.getSource(), getInteger(c,"ticks"), null)).
then(argument("tail command", greedyString()).
executes( (c) -> setWarp(
@@ -53,7 +53,7 @@ public class TickCommand
then(literal("step").
executes((c) -> step(c.getSource(), 1)).
then(argument("ticks", integer(1,72000)).
suggests( (c, b) -> suggestMatching(new String[]{"20"},b)).
suggests( (c, b) -> suggest(new String[]{"20"},b)).
executes((c) -> step(c.getSource(), getInteger(c,"ticks"))))).
then(literal("superHot").executes( (c)-> toggleSuperHot(c.getSource()))).
then(literal("health").
@@ -70,35 +70,35 @@ public class TickCommand
}
private static int setTps(ServerCommandSource source, float tps)
private static int setTps(CommandSourceStack source, float tps)
{
TickSpeed.tickrate(tps, true);
queryTps(source);
return (int)tps;
}
private static int queryTps(ServerCommandSource source)
private static int queryTps(CommandSourceStack source)
{
Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", TickSpeed.tickrate));
return (int)TickSpeed.tickrate;
}
private static int setWarp(ServerCommandSource source, int advance, String tail_command)
private static int setWarp(CommandSourceStack source, int advance, String tail_command)
{
ServerPlayerEntity player = null;
ServerPlayer player = null;
try
{
player = source.getPlayer();
player = source.getPlayerOrException();
}
catch (CommandSyntaxException ignored)
{
}
BaseText message = TickSpeed.tickrate_advance(player, advance, tail_command, source);
source.sendFeedback(message, false);
BaseComponent message = TickSpeed.tickrate_advance(player, advance, tail_command, source);
source.sendSuccess(message, false);
return 1;
}
private static int freezeStatus(ServerCommandSource source)
private static int freezeStatus(CommandSourceStack source)
{
if(TickSpeed.isPaused())
{
@@ -111,7 +111,7 @@ public class TickCommand
return 1;
}
private static int setFreeze(ServerCommandSource source, boolean isDeep, boolean freeze)
private static int setFreeze(CommandSourceStack source, boolean isDeep, boolean freeze)
{
TickSpeed.setFrozenState(freeze, isDeep);
if (TickSpeed.isPaused())
@@ -125,19 +125,19 @@ public class TickCommand
return 1;
}
private static int toggleFreeze(ServerCommandSource source, boolean isDeep)
private static int toggleFreeze(CommandSourceStack source, boolean isDeep)
{
return setFreeze(source, isDeep, !TickSpeed.isPaused());
}
private static int step(ServerCommandSource source, int advance)
private static int step(CommandSourceStack source, int advance)
{
TickSpeed.add_ticks_to_run_in_pause(advance);
Messenger.m(source, "gi Stepping " + advance + " tick" + (advance != 1 ? "s" : ""));
return 1;
}
private static int toggleSuperHot(ServerCommandSource source)
private static int toggleSuperHot(CommandSourceStack source)
{
TickSpeed.is_superHot = !TickSpeed.is_superHot;
ServerNetworkHandler.updateSuperHotStateToConnectedPlayers();
@@ -152,13 +152,13 @@ public class TickCommand
return 1;
}
public static int healthReport(ServerCommandSource source, int ticks)
public static int healthReport(CommandSourceStack source, int ticks)
{
CarpetProfiler.prepare_tick_report(source, ticks);
return 1;
}
public static int healthEntities(ServerCommandSource source, int ticks)
public static int healthEntities(CommandSourceStack source, int ticks)
{
CarpetProfiler.prepare_entity_report(source, ticks);
return 1;
@@ -1,10 +1,10 @@
package carpet.fakes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
public interface BiomeArrayInterface // unused
{
void setBiomeAtIndex(BlockPos pos, World world, Biome what);
void setBiomeAtIndex(BlockPos pos, Level world, Biome what);
}
@@ -1,6 +1,6 @@
package carpet.fakes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.core.BlockPos;
public interface BlockEntityInterface
{
@@ -1,17 +1,16 @@
package carpet.fakes;
import carpet.script.value.Value;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.tag.Tag;
import java.util.Map;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.tags.Tag;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
public interface BlockPredicateInterface
{
BlockState getCMBlockState();
Tag<Block> getCMBlockTag();
Map<Value, Value> getCMProperties();
NbtCompound getCMDataTag();
CompoundTag getCMDataTag();
}
@@ -1,8 +1,8 @@
package carpet.fakes;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.CompoundTag;
public interface BlockStateArgumentInterface
{
NbtCompound getCMTag();
CompoundTag getCMTag();
}
@@ -1,6 +1,6 @@
package carpet.fakes;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.level.biome.Biome;
public interface ChunkGeneratorInterface
{
@@ -1,15 +1,14 @@
package carpet.fakes;
import com.mojang.datafixers.util.Either;
import net.minecraft.server.world.ChunkHolder;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.thread.ThreadExecutor;
import net.minecraft.world.chunk.Chunk;
import java.util.concurrent.CompletableFuture;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkAccess;
public interface ChunkHolderInterface
{
CompletableFuture<Either<Chunk, ChunkHolder.Unloaded>> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor<Runnable> executor, ServerWorld world);
CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> setDefaultProtoChunk(ChunkPos chpos, BlockableEventLoop<Runnable> executor, ServerLevel world);
}
@@ -1,8 +1,8 @@
package carpet.fakes;
import net.minecraft.world.chunk.ChunkNibbleArray;
import net.minecraft.world.level.chunk.DataLayer;
public interface ChunkLightProviderInterface
{
int callGetCurrentLevelFromSection(ChunkNibbleArray array, long blockPos);
int callGetCurrentLevelFromSection(DataLayer array, long blockPos);
}
@@ -1,16 +1,16 @@
package carpet.fakes;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.server.world.ChunkHolder;
import net.minecraft.server.world.ChunkTicket;
import net.minecraft.util.collection.SortedArraySet;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.Ticket;
import net.minecraft.util.SortedArraySet;
import net.minecraft.world.level.ChunkPos;
public interface ChunkTicketManagerInterface
{
void changeSpawnChunks(ChunkPos pos, int distance);
Long2ObjectOpenHashMap<SortedArraySet<ChunkTicket<?>>> getTicketsByPosition();
Long2ObjectOpenHashMap<SortedArraySet<Ticket<?>>> getTicketsByPosition();
void replaceHolder(ChunkHolder oldHolder, ChunkHolder newHolder);
}
@@ -1,12 +1,11 @@
package carpet.fakes;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.Random;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
public interface CoralFeatureInterface
{
boolean growSpecific(World worldIn, Random random, BlockPos pos, BlockState blockUnder);
boolean growSpecific(Level worldIn, Random random, BlockPos pos, BlockState blockUnder);
}
@@ -1,9 +1,8 @@
package carpet.fakes;
import net.minecraft.item.ItemStack;
import java.util.Collection;
import java.util.List;
import net.minecraft.world.item.ItemStack;
public interface IngredientInterface
{
@@ -1,8 +1,8 @@
package carpet.fakes;
import net.minecraft.inventory.Inventory;
import net.minecraft.world.Container;
public interface InventoryBearerInterface
{
Inventory getCMInventory(); // can be removed in 1.17 due to class_6067
Container getCMInventory(); // can be removed in 1.17 due to class_6067
}
@@ -1,10 +1,10 @@
package carpet.fakes;
import net.minecraft.world.chunk.light.ChunkLightProvider;
import net.minecraft.world.level.lighting.LayerLightEngine;
public interface LightStorageInterface extends Lighting_scarpetChunkCreationInterface
{
void processRemoveLightData(long pos);
void processRelight(ChunkLightProvider<?, ?> lightProvider, long pos);
void processRelight(LayerLightEngine<?, ?> lightProvider, long pos);
}
@@ -1,18 +1,17 @@
package carpet.fakes;
import net.minecraft.resource.ServerResourceManager;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.World;
import net.minecraft.world.level.storage.LevelStorage;
import java.util.Map;
import java.util.function.BooleanSupplier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.ServerResources;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.storage.LevelStorageSource;
public interface MinecraftServerInterface
{
void forceTick(BooleanSupplier sup);
LevelStorage.Session getCMSession();
Map<RegistryKey<World>, ServerWorld> getCMWorlds();
ServerResourceManager getResourceManager();
LevelStorageSource.LevelStorageAccess getCMSession();
Map<ResourceKey<Level>, ServerLevel> getCMWorlds();
ServerResources getResourceManager();
}
@@ -1,9 +1,8 @@
package carpet.fakes;
import net.minecraft.entity.ai.goal.Goal;
import net.minecraft.entity.ai.goal.GoalSelector;
import java.util.Map;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.ai.goal.GoalSelector;
public interface MobEntityInterface
{
@@ -1,6 +1,6 @@
package carpet.fakes;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntity;
public interface PistonBlockEntityInterface
{
@@ -1,10 +1,10 @@
package carpet.fakes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.Level;
public interface PistonBlockInterface
{
boolean publicShouldExtend(World world_1, BlockPos blockPos_1, Direction direction_1);
boolean publicShouldExtend(Level world_1, BlockPos blockPos_1, Direction direction_1);
}
@@ -1,8 +1,6 @@
package carpet.fakes;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.FeatureConfig;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
public interface PlacedFeatureInterface {
ConfiguredFeature<?, ?> getRawFeature();
@@ -1,11 +1,9 @@
package carpet.fakes;
import net.minecraft.item.Item;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.RecipeType;
import net.minecraft.util.Identifier;
import java.util.List;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeType;
public interface RecipeManagerInterface
{
@@ -13,5 +11,5 @@ public interface RecipeManagerInterface
* Gets all the recipes for a given item. Also used for {@link carpet.helpers.HopperCounter#guessColor} to guess the
* colour of an item to display it prettily
*/
List<Recipe<?>> getAllMatching(RecipeType<?> type, Identifier output);
List<Recipe<?>> getAllMatching(RecipeType<?> type, ResourceLocation output);
}
@@ -1,11 +1,11 @@
package carpet.fakes;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
public interface RedstoneWireBlockInterface {
BlockState updateLogicPublic(World world_1, BlockPos blockPos_1, BlockState blockState_1);
BlockState updateLogicPublic(Level world_1, BlockPos blockPos_1, BlockState blockState_1);
void setWiresGivePower(boolean wiresGivePower);
boolean getWiresGivePower();
}
@@ -1,12 +1,12 @@
package carpet.fakes;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.recipe.Recipe;
import net.minecraft.screen.Property;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.DataSlot;
import net.minecraft.world.item.crafting.Recipe;
public interface ScreenHandlerInterface {
Property getProperty(int index);
boolean callButtonClickListener(int button, PlayerEntity player);
boolean callSelectRecipeListener(ServerPlayerEntity player, Recipe<?> recipe, boolean craftAll);
DataSlot getProperty(int index);
boolean callButtonClickListener(int button, Player player);
boolean callSelectRecipeListener(ServerPlayer player, Recipe<?> recipe, boolean craftAll);
}
@@ -1,8 +1,8 @@
package carpet.fakes;
import net.minecraft.server.world.ChunkTicketManager;
import net.minecraft.server.level.DistanceManager;
public interface ServerChunkManagerInterface
{
ChunkTicketManager getCMTicketManager();
DistanceManager getCMTicketManager();
}
@@ -1,17 +1,16 @@
package carpet.fakes;
import java.util.concurrent.CompletableFuture;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkAccess;
public interface ServerLightingProviderInterface
{
void invokeUpdateChunkStatus(ChunkPos pos);
void removeLightData(Chunk chunk);
void removeLightData(ChunkAccess chunk);
CompletableFuture<Void> relight(Chunk chunk);
CompletableFuture<Void> relight(ChunkAccess chunk);
void resetLight(Chunk chunk, ChunkPos pos);
void resetLight(ChunkAccess chunk, ChunkPos pos);
}
@@ -1,6 +1,6 @@
package carpet.fakes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.core.BlockPos;
public interface ServerPlayerInteractionManagerInterface
{
@@ -1,10 +1,10 @@
package carpet.fakes;
import net.minecraft.entity.Entity;
import net.minecraft.world.entity.EntityLookup;
import net.minecraft.world.level.ServerWorldProperties;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.entity.LevelEntityGetter;
import net.minecraft.world.level.storage.ServerLevelData;
public interface ServerWorldInterface {
ServerWorldProperties getWorldPropertiesCM();
EntityLookup<Entity> getEntityLookupCMPublic();
ServerLevelData getWorldPropertiesCM();
LevelEntityGetter<Entity> getEntityLookupCMPublic();
}
@@ -1,11 +1,10 @@
package carpet.fakes;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.entity.EntityLike;
import java.util.List;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.entity.EntityAccess;
public interface SimpleEntityLookupInterface<T extends EntityLike>
public interface SimpleEntityLookupInterface<T extends EntityAccess>
{
List<T> getChunkEntities(ChunkPos chpos);
}
@@ -1,10 +1,10 @@
package carpet.fakes;
import net.minecraft.util.math.GravityField;
import net.minecraft.world.level.PotentialCalculator;
public interface SpawnHelperInnerInterface
{
GravityField getPotentialCalculator();
PotentialCalculator getPotentialCalculator();
int cmGetChunkCount();
}
@@ -1,16 +1,12 @@
package carpet.fakes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.HeightLimitView;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.source.BiomeSource;
import net.minecraft.world.gen.random.ChunkRandom;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.feature.FeatureConfig;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
public interface StructureFeatureInterface<C extends FeatureConfig>
public interface StructureFeatureInterface<C extends FeatureConfiguration>
{
boolean plopAnywhere(ServerWorld world, BlockPos pos, ChunkGenerator generator, boolean wireOnly,Biome biome, C config);
boolean plopAnywhere(ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly,Biome biome, C config);
}
@@ -2,9 +2,8 @@ package carpet.fakes;
import java.util.List;
import java.util.Map;
import net.minecraft.server.world.ChunkHolder;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.world.level.ChunkPos;
public interface ThreadedAnvilChunkStorageInterface
{
@@ -1,8 +1,8 @@
package carpet.fakes;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
public interface WorldChunkInterface
{
@@ -1,16 +1,16 @@
package carpet.fakes;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Box;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
public interface WorldInterface
{
@@ -18,5 +18,5 @@ public interface WorldInterface
boolean setBlockStateWithBlockEntity(BlockPos blockPos, BlockState blockState, BlockEntity newBlockEntity, int int1);
List<Entity> getOtherEntitiesLimited(@Nullable Entity except, Box box, Predicate<? super Entity> predicate, int limit);
List<Entity> getOtherEntitiesLimited(@Nullable Entity except, AABB box, Predicate<? super Entity> predicate, int limit);
}
+139 -139
View File
@@ -1,55 +1,55 @@
package carpet.helpers;
import carpet.fakes.PistonBlockInterface;
import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockSource;
import net.minecraft.core.Direction;
import net.minecraft.core.dispenser.DispenseItemBehavior;
import net.minecraft.core.dispenser.OptionalDispenseItemBehavior;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseRailBlock;
import net.minecraft.world.level.block.BedBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.ComparatorBlock;
import net.minecraft.world.level.block.DiodeBlock;
import net.minecraft.world.level.block.DirectionalBlock;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.level.block.EndRodBlock;
import net.minecraft.world.level.block.FenceGateBlock;
import net.minecraft.world.level.block.GlazedTerracottaBlock;
import net.minecraft.world.level.block.HopperBlock;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.LeverBlock;
import net.minecraft.world.level.block.ObserverBlock;
import net.minecraft.world.level.block.RepeaterBlock;
import net.minecraft.world.level.block.RotatedPillarBlock;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.SlabBlock;
import net.minecraft.world.level.block.StairBlock;
import net.minecraft.world.level.block.TrapDoorBlock;
import net.minecraft.world.level.block.piston.PistonBaseBlock;
import net.minecraft.world.level.block.piston.PistonStructureResolver;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.ComparatorMode;
import net.minecraft.world.level.block.state.properties.Half;
import net.minecraft.world.level.block.state.properties.SlabType;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import carpet.CarpetSettings;
import net.minecraft.block.AbstractRailBlock;
import net.minecraft.block.AbstractRedstoneGateBlock;
import net.minecraft.block.BedBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.ComparatorBlock;
import net.minecraft.block.DispenserBlock;
import net.minecraft.block.EndRodBlock;
import net.minecraft.block.FacingBlock;
import net.minecraft.block.FenceGateBlock;
import net.minecraft.block.GlazedTerracottaBlock;
import net.minecraft.block.HopperBlock;
import net.minecraft.block.HorizontalFacingBlock;
import net.minecraft.block.LeverBlock;
import net.minecraft.block.ObserverBlock;
import net.minecraft.block.PillarBlock;
import net.minecraft.block.PistonBlock;
import net.minecraft.block.RepeaterBlock;
import net.minecraft.block.SlabBlock;
import net.minecraft.block.StairsBlock;
import net.minecraft.block.TrapdoorBlock;
import net.minecraft.block.dispenser.DispenserBehavior;
import net.minecraft.block.dispenser.FallibleItemDispenserBehavior;
import net.minecraft.block.enums.BlockHalf;
import net.minecraft.block.enums.ComparatorMode;
import net.minecraft.block.enums.SlabType;
import net.minecraft.block.piston.PistonHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPointer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
public class BlockRotator
{
public static boolean flipBlockWithCactus(BlockState state, World world, PlayerEntity player, Hand hand, BlockHitResult hit)
public static boolean flipBlockWithCactus(BlockState state, Level world, Player player, InteractionHand hand, BlockHitResult hit)
{ //getAbilities()
if (!player.getAbilities().allowModifyWorld || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player))
if (!player.getAbilities().mayBuild || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player))
{
return false;
}
@@ -59,14 +59,14 @@ public class BlockRotator
return retval;
}
public static BlockState alternativeBlockPlacement(Block block, ItemPlacementContext context)//World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
public static BlockState alternativeBlockPlacement(Block block, BlockPlaceContext context)//World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
//actual alternative block placement code
//
if (true) throw new UnsupportedOperationException("Alternative Block Placement / client controlled / is not implemnted");
Direction facing;
Vec3d vec3d = context.getHitPos();
Vec3 vec3d = context.getClickLocation();
float hitX = (float) vec3d.x;
if (hitX<2) // vanilla
@@ -76,75 +76,75 @@ public class BlockRotator
// now it would be great if hitX was adjusted in context to original range from 0.0 to 1.0
// since its actually using it. Its private - maybe with Reflections?
//
PlayerEntity placer = context.getPlayer();
BlockPos pos = context.getBlockPos();
World world = context.getWorld();
Player placer = context.getPlayer();
BlockPos pos = context.getClickedPos();
Level world = context.getLevel();
if (block instanceof GlazedTerracottaBlock)
{
facing = Direction.byId(code);
facing = Direction.from3DDataValue(code);
if(facing == Direction.UP || facing == Direction.DOWN)
{
facing = placer.getHorizontalFacing().getOpposite();
facing = placer.getDirection().getOpposite();
}
return block.getDefaultState().with(HorizontalFacingBlock.FACING, facing);
return block.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, facing);
}
else if (block instanceof ObserverBlock)
{
return block.getDefaultState()
.with(FacingBlock.FACING, Direction.byId(code))
.with(ObserverBlock.POWERED, true);
return block.defaultBlockState()
.setValue(DirectionalBlock.FACING, Direction.from3DDataValue(code))
.setValue(ObserverBlock.POWERED, true);
}
else if (block instanceof RepeaterBlock)
{
facing = Direction.byId(code % 16);
facing = Direction.from3DDataValue(code % 16);
if(facing == Direction.UP || facing == Direction.DOWN)
{
facing = placer.getHorizontalFacing().getOpposite();
facing = placer.getDirection().getOpposite();
}
return block.getDefaultState()
.with(HorizontalFacingBlock.FACING, facing)
.with(RepeaterBlock.DELAY, MathHelper.clamp(code / 16, 1, 4))
.with(RepeaterBlock.LOCKED, Boolean.FALSE);
return block.defaultBlockState()
.setValue(HorizontalDirectionalBlock.FACING, facing)
.setValue(RepeaterBlock.DELAY, Mth.clamp(code / 16, 1, 4))
.setValue(RepeaterBlock.LOCKED, Boolean.FALSE);
}
else if (block instanceof TrapdoorBlock)
else if (block instanceof TrapDoorBlock)
{
return block.getDefaultState()
.with(TrapdoorBlock.FACING, Direction.byId(code % 16))
.with(TrapdoorBlock.OPEN, Boolean.FALSE)
.with(TrapdoorBlock.HALF, (code >= 16) ? BlockHalf.TOP : BlockHalf.BOTTOM)
.with(TrapdoorBlock.OPEN, world.isReceivingRedstonePower(pos));
return block.defaultBlockState()
.setValue(TrapDoorBlock.FACING, Direction.from3DDataValue(code % 16))
.setValue(TrapDoorBlock.OPEN, Boolean.FALSE)
.setValue(TrapDoorBlock.HALF, (code >= 16) ? Half.TOP : Half.BOTTOM)
.setValue(TrapDoorBlock.OPEN, world.hasNeighborSignal(pos));
}
else if (block instanceof ComparatorBlock)
{
facing = Direction.byId(code % 16);
facing = Direction.from3DDataValue(code % 16);
if((facing == Direction.UP) || (facing == Direction.DOWN))
{
facing = placer.getHorizontalFacing().getOpposite();
facing = placer.getDirection().getOpposite();
}
ComparatorMode m = (hitX >= 16)?ComparatorMode.SUBTRACT: ComparatorMode.COMPARE;
return block.getDefaultState()
.with(HorizontalFacingBlock.FACING, facing)
.with(ComparatorBlock.POWERED, Boolean.FALSE)
.with(ComparatorBlock.MODE, m);
return block.defaultBlockState()
.setValue(HorizontalDirectionalBlock.FACING, facing)
.setValue(ComparatorBlock.POWERED, Boolean.FALSE)
.setValue(ComparatorBlock.MODE, m);
}
else if (block instanceof DispenserBlock)
{
return block.getDefaultState()
.with(DispenserBlock.FACING, Direction.byId(code))
.with(DispenserBlock.TRIGGERED, Boolean.FALSE);
return block.defaultBlockState()
.setValue(DispenserBlock.FACING, Direction.from3DDataValue(code))
.setValue(DispenserBlock.TRIGGERED, Boolean.FALSE);
}
else if (block instanceof PistonBlock)
else if (block instanceof PistonBaseBlock)
{
return block.getDefaultState()
.with(FacingBlock.FACING, Direction.byId(code))
.with(PistonBlock.EXTENDED, Boolean.FALSE);
return block.defaultBlockState()
.setValue(DirectionalBlock.FACING, Direction.from3DDataValue(code))
.setValue(PistonBaseBlock.EXTENDED, Boolean.FALSE);
}
else if (block instanceof StairsBlock)
else if (block instanceof StairBlock)
{
return block.getPlacementState(context)//worldIn, pos, facing, hitX, hitY, hitZ, meta, placer)
.with(StairsBlock.FACING, Direction.byId(code % 16))
.with(StairsBlock.HALF, ( hitX >= 16)?BlockHalf.TOP : BlockHalf.BOTTOM);
return block.getStateForPlacement(context)//worldIn, pos, facing, hitX, hitY, hitZ, meta, placer)
.setValue(StairBlock.FACING, Direction.from3DDataValue(code % 16))
.setValue(StairBlock.HALF, ( hitX >= 16)?Half.TOP : Half.BOTTOM);
}
return null;
}
@@ -222,109 +222,109 @@ public class BlockRotator
}
}
public static ItemStack dispenserRotate(BlockPointer source, ItemStack stack)
public static ItemStack dispenserRotate(BlockSource source, ItemStack stack)
{
Direction sourceFace = source.getBlockState().get(DispenserBlock.FACING);
World world = source.getWorld();
BlockPos blockpos = source.getPos().offset(sourceFace); // offset
Direction sourceFace = source.getBlockState().getValue(DispenserBlock.FACING);
Level world = source.getLevel();
BlockPos blockpos = source.getPos().relative(sourceFace); // offset
BlockState iblockstate = world.getBlockState(blockpos);
Block block = iblockstate.getBlock();
// Block rotation for blocks that can be placed in all 6 or 4 rotations.
if(block instanceof FacingBlock || block instanceof DispenserBlock)
if(block instanceof DirectionalBlock || block instanceof DispenserBlock)
{
Direction face = iblockstate.get(FacingBlock.FACING);
if (block instanceof PistonBlock && (
iblockstate.get(PistonBlock.EXTENDED)
|| ( ((PistonBlockInterface)block).publicShouldExtend(world, blockpos, face) && (new PistonHandler(world, blockpos, face, true)).calculatePush() )
Direction face = iblockstate.getValue(DirectionalBlock.FACING);
if (block instanceof PistonBaseBlock && (
iblockstate.getValue(PistonBaseBlock.EXTENDED)
|| ( ((PistonBlockInterface)block).publicShouldExtend(world, blockpos, face) && (new PistonStructureResolver(world, blockpos, face, true)).resolve() )
)
)
return stack;
Direction rotated_face = rotateClockwise(face, sourceFace.getAxis());
if(sourceFace.getId() % 2 == 0 || rotated_face == face)
if(sourceFace.get3DDataValue() % 2 == 0 || rotated_face == face)
{ // Flip to make blocks always rotate clockwise relative to the dispenser
// when index is equal to zero. when index is equal to zero the dispenser is in the opposite direction.
rotated_face = rotated_face.getOpposite();
}
world.setBlockState(blockpos, iblockstate.with(FacingBlock.FACING, rotated_face), 3);
world.setBlock(blockpos, iblockstate.setValue(DirectionalBlock.FACING, rotated_face), 3);
}
else if(block instanceof HorizontalFacingBlock) // Block rotation for blocks that can be placed in only 4 horizontal rotations.
else if(block instanceof HorizontalDirectionalBlock) // Block rotation for blocks that can be placed in only 4 horizontal rotations.
{
if (block instanceof BedBlock)
return stack;
Direction face = iblockstate.get(HorizontalFacingBlock.FACING);
Direction face = iblockstate.getValue(HorizontalDirectionalBlock.FACING);
face = rotateClockwise(face, Direction.Axis.Y);
if(sourceFace == Direction.DOWN)
{ // same as above.
face = face.getOpposite();
}
world.setBlockState(blockpos, iblockstate.with(HorizontalFacingBlock.FACING, face), 3);
world.setBlock(blockpos, iblockstate.setValue(HorizontalDirectionalBlock.FACING, face), 3);
}
else if(block == Blocks.HOPPER )
{
Direction face = iblockstate.get(HopperBlock.FACING);
Direction face = iblockstate.getValue(HopperBlock.FACING);
if (face != Direction.DOWN)
{
face = rotateClockwise(face, Direction.Axis.Y);
world.setBlockState(blockpos, iblockstate.with(HopperBlock.FACING, face), 3);
world.setBlock(blockpos, iblockstate.setValue(HopperBlock.FACING, face), 3);
}
}
// Send block update to the block that just have been rotated.
world.updateNeighbor(blockpos, block, source.getPos());
world.neighborChanged(blockpos, block, source.getPos());
return stack;
}
public static boolean flip_block(BlockState state, World world, PlayerEntity player, Hand hand, BlockHitResult hit)
public static boolean flip_block(BlockState state, Level world, Player player, InteractionHand hand, BlockHitResult hit)
{
Block block = state.getBlock();
BlockPos pos = hit.getBlockPos();
Vec3d hitVec = hit.getPos().subtract(pos.getX(), pos.getY(), pos.getZ());
Direction facing = hit.getSide();
Vec3 hitVec = hit.getLocation().subtract(pos.getX(), pos.getY(), pos.getZ());
Direction facing = hit.getDirection();
BlockState newState = null;
if ( (block instanceof GlazedTerracottaBlock) || (block instanceof AbstractRedstoneGateBlock) || (block instanceof AbstractRailBlock) ||
(block instanceof TrapdoorBlock) || (block instanceof LeverBlock) || (block instanceof FenceGateBlock))
if ( (block instanceof GlazedTerracottaBlock) || (block instanceof DiodeBlock) || (block instanceof BaseRailBlock) ||
(block instanceof TrapDoorBlock) || (block instanceof LeverBlock) || (block instanceof FenceGateBlock))
{
newState = state.rotate(BlockRotation.CLOCKWISE_90);
newState = state.rotate(Rotation.CLOCKWISE_90);
}
else if ((block instanceof ObserverBlock) || (block instanceof EndRodBlock))
{
newState = state.with(FacingBlock.FACING, state.get(FacingBlock.FACING).getOpposite());
newState = state.setValue(DirectionalBlock.FACING, state.getValue(DirectionalBlock.FACING).getOpposite());
}
else if (block instanceof DispenserBlock)
{
newState = state.with(DispenserBlock.FACING, state.get(DispenserBlock.FACING).getOpposite());
newState = state.setValue(DispenserBlock.FACING, state.getValue(DispenserBlock.FACING).getOpposite());
}
else if (block instanceof PistonBlock)
else if (block instanceof PistonBaseBlock)
{
if (!(state.get(PistonBlock.EXTENDED)))
newState = state.with(FacingBlock.FACING, state.get(FacingBlock.FACING).getOpposite());
if (!(state.getValue(PistonBaseBlock.EXTENDED)))
newState = state.setValue(DirectionalBlock.FACING, state.getValue(DirectionalBlock.FACING).getOpposite());
}
else if (block instanceof SlabBlock)
{
if (((SlabBlock) block).hasSidedTransparency(state))
if (((SlabBlock) block).useShapeForLightOcclusion(state))
{
newState = state.with(SlabBlock.TYPE, state.get(SlabBlock.TYPE) == SlabType.TOP ? SlabType.BOTTOM : SlabType.TOP);
newState = state.setValue(SlabBlock.TYPE, state.getValue(SlabBlock.TYPE) == SlabType.TOP ? SlabType.BOTTOM : SlabType.TOP);
}
}
else if (block instanceof HopperBlock)
{
if (state.get(HopperBlock.FACING) != Direction.DOWN)
if (state.getValue(HopperBlock.FACING) != Direction.DOWN)
{
newState = state.with(HopperBlock.FACING, state.get(HopperBlock.FACING).rotateYClockwise());
newState = state.setValue(HopperBlock.FACING, state.getValue(HopperBlock.FACING).getClockWise());
}
}
else if (block instanceof StairsBlock)
else if (block instanceof StairBlock)
{
//LOG.error(String.format("hit with facing: %s, at side %.1fX, X %.1fY, Y %.1fZ",facing, hitX, hitY, hitZ));
if ((facing == Direction.UP && hitVec.y == 1.0f) || (facing == Direction.DOWN && hitVec.y == 0.0f))
{
newState = state.with(StairsBlock.HALF, state.get(StairsBlock.HALF) == BlockHalf.TOP ? BlockHalf.BOTTOM : BlockHalf.TOP );
newState = state.setValue(StairBlock.HALF, state.getValue(StairBlock.HALF) == Half.TOP ? Half.BOTTOM : Half.TOP );
}
else
{
@@ -351,25 +351,25 @@ public class BlockRotator
}
if (turn_right)
{
newState = state.rotate(BlockRotation.COUNTERCLOCKWISE_90);
newState = state.rotate(Rotation.COUNTERCLOCKWISE_90);
}
else
{
newState = state.rotate(BlockRotation.CLOCKWISE_90);
newState = state.rotate(Rotation.CLOCKWISE_90);
}
}
}
else if (block instanceof PillarBlock)
else if (block instanceof RotatedPillarBlock)
{
switch((Direction.Axis)state.get(PillarBlock.AXIS)) {
switch((Direction.Axis)state.getValue(RotatedPillarBlock.AXIS)) {
case X:
newState = (BlockState)state.with(PillarBlock.AXIS, Direction.Axis.Z);
newState = (BlockState)state.setValue(RotatedPillarBlock.AXIS, Direction.Axis.Z);
break;
case Z:
newState = (BlockState)state.with(PillarBlock.AXIS, Direction.Axis.Y);
newState = (BlockState)state.setValue(RotatedPillarBlock.AXIS, Direction.Axis.Y);
break;
case Y:
newState = (BlockState)state.with(PillarBlock.AXIS, Direction.Axis.X);
newState = (BlockState)state.setValue(RotatedPillarBlock.AXIS, Direction.Axis.X);
break;
}
}
@@ -379,34 +379,34 @@ public class BlockRotator
}
if (newState != null)
{
world.setBlockState(pos, newState, 2 | 1024);
world.scheduleBlockRerenderIfNeeded(pos, state, newState);
world.setBlock(pos, newState, 2 | 1024);
world.setBlocksDirty(pos, state, newState);
return true;
}
return false;
}
private static boolean player_holds_cactus_mainhand(PlayerEntity playerIn)
private static boolean player_holds_cactus_mainhand(Player playerIn)
{
return (!playerIn.getMainHandStack().isEmpty()
&& playerIn.getMainHandStack().getItem() instanceof BlockItem &&
((BlockItem) (playerIn.getMainHandStack().getItem())).getBlock() == Blocks.CACTUS);
return (!playerIn.getMainHandItem().isEmpty()
&& playerIn.getMainHandItem().getItem() instanceof BlockItem &&
((BlockItem) (playerIn.getMainHandItem().getItem())).getBlock() == Blocks.CACTUS);
}
public static boolean flippinEligibility(Entity entity)
{
if (CarpetSettings.flippinCactus && (entity instanceof PlayerEntity))
if (CarpetSettings.flippinCactus && (entity instanceof Player))
{
PlayerEntity player = (PlayerEntity)entity;
return (!player.getOffHandStack().isEmpty()
&& player.getOffHandStack().getItem() instanceof BlockItem &&
((BlockItem) (player.getOffHandStack().getItem())).getBlock() == Blocks.CACTUS);
Player player = (Player)entity;
return (!player.getOffhandItem().isEmpty()
&& player.getOffhandItem().getItem() instanceof BlockItem &&
((BlockItem) (player.getOffhandItem().getItem())).getBlock() == Blocks.CACTUS);
}
return false;
}
public static class CactusDispenserBehaviour extends FallibleItemDispenserBehavior implements DispenserBehavior
public static class CactusDispenserBehaviour extends OptionalDispenseItemBehavior implements DispenseItemBehavior
{
@Override
protected ItemStack dispenseSilently(BlockPointer source, ItemStack stack)
protected ItemStack execute(BlockSource source, ItemStack stack)
{
if (CarpetSettings.rotatorBlock)
{
@@ -414,7 +414,7 @@ public class BlockRotator
}
else
{
return super.dispenseSilently(source, stack);
return super.execute(source, stack);
}
}
}
@@ -1,15 +1,15 @@
package carpet.helpers;
import net.minecraft.block.Material;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldAccess;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.material.Material;
public class BlockSaplingHelper
{
// Added code for checking water for dead shrub rule
public static boolean hasWater(WorldAccess worldIn, BlockPos pos)
public static boolean hasWater(LevelAccessor worldIn, BlockPos pos)
{
for (BlockPos blockpos$mutableblockpos : BlockPos.iterate(pos.add(-4, -4, -4), pos.add(4, 1, 4)))
for (BlockPos blockpos$mutableblockpos : BlockPos.betweenClosed(pos.offset(-4, -4, -4), pos.offset(4, 1, 4)))
{
if (worldIn.getBlockState(blockpos$mutableblockpos).getMaterial() == Material.WATER)
{
@@ -1,16 +1,16 @@
package carpet.helpers;
import net.minecraft.entity.EntityType;
import net.minecraft.util.collection.Pool;
import net.minecraft.world.biome.SpawnSettings;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.biome.MobSpawnSettings;
public class CustomSpawnLists
{
public static final Pool<SpawnSettings.SpawnEntry> PYRAMID_SPAWNS = Pool.of(new SpawnSettings.SpawnEntry(EntityType.HUSK, 1, 1, 1));
public static final Pool<SpawnSettings.SpawnEntry> SHULKER_SPAWNS = Pool.of(new SpawnSettings.SpawnEntry(EntityType.SHULKER, 10, 4, 4));
public static final Pool<SpawnSettings.SpawnEntry> BASTION_SPAWNS = Pool.of(
new SpawnSettings.SpawnEntry(EntityType.PIGLIN_BRUTE, 5, 1, 2),
new SpawnSettings.SpawnEntry(EntityType.PIGLIN, 10, 2, 4),
new SpawnSettings.SpawnEntry(EntityType.HOGLIN, 2, 1, 2)
public static final WeightedRandomList<MobSpawnSettings.SpawnerData> PYRAMID_SPAWNS = WeightedRandomList.create(new MobSpawnSettings.SpawnerData(EntityType.HUSK, 1, 1, 1));
public static final WeightedRandomList<MobSpawnSettings.SpawnerData> SHULKER_SPAWNS = WeightedRandomList.create(new MobSpawnSettings.SpawnerData(EntityType.SHULKER, 10, 4, 4));
public static final WeightedRandomList<MobSpawnSettings.SpawnerData> BASTION_SPAWNS = WeightedRandomList.create(
new MobSpawnSettings.SpawnerData(EntityType.PIGLIN_BRUTE, 5, 1, 2),
new MobSpawnSettings.SpawnerData(EntityType.PIGLIN, 10, 2, 4),
new MobSpawnSettings.SpawnerData(EntityType.HOGLIN, 2, 1, 2)
);
}
@@ -1,38 +1,37 @@
package carpet.helpers;
import carpet.fakes.ServerPlayerEntityInterface;
import net.minecraft.block.BlockState;
import net.minecraft.command.argument.EntityAnchorArgumentType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.decoration.ItemFrameEntity;
import net.minecraft.entity.passive.HorseBaseEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.entity.vehicle.BoatEntity;
import net.minecraft.entity.vehicle.MinecartEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.network.packet.s2c.play.UpdateSelectedSlotS2CPacket;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec2f;
import net.minecraft.util.math.Vec3d;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.animal.horse.AbstractHorse;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.entity.vehicle.Minecart;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public class EntityPlayerActionPack
{
private final ServerPlayerEntity player;
private final ServerPlayer player;
private final Map<ActionType, Action> actions = new TreeMap<>();
@@ -48,7 +47,7 @@ public class EntityPlayerActionPack
private int itemUseCooldown;
public EntityPlayerActionPack(ServerPlayerEntity playerIn)
public EntityPlayerActionPack(ServerPlayer playerIn)
{
player = playerIn;
stopAll();
@@ -84,7 +83,7 @@ public class EntityPlayerActionPack
public EntityPlayerActionPack setSneaking(boolean doSneak)
{
sneaking = doSneak;
player.setSneaking(doSneak);
player.setShiftKeyDown(doSneak);
if (sprinting && sneaking)
setSprinting(false);
return this;
@@ -116,36 +115,36 @@ public class EntityPlayerActionPack
case SOUTH: return look(0, 0);
case EAST: return look(-90, 0);
case WEST: return look(90, 0);
case UP: return look(player.getYaw(), -90);
case DOWN: return look(player.getYaw(), 90);
case UP: return look(player.getYRot(), -90);
case DOWN: return look(player.getYRot(), 90);
}
return this;
}
public EntityPlayerActionPack look(Vec2f rotation)
public EntityPlayerActionPack look(Vec2 rotation)
{
return look(rotation.x, rotation.y);
}
public EntityPlayerActionPack look(float yaw, float pitch)
{
player.setYaw(yaw % 360); //setYaw
player.setPitch(MathHelper.clamp(pitch, -90, 90)); // setPitch
player.setYRot(yaw % 360); //setYaw
player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch
// maybe player.setPositionAndAngles(player.x, player.y, player.z, yaw, MathHelper.clamp(pitch,-90.0F, 90.0F));
return this;
}
public EntityPlayerActionPack lookAt(Vec3d position)
public EntityPlayerActionPack lookAt(Vec3 position)
{
player.lookAt(EntityAnchorArgumentType.EntityAnchor.EYES, position);
player.lookAt(EntityAnchorArgument.Anchor.EYES, position);
return this;
}
public EntityPlayerActionPack turn(float yaw, float pitch)
{
return look(player.getYaw() + yaw, player.getPitch() + pitch);
return look(player.getYRot() + yaw, player.getXRot() + pitch);
}
public EntityPlayerActionPack turn(Vec2f rotation)
public EntityPlayerActionPack turn(Vec2 rotation)
{
return turn(rotation.x, rotation.y);
}
@@ -173,12 +172,12 @@ public class EntityPlayerActionPack
List<Entity> entities;
if (onlyRideables)
{
entities = player.world.getOtherEntities(player, player.getBoundingBox().expand(3.0D, 1.0D, 3.0D),
e -> e instanceof MinecartEntity || e instanceof BoatEntity || e instanceof HorseBaseEntity);
entities = player.level.getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D),
e -> e instanceof Minecart || e instanceof Boat || e instanceof AbstractHorse);
}
else
{
entities = player.world.getOtherEntities(player, player.getBoundingBox().expand(3.0D, 1.0D, 3.0D));
entities = player.level.getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D));
}
if (entities.size()==0)
return this;
@@ -189,7 +188,7 @@ public class EntityPlayerActionPack
{
if (e == player || (currentVehicle == e))
continue;
double dd = player.squaredDistanceTo(e);
double dd = player.distanceToSqr(e);
if (dd<distance)
{
distance = dd;
@@ -197,8 +196,8 @@ public class EntityPlayerActionPack
}
}
if (closest == null) return this;
if (closest instanceof HorseBaseEntity && onlyRideables)
((HorseBaseEntity) closest).interactMob(player, Hand.MAIN_HAND);
if (closest instanceof AbstractHorse && onlyRideables)
((AbstractHorse) closest).mobInteract(player, InteractionHand.MAIN_HAND);
else
player.startRiding(closest,true);
return this;
@@ -238,49 +237,49 @@ public class EntityPlayerActionPack
}
if (forward != 0.0F)
{
player.forwardSpeed = forward*(sneaking?0.3F:1.0F);
player.zza = forward*(sneaking?0.3F:1.0F);
}
if (strafing != 0.0F)
{
player.sidewaysSpeed = strafing*(sneaking?0.3F:1.0F);
player.xxa = strafing*(sneaking?0.3F:1.0F);
}
}
static HitResult getTarget(ServerPlayerEntity player)
static HitResult getTarget(ServerPlayer player)
{
double reach = player.interactionManager.isCreative() ? 5 : 4.5f;
double reach = player.gameMode.isCreative() ? 5 : 4.5f;
return Tracer.rayTrace(player, 1, reach, false);
}
private void dropItemFromSlot(int slot, boolean dropAll)
{
PlayerInventory inv = player.getInventory(); // getInventory;
if (!inv.getStack(slot).isEmpty())
player.dropItem(inv.removeStack(slot,
dropAll ? inv.getStack(slot).getCount() : 1
Inventory inv = player.getInventory(); // getInventory;
if (!inv.getItem(slot).isEmpty())
player.drop(inv.removeItem(slot,
dropAll ? inv.getItem(slot).getCount() : 1
), false, true); // scatter, keep owner
}
public void drop(int selectedSlot, boolean dropAll)
{
PlayerInventory inv = player.getInventory(); // getInventory;
Inventory inv = player.getInventory(); // getInventory;
if (selectedSlot == -2) // all
{
for (int i = inv.size(); i >= 0; i--)
for (int i = inv.getContainerSize(); i >= 0; i--)
dropItemFromSlot(i, dropAll);
}
else // one slot
{
if (selectedSlot == -1)
selectedSlot = inv.selectedSlot;
selectedSlot = inv.selected;
dropItemFromSlot(selectedSlot, dropAll);
}
}
public void setSlot(int slot)
{
player.getInventory().selectedSlot = slot-1;
player.networkHandler.sendPacket(new UpdateSelectedSlotS2CPacket(slot-1));
player.getInventory().selected = slot-1;
player.connection.send(new ClientboundSetCarriedItemPacket(slot-1));
}
public enum ActionType
@@ -288,7 +287,7 @@ public class EntityPlayerActionPack
USE(true)
{
@Override
boolean execute(ServerPlayerEntity player, Action action)
boolean execute(ServerPlayer player, Action action)
{
EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack();
if (ap.itemUseCooldown > 0)
@@ -301,23 +300,23 @@ public class EntityPlayerActionPack
return true;
}
HitResult hit = getTarget(player);
for (Hand hand : Hand.values())
for (InteractionHand hand : InteractionHand.values())
{
switch (hit.getType())
{
case BLOCK:
{
player.updateLastActionTime();
ServerWorld world = player.getWorld();
player.resetLastActionTime();
ServerLevel world = player.getLevel();
BlockHitResult blockHit = (BlockHitResult) hit;
BlockPos pos = blockHit.getBlockPos();
Direction side = blockHit.getSide();
if (pos.getY() < player.getWorld().getTopY() - (side == Direction.UP ? 1 : 0) && world.canPlayerModifyAt(player, pos))
Direction side = blockHit.getDirection();
if (pos.getY() < player.getLevel().getMaxBuildHeight() - (side == Direction.UP ? 1 : 0) && world.mayInteract(player, pos))
{
ActionResult result = player.interactionManager.interactBlock(player, world, player.getStackInHand(hand), hand, blockHit);
if (result.isAccepted())
InteractionResult result = player.gameMode.useItemOn(player, world, player.getItemInHand(hand), hand, blockHit);
if (result.consumesAction())
{
if (result.shouldSwingHand()) player.swingHand(hand);
if (result.shouldSwing()) player.swing(hand);
ap.itemUseCooldown = 3;
return true;
}
@@ -326,19 +325,19 @@ public class EntityPlayerActionPack
}
case ENTITY:
{
player.updateLastActionTime();
player.resetLastActionTime();
EntityHitResult entityHit = (EntityHitResult) hit;
Entity entity = entityHit.getEntity();
boolean handWasEmpty = player.getStackInHand(hand).isEmpty();
boolean itemFrameEmpty = (entity instanceof ItemFrameEntity) && ((ItemFrameEntity) entity).getHeldItemStack().isEmpty();
Vec3d relativeHitPos = entityHit.getPos().subtract(entity.getX(), entity.getY(), entity.getZ());
if (entity.interactAt(player, relativeHitPos, hand).isAccepted())
boolean handWasEmpty = player.getItemInHand(hand).isEmpty();
boolean itemFrameEmpty = (entity instanceof ItemFrame) && ((ItemFrame) entity).getItem().isEmpty();
Vec3 relativeHitPos = entityHit.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ());
if (entity.interactAt(player, relativeHitPos, hand).consumesAction())
{
ap.itemUseCooldown = 3;
return true;
}
// fix for SS itemframe always returns CONSUME even if no action is performed
if (player.interact(entity, hand).isAccepted() && !(handWasEmpty && itemFrameEmpty))
if (player.interactOn(entity, hand).consumesAction() && !(handWasEmpty && itemFrameEmpty))
{
ap.itemUseCooldown = 3;
return true;
@@ -346,8 +345,8 @@ public class EntityPlayerActionPack
break;
}
}
ItemStack handItem = player.getStackInHand(hand);
if (player.interactionManager.interactItem(player, player.getWorld(), handItem, hand).isAccepted())
ItemStack handItem = player.getItemInHand(hand);
if (player.gameMode.useItem(player, player.getLevel(), handItem, hand).consumesAction())
{
ap.itemUseCooldown = 3;
return true;
@@ -357,16 +356,16 @@ public class EntityPlayerActionPack
}
@Override
void inactiveTick(ServerPlayerEntity player, Action action)
void inactiveTick(ServerPlayer player, Action action)
{
EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack();
ap.itemUseCooldown = 0;
player.stopUsingItem();
player.releaseUsingItem();
}
},
ATTACK(true) {
@Override
boolean execute(ServerPlayerEntity player, Action action) {
boolean execute(ServerPlayer player, Action action) {
HitResult hit = getTarget(player);
switch (hit.getType()) {
case ENTITY: {
@@ -374,10 +373,10 @@ public class EntityPlayerActionPack
if (!action.isContinuous)
{
player.attack(entityHit.getEntity());
player.swingHand(Hand.MAIN_HAND);
player.swing(InteractionHand.MAIN_HAND);
}
player.resetLastAttackedTicks();
player.updateLastActionTime();
player.resetAttackStrengthTicker();
player.resetLastActionTime();
return true;
}
case BLOCK: {
@@ -389,18 +388,18 @@ public class EntityPlayerActionPack
}
BlockHitResult blockHit = (BlockHitResult) hit;
BlockPos pos = blockHit.getBlockPos();
Direction side = blockHit.getSide();
if (player.isBlockBreakingRestricted(player.world, pos, player.interactionManager.getGameMode())) return false;
if (ap.currentBlock != null && player.world.getBlockState(ap.currentBlock).isAir())
Direction side = blockHit.getDirection();
if (player.blockActionRestricted(player.level, pos, player.gameMode.getGameModeForPlayer())) return false;
if (ap.currentBlock != null && player.level.getBlockState(ap.currentBlock).isAir())
{
ap.currentBlock = null;
return false;
}
BlockState state = player.world.getBlockState(pos);
BlockState state = player.level.getBlockState(pos);
boolean blockBroken = false;
if (player.interactionManager.getGameMode().isCreative())
if (player.gameMode.getGameModeForPlayer().isCreative())
{
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopY());
player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight());
ap.blockHitDelay = 5;
blockBroken = true;
}
@@ -408,15 +407,15 @@ public class EntityPlayerActionPack
{
if (ap.currentBlock != null)
{
player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, side, player.getWorld().getTopY());
player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight());
}
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopY());
player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight());
boolean notAir = !state.isAir();
if (notAir && ap.curBlockDamageMP == 0)
{
state.onBlockBreakStart(player.world, pos, player);
state.attack(player.level, pos, player);
}
if (notAir && state.calcBlockBreakingDelta(player, player.world, pos) >= 1)
if (notAir && state.getDestroyProgress(player, player.level, pos) >= 1)
{
ap.currentBlock = null;
//instamine??
@@ -430,19 +429,19 @@ public class EntityPlayerActionPack
}
else
{
ap.curBlockDamageMP += state.calcBlockBreakingDelta(player, player.world, pos);
ap.curBlockDamageMP += state.getDestroyProgress(player, player.level, pos);
if (ap.curBlockDamageMP >= 1)
{
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.getWorld().getTopY());
player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight());
ap.currentBlock = null;
ap.blockHitDelay = 5;
blockBroken = true;
}
player.world.setBlockBreakingInfo(-1, pos, (int) (ap.curBlockDamageMP * 10));
player.level.destroyBlockProgress(-1, pos, (int) (ap.curBlockDamageMP * 10));
}
player.updateLastActionTime();
player.swingHand(Hand.MAIN_HAND);
player.resetLastActionTime();
player.swing(InteractionHand.MAIN_HAND);
return blockBroken;
}
}
@@ -450,23 +449,23 @@ public class EntityPlayerActionPack
}
@Override
void inactiveTick(ServerPlayerEntity player, Action action)
void inactiveTick(ServerPlayer player, Action action)
{
EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack();
if (ap.currentBlock == null) return;
player.world.setBlockBreakingInfo(-1, ap.currentBlock, -1);
player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getWorld().getTopY());
player.level.destroyBlockProgress(-1, ap.currentBlock, -1);
player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getLevel().getMaxBuildHeight());
ap.currentBlock = null;
}
},
JUMP(true)
{
@Override
boolean execute(ServerPlayerEntity player, Action action)
boolean execute(ServerPlayer player, Action action)
{
if (action.limit == 1)
{
if (player.isOnGround()) player.jump(); // onGround
if (player.isOnGround()) player.jumpFromGround(); // onGround
}
else
{
@@ -476,7 +475,7 @@ public class EntityPlayerActionPack
}
@Override
void inactiveTick(ServerPlayerEntity player, Action action)
void inactiveTick(ServerPlayer player, Action action)
{
player.setJumping(false);
}
@@ -484,32 +483,32 @@ public class EntityPlayerActionPack
DROP_ITEM(true)
{
@Override
boolean execute(ServerPlayerEntity player, Action action)
boolean execute(ServerPlayer player, Action action)
{
player.updateLastActionTime();
player.dropSelectedItem(false); // dropSelectedItem
player.resetLastActionTime();
player.drop(false); // dropSelectedItem
return false;
}
},
DROP_STACK(true)
{
@Override
boolean execute(ServerPlayerEntity player, Action action)
boolean execute(ServerPlayer player, Action action)
{
player.updateLastActionTime();
player.dropSelectedItem(true); // dropSelectedItem
player.resetLastActionTime();
player.drop(true); // dropSelectedItem
return false;
}
},
SWAP_HANDS(true)
{
@Override
boolean execute(ServerPlayerEntity player, Action action)
boolean execute(ServerPlayer player, Action action)
{
player.updateLastActionTime();
ItemStack itemStack_1 = player.getStackInHand(Hand.OFF_HAND);
player.setStackInHand(Hand.OFF_HAND, player.getStackInHand(Hand.MAIN_HAND));
player.setStackInHand(Hand.MAIN_HAND, itemStack_1);
player.resetLastActionTime();
ItemStack itemStack_1 = player.getItemInHand(InteractionHand.OFF_HAND);
player.setItemInHand(InteractionHand.OFF_HAND, player.getItemInHand(InteractionHand.MAIN_HAND));
player.setItemInHand(InteractionHand.MAIN_HAND, itemStack_1);
return false;
}
};
@@ -521,10 +520,10 @@ public class EntityPlayerActionPack
this.preventSpectator = preventSpectator;
}
void start(ServerPlayerEntity player, Action action) {}
abstract boolean execute(ServerPlayerEntity player, Action action);
void inactiveTick(ServerPlayerEntity player, Action action) {}
void stop(ServerPlayerEntity player, Action action)
void start(ServerPlayer player, Action action) {}
abstract boolean execute(ServerPlayer player, Action action);
void inactiveTick(ServerPlayer player, Action action) {}
void stop(ServerPlayer player, Action action)
{
inactiveTick(player, action);
}
+130 -129
View File
@@ -4,80 +4,81 @@ import carpet.CarpetSettings;
import carpet.fakes.ChunkGeneratorInterface;
import carpet.fakes.PlacedFeatureInterface;
import carpet.fakes.StructureFeatureInterface;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMultimap;
import com.mojang.datafixers.util.Pair;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.structure.StructureStart;
import net.minecraft.structure.pool.StructurePool;
import net.minecraft.structure.pool.StructurePoolElement;
import net.minecraft.structure.processor.StructureProcessorLists;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.intprovider.ConstantIntProvider;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.StructurePresence;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeKeys;
import net.minecraft.world.biome.BuiltinBiomes;
import net.minecraft.world.gen.StructureAccessor;
import net.minecraft.world.gen.chunk.StructuresConfig;
import net.minecraft.world.gen.feature.ConfiguredStructureFeatures;
import net.minecraft.world.gen.feature.PlacedFeature;
import net.minecraft.world.gen.feature.size.TwoLayersFeatureSize;
import net.minecraft.world.gen.foliage.BlobFoliagePlacer;
import net.minecraft.world.gen.foliage.LargeOakFoliagePlacer;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.chunk.StructureConfig;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.ConfiguredStructureFeature;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.FeatureConfig;
import net.minecraft.world.gen.feature.SimpleRandomFeatureConfig;
import net.minecraft.world.gen.feature.StructureFeature;
import net.minecraft.world.gen.feature.StructurePoolFeatureConfig;
import net.minecraft.world.gen.feature.TreeFeatureConfig;
import net.minecraft.world.gen.stateprovider.BlockStateProvider;
import net.minecraft.world.gen.treedecorator.BeehiveTreeDecorator;
import net.minecraft.world.gen.trunk.LargeOakTrunkPlacer;
import net.minecraft.world.gen.trunk.StraightTrunkPlacer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.Supplier;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.data.worldgen.ProcessorLists;
import net.minecraft.data.worldgen.StructureFeatures;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.valueproviders.ConstantInt;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.StructureFeatureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.StructureSettings;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.StructureFeature;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import net.minecraft.world.level.levelgen.feature.configurations.JigsawConfiguration;
import net.minecraft.world.level.levelgen.feature.configurations.SimpleRandomFeatureConfiguration;
import net.minecraft.world.level.levelgen.feature.configurations.StructureFeatureConfiguration;
import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration;
import net.minecraft.world.level.levelgen.feature.featuresize.TwoLayersFeatureSize;
import net.minecraft.world.level.levelgen.feature.foliageplacers.BlobFoliagePlacer;
import net.minecraft.world.level.levelgen.feature.foliageplacers.FancyFoliagePlacer;
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import net.minecraft.world.level.levelgen.feature.structures.StructurePoolElement;
import net.minecraft.world.level.levelgen.feature.structures.StructureTemplatePool;
import net.minecraft.world.level.levelgen.feature.treedecorators.BeehiveDecorator;
import net.minecraft.world.level.levelgen.feature.trunkplacers.FancyTrunkPlacer;
import net.minecraft.world.level.levelgen.feature.trunkplacers.StraightTrunkPlacer;
import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import net.minecraft.world.level.levelgen.structure.StructureCheckResult;
import net.minecraft.world.level.levelgen.structure.StructureStart;
public class FeatureGenerator
{
public static final Object boo = new Object();
synchronized public static Boolean plop(String featureName, ServerWorld world, BlockPos pos)
synchronized public static Boolean plop(String featureName, ServerLevel world, BlockPos pos)
{
Thing custom = featureMap.get(featureName);
if (custom != null)
{
return custom.plop(world, pos);
}
Identifier id = new Identifier(featureName);
ConfiguredStructureFeature<?, ?> structureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).get(id);
ResourceLocation id = new ResourceLocation(featureName);
ConfiguredStructureFeature<?, ?> structureFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).get(id);
if (structureFeature != null)
{
return ((StructureFeatureInterface)structureFeature.feature).plopAnywhere(
world, pos, world.getChunkManager().getChunkGenerator(),
false, world.getRegistryManager().get(Registry.BIOME_KEY).get(BiomeKeys.PLAINS), structureFeature.config);
world, pos, world.getChunkSource().getGenerator(),
false, world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(Biomes.PLAINS), structureFeature.config);
}
ConfiguredFeature<?, ?> configuredFeature = world.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY).get(id);
ConfiguredFeature<?, ?> configuredFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).get(id);
if (configuredFeature != null)
{
CarpetSettings.skipGenerationChecks.set(true);
try
{
return configuredFeature.generate(world, world.getChunkManager().getChunkGenerator(), world.random, pos);
return configuredFeature.place(world, world.getChunkSource().getGenerator(), world.random, pos);
}
finally
{
@@ -90,8 +91,8 @@ public class FeatureGenerator
ConfiguredStructureFeature<?,?> configuredStandard = getDefaultFeature(structure, world, pos, true);
if (configuredStandard != null)
return ((StructureFeatureInterface)configuredStandard.feature).plopAnywhere(
world, pos, world.getChunkManager().getChunkGenerator(),
false, world.getRegistryManager().get(Registry.BIOME_KEY).get(BiomeKeys.PLAINS), configuredStandard.config);
world, pos, world.getChunkSource().getGenerator(),
false, world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(Biomes.PLAINS), configuredStandard.config);
}
Feature<?> feature = Registry.FEATURE.get(id);
@@ -103,7 +104,7 @@ public class FeatureGenerator
CarpetSettings.skipGenerationChecks.set(true);
try
{
return configuredStandard.generate(world, world.getChunkManager().getChunkGenerator(), world.random, pos);
return configuredStandard.place(world, world.getChunkSource().getGenerator(), world.random, pos);
}
finally
{
@@ -114,27 +115,27 @@ public class FeatureGenerator
return null;
}
public static ConfiguredStructureFeature<?, ?> resolveConfiguredStructure(String name, ServerWorld world, BlockPos pos)
public static ConfiguredStructureFeature<?, ?> resolveConfiguredStructure(String name, ServerLevel world, BlockPos pos)
{
Identifier id = new Identifier(name);
ConfiguredStructureFeature<?, ?> configuredStructureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).get(id);
ResourceLocation id = new ResourceLocation(name);
ConfiguredStructureFeature<?, ?> configuredStructureFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).get(id);
if (configuredStructureFeature != null) return configuredStructureFeature;
StructureFeature<?> structureFeature = Registry.STRUCTURE_FEATURE.get(id);
if (structureFeature == null) return null;
return getDefaultFeature(structureFeature, world, pos, true);
}
synchronized public static Boolean plopGrid(ConfiguredStructureFeature<?, ?> structureFeature, ServerWorld world, BlockPos pos)
synchronized public static Boolean plopGrid(ConfiguredStructureFeature<?, ?> structureFeature, ServerLevel world, BlockPos pos)
{
return ((StructureFeatureInterface)structureFeature.feature).plopAnywhere(
world, pos, world.getChunkManager().getChunkGenerator(),
true, BuiltinBiomes.PLAINS, structureFeature.config);
world, pos, world.getChunkSource().getGenerator(),
true, net.minecraft.data.worldgen.biome.Biomes.PLAINS, structureFeature.config);
}
@FunctionalInterface
private interface Thing
{
Boolean plop(ServerWorld world, BlockPos pos);
Boolean plop(ServerLevel world, BlockPos pos);
}
private static Thing simplePlop(ConfiguredFeature feature)
{
@@ -142,7 +143,7 @@ public class FeatureGenerator
CarpetSettings.skipGenerationChecks.set(true);
try
{
return feature.generate(w, w.getChunkManager().getChunkGenerator(), w.random, p);
return feature.place(w, w.getChunkSource().getGenerator(), w.random, p);
}
finally
{
@@ -151,45 +152,45 @@ public class FeatureGenerator
};
}
private static Thing simpleTree(TreeFeatureConfig config)
private static Thing simpleTree(TreeConfiguration config)
{
//config.ignoreFluidCheck();
return simplePlop(Feature.TREE.configure(config));
return simplePlop(Feature.TREE.configured(config));
}
private static Thing spawnCustomStructure(StructureFeature structure, FeatureConfig conf, RegistryKey<Biome> biome)
private static Thing spawnCustomStructure(StructureFeature structure, FeatureConfiguration conf, ResourceKey<Biome> biome)
{
return setupCustomStructure(structure, conf, biome, false);
}
private static Thing setupCustomStructure(StructureFeature structure, FeatureConfig conf, RegistryKey<Biome> biome, boolean wireOnly)
private static Thing setupCustomStructure(StructureFeature structure, FeatureConfiguration conf, ResourceKey<Biome> biome, boolean wireOnly)
{
return (w, p) -> ((StructureFeatureInterface)structure).plopAnywhere(w, p, w.getChunkManager().getChunkGenerator(), wireOnly, w.getRegistryManager().get(Registry.BIOME_KEY).get(biome), conf);
return (w, p) -> ((StructureFeatureInterface)structure).plopAnywhere(w, p, w.getChunkSource().getGenerator(), wireOnly, w.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(biome), conf);
}
public static Boolean spawn(String name, ServerWorld world, BlockPos pos)
public static Boolean spawn(String name, ServerLevel world, BlockPos pos)
{
if (featureMap.containsKey(name))
return featureMap.get(name).plop(world, pos);
return null;
}
private static ConfiguredStructureFeature<?, ?> getDefaultFeature(StructureFeature<?> structure, ServerWorld world, BlockPos pos, boolean tryHard)
private static ConfiguredStructureFeature<?, ?> getDefaultFeature(StructureFeature<?> structure, ServerLevel world, BlockPos pos, boolean tryHard)
{
var definedStructures = world.getChunkManager().getChunkGenerator().getStructuresConfig().getConfiguredStructureFeature(structure);
var optinalBiome = world.getRegistryManager().get(Registry.BIOME_KEY).getKey(world.getBiome(pos));
var definedStructures = world.getChunkSource().getGenerator().getSettings().structures(structure);
var optinalBiome = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getResourceKey(world.getBiome(pos));
if (optinalBiome.isPresent())
for (var configureStructure: definedStructures.inverse().get(optinalBiome.get()))
if (configureStructure.feature == structure)
return configureStructure;
if (!tryHard) return null;
return world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getEntries().stream().
return world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).entrySet().stream().
filter(cS -> cS.getValue().feature == structure).
findFirst().map(Map.Entry::getValue).orElse(null);
}
private static ConfiguredFeature<?, ?> getDefaultFeature(Feature<?> feature, ServerWorld world, BlockPos pos, boolean tryHard)
private static ConfiguredFeature<?, ?> getDefaultFeature(Feature<?> feature, ServerLevel world, BlockPos pos, boolean tryHard)
{
List<List<Supplier<PlacedFeature>>> configuredStepFeatures = world.getBiome(pos).getGenerationSettings().getFeatures();
List<List<Supplier<PlacedFeature>>> configuredStepFeatures = world.getBiome(pos).getGenerationSettings().features();
for (List<Supplier<PlacedFeature>> step: configuredStepFeatures)
for (Supplier<PlacedFeature> provider: step)
{
@@ -198,38 +199,38 @@ public class FeatureGenerator
return configuredFeature;
}
if (!tryHard) return null;
return world.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY).getEntries().stream().
return world.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).entrySet().stream().
filter(cS -> cS.getValue().feature == feature).
findFirst().map(Map.Entry::getValue).orElse(null);
}
public static <T extends FeatureConfig> StructureStart shouldStructureStartAt(ServerWorld world, BlockPos pos, StructureFeature<T> structure, boolean computeBox)
public static <T extends FeatureConfiguration> StructureStart shouldStructureStartAt(ServerLevel world, BlockPos pos, StructureFeature<T> structure, boolean computeBox)
{
if (structure == StructureFeature.STRONGHOLD)
return shouldStrongholdStartAt(world, pos, computeBox);
long seed = world.getSeed();
ChunkGenerator generator = world.getChunkManager().getChunkGenerator();
StructuresConfig settings = generator.getStructuresConfig();
StructureConfig structureConfig = settings.getForType(structure);
var structures = settings.getConfiguredStructureFeature(structure);
ChunkGenerator generator = world.getChunkSource().getGenerator();
StructureSettings settings = generator.getSettings();
StructureFeatureConfiguration structureConfig = settings.getConfig(structure);
var structures = settings.structures(structure);
if (structureConfig == null || structures.isEmpty()) {
return null;
}
ChunkPos chunkPos = new ChunkPos(pos);
Biome biome = world.getBiome(pos);
var biomeRegistry = world.getRegistryManager().get(Registry.BIOME_KEY);
var biomeRegistry = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY);
if (structures.values().stream().noneMatch(biomeKey -> biomeRegistry.get(biomeKey) == biome))
{
return null;
}
ChunkPos chunkPos1 = structure.getStartChunk(structureConfig, seed, chunkPos.x, chunkPos.z);
ChunkPos chunkPos1 = structure.getPotentialFeatureChunk(structureConfig, seed, chunkPos.x, chunkPos.z);
if (!chunkPos1.equals(chunkPos))
{
return null;
}
StructureAccessor structureManager = world.getStructureAccessor();
StructurePresence isThere = structureManager.getStructurePresence(chunkPos, structure, false);
if (isThere == StructurePresence.START_NOT_PRESENT)
StructureFeatureManager structureManager = world.structureFeatureManager();
StructureCheckResult isThere = structureManager.checkStructurePresence(chunkPos, structure, false);
if (isThere == StructureCheckResult.START_NOT_PRESENT)
{
return null;
}
@@ -238,100 +239,100 @@ public class FeatureGenerator
//StructureStart<?> start = structureManager.getStructureStart(ChunkSectionPos.from(chunk), structure, chunk);
//if (start != null && start.hasChildren())
//{
if (!computeBox) return StructureStart.DEFAULT;
if (!computeBox) return StructureStart.INVALID_START;
ConfiguredStructureFeature<?, ?> configuredFeature = getDefaultFeature(structure, world, pos, false);
if (configuredFeature == null || configuredFeature.config == null) return null;
var biomeConfig = structures.get(configuredFeature);
StructureStart<?> filledStructure = configuredFeature.tryPlaceStart(world.getRegistryManager(), generator, generator.getBiomeSource(),
world.getStructureManager(), seed, chunkPos, 0, structureConfig, world, (b) -> biomeRegistry.getKey(b).filter(biomeConfig::contains).isPresent());
if (filledStructure != null && filledStructure.hasChildren())
StructureStart<?> filledStructure = configuredFeature.generate(world.registryAccess(), generator, generator.getBiomeSource(),
world.getStructureManager(), seed, chunkPos, 0, structureConfig, world, (b) -> biomeRegistry.getResourceKey(b).filter(biomeConfig::contains).isPresent());
if (filledStructure != null && filledStructure.isValid())
return filledStructure;
return null;
}
public static StructureStart<?> shouldStrongholdStartAt(ServerWorld world, BlockPos pos, boolean computeBox)
public static StructureStart<?> shouldStrongholdStartAt(ServerLevel world, BlockPos pos, boolean computeBox)
{
ChunkGenerator generator = world.getChunkManager().getChunkGenerator();
if (world.getRegistryKey() != World.OVERWORLD || !generator.isStrongholdStartingChunk(new ChunkPos(pos))) return null;
if (!computeBox) return StructureStart.DEFAULT;
StructuresConfig settings = generator.getStructuresConfig();
StructureConfig structureConfig = settings.getForType(StructureFeature.STRONGHOLD);
ChunkGenerator generator = world.getChunkSource().getGenerator();
if (world.dimension() != Level.OVERWORLD || !generator.hasStronghold(new ChunkPos(pos))) return null;
if (!computeBox) return StructureStart.INVALID_START;
StructureSettings settings = generator.getSettings();
StructureFeatureConfiguration structureConfig = settings.getConfig(StructureFeature.STRONGHOLD);
if (structureConfig != null) {
StructureStart<?> filledStructure = ConfiguredStructureFeatures.STRONGHOLD.tryPlaceStart(world.getRegistryManager(), generator, generator.getBiomeSource(),
StructureStart<?> filledStructure = StructureFeatures.STRONGHOLD.generate(world.registryAccess(), generator, generator.getBiomeSource(),
world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0,
structureConfig, world, ((ChunkGeneratorInterface)generator)::canPlaceStrongholdInBiomeCM
);
if (filledStructure != null && filledStructure.hasChildren())
if (filledStructure != null && filledStructure.isValid())
return filledStructure;
}
return null;
}
private static TreeFeatureConfig.Builder createTree(Block block, Block block2, int i, int j, int k, int l) {
return new TreeFeatureConfig.Builder(BlockStateProvider.of(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.of(block2), new BlobFoliagePlacer(ConstantIntProvider.create(l), ConstantIntProvider.create(0), 3), new TwoLayersFeatureSize(1, 0, 1));
private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block, Block block2, int i, int j, int k, int l) {
return new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.simple(block2), new BlobFoliagePlacer(ConstantInt.of(l), ConstantInt.of(0), 3), new TwoLayersFeatureSize(1, 0, 1));
}
public static final Map<String, Thing> featureMap = new HashMap<String, Thing>() {{
put("oak_bees", simpleTree( createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveTreeDecorator(1.00F))).build()));
put("fancy_oak_bees", simpleTree( (new TreeFeatureConfig.Builder(BlockStateProvider.of(Blocks.OAK_LOG), new LargeOakTrunkPlacer(3, 11, 0), BlockStateProvider.of(Blocks.OAK_LEAVES), new LargeOakFoliagePlacer(ConstantIntProvider.create(2), ConstantIntProvider.create(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveTreeDecorator(1.00F))).build()));
put("birch_bees", simpleTree( createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveTreeDecorator(1.00F))).build()));
put("oak_bees", simpleTree( createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build()));
put("fancy_oak_bees", simpleTree( (new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(Blocks.OAK_LOG), new FancyTrunkPlacer(3, 11, 0), BlockStateProvider.simple(Blocks.OAK_LEAVES), new FancyFoliagePlacer(ConstantInt.of(2), ConstantInt.of(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build()));
put("birch_bees", simpleTree( createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build()));
put("coral_tree", simplePlop(Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT)));
put("coral_claw", simplePlop(Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT)));
put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT)));
put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR.configure(new SimpleRandomFeatureConfig(List.of(
() -> Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT).withPlacement(),
() -> Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT).withPlacement(),
() -> Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT).withPlacement()
put("coral_tree", simplePlop(Feature.CORAL_TREE.configured(FeatureConfiguration.NONE)));
put("coral_claw", simplePlop(Feature.CORAL_CLAW.configured(FeatureConfiguration.NONE)));
put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM.configured(FeatureConfiguration.NONE)));
put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR.configured(new SimpleRandomFeatureConfiguration(List.of(
() -> Feature.CORAL_TREE.configured(FeatureConfiguration.NONE).placed(),
() -> Feature.CORAL_CLAW.configured(FeatureConfiguration.NONE).placed(),
() -> Feature.CORAL_MUSHROOM.configured(FeatureConfiguration.NONE).placed()
)))));
put("bastion_remnant_units", spawnCustomStructure(
StructureFeature.BASTION_REMNANT,
new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"),
new Identifier("empty"),
new JigsawConfiguration(() -> new StructureTemplatePool(
new ResourceLocation("bastion/starts"),
new ResourceLocation("empty"),
List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/units/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
Pair.of(StructurePoolElement.single("bastion/units/air_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
),
StructurePool.Projection.RIGID
StructureTemplatePool.Projection.RIGID
), 6),
BiomeKeys.NETHER_WASTES
Biomes.NETHER_WASTES
));
put("bastion_remnant_hoglin_stable", spawnCustomStructure(
StructureFeature.BASTION_REMNANT,
new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"),
new Identifier("empty"),
new JigsawConfiguration(() -> new StructureTemplatePool(
new ResourceLocation("bastion/starts"),
new ResourceLocation("empty"),
List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/hoglin_stable/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
Pair.of(StructurePoolElement.single("bastion/hoglin_stable/air_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
),
StructurePool.Projection.RIGID
StructureTemplatePool.Projection.RIGID
), 6),
BiomeKeys.NETHER_WASTES
Biomes.NETHER_WASTES
));
put("bastion_remnant_treasure", spawnCustomStructure(
StructureFeature.BASTION_REMNANT,
new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"),
new Identifier("empty"),
new JigsawConfiguration(() -> new StructureTemplatePool(
new ResourceLocation("bastion/starts"),
new ResourceLocation("empty"),
List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/treasure/big_air_full", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
Pair.of(StructurePoolElement.single("bastion/treasure/big_air_full", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
),
StructurePool.Projection.RIGID
StructureTemplatePool.Projection.RIGID
), 6),
BiomeKeys.NETHER_WASTES
Biomes.NETHER_WASTES
));
put("bastion_remnant_bridge", spawnCustomStructure(
StructureFeature.BASTION_REMNANT,
new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"),
new Identifier("empty"),
new JigsawConfiguration(() -> new StructureTemplatePool(
new ResourceLocation("bastion/starts"),
new ResourceLocation("empty"),
List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/bridge/starting_pieces/entrance_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
Pair.of(StructurePoolElement.single("bastion/bridge/starting_pieces/entrance_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
),
StructurePool.Projection.RIGID
StructureTemplatePool.Projection.RIGID
), 6),
BiomeKeys.NETHER_WASTES
Biomes.NETHER_WASTES
));
}};
+42 -43
View File
@@ -7,30 +7,29 @@ import carpet.utils.WoolTool;
import carpet.utils.Messenger;
import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import net.minecraft.block.AbstractBannerBlock;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.MapColor;
import net.minecraft.block.Stainable;
import net.minecraft.item.BlockItem;
import net.minecraft.item.DyeItem;
import net.minecraft.item.Items;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.RecipeType;
import net.minecraft.text.Style;
import net.minecraft.text.TextColor;
import net.minecraft.util.DyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.text.BaseText;
import net.minecraft.text.TranslatableText;
import net.minecraft.ChatFormatting;
import net.minecraft.core.Registry;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.DyeItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.AbstractBannerBlock;
import net.minecraft.world.level.block.BeaconBeamBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.material.MaterialColor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -58,7 +57,7 @@ public class HopperCounter
* The default display colour of each item, which makes them look nicer when printing the counter contents to the chat
*/
public static final TextColor WHITE = TextColor.fromFormatting(Formatting.WHITE);
public static final TextColor WHITE = TextColor.fromLegacyFormat(ChatFormatting.WHITE);
static
{
@@ -100,7 +99,7 @@ public class HopperCounter
{
startTick = -1;
this.color = color;
this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMapColor(),"w ") + color.getName();
this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMaterialColor(),"w ") + color.getName();
}
/**
@@ -112,7 +111,7 @@ public class HopperCounter
{
if (startTick < 0)
{
startTick = server.getWorld(World.OVERWORLD).getTime(); //OW
startTick = server.getLevel(Level.OVERWORLD).getGameTime(); //OW
startMillis = System.currentTimeMillis();
}
Item item = stack.getItem();
@@ -126,7 +125,7 @@ public class HopperCounter
public void reset(MinecraftServer server)
{
counter.clear();
startTick = server.getWorld(World.OVERWORLD).getTime(); //OW
startTick = server.getLevel(Level.OVERWORLD).getGameTime(); //OW
startMillis = System.currentTimeMillis();
// pubSubProvider.publish();
}
@@ -147,13 +146,13 @@ public class HopperCounter
/**
* Prints all the counters to chat, nicely formatted, and you can choose whether to diplay in in game time or IRL time
*/
public static List<BaseText> formatAll(MinecraftServer server, boolean realtime)
public static List<BaseComponent> formatAll(MinecraftServer server, boolean realtime)
{
List<BaseText> text = new ArrayList<>();
List<BaseComponent> text = new ArrayList<>();
for (HopperCounter counter : COUNTERS.values())
{
List<BaseText> temp = counter.format(server, realtime, false);
List<BaseComponent> temp = counter.format(server, realtime, false);
if (temp.size() > 1)
{
if (!text.isEmpty()) text.add(Messenger.s(""));
@@ -171,9 +170,9 @@ public class HopperCounter
* Prints a single counter's contents and timings to chat, with the option to keep it short (so no item breakdown,
* only rates). Again, realtime displays IRL time as opposed to in game time.
*/
public List<BaseText> format(MinecraftServer server, boolean realTime, boolean brief)
public List<BaseComponent> format(MinecraftServer server, boolean realTime, boolean brief)
{
long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.getWorld(World.OVERWORLD).getTime() - startTick, 1); //OW
long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.getLevel(Level.OVERWORLD).getGameTime() - startTick, 1); //OW
if (startTick < 0 || ticks == 0)
{
if (brief)
@@ -201,7 +200,7 @@ public class HopperCounter
String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min"
));
}
List<BaseText> items = new ArrayList<>();
List<BaseComponent> items = new ArrayList<>();
items.add(Messenger.c("w Items for ", prettyColour,
"w (",String.format("wb %.2f", ticks*1.0/(20*60)), "w min"+(realTime?" - real time":"")+"), ",
"w total: ", "wb "+total, "w , (",String.format("wb %.1f",total*1.0*(20*60*60)/ticks),"w /h):",
@@ -210,7 +209,7 @@ public class HopperCounter
items.addAll(counter.object2LongEntrySet().stream().sorted((e, f) -> Long.compare(f.getLongValue(), e.getLongValue())).map(e ->
{
Item item = e.getKey();
BaseText itemName = new TranslatableText(item.getTranslationKey());
BaseComponent itemName = new TranslatableComponent(item.getDescriptionId());
Style itemStyle = itemName.getStyle();
TextColor color = guessColor(item);
itemName.setStyle((color != null) ? itemStyle.withColor(color) : itemStyle.withItalic(true));
@@ -229,7 +228,7 @@ public class HopperCounter
*/
public static int appropriateColor(int color)
{
if (color == 0) return MapColor.WHITE.color;
if (color == 0) return MaterialColor.SNOW.col;
int r = (color >> 16 & 255);
int g = (color >> 8 & 255);
int b = (color & 255);
@@ -334,23 +333,23 @@ public class HopperCounter
*/
public static TextColor fromItem(Item item)
{
if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).getDefaultMapColor().color));
if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getColor().getMapColor().color));
if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMaterialColor().col));
if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getDyeColor().getMaterialColor().col));
Block block = null;
Identifier id = Registry.ITEM.getId(item);
ResourceLocation id = Registry.ITEM.getKey(item);
if (item instanceof BlockItem)
{
block = ((BlockItem) item).getBlock();
}
else if (Registry.BLOCK.getOrEmpty(id).isPresent())
else if (Registry.BLOCK.getOptional(id).isPresent())
{
block = Registry.BLOCK.get(id);
}
if (block != null)
{
if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMapColor().color));
if (block instanceof Stainable) return TextColor.fromRgb(appropriateColor( ((Stainable) block).getColor().getMapColor().color));
return TextColor.fromRgb(appropriateColor( block.getDefaultMapColor().color));
if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMaterialColor().col));
if (block instanceof BeaconBeamBlock) return TextColor.fromRgb(appropriateColor( ((BeaconBeamBlock) block).getColor().getMaterialColor().col));
return TextColor.fromRgb(appropriateColor( block.defaultMaterialColor().col));
}
return null;
}
@@ -364,7 +363,7 @@ public class HopperCounter
TextColor direct = fromItem(item);
if (direct != null) return direct;
if (CarpetServer.minecraft_server == null) return WHITE;
Identifier id = Registry.ITEM.getId(item);
ResourceLocation id = Registry.ITEM.getKey(item);
for (RecipeType<?> type: Registry.RECIPE_TYPE)
{
for (Recipe<?> r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id))
@@ -1,7 +1,7 @@
package carpet.helpers;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack;
public class InventoryHelper
{
@@ -23,12 +23,12 @@ public class InventoryHelper
public static boolean cleanUpShulkerBoxTag(ItemStack stack)
{
boolean changed = false;
NbtCompound tag = stack.getNbt();
CompoundTag tag = stack.getTag();
if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND))
return false;
NbtCompound bet = tag.getCompound("BlockEntityTag");
CompoundTag bet = tag.getCompound("BlockEntityTag");
if (bet.contains("Items", TAG_LIST) && bet.getList("Items", TAG_COMPOUND).isEmpty())
{
bet.remove("Items");
@@ -42,7 +42,7 @@ public class InventoryHelper
}
if (tag.isEmpty())
{
stack.setNbt(null);
stack.setTag(null);
changed = true;
}
return changed;
@@ -50,12 +50,12 @@ public class InventoryHelper
public static boolean shulkerBoxHasItems(ItemStack stack)
{
NbtCompound tag = stack.getNbt();
CompoundTag tag = stack.getTag();
if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND))
return false;
NbtCompound bet = tag.getCompound("BlockEntityTag");
CompoundTag bet = tag.getCompound("BlockEntityTag");
return bet.contains("Items", TAG_LIST) && !bet.getList("Items", TAG_COMPOUND).isEmpty();
}
}
@@ -6,7 +6,32 @@ import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.item.PrimedTnt;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.ProtectionEnchantment;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
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.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import carpet.logging.logHelpers.ExplosionLogHelper;
import carpet.mixins.ExplosionAccessor;
import carpet.CarpetSettings;
@@ -15,52 +40,25 @@ import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.TntEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.world.explosion.Explosion;
import net.minecraft.loot.context.LootContext;
import net.minecraft.loot.context.LootContextParameters;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.block.Block;
import net.minecraft.enchantment.ProtectionEnchantment;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import static carpet.script.CarpetEventServer.Event.EXPLOSION_OUTCOME;
public class OptimizedExplosion
{
private static List<Entity> entitylist;
private static Vec3d vec3dmem;
private static Vec3 vec3dmem;
private static long tickmem;
// For disabling the explosion particles and sound
public static int explosionSound = 0;
// masa's optimizations
private static Object2DoubleOpenHashMap<Pair<Vec3d, Box>> densityCache = new Object2DoubleOpenHashMap<>();
private static MutablePair<Vec3d, Box> pairMutable = new MutablePair<>();
private static Object2DoubleOpenHashMap<Pair<Vec3, AABB>> densityCache = new Object2DoubleOpenHashMap<>();
private static MutablePair<Vec3, AABB> pairMutable = new MutablePair<>();
private static Object2ObjectOpenHashMap<BlockPos, BlockState> stateCache = new Object2ObjectOpenHashMap<>();
private static Object2ObjectOpenHashMap<BlockPos, FluidState> fluidCache = new Object2ObjectOpenHashMap<>();
private static BlockPos.Mutable posMutable = new BlockPos.Mutable(0, 0, 0);
private static BlockPos.MutableBlockPos posMutable = new BlockPos.MutableBlockPos(0, 0, 0);
private static ObjectOpenHashSet<BlockPos> affectedBlockPositionsSet = new ObjectOpenHashSet<>();
private static boolean firstRay;
private static boolean rayCalcDone;
@@ -74,7 +72,7 @@ public class OptimizedExplosion
ExplosionAccessor eAccess = (ExplosionAccessor) e;
entityList.clear();
boolean eventNeeded = EXPLOSION_OUTCOME.isNeeded() && !eAccess.getWorld().isClient();
boolean eventNeeded = EXPLOSION_OUTCOME.isNeeded() && !eAccess.getLevel().isClientSide();
blastCalc(e);
if (!CarpetSettings.explosionNoBlockDamage) {
@@ -89,29 +87,29 @@ public class OptimizedExplosion
stateCache.clear();
fluidCache.clear();
e.getAffectedBlocks().addAll(affectedBlockPositionsSet);
e.getToBlow().addAll(affectedBlockPositionsSet);
affectedBlockPositionsSet.clear();
}
float f3 = eAccess.getPower() * 2.0F;
int k1 = MathHelper.floor(eAccess.getX() - (double) f3 - 1.0D);
int l1 = MathHelper.floor(eAccess.getX() + (double) f3 + 1.0D);
int i2 = MathHelper.floor(eAccess.getY() - (double) f3 - 1.0D);
int i1 = MathHelper.floor(eAccess.getY() + (double) f3 + 1.0D);
int j2 = MathHelper.floor(eAccess.getZ() - (double) f3 - 1.0D);
int j1 = MathHelper.floor(eAccess.getZ() + (double) f3 + 1.0D);
Vec3d vec3d = new Vec3d(eAccess.getX(), eAccess.getY(), eAccess.getZ());
float f3 = eAccess.getRadius() * 2.0F;
int k1 = Mth.floor(eAccess.getX() - (double) f3 - 1.0D);
int l1 = Mth.floor(eAccess.getX() + (double) f3 + 1.0D);
int i2 = Mth.floor(eAccess.getY() - (double) f3 - 1.0D);
int i1 = Mth.floor(eAccess.getY() + (double) f3 + 1.0D);
int j2 = Mth.floor(eAccess.getZ() - (double) f3 - 1.0D);
int j1 = Mth.floor(eAccess.getZ() + (double) f3 + 1.0D);
Vec3 vec3d = new Vec3(eAccess.getX(), eAccess.getY(), eAccess.getZ());
if (vec3dmem == null || !vec3dmem.equals(vec3d) || tickmem != eAccess.getWorld().getTime()) {
if (vec3dmem == null || !vec3dmem.equals(vec3d) || tickmem != eAccess.getLevel().getGameTime()) {
vec3dmem = vec3d;
tickmem = eAccess.getWorld().getTime();
entitylist = eAccess.getWorld().getOtherEntities(null, new Box(k1, i2, j2, l1, i1, j1));
tickmem = eAccess.getLevel().getGameTime();
entitylist = eAccess.getLevel().getEntities(null, new AABB(k1, i2, j2, l1, i1, j1));
explosionSound = 0;
}
explosionSound++;
Entity explodingEntity = eAccess.getEntity();
Entity explodingEntity = eAccess.getSource();
for (int k2 = 0; k2 < entitylist.size(); ++k2) {
Entity entity = entitylist.get(k2);
@@ -123,23 +121,23 @@ public class OptimizedExplosion
continue;
}
if (entity instanceof TntEntity && explodingEntity != null &&
if (entity instanceof PrimedTnt && explodingEntity != null &&
entity.getX() == explodingEntity.getX() &&
entity.getY() == explodingEntity.getY() &&
entity.getZ() == explodingEntity.getZ()) {
if (eLogger != null) {
eLogger.onEntityImpacted(entity, new Vec3d(0,-0.9923437498509884d, 0));
eLogger.onEntityImpacted(entity, new Vec3(0,-0.9923437498509884d, 0));
}
continue;
}
if (!entity.isImmuneToExplosion()) {
double d12 = Math.sqrt(entity.squaredDistanceTo(eAccess.getX(), eAccess.getY(), eAccess.getZ())) / (double) f3;
if (!entity.ignoreExplosion()) {
double d12 = Math.sqrt(entity.distanceToSqr(eAccess.getX(), eAccess.getY(), eAccess.getZ())) / (double) f3;
if (d12 <= 1.0D) {
double d5 = entity.getX() - eAccess.getX();
// Change in 1.16 snapshots to fix a bug with TNT jumping
double d7 = (entity instanceof TntEntity ? entity.getY() : entity.getEyeY()) - eAccess.getY();
double d7 = (entity instanceof PrimedTnt ? entity.getY() : entity.getEyeY()) - eAccess.getY();
double d9 = entity.getZ() - eAccess.getZ();
double d13 = (double) Math.sqrt(d5 * d5 + d7 * d7 + d9 * d9);
@@ -155,8 +153,8 @@ public class OptimizedExplosion
if (density == Double.MAX_VALUE)
{
Pair<Vec3d, Box> pair = Pair.of(vec3d, entity.getBoundingBox());
density = Explosion.getExposure(vec3d, entity);
Pair<Vec3, AABB> pair = Pair.of(vec3d, entity.getBoundingBox());
density = Explosion.getSeenPercent(vec3d, entity);
densityCache.put(pair, density);
}
@@ -166,25 +164,25 @@ public class OptimizedExplosion
}
double d10 = (1.0D - d12) * density;
entity.damage(e.getDamageSource(),
entity.hurt(e.getDamageSource(),
(float) ((int) ((d10 * d10 + d10) / 2.0D * 7.0D * (double) f3 + 1.0D)));
double d11 = d10;
if (entity instanceof LivingEntity) {
d11 = ProtectionEnchantment.transformExplosionKnockback((LivingEntity) entity, d10);
d11 = ProtectionEnchantment.getExplosionKnockbackAfterDampener((LivingEntity) entity, d10);
}
if (eLogger != null) {
eLogger.onEntityImpacted(entity, new Vec3d(d5 * d11, d7 * d11, d9 * d11));
eLogger.onEntityImpacted(entity, new Vec3(d5 * d11, d7 * d11, d9 * d11));
}
entity.setVelocity(entity.getVelocity().add(d5 * d11, d7 * d11, d9 * d11));
entity.setDeltaMovement(entity.getDeltaMovement().add(d5 * d11, d7 * d11, d9 * d11));
if (entity instanceof PlayerEntity player) {
if (entity instanceof Player player) {
if (!player.isSpectator()
&& (!player.isCreative() || !player.getAbilities().flying)) { //getAbilities
e.getAffectedPlayers().put(player, new Vec3d(d5 * d10, d7 * d10, d9 * d10));
e.getHitPlayers().put(player, new Vec3(d5 * d10, d7 * d10, d9 * d10));
}
}
}
@@ -198,27 +196,27 @@ public class OptimizedExplosion
public static void doExplosionB(Explosion e, boolean spawnParticles)
{
ExplosionAccessor eAccess = (ExplosionAccessor) e;
World world = eAccess.getWorld();
Level world = eAccess.getLevel();
double posX = eAccess.getX();
double posY = eAccess.getY();
double posZ = eAccess.getZ();
// If it is needed, calls scarpet event
if (EXPLOSION_OUTCOME.isNeeded() && !world.isClient()) {
EXPLOSION_OUTCOME.onExplosion((ServerWorld) world, eAccess.getEntity(), e::getCausingEntity, eAccess.getX(), eAccess.getY(), eAccess.getZ(), eAccess.getPower(), eAccess.isCreateFire(), e.getAffectedBlocks(), entityList, eAccess.getDestructionType());
if (EXPLOSION_OUTCOME.isNeeded() && !world.isClientSide()) {
EXPLOSION_OUTCOME.onExplosion((ServerLevel) world, eAccess.getSource(), e::getSourceMob, eAccess.getX(), eAccess.getY(), eAccess.getZ(), eAccess.getRadius(), eAccess.isFire(), e.getToBlow(), entityList, eAccess.getBlockInteraction());
}
boolean damagesTerrain = eAccess.getDestructionType() != Explosion.DestructionType.NONE;
boolean damagesTerrain = eAccess.getBlockInteraction() != Explosion.BlockInteraction.NONE;
// explosionSound incremented till disabling the explosion particles and sound
if (explosionSound < 100 || explosionSound % 100 == 0)
{
world.playSound(null, posX, posY, posZ, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F,
world.playSound(null, posX, posY, posZ, SoundEvents.GENERIC_EXPLODE, SoundSource.BLOCKS, 4.0F,
(1.0F + (world.random.nextFloat() - world.random.nextFloat()) * 0.2F) * 0.7F);
if (spawnParticles)
{
if (eAccess.getPower() >= 2.0F && damagesTerrain)
if (eAccess.getRadius() >= 2.0F && damagesTerrain)
{
world.addParticle(ParticleTypes.EXPLOSION_EMITTER, posX, posY, posZ, 1.0D, 0.0D, 0.0D);
}
@@ -232,56 +230,56 @@ public class OptimizedExplosion
if (damagesTerrain)
{
ObjectArrayList<Pair<ItemStack, BlockPos>> objectArrayList = new ObjectArrayList();
Collections.shuffle(e.getAffectedBlocks(), world.random);
Collections.shuffle(e.getToBlow(), world.random);
for (BlockPos blockpos : e.getAffectedBlocks())
for (BlockPos blockpos : e.getToBlow())
{
BlockState state = world.getBlockState(blockpos);
Block block = state.getBlock();
if (state.getMaterial() != Material.AIR)
{
if (block.shouldDropItemsOnExplosion(e) && world instanceof ServerWorld)
if (block.dropFromExplosion(e) && world instanceof ServerLevel)
{
BlockEntity blockEntity = state.hasBlockEntity() ? world.getBlockEntity(blockpos) : null; //hasBlockEntity()
LootContext.Builder lootBuilder = (new LootContext.Builder((ServerWorld)eAccess.getWorld()))
.random(eAccess.getWorld().random)
.parameter(LootContextParameters.ORIGIN, Vec3d.ofCenter(blockpos))
.parameter(LootContextParameters.TOOL, ItemStack.EMPTY)
.optionalParameter(LootContextParameters.BLOCK_ENTITY, blockEntity)
.optionalParameter(LootContextParameters.THIS_ENTITY, eAccess.getEntity());
LootContext.Builder lootBuilder = (new LootContext.Builder((ServerLevel)eAccess.getLevel()))
.withRandom(eAccess.getLevel().random)
.withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(blockpos))
.withParameter(LootContextParams.TOOL, ItemStack.EMPTY)
.withOptionalParameter(LootContextParams.BLOCK_ENTITY, blockEntity)
.withOptionalParameter(LootContextParams.THIS_ENTITY, eAccess.getSource());
if (eAccess.getDestructionType() == Explosion.DestructionType.DESTROY)
lootBuilder.parameter(LootContextParameters.EXPLOSION_RADIUS, eAccess.getPower());
if (eAccess.getBlockInteraction() == Explosion.BlockInteraction.DESTROY)
lootBuilder.withParameter(LootContextParams.EXPLOSION_RADIUS, eAccess.getRadius());
state.getDroppedStacks(lootBuilder).forEach((itemStackx) -> {
method_24023(objectArrayList, itemStackx, blockpos.toImmutable());
state.getDrops(lootBuilder).forEach((itemStackx) -> {
method_24023(objectArrayList, itemStackx, blockpos.immutable());
});
}
world.setBlockState(blockpos, Blocks.AIR.getDefaultState(), 3);
block.onDestroyedByExplosion(world, blockpos, e);
world.setBlock(blockpos, Blocks.AIR.defaultBlockState(), 3);
block.wasExploded(world, blockpos, e);
}
}
objectArrayList.forEach(p -> Block.dropStack(world, p.getRight(), p.getLeft()));
objectArrayList.forEach(p -> Block.popResource(world, p.getRight(), p.getLeft()));
}
if (eAccess.isCreateFire())
if (eAccess.isFire())
{
for (BlockPos blockpos1 : e.getAffectedBlocks())
for (BlockPos blockpos1 : e.getToBlow())
{
// Use the same Chunk reference because the positions are in the same xz-column
Chunk chunk = world.getChunk(blockpos1.getX() >> 4, blockpos1.getZ() >> 4);
ChunkAccess chunk = world.getChunk(blockpos1.getX() >> 4, blockpos1.getZ() >> 4);
BlockPos down = blockpos1.down(1);
BlockPos down = blockpos1.below(1);
if (eAccess.getRandom().nextInt(3) == 0 &&
chunk.getBlockState(blockpos1).getMaterial() == Material.AIR &&
chunk.getBlockState(down).isOpaqueFullCube(world, down)
chunk.getBlockState(down).isSolidRender(world, down)
)
{
world.setBlockState(blockpos1, Blocks.FIRE.getDefaultState());
world.setBlockAndUpdate(blockpos1, Blocks.FIRE.defaultBlockState());
}
}
}
@@ -295,7 +293,7 @@ public class OptimizedExplosion
for(int j = 0; j < i; ++j) {
Pair<ItemStack, BlockPos> pair = (Pair)objectArrayList.get(j);
ItemStack itemStack2 = pair.getLeft();
if (ItemEntity.canMerge(itemStack2, itemStack)) {
if (ItemEntity.areMergable(itemStack2, itemStack)) {
ItemStack itemStack3 = ItemEntity.merge(itemStack2, itemStack, 16);
objectArrayList.set(j, Pair.of(itemStack3, pair.getRight()));
if (itemStack.isEmpty()) {
@@ -328,29 +326,29 @@ public class OptimizedExplosion
d0 = d0 / d3;
d1 = d1 / d3;
d2 = d2 / d3;
float rand = eAccess.getWorld().random.nextFloat();
float rand = eAccess.getLevel().random.nextFloat();
if (CarpetSettings.tntRandomRange >= 0) {
rand = (float) CarpetSettings.tntRandomRange;
}
float f = eAccess.getPower() * (0.7F + rand * 0.6F);
float f = eAccess.getRadius() * (0.7F + rand * 0.6F);
double d4 = eAccess.getX();
double d6 = eAccess.getY();
double d8 = eAccess.getZ();
for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) {
BlockPos blockpos = new BlockPos(d4, d6, d8);
BlockState state = eAccess.getWorld().getBlockState(blockpos);
FluidState fluidState = eAccess.getWorld().getFluidState(blockpos);
BlockState state = eAccess.getLevel().getBlockState(blockpos);
FluidState fluidState = eAccess.getLevel().getFluidState(blockpos);
if (state.getMaterial() != Material.AIR) {
float f2 = Math.max(state.getBlock().getBlastResistance(), fluidState.getBlastResistance());
if (eAccess.getEntity() != null)
f2 = eAccess.getEntity().getEffectiveExplosionResistance(e, eAccess.getWorld(), blockpos, state, fluidState, f2);
float f2 = Math.max(state.getBlock().getExplosionResistance(), fluidState.getExplosionResistance());
if (eAccess.getSource() != null)
f2 = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), blockpos, state, fluidState, f2);
f -= (f2 + 0.3F) * 0.3F;
}
if (f > 0.0F && (eAccess.getEntity() == null ||
eAccess.getEntity().canExplosionDestroyBlock(e, eAccess.getWorld(), blockpos, state, f)))
if (f > 0.0F && (eAccess.getSource() == null ||
eAccess.getSource().shouldBlockExplode(e, eAccess.getLevel(), blockpos, state, f)))
{
affectedBlockPositionsSet.add(blockpos);
}
@@ -446,9 +444,9 @@ public class OptimizedExplosion
double xInc = (xRel / len) * 0.3;
double yInc = (yRel / len) * 0.3;
double zInc = (zRel / len) * 0.3;
float rand = eAccess.getWorld().random.nextFloat();
float rand = eAccess.getLevel().random.nextFloat();
float sizeRand = (CarpetSettings.tntRandomRange >= 0 ? (float) CarpetSettings.tntRandomRange : rand);
float size = eAccess.getPower() * (0.7F + sizeRand * 0.6F);
float size = eAccess.getRadius() * (0.7F + sizeRand * 0.6F);
double posX = eAccess.getX();
double posY = eAccess.getY();
double posZ = eAccess.getZ();
@@ -464,20 +462,20 @@ public class OptimizedExplosion
if (state == null)
{
posImmutable = posMutable.toImmutable();
state = eAccess.getWorld().getBlockState(posImmutable);
posImmutable = posMutable.immutable();
state = eAccess.getLevel().getBlockState(posImmutable);
stateCache.put(posImmutable, state);
fluid = eAccess.getWorld().getFluidState(posImmutable);
fluid = eAccess.getLevel().getFluidState(posImmutable);
fluidCache.put(posImmutable, fluid);
}
if (state.getMaterial() != Material.AIR)
{
float resistance = Math.max(state.getBlock().getBlastResistance(), fluid.getBlastResistance());
float resistance = Math.max(state.getBlock().getExplosionResistance(), fluid.getExplosionResistance());
if (eAccess.getEntity() != null)
if (eAccess.getSource() != null)
{
resistance = eAccess.getEntity().getEffectiveExplosionResistance(e, eAccess.getWorld(), posMutable, state, fluid, resistance);
resistance = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), posMutable, state, fluid, resistance);
}
size -= (resistance + 0.3F) * 0.3F;
@@ -485,8 +483,8 @@ public class OptimizedExplosion
if (size > 0.0F)
{
if ((eAccess.getEntity() == null || eAccess.getEntity().canExplosionDestroyBlock(e, eAccess.getWorld(), posMutable, state, size)))
affectedBlockPositionsSet.add(posImmutable != null ? posImmutable : posMutable.toImmutable());
if ((eAccess.getSource() == null || eAccess.getSource().shouldBlockExplode(e, eAccess.getLevel(), posMutable, state, size)))
affectedBlockPositionsSet.add(posImmutable != null ? posImmutable : posMutable.immutable());
}
else if (firstRay)
{
@@ -510,7 +508,7 @@ public class OptimizedExplosion
private static void blastCalc(Explosion e){
ExplosionAccessor eAccess = (ExplosionAccessor) e;
if(blastChanceLocation == null || blastChanceLocation.getSquaredDistance(eAccess.getX(), eAccess.getY(), eAccess.getZ(), false) > 200) return;
if(blastChanceLocation == null || blastChanceLocation.distSqr(eAccess.getX(), eAccess.getY(), eAccess.getZ(), false) > 200) return;
chances.clear();
for (int j = 0; j < 16; ++j) {
for (int k = 0; k < 16; ++k) {
@@ -523,7 +521,7 @@ public class OptimizedExplosion
d0 = d0 / d3;
d1 = d1 / d3;
d2 = d2 / d3;
float f = eAccess.getPower() * (0.7F + 0.6F);
float f = eAccess.getRadius() * (0.7F + 0.6F);
double d4 = eAccess.getX();
double d6 = eAccess.getY();
double d8 = eAccess.getZ();
@@ -531,18 +529,18 @@ public class OptimizedExplosion
for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) {
BlockPos blockpos = new BlockPos(d4, d6, d8);
BlockState state = eAccess.getWorld().getBlockState(blockpos);
FluidState fluidState = eAccess.getWorld().getFluidState(blockpos);
BlockState state = eAccess.getLevel().getBlockState(blockpos);
FluidState fluidState = eAccess.getLevel().getFluidState(blockpos);
if (state.getMaterial() != Material.AIR) {
float f2 = Math.max(state.getBlock().getBlastResistance(), fluidState.getBlastResistance());
if (eAccess.getEntity() != null)
f2 = eAccess.getEntity().getEffectiveExplosionResistance(e, eAccess.getWorld(), blockpos, state, fluidState, f2);
float f2 = Math.max(state.getBlock().getExplosionResistance(), fluidState.getExplosionResistance());
if (eAccess.getSource() != null)
f2 = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), blockpos, state, fluidState, f2);
f -= (f2 + 0.3F) * 0.3F;
}
if (f > 0.0F && (eAccess.getEntity() == null ||
eAccess.getEntity().canExplosionDestroyBlock(e, eAccess.getWorld(), blockpos, state, f))) {
if (f > 0.0F && (eAccess.getSource() == null ||
eAccess.getSource().shouldBlockExplode(e, eAccess.getLevel(), blockpos, state, f))) {
if(!found && blockpos.equals(blastChanceLocation)){
chances.add(f);
found = true;
@@ -563,7 +561,7 @@ public class OptimizedExplosion
private static void showTNTblastChance(Explosion e){
ExplosionAccessor eAccess = (ExplosionAccessor) e;
double randMax = 0.6F * eAccess.getPower();
double randMax = 0.6F * eAccess.getRadius();
double total = 0;
boolean fullyBlownUp = false;
boolean first = true;
@@ -587,7 +585,7 @@ public class OptimizedExplosion
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setRoundingMode (RoundingMode.DOWN);
nf.setMaximumFractionDigits(2);
for(PlayerEntity player : eAccess.getWorld().getPlayers()){
for(Player player : eAccess.getLevel().players()){
Messenger.m(player,"w Pop: ",
"c " + nf.format(chance) + " ",
"^w Chance for the block to be destroyed by the blast: " + chance,
@@ -601,9 +599,9 @@ public class OptimizedExplosion
"^w TNT blast rays going through the block",
"?" + rays,
"w Size: ",
String.format("c %.1f ", eAccess.getPower()),
String.format("c %.1f ", eAccess.getRadius()),
"^w TNT blast size",
"?" + eAccess.getPower(),
"?" + eAccess.getRadius(),
"w @: ",
String.format("c [%.1f %.1f %.1f] ", eAccess.getX(), eAccess.getY(), eAccess.getZ()),
"^w TNT blast location X:" + eAccess.getX() + " Y:" + eAccess.getY() + " Z:" + eAccess.getZ(),
@@ -2,61 +2,60 @@ package carpet.helpers;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.argument.ParticleEffectArgumentType;
import net.minecraft.particle.ParticleEffect;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.Vec3d;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.commands.arguments.ParticleArgument;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.phys.Vec3;
public class ParticleDisplay
{
private static Map<String, ParticleEffect> particleCache = new HashMap<>();
private static Map<String, ParticleOptions> particleCache = new HashMap<>();
private static ParticleEffect parseParticle(String name)
private static ParticleOptions parseParticle(String name)
{
try
{
return ParticleEffectArgumentType.readParameters(new StringReader(name));
return ParticleArgument.readParticle(new StringReader(name));
}
catch (CommandSyntaxException e)
{
throw new RuntimeException("No such particle: "+name);
}
}
public static ParticleEffect getEffect(String name)
public static ParticleOptions getEffect(String name)
{
if (name == null) return null;
ParticleEffect res = particleCache.get(name);
ParticleOptions res = particleCache.get(name);
if (res != null) return res;
particleCache.put(name, parseParticle(name));
return particleCache.get(name);
}
public static void drawParticleLine(ServerPlayerEntity player, Vec3d from, Vec3d to, String main, String accent, int count, double spread)
public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, String main, String accent, int count, double spread)
{
ParticleEffect accentParticle = getEffect(accent);
ParticleEffect mainParticle = getEffect(main);
ParticleOptions accentParticle = getEffect(accent);
ParticleOptions mainParticle = getEffect(main);
if (accentParticle != null) ((ServerWorld)player.world).spawnParticles(
if (accentParticle != null) ((ServerLevel)player.level).sendParticles(
player,
accentParticle,
true,
to.x, to.y, to.z, count,
spread, spread, spread, 0.0);
double lineLengthSq = from.squaredDistanceTo(to);
double lineLengthSq = from.distanceToSqr(to);
if (lineLengthSq == 0) return;
Vec3d incvec = to.subtract(from).normalize();// multiply(50/sqrt(lineLengthSq));
Vec3 incvec = to.subtract(from).normalize();// multiply(50/sqrt(lineLengthSq));
int pcount = 0;
for (Vec3d delta = new Vec3d(0.0,0.0,0.0);
delta.lengthSquared()<lineLengthSq;
delta = delta.add(incvec.multiply(player.world.random.nextFloat())))
for (Vec3 delta = new Vec3(0.0,0.0,0.0);
delta.lengthSqr()<lineLengthSq;
delta = delta.add(incvec.scale(player.level.random.nextFloat())))
{
((ServerWorld)player.world).spawnParticles(
((ServerLevel)player.level).sendParticles(
player,
mainParticle,
true,
@@ -6,14 +6,13 @@ import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ThreadLocalRandom;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.RedStoneWireBlock;
import net.minecraft.world.level.block.state.BlockState;
import carpet.fakes.RedstoneWireBlockInterface;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.RedstoneWireBlock;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class RedstoneWireTurbo
{
@@ -79,7 +78,7 @@ public class RedstoneWireTurbo
/* Reference to RedstoneWireBlock object, which uses this accelerator */
private final RedstoneWireBlock wire;
private final RedStoneWireBlock wire;
/*
@@ -115,7 +114,7 @@ public class RedstoneWireTurbo
private List<UpdateNode> updateQueue2 = new ArrayList<>();
public RedstoneWireTurbo(RedstoneWireBlock wire) {
public RedstoneWireTurbo(RedStoneWireBlock wire) {
this.wire = wire;
}
@@ -294,7 +293,7 @@ public class RedstoneWireTurbo
/*
* For a newly created UpdateNode object, determine what type of block it is.
*/
private void identifyNode(final World worldIn, final UpdateNode upd1) {
private void identifyNode(final Level worldIn, final UpdateNode upd1) {
final BlockPos pos = upd1.self;
final BlockState oldState = worldIn.getBlockState(pos);
upd1.currentState = oldState;
@@ -321,9 +320,9 @@ public class RedstoneWireTurbo
// others are processed internally by the breadth first search
// algorithm. To preserve this game behavior, this check must
// be replicated here.
if (!oldState.canPlaceAt(worldIn, pos)) {
if (!oldState.canSurvive(worldIn, pos)) {
// Pop off the redstone dust
Block.dropStacks(oldState, worldIn, pos);
Block.dropResources(oldState, worldIn, pos);
worldIn.removeBlock(pos, false);
// Mark this position as not being redstone wire
@@ -417,7 +416,7 @@ public class RedstoneWireTurbo
/*
* Process a node whose neighboring redstone wire has experienced value changes.
*/
private void updateNode(final World worldIn, final UpdateNode upd1, final int layer) {
private void updateNode(final Level worldIn, final UpdateNode upd1, final int layer) {
final BlockPos pos = upd1.self;
// Mark this redstone wire as having been visited so that it can be used
@@ -462,7 +461,7 @@ public class RedstoneWireTurbo
* what nodes in the redstone wire graph have been visited, the neighbors
* are reordered left-to-right relative to the direction of information flow.
*/
private void findNeighbors(final World worldIn, final UpdateNode upd1) {
private void findNeighbors(final Level worldIn, final UpdateNode upd1) {
final BlockPos pos = upd1.self;
// Get the list of neighbor coordinates
@@ -553,7 +552,7 @@ public class RedstoneWireTurbo
* For any redstone wire block in layer N, inform neighbors to recompute their states
* in layers N+1 and N+2;
*/
private void propagateChanges(final World worldIn, final UpdateNode upd1, final int layer) {
private void propagateChanges(final Level worldIn, final UpdateNode upd1, final int layer) {
if (upd1.neighbor_nodes == null) {
// If this node has not been expanded yet, find its neigbors
findNeighbors(worldIn, upd1);
@@ -627,7 +626,7 @@ public class RedstoneWireTurbo
* that is a function of distance from the initial call to
* this.neighborChanged.
*/
private void breadthFirstWalk(final World worldIn) {
private void breadthFirstWalk(final Level worldIn) {
shiftQueue();
currentWalkLayer = 1;
@@ -663,7 +662,7 @@ public class RedstoneWireTurbo
// already keeping track of all of the neighbor positions
// that need to be updated. All on its own, handling neighbors
// this way reduces block updates by 1/3 (24 instead of 36).
worldIn.updateNeighbor(upd.self, wire, upd.parent);
worldIn.neighborChanged(upd.self, wire, upd.parent);
}
}
@@ -701,7 +700,7 @@ public class RedstoneWireTurbo
* order to continue processing both the first and second wire in the order of distance from the initial
* trigger.
*/
private BlockState scheduleReentrantNeighborChanged(final World worldIn, final BlockPos pos, final BlockState newState, final BlockPos source)
private BlockState scheduleReentrantNeighborChanged(final Level worldIn, final BlockPos pos, final BlockState newState, final BlockPos source)
{
if (source != null) {
// If the cause of the redstone wire update is known, we can use that to help determine
@@ -762,7 +761,7 @@ public class RedstoneWireTurbo
* few other methods in RedstoneWireBlock. This sets off the breadth-first
* walk through all redstone dust connected to the initial position triggered.
*/
public BlockState updateSurroundingRedstone(final World worldIn, final BlockPos pos, final BlockState state, final BlockPos source)
public BlockState updateSurroundingRedstone(final Level worldIn, final BlockPos pos, final BlockState state, final BlockPos source)
{
// Check this block's neighbors and see if its power level needs to change
// Use the calculateCurrentChanges method in RedstoneWireBlock since we have no
@@ -832,10 +831,10 @@ public class RedstoneWireTurbo
* the UpdateNode's neighbor array to find the redstone states of neighbors
* that might power it.
*/
private BlockState calculateCurrentChanges(final World worldIn, final UpdateNode upd)
private BlockState calculateCurrentChanges(final Level worldIn, final UpdateNode upd)
{
BlockState state = upd.currentState;
final int i = state.get(RedstoneWireBlock.POWER);
final int i = state.getValue(RedStoneWireBlock.POWER);
int j = 0;
j = getMaxCurrentStrength(upd, j);
int l = 0;
@@ -846,7 +845,7 @@ public class RedstoneWireTurbo
// elsewhere in Minecraft into this accelerator. So sadly, we must
// suffer the performance hit of this very expensive call. If there
// is consistency to what this call returns, we may be able to cache it.
final int k = worldIn.getReceivedRedstonePower(upd.self);
final int k = worldIn.getBestNeighborSignal(upd.self);
((RedstoneWireBlockInterface)wire).setWiresGivePower(true);
// The variable 'k' holds the maximum redstone power value of any adjacent blocks.
@@ -865,7 +864,7 @@ public class RedstoneWireTurbo
// position directly above the node being calculated is always
// at index 1.
UpdateNode center_up = upd.neighbor_nodes[1];
boolean center_up_is_cube = center_up.currentState.isSolidBlock(worldIn, center_up.self); //isSimpleFUllBLock
boolean center_up_is_cube = center_up.currentState.isRedstoneConductor(worldIn, center_up.self); //isSimpleFUllBLock
for (int m=0; m<4; m++) {
// Get the neighbor array index of each of the four cardinal
@@ -879,7 +878,7 @@ public class RedstoneWireTurbo
// Also check the positions above and below the cardinal
// neighbors
boolean neighbor_is_cube = neighbor.currentState.isSolidBlock(worldIn, neighbor.self); //isSimpleFUllBLock
boolean neighbor_is_cube = neighbor.currentState.isRedstoneConductor(worldIn, neighbor.self); //isSimpleFUllBLock
if (!neighbor_is_cube) {
UpdateNode neighbor_down = upd.neighbor_nodes[rs_neighbors_dn[m]];
l = getMaxCurrentStrength(neighbor_down, l);
@@ -905,11 +904,11 @@ public class RedstoneWireTurbo
// and set it in the world.
// Possible optimization: Don't commit state changes to the world until they
// need to be known by some nearby non-redstone-wire block.
state = state.with(RedstoneWireBlock.POWER, j);
state = state.setValue(RedStoneWireBlock.POWER, j);
// [gnembon] added state check cause other things in the tick may have popped it up already
// https://github.com/gnembon/fabric-carpet/issues/117
if (worldIn.getBlockState(upd.self).getBlock() == Blocks.REDSTONE_WIRE)
worldIn.setBlockState(upd.self, state, 2);
worldIn.setBlock(upd.self, state, 2);
}
return state;
@@ -921,7 +920,7 @@ public class RedstoneWireTurbo
*/
private static int getMaxCurrentStrength(final UpdateNode upd, final int strength) {
if (upd.type != UpdateNode.Type.REDSTONE) return strength;
final int i = upd.currentState.get(RedstoneWireBlock.POWER);
final int i = upd.currentState.getValue(RedStoneWireBlock.POWER);
return i > strength ? i : strength;
}
}
@@ -1,6 +1,6 @@
package carpet.helpers;
import net.minecraft.util.math.BlockPos;
import net.minecraft.core.BlockPos;
public class ThrowableSuppression extends RuntimeException{
+10 -11
View File
@@ -3,14 +3,13 @@ package carpet.helpers;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.server.level.ServerPlayer;
import carpet.CarpetServer;
import carpet.network.ServerNetworkHandler;
import carpet.utils.Messenger;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.BaseText;
public class TickSpeed
{
@@ -20,9 +19,9 @@ public class TickSpeed
public static long time_bias = 0;
public static long time_warp_start_time = 0;
public static long time_warp_scheduled_ticks = 0;
public static ServerPlayerEntity time_advancerer = null;
public static ServerPlayer time_advancerer = null;
public static String tick_warp_callback = null;
public static ServerCommandSource tick_warp_sender = null;
public static CommandSourceStack tick_warp_sender = null;
public static int player_active_timeout = 0;
public static boolean process_entities = true;
private static boolean deepFreeze = false;
@@ -102,7 +101,7 @@ public class TickSpeed
ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers();
}
public static BaseText tickrate_advance(ServerPlayerEntity player, int advance, String callback, ServerCommandSource source)
public static BaseComponent tickrate_advance(ServerPlayer player, int advance, String callback, CommandSourceStack source)
{
if (0 == advance)
{
@@ -119,7 +118,7 @@ public class TickSpeed
if (time_bias > 0)
{
String who = "Another player";
if (time_advancerer != null) who = time_advancerer.getEntityName();
if (time_advancerer != null) who = time_advancerer.getScoreboardName();
return Messenger.c("l "+who+" is already advancing time at the moment. Try later or ask them");
}
time_advancerer = player;
@@ -147,10 +146,10 @@ public class TickSpeed
time_warp_start_time = 0;
if (tick_warp_callback != null)
{
CommandManager icommandmanager = tick_warp_sender.getServer().getCommandManager();
Commands icommandmanager = tick_warp_sender.getServer().getCommands();
try
{
icommandmanager.execute(tick_warp_sender, tick_warp_callback);
icommandmanager.performCommand(tick_warp_sender, tick_warp_callback);
}
catch (Throwable var23)
{
+26 -27
View File
@@ -1,16 +1,15 @@
package carpet.helpers;
import net.minecraft.entity.Entity;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.RaycastContext;
import net.minecraft.world.World;
import java.util.Optional;
import java.util.function.Predicate;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
public class Tracer
{
@@ -20,7 +19,7 @@ public class Tracer
double maxSqDist = reach * reach;
if (blockHit != null)
{
maxSqDist = blockHit.getPos().squaredDistanceTo(source.getCameraPosVec(partialTicks));
maxSqDist = blockHit.getLocation().distanceToSqr(source.getEyePosition(partialTicks));
}
EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist);
return entityHit == null ? blockHit : entityHit;
@@ -28,31 +27,31 @@ public class Tracer
public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, double reach, boolean fluids)
{
Vec3d pos = source.getCameraPosVec(partialTicks);
Vec3d rotation = source.getRotationVec(partialTicks);
Vec3d reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach);
return source.world.raycast(new RaycastContext(pos, reachEnd, RaycastContext.ShapeType.OUTLINE, fluids ?
RaycastContext.FluidHandling.ANY : RaycastContext.FluidHandling.NONE, source));
Vec3 pos = source.getEyePosition(partialTicks);
Vec3 rotation = source.getViewVector(partialTicks);
Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach);
return source.level.clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ?
ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source));
}
public static EntityHitResult rayTraceEntities(Entity source, float partialTicks, double reach, double maxSqDist)
{
Vec3d pos = source.getCameraPosVec(partialTicks);
Vec3d reachVec = source.getRotationVec(partialTicks).multiply(reach);
Box box = source.getBoundingBox().stretch(reachVec).expand(1);
return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.collides(), maxSqDist);
Vec3 pos = source.getEyePosition(partialTicks);
Vec3 reachVec = source.getViewVector(partialTicks).scale(reach);
AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1);
return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.isPickable(), maxSqDist);
}
public static EntityHitResult rayTraceEntities(Entity source, Vec3d start, Vec3d end, Box box, Predicate<Entity> predicate, double maxSqDistance)
public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate<Entity> predicate, double maxSqDistance)
{
World world = source.world;
Level world = source.level;
double targetDistance = maxSqDistance;
Entity target = null;
Vec3d targetHitPos = null;
for (Entity current : world.getOtherEntities(source, box, predicate))
Vec3 targetHitPos = null;
for (Entity current : world.getEntities(source, box, predicate))
{
Box currentBox = current.getBoundingBox().expand(current.getTargetingMargin());
Optional<Vec3d> currentHit = currentBox.raycast(start, end);
AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius());
Optional<Vec3> currentHit = currentBox.clip(start, end);
if (currentBox.contains(start))
{
if (targetDistance >= 0)
@@ -64,8 +63,8 @@ public class Tracer
}
else if (currentHit.isPresent())
{
Vec3d currentHitPos = currentHit.get();
double currentDistance = start.squaredDistanceTo(currentHitPos);
Vec3 currentHitPos = currentHit.get();
double currentDistance = start.distanceToSqr(currentHitPos);
if (currentDistance < targetDistance || targetDistance == 0)
{
if (current.getRootVehicle() == source.getRootVehicle())
+42 -43
View File
@@ -8,17 +8,16 @@ import carpet.mixins.PlayerListHeaderS2CPacketMixin;
import carpet.utils.Messenger;
import carpet.utils.SpawnReporter;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.protocol.game.ClientboundTabListPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.MathHelper;
import net.minecraft.text.BaseText;
import net.minecraft.text.LiteralText;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.World;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -43,18 +42,18 @@ public class HUDController
HUDListeners.add(listener);
}
public static Map<ServerPlayerEntity, List<BaseText>> player_huds = new HashMap<>();
public static Map<ServerPlayer, List<BaseComponent>> player_huds = new HashMap<>();
//keyed with player names so unlogged players don't hold the reference
public static final Map<String, BaseText> scarpet_headers = new HashMap<>();
public static final Map<String, BaseComponent> scarpet_headers = new HashMap<>();
public static final Map<String, BaseText> scarpet_footers = new HashMap<>();
public static final Map<String, BaseComponent> scarpet_footers = new HashMap<>();
public static void resetScarpetHUDs() {
scarpet_headers.clear();
scarpet_footers.clear();
}
public static void addMessage(ServerPlayerEntity player, BaseText hudMessage)
public static void addMessage(ServerPlayer player, BaseComponent hudMessage)
{
if (player == null) return;
if (!player_huds.containsKey(player))
@@ -63,29 +62,29 @@ public class HUDController
}
else
{
player_huds.get(player).add(new LiteralText("\n"));
player_huds.get(player).add(new TextComponent("\n"));
}
player_huds.get(player).add(hudMessage);
}
public static void clear_player(PlayerEntity player)
public static void clear_player(Player player)
{
PacketByteBuf packetData = new PacketByteBuf(Unpooled.buffer()).writeText(new LiteralText("")).writeText(new LiteralText(""));
PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(packetData);
FriendlyByteBuf packetData = new FriendlyByteBuf(Unpooled.buffer()).writeComponent(new TextComponent("")).writeComponent(new TextComponent(""));
ClientboundTabListPacket packet = new ClientboundTabListPacket(packetData);
//((PlayerListHeaderS2CPacketMixin)packet).setHeader(new LiteralText(""));
//((PlayerListHeaderS2CPacketMixin)packet).setFooter(new LiteralText(""));
((ServerPlayerEntity)player).networkHandler.sendPacket(packet);
((ServerPlayer)player).connection.send(packet);
}
public static void update_hud(MinecraftServer server, List<ServerPlayerEntity> force)
public static void update_hud(MinecraftServer server, List<ServerPlayer> force)
{
if (((server.getTicks() % 20 != 0) && force == null) || CarpetServer.minecraft_server == null)
if (((server.getTickCount() % 20 != 0) && force == null) || CarpetServer.minecraft_server == null)
return;
player_huds.clear();
server.getPlayerManager().getPlayerList().forEach(p -> {
BaseText scarpetFOoter = scarpet_footers.get(p.getEntityName());
server.getPlayerList().getPlayers().forEach(p -> {
BaseComponent scarpetFOoter = scarpet_footers.get(p.getScoreboardName());
if (scarpetFOoter != null) HUDController.addMessage(p, scarpetFOoter);
});
@@ -94,20 +93,20 @@ public class HUDController
if (LoggerRegistry.__mobcaps)
LoggerRegistry.getLogger("mobcaps").log((option, player) -> {
RegistryKey<World> dim = player.world.getRegistryKey(); //getDimType
ResourceKey<Level> dim = player.level.dimension(); //getDimType
switch (option)
{
case "overworld":
dim = World.OVERWORLD; // OW
dim = Level.OVERWORLD; // OW
break;
case "nether":
dim = World.NETHER; // nether
dim = Level.NETHER; // nether
break;
case "end":
dim = World.END; // end
dim = Level.END; // end
break;
}
return new BaseText[]{SpawnReporter.printMobcapsForDimension(server.getWorld(dim), false).get(0)};
return new BaseComponent[]{SpawnReporter.printMobcapsForDimension(server.getLevel(dim), false).get(0)};
});
if(LoggerRegistry.__counter)
@@ -119,43 +118,43 @@ public class HUDController
// extensions have time to pitch in.
HUDListeners.forEach(l -> l.accept(server));
Set<ServerPlayerEntity> targets = new HashSet<>(player_huds.keySet());
Set<ServerPlayer> targets = new HashSet<>(player_huds.keySet());
if (force!= null) targets.addAll(force);
for (ServerPlayerEntity player: targets)
for (ServerPlayer player: targets)
{
PacketByteBuf packetData = new PacketByteBuf(Unpooled.buffer()).
writeText(scarpet_headers.getOrDefault(player.getEntityName(), new LiteralText(""))).
writeText(Messenger.c(player_huds.getOrDefault(player, Collections.emptyList()).toArray(new Object[0])));
PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(packetData);
FriendlyByteBuf packetData = new FriendlyByteBuf(Unpooled.buffer()).
writeComponent(scarpet_headers.getOrDefault(player.getScoreboardName(), new TextComponent(""))).
writeComponent(Messenger.c(player_huds.getOrDefault(player, Collections.emptyList()).toArray(new Object[0])));
ClientboundTabListPacket packet = new ClientboundTabListPacket(packetData);
//PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket();
//((PlayerListHeaderS2CPacketMixin)packet).setHeader(scarpet_headers.getOrDefault(player.getEntityName(), new LiteralText("")));
//((PlayerListHeaderS2CPacketMixin)packet).setFooter(Messenger.c(player_huds.getOrDefault(player, Collections.emptyList()).toArray(new Object[0])));
player.networkHandler.sendPacket(packet);
player.connection.send(packet);
}
}
private static BaseText [] send_tps_display(MinecraftServer server)
private static BaseComponent [] send_tps_display(MinecraftServer server)
{
double MSPT = MathHelper.average(server.lastTickLengths) * 1.0E-6D;
double MSPT = Mth.average(server.tickTimes) * 1.0E-6D;
double TPS = 1000.0D / Math.max((TickSpeed.time_warp_start_time != 0)?0.0:TickSpeed.mspt, MSPT);
String color = Messenger.heatmap_color(MSPT,TickSpeed.mspt);
return new BaseText[]{Messenger.c(
return new BaseComponent[]{Messenger.c(
"g TPS: ", String.format(Locale.US, "%s %.1f",color, TPS),
"g MSPT: ", String.format(Locale.US,"%s %.1f", color, MSPT))};
}
private static BaseText [] send_counter_info(MinecraftServer server, String color)
private static BaseComponent [] send_counter_info(MinecraftServer server, String color)
{
List <BaseText> res = new ArrayList<>();
List <BaseComponent> res = new ArrayList<>();
Arrays.asList(color.split(",")).forEach(c ->{
HopperCounter counter = HopperCounter.getCounter(c);
if (counter != null) res.addAll(counter.format(server, false, true));
});
return res.toArray(new BaseText[0]);
return res.toArray(new BaseComponent[0]);
}
private static BaseText [] packetCounter()
private static BaseComponent [] packetCounter()
{
BaseText [] ret = new BaseText[]{
BaseComponent [] ret = new BaseComponent[]{
Messenger.c("w I/" + PacketCounter.totalIn + " O/" + PacketCounter.totalOut),
};
PacketCounter.reset();
+5 -6
View File
@@ -1,9 +1,8 @@
package carpet.logging;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.BaseText;
import java.lang.reflect.Field;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.server.level.ServerPlayer;
public class HUDLogger extends Logger
{
@@ -38,15 +37,15 @@ public class HUDLogger extends Logger
@Override
public void removePlayer(String playerName)
{
ServerPlayerEntity player = playerFromName(playerName);
ServerPlayer player = playerFromName(playerName);
if (player != null) HUDController.clear_player(player);
super.removePlayer(playerName);
}
@Override
public void sendPlayerMessage(ServerPlayerEntity player, BaseText... messages)
public void sendPlayerMessage(ServerPlayer player, BaseComponent... messages)
{
for (BaseText m:messages) HUDController.addMessage(player, m);
for (BaseComponent m:messages) HUDController.addMessage(player, m);
}
+20 -21
View File
@@ -2,11 +2,6 @@ package carpet.logging;
import carpet.CarpetServer;
import carpet.CarpetSettings;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.BaseText;
import net.minecraft.util.Util;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
@@ -14,6 +9,10 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import net.minecraft.Util;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
public class Logger
{
@@ -136,15 +135,15 @@ public class Logger
* will repeat invocation for players that share the same option
*/
@FunctionalInterface
public interface lMessage { BaseText [] get(String playerOption, PlayerEntity player);}
public interface lMessage { BaseComponent [] get(String playerOption, Player player);}
public void log(lMessage messagePromise)
{
for (Map.Entry<String,String> en : subscribedOnlinePlayers.entrySet())
{
ServerPlayerEntity player = playerFromName(en.getKey());
ServerPlayer player = playerFromName(en.getKey());
if (player != null)
{
BaseText [] messages = messagePromise.get(en.getValue(),player);
BaseComponent [] messages = messagePromise.get(en.getValue(),player);
if (messages != null)
sendPlayerMessage(player, messages);
}
@@ -156,13 +155,13 @@ public class Logger
* and served the same way to all other players subscribed to the same option
*/
@FunctionalInterface
public interface lMessageIgnorePlayer { BaseText [] get(String playerOption);}
public interface lMessageIgnorePlayer { BaseComponent [] get(String playerOption);}
public void log(lMessageIgnorePlayer messagePromise)
{
Map<String, BaseText[]> cannedMessages = new HashMap<>();
Map<String, BaseComponent[]> cannedMessages = new HashMap<>();
for (Map.Entry<String,String> en : subscribedOnlinePlayers.entrySet())
{
ServerPlayerEntity player = playerFromName(en.getKey());
ServerPlayer player = playerFromName(en.getKey());
if (player != null)
{
String option = en.getValue();
@@ -170,7 +169,7 @@ public class Logger
{
cannedMessages.put(option,messagePromise.get(option));
}
BaseText [] messages = cannedMessages.get(option);
BaseComponent [] messages = cannedMessages.get(option);
if (messages != null)
sendPlayerMessage(player, messages);
}
@@ -179,12 +178,12 @@ public class Logger
/**
* guarantees that message is evaluated once, so independent from the player and chosen option
*/
public void log(Supplier<BaseText[]> messagePromise)
public void log(Supplier<BaseComponent[]> messagePromise)
{
BaseText [] cannedMessages = null;
BaseComponent [] cannedMessages = null;
for (Map.Entry<String,String> en : subscribedOnlinePlayers.entrySet())
{
ServerPlayerEntity player = playerFromName(en.getKey());
ServerPlayer player = playerFromName(en.getKey());
if (player != null)
{
if (cannedMessages == null) cannedMessages = messagePromise.get();
@@ -193,22 +192,22 @@ public class Logger
}
}
public void sendPlayerMessage(ServerPlayerEntity player, BaseText ... messages)
public void sendPlayerMessage(ServerPlayer player, BaseComponent ... messages)
{
Arrays.stream(messages).forEach(message -> player.sendSystemMessage(message, Util.NIL_UUID));
Arrays.stream(messages).forEach(message -> player.sendMessage(message, Util.NIL_UUID));
}
/**
* Gets the {@code PlayerEntity} instance for a player given their UUID. Returns null if they are offline.
*/
protected ServerPlayerEntity playerFromName(String name)
protected ServerPlayer playerFromName(String name)
{
return CarpetServer.minecraft_server.getPlayerManager().getPlayer(name);
return CarpetServer.minecraft_server.getPlayerList().getPlayerByName(name);
}
// ----- Event Handlers ----- //
public void onPlayerConnect(PlayerEntity player, boolean firstTime)
public void onPlayerConnect(Player player, boolean firstTime)
{
// If the player was subscribed to the log and offline, move them to the set of online subscribers.
String playerName = player.getName().getString();
@@ -228,7 +227,7 @@ public class Logger
LoggerRegistry.setAccess(this);
}
public void onPlayerDisconnect(PlayerEntity player)
public void onPlayerDisconnect(Player player)
{
// If the player was subscribed to the log, move them to the set of offline subscribers.
String playerName = player.getName().getString();
@@ -2,15 +2,14 @@ package carpet.logging;
import carpet.CarpetServer;
import carpet.CarpetSettings;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.DyeColor;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.DyeColor;
public class LoggerRegistry
{
@@ -152,7 +151,7 @@ public class LoggerRegistry
loggerRegistry.clear();
playerSubscriptions.clear();
}
public static void playerConnected(PlayerEntity player)
public static void playerConnected(Player player)
{
boolean firstTime = false;
if (!seenPlayers.contains(player.getName().getString()))
@@ -167,7 +166,7 @@ public class LoggerRegistry
}
}
public static void playerDisconnected(PlayerEntity player)
public static void playerDisconnected(Player player)
{
for(Logger log: loggerRegistry.values() )
{
@@ -4,23 +4,22 @@ import carpet.logging.LoggerRegistry;
import carpet.utils.Messenger;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.text.BaseText;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.explosion.Explosion;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.core.Registry;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.phys.Vec3;
import static carpet.utils.Messenger.c;
public class ExplosionLogHelper
{
private final boolean createFire;
private final Explosion.DestructionType blockDestructionType;
public final Vec3d pos;
private final Explosion.BlockInteraction blockDestructionType;
public final Vec3 pos;
public final Entity entity;
private final float power;
private boolean affectBlocks = false;
@@ -30,10 +29,10 @@ public class ExplosionLogHelper
private static int explosionCountInCurretGT = 0;
private static boolean newTick;
public ExplosionLogHelper(Entity entity, double x, double y, double z, float power, boolean createFire, Explosion.DestructionType blockDestructionType) {
public ExplosionLogHelper(Entity entity, double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType) {
this.entity = entity;
this.power = power;
this.pos = new Vec3d(x,y,z);
this.pos = new Vec3(x,y,z);
this.createFire = createFire;
this.blockDestructionType = blockDestructionType;
}
@@ -53,7 +52,7 @@ public class ExplosionLogHelper
}
explosionCountInCurretGT++;
LoggerRegistry.getLogger("explosions").log( (option) -> {
List<BaseText> messages = new ArrayList<>();
List<BaseComponent> messages = new ArrayList<>();
if(newTick) messages.add(c("wb tick : ", "d " + gametime));
if ("brief".equals(option))
{
@@ -79,27 +78,27 @@ public class ExplosionLogHelper
messages.add(c((k.pos.equals(pos))?"r - TNT":"w - ",
Messenger.dblt((k.pos.equals(pos))?"r":"y", k.pos.x, k.pos.y, k.pos.z), "w dV",
Messenger.dblt("d", k.accel.x, k.accel.y, k.accel.z),
"w "+Registry.ENTITY_TYPE.getId(k.type).getPath(), (v>1)?"l ("+v+")":""
"w "+Registry.ENTITY_TYPE.getKey(k.type).getPath(), (v>1)?"l ("+v+")":""
));
});
}
}
return messages.toArray(new BaseText[0]);
return messages.toArray(new BaseComponent[0]);
});
}
public void onEntityImpacted(Entity entity, Vec3d accel)
public void onEntityImpacted(Entity entity, Vec3 accel)
{
EntityChangedStatusWithCount ent = new EntityChangedStatusWithCount(entity, accel);
impactedEntities.put(ent, impactedEntities.getOrDefault(ent, 0)+1);
}
public static record EntityChangedStatusWithCount(Vec3d pos, EntityType type, Vec3d accel)
public static record EntityChangedStatusWithCount(Vec3 pos, EntityType<?> type, Vec3 accel)
{
public EntityChangedStatusWithCount(Entity e, Vec3d accel)
public EntityChangedStatusWithCount(Entity e, Vec3 accel)
{
this(e.getPos(), e.getType(), accel);
this(e.position(), e.getType(), accel);
}
}
}
@@ -2,18 +2,18 @@ package carpet.logging.logHelpers;
import carpet.helpers.ParticleDisplay;
import carpet.logging.LoggerRegistry;
import net.minecraft.entity.Entity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.Vec3d;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
public class PathfindingVisualizer
{
public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful)
public static void slowPath(Entity entity, Vec3 target, float miliseconds, boolean successful)
{
if (!LoggerRegistry.__pathfinding) return;
LoggerRegistry.getLogger("pathfinding").log( (option, player)->
{
if (!(player instanceof ServerPlayerEntity))
if (!(player instanceof ServerPlayer))
return null;
int minDuration;
try
@@ -26,14 +26,14 @@ public class PathfindingVisualizer
}
if (miliseconds < minDuration)
return null;
if (player.squaredDistanceTo(entity) > 1000 && player.squaredDistanceTo(target) > 1000)
if (player.distanceToSqr(entity) > 1000 && player.distanceToSqr(target) > 1000)
return null;
if (minDuration < 1)
minDuration = 1;
String accent = successful ? "happy_villager" : "angry_villager";
String color = (miliseconds/minDuration < 2)? "dust 1 1 0 1" : ((miliseconds/minDuration < 4)?"dust 1 0.5 0 1":"dust 1 0 0 1");
ParticleDisplay.drawParticleLine((ServerPlayerEntity) player, entity.getPos(), target, color, accent, 5, 0.5);
ParticleDisplay.drawParticleLine((ServerPlayer) player, entity.position(), target, color, accent, 5, 0.5);
return null;
});
}
@@ -2,8 +2,8 @@ package carpet.logging.logHelpers;
import carpet.logging.LoggerRegistry;
import carpet.utils.Messenger;
import net.minecraft.text.BaseText;
import net.minecraft.util.math.Vec3d;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.world.phys.Vec3;
public class TNTLogHelper
{
@@ -11,11 +11,11 @@ public class TNTLogHelper
private double primedX, primedY, primedZ;
private static long lastGametime = 0;
private static int tntCount = 0;
private Vec3d primedAngle;
private Vec3 primedAngle;
/**
* Runs when the TNT is primed. Expects the position and motion angle of the TNT.
*/
public void onPrimed(double x, double y, double z, Vec3d motion)
public void onPrimed(double x, double y, double z, Vec3 motion)
{
primedX = x;
primedY = y;
@@ -37,12 +37,12 @@ public class TNTLogHelper
switch (option)
{
case "brief":
return new BaseText[]{Messenger.c(
return new BaseComponent[]{Messenger.c(
"l P ",Messenger.dblt("l",primedX,primedY,primedZ),
"w ",Messenger.dblt("l", primedAngle.x, primedAngle.y, primedAngle.z),
"r E ",Messenger.dblt("r",x, y, z))};
case "full":
return new BaseText[]{Messenger.c(
return new BaseComponent[]{Messenger.c(
"r #" + tntCount,
"m @" + gametime,
"g : ",
@@ -3,11 +3,10 @@ package carpet.logging.logHelpers;
import carpet.logging.Logger;
import carpet.logging.LoggerRegistry;
import carpet.utils.Messenger;
import net.minecraft.util.math.Vec3d;
import net.minecraft.text.BaseText;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.network.chat.BaseComponent;
import net.minecraft.world.phys.Vec3;
/**
* A generic log helper for logging the trajectory of things like blocks and throwables.
@@ -19,8 +18,8 @@ public class TrajectoryLogHelper
private boolean doLog;
private Logger logger;
private ArrayList<Vec3d> positions = new ArrayList<>();
private ArrayList<Vec3d> motions = new ArrayList<>();
private ArrayList<Vec3> positions = new ArrayList<>();
private ArrayList<Vec3> motions = new ArrayList<>();
public TrajectoryLogHelper(String logName)
{
@@ -28,10 +27,10 @@ public class TrajectoryLogHelper
this.doLog = this.logger.hasOnlineSubscribers();
}
public void onTick(double x, double y, double z, Vec3d velocity)
public void onTick(double x, double y, double z, Vec3 velocity)
{
if (!doLog) return;
positions.add(new Vec3d(x, y, z));
positions.add(new Vec3(x, y, z));
motions.add(velocity);
}
@@ -39,7 +38,7 @@ public class TrajectoryLogHelper
{
if (!doLog) return;
logger.log( (option) -> {
List<BaseText> comp = new ArrayList<>();
List<BaseComponent> comp = new ArrayList<>();
switch (option)
{
case "brief":
@@ -48,8 +47,8 @@ public class TrajectoryLogHelper
for (int i = 0; i < positions.size(); i++)
{
Vec3d pos = positions.get(i);
Vec3d mot = motions.get(i);
Vec3 pos = positions.get(i);
Vec3 mot = motions.get(i);
line.add("w x");
line.add(String.format("^w Tick: %d\nx: %f\ny: %f\nz: %f\n------------\nmx: %f\nmy: %f\nmz: %f",
i, pos.x, pos.y, pos.z, mot.x, mot.y, mot.z));
@@ -64,15 +63,15 @@ public class TrajectoryLogHelper
comp.add(Messenger.c("w ---------"));
for (int i = 0; i < positions.size(); i++)
{
Vec3d pos = positions.get(i);
Vec3d mot = motions.get(i);
Vec3 pos = positions.get(i);
Vec3 mot = motions.get(i);
comp.add(Messenger.c(
String.format("w tick: %3d pos",i),Messenger.dblt("w",pos.x, pos.y, pos.z),
"w mot",Messenger.dblt("w",mot.x, mot.y, mot.z)));
}
break;
}
return comp.toArray(new BaseText[0]);
return comp.toArray(new BaseComponent[0]);
});
doLog = false;
}
@@ -1,17 +1,17 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.block.AbstractCauldronBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.ShulkerBoxBlock;
import net.minecraft.block.cauldron.CauldronBehavior;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.core.BlockPos;
import net.minecraft.core.cauldron.CauldronInteraction;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.AbstractCauldronBlock;
import net.minecraft.world.level.block.ShulkerBoxBlock;
import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@@ -19,16 +19,16 @@ import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(AbstractCauldronBlock.class)
public class AbstractCauldronBlock_stackableSBoxesMixin
{
@Redirect(method = "onUse", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/cauldron/CauldronBehavior;interact(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/util/Hand;Lnet/minecraft/item/ItemStack;)Lnet/minecraft/util/ActionResult;"))
private ActionResult wrapInteractor(CauldronBehavior cauldronBehavior, BlockState blockState, World world, BlockPos blockPos, PlayerEntity playerEntity, Hand hand, ItemStack itemStack)
@Redirect(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/core/cauldron/CauldronInteraction;interact(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/InteractionResult;"))
private InteractionResult wrapInteractor(CauldronInteraction cauldronBehavior, BlockState blockState, Level world, BlockPos blockPos, Player playerEntity, InteractionHand hand, ItemStack itemStack)
{
int count = -1;
if (CarpetSettings.shulkerBoxStackSize > 1 && itemStack.getItem() instanceof BlockItem && ((BlockItem)itemStack.getItem()).getBlock() instanceof ShulkerBoxBlock)
count = itemStack.getCount();
ActionResult result = cauldronBehavior.interact(blockState, world, blockPos, playerEntity, hand, itemStack);
if (count > 0 && result.isAccepted())
InteractionResult result = cauldronBehavior.interact(blockState, world, blockPos, playerEntity, hand, itemStack);
if (count > 0 && result.consumesAction())
{
ItemStack current = playerEntity.getStackInHand(hand);
ItemStack current = playerEntity.getItemInHand(hand);
if (current.getItem() instanceof BlockItem && ((BlockItem)itemStack.getItem()).getBlock() instanceof ShulkerBoxBlock)
current.setCount(count);
}
@@ -1,18 +1,18 @@
package carpet.mixins;
import carpet.fakes.ScreenHandlerInterface;
import net.minecraft.recipe.Recipe;
import net.minecraft.screen.AbstractRecipeScreenHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.RecipeBookMenu;
import net.minecraft.world.item.crafting.Recipe;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(AbstractRecipeScreenHandler.class)
@Mixin(RecipeBookMenu.class)
public class AbstractRecipeScreenHandler_scarpetMixin {
@Inject(method = "fillInputSlots",at = @At("HEAD"), cancellable = true)
private void selectRecipeCallback(boolean craftAll, Recipe<?> recipe, ServerPlayerEntity player, CallbackInfo ci) {
@Inject(method = "handlePlacement",at = @At("HEAD"), cancellable = true)
private void selectRecipeCallback(boolean craftAll, Recipe<?> recipe, ServerPlayer player, CallbackInfo ci) {
if(((ScreenHandlerInterface) this).callSelectRecipeListener(player,recipe,craftAll))
ci.cancel();
}
@@ -2,10 +2,6 @@ package carpet.mixins;
import carpet.CarpetServer;
import carpet.script.api.Auxiliary;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.decoration.ArmorStandEntity;
import net.minecraft.world.World;
import org.apache.commons.lang3.StringUtils;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@@ -13,11 +9,15 @@ import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Optional;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.decoration.ArmorStand;
import net.minecraft.world.level.Level;
@Mixin(ArmorStandEntity.class)
@Mixin(ArmorStand.class)
public abstract class ArmorStandEntity_scarpetMarkerMixin extends LivingEntity
{
protected ArmorStandEntity_scarpetMarkerMixin(EntityType<? extends LivingEntity> entityType_1, World world_1)
protected ArmorStandEntity_scarpetMarkerMixin(EntityType<? extends LivingEntity> entityType_1, Level world_1)
{
super(entityType_1, world_1);
}
@@ -26,15 +26,15 @@ public abstract class ArmorStandEntity_scarpetMarkerMixin extends LivingEntity
* Remove all markers that do not belong to any script host and not part of the global one when loaded
* @param ci
*/
@Inject(method = "readCustomDataFromNbt", at = @At("HEAD"))
@Inject(method = "readAdditionalSaveData", at = @At("HEAD"))
private void checkScarpetMarkerUnloaded(CallbackInfo ci)
{
if (!world.isClient)
if (!level.isClientSide)
{
if (getScoreboardTags().contains(Auxiliary.MARKER_STRING))
if (getTags().contains(Auxiliary.MARKER_STRING))
{
String prefix = Auxiliary.MARKER_STRING+"_";
Optional<String> owner = getScoreboardTags().stream().filter(s -> s.startsWith(prefix)).findFirst();
Optional<String> owner = getTags().stream().filter(s -> s.startsWith(prefix)).findFirst();
if (owner.isPresent())
{
String hostName = StringUtils.removeStart(owner.get(),prefix);
@@ -1,54 +1,54 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.block.BarrierBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.PoweredRailBlock;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import java.util.Random;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BarrierBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.PoweredRailBlock;
import net.minecraft.world.level.block.state.BlockState;
@Mixin(BarrierBlock.class)
public class BarrierBlock_updateSuppressionBlockMixin extends Block {
private boolean shouldPower = false;
public BarrierBlock_updateSuppressionBlockMixin(Settings settings) { super(settings); }
public BarrierBlock_updateSuppressionBlockMixin(Properties settings) { super(settings); }
@Override
public int getWeakRedstonePower(BlockState state, BlockView world, BlockPos pos, Direction direction) {
public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) {
return (shouldPower && direction == Direction.DOWN) ? 15 : 0;
}
@Override
public void neighborUpdate(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) {
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) {
if (CarpetSettings.updateSuppressionBlockSetting != -1) {
if (fromPos.equals(pos.up())) {
if (fromPos.equals(pos.above())) {
BlockState stateAbove = world.getBlockState(fromPos);
if (stateAbove.isOf(Blocks.ACTIVATOR_RAIL) && !stateAbove.get(PoweredRailBlock.POWERED)) {
if (stateAbove.is(Blocks.ACTIVATOR_RAIL) && !stateAbove.getValue(PoweredRailBlock.POWERED)) {
if (CarpetSettings.updateSuppressionBlockSetting > 0) {
world.createAndScheduleBlockTick(pos, this, CarpetSettings.updateSuppressionBlockSetting);
world.scheduleTick(pos, this, CarpetSettings.updateSuppressionBlockSetting);
}
throw new StackOverflowError("updateSuppressionBlock");
}
}
}
super.neighborUpdate(state, world, pos, block, fromPos, notify);
super.neighborChanged(state, world, pos, block, fromPos, notify);
}
@Override
public void scheduledTick(BlockState state, ServerWorld world, BlockPos pos, Random random) {
BlockPos posAbove = pos.up();
public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) {
BlockPos posAbove = pos.above();
BlockState stateAbove = world.getBlockState(posAbove);
if (stateAbove.isOf(Blocks.ACTIVATOR_RAIL) && !stateAbove.get(PoweredRailBlock.POWERED)) {
if (stateAbove.is(Blocks.ACTIVATOR_RAIL) && !stateAbove.getValue(PoweredRailBlock.POWERED)) {
shouldPower = true;
world.setBlockState(posAbove, stateAbove.with(PoweredRailBlock.POWERED, true), 3);
world.setBlock(posAbove, stateAbove.setValue(PoweredRailBlock.POWERED, true), 3);
shouldPower = false;
}
}
@@ -4,20 +4,13 @@ import carpet.CarpetSettings;
import com.google.common.collect.Lists;
import com.mojang.serialization.Codec;
import net.minecraft.entity.EntityType;
import net.minecraft.util.collection.Pool;
import net.minecraft.world.MobSpawnerLogic;
import net.minecraft.world.biome.SpawnSettings;
import net.minecraft.world.gen.feature.BastionRemnantFeature;
import net.minecraft.world.gen.feature.JigsawFeature;
import net.minecraft.world.gen.feature.StructurePoolFeatureConfig;
import org.spongepowered.asm.mixin.Mixin;
import java.util.Collections;
import java.util.List;
import net.minecraft.world.level.levelgen.feature.BastionFeature;
@Mixin(BastionRemnantFeature.class)
@Mixin(BastionFeature.class)
public abstract class BastionRemnantFeatureMixin //extends JigsawFeature
{
/*
@@ -1,12 +1,6 @@
package carpet.mixins;
import carpet.fakes.BiomeArrayInterface;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
//import net.minecraft.world.biome.source.BiomeArray;
import net.minecraft.world.biome.source.BiomeCoords;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@@ -7,7 +7,7 @@ import org.spongepowered.asm.mixin.injection.Redirect;
import java.util.Random;
@Mixin(targets = "net.minecraft.entity.mob.BlazeEntity$ShootFireballGoal")
@Mixin(targets = "net.minecraft.world.entity.monster.Blaze$BlazeAttackGoal")
public class BlazeEntityShootFireballGoal_extremeMixin
{
@Redirect(method = "tick()V", expect = 2, at = @At(
@@ -1,18 +1,18 @@
package carpet.mixins;
import carpet.utils.RandomTools;
import net.minecraft.entity.mob.BlazeEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.util.Random;
import net.minecraft.world.entity.monster.Blaze;
@Mixin(BlazeEntity.class)
@Mixin(Blaze.class)
public class BlazeEntity_extremeMixin
{
// unused actually
@Redirect(method = "mobTick", expect = 1, at = @At(
@Redirect(method = "customServerAiStep", expect = 1, at = @At(
value = "INVOKE",
target = "Ljava/util/Random;nextGaussian()D"
))
@@ -1,8 +1,8 @@
package carpet.mixins;
import carpet.fakes.BlockEntityInterface;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.entity.BlockEntity;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
@@ -12,10 +12,10 @@ import org.spongepowered.asm.mixin.Shadow;
public abstract class BlockEntity_movableBEMixin implements BlockEntityInterface
{
@Mutable
@Shadow @Final protected BlockPos pos;
@Shadow @Final protected BlockPos worldPosition;
public void setCMPos(BlockPos newPos)
{
pos = newPos;
worldPosition = newPos;
};
}
@@ -1,14 +1,14 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.block.BlockState;
import net.minecraft.block.ShapeContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.World;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@@ -18,19 +18,19 @@ public class BlockItem_creativeNoClipMixin
{
@Redirect(method = "canPlace", at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/World;canPlace(Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/ShapeContext;)Z"
target = "Lnet/minecraft/world/level/Level;isUnobstructed(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Z"
))
private boolean canSpectatingPlace(World world, BlockState state, BlockPos pos, ShapeContext context,
ItemPlacementContext contextOuter, BlockState stateOuter)
private boolean canSpectatingPlace(Level world, BlockState state, BlockPos pos, CollisionContext context,
BlockPlaceContext contextOuter, BlockState stateOuter)
{
PlayerEntity player = contextOuter.getPlayer();
Player player = contextOuter.getPlayer();
if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.getAbilities().flying)
{
// copy from canPlace
VoxelShape voxelShape = state.getCollisionShape(world, pos, context);
return voxelShape.isEmpty() || world.doesNotIntersectEntities(player, voxelShape.offset(pos.getX(), pos.getY(), pos.getZ()));
return voxelShape.isEmpty() || world.isUnobstructed(player, voxelShape.move(pos.getX(), pos.getY(), pos.getZ()));
}
return world.canPlace(state, pos, context);
return world.isUnobstructed(state, pos, context);
}
}
@@ -1,9 +1,5 @@
package carpet.mixins;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.ActionResult;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -11,17 +7,22 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import static carpet.script.CarpetEventServer.Event.PLAYER_PLACES_BLOCK;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.context.BlockPlaceContext;
@Mixin(BlockItem.class)
public class BlockItem_scarpetEventMixin
{
@Inject(method = "place(Lnet/minecraft/item/ItemPlacementContext;)Lnet/minecraft/util/ActionResult;", at = @At(
@Inject(method = "place(Lnet/minecraft/world/item/context/BlockPlaceContext;)Lnet/minecraft/world/InteractionResult;", at = @At(
value = "INVOKE",
target = "Lnet/minecraft/block/Block;onPlaced(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/entity/LivingEntity;Lnet/minecraft/item/ItemStack;)V",
target = "Lnet/minecraft/world/level/block/Block;setPlacedBy(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/item/ItemStack;)V",
shift = At.Shift.AFTER
))
private void afterPlacement(ItemPlacementContext context, CallbackInfoReturnable<ActionResult> cir)
private void afterPlacement(BlockPlaceContext context, CallbackInfoReturnable<InteractionResult> cir)
{
if (context.getPlayer() instanceof ServerPlayerEntity && PLAYER_PLACES_BLOCK.isNeeded())
PLAYER_PLACES_BLOCK.onBlockPlaced((ServerPlayerEntity) context.getPlayer(), context.getBlockPos(), context.getHand(), context.getStack());
if (context.getPlayer() instanceof ServerPlayer && PLAYER_PLACES_BLOCK.isNeeded())
PLAYER_PLACES_BLOCK.onBlockPlaced((ServerPlayer) context.getPlayer(), context.getClickedPos(), context.getHand(), context.getItemInHand());
}
}
@@ -4,55 +4,55 @@ import org.spongepowered.asm.mixin.Mixin;
import carpet.fakes.ChunkLightProviderInterface;
import carpet.fakes.LightStorageInterface;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkSectionPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.LightType;
import net.minecraft.world.chunk.ChunkNibbleArray;
import net.minecraft.world.chunk.ChunkProvider;
import net.minecraft.world.chunk.light.BlockLightStorage;
import net.minecraft.world.chunk.light.BlockLightStorage.Data;
import net.minecraft.world.chunk.light.ChunkLightProvider;
import net.minecraft.world.chunk.light.LightStorage;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.SectionPos;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.chunk.DataLayer;
import net.minecraft.world.level.chunk.LightChunkGetter;
import net.minecraft.world.level.lighting.BlockLightSectionStorage;
import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap;
import net.minecraft.world.level.lighting.LayerLightEngine;
import net.minecraft.world.level.lighting.LayerLightSectionStorage;
@Mixin(BlockLightStorage.class)
public abstract class BlockLightStorage_scarpetChunkCreationMixin extends LightStorage<Data> implements LightStorageInterface
@Mixin(BlockLightSectionStorage.class)
public abstract class BlockLightStorage_scarpetChunkCreationMixin extends LayerLightSectionStorage<BlockDataLayerStorageMap> implements LightStorageInterface
{
private BlockLightStorage_scarpetChunkCreationMixin(final LightType lightType, final ChunkProvider chunkProvider, final Data lightData)
private BlockLightStorage_scarpetChunkCreationMixin(final LightLayer lightType, final LightChunkGetter chunkProvider, final BlockDataLayerStorageMap lightData)
{
super(lightType, chunkProvider, lightData);
}
@Override
public void processRelight(final ChunkLightProvider<?, ?> lightProvider, final long cPos)
public void processRelight(final LayerLightEngine<?, ?> lightProvider, final long cPos)
{
final LevelPropagator_resetChunkInterface levelPropagator = (LevelPropagator_resetChunkInterface) lightProvider;
for (int y = -1; y < 17; ++y)
{
final long sectionPos = ChunkSectionPos.asLong(ChunkSectionPos.unpackX(cPos), y, ChunkSectionPos.unpackZ(cPos));
final long pos = BlockPos.asLong(ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackX(sectionPos)), ChunkSectionPos.getBlockCoord(y), ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackZ(sectionPos)));
final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos));
final long pos = BlockPos.asLong(SectionPos.sectionToBlockCoord(SectionPos.x(sectionPos)), SectionPos.sectionToBlockCoord(y), SectionPos.sectionToBlockCoord(SectionPos.z(sectionPos)));
if (!this.hasSection(sectionPos))
if (!this.storingLightForSection(sectionPos))
continue;
for (final Direction dir : Direction.Type.HORIZONTAL)
for (final Direction dir : Direction.Plane.HORIZONTAL)
{
final ChunkNibbleArray neighborLightArray = this.getLightSection(ChunkSectionPos.offset(sectionPos, dir));
final DataLayer neighborLightArray = this.getDataLayerData(SectionPos.offset(sectionPos, dir));
if (neighborLightArray == null)
continue;
final int ox = 15 * Math.max(dir.getOffsetX(), 0);
final int oz = 15 * Math.max(dir.getOffsetZ(), 0);
final int ox = 15 * Math.max(dir.getStepX(), 0);
final int oz = 15 * Math.max(dir.getStepZ(), 0);
final int dx = Math.abs(dir.getOffsetZ());
final int dz = Math.abs(dir.getOffsetX());
final int dx = Math.abs(dir.getStepZ());
final int dz = Math.abs(dir.getStepX());
for (int t = 0; t < 16; ++t)
for (int dy = 0; dy < 16; ++dy)
{
final long dst = BlockPos.add(pos, ox + t * dx, dy, oz + t * dz);
final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz);
final long src = BlockPos.offset(dst, dir);
final int srcLevel = ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborLightArray, src);
@@ -5,26 +5,26 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import carpet.CarpetSettings;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.command.argument.BlockStateArgument;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldAccess;
import net.minecraft.commands.arguments.blocks.BlockInput;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
@Mixin(BlockStateArgument.class)
@Mixin(BlockInput.class)
public class BlockStateArgument_fillUpdatesMixin
{
@Redirect(method = "setBlockState", at = @At(
@Redirect(method = "place", at = @At(
value = "INVOKE",
target = "Lnet/minecraft/block/Block;postProcessState(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/WorldAccess;Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;"
target = "Lnet/minecraft/world/level/block/Block;updateFromNeighbourShapes(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;"
))
private BlockState postProcessStateProxy(BlockState state, WorldAccess serverWorld, BlockPos blockPos)
private BlockState postProcessStateProxy(BlockState state, LevelAccessor serverWorld, BlockPos blockPos)
{
if (CarpetSettings.impendingFillSkipUpdates.get())
{
return state;
}
return Block.postProcessState(state, serverWorld, blockPos);
return Block.updateFromNeighbourShapes(state, serverWorld, blockPos);
}
}
@@ -1,21 +1,21 @@
package carpet.mixins;
import carpet.fakes.BlockStateArgumentInterface;
import net.minecraft.command.argument.BlockStateArgument;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.commands.arguments.blocks.BlockInput;
import net.minecraft.nbt.CompoundTag;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(BlockStateArgument.class)
@Mixin(BlockInput.class)
public class BlockStateArgument_scarpetMixin implements BlockStateArgumentInterface
{
@Shadow @Final private @Nullable NbtCompound data;
@Shadow @Final private @Nullable CompoundTag tag;
@Override
public NbtCompound getCMTag()
public CompoundTag getCMTag()
{
return data;
return tag;
}
}
@@ -1,19 +1,19 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.BuddingAmethystBlock;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.piston.PistonBehavior;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.Enchantments;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.PickaxeItem;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.PickaxeItem;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.BuddingAmethystBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.PushReaction;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@@ -22,24 +22,24 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(BuddingAmethystBlock.class)
public class BuddingAmethystBlock_movableAmethystMixin extends Block {
public BuddingAmethystBlock_movableAmethystMixin(Settings settings) {
public BuddingAmethystBlock_movableAmethystMixin(Properties settings) {
super(settings);
}
@Inject(at = @At("HEAD"), method = "getPistonBehavior(Lnet/minecraft/block/BlockState;)Lnet/minecraft/block/piston/PistonBehavior;", cancellable = true)
void getPistonBehavior(BlockState state, CallbackInfoReturnable<PistonBehavior> cir) {
if (CarpetSettings.movableAmethyst) cir.setReturnValue(PistonBehavior.NORMAL);
@Inject(at = @At("HEAD"), method = "getPistonPushReaction(Lnet/minecraft/world/level/block/state/BlockState;)Lnet/minecraft/world/level/material/PushReaction;", cancellable = true)
void getPistonBehavior(BlockState state, CallbackInfoReturnable<PushReaction> cir) {
if (CarpetSettings.movableAmethyst) cir.setReturnValue(PushReaction.NORMAL);
}
@Override
public void afterBreak(World world, PlayerEntity player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack stack) {
super.afterBreak(world, player, pos, state, blockEntity, stack);
public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack stack) {
super.playerDestroy(world, player, pos, state, blockEntity, stack);
// doing it here rather than though loottables since loottables are loaded on reload
// drawback - not controlled via loottables, but hey
if (CarpetSettings.movableAmethyst &&
stack.getItem() instanceof PickaxeItem &&
EnchantmentHelper.getLevel(Enchantments.SILK_TOUCH, stack) > 0
EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0
)
dropStack(world, pos, Items.BUDDING_AMETHYST.getDefaultStack());
popResource(world, pos, Items.BUDDING_AMETHYST.getDefaultInstance());
}
}
@@ -1,28 +1,28 @@
package carpet.mixins;
import carpet.utils.WoolTool;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.DyedCarpetBlock;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.WoolCarpetBlock;
import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(DyedCarpetBlock.class) // WoolCarpetBlock
@Mixin(WoolCarpetBlock.class) // WoolCarpetBlock
public abstract class CarpetBlockMixin extends Block
{
public CarpetBlockMixin(Settings block$Settings_1)
public CarpetBlockMixin(Properties block$Settings_1)
{
super(block$Settings_1);
}
public BlockState getPlacementState(ItemPlacementContext context)
public BlockState getStateForPlacement(BlockPlaceContext context)
{
BlockState state = super.getPlacementState(context);
if (context.getPlayer() != null && !context.getWorld().isClient)
BlockState state = super.getStateForPlacement(context);
if (context.getPlayer() != null && !context.getLevel().isClientSide)
{ // getColor()
WoolTool.carpetPlacedAction(((DyedCarpetBlock)(Object)this).getDyeColor(), context.getPlayer(), context.getBlockPos(), (ServerWorld) context.getWorld());
WoolTool.carpetPlacedAction(((WoolCarpetBlock)(Object)this).getColor(), context.getPlayer(), context.getClickedPos(), (ServerLevel) context.getLevel());
}
return state;
}
@@ -1,16 +1,7 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.CauldronBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.level.block.CauldronBlock;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -1,14 +1,14 @@
package carpet.mixins;
import net.minecraft.world.gen.NoiseColumnSampler;
import net.minecraft.world.level.levelgen.NoiseSampler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(NoiseColumnSampler.CaveScaler.class)
@Mixin(NoiseSampler.QuantizedSpaghettiRarity.class)
public interface CaveScalerMixin_scarpetMixin {
@Invoker
static double invokeScaleTunnels(double d) {
static double invokeGetSpaghettiRarity3D(double d) {
throw new AssertionError();
}
}
@@ -1,25 +1,25 @@
package carpet.mixins;
import carpet.fakes.ChunkGeneratorInterface;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.chunk.ChunkGenerator;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(ChunkGenerator.class)
public abstract class ChunkGenerator_scarpetMixin implements ChunkGeneratorInterface
{
@Shadow protected abstract void generateStrongholdPositions();
@Shadow private static boolean canPlaceStrongholdInBiome(Biome biome) { return true;}
@Shadow protected abstract void generateStrongholds();
@Shadow private static boolean validStrongholdBiome(Biome biome) { return true;}
@Override
public void initStrongholds()
{
generateStrongholdPositions();
generateStrongholds();
}
@Override
public boolean canPlaceStrongholdInBiomeCM(Biome biome) {
return canPlaceStrongholdInBiome(biome);
return validStrongholdBiome(biome);
}
}
@@ -2,39 +2,39 @@ package carpet.mixins;
import carpet.fakes.ChunkHolderInterface;
import com.mojang.datafixers.util.Either;
import net.minecraft.server.world.ChunkHolder;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.thread.ThreadExecutor;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkStatus;
import net.minecraft.world.chunk.ProtoChunk;
import net.minecraft.world.chunk.UpgradeData;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReferenceArray;
import net.minecraft.core.Registry;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.UpgradeData;
@Mixin(ChunkHolder.class)
public abstract class ChunkHolder_scarpetChunkCreationMixin implements ChunkHolderInterface
{
@Shadow protected abstract void combineSavingFuture(CompletableFuture<? extends Either<? extends Chunk, ChunkHolder.Unloaded>> newChunkFuture, String type);
@Shadow protected abstract void updateChunkToSave(CompletableFuture<? extends Either<? extends ChunkAccess, ChunkHolder.ChunkLoadingFailure>> newChunkFuture, String type);
@Shadow @Final private AtomicReferenceArray<CompletableFuture<Either<Chunk, ChunkHolder.Unloaded>>> futuresByStatus;
@Shadow @Final private AtomicReferenceArray<CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> futures;
@Override
public CompletableFuture<Either<Chunk, ChunkHolder.Unloaded>> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor<Runnable> executor, ServerWorld world)
public CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> setDefaultProtoChunk(ChunkPos chpos, BlockableEventLoop<Runnable> executor, ServerLevel world)
{
int i = ChunkStatus.EMPTY.getIndex();
CompletableFuture<Either<Chunk, ChunkHolder.Unloaded>> completableFuture2 = CompletableFuture.supplyAsync(
() -> Either.left(new ProtoChunk(chpos, UpgradeData.NO_UPGRADE_DATA, world, world.getRegistryManager().get(Registry.BIOME_KEY), null)), // todo figure out what that does - maybe add an option to reset with blending enabled..?
CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> completableFuture2 = CompletableFuture.supplyAsync(
() -> Either.left(new ProtoChunk(chpos, UpgradeData.EMPTY, world, world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY), null)), // todo figure out what that does - maybe add an option to reset with blending enabled..?
executor
);
combineSavingFuture(completableFuture2, "unfull"); // possible debug data
futuresByStatus.set(i, completableFuture2);
updateChunkToSave(completableFuture2, "unfull"); // possible debug data
futures.set(i, completableFuture2);
return completableFuture2;
}
}
@@ -7,30 +7,30 @@ import org.spongepowered.asm.mixin.gen.Invoker;
import carpet.fakes.ChunkLightProviderInterface;
import carpet.fakes.Lighting_scarpetChunkCreationInterface;
import net.minecraft.world.chunk.ChunkNibbleArray;
import net.minecraft.world.chunk.light.ChunkLightProvider;
import net.minecraft.world.chunk.light.LightStorage;
import net.minecraft.world.level.chunk.DataLayer;
import net.minecraft.world.level.lighting.LayerLightEngine;
import net.minecraft.world.level.lighting.LayerLightSectionStorage;
@Mixin(ChunkLightProvider.class)
@Mixin(LayerLightEngine.class)
public abstract class ChunkLightProvider_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface, ChunkLightProviderInterface
{
@Shadow
@Final
protected LightStorage<?> lightStorage;
protected LayerLightSectionStorage<?> storage;
@Override
public void removeLightData(final long pos)
{
((Lighting_scarpetChunkCreationInterface) this.lightStorage).removeLightData(pos);
((Lighting_scarpetChunkCreationInterface) this.storage).removeLightData(pos);
}
@Override
public void relight(final long pos)
{
((Lighting_scarpetChunkCreationInterface) this.lightStorage).relight(pos);
((Lighting_scarpetChunkCreationInterface) this.storage).relight(pos);
}
@Override
@Invoker("getCurrentLevelFromSection")
public abstract int callGetCurrentLevelFromSection(ChunkNibbleArray array, long blockPos);
@Invoker("getLevel")
public abstract int callGetCurrentLevelFromSection(DataLayer array, long blockPos);
}
+4 -4
View File
@@ -1,18 +1,18 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.chunk.ChunkAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Chunk.class)
@Mixin(ChunkAccess.class)
public abstract class ChunkMixin
{
// failed to mixin into interface. need to mixin in two places that uses it
@Inject(method = "markBlockForPostProcessing(Lnet/minecraft/util/math/BlockPos;)V",
@Inject(method = "markPosForPostprocessing(Lnet/minecraft/core/BlockPos;)V",
at =@At("HEAD"), cancellable = true)
private void squashWarnings(BlockPos blockPos_1, CallbackInfo ci)
{
@@ -1,17 +1,17 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ChunkRegion;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.WorldGenRegion;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ChunkRegion.class)
@Mixin(WorldGenRegion.class)
public class ChunkRegion_scarpetPlopMixin
{
@Inject(method = "markBlockForPostProcessing", at = @At("HEAD"), cancellable = true)
@Inject(method = "markPosForPostprocessing", at = @At("HEAD"), cancellable = true)
private void markOrNot(BlockPos blockPos, CallbackInfo ci)
{
if (CarpetSettings.skipGenerationChecks.get()) ci.cancel();
@@ -1,26 +1,25 @@
package carpet.mixins;
import java.util.Set;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.DistanceManager;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import carpet.fakes.ChunkTicketManagerInterface;
import net.minecraft.server.world.ChunkHolder;
import net.minecraft.server.world.ChunkTicketManager;
@Mixin(ChunkTicketManager.class)
@Mixin(DistanceManager.class)
public abstract class ChunkTicketManager_scarpetChunkCreationMixin implements ChunkTicketManagerInterface
{
@Shadow
@Final
private Set<ChunkHolder> chunkHolders;
private Set<ChunkHolder> chunksToUpdateFutures;
@Override
public void replaceHolder(final ChunkHolder oldHolder, final ChunkHolder newHolder)
{
this.chunkHolders.remove(oldHolder);
this.chunkHolders.add(newHolder);
this.chunksToUpdateFutures.remove(oldHolder);
this.chunksToUpdateFutures.add(newHolder);
}
}
@@ -2,22 +2,22 @@ package carpet.mixins;
import carpet.fakes.ChunkTicketManagerInterface;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.server.world.ChunkTicket;
import net.minecraft.server.world.ChunkTicketManager;
import net.minecraft.util.collection.SortedArraySet;
import net.minecraft.server.level.DistanceManager;
import net.minecraft.server.level.Ticket;
import net.minecraft.util.SortedArraySet;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(ChunkTicketManager.class)
@Mixin(DistanceManager.class)
public abstract class ChunkTicketManager_scarpetMixin implements ChunkTicketManagerInterface
{
@Shadow @Final private Long2ObjectOpenHashMap<SortedArraySet<ChunkTicket<?>>> ticketsByPosition;
@Shadow @Final private Long2ObjectOpenHashMap<SortedArraySet<Ticket<?>>> tickets;
@Override
public Long2ObjectOpenHashMap<SortedArraySet<ChunkTicket<?>>> getTicketsByPosition()
public Long2ObjectOpenHashMap<SortedArraySet<Ticket<?>>> getTicketsByPosition()
{
return ticketsByPosition;
return tickets;
}
}
@@ -2,40 +2,40 @@ package carpet.mixins;
import carpet.fakes.ChunkTicketManagerInterface;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.server.world.ChunkTicket;
import net.minecraft.server.world.ChunkTicketManager;
import net.minecraft.server.world.ChunkTicketType;
import net.minecraft.util.collection.SortedArraySet;
import net.minecraft.server.level.DistanceManager;
import net.minecraft.server.level.Ticket;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.SortedArraySet;
import net.minecraft.util.Unit;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.level.ChunkPos;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.Iterator;
@Mixin(ChunkTicketManager.class)
@Mixin(DistanceManager.class)
public abstract class ChunkTicketManager_spawnChunksMixin implements ChunkTicketManagerInterface
{
@Shadow @Final private Long2ObjectOpenHashMap<SortedArraySet<ChunkTicket<?>>> ticketsByPosition;
@Shadow @Final private Long2ObjectOpenHashMap<SortedArraySet<Ticket<?>>> tickets;
@Shadow protected abstract void removeTicket(long pos, ChunkTicket<?> ticket);
@Shadow protected abstract void removeTicket(long pos, Ticket<?> ticket);
@Shadow public abstract <T> void addTicket(ChunkTicketType<T> type, ChunkPos pos, int radius, T argument);
@Shadow public abstract <T> void addRegionTicket(TicketType<T> type, ChunkPos pos, int radius, T argument);
@Override
public void changeSpawnChunks(ChunkPos chunkPos, int distance)
{
long pos = chunkPos.toLong();
SortedArraySet<ChunkTicket<?>> set = ticketsByPosition.get(pos);
ChunkTicket existingTicket = null;
SortedArraySet<Ticket<?>> set = tickets.get(pos);
Ticket existingTicket = null;
if (set != null)
{
Iterator<ChunkTicket<?>> iter = set.iterator();
Iterator<Ticket<?>> iter = set.iterator();
while(iter.hasNext())
{
ChunkTicket ticket = iter.next();
if (ticket.getType() == ChunkTicketType.START)
Ticket ticket = iter.next();
if (ticket.getType() == TicketType.START)
{
existingTicket = ticket;
iter.remove();
@@ -50,6 +50,6 @@ public abstract class ChunkTicketManager_spawnChunksMixin implements ChunkTicket
}
// set optionally new spawn ticket
if (distance > 0)
addTicket(ChunkTicketType.START, chunkPos, distance, Unit.INSTANCE);
addRegionTicket(TicketType.START, chunkPos, distance, Unit.INSTANCE);
}
}
@@ -1,23 +1,23 @@
package carpet.mixins;
import carpet.helpers.TickSpeed;
import net.minecraft.server.world.ChunkTicketManager;
import net.minecraft.server.level.DistanceManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ChunkTicketManager.class)
@Mixin(DistanceManager.class)
public class ChunkTicketManager_tickMixin
{
@Shadow private long age;
@Shadow private long ticketTickCounter;
@Inject(method = "purge", at = @At("HEAD"), cancellable = true)
@Inject(method = "purgeStaleTickets", at = @At("HEAD"), cancellable = true)
private void pauseTicketSystem(CallbackInfo ci)
{
// pausing expiry of tickets
// that will prevent also chunks from unloading, so require a deep frozen state
if (!TickSpeed.process_entities && TickSpeed.deeplyFrozen()) age--;
if (!TickSpeed.process_entities && TickSpeed.deeplyFrozen()) ticketTickCounter--;
}
}
@@ -6,15 +6,15 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.Packet;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.Packet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientConnection.class)
@Mixin(Connection.class)
public abstract class ClientConnectionMixin implements ClientConnectionInterface
{
// Add to the packet counter whenever a packet is received.
@@ -25,7 +25,7 @@ public abstract class ClientConnectionMixin implements ClientConnectionInterface
}
// Add to the packet counter whenever a packet is sent.
@Inject(method = "sendImmediately", at = @At("HEAD"))
@Inject(method = "sendPacket", at = @At("HEAD"))
private void packetOutCount(Packet<?> packet_1,
GenericFutureListener<? extends Future<? super Void>> genericFutureListener_1, CallbackInfo ci)
{
@@ -2,40 +2,40 @@ package carpet.mixins;
import carpet.network.CarpetClient;
import carpet.network.ClientNetworkHandler;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket;
import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket;
import net.minecraft.text.Text;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket;
import net.minecraft.network.protocol.game.ClientboundLoginPacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientPlayNetworkHandler.class)
@Mixin(ClientPacketListener.class)
public abstract class ClientPlayNetworkHandlerMixin
{
@Shadow private MinecraftClient client;
@Shadow private Minecraft minecraft;
@Inject(method = "onCustomPayload", at = @At("HEAD"), cancellable = true)
private void onOnCustomPayload(CustomPayloadS2CPacket packet, CallbackInfo ci)
@Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true)
private void onOnCustomPayload(ClientboundCustomPayloadPacket packet, CallbackInfo ci)
{
if (CarpetClient.CARPET_CHANNEL.equals(packet.getChannel()))
if (CarpetClient.CARPET_CHANNEL.equals(packet.getIdentifier()))
{
ClientNetworkHandler.handleData(packet.getData(), client.player);
ClientNetworkHandler.handleData(packet.getData(), minecraft.player);
ci.cancel();
}
}
@Inject(method = "onGameJoin", at = @At("RETURN"))
private void onGameJoined(GameJoinS2CPacket packet, CallbackInfo info)
@Inject(method = "handleLogin", at = @At("RETURN"))
private void onGameJoined(ClientboundLoginPacket packet, CallbackInfo info)
{
CarpetClient.gameJoined(client.player);
CarpetClient.gameJoined(minecraft.player);
}
@Inject(method = "onDisconnected", at = @At("HEAD"))
private void onCMDisconnected(Text reason, CallbackInfo ci)
@Inject(method = "onDisconnect", at = @At("HEAD"))
private void onCMDisconnected(Component reason, CallbackInfo ci)
{
CarpetClient.disconnect();
}
@@ -3,16 +3,16 @@ package carpet.mixins;
import carpet.CarpetServer;
import carpet.network.CarpetClient;
import carpet.settings.SettingsManager;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.player.LocalPlayer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientPlayerEntity.class)
@Mixin(LocalPlayer.class)
public class ClientPlayerEntity_clientCommandMixin
{
@Inject(method = "sendChatMessage", at = @At("HEAD"))
@Inject(method = "chat", at = @At("HEAD"))
private void inspectMessage(String string, CallbackInfo ci)
{
if (string.startsWith("/call "))
@@ -22,11 +22,11 @@ public class ClientPlayerEntity_clientCommandMixin
}
if (CarpetServer.minecraft_server == null && !CarpetClient.isCarpet())
{
ClientPlayerEntity playerSource = (ClientPlayerEntity)(Object) this;
CarpetServer.settingsManager.inspectClientsideCommand(playerSource.getCommandSource(), string);
LocalPlayer playerSource = (LocalPlayer)(Object) this;
CarpetServer.settingsManager.inspectClientsideCommand(playerSource.createCommandSourceStack(), string);
CarpetServer.extensions.forEach(e -> {
SettingsManager sm = e.customSettingsManager();
if (sm != null) sm.inspectClientsideCommand(playerSource.getCommandSource(), string);
if (sm != null) sm.inspectClientsideCommand(playerSource.createCommandSourceStack(), string);
});
}
}
@@ -1,10 +1,10 @@
package carpet.mixins;
import carpet.CarpetSettings;
import net.minecraft.block.Block;
import net.minecraft.server.command.CloneCommand;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.core.BlockPos;
import net.minecraft.server.commands.CloneCommands;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Constant;
@@ -12,20 +12,20 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(CloneCommand.class)
@Mixin(CloneCommands.class)
public abstract class CloneCommandMixin
{
@ModifyConstant(method = "execute", constant = @Constant(intValue = 32768))
@ModifyConstant(method = "clone", constant = @Constant(intValue = 32768))
private static int fillLimit(int original) {
return CarpetSettings.fillLimit;
}
@Redirect(method = "execute", at = @At(
@Redirect(method = "clone", at = @At(
value = "INVOKE",
target = "Lnet/minecraft/server/world/ServerWorld;updateNeighbors(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V"
target = "Lnet/minecraft/server/level/ServerLevel;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V"
))
private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1)
private static void conditionalUpdating(ServerLevel serverWorld, BlockPos blockPos_1, Block block_1)
{
if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1);
if (CarpetSettings.fillUpdates) serverWorld.blockUpdated(blockPos_1, block_1);
}
}
@@ -2,13 +2,13 @@ package carpet.mixins;
import carpet.helpers.TickSpeed;
import carpet.utils.CarpetProfiler;
import net.minecraft.server.function.CommandFunctionManager;
import net.minecraft.server.ServerFunctionManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(CommandFunctionManager.class)
@Mixin(ServerFunctionManager.class)
public class CommandFunctionManager_tickMixin
{
CarpetProfiler.ProfilerToken currentSection;
@@ -3,8 +3,8 @@ package carpet.mixins;
import carpet.CarpetServer;
import carpet.CarpetSettings;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import org.slf4j.Logger;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
@@ -16,35 +16,35 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(CommandManager.class)
@Mixin(Commands.class)
public abstract class CommandManagerMixin
{
@Shadow
@Final
private CommandDispatcher<ServerCommandSource> dispatcher;
private CommandDispatcher<CommandSourceStack> dispatcher;
@Inject(method = "<init>", at = @At("RETURN"))
private void onRegister(CommandManager.RegistrationEnvironment arg, CallbackInfo ci) {
private void onRegister(Commands.CommandSelection arg, CallbackInfo ci) {
CarpetServer.registerCarpetCommands(this.dispatcher);
CarpetServer.registerCarpetCommands(this.dispatcher, arg);
}
@Inject(method = "execute", at = @At("HEAD"))
private void onExecuteBegin(ServerCommandSource serverCommandSource_1, String string_1, CallbackInfoReturnable<Integer> cir)
@Inject(method = "performCommand", at = @At("HEAD"))
private void onExecuteBegin(CommandSourceStack serverCommandSource_1, String string_1, CallbackInfoReturnable<Integer> cir)
{
if (!CarpetSettings.fillUpdates)
CarpetSettings.impendingFillSkipUpdates.set(true);
}
@Inject(method = "execute", at = @At("RETURN"))
private void onExecuteEnd(ServerCommandSource serverCommandSource_1, String string_1, CallbackInfoReturnable<Integer> cir)
@Inject(method = "performCommand", at = @At("RETURN"))
private void onExecuteEnd(CommandSourceStack serverCommandSource_1, String string_1, CallbackInfoReturnable<Integer> cir)
{
CarpetSettings.impendingFillSkipUpdates.set(false);
}
@SuppressWarnings("UnresolvedMixinReference")
@Redirect(method = "execute", at = @At(
@Redirect(method = "performCommand", at = @At(
value = "INVOKE",
target = "Lorg/slf4j/Logger;isDebugEnabled()Z"
),
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff. Show more