Search in sources :

Example 26 with PacketRemapper

use of com.viaversion.viaversion.api.protocol.remapper.PacketRemapper in project ViaBackwards by ViaVersion.

the class ItemPackets1_11_1 method registerPackets.

@Override
protected void registerPackets() {
    registerSetSlot(ClientboundPackets1_9_3.SET_SLOT, Type.ITEM);
    registerWindowItems(ClientboundPackets1_9_3.WINDOW_ITEMS, Type.ITEM_ARRAY);
    registerEntityEquipment(ClientboundPackets1_9_3.ENTITY_EQUIPMENT, Type.ITEM);
    // Plugin message Packet -> Trading
    protocol.registerClientbound(ClientboundPackets1_9_3.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Channel
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    if (wrapper.get(Type.STRING, 0).equalsIgnoreCase("MC|TrList")) {
                        // Passthrough Window ID
                        wrapper.passthrough(Type.INT);
                        int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
                        for (int i = 0; i < size; i++) {
                            // Input Item
                            wrapper.write(Type.ITEM, handleItemToClient(wrapper.read(Type.ITEM)));
                            // Output Item
                            wrapper.write(Type.ITEM, handleItemToClient(wrapper.read(Type.ITEM)));
                            // Has second item
                            boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                            if (secondItem) {
                                // Second Item
                                wrapper.write(Type.ITEM, handleItemToClient(wrapper.read(Type.ITEM)));
                            }
                            // Trade disabled
                            wrapper.passthrough(Type.BOOLEAN);
                            // Number of tools uses
                            wrapper.passthrough(Type.INT);
                            // Maximum number of trade uses
                            wrapper.passthrough(Type.INT);
                        }
                    }
                }
            });
        }
    });
    registerClickWindow(ServerboundPackets1_9_3.CLICK_WINDOW, Type.ITEM);
    registerCreativeInvAction(ServerboundPackets1_9_3.CREATIVE_INVENTORY_ACTION, Type.ITEM);
    // Handle item metadata
    protocol.getEntityRewriter().filter().handler((event, meta) -> {
        if (meta.metaType().type().equals(Type.ITEM)) {
            // Is Item
            meta.setValue(handleItemToClient((Item) meta.getValue()));
        }
    });
}
Also used : Item(com.viaversion.viaversion.api.minecraft.item.Item) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)

Example 27 with PacketRemapper

use of com.viaversion.viaversion.api.protocol.remapper.PacketRemapper in project ViaBackwards by ViaVersion.

the class Protocol1_11_1To1_12 method registerPackets.

@Override
protected void registerPackets() {
    blockItemPackets.register();
    entityPackets.register();
    new SoundPackets1_12(this).register();
    new ChatPackets1_12(this).register();
    registerClientbound(ClientboundPackets1_12.TITLE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> {
                int action = wrapper.passthrough(Type.VAR_INT);
                if (action >= 0 && action <= 2) {
                    JsonElement component = wrapper.read(Type.COMPONENT);
                    wrapper.write(Type.COMPONENT, Protocol1_9To1_8.fixJson(component.toString()));
                }
            });
        }
    });
    cancelClientbound(ClientboundPackets1_12.ADVANCEMENTS);
    cancelClientbound(ClientboundPackets1_12.UNLOCK_RECIPES);
    cancelClientbound(ClientboundPackets1_12.SELECT_ADVANCEMENTS_TAB);
}
Also used : Entity1_12Types(com.viaversion.viaversion.api.minecraft.entities.Entity1_12Types) ServerboundPackets1_9_3(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.ServerboundPackets1_9_3) ServerboundPackets1_12(com.viaversion.viaversion.protocols.protocol1_12to1_11_1.ServerboundPackets1_12) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) ClientboundPackets1_12(com.viaversion.viaversion.protocols.protocol1_12to1_11_1.ClientboundPackets1_12) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) EntityPackets1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.packets.EntityPackets1_12) BackwardsProtocol(com.viaversion.viabackwards.api.BackwardsProtocol) ChatPackets1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.packets.ChatPackets1_12) BlockItemPackets1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.packets.BlockItemPackets1_12) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Type(com.viaversion.viaversion.api.type.Type) Protocol1_9To1_8(com.viaversion.viaversion.protocols.protocol1_9to1_8.Protocol1_9To1_8) BackwardsMappings(com.viaversion.viabackwards.api.data.BackwardsMappings) SoundPackets1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.packets.SoundPackets1_12) EntityTrackerBase(com.viaversion.viaversion.data.entity.EntityTrackerBase) UserConnection(com.viaversion.viaversion.api.connection.UserConnection) ClientboundPackets1_9_3(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.ClientboundPackets1_9_3) ShoulderTracker(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.data.ShoulderTracker) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) SoundPackets1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.packets.SoundPackets1_12) ChatPackets1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.packets.ChatPackets1_12)

Example 28 with PacketRemapper

use of com.viaversion.viaversion.api.protocol.remapper.PacketRemapper in project ViaVersion by ViaVersion.

the class AbstractProtocol method transform.

@Override
public void transform(Direction direction, State state, PacketWrapper packetWrapper) throws Exception {
    Packet statePacket = new Packet(state, packetWrapper.getId());
    Map<Packet, ProtocolPacket> packetMap = direction == Direction.CLIENTBOUND ? clientbound : serverbound;
    ProtocolPacket protocolPacket = packetMap.get(statePacket);
    if (protocolPacket == null) {
        return;
    }
    // Write packet id
    int unmappedId = packetWrapper.getId();
    if (protocolPacket.isMappedOverTypes()) {
        packetWrapper.setPacketType(protocolPacket.getMappedPacketType());
    } else {
        int mappedId = direction == Direction.CLIENTBOUND ? protocolPacket.getNewId() : protocolPacket.getOldId();
        if (unmappedId != mappedId) {
            packetWrapper.setId(mappedId);
        }
    }
    PacketRemapper remapper = protocolPacket.getRemapper();
    if (remapper != null) {
        try {
            remapper.remap(packetWrapper);
        } catch (InformativeException e) {
            // Catch InformativeExceptions, pass through CancelExceptions
            throwRemapError(direction, state, unmappedId, packetWrapper.getId(), e);
            return;
        }
        if (packetWrapper.isCancelled()) {
            throw CancelException.generate();
        }
    }
}
Also used : PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) InformativeException(com.viaversion.viaversion.exception.InformativeException)

Example 29 with PacketRemapper

use of com.viaversion.viaversion.api.protocol.remapper.PacketRemapper in project ViaVersion by ViaVersion.

the class InventoryPackets method registerPackets.

@Override
public void registerPackets() {
    protocol.registerClientbound(ClientboundPackets1_12_1.SET_SLOT, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Window ID
            map(Type.UNSIGNED_BYTE);
            // 1 - Slot ID
            map(Type.SHORT);
            // 2 - Slot Value
            map(Type.ITEM, Type.FLAT_ITEM);
            handler(itemToClientHandler(Type.FLAT_ITEM));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.WINDOW_ITEMS, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Window ID
            map(Type.UNSIGNED_BYTE);
            // 1 - Window Values
            map(Type.ITEM_ARRAY, Type.FLAT_ITEM_ARRAY);
            handler(itemArrayHandler(Type.FLAT_ITEM_ARRAY));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.WINDOW_PROPERTY, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Window id
            map(Type.UNSIGNED_BYTE);
            // Property
            map(Type.SHORT);
            // Value
            map(Type.SHORT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    short property = wrapper.get(Type.SHORT, 0);
                    if (property >= 4 && property <= 6) {
                        // Enchantment id
                        wrapper.set(Type.SHORT, 1, (short) protocol.getMappingData().getEnchantmentMappings().getNewId(wrapper.get(Type.SHORT, 1)));
                    }
                }
            });
        }
    });
    // Plugin message Packet -> Trading
    protocol.registerClientbound(ClientboundPackets1_12_1.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Channel
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String channel = wrapper.get(Type.STRING, 0);
                    // Handle stopsound change
                    if (channel.equalsIgnoreCase("MC|StopSound")) {
                        String originalSource = wrapper.read(Type.STRING);
                        String originalSound = wrapper.read(Type.STRING);
                        // Reset the packet
                        wrapper.clearPacket();
                        wrapper.setId(0x4C);
                        byte flags = 0;
                        // Placeholder
                        wrapper.write(Type.BYTE, flags);
                        if (!originalSource.isEmpty()) {
                            flags |= 1;
                            Optional<SoundSource> finalSource = SoundSource.findBySource(originalSource);
                            if (!finalSource.isPresent()) {
                                if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                    Via.getPlatform().getLogger().info("Could not handle unknown sound source " + originalSource + " falling back to default: master");
                                }
                                finalSource = Optional.of(SoundSource.MASTER);
                            }
                            wrapper.write(Type.VAR_INT, finalSource.get().getId());
                        }
                        if (!originalSound.isEmpty()) {
                            flags |= 2;
                            wrapper.write(Type.STRING, originalSound);
                        }
                        // Update flags
                        wrapper.set(Type.BYTE, 0, flags);
                        return;
                    } else if (channel.equalsIgnoreCase("MC|TrList")) {
                        channel = "minecraft:trader_list";
                        // Passthrough Window ID
                        wrapper.passthrough(Type.INT);
                        int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
                        for (int i = 0; i < size; i++) {
                            // Input Item
                            Item input = wrapper.read(Type.ITEM);
                            handleItemToClient(input);
                            wrapper.write(Type.FLAT_ITEM, input);
                            // Output Item
                            Item output = wrapper.read(Type.ITEM);
                            handleItemToClient(output);
                            wrapper.write(Type.FLAT_ITEM, output);
                            // Has second item
                            boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                            if (secondItem) {
                                // Second Item
                                Item second = wrapper.read(Type.ITEM);
                                handleItemToClient(second);
                                wrapper.write(Type.FLAT_ITEM, second);
                            }
                            // Trade disabled
                            wrapper.passthrough(Type.BOOLEAN);
                            // Number of tools uses
                            wrapper.passthrough(Type.INT);
                            // Maximum number of trade uses
                            wrapper.passthrough(Type.INT);
                        }
                    } else {
                        String old = channel;
                        channel = getNewPluginChannelId(channel);
                        if (channel == null) {
                            if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                Via.getPlatform().getLogger().warning("Ignoring outgoing plugin message with channel: " + old);
                            }
                            wrapper.cancel();
                            return;
                        } else if (channel.equals("minecraft:register") || channel.equals("minecraft:unregister")) {
                            String[] channels = new String(wrapper.read(Type.REMAINING_BYTES), StandardCharsets.UTF_8).split("\0");
                            List<String> rewrittenChannels = new ArrayList<>();
                            for (int i = 0; i < channels.length; i++) {
                                String rewritten = getNewPluginChannelId(channels[i]);
                                if (rewritten != null) {
                                    rewrittenChannels.add(rewritten);
                                } else if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                    Via.getPlatform().getLogger().warning("Ignoring plugin channel in outgoing REGISTER: " + channels[i]);
                                }
                            }
                            if (!rewrittenChannels.isEmpty()) {
                                wrapper.write(Type.REMAINING_BYTES, Joiner.on('\0').join(rewrittenChannels).getBytes(StandardCharsets.UTF_8));
                            } else {
                                wrapper.cancel();
                                return;
                            }
                        }
                    }
                    wrapper.set(Type.STRING, 0, channel);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.ENTITY_EQUIPMENT, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity ID
            map(Type.VAR_INT);
            // 1 - Slot ID
            map(Type.VAR_INT);
            // 2 - Item
            map(Type.ITEM, Type.FLAT_ITEM);
            handler(itemToClientHandler(Type.FLAT_ITEM));
        }
    });
    protocol.registerServerbound(ServerboundPackets1_13.CLICK_WINDOW, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Window ID
            map(Type.UNSIGNED_BYTE);
            // 1 - Slot
            map(Type.SHORT);
            // 2 - Button
            map(Type.BYTE);
            // 3 - Action number
            map(Type.SHORT);
            // 4 - Mode
            map(Type.VAR_INT);
            // 5 - Clicked Item
            map(Type.FLAT_ITEM, Type.ITEM);
            handler(itemToServerHandler(Type.ITEM));
        }
    });
    protocol.registerServerbound(ServerboundPackets1_13.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Channel
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String channel = wrapper.get(Type.STRING, 0);
                    String old = channel;
                    channel = getOldPluginChannelId(channel);
                    if (channel == null) {
                        if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                            Via.getPlatform().getLogger().warning("Ignoring incoming plugin message with channel: " + old);
                        }
                        wrapper.cancel();
                        return;
                    } else if (channel.equals("REGISTER") || channel.equals("UNREGISTER")) {
                        String[] channels = new String(wrapper.read(Type.REMAINING_BYTES), StandardCharsets.UTF_8).split("\0");
                        List<String> rewrittenChannels = new ArrayList<>();
                        for (int i = 0; i < channels.length; i++) {
                            String rewritten = getOldPluginChannelId(channels[i]);
                            if (rewritten != null) {
                                rewrittenChannels.add(rewritten);
                            } else if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                Via.getPlatform().getLogger().warning("Ignoring plugin channel in incoming REGISTER: " + channels[i]);
                            }
                        }
                        wrapper.write(Type.REMAINING_BYTES, Joiner.on('\0').join(rewrittenChannels).getBytes(StandardCharsets.UTF_8));
                    }
                    wrapper.set(Type.STRING, 0, channel);
                }
            });
        }
    });
    protocol.registerServerbound(ServerboundPackets1_13.CREATIVE_INVENTORY_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Slot
            map(Type.SHORT);
            // 1 - Clicked Item
            map(Type.FLAT_ITEM, Type.ITEM);
            handler(itemToServerHandler(Type.ITEM));
        }
    });
}
Also used : SoundSource(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.data.SoundSource) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) ArrayList(java.util.ArrayList) Item(com.viaversion.viaversion.api.minecraft.item.Item) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) ArrayList(java.util.ArrayList) List(java.util.List)

Example 30 with PacketRemapper

use of com.viaversion.viaversion.api.protocol.remapper.PacketRemapper in project ViaVersion by ViaVersion.

the class WorldPackets method register.

public static void register(Protocol protocol) {
    // Outgoing packets
    protocol.registerClientbound(ClientboundPackets1_12_1.SPAWN_PAINTING, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity ID
            map(Type.VAR_INT);
            // 1 - Entity UUID
            map(Type.UUID);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    PaintingProvider provider = Via.getManager().getProviders().get(PaintingProvider.class);
                    String motive = wrapper.read(Type.STRING);
                    Optional<Integer> id = provider.getIntByIdentifier(motive);
                    if (!id.isPresent() && (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug())) {
                        Via.getPlatform().getLogger().warning("Could not find painting motive: " + motive + " falling back to default (0)");
                    }
                    wrapper.write(Type.VAR_INT, id.orElse(0));
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.BLOCK_ENTITY_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Location
            map(Type.POSITION);
            // 1 - Action
            map(Type.UNSIGNED_BYTE);
            // 2 - NBT data
            map(Type.NBT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Position position = wrapper.get(Type.POSITION, 0);
                    short action = wrapper.get(Type.UNSIGNED_BYTE, 0);
                    CompoundTag tag = wrapper.get(Type.NBT, 0);
                    BlockEntityProvider provider = Via.getManager().getProviders().get(BlockEntityProvider.class);
                    int newId = provider.transform(wrapper.user(), position, tag, true);
                    if (newId != -1) {
                        BlockStorage storage = wrapper.user().get(BlockStorage.class);
                        BlockStorage.ReplacementData replacementData = storage.get(position);
                        if (replacementData != null) {
                            replacementData.setReplacement(newId);
                        }
                    }
                    if (action == 5) {
                        // Set type of flower in flower pot
                        // Removed
                        wrapper.cancel();
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.BLOCK_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Location
            map(Type.POSITION);
            // Action Id
            map(Type.UNSIGNED_BYTE);
            // Action param
            map(Type.UNSIGNED_BYTE);
            // Block Id - /!\ NOT BLOCK STATE ID
            map(Type.VAR_INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Position pos = wrapper.get(Type.POSITION, 0);
                    short action = wrapper.get(Type.UNSIGNED_BYTE, 0);
                    short param = wrapper.get(Type.UNSIGNED_BYTE, 1);
                    int blockId = wrapper.get(Type.VAR_INT, 0);
                    if (blockId == 25)
                        blockId = 73;
                    else if (blockId == 33)
                        blockId = 99;
                    else if (blockId == 29)
                        blockId = 92;
                    else if (blockId == 54)
                        blockId = 142;
                    else if (blockId == 146)
                        blockId = 305;
                    else if (blockId == 130)
                        blockId = 249;
                    else if (blockId == 138)
                        blockId = 257;
                    else if (blockId == 52)
                        blockId = 140;
                    else if (blockId == 209)
                        blockId = 472;
                    else if (blockId >= 219 && blockId <= 234)
                        blockId = blockId - 219 + 483;
                    if (blockId == 73) {
                        // Note block
                        // block change
                        PacketWrapper blockChange = wrapper.create(0x0B);
                        blockChange.write(Type.POSITION, pos);
                        blockChange.write(Type.VAR_INT, 249 + (action * 24 * 2) + (param * 2));
                        blockChange.send(Protocol1_13To1_12_2.class);
                    }
                    wrapper.set(Type.VAR_INT, 0, blockId);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.BLOCK_CHANGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.POSITION);
            map(Type.VAR_INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Position position = wrapper.get(Type.POSITION, 0);
                    int newId = toNewId(wrapper.get(Type.VAR_INT, 0));
                    UserConnection userConnection = wrapper.user();
                    if (Via.getConfig().isServersideBlockConnections()) {
                        ConnectionData.updateBlockStorage(userConnection, position.x(), position.y(), position.z(), newId);
                        newId = ConnectionData.connect(userConnection, position, newId);
                    }
                    wrapper.set(Type.VAR_INT, 0, checkStorage(wrapper.user(), position, newId));
                    if (Via.getConfig().isServersideBlockConnections()) {
                        // Workaround for packet order issue
                        wrapper.send(Protocol1_13To1_12_2.class);
                        wrapper.cancel();
                        ConnectionData.update(userConnection, position);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.MULTI_BLOCK_CHANGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Chunk X
            map(Type.INT);
            // 1 - Chunk Z
            map(Type.INT);
            // 2 - Records
            map(Type.BLOCK_CHANGE_RECORD_ARRAY);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int chunkX = wrapper.get(Type.INT, 0);
                    int chunkZ = wrapper.get(Type.INT, 1);
                    UserConnection userConnection = wrapper.user();
                    BlockChangeRecord[] records = wrapper.get(Type.BLOCK_CHANGE_RECORD_ARRAY, 0);
                    // Convert ids
                    for (BlockChangeRecord record : records) {
                        int newBlock = toNewId(record.getBlockId());
                        Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                        if (Via.getConfig().isServersideBlockConnections()) {
                            ConnectionData.updateBlockStorage(userConnection, position.x(), position.y(), position.z(), newBlock);
                        }
                        record.setBlockId(checkStorage(wrapper.user(), position, newBlock));
                    }
                    if (Via.getConfig().isServersideBlockConnections()) {
                        for (BlockChangeRecord record : records) {
                            int blockState = record.getBlockId();
                            Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                            ConnectionHandler handler = ConnectionData.getConnectionHandler(blockState);
                            if (handler != null) {
                                blockState = handler.connect(userConnection, position, blockState);
                                record.setBlockId(blockState);
                            }
                        }
                        // Workaround for packet order issue
                        wrapper.send(Protocol1_13To1_12_2.class);
                        wrapper.cancel();
                        for (BlockChangeRecord record : records) {
                            Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                            ConnectionData.update(userConnection, position);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.EXPLOSION, new PacketRemapper() {

        @Override
        public void registerMap() {
            if (!Via.getConfig().isServersideBlockConnections())
                return;
            // X
            map(Type.FLOAT);
            // Y
            map(Type.FLOAT);
            // Z
            map(Type.FLOAT);
            // Radius
            map(Type.FLOAT);
            // Record Count
            map(Type.INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    UserConnection userConnection = wrapper.user();
                    int x = (int) Math.floor(wrapper.get(Type.FLOAT, 0));
                    int y = (int) Math.floor(wrapper.get(Type.FLOAT, 1));
                    int z = (int) Math.floor(wrapper.get(Type.FLOAT, 2));
                    int recordCount = wrapper.get(Type.INT, 0);
                    Position[] records = new Position[recordCount];
                    for (int i = 0; i < recordCount; i++) {
                        Position position = new Position(x + wrapper.passthrough(Type.BYTE), (short) (y + wrapper.passthrough(Type.BYTE)), z + wrapper.passthrough(Type.BYTE));
                        records[i] = position;
                        // Set to air
                        ConnectionData.updateBlockStorage(userConnection, position.x(), position.y(), position.z(), 0);
                    }
                    // Workaround for packet order issue
                    wrapper.send(Protocol1_13To1_12_2.class);
                    wrapper.cancel();
                    for (int i = 0; i < recordCount; i++) {
                        ConnectionData.update(userConnection, records[i]);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.UNLOAD_CHUNK, new PacketRemapper() {

        @Override
        public void registerMap() {
            if (Via.getConfig().isServersideBlockConnections()) {
                handler(new PacketHandler() {

                    @Override
                    public void handle(PacketWrapper wrapper) throws Exception {
                        int x = wrapper.passthrough(Type.INT);
                        int z = wrapper.passthrough(Type.INT);
                        ConnectionData.blockConnectionProvider.unloadChunk(wrapper.user(), x, z);
                    }
                });
            }
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.NAMED_SOUND, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String sound = wrapper.get(Type.STRING, 0).replace("minecraft:", "");
                    String newSoundId = NamedSoundRewriter.getNewId(sound);
                    wrapper.set(Type.STRING, 0, newSoundId);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.CHUNK_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    ClientWorld clientWorld = wrapper.user().get(ClientWorld.class);
                    BlockStorage storage = wrapper.user().get(BlockStorage.class);
                    Chunk1_9_3_4Type type = new Chunk1_9_3_4Type(clientWorld);
                    Chunk1_13Type type1_13 = new Chunk1_13Type(clientWorld);
                    Chunk chunk = wrapper.read(type);
                    wrapper.write(type1_13, chunk);
                    for (int i = 0; i < chunk.getSections().length; i++) {
                        ChunkSection section = chunk.getSections()[i];
                        if (section == null)
                            continue;
                        for (int p = 0; p < section.getPaletteSize(); p++) {
                            int old = section.getPaletteEntry(p);
                            int newId = toNewId(old);
                            section.setPaletteEntry(p, newId);
                        }
                        boolean willSaveToStorage = false;
                        for (int p = 0; p < section.getPaletteSize(); p++) {
                            int newId = section.getPaletteEntry(p);
                            if (storage.isWelcome(newId)) {
                                willSaveToStorage = true;
                                break;
                            }
                        }
                        boolean willSaveConnection = false;
                        if (Via.getConfig().isServersideBlockConnections() && ConnectionData.needStoreBlocks()) {
                            for (int p = 0; p < section.getPaletteSize(); p++) {
                                int newId = section.getPaletteEntry(p);
                                if (ConnectionData.isWelcome(newId)) {
                                    willSaveConnection = true;
                                    break;
                                }
                            }
                        }
                        if (willSaveToStorage) {
                            for (int y = 0; y < 16; y++) {
                                for (int z = 0; z < 16; z++) {
                                    for (int x = 0; x < 16; x++) {
                                        int block = section.getFlatBlock(x, y, z);
                                        if (storage.isWelcome(block)) {
                                            storage.store(new Position((x + (chunk.getX() << 4)), (short) (y + (i << 4)), (z + (chunk.getZ() << 4))), block);
                                        }
                                    }
                                }
                            }
                        }
                        if (willSaveConnection) {
                            for (int y = 0; y < 16; y++) {
                                for (int z = 0; z < 16; z++) {
                                    for (int x = 0; x < 16; x++) {
                                        int block = section.getFlatBlock(x, y, z);
                                        if (ConnectionData.isWelcome(block)) {
                                            ConnectionData.blockConnectionProvider.storeBlock(wrapper.user(), x + (chunk.getX() << 4), y + (i << 4), z + (chunk.getZ() << 4), block);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Rewrite biome id 255 to plains
                    if (chunk.isBiomeData()) {
                        int latestBiomeWarn = Integer.MIN_VALUE;
                        for (int i = 0; i < 256; i++) {
                            int biome = chunk.getBiomeData()[i];
                            if (!VALID_BIOMES.contains(biome)) {
                                if (// is it generated naturally? *shrug*
                                biome != 255 && latestBiomeWarn != biome) {
                                    if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                        Via.getPlatform().getLogger().warning("Received invalid biome id " + biome);
                                    }
                                    latestBiomeWarn = biome;
                                }
                                // Plains
                                chunk.getBiomeData()[i] = 1;
                            }
                        }
                    }
                    // Rewrite BlockEntities to normal blocks
                    BlockEntityProvider provider = Via.getManager().getProviders().get(BlockEntityProvider.class);
                    final Iterator<CompoundTag> iterator = chunk.getBlockEntities().iterator();
                    while (iterator.hasNext()) {
                        CompoundTag tag = iterator.next();
                        int newId = provider.transform(wrapper.user(), null, tag, false);
                        if (newId != -1) {
                            int x = ((NumberTag) tag.get("x")).asInt();
                            int y = ((NumberTag) tag.get("y")).asInt();
                            int z = ((NumberTag) tag.get("z")).asInt();
                            Position position = new Position(x, (short) y, z);
                            // Store the replacement blocks for blockupdates
                            BlockStorage.ReplacementData replacementData = storage.get(position);
                            if (replacementData != null) {
                                replacementData.setReplacement(newId);
                            }
                            chunk.getSections()[y >> 4].setFlatBlock(x & 0xF, y & 0xF, z & 0xF, newId);
                        }
                        final Tag idTag = tag.get("id");
                        if (idTag instanceof StringTag) {
                            // No longer block entities
                            final String id = ((StringTag) idTag).getValue();
                            if (id.equals("minecraft:noteblock") || id.equals("minecraft:flower_pot")) {
                                iterator.remove();
                            }
                        }
                    }
                    if (Via.getConfig().isServersideBlockConnections()) {
                        ConnectionData.connectBlocks(wrapper.user(), chunk);
                        // Workaround for packet order issue
                        wrapper.send(Protocol1_13To1_12_2.class);
                        wrapper.cancel();
                        for (int i = 0; i < chunk.getSections().length; i++) {
                            ChunkSection section = chunk.getSections()[i];
                            if (section == null)
                                continue;
                            ConnectionData.updateChunkSectionNeighbours(wrapper.user(), chunk.getX(), chunk.getZ(), i);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.SPAWN_PARTICLE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Particle ID
            map(Type.INT);
            // 1 - Long Distance
            map(Type.BOOLEAN);
            // 2 - X
            map(Type.FLOAT);
            // 3 - Y
            map(Type.FLOAT);
            // 4 - Z
            map(Type.FLOAT);
            // 5 - Offset X
            map(Type.FLOAT);
            // 6 - Offset Y
            map(Type.FLOAT);
            // 7 - Offset Z
            map(Type.FLOAT);
            // 8 - Particle Data
            map(Type.FLOAT);
            // 9 - Particle Count
            map(Type.INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int particleId = wrapper.get(Type.INT, 0);
                    // Get the data (Arrays are overrated)
                    int dataCount = 0;
                    // Particles with 1 data [BlockCrack,BlockDust,FallingDust]
                    if (particleId == 37 || particleId == 38 || particleId == 46)
                        dataCount = 1;
                    else // Particles with 2 data [IconCrack]
                    if (particleId == 36)
                        dataCount = 2;
                    Integer[] data = new Integer[dataCount];
                    for (int i = 0; i < data.length; i++) data[i] = wrapper.read(Type.VAR_INT);
                    Particle particle = ParticleRewriter.rewriteParticle(particleId, data);
                    // Cancel if null or completely removed
                    if (particle == null || particle.getId() == -1) {
                        wrapper.cancel();
                        return;
                    }
                    // Handle reddust particle color
                    if (particle.getId() == 11) {
                        int count = wrapper.get(Type.INT, 1);
                        float speed = wrapper.get(Type.FLOAT, 6);
                        // Only handle for count = 0
                        if (count == 0) {
                            wrapper.set(Type.INT, 1, 1);
                            wrapper.set(Type.FLOAT, 6, 0f);
                            List<Particle.ParticleData> arguments = particle.getArguments();
                            for (int i = 0; i < 3; i++) {
                                // RGB values are represented by the X/Y/Z offset
                                float colorValue = wrapper.get(Type.FLOAT, i + 3) * speed;
                                if (colorValue == 0 && i == 0) {
                                    // https://minecraft.gamepedia.com/User:Alphappy/reddust
                                    colorValue = 1;
                                }
                                arguments.get(i).setValue(colorValue);
                                wrapper.set(Type.FLOAT, i + 3, 0f);
                            }
                        }
                    }
                    wrapper.set(Type.INT, 0, particle.getId());
                    for (Particle.ParticleData particleData : particle.getArguments()) wrapper.write(particleData.getType(), particleData.getValue());
                }
            });
        }
    });
}
Also used : StringTag(com.github.steveice10.opennbt.tag.builtin.StringTag) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Chunk1_9_3_4Type(com.viaversion.viaversion.protocols.protocol1_9_1_2to1_9_3_4.types.Chunk1_9_3_4Type) Particle(com.viaversion.viaversion.api.type.types.Particle) BlockChangeRecord(com.viaversion.viaversion.api.minecraft.BlockChangeRecord) BlockStorage(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.storage.BlockStorage) Chunk1_13Type(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.types.Chunk1_13Type) CompoundTag(com.github.steveice10.opennbt.tag.builtin.CompoundTag) Position(com.viaversion.viaversion.api.minecraft.Position) PaintingProvider(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.providers.PaintingProvider) Chunk(com.viaversion.viaversion.api.minecraft.chunks.Chunk) UserConnection(com.viaversion.viaversion.api.connection.UserConnection) ConnectionHandler(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.blockconnections.ConnectionHandler) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) NumberTag(com.github.steveice10.opennbt.tag.builtin.NumberTag) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) CompoundTag(com.github.steveice10.opennbt.tag.builtin.CompoundTag) NumberTag(com.github.steveice10.opennbt.tag.builtin.NumberTag) StringTag(com.github.steveice10.opennbt.tag.builtin.StringTag) Tag(com.github.steveice10.opennbt.tag.builtin.Tag) BlockEntityProvider(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.providers.BlockEntityProvider) ChunkSection(com.viaversion.viaversion.api.minecraft.chunks.ChunkSection)

Aggregations

PacketRemapper (com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)109 PacketWrapper (com.viaversion.viaversion.api.protocol.packet.PacketWrapper)78 PacketHandler (com.viaversion.viaversion.api.protocol.remapper.PacketHandler)65 Type (com.viaversion.viaversion.api.type.Type)64 Item (com.viaversion.viaversion.api.minecraft.item.Item)31 Chunk (com.viaversion.viaversion.api.minecraft.chunks.Chunk)24 ClientWorld (com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld)24 UserConnection (com.viaversion.viaversion.api.connection.UserConnection)21 Via (com.viaversion.viaversion.api.Via)19 ChunkSection (com.viaversion.viaversion.api.minecraft.chunks.ChunkSection)19 CompoundTag (com.github.steveice10.opennbt.tag.builtin.CompoundTag)17 ArrayList (java.util.ArrayList)17 List (java.util.List)17 Metadata (com.viaversion.viaversion.api.minecraft.metadata.Metadata)16 Position (com.viaversion.viaversion.api.minecraft.Position)14 EntityType (com.viaversion.viaversion.api.minecraft.entities.EntityType)14 ClientboundPackets1_13 (com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13)14 StringTag (com.github.steveice10.opennbt.tag.builtin.StringTag)13 CompoundTag (com.viaversion.viaversion.libs.opennbt.tag.builtin.CompoundTag)13 StatisticsRewriter (com.viaversion.viaversion.rewriter.StatisticsRewriter)13