{
 "site": "https://mc-packet-reference.netlify.app",
 "version": "1.8.9",
 "count": 28,
 "classes": [
  {
   "slug": "EntityPlayerSP",
   "title": "EntityPlayerSP",
   "rel": "net/minecraft/client/entity/EntityPlayerSP.java",
   "desc": "Client player entity: emits C03 movement, C0A swings, C0B actions and C0C input every tick from onUpdateWalkingPlayer.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/EntityPlayerSP/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/client/entity/EntityPlayerSP.java",
   "packets": [
    "C01PacketChatMessage",
    "C03PacketPlayer",
    "C07PacketPlayerDigging",
    "C0APacketAnimation",
    "C0BPacketEntityAction",
    "C0CPacketInput",
    "C0DPacketCloseWindow",
    "C13PacketPlayerAbilities",
    "C16PacketClientStatus"
   ],
   "peers": [
    "NetHandlerPlayClient",
    "Minecraft",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "World",
    "PlayerControllerMP"
   ],
   "analysis": {
    "overview": "Client-side local player (extends AbstractClientPlayer). Predicts movement, health, input each tick. Tick flow: onUpdate (riding vs walk) -> onUpdateWalkingPlayer + onLivingUpdate (sprint, fly, portal). Bridges Minecraft, MovementInput and NetHandlerPlayClient sendQueue for all C packets.",
    "methods": [
     {
      "detail": "Checks isBlockLoaded at player XZ. If riding sends C05 look + C0C input each tick. Else calls onUpdateWalkingPlayer. Calls super.onUpdate for entity physics first.",
      "name": "onUpdate",
      "packets": [
       "C03_C05",
       "C0C"
      ],
      "purpose": "Per-tick client update; delegates to walk or riding branch."
     },
     {
      "detail": "Compares isSprinting/isSneaking to serverSprint/SneakState, sends C0B on change. Computes dPos>9.0E-4 or ticks>=20 (flag2) and yaw/pitch delta (flag3) to pick C06/C04/C05/base C03.",
      "name": "onUpdateWalkingPlayer",
      "packets": [
       "C0B",
       "C03",
       "C03_C04",
       "C03_C05",
       "C03_C06"
      ],
      "purpose": "Sends sprint/sneak deltas and throttled position/look updates."
     },
     {
      "detail": "Decrements sprintingTicksLeft/sprintToggleTimer/timeUntilPortal. Manages double-tap-W sprint, flyToggleTimer double-space + sendPlayerAbilities, horseJumpPowerCounter charging with sendHorseJump.",
      "name": "onLivingUpdate",
      "packets": [
       "C13",
       "C0B"
      ],
      "purpose": "Handles sprint timers, fly toggle, horse jump, portal, push-out."
     },
     {
      "detail": "No filtering; wraps string in C01PacketChatMessage and queues on sendQueue. Server NetHandlerPlayServer handles commands vs broadcast.",
      "name": "sendChatMessage",
      "packets": [
       "C01"
      ],
      "purpose": "Forwards user chat to server."
     },
     {
      "detail": "Calls super.swingItem for client render, then sends empty C0APacketAnimation. Used for attacks, block hits, item use visuals.",
      "name": "swingItem",
      "packets": [
       "C0A"
      ],
      "purpose": "Local arm swing plus server animation notify."
     },
     {
      "detail": "Maps dropAll bool to DROP_ALL_ITEMS vs DROP_ITEM action with BlockPos.ORIGIN/DOWN. Returns null; server spawns EntityItem.",
      "name": "dropOneItem",
      "packets": [
       "C07"
      ],
      "purpose": "Requests server item drop; no client spawn."
     },
     {
      "detail": "Sends C0DPacketCloseWindow with openContainer.windowId, then clears cursor stack and displays null screen via closeScreenAndDropStack.",
      "name": "closeScreen",
      "packets": [
       "C0D"
      ],
      "purpose": "Notifies server container close."
     },
     {
      "detail": "Wraps this.capabilities in C13PacketPlayerAbilities. Called on fly toggle, landing, spectator transitions in onLivingUpdate.",
      "name": "sendPlayerAbilities",
      "packets": [
       "C13"
      ],
      "purpose": "Syncs capabilities (fly, creative) to server."
     },
     {
      "detail": "Sends C16 with PERFORM_RESPAWN state. Server respawns via configuration manager and resets health/location.",
      "name": "respawnPlayer",
      "packets": [
       "C16"
      ],
      "purpose": "Requests respawn after death screen."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "C01",
      "trigger": "User sends chat via sendChatMessage."
     },
     {
      "direction": "sent",
      "id": "C03",
      "trigger": "Forced keep-alive every tick when pos/look unchanged; also riding look."
     },
     {
      "direction": "sent",
      "id": "C07",
      "trigger": "Q drop key via dropOneItem."
     },
     {
      "direction": "sent",
      "id": "C0A",
      "trigger": "Arm swing via swingItem."
     },
     {
      "direction": "sent",
      "id": "C0B",
      "trigger": "Sprint/sneak toggle, horse jump/inventory."
     },
     {
      "direction": "sent",
      "id": "C0C",
      "trigger": "Riding input each tick in onUpdate."
     },
     {
      "direction": "sent",
      "id": "C0D",
      "trigger": "Closing container screen."
     },
     {
      "direction": "sent",
      "id": "C13",
      "trigger": "Fly state change in onLivingUpdate."
     },
     {
      "direction": "sent",
      "id": "C16",
      "trigger": "Respawn button via respawnPlayer."
     }
    ],
    "internal_fields": [
     {
      "name": "sendQueue",
      "role": "NetHandlerPlayClient used for all addToSendQueue C packets"
     },
     {
      "name": "lastReportedPosX/Y/Z + Yaw/Pitch",
      "role": "Last sent transform; delta vs 9.0E-4 threshold picks packet type"
     },
     {
      "name": "positionUpdateTicks",
      "role": "Forces C03 at least every 20 ticks when idle"
     },
     {
      "name": "serverSprintState/serverSneakState",
      "role": "Caches last C0B state to send only on change"
     },
     {
      "name": "movementInput",
      "role": "Keyboard input driving moveStrafe/Forward/jump/sneak"
     },
     {
      "name": "sprintToggleTimer/sprintingTicksLeft",
      "role": "Double-tap sprint window and sprint expiry timer"
     }
    ],
    "peers": [
     "NetHandlerPlayClient",
     "Minecraft",
     "PlayerControllerMP",
     "MovementInput",
     "AbstractClientPlayer"
    ],
    "methods_detailed": [
     {
      "name": "onUpdate",
      "detail_long": "onUpdate runs every client tick for the local player and first gates on worldObj.isBlockLoaded at BlockPos(posX, 0, posZ) so no packets are sent from unloaded areas. It calls super.onUpdate first to run entity physics, collision, and position integration before any networking decision. If isRiding is true it takes the vehicle branch and does not call onUpdateWalkingPlayer at all. In the riding branch it queues a C03 C05PacketPlayerLook with current rotationYaw, rotationPitch and onGround every tick because the server drives vehicle position. It also queues a C0CPacketInput with moveStrafing, moveForward, movementInput.jump and movementInput.sneak so the server can steer the ridden horse, boat, pig or minecart. If not riding it delegates to onUpdateWalkingPlayer which owns the on-foot C03 family and C0B throttling. This split prevents double-sending position while riding and explains why ground-spoof and blink cheats hook the on-foot path. The receiver NetHandlerPlayServer validates look and input and applies them to the riding entity rather than the player.",
      "code": "    public void onUpdate()\n    {\n        if (this.worldObj.isBlockLoaded(new BlockPos(this.posX, 0.0D, this.posZ)))\n        {\n            super.onUpdate();\n\n            if (this.isRiding())\n            {\n                this.sendQueue.addToSendQueue(new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, this.rotationPitch, this.onGround));\n                this.sendQueue.addToSendQueue(new C0CPacketInput(this.moveStrafing, this.moveForward, this.movementInput.jump, this.movementInput.sneak));\n            }\n            else\n            {\n                this.onUpdateWalkingPlayer();\n            }\n        }\n    }",
      "code_walkthrough": "The isBlockLoaded guard stops updates when the player column is unloaded, preventing desync packets from void or unloaded chunks. super.onUpdate runs shared EntityLivingBase physics before networking so sent values reflect the new tick. The isRiding branch constructs C05PacketPlayerLook from live yaw, pitch and onGround, telling the server where the rider looks while the vehicle moves. The next line constructs C0CPacketInput from strafe, forward, jump and sneak, which is the only channel for steering ridden entities. The else calls onUpdateWalkingPlayer for the on-foot C03 and C0B logic, so suppressing either queue call creates a blink-like stall that the server later corrects."
     },
     {
      "name": "onUpdateWalkingPlayer",
      "detail_long": "onUpdateWalkingPlayer compares live isSprinting against cached serverSprintState and live isSneaking against serverSneakState, sending C0BPacketEntityAction START or STOP only on a flip to save bandwidth. It then gates all position traffic on isCurrentViewEntity so only the camera entity transmits, ignoring other render-view switches. It computes d0, d1 from posX and boundingBox.minY minus lastReported, d2 from posZ, and d3, d4 from yaw and pitch deltas. It sets flag2 when squared positional delta exceeds 9.0E-4D or positionUpdateTicks reaches 20, forcing a keep-alive at least once per second. It sets flag3 when yaw or pitch changed at all, then picks C06 pos-look when both moved, C04 position when only moved, C05 look when only rotated, else bare C03 onGround keep-alive. When ridingEntity is non-null it sends a special C06 with motionX, -999.0D Y and motionZ as a stall marker and forces flag2 false. Finally it increments positionUpdateTicks, and on flag2 or flag3 copies current pos and angles into lastReported fields and zeroes the tick counter, which is the state blink freezes.",
      "code": "        if (this.isCurrentViewEntity())\n        {\n            double d0 = this.posX - this.lastReportedPosX;\n            double d1 = this.getEntityBoundingBox().minY - this.lastReportedPosY;\n            double d2 = this.posZ - this.lastReportedPosZ;\n            double d3 = (double)(this.rotationYaw - this.lastReportedYaw);\n            double d4 = (double)(this.rotationPitch - this.lastReportedPitch);\n            boolean flag2 = d0 * d0 + d1 * d1 + d2 * d2 > 9.0E-4D || this.positionUpdateTicks >= 20;\n            boolean flag3 = d3 != 0.0D || d4 != 0.0D;\n\n            if (this.ridingEntity == null)\n            {\n                if (flag2 && flag3)\n                {\n                    this.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.rotationYaw, this.rotationPitch, this.onGround));\n                }\n                else if (flag2)\n                {\n                    this.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.onGround));\n                }\n                else if (flag3)\n                {\n                    this.sendQueue.addToSendQueue(new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, this.rotationPitch, this.onGround));\n                }\n                else\n                {\n                    this.sendQueue.addToSendQueue(new C03PacketPlayer(this.onGround));\n                }\n            }\n            else\n            {\n                this.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(this.motionX, -999.0D, this.motionZ, this.rotationYaw, this.rotationPitch, this.onGround));",
      "code_walkthrough": "The d0 through d4 lines snapshot how far position and look drifted since the last transmitted report, using boundingBox.minY for the feet Y the server validates. flag2 applies the 9.0E-4D squared-distance threshold plus the 20-tick forced update, which is why standing still still sends a bare C03 once per second. flag3 fires on any yaw or pitch delta, separating look-only C05 traffic from movement. The four-way if chain maps the two booleans to C06, C04, C05 or base C03, each carrying the onGround boolean the server uses for fall damage, so spoofing that bit is ground-spoof. The riding branch with -999.0D Y signals the server not to apply on-foot movement, and freezing these queues while continuing to render locally is exactly a blink exploit."
     },
     {
      "name": "onLivingUpdate",
      "detail_long": "onLivingUpdate runs before physics each tick and first decrements sprintingTicksLeft, sprintToggleTimer and timeUntilPortal so sprint expiry, double-tap windows and portal cooldowns age correctly. It handles double-tap-W sprint by setting sprintToggleTimer to 7 on first tap and calling setSprinting true on second tap within the window, gated on food above 6, allowFlying, onGround and not using an item or blinded. It handles the sprint key, sprint cancel on slowdown or collision, and slows movementInput by 0.2 while using an item. For flight it forces isFlying true in spectator mode with a C13 send, and detects double-space via flyToggleTimer 7 to toggle capabilities.isFlying and call sendPlayerAbilities which emits C13PacketPlayerAbilities. It manages horse jump charging with horseJumpPowerCounter from -10 through 10, sending C0B RIDING_JUMP on release and computing power up to 0.8 plus curve, plus horse inventory via C0B OPEN_INVENTORY. On landing while flying in non-spectator it clears isFlying and re-sends C13, and it accumulates timeInPortal toward 1.0 for dimension travel. The server NetHandlerPlayServer re-validates abilities and jump power, so forged C13 or C0B values are the classic fly and horse-jump cheat vectors.",
      "code": "        if (this.capabilities.allowFlying)\n        {\n            if (this.mc.playerController.isSpectatorMode())\n            {\n                if (!this.capabilities.isFlying)\n                {\n                    this.capabilities.isFlying = true;\n                    this.sendPlayerAbilities();\n                }\n            }\n            else if (!flag && this.movementInput.jump)\n            {\n                if (this.flyToggleTimer == 0)\n                {\n                    this.flyToggleTimer = 7;\n                }\n                else\n                {\n                    this.capabilities.isFlying = !this.capabilities.isFlying;\n                    this.sendPlayerAbilities();\n                    this.flyToggleTimer = 0;\n                }\n            }\n        }\n\n        if (this.capabilities.isFlying && this.isCurrentViewEntity())\n        {\n            if (this.movementInput.sneak)\n            {\n                this.motionY -= (double)(this.capabilities.getFlySpeed() * 3.0F);\n            }",
      "code_walkthrough": "The allowFlying outer gate ensures only creative or spectator clients can enter the toggle logic, otherwise no C13 is produced here. The spectator inner branch forces isFlying true and calls sendPlayerAbilities, which queues C13 with the full capabilities object for server approval. The double-space detector uses flyToggleTimer 7 ticks to distinguish a tap from a hold, flipping isFlying and re-sending C13 on the second press. The isFlying plus isCurrentViewEntity block then applies flySpeed vertical motion locally, so a forged C13 that enables flying without permission lets the client move vertically until the server corrects it."
     },
     {
      "name": "sendChatMessage",
      "detail_long": "sendChatMessage takes the raw string from the chat GUI or command line with no client-side filtering, length splitting or command parsing. It wraps the string verbatim in a new C01PacketChatMessage and adds it to sendQueue via addToSendQueue for TCP flush. It does not distinguish slash commands from public chat, leaving that decision to NetHandlerPlayServer on the receiving side. The server then routes slash-prefixed text to the command dispatcher and other text to broadcast with spam and visibility checks. Because the client sends the full string, server plugins see the exact typed content including formatting codes. Dropping or mutating this packet silences the player, while flooding it is chat spam. No other packet is emitted here, so chat has no movement or inventory side effects.",
      "code": "    public void sendChatMessage(String message)\n    {\n        this.sendQueue.addToSendQueue(new C01PacketChatMessage(message));\n    }\n\n    /**\n     * Swings the item the player is holding.\n     */\n    public void swingItem()\n    {\n        super.swingItem();\n        this.sendQueue.addToSendQueue(new C0APacketAnimation());\n    }\n\n    public void respawnPlayer()\n    {\n        this.sendQueue.addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN));\n    }",
      "code_walkthrough": "The single addToSendQueue line shows the entire method body, constructing C01PacketChatMessage directly from the message argument with no rewrite. sendQueue is the NetHandlerPlayClient channel to the server, so the text leaves the client in one TCP packet. The neighboring swingItem and respawnPlayer snippets show the same one-line queue pattern for C0A and C16, confirming this class delegates all authority to the server. If this C01 is blocked the server never sees chat, and if forged at high rate the server throttle or kick applies."
     },
     {
      "name": "swingItem",
      "detail_long": "swingItem first calls super.swingItem to run the client-side arm swing timer and render animation immediately without waiting for the server. It then constructs an empty C0APacketAnimation with no entity ID or hand argument, because 1.8.9 has a single swing type inferred from the sender. It queues that packet on sendQueue so the server and then other clients via S0B animation can mirror the motion. It is called for attacks, block hits and item use visuals, decoupling visual feedback from damage outcome. The server uses the C0A arrival time as a heuristic alongside C02 attack and C07 dig packets for anti-cheat timing. Suppressing C0A while still attacking creates silent swings that look like no-animation kill-aura. The receiver NetHandlerPlayServer broadcasts the swing to trackers without changing inventory or health.",
      "code": "    public void swingItem()\n    {\n        super.swingItem();\n        this.sendQueue.addToSendQueue(new C0APacketAnimation());\n    }\n\n    public void respawnPlayer()\n    {\n        this.sendQueue.addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN));\n    }\n\n    /**\n     * Deals damage to the entity. If its a EntityPlayer then will take damage from the armor first and then health\n     * second with the reduced value. Args: damageAmount\n     */",
      "code_walkthrough": "super.swingItem starts the local swingTimer and arm render so the player sees instant feedback before any round trip. The new C0APacketAnimation line carries no fields, the server attributes it to the sending NetHandlerPlayServer connection. addToSendQueue flushes it to the server where it fans out as S0B animation to nearby trackers. Deleting this line keeps local visuals but hides swings from others, a common silent-aim artifact, while spamming it has no damage effect without a paired C02."
     },
     {
      "name": "dropOneItem",
      "detail_long": "dropOneItem maps the boolean dropAll from the Q key handler to a C07PacketPlayerDigging Action enum, choosing DROP_ALL_ITEMS when true and DROP_ITEM for a single item. It constructs the packet with BlockPos.ORIGIN and EnumFacing.DOWN as dummy position and facing values because drops carry no block target. It queues the packet on sendQueue and returns null without spawning any EntityItem client-side, keeping inventory authoritative. The server NetHandlerPlayServer interprets the action, splits or clears the held stack, and spawns the EntityItem itself with pickup delay. Holding Ctrl-Q drives the dropAll path to empty the stack, while tapping Q drops one. Forging this C07 with modified actions is how drop-spam or inventory-desync exploits attempt to duplicate items, but the server re-validates the held stack. No S packet is produced locally here.",
      "code": "    /**\n     * Called when player presses the drop item key\n     */\n    public EntityItem dropOneItem(boolean dropAll)\n    {\n        C07PacketPlayerDigging.Action c07packetplayerdigging$action = dropAll ? C07PacketPlayerDigging.Action.DROP_ALL_ITEMS : C07PacketPlayerDigging.Action.DROP_ITEM;\n        this.sendQueue.addToSendQueue(new C07PacketPlayerDigging(c07packetplayerdigging$action, BlockPos.ORIGIN, EnumFacing.DOWN));\n        return null;\n    }\n\n    /**\n     * Joins the passed in entity item with the world. Args: entityItem\n     */\n    protected void joinEntityItemWithWorld(EntityItem itemIn)\n    {\n    }",
      "code_walkthrough": "The ternary line translates the dropAll boolean into the exact C07 Action enum the server switches on, so the packet meaning hinges on that one enum value. The constructor uses BlockPos.ORIGIN and EnumFacing.DOWN as placeholders because the server ignores position for drop actions, unlike dig actions that need a real block. addToSendQueue sends the request without creating an EntityItem, proving drops are server-authoritative. Returning null signals no local entity to the caller, so blocking the packet means nothing drops and replaying it duplicates drop attempts the server must deduplicate."
     },
     {
      "name": "closeScreen",
      "detail_long": "closeScreen reads openContainer.windowId as the server-assigned container ID so the close refers to the exact chest, furnace or custom GUI. It constructs C0DPacketCloseWindow with that ID and queues it on sendQueue to tell the server the client dismissed the screen. It then calls closeScreenAndDropStack which clears the cursor ItemStack via inventory.setItemStack null, calls super.closeScreen and calls mc.displayGuiScreen null to remove the GUI. The server NetHandlerPlayServer closes its Container on C0D, cancels pending slot transactions and may drop or retain the cursor stack. Sending a wrong windowId desyncs containers and can leave ghost items until the next S2E or S30 resync. This is a pure teardown with no item movement packet, so dupes that race C0E clicks against C0D rely on server ordering here.",
      "code": "    public void closeScreen()\n    {\n        this.sendQueue.addToSendQueue(new C0DPacketCloseWindow(this.openContainer.windowId));\n        this.closeScreenAndDropStack();\n    }\n\n    public void closeScreenAndDropStack()\n    {\n        this.inventory.setItemStack((ItemStack)null);\n        super.closeScreen();\n        this.mc.displayGuiScreen((GuiScreen)null);\n    }\n\n    /**\n     * Updates health locally.\n     */",
      "code_walkthrough": "The C0DPacketCloseWindow constructor captures openContainer.windowId at call time, binding the close to the currently open container instance. addToSendQueue delivers that ID to the server where NetHandlerPlayServer matches it against its own openContainer. closeScreenAndDropStack then nulls the dragged cursor stack and clears the GuiScreen locally, so visuals close even if the packet is delayed. If the C0D is dropped the server keeps the container open and later forces S2E close, which is why inventory-desync fixes always resync windowId."
     },
     {
      "name": "sendPlayerAbilities",
      "detail_long": "sendPlayerAbilities wraps the live this.capabilities object, including isFlying, allowFlying, isCreativeMode, flySpeed and walkSpeed, into a new C13PacketPlayerAbilities. It queues that snapshot on sendQueue with no extra validation, trusting the caller in onLivingUpdate to have flipped the flags correctly for spectator, double-space or landing. It is called when spectator forces flight on, when double-space toggles flight, and when landing clears flight in non-spectator. The server compares the received flags against the authoritative GameType and op state, ignoring or kicking on illegal fly enable. Because the whole capabilities struct is sent, stale walkSpeed or flySpeed values can also leak to the server if mods mutate them. The receiver applies allowed changes and echoes the authoritative state back via S39, so a forged C13 only persists until the next S39 correction.",
      "code": "    /**\n     * Sends the player's abilities to the server (if there is one).\n     */\n    public void sendPlayerAbilities()\n    {\n        this.sendQueue.addToSendQueue(new C13PacketPlayerAbilities(this.capabilities));\n    }\n\n    /**\n     * returns true if this is an EntityPlayerSP, or the logged in player.\n     */\n    public boolean isUser()\n    {\n        return true;\n    }\n\n    protected void sendHorseJump()\n    {\n        this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.RIDING_JUMP, (int)(this.getHorseJumpPower() * 100.0F)));\n    }\n\n    public void sendHorseInventory()\n    {\n        this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.OPEN_INVENTORY));\n    }",
      "code_walkthrough": "The one-line body constructs C13PacketPlayerAbilities from this.capabilities by reference copy, so every flag and speed at call time goes on the wire. addToSendQueue pushes it through NetHandlerPlayClient to NetHandlerPlayServer, which re-checks allowFlying against gamemode. The adjacent sendHorseJump and sendHorseInventory lines show the C0B RIDING_JUMP with power times 100 and OPEN_INVENTORY pattern, distinguishing ability sync from action packets. Tampering with capabilities before this call is the client fly-speed hack, corrected when the server replies with S39."
     },
     {
      "name": "respawnPlayer",
      "detail_long": "respawnPlayer is bound to the death-screen respawn button and takes no position or health arguments because the server owns the spawn point. It constructs C16PacketClientStatus with EnumState.PERFORM_RESPAWN, the dedicated respawn enum distinct from OPEN_INVENTORY statistics states. It queues that packet on sendQueue so NetHandlerPlayServer can trigger ServerConfigurationManager respawn, clearing death, resetting health and food, and teleporting to spawn or bed. The client does not move itself or heal locally here, waiting for S07 respawn, S06 health and S21 chunk packets to rebuild state. Pressing the button twice queues duplicate C16s that the server idempotently ignores if already alive. Blocking this packet leaves the player on the death screen indefinitely, while forging it while alive is ignored by the server state check.",
      "code": "    public void respawnPlayer()\n    {\n        this.sendQueue.addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN));\n    }\n\n    /**\n     * Deals damage to the entity. If its a EntityPlayer then will take damage from the armor first and then health\n     * second with the reduced value. Args: damageAmount\n     */\n    protected void damageEntity(DamageSource damageSrc, float damageAmount)\n    {\n        if (!this.isEntityInvulnerable(damageSrc))\n        {\n            this.setHealth(this.getHealth() - damageAmount);\n        }\n    }\n\n    /**\n     * set current crafting inventory back to the 2x2 square\n     */",
      "code_walkthrough": "The constructor argument PERFORM_RESPAWN selects the respawn branch in NetHandlerPlayServer handleClientStatus, not a generic status update. addToSendQueue sends it over the established play channel, so it only works while connected to a server after death. The following damageEntity snippet shows local health subtraction is separate and not invoked here, proving respawn does not heal client-side. The server responds with position, health and inventory resyncs, so dropping C16 strands the client on the death GUI."
     }
    ]
   }
  },
  {
   "slug": "EntityPlayerMP",
   "title": "EntityPlayerMP",
   "rel": "net/minecraft/entity/player/EntityPlayerMP.java",
   "desc": "Server player entity: health, XP and inventory sync fan out S06, S1F, S2F and S30 packets from onUpdateEntity.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/EntityPlayerMP/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/player/EntityPlayerMP.java",
   "packets": [
    "S02PacketChat",
    "S06PacketUpdateHealth",
    "S0APacketUseBed",
    "S0BPacketAnimation",
    "S13PacketDestroyEntities",
    "S19PacketEntityStatus",
    "S1BPacketEntityAttach",
    "S1DPacketEntityEffect",
    "S1EPacketRemoveEntityEffect",
    "S1FPacketSetExperience",
    "S21PacketChunkData",
    "S26PacketMapChunkBulk",
    "S29PacketSoundEffect",
    "S2BPacketChangeGameState",
    "S2DPacketOpenWindow",
    "S2EPacketCloseWindow",
    "S2FPacketSetSlot",
    "S30PacketWindowItems",
    "S31PacketWindowProperty",
    "S36PacketSignEditorOpen",
    "S39PacketPlayerAbilities",
    "S3FPacketCustomPayload",
    "S42PacketCombatEvent",
    "S43PacketCamera",
    "S48PacketResourcePackSend"
   ],
   "peers": [
    "ServerConfigurationManager",
    "NetHandlerPlayServer",
    "WorldServer",
    "PlayerManager",
    "EntityLivingBase",
    "ItemInWorldManager",
    "PacketBuffer",
    "MathHelper",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "Container"
   ],
   "analysis": {
    "overview": "Server-side player entity (extends EntityPlayer, implements ICrafting). Authoritative inventory, health, chunks, effects. Tick flow: onUpdate (block removal, container sync, destroy cache S13, chunk queue S21/S26) + onUpdateEntity (maps, S06 health, S1F XP). Owned by NetHandlerPlayServer + ItemInWorldManager.",
    "methods": [
     {
      "detail": "Calls theItemInWorldManager.updateBlockRemoving, openContainer.detectAndSendChanges. Drains destroyedItemsNetCache into S13 batches. Streams up to 10 chunks as S21 single or S26 bulk plus tile updates.",
      "name": "onUpdate",
      "packets": [
       "S13",
       "S21",
       "S26"
      ],
      "purpose": "Server tick: block mining, containers, chunk streaming, spectate follow."
     },
     {
      "detail": "Sends map packets for held maps. If health/food/saturation-vs-wasHungry changed sends S06. If experienceTotal != lastExperience sends S1F. Every 100 ticks checks exploreAllBiomes.",
      "name": "onUpdateEntity",
      "packets": [
       "S06",
       "S1F"
      ],
      "purpose": "Syncs maps, health/food, scoreboard, XP, biome achievement."
     },
     {
      "detail": "Closes prior container, checks ILockableContainer lock/canOpen/isSpectator; denies with S02 msg + S29 door sound. Else getNextWindowId and S2D with size.",
      "name": "displayGUIChest",
      "packets": [
       "S02",
       "S29",
       "S2D"
      ],
      "purpose": "Opens chest/locked container with validation."
     },
     {
      "detail": "Creates ContainerMerchant, assigns windowId, sends S2D minecraft:villager then MC|TrList S3F custom payload with windowId + MerchantRecipeList buffer.",
      "name": "displayVillagerTradeGui",
      "packets": [
       "S2D",
       "S3F"
      ],
      "purpose": "Opens merchant plus recipe list."
     },
     {
      "detail": "Sends S2EPacketCloseWindow with openContainer.windowId then closeContainer resets to inventoryContainer. Called when canInteractWith fails.",
      "name": "closeScreen",
      "packets": [
       "S2E"
      ],
      "purpose": "Server-initiated container close."
     },
     {
      "detail": "Guards playerNetServerHandler null, sends S39 with capabilities then updatePotionMetadata. Called by setGameType and spectator changes.",
      "name": "sendPlayerAbilities",
      "packets": [
       "S39"
      ],
      "purpose": "Pushes capabilities to client."
     },
     {
      "detail": "Sets ItemInWorldManager type, sends S2B reason 3 with type ID. Dismounts if spectator else setSpectatingEntity(self), then abilities + markPotionsDirty.",
      "name": "setGameType",
      "packets": [
       "S2B",
       "S39"
      ],
      "purpose": "Changes gamemode and reconciles spectator state."
     },
     {
      "detail": "trySleep sends S0A to trackers + self and setPlayerLocation. wakeUp broadcasts S0B anim 2. mountEntity sends S1B attach 0 then setPlayerLocation.",
      "name": "trySleep/wakeUpPlayer/mountEntity",
      "packets": [
       "S0A",
       "S0B",
       "S1B"
      ],
      "purpose": "Broadcasts bed, wake, ride state and resyncs position."
     },
     {
      "detail": "Sends S1D EntityEffect with entityId+effect on add/change, S1E RemoveEntityEffect on finish. Ensures client particles/modifiers match.",
      "name": "onNewPotionEffect/onFinishedPotionEffect",
      "packets": [
       "S1D",
       "S1E"
      ],
      "purpose": "Syncs effect add/change/remove to client."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S02",
      "trigger": "Chat/system messages and locked-container denial."
     },
     {
      "direction": "sent",
      "id": "S06",
      "trigger": "Health/food/saturation change in onUpdateEntity."
     },
     {
      "direction": "sent",
      "id": "S13",
      "trigger": "Batched destroy cache flush in onUpdate; removeEntity for non-players."
     },
     {
      "direction": "sent",
      "id": "S19",
      "trigger": "Eating finish broadcast in onItemUseFinish."
     },
     {
      "direction": "sent",
      "id": "S1B",
      "trigger": "Mount/dismount in mountEntity."
     },
     {
      "direction": "sent",
      "id": "S1D",
      "trigger": "Potion add/change."
     },
     {
      "direction": "sent",
      "id": "S1E",
      "trigger": "Potion finish."
     },
     {
      "direction": "sent",
      "id": "S1F",
      "trigger": "XP total change in onUpdateEntity."
     },
     {
      "direction": "sent",
      "id": "S21/S26",
      "trigger": "Queued chunk delivery in onUpdate."
     },
     {
      "direction": "sent",
      "id": "S2B",
      "trigger": "Dimension/end events and gamemode change."
     },
     {
      "direction": "sent",
      "id": "S2D",
      "trigger": "Container/horse/villager GUI open."
     },
     {
      "direction": "sent",
      "id": "S39",
      "trigger": "Abilities push in sendPlayerAbilities."
     },
     {
      "direction": "sent",
      "id": "S43",
      "trigger": "Spectate target change."
     },
     {
      "direction": "sent",
      "id": "S48",
      "trigger": "Server resource-pack request."
     }
    ],
    "internal_fields": [
     {
      "name": "playerNetServerHandler",
      "role": "NetHandlerPlayServer sink for all sendPacket S messages"
     },
     {
      "name": "theItemInWorldManager",
      "role": "Gamemode/mining logic; back-pointer thisPlayerMP"
     },
     {
      "name": "lastHealth/lastFoodLevel/wasHungry",
      "role": "Dirty check to throttle S06 health sends"
     },
     {
      "name": "lastExperience/combinedHealth",
      "role": "Dirty checks for S1F XP and health scoreboard"
     },
     {
      "name": "loadedChunks/destroyedItemsNetCache",
      "role": "Queues for S21/S26 chunk send and batched S13 destroys"
     },
     {
      "name": "currentWindowId/spectatingEntity",
      "role": "Window counter (%100+1) for S2D and camera target for S43"
     }
    ],
    "peers": [
     "NetHandlerPlayServer",
     "ItemInWorldManager",
     "MinecraftServer",
     "WorldServer",
     "EntityTracker",
     "StatisticsFile"
    ],
    "methods_detailed": [
     {
      "name": "onUpdate",
      "detail_long": "onUpdate is the server per-tick driver that first calls theItemInWorldManager.updateBlockRemoving to progress survival mining cracks and creative breaks. It decrements respawnInvulnerabilityTicks and hurtResistantTime, then calls openContainer.detectAndSendChanges to push S2F, S30 and S31 slot deltas for the open GUI. If the open container no longer passes canInteractWith it forces closeScreen plus inventoryContainer reset to prevent out-of-range crafting. It then drains destroyedItemsNetCache in Integer.MAX_VALUE batches into S13PacketDestroyEntities so batched entity removals leave in one packet rather than spamming. It streams up to 10 queued loadedChunks per tick, checking isBlockLoaded and isPopulated, collecting tile entities for description packets and notifying the tracker. Single chunks go as S21PacketChunkData with mask 65535 while multiples go as S26PacketMapChunkBulk for bandwidth efficiency. Spectator follow at the end repositions the player to the spectated entity and calls serverUpdateMountedMovingPlayer.",
      "code": "        while (!this.destroyedItemsNetCache.isEmpty())\n        {\n            int i = Math.min(this.destroyedItemsNetCache.size(), Integer.MAX_VALUE);\n            int[] aint = new int[i];\n            Iterator<Integer> iterator = this.destroyedItemsNetCache.iterator();\n            int j = 0;\n\n            while (iterator.hasNext() && j < i)\n            {\n                aint[j++] = ((Integer)iterator.next()).intValue();\n                iterator.remove();\n            }\n\n            this.playerNetServerHandler.sendPacket(new S13PacketDestroyEntities(aint));\n        }\n\n        if (!this.loadedChunks.isEmpty())\n        {\n            List<Chunk> list = Lists.<Chunk>newArrayList();\n            Iterator<ChunkCoordIntPair> iterator1 = this.loadedChunks.iterator();\n            List<TileEntity> list1 = Lists.<TileEntity>newArrayList();\n            while (iterator1.hasNext() && ((List)list).size() < 10)\n            {\n                ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair)iterator1.next();",
      "code_walkthrough": "The while loop drains destroyedItemsNetCache with an iterator remove, packing IDs into an int array sized to the queue length for one S13. sendPacket through playerNetServerHandler delivers the destroy batch only to this player, not a broadcast, and non-player removes are batched while player removes send immediately via removeEntity. The loadedChunks guard then builds a max-10 list per tick, throttling chunk bandwidth to avoid flooding the client on login or teleport. This batching is why mass mob clears arrive as few S13s and why chunk streaming staggers as S21 or S26 over multiple ticks."
     },
     {
      "name": "onUpdateEntity",
      "detail_long": "onUpdateEntity runs after onUpdate and wraps everything in a crash-report context labeled Ticking player for debuggability. It first calls super.onUpdate for base entity aging and then scans the entire inventory for ItemStacks whose item isMap, calling createMapDataPacket for each held map and sending any non-null result directly. It compares live getHealth, foodStats.getFoodLevel and saturation-zero versus cached lastHealth, lastFoodLevel and wasHungry, sending S06PacketUpdateHealth only on a real delta to throttle health traffic. On send it copies current health, food and hungry flag into the caches so the next tick can detect the next change. It separately tracks combinedHealth as health plus absorption for scoreboard health objectives without spamming S06. It compares experienceTotal to lastExperience and on change sends S1FPacketSetExperience with experience, experienceTotal and experienceLevel progress. Every 20 times 5 ticks it checks exploreAllBiomes progress, which can later trigger achievements without extra packets here.",
      "code": "    public void onUpdateEntity()\n    {\n        try\n        {\n            super.onUpdate();\n\n            for (int i = 0; i < this.inventory.getSizeInventory(); ++i)\n            {\n                ItemStack itemstack = this.inventory.getStackInSlot(i);\n\n                if (itemstack != null && itemstack.getItem().isMap())\n                {\n                    Packet packet = ((ItemMapBase)itemstack.getItem()).createMapDataPacket(itemstack, this.worldObj, this);\n\n                    if (packet != null)\n                    {\n                        this.playerNetServerHandler.sendPacket(packet);\n                    }\n                }\n            }\n\n            if (this.getHealth() != this.lastHealth || this.lastFoodLevel != this.foodStats.getFoodLevel() || this.foodStats.getSaturationLevel() == 0.0F != this.wasHungry)\n            {\n                this.playerNetServerHandler.sendPacket(new S06PacketUpdateHealth(this.getHealth(), this.foodStats.getFoodLevel(), this.foodStats.getSaturationLevel()));\n                this.lastHealth = this.getHealth();\n                this.lastFoodLevel = this.foodStats.getFoodLevel();\n                this.wasHungry = this.foodStats.getSaturationLevel() == 0.0F;\n            }\n\n            if (this.getHealth() + this.getAbsorptionAmount() != this.combinedHealth)",
      "code_walkthrough": "The inventory loop checks every slot for isMap and calls createMapDataPacket, which returns null when the map has no dirty columns, explaining intermittent map traffic. The health if compares three cached fields at once so saturation flipping to zero alone triggers S06 even if health and food are static. The S06 constructor carries health, food level and saturation that the client applies in setPlayerSPHealth, so suppressing it desyncs hearts. Updating lastHealth, lastFoodLevel and wasHungry right after send implements the throttle, and the following combinedHealth check drives scoreboards without extra network cost."
     },
     {
      "name": "displayGUIChest",
      "detail_long": "displayGUIChest first closes any mismatched openContainer to avoid stacking windows, then checks for ILockableContainer with isLocked, canOpen lock code and isSpectator bypass. On denial it sends S02PacketChat with container.isLocked as type 2 above-hotbar message and S29PacketSoundEffect random.door_close at the player position, then returns without opening. On success it calls getNextWindowId which cycles currentWindowId modulo 100 plus 1 for the next S2D ID. If the inventory is an IInteractionObject it sends S2DPacketOpenWindow with that ID, the GUI ID string, display name and size, else it falls back to minecraft:container with a new ContainerChest. It then assigns openContainer.windowId to the new ID and calls onCraftGuiOpened to register this as ICrafting for S2F and S30 updates. The client uses the windowId to route all future C0E clicks, so a stale ID breaks container interaction until S2E close resyncs.",
      "code": "            if (ilockablecontainer.isLocked() && !this.canOpen(ilockablecontainer.getLockCode()) && !this.isSpectator())\n            {\n                this.playerNetServerHandler.sendPacket(new S02PacketChat(new ChatComponentTranslation(\"container.isLocked\", new Object[] {chestInventory.getDisplayName()}), (byte)2));\n                this.playerNetServerHandler.sendPacket(new S29PacketSoundEffect(\"random.door_close\", this.posX, this.posY, this.posZ, 1.0F, 1.0F));\n                return;\n            }\n        }\n\n        this.getNextWindowId();\n\n        if (chestInventory instanceof IInteractionObject)\n        {\n            this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getDisplayName(), chestInventory.getSizeInventory()));\n            this.openContainer = ((IInteractionObject)chestInventory).createContainer(this.inventory, this);\n        }\n        else\n        {\n            this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, \"minecraft:container\", chestInventory.getDisplayName(), chestInventory.getSizeInventory()));\n            this.openContainer = new ContainerChest(this.inventory, chestInventory, this);\n        }\n\n        this.openContainer.windowId = this.currentWindowId;\n        this.openContainer.onCraftGuiOpened(this);",
      "code_walkthrough": "The isLocked plus canOpen plus isSpectator condition gates locked chests, letting spectators bypass the lock without a key. The S02 line builds a type-2 chat that renders above the hotbar instead of in chat history, carrying the locked-container translation. The S29 line plays door_close only to this player at their coordinates with volume 1 and pitch 1. The S2D lines bind currentWindowId to the GUI type and size, so the client opens the matching GuiChest or furnace screen and routes C0E clicks by that ID."
     },
     {
      "name": "displayVillagerTradeGui",
      "detail_long": "displayVillagerTradeGui allocates a fresh window via getNextWindowId, then creates a ContainerMerchant from player inventory, villager and world and stamps it with currentWindowId. It registers the player via onCraftGuiOpened so slot changes stream as S2F and S30. It resolves the merchant inventory and display name, then sends S2DPacketOpenWindow with minecraft:villager, name and size to open the client GuiMerchant shell. It fetches MerchantRecipeList via villager.getRecipes, and if non-null allocates a PacketBuffer, writes the windowId int first, then serializes the recipe list with writeToBuf. It wraps that buffer in S3FPacketCustomPayload on channel MC|TrList so the client can populate trade arrows and prices. Without the S3F the GUI opens empty, and a mismatched windowId in the payload orphans recipes from the window. Closing later goes through S2E and container teardown.",
      "code": "    public void displayVillagerTradeGui(IMerchant villager)\n    {\n        this.getNextWindowId();\n        this.openContainer = new ContainerMerchant(this.inventory, villager, this.worldObj);\n        this.openContainer.windowId = this.currentWindowId;\n        this.openContainer.onCraftGuiOpened(this);\n        IInventory iinventory = ((ContainerMerchant)this.openContainer).getMerchantInventory();\n        IChatComponent ichatcomponent = villager.getDisplayName();\n        this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, \"minecraft:villager\", ichatcomponent, iinventory.getSizeInventory()));\n        MerchantRecipeList merchantrecipelist = villager.getRecipes(this);\n\n        if (merchantrecipelist != null)\n        {\n            PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer());\n            packetbuffer.writeInt(this.currentWindowId);\n            merchantrecipelist.writeToBuf(packetbuffer);\n            this.playerNetServerHandler.sendPacket(new S3FPacketCustomPayload(\"MC|TrList\", packetbuffer));\n        }\n    }",
      "code_walkthrough": "getNextWindowId cycles the window counter so each trade gets a unique ID for routing C0E clicks. The ContainerMerchant assignment plus onCraftGuiOpened wires server inventory sync before any packet, ensuring slot deltas have a listener. The S2D line opens the villager GUI shell with the merchant name and slot count the client uses to size the screen. The PacketBuffer sequence writes windowId then recipes into MC|TrList, which the client NetHandlerPlayClient matches back to the open window, so dropping S3F leaves a recipe-less merchant."
     },
     {
      "name": "closeScreen",
      "detail_long": "closeScreen implements the server-initiated close path when canInteractWith fails, distance is exceeded, or a plugin forces dismissal. It sends S2EPacketCloseWindow carrying openContainer.windowId so the client tears down exactly the GUI it thinks is open. It then calls closeContainer which invokes onContainerClosed and resets openContainer to inventoryContainer, clearing crafting listeners. Unlike the client C0D path, this originates from the server and the client must obey by clearing its GuiScreen and cursor handling. If the windowId is stale the client may ignore the close until the next S2D or manual Esc, leaving a ghost container. No item stacks are moved here, pending C0E transactions for that window are invalidated. The paired client method sends C0D upward, while this sends S2E downward.",
      "code": "    public void closeScreen()\n    {\n        this.playerNetServerHandler.sendPacket(new S2EPacketCloseWindow(this.openContainer.windowId));\n        this.closeContainer();\n    }\n\n    /**\n     * updates item held by mouse\n     */\n    public void updateHeldItem()\n    {\n        if (!this.isChangingQuantityOnly)\n        {\n            this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack()));\n        }\n    }",
      "code_walkthrough": "The S2E constructor captures the live openContainer.windowId, binding the close to the server idea of the open GUI. sendPacket pushes it only to this player, and closeContainer immediately resets to inventoryContainer so further C0E clicks for the old ID are rejected. The following updateHeldItem snippet shows cursor sync via S2F with -1 -1, which is separate and not sent on close. If S2E is lost the client keeps rendering the container while the server has already discarded it, causing click desync."
     },
     {
      "name": "sendPlayerAbilities",
      "detail_long": "sendPlayerAbilities first null-guards playerNetServerHandler so early login or disconnect ticks do not throw when no channel exists. It sends S39PacketPlayerAbilities constructed from the authoritative this.capabilities, including allowFlying, isFlying, creative and speed fields owned by the server GameType. It then calls updatePotionMetadata to reconcile invisibility, color and ambience flags, which also re-notifies the tracker for spectators. It is invoked from setGameType, spectator mount changes and login capability sync. The client applies S39 directly to EntityPlayerSP capabilities, overriding any forged C13 until the next legitimate toggle. Because S39 carries the full struct, it also corrects flySpeed hacks in one round trip. Failure to send here after a gamemode switch leaves creative flight visually enabled but server-rejected.",
      "code": "    public void sendPlayerAbilities()\n    {\n        if (this.playerNetServerHandler != null)\n        {\n            this.playerNetServerHandler.sendPacket(new S39PacketPlayerAbilities(this.capabilities));\n            this.updatePotionMetadata();\n        }\n    }",
      "code_walkthrough": "The null check protects ticks where the NetHandler has not been assigned yet, such as construction or logout teardown. The S39 line serializes the server capabilities object, which the client must accept as authoritative over its local copy. updatePotionMetadata follows to keep DataWatcher flags and tracker visibility consistent, especially forcing spectators invisible. Blocking S39 after a gamemode change is how stale fly states persist client-side until movement validation kicks."
     },
     {
      "name": "setGameType",
      "detail_long": "setGameType applies the new WorldSettings.GameType to theItemInWorldManager first so mining, interaction and damage rules change atomically. It sends S2BPacketChangeGameState with reason 3 and the game-type ID as float, which drives the client title, HUD and PlayerControllerMP rules. If the target is SPECTATOR it calls mountEntity null to dismount any vehicle before hiding, else it calls setSpectatingEntity self to exit camera mode. It then calls sendPlayerAbilities to push S39 flight and creative flags matching the new mode, plus markPotionsDirty to refresh effect visibility. The client PlayerControllerMP.setGameType mirrors the mode locally on S2B receipt. Skipping S39 here would leave survival flight enabled visually, while skipping the spectate reset would strand the camera. The sequence ensures abilities and camera never disagree with the authoritative mode.",
      "code": "    public void setGameType(WorldSettings.GameType gameType)\n    {\n        this.theItemInWorldManager.setGameType(gameType);\n        this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(3, (float)gameType.getID()));\n\n        if (gameType == WorldSettings.GameType.SPECTATOR)\n        {\n            this.mountEntity((Entity)null);\n        }\n        else\n        {\n            this.setSpectatingEntity(this);\n        }\n\n        this.sendPlayerAbilities();\n        this.markPotionsDirty();\n    }",
      "code_walkthrough": "The setGameType call on theItemInWorldManager flips server mining and block rules before any client notification, preventing a race where the client still mines as creative. The S2B line uses reason 3 which the client interprets as gamemode change, with the ID carried as float per protocol. The spectator branch dismounts or re-attaches the camera so S43 camera and S1B attach stay consistent. sendPlayerAbilities plus markPotionsDirty finish by pushing S39 and S1C metadata, so all three channels agree on the new mode."
     },
     {
      "name": "trySleep/wakeUpPlayer/mountEntity",
      "detail_long": "trySleep delegates to super.trySleep for bed checks on distance, time and occupancy, and only on EnumStatus OK proceeds to networking. It builds S0APacketUseBed with this player and bed BlockPos, broadcasts it via getEntityTracker.sendToAllTrackingEntity so nearby clients render the lying pose, then calls setPlayerLocation to force-resync position and sends the same packet directly to the sleeper. wakeUpPlayer checks isPlayerSleeping, then broadcasts S0BPacketAnimation with ID 2 to trackers to stand the model up before calling super and re-syncing position if a handler exists. mountEntity captures the prior ridingEntity, calls super.mountEntity, and on change sends S1BPacketEntityAttach with type 0 binding this to the new ridingEntity plus a setPlayerLocation correction. Together they keep bed, wake and ride states visible to all trackers while the mover gets an authoritative teleport. Missing S1B or S0A leaves remote clients showing standing or dismounted ghosts.",
      "code": "    public EntityPlayer.EnumStatus trySleep(BlockPos bedLocation)\n    {\n        EntityPlayer.EnumStatus entityplayer$enumstatus = super.trySleep(bedLocation);\n\n        if (entityplayer$enumstatus == EntityPlayer.EnumStatus.OK)\n        {\n            Packet packet = new S0APacketUseBed(this, bedLocation);\n            this.getServerForPlayer().getEntityTracker().sendToAllTrackingEntity(this, packet);\n            this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch);\n            this.playerNetServerHandler.sendPacket(packet);\n        }\n\n        return entityplayer$enumstatus;\n    }",
      "code_walkthrough": "super.trySleep validates the bed and returns OK only when sleep is legal, gating all packets on that enum. The S0A constructor binds the player entity ID to the bed position so remote clients can orient the lying model. sendToAllTrackingEntity fans S0A to trackers while the direct sendPacket plus setPlayerLocation ensures the sleeper also snaps to the bed. wakeUpPlayer mirrors this with S0B animation 2 and mountEntity with S1B attach 0, so blocking any of them desyncs pose or vehicle attachment."
     },
     {
      "name": "onNewPotionEffect/onFinishedPotionEffect",
      "detail_long": "onNewPotionEffect and onChangedPotionEffect both call their super implementations to update the server effect map, then send S1DPacketEntityEffect with getEntityId and the PotionEffect object carrying ID, amplifier, duration, ambient and particles. This covers both fresh application and amplifier or duration refreshes from beacons or splash potions. onFinishedPotionEffect calls super to remove the effect, then sends S1EPacketRemoveEntityEffect with entity ID and the finished effect so the client clears particles and attribute modifiers. The client applies S1D by adding or replacing the effect and S1E by removing it, keeping DataWatcher color in sync via later metadata. Without these pushes the client would show wrong hearts, speed or invisibility until the next S1C. The tracker burst in updatePlayerEntity also replays active effects via S1D on first sight, so late-joining trackers converge.",
      "code": "    protected void onNewPotionEffect(PotionEffect id)\n    {\n        super.onNewPotionEffect(id);\n        this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id));\n    }\n\n    protected void onChangedPotionEffect(PotionEffect id, boolean p_70695_2_)\n    {\n        super.onChangedPotionEffect(id, p_70695_2_);\n        this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id));\n    }\n\n    protected void onFinishedPotionEffect(PotionEffect effect)\n    {\n        super.onFinishedPotionEffect(effect);\n        this.playerNetServerHandler.sendPacket(new S1EPacketRemoveEntityEffect(this.getEntityId(), effect));\n    }",
      "code_walkthrough": "super calls mutate the server PotionEffect map first so the packet reflects committed state rather than a prediction. The S1D constructor packs entity ID plus the full effect struct, letting the client reproduce duration and amplifier exactly. The S1E constructor packs entity ID plus effect ID for removal, clearing client overlays and modifiers. Dropping S1D leaves the client missing particles while the server applies damage or speed, and dropping S1E leaves ghost effects after expiry."
     }
    ]
   }
  },
  {
   "slug": "EntityTrackerEntry",
   "title": "EntityTrackerEntry",
   "rel": "net/minecraft/entity/EntityTrackerEntry.java",
   "desc": "Server per-entity tracker: builds spawn packets and pushes S12 velocity, S14 movement and S18 teleports to tracking players.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/EntityTrackerEntry/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/EntityTrackerEntry.java",
   "packets": [
    "S04PacketEntityEquipment",
    "S0APacketUseBed",
    "S0CPacketSpawnPlayer",
    "S0EPacketSpawnObject",
    "S0FPacketSpawnMob",
    "S10PacketSpawnPainting",
    "S11PacketSpawnExperienceOrb",
    "S12PacketEntityVelocity",
    "S14PacketEntity",
    "S18PacketEntityTeleport",
    "S19PacketEntityHeadLook",
    "S1BPacketEntityAttach",
    "S1CPacketEntityMetadata",
    "S1DPacketEntityEffect",
    "S20PacketEntityProperties",
    "S49PacketUpdateEntityNBT"
   ],
   "peers": [
    "EntityPlayerMP",
    "EntityLivingBase",
    "MathHelper",
    "BlockPos",
    "Entity",
    "EntityPlayer"
   ],
   "analysis": {
    "overview": "Server per-entity tracker state machine. Decides spawn, delta move/look, velocity, metadata for each tick. Tick flow: updatePlayerList (range/ride/ItemFrame) -> motion branch (rel vs teleport) + head/velocity/metadata. Pushes via EntityPlayerMP.playerNetServerHandler to trackingPlayers set.",
    "methods": [
     {
      "detail": "Refreshes player set if moved >16 blocks. Sends S1B on ride change. Every 10 ticks syncs ItemFrame maps+metadata. On frequency/airborne/dataChanged sends rel/teleport, velocity, metadata, head look.",
      "name": "updatePlayerList",
      "packets": [
       "S1B",
       "S14",
       "S18",
       "S12",
       "S19",
       "S1C"
      ],
      "purpose": "Per-tick sync: range scan, attach, ItemFrame maps, movement branch."
     },
     {
      "detail": "Range+chunk+isSpectatedByPlayer gate. On add sends createSpawnPacket then metadata, NBT S49, attributes S20, velocity S12, attach S1B, equipment S04, bed S0A, effects S1D.",
      "name": "updatePlayerEntity",
      "packets": [
       "S1C",
       "S49",
       "S20",
       "S12",
       "S04",
       "S1D"
      ],
      "purpose": "Adds/removes one player from tracking set with full spawn burst."
     },
     {
      "detail": "Switches Item/Player/Minecart/Boat/IAnimals/mobs, projectiles by type IDs (60 arrow,73 potion,etc), FallingBlock state ID, Painting/ItemFrame/LeashKnot with pos overrides.",
      "name": "createSpawnPacket",
      "packets": [
       "S0C",
       "S0E",
       "S0F",
       "S10",
       "S11"
      ],
      "purpose": "Factory mapping entity class to spawn packet type."
     },
     {
      "detail": "If hasObjectChanged sends S1C metadata. If EntityLivingBase with non-empty attribute set sends S20 properties then clears set to avoid resend.",
      "name": "sendMetadataToAllAssociatedPlayers",
      "packets": [
       "S1C",
       "S20"
      ],
      "purpose": "Pushes DataWatcher and attribute deltas."
     },
     {
      "detail": "sendPacket loops trackingPlayers sendPacket. func_151261_b also echoes to tracked EntityPlayerMP self, used for metadata/attributes/velocityChanged.",
      "name": "sendPacketToTrackedPlayers/func_151261_b",
      "packets": [
       "S1C",
       "S20",
       "S12"
      ],
      "purpose": "Fan-out helpers with self-include variant."
     },
     {
      "detail": "Removes from trackingPlayers set and calls player.removeEntity which queues S13 destroy or immediate send for players.",
      "name": "removeFromTrackedPlayers/removeTrackedPlayerSymmetric",
      "packets": [
       "S13"
      ],
      "purpose": "Stops tracking and destroys entity client-side."
     },
     {
      "detail": "Compares player XZ to encodedPos/32 within trackingDistanceThreshold and isSpectatedByPlayer. Prevents sending hidden/spectator-blocked entities.",
      "name": "func_180233_c",
      "packets": [],
      "purpose": "Range + spectator visibility gate."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S0C",
      "trigger": "Player spawn burst in createSpawnPacket."
     },
     {
      "direction": "sent",
      "id": "S0E",
      "trigger": "Item/projectile/object spawn by type ID."
     },
     {
      "direction": "sent",
      "id": "S12",
      "trigger": "Motion delta >0.02 or velocityChanged flag."
     },
     {
      "direction": "sent",
      "id": "S14",
      "trigger": "Small delta move/look within +-128 and 400-tick window."
     },
     {
      "direction": "sent",
      "id": "S18",
      "trigger": "Large delta, 400-tick force sync, or ground change."
     },
     {
      "direction": "sent",
      "id": "S19",
      "trigger": "Head yaw change >=4/256."
     },
     {
      "direction": "sent",
      "id": "S1B",
      "trigger": "Ride/leash change."
     },
     {
      "direction": "sent",
      "id": "S1C",
      "trigger": "DataWatcher dirty."
     },
     {
      "direction": "sent",
      "id": "S20",
      "trigger": "Attribute set non-empty."
     },
     {
      "direction": "sent",
      "id": "S04/S0A/S49",
      "trigger": "Initial burst equipment/bed/NBT."
     }
    ],
    "internal_fields": [
     {
      "name": "trackedEntity/trackingPlayers",
      "role": "Watched entity and subscribed EntityPlayerMP set"
     },
     {
      "name": "encodedPosX/Y/Z + RotationYaw/Pitch",
      "role": "Last sent fixed-point pos (*32) and angle (*256/360) for delta"
     },
     {
      "name": "updateFrequency/trackingDistanceThreshold",
      "role": "Per-type tick divisor and XZ range gate"
     },
     {
      "name": "ticksSinceLastForcedTeleport",
      "role": "Forces S18 every 400 ticks to fix drift"
     },
     {
      "name": "lastTrackedEntityMotionX/Y/motionZ",
      "role": "Last sent velocity; 0.02 threshold for S12"
     },
     {
      "name": "updateCounter/firstUpdateDone",
      "role": "Tick count and initial scan flag with 16-block moved check"
     }
    ],
    "peers": [
     "EntityTracker",
     "EntityPlayerMP",
     "EntityPlayer",
     "DataWatcher",
     "ServersideAttributeMap"
    ],
    "methods_detailed": [
     {
      "name": "updatePlayerList",
      "detail_long": "updatePlayerList runs each server tick and first checks firstUpdateDone or distance squared over 16 to decide whether to rescan tracking membership via updatePlayerEntities. It detects ridingEntity changes or a 60-tick refresh and broadcasts S1BPacketEntityAttach type 0 so vehicle mounts stay glued on remote clients. For EntityItemFrame every 10 ticks it re-sends map data for displayed ItemMaps and forces sendMetadataToAllAssociatedPlayers for frame rotation. The main motion gate fires when updateCounter modulo updateFrequency is zero, isAirBorne is true, or DataWatcher reports a change, ensuring idle entities still heartbeat. Inside it encodes positions times 32 and rotations times 256 over 360, computes deltas against encoded caches, and sets flag for 4-unit move and flag1 for 4-unit look change. It chooses S15 rel-move, S16 look, S17 look-move or S18 teleport based on the 128-unit byte range, 400-tick forced teleport, ridingEntity and onGround flip, then handles S12 velocity and S19 head look. Finally it increments updateCounter and flushes velocityChanged via func_151261_b.",
      "code": "        if (this.updateCounter % this.updateFrequency == 0 || this.trackedEntity.isAirBorne || this.trackedEntity.getDataWatcher().hasObjectChanged())\n        {\n            if (this.trackedEntity.ridingEntity == null)\n            {\n                ++this.ticksSinceLastForcedTeleport;\n                int k = MathHelper.floor_double(this.trackedEntity.posX * 32.0D);\n                int j1 = MathHelper.floor_double(this.trackedEntity.posY * 32.0D);\n                int k1 = MathHelper.floor_double(this.trackedEntity.posZ * 32.0D);\n                int l1 = MathHelper.floor_float(this.trackedEntity.rotationYaw * 256.0F / 360.0F);\n                int i2 = MathHelper.floor_float(this.trackedEntity.rotationPitch * 256.0F / 360.0F);\n                int j2 = k - this.encodedPosX;\n                int k2 = j1 - this.encodedPosY;\n                int i = k1 - this.encodedPosZ;\n                Packet packet1 = null;\n                boolean flag = Math.abs(j2) >= 4 || Math.abs(k2) >= 4 || Math.abs(i) >= 4 || this.updateCounter % 60 == 0;\n                boolean flag1 = Math.abs(l1 - this.encodedRotationYaw) >= 4 || Math.abs(i2 - this.encodedRotationPitch) >= 4;\n\n                if (this.updateCounter > 0 || this.trackedEntity instanceof EntityArrow)\n                {\n                    if (j2 >= -128 && j2 < 128 && k2 >= -128 && k2 < 128 && i >= -128 && i < 128 && this.ticksSinceLastForcedTeleport <= 400 && !this.ridingEntity && this.onGround == this.trackedEntity.onGround)",
      "code_walkthrough": "The outer modulo plus isAirBorne plus hasObjectChanged condition throttles per-type updates, for example mobs every 3 ticks versus arrows every 20, while forcing immediate send on motion or metadata dirt. The times-32 and times-256 encoding lines convert doubles to fixed-point protocol units the client decodes, matching S14 byte deltas and S18 int positions. The flag and flag1 thresholds of 4 encoded units filter sub-pixel jitter to save bandwidth. The inner range check on -128 to 128 plus 400-tick and onGround tests selects cheap S14 deltas versus authoritative S18 teleport, which is why large teleports or long drift always correct with S18."
     },
     {
      "name": "updatePlayerEntity",
      "detail_long": "updatePlayerEntity manages one candidate player against one tracked entity, skipping when the player is the tracked entity itself to avoid self-tracking loops. It calls func_180233_c for XZ range plus spectator visibility, then requires either chunk watch via isPlayerWatchingThisChunk or forceSpawn to admit a new tracker. On admission it adds to trackingPlayers, sends createSpawnPacket as the entity-type-correct S0C, S0E, S0F, S10 or S11 birth packet, then follows with S1C metadata if the DataWatcher is non-blank. It sends S49 NBT when getNBTTagCompound is non-null, S20 attributes for watched collections, and caches motion into lastTracked fields for future S12 deltas. It sends S12 velocity immediately unless the spawn was S0F mob which already carries motion, then replays S1B attach for riding or leashed states, S04 equipment for five armor slots, S0A bed if sleeping, and S1D for each active potion. On range exit it removes from trackingPlayers and calls removeEntity which emits S13 destroy, keeping client worlds garbage-collected.",
      "code": "    public void updatePlayerEntity(EntityPlayerMP playerMP)\n    {\n        if (playerMP != this.trackedEntity)\n        {\n            if (this.func_180233_c(playerMP))\n            {\n                if (!this.trackingPlayers.contains(playerMP) && (this.isPlayerWatchingThisChunk(playerMP) || this.trackedEntity.forceSpawn))\n                {\n                    this.trackingPlayers.add(playerMP);\n                    Packet packet = this.createSpawnPacket();\n                    playerMP.playerNetServerHandler.sendPacket(packet);\n\n                    if (!this.trackedEntity.getDataWatcher().getIsBlank())\n                    {\n                        playerMP.playerNetServerHandler.sendPacket(new S1CPacketEntityMetadata(this.trackedEntity.getEntityId(), this.trackedEntity.getDataWatcher(), true));\n                    }\n\n                    NBTTagCompound nbttagcompound = this.trackedEntity.getNBTTagCompound();\n\n                    if (nbttagcompound != null)\n                    {\n                        playerMP.playerNetServerHandler.sendPacket(new S49PacketUpdateEntityNBT(this.trackedEntity.getEntityId(), nbttagcompound));\n                    }\n\n                    if (this.trackedEntity instanceof EntityLivingBase)\n                    {\n                        ServersideAttributeMap serversideattributemap = (ServersideAttributeMap)((EntityLivingBase)this.trackedEntity).getAttributeMap();",
      "code_walkthrough": "The self-inequality plus func_180233_c plus isPlayerWatchingThisChunk chain ensures a player only receives entities in range, in a watched chunk and visible through spectator rules. createSpawnPacket returns the polymorphic birth packet the client needs to allocate the entity shell with correct ID and position. The S1C and S49 follow-ups hydrate DataWatcher flags and tile NBT that the spawn packet alone cannot carry. Missing this burst leaves invisible or untextured entities, while the else-branch S13 destroy on range exit is what removes them when walking away."
     },
     {
      "name": "createSpawnPacket",
      "detail_long": "createSpawnPacket is a type-switch factory that warns when the entity isDead yet still requested, then returns the exact spawn packet for each class. EntityItem maps to S0E type 2 data 1, EntityPlayerMP to S0C spawn player, minecarts to S0E type 10 with network ID, boats to S0E type 1, and IAnimals plus other EntityLivingBase to S0F mob with head yaw refresh. Projectiles use fixed S0E type IDs including 60 arrow with shooter ID, 61 snowball, 62 egg, 65 pearl, 72 eye, 73 potion with damage, 75 bottle, 76 firework, 90 fish hook with angler fallback, plus fireballs 63, 64 small, 66 wither with acceleration scaled by 8000. FallingBlock uses S0E 70 with Block.getStateId, armor stands 78, XP orbs S11, paintings S10 and item frames or leash knots S0E 71 or 77 with overridden fixed-point hanging coordinates. Any unknown class throws IllegalArgumentException, failing fast rather than sending a corrupt spawn. The caller updatePlayerEntity sends the result before metadata, attributes and equipment so the client has an ID to attach them to.",
      "code": "        else if (this.trackedEntity instanceof EntityArrow)\n        {\n            Entity entity = ((EntityArrow)this.trackedEntity).shootingEntity;\n            return new S0EPacketSpawnObject(this.trackedEntity, 60, entity != null ? entity.getEntityId() : this.trackedEntity.getEntityId());\n        }\n        else if (this.trackedEntity instanceof EntitySnowball)\n        {\n            return new S0EPacketSpawnObject(this.trackedEntity, 61);\n        }\n        else if (this.trackedEntity instanceof EntityPotion)\n        {\n            return new S0EPacketSpawnObject(this.trackedEntity, 73, ((EntityPotion)this.trackedEntity).getPotionDamage());\n        }\n        else if (this.trackedEntity instanceof EntityExpBottle)\n        {\n            return new S0EPacketSpawnObject(this.trackedEntity, 75);\n        }",
      "code_walkthrough": "Each branch constructs S0E with the hardcoded vanilla type ID the client uses to pick a renderer and physics, so 60 versus 61 versus 73 is not interchangeable. The arrow line threads shootingEntity ID with a self-ID fallback when the shooter is gone, letting the client attribute kill credit. The potion line passes getPotionDamage as the data int so the client shows the correct splash color and effect. Sending the wrong ID or data spawns the wrong visual or crashes old clients, which is why the final else throws instead of guessing."
     },
     {
      "name": "sendMetadataToAllAssociatedPlayers",
      "detail_long": "sendMetadataToAllAssociatedPlayers first fetches the trackedEntity DataWatcher and checks hasObjectChanged to avoid spamming identical S1C packets every tick. On dirty it calls func_151261_b with S1CPacketEntityMetadata carrying entity ID, watcher and false for non-initial, which fans out to trackers plus the tracked player if it is an EntityPlayerMP. It then checks for EntityLivingBase, pulls the ServersideAttributeMap, and reads getAttributeInstanceSet as the delta set of recently modified max-health, speed or attack attributes. If that set is non-empty it sends S20PacketEntityProperties with the set through func_151261_b and immediately clears the set to prevent resend on the next tick. This two-channel push keeps flags like sneaking, hurt color and custom names via S1C separate from numeric attributes via S20. The method is called after every movement send and every 10 ticks for item frames, so metadata converges quickly. Suppressing it leaves ghost names or stale health scaling.",
      "code": "    private void sendMetadataToAllAssociatedPlayers()\n    {\n        DataWatcher datawatcher = this.trackedEntity.getDataWatcher();\n\n        if (datawatcher.hasObjectChanged())\n        {\n            this.func_151261_b(new S1CPacketEntityMetadata(this.trackedEntity.getEntityId(), datawatcher, false));\n        }\n\n        if (this.trackedEntity instanceof EntityLivingBase)\n        {\n            ServersideAttributeMap serversideattributemap = (ServersideAttributeMap)((EntityLivingBase)this.trackedEntity).getAttributeMap();\n            Set<IAttributeInstance> set = serversideattributemap.getAttributeInstanceSet();\n\n            if (!set.isEmpty())\n            {\n                this.func_151261_b(new S20PacketEntityProperties(this.trackedEntity.getEntityId(), set));\n            }\n\n            set.clear();\n        }\n    }",
      "code_walkthrough": "The hasObjectChanged guard reads the DataWatcher dirty flag set by updateObject calls, so S1C is only built when a watched byte actually flipped. func_151261_b is used instead of sendPacketToTrackedPlayers so the tracked player itself also receives its own metadata for self-render like skin flags. The attribute set fetch plus isEmpty check isolates numeric modifier changes that DataWatcher cannot express, sending them as S20. The trailing clear resets the delta set, meaning a lost S20 will not auto-retry until the attribute changes again."
     },
     {
      "name": "sendPacketToTrackedPlayers/func_151261_b",
      "detail_long": "sendPacketToTrackedPlayers iterates the trackingPlayers hash set and calls playerNetServerHandler.sendPacket for each member, delivering movement, look, metadata or velocity to exactly those in range. It performs no range recheck itself, relying on updatePlayerEntity and func_180233_c to maintain set membership, which makes it a cheap fan-out on the hot tick path. func_151261_b wraps it by first calling sendPacketToTrackedPlayers, then checking if trackedEntity is an EntityPlayerMP and echoing the same packet to that entity own channel. That self-include variant is used for S1C metadata, S20 attributes and S12 velocityChanged where the subject player must also see its own flags or knockback. Using the wrong helper hides self-effects like potion color or takes no knockback visually. Both take a generic Packet so S14, S18, S19 and S1B all flow through the same loop. The design separates observer sync from subject sync with one branch.",
      "code": "    public void sendPacketToTrackedPlayers(Packet packetIn)\n    {\n        for (EntityPlayerMP entityplayermp : this.trackingPlayers)\n        {\n            entityplayermp.playerNetServerHandler.sendPacket(packetIn);\n        }\n    }\n\n    public void func_151261_b(Packet packetIn)\n    {\n        this.sendPacketToTrackedPlayers(packetIn);\n\n        if (this.trackedEntity instanceof EntityPlayerMP)\n        {\n            ((EntityPlayerMP)this.trackedEntity).playerNetServerHandler.sendPacket(packetIn);\n        }\n    }",
      "code_walkthrough": "The for loop over trackingPlayers shows the fan-out cost scales with observer count, each sendPacket queuing on that player Netty channel. The packetIn parameter is opaque, so the same loop carries tiny S14 deltas and large S20 lists without branching. func_151261_b adds the instanceof EntityPlayerMP self-echo, which is required because a player does not track itself in trackingPlayers. Choosing between the two controls whether the subject sees its own S12 knockback or S1C name flags, a frequent source of self-desync bugs when misused."
     },
     {
      "name": "removeFromTrackedPlayers/removeTrackedPlayerSymmetric",
      "detail_long": "sendDestroyEntityPacketToTrackedPlayers loops trackingPlayers and calls removeEntity on each, which for players sends immediate S13 and for other entities queues into destroyedItemsNetCache for batched S13. removeFromTrackedPlayers checks contains before acting, then calls playerMP.removeEntity to destroy the client-side copy and removes the player from the set to stop future sends. removeTrackedPlayerSymmetric is the symmetric alias used on chunk unload or dimension change, performing the same contains, remove and removeEntity sequence. Together they ensure no stale entity shells linger after range exit, logout or chunk unload. Forgetting the removeEntity call leaks ghost mobs that float until the next S18 or relog. The S13 carries only entity IDs, so the client looks up and deletes the matching world entry. These paths are the only clean teardown for tracker membership.",
      "code": "    public void sendDestroyEntityPacketToTrackedPlayers()\n    {\n        for (EntityPlayerMP entityplayermp : this.trackingPlayers)\n        {\n            entityplayermp.removeEntity(this.trackedEntity);\n        }\n    }\n\n    public void removeFromTrackedPlayers(EntityPlayerMP playerMP)\n    {\n        if (this.trackingPlayers.contains(playerMP))\n        {\n            playerMP.removeEntity(this.trackedEntity);\n            this.trackingPlayers.remove(playerMP);\n        }\n    }",
      "code_walkthrough": "The destroy loop delegates to EntityPlayerMP.removeEntity, which decides between instant S13 for players and batched cache for others, explaining why player logouts vanish instantly. The contains guard prevents double-destroy S13s that would make the client delete a reused entity ID. removeEntity triggers the S13 with the tracked entity ID so the client can free the renderer and physics. The symmetric variant repeats this pattern for unload paths, so skipping either leaves ghost entities that still receive S14 moves."
     },
     {
      "name": "func_180233_c",
      "detail_long": "func_180233_c computes d0 as player X minus encodedPosX divided by 32 and d1 as player Z minus encodedPosZ divided by 32, converting the fixed-point cache back to block units. It checks d0 and d1 against plus and minus trackingDistanceThreshold, which varies by entity type such as 64 for items or 512 for dragons. It also calls trackedEntity.isSpectatedByPlayer to enforce spectator invisibility, hiding non-spectated entities from spectator cameras and vice versa. It ignores Y distance entirely, so vertical range does not gate tracking in 1.8.9. The result gates updatePlayerEntity admission and retention, preventing bandwidth waste on far entities. A false return triggers removal plus S13 destroy, while true plus chunk watch triggers the full spawn burst. Cheats cannot force the server to send out-of-range entities because this gate runs before every send.",
      "code": "    public boolean func_180233_c(EntityPlayerMP playerMP)\n    {\n        double d0 = playerMP.posX - (double)(this.encodedPosX / 32);\n        double d1 = playerMP.posZ - (double)(this.encodedPosZ / 32);\n        return d0 >= (double)(-this.trackingDistanceThreshold) && d0 <= (double)this.trackingDistanceThreshold && d1 >= (double)(-this.trackingDistanceThreshold) && d1 <= (double)this.trackingDistanceThreshold && this.trackedEntity.isSpectatedByPlayer(playerMP);\n    }\n\n    private boolean isPlayerWatchingThisChunk(EntityPlayerMP playerMP)\n    {\n        return playerMP.getServerForPlayer().getPlayerManager().isPlayerWatchingChunk(playerMP, this.trackedEntity.chunkCoordX, this.trackedEntity.chunkCoordZ);\n    }",
      "code_walkthrough": "The d0 and d1 lines decode the last-sent position by integer-dividing the fixed-point cache, noting the int division truncation before cast. The long return line ANDs four range comparisons with isSpectatedByPlayer, so all five must pass to keep tracking. isPlayerWatchingThisChunk below adds a second chunk-visibility requirement checked alongside this gate in updatePlayerEntity. Together they explain why entities pop in at chunk borders or vanish when spectating, and why radar hacks cannot see beyond trackingDistanceThreshold."
     }
    ]
   }
  },
  {
   "slug": "ServerConfigurationManager",
   "title": "ServerConfigurationManager",
   "rel": "net/minecraft/server/management/ServerConfigurationManager.java",
   "desc": "Login/join orchestrator: fires S01 JoinGame, S38 tab-list, S39 abilities and S41 difficulty during initializeConnectionToPlayer.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/ServerConfigurationManager/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/server/management/ServerConfigurationManager.java",
   "packets": [
    "S01PacketJoinGame",
    "S02PacketChat",
    "S03PacketTimeUpdate",
    "S05PacketSpawnPosition",
    "S07PacketRespawn",
    "S09PacketHeldItemChange",
    "S1DPacketEntityEffect",
    "S1FPacketSetExperience",
    "S2BPacketChangeGameState",
    "S38PacketPlayerListItem",
    "S39PacketPlayerAbilities",
    "S3EPacketTeams",
    "S3FPacketCustomPayload",
    "S41PacketServerDifficulty",
    "S44PacketWorldBorder"
   ],
   "peers": [
    "EntityPlayerMP",
    "NetHandlerPlayServer",
    "WorldServer",
    "ServerScoreboard",
    "PlayerManager",
    "ItemInWorldManager",
    "NetworkManager",
    "PacketBuffer",
    "MathHelper",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "World",
    "NetHandlerLoginServer"
   ],
   "analysis": {
    "overview": "Server-wide player roster, bans, whitelist and spawn lifecycle. Creates NetHandlerPlayServer on login, sends join burst, and handles respawn, dimension transfer and logout broadcast.",
    "methods": [
     {
      "detail": "Loads NBT, sets world. Sends JoinGame, MC|Brand, Difficulty, SpawnPosition, Abilities, HeldChange, scoreboard, S08 location, time/weather, potion effects and riding entity.",
      "name": "initializeConnectionToPlayer",
      "packets": [
       "S01",
       "S3F",
       "S41",
       "S05",
       "S39",
       "S09"
      ],
      "purpose": "Sends login burst and places player."
     },
     {
      "detail": "Order: profile ban with expiry date, whitelist via canJoin, IP ban, then full when size>=maxPlayers unless bypassesPlayerLimit. Returns reason string or null.",
      "name": "allowUserToConnect",
      "packets": [],
      "purpose": "Ban, whitelist, IP and full gates."
     },
     {
      "detail": "Untracks old entity, clones player, reuses NetHandler. Resolves bed spawn; sends S2B(0) if invalid. Lifts out of collision to y<256 then S07 Respawn and S08 location.",
      "name": "recreatePlayerEntity",
      "packets": [
       "S07",
       "S05",
       "S1F",
       "S2B"
      ],
      "purpose": "Respawns player preserving connection."
     },
     {
      "detail": "Sends S07 Respawn, removes dangerously, scales coords x8 between 0/-1 clamped to border, places via teleporter, re-adds, resyncs time, inventory and effects.",
      "name": "transferPlayerToDimension",
      "packets": [
       "S07",
       "S1D"
      ],
      "purpose": "Moves player across dimensions."
     },
     {
      "detail": "Adds to list and uuid map, broadcasts ADD_PLAYER, spawns entity, prepares chunk, then sends newcomer full existing roster via ADD_PLAYER.",
      "name": "playerLoggedIn",
      "packets": [
       "S38"
      ],
      "purpose": "Joins roster and announces."
     },
     {
      "detail": "Triggers leaveGameStat, writes NBT/stats, removes mount and entity, drops from maps, broadcasts REMOVE_PLAYER to remaining players.",
      "name": "playerLoggedOut",
      "packets": [
       "S38"
      ],
      "purpose": "Persists and removes player."
     },
     {
      "detail": "Sends WorldBorder INITIALIZE, TimeUpdate with doDaylightCycle, and if raining S2B 1/7/8 for rain state, rain and thunder strength.",
      "name": "updateTimeAndWeatherForPlayer",
      "packets": [
       "S44",
       "S03",
       "S2B"
      ],
      "purpose": "Syncs border, time and rain."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S01",
      "trigger": "Login burst with entityId and gametype"
     },
     {
      "direction": "sent",
      "id": "S05",
      "trigger": "Spawn point on login/respawn"
     },
     {
      "direction": "sent",
      "id": "S07",
      "trigger": "Respawn or dimension change"
     },
     {
      "direction": "sent",
      "id": "S38",
      "trigger": "Tab-list add/remove/latency tick"
     },
     {
      "direction": "sent",
      "id": "S03",
      "trigger": "Time/weather sync for player"
     },
     {
      "direction": "sent",
      "id": "S44",
      "trigger": "WorldBorder init and listener fan-out"
     }
    ],
    "internal_fields": [
     {
      "name": "playerEntityList",
      "role": "Ordered online EntityPlayerMP roster"
     },
     {
      "name": "uuidToPlayerMap",
      "role": "UUID lookup for dup-login and queries"
     },
     {
      "name": "bannedPlayers/bannedIPs",
      "role": "Ban lists checked in allowUserToConnect"
     },
     {
      "name": "maxPlayers/viewDistance",
      "role": "Capacity and chunk radius for PlayerManager"
     },
     {
      "name": "playerPingIndex",
      "role": ">600 ticks triggers latency broadcast"
     }
    ],
    "peers": [
     "NetHandlerPlayServer",
     "NetHandlerLoginServer",
     "PlayerManager",
     "EntityPlayerMP",
     "MinecraftServer"
    ],
    "methods_detailed": [
     {
      "name": "initializeConnectionToPlayer",
      "detail_long": "initializeConnectionToPlayer builds the login burst for a new EntityPlayerMP after NBT load. It resolves the profile name, caches the profile, reads player NBT, binds world and ItemInWorldManager, and logs IP with entityId and coordinates. It sets game type, creates NetHandlerPlayServer and sends S01 JoinGame with entityId, game type, hardcore, dimension, difficulty, max players, terrain and reduced debug. It then sends MC|Brand S3F, S41 difficulty, S05 spawn, S39 abilities and S09 held change. It pushes stats, achievements and full scoreboard, broadcasts the join message and registers the player in the roster. It teleports with setPlayerLocation S08, syncs time and weather, applies resource pack and re-sends potion effects with S1D. Riding NBT is restored by spawning the mount entity.",
      "code": "        NetHandlerPlayServer nethandlerplayserver = new NetHandlerPlayServer(this.mcServer, netManager, playerIn);\n        nethandlerplayserver.sendPacket(new S01PacketJoinGame(playerIn.getEntityId(), playerIn.theItemInWorldManager.getGameType(), worldinfo.isHardcoreModeEnabled(), worldserver.provider.getDimensionId(), worldserver.getDifficulty(), this.getMaxPlayers(), worldinfo.getTerrainType(), worldserver.getGameRules().getBoolean(\"reducedDebugInfo\")));\n        nethandlerplayserver.sendPacket(new S3FPacketCustomPayload(\"MC|Brand\", (new PacketBuffer(Unpooled.buffer())).writeString(this.getServerInstance().getServerModName())));\n        nethandlerplayserver.sendPacket(new S41PacketServerDifficulty(worldinfo.getDifficulty(), worldinfo.isDifficultyLocked()));\n        nethandlerplayserver.sendPacket(new S05PacketSpawnPosition(blockpos));\n        nethandlerplayserver.sendPacket(new S39PacketPlayerAbilities(playerIn.capabilities));\n        nethandlerplayserver.sendPacket(new S09PacketHeldItemChange(playerIn.inventory.currentItem));\n        playerIn.getStatFile().func_150877_d();\n        playerIn.getStatFile().sendAchievements(playerIn);\n        this.sendScoreboard((ServerScoreboard)worldserver.getScoreboard(), playerIn);\n        this.mcServer.refreshStatusNextTick();\n        ChatComponentTranslation chatcomponenttranslation;\n",
      "code_walkthrough": "The NetHandlerPlayServer construction binds the channel to the player entity. S01PacketJoinGame carries entityId, game type, dimension and difficulty so the client can build WorldClient. The MC|Brand S3F advertises server mod name for client display. S41, S05, S39 and S09 sync difficulty lock, spawn point, fly flags and held slot. sendScoreboard plus stats complete the burst before S08 position arrives."
     },
     {
      "name": "allowUserToConnect",
      "detail_long": "allowUserToConnect enforces login gates in fixed order and returns a kick reason or null. First it checks profile bans via bannedPlayers, appending ban reason and formatted expiry date if present. Second it checks whitelist via canJoin, returning not white-listed when enforced and the player is neither op nor listed. Third it checks IP bans via bannedIPs with reason and expiry formatting. Fourth it checks capacity where list size at or above maxPlayers and no bypass returns server is full. Null means all gates passed and NetHandlerLoginServer may proceed to compression and LoginSuccess. The order matters because bans outrank whitelist and capacity. No packets are sent here, the caller closes with S00 using the returned string.",
      "code": "        {\n            UserListBansEntry userlistbansentry = (UserListBansEntry)this.bannedPlayers.getEntry(profile);\n            String s1 = \"You are banned from this server!\\nReason: \" + userlistbansentry.getBanReason();\n\n            if (userlistbansentry.getBanEndDate() != null)\n            {\n                s1 = s1 + \"\\nYour ban will be removed on \" + dateFormat.format(userlistbansentry.getBanEndDate());\n            }\n\n            return s1;\n        }\n        else if (!this.canJoin(profile))\n        {\n            return \"You are not white-listed on this server!\";\n        }\n        else if (this.bannedIPs.isBanned(address))\n        {\n            IPBanEntry ipbanentry = this.bannedIPs.getBanEntry(address);\n            String s = \"Your IP address is banned from this server!\\nReason: \" + ipbanentry.getBanReason();\n\n            if (ipbanentry.getBanEndDate() != null)\n            {\n                s = s + \"\\nYour ban will be removed on \" + dateFormat.format(ipbanentry.getBanEndDate());\n            }\n\n            return s;\n        }\n        else\n        {\n            return this.playerEntityList.size() >= this.maxPlayers && !this.bypassesPlayerLimit(profile) ? \"The server is full!\" : null;\n        }",
      "code_walkthrough": "The bannedPlayers entry lookup builds the profile-ban string with reason and optional expiry date. The canJoin else-if enforces whitelist after profile bans so banned players cannot bypass via listing. The bannedIPs branch mirrors the profile logic for address bans with expiry formatting. The final else encodes capacity as size at or above maxPlayers without bypass returning server is full else null. Returning null is the only success path to S02 LoginSuccess."
     },
     {
      "name": "recreatePlayerEntity",
      "detail_long": "recreatePlayerEntity respawns a dead player while reusing the NetHandlerPlayServer connection. It untracks the old entity from tracker and player manager, removes it dangerously and drops it from the roster. It copies dimension, creates a fresh ItemInWorldManager and EntityPlayerMP, then reuses the handler, clones inventory and stats, and preserves entityId and command stats. It resolves bed spawn via getBedSpawnLocation and places at plus 0.5 plus 0.1 offsets, or sends S2B state zero when the bed is invalid. It loads the chunk, lifts the player above collision up to Y 256, sends S07 Respawn, S08 location via setPlayerLocation, S05 spawn and S1F experience. It resyncs time and weather, re-adds to manager and world, restores maps and heals. No kick occurs.",
      "code": "        if (blockpos != null)\n        {\n            BlockPos blockpos1 = EntityPlayer.getBedSpawnLocation(this.mcServer.worldServerForDimension(playerIn.dimension), blockpos, flag);\n\n            if (blockpos1 != null)\n            {\n                entityplayermp.setLocationAndAngles((double)((float)blockpos1.getX() + 0.5F), (double)((float)blockpos1.getY() + 0.1F), (double)((float)blockpos1.getZ() + 0.5F), 0.0F, 0.0F);\n                entityplayermp.setSpawnPoint(blockpos, flag);\n            }\n            else\n            {\n                entityplayermp.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(0, 0.0F));\n            }\n        }\n\n        worldserver.theChunkProviderServer.loadChunk((int)entityplayermp.posX >> 4, (int)entityplayermp.posZ >> 4);\n\n        while (!worldserver.getCollidingBoundingBoxes(entityplayermp, entityplayermp.getEntityBoundingBox()).isEmpty() && entityplayermp.posY < 256.0D)\n        {\n            entityplayermp.setPosition(entityplayermp.posX, entityplayermp.posY + 1.0D, entityplayermp.posZ);\n        }\n\n        entityplayermp.playerNetServerHandler.sendPacket(new S07PacketRespawn(entityplayermp.dimension, entityplayermp.worldObj.getDifficulty(), entityplayermp.worldObj.getWorldInfo().getTerrainType(), entityplayermp.theItemInWorldManager.getGameType()));\n        BlockPos blockpos2 = worldserver.getSpawnPoint();\n        entityplayermp.playerNetServerHandler.setPlayerLocation(entityplayermp.posX, entityplayermp.posY, entityplayermp.posZ, entityplayermp.rotationYaw, entityplayermp.rotationPitch);",
      "code_walkthrough": "The bed null check skips spawn logic for world-spawn respawns. getBedSpawnLocation validates the bed, with plus 0.5 and plus 0.1 offsets centering the player on respawn. Invalid beds send S2B state zero to show the respawn-screen message. The chunk load plus while-collision lift to Y 256 prevents suffocation on respawn. S07 Respawn plus setPlayerLocation S08 rebuild the client world and pin the position."
     },
     {
      "name": "transferPlayerToDimension",
      "detail_long": "transferPlayerToDimension moves a live player across dimensions without dropping the connection. It records the old dimension, sets the new id and sends S07 Respawn with difficulty, terrain and game type so the client rebuilds WorldClient. It removes the player dangerously, clears isDead, scales coordinates through transferEntityToWorld with factor 8.0 between overworld and nether clamped to border, or spawn point for end. It re-registers with preparePlayer, pins position with setPlayerLocation S08, rebinds ItemInWorldManager world and resyncs time and weather. It then syncs inventory and re-sends every active S1D potion effect. No kick occurs, failure leaves the player in the new world at the portal exit.",
      "code": "    public void transferPlayerToDimension(EntityPlayerMP playerIn, int dimension)\n    {\n        int i = playerIn.dimension;\n        WorldServer worldserver = this.mcServer.worldServerForDimension(playerIn.dimension);\n        playerIn.dimension = dimension;\n        WorldServer worldserver1 = this.mcServer.worldServerForDimension(playerIn.dimension);\n        playerIn.playerNetServerHandler.sendPacket(new S07PacketRespawn(playerIn.dimension, playerIn.worldObj.getDifficulty(), playerIn.worldObj.getWorldInfo().getTerrainType(), playerIn.theItemInWorldManager.getGameType()));\n        worldserver.removePlayerEntityDangerously(playerIn);\n        playerIn.isDead = false;\n        this.transferEntityToWorld(playerIn, i, worldserver, worldserver1);\n        this.preparePlayer(playerIn, worldserver);\n        playerIn.playerNetServerHandler.setPlayerLocation(playerIn.posX, playerIn.posY, playerIn.posZ, playerIn.rotationYaw, playerIn.rotationPitch);\n        playerIn.theItemInWorldManager.setWorld(worldserver1);\n        this.updateTimeAndWeatherForPlayer(playerIn, worldserver1);\n        this.syncPlayerInventory(playerIn);\n\n        for (PotionEffect potioneffect : playerIn.getActivePotionEffects())\n        {\n            playerIn.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(playerIn.getEntityId(), potioneffect));\n        }\n    }",
      "code_walkthrough": "Saving old dimension i preserves the source for coordinate scaling. S07PacketRespawn forces the client to swap WorldClient before the entity moves. removePlayerEntityDangerously plus isDead false detach from the old world without death drops. transferEntityToWorld applies times or divide by 8.0 clamping plus portal placement. setPlayerLocation S08, inventory sync and S1D effect loop complete the handoff so buffs survive travel."
     },
     {
      "name": "playerLoggedIn",
      "detail_long": "playerLoggedIn joins the roster and announces presence with S38 tab-list packets. It appends to playerEntityList and uuidToPlayerMap for lookups and duplicate detection. It broadcasts S38 ADD_PLAYER for the newcomer to all existing players via sendPacketToAllPlayers. It spawns the entity in the dimension world and registers with preparePlayer to load chunks and tracking. It then loops the full roster and sends each existing ADD_PLAYER to the newcomer so tab lists converge symmetrically. No kick or teleport occurs here, position was already set by initializeConnectionToPlayer. Duplicate logins are handled earlier by createPlayerForUser kicking the old session.",
      "code": "    public void playerLoggedIn(EntityPlayerMP playerIn)\n    {\n        this.playerEntityList.add(playerIn);\n        this.uuidToPlayerMap.put(playerIn.getUniqueID(), playerIn);\n        this.sendPacketToAllPlayers(new S38PacketPlayerListItem(S38PacketPlayerListItem.Action.ADD_PLAYER, new EntityPlayerMP[] {playerIn}));\n        WorldServer worldserver = this.mcServer.worldServerForDimension(playerIn.dimension);\n        worldserver.spawnEntityInWorld(playerIn);\n        this.preparePlayer(playerIn, (WorldServer)null);\n\n        for (int i = 0; i < this.playerEntityList.size(); ++i)\n        {\n            EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playerEntityList.get(i);\n            playerIn.playerNetServerHandler.sendPacket(new S38PacketPlayerListItem(S38PacketPlayerListItem.Action.ADD_PLAYER, new EntityPlayerMP[] {entityplayermp}));\n        }\n    }",
      "code_walkthrough": "Adding to list and uuid map makes the player visible to commands and duplicate checks. The broadcast S38 ADD_PLAYER informs all clients to create tab-list entries. spawnEntityInWorld plus preparePlayer load the chunk and start entity tracking. The loop sends the full existing roster as individual S38 ADD_PLAYER packets to the newcomer. This two-way exchange keeps tab lists consistent on join."
     },
     {
      "name": "playerLoggedOut",
      "detail_long": "playerLoggedOut persists and removes a disconnecting player. It triggers leaveGameStat, writes NBT and stats via writePlayerData, and removes any ridden mount dangerously. It removes the player entity and its tracker entry, drops it from playerEntityList, and clears uuidToPlayerMap and stat files only if the mapped entry is identical. It broadcasts S38 REMOVE_PLAYER to remaining players so tab lists drop the entry. No packets go to the leaver because the channel is closing. The method is called from NetHandlerPlayServer onDisconnect after the quit message. Failure to remove from maps would leave ghost tab entries and block relogin.",
      "code": "    public void playerLoggedOut(EntityPlayerMP playerIn)\n    {\n        playerIn.triggerAchievement(StatList.leaveGameStat);\n        this.writePlayerData(playerIn);\n        WorldServer worldserver = playerIn.getServerForPlayer();\n\n        if (playerIn.ridingEntity != null)\n        {\n            worldserver.removePlayerEntityDangerously(playerIn.ridingEntity);\n            logger.debug(\"removing player mount\");\n        }\n\n        worldserver.removeEntity(playerIn);\n        worldserver.getPlayerManager().removePlayer(playerIn);\n        this.playerEntityList.remove(playerIn);\n        UUID uuid = playerIn.getUniqueID();\n        EntityPlayerMP entityplayermp = (EntityPlayerMP)this.uuidToPlayerMap.get(uuid);\n\n        if (entityplayermp == playerIn)\n        {\n            this.uuidToPlayerMap.remove(uuid);\n            this.playerStatFiles.remove(uuid);\n        }\n\n        this.sendPacketToAllPlayers(new S38PacketPlayerListItem(S38PacketPlayerListItem.Action.REMOVE_PLAYER, new EntityPlayerMP[] {playerIn}));\n    }",
      "code_walkthrough": "triggerAchievement plus writePlayerData flush stats and NBT before removal. The ridingEntity check removes horse, boat or pig mounts to avoid orphan vehicles. removeEntity plus removePlayer plus list removal detach tracking and roster membership. The identity check before map removal protects against deleting a newer duplicate login. The final S38 REMOVE_PLAYER broadcast tells clients to purge the tab entry."
     },
     {
      "name": "updateTimeAndWeatherForPlayer",
      "detail_long": "updateTimeAndWeatherForPlayer syncs border, clock and rain to one player after login, respawn or dimension change. It sends S44 WorldBorder INITIALIZE from the overworld border so the client enforces the same center and size. It sends S03 TimeUpdate with total time, day time and doDaylightCycle gamerule. If the target world isRaining it sends S2B state 1 to start rain, state 7 with rain strength and state 8 with thunder strength. Clear weather sends only border and time with no S2B. No kick or teleport occurs. Clients apply rain strength gradually to render particles and sky darkening.",
      "code": "    public void updateTimeAndWeatherForPlayer(EntityPlayerMP playerIn, WorldServer worldIn)\n    {\n        WorldBorder worldborder = this.mcServer.worldServers[0].getWorldBorder();\n        playerIn.playerNetServerHandler.sendPacket(new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.INITIALIZE));\n        playerIn.playerNetServerHandler.sendPacket(new S03PacketTimeUpdate(worldIn.getTotalWorldTime(), worldIn.getWorldTime(), worldIn.getGameRules().getBoolean(\"doDaylightCycle\")));\n\n        if (worldIn.isRaining())\n        {\n            playerIn.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(1, 0.0F));\n            playerIn.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(7, worldIn.getRainStrength(1.0F)));\n            playerIn.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(8, worldIn.getThunderStrength(1.0F)));\n        }\n    }",
      "code_walkthrough": "Fetching the overworld border ensures nether and end players share the same boundary. S44 INITIALIZE carries center, size and warning timers in one packet. S03PacketTimeUpdate carries total age, day time and daylight-cycle flag to drive the sun. The isRaining gate adds S2B 1, 7 and 8 for rain begin plus strength lerps. Without rain the client keeps clear skies from the earlier world load."
     }
    ]
   }
  },
  {
   "slug": "NetHandlerPlayServer",
   "title": "NetHandlerPlayServer",
   "rel": "net/minecraft/network/NetHandlerPlayServer.java",
   "desc": "Server play-state net handler: validates every C-packet (processPlayer movement gates, C02 reach, C0E clicks) and sends S08 corrections.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/NetHandlerPlayServer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/network/NetHandlerPlayServer.java",
   "packets": [
    "S00PacketKeepAlive",
    "S02PacketChat",
    "S07PacketRespawn",
    "S08PacketPlayerPosLook",
    "S18PacketEntityTeleport",
    "S23PacketBlockChange",
    "S2FPacketSetSlot",
    "S32PacketConfirmTransaction",
    "S3APacketTabComplete",
    "S40PacketDisconnect"
   ],
   "peers": [
    "EntityPlayerMP",
    "WorldServer",
    "NetworkManager",
    "PacketBuffer",
    "BlockPos",
    "AxisAlignedBB",
    "Entity",
    "EntityPlayer",
    "Container",
    "NetHandlerPlayClient",
    "ServerConfigurationManager",
    "PlayerManager",
    "ItemInWorldManager"
   ],
   "analysis": {
    "overview": "Server-side PLAY handler for one EntityPlayerMP. Validates all C00-C19 client packets on netty thread via PacketThreadUtil. Enforces movement, chat-spam, floating and reach gates; kicks or teleports back on violation.",
    "methods": [
     {
      "detail": "Sends S00 KeepAlive every 40 ticks; records lastPingTime. Decays chatSpamThresholdCount and itemDropThreshold. Kicks if idle longer than maxPlayerIdleMinutes.",
      "name": "update",
      "packets": [
       "S00"
      ],
      "purpose": "Per-tick keepalive, spam decay and idle kick."
     },
     {
      "detail": "Rejects NaN via func_183006_b with kick. Gates: abs>3.0E7 kick Illegal position; delta>100.0 teleport-back; 0.0625 moved-wrongly; 0.03125 float>80 ticks kick. Sleeping/riding branches.",
      "name": "processPlayer",
      "packets": [
       "C03",
       "C04",
       "C05",
       "C06",
       "S08",
       "S18"
      ],
      "purpose": "Authoritative movement and rotation validation."
     },
     {
      "detail": "Validates ChatAllowedCharacters else kick. Normalizes space. Adds 20 to chatSpamThresholdCount; kick disconnect.spam if >200 and non-op. Delegates / to command manager.",
      "name": "processChatMessage",
      "packets": [
       "C01",
       "S02"
      ],
      "purpose": "Broadcasts chat or executes slash command."
     },
     {
      "detail": "Distance gate 36.0 and buildLimit check else ignore. Protected/world-border blocks resync via S23 BlockChange. DROP_ITEM respects spectator; RELEASE_USE_ITEM stops use.",
      "name": "processPlayerDigging",
      "packets": [
       "C07",
       "S23"
      ],
      "purpose": "Handles dig, cancel, finish and item drop."
     },
     {
      "detail": "Direction 255 means use held item. Requires hasMoved and distSq<64.0, border/protection checks. Too-high build sends S02 chat. Always resyncs with S23; corrects slot with S2F.",
      "name": "processPlayerBlockPlacement",
      "packets": [
       "C08",
       "S23",
       "S2F",
       "S02"
      ],
      "purpose": "Handles use-item and block activate."
     },
     {
      "detail": "Requires matching windowId and getCanCraft. On mismatch stores uid in field_147372_n, sends S32 accepted=false, locks crafting until C0F confirm. Spectators get full resync.",
      "name": "processClickWindow",
      "packets": [
       "C0E",
       "S32"
      ],
      "purpose": "Validates container clicks and desync recovery."
     },
     {
      "detail": "Reach 36.0 if visible else 9.0. Kicks on attacking EntityItem/XPOrb/Arrow/self. INTERACT calls interactWith; INTERACT_AT forwards hitVec; ATTACK applies held item.",
      "name": "processUseEntity",
      "packets": [
       "C02"
      ],
      "purpose": "Validates interact and attack reach."
     },
     {
      "detail": "Only accepts key equal to field_147378_h. Sets ping=(ping*3+delta)/4 using nanoTime ms. No kick; stale keys ignored.",
      "name": "processKeepAlive",
      "packets": [
       "C00"
      ],
      "purpose": "Updates ping from keepalive echo."
     }
    ],
    "packet_usage": [
     {
      "direction": "handled",
      "id": "C00",
      "trigger": "Client echoes S00 key for ping"
     },
     {
      "direction": "handled",
      "id": "C01",
      "trigger": "Chat text or slash command"
     },
     {
      "direction": "handled",
      "id": "C02",
      "trigger": "Interact or attack entity"
     },
     {
      "direction": "handled",
      "id": "C03",
      "trigger": "Position/look/onGround update"
     },
     {
      "direction": "handled",
      "id": "C07",
      "trigger": "Dig state, drop item, stop use"
     },
     {
      "direction": "handled",
      "id": "C08",
      "trigger": "Block place or use item"
     },
     {
      "direction": "handled",
      "id": "C0E",
      "trigger": "Container slot click"
     },
     {
      "direction": "sent",
      "id": "S00",
      "trigger": "Periodic ping every 40 ticks"
     },
     {
      "direction": "sent",
      "id": "S08",
      "trigger": "Teleport-back or setPlayerLocation"
     },
     {
      "direction": "sent",
      "id": "S23",
      "trigger": "Resync rejected dig/place"
     }
    ],
    "internal_fields": [
     {
      "name": "playerEntity",
      "role": "Owning EntityPlayerMP being validated"
     },
     {
      "name": "floatingTickCount",
      "role": "Airborne ticks; >80 kicks for flying"
     },
     {
      "name": "chatSpamThresholdCount",
      "role": "+20 per chat, -1 per tick, >200 kick"
     },
     {
      "name": "lastPosX/Y/Z + hasMoved",
      "role": "Last acked pos for delta and teleport-back"
     },
     {
      "name": "field_147372_n",
      "role": "Pending transaction ids per window"
     }
    ],
    "peers": [
     "NetHandlerPlayClient",
     "ServerConfigurationManager",
     "EntityPlayerMP",
     "PlayerManager",
     "ItemInWorldManager"
    ],
    "methods_detailed": [
     {
      "name": "update",
      "detail_long": "update runs every server tick for each EntityPlayerMP to maintain connection health and throttle counters. It first clears field_147366_g and increments networkTickCount, then opens a keepAlive profiler section. If more than 40 ticks elapsed since lastSentPingPacket it refreshes lastSentPingPacket and lastPingTime from nanoTime millis, stores the int key in field_147378_h and sends S00PacketKeepAlive with that key. It then decays chatSpamThresholdCount by one if positive and does the same for itemDropThreshold, which implements the 20 per message and 20 per creative drop leak. Finally it checks idle kick using getLastActiveTime and getMaxPlayerIdleMinutes, kicking with You have been idle for too long if exceeded. No teleport-back occurs here, only S00 send and conditional S40 kick. The method explains the 40 tick ping cadence and the spam decay loop.",
      "code": "    public void update()\n    {\n        this.field_147366_g = false;\n        ++this.networkTickCount;\n        this.serverController.theProfiler.startSection(\"keepAlive\");\n\n        if ((long)this.networkTickCount - this.lastSentPingPacket > 40L)\n        {\n            this.lastSentPingPacket = (long)this.networkTickCount;\n            this.lastPingTime = this.currentTimeMillis();\n            this.field_147378_h = (int)this.lastPingTime;\n            this.sendPacket(new S00PacketKeepAlive(this.field_147378_h));\n        }\n\n        this.serverController.theProfiler.endSection();\n\n        if (this.chatSpamThresholdCount > 0)\n        {\n            --this.chatSpamThresholdCount;\n        }",
      "code_walkthrough": "The tick counter and keepAlive section frame the periodic work. The greater-than-40L gate throttles S00PacketKeepAlive so ping is sampled about every two seconds. lastPingTime and field_147378_h store the key that processKeepAlive must later echo to compute ping. S00PacketKeepAlive carries that int key to the client for round-trip timing. The chatSpamThresholdCount decrement implements one unit of leak per tick against the plus-20 per chat addition. The following itemDropThreshold block applies the same leak to creative drops."
     },
     {
      "name": "processPlayer",
      "detail_long": "processPlayer is the authoritative movement validator for C03, C04, C05 and C06 packets on the net thread. It first rejects non-finite doubles or floats via func_183006_b and kicks with Invalid move packet received. It then handles special branches for riding entities, sleeping players and conquered End before normal walking. For normal moves it enforces absolute border abs greater than 3.0E7 with kick Illegal position. It enforces speed by comparing squared delta minus motion squared against 100.0D and teleporting back with setPlayerLocation S08 on violation. It enforces collision with a 0.0625F contracted box, flags moved-wrongly when residual delta exceeds 0.0625D, and teleport-backs if cheating through blocks. It enforces floating by counting ticks with fall less than minus 0.03125D threshold and kicking after 80 ticks when flight is not allowed. Riding divergence over 4.0D sends S18PacketEntityTeleport plus S08 correction.",
      "code": "                    if (packetIn.isMoving())\n                    {\n                        d8 = packetIn.getPositionX();\n                        d9 = packetIn.getPositionY();\n                        d10 = packetIn.getPositionZ();\n\n                        if (Math.abs(packetIn.getPositionX()) > 3.0E7D || Math.abs(packetIn.getPositionZ()) > 3.0E7D)\n                        {\n                            this.kickPlayerFromServer(\"Illegal position\");\n                            return;\n                        }\n                    }\n\n                    if (packetIn.getRotating())\n                    {\n                        f1 = packetIn.getYaw();\n                        f2 = packetIn.getPitch();\n                    }\n\n                    this.playerEntity.onUpdateEntity();\n                    this.playerEntity.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, f1, f2);\n\n                    if (!this.hasMoved)\n                    {\n                        return;\n                    }",
      "code_walkthrough": "The isMoving branch copies the claimed X Y Z into d8 d9 d10 for later reconciliation. The 3.0E7D absolute check kicks with Illegal position to enforce world border limits. The isRotating branch copies yaw and pitch into f1 f2 without yet applying position. onUpdateEntity and setPositionAndRotation rewind the player to last acked lastPos values so moveEntity can replay safely. The hasMoved false early return holds the player frozen until setPlayerLocation completes, which is the teleport-back mechanism. Cheat angles include ground-spoof via onGround flag and speed disablers that try to stay under the 100.0D delta gate."
     },
     {
      "name": "processChatMessage",
      "detail_long": "processChatMessage handles inbound C01 chat and slash commands after PacketThreadUtil enqueue. If chat visibility is HIDDEN it replies with S02PacketChat chat.cannotSend in red and stops. Otherwise it marks the player active, normalizes whitespace with StringUtils.normalizeSpace and scans every char with ChatAllowedCharacters, kicking with Illegal characters in chat on failure. Strings starting with slash are delegated to handleSlashCommand and the command manager, others are broadcast as chat.type.text via sendChatMsgImpl. After dispatch it adds 20 to chatSpamThresholdCount and kicks with disconnect.spam if over 200 and the sender lacks command permission via canSendCommands. Ops and command-allowed players bypass the spam kick but still accumulate the counter. No teleport occurs, outcomes are S02 error reply, broadcast S02, or S40 kick.",
      "code": "            this.playerEntity.markPlayerActive();\n            String s = packetIn.getMessage();\n            s = StringUtils.normalizeSpace(s);\n\n            for (int i = 0; i < s.length(); ++i)\n            {\n                if (!ChatAllowedCharacters.isAllowedCharacter(s.charAt(i)))\n                {\n                    this.kickPlayerFromServer(\"Illegal characters in chat\");\n                    return;\n                }\n            }\n\n            if (s.startsWith(\"/\"))\n            {\n                this.handleSlashCommand(s);\n            }\n            else\n            {\n                IChatComponent ichatcomponent = new ChatComponentTranslation(\"chat.type.text\", new Object[] {this.playerEntity.getDisplayName(), s});\n                this.serverController.getConfigurationManager().sendChatMsgImpl(ichatcomponent, false);\n            }\n\n            this.chatSpamThresholdCount += 20;\n\n            if (this.chatSpamThresholdCount > 200 && !this.serverController.getConfigurationManager().canSendCommands(this.playerEntity.getGameProfile()))\n            {\n                this.kickPlayerFromServer(\"disconnect.spam\");\n            }",
      "code_walkthrough": "markPlayerActive resets idle time so chat counts as activity. normalizeSpace and the per-character isAllowedCharacter loop enforce the chat charset gate with kick on illegal characters. The startsWith slash branch separates commands from public broadcast via sendChatMsgImpl which fans out S02PacketChat. The plus-20 increment with greater-than-200 check implements the token bucket that update leaks by one per tick. The canSendCommands exemption lets ops burst without disconnect.spam kick, which spammers abuse by flooding just under the rate."
     },
     {
      "name": "processPlayerDigging",
      "detail_long": "processPlayerDigging validates C07 dig, cancel, finish, drop and stop-use actions. DROP_ITEM and DROP_ALL_ITEMS are allowed only for non-spectators and call dropOneItem false or true. RELEASE_USE_ITEM calls stopUsingItem to end blocking or eating. For START, ABORT and STOP it computes squared distance from eye-adjusted player pos and silently returns if over 36.0D, which is six blocks reach. It also silently returns if block Y is at or above getBuildLimit. START checks isBlockProtected and world border contains, calling onBlockClicked on success or resyncing with S23PacketBlockChange on failure. STOP calls blockRemoving, ABORT calls cancelDestroyingBlock, then resends S23 if the block is still non-air. Invalid status throws IllegalArgumentException with no packet.",
      "code": "                double d0 = this.playerEntity.posX - ((double)blockpos.getX() + 0.5D);\n                double d1 = this.playerEntity.posY - ((double)blockpos.getY() + 0.5D) + 1.5D;\n                double d2 = this.playerEntity.posZ - ((double)blockpos.getZ() + 0.5D);\n                double d3 = d0 * d0 + d1 * d1 + d2 * d2;\n\n                if (d3 > 36.0D)\n                {\n                    return;\n                }\n                else if (blockpos.getY() >= this.serverController.getBuildLimit())\n                {\n                    return;\n                }\n                else\n                {\n                    if (packetIn.getStatus() == C07PacketPlayerDigging.Action.START_DESTROY_BLOCK)\n                    {\n                        if (!this.serverController.isBlockProtected(worldserver, blockpos, this.playerEntity) && worldserver.getWorldBorder().contains(blockpos))\n                        {\n                            this.playerEntity.theItemInWorldManager.onBlockClicked(blockpos, packetIn.getFacing());\n                        }\n                        else\n                        {\n                            this.playerEntity.playerNetServerHandler.sendPacket(new S23PacketBlockChange(worldserver, blockpos));\n                        }",
      "code_walkthrough": "The d0 d1 d2 math builds eye-centered squared distance with plus 0.5 centering and plus 1.5 height offset. The greater-than-36.0D return silently drops over-reach digs without kick or resync. The buildLimit return blocks digs above world height. The START_DESTROY_BLOCK branch checks spawn protection and world border before allowing onBlockClicked. The else sends S23PacketBlockChange carrying server block state to force client resync on protected or out-of-border digs."
     },
     {
      "name": "processPlayerBlockPlacement",
      "detail_long": "processPlayerBlockPlacement handles C08 right-click use-item and block activate. Direction 255 means use held item in air, calling tryUseItem if stack is non-null and returning early. Otherwise it checks build height with getBuildLimit minus one for upward faces and sends red S02PacketChat build.tooHigh when exceeded. For valid heights it requires hasMoved true, squared distance under 64.0D or eight blocks, no spawn protection and world border contains before calling activateBlockOrUseItem. Whether activated or denied it sets flag true to trigger dual S23PacketBlockChange resyncs for target and offset pos. Afterwards it clears zero-size stacks, copies the inventory slot when max use duration is zero, and corrects mismatched held stacks with S2FPacketSetSlot. Spectator and null-stack edges return without action.",
      "code": "        if (packetIn.getPlacedBlockDirection() == 255)\n        {\n            if (itemstack == null)\n            {\n                return;\n            }\n\n            this.playerEntity.theItemInWorldManager.tryUseItem(this.playerEntity, worldserver, itemstack);\n        }\n        else if (blockpos.getY() < this.serverController.getBuildLimit() - 1 || enumfacing != EnumFacing.UP && blockpos.getY() < this.serverController.getBuildLimit())\n        {\n            if (this.hasMoved && this.playerEntity.getDistanceSq((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D) < 64.0D && !this.serverController.isBlockProtected(worldserver, blockpos, this.playerEntity) && worldserver.getWorldBorder().contains(blockpos))\n            {\n                this.playerEntity.theItemInWorldManager.activateBlockOrUseItem(this.playerEntity, worldserver, itemstack, blockpos, enumfacing, packetIn.getPlacedBlockOffsetX(), packetIn.getPlacedBlockOffsetY(), packetIn.getPlacedBlockOffsetZ());\n            }\n\n            flag = true;\n        }\n        else\n        {\n            ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(\"build.tooHigh\", new Object[] {Integer.valueOf(this.serverController.getBuildLimit())});\n            chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED);\n            this.playerEntity.playerNetServerHandler.sendPacket(new S02PacketChat(chatcomponenttranslation));\n            flag = true;\n        }",
      "code_walkthrough": "The 255 direction branch isolates air-use like eating or throwing from block clicks. The buildLimit minus one check separates allowed placement from tooHigh, with UP faces held one lower. The hasMoved plus less-than-64.0D plus protection plus border line gates reach, teleport state, spawn guard and border in one condition. activateBlockOrUseItem carries offsets and facing to apply the actual placement or interaction. The else sends S02PacketChat build.tooHigh in red and the flag triggers S23 resyncs, which prevents ghost blocks."
     },
     {
      "name": "processClickWindow",
      "detail_long": "processClickWindow validates C0E container clicks against the openContainer windowId and getCanCraft flag. Mismatched windowId or locked crafting is ignored entirely with no packet. Spectators bypass slotClick and get a full inventory resync via updateCraftingInventory. For survival players it calls slotClick and compares the result with the client predicted clickedItem via areItemStacksEqual. On match it sends S32PacketConfirmTransaction accepted true, then detectAndSendChanges and updateHeldItem. On mismatch it stores the action number in field_147372_n, sends S32 accepted false, locks further crafting with setCanCraft false and pushes the full server inventory list. The lock persists until C0F confirm with matching uid unlocks it. This is the classic desync recovery and dup-prevention gate.",
      "code": "                ItemStack itemstack = this.playerEntity.openContainer.slotClick(packetIn.getSlotId(), packetIn.getUsedButton(), packetIn.getMode(), this.playerEntity);\n\n                if (ItemStack.areItemStacksEqual(packetIn.getClickedItem(), itemstack))\n                {\n                    this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true));\n                    this.playerEntity.isChangingQuantityOnly = true;\n                    this.playerEntity.openContainer.detectAndSendChanges();\n                    this.playerEntity.updateHeldItem();\n                    this.playerEntity.isChangingQuantityOnly = false;\n                }\n                else\n                {\n                    this.field_147372_n.addKey(this.playerEntity.openContainer.windowId, Short.valueOf(packetIn.getActionNumber()));\n                    this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false));\n                    this.playerEntity.openContainer.setCanCraft(this.playerEntity, false);\n                    List<ItemStack> list1 = Lists.<ItemStack>newArrayList();\n\n                    for (int j = 0; j < this.playerEntity.openContainer.inventorySlots.size(); ++j)\n                    {\n                        list1.add(((Slot)this.playerEntity.openContainer.inventorySlots.get(j)).getStack());\n                    }\n\n                    this.playerEntity.updateCraftingInventory(this.playerEntity.openContainer, list1);",
      "code_walkthrough": "slotClick applies the server-side inventory logic for the given slot button and mode. areItemStacksEqual compares client prediction to server result to detect desync or cheating. The true branch sends S32 accepted true carrying windowId and action number to confirm the transaction. The false branch stores the action number in field_147372_n, sends S32 accepted false, and locks crafting with setCanCraft false. The slot loop plus updateCraftingInventory pushes authoritative stacks, and C0F must later echo the stored uid to unlock."
     },
     {
      "name": "processUseEntity",
      "detail_long": "processUseEntity validates C02 interact and attack after enqueue on the server thread. It resolves the entity from the world by ID and marks the player active, ignoring null entities silently. It computes visibility via canEntityBeSeen to select reach squared 36.0D when visible or 9.0D when not, which is six versus three blocks. If squared distance exceeds the gate the packet is dropped with no response. INTERACT calls interactWith, INTERACT_AT forwards hitVec to interactAt for armor stands and villagers. ATTACK kicks with Attempting to attack an invalid entity plus server warning if target is EntityItem, EntityXPOrb, EntityArrow or self. Otherwise it calls attackTargetEntityWithCurrentItem to apply damage and enchants. No S packets are sent here except the kick disconnect.",
      "code": "            boolean flag = this.playerEntity.canEntityBeSeen(entity);\n            double d0 = 36.0D;\n\n            if (!flag)\n            {\n                d0 = 9.0D;\n            }\n\n            if (this.playerEntity.getDistanceSqToEntity(entity) < d0)\n            {\n                if (packetIn.getAction() == C02PacketUseEntity.Action.INTERACT)\n                {\n                    this.playerEntity.interactWith(entity);\n                }\n                else if (packetIn.getAction() == C02PacketUseEntity.Action.INTERACT_AT)\n                {\n                    entity.interactAt(this.playerEntity, packetIn.getHitVec());\n                }\n                else if (packetIn.getAction() == C02PacketUseEntity.Action.ATTACK)\n                {\n                    if (entity instanceof EntityItem || entity instanceof EntityXPOrb || entity instanceof EntityArrow || entity == this.playerEntity)\n                    {\n                        this.kickPlayerFromServer(\"Attempting to attack an invalid entity\");\n                        this.serverController.logWarning(\"Player \" + this.playerEntity.getName() + \" tried to attack an invalid entity\");\n                        return;",
      "code_walkthrough": "canEntityBeSeen selects the reach gate of 36.0 versus 9.0 squared to stop wall-hit kill aura. The getDistanceSqToEntity less-than-d0 check drops out-of-reach uses without kick to tolerate lag. INTERACT versus INTERACT_AT separates leash and trade from precise hit-vector armor-stand poses. The ATTACK instanceof chain identifies invalid targets like items, XP orbs, arrows and self that normal clients never hit. The kick plus logWarning punishes packet-forged attacks, a common kill-aura and crash exploit probe."
     },
     {
      "name": "processKeepAlive",
      "detail_long": "processKeepAlive handles C00 echo replies used for ping measurement. It runs on netty without PacketThreadUtil enqueue because it only touches volatile timing fields. It compares the echoed key to field_147378_h set by update when S00 was sent. Only exact match updates ping, stale or forged keys are ignored with no kick. On match it computes delta as currentTimeMillis nano millis minus lastPingTime. It smooths ping with weighted average ping times three plus delta divided by four. No packets are sent in response and no kick or teleport occurs. This explains why disabler cheats delay or spoof keepalive to fake lag without triggering fails.",
      "code": "    public void processKeepAlive(C00PacketKeepAlive packetIn)\n    {\n        if (packetIn.getKey() == this.field_147378_h)\n        {\n            int i = (int)(this.currentTimeMillis() - this.lastPingTime);\n            this.playerEntity.ping = (this.playerEntity.ping * 3 + i) / 4;\n        }\n    }",
      "code_walkthrough": "The getKey equals field_147378_h gate ensures only the latest S00 echo counts. currentTimeMillis minus lastPingTime yields round-trip millis using nanoTime resolution. The ping times three plus i divided by four formula smooths jitter across samples. Ignoring mismatched keys avoids penalizing reordered packets, which is why timing disablers hold keepalives to simulate lag."
     }
    ]
   }
  },
  {
   "slug": "NetHandlerPlayClient",
   "title": "NetHandlerPlayClient",
   "rel": "net/minecraft/client/network/NetHandlerPlayClient.java",
   "desc": "Client play-state net handler: handle<Entity> dispatch for every S-packet plus C00/C03/C0F/C17/C19 replies upstream.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/NetHandlerPlayClient/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/client/network/NetHandlerPlayClient.java",
   "packets": [
    "C00PacketKeepAlive",
    "C03PacketPlayer",
    "C0FPacketConfirmTransaction",
    "C17PacketCustomPayload",
    "C19PacketResourcePackStatus"
   ],
   "peers": [
    "EntityPlayerSP",
    "PlayerControllerMP",
    "PlayerManager",
    "EntityLivingBase",
    "Minecraft",
    "NetworkManager",
    "PacketBuffer",
    "MathHelper",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "Container",
    "NetHandlerPlayServer",
    "ServerConfigurationManager"
   ],
   "analysis": {
    "overview": "Client-side PLAY handler applying server state to WorldClient. Dispatches S00-S49 to world, GUI, scoreboard and entities via PacketThreadUtil. Replies with C00 keepalive, C03 pos-look ack, C0F confirm and C17 brand.",
    "methods": [
     {
      "detail": "Builds WorldClient from gametype/dimension/difficulty. Sets maxPlayers, reducedDebug. Sends MC|Brand custom payload and client settings to server.",
      "name": "handleJoinGame",
      "packets": [
       "S01",
       "C17"
      ],
      "purpose": "Creates WorldClient and player controller."
     },
     {
      "detail": "Adds relative flags X/Y/Z/Y_ROT/X_ROT to player pos; zeroes motion on absolute axes. Replies C06 PosLook. First receipt sets doneLoadingTerrain and closes download screen.",
      "name": "handlePlayerPosLook",
      "packets": [
       "S08",
       "C03"
      ],
      "purpose": "Applies server teleport and acks it."
     },
     {
      "detail": "Scales pos /32.0, yaw/pitch *360/256. Type switch: 10 minecart, 60 arrow, 1 boat, 70 fallingblock. Sets serverPos, entityId, velocity /8000.0 and adds to world.",
      "name": "handleSpawnObject",
      "packets": [
       "S0E"
      ],
      "purpose": "Spawns vehicles, projectiles and tiles."
     },
     {
      "detail": "If extractedSize==0 does preChunk unload. Else preChunk load, invalidate region, fillChunk, mark render update. Resets relight unless surface world with full chunk.",
      "name": "handleChunkData",
      "packets": [
       "S21"
      ],
      "purpose": "Loads or unloads a chunk column."
     },
     {
      "detail": "Resolves inventoryContainer vs openContainer by windowId. If S32 accepted=false, replies C0F accepted=true to resync. No action on accepted.",
      "name": "handleConfirmTransaction",
      "packets": [
       "S32",
       "C0F"
      ],
      "purpose": "Acks server inventory transaction."
     },
     {
      "detail": "If dimension differs clears doneLoadingTerrain, preserves scoreboard, creates new WorldClient, shows download terrain. Then setDimensionAndSpawnPlayer and game type.",
      "name": "handleRespawn",
      "packets": [
       "S07"
      ],
      "purpose": "Rebuilds WorldClient on dimension change."
     },
     {
      "detail": "level:// loads local file else checks ServerResourceMode. ENABLED auto-accepts, DISABLED declines, PROMPT shows GuiYesNo. Replies C19 ACCEPTED/DECLINED/SUCCESS/FAIL.",
      "name": "handleResourcePack",
      "packets": [
       "S48",
       "C19"
      ],
      "purpose": "Prompts and downloads server pack."
     },
     {
      "detail": "MC|TrList sets villager recipes if windowId matches. MC|Brand sets clientBrand. MC|BOpen opens written-book GUI. Releases buffer after read.",
      "name": "handleCustomPayload",
      "packets": [
       "S3F"
      ],
      "purpose": "Handles MC|TrList, Brand and BOpen."
     }
    ],
    "packet_usage": [
     {
      "direction": "handled",
      "id": "S01",
      "trigger": "Join: init world and player"
     },
     {
      "direction": "handled",
      "id": "S08",
      "trigger": "Server teleport or login position"
     },
     {
      "direction": "handled",
      "id": "S21",
      "trigger": "Chunk column load/unload"
     },
     {
      "direction": "handled",
      "id": "S32",
      "trigger": "Inventory transaction result"
     },
     {
      "direction": "handled",
      "id": "S48",
      "trigger": "Server resource-pack request"
     },
     {
      "direction": "sent",
      "id": "C00",
      "trigger": "Echo S00 keepalive key"
     },
     {
      "direction": "sent",
      "id": "C03",
      "trigger": "Ack S08 pos-look"
     },
     {
      "direction": "sent",
      "id": "C0F",
      "trigger": "Confirm failed transaction"
     },
     {
      "direction": "sent",
      "id": "C17",
      "trigger": "Send MC|Brand on join"
     },
     {
      "direction": "sent",
      "id": "C19",
      "trigger": "Resource-pack status reply"
     }
    ],
    "internal_fields": [
     {
      "name": "clientWorldController",
      "role": "Active WorldClient being mutated"
     },
     {
      "name": "playerInfoMap",
      "role": "UUID to NetworkPlayerInfo tab-list cache"
     },
     {
      "name": "doneLoadingTerrain",
      "role": "Gate set by first S08, reset on respawn"
     },
     {
      "name": "gameController",
      "role": "Minecraft instance for GUI and world"
     },
     {
      "name": "netManager",
      "role": "Channel used for replies and queue"
     }
    ],
    "peers": [
     "NetHandlerPlayServer",
     "WorldClient",
     "PlayerControllerMP",
     "NetworkPlayerInfo",
     "ServerConfigurationManager"
    ],
    "methods_detailed": [
     {
      "name": "handleJoinGame",
      "detail_long": "handleJoinGame processes S01 on the client thread via PacketThreadUtil and builds the initial WorldClient. It installs a new PlayerControllerMP, then constructs WorldClient from gameType, hardcore flag, world type, dimension, difficulty and profiler. It copies difficulty into gameSettings, loads the world, sets thePlayer dimension and shows GuiDownloadTerrain. It assigns the server entityId, stores maxPlayers in currentServerMaxPlayers and applies reducedDebug. It sets the controller gameType, pushes client settings to the server and sends C17 MC|Brand with ClientBrandRetriever mod name. No kick occurs here, the reply packets are C17 brand and settings. Failure to receive later S08 keeps the download screen up.",
      "code": "    public void handleJoinGame(S01PacketJoinGame packetIn)\n    {\n        PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController);\n        this.gameController.playerController = new PlayerControllerMP(this.gameController, this);\n        this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, packetIn.isHardcoreMode(), packetIn.getWorldType()), packetIn.getDimension(), packetIn.getDifficulty(), this.gameController.mcProfiler);\n        this.gameController.gameSettings.difficulty = packetIn.getDifficulty();\n        this.gameController.loadWorld(this.clientWorldController);\n        this.gameController.thePlayer.dimension = packetIn.getDimension();\n        this.gameController.displayGuiScreen(new GuiDownloadTerrain(this));\n        this.gameController.thePlayer.setEntityId(packetIn.getEntityId());\n        this.currentServerMaxPlayers = packetIn.getMaxPlayers();\n        this.gameController.thePlayer.setReducedDebug(packetIn.isReducedDebugInfo());\n        this.gameController.playerController.setGameType(packetIn.getGameType());\n        this.gameController.gameSettings.sendSettingsToServer();\n        this.netManager.sendPacket(new C17PacketCustomPayload(\"MC|Brand\", (new PacketBuffer(Unpooled.buffer())).writeString(ClientBrandRetriever.getClientModName())));\n    }",
      "code_walkthrough": "checkThreadAndEnqueue hops S01 onto the main client thread before touching the world. The WorldClient constructor carries gameType, hardcore, world type, dimension and difficulty that define physics and rendering. loadWorld plus GuiDownloadTerrain blocks input until terrain and S08 arrive. setEntityId and currentServerMaxPlayers bind the local player to the server id and tab-list cap. The final C17 MC|Brand reply advertises vanilla or modded client to the server."
     },
     {
      "name": "handlePlayerPosLook",
      "detail_long": "handlePlayerPosLook applies S08 server teleports and corrections on the client thread. It reads absolute X Y Z yaw pitch, then adds current player pos or rotation when relative flags X Y Z Y_ROT X_ROT are present. For absolute axes it zeroes motionX, motionY or motionZ to stop rubber-band sliding. It then calls setPositionAndRotation and immediately replies with C06 PacketPlayerPosLook using posX, bounding-box minY, posZ, yaw, pitch and false onGround. On first receipt when doneLoadingTerrain is false it snapshots prevPos, sets the flag true and closes the download screen. Later receipts just correct position without GUI change. No kick occurs, the only response is the C03 C06 ack which lets the server clear hasMoved.",
      "code": "        if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.X_ROT))\n        {\n            f1 += entityplayer.rotationPitch;\n        }\n\n        if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Y_ROT))\n        {\n            f += entityplayer.rotationYaw;\n        }\n\n        entityplayer.setPositionAndRotation(d0, d1, d2, f, f1);\n        this.netManager.sendPacket(new C03PacketPlayer.C06PacketPlayerPosLook(entityplayer.posX, entityplayer.getEntityBoundingBox().minY, entityplayer.posZ, entityplayer.rotationYaw, entityplayer.rotationPitch, false));\n\n        if (!this.doneLoadingTerrain)\n        {\n            this.gameController.thePlayer.prevPosX = this.gameController.thePlayer.posX;\n            this.gameController.thePlayer.prevPosY = this.gameController.thePlayer.posY;\n            this.gameController.thePlayer.prevPosZ = this.gameController.thePlayer.posZ;\n            this.doneLoadingTerrain = true;\n            this.gameController.displayGuiScreen((GuiScreen)null);\n        }\n    }",
      "code_walkthrough": "The X_ROT and Y_ROT flag checks add current pitch and yaw for relative look teleports. setPositionAndRotation applies the final merged coordinates and angles to the local player. The C06 reply carries bounding-box minY and false onGround so the server can validate the ack. The doneLoadingTerrain false branch fires once to initialize prevPos and dismiss GuiDownloadTerrain. Repeated S08 packets cause server-side teleport-backs that clients must ack to avoid movement freeze."
     },
     {
      "name": "handleSpawnObject",
      "detail_long": "handleSpawnObject spawns S0E vehicles, projectiles and blocks in WorldClient. It scales network X Y Z by dividing by 32.0D to get block coordinates. It switches on type where 10 is minecart with subtype, 60 arrow, 61 snowball, 62 egg, 63 large fireball, 64 small fireball, 65 ender pearl, 66 wither skull, 71 item frame, 72 eye, 73 potion, 75 bottle, 76 firework, 77 leash, 78 armor stand, 1 boat, 2 item, 50 TNT, 51 crystal, 70 falling block and 90 fish hook. Fish hook resolves the thrower entity and resets data to zero, frames and leashes floor coords and reset data. After creation it copies serverPos, converts yaw and pitch with times 360 divided by 256, fixes multipart ids, sets entityId and adds to world. If data is positive it sets velocity divided by 8000.0D and links arrows to shooter living base.",
      "code": "    public void handleSpawnObject(S0EPacketSpawnObject packetIn)\n    {\n        PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController);\n        double d0 = (double)packetIn.getX() / 32.0D;\n        double d1 = (double)packetIn.getY() / 32.0D;\n        double d2 = (double)packetIn.getZ() / 32.0D;\n        Entity entity = null;\n\n        if (packetIn.getType() == 10)\n        {\n            entity = EntityMinecart.getMinecart(this.clientWorldController, d0, d1, d2, EntityMinecart.EnumMinecartType.byNetworkID(packetIn.func_149009_m()));\n        }\n        else if (packetIn.getType() == 90)\n        {\n            Entity entity1 = this.clientWorldController.getEntityByID(packetIn.func_149009_m());\n\n            if (entity1 instanceof EntityPlayer)\n            {\n                entity = new EntityFishHook(this.clientWorldController, d0, d1, d2, (EntityPlayer)entity1);\n            }\n\n            packetIn.func_149002_g(0);",
      "code_walkthrough": "checkThreadAndEnqueue ensures spawning happens on the render thread. Dividing by 32.0D converts fixed-point network coords to doubles for accurate placement. The type 10 branch builds minecarts with network subtype for chest, furnace and TNT variants. The type 90 branch looks up the thrower player to attach the fish hook and clears extra data. Later code scales yaw and pitch by 360 over 256 and velocity by 8000, which cheats cannot spoof without server correction."
     },
     {
      "name": "handleChunkData",
      "detail_long": "handleChunkData applies S21 chunk column load or unload on the client thread. If the packet is a full-chunk preChunk signal it checks extracted size, where zero means unload via doPreChunk false and return. Non-zero calls doPreChunk true to allocate the column. It then invalidates the 16 by 256 by 16 receive region, fetches the Chunk object and fills it with extracted bytes, size and full flag. It marks the block range for render update so lighting and meshes rebuild. If not a full chunk or the provider is not surface world, it resets relight checks to avoid stale skylight. Unloads free memory while loads populate blocks and biomes. No reply packet is sent.",
      "code": "    public void handleChunkData(S21PacketChunkData packetIn)\n    {\n        PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController);\n\n        if (packetIn.func_149274_i())\n        {\n            if (packetIn.getExtractedSize() == 0)\n            {\n                this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false);\n                return;\n            }\n\n            this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true);\n        }\n\n        this.clientWorldController.invalidateBlockReceiveRegion(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15);\n        Chunk chunk = this.clientWorldController.getChunkFromChunkCoords(packetIn.getChunkX(), packetIn.getChunkZ());\n        chunk.fillChunk(packetIn.getExtractedDataBytes(), packetIn.getExtractedSize(), packetIn.func_149274_i());\n        this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15);\n\n        if (!packetIn.func_149274_i() || !(this.clientWorldController.provider instanceof WorldProviderSurface))\n        {\n            chunk.resetRelightChecks();\n        }\n    }",
      "code_walkthrough": "The func_149274_i gate distinguishes full-column init from delta updates. Zero extracted size with full flag means unload, so doPreChunk false drops the column. Non-zero calls doPreChunk true then fillChunk with the compressed byte payload. invalidateBlockReceiveRegion and markBlockRangeForRenderUpdate bracket the fill to refresh lighting and rendering. The surface-world check skips relight reset for nether and end where skylight differs."
     },
     {
      "name": "handleConfirmTransaction",
      "detail_long": "handleConfirmTransaction processes S32 server inventory verdicts on the client thread. It resolves the target container by windowId, where zero means inventoryContainer and otherwise the openContainer only if ids match. Null containers from stale windows are ignored. If the packet reports accepted false via func_148888_e it replies with C0F confirm accepted true carrying the same windowId and action number. Accepted true packets need no reply because both sides agree. The C0F reply unlocks the server-side canCraft lock set by processClickWindow mismatch. This single round trip resyncs duped or ghost clicks. No kick or teleport occurs.",
      "code": "    public void handleConfirmTransaction(S32PacketConfirmTransaction packetIn)\n    {\n        PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController);\n        Container container = null;\n        EntityPlayer entityplayer = this.gameController.thePlayer;\n\n        if (packetIn.getWindowId() == 0)\n        {\n            container = entityplayer.inventoryContainer;\n        }\n        else if (packetIn.getWindowId() == entityplayer.openContainer.windowId)\n        {\n            container = entityplayer.openContainer;\n        }\n\n        if (container != null && !packetIn.func_148888_e())\n        {\n            this.addToSendQueue(new C0FPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true));\n        }\n    }",
      "code_walkthrough": "checkThreadAndEnqueue moves the verdict to the main thread. The windowId zero versus openContainer match selects inventory versus chest, furnace or crafting table. Null from closed windows is dropped to avoid acting on stale ids. The not-accepted check via func_148888_e triggers a C0F with accepted true to acknowledge the server correction. That C0F carries windowId and action number so the server can clear field_147372_n and re-enable crafting."
     },
     {
      "name": "handleRespawn",
      "detail_long": "handleRespawn rebuilds WorldClient on S07 dimension change or difficulty sync. It first compares packet dimension to thePlayer dimension to detect cross-dimension moves. On change it clears doneLoadingTerrain, preserves the old scoreboard, constructs a new WorldClient with gameType, hardcore flag, world type, dimension and difficulty, then loads it and shows GuiDownloadTerrain. It always calls setDimensionAndSpawnPlayer and setGameType from the packet even for same-dimension respawns. The scoreboard carry-over keeps teams and objectives across deaths. No reply packet is sent, the client waits for follow-up S08 position and S21 chunks. This explains respawn flicker and why mods must rebind world references.",
      "code": "    public void handleRespawn(S07PacketRespawn packetIn)\n    {\n        PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController);\n\n        if (packetIn.getDimensionID() != this.gameController.thePlayer.dimension)\n        {\n            this.doneLoadingTerrain = false;\n            Scoreboard scoreboard = this.clientWorldController.getScoreboard();\n            this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, this.gameController.theWorld.getWorldInfo().isHardcoreModeEnabled(), packetIn.getWorldType()), packetIn.getDimensionID(), packetIn.getDifficulty(), this.gameController.mcProfiler);\n            this.clientWorldController.setWorldScoreboard(scoreboard);\n            this.gameController.loadWorld(this.clientWorldController);\n            this.gameController.thePlayer.dimension = packetIn.getDimensionID();\n            this.gameController.displayGuiScreen(new GuiDownloadTerrain(this));\n        }\n\n        this.gameController.setDimensionAndSpawnPlayer(packetIn.getDimensionID());\n        this.gameController.playerController.setGameType(packetIn.getGameType());\n    }",
      "code_walkthrough": "The dimension mismatch gate separates full world rebuild from same-world respawn. Clearing doneLoadingTerrain forces the next S08 to dismiss the download screen. Saving and restoring the scoreboard preserves teams across dimension travel. The WorldClient constructor with gameType and difficulty reapplies rules for the new dimension. The final setDimensionAndSpawnPlayer plus setGameType sync player controller even when no rebuild occurred."
     },
     {
      "name": "handleResourcePack",
      "detail_long": "handleResourcePack implements S48 server pack prompt with C19 status replies. It extracts URL and hash, then branches on level slash slash prefix for local saves versus remote packs. Local files under saves are checked with isFile, replying ACCEPTED then async SUCCESSFULLY_LOADED or FAILED_DOWNLOAD, or immediate FAILED_DOWNLOAD if missing. Remote packs check ServerData resource mode where ENABLED auto-accepts and downloads, DISABLED replies DECLINED, and PROMPT schedules a GuiYesNo dialog. Confirming yes sets mode ENABLED, sends ACCEPTED and downloads, while no sets DISABLED and sends DECLINED. Downloads use the repository with Futures callbacks that send final C19 status. No kick occurs directly, but servers may kick on DECLINED.",
      "code": "    public void handleResourcePack(S48PacketResourcePackSend packetIn)\n    {\n        final String s = packetIn.getURL();\n        final String s1 = packetIn.getHash();\n\n        if (s.startsWith(\"level://\"))\n        {\n            String s2 = s.substring(\"level://\".length());\n            File file1 = new File(this.gameController.mcDataDir, \"saves\");\n            File file2 = new File(file1, s2);\n\n            if (file2.isFile())\n            {\n                this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.ACCEPTED));\n                Futures.addCallback(this.gameController.getResourcePackRepository().setResourcePackInstance(file2), new FutureCallback<Object>()\n                {\n                    public void onSuccess(Object p_onSuccess_1_)\n                    {\n                        NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.SUCCESSFULLY_LOADED));\n                    }\n                    public void onFailure(Throwable p_onFailure_1_)\n                    {\n                        NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD));\n                    }\n                });\n            }\n            else\n            {\n                this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD));",
      "code_walkthrough": "getURL and getHash provide the pack location and integrity hash for C19 replies. The startsWith level branch strips the prefix and resolves the file under the saves directory. isFile success sends C19 ACCEPTED immediately before async load. The Futures callbacks send SUCCESSFULLY_LOADED or FAILED_DOWNLOAD after the repository finishes. The missing-file else sends FAILED_DOWNLOAD, while remote ENABLED, DISABLED and PROMPT branches below handle server-hosted packs."
     },
     {
      "name": "handleCustomPayload",
      "detail_long": "handleCustomPayload dispatches S3F plugin channels on the client thread. MC|TrList reads an int windowId, checks the current screen is GuiMerchant and ids match openContainer, then parses MerchantRecipeList and sets villager recipes. MC|Brand reads a string up to 32767 and stores it as clientBrand for server identification. MC|BOpen checks the held item is written_book and opens GuiScreenBook read-only. After TrList the buffer is released in finally to avoid leaks, other branches release via network layer. Unknown channels are ignored. No reply packet is sent, the data only mutates GUI and NBT state. Exploit angle is fake TrList with mismatched windowId which is correctly dropped.",
      "code": "        if (\"MC|TrList\".equals(packetIn.getChannelName()))\n        {\n            PacketBuffer packetbuffer = packetIn.getBufferData();\n\n            try\n            {\n                int i = packetbuffer.readInt();\n                GuiScreen guiscreen = this.gameController.currentScreen;\n\n                if (guiscreen != null && guiscreen instanceof GuiMerchant && i == this.gameController.thePlayer.openContainer.windowId)\n                {\n                    IMerchant imerchant = ((GuiMerchant)guiscreen).getMerchant();\n                    MerchantRecipeList merchantrecipelist = MerchantRecipeList.readFromBuf(packetbuffer);\n                    imerchant.setRecipes(merchantrecipelist);\n                }\n            }\n            catch (IOException ioexception)\n            {\n                logger.error((String)\"Couldn\\'t load trade info\", (Throwable)ioexception);\n            }\n            finally\n            {\n                packetbuffer.release();\n            }\n        }\n        else if (\"MC|Brand\".equals(packetIn.getChannelName()))\n        {\n            this.gameController.thePlayer.setClientBrand(packetIn.getBufferData().readStringFromBuffer(32767));",
      "code_walkthrough": "The MC|TrList equals gate isolates villager trades from brand and book channels. readInt plus GuiMerchant plus windowId match prevents injecting trades into the wrong container. readFromBuf and setRecipes populate the merchant GUI with server offers. The catch logs load failures while finally releases the buffer to prevent netty leaks. The MC|Brand branch stores the server brand string for F3 debug display."
     }
    ]
   }
  },
  {
   "slug": "WorldServer",
   "title": "WorldServer",
   "rel": "net/minecraft/world/WorldServer.java",
   "desc": "Server world: broadcasts S24 block actions, S27 explosions, S2A particles and S2C lightning to nearby players.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/WorldServer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/world/WorldServer.java",
   "packets": [
    "S19PacketEntityStatus",
    "S24PacketBlockAction",
    "S27PacketExplosion",
    "S2APacketParticles",
    "S2BPacketChangeGameState",
    "S2CPacketSpawnGlobalEntity"
   ],
   "peers": [
    "EntityPlayerMP",
    "ServerScoreboard",
    "PlayerManager",
    "EntityLivingBase",
    "BlockPos",
    "AxisAlignedBB",
    "Entity",
    "EntityPlayer",
    "World",
    "ServerConfigurationManager",
    "WorldManager"
   ],
   "analysis": {
    "overview": "Server-side World dimension instance owning EntityTracker and PlayerManager fan-out. Gates broadcasts by dimension ID and distance-squared radii. Handles global weather, explosion, block-event, particle and game-state sync. Delegates chunk block deltas to PlayerManager and entity visibility to EntityTracker.",
    "methods": [
     {
      "detail": "Calls super then sendToAllNear at entity pos with 512.0D radius. Gated by provider.getDimensionId. Only sent if super accepts effect. Returns false otherwise.",
      "name": "addWeatherEffect",
      "packets": [
       "S2C"
      ],
      "purpose": "Broadcast lightning spawn to nearby players in same dimension."
     },
     {
      "detail": "Iterates playerEntities checking distanceSq < 4096.0D (64 blocks). Sends S27PacketExplosion with strength, affected blocks, per-player Vec3 knockback. No dimension check; assumes same WorldServer player list.",
      "name": "newExplosion",
      "packets": [
       "S27"
      ],
      "purpose": "Run explosion then send knockback and block list to players in range."
     },
     {
      "detail": "Swaps blockEventCacheIndex, fires fireBlockEvent validation. On success sends S24PacketBlockAction via sendToAllNear with 64.0D radius. Gated by dimension ID. Deduped in addBlockEvent.",
      "name": "sendQueuedBlockEvents",
      "packets": [
       "S24"
      ],
      "purpose": "Flush double-buffered block events as block-action packets."
     },
     {
      "detail": "Delegates to EntityTracker.func_151248_b with S19PacketEntityStatus. Viewer set determined by tracker distance, not WorldServer radius. Used for totem, hurt, tame states.",
      "name": "setEntityState",
      "packets": [
       "S19"
      ],
      "purpose": "Forward entity status byte to tracking viewers."
     },
     {
      "detail": "If rainingStrength changed sends S2B reason 7 to dimension. If thunderingStrength changed sends reason 8 to dimension. On rain start/stop sends reasons 1/2 plus 7/8 globally to all players.",
      "name": "updateWeather",
      "packets": [
       "S2B"
      ],
      "purpose": "Sync rain and thunder strength changes to clients."
     },
     {
      "detail": "Builds single S2APacketParticles reused for all players. Sends if distanceSq <=256.0D (16 blocks), or if longDistance and <=65536.0D (256 blocks). Iterates playerEntities directly.",
      "name": "spawnParticle(longDistance)",
      "packets": [
       "S2A"
      ],
      "purpose": "Send particle packet with short vs long view-distance gating."
     },
     {
      "detail": "Calls PlayerManager.updatePlayerInstances for block deltas and chunk sync. Calls sendQueuedBlockEvents for S24 fan-out. Also updates villages, mob spawner, portal forcer. No direct packet send.",
      "name": "tick",
      "packets": [
       "S21",
       "S22",
       "S23",
       "S24"
      ],
      "purpose": "Per-tick drive chunk maps and queued block events."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S2C",
      "trigger": "addWeatherEffect lightning added"
     },
     {
      "direction": "sent",
      "id": "S27",
      "trigger": "newExplosion within 4096.0D"
     },
     {
      "direction": "sent",
      "id": "S24",
      "trigger": "queued block event fired, 64.0D"
     },
     {
      "direction": "sent",
      "id": "S19",
      "trigger": "setEntityState via EntityTracker"
     },
     {
      "direction": "sent",
      "id": "S2B",
      "trigger": "updateWeather strength or rain toggle"
     },
     {
      "direction": "sent",
      "id": "S2A",
      "trigger": "spawnParticle 256.0D or 65536.0D longDistance"
     }
    ],
    "internal_fields": [
     {
      "name": "theEntityTracker",
      "role": "Tracks entities and fans out entity packets to viewers"
     },
     {
      "name": "thePlayerManager",
      "role": "Manages chunk watchers and block-change packets"
     },
     {
      "name": "blockEventQueue",
      "role": "Double-buffered ServerBlockEventList dedup queue"
     },
     {
      "name": "mcServer",
      "role": "Access to ServerConfigurationManager broadcast helpers"
     },
     {
      "name": "entitiesByUuid",
      "role": "UUID to Entity lookup for resolution"
     }
    ],
    "peers": [
     "PlayerManager",
     "EntityTracker",
     "ServerConfigurationManager",
     "ServerScoreboard",
     "WorldManager"
    ],
    "methods_detailed": [
     {
      "name": "addWeatherEffect",
      "detail_long": "This method is the server entry point for global weather entities such as lightning bolts. It first calls super.addWeatherEffect to register the entity in the world simulation and validate placement. Only if super returns true does any network fan-out occur, otherwise it returns false with no packets. On success it calls ServerConfigurationManager.sendToAllNear using the entity exact posX posY posZ coordinates. The radius is fixed at 512.0D and the call is gated by provider.getDimensionId so only players in the same dimension receive it. The packet constructed is S2CPacketSpawnGlobalEntity wrapping the entity instance. This large 512 block radius reflects that lightning is a sky-visible global event. Compared to 16.0D sound or 64.0D block-action ranges, this is intentionally wide. No batching is used because each strike is a discrete spawn.",
      "code": "    public boolean addWeatherEffect(Entity entityIn)\n    {\n        if (super.addWeatherEffect(entityIn))\n        {\n            this.mcServer.getConfigurationManager().sendToAllNear(entityIn.posX, entityIn.posY, entityIn.posZ, 512.0D, this.provider.getDimensionId(), new S2CPacketSpawnGlobalEntity(entityIn));\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }",
      "code_walkthrough": "The boolean method signature takes the weather Entity to spawn. The super call gates all networking on simulation acceptance. The sendToAllNear line builds S2CPacketSpawnGlobalEntity from the entity and passes 512.0D plus dimension ID for gating. The true branch returns success after queuing the broadcast. The else branch returns false with no packet when super rejects. This shows dimension-gated wide-radius spawn fan-out."
     },
     {
      "name": "newExplosion",
      "detail_long": "This method runs the full server explosion simulation then notifies nearby clients. It first constructs an Explosion object with entity source, coordinates, strength, and flaming and smoking flags. It then calls doExplosionA for block resistance calculation and doExplosionB with false for no fire spawning here. If isSmoking is false it clears the affected block position list so clients receive an empty list. It then iterates directly over playerEntities belonging to this WorldServer dimension instance. Each player is distance checked with getDistanceSq against x y z with threshold 4096.0D which equals 64 blocks squared. Only players inside that sphere get a direct S27PacketExplosion via playerNetServerHandler.sendPacket. The packet carries x y z strength block list and per-player Vec3 knockback from getPlayerKnockbackMap. No explicit dimension check is needed because playerEntities are already dimension scoped.",
      "code": "    public Explosion newExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, boolean isSmoking)\n    {\n        Explosion explosion = new Explosion(this, entityIn, x, y, z, strength, isFlaming, isSmoking);\n        explosion.doExplosionA();\n        explosion.doExplosionB(false);\n\n        if (!isSmoking)\n        {\n            explosion.clearAffectedBlockPositions();\n        }\n\n        for (EntityPlayer entityplayer : this.playerEntities)\n        {\n            if (entityplayer.getDistanceSq(x, y, z) < 4096.0D)\n            {\n                ((EntityPlayerMP)entityplayer).playerNetServerHandler.sendPacket(new S27PacketExplosion(x, y, z, strength, explosion.getAffectedBlockPositions(), (Vec3)explosion.getPlayerKnockbackMap().get(entityplayer)));\n            }\n        }\n\n        return explosion;\n    }",
      "code_walkthrough": "The signature accepts source entity, position, strength, and flags. The next three lines create the Explosion and run both phases. The isSmoking check empties the block list for non-destructive blasts. The loop plus distanceSq less than 4096.0D gates recipients to a 64 block radius. The sendPacket line constructs S27PacketExplosion with strength, block list, and per-player knockback Vec3. This is direct per-player send, not chunk-scoped."
     },
     {
      "name": "sendQueuedBlockEvents",
      "detail_long": "This method flushes the double-buffered block event queue at end of tick. The queue consists of two ServerBlockEventList buffers with blockEventCacheIndex selecting the active fill buffer. The while loop continues until the current read buffer is empty, handling events added during flushing. It snapshots the read index into i then flips blockEventCacheIndex with xor 1 so new addBlockEvent calls go to the other buffer. For each BlockEventData it calls fireBlockEvent to verify the block still matches and to run onBlockEventReceived. Only if validation returns true does it broadcast via sendToAllNear. That broadcast uses the event position coordinates with fixed 64.0D radius gated by provider.getDimensionId. The packet is S24PacketBlockAction built from position, block, event ID, and event parameter. Finally it clears the processed buffer list before looping.",
      "code": "    private void sendQueuedBlockEvents()\n    {\n        while (!this.blockEventQueue[this.blockEventCacheIndex].isEmpty())\n        {\n            int i = this.blockEventCacheIndex;\n            this.blockEventCacheIndex ^= 1;\n\n            for (BlockEventData blockeventdata : this.blockEventQueue[i])\n            {\n                if (this.fireBlockEvent(blockeventdata))\n                {\n                    this.mcServer.getConfigurationManager().sendToAllNear((double)blockeventdata.getPosition().getX(), (double)blockeventdata.getPosition().getY(), (double)blockeventdata.getPosition().getZ(), 64.0D, this.provider.getDimensionId(), new S24PacketBlockAction(blockeventdata.getPosition(), blockeventdata.getBlock(), blockeventdata.getEventID(), blockeventdata.getEventParameter()));\n                }\n            }\n\n            this.blockEventQueue[i].clear();\n        }\n    }",
      "code_walkthrough": "The private method takes no args and loops on the active queue. The index snapshot plus xor flip implements double buffering. The for loop iterates BlockEventData entries in the frozen buffer. The fireBlockEvent condition gates packet construction on block match and handler acceptance. The sendToAllNear line shows 64.0D radius, dimension gating, and S24PacketBlockAction args. The clear call resets the buffer for the next tick."
     },
     {
      "name": "setEntityState",
      "detail_long": "This method forwards a single-byte entity status to all tracking viewers. It does not implement its own radius check with 16.0D or 64.0D or 512.0D values. Instead it delegates viewer selection to EntityTracker via getEntityTracker. The tracker determines who currently tracks the entity based on tracking range and type. The packet created is S19PacketEntityStatus wrapping the entity and state byte. Typical states include hurt flash, totem use, tame hearts, and other entity events. The call func_151248_b performs the fan-out to that viewer set. Because WorldServer owns theEntityTracker field, this keeps visibility logic centralized. No dimension check appears here because tracker entries are already per-world.",
      "code": "    /**\n     * sends a Packet 38 (Entity Status) to all tracked players of that entity\n     */\n    public void setEntityState(Entity entityIn, byte state)\n    {\n        this.getEntityTracker().func_151248_b(entityIn, new S19PacketEntityStatus(entityIn, state));\n    }\n\n    /**\n     * returns a new explosion. Does initiation (at time of writing Explosion is not finished)\n     */",
      "code_walkthrough": "The comment identifies this as Packet 38 entity status handling. The method signature takes entity and byte state. The body delegates to EntityTracker func_151248_b for viewer resolution. The constructor S19PacketEntityStatus binds entity ID and status byte into the packet. The trailing comment marks the start of the next explosion method. This shows tracker-based fan-out rather than explicit radius gating."
     },
     {
      "name": "updateWeather",
      "detail_long": "This method synchronizes rain and thunder state changes from server simulation to clients. It caches the old isRaining value in flag before calling super.updateWeather to advance strengths. If rainingStrength changed it sends S2BPacketChangeGameState reason 7 with the new strength to all players in the dimension. If thunderingStrength changed it sends reason 8 similarly dimension gated. These two paths handle gradual fade without a full rain toggle. If the boolean raining state flipped, it sends a global toggle to all players with reason 2 for stop or reason 1 for start. It then follows with global sends of reason 7 and reason 8 to resync strengths everywhere. The dimension-scoped sends use sendPacketToAllPlayersInDimension while toggles use sendPacketToAllPlayers. No distance radius like 64.0D or 512.0D is used because weather is global. This produces at most four packets per transition.",
      "code": "    protected void updateWeather()\n    {\n        boolean flag = this.isRaining();\n        super.updateWeather();\n\n        if (this.prevRainingStrength != this.rainingStrength)\n        {\n            this.mcServer.getConfigurationManager().sendPacketToAllPlayersInDimension(new S2BPacketChangeGameState(7, this.rainingStrength), this.provider.getDimensionId());\n        }\n\n        if (this.prevThunderingStrength != this.thunderingStrength)\n        {\n            this.mcServer.getConfigurationManager().sendPacketToAllPlayersInDimension(new S2BPacketChangeGameState(8, this.thunderingStrength), this.provider.getDimensionId());\n        }\n\n        if (flag != this.isRaining())\n        {\n            if (flag)\n            {\n                this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(2, 0.0F));\n            }\n            else\n            {\n                this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(1, 0.0F));\n            }\n\n            this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(7, this.rainingStrength));\n            this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(8, this.thunderingStrength));\n        }\n    }",
      "code_walkthrough": "The flag save plus super call detects rain edges and strength deltas. The first two if blocks compare prev versus current strengths and send S2B reason 7 or 8 dimension gated. The outer flag comparison detects start versus stop transitions. The inner if sends reason 2 stop or reason 1 start globally. The final two sends rebroadcast strengths 7 and 8 globally after a toggle. This separates gradual strength sync from discrete rain state sync."
     },
     {
      "name": "spawnParticle(longDistance)",
      "detail_long": "This overload is the core particle broadcast with explicit longDistance flag. It first builds a single S2APacketParticles instance reused for every recipient to save allocation. The packet packs particle type, longDistance flag, float position, float offsets, float speed, count, and varargs. It then loops over playerEntities in this dimension by index. For each EntityPlayerMP it gets the player BlockPos and computes distanceSq to the spawn coordinates. If that squared distance is at most 256.0D the player receives it, which equals 16 blocks normal view distance. Alternatively if longDistance is true and distance is at most 65536.0D the player receives it, which equals 256 blocks. The same Packet object is sent via playerNetServerHandler.sendPacket to each qualifier. No dimension helper is called because the list is already dimension scoped. This dual threshold lets command or beacon effects travel far while normal effects stay local.",
      "code": "    public void spawnParticle(EnumParticleTypes particleType, boolean longDistance, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int... particleArguments)\n    {\n        Packet packet = new S2APacketParticles(particleType, longDistance, (float)xCoord, (float)yCoord, (float)zCoord, (float)xOffset, (float)yOffset, (float)zOffset, (float)particleSpeed, numberOfParticles, particleArguments);\n\n        for (int i = 0; i < this.playerEntities.size(); ++i)\n        {\n            EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playerEntities.get(i);\n            BlockPos blockpos = entityplayermp.getPosition();\n            double d0 = blockpos.distanceSq(xCoord, yCoord, zCoord);\n\n            if (d0 <= 256.0D || longDistance && d0 <= 65536.0D)\n            {\n                entityplayermp.playerNetServerHandler.sendPacket(packet);\n            }\n        }\n    }",
      "code_walkthrough": "The signature exposes particle type, longDistance, position, count, offsets, speed, and extra args. The packet construction line casts doubles to floats and reuses one instance. The loop resolves each player position and computes distanceSq. The if condition implements 256.0D short versus 65536.0D long gating. The sendPacket line delivers the shared instance only to qualifiers. This is per-player distance filtering without chunk map lookup."
     },
     {
      "name": "tick",
      "detail_long": "This is the per-tick driver for the server world simulation and network flush. It first advances pending block ticks via tickUpdates and random block ticks via updateBlocks with no direct packets. It then enters the chunkMap section by calling thePlayerManager.updatePlayerInstances which flushes S21 S22 S23 block deltas to chunk watchers. Village ticking, siege ticking, and portal staleness removal run next without networking. The profiler sections wrap each subsystem for timing. At the very end it calls sendQueuedBlockEvents to fan out validated S24 block-action packets at 64.0D radius. This ordering ensures block state changes are sent before dependent block events in the same tick. If no players are present, updatePlayerInstances still runs but has no recipients. The method therefore indirectly causes all chunk block packets plus S24 each tick.",
      "code": "        this.theProfiler.endStartSection(\"tickPending\");\n        this.tickUpdates(false);\n        this.theProfiler.endStartSection(\"tickBlocks\");\n        this.updateBlocks();\n        this.theProfiler.endStartSection(\"chunkMap\");\n        this.thePlayerManager.updatePlayerInstances();\n        this.theProfiler.endStartSection(\"village\");\n        this.villageCollectionObj.tick();\n        this.villageSiege.tick();\n        this.theProfiler.endStartSection(\"portalForcer\");\n        this.worldTeleporter.removeStalePortalLocations(this.getTotalWorldTime());\n        this.theProfiler.endSection();\n        this.sendQueuedBlockEvents();\n    }",
      "code_walkthrough": "The tickPending plus tickUpdates lines advance scheduled block ticks. The chunkMap plus updatePlayerInstances line is the indirect S21 S22 S23 fan-out point. The village and portal lines run non-network simulation. The final sendQueuedBlockEvents line triggers S24 64.0D fan-out. Profiler markers show ordering but do not affect packets. This excerpt is the packet-relevant tail of the tick method."
     }
    ]
   }
  },
  {
   "slug": "PlayerControllerMP",
   "title": "PlayerControllerMP",
   "rel": "net/minecraft/client/multiplayer/PlayerControllerMP.java",
   "desc": "Client interaction controller: attackEntity/interact send C02, clickBlock sends C07, windowClick sends C0E, slot sync sends C10.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/PlayerControllerMP/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/client/multiplayer/PlayerControllerMP.java",
   "packets": [
    "C02PacketUseEntity",
    "C07PacketPlayerDigging",
    "C08PacketPlayerBlockPlacement",
    "C09PacketHeldItemChange",
    "C0EPacketClickWindow",
    "C10PacketCreativeInventoryAction",
    "C11PacketEnchantItem"
   ],
   "peers": [
    "EntityPlayerSP",
    "NetHandlerPlayClient",
    "Minecraft",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "World"
   ],
   "analysis": {
    "overview": "Client interaction controller translating clicks/keys to server C packets with prediction. No tick entity itself; driven by Minecraft loop via updateController. Validates creative/adventure/spectator/border locally, plays sounds/particles, then sends authoritative request. Paired with NetHandlerPlayClient and EntityPlayerSP.",
    "methods": [
     {
      "detail": "Rejects spectator/no-edit adventure and outside border. Creative sends START_DESTROY + clickBlockCreative + delay 5. Survival aborts prior block, sends START, inits curBlockDamageMP/step counter.",
      "name": "clickBlock",
      "packets": [
       "C07"
      ],
      "purpose": "Starts block hit; creative instant vs survival progress init."
     },
     {
      "detail": "Honors blockHitDelay. Creative re-sends START. Survival adds getPlayerRelativeBlockHardness, step sound every 4 ticks, on >=1 sends STOP_DESTROY + onPlayerDestroyBlock + delay 5.",
      "name": "onPlayerDamageBlock",
      "packets": [
       "C07"
      ],
      "purpose": "Accumulates crack progress and finishes block."
     },
     {
      "detail": "Border + spectator checks. Tries onBlockActivated, validates canPlaceBlockOnSide for ItemBlock, always sends C08 placement, then locally applies onItemUse (creative restores damage/count).",
      "name": "onPlayerRightClick",
      "packets": [
       "C08"
      ],
      "purpose": "Block activate or ItemBlock place with prediction."
     },
     {
      "detail": "Blocks spectator, syncs hotbar, sends C08 with current item (pos -1), calls useItemRightClick locally and updates mainInventory if count changed.",
      "name": "sendUseItem",
      "packets": [
       "C08"
      ],
      "purpose": "Air right-click (food, bow, etc)."
     },
     {
      "detail": "Syncs item, sends C02 ATTACK or INTERACT (+hitVec variant). Applies local attackTargetEntityWithCurrentItem/interact only if not spectator.",
      "name": "attackEntity/interactWithEntitySendPacket",
      "packets": [
       "C02"
      ],
      "purpose": "Left-click attack vs right-click interact."
     },
     {
      "detail": "Gets next transaction ID, applies local slotClick, sends C0E with result + txn. Enchant sends C11 windowID+button for server-side level roll.",
      "name": "windowClick/sendEnchantPacket",
      "packets": [
       "C0E",
       "C11"
      ],
      "purpose": "Container click and enchant button."
     },
     {
      "detail": "Compares inventory.currentItem to cached currentPlayerItem; on change updates cache and sends C09 HeldItemChange.",
      "name": "syncCurrentPlayItem",
      "packets": [
       "C09"
      ],
      "purpose": "Hotbar change notifier called before most actions."
     },
     {
      "detail": "reset sends ABORT_DESTROY + clears isHittingBlock/damage/progress. stopUsing sends RELEASE_USE_ITEM with ORIGIN/DOWN then local stopUsingItem.",
      "name": "resetBlockRemoving/onStoppedUsingItem",
      "packets": [
       "C07"
      ],
      "purpose": "Abort mining and stop use."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "C02",
      "trigger": "Attack/interact entity."
     },
     {
      "direction": "sent",
      "id": "C07",
      "trigger": "Start/stop/abort mining, drop handled by SP."
     },
     {
      "direction": "sent",
      "id": "C08",
      "trigger": "Right-click block or air use."
     },
     {
      "direction": "sent",
      "id": "C09",
      "trigger": "Hotbar slot change before actions."
     },
     {
      "direction": "sent",
      "id": "C0E",
      "trigger": "Inventory slot click."
     },
     {
      "direction": "sent",
      "id": "C10",
      "trigger": "Creative set/drop slot."
     },
     {
      "direction": "sent",
      "id": "C11",
      "trigger": "Enchant button."
     }
    ],
    "internal_fields": [
     {
      "name": "netClientHandler",
      "role": "NetHandlerPlayClient queue for all C packets"
     },
     {
      "name": "currentBlock/isHittingBlock",
      "role": "Mining target and active flag; abort on change"
     },
     {
      "name": "curBlockDamageMP/stepSoundTickCounter",
      "role": "Accumulated hardness 0-1 and step-sound cadence"
     },
     {
      "name": "blockHitDelay",
      "role": "5-tick cooldown after place/destroy"
     },
     {
      "name": "currentGameType/currentPlayerItem",
      "role": "Survival/creative/spectator rules and cached hotbar for C09"
     },
     {
      "name": "currentItemHittingBlock",
      "role": "Item used at hit start; abort if swapped via isHittingPosition"
     }
    ],
    "peers": [
     "NetHandlerPlayClient",
     "EntityPlayerSP",
     "Minecraft",
     "WorldClient"
    ],
    "methods_detailed": [
     {
      "name": "clickBlock",
      "detail_long": "clickBlock first enforces adventure and spectator rules, returning false for spectators and for adventure players without allowEdit or whose held item cannot destroy the target block. It then enforces world border containment on the block position, refusing clicks outside the border. In creative mode it queues C07 START_DESTROY_BLOCK with position and face, calls clickBlockCreative for instant local break, and sets blockHitDelay to 5 to throttle repeats. In survival it aborts any prior target with C07 ABORT_DESTROY_BLOCK to the old currentBlock when switching positions, then queues C07 START_DESTROY_BLOCK for the new location. It calls onBlockClicked for zero-damage starts, instantly breaks when relative hardness reaches 1.0, else initializes isHittingBlock, currentBlock, currentItemHittingBlock, curBlockDamageMP zero and crack overlay. The server validates reach, hardness and timing, so nuker cheats that spam START without STOP are detected here.",
      "code": "        if (!this.mc.theWorld.getWorldBorder().contains(loc))\n        {\n            return false;\n        }\n        else\n        {\n            if (this.currentGameType.isCreative())\n            {\n                this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, loc, face));\n                clickBlockCreative(this.mc, this, loc, face);\n                this.blockHitDelay = 5;\n            }\n            else if (!this.isHittingBlock || !this.isHittingPosition(loc))\n            {\n                if (this.isHittingBlock)\n                {\n                    this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, face));\n                }\n\n                this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, loc, face));\n                Block block1 = this.mc.theWorld.getBlockState(loc).getBlock();\n                boolean flag = block1.getMaterial() != Material.air;",
      "code_walkthrough": "The border contains check runs before any packet, so out-of-border clicks never reach the server. The creative branch shows the START_DESTROY plus instant client break plus 5-tick delay pattern, explaining creative nuker speed limits. The survival branch first sends ABORT for the stale currentBlock when retargeting, keeping server crack state consistent. The final START_DESTROY carries the new loc and face the server validates for reach and hardness, and suppressing ABORT leaves ghost cracks server-side."
     },
     {
      "name": "onPlayerDamageBlock",
      "detail_long": "onPlayerDamageBlock first calls syncCurrentPlayItem so any hotbar change emits C09 before mining packets, keeping server held-item in sync. It honors blockHitDelay by decrementing and returning true to swallow clicks during the 5-tick cooldown after place or break. In creative with border containment it re-sends C07 START_DESTROY_BLOCK and instantly breaks via clickBlockCreative, re-arming the delay. If isHittingPosition confirms the same block and held item, it returns false on air to clear isHittingBlock, else adds getPlayerRelativeBlockHardness to curBlockDamageMP for progressive cracking. Every 4 stepSoundTickCounter ticks it plays the block step sound locally at the block center for feedback. When curBlockDamageMP reaches 1.0 it clears isHittingBlock, sends C07 STOP_DESTROY_BLOCK, calls onPlayerDestroyBlock for local removal, zeroes damage and re-arms delay. Otherwise it falls through to clickBlock to start a new target, so holding mouse produces START, progress, STOP sequencing.",
      "code": "                this.curBlockDamageMP += block.getPlayerRelativeBlockHardness(this.mc.thePlayer, this.mc.thePlayer.worldObj, posBlock);\n\n                if (this.stepSoundTickCounter % 4.0F == 0.0F)\n                {\n                    this.mc.getSoundHandler().playSound(new PositionedSoundRecord(new ResourceLocation(block.stepSound.getStepSound()), (block.stepSound.getVolume() + 1.0F) / 8.0F, block.stepSound.getFrequency() * 0.5F, (float)posBlock.getX() + 0.5F, (float)posBlock.getY() + 0.5F, (float)posBlock.getZ() + 0.5F));\n                }\n\n                ++this.stepSoundTickCounter;\n\n                if (this.curBlockDamageMP >= 1.0F)\n                {\n                    this.isHittingBlock = false;\n                    this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK, posBlock, directionFacing));\n                    this.onPlayerDestroyBlock(posBlock, directionFacing);\n                    this.curBlockDamageMP = 0.0F;\n                    this.stepSoundTickCounter = 0.0F;\n                    this.blockHitDelay = 5;\n                }\n\n                this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1);",
      "code_walkthrough": "The hardness accumulation line advances crack progress per tick based on tool, haste and block strength, so speed-mine cheats inflate this value locally but the server recomputes it. The step-sound block plays every fourth tick purely client-side with no packet, giving audio feedback during digging. The 1.0 threshold branch sends STOP_DESTROY_BLOCK with exact pos and face, which is the only packet the server accepts as a legitimate break. sendBlockBreakProgress updates the local crack overlay from 0 to 9, and forging STOP without real progress is the core fast-break detection signal."
     },
     {
      "name": "onPlayerRightClick",
      "detail_long": "onPlayerRightClick first syncs the hotbar via syncCurrentPlayItem so the server sees the correct held item for placement. It computes hitVec offsets f, f1, f2 as fractional positions inside the block for precise face placement and tile orientation. It rejects clicks outside the world border with no packet, preventing border-bypass builds. In non-spectator it tries onBlockActivated for doors, chests and levers when not sneaking with an item, setting flag true to indicate activation consumed the click. It validates ItemBlock.canPlaceBlockOnSide before sending, returning false early on illegal placement to save bandwidth. It always queues C08PacketPlayerBlockPlacement with hitPos, face index, current item and f offsets, even for pure activation, because the server re-decides activation versus place. Locally it applies onItemUse with creative restore of damage and count versus survival consume, or returns true for pure activation. Spectators send C08 but skip local world changes, so the server must ignore their placements.",
      "code": "            if (this.currentGameType != WorldSettings.GameType.SPECTATOR)\n            {\n                IBlockState iblockstate = worldIn.getBlockState(hitPos);\n\n                if ((!player.isSneaking() || player.getHeldItem() == null) && iblockstate.getBlock().onBlockActivated(worldIn, hitPos, iblockstate, player, side, f, f1, f2))\n                {\n                    flag = true;\n                }\n\n                if (!flag && heldStack != null && heldStack.getItem() instanceof ItemBlock)\n                {\n                    ItemBlock itemblock = (ItemBlock)heldStack.getItem();\n\n                    if (!itemblock.canPlaceBlockOnSide(worldIn, hitPos, side, player, heldStack))\n                    {\n                        return false;\n                    }\n                }\n            }\n\n            this.netClientHandler.addToSendQueue(new C08PacketPlayerBlockPlacement(hitPos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2));\n\n            if (!flag && this.currentGameType != WorldSettings.GameType.SPECTATOR)",
      "code_walkthrough": "The onBlockActivated call predicts door or chest opening locally so the GUI feels instant, with flag recording whether activation succeeded. The canPlaceBlockOnSide check mirrors server placement rules for ItemBlock, aborting without a packet on illegal faces. The C08 line packs block position, face index, held stack and fractional hit offsets the server uses to orient slabs, stairs and pistons. Sending C08 even when flag is true lets the server confirm activation, and spamming C08 with crafted offsets is the scaffold and ghost-block vector."
     },
     {
      "name": "sendUseItem",
      "detail_long": "sendUseItem blocks all use in SPECTATOR mode with an immediate false and no packet, enforcing spectator intangibility. It syncs the hotbar via syncCurrentPlayItem so the following C08 references the correct slot. It queues C08PacketPlayerBlockPlacement constructed from the current inventory item with the air-use constructor that uses -1 position internally. It records the pre-use stackSize, then calls useItemRightClick locally to predict food eating, bow drawing, potion throwing or snowball spawning. If the returned stack differs by identity or count it writes the result into mainInventory, clears to null on zero, and returns true to indicate consumption. If nothing changed it returns false, meaning the item had no right-click action. The server separately validates cooldowns, food hunger and projectile spawn on C08 receipt, so no-use-delay or fast-eat cheats forge timing around this packet.",
      "code": "    public boolean sendUseItem(EntityPlayer playerIn, World worldIn, ItemStack itemStackIn)\n    {\n        if (this.currentGameType == WorldSettings.GameType.SPECTATOR)\n        {\n            return false;\n        }\n        else\n        {\n            this.syncCurrentPlayItem();\n            this.netClientHandler.addToSendQueue(new C08PacketPlayerBlockPlacement(playerIn.inventory.getCurrentItem()));\n            int i = itemStackIn.stackSize;\n            ItemStack itemstack = itemStackIn.useItemRightClick(worldIn, playerIn);\n\n            if (itemstack != itemStackIn || itemstack != null && itemstack.stackSize != i)\n            {\n                playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = itemstack;\n\n                if (itemstack.stackSize == 0)\n                {\n                    playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = null;\n                }\n\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n    }",
      "code_walkthrough": "The spectator early-return shows air-use is entirely disabled for that mode with no network traffic. syncCurrentPlayItem emits C09 first when needed so the C08 that follows is attributed to the right hotbar slot. The C08 air-use constructor signals right-click-air rather than block-place, which the server maps to food, bows and throwables. The stackSize comparison detects consumption locally for instant inventory feedback, while the server authoritative consume arrives later, so desync here causes ghost food or infinite snowballs if C08 is replayed."
     },
     {
      "name": "attackEntity/interactWithEntitySendPacket",
      "detail_long": "attackEntity syncs the hotbar, queues C02PacketUseEntity with Action.ATTACK for the target entity ID, then applies attackTargetEntityWithCurrentItem locally only when not in spectator. interactWithEntitySendPacket syncs the hotbar, queues C02 with Action.INTERACT, and applies playerIn.interactWith locally only for non-spectators. isPlayerRightClickingOnEntity computes a hitVec offset from entity position, queues C02 with the Vec3 interact-at variant for armor stands and villagers, and applies interactAt locally for non-spectators. All three share netClientHandler as the sink and always send the C02 even in spectator, letting the server decide to ignore effects while still logging the attempt. The server validates distance, line of sight and cooldown, applying damage or leash or trade effects. Suppressing C02 creates silent aura where damage happens without animation, while spamming C02 with forged IDs is the reach and kill-aura vector. Local prediction keeps hits feeling instant pending S19, S0B or S06 confirmations.",
      "code": "    public void attackEntity(EntityPlayer playerIn, Entity targetEntity)\n    {\n        this.syncCurrentPlayItem();\n        this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.ATTACK));\n\n        if (this.currentGameType != WorldSettings.GameType.SPECTATOR)\n        {\n            playerIn.attackTargetEntityWithCurrentItem(targetEntity);\n        }\n    }\n\n    /**\n     * Send packet to server - player is interacting with another entity (left click)\n     */\n    public boolean interactWithEntitySendPacket(EntityPlayer playerIn, Entity targetEntity)\n    {\n        this.syncCurrentPlayItem();\n        this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.INTERACT));\n        return this.currentGameType != WorldSettings.GameType.SPECTATOR && playerIn.interactWith(targetEntity);\n    }",
      "code_walkthrough": "syncCurrentPlayItem before each C02 guarantees the server uses the current weapon for damage calculation rather than a stale slot. The ATTACK constructor carries only the entity ID, while the INTERACT and Vec3 variants add interaction coordinates for precise armor-stand handling. The spectator conditionals show packets are still sent but local effects are skipped, so the server is the final arbiter. Forging ATTACK with distant IDs is reach, and omitting the paired C0A swing is the no-swing signature."
     },
     {
      "name": "windowClick/sendEnchantPacket",
      "detail_long": "windowClick obtains the next short transaction ID from openContainer.getNextTransactionID, applies slotClick locally for instant GUI movement with mouseButton and mode, then queues C0EPacketClickWindow with windowId, slotId, button, mode, resulting ItemStack and transaction ID. The server replays the click against its authoritative Container, validates the transaction, and corrects with S2F or S30 on mismatch. sendEnchantPacket queues C11PacketEnchantItem with windowID and button for the enchantment table selection, where the server rolls levels and applies S31 progress. sendSlotPacket and sendPacketDropItem queue C10 creative actions for set or drop slot, gated on isCreative to prevent survival item spawning. Racing C0E clicks against C0D close or spamming transaction IDs is the classic inventory-dupe and chest-stealer pattern. The local slotClick prediction is why containers feel instant despite round-trip validation.",
      "code": "    public ItemStack windowClick(int windowId, int slotId, int mouseButtonClicked, int mode, EntityPlayer playerIn)\n    {\n        short short1 = playerIn.openContainer.getNextTransactionID(playerIn.inventory);\n        ItemStack itemstack = playerIn.openContainer.slotClick(slotId, mouseButtonClicked, mode, playerIn);\n        this.netClientHandler.addToSendQueue(new C0EPacketClickWindow(windowId, slotId, mouseButtonClicked, mode, itemstack, short1));\n        return itemstack;\n    }\n\n    /**\n     * GuiEnchantment uses this during multiplayer to tell PlayerControllerMP to send a packet indicating the\n     * enchantment action the player has taken.\n     *  \n     * @param windowID The ID of the current window\n     * @param button The button id (enchantment selected)\n     */\n    public void sendEnchantPacket(int windowID, int button)\n    {\n        this.netClientHandler.addToSendQueue(new C11PacketEnchantItem(windowID, button));\n    }",
      "code_walkthrough": "getNextTransactionID allocates the short the server will echo or reject in S32 confirm, linking each C0E to a server settlement. slotClick mutates the client Container immediately for responsive dragging, with the result stack echoed in the C0E for server comparison. The C0E constructor packs window, slot, button, mode and transaction together so the server can replay the exact click. The C11 line carries only window and enchant button, with the actual level cost decided server-side, so forged C11 buttons attempt free-enchant exploits."
     },
     {
      "name": "syncCurrentPlayItem",
      "detail_long": "syncCurrentPlayItem reads the live hotbar index from mc.thePlayer.inventory.currentItem each call and compares it to the cached currentPlayerItem field. On mismatch it copies the new index into the cache and queues C09PacketHeldItemChange with that slot on netClientHandler. It is invoked at the top of updateController, click handling, damage, right-click, use-item, attack and interact paths, making it the universal pre-action hotbar sync. Because it only sends on change, scrolling without acting emits a single C09, while acting without scrolling emits none. The server applies the slot switch before processing the following C07, C08 or C02, so weapon or block identity is correct. Blocking C09 while switching items causes ghost-block or wrong-weapon hits where client and server disagree. The cache also drives isHittingPosition validation for mining continuity.",
      "code": "    private void syncCurrentPlayItem()\n    {\n        int i = this.mc.thePlayer.inventory.currentItem;\n\n        if (i != this.currentPlayerItem)\n        {\n            this.currentPlayerItem = i;\n            this.netClientHandler.addToSendQueue(new C09PacketHeldItemChange(this.currentPlayerItem));\n        }\n    }",
      "code_walkthrough": "The inventory.currentItem read captures the live hotbar slot after number-key or wheel input. The inequality against currentPlayerItem filters redundant sends so idle ticks produce no C09. The C09 constructor carries just the slot index the server equips before handling the next action packet. If this sync is skipped the server applies C07 or C08 with the previous slot, which is the slot-desync behind far-place or wrong-tool anomalies."
     },
     {
      "name": "resetBlockRemoving/onStoppedUsingItem",
      "detail_long": "resetBlockRemoving checks isHittingBlock and on true queues C07 ABORT_DESTROY_BLOCK with currentBlock and DOWN face, clears isHittingBlock and curBlockDamageMP, and clears the crack overlay via sendBlockBreakProgress with -1. It is called when the mouse is released, the target changes, or the held item switches via isHittingPosition mismatch. onStoppedUsingItem syncs the hotbar, queues C07 RELEASE_USE_ITEM with ORIGIN and DOWN placeholders, and calls stopUsingItem locally to end bow draw or food eat. Both use the C07 channel with distinct actions so the server can separate mining abort from use release. For bow release the server spawns the arrow based on draw duration, while for food it cancels eating progress. Omitting ABORT leaves server crack progress running, and omitting RELEASE allows fast-bow or no-slow exploits that the server times via packet intervals.",
      "code": "    public void resetBlockRemoving()\n    {\n        if (this.isHittingBlock)\n        {\n            this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, EnumFacing.DOWN));\n            this.isHittingBlock = false;\n            this.curBlockDamageMP = 0.0F;\n            this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, -1);\n        }\n    }\n\n    public boolean onPlayerDamageBlock(BlockPos posBlock, EnumFacing directionFacing)",
      "code_walkthrough": "The isHittingBlock guard ensures ABORT is only sent when a dig was actually in progress, avoiding spurious server resets. The C07 ABORT carries the stale currentBlock so the server can clear crack state for that exact position. Clearing curBlockDamageMP and sending progress -1 removes the local crack overlay in step with the server. onStoppedUsingItem mirrors this with RELEASE_USE_ITEM for bows and food, so blocking either ABORT or RELEASE desyncs server progress timers used by anti-cheat."
     }
    ]
   }
  },
  {
   "slug": "ServerScoreboard",
   "title": "ServerScoreboard",
   "rel": "net/minecraft/scoreboard/ServerScoreboard.java",
   "desc": "Server scoreboard: objective/team/score mutations broadcast S3B, S3C, S3D and S3E to all players.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/ServerScoreboard/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/scoreboard/ServerScoreboard.java",
   "packets": [
    "S3BPacketScoreboardObjective",
    "S3CPacketUpdateScore",
    "S3DPacketDisplayScoreboard",
    "S3EPacketTeams"
   ],
   "peers": [
    "EntityPlayerMP",
    "ServerConfigurationManager",
    "WorldServer"
   ],
   "analysis": {
    "overview": "Scoreboard subclass broadcasting all objective, score, and team mutations globally. No distance or dimension gating; uses sendPacketToAllPlayers. Tracks dirty save data for persistence. Buffers create vs remove packet lists for late joiners.",
    "methods": [
     {
      "detail": "Calls super then if field_96553_b contains objective sends S3CPacketUpdateScore to all players. Untracked objectives stay local. Marks save data dirty.",
      "name": "func_96536_a",
      "packets": [
       "S3C"
      ],
      "purpose": "Broadcast score value update for tracked objective."
     },
     {
      "detail": "Compares old vs new slot objective. If old orphaned with zero slots sends removal packets, else sends S3DPacketDisplayScoreboard. If new untracked calls func_96549_e burst.",
      "name": "setObjectiveInDisplaySlot",
      "packets": [
       "S3D"
      ],
      "purpose": "Sync sidebar, list, belowName display assignment."
     },
     {
      "detail": "On super success sends S3EPacketTeams with team, single-player list, action 3 join. Global fan-out, no gating. Marks save dirty. Returns false if already on team.",
      "name": "addPlayerToTeam",
      "packets": [
       "S3E"
      ],
      "purpose": "Add member and notify all clients."
     },
     {
      "detail": "Calls super then sends S3EPacketTeams action 4 leave with player list. Global broadcast. Marks save dirty. Throws if player not on team per super.",
      "name": "removePlayerFromTeam",
      "packets": [
       "S3E"
      ],
      "purpose": "Remove member and notify all clients."
     },
     {
      "detail": "Calls super then sends S3EPacketTeams action 0 create with full team fields. Global. Marks save dirty. Paired with func_96513_c remove action 1.",
      "name": "broadcastTeamCreated",
      "packets": [
       "S3E"
      ],
      "purpose": "Register new team on all clients."
     },
     {
      "detail": "Calls super then sends S3EPacketTeams action 2 update to all players. Covers prefix, suffix, friendly fire, visibility. Marks save dirty.",
      "name": "sendTeamUpdate",
      "packets": [
       "S3E"
      ],
      "purpose": "Push team display property change."
     },
     {
      "detail": "Calls super then if tracked sends S3BPacketScoreboardObjective action 2 update. Untracked renames stay local until func_96549_e. Marks save dirty.",
      "name": "onObjectiveDisplayNameChanged",
      "packets": [
       "S3B"
      ],
      "purpose": "Rename tracked objective on clients."
     },
     {
      "detail": "Builds list via func_96550_d: S3B create 0, S3D per used slot of 19, S3C per sorted score. Sends to every player list entry. Adds to tracked set.",
      "name": "func_96549_e",
      "packets": [
       "S3B",
       "S3D",
       "S3C"
      ],
      "purpose": "Burst full objective state to late joiners or new objective."
     },
     {
      "detail": "Builds list via func_96548_f: S3B remove 1 plus S3D per occupied slot. Sends to all players. Removes from tracked set field_96553_b.",
      "name": "sendDisplaySlotRemovalPackets",
      "packets": [
       "S3B",
       "S3D"
      ],
      "purpose": "Remove objective everywhere including display slots."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S3C",
      "trigger": "score created, updated, or removed globally"
     },
     {
      "direction": "sent",
      "id": "S3B",
      "trigger": "objective created, renamed action2, removed action1"
     },
     {
      "direction": "sent",
      "id": "S3D",
      "trigger": "display slot assigned or cleared"
     },
     {
      "direction": "sent",
      "id": "S3E",
      "trigger": "team create0 remove1 update2 join3 leave4"
     }
    ],
    "internal_fields": [
     {
      "name": "scoreboardMCServer",
      "role": "Source of configuration manager for global sends"
     },
     {
      "name": "field_96553_b",
      "role": "Set of tracked broadcast objectives vs local-only"
     },
     {
      "name": "scoreboardSaveData",
      "role": "Dirty-marked persistence for scoreboard changes"
     }
    ],
    "peers": [
     "ServerConfigurationManager",
     "ScoreboardSaveData",
     "WorldServer"
    ],
    "methods_detailed": [
     {
      "name": "func_96536_a",
      "detail_long": "This override broadcasts a score value change for a tracked objective. It first calls super to update the in-memory Score object. It then checks whether field_96553_b tracked set contains the score objective. Only tracked objectives produce network traffic, untracked ones stay local until burst. If tracked it calls sendPacketToAllPlayers with S3CPacketUpdateScore wrapping the Score. That fan-out has no distance or dimension gating and reaches every connected player. It finally calls markSaveDataDirty to persist the change via ScoreboardSaveData. This path handles score creation and value updates. Removal uses a different overload with name-only packet. The tracked set therefore filters global spam.",
      "code": "    public void func_96536_a(Score p_96536_1_)\n    {\n        super.func_96536_a(p_96536_1_);\n\n        if (this.field_96553_b.contains(p_96536_1_.getObjective()))\n        {\n            this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3CPacketUpdateScore(p_96536_1_));\n        }\n\n        this.markSaveDataDirty();\n    }",
      "code_walkthrough": "The signature takes the updated Score. The super call applies the local map change. The contains check gates networking on tracked status. The sendPacketToAllPlayers line builds S3CPacketUpdateScore from the Score. The markSaveDataDirty call flags persistence. This shows global ungated S3C fan-out for tracked scores."
     },
     {
      "name": "setObjectiveInDisplaySlot",
      "detail_long": "This method synchronizes sidebar list and below-name display assignments. It caches the old slot objective then calls super to update the slot map. If the old objective differs and is non-null, it checks how many slots still reference it via func_96552_h. If still referenced elsewhere it sends S3DPacketDisplayScoreboard for that slot and new objective, otherwise it sends removal packets via sendDisplaySlotRemovalPackets. For the new objective, if non-null and already tracked it sends S3DPacketDisplayScoreboard globally. If new and untracked it calls func_96549_e to burst full state including S3B create, S3D slots, and S3C scores. It finally marks save data dirty. Slots 0 tab, 1 sidebar, and 2 below name map to the 19 internal slots. No radius or dimension gating applies.",
      "code": "    public void setObjectiveInDisplaySlot(int p_96530_1_, ScoreObjective p_96530_2_)\n    {\n        ScoreObjective scoreobjective = this.getObjectiveInDisplaySlot(p_96530_1_);\n        super.setObjectiveInDisplaySlot(p_96530_1_, p_96530_2_);\n\n        if (scoreobjective != p_96530_2_ && scoreobjective != null)\n        {\n            if (this.func_96552_h(scoreobjective) > 0)\n            {\n                this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3DPacketDisplayScoreboard(p_96530_1_, p_96530_2_));\n            }\n            else\n            {\n                this.sendDisplaySlotRemovalPackets(scoreobjective);\n            }\n        }\n\n        if (p_96530_2_ != null)\n        {\n            if (this.field_96553_b.contains(p_96530_2_))\n            {\n                this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3DPacketDisplayScoreboard(p_96530_1_, p_96530_2_));\n            }\n            else\n            {\n                this.func_96549_e(p_96530_2_);\n            }\n        }\n\n        this.markSaveDataDirty();\n    }",
      "code_walkthrough": "The signature binds slot index and new objective. The cache plus super lines detect old versus new. The orphan check uses func_96552_h count to choose S3D update versus removal burst. The new objective branch sends S3D if tracked else bursts via func_96549_e. The S3DPacketDisplayScoreboard constructor packs slot and objective. The final dirty mark persists slot assignment."
     },
     {
      "name": "addPlayerToTeam",
      "detail_long": "This method adds a member to a team and notifies all clients. It first calls super.addPlayerToTeam to update the membership map. If super returns false because the player is already on that team, it returns false with no packet. On success it resolves the ScorePlayerTeam via getTeam for the new team name. It then sends S3EPacketTeams globally via sendPacketToAllPlayers with team, singleton player list, and action 3 join. Action 3 means add players to existing team without resending full fields. The fan-out is global with no 16.0D or 64.0D radius and no dimension filter. It marks save data dirty for persistence and returns true. Clients then render nametag and friendly-fire rules accordingly.",
      "code": "    public boolean addPlayerToTeam(String player, String newTeam)\n    {\n        if (super.addPlayerToTeam(player, newTeam))\n        {\n            ScorePlayerTeam scoreplayerteam = this.getTeam(newTeam);\n            this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, Arrays.asList(new String[] {player}), 3));\n            this.markSaveDataDirty();\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }",
      "code_walkthrough": "The signature takes player name and team name. The super if gates networking on membership change. The getTeam line resolves the team object. The sendPacketToAllPlayers line builds S3EPacketTeams with action 3 and single-player list. The dirty mark plus true return confirms persistence. The else returns false with no broadcast. This is global S3E join fan-out."
     },
     {
      "name": "removePlayerFromTeam",
      "detail_long": "This method removes a member from a team and broadcasts the leave. It first calls super.removePlayerFromTeam to update the server map, which throws if the player is not on that team. It then sends S3EPacketTeams globally with team, singleton list, and action 4 leave. Action 4 tells clients to drop that entry from the team roster. Delivery uses sendPacketToAllPlayers with no distance or dimension gating. It finally marks save data dirty for disk persistence. The packet carries only the affected player, not the full roster. If multiple leaves occur each generates its own packet with no batching. This keeps team rosters consistent for tab list and collisions.",
      "code": "     * Removes the given username from the given ScorePlayerTeam. If the player is not on the team then an\n     * IllegalStateException is thrown.\n     */\n    public void removePlayerFromTeam(String p_96512_1_, ScorePlayerTeam p_96512_2_)\n    {\n        super.removePlayerFromTeam(p_96512_1_, p_96512_2_);\n        this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3EPacketTeams(p_96512_2_, Arrays.asList(new String[] {p_96512_1_}), 4));\n        this.markSaveDataDirty();\n    }",
      "code_walkthrough": "The comment warns about IllegalStateException for non-members. The signature binds player name and team object. The super call mutates the roster or throws. The sendPacketToAllPlayers line builds S3EPacketTeams action 4 leave. The markSaveDataDirty call persists removal. This is global ungated single-player S3E update."
     },
     {
      "name": "broadcastTeamCreated",
      "detail_long": "This callback registers a newly created team on all clients. It first calls super.broadcastTeamCreated to add the team to the server map. It then sends S3EPacketTeams with the team object and action 0 create via sendPacketToAllPlayers. Action 0 carries full team fields including display name, prefix, suffix, friendly fire, and visibility. The broadcast is global with no radius or dimension filtering. It marks save data dirty to persist the new team. The paired removal uses func_96513_c with action 1. Without this packet clients would not know the team exists for later join actions. Late joiners receive teams again via burst logic.",
      "code": "    /**\n     * This packet will notify the players that this team is created, and that will register it on the client\n     */\n    public void broadcastTeamCreated(ScorePlayerTeam playerTeam)\n    {\n        super.broadcastTeamCreated(playerTeam);\n        this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3EPacketTeams(playerTeam, 0));\n        this.markSaveDataDirty();\n    }",
      "code_walkthrough": "The comment states client registration intent. The signature takes the new ScorePlayerTeam. The super call stores it server side. The sendPacketToAllPlayers line builds S3EPacketTeams action 0 create. The dirty mark persists creation. This is global full-state S3E fan-out."
     },
     {
      "name": "sendTeamUpdate",
      "detail_long": "This callback pushes team property edits to all clients. It first calls super.sendTeamUpdate to update the server team object. It then sends S3EPacketTeams with the team and action 2 update via sendPacketToAllPlayers. Action 2 carries prefix, suffix, friendly fire, see friendly invisibles, and name tag visibility changes. The fan-out is global with no distance or dimension gate. It marks save data dirty for persistence. Membership is unchanged, so no player list is included unlike actions 3 and 4. Clients apply the new display fields immediately to tab and overhead names. Frequent prefix changes each generate a packet without coalescing.",
      "code": "    /**\n     * This packet will notify the players that this team is updated\n     */\n    public void sendTeamUpdate(ScorePlayerTeam playerTeam)\n    {\n        super.sendTeamUpdate(playerTeam);\n        this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3EPacketTeams(playerTeam, 2));\n        this.markSaveDataDirty();\n    }",
      "code_walkthrough": "The comment identifies property update intent. The signature takes the edited team. The super call applies local fields. The sendPacketToAllPlayers line builds S3EPacketTeams action 2. The dirty mark persists the edit. This is global S3E property sync without roster payload."
     },
     {
      "name": "onObjectiveDisplayNameChanged",
      "detail_long": "This callback renames a tracked objective on all clients. It first calls super.onObjectiveDisplayNameChanged to update the server display string. It then checks whether field_96553_b tracked set contains the objective. Only tracked objectives broadcast, untracked renames remain local until a later burst. If tracked it sends S3BPacketScoreboardObjective with the objective and action 2 update via sendPacketToAllPlayers. Action 2 means update display text without recreating scores. The send is global with no radius or dimension gating. It finally marks save data dirty. Clients update sidebar and tab headers on receipt. Creation uses action 0 and removal uses action 1 elsewhere.",
      "code": "    public void onObjectiveDisplayNameChanged(ScoreObjective p_96532_1_)\n    {\n        super.onObjectiveDisplayNameChanged(p_96532_1_);\n\n        if (this.field_96553_b.contains(p_96532_1_))\n        {\n            this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3BPacketScoreboardObjective(p_96532_1_, 2));\n        }\n\n        this.markSaveDataDirty();\n    }",
      "code_walkthrough": "The signature takes the renamed ScoreObjective. The super call updates the server name. The contains check filters to tracked objectives only. The sendPacketToAllPlayers line builds S3B action 2 rename. The dirty mark persists the new name. This shows conditional global S3B fan-out."
     },
     {
      "name": "func_96549_e",
      "detail_long": "This method bursts full objective state to all players for late joiners or new objectives. It builds the packet list via func_96550_d, which creates S3BPacketScoreboardObjective action 0 create, plus S3DPacketDisplayScoreboard for each of 19 slots referencing it, plus S3CPacketUpdateScore per sorted score. It then loops over every EntityPlayerMP in the configuration manager player list. For each player it loops the list and sends each Packet via playerNetServerHandler.sendPacket. After the fan-out it adds the objective to field_96553_b tracked set so future deltas broadcast incrementally. Delivery is global with no distance or dimension gating. This is the heaviest scoreboard burst, proportional to score count. It pairs with sendDisplaySlotRemovalPackets for teardown.",
      "code": "    public void func_96549_e(ScoreObjective p_96549_1_)\n    {\n        List<Packet> list = this.func_96550_d(p_96549_1_);\n\n        for (EntityPlayerMP entityplayermp : this.scoreboardMCServer.getConfigurationManager().getPlayerList())\n        {\n            for (Packet packet : list)\n            {\n                entityplayermp.playerNetServerHandler.sendPacket(packet);\n            }\n        }\n\n        this.field_96553_b.add(p_96549_1_);\n    }",
      "code_walkthrough": "The signature takes the new ScoreObjective to publish. The func_96550_d call builds S3B plus S3D plus S3C list. The outer loop visits every online player. The inner loop sends each packet in order via playerNetServerHandler. The add call marks the objective tracked. This is ordered global burst for synchronization."
     },
     {
      "name": "sendDisplaySlotRemovalPackets",
      "detail_long": "This method removes an objective everywhere including display slots. It builds the removal list via func_96548_f, which creates S3BPacketScoreboardObjective action 1 remove plus S3DPacketDisplayScoreboard entries for each occupied slot among 19. It then loops over every EntityPlayerMP in the player list. For each player it sends every Packet in that list via playerNetServerHandler.sendPacket. After delivery it removes the objective from field_96553_b tracked set so future score edits stay local. The fan-out is global with no radius or dimension gating. Clients clear sidebar, list, and below-name displays referencing the objective. This is the symmetric teardown to func_96549_e burst creation.",
      "code": "    public void sendDisplaySlotRemovalPackets(ScoreObjective p_96546_1_)\n    {\n        List<Packet> list = this.func_96548_f(p_96546_1_);\n\n        for (EntityPlayerMP entityplayermp : this.scoreboardMCServer.getConfigurationManager().getPlayerList())\n        {\n            for (Packet packet : list)\n            {\n                entityplayermp.playerNetServerHandler.sendPacket(packet);\n            }\n        }\n\n        this.field_96553_b.remove(p_96546_1_);\n    }",
      "code_walkthrough": "The signature takes the objective to delete. The func_96548_f call builds S3B remove plus S3D clears. The outer loop covers all players globally. The inner loop delivers each removal packet in order. The remove call untracks the objective. This ensures clients drop both objective and slot bindings."
     }
    ]
   }
  },
  {
   "slug": "NetHandlerLoginServer",
   "title": "NetHandlerLoginServer",
   "rel": "net/minecraft/server/network/NetHandlerLoginServer.java",
   "desc": "Server login state machine (HELLO/KEY/AUTHENTICATING/READY): S01 encryption challenge, S02 success, S03 compression.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/NetHandlerLoginServer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/server/network/NetHandlerLoginServer.java",
   "packets": [
    "S00PacketDisconnect",
    "S01PacketEncryptionRequest",
    "S02PacketLoginSuccess",
    "S03PacketEnableCompression"
   ],
   "peers": [
    "EntityPlayerMP",
    "NetworkManager",
    "ServerConfigurationManager",
    "NetHandlerPlayServer"
   ],
   "analysis": {
    "overview": "Login-state machine HELLO>KEY>AUTHENTICATING>READY>ACCEPTED. Validates C00 start and C01 encryption, verifies Mojang session off-thread, then hands to ServerConfigurationManager or disconnects.",
    "methods": [
     {
      "detail": "Requires HELLO state via Validate. Online mode and non-local sends S01 EncryptionRequest with serverId, public key and 4-byte verifyToken; else goes READY_TO_ACCEPT.",
      "name": "processLoginStart",
      "packets": [
       "C00",
       "S01"
      ],
      "purpose": "Starts login or requests encryption."
     },
     {
      "detail": "Requires KEY state. Compares verifyToken with private-key decrypt; throws Invalid nonce on mismatch. Enables encryption then spawns User Authenticator thread.",
      "name": "processEncryptionResponse",
      "packets": [
       "C01"
      ],
      "purpose": "Verifies nonce and enables crypto."
     },
     {
      "detail": "READY_TO_ACCEPT calls tryAcceptPlayer. DELAY_ACCEPT waits for duplicate logout then initializes. connectionTimer 600 ticks closes Took too long to log in.",
      "name": "update",
      "packets": [
       "S02",
       "S03"
      ],
      "purpose": "Advances ready/delayed accept and timeout."
     },
     {
      "detail": "Offline-mode generates offline UUID. allowUserToConnect non-null closes with reason. Else sends S03 EnableCompression if threshold>=0, then S02 LoginSuccess and creates player.",
      "name": "tryAcceptPlayer",
      "packets": [
       "S02",
       "S03",
       "S00"
      ],
      "purpose": "Applies bans, compression and success."
     },
     {
      "detail": "Logs info with connection string. Sends S00 Disconnect with text reason then closeChannel. Catches and logs disconnect errors.",
      "name": "closeConnection",
      "packets": [
       "S00"
      ],
      "purpose": "Sends kick and closes channel."
     },
     {
      "detail": "UUID.nameUUIDFromBytes OfflinePlayer:name with UTF-8. Used for offline servers and singleplayer fallback when auth servers down.",
      "name": "getOfflineProfile",
      "packets": [],
      "purpose": "Derives offline UUID profile."
     }
    ],
    "packet_usage": [
     {
      "direction": "handled",
      "id": "C00",
      "trigger": "Client hello with GameProfile"
     },
     {
      "direction": "handled",
      "id": "C01",
      "trigger": "Encrypted secret and verify token"
     },
     {
      "direction": "sent",
      "id": "S00",
      "trigger": "Login disconnect with reason"
     },
     {
      "direction": "sent",
      "id": "S01",
      "trigger": "Encryption request in online mode"
     },
     {
      "direction": "sent",
      "id": "S02",
      "trigger": "Login success before PLAY switch"
     },
     {
      "direction": "sent",
      "id": "S03",
      "trigger": "Enable compression if threshold set"
     }
    ],
    "internal_fields": [
     {
      "name": "currentLoginState",
      "role": "HELLO/KEY/AUTH/READY/DELAY/ACCEPTED enum"
     },
     {
      "name": "verifyToken",
      "role": "4-byte nonce to prevent replay"
     },
     {
      "name": "loginGameProfile",
      "role": "Pending profile, completed after auth"
     },
     {
      "name": "connectionTimer",
      "role": "Ticks since construct; 600 timeout"
     },
     {
      "name": "secretKey",
      "role": "Shared secret enabling encryption"
     }
    ],
    "peers": [
     "ServerConfigurationManager",
     "NetHandlerPlayServer",
     "NetworkManager",
     "MinecraftServer"
    ],
    "methods_detailed": [
     {
      "name": "processLoginStart",
      "detail_long": "processLoginStart handles C00 hello and branches online versus offline login. It validates state equals HELLO via Validate, throwing on duplicate hello. It stores the GameProfile from the packet. If online mode is enabled and the channel is not local, it moves to KEY state and sends S01 EncryptionRequest with empty serverId, server public key and four-byte verifyToken. Otherwise for offline or singleplayer it jumps directly to READY_TO_ACCEPT. No kick occurs here, errors throw IllegalStateException. The verifyToken nonce later proves the client holds the private key. Local channels skip encryption to reduce latency.",
      "code": "    public void processLoginStart(C00PacketLoginStart packetIn)\n    {\n        Validate.validState(this.currentLoginState == NetHandlerLoginServer.LoginState.HELLO, \"Unexpected hello packet\", new Object[0]);\n        this.loginGameProfile = packetIn.getProfile();\n\n        if (this.server.isServerInOnlineMode() && !this.networkManager.isLocalChannel())\n        {\n            this.currentLoginState = NetHandlerLoginServer.LoginState.KEY;\n            this.networkManager.sendPacket(new S01PacketEncryptionRequest(this.serverId, this.server.getKeyPair().getPublic(), this.verifyToken));\n        }\n        else\n        {\n            this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;\n        }\n    }",
      "code_walkthrough": "Validate.validState enforces the HELLO to KEY to AUTH state machine and rejects replays. Storing loginGameProfile preserves the requested name for later Mojang verification. The online-mode plus not-local gate selects encrypted versus instant accept. S01PacketEncryptionRequest carries serverId, public key and verifyToken nonce. The else moves offline logins straight to READY_TO_ACCEPT for tryAcceptPlayer."
     },
     {
      "name": "processEncryptionResponse",
      "detail_long": "processEncryptionResponse handles C01 key exchange in KEY state. It validates KEY state, fetches the server private key and compares the decrypted verifyToken with Arrays equals, throwing Invalid nonce on mismatch to block replay. On match it decrypts the shared secret, moves to AUTHENTICATING and enables encryption on the channel. It then spawns User Authenticator thread with incrementing ID to avoid blocking netty. That thread hashes serverId, public key and secret via CryptManager, calls hasJoinedServer to verify the Mojang session, and on success sets READY_TO_ACCEPT. Singleplayer fallback generates offline profiles when verification fails or auth servers are down, otherwise it closes with Failed to verify username. No S packets are sent here directly.",
      "code": "    public void processEncryptionResponse(C01PacketEncryptionResponse packetIn)\n    {\n        Validate.validState(this.currentLoginState == NetHandlerLoginServer.LoginState.KEY, \"Unexpected key packet\", new Object[0]);\n        PrivateKey privatekey = this.server.getKeyPair().getPrivate();\n\n        if (!Arrays.equals(this.verifyToken, packetIn.getVerifyToken(privatekey)))\n        {\n            throw new IllegalStateException(\"Invalid nonce!\");\n        }\n        else\n        {\n            this.secretKey = packetIn.getSecretKey(privatekey);\n            this.currentLoginState = NetHandlerLoginServer.LoginState.AUTHENTICATING;\n            this.networkManager.enableEncryption(this.secretKey);\n            (new Thread(\"User Authenticator #\" + AUTHENTICATOR_THREAD_ID.incrementAndGet())",
      "code_walkthrough": "The KEY state check rejects out-of-order C01 packets. Decrypting verifyToken with the private key and comparing to stored nonce detects tampering. Throwing Invalid nonce aborts the login without a graceful S00. Storing secretKey, setting AUTHENTICATING and enabling encryption switch the channel to ciphered mode. Spawning the authenticator thread offloads the blocking Mojang HTTPS check."
     },
     {
      "name": "update",
      "detail_long": "update ticks the login state machine and enforces the 600-tick timeout. If state is READY_TO_ACCEPT it calls tryAcceptPlayer immediately to apply bans and compression. If state is DELAY_ACCEPT it polls for the duplicate old player by UUID, and when null it flips to READY_TO_ACCEPT, initializes the new player and clears the pending reference. It increments connectionTimer every tick and closes with Took too long to log in via S00 Disconnect at exactly 600. DELAY_ACCEPT exists because createPlayerForUser kicks the old session but the logout needs ticks to complete. No PLAY packets are sent here, only login S00, S02 and S03 via helpers. Stuck AUTHENTICATING threads eventually hit the same timeout.",
      "code": "    public void update()\n    {\n        if (this.currentLoginState == NetHandlerLoginServer.LoginState.READY_TO_ACCEPT)\n        {\n            this.tryAcceptPlayer();\n        }\n        else if (this.currentLoginState == NetHandlerLoginServer.LoginState.DELAY_ACCEPT)\n        {\n            EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());\n\n            if (entityplayermp == null)\n            {\n                this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;\n                this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.player);\n                this.player = null;\n            }\n        }\n\n        if (this.connectionTimer++ == 600)\n        {\n            this.closeConnection(\"Took too long to log in\");\n        }\n    }",
      "code_walkthrough": "The READY_TO_ACCEPT branch drives immediate accept without waiting for network events. The DELAY_ACCEPT branch looks up the old UUID entry to detect when the kicked duplicate has logged out. Null means safe to initializeConnectionToPlayer with the staged player object. The connectionTimer post-increment equals 600 gate sends S00 Took too long to log in. That timeout bounds Mojang outages and stalled encryption handshakes."
     },
     {
      "name": "tryAcceptPlayer",
      "detail_long": "tryAcceptPlayer applies final login gates and switches to PLAY. It completes incomplete profiles with getOfflineProfile deriving OfflinePlayer UUIDs. It calls allowUserToConnect and closes with the ban, whitelist, IP or full reason when non-null. On success it sets ACCEPTED, and if compression threshold is non-negative on a remote channel it sends S03 EnableCompression then sets the threshold on future. It sends S02 LoginSuccess with the verified profile to trigger client PLAY switch. It checks for duplicate UUID sessions, staging a new player and entering DELAY_ACCEPT when found, otherwise initializing immediately via createPlayerForUser. No teleport occurs, the follow-up initializeConnectionToPlayer sends the S01 burst. Offline servers always take the instant path.",
      "code": "        String s = this.server.getConfigurationManager().allowUserToConnect(this.networkManager.getRemoteAddress(), this.loginGameProfile);\n\n        if (s != null)\n        {\n            this.closeConnection(s);\n        }\n        else\n        {\n            this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED;\n\n            if (this.server.getNetworkCompressionTreshold() >= 0 && !this.networkManager.isLocalChannel())\n            {\n                this.networkManager.sendPacket(new S03PacketEnableCompression(this.server.getNetworkCompressionTreshold()), new ChannelFutureListener()\n                {\n                    public void operationComplete(ChannelFuture p_operationComplete_1_) throws Exception\n                    {\n                        NetHandlerLoginServer.this.networkManager.setCompressionTreshold(NetHandlerLoginServer.this.server.getNetworkCompressionTreshold());\n                    }\n                }, new GenericFutureListener[0]);\n            }\n\n            this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile));\n            EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());\n\n            if (entityplayermp != null)\n            {\n                this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT;\n                this.player = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile);\n            }\n            else\n            {\n                this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile));\n            }",
      "code_walkthrough": "allowUserToConnect returns null only when bans, whitelist, IP and capacity all pass. Non-null triggers closeConnection with S00 carrying that reason. Setting ACCEPTED plus S03 EnableCompression negotiates compression before LoginSuccess. S02PacketLoginSuccess carries the final UUID and name to switch the client to PLAY. The UUID duplicate check stages DELAY_ACCEPT versus immediate initializeConnectionToPlayer for overlap handling."
     },
     {
      "name": "closeConnection",
      "detail_long": "closeConnection terminates a login with S00 Disconnect and channel close. It logs the connection info plus reason for audit. It wraps the reason in ChatComponentText, sends S00PacketDisconnect, then closes the channel with the same component. Exceptions during send or close are caught and logged as Error whilst disconnecting player without rethrow. It is used for ban kicks, auth failures, duplicate handling and the 600-tick timeout. No PLAY packets are involved because the pipeline is still in LOGIN state. The client displays the text on the disconnected screen.",
      "code": "    public void closeConnection(String reason)\n    {\n        try\n        {\n            logger.info(\"Disconnecting \" + this.getConnectionInfo() + \": \" + reason);\n            ChatComponentText chatcomponenttext = new ChatComponentText(reason);\n            this.networkManager.sendPacket(new S00PacketDisconnect(chatcomponenttext));\n            this.networkManager.closeChannel(chatcomponenttext);\n        }\n        catch (Exception exception)\n        {\n            logger.error((String)\"Error whilst disconnecting player\", (Throwable)exception);\n        }\n    }",
      "code_walkthrough": "The try block ensures logging and packet send happen atomically. getConnectionInfo includes profile and remote address for forensics. S00PacketDisconnect carries the human-readable kick reason to the client. closeChannel with the same component tears down the netty pipeline. The catch prevents disconnect-path exceptions from crashing the server tick."
     },
     {
      "name": "getOfflineProfile",
      "detail_long": "getOfflineProfile derives deterministic offline UUIDs for cracked and singleplayer logins. It concatenates OfflinePlayer colon plus original name, encodes as UTF-8 bytes and hashes with nameUUIDFromBytes version three. It returns a new GameProfile with that UUID and the original name preserving case. It is called by tryAcceptPlayer for incomplete profiles and by the auth thread when Mojang verification fails on singleplayer or auth servers are down. Online verified logins never use this path. No packets are sent here, the UUID feeds allowUserToConnect and S02 LoginSuccess. The deterministic mapping lets offline servers keep consistent inventories by name.",
      "code": "    protected GameProfile getOfflineProfile(GameProfile original)\n    {\n        UUID uuid = UUID.nameUUIDFromBytes((\"OfflinePlayer:\" + original.getName()).getBytes(Charsets.UTF_8));\n        return new GameProfile(uuid, original.getName());\n    }\n\n    static enum LoginState\n    {\n        HELLO,\n        KEY,",
      "code_walkthrough": "The OfflinePlayer prefix plus name string is the canonical offline seed. getBytes with UTF_8 ensures cross-platform UUID stability. nameUUIDFromBytes produces a version-three UUID from that seed. Returning a GameProfile with that UUID and original name lets bans and NBT key by stable id. The following LoginState enum defines HELLO, KEY and later states for the handshake."
     }
    ]
   }
  },
  {
   "slug": "WorldManager",
   "title": "WorldManager",
   "rel": "net/minecraft/world/WorldManager.java",
   "desc": "Server world listener: relays S25 break progress, S28 effects and S29 sounds to players near the event.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/WorldManager/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/world/WorldManager.java",
   "packets": [
    "S25PacketBlockBreakAnim",
    "S28PacketEffect",
    "S29PacketSoundEffect"
   ],
   "peers": [
    "EntityPlayerMP",
    "WorldServer",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "PlayerManager",
    "ServerConfigurationManager"
   ],
   "analysis": {
    "overview": "IWorldAccess bridge between WorldServer events and ServerConfigurationManager broadcasts. Applies volume-scaled and fixed radii with dimension gating. Forwards block updates to PlayerManager chunk map. Manages entity tracker add/remove.",
    "methods": [
     {
      "detail": "Uses sendToAllNear with radius 16.0D, or 16.0F*volume if volume>1.0F. Gated by theWorldServer dimension ID. Creates S29PacketSoundEffect with pos, volume, pitch.",
      "name": "playSound",
      "packets": [
       "S29"
      ],
      "purpose": "Broadcast named sound with volume-scaled range."
     },
     {
      "detail": "Same radius rule as playSound: 16.0D or 16*volume. Calls sendToAllNearExcept for originator exclusion. Dimension-gated. Used for player-caused sounds.",
      "name": "playSoundToNearExcept",
      "packets": [
       "S29"
      ],
      "purpose": "Broadcast sound excluding one player."
     },
     {
      "detail": "Calls sendToAllNearExcept with fixed 64.0D radius and dimension gate. Sends S28PacketEffect with sfxType, BlockPos, data, false. Excludes triggering player.",
      "name": "playAuxSFX",
      "packets": [
       "S28"
      ],
      "purpose": "Broadcast block auxiliary effect near position except actor."
     },
     {
      "detail": "Calls sendPacketToAllPlayers with S28PacketEffect soundID, pos, data, true. No distance or dimension gating. Used for portal, wither spawn style events.",
      "name": "broadcastSound",
      "packets": [
       "S28"
      ],
      "purpose": "Global broadcast of auxiliary effect to all players."
     },
     {
      "detail": "Iterates configuration manager player list, filters worldObj==theWorldServer and ID!=breakerId. Checks d2<1024.0D (32 blocks). Sends S25PacketBlockBreakAnim directly.",
      "name": "sendBlockBreakProgress",
      "packets": [
       "S25"
      ],
      "purpose": "Send crack animation to viewers within 32 blocks."
     },
     {
      "detail": "Delegates to PlayerManager.markBlockForUpdate mapping BlockPos to chunk. No immediate packet; PlayerInstance.onUpdate later picks S23/S22/S21 by count. Chunk-scoped fan-out.",
      "name": "markBlockForUpdate",
      "packets": [
       "S23",
       "S22",
       "S21"
      ],
      "purpose": "Queue chunk block change for batched send."
     },
     {
      "detail": "Calls theWorldServer.getEntityTracker.trackEntity. Tracker later emits spawn packets per type. No direct packet here. Entry point for entity spawn fan-out.",
      "name": "onEntityAdded",
      "packets": [],
      "purpose": "Register new entity with tracker for visibility."
     },
     {
      "detail": "Calls EntityTracker.untrackEntity then Scoreboard.func_181140_a. Causes destroy packets via tracker. No radius; removes from all viewers.",
      "name": "onEntityRemoved",
      "packets": [],
      "purpose": "Untrack entity and clear scoreboard state."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S29",
      "trigger": "playSound or playSoundToNearExcept volume radius"
     },
     {
      "direction": "sent",
      "id": "S28",
      "trigger": "playAuxSFX 64.0D except or broadcastSound global"
     },
     {
      "direction": "sent",
      "id": "S25",
      "trigger": "sendBlockBreakProgress within 1024.0D"
     },
     {
      "direction": "sent",
      "id": "S23",
      "trigger": "markBlockForUpdate single-block flush via PlayerManager"
     },
     {
      "direction": "sent",
      "id": "S22",
      "trigger": "markBlockForUpdate multi-block flush via PlayerManager"
     },
     {
      "direction": "sent",
      "id": "S21",
      "trigger": "markBlockForUpdate full-chunk flush via PlayerManager"
     }
    ],
    "internal_fields": [
     {
      "name": "mcServer",
      "role": "Provides ServerConfigurationManager sendToAllNear helpers"
     },
     {
      "name": "theWorldServer",
      "role": "Source dimension ID and PlayerManager/Tracker access"
     },
     {
      "name": "IWorldAccess",
      "role": "Interface hooking world events to network fan-out"
     }
    ],
    "peers": [
     "WorldServer",
     "PlayerManager",
     "EntityTracker",
     "ServerConfigurationManager"
    ],
    "methods_detailed": [
     {
      "name": "playSound",
      "detail_long": "This IWorldAccess hook broadcasts a named sound to nearby players in the same dimension. It is called by world simulation when a block or entity emits a sound. It resolves recipients via ServerConfigurationManager.sendToAllNear at the exact x y z origin. The radius rule is volume scaled: 16.0D by default, or 16.0F times volume when volume exceeds 1.0F. This lets loud sounds like explosions or withers travel farther than quiet clicks. Dimension gating uses theWorldServer.provider.getDimensionId so nether and overworld do not cross hear. The packet is S29PacketSoundEffect built from sound name, position, volume, and pitch. No exclusion applies, so even the causing player hears it. This contrasts with playSoundToNearExcept and the fixed 64.0D aux path.",
      "code": "    /**\n     * Plays the specified sound. Arg: soundName, x, y, z, volume, pitch\n     */\n    public void playSound(String soundName, double x, double y, double z, float volume, float pitch)\n    {\n        this.mcServer.getConfigurationManager().sendToAllNear(x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.theWorldServer.provider.getDimensionId(), new S29PacketSoundEffect(soundName, x, y, z, volume, pitch));\n    }",
      "code_walkthrough": "The comment documents soundName position volume pitch args. The method signature binds those plus coordinates. The single body line calls sendToAllNear with volume ternary for radius. The dimension ID arg gates by world. The S29PacketSoundEffect constructor packs name, coords, volume, pitch. This is inclusive broadcast with scaled 16.0D base radius."
     },
     {
      "name": "playSoundToNearExcept",
      "detail_long": "This variant broadcasts the same named sound but excludes one originator player. It follows the identical volume-scaled radius rule as playSound. When volume is above 1.0F the radius becomes 16.0F times volume, otherwise fixed 16.0D. Recipients are resolved with sendToAllNearExcept passing the except EntityPlayer reference. Dimension gating again uses theWorldServer dimension ID to prevent cross-dimension hearing. The packet is S29PacketSoundEffect with identical sound name, x y z, volume, and pitch fields. This is used for player-caused sounds where the actor plays the sound locally or should not double hear. All other nearby players in range still receive it. The only difference from playSound is the exclusion filter.",
      "code": "    /**\n     * Plays sound to all near players except the player reference given\n     */\n    public void playSoundToNearExcept(EntityPlayer except, String soundName, double x, double y, double z, float volume, float pitch)\n    {\n        this.mcServer.getConfigurationManager().sendToAllNearExcept(except, x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.theWorldServer.provider.getDimensionId(), new S29PacketSoundEffect(soundName, x, y, z, volume, pitch));\n    }",
      "code_walkthrough": "The comment states the except-player behavior. The signature adds the except EntityPlayer first arg. The body mirrors playSound but calls sendToAllNearExcept. The ternary preserves 16.0D versus 16.0F times volume scaling. The S29PacketSoundEffect args are unchanged. This shows exclusion plus dimension-gated radius filtering."
     },
     {
      "name": "playAuxSFX",
      "detail_long": "This hook broadcasts a block auxiliary effect such as dispenser click or record break near a position. It excludes the triggering EntityPlayer passed in, so that player does not get a duplicate local effect. Recipients are resolved via sendToAllNearExcept with the block position coordinates. The radius is fixed at 64.0D regardless of volume, wider than the 16.0D base sound radius. Dimension gating uses theWorldServer dimension ID. The packet is S28PacketEffect constructed with sfxType, BlockPos, data, and false for non-global flag. The data field carries block ID or extra info depending on sfxType. This contrasts with broadcastSound which is global with true flag. Only players within 64 blocks in the same dimension receive it.",
      "code": "    public void playRecord(String recordName, BlockPos blockPosIn)\n    {\n    }\n\n    public void playAuxSFX(EntityPlayer player, int sfxType, BlockPos blockPosIn, int data)\n    {\n        this.mcServer.getConfigurationManager().sendToAllNearExcept(player, (double)blockPosIn.getX(), (double)blockPosIn.getY(), (double)blockPosIn.getZ(), 64.0D, this.theWorldServer.provider.getDimensionId(), new S28PacketEffect(sfxType, blockPosIn, data, false));\n    }",
      "code_walkthrough": "The empty playRecord stub shows no networking for records here. The playAuxSFX signature binds actor, type, pos, and data. The body calls sendToAllNearExcept with 64.0D fixed radius and dimension gate. The S28PacketEffect is built with type, BlockPos, data, and false. The false flag marks it as ranged not global. This is exclusion plus fixed-radius fan-out."
     },
     {
      "name": "broadcastSound",
      "detail_long": "This method sends an auxiliary effect to every connected player with no range limit. It does not use sendToAllNear or any 16.0D or 64.0D or 512.0D radius check. It calls sendPacketToAllPlayers directly so all dimensions hear it unless client filters. The packet is S28PacketEffect built from soundID, BlockPos, data, and true for global flag. The true flag distinguishes it from playAuxSFX ranged effects. Typical uses are wither spawn, ender dragon death, or portal events that need world-wide awareness. Because there is no dimension gating, overworld players can receive nether-originated global events. No exclusion applies, so the trigger player also receives it. This is the loudest scope in WorldManager.",
      "code": "    public void broadcastSound(int soundID, BlockPos pos, int data)\n    {\n        this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S28PacketEffect(soundID, pos, data, true));\n    }\n\n    public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress)\n    {\n        for (EntityPlayerMP entityplayermp : this.mcServer.getConfigurationManager().getPlayerList())\n        {\n        }",
      "code_walkthrough": "The signature takes sound ID, position, and data. The single body line calls sendPacketToAllPlayers with no radius. The S28PacketEffect constructor uses true to mark global broadcast. The following lines reveal the start of sendBlockBreakProgress loop. This contrast shows global versus ranged S28 usage. No dimension or distance filtering occurs here."
     },
     {
      "name": "sendBlockBreakProgress",
      "detail_long": "This method streams block cracking animation stages to nearby viewers. It loops over every EntityPlayerMP in the configuration manager player list. For each candidate it first checks worldObj identity equals theWorldServer to enforce dimension separation. It then skips the breaker entity ID itself so the miner does not receive their own crack echo. It computes dx dy dz from block pos to player posX posY posZ. It checks squared distance less than 1024.0D which equals 32 blocks. Only qualifiers get a direct S25PacketBlockBreakAnim via playerNetServerHandler.sendPacket. The packet carries breakerId, BlockPos, and progress 0 to 9 or negative to clear. Each progress change sends a fresh packet with no batching. This tight 32 block scope keeps digging visuals local.",
      "code": "    public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress)\n    {\n        for (EntityPlayerMP entityplayermp : this.mcServer.getConfigurationManager().getPlayerList())\n        {\n            if (entityplayermp != null && entityplayermp.worldObj == this.theWorldServer && entityplayermp.getEntityId() != breakerId)\n            {\n                double d0 = (double)pos.getX() - entityplayermp.posX;\n                double d1 = (double)pos.getY() - entityplayermp.posY;\n                double d2 = (double)pos.getZ() - entityplayermp.posZ;\n\n                if (d0 * d0 + d1 * d1 + d2 * d2 < 1024.0D)\n                {\n                    entityplayermp.playerNetServerHandler.sendPacket(new S25PacketBlockBreakAnim(breakerId, pos, progress));\n                }\n            }\n        }\n    }",
      "code_walkthrough": "The signature binds breaker ID, position, and stage. The for loop iterates the global player list. The if filters null, same worldObj, and non-breaker ID. The dx dy dz lines compute offset for squared distance. The less than 1024.0D check gates to 32 blocks. The sendPacket line builds S25PacketBlockBreakAnim with ID, pos, and progress. This is manual per-player distance filtering."
     },
     {
      "name": "markBlockForUpdate",
      "detail_long": "This is the server hook that queues a block change for chunk-scoped delivery. On the client the sibling does render updates, but on the server it only flags the chunk. It delegates to theWorldServer.getPlayerManager with markBlockForUpdate and BlockPos. No packet is constructed or sent immediately here. PlayerManager maps the position to chunk XZ via right shift 4 and finds the PlayerInstance. That instance records local coordinates and defers the packet choice to onUpdate next tick. A single flagged block later becomes S23, two to sixty three become S22, and sixty four trigger S21 full chunk. Only players watching that chunk receive the eventual flush. This indirection enables per-tick batching instead of per-setBlock spam.",
      "code": "     * On the client, re-renders all blocks in this range, inclusive. On the server, does nothing. Args: min x, min y,\n     * min z, max x, max y, max z\n     */\n    public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2)\n    {\n    }\n\n    public void markBlockForUpdate(BlockPos pos)\n    {\n        this.theWorldServer.getPlayerManager().markBlockForUpdate(pos);\n    }",
      "code_walkthrough": "The comment describes the client render range behavior. The empty markBlockRangeForRenderUpdate shows no server networking. The markBlockForUpdate signature takes only BlockPos. The body delegates to PlayerManager markBlockForUpdate. No radius or S23 S22 S21 construction appears here. This proves queuing is deferred to PlayerInstance onUpdate batching."
     },
     {
      "name": "onEntityAdded",
      "detail_long": "This IWorldAccess callback registers a newly loaded or spawned entity for visibility tracking. It is invoked on all world accesses when an entity enters the world. On the server it calls theWorldServer.getEntityTracker with trackEntity and the entity. The tracker creates an EntityTrackerEntry that later emits the correct spawn packet per entity type. No packet is sent synchronously inside this method, so no radius like 512.0D applies yet. Viewer assignment uses tracking ranges configured per entity class. This is the entry point that eventually leads to spawn packet fan-out. Without this call clients would never learn about the entity. It complements onEntityRemoved which tears down tracking.",
      "code": "    /**\n     * Called on all IWorldAccesses when an entity is created or loaded. On client worlds, starts downloading any\n     * necessary textures. On server worlds, adds the entity to the entity tracker.\n     */\n    public void onEntityAdded(Entity entityIn)\n    {\n        this.theWorldServer.getEntityTracker().trackEntity(entityIn);\n    }",
      "code_walkthrough": "The comment contrasts client texture versus server tracker behavior. The method signature takes the new Entity. The single body line calls EntityTracker trackEntity. No packet constructor or radius appears inline. Tracking ranges are applied inside the tracker later. This shows deferred spawn fan-out via tracker entries."
     },
     {
      "name": "onEntityRemoved",
      "detail_long": "This callback tears down server visibility when an entity unloads or dies. It first calls theWorldServer.getEntityTracker with untrackEntity for the entity. That causes the tracker to send destroy packets and remove the entry from all viewers. It then calls theWorldServer.getScoreboard with func_181140_a to clear any scoreboard state tied to the entity. No distance radius governs removal because all current viewers must forget the entity. No explicit packet constructor appears here since destroy packets originate inside the tracker. This ensures clients do not retain ghost entities. It is the symmetric counterpart to onEntityAdded registration.",
      "code": "     * Called on all IWorldAccesses when an entity is unloaded or destroyed. On client worlds, releases any downloaded\n     * textures. On server worlds, removes the entity from the entity tracker.\n     */\n    public void onEntityRemoved(Entity entityIn)\n    {\n        this.theWorldServer.getEntityTracker().untrackEntity(entityIn);\n        this.theWorldServer.getScoreboard().func_181140_a(entityIn);\n    }",
      "code_walkthrough": "The comment describes unload versus destroy handling. The signature takes the removed Entity. The first body line calls untrackEntity to trigger destroy fan-out. The second line clears scoreboard objectives for that entity. No 16.0D or 64.0D check is present. Removal is broadcast to all prior viewers. This shows cleanup without direct packet code."
     }
    ]
   }
  },
  {
   "slug": "PlayerManager",
   "title": "PlayerManager",
   "rel": "net/minecraft/server/management/PlayerManager.java",
   "desc": "Chunk watch manager: streams S21 chunk data, S22 multi-block deltas and S26 bulk loads to watching players.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/PlayerManager/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/server/management/PlayerManager.java",
   "packets": [
    "S21PacketChunkData",
    "S22PacketMultiBlockChange",
    "S23PacketBlockChange"
   ],
   "peers": [
    "EntityPlayerMP",
    "WorldServer",
    "MathHelper",
    "BlockPos",
    "WorldManager",
    "ServerConfigurationManager"
   ],
   "analysis": {
    "overview": "Chunk-subscription manager mapping players to PlayerInstance watchers. Fans out block deltas only to watchers of that chunk. Uses playerViewRadius 3-32 for subscription square. Batches changes per tick into single, multi, or full-chunk packets.",
    "methods": [
     {
      "detail": "Converts BlockPos to chunk XZ via >>4. Looks up PlayerInstance without creation. Calls flagChunkForUpdate with local xyz. Defers packet choice to onUpdate.",
      "name": "markBlockForUpdate",
      "packets": [
       "S23",
       "S22",
       "S21"
      ],
      "purpose": "Flag single block coordinate for next tick flush."
     },
     {
      "detail": "If numBlocksToUpdate==1 sends S23PacketBlockChange plus tile desc if hasTileEntity. If 2-63 sends S22PacketMultiBlockChange plus tiles. If 64 sends S21PacketChunkData with flagsYAreasToUpdate.",
      "name": "PlayerInstance.onUpdate",
      "packets": [
       "S23",
       "S22",
       "S21"
      ],
      "purpose": "Flush accumulated block changes to chunk watchers."
     },
     {
      "detail": "Iterates playersWatchingChunk. Skips players whose loadedChunks contains chunkCoords. Sends same Packet instance directly via playerNetServerHandler. No distance check.",
      "name": "PlayerInstance.sendToAllPlayersWatchingChunk",
      "packets": [
       "S23",
       "S22",
       "S21"
      ],
      "purpose": "Chunk-scoped fan-out excluding fully loaded senders."
     },
     {
      "detail": "Computes chunk XZ from posX/posZ. Loops viewRadius square calling getPlayerInstance true then addPlayer. Triggers chunk load and later S21 data. Sets managedPosX/Z.",
      "name": "addPlayer",
      "packets": [
       "S21"
      ],
      "purpose": "Subscribe player to all chunk instances in view square."
     },
     {
      "detail": "Loops managedPos square removing from each instance. When instance empties sends S21PacketChunkData unload true,0, drops chunk, removes instance. Removes from players list.",
      "name": "removePlayer",
      "packets": [
       "S21"
      ],
      "purpose": "Unsubscribe player and unload empty chunks."
     },
     {
      "detail": "If >8000 ticks since full pass, calls onUpdate plus processChunk for inhabited time. Else only queued playerInstancesToUpdate. Clears queue. Unloads all chunks if no players and no respawn.",
      "name": "updatePlayerInstances",
      "packets": [
       "S23",
       "S22",
       "S21"
      ],
      "purpose": "Tick dirty chunk instances each server tick."
     },
     {
      "detail": "Triggers only if moved squared >=64.0D (8 blocks). Diffs old managed chunk square vs new, adds/removes PlayerInstance watchers. Calls filterChunkLoadQueue and updates managedPos.",
      "name": "updateMountedMovingPlayer",
      "packets": [
       "S21"
      ],
      "purpose": "Update subscriptions after fast vehicle movement."
     },
     {
      "detail": "Rebuilds player.loadedChunks using xzDirectionsConst spiral out to viewRadius. Prioritizes center chunk then expanding rings. Controls order of S21 chunk data sends.",
      "name": "filterChunkLoadQueue",
      "packets": [
       "S21"
      ],
      "purpose": "Reorder pending chunk loads in spiral around player."
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S23",
      "trigger": "onUpdate single block change to watchers"
     },
     {
      "direction": "sent",
      "id": "S22",
      "trigger": "onUpdate 2-63 block changes to watchers"
     },
     {
      "direction": "sent",
      "id": "S21",
      "trigger": "onUpdate 64 changes or chunk load/unload"
     }
    ],
    "internal_fields": [
     {
      "name": "playerInstances",
      "role": "LongHashMap chunkKey to PlayerInstance watcher set"
     },
     {
      "name": "players",
      "role": "All players managed in this dimension/world"
     },
     {
      "name": "playerViewRadius",
      "role": "Clamped 3-32 subscription square radius in chunks"
     },
     {
      "name": "playerInstancesToUpdate",
      "role": "Dirty instances with pending block changes"
     },
     {
      "name": "theWorldServer",
      "role": "Owning dimension for chunk provider access"
     }
    ],
    "peers": [
     "WorldServer",
     "WorldManager",
     "ServerConfigurationManager",
     "ChunkProviderServer"
    ],
    "methods_detailed": [
     {
      "name": "markBlockForUpdate",
      "detail_long": "This method maps a world BlockPos to its chunk watcher and queues a delta. It derives chunk X and Z by arithmetic right shift 4 on block X and Z. It looks up the PlayerInstance with getPlayerInstance without creation, so unloaded chunks get no queue. If the instance exists it calls flagChunkForUpdate with local coordinates using bitwise and 15 for X and Z plus full Y. That call records the packed short and sets Y section flags for later S21 use. No S23 S22 or S21 packet is built here. The eventual choice depends on accumulated count: one becomes S23, two to sixty three become S22, sixty four becomes S21. This defers networking to PlayerInstance.onUpdate on the next tick. Chunk-scoped fan-out replaces any global radius broadcast.",
      "code": "    public void markBlockForUpdate(BlockPos pos)\n    {\n        int i = pos.getX() >> 4;\n        int j = pos.getZ() >> 4;\n        PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(i, j, false);\n\n        if (playermanager$playerinstance != null)\n        {\n            playermanager$playerinstance.flagChunkForUpdate(pos.getX() & 15, pos.getY(), pos.getZ() & 15);\n        }\n    }",
      "code_walkthrough": "The signature takes BlockPos to flag. The shift lines convert block to chunk coordinates. The getPlayerInstance call uses false to avoid creating watchers. The null check ensures only watched chunks queue. The flagChunkForUpdate line passes local x y z for packing. Packet selection is deferred to onUpdate batching."
     },
     {
      "name": "PlayerInstance.onUpdate",
      "detail_long": "This is the per-tick flush that converts accumulated block edits into minimal packets. If numBlocksToUpdate is zero it does nothing and returns without networking. If count equals one it decodes the single packed short into world x y z and sends S23PacketBlockChange to chunk watchers. It also sends the tile entity description packet if that block has a tile entity. If count equals sixty four it sends S21PacketChunkData with flagsYAreasToUpdate mask for full chunk resend plus tile entities per dirty section. Otherwise for two to sixty three it sends S22PacketMultiBlockChange with count, short array, and chunk reference plus per-block tile packets. After any branch it resets numBlocksToUpdate and flagsYAreasToUpdate to zero. This 1 versus 2 to 63 versus 64 batching rule minimizes bandwidth. Only players in playersWatchingChunk receive the chosen packet.",
      "code": "        public void onUpdate()\n        {\n            if (this.numBlocksToUpdate != 0)\n            {\n                if (this.numBlocksToUpdate == 1)\n                {\n                    int i = (this.locationOfBlockChange[0] >> 12 & 15) + this.chunkCoords.chunkXPos * 16;\n                    int j = this.locationOfBlockChange[0] & 255;\n                    int k = (this.locationOfBlockChange[0] >> 8 & 15) + this.chunkCoords.chunkZPos * 16;\n                    BlockPos blockpos = new BlockPos(i, j, k);\n                    this.sendToAllPlayersWatchingChunk(new S23PacketBlockChange(PlayerManager.this.theWorldServer, blockpos));\n\n                    if (PlayerManager.this.theWorldServer.getBlockState(blockpos).getBlock().hasTileEntity())\n                    {\n                        this.sendTileToAllPlayersWatchingChunk(PlayerManager.this.theWorldServer.getTileEntity(blockpos));\n                    }\n                }\n                else if (this.numBlocksToUpdate == 64)\n                {\n                    int i1 = this.chunkCoords.chunkXPos * 16;\n                    int k1 = this.chunkCoords.chunkZPos * 16;\n                    this.sendToAllPlayersWatchingChunk(new S21PacketChunkData(PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos), false, this.flagsYAreasToUpdate));\n\n                    for (int i2 = 0; i2 < 16; ++i2)\n                    {\n                        if ((this.flagsYAreasToUpdate & 1 << i2) != 0)\n                        {\n                            int k2 = i2 << 4;\n                            List<TileEntity> list = PlayerManager.this.theWorldServer.getTileEntitiesIn(i1, k2, k1, i1 + 16, k2 + 16, k1 + 16);\n                        }\n                    }\n                }",
      "code_walkthrough": "The method checks numBlocksToUpdate nonzero before branching. The equals one branch decodes packed shorts to world coords and builds S23PacketBlockChange. The tile check adds description packets for containers. The equals 64 branch builds S21PacketChunkData with Y mask for full resend. The loop over 16 sections gathers tile entities per dirty slice. The missing tail handles 2 to 63 via S22 multi change."
     },
     {
      "name": "PlayerInstance.sendToAllPlayersWatchingChunk",
      "detail_long": "This helper implements chunk-scoped fan-out for all block delta packets. It iterates playersWatchingChunk by index for the owning PlayerInstance. For each EntityPlayerMP it checks whether loadedChunks contains the chunkCoords. If the player already fully loaded the chunk via the load queue, the packet is skipped to avoid duplicate S21 or delta spam. Otherwise it sends the supplied Packet directly via playerNetServerHandler.sendPacket. No distance math with 16.0D or 1024.0D is performed because subscription implies proximity. The same Packet instance is reused across recipients, whether S23 single, S22 multi, or S21 chunk. This exclusion of fully loaded senders prevents echo during initial chunk burst. All networking for onUpdate flows through this single choke point.",
      "code": "        public void sendToAllPlayersWatchingChunk(Packet thePacket)\n        {\n            for (int i = 0; i < this.playersWatchingChunk.size(); ++i)\n            {\n                EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playersWatchingChunk.get(i);\n\n                if (!entityplayermp.loadedChunks.contains(this.chunkCoords))\n                {\n                    entityplayermp.playerNetServerHandler.sendPacket(thePacket);\n                }\n            }\n        }",
      "code_walkthrough": "The signature takes a generic Packet to share. The for loop walks playersWatchingChunk for this chunk. The loadedChunks contains check skips players still in initial burst. The sendPacket line delivers the same S23 S22 or S21 instance to qualifiers. No radius or dimension check appears. This is pure subscription-based fan-out."
     },
     {
      "name": "addPlayer",
      "detail_long": "This method subscribes a joining or teleporting player to all nearby chunk watchers. It computes central chunk XZ from posX and posZ with right shift 4. It stores managedPosX and managedPosZ as the subscription origin for later movement diffs. It then loops a square from center minus playerViewRadius to center plus radius in both axes. For each coordinate it calls getPlayerInstance with true to create the instance if absent, which also loads the chunk. It then calls addPlayer on that instance to add the player to playersWatchingChunk and loadedChunks queue. After the square it adds the player to the global players list. It finally calls filterChunkLoadQueue to order pending S21 chunk data sends in spiral priority. The radius is clamped 3 to 32 elsewhere.",
      "code": "    public void addPlayer(EntityPlayerMP player)\n    {\n        int i = (int)player.posX >> 4;\n        int j = (int)player.posZ >> 4;\n        player.managedPosX = player.posX;\n        player.managedPosZ = player.posZ;\n\n        for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k)\n        {\n            for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)\n            {\n                this.getPlayerInstance(k, l, true).addPlayer(player);\n            }\n        }\n\n        this.players.add(player);\n        this.filterChunkLoadQueue(player);\n    }",
      "code_walkthrough": "The signature takes the joining EntityPlayerMP. The shift lines derive central chunk XZ. The managedPos lines snapshot origin for movement checks. The nested loops cover the view radius square and force-create instances. The addPlayer call subscribes to each chunk watcher. The final lines register globally and reorder load queue for S21 sends."
     },
     {
      "name": "removePlayer",
      "detail_long": "This method unsubscribes a leaving player and unloads now-empty chunks. It derives the origin chunk from managedPosX and managedPosZ, not live pos, to cover the subscribed square. It loops the same view radius square around that managed origin. For each coordinate it fetches the PlayerInstance without creation. If non-null it calls removePlayer on the instance to drop the player from watchers and loadedChunks. When an instance becomes empty, that inner method sends S21PacketChunkData unload, drops the chunk, and removes the instance maps. After the loops it removes the player from the global players list. This ensures no ghost watchers remain after logout or dimension change. The S21 unload packet tells the client to discard chunk data.",
      "code": "    public void removePlayer(EntityPlayerMP player)\n    {\n        int i = (int)player.managedPosX >> 4;\n        int j = (int)player.managedPosZ >> 4;\n\n        for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k)\n        {\n            for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)\n            {\n                PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(k, l, false);\n\n                if (playermanager$playerinstance != null)\n                {\n                    playermanager$playerinstance.removePlayer(player);\n                }\n            }\n        }\n\n        this.players.remove(player);\n    }",
      "code_walkthrough": "The signature takes the departing EntityPlayerMP. The managedPos shift lines recover the subscribed center. The nested loops visit every watcher in the square without creating new ones. The null check plus removePlayer call handles unsubscribe and empty-chunk S21 unload. The final remove drops the global reference. This mirrors addPlayer subscription logic."
     },
     {
      "name": "updatePlayerInstances",
      "detail_long": "This per-tick driver flushes dirty chunk instances for block deltas. It reads total world time and compares to previousTotalWorldTime. If more than 8000 ticks elapsed it does a full pass over playerInstanceList calling onUpdate plus processChunk for inhabited time. Otherwise it only iterates playerInstancesToUpdate, which holds instances flagged by markBlockForUpdate. After either path it clears playerInstancesToUpdate to reset dirty state. If the players list is empty and the provider cannot respawn here, it unloads all chunks to save memory. This method is called from WorldServer.tick chunkMap section. It is the indirect source of S23 for one change, S22 for two to sixty three, and S21 for sixty four. No radius check occurs because watchers define recipients.",
      "code": "    public void updatePlayerInstances()\n    {\n        long i = this.theWorldServer.getTotalWorldTime();\n\n        if (i - this.previousTotalWorldTime > 8000L)\n        {\n            this.previousTotalWorldTime = i;\n\n            for (int j = 0; j < this.playerInstanceList.size(); ++j)\n            {\n                PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance)this.playerInstanceList.get(j);\n                playermanager$playerinstance.onUpdate();\n                playermanager$playerinstance.processChunk();\n            }\n        }\n        else\n        {\n            for (int k = 0; k < this.playerInstancesToUpdate.size(); ++k)\n            {\n                PlayerManager.PlayerInstance playermanager$playerinstance1 = (PlayerManager.PlayerInstance)this.playerInstancesToUpdate.get(k);\n                playermanager$playerinstance1.onUpdate();\n            }\n        }\n\n        this.playerInstancesToUpdate.clear();\n\n        if (this.players.isEmpty())\n        {\n            WorldProvider worldprovider = this.theWorldServer.provider;\n        }",
      "code_walkthrough": "The signature takes no args and reads world time. The greater than 8000L branch does full onUpdate plus inhabited time. The else branch flushes only dirty instances queued for S23 S22 S21. The clear call resets the dirty list each tick. The trailing players empty check leads to unload when no viewers remain. This shows tick-driven batched flushing."
     },
     {
      "name": "updateMountedMovingPlayer",
      "detail_long": "This method updates chunk subscriptions after fast vehicle movement like boats or minecarts. It computes current chunk XZ from live posX posZ and the delta from managedPosX managedPosZ. It calculates squared movement d2 and only proceeds if at least 64.0D, which equals 8 blocks. It then derives old managed chunk and view radius plus delta in chunks j1 k1. If no chunk changed it returns without networking. Otherwise it loops the new view square, adding the player to instances not overlapping the old square. It also loops to remove from old instances not overlapping the new square. It finally calls filterChunkLoadQueue and snaps managedPos to live pos. This diff avoids resubscribing the entire square on small moves. New chunks trigger S21 loads while stale ones trigger S21 unloads.",
      "code": "    public void updateMountedMovingPlayer(EntityPlayerMP player)\n    {\n        int i = (int)player.posX >> 4;\n        int j = (int)player.posZ >> 4;\n        double d0 = player.managedPosX - player.posX;\n        double d1 = player.managedPosZ - player.posZ;\n        double d2 = d0 * d0 + d1 * d1;\n\n        if (d2 >= 64.0D)\n        {\n            int k = (int)player.managedPosX >> 4;\n            int l = (int)player.managedPosZ >> 4;\n            int i1 = this.playerViewRadius;\n            int j1 = i - k;\n            int k1 = j - l;\n\n            if (j1 != 0 || k1 != 0)\n            {\n                for (int l1 = i - i1; l1 <= i + i1; ++l1)\n                {\n                    for (int i2 = j - i1; i2 <= j + i1; ++i2)\n                    {\n                        if (!this.overlaps(l1, i2, k, l, i1))\n                        {\n                            this.getPlayerInstance(l1, i2, true).addPlayer(player);\n                        }\n\n                        if (!this.overlaps(l1 - j1, i2 - k1, i, j, i1))\n                        {\n                            PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(l1 - j1, i2 - k1, false);\n\n                            if (playermanager$playerinstance != null)\n                            {\n                                playermanager$playerinstance.removePlayer(player);\n                            }\n                        }\n                    }\n                }\n            }\n        }",
      "code_walkthrough": "The signature takes the mounted EntityPlayerMP. The chunk and delta lines compute movement squared. The greater than equals 64.0D gate equals 8 blocks before work. The j1 k1 check ensures a chunk boundary crossed. The nested loops add new watchers and remove stale ones via overlaps tests. Later lines reorder load queue and snap managedPos. This is differential S21 subscription update."
     },
     {
      "name": "filterChunkLoadQueue",
      "detail_long": "This method reorders a player pending chunk load queue into spiral priority around the player. It copies loadedChunks to a temp list then clears the live queue. It computes view radius, central chunk XZ, and fetches the center PlayerInstance chunkCoords. If the old list contained the center it is added first for immediate S21 send. It then walks outward rings using xzDirectionsConst east south west north vectors with expanding step counts up to twice radius. Each visited coordinate is resolved to its PlayerInstance chunkCoords and re-added if previously queued. A final straight tail fills remaining edge chunks. This ordering makes closest chunks load first on login or teleport. The S21 chunk data sends later follow this queue order. No packets are built here, only queue order.",
      "code": "    public void filterChunkLoadQueue(EntityPlayerMP player)\n    {\n        List<ChunkCoordIntPair> list = Lists.newArrayList(player.loadedChunks);\n        int i = 0;\n        int j = this.playerViewRadius;\n        int k = (int)player.posX >> 4;\n        int l = (int)player.posZ >> 4;\n        int i1 = 0;\n        int j1 = 0;\n        ChunkCoordIntPair chunkcoordintpair = this.getPlayerInstance(k, l, true).chunkCoords;\n        player.loadedChunks.clear();\n\n        if (list.contains(chunkcoordintpair))\n        {\n            player.loadedChunks.add(chunkcoordintpair);\n        }\n\n        for (int k1 = 1; k1 <= j * 2; ++k1)\n        {\n            for (int l1 = 0; l1 < 2; ++l1)\n            {\n                int[] aint = this.xzDirectionsConst[i++ % 4];\n\n                for (int i2 = 0; i2 < k1; ++i2)\n                {\n                    i1 += aint[0];\n                    j1 += aint[1];\n                    chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords;\n\n                    if (list.contains(chunkcoordintpair))\n                    {\n                        player.loadedChunks.add(chunkcoordintpair);\n                    }\n                }\n            }\n        }",
      "code_walkthrough": "The signature takes the player whose queue is rebuilt. The copy plus clear lines snapshot and reset pending chunks. The center fetch plus contains check prioritizes the standing chunk. The nested k1 l1 loops walk the xzDirectionsConst spiral outward. Each step resolves chunkCoords and re-adds if previously pending. This controls S21 send order without sending directly."
     }
    ]
   }
  },
  {
   "slug": "EntityLivingBase",
   "title": "EntityLivingBase",
   "rel": "net/minecraft/entity/EntityLivingBase.java",
   "desc": "Living-entity base: swingItem, potion-effect add/remove and item pickup emit S0B, S1D/S1E and S0D through the tracker.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/EntityLivingBase/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/EntityLivingBase.java",
   "packets": [
    "S04PacketEntityEquipment",
    "S0BPacketAnimation",
    "S0DPacketCollectItem"
   ],
   "peers": [
    "EntityPlayerMP",
    "WorldServer",
    "MathHelper",
    "BlockPos",
    "AxisAlignedBB",
    "Entity",
    "EntityPlayer",
    "World"
   ],
   "analysis": {
    "overview": "Abstract base for all living entities in 1.8.9, owning health, attributes, combat, potions and equipment state. Server-side logic broadcasts visual effects through WorldServer EntityTracker while persistent state syncs via DataWatcher slots. Client mirrors hurt, death, swing, pickup and potion color through status, animation and metadata packets.",
    "methods": [
     {
      "detail": "Resets swingProgressInt and sets isSwingInProgress, then calls EntityTracker.sendToAllTrackingEntity with S0BPacketAnimation type 0 on WorldServer.",
      "name": "swingItem",
      "packets": [
       "S0B"
      ],
      "purpose": "Start arm-swing animation and broadcast to trackers"
     },
     {
      "detail": "Server-only guard on worldObj.isRemote, then sends S0DPacketCollectItem with picked-up and collector entity IDs to all tracking clients.",
      "name": "onItemPickup",
      "packets": [
       "S0D"
      ],
      "purpose": "Broadcast pickup animation when collecting item, arrow or XP orb"
     },
     {
      "detail": "Compares previousEquipment to getEquipmentInSlot each tick on server; on mismatch sends S04PacketEntityEquipment and reapplies attribute modifiers.",
      "name": "onUpdate",
      "packets": [
       "S04"
      ],
      "purpose": "Per-tick equipment diff sync and arrow-count decay"
     },
     {
      "detail": "Server-side damage pipeline with armor and potion reduction; calls worldObj.setEntityState byte 2 which tracker forwards as S19PacketEntityStatus.",
      "name": "attackEntityFrom",
      "packets": [
       "S19"
      ],
      "purpose": "Apply damage, knockback and hurt broadcast"
     },
     {
      "detail": "Awards score, drops loot on server, then setEntityState byte 3 so tracking clients play death sound and animation.",
      "name": "onDeath",
      "packets": [
       "S19"
      ],
      "purpose": "Handle death drops and death animation broadcast"
     },
     {
      "detail": "Byte 2 replays hurt animation and sound; byte 3 sets health zero and calls onDeath. Other IDs delegate to Entity super handler.",
      "name": "handleStatusUpdate",
      "packets": [
       "S19"
      ],
      "purpose": "Client-side handler for hurt and death status bytes"
     },
     {
      "detail": "Validates isPotionApplicable, combines or inserts into activePotionsMap, then marks potionsNeedUpdate so DataWatcher slots 7 and 8 sync via tracker metadata.",
      "name": "addPotionEffect",
      "packets": [
       "S1C"
      ],
      "purpose": "Add or combine active potion effect"
     },
     {
      "detail": "Removes entry from activePotionsMap and calls onFinishedPotionEffect, which strips attribute modifiers and flags DataWatcher color update.",
      "name": "removePotionEffect",
      "packets": [
       "S1C"
      ],
      "purpose": "Remove potion effect and refresh metadata"
     },
     {
      "detail": "Computes liquid color with PotionHelper and updates DataWatcher objects 7 and 8 plus invisibility flag; empty map resets metadata.",
      "name": "updatePotionMetadata",
      "packets": [
       "S1C"
      ],
      "purpose": "Recompute potion color and invisibility flags"
     },
     {
      "detail": "Sets potionsNeedUpdate true; consumed in updatePotionEffects on server to push DataWatcher changes to tracking clients.",
      "name": "markPotionsDirty",
      "packets": [
       "S1C"
      ],
      "purpose": "Flag potion metadata for next tick sync"
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S0B",
      "trigger": "swingItem on WorldServer via EntityTracker"
     },
     {
      "direction": "sent",
      "id": "S0D",
      "trigger": "onItemPickup for EntityItem, EntityArrow, EntityXPOrb"
     },
     {
      "direction": "sent",
      "id": "S04",
      "trigger": "onUpdate equipment change detection"
     },
     {
      "direction": "sent",
      "id": "S19",
      "trigger": "attackEntityFrom byte 2 and onDeath byte 3 via setEntityState"
     },
     {
      "direction": "handled",
      "id": "S19",
      "trigger": "handleStatusUpdate bytes 2 hurt and 3 death"
     },
     {
      "direction": "sent",
      "id": "S1C",
      "trigger": "DataWatcher slots 6 health, 7 potion color, 8 ambient, 9 arrows via tracker"
     }
    ],
    "internal_fields": [
     {
      "name": "activePotionsMap",
      "role": "Maps potion ID to PotionEffect for ticking and NBT"
     },
     {
      "name": "potionsNeedUpdate",
      "role": "Dirty flag driving DataWatcher potion metadata refresh"
     },
     {
      "name": "previousEquipment",
      "role": "5-slot cache used to detect S04 equipment changes"
     },
     {
      "name": "attributeMap",
      "role": "ServersideAttributeMap backing health, speed and modifiers"
     },
     {
      "name": "_combatTracker",
      "role": "Tracks recent damage sources for death messages"
     },
     {
      "name": "hurtTime/deathTime",
      "role": "Client-visible hurt and death animation timers"
     }
    ],
    "peers": [
     "Entity",
     "WorldServer",
     "EntityTracker",
     "EntityPlayerMP",
     "PotionEffect",
     "CombatTracker"
    ],
    "methods_detailed": [
     {
      "name": "swingItem",
      "detail_long": "swingItem starts a client-visible arm swing on the server and broadcasts it to all tracking clients. It first checks isSwingInProgress and swingProgressInt against half of getArmSwingAnimationEnd to avoid restarting a swing mid-stroke unless expired or invalid. On start it sets swingProgressInt to -1 and isSwingInProgress to true so updateArmSwingProgress will advance it next tick. It then guards with worldObj instanceof WorldServer to ensure this only runs on the logical server. It obtains the EntityTracker from WorldServer and calls sendToAllTrackingEntity with new S0BPacketAnimation(this, 0) where type 0 means swing arm. Receivers including the attacker itself if tracked and nearby players get S0B and play the swing animation without changing inventory or health. This keeps swings visual-only while combat damage is handled separately by attack logic. No DataWatcher change is made here because animation is transient.",
      "code": "    public void swingItem()\n    {\n        if (!this.isSwingInProgress || this.swingProgressInt >= this.getArmSwingAnimationEnd() / 2 || this.swingProgressInt < 0)\n        {\n            this.swingProgressInt = -1;\n            this.isSwingInProgress = true;\n\n            if (this.worldObj instanceof WorldServer)\n            {\n                ((WorldServer)this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, new S0BPacketAnimation(this, 0));\n            }\n        }\n    }",
      "code_walkthrough": "The guard condition prevents overlapping swings by allowing restart only when idle, past half duration, or with invalid counter. Resetting swingProgressInt to -1 and setting isSwingInProgress starts the animation timer consumed by updateArmSwingProgress. The instanceof WorldServer check confines packet sending to the logical server and avoids client double-send. sendToAllTrackingEntity forwards the new S0BPacketAnimation with entity ID and type 0 to every tracking client. Clients then render the arm swing while server logic continues independently."
     },
     {
      "name": "onItemPickup",
      "detail_long": "onItemPickup broadcasts the pickup beam animation when a living entity collects an item, arrow, or XP orb. It first rejects dead pickup entities with isDead and rejects client worlds with worldObj.isRemote so only the server emits packets. It fetches EntityTracker from the WorldServer to find all clients tracking the picked-up entity. For EntityItem it sends S0DPacketCollectItem with args picked-up entity ID and collector entity ID so clients can fly the item to the collector. It repeats the same S0D send for EntityArrow and for EntityXPOrb using identical constructor arguments. Receivers hide or remove the ground entity and render it moving into the collector inventory or body. No inventory mutation happens here; actual stack transfer is done by caller logic before or after this visual. This separation keeps visuals in sync even if stack handling differs by subclass.",
      "code": "    public void onItemPickup(Entity p_71001_1_, int p_71001_2_)\n    {\n        if (!p_71001_1_.isDead && !this.worldObj.isRemote)\n        {\n            EntityTracker entitytracker = ((WorldServer)this.worldObj).getEntityTracker();\n\n            if (p_71001_1_ instanceof EntityItem)\n            {\n                entitytracker.sendToAllTrackingEntity(p_71001_1_, new S0DPacketCollectItem(p_71001_1_.getEntityId(), this.getEntityId()));\n            }\n\n            if (p_71001_1_ instanceof EntityArrow)\n            {\n                entitytracker.sendToAllTrackingEntity(p_71001_1_, new S0DPacketCollectItem(p_71001_1_.getEntityId(), this.getEntityId()));\n            }\n\n            if (p_71001_1_ instanceof EntityXPOrb)\n            {\n                entitytracker.sendToAllTrackingEntity(p_71001_1_, new S0DPacketCollectItem(p_71001_1_.getEntityId(), this.getEntityId()));\n            }\n        }\n    }",
      "code_walkthrough": "The method signature takes the picked-up entity and stack size though size is unused for the packet. The isDead plus isRemote guard ensures only live server-side pickups broadcast. Getting EntityTracker from WorldServer provides the audience of tracking clients. Each instanceof branch constructs S0DPacketCollectItem with collected ID first and collector ID second. Tracking clients receive S0D and animate the orb, arrow, or item flying to the collector."
     },
     {
      "name": "onUpdate",
      "detail_long": "onUpdate runs every tick to decay stuck arrows and sync changed equipment to tracking clients. It calls super.onUpdate first for base entity movement and then gates server-only work with !worldObj.isRemote. It reads arrow count from DataWatcher slot 9 via getArrowCountInEntity and if above zero initializes arrowHitTimer to 20 times 30 minus count. It decrements arrowHitTimer each tick and calls setArrowCountInEntity with count minus one when it expires, which updates DataWatcher slot 9 for S1C metadata sync. It then loops slots 0 to 4 comparing previousEquipment cache to getEquipmentInSlot current value with ItemStack.areItemStacksEqual. On mismatch it sends S04PacketEntityEquipment with args entity ID, slot index j, and new ItemStack so clients update rendered held item and armor. It also removes old attribute modifiers and applies new ones to attributeMap to keep damage, armor, and speed correct. It caches a copy of the new stack in previousEquipment to avoid resending every tick. Every 20 ticks it resets CombatTracker to age out old damage entries.",
      "code": "        if (!this.worldObj.isRemote)\n        {\n            int i = this.getArrowCountInEntity();\n\n            if (i > 0)\n            {\n                if (this.arrowHitTimer <= 0)\n                {\n                    this.arrowHitTimer = 20 * (30 - i);\n                }\n\n                --this.arrowHitTimer;\n\n                if (this.arrowHitTimer <= 0)\n                {\n                    this.setArrowCountInEntity(i - 1);\n                }\n            }\n\n            for (int j = 0; j < 5; ++j)\n            {\n                ItemStack itemstack = this.previousEquipment[j];\n                ItemStack itemstack1 = this.getEquipmentInSlot(j);\n\n                if (!ItemStack.areItemStacksEqual(itemstack1, itemstack))\n                {\n                    ((WorldServer)this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, new S04PacketEntityEquipment(this.getEntityId(), j, itemstack1));",
      "code_walkthrough": "The !isRemote branch confines arrow decay and equipment broadcast to the server. Arrow logic reads DataWatcher slot 9 and uses arrowHitTimer as a countdown scaled by remaining arrows before decrementing the visible count. The for loop over five slots diffs cached previousEquipment against live getEquipmentInSlot. On inequality it calls sendToAllTrackingEntity with S04PacketEntityEquipment carrying entity ID, slot, and new stack. Receivers update the rendered equipment slot while the server also swaps attribute modifiers locally."
     },
     {
      "name": "attackEntityFrom",
      "detail_long": "attackEntityFrom is the server damage pipeline that validates, reduces, applies damage, and broadcasts hurt state. Earlier guards reject invulnerable sources, client worlds, dead entities, and fire damage with fire resistance. Armor, absorption, and potion reductions are applied inside damageEntity before health in DataWatcher slot 6 is lowered. Revenge target, recentlyHit timer, and attackingPlayer fields are set from source.getEntity for loot and AI. If flag remains true meaning full hurt rather than throttled repeat hit, it calls worldObj.setEntityState with byte 2. WorldServer forwards that state as S19PacketEntityStatus with entity ID and op code 2 to all tracking clients. Receivers invoke handleStatusUpdate byte 2 to play hurt sound, set hurtTime to 10, and flash red. Knockback via knockBack and hurt or death sounds follow, with onDeath called if health falls to zero. Throttled hits skip the S19 broadcast and knockback by clearing flag.",
      "code": "                if (flag)\n                {\n                    this.worldObj.setEntityState(this, (byte)2);\n\n                    if (source != DamageSource.drown)\n                    {\n                        this.setBeenAttacked();\n                    }\n\n                    if (entity != null)\n                    {\n                        double d1 = entity.posX - this.posX;\n                        double d0;\n\n                        for (d0 = entity.posZ - this.posZ; d1 * d1 + d0 * d0 < 1.0E-4D; d0 = (Math.random() - Math.random()) * 0.01D)\n                        {\n                            d1 = (Math.random() - Math.random()) * 0.01D;\n                        }\n\n                        this.attackedAtYaw = (float)(MathHelper.atan2(d0, d1) * 180.0D / Math.PI - (double)this.rotationYaw);\n                        this.knockBack(entity, amount, d1, d0);\n                    }\n                    else\n                    {\n                        this.attackedAtYaw = (float)((int)(Math.random() * 2.0D) * 180);\n                    }\n                }",
      "code_walkthrough": "The if flag block runs only for full-strength hits that should be visible and knock back. setEntityState with byte 2 is the packet trigger that WorldServer turns into S19 to tracking clients. setBeenAttacked marks velocityChanged except for drown so motion syncs. The entity-null check computes knockback direction from attacker position with a small random fallback to avoid divide by zero. knockBack then applies motion while attackedAtYaw orients the hurt tilt on receivers."
     },
     {
      "name": "onDeath",
      "detail_long": "onDeath awards score, drops loot on the server, and broadcasts the death animation. It resolves the killer via getAttackingEntity and source.getEntity, then calls addToPlayerScore if scoreValue is non-negative. It notifies the killer with onKillEntity for achievements and AI. It sets dead to true and resets CombatTracker to close the combat log. Guarded by !worldObj.isRemote it computes looting level from the killer, checks canDropLoot and doMobLoot gamerule, then calls dropFewItems, dropEquipment, and rarely addRandomDrop. These spawn EntityItem and EntityXPOrb which have their own spawn packets. Finally it calls worldObj.setEntityState with byte 3 which WorldServer forwards as S19PacketEntityStatus op 3. Tracking clients receive S19 and play death sound, rotate the corpse, and start the death timer.",
      "code": "        this.dead = true;\n        this.getCombatTracker().reset();\n\n        if (!this.worldObj.isRemote)\n        {\n            int i = 0;\n\n            if (entity instanceof EntityPlayer)\n            {\n                i = EnchantmentHelper.getLootingModifier((EntityLivingBase)entity);\n            }\n\n            if (this.canDropLoot() && this.worldObj.getGameRules().getBoolean(\"doMobLoot\"))\n            {\n                this.dropFewItems(this.recentlyHit > 0, i);\n                this.dropEquipment(this.recentlyHit > 0, i);\n\n                if (this.recentlyHit > 0 && this.rand.nextFloat() < 0.025F + (float)i * 0.01F)\n                {\n                    this.addRandomDrop();\n                }\n            }\n        }\n\n        this.worldObj.setEntityState(this, (byte)3);",
      "code_walkthrough": "Setting dead and resetting CombatTracker marks the entity as finished on both sides. The !isRemote guard confines looting calculation and dropFewItems plus dropEquipment spawning to the server. Looting level comes from the killer player while doMobLoot and canDropLoot gate drops. The final setEntityState with byte 3 always runs so WorldServer can broadcast S19 death. Clients then run handleStatusUpdate byte 3 to set health zero and invoke onDeath locally."
     },
     {
      "name": "handleStatusUpdate",
      "detail_long": "handleStatusUpdate runs on the client to mirror hurt and death states received as S19PacketEntityStatus. For id 2 it sets limbSwingAmount to 1.5, copies maxHurtResistantTime into hurtResistantTime, and sets hurtTime and maxHurtTime to 10 for the red flash duration. It zeroes attackedAtYaw, plays getHurtSound with randomized pitch, and calls attackEntityFrom with generic zero damage to trigger hurt hooks without changing health. For id 3 it plays getDeathSound with randomized pitch, forces DataWatcher health to zero via setHealth, and calls onDeath with generic source to start client death animation. Both branches rely on the server having sent S19 op 2 from attackEntityFrom or op 3 from onDeath via setEntityState. Unknown IDs delegate to super.handleStatusUpdate for base entity handling like spawn particles. This keeps client visuals driven entirely by server broadcasts rather than local simulation.",
      "code": "    public void handleStatusUpdate(byte id)\n    {\n        if (id == 2)\n        {\n            this.limbSwingAmount = 1.5F;\n            this.hurtResistantTime = this.maxHurtResistantTime;\n            this.hurtTime = this.maxHurtTime = 10;\n            this.attackedAtYaw = 0.0F;\n            String s = this.getHurtSound();\n\n            if (s != null)\n            {\n                this.playSound(this.getHurtSound(), this.getSoundVolume(), (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F);\n            }\n\n            this.attackEntityFrom(DamageSource.generic, 0.0F);\n        }\n        else if (id == 3)\n        {\n            String s1 = this.getDeathSound();\n\n            if (s1 != null)\n            {\n                this.playSound(this.getDeathSound(), this.getSoundVolume(), (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F);\n            }\n\n            this.setHealth(0.0F);\n            this.onDeath(DamageSource.generic);",
      "code_walkthrough": "The id 2 branch reconstructs hurt visuals by setting swing, resistance, and hurt timers plus sound. Calling attackEntityFrom with zero generic damage fires client hooks while early isRemote return prevents health change. The id 3 branch plays death sound, zeroes DataWatcher health, and invokes onDeath for corpse animation. Both branches are entered only when S19PacketEntityStatus with matching op arrives. Other IDs fall through to Entity super handler."
     },
     {
      "name": "addPotionEffect",
      "detail_long": "addPotionEffect adds or combines a potion effect and schedules a metadata sync. It first calls isPotionApplicable which rejects regeneration and poison on undead creatures but allows all else. If activePotionsMap already contains the potion ID it calls combine on the existing PotionEffect to merge duration and amplifier, then calls onChangedPotionEffect with reapply true to refresh attribute modifiers. If new it inserts the effect into activePotionsMap and calls onNewPotionEffect to apply attribute modifiers to attributeMap. Both paths set potionsNeedUpdate to true so updatePotionEffects will recompute DataWatcher slots 7 potion color and 8 ambient flag. Those DataWatcher changes are sent by EntityTracker as S1C reflect S1CPacketEntityMetadata to tracking clients. Clients then render particles, tint, and invisibility without receiving a dedicated potion packet. Duration refresh packets at 600-tick intervals also flow through this dirty path.",
      "code": "    public void addPotionEffect(PotionEffect potioneffectIn)\n    {\n        if (this.isPotionApplicable(potioneffectIn))\n        {\n            if (this.activePotionsMap.containsKey(Integer.valueOf(potioneffectIn.getPotionID())))\n            {\n                ((PotionEffect)this.activePotionsMap.get(Integer.valueOf(potioneffectIn.getPotionID()))).combine(potioneffectIn);\n                this.onChangedPotionEffect((PotionEffect)this.activePotionsMap.get(Integer.valueOf(potioneffectIn.getPotionID())), true);\n            }\n            else\n            {\n                this.activePotionsMap.put(Integer.valueOf(potioneffectIn.getPotionID()), potioneffectIn);\n                this.onNewPotionEffect(potioneffectIn);\n            }\n        }\n    }",
      "code_walkthrough": "The isPotionApplicable guard filters invalid undead heals and poisons before mutation. The containsKey branch merges into the existing effect and calls onChangedPotionEffect to reapply speed, damage, or health modifiers. The else branch inserts the new mapping and calls onNewPotionEffect to apply modifiers once. Both set potionsNeedUpdate so the next tick pushes DataWatcher slots 7 and 8 via S1C metadata."
     },
     {
      "name": "removePotionEffect",
      "detail_long": "removePotionEffect removes a server-side potion and triggers attribute cleanup and resync. It removes the entry from activePotionsMap by integer potion ID and captures the old PotionEffect. If non-null it calls onFinishedPotionEffect which sets potionsNeedUpdate true and on the server removes attribute modifiers from attributeMap via Potion.potionTypes. The dirty flag causes updatePotionEffects to call updatePotionMetadata next tick, recomputing liquid color and ambient flag or clearing slots 7 and 8 if empty. EntityTracker then sends the changed DataWatcher entries as S1C S1CPacketEntityMetadata to all tracking clients. Receivers stop rendering that effect tint and particles and update invisibility. This differs from removePotionEffectClient which only edits the client map without attribute work. If the ID was absent no packet or modifier change occurs.",
      "code": "    public void removePotionEffect(int potionId)\n    {\n        PotionEffect potioneffect = (PotionEffect)this.activePotionsMap.remove(Integer.valueOf(potionId));\n\n        if (potioneffect != null)\n        {\n            this.onFinishedPotionEffect(potioneffect);\n        }\n    }",
      "code_walkthrough": "The map remove by boxed potion ID both unregisters the effect and returns it for cleanup. The null check avoids dirtying metadata when nothing was active. onFinishedPotionEffect sets potionsNeedUpdate and strips server attribute modifiers. The next server tick then emits S1C metadata with updated color, ambient, and invisibility flags."
     },
     {
      "name": "updatePotionMetadata",
      "detail_long": "updatePotionMetadata recomputes potion-driven DataWatcher state for S1C sync. If activePotionsMap is empty it calls resetPotionEffectMetadata which writes 0 to slot 7 color and 0 to slot 8 ambient, then calls setInvisible false to clear invisibility. If non-empty it calls PotionHelper.calcPotionLiquidColor over all active effects to blend the particle tint integer. It writes slot 8 with 1 if PotionHelper.getAreAmbient returns true else 0 to control ambient versus strong particles. It writes slot 7 with the blended color integer for client spell particles. It calls setInvisible based on isPotionActive for invisibility ID so armor and body render correctly. EntityTracker detects these DataWatcher changes and sends S1C S1CPacketEntityMetadata to tracking clients. Clients read slots 7, 8, and invisibility flag to render potion visuals.",
      "code": "    protected void updatePotionMetadata()\n    {\n        if (this.activePotionsMap.isEmpty())\n        {\n            this.resetPotionEffectMetadata();\n            this.setInvisible(false);\n        }\n        else\n        {\n            int i = PotionHelper.calcPotionLiquidColor(this.activePotionsMap.values());\n            this.dataWatcher.updateObject(8, Byte.valueOf((byte)(PotionHelper.getAreAmbient(this.activePotionsMap.values()) ? 1 : 0)));\n            this.dataWatcher.updateObject(7, Integer.valueOf(i));\n            this.setInvisible(this.isPotionActive(Potion.invisibility.id));\n        }\n    }",
      "code_walkthrough": "The isEmpty branch clears color and ambient slots and disables invisibility for the clean state. The else branch blends active effects into a single RGB integer and writes ambient flag to slot 8. Writing slot 7 publishes the tint while setInvisible mirrors the invisibility potion. Changed DataWatcher objects are then broadcast as S1C metadata to trackers."
     },
     {
      "name": "markPotionsDirty",
      "detail_long": "markPotionsDirty flags potion metadata for refresh on the next tick. It sets the private boolean potionsNeedUpdate to true without touching activePotionsMap or DataWatcher immediately. The flag is consumed in updatePotionEffects which on the server calls updatePotionMetadata to rewrite slots 7 and 8 and invisibility. Those DataWatcher deltas are then sent by EntityTracker as S1C S1CPacketEntityMetadata to tracking clients. It is called by onNewPotionEffect, onChangedPotionEffect, and onFinishedPotionEffect after attribute modifiers change. This batches multiple adds or removes in one tick into a single metadata packet. If called on the client it only affects local particle spawning logic. No packet is sent synchronously inside this method itself.",
      "code": "    /**\n     * Sends an END_COMBAT packet to the client\n     */\n    public void sendEndCombat()\n    {\n    }\n\n    protected void markPotionsDirty()\n    {\n        this.potionsNeedUpdate = true;\n    }",
      "code_walkthrough": "The empty sendEndCombat stub shows combat packets are unused in this version. markPotionsDirty simply sets potionsNeedUpdate to true to defer work. The next updatePotionEffects tick sees the flag and calls updatePotionMetadata on the server. Resulting DataWatcher slot 7 and 8 edits flow as S1C metadata to tracking clients."
     }
    ]
   }
  },
  {
   "slug": "OldServerPinger",
   "title": "OldServerPinger",
   "rel": "net/minecraft/client/network/OldServerPinger.java",
   "desc": "Server-list prober: C00Handshake(47, STATUS) + C00 query + C01 ping sequence feeding the multiplayer latency readout.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/OldServerPinger/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/client/network/OldServerPinger.java",
   "packets": [
    "C00Handshake",
    "C00PacketServerQuery",
    "C01PacketPing"
   ],
   "peers": [
    "Minecraft",
    "NetworkManager",
    "EnumConnectionState",
    "MathHelper"
   ],
   "analysis": {
    "overview": "Client-side multiplayer list pinger owned by server-selection GUI. Opens a temporary STATUS connection, parses MOTD, version, player count and favicon, then measures ping. Falls back to pre-1.7 MC|PingHost legacy ping when modern handshake fails.",
    "methods": [
     {
      "detail": "Creates NetworkManager, installs anonymous INetHandlerStatusClient, sends handshake state STATUS plus C00PacketServerQuery; reply chain sends C01PacketPing.",
      "name": "ping",
      "packets": [
       "C00Handshake",
       "C00PacketServerQuery",
       "C01PacketPing"
      ],
      "purpose": "Start modern STATUS ping against a ServerData entry"
     },
     {
      "detail": "Copies MOTD, protocol version, player sample, population string and favicon; records timestamp and sends C01PacketPing for latency.",
      "name": "handleServerInfo",
      "packets": [
       "S00PacketServerInfo"
      ],
      "purpose": "Parse S00 server info into ServerData display fields"
     },
     {
      "detail": "Subtracts stored send time from current time into server.pingToServer, then closes channel with Finished message.",
      "name": "handlePong",
      "packets": [
       "S01PacketPong"
      ],
      "purpose": "Compute latency and close ping channel"
     },
     {
      "detail": "If query never completed, marks MOTD as cant-connect and delegates to tryCompatibilityPing for old servers.",
      "name": "onDisconnect",
      "packets": [],
      "purpose": "Handle failed modern ping and trigger legacy fallback"
     },
     {
      "detail": "Writes MC|PingHost payload with host and port, parses NUL-split UTF-16BE 0xFF response into version, MOTD and player counts.",
      "name": "tryCompatibilityPing",
      "packets": [
       "0xFE",
       "0xFF"
      ],
      "purpose": "Legacy 1.6 Beta-style 0xFE ping over raw Netty"
     },
     {
      "detail": "Iterates pingDestinations, processes received packets while open, otherwise removes and checks disconnect reason.",
      "name": "pingPendingNetworks",
      "packets": [],
      "purpose": "Pump pending ping connections each client tick"
     },
     {
      "detail": "Closes every open NetworkManager in pingDestinations with Cancelled message and removes it from the list.",
      "name": "clearPendingNetworks",
      "packets": [],
      "purpose": "Cancel all outstanding server-list pings"
     }
    ],
    "packet_usage": [
     {
      "direction": "sent",
      "id": "C00Handshake",
      "trigger": "ping sends protocol 47 with STATUS next state"
     },
     {
      "direction": "sent",
      "id": "C00PacketServerQuery",
      "trigger": "ping server query after handshake"
     },
     {
      "direction": "sent",
      "id": "C01PacketPing",
      "trigger": "handleServerInfo timestamp echo for latency"
     },
     {
      "direction": "handled",
      "id": "S00PacketServerInfo",
      "trigger": "handleServerInfo updates MOTD and player list"
     },
     {
      "direction": "handled",
      "id": "S01PacketPong",
      "trigger": "handlePong computes pingToServer"
     },
     {
      "direction": "sent",
      "id": "0xFE/0xFF",
      "trigger": "tryCompatibilityPing legacy MC|PingHost exchange"
     }
    ],
    "internal_fields": [
     {
      "name": "pingDestinations",
      "role": "Synchronized list of active ping NetworkManagers"
     },
     {
      "name": "PING_RESPONSE_SPLITTER",
      "role": "NUL splitter with limit 6 for legacy ping parsing"
     },
     {
      "name": "logger",
      "role": "Logs ping failures and invalid favicon formats"
     },
     {
      "name": "field_175092_e",
      "role": "Ping send timestamp used for latency calc"
     },
     {
      "name": "field_147403_d",
      "role": "Marks query completion to gate fallback ping"
     }
    ],
    "peers": [
     "NetworkManager",
     "ServerData",
     "ServerAddress",
     "INetHandlerStatusClient",
     "ServerStatusResponse"
    ],
    "methods_detailed": [
     {
      "name": "ping",
      "detail_long": "ping starts a modern STATUS ping from the multiplayer list against a ServerData entry. It resolves ServerAddress from serverIP, creates a NetworkManager with createNetworkManagerAndConnect, and adds it to pingDestinations for ticking. It initializes serverMOTD to Pinging, pingToServer to -1, and playerList to null as pending state. It installs an anonymous INetHandlerStatusClient whose handleServerInfo parses S00, handlePong computes latency, and onDisconnect triggers legacy fallback. After installing the handler it sends C00Handshake with protocol 47, host, port, and STATUS next state to switch the channel from HANDSHAKE to STATUS. It then sends C00PacketServerQuery to request ServerStatusResponse. The server replies with S00PacketServerInfo followed by S01PacketPong echo after the client C01PacketPing. Failures are logged without crashing the list thread.",
      "code": "        try\n        {\n            networkmanager.sendPacket(new C00Handshake(47, serveraddress.getIP(), serveraddress.getPort(), EnumConnectionState.STATUS));\n            networkmanager.sendPacket(new C00PacketServerQuery());\n        }\n        catch (Throwable throwable)\n        {\n            logger.error((Object)throwable);\n        }\n    }",
      "code_walkthrough": "The try block sends the two-packet STATUS opening sequence on the fresh NetworkManager. C00Handshake carries protocol 47 plus host and port and requests STATUS state. C00PacketServerQuery then asks for MOTD, version, players, and favicon. Throwables are logged so a bad address does not break the server list. Replies arrive as S00 and S01 handled by the anonymous handler."
     },
     {
      "name": "handleServerInfo",
      "detail_long": "handleServerInfo handles incoming S00PacketServerInfo and prepares the latency probe. It first rejects duplicate S00 with a Received unrequested status close to avoid double parsing. On first reply it marks field_183009_e true and extracts ServerStatusResponse via getResponse. It copies MOTD formatted text into serverMOTD, protocol name and number into gameVersion and version, and online versus max counts into populationInfo with gray formatting. It builds playerList tooltip from GameProfile names plus an and N more suffix when sampled players are fewer than online count. It validates favicon prefix data:image/png;base64 before storing base64 icon data else logs invalid icon. It records field_175092_e with Minecraft.getSystemTime and sends C01PacketPing with that timestamp. The server will echo it in S01PacketPong so handlePong can compute pingToServer. It sets field_147403_d true to suppress legacy fallback.",
      "code": "                    if (serverstatusresponse.getFavicon() != null)\n                    {\n                        String s = serverstatusresponse.getFavicon();\n\n                        if (s.startsWith(\"data:image/png;base64,\"))\n                        {\n                            server.setBase64EncodedIconData(s.substring(\"data:image/png;base64,\".length()));\n                        }\n                        else\n                        {\n                            OldServerPinger.logger.error(\"Invalid server icon (unknown format)\");\n                        }\n                    }\n                    else\n                    {\n                        server.setBase64EncodedIconData((String)null);\n                    }\n\n                    this.field_175092_e = Minecraft.getSystemTime();\n                    networkmanager.sendPacket(new C01PacketPing(this.field_175092_e));\n                    this.field_147403_d = true;",
      "code_walkthrough": "The favicon branch validates the data URL prefix before caching icon bytes else logs an error. Clearing icon to null when absent removes stale images from the list. Recording system time in field_175092_e provides the latency baseline. Sending C01PacketPing with that value asks the server for an S01 echo. Setting field_147403_d marks the query complete to block compatibility ping."
     },
     {
      "name": "handlePong",
      "detail_long": "handlePong handles incoming S01PacketPong and finalizes latency measurement. It reads the stored send time field_175092_e set when C01PacketPing was sent from handleServerInfo. It reads current time via Minecraft.getSystemTime as the receive time. It subtracts send from receive into server.pingToServer in milliseconds for the list display. It then closes the channel with Finished message to terminate the STATUS session cleanly. The outer pingPendingNetworks loop will later remove the closed NetworkManager and call checkDisconnected. No further packets are sent on this connection after close. Duplicate pongs are unlikely because the server closes after one S01.",
      "code": "            public void handlePong(S01PacketPong packetIn)\n            {\n                long i = this.field_175092_e;\n                long j = Minecraft.getSystemTime();\n                server.pingToServer = j - i;\n                networkmanager.closeChannel(new ChatComponentText(\"Finished\"));\n            }\n            public void onDisconnect(IChatComponent reason)",
      "code_walkthrough": "The handler ignores packetIn time and uses the stored send timestamp for consistency. Getting system time at receipt captures round-trip delay including server processing. Assigning j minus i to pingToServer updates the list column. Closing with Finished ends the STATUS connection so resources are freed."
     },
     {
      "name": "onDisconnect",
      "detail_long": "onDisconnect runs when the STATUS channel closes and decides whether to try legacy ping. It checks field_147403_d which is set true only after a valid S00 plus C01PacketPing sequence completed. If true it does nothing because modern ping succeeded even if the close reason is Finished or Cancelled. If false it logs Can't ping plus server IP and reason text via OldServerPinger logger. It sets serverMOTD to dark red Can't connect to server and clears populationInfo. It then calls tryCompatibilityPing on the outer OldServerPinger to attempt a pre-1.7 0xFE MC|PingHost exchange over raw Netty. That fallback can populate version, MOTD, and counts for old servers. Modern servers that refused the handshake will show the error text if legacy also fails.",
      "code": "            public void onDisconnect(IChatComponent reason)\n            {\n                if (!this.field_147403_d)\n                {\n                    OldServerPinger.logger.error(\"Can\\'t ping \" + server.serverIP + \": \" + reason.getUnformattedText());\n                    server.serverMOTD = EnumChatFormatting.DARK_RED + \"Can\\'t connect to server.\";\n                    server.populationInfo = \"\";\n                    OldServerPinger.this.tryCompatibilityPing(server);\n                }\n            }",
      "code_walkthrough": "The !field_147403_d guard distinguishes failed queries from normal Finished closes. Logging includes serverIP and disconnect text for diagnostics. Setting MOTD and populationInfo provides immediate list feedback. Delegating to tryCompatibilityPing opens a raw 0xFE channel for 1.6-era servers."
     },
     {
      "name": "tryCompatibilityPing",
      "detail_long": "tryCompatibilityPing implements the legacy 1.6 Beta-style 0xFE server-list ping over raw Netty. It resolves ServerAddress and builds a Bootstrap on CLIENT_NIO_EVENTLOOP with NioSocketChannel and a ChannelInitializer. The initializer enables TCP_NODELAY and installs a SimpleChannelInboundHandler for ByteBuf. On channelActive it writes packet 0xFE, 1, 0xFA MC|PingHost with host string length, IP chars, and port integer, then flushes with CLOSE_ON_FAILURE. On channelRead0 it reads unsigned byte and expects 0xFF kick response, decodes UTF-16BE length-prefixed string, and splits on NUL with PING_RESPONSE_SPLITTER limit 6. If element zero equals section-1 it parses protocol, version, MOTD, online, and max with parseIntWithDefault into server fields. It then closes the context while exceptionCaught also closes on error. No modern C00 or S00 packets are used on this path.",
      "code": "                        public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception\n                        {\n                            super.channelActive(p_channelActive_1_);\n                            ByteBuf bytebuf = Unpooled.buffer();\n\n                            try\n                            {\n                                bytebuf.writeByte(254);\n                                bytebuf.writeByte(1);\n                                bytebuf.writeByte(250);\n                                char[] achar = \"MC|PingHost\".toCharArray();\n                                bytebuf.writeShort(achar.length);\n\n                                for (char c0 : achar)\n                                {\n                                    bytebuf.writeChar(c0);\n                                }\n\n                                bytebuf.writeShort(7 + 2 * serveraddress.getIP().length());\n                                bytebuf.writeByte(127);\n                                achar = serveraddress.getIP().toCharArray();\n                                bytebuf.writeShort(achar.length);\n\n                                for (char c1 : achar)\n                                {\n                                    bytebuf.writeChar(c1);\n                                }\n\n                                bytebuf.writeInt(serveraddress.getPort());\n                                p_channelActive_1_.channel().writeAndFlush(bytebuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);\n                            }",
      "code_walkthrough": "channelActive fires when the raw TCP connection opens before any STATUS handshake. Allocating an Unpooled buffer lets the code manually encode the 0xFE plus MC|PingHost payload. Writing 254, 1, 250 plus length-prefixed chars reproduces the Beta 1.8 ping format. Appending IP chars and port tells legacy servers which virtual host is queried. Flushing with CLOSE_ON_FAILURE sends the probe while cleaning up on write error."
     },
     {
      "name": "pingPendingNetworks",
      "detail_long": "pingPendingNetworks pumps all outstanding server-list pings each client tick. It synchronizes on pingDestinations because ping and network threads can add or iterate concurrently. It obtains an iterator so closed channels can be removed safely during traversal. For each NetworkManager it checks isChannelOpen and if open calls processReceivedPackets to dispatch S00 to handleServerInfo and S01 to handlePong. If closed it removes the entry from the list and calls checkDisconnected to fire onDisconnect with the close reason. That disconnect step is what triggers legacy fallback when modern query never completed. It runs on the client thread from GuiMultiplayer update logic. Without this pump no STATUS replies would be processed.",
      "code": "    public void pingPendingNetworks()\n    {\n        synchronized (this.pingDestinations)\n        {\n            Iterator<NetworkManager> iterator = this.pingDestinations.iterator();\n\n            while (iterator.hasNext())\n            {\n                NetworkManager networkmanager = (NetworkManager)iterator.next();\n\n                if (networkmanager.isChannelOpen())\n                {\n                    networkmanager.processReceivedPackets();\n                }\n                else\n                {\n                    iterator.remove();\n                    networkmanager.checkDisconnected();\n                }\n            }\n        }\n    }",
      "code_walkthrough": "Synchronizing on pingDestinations prevents concurrent modification from ping creation. The iterator loop visits each pending NetworkManager once per tick. Open channels have processReceivedPackets decode and dispatch STATUS packets. Closed channels are removed and passed to checkDisconnected to deliver the disconnect reason. That callback completes latency display or legacy fallback."
     },
     {
      "name": "clearPendingNetworks",
      "detail_long": "clearPendingNetworks cancels every outstanding server-list ping, typically when leaving multiplayer GUI. It synchronizes on pingDestinations for thread safety with concurrent ping adds. It iterates with an iterator to allow removal while traversing. For each NetworkManager it checks isChannelOpen and only acts on still-open connections. It removes the open entry from the list first to prevent pingPendingNetworks from processing it. It then calls closeChannel with Cancelled message to close TCP and fire onDisconnect. Already-closed entries are left for pingPendingNetworks cleanup rather than double-closed here. After return no modern STATUS or legacy 0xFE probes from this pinger remain active.",
      "code": "    public void clearPendingNetworks()\n    {\n        synchronized (this.pingDestinations)\n        {\n            Iterator<NetworkManager> iterator = this.pingDestinations.iterator();\n\n            while (iterator.hasNext())\n            {\n                NetworkManager networkmanager = (NetworkManager)iterator.next();\n\n                if (networkmanager.isChannelOpen())\n                {\n                    iterator.remove();\n                    networkmanager.closeChannel(new ChatComponentText(\"Cancelled\"));\n                }\n            }\n        }\n    }",
      "code_walkthrough": "The synchronized block guards the shared ping list during cancellation. The iterator with isChannelOpen filter targets only live connections. Removing before close avoids race with the tick pump. Closing with Cancelled terminates handshake, query, or ping waits and releases Netty resources."
     }
    ]
   }
  },
  {
   "slug": "NetHandlerStatusServer",
   "title": "NetHandlerStatusServer",
   "rel": "net/minecraft/server/network/NetHandlerStatusServer.java",
   "desc": "Server status responder: answers C00 query with S00 JSON and C01 ping with S01 echo, then closes the channel.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/NetHandlerStatusServer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/server/network/NetHandlerStatusServer.java",
   "packets": [
    "S00PacketServerInfo",
    "S01PacketPong"
   ],
   "peers": [
    "NetworkManager"
   ],
   "analysis": {
    "overview": "Server-side STATUS connection handler active between handshake and login. Answers a single server-list query with cached ServerStatusResponse and echoes one ping packet. Enforces one-query-per-connection then closes channel.",
    "methods": [
     {
      "detail": "Stores MinecraftServer reference for status response and NetworkManager used to send replies and close channel.",
      "name": "NetHandlerStatusServer",
      "packets": [],
      "purpose": "Bind handler to server and connection"
     },
     {
      "detail": "First C00PacketServerQuery sets handled and sends S00PacketServerInfo; duplicate queries close channel as already handled.",
      "name": "processServerQuery",
      "packets": [
       "C00PacketServerQuery",
       "S00PacketServerInfo"
      ],
      "purpose": "Reply to status query with server info"
     },
     {
      "detail": "Replies with S01PacketPong carrying client time, then closes channel with status-handled exit message.",
      "name": "processPing",
      "packets": [
       "C01PacketPing",
       "S01PacketPong"
      ],
      "purpose": "Echo ping time and terminate status session"
     },
     {
      "detail": "Intentionally empty because status connections carry no player state requiring cleanup.",
      "name": "onDisconnect",
      "packets": [],
      "purpose": "No-op disconnect hook for status phase"
     }
    ],
    "packet_usage": [
     {
      "direction": "handled",
      "id": "C00PacketServerQuery",
      "trigger": "processServerQuery single-shot query gate"
     },
     {
      "direction": "sent",
      "id": "S00PacketServerInfo",
      "trigger": "processServerQuery replies with getServerStatusResponse"
     },
     {
      "direction": "handled",
      "id": "C01PacketPing",
      "trigger": "processPing latency echo request"
     },
     {
      "direction": "sent",
      "id": "S01PacketPong",
      "trigger": "processPing echoes client time then disconnects"
     }
    ],
    "internal_fields": [
     {
      "name": "server",
      "role": "MinecraftServer source of MOTD and player counts"
     },
     {
      "name": "networkManager",
      "role": "Connection used to send replies and close"
     },
     {
      "name": "handled",
      "role": "One-shot guard rejecting duplicate queries"
     },
     {
      "name": "EXIT_MESSAGE",
      "role": "Shared disconnect text after status handled"
     }
    ],
    "peers": [
     "MinecraftServer",
     "NetworkManager",
     "INetHandlerStatusServer",
     "S00PacketServerInfo",
     "S01PacketPong"
    ],
    "methods_detailed": [
     {
      "name": "NetHandlerStatusServer",
      "detail_long": "NetHandlerStatusServer is the constructor that binds a STATUS connection to its server and channel. It stores the MinecraftServer reference used later to fetch cached ServerStatusResponse with MOTD, favicon, version, and player counts. It stores the NetworkManager used to send S00PacketServerInfo and S01PacketPong and to close the channel. It leaves handled false so the first C00PacketServerQuery will be accepted. The EXIT_MESSAGE constant Status request has been handled is shared for closes after query, duplicate query, or ping. No packets are sent inside the constructor itself. The handler lives only between handshake STATUS switch and login or disconnect.",
      "code": "    private static final IChatComponent EXIT_MESSAGE = new ChatComponentText(\"Status request has been handled.\");\n    private final MinecraftServer server;\n    private final NetworkManager networkManager;\n    private boolean handled;\n\n    public NetHandlerStatusServer(MinecraftServer serverIn, NetworkManager netManager)\n    {\n        this.server = serverIn;\n        this.networkManager = netManager;\n    }",
      "code_walkthrough": "The EXIT_MESSAGE field provides the disconnect text sent after STATUS completes. Storing server preserves access to getServerStatusResponse for S00 replies. Storing networkManager preserves the channel for sends and closes. Leaving handled false arms the one-shot query gate for processServerQuery."
     },
     {
      "name": "processServerQuery",
      "detail_long": "processServerQuery handles incoming C00PacketServerQuery with a one-shot guard. If handled is already true it closes the channel with EXIT_MESSAGE to reject duplicate queries on the same STATUS connection. Otherwise it sets handled true to arm the guard before replying. It fetches the cached response via server.getServerStatusResponse containing description, players, version, and favicon. It constructs S00PacketServerInfo with that response and sends it via networkManager.sendPacket. The client OldServerPinger.handleServerInfo will parse it and follow with C01PacketPing. No channel close happens on the first query so the follow-up ping can arrive. A second query on the same connection is treated as abuse and disconnected.",
      "code": "    public void processServerQuery(C00PacketServerQuery packetIn)\n    {\n        if (this.handled)\n        {\n            this.networkManager.closeChannel(EXIT_MESSAGE);\n        }\n        else\n        {\n            this.handled = true;\n            this.networkManager.sendPacket(new S00PacketServerInfo(this.server.getServerStatusResponse()));\n        }\n    }",
      "code_walkthrough": "The handled check enforces one query per STATUS session. Closing duplicates with EXIT_MESSAGE prevents info spam. Setting handled before send avoids race where a fast second query slips through. Sending S00PacketServerInfo with getServerStatusResponse delivers MOTD and counts. The channel stays open for the expected C01 ping."
     },
     {
      "name": "processPing",
      "detail_long": "processPing handles incoming C01PacketPing and terminates the STATUS session. It reads client time via packetIn.getClientTime which is the timestamp the client sent in C01PacketPing. It constructs S01PacketPong with that same long value and sends it via networkManager.sendPacket. The client handlePong subtracts its stored send time from current time to compute pingToServer. Immediately after queuing S01 it closes the channel with EXIT_MESSAGE Status request has been handled. This enforces the query-then-ping-then-close sequence and frees the connection. No state validation on handled is done here because ping is valid even in edge orderings. Further packets on this channel will fail as closed.",
      "code": "    }\n\n    public void processPing(C01PacketPing packetIn)\n    {\n        this.networkManager.sendPacket(new S01PacketPong(packetIn.getClientTime()));\n        this.networkManager.closeChannel(EXIT_MESSAGE);\n    }\n}",
      "code_walkthrough": "The method extracts clientTime from the C01 request to echo it back. Sending S01PacketPong with that value lets the client match ping to send time. Closing with EXIT_MESSAGE ends the STATUS phase per protocol. The trailing brace closes the class after handling."
     },
     {
      "name": "onDisconnect",
      "detail_long": "onDisconnect is the INetHandlerStatusServer disconnect hook for STATUS phase termination. It takes an IChatComponent reason describing normal Finished handling, duplicate query, or network error. Its body is intentionally empty because STATUS connections hold no player entity, inventory, or world state needing cleanup. Unlike play-phase handlers it does not broadcast quit messages or save data. The shared EXIT_MESSAGE close from processServerQuery and processPing flows through here as a no-op. Any resource release is handled by NetworkManager channel teardown itself. Leaving it empty also avoids touching MinecraftServer from the network thread on disconnect.",
      "code": "    /**\n     * Invoked when disconnecting, the parameter is a ChatComponent describing the reason for termination\n     */\n    public void onDisconnect(IChatComponent reason)\n    {\n    }\n\n    public void processServerQuery(C00PacketServerQuery packetIn)\n    {\n        if (this.handled)",
      "code_walkthrough": "The javadoc notes the reason parameter carries termination text. The empty body shows no player cleanup is required for stateless STATUS. The following processServerQuery header confirms disconnect needs no gate logic. NetworkManager handles socket close independently after this callback."
     }
    ]
   }
  },
  {
   "slug": "ItemInWorldManager",
   "title": "ItemInWorldManager",
   "rel": "net/minecraft/server/management/ItemInWorldManager.java",
   "desc": "Survival interaction handler: block break/place and creative resync emit S23 corrections and S38 list updates.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/ItemInWorldManager/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/server/management/ItemInWorldManager.java",
   "packets": [
    "S23PacketBlockChange",
    "S38PacketPlayerListItem"
   ],
   "peers": [
    "EntityPlayerMP",
    "WorldServer",
    "BlockPos",
    "EntityPlayer",
    "World",
    "NetHandlerPlayServer"
   ],
   "analysis": {
    "overview": "Server-side per-player survival, creative, adventure and spectator interaction controller. Validates dig timing, block harvesting, item use and block activation from NetHandlerPlayServer. Sends corrections and progress animations plus gamemode broadcasts to other players.",
    "methods": [
     {
      "detail": "Applies capability preset, pushes abilities to owner, then broadcasts S38PacketPlayerListItem UPDATE_GAME_MODE to every client.",
      "name": "setGameType",
      "packets": [
       "S38"
      ],
      "purpose": "Change gamemode and broadcast to all players"
     },
     {
      "detail": "Creative calls tryHarvestBlock directly; survival starts isDestroyingBlock and calls world.sendBlockBreakProgress for S25 animation.",
      "name": "onBlockClicked",
      "packets": [
       "S25"
      ],
      "purpose": "Begin survival dig or instant creative break"
     },
     {
      "detail": "Advances curblockDamage, sends staged 0-10 break progress or -1 reset through world, harvests when hardness threshold reached.",
      "name": "updateBlockRemoving",
      "packets": [
       "S25"
      ],
      "purpose": "Tick ongoing dig progress and finish harvest"
     },
     {
      "detail": "If hardness above 0.7 finishes immediately with reset animation, else parks state in receivedFinishDiggingPacket for tick completion.",
      "name": "blockRemoving",
      "packets": [
       "S25"
      ],
      "purpose": "Handle stop-digging packet mid-break"
     },
     {
      "detail": "Clears isDestroyingBlock and sends block-break progress -1 for the tracked position to watching clients.",
      "name": "cancelDestroyingBlock",
      "packets": [
       "S25"
      ],
      "purpose": "Abort dig and clear crack overlay"
     },
     {
      "detail": "Enforces adventure canDestroy rules, plays AuxSFX, removes block; in creative sends S23PacketBlockChange so client matches server.",
      "name": "tryHarvestBlock",
      "packets": [
       "S23"
      ],
      "purpose": "Remove block, drop loot and correct creative client"
     },
     {
      "detail": "Calls useItemRightClick, restores stack size and damage in creative, and resyncs inventory container when not using item.",
      "name": "tryUseItem",
      "packets": [],
      "purpose": "Apply right-click item use with creative restore"
     },
     {
      "detail": "Spectator only opens chests; others try onBlockActivated first unless sneaking, then delegates to stack.onItemUse.",
      "name": "activateBlockOrUseItem",
      "packets": [],
      "purpose": "Activate block or place held item"
     }
    ],
    "packet_usage": [
     {
      "direction": "handled",
      "id": "C07/C08",
      "trigger": "NetHandlerPlayServer dig and block-place drive these methods"
     },
     {
      "direction": "sent",
      "id": "S25",
      "trigger": "sendBlockBreakProgress in dig start, tick and cancel"
     },
     {
      "direction": "sent",
      "id": "S23",
      "trigger": "tryHarvestBlock creative correction to breaker"
     },
     {
      "direction": "sent",
      "id": "S38",
      "trigger": "setGameType UPDATE_GAME_MODE broadcast"
     }
    ],
    "internal_fields": [
     {
      "name": "theWorld",
      "role": "Server world where block edits are applied"
     },
     {
      "name": "thisPlayerMP",
      "role": "Owning player for abilities and packet replies"
     },
     {
      "name": "gameType",
      "role": "Current survival, creative, adventure or spectator mode"
     },
     {
      "name": "isDestroyingBlock",
      "role": "Whether survival dig progress is active"
     },
     {
      "name": "receivedFinishDiggingPacket",
      "role": "Pending finish when stop arrived early"
     },
     {
      "name": "durabilityRemainingOnBlock",
      "role": "Last sent 0-10 crack stage to avoid resends"
     }
    ],
    "peers": [
     "EntityPlayerMP",
     "WorldServer",
     "WorldSettings",
     "NetHandlerPlayServer",
     "TileEntityChest"
    ],
    "methods_detailed": [
     {
      "name": "setGameType",
      "detail_long": "setGameType changes the owned player's gamemode and broadcasts it to the whole server. It stores the new WorldSettings.GameType in gameType for later survivalOrAdventure and isCreative checks. It calls type.configurePlayerCapabilities on thisPlayerMP.capabilities to set fly, edit, and damage flags. It calls thisPlayerMP.sendPlayerAbilities to push those flags to the owner, updating its own client permissions. It then broadcasts S38PacketPlayerListItem with Action UPDATE_GAME_MODE and an array containing thisPlayerMP via sendPacketToAllPlayers. Every connected client receives S38 and updates the tab-list gamemode icon plus adventure interaction rules for that player. The owner also gets the broadcast in addition to the direct abilities packet. No block or inventory change happens here.",
      "code": "    public void setGameType(WorldSettings.GameType type)\n    {\n        this.gameType = type;\n        type.configurePlayerCapabilities(this.thisPlayerMP.capabilities);\n        this.thisPlayerMP.sendPlayerAbilities();\n        this.thisPlayerMP.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S38PacketPlayerListItem(S38PacketPlayerListItem.Action.UPDATE_GAME_MODE, new EntityPlayerMP[] {this.thisPlayerMP}));\n    }",
      "code_walkthrough": "Storing gameType updates local mode used by dig and use guards. configurePlayerCapabilities maps survival, creative, adventure, and spectator to capability booleans. sendPlayerAbilities pushes those flags to the owner client. Broadcasting S38 UPDATE_GAME_MODE informs all other clients of the new mode for rendering and permissions."
     },
     {
      "name": "onBlockClicked",
      "detail_long": "onBlockClicked starts block breaking when the client sends a dig-start packet. In creative it tries extinguishFire first to put out fire without breaking, and if not fire it calls tryHarvestBlock for instant removal. In survival and adventure it loads the target Block and enforces adventure canDestroy rules via isAllowEdit and held stack canDestroy, returning early for spectator or disallowed tools. It extinguishes fire at the position, snapshots initialDamage from curblockDamage, and queries getPlayerRelativeBlockHardness for dig speed. It notifies the block via onBlockClicked for doors and special handling. If hardness is at least 1.0 it calls tryHarvestBlock immediately for instant crops or soft blocks. Otherwise it sets isDestroyingBlock true, records field_180240_f position, and calls theWorld.sendBlockBreakProgress with staged crack 0 to 10. That call emits S25PacketBlockBreakAnim to watching clients so all see the crack overlay grow.",
      "code": "    public void onBlockClicked(BlockPos pos, EnumFacing side)\n    {\n        if (this.isCreative())\n        {\n            if (!this.theWorld.extinguishFire((EntityPlayer)null, pos, side))\n            {\n                this.tryHarvestBlock(pos);\n            }\n        }\n        else\n        {\n            Block block = this.theWorld.getBlockState(pos).getBlock();",
      "code_walkthrough": "The isCreative branch handles instant break versus fire extinguish without progress packets. The else branch loads the server block for survival hardness and adventure checks. Adventure validation returns early when the held item cannot destroy the block. Later code sets isDestroyingBlock and sends S25 crack progress to trackers."
     },
     {
      "name": "updateBlockRemoving",
      "detail_long": "updateBlockRemoving ticks every server tick to advance survival digging and emit S25 progress. It increments curblockDamage as the tick counter for both pending-finish and active-dig paths. If receivedFinishDiggingPacket is true meaning stop-dig arrived early, it computes elapsed ticks, loads the Block at field_180241_i, and clears the flag if now air. It multiplies getPlayerRelativeBlockHardness by elapsed plus one to get fraction f and scales to 0 to 10 stage j. If j differs from durabilityRemainingOnBlock it calls theWorld.sendBlockBreakProgress with player ID, position, and stage, which sends S25PacketBlockBreakAnim to trackers. When f reaches 1.0 it clears the flag and calls tryHarvestBlock to remove and loot the block. Else if isDestroyingBlock is active it performs similar progress for field_180240_f, sending -1 reset and clearing the flag if the block turned to air. Stage caching avoids spamming S25 every tick when unchanged.",
      "code": "    public void updateBlockRemoving()\n    {\n        ++this.curblockDamage;\n\n        if (this.receivedFinishDiggingPacket)\n        {\n            int i = this.curblockDamage - this.initialBlockDamage;\n            Block block = this.theWorld.getBlockState(this.field_180241_i).getBlock();\n\n            if (block.getMaterial() == Material.air)\n            {\n                this.receivedFinishDiggingPacket = false;\n            }\n            else\n            {\n                float f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, this.field_180241_i) * (float)(i + 1);\n                int j = (int)(f * 10.0F);\n\n                if (j != this.durabilityRemainingOnBlock)\n                {\n                    this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180241_i, j);\n                    this.durabilityRemainingOnBlock = j;\n                }\n\n                if (f >= 1.0F)\n                {\n                    this.receivedFinishDiggingPacket = false;\n                    this.tryHarvestBlock(this.field_180241_i);\n                }\n            }\n        }\n        else if (this.isDestroyingBlock)\n        {\n            Block block1 = this.theWorld.getBlockState(this.field_180240_f).getBlock();",
      "code_walkthrough": "Incrementing curblockDamage drives both dig paths forward each tick. The receivedFinishDiggingPacket branch finishes blocks whose stop packet arrived before hardness completed. Computing f from hardness times elapsed gives break fraction scaled to S25 stage 0 to 10. sendBlockBreakProgress emits S25 only when the stage changed to limit traffic. Reaching 1.0 harvests the block while the isDestroyingBlock branch maintains live crack for held dig."
     },
     {
      "name": "blockRemoving",
      "detail_long": "blockRemoving handles the stop-digging C07 packet when it arrives mid-break. It first verifies pos equals field_180240_f so stale or moved targets are ignored. It computes elapsed ticks as curblockDamage minus initialDamage and loads the server Block. If material is air it does nothing because onUpdate or harvest already cleared it. It multiplies getPlayerRelativeBlockHardness by elapsed plus one to estimate break fraction f. If f is at least 0.7 it treats the dig as complete: clears isDestroyingBlock, sends progress -1 via sendBlockBreakProgress to erase crack via S25, and calls tryHarvestBlock to remove and drop loot. If below 0.7 and receivedFinishDiggingPacket is not already set, it parks the request by clearing isDestroyingBlock, setting receivedFinishDiggingPacket true, and copying position and initial damage into field_180241_i and initialBlockDamage. updateBlockRemoving will then finish it over subsequent ticks with staged S25 updates.",
      "code": "    public void blockRemoving(BlockPos pos)\n    {\n        if (pos.equals(this.field_180240_f))\n        {\n            int i = this.curblockDamage - this.initialDamage;\n            Block block = this.theWorld.getBlockState(pos).getBlock();\n\n            if (block.getMaterial() != Material.air)\n            {\n                float f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, pos) * (float)(i + 1);\n\n                if (f >= 0.7F)\n                {\n                    this.isDestroyingBlock = false;\n                    this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), pos, -1);\n                    this.tryHarvestBlock(pos);\n                }\n                else if (!this.receivedFinishDiggingPacket)\n                {\n                    this.isDestroyingBlock = false;\n                    this.receivedFinishDiggingPacket = true;\n                    this.field_180241_i = pos;\n                    this.initialBlockDamage = this.initialDamage;\n                }\n            }\n        }\n    }",
      "code_walkthrough": "The pos equality guard ensures only the active dig target can be finished. Elapsed ticks times hardness estimates how far digging progressed. The 0.7 threshold allows slightly early stops to succeed while sending S25 -1 to clear crack. Parking below threshold defers harvest to updateBlockRemoving with staged S25. Air targets are ignored as already broken."
     },
     {
      "name": "cancelDestroyingBlock",
      "detail_long": "cancelDestroyingBlock aborts an in-progress survival dig when the client sends abort or switches target. It unconditionally sets isDestroyingBlock false to stop updateBlockRemoving from advancing crack stages. It calls theWorld.sendBlockBreakProgress with the breaker entity ID, field_180240_f position, and -1 stage. WorldServer forwards that as S25PacketBlockBreakAnim with destroy stage -1 to all clients tracking the position. Receivers clear the crack overlay for that breaker ID. No block removal, loot, or tool damage occurs on cancel. The curblockDamage counter is left for the next onBlockClicked to re-baseline via initialDamage. Duplicate cancels simply resend -1 which clients treat as idempotent clear.",
      "code": "    /**\n     * Stops the block breaking process\n     */\n    public void cancelDestroyingBlock()\n    {\n        this.isDestroyingBlock = false;\n        this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, -1);\n    }\n\n    /**",
      "code_walkthrough": "Clearing isDestroyingBlock halts tick progress in updateBlockRemoving. Sending break progress -1 emits S25 telling trackers to remove the crack. The breaker ID plus position key the overlay so other diggers are unaffected. No harvest or drops follow because cancellation is visual-only."
     },
     {
      "name": "tryHarvestBlock",
      "detail_long": "tryHarvestBlock removes the block, plays break effects, and corrects the client as needed. It first blocks creative sword use from breaking blocks to preserve attack semantics. It loads IBlockState and TileEntity, then enforces adventure and spectator rules with isAllowEdit and canDestroy checks. It plays AuxSFX 2001 break particles and sound at the position via playAuxSFXAtEntity for nearby clients. It calls removeBlock which fires onBlockHarvested and setBlockToAir plus onBlockDestroyedByPlayer. In creative it sends S23PacketBlockChange with world and position directly to the breaker via playerNetServerHandler so the client matches instant server removal. In survival it damages the held stack, destroys it at zero size, and if both removed and harvestable calls harvestBlock to drop items and XP. The boolean return reports whether setBlockToAir succeeded.",
      "code": "            this.theWorld.playAuxSFXAtEntity(this.thisPlayerMP, 2001, pos, Block.getStateId(iblockstate));\n            boolean flag1 = this.removeBlock(pos);\n\n            if (this.isCreative())\n            {\n                this.thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(this.theWorld, pos));\n            }\n            else\n            {\n                ItemStack itemstack1 = this.thisPlayerMP.getCurrentEquippedItem();\n                boolean flag = this.thisPlayerMP.canHarvestBlock(iblockstate.getBlock());",
      "code_walkthrough": "Playing AuxSFX 2001 broadcasts break particles and sound to nearby clients. removeBlock performs the actual setBlockToAir with harvest callbacks. The creative branch sends S23PacketBlockChange to the breaker to force client chunk match after instant break. The survival branch inspects the held stack and harvest permission to decide drops and tool damage."
     },
     {
      "name": "tryUseItem",
      "detail_long": "tryUseItem applies right-click item use from NetHandlerPlayServer C08 handling. It immediately returns false for spectator mode to block consumables, throws, and placements. It snapshots stackSize and metadata before calling stack.useItemRightClick with world and player for potions, food, buckets, or projectiles. If the returned stack differs by identity, size, max use duration, or metadata, it writes the result into the current hotbar slot. In creative it restores stackSize and item damage so blocks and items are infinite while still triggering effects. If size reached zero it clears the slot to null to remove consumed items. If the player is not in a use animation it calls sendContainerToPlayer to resync the inventory container, correcting any client-server drift. True signals the interaction was consumed while false lets the caller try block activation instead. No block-change packet is sent here beyond container sync.",
      "code": "    public boolean tryUseItem(EntityPlayer player, World worldIn, ItemStack stack)\n    {\n        if (this.gameType == WorldSettings.GameType.SPECTATOR)\n        {\n            return false;\n        }\n        else\n        {\n            int i = stack.stackSize;\n            int j = stack.getMetadata();\n            ItemStack itemstack = stack.useItemRightClick(worldIn, player);\n\n            if (itemstack != stack || itemstack != null && (itemstack.stackSize != i || itemstack.getMaxItemUseDuration() > 0 || itemstack.getMetadata() != j))\n            {\n                player.inventory.mainInventory[player.inventory.currentItem] = itemstack;\n\n                if (this.isCreative())\n                {\n                    itemstack.stackSize = i;\n\n                    if (itemstack.isItemStackDamageable())\n                    {\n                        itemstack.setItemDamage(j);\n                    }\n                }",
      "code_walkthrough": "The spectator guard blocks all right-click use for observers. Snapshotting size and metadata detects consumption or transformation from useItemRightClick. Writing the result into mainInventory keeps server inventory authoritative. Creative restore plus damage reset preserves infinite items while still firing use effects."
     },
     {
      "name": "activateBlockOrUseItem",
      "detail_long": "activateBlockOrUseItem handles right-click on a block position, choosing block activation versus item placement. Spectators only open chest and inventory GUIs via displayGUIChest without editing, returning false for other blocks. For players it first tries onBlockActivated when not sneaking or when empty-handed, letting doors, chests, furnaces, and levers consume the click with true. If that fails and stack is null it returns false to end the interaction. In creative it records metadata and size, calls stack.onItemUse for placement, then restores damage and size for infinite blocks before returning the result. In survival it directly returns stack.onItemUse which places blocks, consumes items, and triggers TileEntity updates. Block changes from placement flow through WorldServer mark-and-notify as S22 and S23 packets rather than from this method. Deduplication with NetHandlerPlayServer position and face validation prevents ghost blocks.",
      "code": "        else\n        {\n            if (!player.isSneaking() || player.getHeldItem() == null)\n            {\n                IBlockState iblockstate = worldIn.getBlockState(pos);\n\n                if (iblockstate.getBlock().onBlockActivated(worldIn, pos, iblockstate, player, side, offsetX, offsetY, offsetZ))\n                {\n                    return true;\n                }\n            }\n\n            if (stack == null)\n            {\n                return false;\n            }\n            else if (this.isCreative())\n            {\n                int j = stack.getMetadata();\n                int i = stack.stackSize;\n                boolean flag = stack.onItemUse(player, worldIn, pos, side, offsetX, offsetY, offsetZ);\n                stack.setItemDamage(j);\n                stack.stackSize = i;\n                return flag;\n            }\n            else\n            {\n                return stack.onItemUse(player, worldIn, pos, side, offsetX, offsetY, offsetZ);\n            }\n        }\n    }",
      "code_walkthrough": "The sneaking check lets players place blocks instead of opening GUIs when holding items. onBlockActivated gives the target block first chance to consume the click. Null stack returns false after failed activation to stop further work. Creative placement restores metadata and size after onItemUse while survival delegates directly for consumption."
     }
    ]
   }
  },
  {
   "slug": "Timer",
   "title": "Timer",
   "rel": "net/minecraft/util/Timer.java",
   "desc": "Tick-loop clock: 20 ticks/sec, renderPartialTicks interpolation, timerSpeed for timer cheats to target.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/Timer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/util/Timer.java",
   "packets": [],
   "peers": [
    "Minecraft",
    "MathHelper"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "ticksPerSecond",
      "role": "Target ticks per second, 20 in vanilla"
     },
     {
      "name": "elapsedTicks",
      "role": "Whole ticks to run this frame, capped at 10"
     },
     {
      "name": "elapsedPartialTicks",
      "role": "Fractional tick carry-over between frames"
     },
     {
      "name": "renderPartialTicks",
      "role": "Interpolation factor for rendering"
     },
     {
      "name": "timerSpeed",
      "role": "Speed multiplier, 0.5 is half speed"
     },
     {
      "name": "timeSyncAdjustment",
      "role": "Drift correction ratio for hi-res clock"
     }
    ],
    "methods": [
     {
      "detail": "Stores ticksPerSecond. Seeds lastSyncSysClock via Minecraft.getSystemTime and lastSyncHRClock via nanoTime ms. Initializes timeSyncAdjustment to 1.0.",
      "name": "Timer",
      "packets": [],
      "purpose": "Constructs timer with target ticks-per-second, default 20."
     },
     {
      "detail": "Computes sysClock delta j and hrClock seconds d0. If j outside 0-1000ms resets lastHRTime. Otherwise accumulates counter for drift correction.",
      "name": "updateTimer",
      "packets": [],
      "purpose": "Advances tick counters from wall-clock delta each frame."
     },
     {
      "detail": "When counter exceeds 1000ms computes ratio counter/(k-lastSyncHRClock). Blends into timeSyncAdjustment with 0.2 factor. Resets counter and anchor.",
      "name": "updateTimer#sync-adjust",
      "packets": [],
      "purpose": "Calibrates hi-res clock against system clock once per second."
     },
     {
      "detail": "Formula d2=(d0-lastHRTime)*timeSyncAdjustment. Clamps d2 to 0-1 via MathHelper. Adds d2*timerSpeed*ticksPerSecond to elapsedPartialTicks.",
      "name": "updateTimer#accumulate",
      "packets": [],
      "purpose": "Converts seconds delta into fractional tick progress."
     },
     {
      "detail": "elapsedTicks=(int)elapsedPartialTicks then subtracts back fractional remainder. Caps elapsedTicks at 10. Prevents huge catch-up bursts after lag.",
      "name": "updateTimer#cap-ticks",
      "packets": [],
      "purpose": "Extracts whole ticks and enforces spiral-of-death cap."
     },
     {
      "detail": "Public float field set equal to elapsedPartialTicks each update. Frozen when paused to avoid jitter. Read by entity rendering and camera code.",
      "name": "renderPartialTicks",
      "packets": [],
      "purpose": "Exposes interpolation factor for render and movement smoothing."
     }
    ],
    "overview": "Client tick-rate driver in net.minecraft.util. Owned by Minecraft game loop, called each frame via updateTimer. Converts wall-clock delta into elapsedTicks and renderPartialTicks. Matters for movement because it bounds ticks to 10 and scales by timerSpeed.",
    "packet_usage": [],
    "peers": [
     "Minecraft",
     "MathHelper"
    ]
   }
  },
  {
   "slug": "Minecraft",
   "title": "Minecraft",
   "rel": "net/minecraft/client/Minecraft.java",
   "desc": "Client singleton and main loop: runTick game logic, updateCameraAndRender, thePlayer/theWorld access, addScheduledTask.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/Minecraft/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/client/Minecraft.java",
   "packets": [
    "C00Handshake",
    "C00PacketLoginStart",
    "C16PacketClientStatus"
   ],
   "peers": [
    "EntityPlayerSP",
    "NetHandlerPlayClient",
    "PlayerControllerMP",
    "Timer",
    "NetworkManager",
    "EnumConnectionState",
    "MathHelper",
    "BlockPos",
    "Entity",
    "EntityPlayer",
    "World"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "thePlayer/theWorld",
      "role": "Local player and client world mutated by ticks and packets"
     },
     {
      "name": "scheduledTasks",
      "role": "Main-thread queue drained each frame for packet callbacks"
     },
     {
      "name": "myNetworkManager",
      "role": "Active connection used while world null or integrated login"
     },
     {
      "name": "currentScreen",
      "role": "Top GUI intercepting input and pausing world"
     },
     {
      "name": "playerController",
      "role": "Sends block/entity interactions as C-packets"
     }
    ],
    "methods": [
     {
      "detail": "Calls startGame once, then loops runGameLoop until running false. Catches memory, reported, and unexpected throwables into crash screens.",
      "name": "run",
      "packets": [],
      "purpose": "Outer startup and loop guard with crash handling."
     },
     {
      "detail": "Updates timer, drains scheduledTasks, runs runTick per elapsedTicks, renders via EntityRenderer, syncs display, updates debug FPS and pause state.",
      "name": "runGameLoop",
      "packets": [],
      "purpose": "Frame driver for timer, ticks, render, and FPS limit."
     },
     {
      "detail": "Handles mouse/keyboard, hotbar, inventory key sending C16 open-inventory, click/rightClick dispatch, joinEntityInSurroundings, world.updateEntities/tick, and sound updates.",
      "name": "runTick",
      "packets": [
       "C16"
      ],
      "purpose": "Client tick for input, controller, world, and GUI."
     },
     {
      "detail": "Cleans NetHandler, stops integrated server if unloading, sets renderGlobal/effectRenderer world, spawns thePlayer or clears it. Called on login/logout/respawn.",
      "name": "loadWorld",
      "packets": [],
      "purpose": "Swaps WorldClient and rebuilds player/render state."
     },
     {
      "detail": "Creates IntegratedServer, waits for loop, provides local NetworkManager client, sends C00Handshake then C00 login start. Stores myNetworkManager.",
      "name": "launchIntegratedServer",
      "packets": [
       "C00"
      ],
      "purpose": "Starts local server and connects via loopback channel."
     },
     {
      "detail": "If off thread enqueues ListenableFutureTask into scheduledTasks drained in runGameLoop; if on thread runs immediately. Used by NetHandler packet handling.",
      "name": "addScheduledTask",
      "packets": [],
      "purpose": "Thread-safe queue for main-thread execution."
     },
     {
      "detail": "Returns thePlayer.sendQueue if player exists else null. Used to enqueue C-packets like C16 inventory and movement.",
      "name": "getNetHandler",
      "packets": [],
      "purpose": "Accessor for client play handler via player queue."
     },
     {
      "detail": "Closes old screen, defaults to main menu or game-over, sets resolution, toggles ingame focus and sound pause. Drives inventory and pause menus.",
      "name": "displayGuiScreen",
      "packets": [],
      "purpose": "Manages GUI stack and mouse focus transitions."
     }
    ],
    "overview": "Client singleton owning game loop, window, renderers, player, and world. run/runGameLoop/runTick pump scheduled tasks, input, controller, world ticks, and rendering. Holds thePlayer/theWorld, NetHandler access, GUI stack, and display management. Also bootstraps integrated server connections.",
    "packet_usage": [
     {
      "direction": "sent",
      "id": "C00",
      "trigger": "Integrated-server login: C00Handshake then C00 login start via local channel"
     },
     {
      "direction": "sent",
      "id": "C16",
      "trigger": "Inventory key opens GuiInventory and signals open-inventory achievement"
     }
    ],
    "peers": [
     "NetHandlerPlayClient",
     "WorldClient",
     "EntityPlayerSP",
     "PlayerControllerMP",
     "NetworkManager",
     "GuiScreen",
     "IntegratedServer",
     "Timer"
    ]
   }
  },
  {
   "slug": "NetworkManager",
   "title": "NetworkManager",
   "rel": "net/minecraft/network/NetworkManager.java",
   "desc": "Netty channel wrapper: sendPacket/dispatchPacket, MessageSerializer pipeline, per-connection state machine driver.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/NetworkManager/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/network/NetworkManager.java",
   "packets": [],
   "peers": [
    "EnumConnectionState",
    "NetHandlerPlayClient",
    "NetHandlerPlayServer"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "channel",
      "role": "Active Netty channel carrying encoded packets"
     },
     {
      "name": "packetListener",
      "role": "INetHandler receiving decoded packets via channelRead0"
     },
     {
      "name": "outboundPacketsQueue",
      "role": "Buffer for sends before channel open, drained in order"
     },
     {
      "name": "direction",
      "role": "CLIENTBOUND or SERVERBOUND expected flow for this endpoint"
     },
     {
      "name": "terminationReason",
      "role": "Disconnect message surfaced via getExitMessage"
     }
    ],
    "methods": [
     {
      "detail": "Checks channel open then calls processPacket(packetListener). Swallows ThreadQuickExitException used to abort handling. All play/login/status packets flow through here.",
      "name": "channelRead0",
      "packets": [],
      "purpose": "Inbound entry point that dispatches received Packet to current INetHandler."
     },
     {
      "detail": "If channel open, flushes queue then dispatchPacket; else buffers under write lock. Overload accepts Netty future listeners. Used for every serverbound and clientbound send.",
      "name": "sendPacket",
      "packets": [],
      "purpose": "Queues or immediately dispatches an outbound packet."
     },
     {
      "detail": "Compares EnumConnectionState from packet vs channel attr; disables auto-read on change. If on event loop writes directly, else schedules task. Adds failure listener.",
      "name": "dispatchPacket",
      "packets": [],
      "purpose": "Writes packet to channel, handling protocol switches and threading."
     },
     {
      "detail": "Takes read lock and polls outboundPacketsQueue calling dispatchPacket. Called from sendPacket and processReceivedPackets. Ensures login/handshake ordering.",
      "name": "flushOutboundQueue",
      "packets": [],
      "purpose": "Drains buffered packets queued before channel was open."
     },
     {
      "detail": "Flushes outbound queue, ticks packetListener if ITickable, then flushes channel. Called by client runTick and server loops.",
      "name": "processReceivedPackets",
      "packets": [],
      "purpose": "Per-tick pump for network and packet listener logic."
     },
     {
      "detail": "Stores EnumConnectionState in channel attr and enables auto-read. Called on channelActive as HANDSHAKING and on protocol upgrade during dispatch.",
      "name": "setConnectionState",
      "packets": [],
      "purpose": "Sets protocol state attribute controlling codec routing."
     },
     {
      "detail": "Selects NIO or Epoll channel, installs timeout/splitter/decoder/prepender/encoder/handler. Uses CLIENTBOUND decoder and SERVERBOUND encoder.",
      "name": "createNetworkManagerAndConnect",
      "packets": [],
      "purpose": "Builds client TCP pipeline and connects to remote server."
     },
     {
      "detail": "Adds decrypt before splitter and encrypt before prepender using CryptManager ciphers. Sets isEncrypted flag. Triggered after login encryption response.",
      "name": "enableEncryption",
      "packets": [],
      "purpose": "Inserts cipher codecs for encrypted session after login key exchange."
     },
     {
      "detail": "Adds NettyCompressionDecoder/Encoder before decoder/encoder if threshold >=0, else removes them. Mirrors login compression negotiation.",
      "name": "setCompressionTreshold",
      "packets": [],
      "purpose": "Enables or disables Netty compression codecs dynamically."
     }
    ],
    "overview": "Netty-based transport for all Minecraft connections, extending SimpleChannelInboundHandler<Packet>. Owns the Channel, packet listener (INetHandler), and queued outbound packets with read/write locks. Handles connection-state switching, encryption, compression, and local vs TCP channels. Client and server both pump it via processReceivedPackets and sendPacket.",
    "packet_usage": [],
    "peers": [
     "EnumConnectionState",
     "INetHandler",
     "Packet",
     "MessageDeserializer",
     "MessageSerializer",
     "CryptManager",
     "NetHandlerPlayClient",
     "NetHandlerPlayServer"
    ]
   }
  },
  {
   "slug": "PacketBuffer",
   "title": "PacketBuffer",
   "rel": "net/minecraft/network/PacketBuffer.java",
   "desc": "Wire-format helpers: VarInt/VarLong, BlockPos, ItemStack, NBT, chat, UUID read/write used by every packet.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/PacketBuffer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/network/PacketBuffer.java",
   "packets": [],
   "peers": [
    "BlockPos",
    "EnumConnectionState"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "buf",
      "role": "Wrapped Netty ByteBuf delegating all I/O"
     },
     {
      "name": "getVarIntSize",
      "role": "Static byte-count predictor for VarInt values"
     },
     {
      "name": "readVarLong",
      "role": "Up to 10-byte VarLong reader"
     },
     {
      "name": "writeVarLong",
      "role": "Minimal-byte VarLong writer"
     },
     {
      "name": "readUuid",
      "role": "Two-long UUID codec for player ids"
     }
    ],
    "methods": [
     {
      "detail": "Accumulates 7 bits per byte while high bit set. Throws if more than 5 bytes. Basis for packet framing and array/string lengths.",
      "name": "readVarIntFromBuffer",
      "packets": [],
      "purpose": "Reads 1-5 byte VarInt packet id and lengths."
     },
     {
      "detail": "While (input&-128)!=0 writes (input&127|128) then >>>=7. Single byte fast path for values under 128 like most packet ids.",
      "name": "writeVarIntToBuffer",
      "packets": [],
      "purpose": "Writes minimal-byte VarInt encoding."
     },
     {
      "detail": "VarInt length must be <=maxLength*4 and >=0. Decodes UTF-8 then enforces char length <=maxLength. Throws DecoderException otherwise.",
      "name": "readStringFromBuffer",
      "packets": [],
      "purpose": "Reads UTF-8 string with length and content checks."
     },
     {
      "detail": "Encodes via Charsets.UTF_8, throws EncoderException if >32767 bytes. Prefixes VarInt length then raw bytes. Returns this.",
      "name": "writeString",
      "packets": [],
      "purpose": "Writes UTF-8 string with 32767 byte cap."
     },
     {
      "detail": "Calls readLong then BlockPos.fromLong. Used by block change, dig, place, sign, and tile entity packets. 26/12/26 bit split.",
      "name": "readBlockPos",
      "packets": [],
      "purpose": "Reads packed 8-byte block coordinate."
     },
     {
      "detail": "Calls writeLong(pos.toLong()). Canonical encoding for all block-position fields. 8 bytes versus 12 for raw ints.",
      "name": "writeBlockPos",
      "packets": [],
      "purpose": "Writes BlockPos as single long."
     },
     {
      "detail": "Short id -1 means null. Otherwise byte count plus short meta, then NBT compound. Used by window, creative, and equipment packets.",
      "name": "readItemStackFromBuffer",
      "packets": [],
      "purpose": "Reads item id, count, meta, and NBT."
     },
     {
      "detail": "Peeks first byte; 0 means null. Else resets readerIndex and gunzips via CompressedStreamTools with 2MB NBTSizeTracker cap.",
      "name": "readNBTTagCompoundFromBuffer",
      "packets": [],
      "purpose": "Reads possibly-null compressed NBT tag."
     }
    ],
    "overview": "Netty ByteBuf wrapper in net.minecraft.network adding Minecraft codecs. Used by every Packet readPacket and writePacket method. Matters because VarInt, strings, BlockPos, ItemStack, NBT, UUID, and chat all funnel through it.",
    "packet_usage": [],
    "peers": [
     "BlockPos",
     "ItemStack",
     "NBTTagCompound",
     "IChatComponent",
     "ByteBuf",
     "EnumConnectionState"
    ]
   }
  },
  {
   "slug": "EnumConnectionState",
   "title": "EnumConnectionState",
   "rel": "net/minecraft/network/EnumConnectionState.java",
   "desc": "Protocol registry: HANDSHAKING/STATUS/LOGIN/PLAY packet-ID maps, direction routing, compression hooks.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/EnumConnectionState/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/network/EnumConnectionState.java",
   "packets": [],
   "peers": [
    "NetworkManager",
    "PacketBuffer"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "id",
      "role": "Protocol id -1,0,1,2 per state"
     },
     {
      "name": "directionMaps",
      "role": "Per-direction BiMap of id to packet class"
     },
     {
      "name": "STATES_BY_ID",
      "role": "Array lookup from protocol id to state"
     },
     {
      "name": "STATES_BY_CLASS",
      "role": "Reverse map from packet class to state"
     },
     {
      "name": "field_181136_e",
      "role": "Minimum protocol id -1"
     },
     {
      "name": "field_181137_f",
      "role": "Maximum protocol id 2"
     }
    ],
    "methods": [
     {
      "detail": "Creates Guava HashBiMap per EnumPacketDirection if absent. Throws if class already registered. Id equals bimap.size() before put.",
      "name": "registerPacket",
      "packets": [],
      "purpose": "Assigns next sequential id to packet class per direction."
     },
     {
      "detail": "Inverts direction BiMap and gets class key. Used when writing packet header VarInt. Returns Integer id or null.",
      "name": "getPacketId",
      "packets": [],
      "purpose": "Looks up outbound packet id for encoder."
     },
     {
      "detail": "Looks up class by id then calls newInstance. Returns null if unknown id. Decoder drops or disconnects on null.",
      "name": "getPacket",
      "packets": [],
      "purpose": "Instantiates inbound packet by numeric id."
     },
     {
      "detail": "Bounds-checks against -1 to 2 then indexes STATES_BY_ID. C00Handshake carries this id. Switches pipeline state.",
      "name": "getById",
      "packets": [],
      "purpose": "Resolves protocol state from handshake nextState."
     },
     {
      "detail": "Looks up STATES_BY_CLASS map keyed by class. Populated in static init. Used for validation and logging.",
      "name": "getFromPacket",
      "packets": [],
      "purpose": "Finds owning state for a packet instance."
     },
     {
      "detail": "Clientbound S00-S49 plus S14/S19 sub-ids; serverbound C00-C19 plus C03/C06 splits. Order defines 1.8.9 wire ids, e.g. S08 pos-look.",
      "name": "PLAY-init",
      "packets": [],
      "purpose": "Registers all play-state clientbound and serverbound packets."
     }
    ],
    "overview": "Protocol-state enum mapping packet ids to classes per direction. States HANDSHAKING, PLAY, LOGIN, STATUS with ids -1,0,2,1. Central registry consulted by NetworkManager to instantiate and route every packet.",
    "packet_usage": [
     {
      "direction": "sent",
      "id": "C00Handshake",
      "trigger": "Client connects, carries nextState to select PLAY/LOGIN/STATUS"
     },
     {
      "direction": "handled",
      "id": "S08PacketPlayerPosLook",
      "trigger": "Server teleports or corrects player, client confirms with C03"
     },
     {
      "direction": "handled",
      "id": "C03PacketPlayer",
      "trigger": "Client movement tick, server validates position and look"
     },
     {
      "direction": "sent",
      "id": "S01PacketJoinGame",
      "trigger": "Login success transitions LOGIN to PLAY state"
     }
    ],
    "peers": [
     "Packet",
     "EnumPacketDirection",
     "C00Handshake",
     "NetworkManager",
     "PacketBuffer"
    ]
   }
  },
  {
   "slug": "MathHelper",
   "title": "MathHelper",
   "rel": "net/minecraft/util/MathHelper.java",
   "desc": "Fast lookup-table trig, floor/clamp/angle-wrap helpers backing movement, rotation and render math.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/MathHelper/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/util/MathHelper.java",
   "packets": [],
   "peers": [
    "BlockPos",
    "Timer",
    "AxisAlignedBB"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "SIN_TABLE",
      "role": "65536 float sine samples over 0 to 2pi"
     },
     {
      "name": "SQRT_2",
      "role": "Precomputed sqrt(2) constant"
     },
     {
      "name": "multiplyDeBruijnBitPosition",
      "role": "32-entry log2 lookup for De Bruijn index"
     },
     {
      "name": "field_181164_e",
      "role": "257-entry asin table for fast atan2"
     },
     {
      "name": "field_181165_f",
      "role": "257-entry cos(asin) table for atan2"
     }
    ],
    "methods": [
     {
      "detail": "Index=(int)(value*10430.378)&65535 where constant is 65536/2pi. Table precomputed in static block. Used for yaw, head look, and motion vectors.",
      "name": "sin",
      "packets": [],
      "purpose": "Fast sine via 65536-entry lookup table."
     },
     {
      "detail": "Index adds 16384 (pi/2) before mask. Avoids second table. Same 2pi/65536 step resolution as sin.",
      "name": "cos",
      "packets": [],
      "purpose": "Fast cosine via sine table with quarter-period offset."
     },
     {
      "detail": "Casts to int then subtracts 1 if value below cast. Handles negatives correctly unlike truncation. Basis for BlockPos from entity pos.",
      "name": "floor_double",
      "packets": [],
      "purpose": "Greatest integer <= double for block coords."
     },
     {
      "detail": "Ternary num<min?min:num>max?max:num. Timer uses it to clamp frame delta 0-1. Also used for health, progress, and deltas.",
      "name": "clamp_double",
      "packets": [],
      "purpose": "Constrains value to [min,max] range."
     },
     {
      "detail": "Applies %360 then subtracts 360 if >=180, adds if <-180. Double variant identical. Critical for S08/C03 look deltas.",
      "name": "wrapAngleTo180_float",
      "packets": [],
      "purpose": "Normalizes yaw to [-180,180) degrees."
     },
     {
      "detail": "Returns (int)(value>=0?value:-value+1). Used for entity size and bounding computations. Avoids float rounding edge cases.",
      "name": "func_154353_e",
      "packets": [],
      "purpose": "Ceil of absolute value for packet size math."
     },
     {
      "detail": "Formula p<0?-((-p-1)/size)-1:p/size. Ensures -1..-16 maps to chunk -1. Used for chunk lookup from block pos.",
      "name": "bucketInt",
      "packets": [],
      "purpose": "Floor division bucket for negative chunk coords."
     },
     {
      "detail": "Rounds up to power of two then De Bruijn multiply 125613361>>27 lookup. Subtracts 1 if not power of two. BlockPos uses it for NUM_X_BITS.",
      "name": "calculateLogBaseTwo",
      "packets": [],
      "purpose": "Floor log2 via De Bruijn sequence for bit packing."
     }
    ],
    "overview": "Static math utility in net.minecraft.util used by entities, rendering, and packets. Provides sin table, floor, clamp, angle wrap, and noise helpers. Matters for packets because movement yaw/pitch, positions, and chunk math all normalize through it.",
    "packet_usage": [],
    "peers": [
     "BlockPos",
     "Timer",
     "Vec3i",
     "AxisAlignedBB"
    ]
   }
  },
  {
   "slug": "BlockPos",
   "title": "BlockPos",
   "rel": "net/minecraft/util/BlockPos.java",
   "desc": "Immutable integer position with MutableBlockPos for hot loops, packing, offsets and box iteration.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/BlockPos/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/util/BlockPos.java",
   "packets": [],
   "peers": [
    "MathHelper",
    "Entity",
    "PacketBuffer"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "ORIGIN",
      "role": "Shared zero position constant"
     },
     {
      "name": "NUM_X_BITS",
      "role": "26 bits for X derived from 30M world border"
     },
     {
      "name": "NUM_Y_BITS",
      "role": "12 bits for Y height range"
     },
     {
      "name": "X_SHIFT",
      "role": "Bit shift for X field in packed long"
     },
     {
      "name": "Y_SHIFT",
      "role": "Bit shift for Y field in packed long"
     },
     {
      "name": "MutableBlockPos",
      "role": "Mutable subclass for allocation-free loops"
     }
    ],
    "methods": [
     {
      "detail": "Layout X 26 bits shifted X_SHIFT, Y 12 bits shifted Y_SHIFT, Z 26 bits. Masks with X_MASK/Y_MASK/Z_MASK. Written by PacketBuffer.writeBlockPos.",
      "name": "toLong",
      "packets": [],
      "purpose": "Packs x,y,z into one 64-bit long for wire."
     },
     {
      "detail": "Sign-extending shifts: (serialized<<(64-shift-bits))>>(64-bits). Reconstructs negative coords correctly. Read path for block packets.",
      "name": "fromLong",
      "packets": [],
      "purpose": "Unpacks long back into signed x,y,z."
     },
     {
      "detail": "Adds facing offsets times n to x,y,z. Returns this if n==0. Basis for up/down/north/south/east/west helpers.",
      "name": "offset",
      "packets": [],
      "purpose": "Returns pos shifted n blocks along EnumFacing."
     },
     {
      "detail": "Returns this if delta is zero to avoid allocation. Double variant floors via Vec3i. Used for movement and collision stepping.",
      "name": "add",
      "packets": [],
      "purpose": "Adds int, double, or Vec3i delta returning new pos."
     },
     {
      "detail": "Formula (y1*z2-z1*y2, z1*x2-x1*z2, x1*y2-y1*x2). Used for orientation and normal math. Returns new instance.",
      "name": "crossProduct",
      "packets": [],
      "purpose": "Computes vector cross product as BlockPos."
     },
     {
      "detail": "Normalizes min/max corners. Guava AbstractIterator stepping x then y then z. Used for block scans and multi-block change.",
      "name": "getAllInBox",
      "packets": [],
      "purpose": "Iterates all immutable positions in cuboid."
     },
     {
      "detail": "Avoids allocation by mutating x,y,z fields. Same x-y-z carry order. Preferred for tight collision and lighting loops.",
      "name": "getAllInBoxMutable",
      "packets": [],
      "purpose": "Same cuboid scan reusing one MutableBlockPos."
     },
     {
      "detail": "Sets x,y,z fields and returns this. Overrides immutable getters to read mutable fields. Used in iteration hot paths.",
      "name": "MutableBlockPos.set",
      "packets": [],
      "purpose": "Mutates reusable pos without allocation."
     }
    ],
    "overview": "Immutable integer position extending Vec3i in net.minecraft.util. Created from entities, Vec3, and packet longs. Matters for packets because block dig, place, and change packets carry it as a single packed long.",
    "packet_usage": [],
    "peers": [
     "Vec3i",
     "Vec3",
     "EnumFacing",
     "MathHelper",
     "PacketBuffer",
     "Entity"
    ]
   }
  },
  {
   "slug": "AxisAlignedBB",
   "title": "AxisAlignedBB",
   "rel": "net/minecraft/util/AxisAlignedBB.java",
   "desc": "Immutable collision box: offsets, expansion, axis sweep resolvers and ray intercept used by moveEntity.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/AxisAlignedBB/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/util/AxisAlignedBB.java",
   "packets": [],
   "peers": [
    "BlockPos",
    "Entity"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "minX",
      "role": "Minimum X corner of box"
     },
     {
      "name": "minY",
      "role": "Minimum Y corner of box"
     },
     {
      "name": "minZ",
      "role": "Minimum Z corner of box"
     },
     {
      "name": "maxX",
      "role": "Maximum X corner of box"
     },
     {
      "name": "maxY",
      "role": "Maximum Y corner of box"
     },
     {
      "name": "maxZ",
      "role": "Maximum Z corner of box"
     }
    ],
    "methods": [
     {
      "detail": "If x<0 minX+=x else maxX+=x, same for y,z. Returns new box. Predicts occupied volume before axis-separated clipping.",
      "name": "addCoord",
      "packets": [],
      "purpose": "Sweeps box along motion vector for collision broadphase."
     },
     {
      "detail": "min-=x and max+=x per axis. Negative input shrinks. Used for entity search radii and render culling inflation.",
      "name": "expand",
      "packets": [],
      "purpose": "Grows box symmetrically on all sides."
     },
     {
      "detail": "min+=x and max-=x per axis. Used to test sneaking and suffocation with smaller footprint. Returns new box.",
      "name": "contract",
      "packets": [],
      "purpose": "Shrinks box symmetrically for stuck checks."
     },
     {
      "detail": "Requires other.maxY>minY etc. If offsetX>0 uses minX-other.maxX, if <0 uses maxX-other.minX. Keeps closer-to-zero value.",
      "name": "calculateXOffset",
      "packets": [],
      "purpose": "Clips X motion against this box if YZ overlap."
     },
     {
      "detail": "Same pattern on XZ overlap. Positive uses minY-other.maxY, negative uses maxY-other.minY. Core of gravity and step logic.",
      "name": "calculateYOffset",
      "packets": [],
      "purpose": "Clips Y motion, handles landing and ceilings."
     },
     {
      "detail": "Mirrors X/Y logic on Z axis. Prevents tunneling through walls. Chained with X and Y passes in moveEntity.",
      "name": "calculateZOffset",
      "packets": [],
      "purpose": "Clips Z motion if XY overlap."
     },
     {
      "detail": "Uses > and < so touching faces do not count. Short-circuit ternary chain. Used for entity-entity and block push checks.",
      "name": "intersectsWith",
      "packets": [],
      "purpose": "Tests strict overlap on all three axes."
     },
     {
      "detail": "Computes intermediate points per face, discards via isVecInYZ/XZ/XY, picks nearest by squareDistanceTo. Returns MovingObjectPosition with EnumFacing.",
      "name": "calculateIntercept",
      "packets": [],
      "purpose": "Ray-traces segment against six box planes."
     }
    ],
    "overview": "Immutable double collision box in net.minecraft.util with min/max corners. Used by Entity.moveEntity for collision clipping and ray traces. Matters for movement because server validates player positions against contracted and offset boxes.",
    "packet_usage": [],
    "peers": [
     "BlockPos",
     "Vec3",
     "EnumFacing",
     "MovingObjectPosition",
     "Entity"
    ]
   }
  },
  {
   "slug": "Entity",
   "title": "Entity",
   "rel": "net/minecraft/entity/Entity.java",
   "desc": "Root of all entities: public pos/motion/rotation fields, moveEntity collision, DataWatcher flags, NBT persistence.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/Entity/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/Entity.java",
   "packets": [],
   "peers": [
    "EntityPlayerMP",
    "WorldServer",
    "EntityLivingBase",
    "MathHelper",
    "BlockPos",
    "AxisAlignedBB",
    "EntityPlayer",
    "World"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "dataWatcher",
      "role": "Watched indices 0-4 for flags, air, name, silent; syncs metadata"
     },
     {
      "name": "boundingBox",
      "role": "Current AABB used for collision and render culling"
     },
     {
      "name": "posX/posY/posZ + motion",
      "role": "Authoritative kinematics replicated by tracker packets"
     },
     {
      "name": "entityId",
      "role": "Runtime numeric ID used in spawn and entity packets"
     },
     {
      "name": "ridingEntity/riddenByEntity",
      "role": "Vehicle chain driving attach packets and position updates"
     }
    ],
    "methods": [
     {
      "detail": "Queries World.getCollidingBoundingBoxes per axis, applies step-up logic, sneak edge handling, and fall callbacks. Sets motion to zero on impact. Basis for S14/S18 movement.",
      "name": "moveEntity",
      "packets": [],
      "purpose": "Collision-resolves displacement and updates onGround and flags."
     },
     {
      "detail": "Handles portal countdown and travelToDimension, fire decay and damage, lava ignition, void kill, and DataWatcher burning flag sync. Calls water and sprint particles.",
      "name": "onEntityUpdate",
      "packets": [],
      "purpose": "Per-tick base logic for portal, fire, lava, and flags."
     },
     {
      "detail": "Centers box on x/z with full height. Used by spawn, teleport, and NBT load. Does not perform collision checks.",
      "name": "setPosition",
      "packets": [],
      "purpose": "Sets pos and rebuilds AABB from width/height."
     },
     {
      "detail": "Builds eye pos and look vector then calls World.rayTraceBlocks with returnLastUncollidable true. Used for block targeting.",
      "name": "rayTrace",
      "packets": [],
      "purpose": "Eye-to-look block raycast for interaction reach."
     },
     {
      "detail": "Writes Pos/Motion/Rotation lists plus Dimension, CustomName, Silent, and nested Riding tag. Calls abstract writeEntityToNBT. Basis for chunk save.",
      "name": "writeToNBT",
      "packets": [],
      "purpose": "Serializes pos, motion, rotation, fire, UUID, and rider."
     },
     {
      "detail": "Clamps motion, restores pos/rotation, UUID variants, name visibility, and silent flag. Calls readEntityFromNBT then repositions. Used on chunk load.",
      "name": "readFromNBT",
      "packets": [],
      "purpose": "Restores entity state and re-establishes bounding box."
     },
     {
      "detail": "Clears deltas, breaks old riddenBy links, prevents cycles, sets ridingEntity/riddenByEntity pair. Server broadcasts via S1B attach.",
      "name": "mountEntity",
      "packets": [],
      "purpose": "Attaches or detaches rider/vehicle links."
     },
     {
      "detail": "Bit operations on index 0; isBurning, isSneaking, isSprinting read through it. Watched index 0 syncs via S1C metadata.",
      "name": "getFlag/setFlag",
      "packets": [],
      "purpose": "Packs burning/sneak/ride/sprint/eat/invisible into DataWatcher byte 0."
     }
    ],
    "overview": "Base class for all world objects with position, motion, bounding box, and DataWatcher flags. Implements collision-resolved moveEntity, portal/fire/water ticks, riding, NBT save/load, and eye/look ray helpers. Server tracks pos/motion for spawn and delta packets; client interpolates via setPositionAndRotation2.",
    "packet_usage": [],
    "peers": [
     "World",
     "DataWatcher",
     "AxisAlignedBB",
     "NBTTagCompound",
     "EntityPlayer",
     "DamageSource",
     "Vec3",
     "MovingObjectPosition"
    ]
   }
  },
  {
   "slug": "EntityPlayer",
   "title": "EntityPlayer",
   "rel": "net/minecraft/entity/player/EntityPlayer.java",
   "desc": "Shared player base: inventory, food, capabilities, sleep, XP, attack pipeline inherited by SP and MP.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/EntityPlayer/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/player/EntityPlayer.java",
   "packets": [
    "S12PacketEntityVelocity"
   ],
   "peers": [
    "EntityPlayerSP",
    "EntityPlayerMP",
    "EntityLivingBase",
    "MathHelper",
    "BlockPos",
    "AxisAlignedBB",
    "Entity",
    "World",
    "Container"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "inventory/openContainer",
      "role": "Main inventory plus active window driving slot packets"
     },
     {
      "name": "foodStats",
      "role": "Hunger/exhaustion ticked server-side, synced via health packet"
     },
     {
      "name": "experience/Level/Total",
      "role": "XP bar state synced via S1F set experience"
     },
     {
      "name": "sleeping/playerLocation",
      "role": "Bed occupancy driving S0A use-bed broadcast"
     },
     {
      "name": "capabilities",
      "role": "Fly/speed/edit flags synced via abilities packet"
     }
    ],
    "methods": [
     {
      "detail": "Decrements itemInUseCount to onItemUseFinish, advances sleepTimer, updates FoodStats server-side, clamps world border, closes invalid openContainer.",
      "name": "onUpdate",
      "packets": [],
      "purpose": "Ticks item use, sleep, food, stats, and container validity."
     },
     {
      "detail": "Computes attackDamage plus enchant modifier, crit multiplier, knockback and fire aspect. Calls attackEntityFrom, sends S12 velocity sync for MP victims, applies thorns and stats.",
      "name": "attackTargetEntityWithCurrentItem",
      "packets": [
       "S12"
      ],
      "purpose": "Melee pipeline for damage, knockback, fire, and durability."
     },
     {
      "detail": "Respects creative disableDamage, wakes sleeper, scales by difficulty, halves blocked damage, applies armor/potion/absorption then health and exhaustion.",
      "name": "attackEntityFrom/damageEntity",
      "packets": [],
      "purpose": "Applies difficulty scaling, blocking, armor, and potion reduction."
     },
     {
      "detail": "Checks dimension, daytime, distance, and nearby mobs; shrinks box and positions in bed. Wake restores size, clears occupied flag, optionally sets spawn. Maps to S0A bed.",
      "name": "trySleep/wakeUpPlayer",
      "packets": [],
      "purpose": "Validates bed use and manages sleep state and spawn."
     },
     {
      "detail": "Plays drink/eat sounds, spawns ITEM_CRACK particles, calls onItemUseFinish to replace held stack and clear itemInUse. Status 9 mirrors it client-side.",
      "name": "onItemUseFinish/updateItemUse",
      "packets": [],
      "purpose": "Completes eating/drinking and spawns consumption particles."
     },
     {
      "detail": "Adds score, converts amount via xpBarCap thresholds 7/37/112 formulas, loops level-ups with levelup sound. Server pushes via S1F experience.",
      "name": "addExperience/xpBarCap",
      "packets": [],
      "purpose": "Accumulates XP and levels with cap curve."
     },
     {
      "detail": "Offsets from eye height, sets motion from yaw/pitch plus randomness, sets thrower for stats. World.spawnEntityInWorld replicates via S0E.",
      "name": "dropItem/joinEntityItemWithWorld",
      "packets": [],
      "purpose": "Spawns EntityItem with throw physics and pickup delay."
     },
     {
      "detail": "Stores Inventory list, SelectedItemSlot, Sleeping/SleepTimer, XpP/Level/Total/Seed, Score, SpawnXYZ, FoodStats, capabilities, EnderItems. Restores on login/respawn.",
      "name": "readEntityFromNBT/writeEntityToNBT",
      "packets": [],
      "purpose": "Persists inventory, XP, spawn, food, and ender chest."
     }
    ],
    "overview": "Living player with inventory, ender chest, food, XP, sleep, and combat state. Extends EntityLivingBase with DataWatcher skin/score/absorption fields. Implements item use, attack pipeline with enchant/crit/knockback, bed logic, NBT persistence, and score/team helpers.",
    "packet_usage": [
     {
      "direction": "sent",
      "id": "S12",
      "trigger": "Melee knockback on EntityPlayerMP victim; restores motion after velocity packet"
     }
    ],
    "peers": [
     "InventoryPlayer",
     "Container",
     "FoodStats",
     "World",
     "EntityLivingBase",
     "Scoreboard",
     "ItemStack",
     "EntityPlayerMP"
    ]
   }
  },
  {
   "slug": "World",
   "title": "World",
   "rel": "net/minecraft/world/World.java",
   "desc": "Abstract world: block read/write, raytrace, entity/AABB queries, spawning, weather, scoreboard and border access.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/World/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/world/World.java",
   "packets": [],
   "peers": [
    "MathHelper",
    "BlockPos",
    "AxisAlignedBB",
    "Entity",
    "EntityPlayer",
    "WorldServer"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "loadedEntityList/playerEntities",
      "role": "Ticked entities and player subset for queries and sleep"
     },
     {
      "name": "chunkProvider",
      "role": "Chunk source backing block, light, and entity storage"
     },
     {
      "name": "worldAccesses",
      "role": "Listeners receiving block, sound, particle, entity events"
     },
     {
      "name": "isRemote",
      "role": "Client vs server branch for logic and packet fan-out"
     },
     {
      "name": "worldInfo/worldBorder",
      "role": "Time, spawn, rules, and border constraining validity"
     }
    ],
    "methods": [
     {
      "detail": "Validates coords, delegates to Chunk, handles light check, markBlockForUpdate for render, and neighbor/comparator updates. Flags control notify vs client sync. Basis for S22/S23.",
      "name": "getBlockState/setBlockState",
      "packets": [],
      "purpose": "Chunk-backed block read and flagged write path."
     },
     {
      "detail": "Steps grid up to 200 iterations honoring stopOnLiquid and bounding-box flags. Calls Block.collisionRayTrace per cell. Used by Entity.rayTrace and interaction.",
      "name": "rayTraceBlocks",
      "packets": [],
      "purpose": "DDA voxel traversal returning block hit or miss."
     },
     {
      "detail": "Iterates block range with border checks, adds block collision boxes, then nearby entity boxes. Feeds Entity.moveEntity resolution.",
      "name": "getCollidingBoundingBoxes",
      "packets": [],
      "purpose": "Collects block plus entity boxes intersecting an AABB."
     },
     {
      "detail": "Expands chunk range by margin, delegates to Chunk.getEntitiesWithinAABBForEntity. Powers collision, combat targeting, and sleep safety checks.",
      "name": "getEntitiesWithinAABBExcludingEntity",
      "packets": [],
      "purpose": "Chunk-scoped entity query with spectator filter."
     },
     {
      "detail": "Validates chunk loaded, adds players to playerEntities, links chunk and calls onEntityAdded/Removed for render/tracker hooks. Backs S0E/S13.",
      "name": "spawnEntityInWorld/removeEntity",
      "packets": [],
      "purpose": "Registers and unregisters entities with chunks and lists."
     },
     {
      "detail": "Handles riding consistency, NaN guards, chunk migration, dead removal, and ITickable tiles. Called each world tick before block ticks.",
      "name": "updateEntities/updateEntity",
      "packets": [],
      "purpose": "Ticks weather effects, entities, and tile entities."
     },
     {
      "detail": "Iterates IWorldAccess for playSound, playRecord, broadcastSound, aux SFX, and particle IDs. Server listeners convert to S29/S2A; client renders directly.",
      "name": "playSoundAtEntity/spawnParticle",
      "packets": [],
      "purpose": "Fans out audible and visual effects to world accesses."
     },
     {
      "detail": "Base World is no-op; WorldServer overrides to send S19 entity status and S24 block action to trackers. Comment notes legacy Packet 38.",
      "name": "setEntityState/addBlockEvent",
      "packets": [],
      "purpose": "Hooks for entity status and block animation events."
     }
    ],
    "overview": "Abstract block/entity store and simulation hub for server and client. Provides chunk-backed block access, DDA rayTraceBlocks, AABB entity queries, collision lists, and sound/particle fan-out to IWorldAccess. Owns entity/tile tick loops, light, weather, and save metadata.",
    "packet_usage": [],
    "peers": [
     "Chunk",
     "IChunkProvider",
     "Entity",
     "TileEntity",
     "IWorldAccess",
     "BlockPos",
     "AxisAlignedBB",
     "WorldServer",
     "WorldClient"
    ]
   }
  },
  {
   "slug": "Container",
   "title": "Container",
   "rel": "net/minecraft/inventory/Container.java",
   "desc": "GUI inventory model: Slot views, slotClick prediction, transaction IDs, shift-click merge driving C0E/S32.",
   "url": "https://mc-packet-reference.netlify.app/1.8.9/classes/Container/",
   "source_url": "https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/inventory/Container.java",
   "packets": [],
   "peers": [
    "MathHelper",
    "EntityPlayer"
   ],
   "analysis": {
    "internal_fields": [
     {
      "name": "inventorySlots",
      "role": "Ordered Slot models mapping window slot IDs to inventories"
     },
     {
      "name": "inventoryItemStacks",
      "role": "Last-sent snapshot for change detection"
     },
     {
      "name": "crafters",
      "role": "ICrafting viewers receiving slot and progress updates"
     },
     {
      "name": "dragSlots",
      "role": "Slots collected during mode-5 drag-split gesture"
     },
     {
      "name": "windowId",
      "role": "Window identifier multiplexing client/server containers"
     }
    ],
    "methods": [
     {
      "detail": "Handles pickup/place, shift transfer, hotbar swap, creative clone, drop, and double-click merge. Mode 5 manages dragEvent state machine. Server calls it from C0E click processing.",
      "name": "slotClick",
      "packets": [],
      "purpose": "Implements all window click modes 0-6 including drag-split."
     },
     {
      "detail": "Compares each Slot stack with inventoryItemStacks via areItemStacksEqual. On change copies stack and calls ICrafting.sendSlotContents. Drives S2F and S30 updates.",
      "name": "detectAndSendChanges",
      "packets": [],
      "purpose": "Diffs slots against snapshots and notifies crafting listeners."
     },
     {
      "detail": "Base returns slot stack; subclasses implement mergeItemStack ranges. Result determines what server sends back to client window.",
      "name": "transferStackInSlot",
      "packets": [],
      "purpose": "Shift-click quick-move hook overridden by subclasses."
     },
     {
      "detail": "First pass stacks onto same item/tag, second pass fills empty slots. Honors max stack size and direction flag. Core of shift-click behavior.",
      "name": "mergeItemStack",
      "packets": [],
      "purpose": "Merges stack into slot range respecting stackability and limits."
     },
     {
      "detail": "Adds ICrafting listener, calls updateCraftingInventory with getInventory, then detectAndSendChanges. Maps to S2D open plus S30 bulk.",
      "name": "onCraftGuiOpened",
      "packets": [],
      "purpose": "Registers a viewer and syncs full inventory initially."
     },
     {
      "detail": "If InventoryPlayer cursor stack non-null, drops via dropPlayerItemWithRandomChoice and clears. Prevents item duplication on close.",
      "name": "onContainerClosed",
      "packets": [],
      "purpose": "Drops held cursor stack when window closes."
     },
     {
      "detail": "Increments transactionID counter. NetHandlerPlayServer echoes it in S32 confirm; client C0F uses it for resync.",
      "name": "getNextTransactionID",
      "packets": [],
      "purpose": "Allocates short action number for click confirmations."
     },
     {
      "detail": "Subclasses check block distance or entity liveness. EntityPlayer.onUpdate closes screen when false. Triggers S2E close.",
      "name": "canInteractWith",
      "packets": [],
      "purpose": "Abstract distance/validity check for open window."
     }
    ],
    "overview": "Abstract server-side model for window inventories like chests, furnaces, and player inventory. Owns Slot list, item-stack snapshots, drag state, and ICrafting listeners. Implements full click/drag/shift-click/number-key/drop logic in slotClick. Change detection fans out via detectAndSendChanges.",
    "packet_usage": [],
    "peers": [
     "Slot",
     "ICrafting",
     "InventoryPlayer",
     "EntityPlayer",
     "ItemStack",
     "IInventory"
    ]
   }
  }
 ]
}