Files
systemrevivalserver/Game/World/client_fixes.md
T
2026-02-18 06:48:34 -05:00

18 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,
    "chunkX": 5, "chunkY": 3
  },
  "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
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 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

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": []
}

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

Items array is currently empty (loot tables not yet integrated). Gold is XpReward / 2.


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
}

Only "buy" is currently supported.

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"


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)

PvP

  • Visual indicator when entering a PvP-enabled zone (server does not send zone flags yet -- use hardcoded zone list or future opcode)
  • 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

8. Known Limitations / TODOs

  • Loot tables not integrated: WORLD_MOB_LOOT_RESULT items array is always empty. Only gold drops currently.
  • Player combat stats hardcoded: EnsurePlayersInZoneSimsAsync uses default stats (str=10, int=10, etc). Real gear-based stats not loaded yet.
  • No zone PvP flag sent to client: The client has no way to know if a zone is PvP-enabled. Will need a future opcode or flag in chunk/zone data.
  • Object broken state not persisted: Breakable objects reset on server restart.
  • Sell action not implemented: WORLD_NPC_SHOP_ACTION only supports "buy".
  • No world death/respawn flow: PlayerDeath events are broadcast but there is no respawn opcode or flow yet.
  • Mob AI abilities: Mobs use the dungeon AI system (10 behavior patterns) but world mob abilities haven't been extensively tested.