aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 1b67cdaecdd85d0ad3cd53fda297aa2bb918bbe8
parent 74e607a6853f90d4cc66577d72681c5a5e25faa3
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 01:27:31 +0000

Share default team loot rights by aggregate damage

Diffstat:
MTODO.md | 35+++++++++++++++++++++++++++++++++--
Mdocs/corpse-credits.md | 15+++++++--------
Mdocs/corpse-loot.md | 19++++++++++---------
Adocs/team-loot.md | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 52++++++++++++++++++++++++++++++++++++++++++----------
Mserver/database_test.go | 6+++---
Mserver/fling_shot_test.go | 8++++----
Mserver/loot.go | 24++++++++++++++++++++++--
Mserver/loot_rights_test.go | 1+
Mserver/nano_casting.go | 11++++++++---
Mserver/nano_casting_test.go | 8+++++---
Aserver/npc_outcome.go | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/special_locks.go | 35++++-------------------------------
Mserver/state.go | 4++--
Aserver/team_loot_test.go | 421+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/teams.go | 11++++++++++-
Mserver/world.sql | 6+++++-
Mserver/world_store.go | 36+++++++++++++++++++-----------------
18 files changed, 784 insertions(+), 96 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -505,8 +505,26 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). two-second regeneration cadence; intermediate native prediction can differ. - [ ] Share XP from one team kill. Check: a controlled encounter awards the expected shares once and excludes ineligible members. -- [ ] Apply one team loot policy. Check: a known two-player loot sequence follows - that policy while unrelated players remain excluded. + Depends on the base kill-XP reward path and sourced reward arithmetic. A + January 2004 forum discussion quotes a Sybex team-bonus table, but neither + establishes the 14.9.1 base reward nor verifies the original guide's contents: + [research lead](https://forums-archive.anarchy-online.com/showthread.php?219659-Team-XP=). +- [x] Apply default All team loot rights. Check: aggregate team damage competes + with solo/other-team damage, both members can loot, unrelated players remain + excluded, and concurrent pickup/cash have one durable owner. Current-member + rights are rechecked after departure and restart. See [team loot](docs/team-loot.md). +- [ ] Implement native team loot order commands and Leader/Alpha allocation. + Check: `/team loot` queries and leader-only setters use recovered actions + 145/127 and modes3/4/5; invalid/forged requests and failed SQL change nothing. + Verify alphabetic rotation, allocation timing, empty corpses, roster changes, + offline/remote members, mode/leadership changes on existing remains and + restart. Commit Alpha advancement with corpse assignment, including Fling. + The original command/feedback protocol is retained in + `local/team-loot-research/wire-audit.md`; unresolved policies are listed in + `local/team-loot-research/server-audit.md`. +- [ ] Recover and implement team money splitting. Check: original rules and + native receipts agree for eligible/remote/full-balance members, rollback, + concurrent Use and restart; the current first eligible looter receives cash. - [x] Deliver private team chat. Check: only current members receive it across zones; joining, leaving, disconnect and restart update channel access. Native type2 channels follow committed membership; forged/stale IDs are @@ -768,6 +786,10 @@ and server restarts. Turn every reproduced bug into a focused regression test. matching/wrong/missing ammunition, insufficient stacks, repeated reloads, reload during each attack phase, failed saves and round conservation across equipment changes, reconnect and restart. + Include injected failure after ammunition commits but before a killing-blow + corpse save: ordinary ranged attacks currently have separate transactions. + Unify the significant result so rollback cannot leave a spent round without + the corresponding durable death; Fling saves its outcome and lock together. - [ ] Audit NPC pursuit, recovery and lifecycle. Cover multiple observers, target loss, re-engagement, terrain boundaries, death during movement, no-observer periods and restart during pursuit, return, corpse and respawn. @@ -777,6 +799,10 @@ and server restarts. Turn every reproduced bug into a focused regression test. - [ ] Audit corpse loot, credits and expiry. Cover entitled/unrelated players, simultaneous pickup, partial looting, full inventory, stale windows, expiry, repeat requests and persistence of both sides of each transfer. + Verify the rendered corpse and native picking after reconnect/restart: the + team-loot runtime pass restored server ownership and a native corpse object, + but could not locate clickable remains. Distinguish camera/fixture placement + from mesh creation, original-actor prerequisites and interest replay order. - [ ] Audit consumables and skill locks. Cover self/friendly/invalid targets, resource boundaries, combat and posture restrictions, last-charge removal, overlapping locks, concurrent requests and restart during a lock. @@ -850,6 +876,11 @@ and server restarts. Turn every reproduced bug into a focused regression test. ## Checks that apply to each milestone +- [ ] Align the declared Go test/toolchain requirement with `WaitGroup.Go` + usage. The module declares Go1.24 while existing concurrency tests use the + Go1.25 API; full `go vet` reports `stdversion` errors. The other analyzers + pass with that analyzer disabled. Keep the supported build/test instructions + and `go.mod` coherent. - Exercise the native client path, not only a server helper or admin edit. - Persist durable state as part of the feature; verify reconnect and restart. - Reject invalid, stale and repeated requests without unintended state changes. diff --git a/docs/corpse-credits.md b/docs/corpse-credits.md @@ -67,17 +67,16 @@ range are rejected during loading. ## Ownership and remaining scope Use shares the existing corpse visibility, playfield, range, life, expiry and -session checks. The current killer-only server policy remains provisional: -the shipped `OnSelectRemains.txt` describes majority-damage player/team loot -rights, whose separate TODO remains open. Team money splitting and public -loot expiry are not inferred from this cash path. +session checks and individual or aggregate team damage rights. In default +All mode, the first eligible current teammate to use the corpse receives its +cash. [Team loot](team-loot.md) describes the accounting and policy limits. +Team money splitting and public unlock rules remain unimplemented. -Credits and item ownership share one inventory file, so collecting an item +Credits and item ownership share one SQLite transaction, so collecting an item after cash does not erase the balance. Failed saves preserve both the previous balance and corpse cash. Repeated sequences, later close/reopen -and competing unauthorized users cannot repeat the award. Corpses remain -runtime state; taken credits survive restart, while untaken corpse contents -have the existing nonpersistent lifecycle. +and competing users cannot repeat the award. Corpses, untaken contents and +taken credits survive restart in the world database. Native source streams, switch tables, shipped help, fixtures, packet logs and read-only probes are retained under `local/corpse-credit-smoke/`. See diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md @@ -134,10 +134,10 @@ update the corpse window without a replacement contents update. 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. Individual entitlement follows damage -contribution as described below. Public loot rights, team loot and random -drops remain separate milestones. +twice. Corpses, untaken contents and taken inventory survive reconnect and +server restart in SQLite. Entitlement follows individual or aggregate team +damage contribution as described below and in [team loot](team-loot.md). +Public loot rights, Leader/Alpha orders and random drops remain separate work. [Corpse credits](corpse-credits.md) describes known-amount cash collection and persistence. The level-1 Leet's corpse expiry is described below. @@ -173,8 +173,8 @@ player receiving rights, while qualifying its observations. A later also defines the killing team by most damage. Neither supplies a controlled three-contender result or an equal-damage tie rule. -The server accumulates each player's applied HP damage for one NPC life and -grants individual rights to the greatest contributor. Overkill contributes +The server accumulates each solo player's or team's applied HP damage for one +NPC life and grants rights to the greatest contributor. Overkill contributes only remaining HP. Stopping and restarting attacks does not erase damage. Departure, death or a playfield change does not transfer an existing lead to another player; opening and taking still require the entitled player to be @@ -185,9 +185,10 @@ an XP reward; that remains unimplemented. Ties retain the first contributor to reach the tied total. Greatest damage without a strict majority, applied-damage accounting, contribution retention and this tie rule are explicit reconstruction policies where period evidence -does not establish the exact arithmetic or reset behavior. NPCs currently do -not heal or reset health during a life. Pets, teams and damage shields are -outside the implemented combat scope. +does not establish the exact arithmetic or reset behavior. Contributions +currently remain through NPC regeneration. Pets and damage shields are +outside the implemented combat scope. [Team loot](team-loot.md) describes the +hit-time accounting and current-member All rights. Entitlement lasts until the corpse's existing deadline; opening, closing and taking do not release rights. The level-1 Leet retains the provisional diff --git a/docs/team-loot.md b/docs/team-loot.md @@ -0,0 +1,124 @@ +# Team loot + +Accepted teams share the default All loot order. Damage from current teammates +counts toward one team total, independently of solo players and other teams. +The greatest total wins; the final hitter need not belong to that team. Current +members can open its remains and take items under the ordinary visibility, +session, life, playfield, range and expiry checks. Both Use and pickup recheck +membership. Leaving, being kicked or dissolving a team revokes open handles; +a newly formed team cannot inherit the old team's remains. + +## Original contract + +The shipped 14.9.1 `cd_image/text/tips/OnSelectRemains.txt` assigns rights to +the player or team doing the majority of damage. `help/Team Commands.txt` and +`help/TeamHelp.txt` establish All as the default, Leader as leader-only, and +Alpha as a repeating alphabetical order. Leader and Alpha are not implemented. +Changing the loot order is therefore not acknowledged as a successful action. + +Original `kkr.dll`, SHA256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`, +reads the corpse's team DWORD, mode DWORD and looter identity at +`100af9c0`. Activation `100afcb0` passes them to `1008c740`. With mode3 and +a matching local team stat6, it prints the native All-team entitlement message. +A null designated looter is accepted without the missing-looter warning. +The server supplies the historical team ID, mode3 and null looter for team +remains; solo remains retain their individual identity. + +Retained Ghidra observations, using original image-base addresses: + +| Function | Evidence ID | +| --- | --- | +| Corpse reader `100af9c0` | `ev_f8c10d1214ccfec5696ea6f52779bf8b4db2445af4e1c3b45f6d45e01ccd70f6` | +| Activation `100afcb0` | `ev_3e82ececa597561761499a97017d95500c20e2976780cfbfb7443a09a9354c90` | +| Entitlement `1008c740` | `ev_5b7ba2e86cb9e8f2f9b09548779950b959cad1f341bf8bb7c66014c9dbab7f78` | + +These are static observations, not observations of the original live server. +Indirect call coverage is incomplete; the retained dossiers preserve those +limitations in `local/team-loot-research/native-evidence.json`. + +The independent original-code audit also recovered `/team loot` action145 +and `/team loot MODE` action127 on CharacterAction `5e477770`. Set uses the +first identity's instance; query feedback uses the second. All=3, Leader=4, +Alpha=5. The source/address ledger is +`local/team-loot-research/wire-audit.md`; these commands remain follow-up work. + +## Accounting and durability + +Each hit credits the attacker's team at that moment, or that individual when +unteamed. Player and team IDs occupy separate namespaces. Leaving or joining +does not retroactively move earlier damage. Equal totals retain the first +beneficiary to reach the tied total. Applied damage excludes overkill; stopped +attacks and NPC regeneration retain contributions for this NPC life. + +Hit-time membership, greatest-total plurality, ties and retention are explicit +reconstruction policies. The shipped help does not settle those details. +Authorization uses current membership, so later accepted members may loot old +All remains. If the team dissolves, its old remains become inaccessible until +expiry. Disconnect alone retains membership under the existing team policy. +No public unlock timer or fallback to an individual owner is inferred. + +Routine damage and simulation state use periodic checkpoints. Corpse creation +and its rights are saved immediately before normal/nano death packets. Failed +saves retain the live HP and contribution state; a failed nano result refunds +its reserved cost. Fling commits damage, ownership and its skill lock together. +Corpse state, outstanding contributions and untaken items survive restart. +Historical team IDs are scalar awards, without a cascading reference to a live +team row. Respawn starts a fresh life and damage ledger. + +Ordinary ranged attacks still commit ammunition separately before applying the +hit. A later failed corpse save can therefore leave a spent round without an +accepted death. Unifying that transaction and injecting this exact failure is +an explicit combat-audit TODO; the NPC outcome transaction alone does not +establish atomicity with that earlier debit. + +Item pickup and cash collection retain the existing atomic inventory +transactions. Competing members can receive only one durable item owner and +one cash collection. A committed pickup refreshes other eligible open windows +without reopening them. The taker retains the ordinary native transfer ACK. +The first eligible successful Use receives the whole cash amount; team money +splitting is unimplemented, and this unsplit policy is not claimed as original +team cash behavior. Native deferred cash ordering remains as described in +[corpse credits](corpse-credits.md). + +## Verification + +`TestTeamLoot*` covers aggregate competition, solo/team ID collisions, ties, +competing teams, concurrent Use and pickup, stale outsider handles, departure, +replacement teams, failed saves, restart during combat, immediate durable death, +and normal/nano/Fling awards. Broader verification and runtime captures are +retained in `local/team-loot-research/`. + +The full server suite passed (292.644s), along with gamedata tests (7.631s), +focused race checks (101.312s) and the final team scenarios (12.139s). Full +`go vet` reports the existing Go 1.24 declaration versus Go 1.25 `WaitGroup.Go` +usage in concurrency tests; its other analyzers pass with `stdversion` disabled. + +Three WASM clients used the GPU/OpenGL renderer against the single HTTPS +preview. An ordinary production-server combat kill immediately persisted team 14 +and printed the native All entitlement message for members 21/22, not outsider 23. +A temporary build overlay then supplied two fixture Monster Parts and 123 credits +at death, with a one-hour observation window. It did not change authorization, +native packets, cash collection or pickup. Both members opened the same corpse; +their native Use results were success 1 while the outsider received failure 2. +Member 22 received 123 credits exactly once. Item 194 went to member 22 and item 195 +to leader 21; both open windows changed from two entries to one to none. SQLite +and both native inventories agreed after restart with the ordinary server +binary. No page errors or adapter failures occurred in these verification runs. + +All original 192 item records/placements, fixture-player profiles, ammunition, +cash and NPC state were restored; team 14 was removed and owned browsers closed. +The production preview remains on HTTPS 8443. Assertions and limits are retained +in `local/team-loot-research/verification.json`. + +The earlier reconnect pass restored the native corpse object and server rights +but could not locate clickable remains at its original camera/fixture placement. +That does not establish a rendering defect or verify the replay's picking path. +Interest replay order, original-actor prerequisites, mesh visibility and camera +placement remain an explicit native audit TODO. Earlier fixture/harness setup +failures are excluded from the successful runtime evidence above. + +Remaining work includes Leader/Alpha allocation and persistence, native mode +query/set feedback, team money splitting, original membership/disconnect and +public unlock rules, and production drop tables. Team XP additionally requires +the still-unimplemented base kill-XP award path and verified reward arithmetic. diff --git a/server/combat.go b/server/combat.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "fmt" "log" + "maps" "math/rand/v2" "sort" "time" @@ -350,32 +351,62 @@ func (server *server) advanceCombat(now time.Time) { continue } } - target.health -= damage + if err := server.applyDamage_locked(attacker, target, damage, now); err != nil { + log.Printf("Damage: %v", err) + server.cancelCombat_locked(target.id, updates) + continue + } attack, recharge := attacker.attackDelays() attacker.rechargeUntil = now.Add(recharge) attacker.nextAttack = attacker.rechargeUntil.Add(attack) server.queueCombat_locked(updates, attacker, target, hitPacket(attacker, target, damage)) - server.finishDamage_locked(attacker, target, damage, now, updates) + server.finishDamageEffects_locked(attacker, target, now, updates) } server.mutex.Unlock() server.sendCombatUpdates(updates) } -func (server *server) finishDamage_locked(attacker, target *character, damage uint32, now time.Time, updates map[*worldClient][][]byte) { +type damageContributor struct { + player uint32 + team uint32 +} + +func (server *server) applyDamage_locked(attacker, target *character, damage uint32, now time.Time) error { + // Death awards durable corpse rights before any result is published. + if target.npc && damage == target.health { + candidate := *target + candidate.health = 0 + candidate.damageContributors = maps.Clone(target.damageContributors) + if target.corpse != nil { + corpse := *target.corpse + candidate.corpse = &corpse + } + prepareDamage(attacker, &candidate, damage, now) + if err := server.saveNPCDeath_locked(&candidate, now); err != nil { + return err + } + *target = candidate + return nil + } + target.health -= damage prepareDamage(attacker, target, damage, now) - server.finishDamageEffects_locked(attacker, target, now, updates) + return nil } func prepareDamage(attacker, target *character, damage uint32, now time.Time) { - // Keep individual contributions for this NPC life, including stopped attacks. + // Credit the player or team present at each hit for this NPC life. if target.npc && !attacker.npc { if target.damageContributors == nil { - target.damageContributors = make(map[uint32]uint32) + target.damageContributors = make(map[damageContributor]uint32) + } + contributor := damageContributor{player: attacker.id} + if attacker.team != nil { + contributor = damageContributor{team: attacker.team.id} } - target.damageContributors[attacker.id] += damage + target.damageContributors[contributor] += damage // Equal totals retain the first contributor to reach that total. - if target.damageContributors[attacker.id] > target.damageContributors[target.leadingContributor] { - target.leadingContributor = attacker.id + if target.damageContributors[contributor] > target.damageContributors[target.leadingContributor] { + target.leadingContributor = contributor } } monster := gamedata.MonsterTemplates[target.monsterData] @@ -383,7 +414,8 @@ func prepareDamage(attacker, target *character, damage uint32, now time.Time) { if target.corpse == nil { target.corpse = &npcCorpse{} } - target.corpse.looter = target.leadingContributor + target.corpse.looter = target.leadingContributor.player + target.corpse.team = target.leadingContributor.team target.damageContributors = nil if target.combatProfile != nil && target.combatProfile.CorpseSeconds != 0 { target.corpse.expiresAt = now.Add(time.Duration(target.combatProfile.CorpseSeconds) * time.Second) diff --git a/server/database_test.go b/server/database_test.go @@ -237,14 +237,14 @@ func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) { func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - world.characters[1000000].damageContributors = map[uint32]uint32{1: 4} + world.characters[1000000].damageContributors = map[damageContributor]uint32{{player: 1}: 4} if err := world.flushWorld(); err != nil { t.Fatal(err) } restarted := newServer() defer restarted.db.Close() - restarted.characters[1000000].damageContributors[1] = 9 + restarted.characters[1000000].damageContributors[damageContributor{player: 1}] = 9 if err := restarted.flushWorld(); err != nil { t.Fatal(err) } @@ -253,7 +253,7 @@ func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) { var damage uint32 err := again.db.QueryRow("SELECT damage FROM npc_damage_contributors WHERE npc_id=1000000 AND player_id=1").Scan(&damage) - if err != nil || damage != 9 || again.characters[1000000].damageContributors[1] != 9 { + if err != nil || damage != 9 || again.characters[1000000].damageContributors[damageContributor{player: 1}] != 9 { t.Fatalf("NPC contribution change was not checkpointed: %d, %v", damage, err) } } diff --git a/server/fling_shot_test.go b/server/fling_shot_test.go @@ -33,7 +33,7 @@ func TestFlingShotDamagesOnceWithoutConsumingPre155Ammunition(t *testing.T) { player.inventory.Items[1].Count != 100 || restored.inventory.Items[0].Ammo != 3 || !restored.specialAttackLocks[150].Equal(player.specialAttackLocks[150]) || player.specialAttackLocks[150].Before(started.Add(19*time.Second)) || target.fighting != 1 || - target.damageContributors[1] != 1000-target.health { + target.damageContributors[damageContributor{player: 1}] != 1000-target.health { t.Fatalf("special result or persistent lock mismatch: HP=%d lock=%v, %v", target.health, player.specialAttackLocks, err) } if len(owner.packets) != 3 || len(observer.packets) != 2 || @@ -245,7 +245,7 @@ func TestFlingShotPersistsDamageAndContributionBeforeAnyCheckpoint(t *testing.T) if err != nil || health != world.characters[1000000].health || contribution != 1000-health || world.savedNPCs[1000000].State.Character.Vitals.Health != health || restored.characters[1000000].health != health || - restored.characters[1000000].damageContributors[1] != contribution || + restored.characters[1000000].damageContributors[damageContributor{player: 1}] != contribution || !restored.characters[1].specialAttackLocks[150].Equal(world.characters[1].specialAttackLocks[150]) { t.Fatalf("published special was not durable: HP=%d contribution=%d, %v", health, contribution, err) } @@ -256,7 +256,7 @@ func TestFlingShotKillingSaveFailurePreservesCorpseAndContributors(t *testing.T) target := world.characters[1000000] target.health, target.monsterData, target.level = 1, 17655, 1 target.combatProfile = gamedata.NPCCombatProfiles[17655][1] - target.damageContributors, target.leadingContributor = map[uint32]uint32{2: 10}, 2 + target.damageContributors, target.leadingContributor = map[damageContributor]uint32{{player: 2}: 10}, damageContributor{player: 2} target.corpse = &npcCorpse{looter: 2, credits: 10} if err := world.flushWorld(); err != nil { t.Fatal(err) @@ -269,7 +269,7 @@ func TestFlingShotKillingSaveFailurePreservesCorpseAndContributors(t *testing.T) restored := newTestInventoryServer(t) if err == nil || target.health != 1 || target.corpse.looter != 2 || !target.corpse.expiresAt.IsZero() || - target.damageContributors[2] != 10 || len(target.damageContributors) != 1 || len(world.npcRespawns) != 0 || + target.damageContributors[damageContributor{player: 2}] != 10 || len(target.damageContributors) != 1 || len(world.npcRespawns) != 0 || len(conn.packets) != 0 || restored.characters[1000000].health != 1 || restored.characters[1000000].corpse.looter != 2 || len(restored.characters[1].specialAttackLocks) != 0 { t.Fatal("failed special kill leaked staged corpse, contribution or lock state") diff --git a/server/loot.go b/server/loot.go @@ -11,6 +11,7 @@ import ( type npcCorpse struct { looter uint32 + team uint32 items []ownedItem credits uint32 expiresAt time.Time @@ -48,9 +49,13 @@ func corpsePacket(character *character) []byte { // The creation event holds the final death frame; an empty animation list // makes n3VisualDynel_t::Run replace the otherwise valid model with a cube. + looterType := uint32(50000) + if character.corpse.team != 0 { + looterType = 0 + } for _, value := range []uint32{2, 0, 1009, 3, 2018, 53003, 0, 4, 0, 1, 0, 0, 0xffffffff, 51050, character.id, monster.DeathAnimations[0], 1, 0, - 50000, character.id, 1009, 0, 0, 3, 50000, character.corpse.looter, 0} { + 50000, character.id, 1009, 0, character.corpse.team, 3, looterType, character.corpse.looter, 0} { body = binary.BigEndian.AppendUint32(body, value) } return n3Packet(0x4f474e05, 51050, character.id, body) @@ -84,7 +89,14 @@ func lootClosePacket(owner, corpse uint32) []byte { func (server *server) canLoot_locked(client *worldClient, corpse *character) bool { if corpse == nil || corpse.corpse == nil || corpse.health != 0 || !client.npcs[corpse.id] || - corpse.corpse.looter != client.id || corpse.playfield != server.characters[client.id].playfield { + corpse.playfield != server.characters[client.id].playfield { + return false + } + if corpse.corpse.team != 0 { + if team := server.characters[client.id].team; team == nil || team.id != corpse.corpse.team { + return false + } + } else if corpse.corpse.looter != client.id { return false } if !corpse.corpse.expiresAt.IsZero() && !time.Now().Before(corpse.corpse.expiresAt) { @@ -221,6 +233,14 @@ func (server *server) takeLoot_locked(client *worldClient, body []byte) error { return err } server.nextItem = max(server.nextItem, item.ID) + // Other eligible open windows must lose the same icon after the commit. + for _, other := range server.clients { + if other != client && other.ready && !other.loading && other.lootCorpse == corpse.id && server.canLoot_locked(other, corpse) { + if err := other.send(lootInventoryPacket(other.id, corpse, false)); err != nil { + other.disconnect(other.conn) + } + } + } reply := append([]byte(nil), body[16:]...) binary.BigEndian.PutUint32(reply[16:20], slot) return client.send(n3Packet(0x47537a24, 50000, client.id, reply)) diff --git a/server/loot_rights_test.go b/server/loot_rights_test.go @@ -19,6 +19,7 @@ func newLootRightsWorld(t *testing.T) *server { } world.clients[player.id] = &worldClient{id: player.id, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} } + t.Cleanup(func() { world.db.Close() }) // High melee AC makes ordinary fists deal exactly three damage. npc := world.characters[1000000] npc.monsterData = 17655 diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -4,6 +4,7 @@ import ( "ao/server/gamedata" "encoding/binary" "fmt" + "log" "math/rand/v2" "slices" "time" @@ -151,16 +152,20 @@ func (server *server) advanceNanos(now time.Time) { } // Only this result changes HP; the native Hit effect is server-owned. + damage := min(10+rand.Uint32N(14), target.health) + if err := server.applyDamage_locked(player, target, damage, now); err != nil { + log.Printf("Nano damage: %v", err) + server.abortNano_locked(client, now, updates) + continue + } client.nanoCast = nil recharge := float64(itemStat(gamedata.NanoTemplates[29618], 210)) * float64(float32(0.01)) player.nanoRechargeUntil = now.Add(time.Duration(recharge * float64(time.Second))) - damage := min(10+rand.Uint32N(14), target.health) - target.health -= damage body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) body = binary.BigEndian.AppendUint32(body, 95) server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, 29618})) server.queueCombat_locked(updates, target, target, n3Packet(0x4727213e, 50000, target.id, body)) - server.finishDamage_locked(player, target, damage, now, updates) + server.finishDamageEffects_locked(player, target, now, updates) if target.health == 0 { // StopFight drains pending weapon results before the explicit nano death reset. server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{153, 0, 0, 0, 5})) diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -53,7 +53,7 @@ func TestWinterBiteTimesOneResultAndRecharge(t *testing.T) { if binary.BigEndian.Uint32(conn.packets[0][41:45]) != 0 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 29618 || binary.BigEndian.Uint32(conn.packets[2][29:33]) != 107 || binary.BigEndian.Uint32(conn.packets[3][16:20]) != 0x4727213e || int32(binary.BigEndian.Uint32(conn.packets[3][29:33])) != int32(health)-100 || binary.BigEndian.Uint32(conn.packets[3][33:37]) != 95 { t.Fatalf("native nano packets: %x", conn.packets) } - if len(npc.damageContributors) != 1 || npc.damageContributors[1] != 100-health { + if len(npc.damageContributors) != 1 || npc.damageContributors[damageContributor{player: 1}] != 100-health { t.Fatal("missing damage contribution", npc.damageContributors) } } @@ -180,12 +180,14 @@ func TestWinterBiteCancellationAndInvalidatedTargetRefundOnce(t *testing.T) { } func TestWinterBiteDeathUsesSharedLootAndStopsPendingWeapons(t *testing.T) { + t.Chdir(t.TempDir()) world, conn := newNanoCastingWorld() + t.Cleanup(func() { world.db.Close() }) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] npc.health, npc.monsterData = 1, 17655 npc.combatProfile = &gamedata.NPCCombatProfile{CorpseSeconds: 60, RespawnSeconds: 90} - npc.damageContributors = map[uint32]uint32{2: 10} - npc.leadingContributor = 2 + npc.damageContributors = map[damageContributor]uint32{{player: 2}: 10} + npc.leadingContributor = damageContributor{player: 2} world.handleCombat(client, attackPacket(1, npc.id)[20:]) player.rechargeUntil = time.Now().Add(time.Second) world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -0,0 +1,64 @@ +package main + +import ( + "database/sql" + "maps" + "time" +) + +func writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcState, error) { + state := target.worldState(true, time.Time{}) + if target.health == 0 { + state.Roaming.Moving, state.Roaming.Returning = false, false + if target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 { + state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second) + } + } + if _, err := tx.Exec(upsertRecordSQL("characters", characterColumns), append([]any{target.id}, state.Character.fields()...)...); err != nil { + return state, err + } + if _, err := tx.Exec(upsertRecordSQL("npcs", npcColumns), append([]any{target.id}, state.fields()...)...); err != nil { + return state, err + } + if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", target.id); err != nil { + return state, err + } + for contributor, damage := range target.damageContributors { + if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", target.id, contributor.player, contributor.team, damage); err != nil { + return state, err + } + } + return state, nil +} + +func (server *server) rememberNPCOutcome_locked(target *character, state npcState, now time.Time) { + if server.savedNPCs == nil { + server.savedNPCs = make(map[uint32]savedNPC) + } + nextSave := server.savedNPCs[target.id].NextSave + if nextSave.IsZero() { + nextSave = now.Add(20 * time.Second) + } + server.savedNPCs[target.id] = savedNPC{state, maps.Clone(target.damageContributors), nextSave} +} + +func (server *server) saveNPCDeath_locked(target *character, now time.Time) error { + db, err := server.database() + if err != nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + state, err := writeNPCOutcome_locked(tx, target, now) + if err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + server.rememberNPCOutcome_locked(target, state, now) + return nil +} diff --git a/server/special_locks.go b/server/special_locks.go @@ -1,9 +1,6 @@ package main -import ( - "maps" - "time" -) +import "time" func (server *server) loadSpecialAttackLocks() error { db, err := server.database() @@ -47,27 +44,10 @@ func (server *server) saveSpecialAttack_locked(player, target *character, skill "ON CONFLICT (player_id, skill) DO UPDATE SET locked_until=excluded.locked_until", player.id, skill, deadline); err != nil { return err } - state := target.worldState(true, time.Time{}) - if target.health == 0 { - state.Roaming.Moving, state.Roaming.Returning = false, false - if target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 { - state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second) - } - } - if _, err := tx.Exec(upsertRecordSQL("characters", characterColumns), append([]any{target.id}, state.Character.fields()...)...); err != nil { - return err - } - if _, err := tx.Exec(upsertRecordSQL("npcs", npcColumns), append([]any{target.id}, state.fields()...)...); err != nil { - return err - } - if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", target.id); err != nil { + state, err := writeNPCOutcome_locked(tx, target, now) + if err != nil { return err } - for id, damage := range target.damageContributors { - if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, damage) VALUES (?, ?, ?)", target.id, id, damage); err != nil { - return err - } - } if err := tx.Commit(); err != nil { return err } @@ -76,13 +56,6 @@ func (server *server) saveSpecialAttack_locked(player, target *character, skill player.specialAttackLocks = make(map[uint32]time.Time) } player.specialAttackLocks[skill] = deadline - if server.savedNPCs == nil { - server.savedNPCs = make(map[uint32]savedNPC) - } - nextSave := server.savedNPCs[target.id].NextSave - if nextSave.IsZero() { - nextSave = now.Add(20 * time.Second) - } - server.savedNPCs[target.id] = savedNPC{state, maps.Clone(target.damageContributors), nextSave} + server.rememberNPCOutcome_locked(target, state, now) return nil } diff --git a/server/state.go b/server/state.go @@ -40,8 +40,8 @@ type character struct { npcDefinitionID string roaming *npcRoaming - damageContributors map[uint32]uint32 - leadingContributor uint32 + damageContributors map[damageContributor]uint32 + leadingContributor damageContributor browserTokenHash string resurrectionTerminal uint32 diff --git a/server/team_loot_test.go b/server/team_loot_test.go @@ -0,0 +1,421 @@ +package main + +import ( + "bytes" + "encoding/binary" + "sync" + "testing" + "time" +) + +func teamLootUse(owner, sequence uint32) []byte { + request := lootUseRequest(sequence) + binary.BigEndian.PutUint32(request[8:12], owner) + binary.BigEndian.PutUint32(request[36:40], owner) + return request +} + +func TestTeamLootNanoAndFlingUseTheSameDurableTeamAward(t *testing.T) { + for _, attack := range []string{"nano", "Fling"} { + t.Run(attack, func(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + formTestTeam(t, world, 1, 2) + player, npc := world.characters[1], world.characters[1000000] + player.profession, player.nano = 8, 30 + player.stats = defaultCharacterStats() + player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6 + player.inventory.LearnedNanos = []uint32{29618} + if attack == "Fling" { + player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: 3}} + } + npc.health, npc.level = 1, 1 + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + + if attack == "nano" { + if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + world.advanceNanos(world.clients[1].nanoCast.readyAt.Add(time.Nanosecond)) + } else if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t) + world.handleLootUse(world.clients[2], teamLootUse(2, 1)) + + if npc.health != 0 || npc.corpse == nil || npc.corpse.team != 1 || world.clients[2].lootCorpse != npc.id || + restored.characters[1000000].corpse == nil || restored.characters[1000000].corpse.team != 1 || + len(world.npcRespawns) != 1 || len(world.corpseExpiry) != 1 { + t.Fatal("alternate attack lost durable team ownership or shared native Use") + } + }) + } +} + +func TestTeamLootHitTimeCreditDoesNotMoveWhenMemberLeaves(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + fourth := world.newCharacter() + fourth.position = [3]float32{} + if err := world.saveUser_locked(fourth); err != nil { + t.Fatal(err) + } + world.clients[4] = &worldClient{id: 4, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + formTestTeam(t, world, 1, 2) + formTestTeam(t, world, 1, 4) + npc := world.characters[1000000] + npc.health = 13 + for _, id := range []uint32{1, 2} { + world.handleCombat(world.clients[id], attackPacket(id, npc.id)[20:]) + world.advanceCombat(world.characters[id].nextAttack) + world.handleCombat(world.clients[id], stopFightPacket(id)[20:]) + } + + if err := world.handleTeamAction(world.clients[2], teamRequest(2, 24, 0, 0)); err != nil { + t.Fatal(err) + } + for _, id := range []uint32{2, 3, 3} { + world.handleCombat(world.clients[id], attackPacket(id, npc.id)[20:]) + world.advanceCombat(world.characters[id].nextAttack) + world.handleCombat(world.clients[id], stopFightPacket(id)[20:]) + } + world.handleLootUse(world.clients[2], teamLootUse(2, 1)) + world.handleLootUse(world.clients[4], teamLootUse(4, 1)) + + if npc.corpse == nil || npc.corpse.team != 1 || world.clients[2].lootCorpse != 0 || world.clients[4].lootCorpse != npc.id { + t.Fatal("departure retroactively moved team damage into solo credit or retained team access") + } +} + +func TestTeamLootFailedCashUseRetainsMoneyAndPublishesNoSuccess(t *testing.T) { + world := newTeamLootWorld(t) + for _, client := range world.clients { + client.conn.(*combatTestConn).packets = nil + } + failDatabaseWrites(t, world) + + err := world.handleLootUse(world.clients[2], teamLootUse(2, 1)) + + if err == nil || world.characters[1000000].corpse.credits != 123 || world.characters[2].inventory.Credits != 0 || world.clients[2].lootCorpse != 0 { + t.Fatal("failed cash transaction changed corpse or player ownership") + } + for _, client := range world.clients { + if len(client.conn.(*combatTestConn).packets) != 0 { + t.Fatal("failed cash transaction published success or a cash reset") + } + } +} + +func TestTeamLootFailedNanoDeathRefundsCostWithoutAnAward(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + formTestTeam(t, world, 1, 2) + player, npc := world.characters[1], world.characters[1000000] + player.profession, player.nano = 8, 30 + player.stats = defaultCharacterStats() + player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6 + player.inventory.LearnedNanos = []uint32{29618} + npc.health = 1 + if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + deadline := world.clients[1].nanoCast.readyAt + failDatabaseWrites(t, world) + + world.advanceNanos(deadline.Add(time.Nanosecond)) + + if npc.health != 1 || npc.corpse != nil || len(npc.damageContributors) != 0 || player.nano != 30 || world.clients[1].nanoCast != nil || + len(world.npcRespawns)+len(world.corpseExpiry) != 0 { + t.Fatal("failed nano death spent cost or published a team award") + } +} + +func TestTeamLootFilledBackpackRetainsContentsForTheTakingMember(t *testing.T) { + world := newFilledLootContainerWorld(t, 143832) + member := world.newCharacter() + member.position = [3]float32{} + if err := world.saveUser_locked(member); err != nil { + t.Fatal(err) + } + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + formTestTeam(t, world, 1, 2) + corpse := world.characters[1000000] + corpse.corpse.looter, corpse.corpse.team = 0, world.characters[1].team.id + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + + if err := world.handleLootUse(world.clients[2], teamLootUse(2, 1)); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(world.clients[2], teamLootTake(2)); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t) + + if len(corpse.corpse.items) != 0 || len(restored.characters[1].inventory.Items) != 0 || len(restored.characters[2].inventory.Items) != 1 || + restored.characters[2].inventory.Items[0] != (ownedItem{ID: 17, Type: 51017, Template: 143832, Quality: 1, Slot: 64, Count: 1}) || + len(restored.characters[2].inventory.Containers[17]) != 1 || + restored.characters[2].inventory.Containers[17][0] != (ownedItem{ID: 18, Type: 51005, Template: 152030, Quality: 42, Count: 3}) || + len(restored.items) != 2 || restored.nextItem != 18 { + t.Fatal("team pickup detached a filled backpack, duplicated its contents or changed item metadata") + } +} + +func teamLootTake(owner uint32) []byte { + request := lootTakeRequest() + binary.BigEndian.PutUint32(request[8:12], owner) + binary.BigEndian.PutUint32(request[28:32], owner) + return request +} + +func newTeamLootWorld(t *testing.T) *server { + t.Helper() + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + formTestTeam(t, world, 1, 2) + npc := world.characters[1000000] + npc.health, npc.level = 1, 1 + if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(world.characters[1].nextAttack) + npc.corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}} + npc.corpse.credits = 123 + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + return world +} + +func TestTeamLootAggregatesDamageAndAllowsBothMembers(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + formTestTeam(t, world, 1, 2) + npc := world.characters[1000000] + npc.health = 19 + + for _, id := range []uint32{1, 3, 3, 2, 3, 2, 1} { + if err := world.handleCombat(world.clients[id], attackPacket(id, npc.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(world.characters[id].nextAttack) + world.handleCombat(world.clients[id], stopFightPacket(id)[20:]) + } + for _, id := range []uint32{1, 2, 3} { + request := lootUseRequest(1) + binary.BigEndian.PutUint32(request[8:12], id) + binary.BigEndian.PutUint32(request[36:40], id) + if err := world.handleLootUse(world.clients[id], request); err != nil { + t.Fatal(err) + } + } + + if npc.health != 0 || world.clients[1].lootCorpse != npc.id || world.clients[2].lootCorpse != npc.id || world.clients[3].lootCorpse != 0 { + t.Fatal("team's ten damage did not beat the solo player's nine, or All rights were not shared") + } + packet := corpsePacket(npc) + length := int(binary.BigEndian.Uint16(packet[6:8])) + if binary.BigEndian.Uint32(packet[length-20:]) != world.characters[1].team.id || binary.BigEndian.Uint32(packet[length-16:]) != 3 || + binary.BigEndian.Uint64(packet[length-12:length-4]) != 0 { + t.Fatal("native corpse did not announce team All rights with a null designated looter") + } +} + +func TestTeamLootCompetingBeneficiariesAndTies(t *testing.T) { + for _, scenario := range []struct { + name string + teams [][2]uint32 + health uint32 + swings []uint32 + player uint32 + team uint32 + }{ + {"overlapping player and team IDs", [][2]uint32{{2, 3}}, 19, []uint32{2, 1, 1, 3, 1, 3, 2}, 0, 1}, + {"stronger solo wins despite team final hit", [][2]uint32{{1, 2}}, 19, []uint32{3, 1, 3, 2, 3, 3, 1}, 3, 0}, + {"team reaches tied total first", [][2]uint32{{1, 2}}, 12, []uint32{1, 3, 2, 3}, 0, 1}, + {"solo reaches tied total first", [][2]uint32{{1, 2}}, 12, []uint32{3, 1, 3, 2}, 3, 0}, + {"stronger second team wins", [][2]uint32{{1, 2}, {3, 4}}, 19, []uint32{1, 3, 4, 2, 3, 4, 1}, 0, 2}, + } { + t.Run(scenario.name, func(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + fourth := world.newCharacter() + if err := world.saveUser_locked(fourth); err != nil { + t.Fatal(err) + } + fourth.position = [3]float32{} + world.clients[4] = &worldClient{id: 4, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + for _, pair := range scenario.teams { + formTestTeam(t, world, pair[0], pair[1]) + } + npc := world.characters[1000000] + npc.health = scenario.health + + for _, id := range scenario.swings { + world.handleCombat(world.clients[id], attackPacket(id, npc.id)[20:]) + world.advanceCombat(world.characters[id].nextAttack) + world.handleCombat(world.clients[id], stopFightPacket(id)[20:]) + } + + if npc.health != 0 || npc.corpse.looter != scenario.player || npc.corpse.team != scenario.team { + t.Fatalf("wrong winning beneficiary: %+v", npc.corpse) + } + }) + } +} + +func TestTeamLootConcurrentUseAndPickupHaveOneDurableOwner(t *testing.T) { + world := newTeamLootWorld(t) + npc := world.characters[1000000] + var workers sync.WaitGroup + + for _, id := range []uint32{1, 2, 3} { + workers.Go(func() { + if err := world.handleLootUse(world.clients[id], teamLootUse(id, 1)); err != nil { + t.Error(err) + } + }) + } + workers.Wait() + if world.clients[1].lootCorpse != npc.id || world.clients[2].lootCorpse != npc.id || world.clients[3].lootCorpse != 0 { + t.Fatal("All windows or outsider exclusion failed") + } + world.clients[3].lootCorpse = npc.id + for _, id := range []uint32{1, 2, 3} { + workers.Go(func() { + if err := world.handleInventory(world.clients[id], teamLootTake(id)); err != nil { + t.Error(err) + } + }) + } + workers.Wait() + restored := newTestInventoryServer(t) + + if len(npc.corpse.items) != 0 || len(restored.characters[1000000].corpse.items) != 0 || + len(restored.characters[1].inventory.Items)+len(restored.characters[2].inventory.Items) != 1 || + len(restored.characters[3].inventory.Items) != 0 || restored.characters[3].inventory.Credits != 0 || + restored.characters[1].inventory.Credits+restored.characters[2].inventory.Credits != 123 || restored.characters[1000000].corpse.credits != 0 { + t.Fatal("concurrent members duplicated an item or cash, or stale outsider handle authorized pickup") + } + for _, id := range []uint32{1, 2} { + packets := world.clients[id].conn.(*combatTestConn).packets + refreshed := false + for _, packet := range packets { + refreshed = refreshed || bytes.Equal(packet[16:], targetPacket(lootInventoryPacket(id, npc, false))[16:]) + } + if len(world.characters[id].inventory.Items) == 0 && !refreshed { + t.Fatal("other open team window retained a taken icon") + } + } +} + +func TestTeamLootDepartureRevokesOpenHandlesAndNewTeamCannotInherit(t *testing.T) { + for _, action := range []uint32{22, 24} { + t.Run(map[uint32]string{22: "kick", 24: "leave"}[action], func(t *testing.T) { + world := newTeamLootWorld(t) + previous := world.characters[1].team.id + for _, id := range []uint32{1, 2} { + world.handleLootUse(world.clients[id], teamLootUse(id, 1)) + } + + owner, target := uint32(1), uint32(2) + if action == 24 { + owner, target = 2, 0 + } + if err := world.handleTeamAction(world.clients[owner], teamRequest(owner, action, target, 0)); err != nil { + t.Fatal(err) + } + if world.clients[1].lootCorpse != 0 || world.clients[2].lootCorpse != 0 { + t.Fatal("dissolving a pair retained open corpse handles") + } + formTestTeam(t, world, 1, 2) + for _, id := range []uint32{1, 2} { + world.clients[id].lootCorpse = 1000000 + world.handleInventory(world.clients[id], teamLootTake(id)) + world.handleLootUse(world.clients[id], teamLootUse(id, 2)) + } + + if world.characters[1].team.id == previous || len(world.characters[1000000].corpse.items) != 1 || + len(world.characters[1].inventory.Items)+len(world.characters[2].inventory.Items) != 0 { + t.Fatal("replacement team inherited historical corpse rights") + } + }) + } +} + +func TestTeamLootFailedPickupAndDeparturePreserveRightsAndContents(t *testing.T) { + world := newTeamLootWorld(t) + world.handleLootUse(world.clients[2], teamLootUse(2, 1)) + before := len(world.clients[2].conn.(*combatTestConn).packets) + failDatabaseWrites(t, world) + + errTake := world.handleInventory(world.clients[2], teamLootTake(2)) + errLeave := world.handleTeamAction(world.clients[2], teamRequest(2, 24, 0, 0)) + + if errTake == nil || errLeave == nil || world.clients[2].lootCorpse != 1000000 || world.characters[2].team == nil || + len(world.clients[2].conn.(*combatTestConn).packets) != before || len(world.characters[1000000].corpse.items) != 1 || + len(world.characters[2].inventory.Items) != 0 { + t.Fatal("failed writes changed live rights, contents or acknowledgements") + } +} + +func TestTeamLootContributionsAndAwardSurviveRestart(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + formTestTeam(t, world, 2, 3) + npc := world.characters[1000000] + npc.health, npc.level = 7, 1 + world.handleCombat(world.clients[2], attackPacket(2, npc.id)[20:]) + world.advanceCombat(world.characters[2].nextAttack) + world.handleCombat(world.clients[2], stopFightPacket(2)[20:]) + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t) + for _, id := range []uint32{1, 2, 3} { + restored.clients[id] = &worldClient{id: id, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + } + + for _, id := range []uint32{3, 1} { + restored.handleCombat(restored.clients[id], attackPacket(id, npc.id)[20:]) + restored.advanceCombat(restored.characters[id].nextAttack) + restored.handleCombat(restored.clients[id], stopFightPacket(id)[20:]) + } + again := newTestInventoryServer(t) + + if npc.damageContributors[damageContributor{team: 1}] != 3 || restored.characters[1000000].health != 0 || + again.characters[1000000].corpse == nil || again.characters[1000000].corpse.team != 1 || again.characters[1000000].corpse.looter != 0 || + again.characters[2].team.id != 1 || again.characters[3].team.id != 1 || len(again.characters[1000000].damageContributors) != 0 || + len(again.npcRespawns) != 1 || len(again.corpseExpiry) != 1 { + t.Fatalf("restart lost hit-time team credit or the immediate durable death award: old=%+v HP=%d corpse=%+v team=%+v respawns=%d expiry=%d", npc.damageContributors, restored.characters[1000000].health, again.characters[1000000].corpse, again.characters[2].team, len(again.npcRespawns), len(again.corpseExpiry)) + } +} + +func TestTeamLootFailedKillingBlowPublishesNoDeath(t *testing.T) { + t.Chdir(t.TempDir()) + world := newLootRightsWorld(t) + formTestTeam(t, world, 1, 2) + npc := world.characters[1000000] + npc.health = 1 + if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + world.clients[1].conn.(*combatTestConn).packets = nil + failDatabaseWrites(t, world) + + world.advanceCombat(world.characters[1].nextAttack) + world.advanceCombat(time.Now().Add(time.Hour)) + + if npc.health != 1 || npc.corpse != nil || len(npc.damageContributors) != 0 || len(world.npcRespawns)+len(world.corpseExpiry) != 0 { + t.Fatal("failed killing-blow transaction changed HP, rights or lifecycle") + } + for _, packet := range world.clients[1].conn.(*combatTestConn).packets { + if key := binary.BigEndian.Uint32(packet[16:20]); key == 0x4f474e05 || key == 0x46002f16 || + key == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 99 { + t.Fatal("failed death was published") + } + } +} diff --git a/server/teams.go b/server/teams.go @@ -323,7 +323,16 @@ func (server *server) leaveTeam_locked(player *character, updates map[*worldClie } for _, member := range previous.members { other := server.clients[member] - if other == nil || !other.ready || other.loading { + if other == nil { + continue + } + // A committed departure revokes this team's existing open remains. + if corpse := server.characters[other.lootCorpse]; corpse != nil && corpse.corpse != nil && corpse.corpse.team == previous.id && + (server.characters[member].team == nil || server.characters[member].team.id != previous.id) { + updates[other] = append(updates[other], lootClosePacket(member, other.lootCorpse)) + other.lootCorpse = 0 + } + if !other.ready || other.loading { continue } if remaining == nil { diff --git a/server/world.sql b/server/world.sql @@ -147,6 +147,7 @@ CREATE TABLE IF NOT EXISTS npcs ( present INTEGER NOT NULL, respawn_at DATETIME NOT NULL, leading_contributor INTEGER NOT NULL, + leading_team INTEGER NOT NULL, has_roaming INTEGER NOT NULL, home_x REAL NOT NULL, home_y REAL NOT NULL, home_z REAL NOT NULL, destination_x REAL NOT NULL, destination_y REAL NOT NULL, destination_z REAL NOT NULL, @@ -155,14 +156,17 @@ CREATE TABLE IF NOT EXISTS npcs ( returning_home INTEGER NOT NULL, has_corpse INTEGER NOT NULL, looter INTEGER NOT NULL, + loot_team INTEGER NOT NULL, credits INTEGER NOT NULL, expires_at DATETIME NOT NULL ); CREATE TABLE IF NOT EXISTS npc_damage_contributors ( npc_id INTEGER NOT NULL REFERENCES npcs(id) ON DELETE CASCADE, player_id INTEGER NOT NULL, + team_id INTEGER NOT NULL, damage INTEGER NOT NULL, - PRIMARY KEY (npc_id, player_id) + PRIMARY KEY (npc_id, player_id, team_id), + CHECK ((player_id > 0 AND team_id = 0) OR (player_id = 0 AND team_id > 0)) ); CREATE TABLE IF NOT EXISTS items ( id INTEGER PRIMARY KEY CHECK (id BETWEEN 1 AND 4294967295), diff --git a/server/world_store.go b/server/world_store.go @@ -18,6 +18,7 @@ type roamingState struct { type corpseState struct { Looter uint32 + Team uint32 Credits uint32 ExpiresAt time.Time } @@ -31,21 +32,21 @@ type npcState struct { HasCorpse bool Present bool RespawnAt time.Time - LeadingContributor uint32 + LeadingContributor damageContributor } type savedNPC struct { State npcState - Contributors map[uint32]uint32 + Contributors map[damageContributor]uint32 NextSave time.Time } -const npcColumns = "definition, present, respawn_at, leading_contributor, has_roaming, home_x, home_y, home_z, destination_x, destination_y, destination_z, next_move, moving, returning_home, has_corpse, looter, credits, expires_at" +const npcColumns = "definition, present, respawn_at, leading_contributor, leading_team, has_roaming, home_x, home_y, home_z, destination_x, destination_y, destination_z, next_move, moving, returning_home, has_corpse, looter, loot_team, credits, expires_at" func (state *npcState) fields() []any { - return []any{&state.Definition, &state.Present, &state.RespawnAt, &state.LeadingContributor, &state.HasRoaming, + return []any{&state.Definition, &state.Present, &state.RespawnAt, &state.LeadingContributor.player, &state.LeadingContributor.team, &state.HasRoaming, &state.Roaming.Home[0], &state.Roaming.Home[1], &state.Roaming.Home[2], &state.Roaming.Destination[0], &state.Roaming.Destination[1], &state.Roaming.Destination[2], - &state.Roaming.NextMove, &state.Roaming.Moving, &state.Roaming.Returning, &state.HasCorpse, &state.Corpse.Looter, &state.Corpse.Credits, &state.Corpse.ExpiresAt} + &state.Roaming.NextMove, &state.Roaming.Moving, &state.Roaming.Returning, &state.HasCorpse, &state.Corpse.Looter, &state.Corpse.Team, &state.Corpse.Credits, &state.Corpse.ExpiresAt} } func (npc *character) worldState(present bool, respawnAt time.Time) npcState { @@ -58,7 +59,7 @@ func (npc *character) worldState(present bool, respawnAt time.Time) npcState { } if npc.corpse != nil { state.HasCorpse = true - state.Corpse = corpseState{npc.corpse.looter, npc.corpse.credits, npc.corpse.expiresAt} + state.Corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt} } return state } @@ -100,7 +101,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui leaving := server.npcZones[npc.playfield] && !zones[npc.playfield] corpse := corpseState{} if npc.corpse != nil { - corpse = corpseState{npc.corpse.looter, npc.corpse.credits, npc.corpse.expiresAt} + corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt} } // Loot transactions must persist corpse ownership and cash atomically. lootChanged := npc.corpse != nil && (!exists || !previous.State.HasCorpse || previous.State.Corpse != corpse) @@ -127,8 +128,8 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", id); err != nil { return nil, err } - for player, damage := range npc.damageContributors { - if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, damage) VALUES (?, ?, ?)", id, player, damage); err != nil { + for contributor, damage := range npc.damageContributors { + if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", id, contributor.player, contributor.team, damage); err != nil { return nil, err } } @@ -186,7 +187,7 @@ func (server *server) loadNPCs() (bool, error) { npc.roaming = &npcRoaming{state.Roaming.Home, state.Roaming.Destination, state.Roaming.NextMove, state.Roaming.Moving, state.Roaming.Returning} } if state.HasCorpse { - npc.corpse = &npcCorpse{looter: state.Corpse.Looter, credits: state.Corpse.Credits, expiresAt: state.Corpse.ExpiresAt} + npc.corpse = &npcCorpse{looter: state.Corpse.Looter, team: state.Corpse.Team, credits: state.Corpse.Credits, expiresAt: state.Corpse.ExpiresAt} } if state.Present { server.characters[npc.id] = npc @@ -210,25 +211,26 @@ func (server *server) loadNPCs() (bool, error) { rows.Close() // Contribution rows include hidden respawn sources as well as visible NPCs. - rows, err = db.Query("SELECT npc_id, player_id, damage FROM npc_damage_contributors") + rows, err = db.Query("SELECT npc_id, player_id, team_id, damage FROM npc_damage_contributors") if err != nil { return false, err } defer rows.Close() for rows.Next() { - var id, player, damage uint32 - if err := rows.Scan(&id, &player, &damage); err != nil { + var id, damage uint32 + var contributor damageContributor + if err := rows.Scan(&id, &contributor.player, &contributor.team, &damage); err != nil { return false, err } if characters[id].damageContributors == nil { - characters[id].damageContributors = make(map[uint32]uint32) + characters[id].damageContributors = make(map[damageContributor]uint32) } - characters[id].damageContributors[player] = damage + characters[id].damageContributors[contributor] = damage saved := server.savedNPCs[id] if saved.Contributors == nil { - saved.Contributors = make(map[uint32]uint32) + saved.Contributors = make(map[damageContributor]uint32) } - saved.Contributors[player] = damage + saved.Contributors[contributor] = damage server.savedNPCs[id] = saved } return true, rows.Err()