commit 07fe521166a42885605f0e2568c0f735bdae0fe7
parent 59009d7bb3d63fa47f9cacb0963a9b1c089e406f
Author: anon <anon@example.com>
Date: Thu, 22 Oct 2026 09:25:05 +0000
Expire profiled corpses and close native loot windows
Diffstat:
14 files changed, 331 insertions(+), 14 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -157,7 +157,7 @@ in [creature respawn](docs/npc-respawn.md).
changes the balance once and survives reconnect and restart.
- [ ] Roll loot for one creature profile. Check: controlled rolls select the
documented entries and quantities, including an empty result where allowed.
-- [ ] Remove an expired corpse. Check: observers lose the corpse and stale loot
+- [x] Remove an expired corpse. Check: observers lose the corpse and stale loot
requests cannot recover or duplicate its contents.
The fixed-item checks use a controlled fixture after a real combat kill;
diff --git a/docs/combat-client-reconstruction.md b/docs/combat-client-reconstruction.md
@@ -84,7 +84,7 @@ unknowns for each area:
| Line of sight | Client checks cannot establish original server validation | Not implemented on the server |
| Dual wield, ammunition/reload, specials and nanos | Scheduling, core effect streams and skill-lock contract recovered; full effect semantics remain partial | Not implemented |
| Resource regeneration | Native prediction formulas and injured-client probes | Authoritative player recovery; absolute quiet corrections reconcile prediction |
-| Corpse loot | Native handlers and real combat/loot encounters | Fixed-item transfer persists; production drop tables remain unimplemented |
+| Corpse loot | Native handlers and real combat/loot encounters | Fixed-item transfer persists; level-1 Leet corpses expire after a provisional 180 seconds; production drop tables remain unimplemented |
| Creature respawn | Explicit provisional level-1 Leet delay; historical district units unresolved | One fresh replacement after 100 seconds; see [respawn](npc-respawn.md) |
| XP, reclaim and player resurrection | Separate rules and state required | Not implemented |
diff --git a/docs/combat-npc-balance.md b/docs/combat-npc-balance.md
@@ -71,6 +71,7 @@ and AggDef outside -100..100.
| AggDef | 75 | Provisional actor value |
| Attack/recharge phases | 1.75s / 1.75s | Derived from the shipped 175 cs delays and the selected initiative/AggDef using the recovered timing formula |
| Respawn delay from death | 100 seconds | Provisional; independent of unresolved district time units |
+| Corpse lifetime from death | 180 seconds | Provisional; independent of respawn, contents and whether the corpse is open |
The first bite lands after the attack phase; subsequent bites are 3.5 seconds
apart before world-tick quantization. Range still uses the existing four-metre
diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md
@@ -136,8 +136,57 @@ Failed saves, full inventory, stale sessions and unavailable items retain the
previous owner. Repeated and concurrent requests cannot take the same item
twice. Corpses and untaken contents are currently runtime state; taken inventory
survives reconnect and server restart. Killer-only access is an initial policy:
-public expiry, team loot, corpse cleanup, credits and random drops remain
-separate milestones.
+public loot rights, team loot, credits and random drops remain separate
+milestones. The level-1 Leet's corpse expiry is described below.
+
+## Corpse expiry
+
+The shipped 14.9.1 `cd_image/text/help/combat.txt` states that an unlooted
+monster corpse decays after a time period. It supplies no duration. A bounded
+search of the local wiki and online corpse/decay/timer references did not
+establish this Leet's historical lifetime. Later boss-specific corpse times
+and emulator defaults are insufficient to establish a universal 14.9.1 rule.
+
+The MonsterData 17655, level-1 profile explicitly sets `corpse_seconds: 180`.
+This duration and its death-based clock origin are provisional reconstruction
+policy. Empty and populated corpses have the same deadline; opening, closing
+and taking items neither extends nor shortens it. Unprofiled corpses have no
+automatic expiry yet. This timer is independent of the profile's
+100-second respawn delay and is not supplied as a client `TimeExist` value.
+
+At expiry, the server clears the session's loot handle and sends the native
+action-102 close before deleting the hidden character (50000) and corpse
+(51050) through `0x36510078`. Only observers that know the corpse receive its
+deletions, including clients still loading an already queued snapshot. The
+FIFO output queue retires those objects after their initialization packets.
+Interest entries, the actor, its inactive roaming entry and its
+expiry queue entry are removed. A pending respawn retains the source needed
+to create a fresh life if the corpse's deadline comes first; an existing
+replacement has a separate identity and remains untouched.
+
+Use and pickup also check the deadline directly, rejecting expired requests
+before the cleanup tick. Cleanup and pickup share the normal update/state
+lock order, so a competing pickup either commits ownership first or finds no
+available corpse. Taken inventory remains durable; untaken contents are
+discarded with the corpse. Offline cleanup does not wait for an observer, and
+reentry cannot recreate an expired actor or recover its contents.
+
+`server/corpse_expiry_test.go` covers the exact boundary, close/delete ordering
+for two observers, stale requests before and after cleanup, pickup persistence,
+concurrent expiry/pickup, both timer orderings, fixed and roaming creatures,
+offline cleanup, loading clients and reentry.
+
+Two published WASM clients checked the full 180-second lifetime after a real
+100-HP Leet kill. Corpse 1000000 held untaken fixture item 101 while the owner
+already held item 100. Its window remained open across respawn, then closed at
+expiry with the cursor over the loot item. Both clients lost the fallen model;
+replacement 1068609 remained alive at 100 HP. The expired actor and loot handle
+were absent from the server state, and inventory retained item 100 without
+acquiring item 101. Page reconnect and server restart preserved that ownership
+and did not restore the expired corpse. The passing run had no page errors;
+socket failures were confined to the intentional restart. Screenshots,
+per-step states and machine-checked results are retained in
+`local/corpse-expiry-smoke/`.
The published WASM client was checked with a real combat kill, fallen corpse,
open/close/reopen, native Monster Parts details showing QL 1, pickup into the
diff --git a/docs/npc-respawn.md b/docs/npc-respawn.md
@@ -35,7 +35,8 @@ and combat in the world tick.
Each replacement receives a fresh character identity, the same definition and
combat profile, full profile health, and empty combat/recharge state. A roaming
creature returns to its authored home with a fresh roaming state. Its entry in
-the roaming roster is replaced, so successive deaths do not add roaming workers.
+the roaming roster is replaced or recreated if the corpse has already expired,
+so successive deaths do not add roaming workers.
Fixed creatures remain at their fixed post. Normal interest handling sends the
new actor before its native weapon profile, only to eligible nearby observers.
@@ -43,7 +44,8 @@ The previous corpse retains its original identity and contents. An open loot
window remains attached to that corpse; requests using the dead actor cannot
attack the replacement. Taking an old item uses the existing durable inventory
transfer, and repeating that request cannot manufacture a new drop. Corpse
-expiration remains a separate TODO, so old corpses can currently accumulate.
+expiration uses the profile's independent provisional 180-second lifetime;
+see [corpse expiry](corpse-loot.md#corpse-expiry).
NPC lives, corpses and pending timers remain runtime state. Restart reconstructs
exactly the authored living population with full resources; it does not persist
diff --git a/server/combat.go b/server/combat.go
@@ -255,6 +255,10 @@ func (server *server) advanceCombat(now time.Time) {
target.corpse = &npcCorpse{}
}
target.corpse.looter = attacker.id
+ if target.combatProfile != nil && target.combatProfile.CorpseSeconds != 0 {
+ target.corpse.expiresAt = now.Add(time.Duration(target.combatProfile.CorpseSeconds) * time.Second)
+ server.corpseExpiry = append(server.corpseExpiry, target)
+ }
server.queueCombat_locked(updates, target, target, corpsePacket(target))
}
if target.npc && target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 {
diff --git a/server/corpse_expiry.go b/server/corpse_expiry.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "slices"
+ "time"
+)
+
+func (server *server) advanceCorpseExpiry(now time.Time) {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ corpses := server.corpseExpiry
+ server.corpseExpiry = nil
+ updates := make(map[*worldClient][][]byte)
+ for _, corpse := range corpses {
+ if now.Before(corpse.corpse.expiresAt) {
+ server.corpseExpiry = append(server.corpseExpiry, corpse)
+ continue
+ }
+
+ // Close the registered container before deleting the corpse and hidden actor.
+ for _, client := range server.clients {
+ if client.lootCorpse == corpse.id {
+ client.lootCorpse = 0
+ updates[client] = append(updates[client], lootClosePacket(client.id, corpse.id))
+ }
+ if client.npcs[corpse.id] {
+ delete(client.npcs, corpse.id)
+ updates[client] = append(updates[client],
+ n3Packet(0x36510078, 50000, corpse.id, nil),
+ n3Packet(0x36510078, 51050, corpse.id, nil))
+ }
+ }
+
+ // Respawn holds its own source reference when its deadline is later.
+ delete(server.characters, corpse.id)
+ if corpse.roaming != nil {
+ server.roamingNPCs[corpse.playfield] = slices.DeleteFunc(server.roamingNPCs[corpse.playfield], func(other *character) bool { return other == corpse })
+ }
+ }
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+}
diff --git a/server/corpse_expiry_test.go b/server/corpse_expiry_test.go
@@ -0,0 +1,206 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+)
+
+func newExpiringCorpseWorld(t *testing.T) (*server, *combatTestConn, time.Time) {
+ t.Helper()
+ world, conn := newRespawnWorld(t)
+ if err := world.saveUser_locked(world.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ killed := world.characters[1].nextAttack
+ world.advanceCombat(killed)
+ world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1}}
+ return world, conn, killed
+}
+
+func TestCorpseExpiryClosesLootAndRemovesOnlyTheDeadLifeForBothObservers(t *testing.T) {
+ world, owner, killed := newExpiringCorpseWorld(t)
+ observer := world.newCharacter()
+ other := &combatTestConn{}
+ world.clients[observer.id] = &worldClient{id: observer.id, conn: other, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ world.handleLootUse(world.clients[1], lootUseRequest(1))
+ if world.characters[1000000].corpse.expiresAt != killed.Add(180*time.Second) {
+ t.Fatal("corpse lifetime did not come from the profile and killing blow")
+ }
+ world.advanceNPCRespawns(killed.Add(100 * time.Second))
+ owner.packets, other.packets = nil, nil
+
+ world.advanceCorpseExpiry(killed.Add(180*time.Second - time.Nanosecond))
+ if world.characters[1000000] == nil || len(owner.packets) != 0 {
+ t.Fatal("corpse disappeared before its deadline")
+ }
+ world.advanceCorpseExpiry(killed.Add(180 * time.Second))
+ world.advanceCorpseExpiry(killed.Add(time.Hour))
+
+ if world.characters[1000000] != nil || world.clients[1].lootCorpse != 0 ||
+ world.clients[1].npcs[1000000] || world.clients[2].npcs[1000000] || len(world.corpseExpiry) != 0 {
+ t.Fatal("expired corpse retained its actor, loot window, interest or expiry entry")
+ }
+ if len(world.characters) != 3 || world.characters[1000001].health != 100 ||
+ len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0].id != 1000001 {
+ t.Fatal("corpse removal changed the living replacement")
+ }
+ if len(owner.packets) != 3 || len(other.packets) != 2 ||
+ binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x2049527c ||
+ binary.BigEndian.Uint32(owner.packets[0][33:37]) != 102 {
+ t.Fatal("expiry did not close the owner's native container before deletion")
+ }
+ for index, identity := range []uint32{50000, 51050} {
+ packet := owner.packets[index+1]
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x36510078 || binary.BigEndian.Uint32(packet[20:24]) != identity ||
+ binary.BigEndian.Uint32(packet[24:28]) != 1000000 || !bytes.Equal(packet[16:], other.packets[index][16:]) {
+ t.Fatalf("observers did not delete the same hidden actor and corpse: %x", packet)
+ }
+ }
+}
+
+func TestCorpseExpiryRejectsUseAndPickupEvenBeforeTheCleanupTick(t *testing.T) {
+ world, conn, killed := newExpiringCorpseWorld(t)
+ world.handleLootUse(world.clients[1], lootUseRequest(1))
+ world.characters[1000000].corpse.expiresAt = time.Now().Add(-time.Second)
+ conn.packets = nil
+
+ world.handleLootUse(world.clients[1], lootUseRequest(2))
+ world.handleInventory(world.clients[1], lootTakeRequest())
+ if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 ||
+ len(world.characters[1].inventory.Items) != 0 || len(world.characters[1000000].corpse.items) != 1 {
+ t.Fatal("an expired corpse accepted a request between scheduler visits")
+ }
+ world.advanceCorpseExpiry(killed.Add(180 * time.Second))
+ world.handleLootUse(world.clients[1], lootUseRequest(3))
+ world.handleInventory(world.clients[1], lootTakeRequest())
+ world.advanceNPCs(killed.Add(181 * time.Second))
+ restarted := newTestInventoryServer(t)
+
+ if world.characters[1000000] != nil || world.clients[1].lootCorpse != 0 || world.clients[1].npcs[1000000] ||
+ len(world.characters[1].inventory.Items) != 0 || len(restarted.characters[1].inventory.Items) != 0 {
+ t.Fatal("stale use, pickup, reentry or restart recovered an expired item")
+ }
+}
+
+func TestCorpseExpiryPreservesAlreadyTakenInventoryAfterRestart(t *testing.T) {
+ world, _, killed := newExpiringCorpseWorld(t)
+ world.handleLootUse(world.clients[1], lootUseRequest(1))
+ if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
+ t.Fatal(err)
+ }
+
+ world.advanceCorpseExpiry(killed.Add(180 * time.Second))
+ world.handleInventory(world.clients[1], lootTakeRequest())
+ restarted := newTestInventoryServer(t)
+
+ expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64}}
+ if world.characters[1000000] != nil || !slices.Equal(world.characters[1].inventory.Items, expected) ||
+ !slices.Equal(restarted.characters[1].inventory.Items, expected) {
+ t.Fatal("expiry lost or duplicated the item that had already changed owners")
+ }
+}
+
+func TestCorpseExpiryBeforeRespawnWithoutObserversKeepsOneRoamingReplacement(t *testing.T) {
+ world, conn := newRespawnWorld(t)
+ profile := *world.characters[1000000].combatProfile
+ profile.CorpseSeconds = 1
+ world.characters[1000000].combatProfile = &profile
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ killed := world.characters[1].nextAttack
+ world.advanceCombat(killed)
+ client := world.clients[1]
+ delete(world.clients, 1)
+ conn.packets = nil
+
+ world.advanceCorpseExpiry(killed.Add(time.Second))
+ if world.characters[1000000] != nil || len(world.roamingNPCs[950]) != 0 || len(world.npcRespawns) != 1 {
+ t.Fatal("early corpse expiry retained the dead actor or discarded its pending respawn")
+ }
+ world.advanceNPCRespawns(killed.Add(100 * time.Second))
+ if len(conn.packets) != 0 {
+ t.Fatal("an unavailable observer received expiry or respawn packets")
+ }
+ world.clients[1] = client
+ client.npcs = make(map[uint32]bool)
+ world.advanceNPCs(killed.Add(101 * time.Second))
+
+ if len(world.characters) != 2 || world.characters[1000001].health != 100 || len(world.npcRespawns) != 0 ||
+ len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0].id != 1000001 ||
+ len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x271b3a6b ||
+ binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x1d3c0f1c {
+ t.Fatal("respawn or reentry lost the roaming replacement or restored its expired corpse")
+ }
+}
+
+func TestCorpseExpiryConcurrentPickupHasAtMostOneDurableOwner(t *testing.T) {
+ world, _, killed := newExpiringCorpseWorld(t)
+ world.handleLootUse(world.clients[1], lootUseRequest(1))
+ var workers sync.WaitGroup
+ errors := make(chan error, 8)
+
+ workers.Go(func() { world.advanceCorpseExpiry(killed.Add(180 * time.Second)) })
+ for range 8 {
+ workers.Go(func() { errors <- world.handleInventory(world.clients[1], lootTakeRequest()) })
+ }
+ workers.Wait()
+ close(errors)
+ for err := range errors {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ restarted := newTestInventoryServer(t)
+
+ items := world.characters[1].inventory.Items
+ if world.characters[1000000] != nil || len(items) > 1 || !slices.Equal(items, restarted.characters[1].inventory.Items) ||
+ (len(items) == 1 && items[0] != (ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64})) {
+ t.Fatal("a pickup racing expiry duplicated or lost durable ownership")
+ }
+}
+
+func TestCorpseWithoutExpiryProfileKeepsItsExistingPolicy(t *testing.T) {
+ world, _ := newLootWorld(t)
+
+ world.advanceCorpseExpiry(time.Now().Add(time.Hour))
+
+ if world.characters[1000000] == nil || !world.characters[1000000].corpse.expiresAt.IsZero() {
+ t.Fatal("an unprofiled corpse received an invented lifetime")
+ }
+}
+
+func TestCorpseExpiryRetiresKnownObjectsWhileTheObserverIsLoading(t *testing.T) {
+ world, conn, killed := newExpiringCorpseWorld(t)
+ world.clients[1].ready = false
+ world.clients[1].loading = true
+ conn.packets = nil
+
+ world.advanceCorpseExpiry(killed.Add(180 * time.Second))
+ world.clients[1].ready = true
+ world.clients[1].loading = false
+ world.advanceNPCs(killed.Add(181 * time.Second))
+
+ if len(conn.packets) != 2 || world.clients[1].npcs[1000000] ||
+ binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x36510078 || binary.BigEndian.Uint32(conn.packets[0][20:24]) != 50000 ||
+ binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x36510078 || binary.BigEndian.Uint32(conn.packets[1][20:24]) != 51050 {
+ t.Fatal("an object sent during initialization survived expiry as a client-only corpse")
+ }
+}
+
+func TestCorpseExpiryFixedCreatureDoesNotRequireARoamingRoster(t *testing.T) {
+ world, _, killed := newExpiringCorpseWorld(t)
+ world.characters[1000000].roaming = nil
+ world.roamingNPCs = nil
+
+ world.advanceCorpseExpiry(killed.Add(180 * time.Second))
+ world.advanceNPCRespawns(killed.Add(181 * time.Second))
+
+ if world.characters[1000000] != nil || world.characters[1000001].health != 100 ||
+ world.characters[1000001].roaming != nil || len(world.corpseExpiry) != 0 || len(world.npcRespawns) != 0 {
+ t.Fatal("fixed corpse cleanup or its replacement required an unrelated roaming roster")
+ }
+}
diff --git a/server/gamedata/npc_combat.yaml b/server/gamedata/npc_combat.yaml
@@ -11,3 +11,5 @@
agg_def: 75
# Provisional delay from death, independent of unresolved district time units.
respawn_seconds: 100
+ # Provisional lifetime from death; applies to empty and unlooted remains.
+ corpse_seconds: 180
diff --git a/server/gamedata/types.go b/server/gamedata/types.go
@@ -20,6 +20,7 @@ type NPCCombatProfile struct {
Initiative int32 `yaml:"initiative"`
AggDef int32 `yaml:"agg_def"`
RespawnSeconds uint32 `yaml:"respawn_seconds"`
+ CorpseSeconds uint32 `yaml:"corpse_seconds"`
}
type NPCPlayfield struct {
diff --git a/server/loot.go b/server/loot.go
@@ -9,8 +9,9 @@ import (
)
type npcCorpse struct {
- looter uint32
- items []ownedItem
+ looter uint32
+ items []ownedItem
+ expiresAt time.Time
}
func corpsePacket(character *character) []byte {
@@ -83,6 +84,9 @@ func (server *server) canLoot_locked(client *worldClient, corpse *character) boo
corpse.corpse.looter != client.id || corpse.playfield != server.characters[client.id].playfield {
return false
}
+ if !corpse.corpse.expiresAt.IsZero() && !time.Now().Before(corpse.corpse.expiresAt) {
+ return false
+ }
position := predictedPosition_locked(server.characters[client.id], client, time.Now())
x, y, z := position[0]-corpse.position[0], position[1]-corpse.position[1], position[2]-corpse.position[2]
// kkr.dll sub_3604D350 checks five metres for world item use.
diff --git a/server/respawn.go b/server/respawn.go
@@ -1,6 +1,9 @@
package main
-import "time"
+import (
+ "slices"
+ "time"
+)
type npcRespawn struct {
npc *character
@@ -33,11 +36,11 @@ func (server *server) advanceNPCRespawns(now time.Time) {
if respawn.npc.roaming != nil {
npc.position = respawn.npc.roaming.home
npc.roaming = &npcRoaming{home: npc.position}
- for index, other := range server.roamingNPCs[npc.playfield] {
- if other == respawn.npc {
- server.roamingNPCs[npc.playfield][index] = npc
- break
- }
+ index := slices.Index(server.roamingNPCs[npc.playfield], respawn.npc)
+ if index < 0 {
+ server.roamingNPCs[npc.playfield] = append(server.roamingNPCs[npc.playfield], npc)
+ } else {
+ server.roamingNPCs[npc.playfield][index] = npc
}
}
server.characters[npc.id] = npc
diff --git a/server/roaming.go b/server/roaming.go
@@ -19,6 +19,7 @@ func (server *server) roamNPCs() {
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for now := range ticker.C {
+ server.advanceCorpseExpiry(now)
server.advanceNPCRespawns(now)
server.advanceNPCs(now)
server.advanceEquipment(now)
diff --git a/server/state.go b/server/state.go
@@ -88,6 +88,7 @@ type server struct {
characters map[uint32]*character
roamingNPCs map[uint32][]*character
npcRespawns []npcRespawn
+ corpseExpiry []*character
clients map[uint32]*worldClient
fighting map[uint32]*character
chats map[uint32]*chatClient