Files
2026-02-18 07:08:49 -05:00

22 KiB

Client Fixes for World Systems Update

This document covers all client-side changes needed for the world overhaul: Z-levels, world mobs/NPCs, combat, object interaction, and portal updates.


1. Breaking Changes

1.1 Chunk Key Format (6-part, was 5-part)

All chunk keys now include zoneZ:

OLD: "{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}"
NEW: "{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}"

Update any client-side chunk key parsing/caching to expect the 6-segment format.

1.2 WORLD_STATE (711) - New Fields

The per-tick WORLD_STATE payload now includes mobs and npcs arrays. These are null when no zone simulation is active, so guard against null.

{
  "tick": 1234,
  "ackSeq": 42,
  "self": {
    "x": 1024.5, "y": 512.3,
    "velocityX": 120.0, "velocityY": 0.0,
    "regionId": 1,
    "zoneX": 0, "zoneY": 0,
    "zoneZ": 0,                                   // NEW - current Z-level
    "chunkX": 5, "chunkY": 3,
    "isPvp": false                                 // NEW - true if zone is PvP-enabled
  },
  "players": [ ... ],
  "mobs": [                                     // NEW - nullable
    {
      "id": 1,
      "definitionId": 101,
      "name": "Goblin",
      "x": 800.0, "y": 400.0,
      "health": 45, "maxHealth": 100,
      "isAlive": true,
      "state": "Idle",                           // "Idle","Chasing","Attacking","Dead"
      "animation": "idle_down",
      "facing": "down",
      "spriteConfig": "{...}",
      "tintColor": "#ffffff",
      "scale": 1.0
    }
  ],
  "npcs": [                                      // NEW - nullable
    {
      "id": 1,
      "definitionId": 5,
      "name": "Village Elder",
      "x": 1200.0, "y": 600.0,
      "health": 100, "maxHealth": 100,
      "isAlive": true,
      "canShop": true,
      "hasDialog": true,
      "animation": "idle",
      "spriteConfig": "{...}",
      "tintColor": "#ffffff",
      "scale": 1.0
    }
  ],
  "chunkUpdates": [ ... ],
  "portalEvent": { ... },
  "errors": [ ... ]
}

Mob/NPC arrays contain all entities within 1536px (48 tiles) of the player, same Z-level only. Render mobs and NPCs from these arrays every tick. Dead mobs (isAlive: false) should show death animation and remain for looting.

1.3 Chunk Payload - zoneZ Added

Every chunk payload now includes zoneZ in its chunk object:

{
  "type": "chunk_full",
  "chunk": {
    "regionId": 1,
    "zoneX": 0, "zoneY": 0,
    "zoneZ": 0,                                  // NEW
    "chunkX": 5, "chunkY": 3,
    "version": 12345,
    "width": 20, "height": 20
  },
  "tiles": [ ... ],
  "objects": [ ... ],
  "npcs": [ ... ],
  "mobs": [ ... ]
}

1.4 Visible Players Filtered by Z-Level

Players on different Z-levels are no longer visible to each other. The server already handles this -- the client just needs to be aware that entering a building (Z-level change) will make other ground-level players disappear.


2. New OpCodes

OpCode Constant Direction Purpose
720 WORLD_COMBAT_STATE S -> C Combat events broadcast
721 WORLD_ATTACK C -> S Player attacks mob or player
722 WORLD_MOB_LOOT_REQUEST C -> S Loot a dead mob
723 WORLD_MOB_LOOT_RESULT S -> C Loot contents
724 WORLD_RESPAWN_REQUEST C -> S Request respawn after death
725 WORLD_RESPAWN_RESULT S -> C Respawn result + new position
740 WORLD_NPC_INTERACT C -> S Start NPC interaction
741 WORLD_NPC_INTERACT_STATE S -> C NPC metadata + dialog/shop state
742 WORLD_NPC_DIALOG_SELECT C -> S Choose a dialog option
743 WORLD_NPC_DIALOG_RESULT S -> C Dialog option outcome
744 WORLD_NPC_SHOP_ACTION C -> S Buy/sell from NPC shop
745 WORLD_NPC_SHOP_RESULT S -> C Shop transaction result
750 WORLD_OBJECT_INTERACT C -> S Interact with world object
751 WORLD_OBJECT_INTERACT_RESULT S -> C Object interaction result
752 WORLD_OBJECT_STATE S -> C Object state broadcast (broken)

3. Combat System

3.1 Sending an Attack (721 WORLD_ATTACK) C -> S

{
  "targetType": "mob",             // "mob" or "player"
  "targetMobId": 1,                // required when targetType = "mob"
  "targetPlayerId": 67890          // required when targetType = "player"
}
  • Server validates: alive, not stunned, within 80px melee range.
  • PvP attacks are rejected unless the zone has IsPvpEnabled = true.

3.2 Combat Events (720 WORLD_COMBAT_STATE) S -> C

Sent to all players in the zone when combat occurs. Contains an events array. Each event has a type string field.

{
  "events": [
    {
      "type": "PlayerAttack",
      "sourcePlayerId": 12345,
      "targetMobId": 1,
      "damage": 45,
      "damageTypeKey": "physical",
      "x": 800.0, "y": 400.0,
      "wasResisted": false,
      "wasWeakness": true
    }
  ]
}

Event types from player-initiated combat (WorldHandler.Combat.cs):

type Fields When
PlayerAttack sourcePlayerId, targetMobId, damage, damageTypeKey, x, y, wasResisted, wasWeakness Player hits mob
MobDeath targetMobId, sourcePlayerId, x, y, xpReward, lootAvailable Mob killed
PvpDamage sourcePlayerId, targetPlayerId, damage, damageTypeKey, x, y Player hits player (PvP)
PlayerDeath targetPlayerId, sourcePlayerId, x, y, isPvpKill Player killed (PvP)
AttackFailed error Attack rejected
PlayerRespawn targetPlayerId, x, y Player respawned (broadcast to others)

AttackFailed error values: "stunned", "dead", "target_not_found", "out_of_range", "pvp_disabled_in_zone", "target_invulnerable"

Event types from zone simulation ticks (WorldZoneSimulation.cs via BroadcastCombatEventsAsync):

type Fields When
Damage sourceMobId, targetPlayerId, damage, damageTypeKey, x, y Mob hits player
MobDeath targetMobId, sourcePlayerId, x, y Mob dies from AI tick
PlayerDeath targetPlayerId, x, y Player killed by mob
MobSpawn targetMobId, x, y, mobData (full mob serialize object) Mob respawned
ProjectileSpawn sourceMobId, x, y Mob fires projectile
AbilityUsed sourceMobId, targetPlayerId, damage, damageTypeKey, x, y Mob uses ability

Note: Zone-tick events use the generic serialization format:

{
  "type": "Damage",
  "sourceMobId": 2,
  "sourcePlayerId": 0,
  "targetMobId": 0,
  "targetPlayerId": 12345,
  "damage": 25,
  "damageTypeKey": "fire",
  "x": 1024.0, "y": 512.0,
  "mobData": null
}

The client should handle both formats -- direct combat events from WorldHandler.Combat.cs (only the relevant fields) and zone-broadcast events (all fields present, irrelevant ones zeroed/null).

3.3 Mob Looting (722/723) C -> S / S -> C

Request (722 WORLD_MOB_LOOT_REQUEST):

{ "mobId": 1 }

Server validates: mob is dead, within 128px, exists.

Response (723 WORLD_MOB_LOOT_RESULT):

{
  "success": true,
  "mobId": 1,
  "gold": 75,
  "items": [
    {
      "itemDefinitionId": 42,
      "itemName": "Healing Potion",
      "quantity": 2
    }
  ]
}

Error cases: "mob_not_found", "mob_still_alive", "too_far"

Loot is generated from mob loot tables via LootService. Gold uses the loot table's gold drop, or falls back to XpReward / 2. Items are added to the player's inventory server-side automatically. The client should display the loot popup to confirm what was received.

3.4 Death and Respawn (724/725) C -> S / S -> C

When a player dies (from mob or PvP), a PlayerDeath event is broadcast. The dead player cannot move or attack. To respawn, the client sends:

Request (724 WORLD_RESPAWN_REQUEST):

{}

No payload needed (server knows who is requesting from the connection).

Response (725 WORLD_RESPAWN_RESULT):

{
  "success": true,
  "x": 1024.0,
  "y": 512.0,
  "health": 100,
  "maxHealth": 100,
  "invulnerableSeconds": 3.0
}

On respawn:

  • Player teleports to zone spawn point (center of chunk 0,0 in current zone).
  • Health is fully restored.
  • 3-second invulnerability (immune to all damage).
  • All status effects (stuns, roots, DOTs) are cleared.
  • No item or XP loss (overworld is less punishing than dungeon).
  • TotalDeaths counter incremented server-side.
  • A PlayerRespawn event is broadcast to other players in the zone.

Error cases: "not_dead" (player is still alive)

The client should:

  • Show death screen / overlay when receiving PlayerDeath event
  • Show "Respawn" button
  • On click, send WORLD_RESPAWN_REQUEST (724)
  • On success, move player to new x/y, restore health bar
  • Show invulnerability visual (shield/glow) for invulnerableSeconds
  • Handle PlayerRespawn events for other players (teleport their sprite)

4. NPC Interaction System

4.1 Starting NPC Interaction (740/741)

Request (740 WORLD_NPC_INTERACT):

{ "npcId": 1 }

Server validates: NPC exists in zone sim, within 128px.

Response (741 WORLD_NPC_INTERACT_STATE):

The server sends NPC metadata, and then auto-sends dialog and/or shop state if the NPC supports them. All arrive on opcode 741.

{
  "success": true,
  "npc": {
    "id": 1,
    "definitionId": 5,
    "name": "Village Elder",
    "canShop": true,
    "hasDialog": true,
    "isKillable": false,
    "behavior": "passive",
    "onAttackBehavior": "flee",
    "shopId": 10,
    "dialogTreeId": 25
  }
}

If hasDialog && dialogTreeId != null, a follow-up 741 arrives with dialog:

{
  "success": true,
  "npcId": 1,
  "dialogNode": {
    "id": 100,
    "text": "Hello traveler! What brings you here?",
    "isTerminal": false,
    "rewardGold": 0,
    "rewardXp": 0,
    "rewardItemDefinitionId": null,
    "rewardItemQuantity": 0
  },
  "options": [
    { "id": 200, "text": "Tell me about yourself", "nextNodeId": 101 },
    { "id": 201, "text": "I'm looking for work", "nextNodeId": 102 }
  ]
}

If canShop && shopId != null, a follow-up 741 arrives with shop:

{
  "success": true,
  "shop": {
    "id": 10,
    "name": "General Store",
    "items": [
      {
        "slotIndex": 0,
        "itemDefinitionId": 42,
        "itemName": "Healing Potion",
        "quantity": 10,
        "priceGold": 50,
        "restocks": true,
        "restockIntervalSeconds": 3600
      }
    ]
  }
}

Error cases on 741: "npc_not_found", "too_far"

4.2 Selecting a Dialog Option (742/743)

Request (742 WORLD_NPC_DIALOG_SELECT):

{ "npcId": 1, "optionId": 200 }

Response (743 WORLD_NPC_DIALOG_RESULT):

{
  "success": true,
  "npcId": 1,
  "nextNodeId": 101,
  "isTerminal": false
}

On success, the server also sends the next dialog node on opcode 741 (same as initial dialog state), so the client should update the dialog UI when it gets a new 741 with dialogNode.

If the selected option has rewards (gold, XP, items), they are applied server-side automatically when the next node loads. The client should display the rewardGold/rewardXp/rewardItemDefinitionId fields from the dialogNode in the follow-up 741 to show the player what they received.

If the option required consuming items (e.g. quest turn-in), those are deducted server-side as well. On "condition_failed" error, the option's prerequisite is not met.

Error cases on 743: "npc_dialog_unavailable", "invalid_option", "condition_failed", "requires_item", "level_too_low", "level_too_high", "not_enough_gold"

4.3 Buying from a Shop (744/745)

Request (744 WORLD_NPC_SHOP_ACTION):

{
  "npcId": 1,
  "action": "buy",
  "slotIndex": 0,
  "quantity": 1
}

Response (745 WORLD_NPC_SHOP_RESULT):

{
  "success": true,
  "npcId": 1,
  "action": "buy",
  "itemDefinitionId": 42,
  "quantity": 1,
  "totalPrice": 50,
  "remainingGold": 450,
  "remainingStock": 9
}

On success, the server also re-sends the full shop state on opcode 741 (shop object) with updated quantities.

Error cases on 745: "npc_shop_unavailable", "unsupported_shop_action", "shop_item_not_found", "out_of_stock", "character_not_found", "not_enough_gold" (includes requiredGold + currentGold), "inventory_full"

4.4 Selling to a Shop (744/745)

Request (744 WORLD_NPC_SHOP_ACTION):

{
  "npcId": 1,
  "action": "sell",
  "slotIndex": 3,
  "quantity": 1
}

slotIndex refers to the player's inventory slot (0-29), not the shop slot.

Response (745 WORLD_NPC_SHOP_RESULT):

{
  "success": true,
  "npcId": 1,
  "action": "sell",
  "itemDefinitionId": 15,
  "quantity": 1,
  "totalPrice": 12,
  "remainingGold": 512
}

Sell price is 25% of the shop's buy price for that item (if the shop sells it), otherwise a base price heuristic (requiredLevel * 2). Items are removed from inventory server-side. Equipped items cannot be sold (only unequipped inventory items).

Error cases: "item_not_found", "character_not_found"


5. World Object Interaction

5.1 Interacting with an Object (750/751)

Request (750 WORLD_OBJECT_INTERACT):

{
  "objectId": 999,
  "action": "interact"
}

action values: "interact" (default), "break" (for destructibles), "loot" (for containers).

Server validates: object exists in DB, within 128px.

Response (751 WORLD_OBJECT_INTERACT_RESULT):

Response shape varies by object type:

Destructible object (when action = "break" and IsDestructible = true):

{
  "success": true,
  "objectId": 999,
  "type": "break",
  "gold": 25,
  "items": []
}

Container / OpenContainer (lootable):

{
  "success": true,
  "objectId": 999,
  "type": "loot",
  "gold": 50,
  "items": []
}

Trigger (readable signs, plaques, etc.):

{
  "success": true,
  "objectId": 999,
  "type": "readable",
  "name": "Weathered Sign",
  "text": "Danger ahead!"
}

Teleport (handled by movement system, not this handler):

{
  "success": true,
  "objectId": 999,
  "type": "teleport",
  "message": "Portal triggered by movement."
}

Generic / unhandled types:

{
  "success": true,
  "objectId": 999,
  "type": "heal",
  "name": "Healing Shrine",
  "metadataJson": "{...}"
}

Error cases on 751: "object_not_found", "object_chunk_not_found", "too_far"

5.2 Object State Broadcast (752 WORLD_OBJECT_STATE) S -> C

Broadcast to all players in the zone when an object's state changes (e.g. a destructible is broken):

{
  "objectId": 999,
  "state": "broken",
  "x": 5,
  "y": 10
}

The client should visually remove or swap the object sprite when receiving this. Coordinates are tile positions (not world pixels).


6. Portal / Z-Level System

6.1 Portal Metadata

Portal objects on tiles now include targetZoneZ and a portalType field in their MetadataJson:

portalType Behavior
"world" Teleport to different region/zone. Includes full target.
"building" Enter a building: stays same zoneX/zoneY, changes zoneZ.
"building_exit" Exit building: returns to zoneZ=0 (ground level).

6.2 Portal Events in WORLD_STATE

When a player walks over a portal tile, the server triggers a teleport and includes a portalEvent in the next WORLD_STATE:

{
  "portalEvent": {
    "type": "world_teleport",
    "sourceObjectId": 123,
    "regionId": 2,
    "zoneX": 1, "zoneY": 1, "zoneZ": 0,
    "chunkX": 2, "chunkY": 2,
    "x": 512.0, "y": 512.0
  }
}

For building portals, the portal event may only change zoneZ while keeping the same region/zone XY. The client should:

  1. Detect the portalEvent in WORLD_STATE.
  2. Clear loaded chunks (new Z-level = new tile data).
  3. Start loading chunks from the new position.
  4. The server sends new chunks via chunkUpdates automatically.

Portal cooldown is 0.8 seconds (8 server ticks), enforced server-side.


7. Client Implementation Checklist

Mob Rendering

  • Parse mobs array from WORLD_STATE (nullable -- skip if null)
  • Render mob sprites using spriteConfig, tintColor, scale
  • Animate using animation string (e.g. "idle_down", "walk_right")
  • Show mob health bars (health/maxHealth)
  • Handle mob states: Idle, Chasing, Attacking, Dead
  • Dead mobs: play death animation, show loot indicator if lootAvailable
  • Mob click/tap target -> send WORLD_ATTACK with targetType: "mob"
  • Show damage numbers from WORLD_COMBAT_STATE events

NPC Rendering

  • Parse npcs array from WORLD_STATE (nullable -- skip if null)
  • Render NPC sprites using spriteConfig, tintColor, scale
  • Show interaction indicator (speech bubble? shop icon?) based on canShop/hasDialog
  • NPC click/tap -> send WORLD_NPC_INTERACT
  • Build dialog UI: show dialogNode.text + selectable options
  • On option click -> send WORLD_NPC_DIALOG_SELECT
  • Build shop UI: list items with prices, buy button
  • On buy -> send WORLD_NPC_SHOP_ACTION

Combat UI

  • Register handler for opcode 720 (WORLD_COMBAT_STATE)
  • Floating damage numbers (position from event x/y)
  • Color coding: red for damage, yellow for resisted, green for weakness
  • Death handling: PvP death shows killer name, mob death shows respawn
  • XP popup on MobDeath events (xpReward field)
  • Mob target frame / health bar while attacking

Mob Looting

  • On dead mob click -> send WORLD_MOB_LOOT_REQUEST
  • Register handler for opcode 723 (WORLD_MOB_LOOT_RESULT)
  • Show loot window with gold + items
  • Update local gold counter from loot result

Object Interaction

  • Register handler for opcode 751 (WORLD_OBJECT_INTERACT_RESULT)
  • Register handler for opcode 752 (WORLD_OBJECT_STATE)
  • Object click/tap -> send WORLD_OBJECT_INTERACT (action based on object type)
  • Breakable objects: show break animation then remove sprite on WORLD_OBJECT_STATE
  • Lootable objects: show loot popup with gold + items
  • Readable objects: show text popup with text field
  • Handle WORLD_OBJECT_STATE broadcast to update/remove objects broken by other players

Z-Level / Portals

  • Handle portalEvent in WORLD_STATE response
  • On portalEvent: clear chunk cache, transition to new position
  • Building entrance visual indicator on portal tiles
  • Building interior: same zone XY but different Z = different tile set
  • Track current zoneZ client-side (from self in WORLD_STATE)

Death/Respawn

  • Show death screen on PlayerDeath event (from mob or PvP)
  • Show "Respawn" button on death screen
  • Send WORLD_RESPAWN_REQUEST (724) on click
  • Register handler for opcode 725 (WORLD_RESPAWN_RESULT)
  • On respawn success: move player, restore health, show invulnerability
  • Handle PlayerRespawn events for other players

PvP

  • Read isPvp flag from self in WORLD_STATE (sent every tick)
  • Visual indicator when entering a PvP-enabled zone
  • Player click/tap in PvP zone -> send WORLD_ATTACK with targetType: "player"
  • Handle PvpDamage and PlayerDeath with isPvpKill: true events
  • Invulnerability visual (shield icon) when defender isInvulnerable

Shop Selling

  • Add "Sell" tab/button to shop UI
  • Show player inventory items with sell prices
  • Send WORLD_NPC_SHOP_ACTION with action: "sell", slotIndex = inventory slot
  • Update gold counter from response remainingGold

8. Known Limitations / TODOs

  • Loot tables not integrated: FIXED - Mob loot now uses LootService with configured loot tables. Items + gold are generated and added to inventory.
  • Player combat stats hardcoded: FIXED - Player stats now loaded from DungeonCharacter + equipped gear (armor, resistances, stat bonuses from items + crafted bonuses).
  • No zone PvP flag sent to client: FIXED - self.isPvp is now included in every WORLD_STATE tick. Also self.zoneZ added.
  • Sell action not implemented: FIXED - WORLD_NPC_SHOP_ACTION now supports "sell". Sell price = 25% of shop buy price.
  • No world death/respawn flow: FIXED - New opcodes 724/725 (WORLD_RESPAWN_REQUEST/RESULT). 3s invulnerability, zone spawn point, death counter.
  • Object broken state not persisted: Breakable objects reset on server restart. (Design choice - low priority.)
  • Mob AI abilities: Mobs use the dungeon AI system (10 behavior patterns) but world mob abilities haven't been extensively tested.
  • Player stats not refreshed on gear change: If the player equips/unequips gear while in a zone, the WorldPlayerCombatState is not updated until they re-enter the zone. A future "refresh stats" flow would be needed.
  • Respawn location is always zone center: Currently respawns at chunk 0,0 center. A more sophisticated system could use the nearest safe NPC or designated spawn point.