Skip to content

Commit

Permalink
Update packet tweaker, cleanup / simplify custom model data support, …
Browse files Browse the repository at this point in the history
…as it won't be needed in many cases
  • Loading branch information
Patbox committed Oct 13, 2024
1 parent f932352 commit 629f825
Show file tree
Hide file tree
Showing 36 changed files with 158 additions and 345 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ mod_version = 0.10.0-alpha

minecraft_version_supported = ">=1.21.2-"

packet_tweaker_version = 0.5.5+1.21
packet_tweaker_version = 0.6.0-pre.1+1.21.2-pre3

is_stable = true
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public static void registerEmpty(BlockModelType type) {

Registry.register(Registries.ITEM, id, new PolymerBlockItem(block, new Item.Settings()
.registryKey(RegistryKey.of(RegistryKeys.ITEM, id))
.modelId(block.getPolymerBlockState(block.getDefaultState(), PacketContext.of()).getBlock().getRegistryEntry().registryKey().getValue())
.modelId(block.getPolymerBlockState(block.getDefaultState(), PacketContext.create()).getBlock().getRegistryEntry().registryKey().getValue())
.component(DataComponentTypes.ENCHANTMENT_GLINT_OVERRIDE, true),
block.getPolymerBlockState(block.getDefaultState(), PacketContext.of()).getBlock().asItem()));
block.getPolymerBlockState(block.getDefaultState(), PacketContext.create()).getBlock().asItem()));
}
}
15 changes: 8 additions & 7 deletions polymer-blocks/src/testmod/java/eu/pb4/blocktest/TestItem.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
package eu.pb4.blocktest;

import eu.pb4.polymer.core.api.item.PolymerItem;
import eu.pb4.polymer.resourcepack.api.PolymerModelData;
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
import net.minecraft.block.Block;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
import xyz.nucleoid.packettweaker.PacketContext;

public class TestItem extends BlockItem implements PolymerItem {

private final PolymerModelData polymerModel;

private final Identifier polymerModel;
public TestItem(Settings settings, Block block, String modelId) {
super(block, settings);
this.polymerModel = PolymerResourcePackUtils.requestModel(Items.BARRIER, Identifier.of("blocktest", modelId));
this.polymerModel = PolymerResourcePackUtils.getBridgedModelId(Identifier.of("blocktest", modelId));

}

@Override
public Item getPolymerItem(ItemStack itemStack, PacketContext player) {
return this.polymerModel.item();
return Items.BARRIER;
}

@Override
public @Nullable Identifier getPolymerItemModel(ItemStack stack, PacketContext context) {
return this.polymerModel;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.nio.file.Path;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier;

public final class PolymerCommonUtils {
private static final ThreadLocal<LogicOverride> FORCE_NETWORKING = ThreadLocal.withInitial(() -> LogicOverride.DEFAULT);
Expand Down Expand Up @@ -129,10 +130,44 @@ public static void executeWithNetworkingLogic(PacketListener listener, Runnable
public static void executeWithoutNetworkingLogic(Runnable runnable) {
var val = FORCE_NETWORKING.get();
FORCE_NETWORKING.set(LogicOverride.FALSE);
PacketContext.runWithContext(null, runnable);
FORCE_NETWORKING.set(val);
try {
PacketContext.runWithContext(null, runnable);
} finally {
FORCE_NETWORKING.set(val);
}
}

public static <T> T executeWithNetworkingLogic(Supplier<T> supplier) {
var val = FORCE_NETWORKING.get();
FORCE_NETWORKING.set(LogicOverride.TRUE);
try {
return supplier.get();
} finally {
FORCE_NETWORKING.set(val);
}
}

public static <T> T executeWithNetworkingLogic(PacketListener listener, Supplier<T> supplier) {
var val = FORCE_NETWORKING.get();
FORCE_NETWORKING.set(LogicOverride.TRUE);
try {
return PacketContext.supplyWithContext(listener, supplier);
} finally {
FORCE_NETWORKING.set(val);
}
}

public static <T> T executeWithoutNetworkingLogic(Supplier<T> supplier) {
var val = FORCE_NETWORKING.get();
FORCE_NETWORKING.set(LogicOverride.FALSE);
try {
return PacketContext.supplyWithContext(null, supplier);
} finally {
FORCE_NETWORKING.set(val);
}
}


public static World getFakeWorld() {
return FakeWorld.INSTANCE;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import java.util.function.BiFunction;

/**
* Do not use, unless you really need it and you are 100% sure about what you need!
* Do not use, unless you really need it, and you are 100% sure about what you need!
*
* Allows changing how blocks display for certain players.
* You can replace any block that way, including vanilla ones.
Expand Down Expand Up @@ -62,7 +62,7 @@ static BlockMapper getFrom(@Nullable ServerPlayerEntity player) {

static void resetMapper(@Nullable ServerPlayerEntity player) {
if (player != null) {
PolymerPlayNetworkHandlerExtension.of(player).polymer$setBlockMapper(getDefault(PacketContext.of(player)));
PolymerPlayNetworkHandlerExtension.of(player).polymer$setBlockMapper(getDefault(PacketContext.create(player)));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public interface PolymerBlock extends PolymerSyncedObject<Block> {
* in case of using in packets, as it's reused for other positions!
* @param contexts Context packet is sent to. Should always contain a player
*/
default void onPolymerBlockSend(BlockState blockState, BlockPos.Mutable pos, PacketContext contexts) { }
default void onPolymerBlockSend(BlockState blockState, BlockPos.Mutable pos, PacketContext.NotNullWithPlayer contexts) { }

/**
* You can override this method in case of issues with light updates of this block. In most cases it's not needed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ default Packet<?> getPolymerHeadPacket(BlockState state, BlockPos pos, PacketCon
}

@Override
default void onPolymerBlockSend(BlockState blockState, BlockPos.Mutable pos, PacketContext context) {
default void onPolymerBlockSend(BlockState blockState, BlockPos.Mutable pos, PacketContext.NotNullWithPlayer context) {
context.getPlayer().networkHandler.sendPacket(this.getPolymerHeadPacket(blockState, pos.toImmutable(), context));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -405,17 +405,17 @@ public static ItemStack createItemStack(ItemStack itemStack, TooltipType tooltip


try {
PolymerCommonUtils.executeWithoutNetworkingLogic(() -> {
out.set(DataComponentTypes.CUSTOM_DATA, PolymerCommonUtils.executeWithoutNetworkingLogic(() -> {
var comp = NbtComponent.of(
(NbtCompound) (storeCount ? POLYMER_STACK_CODEC : POLYMER_STACK_UNCOUNTED_CODEC).encoder()
.encodeStart(RegistryOps.of(NbtOps.INSTANCE, lookup), itemStack).getOrThrow()
);
if (storeCount) {
out.set(DataComponentTypes.CUSTOM_DATA, comp.with(RegistryOps.of(NbtOps.INSTANCE, lookup), POLYMER_STACK_HAS_COUNT_CODEC, true).getOrThrow());
return comp.with(RegistryOps.of(NbtOps.INSTANCE, lookup), POLYMER_STACK_HAS_COUNT_CODEC, true).getOrThrow();
} else {
out.set(DataComponentTypes.CUSTOM_DATA, comp);
return comp;
}
});
}));
} catch (Throwable e) {
out.set(DataComponentTypes.CUSTOM_DATA, NbtComponent.DEFAULT.with(RegistryOps.of(NbtOps.INSTANCE, lookup), POLYMER_STACK_ID_CODEC, Registries.ITEM.getId(itemStack.getItem())).getOrThrow());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ private static int creativeTab(CommandContext<ServerCommandSource> context) {

private static int displayClientItem(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
var player = context.getSource().getPlayerOrThrow();
var stack = PolymerItemUtils.getPolymerItemStack(player.getMainHandStack(), PacketContext.of(player)).copy();
var stack = PolymerItemUtils.getPolymerItemStack(player.getMainHandStack(), PacketContext.create(player)).copy();
stack.remove(DataComponentTypes.CUSTOM_DATA);

context.getSource().sendFeedback(() -> (new NbtTextFormatter("")).apply(stack.toNbtAllowEmpty(context.getSource().getRegistryManager())), false);
Expand All @@ -489,7 +489,7 @@ private static int displayClientItem(CommandContext<ServerCommandSource> context
private static int getClientItem(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
var player = context.getSource().getPlayerOrThrow();

var stack = PolymerItemUtils.getPolymerItemStack(player.getMainHandStack(), PacketContext.of(player));
var stack = PolymerItemUtils.getPolymerItemStack(player.getMainHandStack(), PacketContext.create(player));
stack.remove(DataComponentTypes.CUSTOM_DATA);
player.giveItemStack(stack);
context.getSource().sendFeedback(() -> Text.literal("Given client representation to player"), true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public static ItemStack convertStack(ItemStack representation, ServerPlayerEntit
}

public static ItemStack convertStack(ItemStack representation, ServerPlayerEntity player, TooltipType context) {
return ServerTranslationUtils.parseFor(player.networkHandler, PolyMcUtils.toVanilla(PolymerItemUtils.getPolymerItemStack(representation, context, PacketContext.of(player)), player));
return ServerTranslationUtils.parseFor(player.networkHandler, PolyMcUtils.toVanilla(PolymerItemUtils.getPolymerItemStack(representation, context, PacketContext.create(player)), player));
}

public static void pickBlock(ServerPlayerEntity player, BlockPos pos, boolean withNbt) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public static BlockState getRealBlockState(int rawPolymerId) {
if (PolymerClientDecoded.checkDecode(state.blockState().getBlock())) {
return state.blockState();
} else {
return PolymerBlockUtils.getPolymerBlockState(state.blockState(), PacketContext.of());
return PolymerBlockUtils.getPolymerBlockState(state.blockState(), PacketContext.create());
}
}

Expand All @@ -188,11 +188,7 @@ private static void setDecoders() {

public static Object decodeRegistry(IndexedIterable<?> instance, int i) {
if (serverHasPolymer) {
var mut = new MutableObject<>();
PolymerCommonUtils.executeWithNetworkingLogic(() -> {
mut.setValue(instance.getOrThrow(i));
});
return mut.getValue();
return PolymerCommonUtils.executeWithNetworkingLogic(() -> instance.getOrThrow(i));
}

return instance.getOrThrow(i);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static void sendFromPacket(Packet<?> packet, ServerPlayNetworkHandler han
PolymerBlockPosStorage wci = (PolymerBlockPosStorage) wc;
if (wc != null && wci.polymer$hasAny()) {
PolymerServerProtocol.sendSectionUpdate(handler, wc);
var ctx = PacketContext.of(handler);
var ctx = PacketContext.create(handler);
var iterator = wci.polymer$iterator();
while (iterator.hasNext()) {
var pos = iterator.next();
Expand All @@ -57,7 +57,7 @@ private record SendSingleBlockInfo(ServerPlayNetworkHandler handler, BlockPos po
public void run() {
PolymerServerProtocol.sendBlockUpdate(handler, pos, blockState);
if (blockState.getBlock() instanceof PolymerBlock polymerBlock) {
polymerBlock.onPolymerBlockSend(blockState, pos.mutableCopy(), PacketContext.of(handler));
polymerBlock.onPolymerBlockSend(blockState, pos.mutableCopy(), PacketContext.create(handler));
}
}
}
Expand All @@ -69,7 +69,7 @@ public void run() {
PolymerServerProtocol.sendMultiBlockUpdate(handler, chunkPos, localPos, blockStates);

var blockPos = new BlockPos.Mutable();
var ctx = PacketContext.of(handler);
var ctx = PacketContext.create(handler);


for (int i = 0; i < localPos.length; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public static void sendExtra(ServerCommonNetworkHandler handler, Packet<?> packe

public static boolean prevent(ServerCommonNetworkHandler handler, Packet<?> packet) {
if (handler.getClass() == ServerPlayNetworkHandler.class) {
var player = PacketContext.of(handler);
var player = PacketContext.create(handler);
if ((
packet instanceof StatusEffectPacketExtension packet2
&& ((packet2.polymer$getStatusEffect() instanceof PolymerStatusEffect pol && pol.getPolymerReplacement(player) == null))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ private static <T, A> void sendSync(ServerPlayNetworkHandler handler, CustomPayl

if (version != -1) {
var entries = new ArrayList<A>();
var ctx = PacketContext.of(handler);
var ctx = PacketContext.create(handler);
for (var entry : iterable) {
if (!bypassPolymerCheck || (entry instanceof PolymerSyncedObject<?> obj && obj.canSynchronizeToPolymerClient(ctx))) {
var val = writableFunction.serialize(entry, handler, version);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static PolymerItemGroupContentAddS2CPayload of(ItemGroup group, ServerPla
stacksMain = List.copyOf(contents.main());
stacksSearch = List.copyOf(contents.search());
} else {
var ctx = PacketContext.of(handler);
var ctx = PacketContext.create(handler);
stacksMain = new ArrayList<>();
stacksSearch = new ArrayList<>();
for (var item : contents.main()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.BlockView;
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;
Expand All @@ -20,8 +21,8 @@
public class AbstractBlockMixin {
@Inject(method = "getOutlineShape", at = @At("HEAD"), cancellable = true)
private void polymer$replaceOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context, CallbackInfoReturnable<VoxelShape> cir) {
if (this instanceof PolymerBlock block) {
var clientState = PolymerBlockUtils.getBlockStateSafely(block, state, PacketContext.of());
if (this instanceof PolymerBlock block && world instanceof World realWorld) {
var clientState = PolymerBlockUtils.getBlockStateSafely(block, state, PacketContext.create(realWorld.getRegistryManager()));
if (!(clientState.getBlock() instanceof PolymerBlock)) {
cir.setReturnValue(clientState.getOutlineShape(world, pos, context));
}
Expand All @@ -30,11 +31,11 @@ public class AbstractBlockMixin {

@Inject(method = "getCollisionShape", at = @At("HEAD"), cancellable = true)
private void polymer$replaceCollision(BlockState state, BlockView world, BlockPos pos, ShapeContext context, CallbackInfoReturnable<VoxelShape> cir) {
if (this instanceof PolymerBlock block) {
if (this instanceof PolymerBlock block && world instanceof World realWorld) {
var clientState = context instanceof EntityShapeContext entityShapeContext
&& entityShapeContext.getEntity() instanceof ServerPlayerEntity player
? PolymerBlockUtils.getBlockStateSafely(block, state, PacketContext.of(player))
: PolymerBlockUtils.getBlockStateSafely(block, state, PacketContext.of());
? PolymerBlockUtils.getBlockStateSafely(block, state, PacketContext.create(player))
: PolymerBlockUtils.getBlockStateSafely(block, state, PacketContext.create(realWorld.getRegistryManager()));
if (!(clientState.getBlock() instanceof PolymerBlock)) {
cir.setReturnValue(clientState.getCollisionShape(world, pos, context));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public abstract class BlockStateMixin implements BlockStateExtra {
}

if (this.asBlockState().getBlock() instanceof PolymerBlock polymerBlock) {
this.polymer$isLight = this.asBlockState().getLuminance() != polymerBlock.getPolymerBlockState(this.asBlockState(), PacketContext.of()).getLuminance();
this.polymer$isLight = this.asBlockState().getLuminance() != polymerBlock.getPolymerBlockState(this.asBlockState(), PacketContext.create()).getLuminance();
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ public class ChunkDataSenderMixin {
@WrapOperation(method = "sendChunkData", at = @At(value = "NEW", target = "(Lnet/minecraft/world/chunk/WorldChunk;Lnet/minecraft/world/chunk/light/LightingProvider;Ljava/util/BitSet;Ljava/util/BitSet;)Lnet/minecraft/network/packet/s2c/play/ChunkDataS2CPacket;"), require = 0)
private static ChunkDataS2CPacket addContext(WorldChunk chunk, LightingProvider lightProvider, @Nullable BitSet skyBits, @Nullable BitSet blockBits, Operation<ChunkDataS2CPacket> call,
@Local(argsOnly = true) ServerPlayNetworkHandler handler) {
var storage = new ChunkDataS2CPacket[1];
PolymerCommonUtils.executeWithNetworkingLogic(handler, () -> storage[0] = call.call(chunk, lightProvider, skyBits, blockBits));
return storage[0];
return PolymerCommonUtils.executeWithNetworkingLogic(handler, () -> call.call(chunk, lightProvider, skyBits, blockBits));
}

@WrapWithCondition(method = "unload", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;sendPacket(Lnet/minecraft/network/packet/Packet;)V"), require = 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private void polymer_packetReceivedInject(BlockPos pos, PlayerActionC2SPacket.Ac
this.polymer$currentBreakingProgress = 0;
var ogDelta = state.calcBlockBreakingDelta(this.player, this.world, pos);;
if (state.getBlock() instanceof PolymerBlock virtualBlock) {
state = PolymerBlockUtils.getBlockStateSafely(virtualBlock, state, PacketContext.of(this.player));
state = PolymerBlockUtils.getBlockStateSafely(virtualBlock, state, PacketContext.create(this.player));
}

float delta = state.calcBlockBreakingDelta(this.player, this.world, pos);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public ServerPlayNetworkHandlerMixin(MinecraftServer server, ClientConnection co
ItemStack itemStack = this.player.getStackInHand(packet.getHand());

if (itemStack.getItem() instanceof PolymerItem polymerItem) {
var data = PolymerItemUtils.getItemSafely(polymerItem, itemStack, PacketContext.of(this.player));
var data = PolymerItemUtils.getItemSafely(polymerItem, itemStack, PacketContext.create(this.player));
if (data.item() instanceof BlockItem || data.item() instanceof BucketItem) {
this.sendPacket(new ScreenHandlerSlotUpdateS2CPacket(this.player.playerScreenHandler.syncId, this.player.playerScreenHandler.nextRevision(), packet.getHand() == Hand.MAIN_HAND ? 36 + this.player.getInventory().selectedSlot : 45, itemStack));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public abstract class ServerPlayNetworkHandlerMixin implements PolymerPlayNetwor

@Inject(method = "<init>", at = @At("TAIL"))
private void polymer$setupInitial(MinecraftServer server, ClientConnection connection, ServerPlayerEntity player, ConnectedClientData clientData, CallbackInfo ci) {
this.polymer$blockMapper = BlockMapper.getDefault(PacketContext.of(player));
this.polymer$blockMapper = BlockMapper.getDefault(PacketContext.create(player));
var advTool = PolymerNetworking.getMetadata(connection, ClientMetadataKeys.ADVANCED_TOOLTIP, NbtByte.TYPE);

this.polymer$advancedTooltip = advTool != null && advTool.intValue() > 0;
Expand Down
Loading

0 comments on commit 629f825

Please sign in to comment.