From 87669ed6eceb5d688950f38bdae3a910080fcb2b Mon Sep 17 00:00:00 2001 From: Tanner Date: Tue, 3 Nov 2026 23:33:05 +0000 Subject: [PATCH] Add 26.3 inventory component decoding --- minecraft/networking/connection.py | 9 + minecraft/networking/modern.py | 722 ++++++++++++++++++++++++++++- 2 files changed, 714 insertions(+), 17 deletions(-) diff --git a/minecraft/networking/connection.py b/minecraft/networking/connection.py index 5d87e54..010997b 100644 --- a/minecraft/networking/connection.py +++ b/minecraft/networking/connection.py @@ -340,6 +340,10 @@ class Connection(object): print('[pyCraft/777] TX state={} id=0x{:02x} packet={}'.format( type(self.reactor).__name__, packet.id, packet.packet_name), flush=True) + if (self.context.protocol_version >= 777 and + packet.packet_name == 'move player position and rotation'): + self.player_position = ( + packet.x, packet.y, packet.z, packet.yaw, packet.pitch) if self.options.compression_enabled: packet.write(self.socket, self.options.compression_threshold) else: @@ -349,6 +353,11 @@ class Connection(object): listener.call_packet(packet) except IgnorePacket: pass + except OSError: + # An immediate disconnect can close the socket while the network + # thread is draining a packet queued just before shutdown. + if self.connected: + raise def status(self, handle_status=None, handle_ping=False): """Issue a status request to the server and then disconnect. diff --git a/minecraft/networking/modern.py b/minecraft/networking/modern.py index cef859c..d8aba0e 100644 --- a/minecraft/networking/modern.py +++ b/minecraft/networking/modern.py @@ -1,17 +1,19 @@ -"""Minimal protocol support for current Java Edition releases (26.3/777). +"""Incremental protocol support for Java Edition 26.3 (protocol 777). -This deliberately implements only status, offline login, configuration, keepalive, -position acknowledgement, and unsigned chat command traffic. It is enough for -headless clients that need to remain connected and interact with server plugins. +Implemented paths cover offline login/configuration, AuthMe dialogs, chat, +world/chunk state, basic entity and inventory updates, keepalive, teleports, +and player movement. Legacy gameplay interactions remain a separate porting +stage. """ import io import json import os +import struct from minecraft.networking.packets import Packet from minecraft.networking.types import ( - Boolean, Byte, Double, Float, Long, String, TrailingByteArray, Type, UUID, - UnsignedByte, VarInt, + Boolean, Byte, Double, Float, Integer, Long, Position, Short, String, + TrailingByteArray, Type, UUID, UnsignedByte, VarInt, VarLong, ) from minecraft.networking.connection import PacketReactor @@ -21,6 +23,11 @@ def trace(message): print('[pyCraft/777] ' + message, flush=True) +def read_signed_varint(file_object): + value = VarInt.read(file_object) + return value - (1 << 32) if value & (1 << 31) else value + + def nbt_plain(value): raw = getattr(value, 'value', value) if hasattr(raw, 'items'): @@ -30,6 +37,31 @@ def nbt_plain(value): return raw +def read_lp_vec3(file_object): + """Decode Mojang's compact LpVec3 representation.""" + low = file_object.read(1) + if not low: + raise EOFError('truncated LpVec3') + low = low[0] + if low == 0: + return (0.0, 0.0, 0.0) + middle = file_object.read(1) + high = file_object.read(4) + if len(middle) != 1 or len(high) != 4: + raise EOFError('truncated LpVec3') + buffer = (struct.unpack('>I', high)[0] << 16) | (middle[0] << 8) | low + scale = low & 3 + if low & 4: + scale |= VarInt.read(file_object) << 2 + + def unpack(value): + value = min(value & 0x7fff, 32766) + return (value * 2.0 / 32766.0 - 1.0) * scale + + return (unpack(buffer >> 3), unpack(buffer >> 18), + unpack(buffer >> 33)) + + def read_anonymous_nbt(file_object): import functools import pynbt @@ -90,6 +122,19 @@ class CodeOfConduct(Packet): self.dialog_text = 'could not decode ({})'.format(exc) +class RegistryData(Packet): + id = 0x07 + packet_name = "registry data" + + def read(self, file_object): + self.registry = String.read(file_object) + self.entries = [] + for _ in range(VarInt.read(file_object)): + key = String.read(file_object) + value = AnonymousNBT.read(file_object) if Boolean.read(file_object) else None + self.entries.append((key, nbt_plain(value) if value is not None else None)) + + class ConfigurationCustomPayload(Packet): id = 0x01 packet_name = "configuration custom payload" @@ -138,6 +183,510 @@ class PlayerLoaded(Packet): definition = [] +class ChunkBatchReceived(Packet): + id = 0x0B + packet_name = "chunk batch received" + definition = [{'desired_chunks_per_tick': Float}] + + +class ClientboundChunkBatchFinished(Packet): + id = 0x0B + packet_name = "chunk batch finished" + definition = [{'batch_size': VarInt}] + + +class ChunkDataPacket(Packet): + id = 0x2E + packet_name = "chunk data" + + def read(self, file_object): + from mosfet.world_26_3 import decode_chunk_sections + self.x = Integer.read(file_object) + self.z = Integer.read(file_object) + self.heightmaps = {} + for _ in range(VarInt.read(file_object)): + key = VarInt.read(file_object) + self.heightmaps[key] = [ + Long.read(file_object) for _ in range(VarInt.read(file_object)) + ] + data_size = VarInt.read(file_object) + self.data = file_object.read(data_size) + self.sections = decode_chunk_sections(self.data) + + +class BlockUpdatePacket(Packet): + id = 0x08 + packet_name = "block update" + definition = [{'location': Position}, {'block_state_id': VarInt}] + + +class SectionBlocksUpdatePacket(Packet): + id = 0x56 + packet_name = "section blocks update" + + def read(self, file_object): + packed_section = Long.read(file_object) + section_x = packed_section >> 42 + section_y = packed_section << 44 >> 44 + section_z = packed_section << 22 >> 42 + self.changes = [] + for _ in range(VarInt.read(file_object)): + packed_change = VarLong.read(file_object) + local = packed_change & 0xFFF + x = (section_x << 4) + ((local >> 8) & 0xF) + y = (section_y << 4) + ((local >> 4) & 0xF) + z = (section_z << 4) + (local & 0xF) + self.changes.append((x, y, z, packed_change >> 12)) + + +def _read_vec_delta(file_object, step_count): + from minecraft.networking.types import Short + if step_count > 1024: + raise ValueError('entity movement step count too large: {}'.format(step_count)) + deltas = [] + for _ in range(max(1, step_count)): + if step_count: + VarInt.read(file_object) # interpolation tick offset + deltas.append((Short.read(file_object), Short.read(file_object), + Short.read(file_object))) + return tuple(sum(delta[i] for delta in deltas) / 4096.0 + for i in range(3)) + + +class AddEntityPacket(Packet): + id = 0x01 + packet_name = "add entity" + + def read(self, file_object): + self.entity_id = VarInt.read(file_object) + self.entity_uuid = UUID.read(file_object) + self.entity_type_id = VarInt.read(file_object) + self.x, self.y, self.z = (Double.read(file_object), + Double.read(file_object), + Double.read(file_object)) + self.velocity_x, self.velocity_y, self.velocity_z = read_lp_vec3(file_object) + self.pitch = Byte.read(file_object) * (360.0 / 256.0) + self.yaw = Byte.read(file_object) * (360.0 / 256.0) + self.head_yaw = Byte.read(file_object) * (360.0 / 256.0) + self.data = VarInt.read(file_object) + + +class MoveEntityPositionPacket(Packet): + id = 0x36 + packet_name = "move entity position" + + def read(self, file_object): + self.entity_id = VarInt.read(file_object) + properties = VarInt.read(file_object) + self.delta_x, self.delta_y, self.delta_z = _read_vec_delta( + file_object, properties >> 1) + self.on_ground = bool(properties & 1) + + +class MoveEntityPositionRotationPacket(Packet): + id = 0x37 + packet_name = "move entity position and rotation" + + def read(self, file_object): + self.entity_id = VarInt.read(file_object) + properties = VarInt.read(file_object) + self.delta_x, self.delta_y, self.delta_z = _read_vec_delta( + file_object, properties >> 1) + self.yaw = Byte.read(file_object) * (360.0 / 256.0) + self.pitch = Byte.read(file_object) * (360.0 / 256.0) + self.on_ground = bool(properties & 1) + + +class MoveEntityRotationPacket(Packet): + id = 0x39 + packet_name = "move entity rotation" + + def read(self, file_object): + self.entity_id = VarInt.read(file_object) + self.on_ground = Boolean.read(file_object) + self.yaw = Byte.read(file_object) * (360.0 / 256.0) + self.pitch = Byte.read(file_object) * (360.0 / 256.0) + + +class EntityPositionSyncPacket(Packet): + id = 0x23 + packet_name = "entity position sync" + + def read(self, file_object): + self.entity_id = VarInt.read(file_object) + path_type = VarInt.read(file_object) + if path_type == 0: + self.x, self.y, self.z = (Double.read(file_object), + Double.read(file_object), + Double.read(file_object)) + elif path_type == 1: + count = VarInt.read(file_object) + if count <= 0 or count > 1024: + raise ValueError('invalid stepped entity path length {}'.format(count)) + for _ in range(count): + position = (Double.read(file_object), Double.read(file_object), + Double.read(file_object)) + VarInt.read(file_object) # tick offset + self.x, self.y, self.z = position + else: + raise ValueError('unknown entity position path type {}'.format(path_type)) + self.yaw = Float.read(file_object) + self.pitch = Float.read(file_object) + self.on_ground = Boolean.read(file_object) + + +class RemoveEntitiesPacket(Packet): + id = 0x4E + packet_name = "remove entities" + + def read(self, file_object): + self.entity_ids = [VarInt.read(file_object) + for _ in range(VarInt.read(file_object))] + + +class PlayerInfoRemovePacket(Packet): + id = 0x46 + packet_name = "player info remove" + + def read(self, file_object): + self.uuids = [UUID.read(file_object) + for _ in range(VarInt.read(file_object))] + + +class PlayerInfoUpdatePacket(Packet): + id = 0x47 + packet_name = "player info update" + + def read(self, file_object): + self.actions = UnsignedByte.read(file_object) + self.entries = [] + for _ in range(VarInt.read(file_object)): + profile_uuid = UUID.read(file_object) + name = None + if self.actions & 1: + name = String.read(file_object) + for _ in range(VarInt.read(file_object)): + String.read(file_object) + String.read(file_object) + if Boolean.read(file_object): + String.read(file_object) + if self.actions & 2 and Boolean.read(file_object): + UUID.read(file_object) + Long.read(file_object) + key_size = VarInt.read(file_object) + file_object.read(key_size) + signature_size = VarInt.read(file_object) + file_object.read(signature_size) + if self.actions & 4: + VarInt.read(file_object) + if self.actions & 8: + Boolean.read(file_object) + if self.actions & 16: + VarInt.read(file_object) + if self.actions & 32 and Boolean.read(file_object): + read_anonymous_nbt(file_object) + if self.actions & 64: + VarInt.read(file_object) + if self.actions & 128: + Boolean.read(file_object) + self.entries.append((profile_uuid, name)) + + +DATA_COMPONENT_TYPES = ( + 'custom_data', 'max_stack_size', 'max_damage', 'damage', 'unbreakable', + 'use_effects', 'custom_name', 'minimum_attack_charge', 'damage_type', + 'item_name', 'item_model', 'lore', 'rarity', 'enchantments', + 'can_place_on', 'can_break', 'attribute_modifiers', 'custom_model_data', + 'tooltip_display', 'repair_cost', 'creative_slot_lock', + 'enchantment_glint_override', 'intangible_projectile', 'food', + 'consumable', 'use_remainder', 'use_cooldown', 'damage_resistant', + 'tool', 'weapon', 'attack_range', 'enchantable', 'equippable', + 'repairable', 'glider', 'tooltip_style', 'death_protection', + 'blocks_attacks', 'piercing_weapon', 'kinetic_weapon', + 'attack_animation', 'interact_animation', 'additional_trade_cost', + 'block_transformer', 'villager_food', 'stored_enchantments', 'dye', + 'dyed_color', 'map_id', 'map_decorations', 'map_post_processing', + 'charged_projectiles', 'bundle_contents', 'potion_contents', + 'potion_duration_scale', 'suspicious_stew_effects', + 'writable_book_content', 'written_book_content', 'trim', + 'debug_stick_state', 'entity_data', 'bucket_entity_data', + 'block_entity_data', 'instrument', 'provides_trim_material', + 'ominous_bottle_amplifier', 'jukebox_playable', + 'provides_banner_patterns', 'recipes', 'lodestone_tracker', + 'firework_explosion', 'fireworks', 'profile', 'note_block_sound', + 'banner_patterns', 'base_color', 'pot_decorations', 'container', + 'block_state', 'bees', 'sulfur_cube_content', 'lock', 'container_loot', + 'break_sound', 'compostable', 'cooking_fuel', 'brewing_fuel', + 'mob_visibility', 'villager/variant', 'wolf/variant', 'wolf/sound_variant', + 'wolf/collar', 'fox/variant', 'salmon/size', 'parrot/variant', + 'tropical_fish/pattern', 'tropical_fish/base_color', + 'tropical_fish/pattern_color', 'mooshroom/variant', 'rabbit/variant', + 'pig/variant', 'pig/sound_variant', 'cow/variant', 'cow/sound_variant', + 'chicken/variant', 'chicken/sound_variant', 'zombie_nautilus/variant', + 'frog/variant', 'horse/variant', 'painting/variant', 'llama/variant', + 'axolotl/variant', 'cat/variant', 'cat/sound_variant', 'cat/collar', + 'sheep/color', 'shulker/color', 'provides_pottery_pattern', + 'sign_text_front', 'sign_text_back', 'waxed', 'cushion/color', +) + + +class ItemStackData: + def __init__(self, present=False, item_id=None, item_count=None, + components_unknown=False, components=None, + component_ids=None, removed_components=None): + self.present = present + self.item_id = item_id + self.item_count = item_count + self.components_unknown = components_unknown + self.components = components or {} + self.component_ids = component_ids or [] + self.removed_components = removed_components or [] + + +class UnsupportedItemComponents(Exception): + def __init__(self, stack): + self.stack = stack + + +def _component_name(component_id, context): + registry = getattr(context, 'registry_ids', {}).get( + 'minecraft:data_component_type', {}) + for name, value in registry.items(): + if value == component_id: + return name.removeprefix('minecraft:') + return (DATA_COMPONENT_TYPES[component_id] + if 0 <= component_id < len(DATA_COMPONENT_TYPES) else None) + + +def _read_filterable(file_object, component=False): + value = (nbt_plain(read_anonymous_nbt(file_object)) if component + else String.read(file_object)) + filtered = None + if Boolean.read(file_object): + filtered = (nbt_plain(read_anonymous_nbt(file_object)) if component + else String.read(file_object)) + return {'raw': value, 'filtered': filtered} + + +def _read_item_template(file_object, context, depth, diagnostic_stack): + if depth > 8: + raise ValueError('nested item components exceed depth limit') + item_id = VarInt.read(file_object) + count = VarInt.read(file_object) + stack = ItemStackData(True, item_id, count) + _read_component_patch(file_object, context, depth, stack, + diagnostic_stack) + return stack + + +def _read_component_value(name, file_object, context, depth, stack, + diagnostic_stack): + if name in ('custom_data', 'bucket_entity_data'): + return nbt_plain(read_anonymous_nbt(file_object)) + if name in ('custom_name', 'item_name'): + return nbt_plain(read_anonymous_nbt(file_object)) + if name == 'lore': + count = VarInt.read(file_object) + if count > 256: + raise ValueError('item lore has too many lines') + return [nbt_plain(read_anonymous_nbt(file_object)) + for _ in range(count)] + if name in ('damage', 'max_damage', 'max_stack_size', 'repair_cost', + 'additional_trade_cost'): + return VarInt.read(file_object) + if name in ('enchantments', 'stored_enchantments'): + count = VarInt.read(file_object) + if count > 256: + raise ValueError('item has too many enchantments') + enchantments = {} + registry = getattr(context, 'registry_ids', {}).get( + 'minecraft:enchantment', {}) + names = {value: key.removeprefix('minecraft:') + for key, value in registry.items()} + for _ in range(count): + enchantment_id = VarInt.read(file_object) + level = VarInt.read(file_object) + enchantments[names.get(enchantment_id, enchantment_id)] = level + return enchantments + if name == 'dyed_color': + return Integer.read(file_object) + if name == 'enchantment_glint_override': + return Boolean.read(file_object) + if name == 'unbreakable': + return True # Unit stream codec has no payload. + if name in ('written_book_content', 'writable_book_content'): + if name == 'writable_book_content': + count = VarInt.read(file_object) + if count > 100: + raise ValueError('writable book has too many pages') + return [_read_filterable(file_object) for _ in range(count)] + title = _read_filterable(file_object) + author = String.read(file_object) + generation = VarInt.read(file_object) + count = VarInt.read(file_object) + if count > 100: + raise ValueError('written book has too many pages') + pages = [_read_filterable(file_object, component=True) + for _ in range(count)] + return {'title': title, 'author': author, + 'generation': generation, 'pages': pages, + 'resolved': Boolean.read(file_object)} + if name == 'container': + count = VarInt.read(file_object) + if count > 256: + raise ValueError('container component has too many slots') + contents = [] + for _ in range(count): + contents.append(_read_item_template( + file_object, context, depth + 1, diagnostic_stack) + if Boolean.read(file_object) else None) + return contents + if name in ('creative_slot_lock', 'glider', 'intangible_projectile'): + return True # Unit stream codec has no payload. + if name == 'custom_model_data': + # The modern structure is four independently length-prefixed lists. + floats = [Float.read(file_object) for _ in range(VarInt.read(file_object))] + flags = [Boolean.read(file_object) for _ in range(VarInt.read(file_object))] + strings = [String.read(file_object) for _ in range(VarInt.read(file_object))] + colors = [Integer.read(file_object) for _ in range(VarInt.read(file_object))] + return {'floats': floats, 'flags': flags, + 'strings': strings, 'colors': colors} + return _COMPONENT_UNSUPPORTED + + +_COMPONENT_UNSUPPORTED = object() + + +def _read_component_patch(file_object, context, depth=0, stack=None, + diagnostic_stack=None): + positive_count = VarInt.read(file_object) + negative_count = VarInt.read(file_object) + if positive_count > 256 or negative_count > 256: + raise ValueError('item component patch is too large') + components = {} + removed = [] + for _ in range(positive_count): + component_id = VarInt.read(file_object) + name = _component_name(component_id, context) + if name is None: + target = diagnostic_stack or stack + if target is not None: + target.component_ids.append(component_id) + target.components_unknown = True + raise UnsupportedItemComponents(target) + raise ValueError('unknown data component id {}'.format(component_id)) + if stack is not None: + stack.component_ids.append(name) + value = _read_component_value( + name, file_object, context, depth, stack, + diagnostic_stack or stack) + if value is _COMPONENT_UNSUPPORTED: + target = diagnostic_stack or stack + if target is not None: + target.components_unknown = True + raise UnsupportedItemComponents(target) + raise ValueError('unsupported data component {}'.format(name)) + components[name] = value + if stack is not None: + stack.components[name] = value + for _ in range(negative_count): + component_id = VarInt.read(file_object) + removed.append(_component_name(component_id, context) or component_id) + if stack is not None: + stack.removed_components.extend(removed) + return components, removed + + +def read_item_stack(file_object, context=None): + count = VarInt.read(file_object) + if count == 0: + return ItemStackData() + item_id = VarInt.read(file_object) + stack = ItemStackData(True, item_id, count) + try: + stack.components, stack.removed_components = _read_component_patch( + file_object, context, stack=stack, diagnostic_stack=stack) + except UnsupportedItemComponents: + stack.components_unknown = True + raise + return stack + + +class ContainerSetContentPacket(Packet): + id = 0x12 + packet_name = "container set content" + + def read(self, file_object): + self.container_id = VarInt.read(file_object) + self.state_id = VarInt.read(file_object) + self.items = [] + self.partial = False + for _ in range(VarInt.read(file_object)): + try: + self.items.append(read_item_stack(file_object, self.context)) + except UnsupportedItemComponents as exc: + self.items.append(exc.stack) + self.partial = True + self.carried_item = ItemStackData() + return + try: + self.carried_item = read_item_stack(file_object, self.context) + except UnsupportedItemComponents as exc: + self.carried_item = exc.stack + self.partial = True + + +class ContainerSetSlotPacket(Packet): + id = 0x14 + packet_name = "container set slot" + + def read(self, file_object): + self.container_id = VarInt.read(file_object) + self.state_id = VarInt.read(file_object) + self.slot = Short.read(file_object) + try: + self.item = read_item_stack(file_object, self.context) + except UnsupportedItemComponents as exc: + self.item = exc.stack + + +class SetCursorItemPacket(Packet): + id = 0x62 + packet_name = "set cursor item" + + def read(self, file_object): + try: + self.item = read_item_stack(file_object, self.context) + except UnsupportedItemComponents as exc: + self.item = exc.stack + + +class ForgetChunkPacket(Packet): + id = 0x26 + packet_name = "forget chunk" + + def read(self, file_object): + packed = Long.read(file_object) + self.x = packed >> 32 + z = packed & 0xFFFFFFFF + self.z = z if z < 0x80000000 else z - 0x100000000 + + +class ChunkCacheCenterPacket(Packet): + id = 0x60 + packet_name = "chunk cache center" + + def read(self, file_object): + self.x = read_signed_varint(file_object) + self.z = read_signed_varint(file_object) + + +class ChunkCacheRadiusPacket(Packet): + id = 0x61 + packet_name = "chunk cache radius" + definition = [{'radius': VarInt}] + + class KeepAlive(Packet): id = 0x1C packet_name = "keep alive" @@ -157,7 +706,7 @@ class TeleportPosition(Packet): {'teleport_id': VarInt}, {'x': Double}, {'y': Double}, {'z': Double}, {'velocity_x': Double}, {'velocity_y': Double}, {'velocity_z': Double}, - {'yaw': Float}, {'pitch': Float}, + {'yaw': Float}, {'pitch': Float}, {'relative_flags': Integer}, ] @@ -171,6 +720,26 @@ class TeleportConfirm(Packet): ] +class ClientTickEnd(Packet): + id = 0x0D + packet_name = "client tick end" + definition = [] + + +class PlayerPositionRotation(Packet): + id = 0x1F + packet_name = "move player position and rotation" + definition = [ + {'x': Double}, {'y': Double}, {'z': Double}, + {'yaw': Float}, {'pitch': Float}, {'flags': Byte}, + ] + + def __init__(self, x, y, z, yaw, pitch, on_ground=True, + horizontal_collision=False): + flags = (1 if on_ground else 0) | (2 if horizontal_collision else 0) + super().__init__(x=x, y=y, z=z, yaw=yaw, pitch=pitch, flags=flags) + + class AnonymousNBT(Type): """Minecraft's unnamed NBT root used by chat components since 1.20.5.""" @staticmethod @@ -189,7 +758,23 @@ class PlayLogin(Packet): packet_name = "play login" def read(self, file_object): - self.payload = file_object.read() + self.player_id = Integer.read(file_object) + self.hardcore = Boolean.read(file_object) + self.levels = [String.read(file_object) + for _ in range(VarInt.read(file_object))] + self.max_players = VarInt.read(file_object) + self.chunk_radius = VarInt.read(file_object) + self.simulation_distance = VarInt.read(file_object) + self.reduced_debug_info = Boolean.read(file_object) + self.show_death_screen = Boolean.read(file_object) + self.do_limited_crafting = Boolean.read(file_object) + self.dimension_type_id = VarInt.read(file_object) + self.dimension = String.read(file_object) + # Names retained by the legacy Game adapter while its packet handlers + # are migrated to 26.3. + self.entity_id = self.player_id + self.world_name = self.dimension + self.render_distance = self.chunk_radius class PlayDisconnect(Packet): @@ -204,6 +789,33 @@ class ChatCommand(Packet): definition = [{'command': String}] +class ClientboundPlayerChatPacket(Packet): + id = 0x42 + packet_name = "player chat" + + def read(self, file_object): + self.global_index = VarInt.read(file_object) + self.sender = UUID.read(file_object) + self.index = VarInt.read(file_object) + if Boolean.read(file_object): + file_object.read(256) + self.message = String.read(file_object) + + +class ServerboundChatPacket(Packet): + id = 0x09 + packet_name = "chat message" + + def write_fields(self, packet_buffer): + String.send(self.message, packet_buffer) + Long.send(self.timestamp, packet_buffer) + Long.send(0, packet_buffer) # unsigned-chat salt + Boolean.send(False, packet_buffer) # no signature + VarInt.send(0, packet_buffer) # last-seen message offset + packet_buffer.send(b'\x00\x00\x00') # 20-bit acknowledgement set + Byte.send(0, packet_buffer) # checksum (ignored with empty acknowledgements) + + class AuthMeDialogAction(Packet): packet_name = "AuthMe dialog action" action_id = None @@ -259,9 +871,6 @@ class PlayShowDialog(Packet): def read(self, file_object): self.payload = file_object.read() - # Length-prefixed optional NBT payload: an End tag represents None. - VarInt.send(1, packet_buffer) - packet_buffer.send(b'\x00') class ModernLoginReactor(PacketReactor): @@ -295,7 +904,7 @@ class ModernConfigurationReactor(PacketReactor): @staticmethod def get_clientbound_packets(_context): return {FinishConfiguration, ConfigurationKeepAlive, SelectKnownPacks, - ConfigurationCustomPayload, CodeOfConduct} + ConfigurationCustomPayload, CodeOfConduct, RegistryData} def react(self, packet): if packet.packet_name == 'base': @@ -303,6 +912,19 @@ class ModernConfigurationReactor(PacketReactor): elif packet.packet_name == "configuration custom payload": trace('configuration payload channel={!r} bytes={}'.format( packet.channel, len(packet.data))) + elif packet.packet_name == "registry data": + trace('received registry {} ({} entries)'.format( + packet.registry, len(packet.entries))) + registry_ids = getattr(self.connection, 'registry_ids', {}) + registry_ids[packet.registry] = { + key: index for index, (key, _value) in enumerate(packet.entries) + } + self.connection.registry_ids = registry_ids + self.connection.context.registry_ids = registry_ids + if packet.registry == 'minecraft:dimension_type': + self.connection.dimension_types_by_id = [ + value or {} for _, value in packet.entries + ] elif packet.packet_name == "code of conduct": print('[server AuthMe registration dialog] ' + packet.dialog_text, flush=True) try: @@ -335,8 +957,18 @@ class ModernConfigurationReactor(PacketReactor): class ModernPlayingReactor(PacketReactor): @staticmethod def get_clientbound_packets(_context): - return {KeepAliveClientbound, SystemChat, PlayDisconnect, TeleportPosition, - PlayShowDialog, PlayLogin} + return { + KeepAliveClientbound, SystemChat, PlayDisconnect, TeleportPosition, + PlayShowDialog, PlayLogin, ChunkDataPacket, BlockUpdatePacket, + SectionBlocksUpdatePacket, ForgetChunkPacket, + ChunkCacheCenterPacket, ChunkCacheRadiusPacket, + ClientboundChunkBatchFinished, ClientboundPlayerChatPacket, + AddEntityPacket, RemoveEntitiesPacket, MoveEntityPositionPacket, + MoveEntityPositionRotationPacket, MoveEntityRotationPacket, + EntityPositionSyncPacket, PlayerInfoUpdatePacket, + PlayerInfoRemovePacket, ContainerSetContentPacket, + ContainerSetSlotPacket, SetCursorItemPacket, + } def react(self, packet): if packet.packet_name == 'base': @@ -346,10 +978,66 @@ class ModernPlayingReactor(PacketReactor): keep_alive_id=packet.keep_alive_id), force=True) elif packet.packet_name == "play login": self.connection.write_packet(PlayerLoaded(), force=True) + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + world_state.player_id = packet.player_id + dimension_types = getattr(self.connection, + 'dimension_types_by_id', []) + dimension_type = (dimension_types[packet.dimension_type_id] + if packet.dimension_type_id < len(dimension_types) + else None) + world_state.set_dimension(packet.dimension, dimension_type) + elif packet.packet_name == "chunk data": + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + world_state.load_chunk(packet) + if os.getenv('PYCRAFT_TRACE_CHUNKS'): + trace('cached chunk {},{} ({} sections, {} total)'.format( + packet.x, packet.z, len(packet.sections), + len(world_state.chunks))) + elif packet.packet_name == "block update": + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + pos = packet.location + world_state.set_block_at(pos.x, pos.y, pos.z, + packet.block_state_id) + elif packet.packet_name == "section blocks update": + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + world_state.handle_section_update(packet) + elif packet.packet_name == "forget chunk": + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + world_state.unload_chunk(packet.x, packet.z) + elif packet.packet_name == "chunk cache center": + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + world_state.center = (packet.x, packet.z) + elif packet.packet_name == "chunk cache radius": + world_state = getattr(self.connection, 'world_state', None) + if world_state is not None: + world_state.radius = packet.radius + elif packet.packet_name == "chunk batch finished": + self.connection.write_packet(ChunkBatchReceived( + desired_chunks_per_tick=8.0), force=True) + elif packet.packet_name == "player chat": + pass elif packet.packet_name == "player position and look": + previous = getattr(self.connection, 'player_position', None) + flags = packet.relative_flags + if previous is None: + previous = (0.0, 0.0, 0.0, 0.0, 0.0) + x = packet.x + (previous[0] if flags & 1 else 0.0) + y = packet.y + (previous[1] if flags & 2 else 0.0) + z = packet.z + (previous[2] if flags & 4 else 0.0) + yaw = packet.yaw + (previous[3] if flags & 8 else 0.0) + pitch = packet.pitch + (previous[4] if flags & 16 else 0.0) + self.connection.player_position = (x, y, z, yaw, pitch) + trace('teleport id={} relative=0x{:x} absolute=({:.3f}, {:.3f}, {:.3f}, {:.1f}, {:.1f})'.format( + packet.teleport_id, flags, x, y, z, yaw, pitch)) self.connection.write_packet(TeleportConfirm( - teleport_id=packet.teleport_id, x=packet.x, y=packet.y, - z=packet.z, yaw=packet.yaw, pitch=packet.pitch), force=True) + teleport_id=packet.teleport_id, x=x, y=y, z=z, + yaw=yaw, pitch=pitch), force=True) elif packet.packet_name == "show dialog": # Dialog actions are handled by the application so it can choose # a text command or other AuthMe flow. @@ -357,4 +1045,4 @@ class ModernPlayingReactor(PacketReactor): elif packet.packet_name == "disconnect": print('[server disconnect] ' + json.dumps( nbt_plain(packet.reason), ensure_ascii=False), flush=True) - self.connection.disconnect() + self.connection.disconnect(immediate=True)