diff --git a/build.gradle b/build.gradle index dbc2d6b4..74ed523b 100644 --- a/build.gradle +++ b/build.gradle @@ -3,8 +3,8 @@ plugins { id 'maven-publish' } -sourceCompatibility = JavaVersion.VERSION_1_8 -targetCompatibility = JavaVersion.VERSION_1_8 +sourceCompatibility = JavaVersion.VERSION_16 +targetCompatibility = JavaVersion.VERSION_16 archivesBaseName = project.archives_base_name version = project.minecraft_version+'-'+project.mod_version+'+v'+new Date().format('yyMMdd') @@ -44,16 +44,8 @@ tasks.withType(JavaCompile).configureEach { // If Javadoc is generated, this must be specified in that task too. it.options.encoding = "UTF-8" - // The Minecraft launcher currently installs Java 8 for users, so your mod probably wants to target Java 8 too - // JDK 9 introduced a new way of specifying this that will make sure no newer classes or methods are used. - // We'll use that if it's available, but otherwise we'll use the older option. - def targetVersion = 8 - if (JavaVersion.current().isJava9Compatible()) { - it.options.release = targetVersion - } - // Minecraft 1.17 (21w19a) upwards uses Java 16. - //it.options.release = 16 + it.options.release = 16 } java { diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index d913eca2..4b63e097 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -470,7 +470,14 @@ Boolean function, true if the block at position blocks movement. Returns the name of sound type made by the block at position. One of: `'wood'`, `'gravel'`, `'grass'`, `'stone'`, `'metal'`, `'glass'`, `'wool'`, `'sand'`, `'snow'`, -`'ladder'`, `'anvil'`, `'slime'`, `'sea_grass'`, `'coral'` +`'ladder'`, `'anvil'`, `'slime'`, `'sea_grass'`, `'coral'`, `'bamboo'`', `'shoots'`', `'scaffolding'`', `'berry'`', `'crop'`', +`'stem'`', `'wart'`', +`'lantern'`', `'fungi_stem'`', `'nylium'`', `'fungus'`', `'roots'`', `'shroomlight'`', `'weeping_vines'`', `'soul_sand'`', + `'soul_soil'`', `'basalt'`', +`'wart'`', `'netherrack'`', `'nether_bricks'`', `'nether_sprouts'`', `'nether_ore'`', `'bone'`', `'netherite'`', `'ancient_debris'`', +`'lodestone'`', `'chain'`', `'nether_gold_ore'`', `'gilded_blackstone'`', +`'candle'`', `'amethyst'`', `'amethyst_cluster'`', `'small_amethyst_bud'`', `'large_amethyst_bud'`', `'medium_amethyst_bud'`', +`'tuff'`', `'calcite'`', `'copper'`' ### `material(pos)` @@ -480,7 +487,7 @@ Returns the name of material of the block at position. very useful to target a g `'bubble_column'`, `'lava'`, `'snow_layer'`, `'fire'`, `'redstone_bits'`, `'cobweb'`, `'redstone_lamp'`, `'clay'`, `'dirt'`, `'grass'`, `'packed_ice'`, `'sand'`, `'sponge'`, `'wood'`, `'wool'`, `'tnt'`, `'leaves'`, `'glass'`, `'ice'`, `'cactus'`, `'stone'`, `'iron'`, `'snow'`, `'anvil'`, `'barrier'`, `'piston'`, `'coral'`, `'gourd'`, -`'dragon_egg'`, `'cake'` +`'dragon_egg'`, `'cake'`, `'amethyst'` ### `map_colour(pos)` @@ -492,7 +499,8 @@ Returns the map colour of a block at position. One of: '`, `'diamond'`, `'lapis'`, `'emerald'`, `'obsidian'`, `'netherrack'`, `'white_terracotta'`, `'orange_terracotta'`, `'magenta_terracotta'`, `'light_blue_terracotta'`, `'yellow_terracotta'`, `'lime_terracotta'`, `'pink_terracotta'`, `'gray_terracotta'`, `'light_gray_terracotta'`, `'cyan_terracotta'`, `'purple_terracotta'`, `'blue_terracotta'`, -`'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'` +`'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`, +`'crimson_nylium'`, `'crimson_stem'`, `'crimson_hyphae'`, `'warped_nylium'`, `'warped_stem'`, `'warped_hyphae'`, `'warped_wart'` ### `loaded(pos)` diff --git a/gradle.properties b/gradle.properties index acdae237..a8223766 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,10 +4,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://fabricmc.net/use # or better: https://modmuss50.me/fabric.html - minecraft_version=1.16.5 - yarn_mappings=1.16.5+build.1 - loader_version=0.11.1 - fabric_version=0.29.4+1.16 + minecraft_version=1.17.1 + yarn_mappings=1.17.1+build.1 + loader_version=0.11.6 + fabric_version=0.36.1+1.17 # Mod Properties mod_version = 1.4.44 diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 276b9e8a..88fb81de 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -32,8 +32,10 @@ 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.server.MinecraftServer; +import net.minecraft.server.dedicated.command.PerfCommand; import net.minecraft.server.network.ServerPlayerEntity; public class CarpetServer // static for now - easier to handle all around the code, its one anyways @@ -113,7 +115,11 @@ public class CarpetServer // static for now - easier to handle all around the co extensions.forEach(e -> e.onTick(server)); } - public static void registerCarpetCommands(CommandDispatcher dispatcher) + @Deprecated + public static void registerCarpetCommands(CommandDispatcher dispatcher) { + } + + public static void registerCarpetCommands(CommandDispatcher dispatcher, CommandManager.RegistrationEnvironment environment) { settingsManager.registerCommand(dispatcher); extensions.forEach(e -> { @@ -137,6 +143,9 @@ public class CarpetServer // static for now - easier to handle all around the co // for all other, they will have them registered when they add themselves extensions.forEach(e -> e.registerCommands(dispatcher)); currentCommandDispatcher = dispatcher; + + if (environment != CommandManager.RegistrationEnvironment.DEDICATED) + PerfCommand.register(dispatcher); if (FabricLoader.getInstance().isDevelopmentEnvironment()) TestCommand.register(dispatcher); diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 7974d61b..bb463007 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -186,15 +186,17 @@ public class CarpetSettings @Rule( desc = "Players absorb XP instantly, without delay", category = CREATIVE ) public static boolean xpNoCooldown = false; + @Rule( desc = "XP orbs combine with other into bigger orbs", category = FEATURE ) public static boolean combineXPOrbs = false; @Rule( desc = "Empty shulker boxes can stack to 64 when dropped on the ground", - extra = "To move them around between inventories, use shift click to move entire stacks", + extra = ".. or when manipulated inside the inventories", category = {SURVIVAL, FEATURE} ) public static boolean stackableShulkerBoxes = false; + public static final int SHULKER_STACK_SIZE = 64; @Rule( desc = "Explosions won't destroy blocks", category = {CREATIVE, TNT} ) public static boolean explosionNoBlockDamage = false; @@ -316,6 +318,16 @@ public class CarpetSettings ) public static boolean hopperCounters = false; + @Rule( + desc = "Allows Budding Amethyst blocks to be moved", + extra = { + "Allow for them to be moved by pistons", + "as well as adds extra drop when mining with silk touch pickaxe" + }, + category = FEATURE + ) + public static boolean movableAmethyst = false; + @Rule( desc = "Guardians turn into Elder Guardian when struck by lightning", category = FEATURE ) public static boolean renewableSponges = false; @@ -366,6 +378,13 @@ public class CarpetSettings ) public static String commandProfile = "true"; + @Rule( + desc = "Required permission level for /perf command", + options = {"2", "4"}, + category = CREATIVE + ) + public static int perfPermissionLevel = 4; + @Rule(desc = "Enables /log command to monitor events via chat and overlays", category = COMMAND) public static String commandLog = "true"; @@ -588,8 +607,8 @@ public class CarpetSettings public static boolean waterFlow = true; */ - @Rule(desc = "One player is required on the server to cause night to pass", category = SURVIVAL) - public static boolean onePlayerSleeping = false; + //@Rule(desc = "One player is required on the server to cause night to pass", category = SURVIVAL) + //public static boolean onePlayerSleeping = false; @Rule( desc = "Sets a different motd message on client trying to connect to the server", @@ -620,7 +639,7 @@ public class CarpetSettings Messenger.m(source, "r view distance has to be between 0 and 32"); return null; } - MinecraftServer server = source.getMinecraftServer(); + MinecraftServer server = source.getServer(); if (server.isDedicated()) { @@ -754,6 +773,13 @@ public class CarpetSettings ) public static boolean renewableBlackstone = false; + @Rule( + desc = "Lava and water generate deepslate and cobbled deepslate instead below Y16", + extra = "This rule may change Y value to 0 with 1.18", + category = FEATURE + ) + public static boolean renewableDeepslate = false; + @Rule(desc = "fixes block placement rotation issue when player rotates quickly while placing blocks", category = BUGFIX) public static boolean placementRotationFix = false; @@ -810,7 +836,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).abilities.flying; + return CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying; } @@ -909,7 +935,7 @@ public class CarpetSettings strict = false, validate = Validator.NONNEGATIVE_NUMBER.class ) - public static double structureBlockOutlineDistance = 96d; + public static int structureBlockOutlineDistance = 96; @Rule( desc = "Lightning kills the items that drop when lightning kills an entity", diff --git a/src/main/java/carpet/commands/CounterCommand.java b/src/main/java/carpet/commands/CounterCommand.java index 973bfa01..484a7b4d 100644 --- a/src/main/java/carpet/commands/CounterCommand.java +++ b/src/main/java/carpet/commands/CounterCommand.java @@ -56,7 +56,7 @@ public class CounterCommand HopperCounter counter = HopperCounter.getCounter(color); if (counter == null) throw new CommandException(Messenger.s("Unknown wool color: "+color)); - for (BaseText message: counter.format(source.getMinecraftServer(), realtime, false)) + for (BaseText message: counter.format(source.getServer(), realtime, false)) { source.sendFeedback(message, false); } @@ -72,14 +72,14 @@ public class CounterCommand { if (color == null) { - HopperCounter.resetAll(source.getMinecraftServer(), false); + HopperCounter.resetAll(source.getServer(), false); Messenger.m(source, "w Restarted all counters"); } else { HopperCounter counter = HopperCounter.getCounter(color); if (counter == null) throw new CommandException(Messenger.s("Unknown wool color")); - counter.reset(source.getMinecraftServer()); + counter.reset(source.getServer()); Messenger.m(source, "w Restarted "+color+" counter"); } return 1; @@ -92,7 +92,7 @@ public class CounterCommand */ private static int listAllCounters(ServerCommandSource source, boolean realtime) { - for (BaseText message: HopperCounter.formatAll(source.getMinecraftServer(), realtime)) + for (BaseText message: HopperCounter.formatAll(source.getServer(), realtime)) { source.sendFeedback(message, false); } diff --git a/src/main/java/carpet/commands/LogCommand.java b/src/main/java/carpet/commands/LogCommand.java index e347885b..d7400183 100644 --- a/src/main/java/carpet/commands/LogCommand.java +++ b/src/main/java/carpet/commands/LogCommand.java @@ -133,7 +133,7 @@ public class LogCommand } private static int unsubFromAll(ServerCommandSource source, String player_name) { - PlayerEntity player = source.getMinecraftServer().getPlayerManager().getPlayer(player_name); + PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); if (player == null) { Messenger.m(source, "r No player specified"); @@ -148,7 +148,7 @@ public class LogCommand } private static int unsubFromLogger(ServerCommandSource source, String player_name, String logname) { - PlayerEntity player = source.getMinecraftServer().getPlayerManager().getPlayer(player_name); + PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); if (player == null) { Messenger.m(source, "r No player specified"); @@ -166,7 +166,7 @@ public class LogCommand private static int toggleSubscription(ServerCommandSource source, String player_name, String logName) { - PlayerEntity player = source.getMinecraftServer().getPlayerManager().getPlayer(player_name); + PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); if (player == null) { Messenger.m(source, "r No player specified"); @@ -190,7 +190,7 @@ public class LogCommand } private static int subscribePlayer(ServerCommandSource source, String player_name, String logname, String option) { - PlayerEntity player = source.getMinecraftServer().getPlayerManager().getPlayer(player_name); + PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); if (player == null) { Messenger.m(source, "r No player specified"); diff --git a/src/main/java/carpet/commands/PerimeterInfoCommand.java b/src/main/java/carpet/commands/PerimeterInfoCommand.java index 975ac231..d700dd3b 100644 --- a/src/main/java/carpet/commands/PerimeterInfoCommand.java +++ b/src/main/java/carpet/commands/PerimeterInfoCommand.java @@ -13,7 +13,7 @@ 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.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.util.math.BlockPos; import static net.minecraft.server.command.CommandManager.argument; @@ -46,19 +46,19 @@ public class PerimeterInfoCommand private static int perimeterDiagnose(ServerCommandSource source, BlockPos pos, String mobId) { - CompoundTag nbttagcompound = new CompoundTag(); + NbtCompound nbttagcompound = new NbtCompound(); MobEntity 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(), -10, pos.getZ()), entity_1x.yaw, entity_1x.pitch); + entity_1x.refreshPositionAndAngles(new BlockPos(pos.getX(), -10, pos.getZ()), entity_1x.getYaw(), entity_1x. getPitch()); return !source.getWorld().tryLoadEntity(entity_1x) ? null : entity_1x; }); if (!(baseEntity instanceof MobEntity)) { Messenger.m(source, "r /perimeterinfo requires a mob entity to test agains."); - if (baseEntity != null) baseEntity.remove(); + if (baseEntity != null) baseEntity.discard(); return 0; } entityliving = (MobEntity) baseEntity; @@ -72,7 +72,7 @@ public class PerimeterInfoCommand { Messenger.m(source, "w ", entityliving.getDisplayName() ,"w : ","wb "+res.specific); res.samples.forEach(bp -> Messenger.m(source, "w ", Messenger.tp("c", bp))); - entityliving.remove(); + entityliving.discard(); // dicard // remove(); } return 1; } diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index 1ca9b264..b849276b 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -136,7 +136,7 @@ public class PlayerCommand private static ServerPlayerEntity getPlayer(CommandContext context) { String playerName = StringArgumentType.getString(context, "player"); - MinecraftServer server = context.getSource().getMinecraftServer(); + MinecraftServer server = context.getSource().getServer(); return server.getPlayerManager().getPlayer(playerName); } @@ -158,7 +158,7 @@ public class PlayerCommand return false; } - if (!context.getSource().getMinecraftServer().getPlayerManager().isOperator(sendingPlayer.getGameProfile())) + if (!context.getSource().getServer().getPlayerManager().isOperator(sendingPlayer.getGameProfile())) { if (sendingPlayer != player && !(player instanceof EntityPlayerMPFake)) { @@ -181,7 +181,7 @@ public class PlayerCommand private static boolean cantSpawn(CommandContext context) { String playerName = StringArgumentType.getString(context, "player"); - MinecraftServer server = context.getSource().getMinecraftServer(); + MinecraftServer server = context.getSource().getServer(); PlayerManager manager = server.getPlayerManager(); PlayerEntity player = manager.getPlayer(playerName); if (player != null) @@ -189,7 +189,7 @@ public class PlayerCommand Messenger.m(context.getSource(), "r Player ", "rb " + playerName, "r is already logged on"); return true; } - GameProfile profile = server.getUserCache().findByName(playerName); + GameProfile profile = server.getUserCache().findByName(playerName).orElse(null); if (profile == null) { if (!CarpetSettings.allowSpawningOfflinePlayers) @@ -224,9 +224,9 @@ public class PlayerCommand private static int lookAt(CommandContext context) { return manipulate(context, ap -> { - try { + //try { ap.lookAt(Vec3ArgumentType.getVec3(context, "position")); - } catch (CommandSyntaxException ignored) {} + //} catch (CommandSyntaxException ignored) {} }); } @@ -270,18 +270,18 @@ public class PlayerCommand { ServerPlayerEntity player = context.getSource().getPlayer(); mode = player.interactionManager.getGameMode(); - flying = player.abilities.flying; + flying = player.getAbilities().flying; } catch (CommandSyntaxException ignored) {} String playerName = StringArgumentType.getString(context, "player"); - if (playerName.length()>maxPlayerLength(source.getMinecraftServer())) + if (playerName.length()>maxPlayerLength(source.getServer())) { Messenger.m(context.getSource(), "rb Player name: "+playerName+" is too long"); return 0; } - MinecraftServer server = source.getMinecraftServer(); - if (!World.isInBuildLimit(new BlockPos(pos.x, pos.y, pos.z))) + MinecraftServer server = source.getServer(); + if (!World.isValid(new BlockPos(pos.x, pos.y, pos.z))) { Messenger.m(context.getSource(), "rb Player "+playerName+" cannot be placed outside of the world"); return 0; diff --git a/src/main/java/carpet/commands/ScriptCommand.java b/src/main/java/carpet/commands/ScriptCommand.java index 8b1c6c0c..4b867655 100644 --- a/src/main/java/carpet/commands/ScriptCommand.java +++ b/src/main/java/carpet/commands/ScriptCommand.java @@ -512,9 +512,9 @@ public class ScriptCommand { ServerCommandSource source = context.getSource(); CarpetScriptHost host = getHost(context); - BlockBox area = new BlockBox(a, b); + BlockBox area = BlockBox.create(a, b); CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); + int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); // 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.minX; x <= area.maxX; x++) + for (int x = area.getMinX(); x <= area.getMaxX(); x++) { - for (int y = area.minY; y <= area.maxY; y++) + for (int y = area.getMinY(); y <= area.getMaxY(); y++) { - for (int z = area.minZ; z <= area.maxZ; z++) + for (int z = area.getMinZ(); z <= area.getMaxZ(); z++) { try { @@ -561,7 +561,7 @@ public class ScriptCommand { ServerCommandSource source = context.getSource(); CarpetScriptHost host = getHost(context); - BlockBox area = new BlockBox(a, b); + BlockBox area = BlockBox.create(a, b); CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); if (int_1 > CarpetSettings.fillLimit) @@ -570,22 +570,22 @@ public class ScriptCommand return 1; } - boolean[][][] volume = new boolean[area.getBlockCountX()][area.getBlockCountY()][area.getBlockCountZ()]; + boolean[][][] volume = new boolean[area.getBlockCountX()][area.getBlockCountY()][area.getBlockCountZ()]; //X then Y then Z got messedup BlockPos.Mutable mbpos = origin.mutableCopy(); ServerWorld world = source.getWorld(); - for (int x = area.minX; x <= area.maxX; x++) + for (int x = area.getMinX(); x <= area.getMaxX(); x++) { - for (int y = area.minY; y <= area.maxY; y++) + for (int y = area.getMinY(); y <= area.getMaxY(); y++) { - for (int z = area.minZ; z <= area.maxZ; z++) + for (int z = area.getMinZ(); z <= area.getMaxZ(); z++) { try { if (cexpr.fillAndScanCommand(host, x, y, z)) { - volume[x-area.minX][y-area.minY][z-area.minZ]=true; + volume[x-area.getMinX()][y-area.getMinY()][z-area.getMinZ()]=true; } } catch (CarpetExpressionException e) @@ -640,7 +640,7 @@ public class ScriptCommand { if (volume[x][y][z]) { - mbpos.set(x+area.minX, y+area.minY, z+area.minZ); + mbpos.set(x+area.getMinX(), y+area.getMinY(), z+area.getMinZ()); if (replacement == null || replacement.test( new CachedBlockPosition( world, mbpos, true))) { @@ -668,7 +668,7 @@ public class ScriptCommand { if (volume[x][y][z]) { - mbpos.set(x+area.minX, y+area.minY, z+area.minZ); + mbpos.set(x+area.getMinX(), y+area.getMinY(), z+area.getMinZ()); Block blokc = world.getBlockState(mbpos).getBlock(); world.updateNeighbors(mbpos, blokc); } diff --git a/src/main/java/carpet/commands/SpawnCommand.java b/src/main/java/carpet/commands/SpawnCommand.java index 5d1e075e..1f9010d4 100644 --- a/src/main/java/carpet/commands/SpawnCommand.java +++ b/src/main/java/carpet/commands/SpawnCommand.java @@ -146,8 +146,8 @@ public class SpawnCommand Math.max(a.getY(), b.getY()), Math.max(a.getZ(), b.getZ()) ); } - SpawnReporter.reset_spawn_stats(source.getMinecraftServer(), false); - SpawnReporter.track_spawns = (long) source.getMinecraftServer().getTicks(); + SpawnReporter.reset_spawn_stats(source.getServer(), false); + SpawnReporter.track_spawns = (long) source.getServer().getTicks(); SpawnReporter.lower_spawning_limit = lsl; SpawnReporter.upper_spawning_limit = usl; Messenger.m(source, "gi Spawning tracking started."); @@ -157,7 +157,7 @@ public class SpawnCommand private static int stopTracking(ServerCommandSource source) { Messenger.send(source, SpawnReporter.tracking_report(source.getWorld())); - SpawnReporter.reset_spawn_stats(source.getMinecraftServer(),false); + SpawnReporter.reset_spawn_stats(source.getServer(),false); SpawnReporter.track_spawns = 0L; SpawnReporter.lower_spawning_limit = null; SpawnReporter.upper_spawning_limit = null; @@ -175,19 +175,19 @@ public class SpawnCommand private static int runTest(ServerCommandSource source, int ticks, String counter) { //stop tracking - SpawnReporter.reset_spawn_stats(source.getMinecraftServer(),false); + SpawnReporter.reset_spawn_stats(source.getServer(),false); //start tracking - SpawnReporter.track_spawns = (long) source.getMinecraftServer().getTicks(); + SpawnReporter.track_spawns = (long) source.getServer().getTicks(); //counter reset if (counter == null) { - HopperCounter.resetAll(source.getMinecraftServer(), false); + HopperCounter.resetAll(source.getServer(), false); } else { HopperCounter hCounter = HopperCounter.getCounter(counter); if (hCounter != null) - hCounter.reset(source.getMinecraftServer()); + hCounter.reset(source.getServer()); } diff --git a/src/main/java/carpet/fakes/BlockEntityInterface.java b/src/main/java/carpet/fakes/BlockEntityInterface.java new file mode 100644 index 00000000..ca734897 --- /dev/null +++ b/src/main/java/carpet/fakes/BlockEntityInterface.java @@ -0,0 +1,8 @@ +package carpet.fakes; + +import net.minecraft.util.math.BlockPos; + +public interface BlockEntityInterface +{ + void setCMPos(BlockPos pos); +} diff --git a/src/main/java/carpet/fakes/BlockPredicateInterface.java b/src/main/java/carpet/fakes/BlockPredicateInterface.java index cd1e4349..c8d3e32b 100644 --- a/src/main/java/carpet/fakes/BlockPredicateInterface.java +++ b/src/main/java/carpet/fakes/BlockPredicateInterface.java @@ -3,7 +3,7 @@ package carpet.fakes; import carpet.script.value.Value; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.tag.Tag; import java.util.Map; @@ -13,5 +13,5 @@ public interface BlockPredicateInterface BlockState getCMBlockState(); Tag getCMBlockTag(); Map getCMProperties(); - CompoundTag getCMDataTag(); + NbtCompound getCMDataTag(); } diff --git a/src/main/java/carpet/fakes/BlockStateArgumentInterface.java b/src/main/java/carpet/fakes/BlockStateArgumentInterface.java index 20610ed3..ceda6f03 100644 --- a/src/main/java/carpet/fakes/BlockStateArgumentInterface.java +++ b/src/main/java/carpet/fakes/BlockStateArgumentInterface.java @@ -1,8 +1,8 @@ package carpet.fakes; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; public interface BlockStateArgumentInterface { - CompoundTag getCMTag(); + NbtCompound getCMTag(); } diff --git a/src/main/java/carpet/fakes/ChunkHolderInterface.java b/src/main/java/carpet/fakes/ChunkHolderInterface.java index ae28edc9..7619279d 100644 --- a/src/main/java/carpet/fakes/ChunkHolderInterface.java +++ b/src/main/java/carpet/fakes/ChunkHolderInterface.java @@ -2,6 +2,7 @@ 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; @@ -10,5 +11,5 @@ import java.util.concurrent.CompletableFuture; public interface ChunkHolderInterface { - CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor executor); + CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor executor, ServerWorld world); } diff --git a/src/main/java/carpet/fakes/ExperienceOrbInterface.java b/src/main/java/carpet/fakes/ExperienceOrbInterface.java index 00179d01..f6f0485f 100644 --- a/src/main/java/carpet/fakes/ExperienceOrbInterface.java +++ b/src/main/java/carpet/fakes/ExperienceOrbInterface.java @@ -5,4 +5,6 @@ public interface ExperienceOrbInterface int getCombineDelay(); void setCombineDelay(int what); void setAmount(int what); + int getCount(); + void setCount(int i); } diff --git a/src/main/java/carpet/fakes/InventoryBearerInterface.java b/src/main/java/carpet/fakes/InventoryBearerInterface.java index aa282382..5355786b 100644 --- a/src/main/java/carpet/fakes/InventoryBearerInterface.java +++ b/src/main/java/carpet/fakes/InventoryBearerInterface.java @@ -4,5 +4,5 @@ import net.minecraft.inventory.Inventory; public interface InventoryBearerInterface { - Inventory getCMInventory(); + Inventory getCMInventory(); // can be removed in 1.17 due to class_6067 } diff --git a/src/main/java/carpet/fakes/ServerWorldInterface.java b/src/main/java/carpet/fakes/ServerWorldInterface.java index 67414706..106eb72a 100644 --- a/src/main/java/carpet/fakes/ServerWorldInterface.java +++ b/src/main/java/carpet/fakes/ServerWorldInterface.java @@ -1,7 +1,10 @@ package carpet.fakes; +import net.minecraft.entity.Entity; +import net.minecraft.world.entity.EntityLookup; import net.minecraft.world.level.ServerWorldProperties; public interface ServerWorldInterface { ServerWorldProperties getWorldPropertiesCM(); + EntityLookup getEntityLookupCMPublic(); } diff --git a/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java b/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java new file mode 100644 index 00000000..2802581d --- /dev/null +++ b/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java @@ -0,0 +1,11 @@ +package carpet.fakes; + +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.entity.EntityLike; + +import java.util.List; + +public interface SimpleEntityLookupInterface +{ + List getChunkEntities(ChunkPos chpos); +} diff --git a/src/main/java/carpet/fakes/StructureFeatureInterface.java b/src/main/java/carpet/fakes/StructureFeatureInterface.java index d74f087c..75d34585 100644 --- a/src/main/java/carpet/fakes/StructureFeatureInterface.java +++ b/src/main/java/carpet/fakes/StructureFeatureInterface.java @@ -3,6 +3,7 @@ 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.ChunkRandom; @@ -12,5 +13,5 @@ import net.minecraft.world.gen.feature.FeatureConfig; public interface StructureFeatureInterface { boolean plopAnywhere(ServerWorld world, BlockPos pos, ChunkGenerator generator, boolean wireOnly,Biome biome, FeatureConfig config); - boolean shouldStartPublicAt(ChunkGenerator chunkGenerator, BiomeSource biomeSource, long l, ChunkRandom chunkRandom, int i, int j, Biome biome, ChunkPos chunkPos, C featureConfig); + boolean shouldStartPublicAt(ChunkGenerator chunkGenerator, BiomeSource biomeSource, long l, ChunkRandom chunkRandom, ChunkPos chpos, Biome biome, ChunkPos chunkPos, C featureConfig, HeightLimitView heightLimitView); } diff --git a/src/main/java/carpet/helpers/BlockRotator.java b/src/main/java/carpet/helpers/BlockRotator.java index 543afb33..f2ee22d7 100644 --- a/src/main/java/carpet/helpers/BlockRotator.java +++ b/src/main/java/carpet/helpers/BlockRotator.java @@ -48,8 +48,8 @@ import net.minecraft.world.World; public class BlockRotator { public static boolean flipBlockWithCactus(BlockState state, World world, PlayerEntity player, Hand hand, BlockHitResult hit) - { - if (!player.abilities.allowModifyWorld || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player)) + { //getAbilities() + if (!player.getAbilities().allowModifyWorld || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player)) { return false; } @@ -226,7 +226,7 @@ public class BlockRotator { Direction sourceFace = source.getBlockState().get(DispenserBlock.FACING); World world = source.getWorld(); - BlockPos blockpos = source.getBlockPos().offset(sourceFace); + BlockPos blockpos = source.getPos().offset(sourceFace); // offset BlockState iblockstate = world.getBlockState(blockpos); Block block = iblockstate.getBlock(); @@ -274,7 +274,7 @@ public class BlockRotator } } // Send block update to the block that just have been rotated. - world.updateNeighbor(blockpos, block, source.getBlockPos()); + world.updateNeighbor(blockpos, block, source.getPos()); return stack; } diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 0c1d8253..e722abbd 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -10,7 +10,7 @@ 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.HeldItemChangeS2CPacket; +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; @@ -116,8 +116,8 @@ 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.yaw, -90); - case DOWN: return look(player.yaw, 90); + case UP: return look(player.getYaw(), -90); + case DOWN: return look(player.getYaw(), 90); } return this; } @@ -128,8 +128,8 @@ public class EntityPlayerActionPack public EntityPlayerActionPack look(float yaw, float pitch) { - player.yaw = yaw % 360; - player.pitch = MathHelper.clamp(pitch, -90, 90); + player.setYaw(yaw % 360); //setYaw + player.setPitch(MathHelper.clamp(pitch, -90, 90)); // setPitch // maybe player.setPositionAndAngles(player.x, player.y, player.z, yaw, MathHelper.clamp(pitch,-90.0F, 90.0F)); return this; } @@ -142,7 +142,7 @@ public class EntityPlayerActionPack public EntityPlayerActionPack turn(float yaw, float pitch) { - return look(player.yaw + yaw, player.pitch + pitch); + return look(player.getYaw() + yaw, player.getPitch() + pitch); } public EntityPlayerActionPack turn(Vec2f rotation) @@ -254,7 +254,7 @@ public class EntityPlayerActionPack private void dropItemFromSlot(int slot, boolean dropAll) { - PlayerInventory inv = player.inventory; + PlayerInventory inv = player.getInventory(); // getInventory; if (!inv.getStack(slot).isEmpty()) player.dropItem(inv.removeStack(slot, dropAll ? inv.getStack(slot).getCount() : 1 @@ -263,7 +263,7 @@ public class EntityPlayerActionPack public void drop(int selectedSlot, boolean dropAll) { - PlayerInventory inv = player.inventory; + PlayerInventory inv = player.getInventory(); // getInventory; if (selectedSlot == -2) // all { for (int i = inv.size(); i >= 0; i--) @@ -279,8 +279,8 @@ public class EntityPlayerActionPack public void setSlot(int slot) { - player.inventory.selectedSlot = slot-1; - player.networkHandler.sendPacket(new HeldItemChangeS2CPacket(slot-1)); + player.getInventory().selectedSlot = slot-1; + player.networkHandler.sendPacket(new UpdateSelectedSlotS2CPacket(slot-1)); } public enum ActionType @@ -312,7 +312,7 @@ public class EntityPlayerActionPack BlockHitResult blockHit = (BlockHitResult) hit; BlockPos pos = blockHit.getBlockPos(); Direction side = blockHit.getSide(); - if (pos.getY() < player.server.getWorldHeight() - (side == Direction.UP ? 1 : 0) && world.canPlayerModifyAt(player, pos)) + if (pos.getY() < player.getServerWorld().getTopY() - (side == Direction.UP ? 1 : 0) && world.canPlayerModifyAt(player, pos)) { ActionResult result = player.interactionManager.interactBlock(player, world, player.getStackInHand(hand), hand, blockHit); if (result.isAccepted()) @@ -400,7 +400,7 @@ public class EntityPlayerActionPack boolean blockBroken = false; if (player.interactionManager.getGameMode().isCreative()) { - player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.server.getWorldHeight()); + player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getServerWorld().getTopY()); ap.blockHitDelay = 5; blockBroken = true; } @@ -408,9 +408,9 @@ public class EntityPlayerActionPack { if (ap.currentBlock != null) { - player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, side, player.server.getWorldHeight()); + player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, side, player.getServerWorld().getTopY()); } - player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.server.getWorldHeight()); + player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getServerWorld().getTopY()); boolean notAir = !state.isAir(); if (notAir && ap.curBlockDamageMP == 0) { @@ -433,7 +433,7 @@ public class EntityPlayerActionPack ap.curBlockDamageMP += state.calcBlockBreakingDelta(player, player.world, pos); if (ap.curBlockDamageMP >= 1) { - player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.server.getWorldHeight()); + player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.getServerWorld().getTopY()); ap.currentBlock = null; ap.blockHitDelay = 5; blockBroken = true; @@ -455,7 +455,7 @@ public class EntityPlayerActionPack 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.server.getWorldHeight()); + player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getServerWorld().getTopY()); ap.currentBlock = null; } }, @@ -487,7 +487,7 @@ public class EntityPlayerActionPack boolean execute(ServerPlayerEntity player, Action action) { player.updateLastActionTime(); - player.dropSelectedItem(false); + player.dropSelectedItem(false); // dropSelectedItem return false; } }, @@ -497,7 +497,7 @@ public class EntityPlayerActionPack boolean execute(ServerPlayerEntity player, Action action) { player.updateLastActionTime(); - player.dropSelectedItem(true); + player.dropSelectedItem(true); // dropSelectedItem return false; } }, diff --git a/src/main/java/carpet/helpers/FeatureGenerator.java b/src/main/java/carpet/helpers/FeatureGenerator.java index c82077a6..05ed8afa 100644 --- a/src/main/java/carpet/helpers/FeatureGenerator.java +++ b/src/main/java/carpet/helpers/FeatureGenerator.java @@ -24,7 +24,7 @@ import net.minecraft.world.biome.source.BiomeAccess; import net.minecraft.world.gen.ChunkRandom; import net.minecraft.world.gen.chunk.ChunkGenerator; import net.minecraft.world.gen.chunk.StructureConfig; -import net.minecraft.world.gen.tree.BeehiveTreeDecorator; +import net.minecraft.world.gen.treedecorator.BeehiveTreeDecorator; import net.minecraft.world.gen.feature.ConfiguredFeature; import net.minecraft.world.gen.feature.ConfiguredFeatures; import net.minecraft.world.gen.feature.ConfiguredStructureFeature; @@ -49,7 +49,7 @@ public class FeatureGenerator return custom.plop(world, pos); } Identifier id = new Identifier(featureName); - ConfiguredStructureFeature structureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_WORLDGEN).get(id); + ConfiguredStructureFeature structureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).get(id); if (structureFeature != null) { return ((StructureFeatureInterface)structureFeature.feature).plopAnywhere( @@ -58,7 +58,7 @@ public class FeatureGenerator } - ConfiguredFeature feature = world.getRegistryManager().get(Registry.CONFIGURED_FEATURE_WORLDGEN).get(id); + ConfiguredFeature feature = world.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY).get(id); if (feature != null) { CarpetSettings.skipGenerationChecks.set(true); @@ -77,7 +77,7 @@ public class FeatureGenerator public static ConfiguredStructureFeature resolveConfiguredStructure(String name, ServerWorld world, BlockPos pos) { Identifier id = new Identifier(name); - ConfiguredStructureFeature configuredStructureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_WORLDGEN).get(id); + ConfiguredStructureFeature configuredStructureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).get(id); if (configuredStructureFeature != null) return configuredStructureFeature; StructureFeature structureFeature = Registry.STRUCTURE_FEATURE.get(id); if (structureFeature == null) return null; @@ -113,7 +113,7 @@ public class FeatureGenerator private static Thing simpleTree(TreeFeatureConfig config) { - config.ignoreFluidCheck(); + //config.ignoreFluidCheck(); return simplePlop(Feature.TREE.configure(config)); } @@ -137,7 +137,7 @@ public class FeatureGenerator { ConfiguredStructureFeature configuredFeature = world.getBiome(pos).getGenerationSettings().method_30978(structure.configure(null)); if (configuredFeature.config != null || !tryHard) return configuredFeature; - return world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_WORLDGEN).getEntries().stream(). + return world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getEntries().stream(). filter(cS -> cS.getValue().feature == structure). findFirst().map(Map.Entry::getValue).orElse(null); } @@ -158,13 +158,15 @@ public class FeatureGenerator ConfiguredStructureFeature configuredFeature = biome.getGenerationSettings().method_30978(structure.configure(null)); if (configuredFeature == null || configuredFeature.config == null) return null; ChunkPos chunkPos2 = structure.getStartChunk(params, seed, chunkRandom, chunkPos.x, chunkPos.z); //find some chunk I guess - if (chunkPos.x == chunkPos2.x && chunkPos.z == chunkPos2.z && ((StructureFeatureInterface)structure).shouldStartPublicAt(generator, generator.getBiomeSource(), seed, chunkRandom, chunkPos.x, chunkPos.z, biome, chunkPos, configuredFeature.config)) // should start at + // using here world for heightview, rather than chunk since we - unlike vanilla, want to avoid creating any chunks even on the + // structure starts level - lets see where would that take us. + if (chunkPos.x == chunkPos2.x && chunkPos.z == chunkPos2.z && ((StructureFeatureInterface)structure).shouldStartPublicAt(generator, generator.getBiomeSource(), seed, chunkRandom, chunkPos, biome, chunkPos, configuredFeature.config, world)) // should start at { if (!computeBox) return StructureStart.DEFAULT; StructureManager manager = world.getStructureManager(); - StructureStart structureStart3 = structure.getStructureStartFactory().create((StructureFeature) configuredFeature.feature, chunkPos.x, chunkPos.z, BlockBox.empty(), 0, seed); + StructureStart structureStart3 = structure.getStructureStartFactory().create((StructureFeature) configuredFeature.feature, chunkPos, 0, seed); synchronized (boo) { - structureStart3.init(world.getRegistryManager(), generator, manager, chunkPos.x, chunkPos.z, biome, (T) configuredFeature.config); + structureStart3.init(world.getRegistryManager(), generator, manager, chunkPos, biome, (T) configuredFeature.config, world); } if (!structureStart3.hasChildren()) return null; return structureStart3; @@ -190,7 +192,7 @@ public class FeatureGenerator new Identifier("bastion/starts"), new Identifier("empty"), ImmutableList.of( - Pair.of(StructurePoolElement.method_30435("bastion/units/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.ofProcessedSingle("bastion/units/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructurePool.Projection.RIGID ), 6), @@ -202,7 +204,7 @@ public class FeatureGenerator new Identifier("bastion/starts"), new Identifier("empty"), ImmutableList.of( - Pair.of(StructurePoolElement.method_30435("bastion/hoglin_stable/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.ofProcessedSingle("bastion/hoglin_stable/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructurePool.Projection.RIGID ), 6), @@ -214,7 +216,7 @@ public class FeatureGenerator new Identifier("bastion/starts"), new Identifier("empty"), ImmutableList.of( - Pair.of(StructurePoolElement.method_30435("bastion/treasure/big_air_full", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.ofProcessedSingle("bastion/treasure/big_air_full", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructurePool.Projection.RIGID ), 6), @@ -226,7 +228,7 @@ public class FeatureGenerator new Identifier("bastion/starts"), new Identifier("empty"), ImmutableList.of( - Pair.of(StructurePoolElement.method_30435("bastion/bridge/starting_pieces/entrance_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.ofProcessedSingle("bastion/bridge/starting_pieces/entrance_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructurePool.Projection.RIGID ), 6), diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java index 9f0626d4..b9421459 100644 --- a/src/main/java/carpet/helpers/HopperCounter.java +++ b/src/main/java/carpet/helpers/HopperCounter.java @@ -12,7 +12,7 @@ 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.MaterialColor; +import net.minecraft.block.MapColor; import net.minecraft.block.Stainable; import net.minecraft.item.BlockItem; import net.minecraft.item.DyeItem; @@ -100,7 +100,7 @@ public class HopperCounter { startTick = -1; this.color = color; - this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMaterialColor(),"w ") + color.getName(); + this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMapColor(),"w ") + color.getName(); } /** @@ -229,7 +229,7 @@ public class HopperCounter */ public static int appropriateColor(int color) { - if (color == 0) return MaterialColor.WHITE.color; + if (color == 0) return MapColor.WHITE.color; int r = (color >> 16 & 255); int g = (color >> 8 & 255); int b = (color & 255); @@ -326,6 +326,8 @@ public class HopperCounter .put(Items.PHANTOM_MEMBRANE,Blocks.BONE_BLOCK) .put(Items.EGG,Blocks.BONE_BLOCK) //.put(Items.,Blocks.) + .put(Items.COPPER_INGOT,Blocks.COPPER_BLOCK) + .put(Items.AMETHYST_SHARD, Blocks.AMETHYST_BLOCK) .build(); /** @@ -333,8 +335,8 @@ public class HopperCounter */ public static TextColor fromItem(Item item) { - if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).getDefaultMaterialColor().color)); - if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getColor().getMaterialColor().color)); + 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)); Block block = null; Identifier id = Registry.ITEM.getId(item); if (item instanceof BlockItem) @@ -347,9 +349,9 @@ public class HopperCounter } if (block != null) { - if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMaterialColor().color)); - if (block instanceof Stainable) return TextColor.fromRgb(appropriateColor( ((Stainable) block).getColor().getMaterialColor().color)); - return TextColor.fromRgb(appropriateColor( block.getDefaultMaterialColor().color)); + 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)); } return null; } @@ -368,7 +370,7 @@ public class HopperCounter { for (Recipe r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id)) { - for (Ingredient ingredient: r.getPreviewInputs()) + for (Ingredient ingredient: r.getIngredients()) { for (Collection stacks : ((IngredientInterface) (Object) ingredient).getRecipeStacks()) { diff --git a/src/main/java/carpet/helpers/InventoryHelper.java b/src/main/java/carpet/helpers/InventoryHelper.java index acc3c0f2..73093f83 100644 --- a/src/main/java/carpet/helpers/InventoryHelper.java +++ b/src/main/java/carpet/helpers/InventoryHelper.java @@ -1,11 +1,11 @@ package carpet.helpers; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; public class InventoryHelper { - // From nbt/Tag.java createTag() + // From nbt/NbtElement.java createTag() public static final int TAG_END = 0; public static final int TAG_BYTE = 1; public static final int TAG_SHORT = 2; @@ -23,12 +23,12 @@ public class InventoryHelper public static boolean cleanUpShulkerBoxTag(ItemStack stack) { boolean changed = false; - CompoundTag tag = stack.getTag(); + NbtCompound tag = stack.getTag(); if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND)) return false; - CompoundTag bet = tag.getCompound("BlockEntityTag"); + NbtCompound bet = tag.getCompound("BlockEntityTag"); if (bet.contains("Items", TAG_LIST) && bet.getList("Items", TAG_COMPOUND).isEmpty()) { bet.remove("Items"); @@ -50,12 +50,12 @@ public class InventoryHelper public static boolean shulkerBoxHasItems(ItemStack stack) { - CompoundTag tag = stack.getTag(); + NbtCompound tag = stack.getTag(); if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND)) return false; - CompoundTag bet = tag.getCompound("BlockEntityTag"); + NbtCompound bet = tag.getCompound("BlockEntityTag"); return bet.contains("Items", TAG_LIST) && !bet.getList("Items", TAG_COMPOUND).isEmpty(); } } diff --git a/src/main/java/carpet/helpers/OptimizedExplosion.java b/src/main/java/carpet/helpers/OptimizedExplosion.java index 50475ab3..cfd8316a 100644 --- a/src/main/java/carpet/helpers/OptimizedExplosion.java +++ b/src/main/java/carpet/helpers/OptimizedExplosion.java @@ -134,14 +134,14 @@ public class OptimizedExplosion } if (!entity.isImmuneToExplosion()) { - double d12 = MathHelper.sqrt(entity.squaredDistanceTo(eAccess.getX(), eAccess.getY(), eAccess.getZ())) / (double) f3; + double d12 = Math.sqrt(entity.squaredDistanceTo(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 d9 = entity.getZ() - eAccess.getZ(); - double d13 = (double) MathHelper.sqrt(d5 * d5 + d7 * d7 + d9 * d9); + double d13 = (double) Math.sqrt(d5 * d5 + d7 * d7 + d9 * d9); if (d13 != 0.0D) { d5 = d5 / d13; @@ -184,7 +184,7 @@ public class OptimizedExplosion PlayerEntity player = (PlayerEntity) entity; if (!player.isSpectator() - && (!player.isCreative() || !player.abilities.flying)) { + && (!player.isCreative() || !player.getAbilities().flying)) { //getAbilities e.getAffectedPlayers().put(player, new Vec3d(d5 * d10, d7 * d10, d9 * d10)); } } @@ -244,7 +244,7 @@ public class OptimizedExplosion { if (block.shouldDropItemsOnExplosion(e) && world instanceof ServerWorld) { - BlockEntity blockEntity = block.hasBlockEntity() ? world.getBlockEntity(blockpos) : null; + BlockEntity blockEntity = state.hasBlockEntity() ? world.getBlockEntity(blockpos) : null; //hasBlockEntity() LootContext.Builder lootBuilder = (new LootContext.Builder((ServerWorld)eAccess.getWorld())) .random(eAccess.getWorld().random) diff --git a/src/main/java/carpet/helpers/ParticleDisplay.java b/src/main/java/carpet/helpers/ParticleDisplay.java index ff82f24b..a86d2973 100644 --- a/src/main/java/carpet/helpers/ParticleDisplay.java +++ b/src/main/java/carpet/helpers/ParticleDisplay.java @@ -2,7 +2,7 @@ package carpet.helpers; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.argument.ParticleArgumentType; +import net.minecraft.command.argument.ParticleEffectArgumentType; import net.minecraft.particle.ParticleEffect; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; @@ -19,7 +19,7 @@ public class ParticleDisplay { try { - return ParticleArgumentType.readParameters(new StringReader(name)); + return ParticleEffectArgumentType.readParameters(new StringReader(name)); } catch (CommandSyntaxException e) { diff --git a/src/main/java/carpet/helpers/TickSpeed.java b/src/main/java/carpet/helpers/TickSpeed.java index ffee2e27..0ee668be 100644 --- a/src/main/java/carpet/helpers/TickSpeed.java +++ b/src/main/java/carpet/helpers/TickSpeed.java @@ -147,7 +147,7 @@ public class TickSpeed time_warp_start_time = 0; if (tick_warp_callback != null) { - CommandManager icommandmanager = tick_warp_sender.getMinecraftServer().getCommandManager(); + CommandManager icommandmanager = tick_warp_sender.getServer().getCommandManager(); try { icommandmanager.execute(tick_warp_sender, tick_warp_callback); diff --git a/src/main/java/carpet/helpers/XPcombine.java b/src/main/java/carpet/helpers/XPcombine.java index 0f27e5c6..e75a2931 100644 --- a/src/main/java/carpet/helpers/XPcombine.java +++ b/src/main/java/carpet/helpers/XPcombine.java @@ -28,7 +28,7 @@ public class XPcombine first == other || first.world.isClient || first.getServer().getTicks() == lastTickCombine || !first.isAlive() || !other.isAlive() || first.getExperienceAmount() > 15000 || other.getExperienceAmount() > 15000 - || first.pickupDelay == 32767 || other.pickupDelay == 32767 + //|| first.pickupDelay == 32767 || other.pickupDelay == 32767 || first.age == -32768 || other.age == -32768 || ((ExperienceOrbInterface)first).getCombineDelay() != 0 || ((ExperienceOrbInterface)other).getCombineDelay() != 0 ) @@ -37,21 +37,24 @@ public class XPcombine } int size = getTextureByXP(first.getExperienceAmount()); - ((ExperienceOrbInterface) first).setAmount(first.getExperienceAmount() + other.getExperienceAmount()); - ((ExperienceOrbInterface) first).setCombineDelay(Math.max(first.pickupDelay, other.pickupDelay)); + ((ExperienceOrbInterface) first).setAmount( + first.getExperienceAmount()*((ExperienceOrbInterface) first).getCount() + + other.getExperienceAmount()*((ExperienceOrbInterface) other).getCount()); + ((ExperienceOrbInterface) first).setCount(1); + //((ExperienceOrbInterface) first).setCombineDelay(Math.max(first.pickupDelay, other.pickupDelay)); first.age = Math.min(first.age, other.age); - other.remove(); + other.discard(); //discard ExperienceOrbEntity newOrb; if (getTextureByXP(first.getExperienceAmount()) != size) { newOrb = new ExperienceOrbEntity(EntityType.EXPERIENCE_ORB, first.world); - newOrb.refreshPositionAndAngles(first.getX(), first.getY(), first.getZ(), first.yaw, first.pitch); + newOrb.refreshPositionAndAngles(first.getX(), first.getY(), first.getZ(), first.getYaw(), first.getPitch()); ((ExperienceOrbInterface)newOrb).setAmount(first.getExperienceAmount()); first.world.spawnEntity(newOrb); - first.remove(); + first.discard(); // discard } else { diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java index 2b679fb1..6cabcfc4 100644 --- a/src/main/java/carpet/logging/HUDController.java +++ b/src/main/java/carpet/logging/HUDController.java @@ -7,7 +7,9 @@ import carpet.logging.logHelpers.PacketCounter; 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.server.MinecraftServer; @@ -42,10 +44,9 @@ public class HUDController } public static Map> player_huds = new HashMap<>(); - - //keyed with player names so unlogged players don't hold the reference +//keyed with player names so unlogged players don't hold the reference public static final Map scarpet_headers = new HashMap<>(); - + public static final Map scarpet_footers = new HashMap<>(); public static void resetScarpetHUDs() { @@ -68,9 +69,10 @@ public class HUDController } public static void clear_player(PlayerEntity player) { - PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(); - ((PlayerListHeaderS2CPacketMixin)packet).setHeader(new LiteralText("")); - ((PlayerListHeaderS2CPacketMixin)packet).setFooter(new LiteralText("")); + PacketByteBuf packetData = new PacketByteBuf(Unpooled.buffer()).writeText(new LiteralText("")).writeText(new LiteralText("")); + PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(packetData); + //((PlayerListHeaderS2CPacketMixin)packet).setHeader(new LiteralText("")); + //((PlayerListHeaderS2CPacketMixin)packet).setFooter(new LiteralText("")); ((ServerPlayerEntity)player).networkHandler.sendPacket(packet); } @@ -121,9 +123,14 @@ public class HUDController if (force!= null) targets.addAll(force); for (ServerPlayerEntity player: targets) { - 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]))); + 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); + + //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); } } diff --git a/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java new file mode 100644 index 00000000..003d8773 --- /dev/null +++ b/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java @@ -0,0 +1,37 @@ +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 org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +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) + { + int count = -1; + if (CarpetSettings.stackableShulkerBoxes && 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()) + { + ItemStack current = playerEntity.getStackInHand(hand); + if (current.getItem() instanceof BlockItem && ((BlockItem)itemStack.getItem()).getBlock() instanceof ShulkerBoxBlock) + current.setCount(count); + } + return result; + } +} diff --git a/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java b/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java index 0bd6d395..5bb4b7c2 100644 --- a/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java +++ b/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java @@ -26,7 +26,7 @@ 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 = "readCustomDataFromTag", at = @At("HEAD")) + @Inject(method = "readCustomDataFromNbt", at = @At("HEAD")) private void checkScarpetMarkerUnloaded(CallbackInfo ci) { if (!world.isClient) @@ -40,13 +40,13 @@ public abstract class ArmorStandEntity_scarpetMarkerMixin extends LivingEntity String hostName = StringUtils.removeStart(owner.get(),prefix); if (!hostName.isEmpty() && CarpetServer.scriptServer.getHostByName(hostName) == null) { - remove(); + discard(); //discard } } else { - remove(); + discard(); // discard } } } diff --git a/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java b/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java index bee4a591..0633874c 100644 --- a/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java +++ b/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java @@ -5,6 +5,8 @@ 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; @@ -18,7 +20,7 @@ import java.util.List; @Mixin(BastionRemnantFeature.class) public abstract class BastionRemnantFeatureMixin extends JigsawFeature { - private static final List spawnList = Lists.newArrayList( + private static final Pool spawnList = 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) @@ -30,10 +32,10 @@ public abstract class BastionRemnantFeatureMixin extends JigsawFeature } @Override - public List getMonsterSpawns() + public Pool getMonsterSpawns() { if (CarpetSettings.piglinsSpawningInBastions) return spawnList; - return Collections.emptyList(); + return SpawnSettings.EMPTY_ENTRY_POOL; } } diff --git a/src/main/java/carpet/mixins/BiomeArray_cleanLogsMixin.java b/src/main/java/carpet/mixins/BiomeArray_cleanLogsMixin.java index cf7fc1a0..109f7e29 100644 --- a/src/main/java/carpet/mixins/BiomeArray_cleanLogsMixin.java +++ b/src/main/java/carpet/mixins/BiomeArray_cleanLogsMixin.java @@ -10,12 +10,14 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(BiomeArray.class) public class BiomeArray_cleanLogsMixin { - @Redirect(method = "(Lnet/minecraft/util/collection/IndexedIterable;[I)V", at = @At( + // this changed in 21w18a - maybe its not needed anymore, please check + @SuppressWarnings("UnresolvedMixinReference") + @Redirect(method = "(Lnet/minecraft/util/collection/IndexedIterable;Lnet/minecraft/world/HeightLimitView;[I)V", at = @At( value = "INVOKE", - target = "Lorg/apache/logging/log4j/Logger;warn(Ljava/lang/String;)V") + target = "Lorg/apache/logging/log4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V") ) - private void skipLog(Logger logger, String message) + private void skipLog(Logger logger, String message, Object p0, Object p1) { - if (!CarpetSettings.cleanLogs) logger.warn(message); + if (!CarpetSettings.cleanLogs) logger.warn(message, p0, p1); } } diff --git a/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java b/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java index 5f431cb3..3c757a7f 100644 --- a/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java +++ b/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java @@ -6,6 +6,7 @@ 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; @@ -18,16 +19,20 @@ public class BiomeArray_getBiomeArrayMixin implements BiomeArrayInterface @Shadow @Final public static int HORIZONTAL_BIT_MASK; - @Shadow @Final public static int VERTICAL_BIT_MASK; + //@Shadow @Final public static int VERTICAL_BIT_MASK; @Shadow @Final private Biome[] data; + @Shadow @Final private int field_28126; + + @Shadow @Final private int field_28127; + @Override public void setBiomeAtIndex(BlockPos pos, World world, Biome what) { - int int_4 = (pos.getX() >> 2) & HORIZONTAL_BIT_MASK; - int int_5 = MathHelper.clamp((pos.getY() >> 2), 0, VERTICAL_BIT_MASK); - int int_6 = (pos.getZ() >> 2) & HORIZONTAL_BIT_MASK; + int int_4 = BiomeCoords.fromBlock(pos.getX()) & HORIZONTAL_BIT_MASK; + int int_5 = MathHelper.clamp(BiomeCoords.fromBlock(pos.getY())-field_28126, 0, field_28127); + int int_6 = BiomeCoords.fromBlock(pos.getZ()) & HORIZONTAL_BIT_MASK; data[(int_5 << (HORIZONTAL_SECTION_COUNT + HORIZONTAL_SECTION_COUNT)) | (int_6 << HORIZONTAL_SECTION_COUNT) | int_4] = what; } } diff --git a/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java b/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java new file mode 100644 index 00000000..a848ee2e --- /dev/null +++ b/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java @@ -0,0 +1,21 @@ +package carpet.mixins; + +import carpet.fakes.BlockEntityInterface; +import net.minecraft.block.entity.BlockEntity; +import net.minecraft.util.math.BlockPos; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(BlockEntity.class) +public abstract class BlockEntity_movableBEMixin implements BlockEntityInterface +{ + @Mutable + @Shadow @Final protected BlockPos pos; + + public void setCMPos(BlockPos newPos) + { + pos = newPos; + }; +} diff --git a/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java b/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java index 48bf7e8b..329a72ff 100644 --- a/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java @@ -24,7 +24,7 @@ public class BlockItem_creativeNoClipMixin ItemPlacementContext contextOuter, BlockState stateOuter) { PlayerEntity player = contextOuter.getPlayer(); - if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.abilities.flying) + if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.getAbilities().flying) { // copy from canPlace VoxelShape voxelShape = state.getCollisionShape(world, pos, context); diff --git a/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java b/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java index b4258426..16d905c7 100644 --- a/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java +++ b/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java @@ -2,7 +2,7 @@ package carpet.mixins; import carpet.fakes.BlockStateArgumentInterface; import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -11,10 +11,10 @@ import org.spongepowered.asm.mixin.Shadow; @Mixin(BlockStateArgument.class) public class BlockStateArgument_scarpetMixin implements BlockStateArgumentInterface { - @Shadow @Final private @Nullable CompoundTag data; + @Shadow @Final private @Nullable NbtCompound data; @Override - public CompoundTag getCMTag() + public NbtCompound getCMTag() { return data; } diff --git a/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java b/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java new file mode 100644 index 00000000..3e9c2449 --- /dev/null +++ b/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java @@ -0,0 +1,45 @@ +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 org.jetbrains.annotations.Nullable; +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.CallbackInfoReturnable; + +@Mixin(BuddingAmethystBlock.class) +public class BuddingAmethystBlock_movableAmethystMixin extends Block { + public BuddingAmethystBlock_movableAmethystMixin(Settings 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 cir) { + if (CarpetSettings.movableAmethyst) cir.setReturnValue(PistonBehavior.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); + // 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 + ) + dropStack(world, pos, Items.BUDDING_AMETHYST.getDefaultStack()); + } +} diff --git a/src/main/java/carpet/mixins/CarpetBlockMixin.java b/src/main/java/carpet/mixins/CarpetBlockMixin.java index 922538dd..32b4b481 100644 --- a/src/main/java/carpet/mixins/CarpetBlockMixin.java +++ b/src/main/java/carpet/mixins/CarpetBlockMixin.java @@ -3,12 +3,12 @@ package carpet.mixins; import carpet.utils.WoolTool; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.block.CarpetBlock; +import net.minecraft.block.DyedCarpetBlock; import net.minecraft.item.ItemPlacementContext; import net.minecraft.server.world.ServerWorld; import org.spongepowered.asm.mixin.Mixin; -@Mixin(CarpetBlock.class) +@Mixin(DyedCarpetBlock.class) // WoolCarpetBlock public abstract class CarpetBlockMixin extends Block { @@ -21,8 +21,8 @@ public abstract class CarpetBlockMixin extends Block { BlockState state = super.getPlacementState(context); if (context.getPlayer() != null && !context.getWorld().isClient) - { - WoolTool.carpetPlacedAction(((CarpetBlock)(Object)this).getColor(), context.getPlayer(), context.getBlockPos(), (ServerWorld) context.getWorld()); + { // getColor() + WoolTool.carpetPlacedAction(((DyedCarpetBlock)(Object)this).getDyeColor(), context.getPlayer(), context.getBlockPos(), (ServerWorld) context.getWorld()); } return state; } diff --git a/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java index 783a035a..be348daf 100644 --- a/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java +++ b/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java @@ -19,7 +19,7 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(CauldronBlock.class) public class CauldronBlock_stackableSBoxesMixin -{ +{/* @Inject(method = "onUse", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;hasTag()Z", @@ -30,5 +30,5 @@ public class CauldronBlock_stackableSBoxesMixin { if (CarpetSettings.stackableShulkerBoxes) itemStack5.setCount(itemStack.getCount()); - } + }*/ } diff --git a/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java index 7a1d8fc7..39cbca4f 100644 --- a/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java @@ -3,6 +3,7 @@ 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.thread.ThreadExecutor; import net.minecraft.world.chunk.Chunk; @@ -19,19 +20,19 @@ import java.util.concurrent.atomic.AtomicReferenceArray; @Mixin(ChunkHolder.class) public abstract class ChunkHolder_scarpetChunkCreationMixin implements ChunkHolderInterface { - @Shadow protected abstract void combineSavingFuture(CompletableFuture> newChunkFuture); + @Shadow protected abstract void combineSavingFuture(CompletableFuture> newChunkFuture, String type); @Shadow @Final private AtomicReferenceArray>> futuresByStatus; @Override - public CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor executor) + public CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor executor, ServerWorld world) { int i = ChunkStatus.EMPTY.getIndex(); CompletableFuture> completableFuture2 = CompletableFuture.supplyAsync( - () -> Either.left(new ProtoChunk(chpos, UpgradeData.NO_UPGRADE_DATA)), + () -> Either.left(new ProtoChunk(chpos, UpgradeData.NO_UPGRADE_DATA, world)), executor ); - combineSavingFuture(completableFuture2); + combineSavingFuture(completableFuture2, "unfull"); // possible debug data futuresByStatus.set(i, completableFuture2); return completableFuture2; } diff --git a/src/main/java/carpet/mixins/CommandManagerMixin.java b/src/main/java/carpet/mixins/CommandManagerMixin.java index 0b3ef549..05e82a37 100644 --- a/src/main/java/carpet/mixins/CommandManagerMixin.java +++ b/src/main/java/carpet/mixins/CommandManagerMixin.java @@ -27,6 +27,7 @@ public abstract class CommandManagerMixin @Inject(method = "", at = @At("RETURN")) private void onRegister(CommandManager.RegistrationEnvironment arg, CallbackInfo ci) { CarpetServer.registerCarpetCommands(this.dispatcher); + CarpetServer.registerCarpetCommands(this.dispatcher, arg); } @Inject(method = "execute", at = @At("HEAD")) diff --git a/src/main/java/carpet/mixins/ContainerMixin.java b/src/main/java/carpet/mixins/ContainerMixin.java index f2beddee..96e650fa 100644 --- a/src/main/java/carpet/mixins/ContainerMixin.java +++ b/src/main/java/carpet/mixins/ContainerMixin.java @@ -7,11 +7,13 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.screen.ScreenHandler; +import net.minecraft.util.collection.DefaultedList; import org.spongepowered.asm.mixin.Final; 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; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; @@ -19,20 +21,25 @@ import java.util.List; @Mixin(ScreenHandler.class) public abstract class ContainerMixin { - @Shadow @Final public List slots; - @Shadow public abstract ItemStack onSlotClick(int int_1, int int_2, SlotActionType slotActionType_1, PlayerEntity playerEntity_1); + @Shadow public abstract void onSlotClick(int int_1, int int_2, SlotActionType slotActionType_1, PlayerEntity playerEntity_1); @Shadow public abstract void sendContentUpdates(); - @Inject( method = "onSlotClick", at = @At(value = "HEAD"), cancellable = true) - private void onThrowClick( int slotId, int clickData, SlotActionType actionType, PlayerEntity playerEntity, CallbackInfoReturnable cir) + @Shadow @Final public DefaultedList slots; + + @Shadow protected abstract void endQuickCraft(); + + @Shadow public abstract ItemStack getCursorStack(); + + @Inject( method = "internalOnSlotClick", at = @At(value = "HEAD"), cancellable = true) + private void onThrowClick(int slotId, int clickData, SlotActionType actionType, PlayerEntity playerEntity, CallbackInfo ci) { - if (actionType == SlotActionType.THROW && CarpetSettings.ctrlQCraftingFix && playerEntity.inventory.getCursorStack().isEmpty() && slotId >= 0) + if (actionType == SlotActionType.THROW && CarpetSettings.ctrlQCraftingFix && this.getCursorStack().isEmpty() && slotId >= 0) { ItemStack itemStack_1 = ItemStack.EMPTY; Slot slot_4 = slots.get(slotId); - if (slot_4 != null && slot_4.hasStack() && slot_4.canTakeItems(playerEntity)) + if (/*slot_4 != null && */slot_4.hasStack() && slot_4.canTakeItems(playerEntity)) { if(slotId == 0 && clickData == 1) { @@ -42,8 +49,8 @@ public abstract class ContainerMixin this.onSlotClick(slotId, 0, SlotActionType.THROW, playerEntity); } this.sendContentUpdates(); - cir.setReturnValue(itemStack_1); - cir.cancel(); + this.endQuickCraft(); + ci.cancel(); } } } diff --git a/src/main/java/carpet/mixins/CoralBlockMixin.java b/src/main/java/carpet/mixins/CoralBlockMixin.java index ea6db8e0..9e241b41 100644 --- a/src/main/java/carpet/mixins/CoralBlockMixin.java +++ b/src/main/java/carpet/mixins/CoralBlockMixin.java @@ -8,7 +8,7 @@ import net.minecraft.block.Blocks; import net.minecraft.block.CoralBlock; import net.minecraft.block.CoralParentBlock; import net.minecraft.block.Fertilizable; -import net.minecraft.block.MaterialColor; +import net.minecraft.block.MapColor; import net.minecraft.server.world.ServerWorld; import net.minecraft.tag.BlockTags; import net.minecraft.tag.FluidTags; @@ -49,12 +49,12 @@ public abstract class CoralBlockMixin implements Fertilizable else coral = new CoralMushroomFeature(DefaultFeatureConfig.CODEC); - MaterialColor color = blockUnder.getTopMaterialColor(worldIn, pos); + MapColor color = blockUnder.getMapColor(worldIn, pos); BlockState proper_block = blockUnder; for (Block block: BlockTags.CORAL_BLOCKS.values()) { proper_block = block.getDefaultState(); - if (proper_block.getTopMaterialColor(worldIn,pos) == color) + if (proper_block.getMapColor(worldIn,pos) == color) { break; } diff --git a/src/main/java/carpet/mixins/CoralFeatureMixin.java b/src/main/java/carpet/mixins/CoralFeatureMixin.java index 2271bffd..41b88df0 100644 --- a/src/main/java/carpet/mixins/CoralFeatureMixin.java +++ b/src/main/java/carpet/mixins/CoralFeatureMixin.java @@ -15,11 +15,11 @@ import java.util.Random; public abstract class CoralFeatureMixin implements CoralFeatureInterface { - @Shadow protected abstract boolean spawnCoral(WorldAccess var1, Random var2, BlockPos var3, BlockState var4); + @Shadow protected abstract boolean generateCoral(WorldAccess var1, Random var2, BlockPos var3, BlockState var4); @Override public boolean growSpecific(World worldIn, Random random, BlockPos pos, BlockState blockUnder) { - return spawnCoral(worldIn, random, pos, blockUnder); + return generateCoral(worldIn, random, pos, blockUnder); } } diff --git a/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java b/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java index dd156441..e2dcf2d7 100644 --- a/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java +++ b/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java @@ -1,7 +1,9 @@ package carpet.mixins; +import java.util.function.Supplier; import java.util.stream.Collectors; +import net.minecraft.util.SystemDetails; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -9,19 +11,16 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import carpet.CarpetServer; -import net.minecraft.util.crash.CrashReport; -import net.minecraft.util.crash.CrashReportSection; -@Mixin(CrashReport.class) +@Mixin(SystemDetails.class) public abstract class CrashReport_addScarpetAppsMixin { - @Shadow - public abstract CrashReportSection getSystemDetailsSection(); - - @Inject(at = @At("RETURN"), method = "fillSystemDetails") + @Shadow public abstract void addSection(String name, Supplier valueSupplier); + + @Inject(method = "", at = @At("RETURN")) private void fillSystemDetails(CallbackInfo info) { if (CarpetServer.scriptServer == null || CarpetServer.scriptServer.modules.isEmpty()) return; - getSystemDetailsSection().add("Loaded Scarpet Apps", () -> { + addSection("Loaded Scarpet Apps", () -> { return CarpetServer.scriptServer.modules.keySet().stream().collect(Collectors.joining("\n\t\t", "\n\t\t", "")); }); } diff --git a/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java b/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java index 0b08e722..ff46ca42 100644 --- a/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java +++ b/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java @@ -4,6 +4,7 @@ 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.biome.SpawnSettings; import net.minecraft.world.gen.feature.DefaultFeatureConfig; import net.minecraft.world.gen.feature.DesertPyramidFeature; @@ -16,11 +17,11 @@ import java.util.List; @Mixin(DesertPyramidFeature.class) public abstract class DesertPyramidFeatureMixin extends StructureFeature { - private static final List MONSTER_SPAWNS; + private static final Pool MONSTER_SPAWNS; static { - MONSTER_SPAWNS = Lists.newArrayList(new SpawnSettings.SpawnEntry(EntityType.HUSK, 1, 1, 1)); + MONSTER_SPAWNS = Pool.of(new SpawnSettings.SpawnEntry(EntityType.HUSK, 1, 1, 1)); } public DesertPyramidFeatureMixin(Codec codec) @@ -30,13 +31,13 @@ public abstract class DesertPyramidFeatureMixin extends StructureFeature getMonsterSpawns() + public Pool getMonsterSpawns() { if (CarpetSettings.huskSpawningInTemples) { return MONSTER_SPAWNS; } - return Collections.emptyList(); + return SpawnSettings.EMPTY_ENTRY_POOL; } } diff --git a/src/main/java/carpet/mixins/EndCityFeatureMixin.java b/src/main/java/carpet/mixins/EndCityFeatureMixin.java index 7ff4227c..382b86e2 100644 --- a/src/main/java/carpet/mixins/EndCityFeatureMixin.java +++ b/src/main/java/carpet/mixins/EndCityFeatureMixin.java @@ -4,6 +4,7 @@ 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.biome.SpawnSettings; import net.minecraft.world.gen.feature.DefaultFeatureConfig; import net.minecraft.world.gen.feature.EndCityFeature; @@ -16,7 +17,7 @@ import java.util.List; @Mixin(EndCityFeature.class) public abstract class EndCityFeatureMixin extends StructureFeature { - private static final List spawnList = Lists.newArrayList(new SpawnSettings.SpawnEntry(EntityType.SHULKER, 10, 4, 4)); + private static final Pool spawnList = Pool.of(new SpawnSettings.SpawnEntry(EntityType.SHULKER, 10, 4, 4)); public EndCityFeatureMixin(Codec codec) { @@ -24,10 +25,10 @@ public abstract class EndCityFeatureMixin extends StructureFeature getMonsterSpawns() + public Pool getMonsterSpawns() { if (CarpetSettings.shulkerSpawningInEndCities) return spawnList; - return Collections.emptyList(); + return SpawnSettings.EMPTY_ENTRY_POOL; } } diff --git a/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java b/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java index 8d3703d0..36df899d 100644 --- a/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java @@ -11,7 +11,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(EndGatewayBlockEntity.class) public class EndGatewayBlockEntity_creativeNoClipMixin { - @Inject(method = "method_30276", cancellable = true, at = @At("HEAD")) + @Inject(method = "canTeleport", cancellable = true, at = @At("HEAD")) private static void checkFlyingCreative(Entity entity, CallbackInfoReturnable cir) { if (CarpetSettings.isCreativeFlying(entity)) cir.setReturnValue(false); diff --git a/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java b/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java index b819f013..b85704cd 100644 --- a/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java +++ b/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java @@ -7,6 +7,7 @@ import net.minecraft.entity.ai.pathing.Path; import net.minecraft.entity.mob.MobEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,18 +23,18 @@ public abstract class EntityNavigation_pathfindingMixin @Shadow @Final protected MobEntity entity; - @Shadow /*@Nullable*/ protected abstract Path findPathToAny(Set set_1, int int_1, boolean boolean_1, int int_2); + @Shadow protected @Nullable abstract Path findPathTo(Set set, int i, boolean bl, int j); @Redirect(method = "findPathTo(Lnet/minecraft/util/math/BlockPos;I)Lnet/minecraft/entity/ai/pathing/Path;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/ai/pathing/EntityNavigation;findPathToAny(Ljava/util/Set;IZI)Lnet/minecraft/entity/ai/pathing/Path;" + target = "Lnet/minecraft/entity/ai/pathing/EntityNavigation;findPathTo(Ljava/util/Set;IZI)Lnet/minecraft/entity/ai/pathing/Path;" )) private Path pathToBlock(EntityNavigation entityNavigation, Set set_1, int int_1, boolean boolean_1, int int_2) { if (!LoggerRegistry.__pathfinding) - return findPathToAny(set_1, int_1, boolean_1, int_2); + return findPathTo(set_1, int_1, boolean_1, int_2); long start = System.nanoTime(); - Path path = findPathToAny(set_1, int_1, boolean_1, int_2); + Path path = findPathTo(set_1, int_1, boolean_1, int_2); long finish = System.nanoTime(); float duration = (1.0F*((finish - start)/1000))/1000; set_1.forEach(b -> PathfindingVisualizer.slowPath(entity, Vec3d.ofBottomCenter(b), duration, path != null)); // ground centered position @@ -42,14 +43,14 @@ public abstract class EntityNavigation_pathfindingMixin @Redirect(method = "findPathTo(Lnet/minecraft/entity/Entity;I)Lnet/minecraft/entity/ai/pathing/Path;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/ai/pathing/EntityNavigation;findPathToAny(Ljava/util/Set;IZI)Lnet/minecraft/entity/ai/pathing/Path;" + target = "Lnet/minecraft/entity/ai/pathing/EntityNavigation;findPathTo(Ljava/util/Set;IZI)Lnet/minecraft/entity/ai/pathing/Path;" )) private Path pathToEntity(EntityNavigation entityNavigation, Set set_1, int int_1, boolean boolean_1, int int_2) { if (!LoggerRegistry.__pathfinding) - return findPathToAny(set_1, int_1, boolean_1, int_2); + return findPathTo(set_1, int_1, boolean_1, int_2); long start = System.nanoTime(); - Path path = findPathToAny(set_1, int_1, boolean_1, int_2); + Path path = findPathTo(set_1, int_1, boolean_1, int_2); long finish = System.nanoTime(); float duration = (1.0F*((finish - start)/1000))/1000; set_1.forEach(b -> PathfindingVisualizer.slowPath(entity, Vec3d.ofBottomCenter(b), duration, path != null)); diff --git a/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java index c68be88b..0070517a 100644 --- a/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java @@ -12,10 +12,13 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Entity.class) public abstract class Entity_scarpetEventsMixin implements EntityInterface { - @Shadow public boolean removed; + //@Shadow public boolean removed; @Shadow protected int netherPortalTime; @Shadow private int netherPortalCooldown; + + @Shadow public abstract boolean isRemoved(); + private boolean permanentVehicle; private final EntityEventsGroup events = new EntityEventsGroup((Entity) (Object)this); @@ -72,7 +75,7 @@ public abstract class Entity_scarpetEventsMixin implements EntityInterface @Inject(method = "remove", at = @At("HEAD")) private void onRemove(CallbackInfo ci) { - if (!removed) events.onEvent(EntityEventsGroup.Event.ON_REMOVED); + if (!isRemoved()) events.onEvent(EntityEventsGroup.Event.ON_REMOVED); // ! isRemoved() } diff --git a/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java b/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java index c639b3cf..30aa4a50 100644 --- a/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java +++ b/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java @@ -3,19 +3,31 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.ExperienceOrbInterface; import carpet.helpers.XPcombine; +import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.ExperienceOrbEntity; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.ItemStack; 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; + +import java.util.Map; @Mixin(ExperienceOrbEntity.class) public abstract class ExperienceOrbEntityMixin implements ExperienceOrbInterface { @Shadow private int amount; + @Shadow private int pickingCount; + + @Shadow protected abstract int getMendingRepairCost(int repairAmount); + + @Shadow protected abstract int getMendingRepairAmount(int experienceAmount); + public void setAmount(int amount) { this.amount = amount; } public int combineDelay = 50; @@ -45,6 +57,16 @@ public abstract class ExperienceOrbEntityMixin implements ExperienceOrbInterface } } + @Override + public int getCount() { + return pickingCount; + } + + @Override + public void setCount(int i) { + pickingCount = i; + } + @Inject(method = "onPlayerCollision", at = @At("HEAD")) void removeDelay(PlayerEntity playerEntity_1, CallbackInfo ci) { @@ -52,4 +74,14 @@ public abstract class ExperienceOrbEntityMixin implements ExperienceOrbInterface playerEntity_1.experiencePickUpDelay = 0; } + @Redirect(method = "onPlayerCollision", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addExperience(I)V")) + void addXP(PlayerEntity playerEntity, int experience) + { + playerEntity.addExperience(experience); + if (CarpetSettings.xpNoCooldown) while(pickingCount > 1) + { + pickingCount --; + playerEntity.addExperience(experience); + } + } } diff --git a/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java b/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java index 8bca895d..24810333 100644 --- a/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java @@ -15,6 +15,7 @@ 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @@ -39,6 +40,8 @@ public abstract class Explosion_scarpetEventMixin @Shadow /*@Nullable*/ public abstract /*@Nullable*/ LivingEntity getCausingEntity(); + @Shadow public static float getExposure(Vec3d source, Entity entity) {return 0.0f;} + private List affectedEntities; @Inject(method = "(Lnet/minecraft/world/World;Lnet/minecraft/entity/Entity;Lnet/minecraft/entity/damage/DamageSource;Lnet/minecraft/world/explosion/ExplosionBehavior;DDDFZLnet/minecraft/world/explosion/Explosion$DestructionType;)V", @@ -51,13 +54,17 @@ public abstract class Explosion_scarpetEventMixin } } - @Inject(method = "collectBlocksAndDamageEntities", locals= LocalCapture.CAPTURE_FAILHARD, at=@At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;damage(Lnet/minecraft/entity/damage/DamageSource;F)Z")) - private void onExplosion(CallbackInfo ci, Set s1, float f1, int i1, int i2, int i3, int i4, int i5, int i6, List l1, Vec3d v1, int i7, Entity entity) + @Redirect(method = "collectBlocksAndDamageEntities", at=@At( + value = "INVOKE", + target = "Lnet/minecraft/world/explosion/Explosion;getExposure(Lnet/minecraft/util/math/Vec3d;Lnet/minecraft/entity/Entity;)F") + ) + private float onExplosion(Vec3d source, Entity entity) { if (affectedEntities != null) { affectedEntities.add(entity); } + return getExposure(source, entity); } @Inject(method = "affectWorld", at = @At("HEAD")) diff --git a/src/main/java/carpet/mixins/FallingBlockEntityMixin.java b/src/main/java/carpet/mixins/FallingBlockEntityMixin.java index 5cc0b912..82db5835 100644 --- a/src/main/java/carpet/mixins/FallingBlockEntityMixin.java +++ b/src/main/java/carpet/mixins/FallingBlockEntityMixin.java @@ -33,9 +33,9 @@ public abstract class FallingBlockEntityMixin extends Entity } @Override - public void remove() + public void remove(Entity.RemovalReason arg) // reason { - super.remove(); + super.remove(arg); if (LoggerRegistry.__fallingBlocks && logHelper != null) logHelper.onFinish(); } diff --git a/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java b/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java index 5dfa9edd..7a6adc4c 100644 --- a/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java +++ b/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java @@ -2,6 +2,7 @@ package carpet.mixins; import carpet.CarpetSettings; import net.minecraft.entity.SpawnGroup; +import net.minecraft.util.collection.Pool; import net.minecraft.util.math.BlockPos; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.SpawnSettings; @@ -25,7 +26,7 @@ public abstract class FlatChunkGeneratorMixin extends ChunkGenerator } @Override - public List getEntitySpawnList(Biome biome, StructureAccessor accessor, SpawnGroup group, BlockPos pos) + public Pool getEntitySpawnList(Biome biome, StructureAccessor accessor, SpawnGroup group, BlockPos pos) { if (CarpetSettings.flatWorldStructureSpawning) { diff --git a/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java b/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java index e3b620d8..1a55a6af 100644 --- a/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java +++ b/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java @@ -33,7 +33,7 @@ public abstract class FluidBlock_renewableBlackstoneMixin for(Direction direction : Direction.values()) { if (direction != Direction.DOWN) { - BlockPos blockPos = pos.offset(direction); + BlockPos blockPos = pos.offset(direction); // offset if (world.getBlockState(blockPos).isOf(Blocks.BLUE_ICE)) { world.setBlockState(pos, Blocks.BLACKSTONE.getDefaultState()); playExtinguishSound(world, pos); diff --git a/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java b/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java new file mode 100644 index 00000000..2a7a3e8c --- /dev/null +++ b/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java @@ -0,0 +1,32 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.block.FluidBlock; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.WorldAccess; +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.CallbackInfoReturnable; + +@Mixin(FluidBlock.class) +public abstract class FluidBlock_renewableDeepslateMixin { + + @Shadow protected abstract void playExtinguishSound(WorldAccess world, BlockPos pos); + + @Inject(method = "receiveNeighborFluids", at = @At(value = "INVOKE",target = "Lnet/minecraft/fluid/FluidState;isStill()Z"), cancellable = true) + private void receiveFluidToDeepslate(World world, BlockPos pos, BlockState state, CallbackInfoReturnable cir) + { + if(CarpetSettings.renewableDeepslate && !world.getFluidState(pos).isStill() && world.getRegistryKey() == World.OVERWORLD && pos.getY() < 16) + { + world.setBlockState(pos, Blocks.COBBLED_DEEPSLATE.getDefaultState()); + this.playExtinguishSound(world, pos); + cir.setReturnValue(false); + cir.cancel(); + } + } +} diff --git a/src/main/java/carpet/mixins/GuardianEntityMixin.java b/src/main/java/carpet/mixins/GuardianEntityMixin.java index 694ae931..6ec860c5 100644 --- a/src/main/java/carpet/mixins/GuardianEntityMixin.java +++ b/src/main/java/carpet/mixins/GuardianEntityMixin.java @@ -8,7 +8,7 @@ import net.minecraft.entity.SpawnReason; import net.minecraft.entity.mob.ElderGuardianEntity; import net.minecraft.entity.mob.GuardianEntity; import net.minecraft.entity.mob.HostileEntity; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.server.world.ServerWorld; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; @@ -23,12 +23,12 @@ public abstract class GuardianEntityMixin extends HostileEntity @Override public void onStruckByLightning(ServerWorld serverWorld, LightningEntity lightningEntity) - { - if (!this.world.isClient && !this.removed && CarpetSettings.renewableSponges && !((Object)this instanceof ElderGuardianEntity)) + { // isRemoved() + if (!this.world.isClient && !this.isRemoved() && CarpetSettings.renewableSponges && !((Object)this instanceof ElderGuardianEntity)) { ElderGuardianEntity elderGuardian = new ElderGuardianEntity(EntityType.ELDER_GUARDIAN ,this.world); - elderGuardian.refreshPositionAndAngles(this.getX(), this.getY(), this.getZ(), this.yaw, this.pitch); - elderGuardian.initialize(serverWorld ,this.world.getLocalDifficulty(elderGuardian.getBlockPos()), SpawnReason.CONVERSION, (EntityData)null, (CompoundTag)null); + elderGuardian.refreshPositionAndAngles(this.getX(), this.getY(), this.getZ(), this.getYaw(), this.getPitch()); + elderGuardian.initialize(serverWorld ,this.world.getLocalDifficulty(elderGuardian.getBlockPos()), SpawnReason.CONVERSION, (EntityData)null, (NbtCompound)null); elderGuardian.setAiDisabled(this.isAiDisabled()); if (this.hasCustomName()) @@ -38,7 +38,7 @@ public abstract class GuardianEntityMixin extends HostileEntity } this.world.spawnEntity(elderGuardian); - this.remove(); + this.discard(); // discard remove(); } else { diff --git a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java index bf184a2b..0d0a323b 100644 --- a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java +++ b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java @@ -1,13 +1,16 @@ package carpet.mixins; import carpet.CarpetSettings; +import net.minecraft.block.BlockState; import net.minecraft.block.HopperBlock; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.block.entity.HopperBlockEntity; import net.minecraft.block.entity.LootableContainerBlockEntity; +import net.minecraft.inventory.Inventory; import net.minecraft.item.ItemStack; import net.minecraft.util.DyeColor; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -20,21 +23,12 @@ import carpet.utils.WoolTool; * The {@link Mixin} which removes items in a hopper if it points into a wool counter, and calls {@link HopperCounter#add} */ @Mixin(HopperBlockEntity.class) -public abstract class HopperBlockEntityMixin extends LootableContainerBlockEntity { - - protected HopperBlockEntityMixin(BlockEntityType blockEntityType_1) { - super(blockEntityType_1); +public abstract class HopperBlockEntityMixin extends LootableContainerBlockEntity +{ + protected HopperBlockEntityMixin(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { + super(blockEntityType, blockPos, blockState); } - @Shadow - public abstract double getHopperX(); - - @Shadow - public abstract double getHopperY(); - - @Shadow - public abstract double getHopperZ(); - @Shadow public abstract int size(); @Shadow public abstract void setStack(int slot, ItemStack stack); @@ -43,21 +37,21 @@ public abstract class HopperBlockEntityMixin extends LootableContainerBlockEntit * A method to remove items from hoppers pointing into wool and count them via {@link HopperCounter#add} method */ @Inject(method = "insert", at = @At("HEAD"), cancellable = true) - private void onInsert(CallbackInfoReturnable cir) + private static void onInsert(World world, BlockPos blockPos, BlockState blockState, Inventory inventory, CallbackInfoReturnable cir) { if (CarpetSettings.hopperCounters) { DyeColor wool_color = WoolTool.getWoolColorAtPosition( - getWorld(), - new BlockPos(getHopperX(), getHopperY(), getHopperZ()).offset(this.getCachedState().get(HopperBlock.FACING))); + world, + blockPos.offset(blockState.get(HopperBlock.FACING))); // offset if (wool_color != null) { - for (int i = 0; i < size(); ++i) + for (int i = 0; i < inventory.size(); ++i) { - if (!this.getStack(i).isEmpty()) + if (!inventory.getStack(i).isEmpty()) { - ItemStack itemstack = this.getStack(i);//.copy(); - HopperCounter.COUNTERS.get(wool_color).add(this.getWorld().getServer(), itemstack); - this.setStack(i, ItemStack.EMPTY); + ItemStack itemstack = inventory.getStack(i);//.copy(); + HopperCounter.COUNTERS.get(wool_color).add(world.getServer(), itemstack); + inventory.setStack(i, ItemStack.EMPTY); } } cir.setReturnValue(true); diff --git a/src/main/java/carpet/mixins/ItemEntityMixin.java b/src/main/java/carpet/mixins/ItemEntityMixin.java index 2fd31ad6..233540e8 100644 --- a/src/main/java/carpet/mixins/ItemEntityMixin.java +++ b/src/main/java/carpet/mixins/ItemEntityMixin.java @@ -24,7 +24,7 @@ public abstract class ItemEntityMixin extends Entity implements ItemEntityInterf { private static final int SHULKERBOX_MAX_STACK_AMOUNT = 64; - @Shadow private int age; + @Shadow private int itemAge; @Shadow private int pickupDelay; public ItemEntityMixin(EntityType entityType_1, World world_1) { @@ -34,7 +34,7 @@ public abstract class ItemEntityMixin extends Entity implements ItemEntityInterf @Override public void onStruckByLightning(ServerWorld world, LightningEntity lightning) { if (CarpetSettings.lightningKillsDropsFix) { - if (this.age > 8) { //Only kill item if its older then 8 ticks + if (this.itemAge > 8) { //Only kill item if its older then 8 ticks super.onStruckByLightning(world, lightning); } } else { @@ -44,7 +44,7 @@ public abstract class ItemEntityMixin extends Entity implements ItemEntityInterf @Override public int getAgeCM() { - return this.age; + return this.itemAge; } @Override @@ -105,12 +105,12 @@ public abstract class ItemEntityMixin extends Entity implements ItemEntityInterf self.setStack(selfStack); this.pickupDelay = Math.max(((ItemEntityInterface)other).getPickupDelayCM(), this.pickupDelay); - this.age = Math.min(((ItemEntityInterface)other).getAgeCM(), this.age); + this.itemAge = Math.min(((ItemEntityInterface)other).getAgeCM(), this.itemAge); otherStack.decrement(amount); if (otherStack.isEmpty()) { - other.remove(); + other.discard(); // discard remove(); } else { diff --git a/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java b/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java new file mode 100644 index 00000000..8d902f65 --- /dev/null +++ b/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java @@ -0,0 +1,32 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.fluid.FluidState; +import net.minecraft.fluid.LavaFluid; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; +import net.minecraft.world.World; +import net.minecraft.world.WorldAccess; +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(LavaFluid.class) +public abstract class LavaFluid_renewableDeepslateMixin { + @Shadow protected abstract void playExtinguishEvent(WorldAccess world, BlockPos pos); + + @Inject(method = "flow", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;getDefaultState()Lnet/minecraft/block/BlockState;"), cancellable = true) + private void generateDeepslate(WorldAccess world, BlockPos pos, BlockState state, Direction direction, FluidState fluidState, CallbackInfo ci) + { + if(CarpetSettings.renewableDeepslate && ((World)world).getRegistryKey() == World.OVERWORLD && pos.getY() < 16) + { + world.setBlockState(pos, Blocks.DEEPSLATE.getDefaultState(), 3); + this.playExtinguishEvent(world, pos); + ci.cancel(); + } + } +} diff --git a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java index c50a364c..7de5e55c 100644 --- a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java @@ -30,7 +30,7 @@ public abstract class LivingEntity_creativeFlyMixin extends Entity if (CarpetSettings.creativeFlyDrag != 0.09 && (Object)this instanceof PlayerEntity) { PlayerEntity self = (PlayerEntity)(Object)(this); - if (self.abilities.flying && ! onGround ) + if (self.getAbilities().flying && ! onGround ) return (float)(1.0-CarpetSettings.creativeFlyDrag); } return original; @@ -43,7 +43,7 @@ public abstract class LivingEntity_creativeFlyMixin extends Entity if (CarpetSettings.creativeFlySpeed != 1.0D && (Object)this instanceof PlayerEntity) { PlayerEntity self = (PlayerEntity)(Object)(this); - if (self.abilities.flying && !onGround) + if (self.getAbilities().flying && !onGround) cir.setReturnValue(flyingSpeed* (float)CarpetSettings.creativeFlySpeed); } } diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index 6f11ef08..6a94c2eb 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -1,14 +1,17 @@ package carpet.mixins; import carpet.helpers.TickSpeed; +import carpet.patches.CopyProfilerResult; import carpet.utils.CarpetProfiler; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerTask; -import net.minecraft.util.TickDurationMonitor; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.Util; +import net.minecraft.util.profiler.EmptyProfileResult; +import net.minecraft.util.profiler.ProfileResult; import net.minecraft.util.profiler.Profiler; import net.minecraft.util.thread.ReentrantThreadExecutor; +import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -17,6 +20,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.function.BooleanSupplier; @@ -40,20 +44,25 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec @Shadow protected abstract boolean shouldKeepTicking(); - @Shadow private long field_19248; - - @Shadow protected abstract void method_16208(); + @Shadow private long nextTickTimestamp; @Shadow private volatile boolean loading; - @Shadow protected abstract void startMonitor(TickDurationMonitor monitor); - @Shadow private long lastTimeReference; @Shadow private boolean waitingForNextTick; @Shadow public abstract Iterable getWorlds(); + @Shadow private int ticks; + + @Shadow protected abstract void runTasksTillTickEnd(); + + @Shadow protected abstract void startTickMetrics(); + + @Shadow protected abstract void endTickMetrics(); + + @Shadow private boolean needsDebugSetup; CarpetProfiler.ProfilerToken currentSection; private float carpetMsptAccum = 0.0f; @@ -115,10 +124,15 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec this.lastTimeReference = this.timeReference; } + if (this.needsDebugSetup) { + this.needsDebugSetup = false; + this.profilerTimings = Pair.of(Util.getMeasuringTimeNano(), ticks); + //this.field_33978 = new MinecraftServer.class_6414(Util.getMeasuringTimeNano(), this.ticks); + } this.timeReference += msThisTick;//50L; - TickDurationMonitor tickDurationMonitor = TickDurationMonitor.create("Server"); - this.startMonitor(tickDurationMonitor); - this.profiler.startTick(); + //TickDurationMonitor tickDurationMonitor = TickDurationMonitor.create("Server"); + //this.startMonitor(tickDurationMonitor); + this.startTickMetrics(); this.profiler.push("tick"); this.tick(TickSpeed.time_warp_start_time != 0 ? ()->true : this::shouldKeepTicking); this.profiler.swap("nextTickWait"); @@ -127,16 +141,39 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec while(this.runEveryTask()) {Thread.yield();} } this.waitingForNextTick = true; - this.field_19248 = Math.max(Util.getMeasuringTimeMs() + /*50L*/ msThisTick, this.timeReference); + this.nextTickTimestamp = Math.max(Util.getMeasuringTimeMs() + /*50L*/ msThisTick, this.timeReference); // run all tasks (this will not do a lot when warping), but that's fine since we already run them - this.method_16208(); + this.runTasksTillTickEnd(); this.profiler.pop(); - this.profiler.endTick(); + this.endTickMetrics(); this.loading = true; } } + // just because profilerTimings class is public + Pair profilerTimings = null; + /// overworld around profiler timings + @Inject(method = "isDebugRunning", at = @At("HEAD"), cancellable = true) + public void isCMDebugRunning(CallbackInfoReturnable cir) + { + cir.setReturnValue(needsDebugSetup || profilerTimings != null); + } + @Inject(method = "stopDebug", at = @At("HEAD"), cancellable = true) + public void stopCMDebug(CallbackInfoReturnable cir) + { + if (this.profilerTimings == null) { + cir.setReturnValue(EmptyProfileResult.INSTANCE); + } else { + ProfileResult profileResult = new CopyProfilerResult( + profilerTimings.getRight(), profilerTimings.getLeft(), + this.ticks, Util.getMeasuringTimeNano() + ); + this.profilerTimings = null; + cir.setReturnValue(profileResult); + } + } + private boolean runEveryTask() { if (super.runTask()) { @@ -194,12 +231,12 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec CarpetProfiler.end_current_section(currentSection); } - @Inject(method = "method_16208", at = @At("HEAD")) + @Inject(method = "runTasksTillTickEnd", at = @At("HEAD")) private void startAsync(CallbackInfo ci) { currentSection = CarpetProfiler.start_section(null, "Async Tasks", CarpetProfiler.TYPE.GENERAL); } - @Inject(method = "method_16208", at = @At( + @Inject(method = "runTasksTillTickEnd", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;runTasks(Ljava/util/function/BooleanSupplier;)V", shift = At.Shift.BEFORE diff --git a/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java b/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java index d547b313..8f563592 100644 --- a/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java +++ b/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java @@ -2,6 +2,7 @@ package carpet.mixins; import carpet.CarpetSettings; import net.minecraft.entity.SpawnGroup; +import net.minecraft.util.collection.Pool; import net.minecraft.util.math.BlockPos; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.SpawnSettings; @@ -29,7 +30,7 @@ public abstract class NoiseChunkGenerator_husksSpawnMixin extends ChunkGenerator } @Inject(method = "getEntitySpawnList", at = @At("HEAD"), cancellable = true) - private void isInsidePyramid(Biome biome, StructureAccessor accessor, SpawnGroup group, BlockPos pos, CallbackInfoReturnable> cir) + private void isInsidePyramid(Biome biome, StructureAccessor accessor, SpawnGroup group, BlockPos pos, CallbackInfoReturnable> cir) { if (CarpetSettings.huskSpawningInTemples && group == SpawnGroup.MONSTER) { diff --git a/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java b/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java new file mode 100644 index 00000000..014e1d32 --- /dev/null +++ b/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java @@ -0,0 +1,21 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.dedicated.command.PerfCommand; +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.CallbackInfoReturnable; + +@Mixin(PerfCommand.class) +public class PerfCommand_permissionMixin +{ + @SuppressWarnings("UnresolvedMixinReference") + @Inject(method = "method_37340(Lnet/minecraft/server/command/ServerCommandSource;)Z", at = @At("HEAD"), cancellable = true) + private static void canRun(ServerCommandSource source, CallbackInfoReturnable cir) + { + cir.setReturnValue(source.hasPermissionLevel(CarpetSettings.perfPermissionLevel)); + } + +} diff --git a/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java b/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java index 6cb12ded..ed77613f 100644 --- a/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java +++ b/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java @@ -1,25 +1,31 @@ package carpet.mixins; import carpet.CarpetSettings; +import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Material; +import net.minecraft.item.ItemStack; +import net.minecraft.item.MiningToolItem; import net.minecraft.item.PickaxeItem; +import net.minecraft.item.ToolMaterial; +import net.minecraft.tag.Tag; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; +//import org.spongepowered.asm.mixin.injection.At; +//import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(PickaxeItem.class) -public class PickaxeItem_missingToolsMixin +public class PickaxeItem_missingToolsMixin extends MiningToolItem { - @Redirect(method = "getMiningSpeedMultiplier", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/block/BlockState;getMaterial()Lnet/minecraft/block/Material;" - )) - private Material getCustomMaterial(BlockState blockState) - { - Material material = blockState.getMaterial(); + + protected PickaxeItem_missingToolsMixin(float attackDamage, float attackSpeed, ToolMaterial material, Tag tag, Settings settings) { + super(attackDamage, attackSpeed, material, tag, settings); + } + + @Override + public float getMiningSpeedMultiplier(ItemStack stack, BlockState state) { + Material material = state.getMaterial(); if (CarpetSettings.missingTools && material == Material.GLASS) - material = Material.STONE; - return material; + return miningSpeed; + return super.getMiningSpeedMultiplier(stack, state); } } diff --git a/src/main/java/carpet/mixins/PillagerEntity_scarpetMixin.java b/src/main/java/carpet/mixins/PillagerEntity_scarpetMixin.java deleted file mode 100644 index 66db248f..00000000 --- a/src/main/java/carpet/mixins/PillagerEntity_scarpetMixin.java +++ /dev/null @@ -1,21 +0,0 @@ -package carpet.mixins; - -import carpet.fakes.InventoryBearerInterface; -import net.minecraft.entity.mob.PillagerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(PillagerEntity.class) -public class PillagerEntity_scarpetMixin implements InventoryBearerInterface -{ - @Shadow @Final private SimpleInventory inventory; - - @Override - public Inventory getCMInventory() - { - return inventory; - } -} diff --git a/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java index 910cd16c..801e9693 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java @@ -7,6 +7,7 @@ import net.minecraft.block.entity.PistonBlockEntity; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher; import net.minecraft.client.render.block.entity.BlockEntityRenderer; +import net.minecraft.client.render.block.entity.BlockEntityRendererFactory; import net.minecraft.client.render.block.entity.PistonBlockEntityRenderer; import net.minecraft.client.util.math.MatrixStack; import org.spongepowered.asm.mixin.Mixin; @@ -16,15 +17,17 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(PistonBlockEntityRenderer.class) -public abstract class PistonBlockEntityRenderer_movableTEMixin extends BlockEntityRenderer +public abstract class PistonBlockEntityRenderer_movableTEMixin implements BlockEntityRenderer { - public PistonBlockEntityRenderer_movableTEMixin(BlockEntityRenderDispatcher blockEntityRenderDispatcher_1) + BlockEntityRenderDispatcher dispatcher; + @Inject(method = "", at = @At("TAIL")) + private void onInitCM(BlockEntityRendererFactory.Context arguments, CallbackInfo ci) { - super(blockEntityRenderDispatcher_1); + dispatcher = arguments.getRenderDispatcher(); } @Inject(method = "render", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/render/block/entity/PistonBlockEntityRenderer;method_3575(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/world/World;ZI)V", ordinal = 3)) + target = "Lnet/minecraft/client/render/block/entity/PistonBlockEntityRenderer;renderModel(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/world/World;ZI)V", ordinal = 3)) private void updateRenderBool(PistonBlockEntity pistonBlockEntity_1, float float_1, MatrixStack matrixStack_1, VertexConsumerProvider layeredVertexConsumerStorage_1, int int_1, int int_2, CallbackInfo ci) //private void updateRenderBool(PistonBlockEntity pistonBlockEntity_1, double double_1, double double_2, double double_3, float float_1, class_4587 class_4587_1, class_4597 class_4597_1, int int_1, CallbackInfo ci) { @@ -41,14 +44,14 @@ public abstract class PistonBlockEntityRenderer_movableTEMixin extends BlockEnti BlockEntity carriedBlockEntity = ((PistonBlockEntityInterface) pistonBlockEntity_1).getCarriedBlockEntity(); if (carriedBlockEntity != null) { - carriedBlockEntity.setPos(pistonBlockEntity_1.getPos()); + // maybe ??? carriedBlockEntity.setPos(pistonBlockEntity_1.getPos()); //((BlockEntityRenderDispatcherInterface) BlockEntityRenderDispatcher.INSTANCE).renderBlockEntityOffset(carriedBlockEntity, float_1, int_1, BlockRenderLayer.field_20799, bufferBuilder_1, pistonBlockEntity_1.getRenderOffsetX(float_1), pistonBlockEntity_1.getRenderOffsetY(float_1), pistonBlockEntity_1.getRenderOffsetZ(float_1)); matrixStack_1.translate( pistonBlockEntity_1.getRenderOffsetX(partialTicks), pistonBlockEntity_1.getRenderOffsetY(partialTicks), pistonBlockEntity_1.getRenderOffsetZ(partialTicks) ); - BlockEntityRenderDispatcher.INSTANCE.render(carriedBlockEntity, partialTicks, matrixStack_1, layeredVertexConsumerStorage_1); + dispatcher.render(carriedBlockEntity, partialTicks, matrixStack_1, layeredVertexConsumerStorage_1); } } diff --git a/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java index ef16df54..a8a8bacd 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java @@ -1,6 +1,7 @@ package carpet.mixins; import carpet.CarpetSettings; +import carpet.fakes.BlockEntityInterface; import carpet.fakes.PistonBlockEntityInterface; import carpet.fakes.WorldInterface; import net.minecraft.block.Block; @@ -10,7 +11,7 @@ import net.minecraft.block.Blocks; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.block.entity.PistonBlockEntity; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; @@ -32,13 +33,12 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple private BlockEntity carriedBlockEntity; private boolean renderCarriedBlockEntity = false; private boolean renderSet = false; - - public PistonBlockEntity_movableTEMixin(BlockEntityType blockEntityType_1) - { - super(blockEntityType_1); + + public PistonBlockEntity_movableTEMixin(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { + super(blockEntityType, blockPos, blockState); } - - + + /** * @author 2No2Name */ @@ -46,12 +46,23 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple { return carriedBlockEntity; } - + + @Override + public void setWorld(World world) { + super.setWorld(world); + if (carriedBlockEntity != null) carriedBlockEntity.setWorld(world); + } + public void setCarriedBlockEntity(BlockEntity blockEntity) { this.carriedBlockEntity = blockEntity; if (this.carriedBlockEntity != null) - this.carriedBlockEntity.setPos(this.pos); + { + ((BlockEntityInterface)carriedBlockEntity).setCMPos(pos); + // this might be little dangerous since pos is final for a hashing reason? + if (world != null) carriedBlockEntity.setWorld(world); + } + // this.carriedBlockEntity.setPos(this.pos); } public boolean isRenderModeSet() @@ -75,12 +86,14 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple */ @Redirect(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;I)Z")) - private boolean movableTEsetBlockState0(World world, BlockPos blockPos_1, BlockState blockAState_2, int int_1) + private static boolean movableTEsetBlockState0( + World world, BlockPos blockPos_1, BlockState blockAState_2, int int_1, + World world2, BlockPos blockPos, BlockState blockState, PistonBlockEntity pistonBlockEntity) { if (!CarpetSettings.movableBlockEntities) return world.setBlockState(blockPos_1, blockAState_2, int_1); else - return ((WorldInterface) (world)).setBlockStateWithBlockEntity(blockPos_1, blockAState_2, this.carriedBlockEntity, int_1); + return ((WorldInterface) (world)).setBlockStateWithBlockEntity(blockPos_1, blockAState_2, ((PistonBlockEntityInterface)pistonBlockEntity).getCarriedBlockEntity(), int_1); } @Redirect(method = "finish", at = @At(value = "INVOKE", @@ -115,25 +128,26 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple } } - @Inject(method = "fromTag", at = @At(value = "TAIL")) - private void onFromTag(BlockState state, CompoundTag compoundTag_1, CallbackInfo ci) + @Inject(method = "readNbt", at = @At(value = "TAIL")) + private void onFromTag(NbtCompound NbtCompound_1, CallbackInfo ci) { - if (CarpetSettings.movableBlockEntities && compoundTag_1.contains("carriedTileEntityCM", 10)) + if (CarpetSettings.movableBlockEntities && NbtCompound_1.contains("carriedTileEntityCM", 10)) { if (this.pushedBlock.getBlock() instanceof BlockEntityProvider) - this.carriedBlockEntity = ((BlockEntityProvider) (this.pushedBlock.getBlock())).createBlockEntity(this.world); + this.carriedBlockEntity = ((BlockEntityProvider) (this.pushedBlock.getBlock())).createBlockEntity(pos, pushedBlock);// this.world); if (carriedBlockEntity != null) //Can actually be null, as BlockPistonMoving.createNewTileEntity(...) returns null - this.carriedBlockEntity.fromTag(state, compoundTag_1.getCompound("carriedTileEntityCM")); + this.carriedBlockEntity.readNbt(NbtCompound_1.getCompound("carriedTileEntityCM")); + setCarriedBlockEntity(carriedBlockEntity); } } - @Inject(method = "toTag", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) - private void onToTag(CompoundTag compoundTag_1, CallbackInfoReturnable cir) + @Inject(method = "writeNbt", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) + private void onToTag(NbtCompound NbtCompound_1, CallbackInfoReturnable cir) { if (CarpetSettings.movableBlockEntities && this.carriedBlockEntity != null) { //Leave name "carriedTileEntityCM" instead of "carriedBlockEntityCM" for upgrade compatibility with 1.13.2 movable TE - compoundTag_1.put("carriedTileEntityCM", this.carriedBlockEntity.toTag(new CompoundTag())); + NbtCompound_1.put("carriedTileEntityCM", this.carriedBlockEntity.writeNbt(new NbtCompound())); } } } diff --git a/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java b/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java index e2b5f65b..bf08598f 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java @@ -8,8 +8,10 @@ import net.minecraft.block.entity.PistonBlockEntity; import net.minecraft.block.piston.PistonBehavior; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -24,16 +26,16 @@ public abstract class PistonBlockEntity_playerHandlingMixin @Shadow public abstract Direction getMovementDirection(); - @Inject(method = "method_23672", at = @At("HEAD"), cancellable = true) + @Inject(method = "moveEntity", at = @At("HEAD"), cancellable = true) private static void dontPushSpectators(Direction direction, Entity entity, double d, Direction direction2, CallbackInfo ci) { - if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).abilities.flying) ci.cancel(); + if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying) ci.cancel(); } @Redirect(method = "pushEntities", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;setVelocity(DDD)V")) - private void ignoreAccel(Entity entity, double x, double y, double z) + private static void ignoreAccel(Entity entity, double x, double y, double z) { - if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).abilities.flying) return; + if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying) return; entity.setVelocity(x,y,z); } @@ -41,15 +43,16 @@ public abstract class PistonBlockEntity_playerHandlingMixin value = "INVOKE", target = "Lnet/minecraft/entity/Entity;getPistonBehavior()Lnet/minecraft/block/piston/PistonBehavior;" )) - private PistonBehavior moveFakePlayers(Entity entity) + private static PistonBehavior moveFakePlayers(Entity entity, + World world, BlockPos blockPos, float ff, PistonBlockEntity pistonBlockEntity) { - if (entity instanceof EntityPlayerMPFake && pushedBlock.isOf(Blocks.SLIME_BLOCK)) + if (entity instanceof EntityPlayerMPFake && pistonBlockEntity.getPushedBlock().isOf(Blocks.SLIME_BLOCK)) { Vec3d vec3d = entity.getVelocity(); double e = vec3d.x; double f = vec3d.y; double g = vec3d.z; - Direction direction = getMovementDirection(); + Direction direction = pistonBlockEntity.getMovementDirection(); switch(direction.getAxis()) { case X: e = (double)direction.getOffsetX(); diff --git a/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java index 518dfb2d..23ea423a 100644 --- a/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java @@ -50,16 +50,16 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock block != Blocks.SPAWNER; } - @Redirect(method = "isMovable", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;hasBlockEntity()Z")) // hasBLockENtity - private static boolean ifHasBlockEntity(Block block) + @Redirect(method = "isMovable", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;hasBlockEntity()Z")) + private static boolean ifHasBlockEntity(BlockState blockState) { - if (!block.hasBlockEntity()) + if (!blockState.hasBlockEntity()) { return false; } else { - return !(CarpetSettings.movableBlockEntities && isPushableBlockEntity(block)); + return !(CarpetSettings.movableBlockEntities && isPushableBlockEntity(blockState.getBlock())); } } @@ -87,7 +87,7 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock for (int i = 0; i < list_1.size(); ++i) { BlockPos blockpos = list_1.get(i); - BlockEntity blockEntity = (list_2.get(i).getBlock().hasBlockEntity()) ? world_1.getBlockEntity(blockpos) : null; + BlockEntity blockEntity = (list_2.get(i).hasBlockEntity()) ? world_1.getBlockEntity(blockpos) : null; list1_BlockEntities.get().add(blockEntity); if (blockEntity != null) { @@ -101,34 +101,32 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock } @Inject(method = "move", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, - target = "Lnet/minecraft/world/World;setBlockEntity(Lnet/minecraft/util/math/BlockPos;" + - "Lnet/minecraft/block/entity/BlockEntity;)V", ordinal = 0), + target = "Lnet/minecraft/world/World;addBlockEntity(Lnet/minecraft/block/entity/BlockEntity;)V", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD) private void setBlockEntityWithCarried(World world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, CallbackInfoReturnable cir, BlockPos blockPos_2, PistonHandler pistonHandler_1, Map map_1, List list_1, List list_2, List list_3, BlockState[] blockStates_1, Direction direction_2, int int_2, - int int_3, BlockPos blockPos_4, BlockState blockState_1) + int int_3, BlockPos blockPos_4, BlockState blockState9, BlockState blockState4) { - BlockEntity blockEntityPiston = PistonExtensionBlock.createBlockEntityPiston((BlockState) list_2.get(int_3), + BlockEntity blockEntityPiston = PistonExtensionBlock.createBlockEntityPiston(blockPos_4, blockState4, (BlockState) list_2.get(int_3), direction_1, boolean_1, false); if (CarpetSettings.movableBlockEntities) ((PistonBlockEntityInterface) blockEntityPiston).setCarriedBlockEntity(list1_BlockEntities.get().get(int_3)); - world_1.setBlockEntity(blockPos_4, blockEntityPiston); + world_1.addBlockEntity(blockEntityPiston); + //world_1.setBlockEntity(blockPos_4, blockEntityPiston); } @Redirect(method = "move", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/World;setBlockEntity(Lnet/minecraft/util/math/BlockPos;" + - "Lnet/minecraft/block/entity/BlockEntity;)V", + target = "Lnet/minecraft/world/World;addBlockEntity(Lnet/minecraft/block/entity/BlockEntity;)V", ordinal = 0)) - private void dontDoAnything(World world, BlockPos blockPos_6, BlockEntity blockEntityPiston) + private void dontDoAnything(World world, BlockEntity blockEntity) { } @Redirect(method = "move", at = @At(value = "INVOKE", - target = "Lnet/minecraft/block/PistonExtensionBlock;createBlockEntityPiston(Lnet/minecraft/block/BlockState;" + - "Lnet/minecraft/util/math/Direction;ZZ)Lnet/minecraft/block/entity/BlockEntity;", + target = "Lnet/minecraft/block/PistonExtensionBlock;createBlockEntityPiston(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/Direction;ZZ)Lnet/minecraft/block/entity/BlockEntity;", ordinal = 0)) - private BlockEntity returnNull(BlockState blockState_1, Direction direction_1, boolean boolean_1, boolean boolean_2) + private BlockEntity returnNull(BlockPos blockPos, BlockState blockState, BlockState blockState2, Direction direction, boolean bl, boolean bl2) { return null; } diff --git a/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java b/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java index b262f9cc..a251f251 100644 --- a/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java +++ b/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java @@ -39,21 +39,19 @@ public abstract class PistonHandler_customStickyMixin @Shadow @Final private World world; @Shadow @Final private Direction motionDirection; @Shadow protected abstract boolean tryMove(BlockPos blockPos_1, Direction direction_1); - @Shadow private static boolean isBlockSticky(Block block_1) { return false; } - @Shadow private static boolean isAdjacentBlockStuck(Block block, Block block2) {return false;} - @Shadow protected abstract boolean canMoveAdjacentBlock(BlockPos pos); + @Shadow private static boolean isBlockSticky(BlockState block_1) { return false; } + @Shadow private static boolean isAdjacentBlockStuck(BlockState block, BlockState block2) {return false;} + @Shadow protected abstract boolean tryMoveAdjacentBlock(BlockPos pos); // collects information about sticking block when backtracking. private BlockPos currentPos; private BlockState currentState; - private BlockState previousState; @Redirect(method = "tryMove", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;", ordinal = 0)) private BlockState redirectGetBlockState_1_A(World world, BlockPos pos) { - return currentState = previousState = world.getBlockState(pos); + return currentState = world.getBlockState(pos); } @Redirect(method = "tryMove", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;", ordinal = 1)) private BlockState redirectGetBlockState_1_B(World world, BlockPos pos) { - previousState = currentState; currentPos = pos; return currentState = world.getBlockState(pos); } @@ -64,13 +62,13 @@ public abstract class PistonHandler_customStickyMixin */ @Redirect(method = "tryMove", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isBlockSticky(Lnet/minecraft/block/Block;)Z", + target = "Lnet/minecraft/block/piston/PistonHandler;isBlockSticky(Lnet/minecraft/block/BlockState;)Z", ordinal = 0 ) ) - private boolean redirectIsStickyBlock(Block block_1) + private boolean redirectIsStickyBlock(BlockState blockState) { // applies to both MBE chests as well as sticky chains - return blockCanBePulled(currentState) || isBlockSticky(block_1); + return blockCanBePulled(blockState) || isBlockSticky(blockState); } /** @@ -107,17 +105,17 @@ public abstract class PistonHandler_customStickyMixin */ @Redirect(method = "tryMove", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/Block;Lnet/minecraft/block/Block;)Z") + target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)Z") ) - private boolean isDraggingPreviousBlockBehind(Block previous, Block next) + private boolean isDraggingPreviousBlockBehind(BlockState previous, BlockState next) { if (CarpetSettings.doChainStone) { - if (previousState.getBlock() == Blocks.CHAIN && isChainOnAxis(previousState, motionDirection)) + if (previous.getBlock() == Blocks.CHAIN && isChainOnAxis(previous, motionDirection)) { - if ( (currentState.getBlock() == Blocks.CHAIN && isChainOnAxis(currentState, motionDirection)) + if ( (next.getBlock() == Blocks.CHAIN && isChainOnAxis(next, motionDirection)) || CarpetSettings.chainStoneStickToAll - || isEndRodOnAxis(currentState, motionDirection.getAxis()) + || isEndRodOnAxis(next, motionDirection.getAxis()) || Block.sideCoversSmallSquare(world, currentPos, motionDirection)) { return true; @@ -138,7 +136,7 @@ public abstract class PistonHandler_customStickyMixin target = "Ljava/util/List;get(I)Ljava/lang/Object;", shift = At.Shift.AFTER )) - private void stickToStickySide(BlockPos blockPos_1, Direction direction_1, CallbackInfoReturnable cir, BlockState blockState_1, Block block_1, int int_1, int int_2, int int_4, BlockPos blockPos_3, int int_5, int int_6) + private void stickToStickySide(BlockPos blockPos_1, Direction direction_1, CallbackInfoReturnable cir, BlockState blockState_1, int int_1, int int_2, int int_4, BlockPos blockPos_3, int int_5, int int_6) { if (CarpetSettings.movableBlockEntities) { @@ -171,7 +169,7 @@ public abstract class PistonHandler_customStickyMixin BlockState chainState = world.getBlockState(pos); // chain is sideways if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, motionDirection) - && !this.canMoveAdjacentBlock(pos)) + && !this.tryMoveAdjacentBlock(pos)) { cir.setReturnValue(false); } @@ -198,7 +196,7 @@ public abstract class PistonHandler_customStickyMixin // stickyDirection = blockState_1.get(FacingBlock.FACING); //} - return stickyDirection == null || this.tryMove(blockPos_1.offset(stickyDirection), stickyDirection); + return stickyDirection == null || this.tryMove(blockPos_1.offset(stickyDirection), stickyDirection); //offset } @@ -208,18 +206,18 @@ public abstract class PistonHandler_customStickyMixin */ @Inject(method = "tryMove", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at= @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isBlockSticky(Lnet/minecraft/block/Block;)Z", + target = "Lnet/minecraft/block/piston/PistonHandler;isBlockSticky(Lnet/minecraft/block/BlockState;)Z", ordinal = 1, shift = At.Shift.BEFORE ) ) private void redirectIsStickyBlock(BlockPos pos, Direction dir, CallbackInfoReturnable cir, - BlockState blockState, Block block, int i, int j, int l, BlockPos blockPos2, int m, int n, BlockPos blockPos3) + BlockState blockState, int i, int j, int l, BlockPos blockPos2, int m, int n, BlockPos blockPos3) { if (CarpetSettings.doChainStone) { BlockState chainState = world.getBlockState(blockPos3); - if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, motionDirection) && !canMoveAdjacentBlock(blockPos3)) + if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, motionDirection) && !tryMoveAdjacentBlock(blockPos3)) { cir.setReturnValue(false); } @@ -230,9 +228,9 @@ public abstract class PistonHandler_customStickyMixin /** * Custom movement of blocks stuck to the sides of blocks other than slimeblocks like chains */ - @Inject(method = "canMoveAdjacentBlock", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( + @Inject(method = "tryMoveAdjacentBlock", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/Block;Lnet/minecraft/block/Block;)Z", + target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)Z", shift = At.Shift.BEFORE )) private void otherSideStickyCases(BlockPos pos, CallbackInfoReturnable cir, @@ -266,11 +264,11 @@ public abstract class PistonHandler_customStickyMixin * @param block2 * @return */ - @Redirect(method = "canMoveAdjacentBlock", at = @At( + @Redirect(method = "tryMoveAdjacentBlock", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/Block;Lnet/minecraft/block/Block;)Z") + target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)Z") ) - private boolean isStuckSlimeStone(Block block, Block block2) + private boolean isStuckSlimeStone(BlockState block, BlockState block2) { return isBlockSticky(block2) && isAdjacentBlockStuck(block, block2); } diff --git a/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java b/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java index 2b5456be..d0e51b81 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java @@ -23,7 +23,7 @@ public abstract class PlayerEntity_creativeNoClipMixin extends LivingEntity ) private boolean canClipTroughWorld(PlayerEntity playerEntity) { - return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.abilities.flying); + return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.getAbilities().flying); } @@ -33,15 +33,15 @@ public abstract class PlayerEntity_creativeNoClipMixin extends LivingEntity ) private boolean collidesWithEntities(PlayerEntity playerEntity) { - return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.abilities.flying); + return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.getAbilities().flying); } - @Redirect(method = "updateSize", at = @At( + @Redirect(method = "updatePose", at = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;isSpectator()Z") ) private boolean spectatorsDontPose(PlayerEntity playerEntity) { - return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.abilities.flying); + return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.getAbilities().flying); } } diff --git a/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java b/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java index 5dd06a2f..48118e7c 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java @@ -6,7 +6,7 @@ import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.player.PlayerAbilities; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -24,15 +24,15 @@ public abstract class PlayerEntity_parrotMixin extends LivingEntity @Shadow protected abstract void dropShoulderEntities(); - @Shadow public abstract CompoundTag getShoulderEntityLeft(); + @Shadow public abstract NbtCompound getShoulderEntityLeft(); - @Shadow protected abstract void setShoulderEntityLeft(CompoundTag compoundTag_1); + @Shadow protected abstract void setShoulderEntityLeft(NbtCompound NbtCompound_1); - @Shadow protected abstract void setShoulderEntityRight(CompoundTag compoundTag_1); + @Shadow protected abstract void setShoulderEntityRight(NbtCompound NbtCompound_1); - @Shadow public abstract CompoundTag getShoulderEntityRight(); + @Shadow public abstract NbtCompound getShoulderEntityRight(); - @Shadow protected abstract void dropShoulderEntity(CompoundTag entityNbt); + @Shadow protected abstract void dropShoulderEntity(NbtCompound entityNbt); protected PlayerEntity_parrotMixin(EntityType entityType_1, World world_1) { @@ -47,7 +47,7 @@ public abstract class PlayerEntity_parrotMixin extends LivingEntity } @Inject(method = "tickMovement", at = @At(value = "INVOKE", shift = At.Shift.AFTER, ordinal = 1, - target = "Lnet/minecraft/entity/player/PlayerEntity;updateShoulderEntity(Lnet/minecraft/nbt/CompoundTag;)V")) + target = "Lnet/minecraft/entity/player/PlayerEntity;updateShoulderEntity(Lnet/minecraft/nbt/NbtCompound;)V")) private void onTickMovement(CallbackInfo ci) { boolean parrots_will_drop = !CarpetSettings.persistentParrots || this.abilities.invulnerable; @@ -67,13 +67,13 @@ public abstract class PlayerEntity_parrotMixin extends LivingEntity protected void dismount_left() { dropShoulderEntity(this.getShoulderEntityLeft()); - this.setShoulderEntityLeft(new CompoundTag()); + this.setShoulderEntityLeft(new NbtCompound()); } protected void dismount_right() { dropShoulderEntity(this.getShoulderEntityRight()); - this.setShoulderEntityRight(new CompoundTag()); + this.setShoulderEntityRight(new NbtCompound()); } @Inject(method = "damage", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, diff --git a/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java index 9ac76586..999105bb 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java @@ -8,14 +8,19 @@ import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.ActionResult; +import net.minecraft.util.Hand; import net.minecraft.world.World; 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; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; +import static carpet.script.CarpetEventServer.Event.PLAYER_ATTACKS_ENTITY; import static carpet.script.CarpetEventServer.Event.PLAYER_DEALS_DAMAGE; +import static carpet.script.CarpetEventServer.Event.PLAYER_INTERACTS_WITH_ENTITY; import static carpet.script.CarpetEventServer.Event.PLAYER_TAKES_DAMAGE; import static carpet.script.CarpetEventServer.Event.PLAYER_COLLIDES_WITH_ENTITY; @@ -53,4 +58,22 @@ public abstract class PlayerEntity_scarpetEventsMixin extends LivingEntity PLAYER_COLLIDES_WITH_ENTITY.onEntityHandAction((ServerPlayerEntity)(Object)this, entity, null); } } + + @Inject(method = "interact", at = @At("HEAD")) + private void doInteract(Entity entity, Hand hand, CallbackInfoReturnable cir) + { + if (!world.isClient && PLAYER_INTERACTS_WITH_ENTITY.isNeeded()) + { + PLAYER_INTERACTS_WITH_ENTITY.onEntityHandAction((ServerPlayerEntity) (Object)this, entity, hand); + } + } + + @Inject(method = "attack", at = @At("HEAD")) + private void onAttack(Entity target, CallbackInfo ci) + { + if (!world.isClient && PLAYER_ATTACKS_ENTITY.isNeeded() && target.isAttackable()) + { + PLAYER_ATTACKS_ENTITY.onEntityHandAction((ServerPlayerEntity) (Object)this, target, null); + } + } } diff --git a/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java b/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java index 1b5f6be8..bd1f3733 100644 --- a/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import com.mojang.authlib.GameProfile; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.network.ClientConnection; import net.minecraft.text.TranslatableText; import net.minecraft.server.MinecraftServer; @@ -31,7 +31,7 @@ public abstract class PlayerManager_fakePlayersMixin private MinecraftServer server; @Inject(method = "loadPlayerData", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) - private void fixStartingPos(ServerPlayerEntity serverPlayerEntity_1, CallbackInfoReturnable cir) + private void fixStartingPos(ServerPlayerEntity serverPlayerEntity_1, CallbackInfoReturnable cir) { if (serverPlayerEntity_1 instanceof EntityPlayerMPFake) { diff --git a/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java index 195dad23..2c63ef02 100644 --- a/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java @@ -21,7 +21,11 @@ public class PlayerManager_scarpetEventsMixin PLAYER_RESPAWNS.onPlayerEvent(player); } - @Inject(method = "respawnPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;onSpawn()V")) + @Inject(method = "respawnPlayer", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/server/network/ServerPlayerEntity;onSpawn()V" + //target = "Lnet/minecraft/server/network/ServerPlayerEntity;method_34225()V" + )) private void invalidatePreviousInstance(ServerPlayerEntity player, boolean alive, CallbackInfoReturnable cir) { ((ServerPlayerEntityInterface)player).invalidateEntityObjectReference(); diff --git a/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java b/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java index bf460603..ef5a8644 100644 --- a/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java +++ b/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java @@ -18,6 +18,6 @@ public class ReloadCommand_reloadAppsMixin { private static void onReload(CommandContext context, CallbackInfoReturnable cir) { // can't fetch here the reference to the server - CarpetServer.onReload(context.getSource().getMinecraftServer()); + CarpetServer.onReload(context.getSource().getServer()); } } diff --git a/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java b/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java index a7506dde..78cd63dc 100644 --- a/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java @@ -3,10 +3,11 @@ package carpet.mixins; import net.minecraft.scoreboard.ScoreboardCriterion; import net.minecraft.scoreboard.ScoreboardObjective; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(ScoreboardObjective.class) public interface ScoreboardObjective_scarpetMixin { - @Accessor("criterion") + @Mutable @Accessor("criterion") void setCriterion(ScoreboardCriterion criterion); } diff --git a/src/main/java/carpet/mixins/ServerChunkManagerMixin.java b/src/main/java/carpet/mixins/ServerChunkManagerMixin.java index c8bfcd21..3f2edb09 100644 --- a/src/main/java/carpet/mixins/ServerChunkManagerMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkManagerMixin.java @@ -77,7 +77,7 @@ public abstract class ServerChunkManagerMixin implements ServerChunkManagerInter int spawnTries = SpawnReporter.spawn_tries.get(cat); if (!SpawnReporter.local_spawns.containsKey(cat)) { - if (!cat.isAnimal() || boolean_3) + if (!cat.isRare() || boolean_3) // isAnimal { // fill mobcaps for that category so spawn got cancelled SpawnReporter.spawn_ticks_full.put(key, diff --git a/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java b/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java new file mode 100644 index 00000000..bdf7327e --- /dev/null +++ b/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java @@ -0,0 +1,51 @@ +package carpet.mixins; + +import carpet.script.CarpetEventServer; +import carpet.script.CarpetScriptServer; +import net.minecraft.entity.Entity; +import net.minecraft.server.world.ServerEntityManager; +import net.minecraft.world.entity.EntityLike; +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.CallbackInfoReturnable; + +@Mixin(ServerEntityManager.class) +public class ServerEntityManager_scarpetMixin +{ + @Inject(method = "addEntity(Lnet/minecraft/world/entity/EntityLike;Z)Z", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/entity/EntityTrackingStatus;shouldTick()Z" + )) + private void handleAddedEntity(EntityLike entityLike, boolean existing, CallbackInfoReturnable cir) + { + Entity entity = (Entity)entityLike; + CarpetEventServer.Event event = CarpetEventServer.Event.ENTITY_HANDLER.get(entity.getType()); + if (event != null) + { + if (event.isNeeded()) + { + event.onEntityAction(entity, !existing); + } + } + else + { + CarpetScriptServer.LOG.error("Failed to handle entity type " + entity.getType().getTranslationKey()); + } + + event = CarpetEventServer.Event.ENTITY_LOAD.get(entity.getType()); + if (event != null) + { + if (event.isNeeded()) + { + event.onEntityAction(entity, true); + } + } + else + { + CarpetScriptServer.LOG.error("Failed to handle entity type " + entity.getType().getTranslationKey()); + } + + } + +} diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java index 33fdb428..812906b3 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java @@ -51,7 +51,7 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin { @Shadow public ServerPlayerEntity player; - @Inject(method = "onPlayerInput", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;method_14218(FFZZ)V")) + @Inject(method = "onPlayerInput", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;updateInput(FFZZ)V")) private void checkMoves(PlayerInputC2SPacket p, CallbackInfo ci) { if (PLAYER_RIDES.isNeeded() && (p.getSideways() != 0.0F || p.getForward() != 0.0F || p.isJumping() || p.isSneaking())) @@ -62,7 +62,7 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin @Inject(method = "onPlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;dropSelectedItem(Z)Z", + target = "Lnet/minecraft/server/network/ServerPlayerEntity;dropSelectedItem(Z)Z", // dropSelectedItem ordinal = 0, shift = At.Shift.BEFORE )) @@ -84,7 +84,7 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin @Inject(method = "onPlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;dropSelectedItem(Z)Z", + target = "Lnet/minecraft/server/network/ServerPlayerEntity;dropSelectedItem(Z)Z", // dropSelectedItem ordinal = 1, shift = At.Shift.BEFORE )) @@ -225,16 +225,16 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin PLAYER_DEPLOYS_ELYTRA.onPlayerEvent(player); } - @Inject(method = "onPlayerInteractEntity", at = @At( + /*@Inject(method = "onPlayerInteractEntity", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;interact(Lnet/minecraft/entity/Entity;Lnet/minecraft/util/Hand;)Lnet/minecraft/util/ActionResult;" )) private void onEntityInteract(PlayerInteractEntityC2SPacket playerInteractEntityC2SPacket_1, CallbackInfo ci) { PLAYER_INTERACTS_WITH_ENTITY.onEntityHandAction(player, playerInteractEntityC2SPacket_1.getEntity(player.getServerWorld()), playerInteractEntityC2SPacket_1.getHand()); - } + }*/ - @Inject(method = "onPlayerInteractEntity", at = @At( + /*@Inject(method = "onPlayerInteractEntity", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;attack(Lnet/minecraft/entity/Entity;)V" )) @@ -242,7 +242,7 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin { //todo add hit and hand in the future PLAYER_ATTACKS_ENTITY.onEntityHandAction(player, playerInteractEntityC2SPacket_1.getEntity(player.getServerWorld()), null); - } + }*/ @Inject(method = "onButtonClick", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;updateLastActionTime()V")) private void onItemBeingPickedFromInventory(ButtonClickC2SPacket packet, CallbackInfo ci) @@ -264,7 +264,7 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin { if (PLAYER_SWITCHES_SLOT.isNeeded() && player.getServer() != null && player.getServer().isOnThread()) { - PLAYER_SWITCHES_SLOT.onSlotSwitch(player, player.inventory.selectedSlot, packet.getSelectedSlot()); + PLAYER_SWITCHES_SLOT.onSlotSwitch(player, player.getInventory().selectedSlot, packet.getSelectedSlot()); } } diff --git a/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java b/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java index 5fa840f3..24acee10 100644 --- a/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java @@ -27,7 +27,6 @@ public abstract class ServerPlayerEntityMixin implements ServerPlayerEntityInter MinecraftServer minecraftServer_1, ServerWorld serverWorld_1, GameProfile gameProfile_1, - ServerPlayerInteractionManager serverPlayerInteractionManager_1, CallbackInfo ci) { this.actionPack = new EntityPlayerActionPack((ServerPlayerEntity) (Object) this); diff --git a/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java index 06396698..6ef2e4e0 100644 --- a/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java @@ -82,7 +82,7 @@ public abstract class ServerPlayerEntity_scarpetEventMixin extends PlayerEntity } } - @Redirect(method = "method_14218", at = @At( + @Redirect(method = "updateInput", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;setSneaking(Z)V" )) diff --git a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java index 559fbc91..d7ce33b2 100644 --- a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java @@ -75,6 +75,6 @@ public class ServerPlayerInteractionManager_scarpetEventsMixin implements Server public void setBlockBreakingProgress(int progress) { blockBreakingProgress = MathHelper.clamp(progress, -1, 10); - world.setBlockBreakingInfo(-1*this.player.getEntityId(), miningPos, blockBreakingProgress); + world.setBlockBreakingInfo(-1*this.player.getId(), miningPos, blockBreakingProgress); } } diff --git a/src/main/java/carpet/mixins/ServerWorld_fakePlayersMixin.java b/src/main/java/carpet/mixins/ServerWorld_fakePlayersMixin.java index 352c1622..3e6f97bf 100644 --- a/src/main/java/carpet/mixins/ServerWorld_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_fakePlayersMixin.java @@ -14,8 +14,9 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(ServerWorld.class) public abstract class ServerWorld_fakePlayersMixin { - @Shadow /*@Nonnull*/ public abstract MinecraftServer getServer(); + @Shadow /*@Nonnull*/ public abstract MinecraftServer getServer(); +/* @Shadow private boolean inEntityTick; @Redirect( method = "removePlayer", at = @At( @@ -24,7 +25,7 @@ public abstract class ServerWorld_fakePlayersMixin )) private void crashRemovePlayer(ServerWorld serverWorld, Entity entity_1, ServerPlayerEntity serverPlayerEntity_1) { - if ( !(inEntityTick && serverPlayerEntity_1 instanceof EntityPlayerMPFake) ) + if ( !(serverPlayerEntity_1 instanceof EntityPlayerMPFake) ) serverWorld.removeEntity(entity_1); else getServer().send(new ServerTask(getServer().getTicks(), () -> @@ -33,5 +34,5 @@ public abstract class ServerWorld_fakePlayersMixin serverPlayerEntity_1.onTeleportationDone(); })); - } + }*/ } diff --git a/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java b/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java index 32f8a630..6d2d6fab 100644 --- a/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java @@ -17,7 +17,7 @@ import java.util.stream.Stream; @Mixin(ServerWorld.class) public class ServerWorld_onePlayerSleepingMixin -{ +{/* removed due to 1.17 changes @Shadow @Final private List players; @Shadow private boolean allPlayersSleeping; @@ -49,5 +49,5 @@ public class ServerWorld_onePlayerSleepingMixin return stream.anyMatch((p) -> !p.isSpectator() && p.isSleepingLongEnough()); return stream.noneMatch(predicate); } - +*/ } diff --git a/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java b/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java index b8edea11..cb5277ed 100644 --- a/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java @@ -4,13 +4,16 @@ import carpet.CarpetSettings; import carpet.fakes.ServerWorldInterface; import carpet.script.CarpetEventServer; import net.minecraft.entity.Entity; +import net.minecraft.world.entity.EntityLike; import net.minecraft.entity.LightningEntity; import net.minecraft.entity.damage.DamageSource; +import net.minecraft.server.world.ServerEntityManager; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.profiler.Profiler; import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.world.entity.EntityLookup; import net.minecraft.world.explosion.Explosion; import net.minecraft.world.explosion.ExplosionBehavior; import net.minecraft.world.level.ServerWorldProperties; @@ -19,12 +22,11 @@ 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; -import static carpet.script.CarpetEventServer.Event.ENTITY_HANDLER; -import static carpet.script.CarpetEventServer.Event.ENTITY_LOAD; import static carpet.script.CarpetEventServer.Event.EXPLOSION; import static carpet.script.CarpetEventServer.Event.LIGHTNING; @@ -44,51 +46,29 @@ public class ServerWorld_scarpetMixin implements ServerWorldInterface if (LIGHTNING.isNeeded()) LIGHTNING.onWorldEventFlag((ServerWorld) (Object)this, blockPos, bl2?1:0); } - - private ThreadLocal entityJustLoaded = ThreadLocal.withInitial(() -> false); - - @Inject(method = "loadEntityUnchecked", at = @At( + /* + moved to ServerEntityManager_scarpetMixin in 1.17 + @Redirect(method = "addEntity", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerChunkManager;loadEntity(Lnet/minecraft/entity/Entity;)V" + target = "Lnet/minecraft/server/world/ServerEntityManager;addEntity(Lnet/minecraft/world/entity/EntityLike;)Z" )) - private void onEntityAddedToWorld(Entity entity, CallbackInfo ci) + private boolean onEntityAddedToWorld(ServerEntityManager serverEntityManager, EntityLike entityLike) { - boolean justLoaded = entityJustLoaded.get(); - entityJustLoaded.set(false); - CarpetEventServer.Event event = ENTITY_HANDLER.get(entity.getType()); - if (event != null) - { - if (event.isNeeded()) - { - event.onEntityAction(entity, !justLoaded); + Entity entity = (Entity)entityLike; + boolean success = serverEntityManager.addEntity(entity); + if (success) { + CarpetEventServer.Event event = ENTITY_LOAD.get(entity.getType()); + if (event != null) { + if (event.isNeeded()) { + event.onEntityAction(entity); + } + } else { + CarpetSettings.LOG.error("Failed to handle entity " + entity.getType().getTranslationKey()); } - } - else - { - CarpetSettings.LOG.error("Failed to handle entity "+entity.getType().getTranslationKey()); - } - - // deprecated usage - event = ENTITY_LOAD.get(entity.getType()); - if (event != null) - { - if (event.isNeeded()) - { - event.onEntityAction(entity, true); - } - } - else - { - CarpetSettings.LOG.error("Failed to handle entity "+entity.getType().getTranslationKey()); - } - } - - // 1.16only - @Inject(method = "loadEntity", at= @At("HEAD")) - private void onSideLoaded(Entity entity, CallbackInfoReturnable cir) - { - entityJustLoaded.set(true); + }; + return success; } + */ @Inject(method = "createExplosion", at = @At("HEAD")) private void handleExplosion(/*@Nullable*/ Entity entity, /*@Nullable*/ DamageSource damageSource, /*@Nullable*/ ExplosionBehavior explosionBehavior, double d, double e, double f, float g, boolean bl, Explosion.DestructionType destructionType, CallbackInfoReturnable cir) @@ -100,7 +80,14 @@ public class ServerWorld_scarpetMixin implements ServerWorldInterface @Final @Shadow private ServerWorldProperties worldProperties; + @Shadow @Final private ServerEntityManager entityManager; + public ServerWorldProperties getWorldPropertiesCM(){ return worldProperties; } + + @Override + public EntityLookup getEntityLookupCMPublic() { + return entityManager.getLookup(); + } } diff --git a/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java b/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java index d3deec9c..f662c1c3 100644 --- a/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java @@ -18,7 +18,7 @@ public class ShulkerBoxBlockEntity_creativeNoClipMixin )) private PistonBehavior getPistonBehaviourOfNoClipPlayers(Entity entity) { - if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).abilities.flying) + if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying) return PistonBehavior.IGNORE; return entity.getPistonBehavior(); } diff --git a/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java b/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java new file mode 100644 index 00000000..eeb85747 --- /dev/null +++ b/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java @@ -0,0 +1,28 @@ +package carpet.mixins; + +import carpet.fakes.SimpleEntityLookupInterface; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.entity.EntityLike; +import net.minecraft.world.entity.EntityTrackingSection; +import net.minecraft.world.entity.SectionedEntityCache; +import net.minecraft.world.entity.SimpleEntityLookup; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.List; +import java.util.stream.Collectors; + +@Mixin(SimpleEntityLookup.class) +public class SimpleEntityLookup_scarpetMixin implements SimpleEntityLookupInterface +{ + + @Shadow @Final private SectionedEntityCache cache; + + @Override + public List getChunkEntities(ChunkPos chpos) { + return this.cache.getTrackingSections(chpos.toLong()).flatMap(EntityTrackingSection::stream).collect(Collectors.toList()); + } +} + + diff --git a/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java index bf6bdc07..cf4d0543 100644 --- a/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java @@ -88,18 +88,26 @@ public abstract class SkyLightStorage_scarpetChunkCreationMixin extends LightSto final int dx = Math.abs(dir.getOffsetZ()); final int dz = Math.abs(dir.getOffsetX()); + int emptyLightLevel = (neighborCeilingLightArray == null) + ? (this.isSectionEnabled(ChunkSectionPos.withZeroY(neighborCeilingSectionPos)) ? 0 : 15) + : 0; + int neighbourY = (neighborLightArray == null) + ? ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackY(neighborCeilingSectionPos)) + : 0; + 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); long src = BlockPos.offset(dst, dir); - if (neighborLightArray == null) - src = BlockPos.asLong(BlockPos.unpackLongX(src), ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackY(neighborCeilingSectionPos)), BlockPos.unpackLongZ(src)); + long adj_src = (neighborLightArray != null) + ? src + : BlockPos.asLong(BlockPos.unpackLongX(src), neighbourY, BlockPos.unpackLongZ(src)); - final int srcLevel = neighborCeilingLightArray != null ? - ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborCeilingLightArray, src) - : this.isSectionEnabled(ChunkSectionPos.withZeroY(neighborCeilingSectionPos)) ? 0 : 15; + final int srcLevel = neighborCeilingLightArray != null + ? ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborCeilingLightArray, adj_src) + : emptyLightLevel; levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); } diff --git a/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java new file mode 100644 index 00000000..557ea506 --- /dev/null +++ b/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java @@ -0,0 +1,31 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import carpet.helpers.InventoryHelper; +import net.minecraft.block.ShulkerBoxBlock; +import net.minecraft.item.BlockItem; +import net.minecraft.item.ItemStack; +import net.minecraft.screen.slot.Slot; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(Slot.class) +public class Slot_stackableSBoxesMixin { + @Redirect(method = "insertStack(Lnet/minecraft/item/ItemStack;I)Lnet/minecraft/item/ItemStack;", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/screen/slot/Slot;getMaxItemCount(Lnet/minecraft/item/ItemStack;)I" + )) + private int getMaxCountForSboxes(Slot slot, ItemStack stack) + { + if (CarpetSettings.stackableShulkerBoxes && + stack.getItem() instanceof BlockItem && + ((BlockItem)stack.getItem()).getBlock() instanceof ShulkerBoxBlock && + !InventoryHelper.shulkerBoxHasItems(stack) + ) + { + return CarpetSettings.SHULKER_STACK_SIZE; + } + return slot.getMaxItemCount(stack); + } +} diff --git a/src/main/java/carpet/mixins/SpawnHelperMixin.java b/src/main/java/carpet/mixins/SpawnHelperMixin.java index edfb9500..f97cf954 100644 --- a/src/main/java/carpet/mixins/SpawnHelperMixin.java +++ b/src/main/java/carpet/mixins/SpawnHelperMixin.java @@ -13,7 +13,7 @@ import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnReason; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.server.world.ServerWorld; import net.minecraft.tag.BlockTags; import net.minecraft.util.math.BlockPos; @@ -117,8 +117,8 @@ public class SpawnHelperMixin BlockState state = world.getBlockState(blockpos); Block block = state.getBlock(); if ( - block.isIn(BlockTags.FENCES) || - block.isIn(BlockTags.WALLS) || + state.isIn(BlockTags.FENCES) || + state.isIn(BlockTags.WALLS) || ((block instanceof FenceGateBlock) && !state.get(FenceGateBlock.OPEN)) ) { @@ -175,9 +175,9 @@ public class SpawnHelperMixin @Redirect(method = "spawnEntitiesInChunk(Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/SpawnHelper$Checker;Lnet/minecraft/world/SpawnHelper$Runner;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/mob/MobEntity;initialize(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/world/LocalDifficulty;Lnet/minecraft/entity/SpawnReason;Lnet/minecraft/entity/EntityData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/entity/EntityData;" + target = "Lnet/minecraft/entity/mob/MobEntity;initialize(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/world/LocalDifficulty;Lnet/minecraft/entity/SpawnReason;Lnet/minecraft/entity/EntityData;Lnet/minecraft/nbt/NbtCompound;)Lnet/minecraft/entity/EntityData;" )) - private static EntityData spawnEntity(MobEntity mobEntity, ServerWorldAccess serverWorldAccess, LocalDifficulty difficulty, SpawnReason spawnReason, EntityData entityData, CompoundTag entityTag) + private static EntityData spawnEntity(MobEntity mobEntity, ServerWorldAccess serverWorldAccess, LocalDifficulty difficulty, SpawnReason spawnReason, EntityData entityData, NbtCompound entityTag) { if (!SpawnReporter.mock_spawns) // WorldAccess return mobEntity.initialize(serverWorldAccess, difficulty, spawnReason, entityData, entityTag); @@ -279,7 +279,7 @@ public class SpawnHelperMixin for(int var8 = 0; var8 < var7; ++var8) { SpawnGroup entityCategory = var6[var8]; - if ((spawnAnimals || !entityCategory.isPeaceful()) && (spawnMonsters || entityCategory.isPeaceful()) && (shouldSpawnAnimals || !entityCategory.isAnimal()) ) + if ((spawnAnimals || !entityCategory.isPeaceful()) && (spawnMonsters || entityCategory.isPeaceful()) && (shouldSpawnAnimals || !entityCategory.isRare()) ) { RegistryKey dim = world.getRegistryKey(); // getDimensionType; int newCap = (int) ((double)entityCategory.getCapacity()*(Math.pow(2.0,(SpawnReporter.mobcap_exponent/4)))); diff --git a/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java b/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java index 5ef599e9..f328921e 100644 --- a/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java +++ b/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java @@ -6,7 +6,7 @@ import carpet.script.value.Value; import carpet.script.value.ValueConversions; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.state.property.Property; import net.minecraft.tag.Tag; import org.spongepowered.asm.mixin.Final; @@ -23,7 +23,7 @@ public class StatePredicate_scarpetMixin implements BlockPredicateInterface @Shadow @Final private BlockState state; - @Shadow @Final /*@Nullable*/ private CompoundTag nbt; + @Shadow @Final /*@Nullable*/ private NbtCompound nbt; @Shadow @Final private Set> properties; @@ -50,7 +50,7 @@ public class StatePredicate_scarpetMixin implements BlockPredicateInterface } @Override - public CompoundTag getCMDataTag() + public NbtCompound getCMDataTag() { return nbt; } diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java new file mode 100644 index 00000000..57cf46c6 --- /dev/null +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java @@ -0,0 +1,21 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.block.entity.StructureBlockBlockEntity; +import net.minecraft.client.render.block.entity.BlockEntityRenderer; +import net.minecraft.client.render.block.entity.StructureBlockBlockEntityRenderer; +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.CallbackInfoReturnable; + +@Mixin(StructureBlockBlockEntityRenderer.class) +public abstract class StructureBlockBlockEntityRenderer_mixin implements BlockEntityRenderer +{ + @Inject(method = "getRenderDistance", at = @At("HEAD"), cancellable = true) + void newLimit(CallbackInfoReturnable cir) + { + if (CarpetSettings.structureBlockOutlineDistance != 96) + cir.setReturnValue(CarpetSettings.structureBlockOutlineDistance); + } +} diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java index e660c97a..b7279ace 100644 --- a/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java @@ -17,15 +17,15 @@ public abstract class StructureBlockBlockEntity_fillUpdatesMixin { @Redirect(method = "place", at = @At( value = "INVOKE", - target = "Lnet/minecraft/structure/Structure;place(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/structure/StructurePlacementData;Ljava/util/Random;)V" + target = "Lnet/minecraft/structure/Structure;place(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/structure/StructurePlacementData;Ljava/util/Random;I)Z" )) - private void onStructurePlacen(Structure structure, ServerWorldAccess serverWorldAccess, BlockPos pos, StructurePlacementData placementData, Random random) + private boolean onStructurePlacen(Structure structure, ServerWorldAccess serverWorldAccess, BlockPos pos, BlockPos blockPos, StructurePlacementData placementData, Random random, int i) { if(!CarpetSettings.fillUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); try { - structure.place(serverWorldAccess, pos, placementData, random); + return structure.place(serverWorldAccess, pos, blockPos, placementData, random, i); // serverWorldAccess, pos, placementData, random); } finally { diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java index c676ae56..8ff19855 100644 --- a/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java @@ -15,7 +15,7 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant; public abstract class StructureBlockBlockEntity_limitsMixin { @ModifyConstant( - method = "fromTag", + method = "readNbt", constant = @Constant(intValue = 48) ) private int positiveLimit(int original) { @@ -23,7 +23,7 @@ public abstract class StructureBlockBlockEntity_limitsMixin } @ModifyConstant( - method = "fromTag", + method = "readNbt", constant = @Constant(intValue = -48) ) private int negativeLimit(int original) { @@ -34,14 +34,14 @@ public abstract class StructureBlockBlockEntity_limitsMixin method = "saveStructure(Z)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/structure/Structure;saveFromWorld(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/BlockPos;ZLnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/structure/Structure;saveFromWorld(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/Vec3i;ZLnet/minecraft/block/Block;)V" ), index = 4 ) private Block ignoredBlock(Block original) { return CarpetSettings.structureBlockIgnoredBlock; } - +/* @Environment(EnvType.CLIENT) @ModifyConstant( method = "getSquaredRenderDistance", @@ -50,4 +50,6 @@ public abstract class StructureBlockBlockEntity_limitsMixin private double outlineRenderDistanceLimit(double original) { return CarpetSettings.structureBlockOutlineDistance; } + + */ } diff --git a/src/main/java/carpet/mixins/StructureFeatureMixin.java b/src/main/java/carpet/mixins/StructureFeatureMixin.java index b43a9c3c..d1ca1993 100644 --- a/src/main/java/carpet/mixins/StructureFeatureMixin.java +++ b/src/main/java/carpet/mixins/StructureFeatureMixin.java @@ -7,6 +7,7 @@ import net.minecraft.structure.StructureStart; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.BlockBox; +import net.minecraft.world.HeightLimitView; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.source.BiomeSource; import net.minecraft.world.chunk.Chunk; @@ -28,7 +29,7 @@ public abstract class StructureFeatureMixin implements @Shadow public abstract StructureFeature.StructureStartFactory getStructureStartFactory(); - @Shadow protected abstract boolean shouldStartAt(ChunkGenerator chunkGenerator, BiomeSource biomeSource, long l, ChunkRandom chunkRandom, int i, int j, Biome biome, ChunkPos chunkPos, C featureConfig); + @Shadow protected abstract boolean shouldStartAt(ChunkGenerator chunkGenerator, BiomeSource biomeSource, long worldSeed, ChunkRandom random, ChunkPos chunkPos, Biome biome, ChunkPos chunkPos2, C featureConfig, HeightLimitView heightLimitView); @Override public boolean plopAnywhere(ServerWorld world, BlockPos pos, ChunkGenerator generator, boolean wireOnly, Biome biome, FeatureConfig config) @@ -49,13 +50,13 @@ public abstract class StructureFeatureMixin implements } world.getChunk(j, k).addStructureReference((StructureFeature) (Object)this, chId); - BlockBox box = structurestart.getBoundingBox(); + BlockBox box = structurestart.setBoundingBoxFromChildren(); // getBB if (!wireOnly) { structurestart.generateStructure(world, world.getStructureAccessor(), generator, rand,box, new ChunkPos(j, k)); } //structurestart.notifyPostProcessAt(new ChunkPos(j, k)); - int i = Math.max(box.getBlockCountX(),box.getBlockCountZ())/16+1; //size + int i = Math.max(box.getBlockCountX(),box.getBlockCountZ())/16+1; //int i = getRadius(); for (int k1 = j - i; k1 <= j + i; ++k1) @@ -104,10 +105,10 @@ public abstract class StructureFeatureMixin implements if (biome == null) biome_1 = generator.getBiomeSource().getBiomeForNoiseGen((chunkpos.getStartX() + 9) >> 2, 0, (chunkpos.getStartZ() + 9) >> 2 ); - StructureStart structurestart1 = getStructureStartFactory().create((StructureFeature)(Object)this, chunkpos.x, chunkpos.z, BlockBox.empty(),0,worldIn.getSeed()); + StructureStart structurestart1 = getStructureStartFactory().create((StructureFeature)(Object)this, chunkpos,0,worldIn.getSeed()); if (config == null) config = new DefaultFeatureConfig(); - structurestart1.init(worldIn.getRegistryManager(), generator, worldIn.getStructureManager() , chunkpos.x, chunkpos.z, biome_1, config); + structurestart1.init(worldIn.getRegistryManager(), generator, worldIn.getStructureManager() , chunkpos, biome_1, config, ichunk); structurestart = structurestart1.hasChildren() ? structurestart1 : StructureStart.DEFAULT; if (structurestart.hasChildren()) @@ -120,8 +121,8 @@ public abstract class StructureFeatureMixin implements } @Override - public boolean shouldStartPublicAt(ChunkGenerator chunkGenerator, BiomeSource biomeSource, long l, ChunkRandom chunkRandom, int i, int j, Biome biome, ChunkPos chunkPos, C featureConfig) + public boolean shouldStartPublicAt(ChunkGenerator chunkGenerator, BiomeSource biomeSource, long l, ChunkRandom chunkRandom, ChunkPos chpos, Biome biome, ChunkPos chunkPos, C featureConfig, HeightLimitView heightLimitView) { - return shouldStartAt(chunkGenerator, biomeSource, l, chunkRandom, i, j, biome, chunkPos, featureConfig); + return shouldStartAt(chunkGenerator, biomeSource, l, chunkRandom, chpos, biome, chunkPos, featureConfig, heightLimitView); } } diff --git a/src/main/java/carpet/mixins/SummonCommandMixin.java b/src/main/java/carpet/mixins/SummonCommandMixin.java index 4f936254..8825c743 100644 --- a/src/main/java/carpet/mixins/SummonCommandMixin.java +++ b/src/main/java/carpet/mixins/SummonCommandMixin.java @@ -31,10 +31,10 @@ public class SummonCommandMixin LocalDifficulty localDifficulty_1 = world.getLocalDifficulty(at); boolean boolean_2 = world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING) && world.random.nextDouble() < (double)localDifficulty_1.getLocalDifficulty() * 0.01D; if (boolean_2) { - SkeletonHorseEntity skeletonHorseEntity_1 = (SkeletonHorseEntity) EntityType.SKELETON_HORSE.create(world); + SkeletonHorseEntity skeletonHorseEntity_1 = EntityType.SKELETON_HORSE.create(world); skeletonHorseEntity_1.setTrapped(true); skeletonHorseEntity_1.setBreedingAge(0); - skeletonHorseEntity_1.resetPosition(entity.getX(), entity.getY(), entity.getZ()); + skeletonHorseEntity_1.setPosition(entity.getX(), entity.getY(), entity.getZ()); world.spawnEntity(skeletonHorseEntity_1); } } diff --git a/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java b/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java index f64062e0..d6e4fc40 100644 --- a/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java +++ b/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java @@ -5,7 +5,7 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.tag.Tag; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -21,7 +21,7 @@ public class TagPredicate_scarpetMixin implements BlockPredicateInterface @Shadow @Final private Map properties; - @Shadow @Final /*@Nullable*/ private CompoundTag nbt; + @Shadow @Final /*@Nullable*/ private NbtCompound nbt; @Override public BlockState getCMBlockState() @@ -45,7 +45,7 @@ public class TagPredicate_scarpetMixin implements BlockPredicateInterface } @Override - public CompoundTag getCMDataTag() + public NbtCompound getCMDataTag() { return nbt; } diff --git a/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java index 0f7fee88..3940b5ee 100644 --- a/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java @@ -12,6 +12,10 @@ import java.util.concurrent.Future; import java.util.function.IntFunction; import java.util.stream.Collectors; +import carpet.fakes.SimpleEntityLookupInterface; +import carpet.fakes.ServerWorldInterface; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.PlayerEntity; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerTask; import org.apache.commons.lang3.tuple.Pair; @@ -74,7 +78,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem @Shadow @Final - private ServerLightingProvider serverLightingProvider; + private ServerLightingProvider lightingProvider; @Shadow @Final @@ -285,12 +289,12 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem this.currentChunkHolders.get(pos.toLong()).getChunkAt(ChunkStatus.EMPTY, (ThreadedAnvilChunkStorage) (Object) this); final Chunk chunk = this.getCurrentChunk(pos); if (!(chunk.getStatus().isAtLeast(ChunkStatus.LIGHT.getPrevious()))) return; - ((ServerLightingProviderInterface) this.serverLightingProvider).removeLightData(chunk); + ((ServerLightingProviderInterface) this.lightingProvider).removeLightData(chunk); this.addRelightTicket(pos); final CompletableFuture lightFuture = this.getRegion (pos, 1, (pos_) -> ChunkStatus.LIGHT) .thenCompose( either -> either.map( - list -> ((ServerLightingProviderInterface) this.serverLightingProvider).relight(chunk), + list -> ((ServerLightingProviderInterface) this.lightingProvider).relight(chunk), unloaded -> { this.releaseRelightTicket(pos); return CompletableFuture.completedFuture(null); @@ -358,14 +362,20 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem { final ChunkPos pos = chunk.getPos(); + // remove entities + long longPos = pos.toLong(); + if (this.loadedChunks.contains(longPos) && chunk instanceof WorldChunk) + ((SimpleEntityLookupInterface)((ServerWorldInterface)world).getEntityLookupCMPublic()).getChunkEntities(pos).forEach(entity -> { if (!(entity instanceof PlayerEntity)) entity.discard();}); + + if (chunk instanceof WorldChunk) ((WorldChunk) chunk).setLoadedToWorld(false); if (this.loadedChunks.remove(pos.toLong()) && chunk instanceof WorldChunk) - this.world.unloadEntities((WorldChunk) chunk); + this.world.unloadEntities((WorldChunk) chunk); // block entities only - ((ServerLightingProviderInterface) this.serverLightingProvider).invokeUpdateChunkStatus(pos); - ((ServerLightingProviderInterface) this.serverLightingProvider).removeLightData(chunk); + ((ServerLightingProviderInterface) this.lightingProvider).invokeUpdateChunkStatus(pos); + ((ServerLightingProviderInterface) this.lightingProvider).removeLightData(chunk); this.worldGenerationProgressListener.setChunkStatus(pos, null); } @@ -378,8 +388,8 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem final long pos = cPos.toLong(); final ChunkHolder oldHolder = this.currentChunkHolders.remove(pos); - final ChunkHolder newHolder = new ChunkHolder(cPos, oldHolder.getLevel(), this.serverLightingProvider, this.chunkTaskPrioritySystem, (ChunkHolder.PlayersWatchingChunkProvider) this); - ((ChunkHolderInterface) newHolder).setDefaultProtoChunk(cPos, this.mainThreadExecutor); + final ChunkHolder newHolder = new ChunkHolder(cPos, oldHolder.getLevel(), world, this.lightingProvider, this.chunkTaskPrioritySystem, (ChunkHolder.PlayersWatchingChunkProvider) this); + ((ChunkHolderInterface) newHolder).setDefaultProtoChunk(cPos, this.mainThreadExecutor, world); this.currentChunkHolders.put(pos, newHolder); ((ChunkTicketManagerInterface) this.ticketManager).replaceHolder(oldHolder, newHolder); @@ -391,7 +401,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem // Remove light for affected neighbors for (final Chunk chunk : affectedNeighbors) - ((ServerLightingProviderInterface) this.serverLightingProvider).removeLightData(chunk); + ((ServerLightingProviderInterface) this.lightingProvider).removeLightData(chunk); // Schedule relighting of neighbors @@ -408,7 +418,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem lightFutures.add(this.getRegion (pos, 1, (pos_) -> ChunkStatus.LIGHT).thenCompose( either -> either.map( - list -> ((ServerLightingProviderInterface) this.serverLightingProvider).relight(chunk), + list -> ((ServerLightingProviderInterface) this.lightingProvider).relight(chunk), unloaded -> { this.releaseRelightTicket(pos); return CompletableFuture.completedFuture(null); diff --git a/src/main/java/carpet/mixins/ThrownEntityMixin.java b/src/main/java/carpet/mixins/ThrownEntityMixin.java index 2ee48f38..f1eb5f35 100644 --- a/src/main/java/carpet/mixins/ThrownEntityMixin.java +++ b/src/main/java/carpet/mixins/ThrownEntityMixin.java @@ -33,9 +33,9 @@ public abstract class ThrownEntityMixin extends Entity } @Override - public void remove() + public void remove(Entity.RemovalReason arg) { - super.remove(); + super.remove(arg); if (LoggerRegistry.__projectiles && logHelper != null) logHelper.onFinish(); } diff --git a/src/main/java/carpet/mixins/TntEntityMixin.java b/src/main/java/carpet/mixins/TntEntityMixin.java index e9285e7e..52849252 100644 --- a/src/main/java/carpet/mixins/TntEntityMixin.java +++ b/src/main/java/carpet/mixins/TntEntityMixin.java @@ -20,7 +20,9 @@ import carpet.logging.logHelpers.TNTLogHelper; @Mixin(TntEntity.class) public abstract class TntEntityMixin extends Entity implements TntEntityInterface { - @Shadow private int fuseTimer; + //@Shadow private int fuseTimer; + + @Shadow public abstract int getFuse(); private TNTLogHelper logHelper; private boolean mergeBool = false; @@ -93,14 +95,14 @@ public abstract class TntEntityMixin extends Entity implements TntEntityInterfac if(!world.isClient && mergeBool && velocity.x == 0 && velocity.y == 0 && velocity.z == 0){ mergeBool = false; for(Entity entity : world.getOtherEntities(this, this.getBoundingBox())){ - if(entity instanceof TntEntity && !entity.removed){ + if(entity instanceof TntEntity && !entity.isRemoved()){ TntEntity entityTNTPrimed = (TntEntity)entity; Vec3d tntVelocity = entityTNTPrimed.getVelocity(); if(tntVelocity.x == 0 && tntVelocity.y == 0 && tntVelocity.z == 0 && this.getX() == entityTNTPrimed.getX() && this.getZ() == entityTNTPrimed.getZ() && this.getY() == entityTNTPrimed.getY() - && this.fuseTimer == entityTNTPrimed.getFuseTimer()){ + && getFuse() == entityTNTPrimed.getFuse()){ mergedTNT += ((TntEntityInterface) entityTNTPrimed).getMergedTNT(); - entityTNTPrimed.remove(); + entityTNTPrimed.discard(); // discard remove(); } } } @@ -108,9 +110,7 @@ public abstract class TntEntityMixin extends Entity implements TntEntityInterfac } } - @Inject(method = "tick", at = @At(value = "FIELD", - target = "Lnet/minecraft/entity/TntEntity;fuseTimer:I", - ordinal = 0)) + @Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/TntEntity;setFuse(I)V")) private void setMergeable(CallbackInfo ci) { // Merge code, merge only tnt that have had a chance to move CARPET-XCOM diff --git a/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java b/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java index 053e799b..a1f5fd18 100644 --- a/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java @@ -11,6 +11,7 @@ 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; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @@ -25,7 +26,7 @@ public abstract class TradeOutputSlot_scarpetEventMixin { @Inject(method = "onTakeItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/village/Merchant;trade(Lnet/minecraft/village/TradeOffer;)V") ) - private void onTrade(PlayerEntity player, ItemStack stack, CallbackInfoReturnable cir) { + private void onTrade(PlayerEntity player, ItemStack stack, CallbackInfo ci) { if(PLAYER_TRADES.isNeeded() && !this.merchant.getMerchantWorld().isClient()) { PLAYER_TRADES.onTrade((ServerPlayerEntity) player, merchant, merchantInventory.getTradeOffer()); diff --git a/src/main/java/carpet/mixins/TrapezoidHeightProvider_cleanLogsMixin.java b/src/main/java/carpet/mixins/TrapezoidHeightProvider_cleanLogsMixin.java new file mode 100644 index 00000000..4c024ba4 --- /dev/null +++ b/src/main/java/carpet/mixins/TrapezoidHeightProvider_cleanLogsMixin.java @@ -0,0 +1,21 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.world.gen.heightprovider.TrapezoidHeightProvider; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(TrapezoidHeightProvider.class) +public class TrapezoidHeightProvider_cleanLogsMixin { + + @SuppressWarnings("UnresolvedMixinReference") + @Redirect(method = "get", + at = @At(value = "INVOKE", target = "Lorg/apache/logging/log4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V") + ) + private void skipLogs(Logger logger, String message, Object p0) + { + if (!CarpetSettings.cleanLogs) logger.warn(message, p0); + } +} diff --git a/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java b/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java index 78509307..4be905f1 100644 --- a/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java +++ b/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java @@ -7,6 +7,7 @@ import net.minecraft.network.PacketByteBuf; import net.minecraft.network.packet.c2s.play.UpdateStructureBlockC2SPacket; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.Vec3i; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -18,17 +19,17 @@ public class UpdateStructureBlockC2SPacketMixin { @Shadow private BlockPos offset; @Shadow - private BlockPos size; + private Vec3i size; @Inject( - method = "read", + method = "(Lnet/minecraft/network/PacketByteBuf;)V", at = @At("TAIL") ) private void structureBlockLimitsRead(PacketByteBuf buf, CallbackInfo ci) { if (buf.readableBytes() == 6*4) { // This will throw an exception if carpet is not installed on client offset = new BlockPos(MathHelper.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit)); - size = new BlockPos(MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit)); + size = new Vec3i(MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit)); } } diff --git a/src/main/java/carpet/mixins/VeryBiasedToBottomHeightProvider_cleanLogsMixin.java b/src/main/java/carpet/mixins/VeryBiasedToBottomHeightProvider_cleanLogsMixin.java new file mode 100644 index 00000000..d64569eb --- /dev/null +++ b/src/main/java/carpet/mixins/VeryBiasedToBottomHeightProvider_cleanLogsMixin.java @@ -0,0 +1,21 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.world.gen.heightprovider.VeryBiasedToBottomHeightProvider; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(VeryBiasedToBottomHeightProvider.class) +public class VeryBiasedToBottomHeightProvider_cleanLogsMixin { + + //@SuppressWarnings("UnresolvedMixinReference") + @Redirect(method = "get", + at = @At(value = "INVOKE", target = "Lorg/apache/logging/log4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V") + ) + private void skipLogs(Logger logger, String message, Object p0) + { + if (!CarpetSettings.cleanLogs) logger.warn(message, p0); + } +} diff --git a/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java b/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java index b8035233..d71bb474 100644 --- a/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java @@ -26,7 +26,7 @@ public class WallStandingBlockItem_creativeNoClipMixin ) { PlayerEntity player = itemcontext.getPlayer(); - if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.abilities.flying) + if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.getAbilities().flying) { // copy from canPlace VoxelShape voxelShape = state.getCollisionShape(worldView, pos, context); diff --git a/src/main/java/carpet/mixins/WeightedPickerEntryMixin.java b/src/main/java/carpet/mixins/WeightedPickerEntryMixin.java index 59fd71c1..c4c07802 100644 --- a/src/main/java/carpet/mixins/WeightedPickerEntryMixin.java +++ b/src/main/java/carpet/mixins/WeightedPickerEntryMixin.java @@ -6,7 +6,7 @@ import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(WeightedPicker.Entry.class) public interface WeightedPickerEntryMixin -{ +{/* /// not needed in 1.17 @Accessor("weight") - int getWeight(); + int getWeight();*/ } diff --git a/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java b/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java index e6b5aca4..07bacb52 100644 --- a/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java @@ -12,7 +12,10 @@ import java.util.Random; @Mixin(WitherEntity.class) public class WitherEntity_extremeMixin { - @Redirect(method = "method_6878", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextFloat()F")) + @Redirect(method = "shootSkullAt(ILnet/minecraft/entity/LivingEntity;)V", at = @At( + value = "INVOKE", + target = "Ljava/util/Random;nextFloat()F") + ) private float nextFloatAmplfied(Random random) { if (CarpetSettings.extremeBehaviours) return random.nextFloat()/100; diff --git a/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java b/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java new file mode 100644 index 00000000..b6136a8c --- /dev/null +++ b/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java @@ -0,0 +1,46 @@ +package carpet.mixins; + +import carpet.helpers.TickSpeed; +import carpet.utils.CarpetProfiler; +import net.minecraft.block.BlockState; +import net.minecraft.block.entity.BlockEntity; +import net.minecraft.block.entity.BlockEntityTicker; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Final; +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.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(targets = "net.minecraft.world.chunk.WorldChunk$DirectBlockEntityTickInvoker") +public class WorldChunkBEList_tickMixin +{ + @Shadow @Final private T blockEntity; + CarpetProfiler.ProfilerToken entitySection; + + + @Inject(method = "tick()V", at = @At("HEAD")) + private void startTileEntitySection(CallbackInfo ci) + { + entitySection = CarpetProfiler.start_block_entity_section(blockEntity.getWorld(), blockEntity, CarpetProfiler.TYPE.TILEENTITY); + } + + @Redirect(method = "tick()V", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/block/entity/BlockEntityTicker;tick(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/entity/BlockEntity;)V" + )) + private void checkProcessTEs(BlockEntityTicker blockEntityTicker, World world, BlockPos pos, BlockState state, T blockEntity) + { + if (TickSpeed.process_entities) blockEntityTicker.tick(world, pos, state, blockEntity); + } + + @Inject(method = "tick()V", at = @At("RETURN")) + private void endTileEntitySection(CallbackInfo ci) + { + CarpetProfiler.end_current_entity_section(entitySection); + } + +} diff --git a/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java b/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java index 1aeac766..14f3039a 100644 --- a/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java @@ -31,7 +31,7 @@ public class WorldChunk_fillUpdatesMixin { if (CarpetSettings.impendingFillSkipUpdates.get()) // doing due dilligence from AbstractBlock onStateReplaced { - if (blockState.getBlock().hasBlockEntity() && !blockState.isOf(state.getBlock())) + if (blockState.hasBlockEntity() && !blockState.isOf(state.getBlock())) { world.removeBlockEntity(pos); } diff --git a/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java b/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java index 5778f729..fc1c0160 100644 --- a/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java +++ b/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java @@ -8,6 +8,7 @@ import net.minecraft.block.BlockState; import net.minecraft.block.PistonExtensionBlock; import net.minecraft.block.entity.BlockEntity; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkSectionPos; import net.minecraft.world.Heightmap; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkSection; @@ -40,10 +41,13 @@ public abstract class WorldChunk_movableTEMixin implements WorldChunkInterface @Shadow /* @Nullable */ public abstract BlockEntity getBlockEntity(BlockPos blockPos_1, WorldChunk.CreationType worldChunk$CreationType_1); - + + @Shadow protected abstract void updateTicker(T blockEntity); + // Fix Failure: If a moving BlockEntity is placed while BlockEntities are ticking, this will not find it and then replace it with a new TileEntity! // blockEntity_2 = this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); - @Redirect(method = "setBlockState", at = @At(value = "INVOKE", ordinal = 1, + // question is - with the changes in the BE handling this might not be a case anymore + @Redirect(method = "setBlockState", at = @At(value = "INVOKE", ordinal = 0, target = "Lnet/minecraft/world/chunk/WorldChunk;getBlockEntity(Lnet/minecraft/util/math/BlockPos;" + "Lnet/minecraft/world/chunk/WorldChunk$CreationType;)" + "Lnet/minecraft/block/entity/BlockEntity;")) private BlockEntity ifGetBlockEntity(WorldChunk worldChunk, BlockPos blockPos_1, WorldChunk.CreationType worldChunk$CreationType_1) @@ -72,7 +76,8 @@ public abstract class WorldChunk_movableTEMixin implements WorldChunkInterface int x = blockPos_1.getX() & 15; int y = blockPos_1.getY(); int z = blockPos_1.getZ() & 15; - ChunkSection chunkSection = this.sections[y >> 4]; + int section = world.getSectionIndex(y); + ChunkSection chunkSection = this.sections[section]; if (chunkSection == EMPTY_SECTION) { if (newBlockState.isAir()) @@ -80,8 +85,8 @@ public abstract class WorldChunk_movableTEMixin implements WorldChunkInterface return null; } - chunkSection = new ChunkSection(y >> 4 << 4); - this.sections[y >> 4] = chunkSection; + chunkSection = new ChunkSection(ChunkSectionPos.getSectionCoord(y)); + this.sections[section] = chunkSection; } boolean boolean_2 = chunkSection.isEmpty(); @@ -121,29 +126,31 @@ public abstract class WorldChunk_movableTEMixin implements WorldChunkInterface else { BlockEntity oldBlockEntity = null; - if (oldBlock instanceof BlockEntityProvider) + if (oldBlockState.hasBlockEntity()) { oldBlockEntity = this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); if (oldBlockEntity != null) { - oldBlockEntity.resetBlock(); + oldBlockEntity.setCachedState(oldBlockState); + updateTicker(oldBlockEntity); } } - - if (newBlock instanceof BlockEntityProvider) + + if (oldBlockState.hasBlockEntity()) { if (newBlockEntity == null) { - newBlockEntity = ((BlockEntityProvider) newBlock).createBlockEntity(this.world); + newBlockEntity = ((BlockEntityProvider) newBlock).createBlockEntity(blockPos_1, newBlockState); } if (newBlockEntity != oldBlockEntity && newBlockEntity != null) { newBlockEntity.cancelRemoval(); - this.world.setBlockEntity(blockPos_1, newBlockEntity); - newBlockEntity.resetBlock(); + this.world.addBlockEntity(newBlockEntity); + newBlockEntity.setCachedState(newBlockState); + updateTicker(newBlockEntity); } } - + if (!this.world.isClient) { newBlockState.onBlockAdded(this.world, blockPos_1, oldBlockState, boolean_1); //This can call setblockstate! (e.g. hopper does) diff --git a/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java b/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java index ea412ab0..7cb983a1 100644 --- a/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java +++ b/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java @@ -2,10 +2,7 @@ package carpet.mixins; import carpet.network.CarpetClient; import carpet.script.utils.ShapesRenderer; -import carpet.utils.FabricAPIHooks; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gl.ShaderEffect; import net.minecraft.client.render.BufferBuilderStorage; import net.minecraft.client.render.Camera; import net.minecraft.client.render.GameRenderer; @@ -14,7 +11,6 @@ import net.minecraft.client.render.WorldRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.util.math.Matrix4f; 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; @@ -22,8 +18,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(WorldRenderer.class) public class WorldRenderer_scarpetRenderMixin { - @Shadow private /*@Nullable*/ ShaderEffect transparencyShader; - @Inject(method = "", at = @At("RETURN")) private void addRenderers(MinecraftClient client, BufferBuilderStorage bufferBuilders, CallbackInfo ci) { @@ -32,33 +26,22 @@ public class WorldRenderer_scarpetRenderMixin @Inject(method = "render", at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/render/Camera;)V", - shift = At.Shift.AFTER + target = "Lnet/minecraft/client/render/TexturedRenderLayers;getEntityTranslucentCull()Lnet/minecraft/client/render/RenderLayer;", shift = At.Shift.BEFORE + //target = "Lnet/minecraft/client/render/RenderLayer;getWaterMask()Lnet/minecraft/client/render/RenderLayer;", shift = At.Shift.AFTER + //target = "Lnet/minecraft/client/render/BufferBuilderStorage;getEffectVertexConsumers()Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;", shift = At.Shift.BEFORE + //target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/render/Camera;)V", shift = At.Shift.AFTER + //target = "Lnet/minecraft/client/render/BackgroundRenderer;method_23792()V", shift = At.Shift.AFTER + //target = "Lnet/minecraft/client/render/BufferBuilderStorage;getEntityVertexConsumers()Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;", shift = At.Shift.AFTER + //target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/render/Camera;)V", shift = At.Shift.AFTER // before return )) private void renderScarpetThings(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f matrix4f, CallbackInfo ci) { // in normal circumstances we want to render shapes at the very end so it appears correctly behind stuff. - if (!FabricAPIHooks.WORLD_RENDER_EVENTS && CarpetClient.shapes != null && transparencyShader == null) + // we might actually not need to play with render hooks here. + //if (!FabricAPIHooks.WORLD_RENDER_EVENTS && CarpetClient.shapes != null ) + if (CarpetClient.shapes != null) { - RenderSystem.pushMatrix(); - CarpetClient.shapes.render(camera, tickDelta); - RenderSystem.popMatrix(); - } - } - - @Inject(method = "render", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/render/debug/DebugRenderer;render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;DDD)V", - shift = At.Shift.AFTER - )) - private void renderScarpetThingsFabulously(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f matrix4f, CallbackInfo ci) - { - // with fabulous graphics - stuff doesn't work this way for some reason - need to render with chunk lines. - if (!FabricAPIHooks.WORLD_RENDER_EVENTS && CarpetClient.shapes != null && transparencyShader != null) - { - RenderSystem.pushMatrix(); - CarpetClient.shapes.render(camera, tickDelta); - RenderSystem.popMatrix(); + CarpetClient.shapes.render(matrices, camera, tickDelta); } } } diff --git a/src/main/java/carpet/mixins/World_movableTEMixin.java b/src/main/java/carpet/mixins/World_movableTEMixin.java index 9fc413ff..13a217c9 100644 --- a/src/main/java/carpet/mixins/World_movableTEMixin.java +++ b/src/main/java/carpet/mixins/World_movableTEMixin.java @@ -59,76 +59,63 @@ public abstract class World_movableTEMixin implements WorldInterface, WorldAcces */ public boolean setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState blockState_1, BlockEntity newBlockEntity, int int_1) { - if ((Object) this instanceof EmptyChunk) - return false; - - if (World.isOutOfBuildLimitVertically(blockPos_1)) - { - return false; - } - else if (!this.isClient && isDebugWorld()) + if (isOutOfHeightLimit(blockPos_1) || !this.isClient && isDebugWorld()) return false; + WorldChunk worldChunk_1 = this.getWorldChunk(blockPos_1); + Block block_1 = blockState_1.getBlock(); + + BlockState blockState_2; + if (newBlockEntity != null && block_1 instanceof BlockEntityProvider) + blockState_2 = ((WorldChunkInterface) worldChunk_1).setBlockStateWithBlockEntity(blockPos_1, blockState_1, newBlockEntity, (int_1 & 64) != 0); + else + blockState_2 = worldChunk_1.setBlockState(blockPos_1, blockState_1, (int_1 & 64) != 0); + + if (blockState_2 == null) { return false; } else { - WorldChunk worldChunk_1 = this.getWorldChunk(blockPos_1); - Block block_1 = blockState_1.getBlock(); - - BlockState blockState_2; - if (newBlockEntity != null && block_1 instanceof BlockEntityProvider) - blockState_2 = ((WorldChunkInterface) worldChunk_1).setBlockStateWithBlockEntity(blockPos_1, blockState_1, newBlockEntity, (int_1 & 64) != 0); - else - blockState_2 = worldChunk_1.setBlockState(blockPos_1, blockState_1, (int_1 & 64) != 0); - - if (blockState_2 == null) + BlockState blockState_3 = this.getBlockState(blockPos_1); + + if (blockState_3 != blockState_2 && (blockState_3.getOpacity((BlockView) this, blockPos_1) != blockState_2.getOpacity((BlockView) this, blockPos_1) || blockState_3.getLuminance() != blockState_2.getLuminance() || blockState_3.hasSidedTransparency() || blockState_2.hasSidedTransparency())) { - return false; + Profiler profiler = getProfiler(); + profiler.push("queueCheckLight"); + this.getChunkManager().getLightingProvider().checkBlock(blockPos_1); + profiler.pop(); } - else + + if (blockState_3 == blockState_1) { - BlockState blockState_3 = this.getBlockState(blockPos_1); - - if (blockState_3 != blockState_2 && (blockState_3.getOpacity((BlockView) this, blockPos_1) != blockState_2.getOpacity((BlockView) this, blockPos_1) || blockState_3.getLuminance() != blockState_2.getLuminance() || blockState_3.hasSidedTransparency() || blockState_2.hasSidedTransparency())) + if (blockState_2 != blockState_3) { - Profiler profiler = getProfiler(); - profiler.push("queueCheckLight"); - this.getChunkManager().getLightingProvider().checkBlock(blockPos_1); - profiler.pop(); + this.scheduleBlockRerenderIfNeeded(blockPos_1, blockState_2, blockState_3); } - - if (blockState_3 == blockState_1) + + if ((int_1 & 2) != 0 && (!this.isClient || (int_1 & 4) == 0) && (this.isClient || worldChunk_1.getLevelType() != null && worldChunk_1.getLevelType().isAfter(ChunkHolder.LevelType.TICKING))) { - if (blockState_2 != blockState_3) - { - this.scheduleBlockRerenderIfNeeded(blockPos_1, blockState_2, blockState_3); - } - - if ((int_1 & 2) != 0 && (!this.isClient || (int_1 & 4) == 0) && (this.isClient || worldChunk_1.getLevelType() != null && worldChunk_1.getLevelType().isAfter(ChunkHolder.LevelType.TICKING))) - { - this.updateListeners(blockPos_1, blockState_2, blockState_1, int_1); - } - - if (!this.isClient && (int_1 & 1) != 0) - { - this.updateNeighborsAlways(blockPos_1, blockState_2.getBlock()); - if (blockState_1.hasComparatorOutput()) - { - updateComparators(blockPos_1, block_1); - } - } - - if ((int_1 & 16) == 0) - { - int int_2 = int_1 & -34; - blockState_2.prepare(this, blockPos_1, int_2); // prepare - blockState_1.updateNeighbors(this, blockPos_1, int_2); // updateNeighbours - blockState_1.prepare(this, blockPos_1, int_2); // prepare - } - this.onBlockChanged(blockPos_1, blockState_2, blockState_3); + this.updateListeners(blockPos_1, blockState_2, blockState_1, int_1); } - return true; + + if (!this.isClient && (int_1 & 1) != 0) + { + this.updateNeighborsAlways(blockPos_1, blockState_2.getBlock()); + if (blockState_1.hasComparatorOutput()) + { + updateComparators(blockPos_1, block_1); + } + } + + if ((int_1 & 16) == 0) + { + int int_2 = int_1 & -34; + blockState_2.prepare(this, blockPos_1, int_2); // prepare + blockState_1.updateNeighbors(this, blockPos_1, int_2); // updateNeighbours + blockState_1.prepare(this, blockPos_1, int_2); // prepare + } + this.onBlockChanged(blockPos_1, blockState_2, blockState_3); } + return true; } } } diff --git a/src/main/java/carpet/mixins/World_tickMixin.java b/src/main/java/carpet/mixins/World_tickMixin.java index 6fe4b6a5..0514d750 100644 --- a/src/main/java/carpet/mixins/World_tickMixin.java +++ b/src/main/java/carpet/mixins/World_tickMixin.java @@ -46,39 +46,39 @@ public abstract class World_tickMixin implements WorldInterface private void endBlockEntities(CallbackInfo ci) { CarpetProfiler.end_current_section(currentSection); } - +/* @Inject(method = "tickBlockEntities", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/entity/BlockEntity;isRemoved()Z", + target = "Lnet/minecraft/class_5562;method_31704()Z", shift = At.Shift.BEFORE, ordinal = 0 )) - private void startTileEntitySection(CallbackInfo ci, Profiler profiler_1, Iterator i, BlockEntity blockEntity_2) + private void startTileEntitySection(CallbackInfo ci, Profiler profiler_1, Iterator i, class_5562 lv) { - entitySection = CarpetProfiler.start_block_entity_section((World)(Object)this, blockEntity_2, CarpetProfiler.TYPE.TILEENTITY); + entitySection = CarpetProfiler.start_block_entity_section((World)(Object)this, (BlockEntity) lv, CarpetProfiler.TYPE.TILEENTITY); } @Redirect(method = "tickBlockEntities", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/entity/BlockEntity;isRemoved()Z", + target = "Lnet/minecraft/class_5562;method_31704()Z", ordinal = 0 - )) - private boolean checkProcessTEs(BlockEntity blockEntity) + )) // isRemoved() + private boolean checkProcessTEs(class_5562 class_5562) { - return blockEntity.isRemoved() || !TickSpeed.process_entities; // blockEntity can be NULL? happened once with fake player + return class_5562.method_31704() || !TickSpeed.process_entities; // blockEntity can be NULL? happened once with fake player } @Inject(method = "tickBlockEntities", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/entity/BlockEntity;isRemoved()Z", - shift = At.Shift.BEFORE, - ordinal = 1 + target = "Lnet/minecraft/class_5562;method_31703()V", + shift = At.Shift.AFTER, + ordinal = 0 )) private void endTileEntitySection(CallbackInfo ci) { CarpetProfiler.end_current_entity_section(entitySection); } - +*/ @Inject(method = "tickEntity", at = @At("HEAD"), cancellable = true) private void startEntity(Consumer consumer_1, Entity e, CallbackInfo ci) { diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 1ccd4c1d..ac59bc26 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -4,9 +4,9 @@ import carpet.CarpetServer; import carpet.CarpetSettings; import carpet.script.utils.ShapesRenderer; import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtList; +import net.minecraft.nbt.NbtElement; import net.minecraft.text.Text; import net.minecraft.util.Identifier; @@ -72,16 +72,16 @@ public class CarpetClient return true; } - public static void onClientCommand(Tag t) + public static void onClientCommand(NbtElement t) { CarpetSettings.LOG.info("Server Response:"); - CompoundTag tag = (CompoundTag)t; + NbtCompound tag = (NbtCompound)t; CarpetSettings.LOG.info(" - id: "+tag.getString("id")); CarpetSettings.LOG.info(" - code: "+tag.getInt("code")); if (tag.contains("error")) CarpetSettings.LOG.warn(" - error: "+tag.getString("error")); if (tag.contains("output")) { - ListTag outputTag = (ListTag) tag.get("output"); + NbtList outputTag = (NbtList) tag.get("output"); for (int i = 0; i < outputTag.size(); i++) CarpetSettings.LOG.info(" - response: " + Text.Serializer.fromJson(outputTag.getString(i)).getString()); } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 13d25492..9a34ec2d 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -8,11 +8,11 @@ import carpet.settings.ParsedRule; import carpet.settings.SettingsManager; import io.netty.buffer.Unpooled; import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.nbt.AbstractNumberTag; -import net.minecraft.nbt.ByteTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.AbstractNbtNumber; +import net.minecraft.nbt.NbtByte; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtList; +import net.minecraft.nbt.NbtElement; import net.minecraft.network.PacketByteBuf; import net.minecraft.network.packet.c2s.play.CustomPayloadC2SPacket; @@ -22,14 +22,14 @@ import java.util.function.BiConsumer; public class ClientNetworkHandler { - private static final Map> dataHandlers = new HashMap>(); + private static final Map> dataHandlers = new HashMap>(); static { dataHandlers.put("Rules", (p, t) -> { - CompoundTag ruleset = (CompoundTag)t; + NbtCompound ruleset = (NbtCompound)t; for (String ruleKey: ruleset.getKeys()) { - CompoundTag ruleNBT = (CompoundTag) ruleset.get(ruleKey); + NbtCompound ruleNBT = (NbtCompound) ruleset.get(ruleKey); SettingsManager manager = null; String ruleName; if (ruleNBT.contains("Manager")) @@ -65,22 +65,22 @@ public class ClientNetworkHandler } } }); - dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrate(((AbstractNumberTag)t).getFloat(), false)); + dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrate(((AbstractNbtNumber)t).floatValue(), false)); dataHandlers.put("TickingState", (p, t) -> { - CompoundTag tickingState = (CompoundTag)t; + NbtCompound tickingState = (NbtCompound)t; TickSpeed.setFrozenState(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); }); dataHandlers.put("SuperHotState", (p, t) -> { - TickSpeed.is_superHot = ((ByteTag) t).equals(ByteTag.ONE); + TickSpeed.is_superHot = ((NbtByte) t).equals(NbtByte.ONE); }); - dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.player_active_timeout = ((AbstractNumberTag)t).getInt()); + dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.player_active_timeout = ((AbstractNbtNumber)t).intValue()); dataHandlers.put("scShape", (p, t) -> { // deprecated // and unused // should remove for 1.17 if (CarpetClient.shapes != null) - CarpetClient.shapes.addShape((CompoundTag)t); + CarpetClient.shapes.addShape((NbtCompound)t); }); dataHandlers.put("scShapes", (p, t) -> { if (CarpetClient.shapes != null) - CarpetClient.shapes.addShapes((ListTag) t); + CarpetClient.shapes.addShapes((NbtList) t); }); dataHandlers.put("clientCommand", (p, t) -> { CarpetClient.onClientCommand(t); @@ -129,7 +129,7 @@ public class ClientNetworkHandler private static void onSyncData(PacketByteBuf data, ClientPlayerEntity player) { - CompoundTag compound = data.readCompoundTag(); + NbtCompound compound = data.readNbt(); if (compound == null) return; for (String key: compound.getKeys()) { @@ -149,14 +149,14 @@ public class ClientNetworkHandler public static void clientCommand(String command) { - CompoundTag tag = new CompoundTag(); + NbtCompound tag = new NbtCompound(); tag.putString("id", command); tag.putString("command", command); - CompoundTag outer = new CompoundTag(); + NbtCompound outer = new NbtCompound(); outer.put("clientCommand", tag); CarpetClient.getPlayer().networkHandler.sendPacket(new CustomPayloadC2SPacket( CarpetClient.CARPET_CHANNEL, - (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.DATA).writeCompoundTag(outer) + (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.DATA).writeNbt(outer) )); } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 97bf6dc3..aee49d03 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -7,10 +7,10 @@ import carpet.script.utils.SnoopyCommandSource; import carpet.settings.ParsedRule; import carpet.settings.SettingsManager; import io.netty.buffer.Unpooled; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtList; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import net.minecraft.network.PacketByteBuf; import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket; import net.minecraft.server.network.ServerPlayerEntity; @@ -31,9 +31,9 @@ public class ServerNetworkHandler private static Map remoteCarpetPlayers = new HashMap<>(); private static Set validCarpetPlayers = new HashSet<>(); - private static Map> dataHandlers = new HashMap>(){{ + private static Map> dataHandlers = new HashMap>(){{ put("clientCommand", (p, t) -> { - handleClientCommand(p, (CompoundTag)t); + handleClientCommand(p, (NbtCompound)t); }); }}; @@ -88,7 +88,7 @@ public class ServerNetworkHandler playerEntity.networkHandler.sendPacket(new CustomPayloadS2CPacket(CarpetClient.CARPET_CHANNEL, data.build() )); } - private static void handleClientCommand(ServerPlayerEntity player, CompoundTag commandData) + private static void handleClientCommand(ServerPlayerEntity player, NbtCompound commandData) { String command = commandData.getString("command"); String id = commandData.getString("id"); @@ -105,12 +105,12 @@ public class ServerNetworkHandler new SnoopyCommandSource(player, error, output), command ); } - CompoundTag result = new CompoundTag(); + NbtCompound result = new NbtCompound(); result.putString("id", id); result.putInt("code", resultCode); if (error[0] != null) result.putString("error", error[0].asString()); - ListTag outputResult = new ListTag(); - for (Text line: output) outputResult.add(StringTag.of(Text.Serializer.toJson(line))); + NbtList outputResult = new NbtList(); + for (Text line: output) outputResult.add(NbtString.of(Text.Serializer.toJson(line))); if (!output.isEmpty()) result.put("output", outputResult); player.networkHandler.sendPacket(new CustomPayloadS2CPacket( CarpetClient.CARPET_CHANNEL, @@ -122,7 +122,7 @@ public class ServerNetworkHandler private static void onClientData(ServerPlayerEntity player, PacketByteBuf data) { - CompoundTag compound = data.readCompoundTag(); + NbtCompound compound = data.readNbt(); if (compound == null) return; for (String key: compound.getKeys()) { @@ -193,7 +193,7 @@ public class ServerNetworkHandler } } - public static void broadcastCustomCommand(String command, Tag data) + public static void broadcastCustomCommand(String command, NbtElement data) { if (CarpetSettings.superSecretSetting) return; for (ServerPlayerEntity player : validCarpetPlayers) @@ -205,7 +205,7 @@ public class ServerNetworkHandler } } - public static void sendCustomCommand(ServerPlayerEntity player, String command, Tag data) + public static void sendCustomCommand(ServerPlayerEntity player, String command, NbtElement data) { if (isValidCarpetPlayer(player)) { @@ -246,14 +246,14 @@ public class ServerNetworkHandler private static class DataBuilder { - private CompoundTag tag; + private NbtCompound tag; private static DataBuilder create() { return new DataBuilder(); } private DataBuilder() { - tag = new CompoundTag(); + tag = new NbtCompound(); } private DataBuilder withTickRate() { @@ -262,7 +262,7 @@ public class ServerNetworkHandler } private DataBuilder withFrozenState() { - CompoundTag tickingState = new CompoundTag(); + NbtCompound tickingState = new NbtCompound(); tickingState.putBoolean("is_paused", TickSpeed.isPaused()); tickingState.putBoolean("deepFreeze", TickSpeed.deeplyFrozen()); tag.put("TickingState", tickingState); @@ -280,16 +280,16 @@ public class ServerNetworkHandler } private DataBuilder withRule(ParsedRule rule) { - CompoundTag rules = (CompoundTag) tag.get("Rules"); + NbtCompound rules = (NbtCompound) tag.get("Rules"); if (rules == null) { - rules = new CompoundTag(); + rules = new NbtCompound(); tag.put("Rules", rules); } String identifier = rule.settingsManager.getIdentifier(); String key = rule.name; while (rules.contains(key)) { key = key+"2";} - CompoundTag ruleNBT = new CompoundTag(); + NbtCompound ruleNBT = new NbtCompound(); ruleNBT.putString("Value", rule.getAsString()); ruleNBT.putString("Manager",identifier); ruleNBT.putString("Rule",rule.name); @@ -297,7 +297,7 @@ public class ServerNetworkHandler return this; } - public DataBuilder withCustomNbt(String key, Tag value) + public DataBuilder withCustomNbt(String key, NbtElement value) { tag.put(key, value); return this; @@ -307,7 +307,7 @@ public class ServerNetworkHandler { PacketByteBuf packetBuf = new PacketByteBuf(Unpooled.buffer()); packetBuf.writeVarInt(CarpetClient.DATA); - packetBuf.writeCompoundTag(tag); + packetBuf.writeNbt(tag); return packetBuf; } diff --git a/src/main/java/carpet/patches/CopyProfilerResult.java b/src/main/java/carpet/patches/CopyProfilerResult.java new file mode 100644 index 00000000..07a13782 --- /dev/null +++ b/src/main/java/carpet/patches/CopyProfilerResult.java @@ -0,0 +1,54 @@ +package carpet.patches; + +import net.minecraft.util.profiler.ProfileResult; +import net.minecraft.util.profiler.ProfilerTiming; + +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; + +public class CopyProfilerResult implements ProfileResult { + int startI, endI; + long startL, endL; + public CopyProfilerResult(int startI, long startL, int endI, long endL) + { + this.startI = startI; + this.startL = startL; + this.endI = endI; + this.endL = endL; + } + @Override + public List getTimings(String parentPath) { + return Collections.emptyList(); + } + + @Override + public boolean save(Path path) { + return false; + } + + @Override + public long getStartTime() { + return startL; + } + + @Override + public int getStartTick() { + return startI; + } + + @Override + public long getEndTime() { + return endL; + } + + @Override + public int getEndTick() { + return endI; + } + + @Override + public String getRootTimings() { + return ""; + } +} diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 46264d76..19dafed4 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -17,7 +17,6 @@ import net.minecraft.text.TranslatableText; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerTask; import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.network.ServerPlayerInteractionManager; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.UserCache; import net.minecraft.util.registry.RegistryKey; @@ -26,6 +25,8 @@ import net.minecraft.world.World; import carpet.fakes.ServerPlayerEntityInterface; import carpet.utils.Messenger; +import java.util.concurrent.atomic.AtomicReference; + @SuppressWarnings("EntityConstructor") public class EntityPlayerMPFake extends ServerPlayerEntity { @@ -36,11 +37,10 @@ public class EntityPlayerMPFake extends ServerPlayerEntity { //prolly half of that crap is not necessary, but it works ServerWorld worldIn = server.getWorld(dimensionId); - ServerPlayerInteractionManager interactionManagerIn = new ServerPlayerInteractionManager(worldIn); UserCache.setUseRemote(false); GameProfile gameprofile; try { - gameprofile = server.getUserCache().findByName(username); + gameprofile = server.getUserCache().findByName(username).orElse(null); } finally { UserCache.setUseRemote(server.isDedicated() && server.isOnlineMode()); @@ -56,21 +56,23 @@ public class EntityPlayerMPFake extends ServerPlayerEntity } if (gameprofile.getProperties().containsKey("textures")) { - gameprofile = SkullBlockEntity.loadProperties(gameprofile); + AtomicReference result = new AtomicReference<>(); + SkullBlockEntity.loadProperties(gameprofile, result::set); + gameprofile = result.get(); } - EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, gameprofile, interactionManagerIn, false); + EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, gameprofile, false); instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(d0, d1, d2, (float) yaw, (float) pitch); server.getPlayerManager().onPlayerConnect(new NetworkManagerFake(NetworkSide.SERVERBOUND), instance); instance.teleport(worldIn, d0, d1, d2, (float)yaw, (float)pitch); instance.setHealth(20.0F); - instance.removed = false; + instance.unsetRemoved(); instance.stepHeight = 0.6F; - interactionManagerIn.setGameMode(gamemode); + instance.interactionManager.changeGameMode(gamemode); server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(instance, (byte) (instance.headYaw * 256 / 360)), dimensionId);//instance.dimension); server.getPlayerManager().sendToDimension(new EntityPositionS2CPacket(instance), dimensionId);//instance.dimension); - instance.getServerWorld().getChunkManager().updateCameraPosition(instance); + instance.getServerWorld().getChunkManager().updatePosition(instance); instance.dataTracker.set(PLAYER_MODEL_PARTS, (byte) 0x7f); // show all model layers (incl. capes) - instance.abilities.flying = flying; + instance.getAbilities().flying = flying; return instance; } @@ -79,14 +81,13 @@ public class EntityPlayerMPFake extends ServerPlayerEntity player.getServer().getPlayerManager().remove(player); player.networkHandler.disconnect(new TranslatableText("multiplayer.disconnect.duplicate_login")); ServerWorld worldIn = player.getServerWorld();//.getWorld(player.dimension); - ServerPlayerInteractionManager interactionManagerIn = new ServerPlayerInteractionManager(worldIn); GameProfile gameprofile = player.getGameProfile(); - EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, interactionManagerIn, true); + EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, true); server.getPlayerManager().onPlayerConnect(new NetworkManagerFake(NetworkSide.SERVERBOUND), playerShadow); playerShadow.setHealth(player.getHealth()); - playerShadow.networkHandler.requestTeleport(player.getX(), player.getY(), player.getZ(), player.yaw, player.pitch); - interactionManagerIn.setGameMode(player.interactionManager.getGameMode()); + playerShadow.networkHandler.requestTeleport(player.getX(), player.getY(), player.getZ(), player.getYaw(), player.getPitch()); + playerShadow.interactionManager.changeGameMode(player.interactionManager.getGameMode()); ((ServerPlayerEntityInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerEntityInterface) player).getActionPack()); playerShadow.stepHeight = 0.6F; playerShadow.dataTracker.set(PLAYER_MODEL_PARTS, player.getDataTracker().get(PLAYER_MODEL_PARTS)); @@ -94,14 +95,14 @@ public class EntityPlayerMPFake extends ServerPlayerEntity server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(playerShadow, (byte) (player.headYaw * 256 / 360)), playerShadow.world.getRegistryKey()); server.getPlayerManager().sendToAll(new PlayerListS2CPacket(PlayerListS2CPacket.Action.ADD_PLAYER, playerShadow)); - player.getServerWorld().getChunkManager().updateCameraPosition(playerShadow); - playerShadow.abilities.flying = player.abilities.flying; + player.getServerWorld().getChunkManager().updatePosition(playerShadow); + playerShadow.getAbilities().flying = player.getAbilities().flying; return playerShadow; } - private EntityPlayerMPFake(MinecraftServer server, ServerWorld worldIn, GameProfile profile, ServerPlayerInteractionManager interactionManagerIn, boolean shadow) + private EntityPlayerMPFake(MinecraftServer server, ServerWorld worldIn, GameProfile profile, boolean shadow) { - super(server, worldIn, profile, interactionManagerIn); + super(server, worldIn, profile); isAShadow = shadow; } @@ -131,8 +132,8 @@ public class EntityPlayerMPFake extends ServerPlayerEntity if (this.getServer().getTicks() % 10 == 0) { this.networkHandler.syncWithPlayerPosition(); - this.getServerWorld().getChunkManager().updateCameraPosition(this); - //if (netherPortalCooldown==10) onTeleportationDone(); <- causes hard crash but would need to be done to enable portals + this.getServerWorld().getChunkManager().updatePosition(this); + onTeleportationDone(); //<- causes hard crash but would need to be done to enable portals // not as of 1.17 } super.tick(); this.playerTick(); diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 367a3f4d..fa80b5b7 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -835,7 +835,9 @@ public class CarpetEventServer private final Set skippedStats = new HashSet(){{ add(Stats.TIME_SINCE_DEATH); add(Stats.TIME_SINCE_REST); - add(Stats.PLAY_ONE_MINUTE); + //add(Stats.PLAY_ONE_MINUTE); + add(Stats.PLAY_TIME); + add(Stats.TOTAL_WORLD_TIME); }}; @Override public void onPlayerStatistic(ServerPlayerEntity player, Stat stat, int amount) @@ -943,7 +945,8 @@ public class CarpetEventServer } @Deprecated - public static final Map, Event> ENTITY_LOAD= new HashMap, Event>() {{ + public static final Map, Event> ENTITY_LOAD= new HashMap<>() + {{ EntityType.get("zombie"); Registry.ENTITY_TYPE.forEach(et -> { put(et, new Event(getEntityLoadEventName(et), 1, true, false) @@ -965,7 +968,8 @@ public class CarpetEventServer return "entity_handler_" + ValueConversions.of(Registry.ENTITY_TYPE.getId(et)).getString(); } - public static final Map, Event> ENTITY_HANDLER= new HashMap, Event>() {{ + public static final Map, Event> ENTITY_HANDLER= new HashMap<>() + {{ EntityType.get("zombie"); Registry.ENTITY_TYPE.forEach(et -> { put(et, new Event(getEntityHandlerEventName(et), 2, true, false) diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 1f953d70..8e8a4698 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -38,7 +38,7 @@ import net.fabricmc.loader.api.Version; import net.fabricmc.loader.api.VersionParsingException; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtElement; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; @@ -72,7 +72,7 @@ public class CarpetScriptHost extends ScriptHost private final CarpetScriptServer scriptServer; public ServerCommandSource responsibleSource; - private Tag globalState; + private NbtElement globalState; private int saveTimeout; public boolean persistenceRequired; @@ -651,7 +651,7 @@ public class CarpetScriptHost extends ScriptHost { if (optionalTarget == null) { - for (ServerPlayerEntity player : source.getMinecraftServer().getPlayerManager().getPlayerList()) + for (ServerPlayerEntity player : source.getServer().getPlayerManager().getPlayerList()) { CarpetScriptHost host = (CarpetScriptHost) retrieveForExecution(player.getEntityName()); targets.add(host); @@ -660,7 +660,7 @@ public class CarpetScriptHost extends ScriptHost } else { - ServerPlayerEntity player = source.getMinecraftServer().getPlayerManager().getPlayer(optionalTarget); + ServerPlayerEntity player = source.getServer().getPlayerManager().getPlayer(optionalTarget); if (player != null) { CarpetScriptHost host = (CarpetScriptHost) retrieveForExecution(player.getEntityName()); @@ -937,7 +937,7 @@ public class CarpetScriptHost extends ScriptHost { for (Entity e : world.getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName))) { - e.remove(); + e.discard(); } } if (this.saveTimeout > 0) @@ -950,12 +950,12 @@ public class CarpetScriptHost extends ScriptHost Module.saveData(main, globalState); } - private Tag loadState() + private NbtElement loadState() { return Module.getData(main); } - public Tag readFileTag(FileArgument fdesc) + public NbtElement readFileTag(FileArgument fdesc) { if (getName() == null && !fdesc.isShared) return null; if (fdesc.resource != null) @@ -965,7 +965,7 @@ public class CarpetScriptHost extends ScriptHost return ((CarpetScriptHost)parent).globalState; } - public boolean writeTagFile(Tag tag, FileArgument fdesc) + public boolean writeTagFile(NbtElement tag, FileArgument fdesc) { if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host. diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index e76a61ba..f6000cb5 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -383,7 +383,7 @@ public class CarpetScriptServer ServerPlayerEntity target = null; if (optionalTarget != null) { - target = sender.getMinecraftServer().getPlayerManager().getPlayer(optionalTarget); + target = sender.getServer().getPlayerManager().getPlayer(optionalTarget); if (target == null) return false; } int successes = signal(sender, target, hostname, udf, argv, true ); @@ -436,8 +436,8 @@ public class CarpetScriptServer { // getPlayer will always return nonnull cause retrieve for execution only returns hosts for existing players. ServerCommandSource executingSource = host.perUser - ? source.getMinecraftServer().getPlayerManager().getPlayer(host.user).getCommandSource() - : source.getMinecraftServer().getCommandSource(); + ? source.getServer().getPlayerManager().getPlayer(host.user).getCommandSource() + : source.getServer().getCommandSource(); try { host.callUDF(BlockPos.ORIGIN, source.withLevel(CarpetSettings.runPermissionLevel), udf, argv); diff --git a/src/main/java/carpet/script/annotation/FunctionsTestClass.java b/src/main/java/carpet/script/annotation/FunctionsTestClass.java index d56a3fbc..93aa1b35 100644 --- a/src/main/java/carpet/script/annotation/FunctionsTestClass.java +++ b/src/main/java/carpet/script/annotation/FunctionsTestClass.java @@ -12,7 +12,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; - +/* There is no worse example to use for 1.17 compatibility import static net.minecraft.network.packet.s2c.play.TitleS2CPacket.Action; public class FunctionsTestClass { @@ -58,3 +58,4 @@ public class FunctionsTestClass { return targets.size(); } } +*/ \ No newline at end of file diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index 22bd7954..da4f64ee 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Objects; import java.util.function.Function; +import net.minecraft.nbt.NbtElement; import org.apache.commons.lang3.ClassUtils; import carpet.script.LazyValue; @@ -17,7 +18,6 @@ import carpet.script.value.Value; import carpet.script.value.ValueConversions; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.Tag; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.dynamic.GlobalPos; @@ -48,7 +48,7 @@ public final class OutputConverter registerToValue(String.class, StringValue::new); registerToValue(Entity.class, EntityValue::new); registerToValue(Text.class, FormattedTextValue::new); - registerToValue(Tag.class, NBTSerializableValue::new); + registerToValue(NbtElement.class, NBTSerializableValue::new); registerToValue(BlockPos.class, ValueConversions::of); registerToValue(Vec3d.class, ValueConversions::of); registerToValue(ItemStack.class, ValueConversions::of); diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index e372b03f..5237612c 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -50,14 +50,21 @@ import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.decoration.ArmorStandEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtHelper; import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; +import net.minecraft.network.Packet; +import net.minecraft.network.packet.s2c.play.ClearTitleS2CPacket; +import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket; import net.minecraft.network.packet.s2c.play.PlaySoundIdS2CPacket; +import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket; +//import net.minecraft.network.packet.s2c.play.TitleS2CPacket; +//import net.minecraft.network.packet.s2c.play.TitleS2CPacket.Action; +import net.minecraft.network.packet.s2c.play.SubtitleS2CPacket; +import net.minecraft.network.packet.s2c.play.TitleFadeS2CPacket; import net.minecraft.network.packet.s2c.play.TitleS2CPacket; -import net.minecraft.network.packet.s2c.play.TitleS2CPacket.Action; import net.minecraft.particle.ParticleEffect; import net.minecraft.resource.DataPackSettings; import net.minecraft.resource.ReloadableResourceManagerImpl; @@ -120,6 +127,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -190,7 +198,7 @@ public class Auxiliary { { CarpetContext cc = (CarpetContext)c; if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.getIds().stream().map(ValueConversions::of)); - MinecraftServer ms = cc.s.getMinecraftServer(); + MinecraftServer ms = cc.s.getServer(); ServerWorld world = cc.s.getWorld(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); String particleName = lv.get(0).getString(); @@ -262,7 +270,7 @@ public class Auxiliary { } else { - player = cc.s.getMinecraftServer().getPlayerManager().getPlayer(playerValue.getString()); + player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString()); } } } @@ -302,7 +310,7 @@ public class Auxiliary { } else { - player = cc.s.getMinecraftServer().getPlayerManager().getPlayer(playerValue.getString()); + player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString()); } } } @@ -429,14 +437,14 @@ public class Auxiliary { for (Entity e : cc.s.getWorld().getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName))) { total ++; - e.remove(); + e.discard(); // discard // remove(); } return new NumericValue(total); }); expression.addUnaryFunction("nbt", NBTSerializableValue::fromValue); - expression.addUnaryFunction("escape_nbt", v -> new StringValue(StringTag.escape(v.getString()))); + expression.addUnaryFunction("escape_nbt", v -> new StringValue(NbtString.escape(v.getString()))); expression.addUnaryFunction("parse_nbt", v -> { if (v instanceof NBTSerializableValue) return ((NBTSerializableValue) v).toValue(); @@ -450,8 +458,8 @@ public class Auxiliary { if (numParam != 2 && numParam != 3) throw new InternalExpressionException("'tag_matches' requires 2 or 3 arguments"); if (lv.get(1).isNull()) return Value.TRUE; if (lv.get(0).isNull()) return Value.FALSE; - Tag source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag(); - Tag match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag(); + NbtElement source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag(); + NbtElement match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag(); return BooleanValue.of(NbtHelper.matches(match, source, numParam == 2 || lv.get(2).getBoolean())); }); @@ -460,7 +468,7 @@ public class Auxiliary { if (argSize==0 || argSize > 2) throw new InternalExpressionException("'encode_nbt' requires 1 or 2 parameters"); Value v = lv.get(0); boolean force = (argSize > 1) && lv.get(1).getBoolean(); - Tag tag; + NbtElement tag; try { tag = v.toTag(force); @@ -477,7 +485,7 @@ public class Auxiliary { { if (lv.size() == 0 || lv.size() > 2) throw new InternalExpressionException("'print' takes one or two arguments"); ServerCommandSource s = ((CarpetContext)c).s; - MinecraftServer server = s.getMinecraftServer(); + MinecraftServer server = s.getServer(); Value res = lv.get(0); List targets = null; if (lv.size() == 2) @@ -508,38 +516,51 @@ public class Auxiliary { if (lv.size() < 2) throw new InternalExpressionException("'display_title' needs at least a target, type and message, and optionally times"); Value pVal = lv.get(0); if (!(pVal instanceof ListValue)) pVal = ListValue.of(pVal); - MinecraftServer server = ((CarpetContext)c).s.getMinecraftServer(); + MinecraftServer server = ((CarpetContext)c).s.getServer(); Stream targets = ((ListValue) pVal).getItems().stream().map(v -> { ServerPlayerEntity player = EntityValue.getPlayerByValue(server, v); if (player == null) throw new InternalExpressionException("'display_title' requires a valid online player or a list of players as first argument. "+v.getString()+" is not a player."); return player; }); - TitleS2CPacket.Action action; + Function> packetGetter = null; + //TitleS2CPacket.Action action; String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT); switch (actionString) { case "title": - action = Action.TITLE; + packetGetter = TitleS2CPacket::new; + //action = Action.TITLE; + if (lv.size() < 3) + throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); + break; case "subtitle": - action = Action.SUBTITLE; + packetGetter = SubtitleS2CPacket::new; + if (lv.size() < 3) + throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); + + //action = Action.SUBTITLE; break; case "actionbar": - action = Action.ACTIONBAR; + packetGetter = OverlayMessageS2CPacket::new; + if (lv.size() < 3) + throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); + + //action = Action.ACTIONBAR; break; case "clear": - action = Action.CLEAR; + packetGetter = (x) -> new ClearTitleS2CPacket(true); // resetting default fade + //action = Action.CLEAR; break; case "player_list_header": case "player_list_footer": - action = null; break; default: throw new InternalExpressionException("'display_title' requires 'title', 'subtitle', 'actionbar', 'player_list_header', 'player_list_footer' or 'clear' as second argument"); } - if (action != Action.CLEAR && lv.size() < 3) - throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); + //if (action != Action.CLEAR && lv.size() < 3) + // throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); Text title; boolean soundsTrue = false; if (lv.size() > 2) @@ -549,14 +570,14 @@ public class Auxiliary { soundsTrue = pVal.getBoolean(); } else title = null; // Will never happen, just to make lambda happy - if (action == null) + if (packetGetter == null) { Map map; if (actionString.equals("player_list_header")) map = HUDController.scarpet_headers; else map = HUDController.scarpet_footers; - + AtomicInteger total = new AtomicInteger(0); List targetList = targets.collect(Collectors.toList()); if (!soundsTrue) // null or empty string @@ -569,21 +590,23 @@ public class Auxiliary { map.put(target.getEntityName(), (BaseText) title); total.getAndIncrement(); }); - HUDController.update_hud(((CarpetContext)c).s.getMinecraftServer(), targetList); + HUDController.update_hud(((CarpetContext)c).s.getServer(), targetList); return NumericValue.of(total.get()); } - TitleS2CPacket timesPacket; + TitleFadeS2CPacket timesPacket; // TimesPacket if (lv.size() > 3) { if (lv.size() != 6) throw new InternalExpressionException("'display_title' needs all fade-in, stay and fade-out times"); int in = NumericValue.asNumber(lv.get(3),"fade in for display_title" ).getInt(); int stay = NumericValue.asNumber(lv.get(4),"stay for display_title" ).getInt(); int out = NumericValue.asNumber(lv.get(5),"fade out for display_title" ).getInt(); - timesPacket = new TitleS2CPacket(Action.TIMES, null, in, stay, out); + timesPacket = new TitleFadeS2CPacket(in, stay, out); + //timesPacket = new TitleS2CPacket(Action.TIMES, null, in, stay, out); } else timesPacket = null; - TitleS2CPacket packet = new TitleS2CPacket(action, title); + Packet packet = packetGetter.apply(title); + //TitleS2CPacket packet = new TitleS2CPacket(action, title); AtomicInteger total = new AtomicInteger(0); targets.forEach(p -> { if (timesPacket != null) p.networkHandler.sendPacket(timesPacket); @@ -607,7 +630,7 @@ public class Auxiliary { { Text[] error = {null}; List output = new ArrayList<>(); - Value retval = new NumericValue(s.getMinecraftServer().getCommandManager().execute( + Value retval = new NumericValue(s.getServer().getCommandManager().execute( new SnoopyCommandSource(s, error, output), lv.get(0).getString()) ); @@ -626,15 +649,15 @@ public class Auxiliary { expression.addContextFunction("save", 0, (c, t, lv) -> { ServerCommandSource s = ((CarpetContext)c).s; - s.getMinecraftServer().getPlayerManager().saveAllPlayerData(); - s.getMinecraftServer().save(true,true,true); + s.getServer().getPlayerManager().saveAllPlayerData(); + s.getServer().save(true,true,true); s.getWorld().getChunkManager().tick(() -> true); CarpetScriptServer.LOG.warn("Saved chunks"); return Value.TRUE; }); expression.addContextFunction("tick_time", 0, (c, t, lv) -> - new NumericValue(((CarpetContext) c).s.getMinecraftServer().getTicks())); + new NumericValue(((CarpetContext) c).s.getServer().getTicks())); expression.addContextFunction("world_time", 0, (c, t, lv) -> new NumericValue(((CarpetContext) c).s.getWorld().getTime())); @@ -655,9 +678,9 @@ public class Auxiliary { { //assuming we are in the tick world section // might be off one tick when run in the off tasks or asynchronously. - int currentReportedTick = ((CarpetContext) c).s.getMinecraftServer().getTicks()-1; + int currentReportedTick = ((CarpetContext) c).s.getServer().getTicks()-1; List ticks = new ArrayList<>(100); - final long[] tickArray = ((CarpetContext) c).s.getMinecraftServer().lastTickLengths; + final long[] tickArray = ((CarpetContext) c).s.getServer().lastTickLengths; for (int i=currentReportedTick+100; i > currentReportedTick; i--) { ticks.add(new NumericValue(((double)tickArray[i % 100])/1000000.0)); @@ -669,12 +692,12 @@ public class Auxiliary { expression.addContextFunction("game_tick", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; ServerCommandSource s = cc.s; - if (!s.getMinecraftServer().isOnThread()) throw new InternalExpressionException("Unable to run ticks from threads"); + if (!s.getServer().isOnThread()) throw new InternalExpressionException("Unable to run ticks from threads"); if (CarpetServer.scriptServer.tickDepth > 16) throw new InternalExpressionException("'game_tick' function caused other 'game_tick' functions to run. You should not allow that."); try { CarpetServer.scriptServer.tickDepth ++; - ((MinecraftServerInterface) s.getMinecraftServer()).forceTick(() -> System.nanoTime() - CarpetServer.scriptServer.tickStart < 50000000L); + ((MinecraftServerInterface) s.getServer()).forceTick(() -> System.nanoTime() - CarpetServer.scriptServer.tickStart < 50000000L); if (lv.size() > 0) { long ms_total = NumericValue.asNumber(lv.get(0)).getLong(); @@ -724,13 +747,13 @@ public class Auxiliary { ValueConversions.of( ((CarpetContext)c).s.getWorld())); expression.addContextFunction("view_distance", 0, (c, t, lv) -> - new NumericValue(((CarpetContext)c).s.getMinecraftServer().getPlayerManager().getViewDistance())); + new NumericValue(((CarpetContext)c).s.getServer().getPlayerManager().getViewDistance())); // lazy due to passthrough and context changing ability expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> { ServerCommandSource outerSource = ((CarpetContext)c).s; Value dimensionValue = lv.get(0).evalValue(c); - World world = ValueConversions.dimFromValue(dimensionValue, outerSource.getMinecraftServer()); + World world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer()); if (world == outerSource.getWorld()) return lv.get(1); ServerCommandSource innerSource = outerSource.withWorld((ServerWorld)world); Context newCtx = c.recreate(); @@ -753,13 +776,13 @@ public class Auxiliary { ListValue.wrap(Registry.FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("configured_features"), - ListValue.wrap(registryManager.get(Registry.CONFIGURED_FEATURE_WORLDGEN).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(registryManager.get(Registry.CONFIGURED_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("structures"), ListValue.wrap(Registry.STRUCTURE_FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("configured_structures"), - ListValue.wrap(registryManager.get(Registry.CONFIGURED_STRUCTURE_FEATURE_WORLDGEN).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(registryManager.get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); return MapValue.wrap(plopData); } @@ -768,7 +791,7 @@ public class Auxiliary { throw new InternalExpressionException("'plop' needs extra argument indicating what to plop"); String what = lv.get(locator.offset).getString(); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getMinecraftServer().submitAndJoin( () -> + ((CarpetContext)c).s.getServer().submitAndJoin( () -> { Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getWorld(), locator.block.getPos()); @@ -837,7 +860,7 @@ public class Auxiliary { Value retVal; if (fdesc.type == FileArgument.Type.NBT) { - Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); + NbtElement state = ((CarpetScriptHost) c.host).readFileTag(fdesc); if (state == null) return Value.NULL; retVal = new NBTSerializableValue(state); } @@ -874,7 +897,7 @@ public class Auxiliary { NBTSerializableValue tagValue = (val instanceof NBTSerializableValue) ? (NBTSerializableValue) val : new NBTSerializableValue(val.getString()); - Tag tag = tagValue.getTag(); + NbtElement tag = tagValue.getTag(); success = ((CarpetScriptHost) c.host).writeTagFile(tag, fdesc); } else if (fdesc.type == FileArgument.Type.JSON) @@ -946,7 +969,7 @@ public class Auxiliary { expression.addContextFunction("statistic", 3, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerPlayerEntity player = EntityValue.getPlayerByValue(cc.s.getMinecraftServer(), lv.get(0)); + ServerPlayerEntity player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0)); if (player == null) return Value.NULL; Identifier category; Identifier statName; @@ -1000,11 +1023,11 @@ public class Auxiliary { expression.addContextFunction("nbt_storage", -1, (c, t, lv) -> { if (lv.size() > 2) throw new InternalExpressionException("'nbt_storage' requires 0, 1 or 2 arguments."); CarpetContext cc = (CarpetContext) c; - DataCommandStorage storage = cc.s.getMinecraftServer().getDataCommandStorage(); + DataCommandStorage storage = cc.s.getServer().getDataCommandStorage(); if (lv.size() == 0) return ListValue.wrap(storage.getIds().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList())); String key = lv.get(0).getString(); - CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key)); + NbtCompound old_nbt = storage.get(InputValidator.identifierOf(key)); if (lv.size() == 2) { Value nbt = lv.get(1); NBTSerializableValue new_nbt = (nbt instanceof NBTSerializableValue) ? (NBTSerializableValue) nbt @@ -1019,7 +1042,7 @@ public class Auxiliary { CarpetContext cc = (CarpetContext)c; String origName = lv.get(0).getString(); String name = InputValidator.validateSimpleString(origName, true); - MinecraftServer server = cc.s.getMinecraftServer(); + MinecraftServer server = cc.s.getServer(); for (String dpName : server.getDataPackManager().getNames()) { if (dpName.equalsIgnoreCase("file/"+name+".zip") || @@ -1084,7 +1107,7 @@ public class Auxiliary { expression.addContextFunction("enable_hidden_dimensions", 0, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; // from minecraft.server.Main.main - MinecraftServer server = cc.s.getMinecraftServer(); + MinecraftServer server = cc.s.getServer(); LevelStorage.Session session = ((MinecraftServerInterface)server).getCMSession(); DataPackSettings dataPackSettings = session.getDataPackSettings(); ResourcePackManager resourcePackManager = server.getDataPackManager(); @@ -1099,7 +1122,7 @@ public class Auxiliary { //not sure its needed, but doesn't seem to have a negative effect and might be used in some custom shtuff serverRM.loadRegistryTags(); - RegistryOps registryOps = RegistryOps.of(NbtOps.INSTANCE, serverRM.getResourceManager(), (DynamicRegistryManager.Impl) server.getRegistryManager()); + RegistryOps registryOps = RegistryOps.of(NbtOps.INSTANCE, serverRM.getResourceManager(), (DynamicRegistryManager.Impl) server.getRegistryManager()); SaveProperties saveProperties = session.readLevelProperties(registryOps, dataPackSettings2); if (saveProperties == null) return Value.NULL; //session.backupLevelDataFile(server.getRegistryManager(), saveProperties); // no need @@ -1117,7 +1140,7 @@ public class Auxiliary { if (!existing_worlds.containsKey(registryKey)) { addeds.add(ValueConversions.of(registryKey.getValue())); - RegistryKey registryKey2 = RegistryKey.of(Registry.DIMENSION, registryKey.getValue()); + RegistryKey registryKey2 = RegistryKey.of(Registry.WORLD_KEY, registryKey.getValue()); DimensionType dimensionType3 = entry.getValue().getDimensionType(); ChunkGenerator chunkGenerator3 = entry.getValue().getChunkGenerator(); UnmodifiableLevelProperties unmodifiableLevelProperties = new UnmodifiableLevelProperties(saveProperties, ((ServerWorldInterface) server.getOverworld()).getWorldPropertiesCM()); diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index 902d264d..db68f7be 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -19,7 +19,7 @@ import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnReason; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; @@ -48,7 +48,7 @@ public class Entities { CarpetContext cc = (CarpetContext)c; if (cc.host.user != null) { - ServerPlayerEntity player = cc.s.getMinecraftServer().getPlayerManager().getPlayer(cc.host.user); + ServerPlayerEntity player = cc.s.getServer().getPlayerManager().getPlayer(cc.host.user); return EntityValue.of(player); } Entity callingEntity = cc.s.getEntity(); @@ -62,7 +62,7 @@ public class Entities { if ("all".equalsIgnoreCase(playerName)) { retval = ListValue.wrap( - ((CarpetContext)c).s.getMinecraftServer().getPlayerManager().getPlayerList(). + ((CarpetContext)c).s.getServer().getPlayerManager().getPlayerList(). stream().map(EntityValue::new).collect(Collectors.toList())); } else if ("*".equalsIgnoreCase(playerName)) @@ -97,7 +97,7 @@ public class Entities { } else { - ServerPlayerEntity player = ((CarpetContext) c).s.getMinecraftServer().getPlayerManager().getPlayer(playerName); + ServerPlayerEntity player = ((CarpetContext) c).s.getServer().getPlayerManager().getPlayer(playerName); if (player != null) retval = new EntityValue(player); } @@ -126,7 +126,7 @@ public class Entities { Vector3Argument position = Vector3Argument.findIn(lv, 1); if (position.fromBlock) position.vec = position.vec.subtract(0, 0.5, 0); - CompoundTag tag = new CompoundTag(); + NbtCompound tag = new NbtCompound(); boolean hasTag = false; if (lv.size() > position.offset) { @@ -142,7 +142,7 @@ public class Entities { ServerWorld serverWorld = cc.s.getWorld(); Entity entity_1 = EntityType.loadEntityWithPassengers(tag, serverWorld, (entity_1x) -> { - entity_1x.refreshPositionAndAngles(vec3d.x, vec3d.y, vec3d.z, entity_1x.yaw, entity_1x.pitch); + entity_1x.refreshPositionAndAngles(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYaw(), entity_1x.getPitch()); return !serverWorld.tryLoadEntity(entity_1x) ? null : entity_1x; }); if (entity_1 == null) { @@ -167,8 +167,8 @@ public class Entities { { String who = lv.get(0).getString(); ServerCommandSource source = ((CarpetContext)c).s; - EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getMinecraftServer()); - List entityList = source.getWorld().getEntitiesByType(eDesc.directType, eDesc.filteringPredicate); + EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); + List entityList = source.getWorld().getEntitiesByType(eDesc.directType, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList())); }); @@ -195,7 +195,7 @@ public class Entities { throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument"); Vec3d range = rangeLocator.vec; Box area = centerBox.expand(range.x, range.y, range.z); - EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.s.getMinecraftServer()); + EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.s.getServer()); List entityList = cc.s.getWorld().getEntitiesByType(eDesc.directType, area,eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList())); }); @@ -257,7 +257,7 @@ public class Entities { { if (lv.size() > 1) throw new InternalExpressionException("'entity_types' requires one or no arguments"); String desc = (lv.size() == 1)?lv.get(0).getString():"*"; - return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).s.getMinecraftServer()).listValue; + return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).s.getServer()).listValue; }); expression.addContextFunction("entity_load_handler", -1, (c, t, lv) -> @@ -269,7 +269,7 @@ public class Entities { ? ((ListValue) entityValue).getItems().stream().map(Value::getString).collect(Collectors.toList()) : Collections.singletonList(entityValue.getString()); Set> types = new HashSet<>(); - descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).s.getMinecraftServer()).typeList)); + descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).s.getServer()).typeList)); FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); CarpetEventServer events = ((CarpetScriptHost)c.host).getScriptServer().events; if (funArg.function == null) diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index f062d484..75838238 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -26,7 +26,7 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.s2c.play.ScreenHandlerSlotUpdateS2CPacket; import net.minecraft.recipe.AbstractCookingRecipe; import net.minecraft.recipe.CuttingRecipe; @@ -36,6 +36,7 @@ import net.minecraft.recipe.ShapedRecipe; import net.minecraft.recipe.ShapelessRecipe; import net.minecraft.recipe.SpecialCraftingRecipe; import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.tag.Tag; import net.minecraft.tag.TagManager; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; @@ -65,9 +66,9 @@ public class Inventories { if (lv.size() == 0) return ListValue.wrap(Registry.ITEM.getIds().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getMinecraftServer().getTagManager(); + TagManager tagManager = cc.s.getServer().getTagManager(); String tag = lv.get(0).getString(); - net.minecraft.tag.Tag itemTag = tagManager.getItems().getTag(InputValidator.identifierOf(tag)); + net.minecraft.tag.Tag itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag)); if (itemTag == null) return Value.NULL; return ListValue.wrap(itemTag.values().stream().map(b -> ValueConversions.of(Registry.ITEM.getId(b))).collect(Collectors.toList())); }); @@ -75,16 +76,16 @@ public class Inventories { expression.addContextFunction("item_tags", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getMinecraftServer().getTagManager(); + TagManager tagManager = cc.s.getServer().getTagManager(); if (lv.size() == 0) - return ListValue.wrap(tagManager.getItems().getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList())); Item item = NBTSerializableValue.parseItem(lv.get(0).getString()).getItem(); if (lv.size() == 1) - return ListValue.wrap(tagManager.getItems().getTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); String tag = lv.get(1).getString(); - net.minecraft.tag.Tag itemTag = tagManager.getItems().getTag(InputValidator.identifierOf(tag)); + net.minecraft.tag.Tag itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag)); if (itemTag == null) return Value.NULL; - return BooleanValue.of(item.isIn(itemTag)); + return BooleanValue.of(itemTag.contains(item)); }); expression.addContextFunction("recipe_data", -1, (c, t, lv) -> @@ -99,7 +100,7 @@ public class Inventories { type = Registry.RECIPE_TYPE.get(InputValidator.identifierOf(recipeType)); } List> recipes; - recipes = ((RecipeManagerInterface) cc.s.getMinecraftServer().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName)); + recipes = ((RecipeManagerInterface) cc.s.getServer().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName)); if (recipes.isEmpty()) return Value.NULL; List recipesOutput = new ArrayList<>(); @@ -107,7 +108,7 @@ public class Inventories { { ItemStack result = recipe.getOutput(); List ingredientValue = new ArrayList<>(); - recipe.getPreviewInputs().forEach( + recipe.getIngredients().forEach( ingredient -> { // I am flattening ingredient lists per slot. @@ -239,7 +240,7 @@ public class Inventories { syncPlayerInventory(inventoryLocator, slot); return ValueConversions.of(previousStack); } - CompoundTag nbt = null; // skipping one argument + NbtCompound nbt = null; // skipping one argument if (lv.size() > inventoryLocator.offset+3) { Value nbtValue = lv.get(inventoryLocator.offset+3); @@ -389,7 +390,7 @@ public class Inventories { { ServerPlayerEntity player = (ServerPlayerEntity) inventory.owner; player.networkHandler.sendPacket(new ScreenHandlerSlotUpdateS2CPacket( - -2, + -2, 0, // resolve mystery argument int_1, inventory.inventory.getStack(int_1) )); diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index 06277159..435736ba 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -70,7 +70,7 @@ public class Scoreboards { expression.addContextFunction("scoreboard", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + Scoreboard scoreboard = cc.s.getServer().getScoreboard(); if (lv.size()==0) return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new).collect(Collectors.toList())); String objectiveName = lv.get(0).getString(); @@ -103,7 +103,7 @@ public class Scoreboards { { if (lv.size()==0) throw new InternalExpressionException("'scoreboard_remove' requires at least one parameter"); CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + Scoreboard scoreboard = cc.s.getServer().getScoreboard(); String objectiveName = lv.get(0).getString(); ScoreboardObjective objective = scoreboard.getObjective(objectiveName); if (objective == null) return Value.FALSE; @@ -126,7 +126,7 @@ public class Scoreboards { expression.addContextFunction("scoreboard_add", -1, (c, t, lv)-> { CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + Scoreboard scoreboard = cc.s.getServer().getScoreboard(); if (lv.size() == 0 || lv.size()>2) throw new InternalExpressionException("'scoreboard_add' should have one or two parameters"); String objectiveName = lv.get(0).getString(); ScoreboardCriterion criterion; @@ -137,7 +137,7 @@ public class Scoreboards { else { String critetionName = lv.get(1).getString(); - criterion = ScoreboardCriterion.createStatCriterion(critetionName).orElse(null); + criterion = ScoreboardCriterion.getOrCreateStatCriterion(critetionName).orElse(null); if (criterion==null) { throw new ThrowStatement(critetionName, Throwables.UNKNOWN_CRITERION); @@ -156,7 +156,7 @@ public class Scoreboards { return Value.FALSE; } - scoreboard.addObjective(objectiveName, criterion, new LiteralText(objectiveName), criterion.getCriterionType()); + scoreboard.addObjective(objectiveName, criterion, new LiteralText(objectiveName), criterion.getDefaultRenderType()); return Value.TRUE; }); @@ -164,7 +164,7 @@ public class Scoreboards { { if(lv.size() < 2) throw new InternalExpressionException("'scoreboard_property' requires at least two parameters"); CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + Scoreboard scoreboard = cc.s.getServer().getScoreboard(); ScoreboardObjective objective = scoreboard.getObjective(lv.get(0).getString()); if(objective == null) return Value.NULL; @@ -177,7 +177,7 @@ public class Scoreboards { switch (property) { case "criterion": if(modify) { - ScoreboardCriterion criterion = ScoreboardCriterion.createStatCriterion(setValue.getString()).orElse(null); + ScoreboardCriterion criterion = ScoreboardCriterion.getOrCreateStatCriterion(setValue.getString()).orElse(null); if (criterion==null) throw new InternalExpressionException("Unknown scoreboard criterion: "+ setValue.getString()); if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.FALSE; ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective); @@ -229,7 +229,7 @@ public class Scoreboards { expression.addContextFunction("scoreboard_display", 2, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + Scoreboard scoreboard = cc.s.getServer().getScoreboard(); String location = lv.get(0).getString(); int slot = Scoreboard.getDisplaySlotId(location); if (slot < 0) throw new InternalExpressionException("Invalid objective slot: "+location); @@ -250,7 +250,7 @@ public class Scoreboards { { if(lv.size() > 1) throw new InternalExpressionException("'team_list' requires zero or one parameters"); CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); if(lv.size() == 0) return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of).collect(Collectors.toList())); if (lv.size() != 1) return Value.NULL; @@ -265,7 +265,7 @@ public class Scoreboards { if(!(lv.size() < 3 && lv.size() > 0)) throw new InternalExpressionException("'team_add' requires one or two parameters"); CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); String teamName = lv.get(0).getString(); if(lv.size() == 1) @@ -288,7 +288,7 @@ public class Scoreboards { expression.addContextFunction("team_remove", 1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); Value teamVal = lv.get(0); String team = teamVal.getString(); if(scoreboard.getTeam(team) == null) return Value.NULL; @@ -300,7 +300,7 @@ public class Scoreboards { expression.addContextFunction("team_leave", 1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); Value playerVal = lv.get(0); String player = EntityValue.getPlayerNameByValue(playerVal); if(player == null) return Value.NULL; @@ -310,7 +310,7 @@ public class Scoreboards { expression.addContextFunction("team_property", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getMinecraftServer().getScoreboard(); + ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); if(lv.size() < 2 || lv.size() > 3) throw new InternalExpressionException("'team_property' requires two or three arguments"); @@ -401,7 +401,7 @@ public class Scoreboards { expression.addContextFunction("bossbar", -1, (c, t, lv) -> { - BossBarManager bossBarManager = ((CarpetContext)c).s.getMinecraftServer().getBossBarManager(); + BossBarManager bossBarManager = ((CarpetContext)c).s.getServer().getBossBarManager(); if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments"); if(lv.size() == 0) return ListValue.wrap(bossBarManager.getAll().stream().map(CommandBossBar::getId).map(Identifier::toString).map(StringValue::of).collect(Collectors.toList())); @@ -451,13 +451,13 @@ public class Scoreboards { if(propertyValue instanceof ListValue) { ((ListValue) propertyValue).getItems().forEach((v)->{ - ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getMinecraftServer(),propertyValue); + ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue); if(player != null) bossBar.addPlayer(player); }); return Value.TRUE; } - ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getMinecraftServer(), propertyValue); + ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); if(player != null) { bossBar.addPlayer(player); return Value.TRUE; @@ -469,14 +469,14 @@ public class Scoreboards { { bossBar.clearPlayers(); ((ListValue) propertyValue).getItems().forEach((v) -> { - ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getMinecraftServer(), v); + ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v); if (p != null) bossBar.addPlayer(p); }); return Value.TRUE; } - ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getMinecraftServer(), propertyValue); + ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); bossBar.clearPlayers(); if (p != null) { bossBar.addPlayer(p); @@ -484,10 +484,10 @@ public class Scoreboards { } return Value.FALSE; case "style": - if(propertyValue == null) return StringValue.of(bossBar.getOverlay().getName()); + if(propertyValue == null) return StringValue.of(bossBar.getStyle().getName()); BossBar.Style style = BossBar.Style.byName(propertyValue.getString()); if(style == null) throw new InternalExpressionException("'" + propertyValue.getString() + "' is not a valid value for property " + property); - bossBar.setOverlay(style); + bossBar.setStyle(style); return Value.TRUE; case "value": if(propertyValue == null) return NumericValue.of(bossBar.getValue()); diff --git a/src/main/java/carpet/script/api/Threading.java b/src/main/java/carpet/script/api/Threading.java index baff04ab..257f4084 100644 --- a/src/main/java/carpet/script/api/Threading.java +++ b/src/main/java/carpet/script/api/Threading.java @@ -16,7 +16,7 @@ public class Threading { //"overidden" native call to cancel if on main thread expression.addContextFunction("task_join", 1, (c, t, lv) -> { - if (((CarpetContext)c).s.getMinecraftServer().isOnThread()) + if (((CarpetContext)c).s.getServer().isOnThread()) throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks"); Value v = lv.get(0); if (!(v instanceof ThreadValue)) @@ -27,13 +27,13 @@ public class Threading // has to be lazy due to deferred execution of the expression expression.addLazyFunctionWithDelegation("task_dock", 1, false,true, (c, t, expr, tok, lv) -> { CarpetContext cc = (CarpetContext)c; - MinecraftServer server = cc.s.getMinecraftServer(); + MinecraftServer server = cc.s.getServer(); if (server.isOnThread()) return lv.get(0); // pass through for on thread tasks Value[] result = new Value[]{Value.NULL}; RuntimeException[] internal = new RuntimeException[]{null}; try { - ((CarpetContext) c).s.getMinecraftServer().submitAndJoin(() -> + ((CarpetContext) c).s.getServer().submitAndJoin(() -> { try { diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 48c699a5..4bd79a1d 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -62,8 +62,8 @@ import net.minecraft.item.MiningToolItem; import net.minecraft.item.ShearsItem; import net.minecraft.item.SwordItem; import net.minecraft.item.TridentItem; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtElement; import net.minecraft.network.packet.s2c.play.ExplosionS2CPacket; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ChunkTicket; @@ -74,6 +74,7 @@ import net.minecraft.sound.SoundCategory; import net.minecraft.state.StateManager; import net.minecraft.state.property.Property; import net.minecraft.structure.StructureStart; +import net.minecraft.tag.Tag; import net.minecraft.tag.TagManager; import net.minecraft.util.ActionResult; import net.minecraft.util.Clearable; @@ -245,7 +246,7 @@ public class WorldAccess { return true; } else { ItemStack itemStack_1 = player.getMainHandStack(); - boolean boolean_2 = player.isUsingEffectiveTool(blockState_1); + boolean boolean_2 = player.canHarvest(blockState_1); itemStack_1.postMine(player.world, blockState_1, blockPos_1, player); if (boolean_1 && boolean_2) { ItemStack itemStack_2 = itemStack_1.isEmpty() ? ItemStack.EMPTY : itemStack_1.copy(); @@ -286,7 +287,7 @@ public class WorldAccess { { if (lv.size() == 0) throw new InternalExpressionException("Block requires at least one parameter"); - CompoundTag tag = BlockArgument.findIn( (CarpetContext) c, lv, 0, true).block.getData(); + NbtCompound tag = BlockArgument.findIn( (CarpetContext) c, lv, 0, true).block.getData(); return NBTSerializableValue.of(tag); }); @@ -582,7 +583,7 @@ public class WorldAccess { { c.host.issueDeprecation("loaded_ep(...)"); BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - return BooleanValue.of(((CarpetContext)c).s.getWorld().getChunkManager().shouldTickChunk(new ChunkPos(pos))); + return BooleanValue.of(((CarpetContext)c).s.getWorld().method_37118(pos));// 1.17pre1 getChunkManager().shouldTickChunk(new ChunkPos(pos))); }); expression.addContextFunction("loaded_status", -1, (c, t, lv) -> @@ -698,7 +699,7 @@ public class WorldAccess { boolean previous = CarpetSettings.impendingFillSkipUpdates.get(); if (previous) return lv.get(0); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getMinecraftServer().submitAndJoin( () -> + ((CarpetContext)c).s.getServer().submitAndJoin( () -> { try { @@ -721,7 +722,7 @@ public class WorldAccess { BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); BlockState sourceBlockState = sourceLocator.block.getBlockState(); BlockState targetBlockState = world.getBlockState(targetLocator.block.getPos()); - CompoundTag data = null; + NbtCompound data = null; if (lv.size() > sourceLocator.offset) { List args = new ArrayList<>(); @@ -780,14 +781,14 @@ public class WorldAccess { } if (data == null) data = sourceLocator.block.getData(); - CompoundTag finalData = data; + NbtCompound finalData = data; if (sourceBlockState == targetBlockState && data == null) return Value.FALSE; BlockState finalSourceBlockState = sourceBlockState; BlockPos targetPos = targetLocator.block.getPos(); Boolean[] result = new Boolean[]{true}; - cc.s.getMinecraftServer().submitAndJoin( () -> + cc.s.getServer().submitAndJoin( () -> { Clearable.clear(world.getBlockEntity(targetPos)); boolean success = world.setBlockState(targetPos, finalSourceBlockState, 2); @@ -796,11 +797,11 @@ public class WorldAccess { BlockEntity be = world.getBlockEntity(targetPos); if (be != null) { - CompoundTag destTag = finalData.copy(); + NbtCompound destTag = finalData.copy(); destTag.putInt("x", targetPos.getX()); destTag.putInt("y", targetPos.getY()); destTag.putInt("z", targetPos.getZ()); - be.fromTag(finalSourceBlockState, destTag); + be.readNbt(destTag); be.markDirty(); success = true; } @@ -838,7 +839,7 @@ public class WorldAccess { .orElseThrow(() -> new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM)); } } - CompoundTag tag = null; + NbtCompound tag = null; if (lv.size() > locator.offset+1) { if (!playerBreak) throw new InternalExpressionException("tag is not necessary with 'destroy' with no item"); @@ -866,7 +867,7 @@ public class WorldAccess { boolean dropLoot = true; if (playerBreak) { - boolean isUsingEffectiveTool = !state.isToolRequired() || tool.isEffectiveOn(state); + boolean isUsingEffectiveTool = !state.isToolRequired() || tool.isSuitableFor(state); //postMine() durability from item classes float hardness = state.getHardness(world, where); int damageAmount = 0; @@ -901,7 +902,7 @@ public class WorldAccess { return Value.TRUE; if (toolBroke) return Value.NULL; - Tag outtag = tool.getTag(); + NbtElement outtag = tool.getTag(); if (outtag == null) return Value.TRUE; return new NBTSerializableValue(() -> outtag); @@ -1083,7 +1084,7 @@ public class WorldAccess { expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - BlockInfo.mapColourName.get(s.getTopMaterialColor(((CarpetContext)c).s.getWorld(), p)))); + BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext)c).s.getWorld(), p)))); // Deprecated for block_state() @@ -1141,9 +1142,9 @@ public class WorldAccess { if (lv.size() == 0) return ListValue.wrap(Registry.BLOCK.getIds().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getMinecraftServer().getTagManager(); + TagManager tagManager = cc.s.getServer().getTagManager(); String tag = lv.get(0).getString(); - net.minecraft.tag.Tag blockTag = tagManager.getBlocks().getTag(InputValidator.identifierOf(tag)); + net.minecraft.tag.Tag blockTag = tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTag(InputValidator.identifierOf(tag)); if (blockTag == null) return Value.NULL; return ListValue.wrap(blockTag.values().stream().map(b -> ValueConversions.of(Registry.BLOCK.getId(b))).collect(Collectors.toList())); }); @@ -1151,17 +1152,17 @@ public class WorldAccess { expression.addContextFunction("block_tags", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getMinecraftServer().getTagManager(); + TagManager tagManager = cc.s.getServer().getTagManager(); if (lv.size() == 0) - return ListValue.wrap(tagManager.getBlocks().getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList())); BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); if (blockLocator.offset == lv.size()) { Block target = blockLocator.block.getBlockState().getBlock(); - return ListValue.wrap(tagManager.getBlocks().getTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); } String tag = lv.get(blockLocator.offset).getString(); - net.minecraft.tag.Tag blockTag = tagManager.getBlocks().getTag(InputValidator.identifierOf(tag)); + Tag blockTag = tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTag(InputValidator.identifierOf(tag)); if (blockTag == null) return Value.NULL; return BooleanValue.of(blockLocator.block.getBlockState().isIn(blockTag)); }); @@ -1188,7 +1189,7 @@ public class WorldAccess { // in locatebiome if (locator.offset == lv.size()) { - Identifier biomeId = cc.s.getMinecraftServer().getRegistryManager().get(Registry.BIOME_KEY).getId(biome); + Identifier biomeId = cc.s.getServer().getRegistryManager().get(Registry.BIOME_KEY).getId(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } String biomeFeature = lv.get(locator.offset).getString(); @@ -1205,7 +1206,7 @@ public class WorldAccess { throw new InternalExpressionException("'set_biome' needs a biome name as an argument"); String biomeName = lv.get(locator.offset+0).getString(); // from locatebiome command code - Biome biome = cc.s.getMinecraftServer().getRegistryManager().get(Registry.BIOME_KEY).getOrEmpty(InputValidator.identifierOf(biomeName)) + Biome biome = cc.s.getServer().getRegistryManager().get(Registry.BIOME_KEY).getOrEmpty(InputValidator.identifierOf(biomeName)) .orElseThrow(() -> new ThrowStatement(biomeName, Throwables.UNKNOWN_BIOME)); boolean doImmediateUpdate = true; if (lv.size() > locator.offset+1) @@ -1224,7 +1225,7 @@ public class WorldAccess { CarpetContext cc = (CarpetContext)c; BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); ServerWorld world = cc.s.getWorld(); - cc.s.getMinecraftServer().submitAndJoin( () -> WorldTools.forceChunkUpdate(pos, world)); + cc.s.getServer().submitAndJoin( () -> WorldTools.forceChunkUpdate(pos, world)); return Value.TRUE; }); @@ -1323,10 +1324,10 @@ public class WorldAccess { StructureStart start = entry.getValue(); if (start == StructureStart.DEFAULT) continue; - BlockBox box = start.getBoundingBox(); + BlockBox box = start.setBoundingBoxFromChildren(); structureList.put( new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getId(entry.getKey()))), - ListValue.of(ListValue.fromTriple(box.minX, box.minY, box.minZ), ListValue.fromTriple(box.maxX, box.maxY, box.maxZ)) + ListValue.of(ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()), ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ())) ); } return MapValue.wrap(structureList); @@ -1351,7 +1352,7 @@ public class WorldAccess { // good 'ol pointer Value[] result = new Value[]{Value.NULL}; // technically a world modification. Even if we could let it slide, we will still park it - ((CarpetContext) c).s.getMinecraftServer().submitAndJoin(() -> + ((CarpetContext) c).s.getServer().submitAndJoin(() -> { Map, StructureStart> structures = world.getChunk(pos).getStructureStarts(); if (lv.size() == locator.offset + 1) @@ -1371,11 +1372,11 @@ public class WorldAccess { return; } StructureStart start = structures.get(structure); - ChunkPos structureChunkPos = new ChunkPos(start.getChunkX(), start.getChunkZ()); - BlockBox box = start.getBoundingBox(); - for (int chx = box.minX / 16; chx <= box.maxX / 16; chx++) + ChunkPos structureChunkPos = start.getPos(); // new ChunkPos(start.getChunkX(), start.getChunkZ()); + BlockBox box = start.setBoundingBoxFromChildren(); + for (int chx = box.getMinX() / 16; chx <= box.getMaxX() / 16; chx++) // minx maxx { - for (int chz = box.minZ / 16; chz <= box.maxZ / 16; chz++) + for (int chz = box.getMinZ() / 16; chz <= box.getMaxZ() / 16; chz++) //minZ maxZ { ChunkPos chpos = new ChunkPos(chx, chz); // getting a chunk will convert it to full, allowing to modify references @@ -1413,7 +1414,7 @@ public class WorldAccess { } } - boolean success = WorldTools.createWorld(cc.s.getMinecraftServer(), worldKey, seed); + boolean success = WorldTools.createWorld(cc.s.getServer(), worldKey, seed); if (!success) return Value.FALSE; CarpetServer.settingsManager.notifyPlayersCommandsChanged(); return Value.TRUE; @@ -1472,16 +1473,16 @@ public class WorldAccess { Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getMinecraftServer().submitAndJoin( () -> + ((CarpetContext)c).s.getServer().submitAndJoin( () -> { Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkManager().threadedAnvilChunkStorage).regenerateChunkRegion(requestedChunks); - for (ChunkPos chpos: requestedChunks) + /*for (ChunkPos chpos: requestedChunks) // needed in 1.16 only { if (world.getChunk(chpos.x, chpos.z, ChunkStatus.FULL, false) != null) { WorldTools.forceChunkUpdate(chpos.getStartPos(), world); } - } + }*/ result[0] = MapValue.wrap(report.entrySet().stream().collect(Collectors.toMap( e -> new StringValue((String)((Map.Entry) e).getKey()), e -> new NumericValue((Integer)((Map.Entry) e).getValue()) diff --git a/src/main/java/carpet/script/argument/FileArgument.java b/src/main/java/carpet/script/argument/FileArgument.java index 02d0728b..22984c8b 100644 --- a/src/main/java/carpet/script/argument/FileArgument.java +++ b/src/main/java/carpet/script/argument/FileArgument.java @@ -14,11 +14,11 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtIo; -import net.minecraft.nbt.PositionTracker; -import net.minecraft.nbt.Tag; -import net.minecraft.nbt.TagReaders; +import net.minecraft.nbt.NbtTagSizeTracker; +import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.NbtTypes; import net.minecraft.util.WorldSavePath; import net.minecraft.util.crash.CrashException; import org.apache.commons.io.FilenameUtils; @@ -331,7 +331,7 @@ public class FileArgument return true; } - public Tag getNbtData(Module module) // aka getData + public NbtElement getNbtData(Module module) // aka getData { try { synchronized (writeIOSync) { Path dataFile = toPath(module); @@ -345,7 +345,7 @@ public class FileArgument //copied private method from net.minecraft.nbt.NbtIo.read() // to read non-compound tags - these won't be compressed - public static Tag readTag(Path path) + public static NbtElement readTag(Path path) { try { @@ -375,7 +375,7 @@ public class FileArgument else { dataInput_1.readUTF(); - return TagReaders.of(byte_1).read(dataInput_1, 0, PositionTracker.DEFAULT); + return NbtTypes.byId(byte_1).read(dataInput_1, 0, NbtTagSizeTracker.EMPTY); } } catch (IOException secondIO) @@ -393,7 +393,7 @@ public class FileArgument } } - public boolean saveNbtData(Module module, Tag tag) // aka saveData + public boolean saveNbtData(Module module, NbtElement tag) // aka saveData { try { synchronized (writeIOSync) { Path dataFile = toPath(module); @@ -408,7 +408,7 @@ public class FileArgument } //copied private method from net.minecraft.nbt.NbtIo.write() and client method safe_write - public static boolean writeTagDisk(Tag tag_1, Path path, boolean zipped) + public static boolean writeTagDisk(NbtElement tag_1, Path path, boolean zipped) { Path original = path; try @@ -419,9 +419,9 @@ public class FileArgument Files.deleteIfExists(path); } - if (tag_1 instanceof CompoundTag) + if (tag_1 instanceof NbtCompound) { - NbtIo.writeCompressed((CompoundTag) tag_1, Files.newOutputStream(path)); + NbtIo.writeCompressed((NbtCompound) tag_1, Files.newOutputStream(path)); } else { diff --git a/src/main/java/carpet/script/bundled/Module.java b/src/main/java/carpet/script/bundled/Module.java index a6d29d85..369f4197 100644 --- a/src/main/java/carpet/script/bundled/Module.java +++ b/src/main/java/carpet/script/bundled/Module.java @@ -2,7 +2,7 @@ package carpet.script.bundled; import carpet.CarpetServer; import carpet.script.argument.FileArgument; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtElement; import net.minecraft.util.WorldSavePath; import java.nio.file.Files; @@ -14,7 +14,7 @@ public abstract class Module public abstract String getCode(); public abstract boolean isLibrary(); - public static Tag getData(Module module) + public static NbtElement getData(Module module) { Path dataFile = resolveResource(module); if (dataFile == null) return null; @@ -22,7 +22,7 @@ public abstract class Module synchronized (FileArgument.writeIOSync) { return FileArgument.readTag(dataFile); } } - public static void saveData(Module module, Tag globalState) + public static void saveData(Module module, NbtElement globalState) { Path dataFile = resolveResource(module); if (dataFile == null) return; diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 1a406c3c..92cc3392 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -50,18 +50,18 @@ import net.minecraft.command.argument.EntityArgumentType; import net.minecraft.command.argument.EntitySummonArgumentType; import net.minecraft.command.argument.GameProfileArgumentType; import net.minecraft.command.argument.IdentifierArgumentType; -import net.minecraft.command.argument.ItemEnchantmentArgumentType; +import net.minecraft.command.argument.EnchantmentArgumentType; import net.minecraft.command.argument.ItemSlotArgumentType; import net.minecraft.command.argument.ItemStackArgumentType; import net.minecraft.command.argument.MessageArgumentType; -import net.minecraft.command.argument.MobEffectArgumentType; -import net.minecraft.command.argument.NbtCompoundTagArgumentType; +import net.minecraft.command.argument.StatusEffectArgumentType; +import net.minecraft.command.argument.NbtCompoundArgumentType; import net.minecraft.command.argument.NbtPathArgumentType; -import net.minecraft.command.argument.NbtTagArgumentType; +import net.minecraft.command.argument.NbtElementArgumentType; import net.minecraft.command.argument.NumberRangeArgumentType; -import net.minecraft.command.argument.ObjectiveArgumentType; -import net.minecraft.command.argument.ObjectiveCriteriaArgumentType; -import net.minecraft.command.argument.ParticleArgumentType; +import net.minecraft.command.argument.ScoreboardObjectiveArgumentType; +import net.minecraft.command.argument.ScoreboardCriterionArgumentType; +import net.minecraft.command.argument.ParticleEffectArgumentType; import net.minecraft.command.argument.RotationArgumentType; import net.minecraft.command.argument.ScoreHolderArgumentType; import net.minecraft.command.argument.ScoreboardSlotArgumentType; @@ -132,7 +132,7 @@ public abstract class CommandArgument false ), new VanillaUnconfigurableArgument( "blockpredicate", BlockPredicateArgumentType::blockPredicate, - (c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getMinecraftServer().getTagManager(), BlockPredicateArgumentType.getBlockPredicate(c, p)), false + (c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getServer().getTagManager(), BlockPredicateArgumentType.getBlockPredicate(c, p)), false ), new VanillaUnconfigurableArgument("teamcolor", ColorArgumentType::color, (c, p) -> { @@ -155,17 +155,17 @@ public abstract class CommandArgument new VanillaUnconfigurableArgument("entitytype", EntitySummonArgumentType::entitySummon, (c, p) -> ValueConversions.of(EntitySummonArgumentType.getEntitySummon(c, p)), SuggestionProviders.SUMMONABLE_ENTITIES ), - new VanillaUnconfigurableArgument("floatrange", NumberRangeArgumentType::method_30918, + new VanillaUnconfigurableArgument("floatrange", NumberRangeArgumentType::floatRange, (c, p) -> ValueConversions.of(c.getArgument(p, NumberRange.FloatRange.class)), true ), // function?? new PlayerProfileArgument(), - new VanillaUnconfigurableArgument("intrange", NumberRangeArgumentType::numberRange, + new VanillaUnconfigurableArgument("intrange", NumberRangeArgumentType::intRange, (c, p) -> ValueConversions.of(NumberRangeArgumentType.IntRangeArgumentType.getRangeArgument(c, p)), true ), - new VanillaUnconfigurableArgument("enchantment", ItemEnchantmentArgumentType::itemEnchantment, - (c, p) -> ValueConversions.of(Registry.ENCHANTMENT.getId(ItemEnchantmentArgumentType.getEnchantment(c, p))), false + new VanillaUnconfigurableArgument("enchantment", EnchantmentArgumentType::enchantment, + (c, p) -> ValueConversions.of(Registry.ENCHANTMENT.getId(EnchantmentArgumentType.getEnchantment(c, p))), false ), // item_predicate ?? //same as item but accepts tags, not sure right now new SlotArgument(), @@ -175,22 +175,22 @@ public abstract class CommandArgument new VanillaUnconfigurableArgument("message", MessageArgumentType::message, (c, p) -> new FormattedTextValue(MessageArgumentType.getMessage(c, p)), true ), - new VanillaUnconfigurableArgument("effect", MobEffectArgumentType::mobEffect, - (c, p) -> ValueConversions.of(Registry.STATUS_EFFECT.getId(MobEffectArgumentType.getMobEffect(c, p))),false + new VanillaUnconfigurableArgument("effect", StatusEffectArgumentType::statusEffect, + (c, p) -> ValueConversions.of(Registry.STATUS_EFFECT.getId(StatusEffectArgumentType.getStatusEffect(c, p))),false ), new TagArgument(), // for nbt_compound_tag and nbt_tag new VanillaUnconfigurableArgument("path", NbtPathArgumentType::nbtPath, (c, p) -> StringValue.of(NbtPathArgumentType.getNbtPath(c, p).toString()), true ), - new VanillaUnconfigurableArgument("objective", ObjectiveArgumentType::objective, - (c, p) -> ValueConversions.of(ObjectiveArgumentType.getObjective(c, p)), false + new VanillaUnconfigurableArgument("objective", ScoreboardObjectiveArgumentType::scoreboardObjective, + (c, p) -> ValueConversions.of(ScoreboardObjectiveArgumentType.getObjective(c, p)), false ), - new VanillaUnconfigurableArgument("criterion", ObjectiveCriteriaArgumentType::objectiveCriteria, - (c, p) -> StringValue.of(ObjectiveCriteriaArgumentType.getCriteria(c, p).getName()), false + new VanillaUnconfigurableArgument("criterion", ScoreboardCriterionArgumentType::scoreboardCriterion, + (c, p) -> StringValue.of(ScoreboardCriterionArgumentType.getCriterion(c, p).getName()), false ), // operation // not sure if we need it, you have scarpet for that - new VanillaUnconfigurableArgument("particle", ParticleArgumentType::particle, - (c, p) -> ValueConversions.of(ParticleArgumentType.getParticle(c, p)), false + new VanillaUnconfigurableArgument("particle", ParticleEffectArgumentType::particleEffect, + (c, p) -> ValueConversions.of(ParticleEffectArgumentType.getParticle(c, p)), false ), // resource / identifier section @@ -199,16 +199,16 @@ public abstract class CommandArgument (c, p) -> ValueConversions.of( IdentifierArgumentType.getRecipeArgument(c, p).getId()), SuggestionProviders.ALL_RECIPES ), new VanillaUnconfigurableArgument("advancement", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getAdvancementArgument(c, p).getId()), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getMinecraftServer().getAdvancementLoader().getAdvancements().stream().map(Advancement::getId), builder) + (c, p) -> ValueConversions.of( IdentifierArgumentType.getAdvancementArgument(c, p).getId()), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getAdvancementLoader().getAdvancements().stream().map(Advancement::getId), builder) ), new VanillaUnconfigurableArgument("lootcondition", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( Registry.LOOT_CONDITION_TYPE.getId(IdentifierArgumentType.method_23727(c, p).getType())), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getMinecraftServer().getPredicateManager().getIds(), builder) + (c, p) -> ValueConversions.of( Registry.LOOT_CONDITION_TYPE.getId(IdentifierArgumentType.getPredicateArgument(c, p).getType())), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getPredicateManager().getIds(), builder) ), new VanillaUnconfigurableArgument("loottable", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getMinecraftServer().getLootManager().getTableIds(), builder) + (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getLootManager().getTableIds(), builder) ), new VanillaUnconfigurableArgument("attribute", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( Registry.ATTRIBUTE.getId(IdentifierArgumentType.method_27575(c, p))), (ctx, builder) -> CommandSource.suggestIdentifiers(Registry.ATTRIBUTE.getIds(), builder) + (c, p) -> ValueConversions.of( Registry.ATTRIBUTE.getId(IdentifierArgumentType.getAttributeArgument(c, p))), (ctx, builder) -> CommandSource.suggestIdentifiers(Registry.ATTRIBUTE.getIds(), builder) ), new VanillaUnconfigurableArgument("boss", IdentifierArgumentType::identifier, (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), BossBarCommand.SUGGESTION_PROVIDER @@ -220,7 +220,7 @@ public abstract class CommandArgument (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), SuggestionProviders.AVAILABLE_SOUNDS ), new VanillaUnconfigurableArgument("storekey", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getMinecraftServer().getDataCommandStorage().getIds(), builder) + (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getDataCommandStorage().getIds(), builder) ), // default @@ -698,22 +698,22 @@ public abstract class CommandArgument boolean mapRequired; private TagArgument() { - super("tag", NbtCompoundTagArgumentType.nbtCompound().getExamples(), false); + super("tag", NbtCompoundArgumentType.nbtCompound().getExamples(), false); mapRequired = true; } @Override protected ArgumentType getArgumentType() { - return mapRequired?NbtCompoundTagArgumentType.nbtCompound(): NbtTagArgumentType.nbtTag(); + return mapRequired?NbtCompoundArgumentType.nbtCompound(): NbtElementArgumentType.nbtElement(); } @Override protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { if (mapRequired) - return new NBTSerializableValue(NbtCompoundTagArgumentType.getCompoundTag(context, param)); + return new NBTSerializableValue(NbtCompoundArgumentType.getNbtCompound(context, param)); else - return new NBTSerializableValue(NbtTagArgumentType.getTag(context, param)); + return new NBTSerializableValue(NbtElementArgumentType.getNbtElement(context, param)); } @Override diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index 9c723b13..9324b477 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -305,13 +305,13 @@ public class AppStoreManager public static boolean saveScriptToFile(ServerCommandSource source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash) { Path scriptLocation; - if (globalSavePath && !source.getMinecraftServer().isDedicated()) // never happens, this is always called with globalSavePath being false + if (globalSavePath && !source.getServer().isDedicated()) // never happens, this is always called with globalSavePath being false { //cos config folder only is in clients scriptLocation = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts/appstore").toAbsolutePath().resolve(path); } else { - scriptLocation = source.getMinecraftServer().getSavePath(WorldSavePath.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName); + scriptLocation = source.getServer().getSavePath(WorldSavePath.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName); } try { @@ -384,7 +384,7 @@ public class AppStoreManager Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING); } } - + private static String getFullContentUrl(String original, StoreNode storeSource) { if (original.matches("^https?://.*$")) // We've got a full url here: Just use it diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java index 2394cddb..13603ca2 100644 --- a/src/main/java/carpet/script/utils/BiomeInfo.java +++ b/src/main/java/carpet/script/utils/BiomeInfo.java @@ -37,7 +37,7 @@ public class BiomeInfo put("scale", (w, b) -> NumericValue.of(b.getScale())); put("features", (w, b) -> { - Registry> registry = w.getRegistryManager().get(Registry.CONFIGURED_FEATURE_WORLDGEN); + Registry> registry = w.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY); return ListValue.wrap( b.getGenerationSettings().getFeatures().stream().map(step -> ListValue.wrap(step.stream().map(cfp -> @@ -47,7 +47,7 @@ public class BiomeInfo ); }); put("structures", (w, b) -> { - Registry> registry = w.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_WORLDGEN); + Registry> registry = w.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY); return ListValue.wrap(b.getGenerationSettings().getStructureFeatures().stream().map(str -> ValueConversions.of(registry.getId(str.get())))); }); }}; diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index ce9ad502..9a6225bc 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -21,16 +21,16 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.argument.ParticleArgumentType; +import net.minecraft.command.argument.ParticleEffectArgumentType; import net.minecraft.entity.Entity; -import net.minecraft.nbt.ByteTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.FloatTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtByte; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtDouble; +import net.minecraft.nbt.NbtFloat; +import net.minecraft.nbt.NbtInt; +import net.minecraft.nbt.NbtList; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import net.minecraft.particle.ParticleEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerPlayerEntity; @@ -135,7 +135,7 @@ public class ShapeDispatcher if (!clientPlayers.isEmpty()) { - ListTag tag = new ListTag(); + NbtList tag = new NbtList(); int tagcount = 0; for (Pair> s : shapes) { @@ -143,12 +143,12 @@ public class ShapeDispatcher if (tagcount++>1000) { tagcount = 0; - Tag finalTag = tag; + NbtElement finalTag = tag; clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); - tag = new ListTag(); + tag = new NbtList(); } } - Tag finalTag = tag; + NbtElement finalTag = tag; if (tag.size() > 0) clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); } if (!alternativePlayers.isEmpty()) @@ -166,7 +166,7 @@ public class ShapeDispatcher return particle; try { - particle = ParticleArgumentType.readParameters(new StringReader(name)); + particle = ParticleEffectArgumentType.readParameters(new StringReader(name)); } catch (CommandSyntaxException e) { @@ -206,7 +206,7 @@ public class ShapeDispatcher } // client - public static ExpiringShape fromTag(CompoundTag tag) + public static ExpiringShape fromTag(NbtCompound tag) { Map options = new HashMap<>(); for (String key : tag.getKeys()) @@ -277,11 +277,11 @@ public class ShapeDispatcher protected ExpiringShape() { } - public static CompoundTag toTag(Map params) + public static NbtCompound toTag(Map params) { - CompoundTag tag = new CompoundTag(); + NbtCompound tag = new NbtCompound(); params.forEach((k, v) -> { - Tag valTag = Param.of.get(k).toTag(v); + NbtElement valTag = Param.of.get(k).toTag(v); if (valTag != null) tag.put(k, valTag); }); return tag; @@ -326,7 +326,7 @@ public class ShapeDispatcher key = 0; followEntity = -1; - shapeDimension = RegistryKey.of(Registry.DIMENSION, new Identifier(options.get("dim").getString())); + shapeDimension = RegistryKey.of(Registry.WORLD_KEY, new Identifier(options.get("dim").getString())); if (options.containsKey("follow")) { followEntity = NumericValue.asNumber(options.getOrDefault("follow", optional.get("follow"))).getInt(); @@ -902,9 +902,9 @@ public class ShapeDispatcher this.id = id; } - public abstract Tag toTag(Value value); //validates value, returning null if not necessary to keep it and serialize + public abstract NbtElement toTag(Value value); //validates value, returning null if not necessary to keep it and serialize public abstract Value validate(Map options, MinecraftServer server, Value value); // makes sure the value is proper - public abstract Value decode(Tag tag); + public abstract Value decode(NbtElement tag); } public abstract static class StringParam extends Param @@ -912,8 +912,8 @@ public class ShapeDispatcher protected StringParam(String id) { super(id); } @Override - public Tag toTag(Value value) { return StringTag.of(value.getString()); } - public Value decode(Tag tag) { return new StringValue(tag.asString()); } + public NbtElement toTag(Value value) { return NbtString.of(value.getString()); } + public Value decode(NbtElement tag) { return new StringValue(tag.asString()); } } public static class TextParam extends StringParam { @@ -943,15 +943,15 @@ public class ShapeDispatcher } @Override - public Tag toTag(Value value) + public NbtElement toTag(Value value) { if (!(value instanceof FormattedTextValue)) value = new FormattedTextValue(new LiteralText(value.getString())); - return StringTag.of(((FormattedTextValue)value).serialize()); + return NbtString.of(((FormattedTextValue)value).serialize()); } @Override - public Value decode(Tag tag) + public Value decode(NbtElement tag) { return FormattedTextValue.deserialize(tag.asString()); } @@ -1016,24 +1016,24 @@ public class ShapeDispatcher } @Override - public Tag toTag(Value value) + public NbtElement toTag(Value value) { - return ByteTag.of(value.getBoolean()); + return NbtByte.of(value.getBoolean()); } @Override - public Value decode(Tag tag) + public Value decode(NbtElement tag) { - return BooleanValue.of(((ByteTag) tag).getByte() > 0); + return BooleanValue.of(((NbtByte) tag).byteValue() > 0); } } public static class FloatParam extends NumericParam { protected FloatParam(String id) { super(id); } @Override - public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getFloat()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); } @Override - public Tag toTag(Value value) { return FloatTag.of(NumericValue.asNumber(value, id).getFloat()); } + public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); } } public static abstract class PositiveParam extends NumericParam @@ -1050,27 +1050,27 @@ public class ShapeDispatcher { protected PositiveFloatParam(String id) { super(id); } @Override - public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getFloat()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); } @Override - public Tag toTag(Value value) { return FloatTag.of(NumericValue.asNumber(value, id).getFloat()); } + public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); } } public static class PositiveIntParam extends PositiveParam { protected PositiveIntParam(String id) { super(id); } @Override - public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getInt()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } @Override - public Tag toTag(Value value) { return IntTag.of(NumericValue.asNumber(value, id).getInt()); } + public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } } public static class NonNegativeIntParam extends NumericParam { protected NonNegativeIntParam(String id) { super(id); } @Override - public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getInt()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } @Override - public Tag toTag(Value value) { return IntTag.of(NumericValue.asNumber(value, id).getInt()); } + public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } @Override public Value validate(Map options, MinecraftServer server, Value value) { Value ret = super.validate(options, server, value); @@ -1082,9 +1082,9 @@ public class ShapeDispatcher { protected NonNegativeFloatParam(String id) { super(id); } @Override - public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getFloat()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); } @Override - public Tag toTag(Value value) { return FloatTag.of(NumericValue.asNumber(value, id).getFloat()); } + public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); } @Override public Value validate(Map options, MinecraftServer server, Value value) { Value ret = super.validate(options, server, value); @@ -1149,9 +1149,9 @@ public class ShapeDispatcher throw new InternalExpressionException("'"+p.id+"' requires a triple, block or entity to indicate position"); } - public Value decode(Tag tag) + public Value decode(NbtElement tag) { - ListTag ctag = (ListTag)tag; + NbtList ctag = (NbtList)tag; return ListValue.of( new NumericValue(ctag.getDouble(0)), new NumericValue(ctag.getDouble(1)), @@ -1159,13 +1159,13 @@ public class ShapeDispatcher ); } @Override - public Tag toTag(Value value) + public NbtElement toTag(Value value) { List lv = ((ListValue)value).getItems(); - ListTag tag = new ListTag(); - tag.add(DoubleTag.of(NumericValue.asNumber(lv.get(0), "x").getDouble())); - tag.add(DoubleTag.of(NumericValue.asNumber(lv.get(1), "y").getDouble())); - tag.add(DoubleTag.of(NumericValue.asNumber(lv.get(2), "z").getDouble())); + NbtList tag = new NbtList(); + tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble())); + tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble())); + tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble())); return tag; } } @@ -1187,13 +1187,13 @@ public class ShapeDispatcher return ListValue.wrap(points); } - public Value decode(Tag tag) + public Value decode(NbtElement tag) { - ListTag ltag = (ListTag)tag; + NbtList ltag = (NbtList)tag; List points = new ArrayList<>(); for (int i=0, ll = ltag.size(); i lv = ((ListValue)pointsValue).getItems(); - ListTag ltag = new ListTag(); + NbtList ltag = new NbtList(); for (Value value : lv) { List coords = ((ListValue)value).getItems(); - ListTag tag = new ListTag(); - tag.add(DoubleTag.of(NumericValue.asNumber(lv.get(0), "x").getDouble())); - tag.add(DoubleTag.of(NumericValue.asNumber(lv.get(1), "y").getDouble())); - tag.add(DoubleTag.of(NumericValue.asNumber(lv.get(2), "z").getDouble())); + NbtList tag = new NbtList(); + tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble())); + tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble())); + tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble())); ltag.add(tag); } return ltag; @@ -1228,9 +1228,9 @@ public class ShapeDispatcher super(id); } - public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getInt()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } @Override - public Tag toTag(Value value) { return IntTag.of(NumericValue.asNumber(value, id).getInt()); } + public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } } public static class EntityParam extends Param @@ -1239,22 +1239,22 @@ public class ShapeDispatcher protected EntityParam(String id) { super(id); } @Override - public Tag toTag(Value value) + public NbtElement toTag(Value value) { - return IntTag.of(NumericValue.asNumber(value, id).getInt()); + return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } @Override public Value validate(Map options, MinecraftServer server, Value value) { - if (value instanceof EntityValue) return new NumericValue(((EntityValue) value).getEntity().getEntityId()); + if (value instanceof EntityValue) return new NumericValue(((EntityValue) value).getEntity().getId()); ServerPlayerEntity player = EntityValue.getPlayerByValue(server, value); if (player == null) throw new InternalExpressionException(id+" parameter needs to represent an entity or player"); - return new NumericValue(player.getEntityId()); + return new NumericValue(player.getId()); } - public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getInt()); } + public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } } private static boolean isStraight(Vec3d from, Vec3d to, double density) @@ -1328,7 +1328,7 @@ public class ShapeDispatcher } if (isStraight(from, to, density)) return drawOptimizedParticleLine(players, particle, from, to, density); - Vec3d incvec = to.subtract(from).multiply(2*density/MathHelper.sqrt(distance)); + Vec3d incvec = to.subtract(from).multiply(2*density/Math.sqrt(distance)); for (Vec3d delta = new Vec3d(0.0,0.0,0.0); delta.lengthSquared(), Long2ObjectOpenHashMap>> shapes; + private final Map, Long2ObjectOpenHashMap>> labels; private MinecraftClient client; private Map>> renderedShapes @@ -46,34 +48,33 @@ public class ShapesRenderer { this.client = minecraftClient; shapes = new HashMap<>(); + labels = new HashMap<>(); } - public void render(Camera camera, float partialTick) + public void render(MatrixStack matrices, Camera camera, float partialTick) { CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); //Camera camera = this.client.gameRenderer.getCamera(); ClientWorld iWorld = this.client.world; RegistryKey dimensionType = iWorld.getRegistryKey(); - if (shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) return; + if ((shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) && + (labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty())) return; long currentTime = client.world.getTime(); RenderSystem.disableTexture(); RenderSystem.enableDepthTest(); + RenderSystem.setShader(GameRenderer::getPositionColorShader); RenderSystem.depthFunc(515); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); + // too bright //RenderSystem.blendFuncSeparate(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE, GlStateManager.SrcFactor.ONE, GlStateManager.DstFactor.ZERO); - //RenderSystem.shadeModel(7425); - RenderSystem.shadeModel(GL11.GL_FLAT); - RenderSystem.enableAlphaTest(); - RenderSystem.alphaFunc(GL11.GL_GREATER, 0.003f); + // meh + //RenderSystem.blendFuncSeparate(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SrcFactor.ONE, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA); + RenderSystem.disableCull(); - RenderSystem.disableLighting(); RenderSystem.depthMask(false); - // causes water to vanish - //RenderSystem.depthMask(true); //RenderSystem.polygonOffset(-3f, -3f); //RenderSystem.enablePolygonOffset(); - //Entity entity = this.client.gameRenderer.getCamera().getFocusedEntity(); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferBuilder = tessellator.getBuffer(); @@ -83,49 +84,48 @@ public class ShapesRenderer double cameraY = camera.getPos().y; double cameraZ = camera.getPos().z; - synchronized (shapes) - { + if (shapes.size() != 0) { synchronized (shapes) { shapes.get(dimensionType).long2ObjectEntrySet().removeIf( entry -> entry.getValue().isExpired(currentTime) ); + MatrixStack matrixStack = RenderSystem.getModelViewStack(); + matrixStack.push(); + matrixStack.method_34425(matrices.peek().getModel()); + RenderSystem.applyModelViewMatrix(); - shapes.get(dimensionType).values().forEach( - s -> - { - if ( !s.lastCall() && s.shouldRender(dimensionType)) - s.renderFaces(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); - } - ); - //lines - shapes.get(dimensionType).values().forEach( + // lines + RenderSystem.lineWidth(0.5F); + shapes.get(dimensionType).values().forEach( s -> { + if (s.shouldRender(dimensionType)) s.renderLines(matrices, tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + }); + // faces + RenderSystem.lineWidth(0.1F); + shapes.get(dimensionType).values().forEach(s -> { + if (s.shouldRender(dimensionType)) s.renderFaces(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + }); + RenderSystem.lineWidth(1.0F); + matrixStack.pop(); + RenderSystem.applyModelViewMatrix(); - s -> { - if ( !s.lastCall() && s.shouldRender(dimensionType)) - s.renderLines(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); - } + }} + if (labels.size() != 0) { synchronized (labels) + { + labels.get(dimensionType).long2ObjectEntrySet().removeIf( + entry -> entry.getValue().isExpired(currentTime) ); - //texts - // maybe we can move it laster to lines and makes sure we don't overpass and don't have blinky transparency problems - shapes.get(dimensionType).values().forEach( - s -> - { - if ( s.lastCall() && s.shouldRender(dimensionType)) - s.renderLines(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); - } - ); - - } + labels.get(dimensionType).values().forEach(s -> { + if (s.shouldRender(dimensionType)) s.renderLines(matrices, tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + }); + }} RenderSystem.enableCull(); RenderSystem.depthMask(true); - RenderSystem.lineWidth(1.0F); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.enableTexture(); - RenderSystem.shadeModel(7424); CarpetProfiler.end_current_section(token); } - public void addShapes(ListTag tag) + public void addShapes(NbtList tag) { CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); for (int i=0, count = tag.size(); i < count; i++) @@ -135,7 +135,7 @@ public class ShapesRenderer CarpetProfiler.end_current_section(token); } - public void addShape(CompoundTag tag) + public void addShape(NbtCompound tag) { ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag); if (shape == null) return; @@ -150,16 +150,18 @@ public class ShapesRenderer RenderedShape rshape = shapeFactory.apply(client, shape); RegistryKey dim = shape.shapeDimension; long key = rshape.key(); - synchronized (shapes) + Map, Long2ObjectOpenHashMap>> container = + rshape.stageDeux()?labels:shapes; + synchronized (container) { - RenderedShape existing = shapes.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key); + RenderedShape existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key); if (existing != null) { // promoting previous shape existing.promoteWith(rshape); } else { - shapes.get(dim).put(key, rshape); + container.get(dim).put(key, rshape); } } } @@ -170,6 +172,10 @@ public class ShapesRenderer { shapes.values().forEach(Long2ObjectOpenHashMap::clear); } + synchronized (labels) + { + labels.values().forEach(Long2ObjectOpenHashMap::clear); + } } public void renewShapes() @@ -177,9 +183,11 @@ public class ShapesRenderer CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); synchronized (shapes) { - shapes.values().forEach(el -> el.values().forEach(shape -> { - shape.expiryTick++; - })); + shapes.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); + } + synchronized (labels) + { + labels.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); } CarpetProfiler.end_current_section(token); } @@ -190,7 +198,7 @@ public class ShapesRenderer protected MinecraftClient client; long expiryTick; double renderEpsilon = 0; - public abstract void renderLines(Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ); + public abstract void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ); public void renderFaces(Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ) {} protected RenderedShape(MinecraftClient client, T shape) { @@ -213,10 +221,9 @@ public class ShapesRenderer if (shape.followEntity <=0 ) return true; if (client.world == null) return false; if (client.world.getRegistryKey() != dim) return false; - if (client.world.getEntityById(shape.followEntity) == null) return false; - return true; + return client.world.getEntityById(shape.followEntity) != null; } - public boolean lastCall() + public boolean stageDeux() { return false; } @@ -236,26 +243,22 @@ public class ShapesRenderer } @Override - public void renderLines(Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick) + public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; Vec3d v1 = shape.relativiseRender(client.world, shape.pos, partialTick); Camera camera1 = client.gameRenderer.getCamera(); TextRenderer textRenderer = client.textRenderer; - double d = camera1.getPos().x; - double e = camera1.getPos().y; - double f = camera1.getPos().z; if (shape.doublesided) RenderSystem.disableCull(); else RenderSystem.enableCull(); - RenderSystem.pushMatrix(); - RenderSystem.translatef((float)(v1.x - d), (float)(v1.y - e), (float)(v1.z - f)); - RenderSystem.normal3f(0.0F, 1.0F, 0.0F); - + matrices.push(); + matrices.translate(v1.x - cx,v1.y - cy,v1.z - cz); if (shape.facing == null) { - RenderSystem.multMatrix(new Matrix4f(camera1.getRotation())); + //matrices.method_34425(new Matrix4f(camera1.getRotation())); + matrices.multiply(camera1.getRotation()); } else { @@ -264,38 +267,31 @@ public class ShapesRenderer case NORTH: break; case SOUTH: - RenderSystem.rotatef(180.0f, 0.0f, 1.0f, 0.0f); + matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(180)); break; case EAST: - RenderSystem.rotatef(270.0f, 0.0f, 1.0f, 0.0f); + matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(270)); break; case WEST: - RenderSystem.rotatef(90.0f, 0.0f, 1.0f, 0.0f); + matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(90)); break; case UP: - RenderSystem.rotatef(90.0f, 1.0f, 0.0f, 0.0f); + matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(90)); break; case DOWN: - RenderSystem.rotatef(-90.0f, 1.0f, 0.0f, 0.0f); + matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(-90)); break; } } - RenderSystem.scalef(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); - if (shape.tilt!=0.0f) - { - RenderSystem.rotatef(shape.tilt, 0.0f, 0.0f, 1.0f); - } - if (shape.lean!=0.0f) - { - RenderSystem.rotatef(shape.lean, 1.0f, 0.0f, 0.0f); - } - if (shape.turn!=0.0f) - { - RenderSystem.rotatef(shape.turn, 0.0f, 1.0f, 0.0f); - } - RenderSystem.translatef(-10*shape.indent, -10*shape.height-9, (float) (-10*renderEpsilon)-10*shape.raise); + matrices.scale(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); + //RenderSystem.scalef(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); + if (shape.tilt!=0.0f) matrices.multiply(Vec3f.POSITIVE_Z.getDegreesQuaternion(shape.tilt)); + if (shape.lean!=0.0f) matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(shape.lean)); + if (shape.turn!=0.0f) matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(shape.turn)); + matrices.translate(-10*shape.indent, -10*shape.height-9, (-10*renderEpsilon)-10*shape.raise); //if (visibleThroughWalls) RenderSystem.disableDepthTest(); - RenderSystem.scalef(-1.0F, 1.0F, 1.0F); + matrices.scale(-1, 1, 1); + //RenderSystem.applyModelViewMatrix(); // passed matrix directly to textRenderer.draw, not AffineTransformation.identity().getMatrix(), float text_x = 0; if (shape.align == 0) @@ -306,19 +302,15 @@ public class ShapesRenderer { text_x = (float)(-textRenderer.getWidth(shape.value.getString())); } - VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer()); - textRenderer.draw(shape.value, text_x, 0.0F, shape.textcolor, false, AffineTransformation.identity().getMatrix(), immediate, false, shape.textbck, 15728880); + VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(builder); + textRenderer.draw(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.peek().getModel(), immediate, false, shape.textbck, 15728880); immediate.draw(); - RenderSystem.popMatrix(); + matrices.pop(); RenderSystem.enableCull(); - //RenderSystem.enableDepthTest(); - //RenderSystem.depthFunc(515); - //RenderSystem.enableAlphaTest(); - //RenderSystem.alphaFunc(GL11.GL_GREATER, 0.003f); } @Override - public boolean lastCall() + public boolean stageDeux() { return true; } @@ -347,12 +339,11 @@ public class ShapesRenderer } @Override - public void renderLines(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; Vec3d v1 = shape.relativiseRender(client.world, shape.from, partialTick); Vec3d v2 = shape.relativiseRender(client.world, shape.to, partialTick); - RenderSystem.lineWidth(shape.lineWidth); drawBoxWireGLLines(tessellator, bufferBuilder, (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), @@ -366,7 +357,8 @@ public class ShapesRenderer if (shape.fa == 0.0) return; Vec3d v1 = shape.relativiseRender(client.world, shape.from, partialTick); Vec3d v2 = shape.relativiseRender(client.world, shape.to, partialTick); - RenderSystem.lineWidth(1.0F); + // consider using built-ins + //DebugRenderer.drawBox(new Box(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z), 0.5f, 0.5f, 0.5f, 0.5f);//shape.r, shape.g, shape.b, shape.a); drawBoxFaces(tessellator, bufferBuilder, (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), @@ -384,11 +376,10 @@ public class ShapesRenderer super(client, (ShapeDispatcher.Line)shape); } @Override - public void renderLines(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { Vec3d v1 = shape.relativiseRender(client.world, shape.from, partialTick); Vec3d v2 = shape.relativiseRender(client.world, shape.to, partialTick); - RenderSystem.lineWidth(shape.lineWidth); drawLine(tessellator, bufferBuilder, (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), @@ -404,11 +395,10 @@ public class ShapesRenderer super(client, (ShapeDispatcher.Sphere)shape); } @Override - public void renderLines(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); - RenderSystem.lineWidth(shape.lineWidth); drawSphereWireframe(tessellator, bufferBuilder, (float)(vc.x-cx), (float)(vc.y-cy), (float)(vc.z-cz), (float)(shape.radius+renderEpsilon), shape.subdivisions, @@ -419,7 +409,6 @@ public class ShapesRenderer { if (shape.fa == 0.0) return; Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); - RenderSystem.lineWidth(1.0f); drawSphereFaces(tessellator, bufferBuilder, (float)(vc.x-cx), (float)(vc.y-cy), (float)(vc.z-cz), (float)(shape.radius+renderEpsilon), shape.subdivisions, @@ -434,11 +423,10 @@ public class ShapesRenderer super(client, (ShapeDispatcher.Cylinder)shape); } @Override - public void renderLines(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); - RenderSystem.lineWidth(shape.lineWidth); double dir = MathHelper.sign(shape.height); drawCylinderWireframe(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), @@ -452,7 +440,6 @@ public class ShapesRenderer { if (shape.fa == 0.0) return; Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); - RenderSystem.lineWidth(1.0f); double dir = MathHelper.sign(shape.height); drawCylinderFaces(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), @@ -465,7 +452,7 @@ public class ShapesRenderer // some raw shit public static void drawLine(Tessellator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, float red1, float grn1, float blu1, float alpha) { - builder.begin(GL11.GL_LINES, VertexFormats.POSITION_COLOR); // 3 + builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).next(); builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); tessellator.draw(); @@ -478,7 +465,7 @@ public class ShapesRenderer boolean xthick, boolean ythick, boolean zthick, float red1, float grn1, float blu1, float alpha, float red2, float grn2, float blu2) { - builder.begin(GL11.GL_LINES, VertexFormats.POSITION_COLOR); // 3 + builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); if (xthick) { builder.vertex(x1, y1, z1).color(red1, grn2, blu2, alpha).next(); @@ -531,7 +518,7 @@ public class ShapesRenderer boolean xthick, boolean ythick, boolean zthick, float red1, float grn1, float blu1, float alpha) { - builder.begin(GL11.GL_QUADS, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); if (xthick && ythick) { @@ -606,8 +593,8 @@ public class ShapesRenderer for (int dh = 0; dh < hsteps; dh++) { float hh = dh*hstep; - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); - for (int i = 0; i <= num_steps360; i++) + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + for (int i = 0; i <= num_steps360+1; i++) { float theta = step * i; float x = r * MathHelper.cos(theta); @@ -622,7 +609,7 @@ public class ShapesRenderer { for (int i = 0; i <= num_steps180; i++) { - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip float theta = step * i; float x = r * MathHelper.cos(theta); @@ -632,12 +619,13 @@ public class ShapesRenderer builder.vertex(cx + x, cy + 0, cz - z).color(red, grn, blu, alpha).next(); builder.vertex(cx + x, cy + h, cz - z).color(red, grn, blu, alpha).next(); builder.vertex(cx - x, cy + h, cz + z).color(red, grn, blu, alpha).next(); + builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).next(); tessellator.draw(); } } else { - builder.begin(GL11.GL_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { float theta = step * i; @@ -655,7 +643,7 @@ public class ShapesRenderer for (int dh = 0; dh < hsteps; dh++) { float hh = dh * hstep; - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { float theta = step * i; @@ -671,7 +659,7 @@ public class ShapesRenderer { for (int i = 0; i <= num_steps180; i++) { - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip float theta = step * i; float y = r * MathHelper.cos(theta); @@ -686,7 +674,7 @@ public class ShapesRenderer } else { - builder.begin(GL11.GL_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { float theta = step * i; @@ -703,7 +691,7 @@ public class ShapesRenderer for (int dh = 0; dh < hsteps; dh++) { float hh = dh * hstep; - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { float theta = step * i; @@ -718,7 +706,7 @@ public class ShapesRenderer { for (int i = 0; i <= num_steps180; i++) { - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip float theta = step * i; float x = r * MathHelper.cos(theta); @@ -733,7 +721,7 @@ public class ShapesRenderer } else { - builder.begin(GL11.GL_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { float theta = step * i; @@ -760,7 +748,7 @@ public class ShapesRenderer if (axis == Direction.Axis.Y) { - builder.begin(GL11.GL_TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).next(); for (int i = 0; i <= num_steps360; i++) { @@ -772,7 +760,7 @@ public class ShapesRenderer tessellator.draw(); if (!isFlat) { - builder.begin(GL11.GL_TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); builder.vertex(cx, cy+h, cz).color(red, grn, blu, alpha).next(); for (int i = 0; i <= num_steps360; i++) { @@ -783,14 +771,20 @@ public class ShapesRenderer } tessellator.draw(); - builder.begin(GL11.GL_QUAD_STRIP, VertexFormats.POSITION_COLOR); - for (int i = 0; i <= num_steps360; i++) + builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + float xp = r * 1; + float zp = r * 0; + for (int i = 1; i <= num_steps360; i++) { float theta = step * i; float x = r * MathHelper.cos(theta); float z = r * MathHelper.sin(theta); - builder.vertex(cx + x, cy + 0, cz + z).color(red, grn, blu, alpha).next(); + builder.vertex(cx + xp, cy + 0, cz + zp).color(red, grn, blu, alpha).next(); + builder.vertex(cx + xp, cy + h, cz + zp).color(red, grn, blu, alpha).next(); builder.vertex(cx + x, cy + h, cz + z).color(red, grn, blu, alpha).next(); + builder.vertex(cx + x, cy + 0, cz + z).color(red, grn, blu, alpha).next(); + xp = x; + zp = z; } tessellator.draw(); } @@ -798,7 +792,7 @@ public class ShapesRenderer } else if (axis == Direction.Axis.X) { - builder.begin(GL11.GL_TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).next(); for (int i = 0; i <= num_steps360; i++) { @@ -810,7 +804,7 @@ public class ShapesRenderer tessellator.draw(); if (!isFlat) { - builder.begin(GL11.GL_TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); builder.vertex(cx+h, cy, cz).color(red, grn, blu, alpha).next(); for (int i = 0; i <= num_steps360; i++) { @@ -821,21 +815,27 @@ public class ShapesRenderer } tessellator.draw(); - builder.begin(GL11.GL_QUAD_STRIP, VertexFormats.POSITION_COLOR); - for (int i = 0; i <= num_steps360; i++) + builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + float yp = r * 1; + float zp = r * 0; + for (int i = 1; i <= num_steps360; i++) { float theta = step * i; float y = r * MathHelper.cos(theta); float z = r * MathHelper.sin(theta); - builder.vertex(cx + 0, cy + y, cz + z).color(red, grn, blu, alpha).next(); + builder.vertex(cx + 0, cy + yp, cz + zp).color(red, grn, blu, alpha).next(); + builder.vertex(cx + h, cy + yp, cz + zp).color(red, grn, blu, alpha).next(); builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).next(); + builder.vertex(cx + 0, cy + y, cz + z).color(red, grn, blu, alpha).next(); + yp = y; + zp = z; } tessellator.draw(); } } else if (axis == Direction.Axis.Z) { - builder.begin(GL11.GL_TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).next(); for (int i = 0; i <= num_steps360; i++) { @@ -847,7 +847,7 @@ public class ShapesRenderer tessellator.draw(); if (!isFlat) { - builder.begin(GL11.GL_TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); builder.vertex(cx, cy, cz+h).color(red, grn, blu, alpha).next(); for (int i = 0; i <= num_steps360; i++) { @@ -858,14 +858,20 @@ public class ShapesRenderer } tessellator.draw(); - builder.begin(GL11.GL_QUAD_STRIP, VertexFormats.POSITION_COLOR); - for (int i = 0; i <= num_steps360; i++) + builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + float xp = r; + float yp = 0; + for (int i = 1; i <= num_steps360; i++) { float theta = step * i; float x = r * MathHelper.cos(theta); float y = r * MathHelper.sin(theta); - builder.vertex(cx + x, cy + y, cz + 0).color(red, grn, blu, alpha).next(); + builder.vertex(cx + xp, cy + yp, cz + 0).color(red, grn, blu, alpha).next(); + builder.vertex(cx + xp, cy + yp, cz + h).color(red, grn, blu, alpha).next(); builder.vertex(cx + x, cy + y, cz + h).color(red, grn, blu, alpha).next(); + builder.vertex(cx + x, cy + y, cz + 0).color(red, grn, blu, alpha).next(); + xp = x; + yp = y; } tessellator.draw(); } @@ -879,10 +885,10 @@ public class ShapesRenderer { float step = (float)Math.PI / (subd/2); int num_steps180 = (int)(Math.PI / step)+1; - int num_steps360 = (int)(2*Math.PI / step); + int num_steps360 = (int)(2*Math.PI / step)+1; for (int i = 0; i <= num_steps360; i++) { - builder.begin(GL11.GL_LINE_STRIP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); float theta = step * i ; for (int j = 0; j <= num_steps180; j++) { @@ -896,7 +902,7 @@ public class ShapesRenderer } for (int j = 0; j <= num_steps180; j++) { - builder.begin(GL11.GL_LINE_LOOP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip float phi = step * j ; for (int i = 0; i <= num_steps360; i++) @@ -925,7 +931,12 @@ public class ShapesRenderer { float theta = i * step; float thetaprime = theta+step; - builder.begin(GL11.GL_QUAD_STRIP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + float xb = 0; + float zb = 0; + float xbp = 0; + float zbp = 0; + float yp = r; for (int j = 0; j <= num_steps180; j++) { float phi = j * step; @@ -934,8 +945,15 @@ public class ShapesRenderer float y = r * MathHelper.cos(phi); float xp = r * MathHelper.sin(phi) * MathHelper.cos(thetaprime); float zp = r * MathHelper.sin(phi) * MathHelper.sin(thetaprime); - builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).next(); + builder.vertex(xb + cx, yp + cy, zb + cz).color(red, grn, blu, alpha).next(); + builder.vertex(xbp + cx, yp + cy, zbp + cz).color(red, grn, blu, alpha).next(); builder.vertex(xp + cx, y + cy, zp + cz).color(red, grn, blu, alpha).next(); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).next(); + xb = x; + zb = z; + xbp = xp; + zbp = zp; + yp = y; } tessellator.draw(); } diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index 5092c371..bf48a730 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -2,7 +2,6 @@ package carpet.script.utils; import carpet.CarpetSettings; import com.mojang.brigadier.ResultConsumer; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.command.argument.EntityAnchorArgumentType; import net.minecraft.entity.Entity; import net.minecraft.server.MinecraftServer; @@ -41,7 +40,7 @@ public class SnoopyCommandSource extends ServerCommandSource public SnoopyCommandSource(ServerCommandSource original, Text[] error, List chatOutput) { super(CommandOutput.DUMMY, original.getPosition(), original.getRotation(), original.getWorld(), CarpetSettings.runPermissionLevel, - original.getName(), original.getDisplayName(), original.getMinecraftServer(), original.getEntity(), false, + original.getName(), original.getDisplayName(), original.getServer(), original.getEntity(), false, (ctx, succ, res) -> { }, EntityAnchorArgumentType.EntityAnchor.FEET); this.output = CommandOutput.DUMMY; this.position = original.getPosition(); @@ -49,7 +48,7 @@ public class SnoopyCommandSource extends ServerCommandSource this.level = CarpetSettings.runPermissionLevel; this.simpleName = original.getName(); this.name = original.getDisplayName(); - this.server = original.getMinecraftServer(); + this.server = original.getServer(); this.entity = original.getEntity(); this.resultConsumer = (ctx, succ, res) -> { }; this.entityAnchor = original.getEntityAnchor(); @@ -123,7 +122,8 @@ public class SnoopyCommandSource extends ServerCommandSource return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, error, chatOutput); } - public ServerCommandSource mergeConsumers(ResultConsumer consumer, BinaryOperator> binaryOperator) { + public ServerCommandSource mergeConsumers(ResultConsumer consumer, BinaryOperator> binaryOperator) + { ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); return this.withConsumer(resultConsumer); } @@ -153,18 +153,19 @@ public class SnoopyCommandSource extends ServerCommandSource @Override public ServerCommandSource withWorld(ServerWorld world) { - double d = DimensionType.method_31109(this.world.getDimension(), world.getDimension()); + double d = DimensionType.getCoordinateScaleFactor(this.world.getDimension(), world.getDimension()); Vec3d position = new Vec3d(this.position.x * d, this.position.y, this.position.z * d); return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput); } @Override - public ServerCommandSource withLookingAt(Vec3d position) throws CommandSyntaxException { + public ServerCommandSource withLookingAt(Vec3d position) + { Vec3d vec3d = this.entityAnchor.positionAt(this); double d = position.x - vec3d.x; double e = position.y - vec3d.y; double f = position.z - vec3d.z; - double g = (double) MathHelper.sqrt(d * d + f * f); + double g = (double) Math.sqrt(d * d + f * f); float h = MathHelper.wrapDegrees((float)(-(MathHelper.atan2(e, g) * 57.2957763671875D))); float i = MathHelper.wrapDegrees((float)(MathHelper.atan2(f, d) * 57.2957763671875D) - 90.0F); return this.withRotation(new Vec2f(h, i)); diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java index 9247cf15..dc7c3976 100644 --- a/src/main/java/carpet/script/utils/SystemInfo.java +++ b/src/main/java/carpet/script/utils/SystemInfo.java @@ -42,33 +42,33 @@ public class SystemInfo { put("app_scope", c -> StringValue.of((c.host).isPerUser()?"player":"global")); put("app_players", c -> ListValue.wrap(c.host.getUserList().stream().map(StringValue::new).collect(Collectors.toList()))); - put("world_name", c -> new StringValue(c.s.getMinecraftServer().getSaveProperties().getLevelName())); + put("world_name", c -> new StringValue(c.s.getServer().getSaveProperties().getLevelName())); put("world_seed", c -> new NumericValue(c.s.getWorld().getSeed())); - put("server_motd", c -> StringValue.of(c.s.getMinecraftServer().getServerMotd())); - put("world_path", c -> StringValue.of(c.s.getMinecraftServer().getSavePath(WorldSavePath.ROOT).toString())); + put("server_motd", c -> StringValue.of(c.s.getServer().getServerMotd())); + put("world_path", c -> StringValue.of(c.s.getServer().getSavePath(WorldSavePath.ROOT).toString())); put("world_folder", c -> { - Path serverPath = c.s.getMinecraftServer().getSavePath(WorldSavePath.ROOT); + Path serverPath = c.s.getServer().getSavePath(WorldSavePath.ROOT); int nodeCount = serverPath.getNameCount(); if (nodeCount < 2) return Value.NULL; String tlf = serverPath.getName(nodeCount-2).toString(); return StringValue.of(tlf); }); - put("world_dimensions", c -> ListValue.wrap(c.s.getMinecraftServer().getWorldRegistryKeys().stream().map(k -> ValueConversions.of(k.getValue())).collect(Collectors.toList()))); + put("world_dimensions", c -> ListValue.wrap(c.s.getServer().getWorldRegistryKeys().stream().map(k -> ValueConversions.of(k.getValue())).collect(Collectors.toList()))); put("world_spawn_point", c -> { - WorldProperties prop = c.s.getMinecraftServer().getOverworld().getLevelProperties(); + WorldProperties prop = c.s.getServer().getOverworld().getLevelProperties(); return ListValue.of(NumericValue.of(prop.getSpawnX()), NumericValue.of(prop.getSpawnY()), NumericValue.of(prop.getSpawnZ())); }); - put("game_difficulty", c -> StringValue.of(c.s.getMinecraftServer().getSaveProperties().getDifficulty().getName())); - put("game_hardcore", c -> BooleanValue.of(c.s.getMinecraftServer().getSaveProperties().isHardcore())); - put("game_storage_format", c -> StringValue.of(c.s.getMinecraftServer().getSaveProperties().getFormatName(c.s.getMinecraftServer().getSaveProperties().getVersion()))); - put("game_default_gamemode", c -> StringValue.of(c.s.getMinecraftServer().getDefaultGameMode().getName())); - put("game_max_players", c -> new NumericValue(c.s.getMinecraftServer().getMaxPlayerCount())); - put("game_view_distance", c -> new NumericValue(c.s.getMinecraftServer().getPlayerManager().getViewDistance())); - put("game_mod_name", c -> StringValue.of(c.s.getMinecraftServer().getServerModName())); - put("game_version", c -> StringValue.of(c.s.getMinecraftServer().getVersion())); + put("game_difficulty", c -> StringValue.of(c.s.getServer().getSaveProperties().getDifficulty().getName())); + put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getSaveProperties().isHardcore())); + put("game_storage_format", c -> StringValue.of(c.s.getServer().getSaveProperties().getFormatName(c.s.getServer().getSaveProperties().getVersion()))); + put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameMode().getName())); + put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayerCount())); + put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerManager().getViewDistance())); + put("game_mod_name", c -> StringValue.of(c.s.getServer().getServerModName())); + put("game_version", c -> StringValue.of(c.s.getServer().getVersion())); put("game_target", c -> StringValue.of(SharedConstants.getGameVersion().getReleaseTarget())); - put("game_protocol", c -> NumericValue.of(SharedConstants.method_31372())); + put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion())); put("game_major_target", c -> { String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\."); return NumericValue.of((vers.length > 1)?Integer.parseInt(vers[1]):0); @@ -81,11 +81,11 @@ public class SystemInfo { put("game_data_version", c->NumericValue.of(SharedConstants.getGameVersion().getWorldVersion())); put("game_pack_version", c->NumericValue.of(SharedConstants.getGameVersion().getPackVersion())); - put("server_ip", c -> StringValue.of(c.s.getMinecraftServer().getServerIp())); - put("server_whitelisted", c -> BooleanValue.of(c.s.getMinecraftServer().isEnforceWhitelist())); + put("server_ip", c -> StringValue.of(c.s.getServer().getServerIp())); + put("server_whitelisted", c -> BooleanValue.of(c.s.getServer().isEnforceWhitelist())); put("server_whitelist", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getMinecraftServer().getPlayerManager().getWhitelistedNames()) + for (String s: c.s.getServer().getPlayerManager().getWhitelistedNames()) { whitelist.append(StringValue.of(s)); } @@ -93,7 +93,7 @@ public class SystemInfo { }); put("server_banned_players", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getMinecraftServer().getPlayerManager().getUserBanList().getNames()) + for (String s: c.s.getServer().getPlayerManager().getUserBanList().getNames()) { whitelist.append(StringValue.of(s)); } @@ -101,7 +101,7 @@ public class SystemInfo { }); put("server_banned_ips", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getMinecraftServer().getPlayerManager().getIpBanList().getNames()) + for (String s: c.s.getServer().getPlayerManager().getIpBanList().getNames()) { whitelist.append(StringValue.of(s)); } diff --git a/src/main/java/carpet/script/utils/WorldTools.java b/src/main/java/carpet/script/utils/WorldTools.java index 8d6c4b27..e90f3d44 100644 --- a/src/main/java/carpet/script/utils/WorldTools.java +++ b/src/main/java/carpet/script/utils/WorldTools.java @@ -2,6 +2,8 @@ package carpet.script.utils; import carpet.fakes.MinecraftServerInterface; import com.google.common.collect.ImmutableList; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.WorldGenerationProgressListener; @@ -97,21 +99,21 @@ public class WorldTools ChunkGenerator chunkGenerator2; DimensionType dimensionType2; if (dimensionOptions == null) { - dimensionType2 = (DimensionType)server.getRegistryManager().getDimensionTypes().getOrThrow(DimensionType.OVERWORLD_REGISTRY_KEY); - chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager().get(Registry.BIOME_KEY), server.getRegistryManager().get(Registry.NOISE_SETTINGS_WORLDGEN), (new Random()).nextLong()); + dimensionType2 = server.getRegistryManager().getMutable(Registry.DIMENSION_TYPE_KEY).getOrThrow(DimensionType.OVERWORLD_REGISTRY_KEY); + chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager().get(Registry.BIOME_KEY), server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY), (new Random()).nextLong()); } else { dimensionType2 = dimensionOptions.getDimensionType(); chunkGenerator2 = dimensionOptions.getChunkGenerator(); } - RegistryKey customWorld = RegistryKey.of(Registry.DIMENSION, worldId); + RegistryKey customWorld = RegistryKey.of(Registry.WORLD_KEY, worldId); //chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager().get(Registry.BIOME_KEY), server.getRegistryManager().get(Registry.NOISE_SETTINGS_WORLDGEN), (seed==null)?l:seed); chunkGenerator2 = new NoiseChunkGenerator( new VanillaLayeredBiomeSource((seed==null)?l:seed, false, false, server.getRegistryManager().get(Registry.BIOME_KEY)), (seed==null)?l:seed, - () -> server.getRegistryManager().get(Registry.NOISE_SETTINGS_WORLDGEN).getOrThrow(ChunkGeneratorSettings.OVERWORLD) + () -> server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD) ); ServerWorld serverWorld = new ServerWorld( @@ -142,7 +144,7 @@ public class WorldTools List nearbyPlayers = world.getPlayers(p -> pos.getSquaredDistance(p.getX(), pos.getY(), p.getZ(), true) < vvd); if (!nearbyPlayers.isEmpty()) { - ChunkDataS2CPacket packet = new ChunkDataS2CPacket(worldChunk, 65535); + ChunkDataS2CPacket packet = new ChunkDataS2CPacket(worldChunk); ChunkPos chpos = new ChunkPos(pos); nearbyPlayers.forEach(p -> p.networkHandler.sendPacket(packet)); } @@ -154,6 +156,8 @@ public class WorldTools { @Override public void start(ChunkPos spawnPos) { } @Override public void setChunkStatus(ChunkPos pos, ChunkStatus status) { } + @Environment(EnvType.CLIENT) + @Override public void start() { } @Override public void stop() { } } diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index 27d21cdd..12b159e4 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -13,9 +13,9 @@ import net.minecraft.command.argument.BlockArgumentParser; import net.minecraft.block.Blocks; import net.minecraft.item.ItemPlacementContext; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import net.minecraft.server.world.ServerWorld; import net.minecraft.state.property.Property; import net.minecraft.util.dynamic.GlobalPos; @@ -45,7 +45,7 @@ public class BlockValue extends Value private BlockState blockState; private final BlockPos pos; private final ServerWorld world; - private CompoundTag data; + private NbtCompound data; public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) { @@ -63,9 +63,9 @@ public class BlockValue extends Value BlockArgumentParser blockstateparser = (new BlockArgumentParser(new StringReader(str), false)).parse(true); if (blockstateparser.getBlockState() != null) { - CompoundTag bd = blockstateparser.getNbtData(); + NbtCompound bd = blockstateparser.getNbtData(); if (bd == null) - bd = new CompoundTag(); + bd = new NbtCompound(); bv = new BlockValue(blockstateparser.getBlockState(), null, null, bd ); if (bvCache.size()>10000) bvCache.clear(); @@ -107,7 +107,7 @@ public class BlockValue extends Value } - public CompoundTag getData() + public NbtCompound getData() { if (data != null) { @@ -118,13 +118,13 @@ public class BlockValue extends Value if (world != null && pos != null) { BlockEntity be = getBlockEntity(world, pos); - CompoundTag tag = new CompoundTag(); + NbtCompound tag = new NbtCompound(); if (be == null) { data = tag; return null; } - data = be.toTag(tag); + data = be.writeNbt(tag); return data; } return null; @@ -139,7 +139,7 @@ public class BlockValue extends Value data = null; } - public BlockValue(BlockState state, ServerWorld world, BlockPos position, CompoundTag nbt) + public BlockValue(BlockState state, ServerWorld world, BlockPos position, NbtCompound nbt) { this.world = world; blockState = state; @@ -188,26 +188,26 @@ public class BlockValue extends Value public ServerWorld getWorld() { return world;} @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); // follows falling block convertion - CompoundTag tag = new CompoundTag(); - CompoundTag state = new CompoundTag(); + NbtCompound tag = new NbtCompound(); + NbtCompound state = new NbtCompound(); BlockState s = getBlockState(); - state.put("Name", StringTag.of(Registry.BLOCK.getId(s.getBlock()).toString())); + state.put("Name", NbtString.of(Registry.BLOCK.getId(s.getBlock()).toString())); Collection> properties = s.getProperties(); if (!properties.isEmpty()) { - CompoundTag props = new CompoundTag(); + NbtCompound props = new NbtCompound(); for (Property p: properties) { - props.put(p.getName(), StringTag.of(s.get(p).toString().toLowerCase(Locale.ROOT))); + props.put(p.getName(), NbtString.of(s.get(p).toString().toLowerCase(Locale.ROOT))); } state.put("Properties", props); } tag.put("BlockState", state); - CompoundTag dataTag = getData(); + NbtCompound dataTag = getData(); if (dataTag != null) { tag.put("TileEntityData", dataTag); diff --git a/src/main/java/carpet/script/value/BooleanValue.java b/src/main/java/carpet/script/value/BooleanValue.java index 74dea6dd..4134c008 100644 --- a/src/main/java/carpet/script/value/BooleanValue.java +++ b/src/main/java/carpet/script/value/BooleanValue.java @@ -2,8 +2,8 @@ package carpet.script.value; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import net.minecraft.nbt.ByteTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtByte; +import net.minecraft.nbt.NbtElement; public class BooleanValue extends NumericValue { @@ -47,8 +47,8 @@ public class BooleanValue extends NumericValue } @Override - public Tag toTag(boolean force) { - return ByteTag.of(boolValue); + public NbtElement toTag(boolean force) { + return NbtByte.of(boolValue); } @Override diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index c68bd9c0..9307ef8b 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -31,8 +31,8 @@ import net.minecraft.entity.attribute.AttributeContainer; import net.minecraft.entity.attribute.EntityAttribute; import net.minecraft.entity.projectile.ProjectileEntity; import net.minecraft.entity.vehicle.AbstractMinecartEntity; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import net.minecraft.network.packet.s2c.play.EntityPassengersSetS2CPacket; import net.minecraft.network.packet.s2c.play.EntityPositionS2CPacket; import net.minecraft.network.packet.s2c.play.ExperienceBarUpdateS2CPacket; @@ -53,14 +53,16 @@ import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.mob.PathAwareEntity; import net.minecraft.entity.passive.PassiveEntity; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtCompound; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; +import net.minecraft.tag.Tag; import net.minecraft.util.Hand; import net.minecraft.util.Identifier; +import net.minecraft.util.TypeFilter; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.util.hit.HitResult; @@ -200,7 +202,7 @@ public class EntityValue extends Value { if (v instanceof EntityValue) { - return getEntity().getEntityId()==((EntityValue) v).getEntity().getEntityId(); + return getEntity().getId()==((EntityValue) v).getEntity().getId(); } return super.equals((Value)v); } @@ -250,7 +252,7 @@ public class EntityValue extends Value positive = false; who = who.substring(1); } - net.minecraft.tag.Tag> eTag = server.getTagManager().getEntityTypes().getTag(InputValidator.identifierOf(who)); + Tag> eTag = server.getTagManager().getOrCreateTagGroup(Registry.ENTITY_TYPE_KEY).getTag(InputValidator.identifierOf(who)); if (eTag == null) throw new InternalExpressionException(who+" is not a valid entity descriptor"); if (positive) { @@ -268,7 +270,7 @@ public class EntityValue extends Value public static class EntityClassDescriptor { - public EntityType directType; + public TypeFilter directType; // interface of EntityType public Predicate filteringPredicate; public List> typeList; public Value listValue; @@ -279,11 +281,25 @@ public class EntityValue extends Value typeList = types; listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getId(et)))).collect(Collectors.toList())); } + + EntityClassDescriptor( TypeFilter type, Predicate predicate, List> types) + { + directType = type; + filteringPredicate = predicate; + typeList = types; + listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getId(et)))).collect(Collectors.toList())); + } + EntityClassDescriptor(EntityType type, Predicate predicate, Stream> types) { this(type, predicate, types.collect(Collectors.toList())); } + EntityClassDescriptor(TypeFilter type, Predicate predicate, Stream> types) + { + this(type, predicate, types.collect(Collectors.toList())); + } + public final static Map byName = new HashMap() {{ List> allTypes = Registry.ENTITY_TYPE.stream().collect(Collectors.toList()); // nonliving types @@ -295,9 +311,9 @@ public class EntityValue extends Value EntityType.TRIDENT, EntityType.WITHER_SKULL, EntityType.FISHING_BOBBER, EntityType.SHULKER_BULLET ); Set> deads = Sets.newHashSet( - EntityType.AREA_EFFECT_CLOUD, EntityType.BOAT, EntityType.END_CRYSTAL, + EntityType.AREA_EFFECT_CLOUD, EntityType.MARKER, EntityType.BOAT, EntityType.END_CRYSTAL, EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, EntityType.EYE_OF_ENDER, - EntityType.FALLING_BLOCK, EntityType.ITEM, EntityType.ITEM_FRAME, + EntityType.FALLING_BLOCK, EntityType.ITEM, EntityType.ITEM_FRAME, EntityType.GLOW_ITEM_FRAME, EntityType.LEASH_KNOT, EntityType.LIGHTNING_BOLT, EntityType.PAINTING, EntityType.TNT, EntityType.ARMOR_STAND @@ -337,49 +353,49 @@ public class EntityValue extends Value ).collect(Collectors.toSet()); - put("*", new EntityClassDescriptor(null, e -> true, allTypes) ); - put("valid", new EntityClassDescriptor(null, EntityPredicates.VALID_ENTITY, allTypes)); - put("!valid", new EntityClassDescriptor(null, e -> !e.isAlive(), allTypes)); + put("*", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> true, allTypes) ); + put("valid", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), EntityPredicates.VALID_ENTITY, allTypes)); + put("!valid", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> !e.isAlive(), allTypes)); - put("living", new EntityClassDescriptor(null, (e) -> (e instanceof LivingEntity && e.isAlive()), allTypes.stream().filter(living::contains))); - put("!living", new EntityClassDescriptor(null, (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et)))); + put("living", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), EntityPredicates.VALID_ENTITY, allTypes.stream().filter(living::contains))); + put("!living", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et)))); - put("projectile", new EntityClassDescriptor(null, (e) -> (e instanceof ProjectileEntity && e.isAlive()), allTypes.stream().filter(projectiles::contains))); - put("!projectile", new EntityClassDescriptor(null, (e) -> (!(e instanceof ProjectileEntity) && e.isAlive()), allTypes.stream().filter(et -> !projectiles.contains(et) && !living.contains(et)))); + put("projectile", new EntityClassDescriptor(TypeFilter.instanceOf(ProjectileEntity.class), EntityPredicates.VALID_ENTITY, allTypes.stream().filter(projectiles::contains))); + put("!projectile", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> (!(e instanceof ProjectileEntity) && e.isAlive()), allTypes.stream().filter(et -> !projectiles.contains(et) && !living.contains(et)))); - put("minecarts", new EntityClassDescriptor(null, (e) -> (e instanceof AbstractMinecartEntity && e.isAlive()), allTypes.stream().filter(minecarts::contains))); - put("!minecarts", new EntityClassDescriptor(null, (e) -> (!(e instanceof AbstractMinecartEntity) && e.isAlive()), allTypes.stream().filter(et -> !minecarts.contains(et) && !living.contains(et)))); + put("minecarts", new EntityClassDescriptor(TypeFilter.instanceOf(AbstractMinecartEntity.class), EntityPredicates.VALID_ENTITY, allTypes.stream().filter(minecarts::contains))); + put("!minecarts", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> (!(e instanceof AbstractMinecartEntity) && e.isAlive()), allTypes.stream().filter(et -> !minecarts.contains(et) && !living.contains(et)))); // combat groups - put("arthropod", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() == EntityGroup.ARTHROPOD && e.isAlive()), allTypes.stream().filter(arthropods::contains))); - put("!arthropod", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() != EntityGroup.ARTHROPOD && e.isAlive()), allTypes.stream().filter(et -> !arthropods.contains(et) && living.contains(et)))); + put("arthropod", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.ARTHROPOD && e.isAlive()), allTypes.stream().filter(arthropods::contains))); + put("!arthropod", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.ARTHROPOD && e.isAlive()), allTypes.stream().filter(et -> !arthropods.contains(et) && living.contains(et)))); - put("undead", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() == EntityGroup.UNDEAD && e.isAlive()), allTypes.stream().filter(undeads::contains))); - put("!undead", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() != EntityGroup.UNDEAD && e.isAlive()), allTypes.stream().filter(et -> !undeads.contains(et) && living.contains(et)))); + put("undead", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.UNDEAD && e.isAlive()), allTypes.stream().filter(undeads::contains))); + put("!undead", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.UNDEAD && e.isAlive()), allTypes.stream().filter(et -> !undeads.contains(et) && living.contains(et)))); - put("aquatic", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() == EntityGroup.AQUATIC && e.isAlive()), allTypes.stream().filter(aquatique::contains))); - put("!aquatic", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() != EntityGroup.AQUATIC && e.isAlive()), allTypes.stream().filter(et -> !aquatique.contains(et) && living.contains(et)))); + put("aquatic", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.AQUATIC && e.isAlive()), allTypes.stream().filter(aquatique::contains))); + put("!aquatic", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.AQUATIC && e.isAlive()), allTypes.stream().filter(et -> !aquatique.contains(et) && living.contains(et)))); - put("illager", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() == EntityGroup.ILLAGER && e.isAlive()), allTypes.stream().filter(illagers::contains))); - put("!illager", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() != EntityGroup.ILLAGER && e.isAlive()), allTypes.stream().filter(et -> !illagers.contains(et) && living.contains(et)))); + put("illager", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.ILLAGER && e.isAlive()), allTypes.stream().filter(illagers::contains))); + put("!illager", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.ILLAGER && e.isAlive()), allTypes.stream().filter(et -> !illagers.contains(et) && living.contains(et)))); - put("regular", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() == EntityGroup.DEFAULT && e.isAlive()), allTypes.stream().filter(regular::contains))); - put("!regular", new EntityClassDescriptor(null, e -> ((e instanceof LivingEntity) && ((LivingEntity) e).getGroup() != EntityGroup.DEFAULT && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et)))); + put("regular", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.DEFAULT && e.isAlive()), allTypes.stream().filter(regular::contains))); + put("!regular", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.DEFAULT && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et)))); for (Identifier typeId : Registry.ENTITY_TYPE.getIds()) { EntityType type = Registry.ENTITY_TYPE.get(typeId); String mobType = ValueConversions.simplify(typeId); put( mobType, new EntityClassDescriptor(type, EntityPredicates.VALID_ENTITY, Stream.of(type))); - put("!"+mobType, new EntityClassDescriptor(null, (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); + put("!"+mobType, new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); } for (SpawnGroup catId : SpawnGroup.values()) { String catStr = catId.getName(); - put( catStr, new EntityClassDescriptor(null, e -> ((e.getType().getSpawnGroup() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getSpawnGroup() == catId))); - put("!"+catStr, new EntityClassDescriptor(null, e -> ((e.getType().getSpawnGroup() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getSpawnGroup() != catId))); + put( catStr, new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> ((e.getType().getSpawnGroup() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getSpawnGroup() == catId))); + put("!"+catStr, new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> ((e.getType().getSpawnGroup() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getSpawnGroup() != catId))); } }}; } @@ -408,11 +424,11 @@ public class EntityValue extends Value private static final Map> featureAccessors = new HashMap>() {{ //put("test", (e, a) -> a == null ? Value.NULL : new StringValue(a.getString())); - put("removed", (entity, arg) -> BooleanValue.of(entity.removed)); + put("removed", (entity, arg) -> BooleanValue.of(entity.isRemoved())); put("uuid",(e, a) -> new StringValue(e.getUuidAsString())); - put("id",(e, a) -> new NumericValue(e.getEntityId())); + put("id",(e, a) -> new NumericValue(e.getId())); put("pos", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()))); - put("location", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()), new NumericValue(e.yaw), new NumericValue(e.pitch))); + put("location", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()), new NumericValue(e.getYaw()), new NumericValue(e.getPitch()))); put("x", (e, a) -> new NumericValue(e.getX())); put("y", (e, a) -> new NumericValue(e.getY())); put("z", (e, a) -> new NumericValue(e.getZ())); @@ -439,18 +455,18 @@ public class EntityValue extends Value put("tags", (e, a) -> ListValue.wrap(e.getScoreboardTags().stream().map(StringValue::new).collect(Collectors.toList()))); put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getScoreboardTags().stream().map(StringValue::new).collect(Collectors.toList()))); - put("entity_tags", (e, a) -> ListValue.wrap(e.getServer().getTagManager().getEntityTypes().getTags().entrySet().stream().filter(entry -> entry.getValue().contains(e.getType())).map(entry -> ValueConversions.of(entry.getKey())).collect(Collectors.toList()))); + put("entity_tags", (e, a) -> ListValue.wrap(e.getServer().getTagManager().getOrCreateTagGroup(Registry.ENTITY_TYPE_KEY).getTags().entrySet().stream().filter(entry -> entry.getValue().contains(e.getType())).map(entry -> ValueConversions.of(entry.getKey())).collect(Collectors.toList()))); // deprecated put("has_tag", (e, a) -> BooleanValue.of(e.getScoreboardTags().contains(a.getString()))); put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getScoreboardTags().contains(a.getString()))); put("has_entity_tag", (e, a) -> { - net.minecraft.tag.Tag> tag = e.getServer().getTagManager().getEntityTypes().getTag(InputValidator.identifierOf(a.getString())); + Tag> tag = e.getServer().getTagManager().getOrCreateTagGroup(Registry.ENTITY_TYPE_KEY).getTag(InputValidator.identifierOf(a.getString())); if (tag == null) return Value.NULL; return BooleanValue.of(e.getType().isIn(tag)); }); - put("yaw", (e, a)-> new NumericValue(e.yaw)); + put("yaw", (e, a)-> new NumericValue(e.getYaw())); put("head_yaw", (e, a)-> { if (e instanceof LivingEntity) { @@ -466,16 +482,19 @@ public class EntityValue extends Value return Value.NULL; }); - put("pitch", (e, a)-> new NumericValue(e.pitch)); + put("pitch", (e, a)-> new NumericValue(e.getPitch())); put("look", (e, a) -> { Vec3d look = e.getRotationVector(); return ListValue.of(new NumericValue(look.x),new NumericValue(look.y),new NumericValue(look.z)); }); put("is_burning", (e, a) -> BooleanValue.of(e.isOnFire())); put("fire", (e, a) -> new NumericValue(e.getFireTicks())); + put("is_freezing", (e, a) -> BooleanValue.of(e.isFreezing())); + put("frost", (e, a) -> new NumericValue(e.getFrozenTicks())); put("silent", (e, a)-> BooleanValue.of(e.isSilent())); put("gravity", (e, a) -> BooleanValue.of(!e.hasNoGravity())); put("immune_to_fire", (e, a) -> BooleanValue.of(e.isFireImmune())); + put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze())); put("invulnerable", (e, a) -> BooleanValue.of(e.isInvulnerable())); put("dimension", (e, a) -> new StringValue(nameFromRegistryId(e.world.getRegistryKey().getValue()))); // getDimId @@ -739,7 +758,7 @@ public class EntityValue extends Value put("selected_slot", (e, a) -> { if (e instanceof PlayerEntity) - return new NumericValue(((PlayerEntity) e).inventory.selectedSlot); + return new NumericValue(((PlayerEntity) e).getInventory().selectedSlot); //getInventory return Value.NULL; }); @@ -858,7 +877,7 @@ public class EntityValue extends Value }); put("nbt",(e, a) -> { - CompoundTag nbttagcompound = e.toTag((new CompoundTag())); + NbtCompound nbttagcompound = e.writeNbt((new NbtCompound())); if (a==null) return new NBTSerializableValue(nbttagcompound); return new NBTSerializableValue(nbttagcompound).get(a); @@ -901,7 +920,7 @@ public class EntityValue extends Value EnumSet set = EnumSet.noneOf(PlayerPositionLookS2CPacket.Flag.class); set.add(PlayerPositionLookS2CPacket.Flag.X_ROT); set.add(PlayerPositionLookS2CPacket.Flag.Y_ROT); - ((ServerPlayerEntity)e).networkHandler.teleportRequest(x, y, z, yaw, pitch, set ); + ((ServerPlayerEntity)e).networkHandler.requestTeleport(x, y, z, yaw, pitch, set ); } else { @@ -933,7 +952,7 @@ public class EntityValue extends Value } private static final Map> featureModifiers = new HashMap>() {{ - put("remove", (entity, value) -> entity.remove()); + put("remove", (entity, value) -> entity.discard()); // using discard here - will see other options if valid put("age", (e, v) -> e.age = Math.abs((int)NumericValue.asNumber(v).getLong()) ); put("health", (e, v) -> { float health = (float) NumericValue.asNumber(v).getDouble(); @@ -993,25 +1012,25 @@ public class EntityValue extends Value NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), NumericValue.asNumber(coords.get(2)).getDouble(), - e.yaw, - e.pitch + e.getYaw(), + e.getPitch() ); }); put("x", (e, v) -> { - updatePosition(e, NumericValue.asNumber(v).getDouble(), e.getY(), e.getZ(), e.yaw, e.pitch); + updatePosition(e, NumericValue.asNumber(v).getDouble(), e.getY(), e.getZ(), e.getYaw(), e.getPitch()); }); put("y", (e, v) -> { - updatePosition(e, e.getX(), NumericValue.asNumber(v).getDouble(), e.getZ(), e.yaw, e.pitch); + updatePosition(e, e.getX(), NumericValue.asNumber(v).getDouble(), e.getZ(), e.getYaw(), e.getPitch()); }); put("z", (e, v) -> { - updatePosition(e, e.getX(), e.getY(), NumericValue.asNumber(v).getDouble(), e.yaw, e.pitch); + updatePosition(e, e.getX(), e.getY(), NumericValue.asNumber(v).getDouble(), e.getYaw(), e.getPitch()); }); put("yaw", (e, v) -> { - updatePosition(e, e.getX(), e.getY(), e.getZ(), ((float)NumericValue.asNumber(v).getDouble()) % 360, e.pitch); + updatePosition(e, e.getX(), e.getY(), e.getZ(), ((float)NumericValue.asNumber(v).getDouble()) % 360, e.getPitch()); }); put("head_yaw", (e, v) -> { @@ -1030,7 +1049,7 @@ public class EntityValue extends Value put("pitch", (e, v) -> { - updatePosition(e, e.getX(), e.getY(), e.getZ(), e.yaw, MathHelper.clamp((float)NumericValue.asNumber(v).getDouble(), -90, 90)); + updatePosition(e, e.getX(), e.getY(), e.getZ(), e.getYaw(), MathHelper.clamp((float)NumericValue.asNumber(v).getDouble(), -90, 90)); }); put("look", (e, v) -> { @@ -1045,7 +1064,7 @@ public class EntityValue extends Value y /= l; z /= l; float pitch = (float) -Math.asin(y) / 0.017453292F; - float yaw = (float) (x==0 && z==0 ? e.yaw : MathHelper.atan2(-x,z) / 0.017453292F); + float yaw = (float) (x==0 && z==0 ? e.getYaw() : MathHelper.atan2(-x,z) / 0.017453292F); updatePosition(e, e.getX(), e.getY(), e.getZ(), yaw, pitch); }); @@ -1063,8 +1082,8 @@ public class EntityValue extends Value e.getX() + NumericValue.asNumber(coords.get(0)).getDouble(), e.getY() + NumericValue.asNumber(coords.get(1)).getDouble(), e.getZ() + NumericValue.asNumber(coords.get(2)).getDouble(), - e.yaw, - e.pitch + e.getYaw(), + e.getPitch() ); }); @@ -1288,7 +1307,7 @@ public class EntityValue extends Value BlockValue bv= (BlockValue)a; if (bv.getPos()==null || bv.getWorld() == null) throw new InternalExpressionException("block for spawn modification should be localised in the world"); - spe.setSpawnPoint(bv.getWorld().getRegistryKey(), bv.getPos(), e.yaw, true, false); + spe.setSpawnPoint(bv.getWorld().getRegistryKey(), bv.getPos(), e.getYaw(), true, false); // yaw } else if (a.isNull()) { @@ -1408,7 +1427,7 @@ public class EntityValue extends Value GameMode toSet = v instanceof NumericValue ? GameMode.byId(((NumericValue) v).getInt(), null) : GameMode.byName(v.getString().toLowerCase(Locale.ROOT), null); - if (toSet != null) ((ServerPlayerEntity) e).setGameMode(toSet); + if (toSet != null) ((ServerPlayerEntity) e).changeGameMode(toSet); }); put("jumping",(e,v)->{ @@ -1447,6 +1466,7 @@ public class EntityValue extends Value put("invulnerable",(e,v)-> e.setInvulnerable(v.getBoolean())); put("fire",(e,v)-> e.setFireTicks((int)NumericValue.asNumber(v).getLong())); + put("frost",(e,v)-> e.setFrozenTicks((int)NumericValue.asNumber(v).getLong())); put("hunger", (e, v)-> { if(e instanceof PlayerEntity) ((PlayerEntity) e).getHungerManager().setFoodLevel((int) NumericValue.asNumber(v).getLong()); @@ -1507,7 +1527,7 @@ public class EntityValue extends Value Value tagValue = NBTSerializableValue.fromValue(v); if (tagValue instanceof NBTSerializableValue) { - e.fromTag(((NBTSerializableValue) tagValue).getCompoundTag()); + e.readNbt(((NBTSerializableValue) tagValue).getCompoundTag()); e.setUuid(uUID); } } @@ -1519,9 +1539,9 @@ public class EntityValue extends Value Value tagValue = NBTSerializableValue.fromValue(v); if (tagValue instanceof NBTSerializableValue) { - CompoundTag nbttagcompound = e.toTag((new CompoundTag())); + NbtCompound nbttagcompound = e.writeNbt((new NbtCompound())); nbttagcompound.copyFrom(((NBTSerializableValue) tagValue).getCompoundTag()); - e.fromTag(nbttagcompound); + e.readNbt(nbttagcompound); e.setUuid(uUID); } } @@ -1542,12 +1562,12 @@ public class EntityValue extends Value } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - CompoundTag tag = new CompoundTag(); - tag.put("Data", getEntity().toTag( new CompoundTag())); - tag.put("Name", StringTag.of(Registry.ENTITY_TYPE.getId(getEntity().getType()).toString())); + NbtCompound tag = new NbtCompound(); + tag.put("Data", getEntity().writeNbt( new NbtCompound())); + tag.put("Name", NbtString.of(Registry.ENTITY_TYPE.getId(getEntity().getType()).toString())); return tag; } } diff --git a/src/main/java/carpet/script/value/FormattedTextValue.java b/src/main/java/carpet/script/value/FormattedTextValue.java index c237d7ec..ae71913f 100644 --- a/src/main/java/carpet/script/value/FormattedTextValue.java +++ b/src/main/java/carpet/script/value/FormattedTextValue.java @@ -1,7 +1,7 @@ package carpet.script.value; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import net.minecraft.text.BaseText; import net.minecraft.text.LiteralText; import net.minecraft.text.Text; @@ -75,10 +75,10 @@ public class FormattedTextValue extends StringValue } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return StringTag.of(Text.Serializer.toJson(text)); + return NbtString.of(Text.Serializer.toJson(text)); } @Override diff --git a/src/main/java/carpet/script/value/FrameworkValue.java b/src/main/java/carpet/script/value/FrameworkValue.java index a432974e..a330876f 100644 --- a/src/main/java/carpet/script/value/FrameworkValue.java +++ b/src/main/java/carpet/script/value/FrameworkValue.java @@ -1,6 +1,6 @@ package carpet.script.value; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtElement; public abstract class FrameworkValue extends Value { @@ -29,7 +29,7 @@ public abstract class FrameworkValue extends Value } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { throw new UnsupportedOperationException("Scarpet language component cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionAnnotationValue.java b/src/main/java/carpet/script/value/FunctionAnnotationValue.java index 41ba7914..4d213c89 100644 --- a/src/main/java/carpet/script/value/FunctionAnnotationValue.java +++ b/src/main/java/carpet/script/value/FunctionAnnotationValue.java @@ -1,7 +1,7 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtElement; public class FunctionAnnotationValue extends Value { @@ -37,7 +37,7 @@ public class FunctionAnnotationValue extends Value } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { throw new UnsupportedOperationException("Global value cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionValue.java b/src/main/java/carpet/script/value/FunctionValue.java index cb91dac2..f7bdee6d 100644 --- a/src/main/java/carpet/script/value/FunctionValue.java +++ b/src/main/java/carpet/script/value/FunctionValue.java @@ -12,8 +12,8 @@ import carpet.script.exception.ContinueStatement; import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ReturnStatement; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import java.util.ArrayList; import java.util.Collections; @@ -281,10 +281,10 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction public String getVarArgs() {return varArgs; } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return StringTag.of(getString()); + return NbtString.of(getString()); } public void assertArgsOk(List list, Consumer feedback) diff --git a/src/main/java/carpet/script/value/LazyListValue.java b/src/main/java/carpet/script/value/LazyListValue.java index 725bcfe3..ec9ea88f 100644 --- a/src/main/java/carpet/script/value/LazyListValue.java +++ b/src/main/java/carpet/script/value/LazyListValue.java @@ -1,8 +1,8 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import java.util.ArrayList; import java.util.Iterator; @@ -204,9 +204,9 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return StringTag.of(getString()); + return NbtString.of(getString()); } } diff --git a/src/main/java/carpet/script/value/ListValue.java b/src/main/java/carpet/script/value/ListValue.java index 25e1be8b..7420e4ac 100644 --- a/src/main/java/carpet/script/value/ListValue.java +++ b/src/main/java/carpet/script/value/ListValue.java @@ -4,14 +4,14 @@ import carpet.script.LazyValue; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import net.minecraft.nbt.AbstractNumberTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.LongTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.AbstractNbtNumber; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtDouble; +import net.minecraft.nbt.NbtInt; +import net.minecraft.nbt.NbtList; +import net.minecraft.nbt.NbtLong; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import java.util.ArrayList; import java.util.Arrays; @@ -477,31 +477,31 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf LIST, MAP, STRING; - private static TagTypeCompat getType(Tag tag) + private static TagTypeCompat getType(NbtElement tag) { - if (tag instanceof IntTag) return INT; - if (tag instanceof LongTag) return LONG; - if (tag instanceof DoubleTag) return DBL; - if (tag instanceof ListTag) return LIST; - if (tag instanceof CompoundTag) return MAP; + if (tag instanceof NbtInt) return INT; + if (tag instanceof NbtLong) return LONG; + if (tag instanceof NbtDouble) return DBL; + if (tag instanceof NbtList) return LIST; + if (tag instanceof NbtCompound) return MAP; return STRING; } } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { int argSize = items.size(); - if (argSize == 0) return new ListTag(); - ListTag tag = new ListTag(); + if (argSize == 0) return new NbtList(); + NbtList tag = new NbtList(); if (argSize ==1) { tag.add(items.get(0).toTag(force)); return tag; } // figuring out the types - List tags= new ArrayList<>(); + List tags= new ArrayList<>(); items.forEach(v -> tags.add(v.toTag(force))); Set cases = EnumSet.noneOf(TagTypeCompat.class); tags.forEach(t -> cases.add(TagTypeCompat.getType(t))); @@ -515,17 +515,17 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf || cases.contains(TagTypeCompat.STRING)) // incompatible types { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - tags.forEach(t -> tag.add(StringTag.of(t.asString()))); + tags.forEach(t -> tag.add(NbtString.of(t.asString()))); return tag; } // only numbers / mixed types if (cases.contains(TagTypeCompat.DBL)) { - tags.forEach(t -> tag.add(DoubleTag.of(((AbstractNumberTag)t).getDouble()))); + tags.forEach(t -> tag.add(NbtDouble.of(((AbstractNbtNumber)t).doubleValue()))); } else { - tags.forEach(t -> tag.add(LongTag.of(((AbstractNumberTag)t).getLong()))); + tags.forEach(t -> tag.add(NbtLong.of(((AbstractNbtNumber)t).longValue()))); } return tag; } diff --git a/src/main/java/carpet/script/value/MapValue.java b/src/main/java/carpet/script/value/MapValue.java index 19e05681..6923edec 100644 --- a/src/main/java/carpet/script/value/MapValue.java +++ b/src/main/java/carpet/script/value/MapValue.java @@ -3,8 +3,8 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtElement; import java.util.ArrayList; import java.util.Collections; @@ -260,9 +260,9 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { - CompoundTag tag = new CompoundTag() ; + NbtCompound tag = new NbtCompound() ; map.forEach( (k, v) -> { if (!force && !(k instanceof StringValue)) throw new NBTSerializableValue.IncompatibleTypeException(k); diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index 3d59ec48..4a3a7b00 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -19,19 +19,21 @@ import net.minecraft.command.argument.ItemStackArgument; import net.minecraft.command.argument.ItemStringReader; import net.minecraft.command.argument.NbtPathArgumentType; import net.minecraft.entity.Entity; +import net.minecraft.entity.InventoryOwner; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.mob.MobEntity; +import net.minecraft.entity.passive.MerchantEntity; import net.minecraft.entity.passive.VillagerEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.Inventory; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.AbstractListTag; -import net.minecraft.nbt.AbstractNumberTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.AbstractNbtList; +import net.minecraft.nbt.AbstractNbtNumber; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtList; import net.minecraft.nbt.StringNbtReader; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; @@ -53,8 +55,8 @@ import java.util.stream.Collectors; public class NBTSerializableValue extends Value implements ContainerValueInterface { private String nbtString = null; - private Tag nbtTag = null; - private Supplier nbtSupplier = null; + private NbtElement nbtTag = null; + private Supplier nbtSupplier = null; private boolean owned = false; private NBTSerializableValue() {} @@ -65,7 +67,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa { try { - return (new StringNbtReader(new StringReader(nbtString))).parseTag(); + return (new StringNbtReader(new StringReader(nbtString))).parseElement(); } catch (CommandSyntaxException e) { @@ -75,19 +77,19 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa owned = true; } - public NBTSerializableValue(Tag tag) + public NBTSerializableValue(NbtElement tag) { nbtTag = tag; owned = true; } - public static Value of(Tag tag) + public static Value of(NbtElement tag) { if (tag == null) return Value.NULL; return new NBTSerializableValue(tag); } - public NBTSerializableValue(Supplier tagSupplier) + public NBTSerializableValue(Supplier tagSupplier) { nbtSupplier = tagSupplier; } @@ -114,10 +116,10 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa public static NBTSerializableValue parseString(String nbtString, boolean fail) { - Tag tag; + NbtElement tag; try { - tag = (new StringNbtReader(new StringReader(nbtString))).parseTag(); + tag = (new StringNbtReader(new StringReader(nbtString))).parseElement(); } catch (CommandSyntaxException e) { @@ -163,7 +165,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa Block block = blockState.getBlock(); if (block instanceof InventoryProvider) { inventory = ((InventoryProvider)block).getInventory(blockState, world, blockPos); - } else if (block.hasBlockEntity()) { + } else if (blockState.hasBlockEntity()) { BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos); if (blockEntity instanceof Inventory) { inventory = (Inventory)blockEntity; @@ -205,7 +207,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa if (strVal.equals("enderchest")) { Value v2 = params.get(1 + offset); - ServerPlayerEntity player = EntityValue.getPlayerByValue(c.s.getMinecraftServer(), v2); + ServerPlayerEntity player = EntityValue.getPlayerByValue(c.s.getServer(), v2); if (player == null) throw new InternalExpressionException("enderchest inventory requires player argument"); return new InventoryLocator(player, player.getBlockPos(), player.getEnderChestInventory(), offset + 2, true); } @@ -219,12 +221,12 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } boolean isEnder = strVal.startsWith("enderchest_"); if (isEnder) strVal = strVal.substring(11); // len("enderchest_") - ServerPlayerEntity player = c.s.getMinecraftServer().getPlayerManager().getPlayer(strVal); + ServerPlayerEntity player = c.s.getServer().getPlayerManager().getPlayer(strVal); if (player == null) throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest"); return new InventoryLocator( player, player.getBlockPos(), - isEnder ? player.getEnderChestInventory() : player.inventory, + isEnder ? player.getEnderChestInventory() : player.getInventory(), offset + 1, isEnder ); @@ -233,10 +235,10 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa { Inventory inv = null; Entity e = ((EntityValue) v1).getEntity(); - if (e instanceof PlayerEntity) inv = ((PlayerEntity) e).inventory; + if (e instanceof PlayerEntity) inv = ((PlayerEntity) e).getInventory(); else if (e instanceof Inventory) inv = (Inventory) e; - else if (e instanceof VillagerEntity) inv = ((VillagerEntity) e).getInventory(); - else if (e instanceof InventoryBearerInterface) inv = ((InventoryBearerInterface)e).getCMInventory(); + else if (e instanceof InventoryOwner) inv = ((InventoryOwner) e).getInventory(); + else if (e instanceof InventoryBearerInterface) inv = ((InventoryBearerInterface)e).getCMInventory(); // horse only else if (e instanceof LivingEntity) return new InventoryLocator(e, e.getBlockPos(), new EquipmentInventory((MobEntity) e), offset+1); if (inv == null) return null; @@ -287,7 +289,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return parseItem(itemString, null); } - public static ItemStackArgument parseItem(String itemString, CompoundTag customTag) + public static ItemStackArgument parseItem(String itemString, NbtCompound customTag) { try { @@ -299,7 +301,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return new ItemStackArgument(res.getItem(), customTag); ItemStringReader parser = (new ItemStringReader(new StringReader(itemString), false)).consume(); - res = new ItemStackArgument(parser.getItem(), parser.getTag()); + res = new ItemStackArgument(parser.getItem(), parser.getNbt()); itemCache.put(itemString, res); if (itemCache.size()>64000) itemCache.clear(); @@ -324,12 +326,12 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return slot; } - private static Value decodeTag(Tag t) + private static Value decodeTag(NbtElement t) { - if (t instanceof CompoundTag) + if (t instanceof NbtCompound) return new NBTSerializableValue(() -> t); - if (t instanceof AbstractNumberTag) - return new NumericValue(((AbstractNumberTag) t).getDouble()); + if (t instanceof AbstractNbtNumber) + return new NumericValue(((AbstractNbtNumber) t).doubleValue()); // more can be done here return new StringValue(t.asString()); } @@ -349,35 +351,35 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } - private static Value decodeTagDeep(Tag t) + private static Value decodeTagDeep(NbtElement t) { - if (t instanceof CompoundTag) + if (t instanceof NbtCompound) { Map pairs = new HashMap<>(); - CompoundTag ctag = (CompoundTag)t; + NbtCompound ctag = (NbtCompound)t; for (String key: ctag.getKeys()) { pairs.put(new StringValue(key), decodeTagDeep(ctag.get(key))); } return MapValue.wrap(pairs); } - if (t instanceof AbstractListTag) + if (t instanceof AbstractNbtList) { List elems = new ArrayList<>(); - AbstractListTag ltag = (AbstractListTag)t; - for (Tag elem: ltag) + AbstractNbtList ltag = (AbstractNbtList)t; + for (NbtElement elem: ltag) { elems.add(decodeTagDeep(elem)); } return ListValue.wrap(elems); } - if (t instanceof AbstractNumberTag) - return new NumericValue(((AbstractNumberTag) t).getDouble()); + if (t instanceof AbstractNbtNumber) + return new NumericValue(((AbstractNbtNumber) t).doubleValue()); // more can be done here return new StringValue(t.asString()); } - public Tag getTag() + public NbtElement getTag() { if (nbtTag == null) nbtTag = nbtSupplier.get(); @@ -403,24 +405,24 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa @Override public boolean getBoolean() { - Tag tag = getTag(); - if (tag instanceof CompoundTag) - return !((CompoundTag) tag).isEmpty(); - if (tag instanceof AbstractListTag) - return ((AbstractListTag) tag).isEmpty(); - if (tag instanceof AbstractNumberTag) - return ((AbstractNumberTag) tag).getDouble()!=0.0; - if (tag instanceof StringTag) + NbtElement tag = getTag(); + if (tag instanceof NbtCompound) + return !((NbtCompound) tag).isEmpty(); + if (tag instanceof AbstractNbtList) + return ((AbstractNbtList) tag).isEmpty(); + if (tag instanceof AbstractNbtNumber) + return ((AbstractNbtNumber) tag).doubleValue()!=0.0; + if (tag instanceof NbtString) return tag.asString().isEmpty(); return true; } - public CompoundTag getCompoundTag() + public NbtCompound getCompoundTag() { try { ensureOwnership(); - return (CompoundTag) getTag(); + return (NbtCompound) getTag(); } catch (ClassCastException e) { @@ -440,7 +442,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa /// WIP ensureOwnership(); NbtPathArgumentType.NbtPath path = cachePath(where.getString()); - Tag tagToInsert = value instanceof NBTSerializableValue ? + NbtElement tagToInsert = value instanceof NBTSerializableValue ? ((NBTSerializableValue) value).getTag() : new NBTSerializableValue(value.getString()).getTag(); boolean modifiedTag; @@ -470,17 +472,17 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa - private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, Tag newElement) + private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, NbtElement newElement) { return modify_insert(index, nbtPath, newElement, this.getTag()); } - private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, Tag newElement, Tag currentTag) + private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, NbtElement newElement, NbtElement currentTag) { - Collection targets; + Collection targets; try { - targets = nbtPath.getOrInit(currentTag, ListTag::new); + targets = nbtPath.getOrInit(currentTag, NbtList::new); } catch (CommandSyntaxException e) { @@ -488,16 +490,16 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } boolean modified = false; - for (Tag target : targets) + for (NbtElement target : targets) { - if (!(target instanceof AbstractListTag)) + if (!(target instanceof AbstractNbtList)) { continue; } try { - AbstractListTag targetList = (AbstractListTag) target; - if (!targetList.addTag(index < 0 ? targetList.size() + index + 1 : index, newElement.copy())) + AbstractNbtList targetList = (AbstractNbtList) target; + if (!targetList.addElement(index < 0 ? targetList.size() + index + 1 : index, newElement.copy())) return false; modified = true; } @@ -509,22 +511,22 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } - private boolean modify_merge(NbtPathArgumentType.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modify_merge(NbtPathArgumentType.NbtPath nbtPath, NbtElement replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - if (!(replacement instanceof CompoundTag)) + if (!(replacement instanceof NbtCompound)) { return false; } - Tag ownTag = getTag(); + NbtElement ownTag = getTag(); try { - for (Tag target : nbtPath.getOrInit(ownTag, CompoundTag::new)) + for (NbtElement target : nbtPath.getOrInit(ownTag, NbtCompound::new)) { - if (!(target instanceof CompoundTag)) + if (!(target instanceof NbtCompound)) { continue; } - ((CompoundTag) target).copyFrom((CompoundTag) replacement); + ((NbtCompound) target).copyFrom((NbtCompound) replacement); } } catch (CommandSyntaxException ignored) @@ -534,9 +536,9 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return true; } - private boolean modify_replace(NbtPathArgumentType.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modify_replace(NbtPathArgumentType.NbtPath nbtPath, NbtElement replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - Tag tag = getTag(); + NbtElement tag = getTag(); String pathText = nbtPath.toString(); if (pathText.endsWith("]")) // workaround for array replacement or item in the array replacement { @@ -584,7 +586,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa NbtPathArgumentType.NbtPath path = cachePath(valString); try { - List tags = path.get(getTag()); + List tags = path.get(getTag()); if (tags.size()==0) return Value.NULL; if (tags.size()==1 && !valString.endsWith("[]")) @@ -681,7 +683,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); ensureOwnership(); diff --git a/src/main/java/carpet/script/value/NullValue.java b/src/main/java/carpet/script/value/NullValue.java index 1e5f08a0..8374e51f 100644 --- a/src/main/java/carpet/script/value/NullValue.java +++ b/src/main/java/carpet/script/value/NullValue.java @@ -4,8 +4,8 @@ import java.util.ArrayList; import com.google.gson.JsonElement; import com.google.gson.JsonNull; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; public class NullValue extends NumericValue // TODO check nonsingleton code { @@ -80,10 +80,10 @@ public class NullValue extends NumericValue // TODO check nonsingleton code } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return StringTag.of("null"); + return NbtString.of("null"); } @Override diff --git a/src/main/java/carpet/script/value/NumericValue.java b/src/main/java/carpet/script/value/NumericValue.java index 33f599a6..93a05160 100644 --- a/src/main/java/carpet/script/value/NumericValue.java +++ b/src/main/java/carpet/script/value/NumericValue.java @@ -3,10 +3,10 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.LongTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtDouble; +import net.minecraft.nbt.NbtInt; +import net.minecraft.nbt.NbtLong; +import net.minecraft.nbt.NbtElement; import org.apache.commons.lang3.StringUtils; import java.math.BigDecimal; @@ -278,20 +278,20 @@ public class NumericValue extends Value } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (longValue != null) - return LongTag.of(longValue); + return NbtLong.of(longValue); long lv = getLong(); if (value == (double)lv) { if (abs(value) < Integer.MAX_VALUE-2) - return IntTag.of((int)lv); - return LongTag.of(getLong()); + return NbtInt.of((int)lv); + return NbtLong.of(getLong()); } else { - return DoubleTag.of(value); + return NbtDouble.of(value); } } diff --git a/src/main/java/carpet/script/value/StringValue.java b/src/main/java/carpet/script/value/StringValue.java index 48fea7c1..65d7553c 100644 --- a/src/main/java/carpet/script/value/StringValue.java +++ b/src/main/java/carpet/script/value/StringValue.java @@ -1,7 +1,7 @@ package carpet.script.value; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtString; +import net.minecraft.nbt.NbtElement; public class StringValue extends Value { @@ -43,8 +43,8 @@ public class StringValue extends Value } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { - return StringTag.of(str); + return NbtString.of(str); } } diff --git a/src/main/java/carpet/script/value/ThreadValue.java b/src/main/java/carpet/script/value/ThreadValue.java index 0e814f26..30c63555 100644 --- a/src/main/java/carpet/script/value/ThreadValue.java +++ b/src/main/java/carpet/script/value/ThreadValue.java @@ -6,7 +6,7 @@ import carpet.script.Tokenizer; import carpet.script.exception.ExitStatement; import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtElement; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -117,7 +117,7 @@ public class ThreadValue extends Value } @Override - public Tag toTag(boolean force) + public NbtElement toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); return getValue().toTag(true); diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java index 56ff2d31..0c004039 100644 --- a/src/main/java/carpet/script/value/Value.java +++ b/src/main/java/carpet/script/value/Value.java @@ -3,7 +3,7 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NbtElement; import java.util.ArrayList; import java.util.Arrays; @@ -236,7 +236,7 @@ public abstract class Value implements Comparable, Cloneable } } - public abstract Tag toTag(boolean force); + public abstract NbtElement toTag(boolean force); public JsonElement toJson() { diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index f2346269..2d9999b9 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -6,7 +6,7 @@ import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; import carpet.utils.BlockInfo; import net.minecraft.block.BlockState; -import net.minecraft.block.MaterialColor; +import net.minecraft.block.MapColor; import net.minecraft.block.pattern.CachedBlockPosition; import net.minecraft.entity.Entity; import net.minecraft.entity.ai.brain.LookTarget; @@ -75,7 +75,7 @@ public class ValueConversions return of(world.getRegistryKey().getValue()); } - public static Value of(MaterialColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.color));} + public static Value of(MapColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.color));} public static Value of(NumberRange range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));} @@ -207,7 +207,7 @@ public class ValueConversions { PathNode node = path.getNode(i); nodes.add( ListValue.of( - new BlockValue(null, world, node.getPos()), + new BlockValue(null, world, node.getBlockPos()), new StringValue(node.type.name().toLowerCase(Locale.ROOT)), new NumericValue(node.penalty), BooleanValue.of(node.visited) @@ -310,36 +310,32 @@ public class ValueConversions ListValue.fromTriple(box.maxX, box.maxY, box.maxZ) ); } - public static Value of(BlockBox box) { return ListValue.of( - ListValue.fromTriple(box.minX, box.minY, box.minZ), - ListValue.fromTriple(box.maxX, box.maxY, box.maxZ) + ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()), + ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ()) ); } public static Value of(StructureStart structure) { if (structure == null || structure == StructureStart.DEFAULT) return Value.NULL; - BlockBox boundingBox = structure.getBoundingBox(); - if (boundingBox.maxX < boundingBox.minX || boundingBox.maxY < boundingBox.minY || boundingBox.maxZ < boundingBox.minZ) return Value.NULL; + BlockBox boundingBox = structure.setBoundingBoxFromChildren(); + if (boundingBox.getMaxX() < boundingBox.getMinX() || boundingBox.getMaxY() < boundingBox.getMinY() || boundingBox.getMaxZ() < boundingBox.getMinZ()) return Value.NULL; Map ret = new HashMap<>(); - ret.put(new StringValue("box"), ListValue.of( - ListValue.fromTriple(boundingBox.minX, boundingBox.minY, boundingBox.minZ), - ListValue.fromTriple(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ) - )); + ret.put(new StringValue("box"), of(boundingBox)); List pieces = new ArrayList<>(); for (StructurePiece piece : structure.getChildren()) { BlockBox box = piece.getBoundingBox(); - if (box.maxX >= box.minX && box.maxY >= box.minY && box.maxZ >= box.minZ) + if (box.getMaxX() >= box.getMinX() && box.getMaxY() >= box.getMinY() && box.getMaxZ() >= box.getMinZ()) { pieces.add(ListValue.of( new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_PIECE.getId(piece.getType()))), (piece.getFacing() == null) ? Value.NULL : new StringValue(piece.getFacing().getName()), - ListValue.fromTriple(box.minX, box.minY, box.minZ), - ListValue.fromTriple(box.maxX, box.maxY, box.maxZ) + ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()), + ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ()) )); } } @@ -408,7 +404,7 @@ public class ValueConversions BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; return ListValue.of( predicateData.getCMBlockState()==null?Value.NULL:of(Registry.BLOCK.getId(predicateData.getCMBlockState().getBlock())), - predicateData.getCMBlockTag()==null?Value.NULL:of(tagManager.getBlocks().getTagId(predicateData.getCMBlockTag())), + predicateData.getCMBlockTag()==null?Value.NULL:of(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getUncheckedTagId(predicateData.getCMBlockTag())), MapValue.wrap(predicateData.getCMProperties()), predicateData.getCMDataTag() == null?Value.NULL:new NBTSerializableValue(predicateData.getCMDataTag()) ); diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index 85ad6cb4..1a7a933c 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -3,10 +3,10 @@ package carpet.utils; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Material; -import net.minecraft.block.MaterialColor; +import net.minecraft.block.MapColor; import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.ai.TargetFinder; +import net.minecraft.entity.ai.NoPenaltyTargeting; import net.minecraft.entity.ai.goal.WanderAroundGoal; import net.minecraft.entity.ai.pathing.NavigationType; import net.minecraft.entity.mob.PathAwareEntity; @@ -67,61 +67,81 @@ public class BlockInfo put(BlockSoundGroup.BONE, "bone"); put(BlockSoundGroup.NETHERITE, "netherite"); put(BlockSoundGroup.ANCIENT_DEBRIS, "ancient_debris"); + put(BlockSoundGroup.LODESTONE, "lodestone"); + put(BlockSoundGroup.CHAIN, "chain"); + put(BlockSoundGroup.NETHER_GOLD_ORE, "nether_gold_ore"); + put(BlockSoundGroup.GILDED_BLACKSTONE, "gilded_blackstone"); + put(BlockSoundGroup.CANDLE, "candle"); + put(BlockSoundGroup.AMETHYST_BLOCK, "amethyst"); + put(BlockSoundGroup.AMETHYST_CLUSTER, "amethyst_cluster"); + put(BlockSoundGroup.SMALL_AMETHYST_BUD, "small_amethyst_bud"); + put(BlockSoundGroup.LARGE_AMETHYST_BUD, "large_amethyst_bud"); + put(BlockSoundGroup.MEDIUM_AMETHYST_BUD, "medium_amethyst_bud"); + put(BlockSoundGroup.TUFF, "tuff"); + put(BlockSoundGroup.CALCITE, "calcite"); + put(BlockSoundGroup.COPPER, "copper"); }}; - public static final Map mapColourName = new HashMap() {{ - put(MaterialColor.CLEAR , "air" ); - put(MaterialColor.GRASS , "grass" ); - put(MaterialColor.SAND , "sand" ); - put(MaterialColor.WEB , "wool" ); - put(MaterialColor.LAVA , "tnt" ); - put(MaterialColor.ICE , "ice" ); - put(MaterialColor.IRON , "iron" ); - put(MaterialColor.FOLIAGE , "foliage" ); - put(MaterialColor.WHITE , "snow" ); - put(MaterialColor.CLAY , "clay" ); - put(MaterialColor.DIRT , "dirt" ); - put(MaterialColor.STONE , "stone" ); - put(MaterialColor.WATER , "water" ); - put(MaterialColor.WOOD , "wood" ); - put(MaterialColor.QUARTZ , "quartz" ); - put(MaterialColor.ORANGE , "adobe" ); - put(MaterialColor.MAGENTA , "magenta" ); - put(MaterialColor.LIGHT_BLUE, "light_blue"); - put(MaterialColor.YELLOW , "yellow" ); - put(MaterialColor.LIME , "lime" ); - put(MaterialColor.PINK , "pink" ); - put(MaterialColor.GRAY , "gray" ); - put(MaterialColor.LIGHT_GRAY, "light_gray"); - put(MaterialColor.CYAN , "cyan" ); - put(MaterialColor.PURPLE , "purple" ); - put(MaterialColor.BLUE , "blue" ); - put(MaterialColor.BROWN , "brown" ); - put(MaterialColor.GREEN , "green" ); - put(MaterialColor.RED , "red" ); - put(MaterialColor.BLACK , "black" ); - put(MaterialColor.GOLD , "gold" ); - put(MaterialColor.DIAMOND , "diamond" ); - put(MaterialColor.LAPIS , "lapis" ); - put(MaterialColor.EMERALD , "emerald" ); - put(MaterialColor.SPRUCE , "obsidian" ); - put(MaterialColor.NETHER , "netherrack"); //TODO fix these - put(MaterialColor.WHITE_TERRACOTTA , "white_terracotta" ); - put(MaterialColor.ORANGE_TERRACOTTA , "orange_terracotta" ); - put(MaterialColor.MAGENTA_TERRACOTTA , "magenta_terracotta" ); - put(MaterialColor.LIGHT_BLUE_TERRACOTTA, "light_blue_terracotta" ); - put(MaterialColor.YELLOW_TERRACOTTA , "yellow_terracotta" ); - put(MaterialColor.LIME_TERRACOTTA , "lime_terracotta" ); - put(MaterialColor.PINK_TERRACOTTA , "pink_terracotta" ); - put(MaterialColor.GRAY_TERRACOTTA , "gray_terracotta" ); - put(MaterialColor.LIGHT_GRAY_TERRACOTTA, "light_gray_terracotta" ); - put(MaterialColor.CYAN_TERRACOTTA , "cyan_terracotta" ); - put(MaterialColor.PURPLE_TERRACOTTA , "purple_terracotta" ); - put(MaterialColor.BLUE_TERRACOTTA , "blue_terracotta" ); - put(MaterialColor.BROWN_TERRACOTTA , "brown_terracotta" ); - put(MaterialColor.GREEN_TERRACOTTA , "green_terracotta" ); - put(MaterialColor.RED_TERRACOTTA , "red_terracotta" ); - put(MaterialColor.BLACK_TERRACOTTA , "black_terracotta" ); + public static final Map mapColourName = new HashMap() {{ + put(MapColor.CLEAR , "air" ); + put(MapColor.PALE_GREEN , "grass" ); + put(MapColor.PALE_YELLOW , "sand" ); + put(MapColor.WHITE_GRAY , "wool" ); + put(MapColor.BRIGHT_RED , "tnt" ); + put(MapColor.PALE_PURPLE , "ice" ); + put(MapColor.IRON_GRAY , "iron" ); + put(MapColor.DARK_GREEN , "foliage" ); + put(MapColor.WHITE , "snow" ); + put(MapColor.LIGHT_BLUE_GRAY , "clay" ); + put(MapColor.DIRT_BROWN , "dirt" ); + put(MapColor.STONE_GRAY , "stone" ); + put(MapColor.WATER_BLUE , "water" ); + put(MapColor.OAK_TAN , "wood" ); + put(MapColor.OFF_WHITE , "quartz" ); + put(MapColor.ORANGE , "adobe" ); + put(MapColor.MAGENTA , "magenta" ); + put(MapColor.LIGHT_BLUE, "light_blue"); + put(MapColor.YELLOW , "yellow" ); + put(MapColor.LIME , "lime" ); + put(MapColor.PINK , "pink" ); + put(MapColor.GRAY , "gray" ); + put(MapColor.LIGHT_GRAY, "light_gray"); + put(MapColor.CYAN , "cyan" ); + put(MapColor.PURPLE , "purple" ); + put(MapColor.BLUE , "blue" ); + put(MapColor.BROWN , "brown" ); + put(MapColor.GREEN , "green" ); + put(MapColor.RED , "red" ); + put(MapColor.BLACK , "black" ); + put(MapColor.GOLD , "gold" ); + put(MapColor.DIAMOND_BLUE , "diamond" ); + put(MapColor.LAPIS_BLUE , "lapis" ); + put(MapColor.EMERALD_GREEN , "emerald" ); + put(MapColor.SPRUCE_BROWN , "obsidian" ); + put(MapColor.DARK_RED , "netherrack"); //TODO fix these + put(MapColor.TERRACOTTA_WHITE , "white_terracotta" ); + put(MapColor.TERRACOTTA_ORANGE , "orange_terracotta" ); + put(MapColor.TERRACOTTA_MAGENTA , "magenta_terracotta" ); + put(MapColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ); + put(MapColor.TERRACOTTA_YELLOW , "yellow_terracotta" ); + put(MapColor.TERRACOTTA_LIME , "lime_terracotta" ); + put(MapColor.TERRACOTTA_PINK , "pink_terracotta" ); + put(MapColor.TERRACOTTA_GRAY , "gray_terracotta" ); + put(MapColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ); + put(MapColor.TERRACOTTA_CYAN , "cyan_terracotta" ); + put(MapColor.TERRACOTTA_PURPLE , "purple_terracotta" ); + put(MapColor.TERRACOTTA_BLUE , "blue_terracotta" ); + put(MapColor.TERRACOTTA_BROWN , "brown_terracotta" ); + put(MapColor.TERRACOTTA_GREEN , "green_terracotta" ); + put(MapColor.TERRACOTTA_RED , "red_terracotta" ); + put(MapColor.TERRACOTTA_BLACK , "black_terracotta" ); + put(MapColor.DULL_RED , "crimson_nylium" ); + put(MapColor.DULL_PINK , "crimson_stem" ); + put(MapColor.DARK_CRIMSON , "crimson_hyphae" ); + put(MapColor.TEAL , "warped_nylium" ); + put(MapColor.DARK_AQUA , "warped_stem" ); + put(MapColor.DARK_DULL_PINK , "warped_hyphae" ); + put(MapColor.BRIGHT_TEAL , "warped_wart" ); }}; public static final Map materialName = new HashMap() {{ @@ -132,20 +152,20 @@ public class BlockInfo put(Material.PLANT , "plant" ); put(Material.UNDERWATER_PLANT, "water_plant" ); put(Material.REPLACEABLE_PLANT, "vegetation" ); - put(Material.REPLACEABLE_UNDERWATER_PLANT , "sea_grass" ); + put(Material.REPLACEABLE_UNDERWATER_PLANT, "sea_grass" ); put(Material.WATER , "water" ); put(Material.BUBBLE_COLUMN , "bubble_column"); put(Material.LAVA , "lava" ); - put(Material.SNOW_LAYER , "snow_layer" ); + put(Material.SNOW_LAYER , "snow_layer" ); put(Material.FIRE , "fire" ); - put(Material.SUPPORTED , "decoration" ); + put(Material.DECORATION , "decoration" ); put(Material.COBWEB , "cobweb" ); put(Material.REDSTONE_LAMP , "redstone_lamp"); - put(Material.ORGANIC_PRODUCT , "clay" ); - put(Material.SOIL , "dirt" ); - put(Material.SOLID_ORGANIC , "grass" ); - put(Material.DENSE_ICE , "packed_ice" ); - put(Material.AGGREGATE , "sand" ); + put(Material.ORGANIC_PRODUCT, "clay" ); + put(Material.SOIL , "dirt" ); + put(Material.SOLID_ORGANIC , "grass" ); + put(Material.DENSE_ICE , "packed_ice" ); + put(Material.AGGREGATE , "sand" ); put(Material.SPONGE , "sponge" ); put(Material.SHULKER_BOX , "shulker" ); put(Material.WOOD , "wood" ); @@ -161,13 +181,14 @@ public class BlockInfo put(Material.STONE , "stone" ); put(Material.METAL , "metal" ); put(Material.SNOW_BLOCK , "snow" ); - put(Material.REPAIR_STATION , "anvil" ); + put(Material.REPAIR_STATION , "anvil" ); put(Material.BARRIER , "barrier" ); put(Material.PISTON , "piston" ); - put(Material.UNUSED_PLANT , "coral" ); - put(Material.GOURD , "gourd" ); + put(Material.MOSS_BLOCK , "moss" ); + put(Material.GOURD , "gourd" ); put(Material.EGG , "dragon_egg" ); put(Material.CAKE , "cake" ); + put(Material.AMETHYST , "amethyst" ); }}; public static List blockInfo(BlockPos pos, ServerWorld world) @@ -185,7 +206,7 @@ public class BlockInfo lst.add(Messenger.s("=====================================")); lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):",Registry.BLOCK.getId(block),metastring, Registry.BLOCK.getRawId(block), metastring ))); lst.add(Messenger.s(String.format(" - Material: %s", materialName.get(material)))); - lst.add(Messenger.s(String.format(" - Map colour: %s", mapColourName.get(state.getTopMaterialColor(world, pos))))); + lst.add(Messenger.s(String.format(" - Map colour: %s", mapColourName.get(state.getMapColor(world, pos))))); lst.add(Messenger.s(String.format(" - Sound type: %s", soundName.get(block.getSoundGroup(state))))); lst.add(Messenger.s("")); lst.add(Messenger.s(String.format(" - Full block: %s", state.isFullCube(world, pos)))); // isFullCube() ))); @@ -231,7 +252,7 @@ public class BlockInfo for (int i=0; i<1000; i++) { - Vec3d vec = TargetFinder.findTarget(creature, 10, 7); + Vec3d vec = NoPenaltyTargeting.find(creature, 10, 7); // TargetFinder.findTarget(creature, 10, 7); if (vec == null) { continue; @@ -251,7 +272,7 @@ public class BlockInfo } total_ticks += 3*i; } - creature.remove(); + creature.discard(); // discarded // remove(Entity.RemovalReason.field_26999); // 2nd option - DISCARDED long total_time = (total_ticks)/1000/20; return Messenger.s(String.format(" - Wander chance above: %.1f%%\n - Average standby above: %s", (100.0F*success)/1000, diff --git a/src/main/java/carpet/utils/CarpetProfiler.java b/src/main/java/carpet/utils/CarpetProfiler.java index fd973229..a8889799 100644 --- a/src/main/java/carpet/utils/CarpetProfiler.java +++ b/src/main/java/carpet/utils/CarpetProfiler.java @@ -82,7 +82,7 @@ public class CarpetProfiler { SECTION_STATS.put(section, 0L); } - for (RegistryKey level : source.getMinecraftServer().getWorldRegistryKeys()) + for (RegistryKey level : source.getServer().getWorldRegistryKeys()) { for (String section : SECTIONS) { diff --git a/src/main/java/carpet/utils/DistanceCalculator.java b/src/main/java/carpet/utils/DistanceCalculator.java index a6b5d616..f7b97bdc 100644 --- a/src/main/java/carpet/utils/DistanceCalculator.java +++ b/src/main/java/carpet/utils/DistanceCalculator.java @@ -24,8 +24,8 @@ public class DistanceCalculator double dy = MathHelper.abs((float)pos1.y-(float)pos2.y); double dz = MathHelper.abs((float)pos1.z-(float)pos2.z); double manhattan = dx+dy+dz; - double spherical = MathHelper.sqrt(dx*dx + dy*dy + dz*dz); - double cylindrical = MathHelper.sqrt(dx*dx + dz*dz); + double spherical = Math.sqrt(dx*dx + dy*dy + dz*dz); + double cylindrical = Math.sqrt(dx*dx + dz*dz); List res = new ArrayList<>(); res.add(Messenger.c("w Distance between ", Messenger.tp("c",pos1),"w and ", diff --git a/src/main/java/carpet/utils/FabricAPIHooks.java b/src/main/java/carpet/utils/FabricAPIHooks.java index b9c49bd5..5120fb70 100644 --- a/src/main/java/carpet/utils/FabricAPIHooks.java +++ b/src/main/java/carpet/utils/FabricAPIHooks.java @@ -18,10 +18,8 @@ public class FabricAPIHooks { public static void initialize() { if (WORLD_RENDER_EVENTS) { WorldRenderEvents.BEFORE_DEBUG_RENDER.register(context -> { - if (CarpetClient.shapes != null) { - RenderSystem.pushMatrix(); - CarpetClient.shapes.render(context.camera(), context.tickDelta()); - RenderSystem.popMatrix(); + if (false) {//(CarpetClient.shapes != null) { // likely won't need it. + CarpetClient.shapes.render(context.matrixStack(), context.camera(), context.tickDelta()); } }); } diff --git a/src/main/java/carpet/utils/Messenger.java b/src/main/java/carpet/utils/Messenger.java index 68270e10..e5a6c7f2 100644 --- a/src/main/java/carpet/utils/Messenger.java +++ b/src/main/java/carpet/utils/Messenger.java @@ -253,7 +253,7 @@ public class Messenger public static void m(ServerCommandSource source, Object ... fields) { if (source != null) - source.sendFeedback(Messenger.c(fields),source.getMinecraftServer() != null && source.getMinecraftServer().getWorld(World.OVERWORLD) != null); //OW + source.sendFeedback(Messenger.c(fields),source.getServer() != null && source.getServer().getWorld(World.OVERWORLD) != null); //OW } public static void m(PlayerEntity player, Object ... fields) { diff --git a/src/main/java/carpet/utils/MobAI.java b/src/main/java/carpet/utils/MobAI.java index c332755c..eb5b58f6 100644 --- a/src/main/java/carpet/utils/MobAI.java +++ b/src/main/java/carpet/utils/MobAI.java @@ -39,7 +39,7 @@ public class MobAI return currentTrackers.contains(type); } - public static void clearTracking(EntityType etype) + public static void clearTracking(EntityType etype) { aiTrackers.remove(etype); for(ServerWorld world : CarpetServer.minecraft_server.getWorlds() ) @@ -114,7 +114,7 @@ public class MobAI e.setVelocity(vec3d.x, jumpStrength, vec3d.z); if (e.isSprinting()) { - float u = e.yaw * 0.017453292F; + float u = e.getYaw() * 0.017453292F; // yaw e.setVelocity(e.getVelocity().add((-MathHelper.sin(g) * 0.2F), 0.0D, (MathHelper.cos(u) * 0.2F))); } e.velocityDirty = true; diff --git a/src/main/java/carpet/utils/PerimeterDiagnostics.java b/src/main/java/carpet/utils/PerimeterDiagnostics.java index 8fab4bd8..257068fd 100644 --- a/src/main/java/carpet/utils/PerimeterDiagnostics.java +++ b/src/main/java/carpet/utils/PerimeterDiagnostics.java @@ -159,10 +159,10 @@ public class PerimeterDiagnostics private boolean check_entity_spawn(BlockPos pos) { - if (sle == null || !worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).contains(sle)) + if (sle == null || !worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).getEntries().contains(sle)) { sle = null; - for (SpawnSettings.SpawnEntry sle: worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos)) + for (SpawnSettings.SpawnEntry sle: worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).getEntries()) { if (el.getType() == sle.type) { @@ -170,7 +170,7 @@ public class PerimeterDiagnostics break; } } - if (sle == null || !worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).contains(sle)) + if (sle == null || !worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).getEntries().contains(sle)) { return false; } diff --git a/src/main/java/carpet/utils/SpawnReporter.java b/src/main/java/carpet/utils/SpawnReporter.java index c11c2c39..0b71532d 100644 --- a/src/main/java/carpet/utils/SpawnReporter.java +++ b/src/main/java/carpet/utils/SpawnReporter.java @@ -1,7 +1,6 @@ package carpet.utils; -import carpet.mixins.WeightedPickerEntryMixin; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; @@ -20,6 +19,7 @@ import net.minecraft.tag.BlockTags; import net.minecraft.text.BaseText; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.DyeColor; +import net.minecraft.util.TypeFilter; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.registry.RegistryKey; @@ -276,7 +276,7 @@ public class SpawnReporter { List lst = new ArrayList<>(); lst.add( Messenger.s(String.format("Loaded entities for %s class:", get_type_string(cat)))); - for (Entity entity : ((ServerWorld)worldIn).getEntitiesByType(null, (e) -> e.getType().getSpawnGroup()==cat)) + for (Entity entity : ((ServerWorld)worldIn).getEntitiesByType(TypeFilter.instanceOf(Entity.class), (e) -> e.getType().getSpawnGroup()==cat)) { boolean persistent = entity instanceof MobEntity && ( ((MobEntity) entity).isPersistent() || ((MobEntity) entity).cannotDespawn()); if (!all && persistent) @@ -399,28 +399,28 @@ public class SpawnReporter { if (entity.hasVehicle()) { - entity.getVehicle().remove(); + entity.getVehicle().discard(); } if (entity.hasPassengers()) { for (Entity e: entity.getPassengerList()) { - e.remove(); + e.discard(); } } if (entity instanceof OcelotEntity) { for (Entity e: entity.getEntityWorld().getOtherEntities(entity, entity.getBoundingBox())) { - e.remove(); + e.discard(); } } - entity.remove(); + entity.discard(); } // yeeted from SpawnHelper - temporary fix private static List method_29950(ServerWorld serverWorld, StructureAccessor structureAccessor, ChunkGenerator chunkGenerator, SpawnGroup spawnGroup, BlockPos blockPos, /*@Nullable*/ Biome biome) { - return spawnGroup == SpawnGroup.MONSTER && serverWorld.getBlockState(blockPos.down()).getBlock() == Blocks.NETHER_BRICKS && structureAccessor.getStructureAt(blockPos, false, StructureFeature.FORTRESS).hasChildren() ? StructureFeature.FORTRESS.getMonsterSpawns() : chunkGenerator.getEntitySpawnList(biome != null ? biome : serverWorld.getBiome(blockPos), structureAccessor, spawnGroup, blockPos); + return spawnGroup == SpawnGroup.MONSTER && serverWorld.getBlockState(blockPos.down()).getBlock() == Blocks.NETHER_BRICKS && structureAccessor.getStructureAt(blockPos, false, StructureFeature.FORTRESS).hasChildren() ? StructureFeature.FORTRESS.getMonsterSpawns().getEntries() : chunkGenerator.getEntitySpawnList(biome != null ? biome : serverWorld.getBiome(blockPos), structureAccessor, spawnGroup, blockPos).getEntries(); } public static List report(BlockPos pos, ServerWorld worldIn) @@ -520,7 +520,7 @@ public class SpawnReporter String creature_name = mob.getType().getName().getString(); String pack_size = String.format("%d", mob.getLimitPerChunk());//String.format("%d-%d", animal.minGroupCount, animal.maxGroupCount); - int weight = ((WeightedPickerEntryMixin) spawnEntry).getWeight(); + int weight = spawnEntry.getWeight().getValue();// ((WeightedPickerEntryMixin) spawnEntry).getWeight(); if (canspawn) { String c = (fits_true && will_spawn>0)?"e":"gi"; diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index ca1c33af..75c00df8 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -3,7 +3,7 @@ package carpet.utils; import carpet.CarpetSettings; import carpet.helpers.HopperCounter; import net.minecraft.block.Material; -import net.minecraft.block.MaterialColor; +import net.minecraft.block.MapColor; import net.minecraft.block.BlockState; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.entity.player.PlayerEntity; @@ -28,37 +28,36 @@ public class WoolTool * A map of the {@link MaterialColor} to the {@link DyeColor} which is used in {@link WoolTool#getWoolColorAtPosition} * to get the colour of wool at a position. */ - private static final HashMap Material2Dye = new HashMap<>(); + private static final HashMap Material2Dye = new HashMap<>(); /** * A map of all the wool colours to their respective colours in the {@link Messenger#m} format so the name of the counter * gets printed in colour. */ - public static final HashMap Material2DyeName = new HashMap(){{ - put(MaterialColor.WHITE, "w "); - put(MaterialColor.ORANGE, "#F9801D "); - put(MaterialColor.MAGENTA, "m "); - put(MaterialColor.LIGHT_BLUE, "t "); - put(MaterialColor.YELLOW, "y "); - put(MaterialColor.LAPIS, "l "); - put(MaterialColor.PINK, "#FFACCB "); - put(MaterialColor.GRAY, "f "); - put(MaterialColor.LIGHT_GRAY, "g "); - put(MaterialColor.CYAN, "c "); - put(MaterialColor.PURPLE, "p "); - put(MaterialColor.BLUE, "v "); - put(MaterialColor.BROWN, "#835432 "); - put(MaterialColor.GREEN, "e "); - put(MaterialColor.RED, "r "); - put(MaterialColor.BLACK, "k "); + public static final HashMap Material2DyeName = new HashMap(){{ + put(MapColor.WHITE, "w "); + put(MapColor.ORANGE, "#F9801D "); + put(MapColor.MAGENTA, "m "); + put(MapColor.LIGHT_BLUE, "t "); + put(MapColor.YELLOW, "y "); + put(MapColor.LIME, "l "); + put(MapColor.PINK, "#FFACCB "); + put(MapColor.GRAY, "f "); + put(MapColor.LIGHT_GRAY, "g "); + put(MapColor.CYAN, "c "); + put(MapColor.PURPLE, "p "); + put(MapColor.BLUE, "v "); + put(MapColor.BROWN, "#835432 "); + put(MapColor.GREEN, "e "); + put(MapColor.RED, "r "); + put(MapColor.BLACK, "k "); }}; - static { for (DyeColor color: DyeColor.values()) { - Material2Dye.put(color.getMaterialColor(),color); + Material2Dye.put(color.getMapColor(),color); } } @@ -141,6 +140,6 @@ public class WoolTool BlockState state = worldIn.getBlockState(pos); if (state.getMaterial() != Material.WOOL || !state.isSolidBlock(worldIn, pos)) //isSimpleFullBlock return null; - return Material2Dye.get(state.getTopMaterialColor(worldIn, pos)); + return Material2Dye.get(state.getMapColor(worldIn, pos)); } } diff --git a/src/main/resources/assets/carpet/scripts/ai_tracker.sc b/src/main/resources/assets/carpet/scripts/ai_tracker.sc index f0ef60ec..b9ad7206 100644 --- a/src/main/resources/assets/carpet/scripts/ai_tracker.sc +++ b/src/main/resources/assets/carpet/scripts/ai_tracker.sc @@ -300,7 +300,8 @@ global_functions = { 'health' -> { '*' -> [ _(arg) -> _(e) -> ( - [[], [], [['health', 'health:', e~'health']]] + health = e~'health'; + [[], [], if (health != null, [['health', 'health:', e~'health']], [])] ), , null @@ -325,10 +326,7 @@ global_functions = { _(arg) -> _(orb) -> ( tag = query(orb, 'nbt'); ct = tag:'Count'; - [[], [], if (ct > 1, [ - //['value', 'size:', tag:'Value'], - ['stack', ct] - ],[]) ] + [[], [], if (ct > 1, [['stack', ct]],[]) ] ), , null diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener index e9dad565..625c69ec 100644 --- a/src/main/resources/carpet.accesswidener +++ b/src/main/resources/carpet.accesswidener @@ -2,4 +2,5 @@ accessWidener v1 named accessible class net/minecraft/server/world/ThreadedAnvilChunkStorage$TicketManager accessible class net/minecraft/server/world/ServerLightingProvider$Stage -accessible class net/minecraft/recipe/Ingredient$Entry \ No newline at end of file +accessible class net/minecraft/recipe/Ingredient$Entry +accessible class net/minecraft/world/chunk/light/BlockLightStorage$Data \ No newline at end of file diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index bfdfbd91..e448a7e0 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -2,7 +2,7 @@ "required": true, "refmap": "fabric-carpet-refmap.json", "package": "carpet.mixins", - "compatibilityLevel": "JAVA_8", + "compatibilityLevel": "JAVA_16", "mixins": [ "BarrierBlock_updateSuppressionBlockMixin", @@ -12,6 +12,7 @@ "ServerPlayNetworkHandlerMixin", "CustomPayloadC2SPacketMixin", + "PerfCommand_permissionMixin", "FillCommandMixin", "CloneCommandMixin", "SetBlockCommandMixin", @@ -33,12 +34,14 @@ "MinecraftServer_tickspeedMixin", "World_tickMixin", "ServerWorld_tickMixin", + "WorldChunkBEList_tickMixin", "ServerChunkManager_tickMixin", "ThreadedAnvilChunkStorage_tickMixin", "ChunkTicketManager_tickMixin", "CommandFunctionManager_tickMixin", "ThreadedAnvilChunkStorage_scarpetChunkCreationMixin", + "SimpleEntityLookup_scarpetMixin", "ChunkHolder_scarpetChunkCreationMixin", "ServerLightingProvider_scarpetMixin", "LevelPropagator_resetChunkInterface", @@ -88,7 +91,10 @@ "ServerWorld_onePlayerSleepingMixin", "CoralBlockMixin", "CoralFeatureMixin", + "BuddingAmethystBlock_movableAmethystMixin", "FluidBlock_renewableBlackstoneMixin", + "FluidBlock_renewableDeepslateMixin", + "LavaFluid_renewableDeepslateMixin", "StructureFeatureMixin", "World_scarpetPlopMixin", "ChunkRegion_scarpetPlopMixin", @@ -129,6 +135,8 @@ "ContainerMixin", "ClientConnectionMixin", "CauldronBlock_stackableSBoxesMixin", + "AbstractCauldronBlock_stackableSBoxesMixin", + "Slot_stackableSBoxesMixin", "ItemEntityMixin", "TntBlockMixin", "ExplosionMixin", @@ -183,6 +191,7 @@ "StatType_scarpetMixin", "PointOfInterest_scarpetMixin", "ServerWorld_scarpetMixin", + "ServerEntityManager_scarpetMixin", "HungerManagerMixin_scarpetEventsMixin", "ReloadCommand_reloadAppsMixin", "CrashReport_addScarpetAppsMixin", @@ -193,8 +202,8 @@ "StatePredicate_scarpetMixin", "TagPredicate_scarpetMixin", "HorseBaseEntity_scarpetMixin", - "PillagerEntity_scarpetMixin", + "BlockEntity_movableBEMixin", "PistonBlock_movableTEMixin", "PistonBlockEntity_movableTEMixin", "World_movableTEMixin", @@ -206,8 +215,10 @@ "WallStandingBlockItem_creativeNoClipMixin", "ShulkerBoxBlockEntity_creativeNoClipMixin", "EndGatewayBlockEntity_creativeNoClipMixin", - "LivingEntity_creativeFlyMixin" + "LivingEntity_creativeFlyMixin", + "VeryBiasedToBottomHeightProvider_cleanLogsMixin", + "TrapezoidHeightProvider_cleanLogsMixin" ], "client": [ "RenderTickCounter_tickSpeedMixin", @@ -217,6 +228,7 @@ "InGameHudMixin", "PlayerListHudMixin", "PistonBlockEntityRenderer_movableTEMixin", + "StructureBlockBlockEntityRenderer_mixin", "ClientPlayerEntity_clientCommandMixin", "WorldRenderer_fogOffMixin", "WorldRenderer_creativeNoClipMixin", diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index ecf360d9..e5329f06 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -32,7 +32,8 @@ "accessWidener" : "carpet.accesswidener", "depends": { - "minecraft": "1.16.x", - "fabricloader": ">=0.7.1" + "minecraft": "1.17.x", + "fabricloader": ">=0.11.3", + "java": ">=16" } }