aorecomp

Anarchy Online classic in the browser

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


commit e4bc2b7c67bd19e70671a07637e08fea8fcc5073
parent c4be0d351c00932ecfcdc9102e7d4985bbf04897
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 23:38:54 +0000

Enable starter pet attacks with owner rewards and atomic death

Diffstat:
MTODO.md | 7+++++--
Adocs/pet-attack.md | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/pet-owner-protocol.md | 2++
Mdocs/pet-summoning.md | 5+++--
Aserver/browser_pet_attack_test.go | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 34++++++++++++++++++----------------
Mserver/interest.go | 2+-
Mserver/npc_outcome.go | 9+++++++++
Mserver/npc_pursuit.go | 8+++++---
Mserver/npc_threat.go | 27++++++++++++++++++++++++---
Aserver/pet_attack_test.go | 304+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/pet_follow.go | 45++++++++++++++++++++++++++++++++++++++++-----
Mserver/pets.go | 14+++++++++++++-
Atools/client/test_pet_attack.mjs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/client/test_pet_owner_protocol.mjs | 14+++++++++++++-
15 files changed, 689 insertions(+), 34 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -121,8 +121,11 @@ research separately. More screenshots and test cases do not count as new gamepla reconnect/cold recovery, with every row covered by server regressions. 123 placements remain empty and visibly identify unsupported purchases while retaining loot sales. The Meta-Physicist starter Mind Pain now executes its - complete damage and six-skill debuff; useful shop upgrades and pet attacks, - Engineer robots and other unfinished profession essentials remain open, + complete damage and six-skill debuff. Its existing Lesser Anger Manifestation + now accepts native attack commands, pursues enemies, takes retaliation and + credits its owner through shared rewards; retreat, death/removal and recovery + checks pass under an explicit [provisional fist profile](docs/pet-attack.md). + Useful shop upgrades, Engineer robots and other profession essentials remain open, alongside the bounded ordinary-play affordability check. New mission offers now pay an explicit provisional 500 credits per selected mission level; level-one completion cash covers recovery/ammunition resupply in all three diff --git a/docs/pet-attack.md b/docs/pet-attack.md @@ -0,0 +1,78 @@ +# Starter attack pet + +A5 admits `/pet attack` for the existing Lesser Anger Manifestation (nano43324, +PT50, level1). The owner selects a living, visible creature in the same playfield. +Players, owned pets, human NPCs, corpses and unavailable targets are rejected, +matching the current ordinary player PvE scope. No named-pet selector is admitted. + +## Original evidence and explicit policy + +Real keyboard input in `TestBrowserPetOwnerProtocol` captures command body +`7, 0, 1009, 0, 0`. The separate native target-selection message supplies the +opponent; the command's zero argument is not an opponent ID. The capture is in +`local/pet-owner-protocol/20261105-152636/verification.json`. Original help in +`cd_image/text/help/Pet Commands.txt` describes attacking the selected target. + +Original item records120637/120638 are the right combat-pet fist, QL1..400. +At QL1 they supply damage9..16, critical bonus9, MeleeAC91, MA100 against +EvadeClose155 (both100%), range10 and attack/recharge235 centiseconds. The left +pair120634/120635 has the same numeric fields and a different animation. +Equippers120639/120636 reference MEW1/MEW2. Complete records are retained in +`server/gamedata/items/items_036.yaml`; the summon record is in `items_167.yaml`. + +The original server binding from PT50 to a weapon, hand count and actor ratings +is unavailable. The alpha explicitly selects one right fist, raw MA/evades/Nano +Resist5, initiative0 and AggDef75. This is a provisional policy, not proof of +original dual wielding or balance. Existing17HP/25nano and model96195 retain +[their earlier evidence limitations](pet-summoning.md). Reopen historical +research only with an original server template or direct original-server +measurement of that binding. + +## Combat and ownership + +The pet uses shared NPC route planning, collision, range/line-of-sight checks, +hit rolls, weapon timing and damage. Repeated attack commands preserve its +pending swing. Follow, behind and wait cancel outgoing combat; an enemy's +independent attack continues. Termination and expiry cancel both sides. + +Enemy threat identifies the attacking pet. Damage credit identifies its owner +or the owner's team at each hit, using existing kill/loot eligibility and team +rules. A kill commits enemy death, loot and owner XP through the shared outcome +transaction. This does not add previously unsupported team XP distribution. + +Owner death, disconnection, loading, zoning or pet expiry stops the encounter. +A lethal hit on the pet atomically deletes the NPC and ownership before removing +it from clients. The summon dissolves without loot, XP, mission kill credit or +respawn; its owner can summon again. Failed deletion/commit retains the living +entity and ownership for retry. This dissolution policy is provisional. + +Cold recovery restores the weapon profile and ownership, while combat commands +remain transient. Existing idle NPC regeneration supplies recovery between +fights. This change adds no new pet levels, healing commands, guard/hunt modes, +Engineer robots or shop upgrades. + +## Focused checks + +`pet_attack_test.go` exercises command admission, pursuit, original weapon +cadence, retaliation, owner/team attribution, kill rewards, owner availability, +failed reward/removal writes, cold recovery and replacement summoning. Existing +follow, wait, retreat, dismissal and expiry regressions protect command changes. + +`TestBrowserPetAttack` uses two native clients, real target picking and keyboard +commands, with a controlled32HP Leet to keep two hits and one retaliation short. +It checks behind/wait, pursuit, owner credit, reconnect, termination and cold +recovery. This fixture is not evidence of ordinary-play progression or pet +balance against a full-health enemy. + +November 5 native passes: combat31.42 seconds in +`local/pet-attack/20261105-153601/`, owner protocol23.57 seconds in +`local/pet-owner-protocol/20261105-153420/`, and retreat22.23 seconds in +`local/pet-retreat/20261105-153444/`. Both combat views were visually inspected. +The32HP fixture took two16-point hits; the pet took8, owner health stayed34, +owner XP became100 and the corpse retained owner1's rights and5credits. +Reconnect and cold recovery retained the reward; termination removed only +owner1's pet. Validation logs are in `local/alpha-pet-attack/`. +The final shared regression selection passed133 roots/1162 results; the new +interest-replay assertion passed separately after its fixture was corrected to +inspect the normal sent-packet format (134 roots/1163 results in total). +`go vet ./server/...`, JavaScript syntax checks and `git diff --check` also pass. diff --git a/docs/pet-owner-protocol.md b/docs/pet-owner-protocol.md @@ -30,6 +30,8 @@ Original `/pet behind` captures `2, 0, 1009, 0, 0`; its admitted combat stop and owner-follow transition are documented in [pet retreat](pet-retreat.md). Original `/pet terminate` captures `10, 0, 1009, 0, 0`; the owned [dismissal implementation](pet-dismissal.md) retires only that owner's set. +Original `/pet attack` captures `7, 0, 1009, 0, 0`; its opponent comes from +separate target selection. See [starter pet combat](pet-attack.md). Owner membership replays after CharacterReady and the actor's equipment/nano effects. A two-owned-pet reload regression shows that early bootstrap AddPet diff --git a/docs/pet-summoning.md b/docs/pet-summoning.md @@ -24,8 +24,9 @@ the [original protocol](pet-owner-protocol.md). Model96195, name, appearance229 and the level1 resource profile17HP/25nano are a bounded reconstruction. The HP/nano values come from retained2006..2010 wiki data, not an original14.9.1 server measurement. The later data's four-point skill -requirements are not imported: the original requires eight. Weapon selection, -raw combat stats, master/type metadata and exact spawn placement remain open. +requirements are not imported: the original requires eight. The alpha now uses +an explicit provisional [single-fist combat profile](pet-attack.md). Historical +weapon binding, raw stats, master/type metadata and exact placement remain open. Player-versus-pet combat remains unsupported. The owned pet separately admits the original all-pets [follow and wait commands](pet-follow.md) and [dismissal](pet-dismissal.md). diff --git a/server/browser_pet_attack_test.go b/server/browser_pet_attack_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "ao/server/gamedata" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserPetAttack(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native pet attack") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/pet-attack", time.Now().Format("20060102-150405")) + world := newBrowserOwnedPetWorld(t) + // A weakened enemy makes the two-hit/one-retaliation outcome a short fixture. + target := world.characters[1000000] + target.level, target.health, target.position = 1, 32, [3]float32{950, 16.5, 511} + target.geometry = world.geometry + target.walkSurface(target.position, 2) + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + target.motion = &npcMotion{home: target.position} + world.mobileNPCs = map[uint32][]*character{705: {target}} + world.combatRoll = landedCombatRoll + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + pet := world.characters[1000001] + state := map[string]any{"targetHealth": target.health, "targetFighting": target.fighting, + "experience": world.characters[1].experience, "ownerNano": world.characters[1].nano, + "ownerHealth": world.characters[1].health, "ownerPets": len(world.characters[1].pets), + "peerPets": len(world.characters[2].pets), "petPresent": pet != nil} + if pet != nil { + state["petHealth"], state["petFighting"], state["petPosition"], state["follow"] = pet.health, pet.fighting, pet.position, pet.followTarget + } + if target.corpse != nil { + state["looter"], state["credits"] = target.corpse.looter, target.corpse.credits + } + json.NewEncoder(w).Encode(state) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advancePlayerMovement(now) + world.advanceNPCs(now) + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_pet_attack.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } + cancel() + <-stopped + cold := newServerForTest(t) + if target.health != 0 || target.corpse == nil || target.corpse.looter != 1 || target.corpse.credits != 5 || + world.characters[1].experience != 100 || cold.characters[1].experience != 100 || cold.characters[1000000].corpse.looter != 1 || + len(world.characters[1].pets) != 0 || len(cold.characters[1].pets) != 0 || len(cold.characters[2].pets) != 1 || + world.characters[1].nano != 25 || cold.characters[1].nano != 25 { + t.Fatal("native attack lost rewards, pet ownership or cold recovery") + } +} diff --git a/server/combat.go b/server/combat.go @@ -434,15 +434,8 @@ func (server *server) advanceCombat(now time.Time) { server.stopAttack_locked(attacker, updates) continue } - // Require each player to still have a ready connection in this playfield. - available := true - for _, character := range []*character{attacker, target} { - if !character.npc { - client := server.clients[character.id] - available = available && client != nil && client.ready && !client.loading - } - } - if !available { + // Owned pets share their owner's connection and playfield availability. + if !server.combatParticipantAvailable_locked(attacker, now) || !server.combatParticipantAvailable_locked(target, now) { server.stopAttack_locked(attacker, updates) continue } @@ -530,8 +523,12 @@ func (server *server) prepareDamage_locked(attacker, target *character, damage u corpse := *target.corpse candidate.corpse = &corpse } - // Credit the player or team present at each hit for this NPC life. - if candidate.npc && !attacker.npc && damage != 0 { + // Threat follows the attacking actor; reward credit follows its owner/team. + owner := attacker + if attacker.pet != nil { + owner = server.characters[attacker.pet.owner] + } + if candidate.npc && candidate.pet == nil && !owner.npc && damage != 0 { if candidate.threat == nil { candidate.threat = make(map[uint32]int64) } @@ -539,9 +536,9 @@ func (server *server) prepareDamage_locked(attacker, target *character, damage u if candidate.damageContributors == nil { candidate.damageContributors = make(map[damageContributor]uint32) } - contributor := damageContributor{player: attacker.id} - if attacker.team != nil { - contributor = damageContributor{team: attacker.team.id} + contributor := damageContributor{player: owner.id} + if owner.team != nil { + contributor = damageContributor{team: owner.team.id} } candidate.damageContributors[contributor] += damage // Equal totals retain the first contributor to reach that total. @@ -553,7 +550,7 @@ func (server *server) prepareDamage_locked(attacker, target *character, damage u candidate.threat = nil } monster := gamedata.MonsterTemplates[candidate.monsterData] - if candidate.health == 0 && candidate.npc && monster != nil && len(monster.DeathAnimations) != 0 { + if candidate.health == 0 && candidate.npc && candidate.pet == nil && monster != nil && len(monster.DeathAnimations) != 0 { if candidate.corpse == nil { candidate.corpse = &npcCorpse{} } @@ -569,6 +566,11 @@ func (server *server) prepareDamage_locked(attacker, target *character, damage u } func (server *server) finishDamageEffects_locked(attacker, target *character, previous character, now time.Time, updates map[*worldClient][][]byte) { + if target.health == 0 && target.pet != nil { + // The committed lethal hit dissolves the summon and frees the owner's slot. + server.removePet_locked(target, updates) + return + } if target.health != 0 { for _, effect := range previous.activeNanos { // Replacement replays its strain through Action177; breaks need explicit removal. @@ -630,7 +632,7 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr npc: target, at: respawn, }) } - } else if target.npc && !attacker.npc { + } else if target.npc && target.pet == nil && (!attacker.npc || attacker.pet != nil) { // A hostile cast or a zero-damage hit still starts an encounter. if target.threat == nil { target.threat = make(map[uint32]int64) diff --git a/server/interest.go b/server/interest.go @@ -76,7 +76,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim } if other.pet != nil && other.followTarget != 0 && !other.pet.paused { updates = append(updates, petFollowPacket(other, other.followTarget)) - } else if other.pet == nil && other.motion != nil && other.motion.moving { + } else if other.motion != nil && other.motion.moving { updates = append(updates, npcRoutePacket(other, other.position)) } } diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -8,6 +8,12 @@ import ( ) func (server *server) writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcState, error) { + if target.pet != nil && target.health == 0 { + // Summons dissolve without loot, mission completion or a respawn schedule. + var removed uint32 + err := tx.QueryRow("DELETE FROM characters WHERE id=? RETURNING id", target.id).Scan(&removed) + return npcState{}, err + } drops, err := server.rollCorpseLoot_locked(target) if err != nil { return npcState{}, err @@ -87,6 +93,9 @@ func writeNPCState_locked(tx *sql.Tx, target *character, state *npcState) error } func (server *server) rememberNPCOutcome_locked(target *character, state npcState, now time.Time) { + if target.pet != nil && target.health == 0 { + return + } if server.savedNPCs == nil { server.savedNPCs = make(map[uint32]savedNPC) } diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go @@ -16,13 +16,15 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se destination := npc.motion.home if npc.fighting != 0 { target := server.characters[npc.fighting] - client := server.clients[npc.fighting] - if target == nil || target.health == 0 || target.playfield != npc.playfield || client == nil || !client.ready || client.loading { + if !server.combatParticipantAvailable_locked(target, now) || target.playfield != npc.playfield { server.selectNPCTarget_locked(npc, now, updates) target = server.characters[npc.fighting] } if npc.fighting != 0 { - destination = predictedPosition_locked(target, now) + destination = target.position + if !target.npc { + destination = predictedPosition_locked(target, now) + } if !npc.motion.moving && npc.pursuitArrived(destination) { server.stopNPCMotion_locked(npc, updates) return true diff --git a/server/npc_threat.go b/server/npc_threat.go @@ -2,13 +2,34 @@ package main import "time" +func (server *server) combatParticipantAvailable_locked(actor *character, now time.Time) bool { + if actor == nil || actor.health == 0 { + return false + } + if actor.pet != nil { + owner := server.characters[actor.pet.owner] + return now.Before(actor.pet.expiresAt) && owner.playfield == actor.playfield && server.combatParticipantAvailable_locked(owner, now) + } + if actor.npc { + return true + } + client := server.clients[actor.id] + return client != nil && client.ready && !client.loading +} + func (server *server) selectNPCTarget_locked(npc *character, now time.Time, updates map[*worldClient][][]byte) { var target *character if npc.health != 0 { for id, score := range npc.threat { - player, client := server.characters[id], server.clients[id] - if player == nil || player.health == 0 || player.playfield != npc.playfield || - client == nil || !client.ready || client.loading || !client.npcs[npc.id] { + player := server.characters[id] + if !server.combatParticipantAvailable_locked(player, now) || player.playfield != npc.playfield { + continue + } + client := server.clients[id] + if player.pet != nil { + client = server.clients[player.pet.owner] + } + if client == nil || !client.npcs[npc.id] { continue } // Keep the current opponent on ties; otherwise use stable identity order. diff --git a/server/pet_attack_test.go b/server/pet_attack_test.go @@ -0,0 +1,304 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "testing" + "time" +) + +func newPetAttackWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, output := newPetSummonWorld(t) + client := world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + target := world.characters[1000000] + target.monsterData, target.level = 17655, 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + target.motion = &npcMotion{home: target.position} + world.mobileNPCs = map[uint32][]*character{950: {target}} + client.selectedTarget = [2]uint32{50000, target.id} + output.packets = nil + return world, output +} + +func petAttackRequest() []byte { + request := petFollowRequest(1) + binary.BigEndian.PutUint32(request[36:], 7) + return request[20:] +} + +func TestPetAttackPursuesAndCreditsOwnerWhileEnemyRetaliatesAgainstPet(t *testing.T) { + world, _ := newPetAttackWorld(t) + pet, target, owner := world.characters[1000001], world.characters[1000000], world.characters[1] + target.position, target.health = [3]float32{40, 0, 0}, 32 + ownerHealth := owner.health + + if err := world.handlePetCommand(world.clients[1], petAttackRequest()); err != nil { + t.Fatal(err) + } + deadline := pet.nextAttack + world.handlePetCommand(world.clients[1], petAttackRequest()) + if pet.nextAttack != deadline { + t.Fatal("repeated command restarted the attack phase") + } + world.advanceCombat(deadline) + if target.health != 32 || pet.nextAttack != deadline { + t.Fatal("pet hit outside range or restarted its pending swing", target.health, pet.nextAttack, deadline) + } + start := pet.movement.updatedAt + for tick := 1; tick <= 120 && target.health == 32; tick++ { + now := start.Add(time.Duration(tick) * 100 * time.Millisecond) + world.advancePlayerMovement(now) + world.advanceCombat(now) + } + if target.health != 16 || target.fighting != pet.id || target.threat[pet.id] != 16 || + target.damageContributors[damageContributor{player: 1}] != 16 || pet.position[0] <= 2 || owner.fighting != 0 { + t.Fatal("pursuit, individual retaliation or owner credit failed", target.health, target.fighting, pet.position) + } + for tick := 1; tick <= 50 && pet.health == 17; tick++ { + now := target.nextAttack.Add(time.Duration(tick) * 100 * time.Millisecond) + world.advancePlayerMovement(now) + world.advanceNPCs(now) + world.advanceCombat(now) + } + if pet.health != 9 || owner.health != ownerHealth { + t.Fatal("enemy did not damage the pet independently of its owner", pet.health, owner.health) + } + world.advanceCombat(pet.nextAttack) + cold := newServerForTest(t) + + for _, current := range []*server{world, cold} { + corpse := current.characters[1000000].corpse + if current.characters[1000000].health != 0 || corpse == nil || corpse.looter != 1 || corpse.credits != 5 || + current.characters[1].experience != 100 || len(current.characters[1].pets) != 1 || current.characters[1].nano != 25 || + current.characters[1000001].attackWeapon().ID != 120637 { + t.Fatal("pet kill lost reward, owner or cold weapon profile", corpse) + } + } + if pet.fighting != 0 || !pet.nextAttack.IsZero() || len(world.fighting) != 0 { + t.Fatal("dead target retained an encounter") + } +} + +func TestPetAttackRejectsInvalidTargetsAndUnavailableOwners(t *testing.T) { + for _, scenario := range []string{"no selection", "corpse identity", "unknown", "player", "pet", "human", "dead", "zone", "hidden", "owner dead", "loading", "offline", "expired"} { + t.Run(scenario, func(t *testing.T) { + world, output := newPetAttackWorld(t) + client, pet, target := world.clients[1], world.characters[1000001], world.characters[1000000] + switch scenario { + case "no selection": + client.selectedTarget = [2]uint32{} + case "corpse identity": + client.selectedTarget[0] = 51050 + case "unknown": + client.selectedTarget[1] = 999 + case "player": + client.selectedTarget[1] = 1 + case "pet": + client.selectedTarget[1] = pet.id + case "human": + target.appearance = 277 + case "dead": + target.health = 0 + case "zone": + target.playfield++ + case "hidden": + delete(client.npcs, target.id) + case "owner dead": + world.characters[1].health = 0 + case "loading": + client.loading = true + case "offline": + delete(world.clients, 1) + case "expired": + pet.pet.expiresAt = time.Now().Add(-time.Second) + } + + err := world.handlePetCommand(client, petAttackRequest()) + + if err != nil || pet.fighting != 0 || pet.motion != nil || len(output.packets) != 0 || len(world.fighting) != 0 { + t.Fatal("invalid pet attack changed combat or motion", err) + } + }) + } +} + +func TestPetCombatStopsWhenOwnerBecomesUnavailable(t *testing.T) { + for _, scenario := range []string{"dead", "zone", "loading", "offline", "expired"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newPetAttackWorld(t) + pet, target := world.characters[1000001], world.characters[1000000] + world.handlePetCommand(world.clients[1], petAttackRequest()) + world.advanceCombat(pet.nextAttack) + health := target.health + switch scenario { + case "dead": + world.characters[1].health = 0 + case "zone": + world.characters[1].playfield++ + case "loading": + world.clients[1].loading = true + case "offline": + delete(world.clients, 1) + case "expired": + pet.pet.expiresAt = time.Now().Add(-time.Second) + } + + world.advanceCombat(pet.nextAttack) + world.advancePlayerMovement(time.Now().Add(time.Second)) + + if pet.fighting != 0 || target.fighting != 0 || target.health != health || pet.health != 17 || pet.motion.returning { + t.Fatal("unavailable owner left pet combat or pursuit running") + } + }) + } +} + +func TestPetDeathCommitsRemovalAndAllowsAnotherSummon(t *testing.T) { + for _, fault := range []string{"none", "ignored deletion", "cascade failure", "commit failure"} { + t.Run(fault, func(t *testing.T) { + world, output := newPetAttackWorld(t) + pet, target, owner := world.characters[1000001], world.characters[1000000], world.characters[1] + world.handlePetCommand(world.clients[1], petAttackRequest()) + world.advanceCombat(pet.nextAttack) + pet.health = 1 + query := "CREATE TRIGGER reject_pet_death BEFORE DELETE ON characters WHEN OLD.id=1000001 BEGIN SELECT RAISE(IGNORE); END" + if fault == "cascade failure" { + query = "CREATE TRIGGER reject_pet_death BEFORE DELETE ON pets BEGIN SELECT RAISE(ABORT,'pet death'); END" + } + if fault == "commit failure" { + if _, err := world.db.Exec("CREATE TABLE pet_death_failure (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED)"); err != nil { + t.Fatal(err) + } + query = "CREATE TRIGGER reject_pet_death AFTER DELETE ON characters WHEN OLD.id=1000001 BEGIN INSERT INTO pet_death_failure VALUES (999); END" + } + if fault != "none" { + if _, err := world.db.Exec(query); err != nil { + t.Fatal(err) + } + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + + world.advanceCombat(target.nextAttack) + if fault != "none" { + after, err := readTestItemStore(world) + if err != nil || !bytes.Equal(before, after) || pet.health != 1 || owner.pets[pet.id] != pet || world.characters[pet.id] != pet { + t.Fatal("failed lethal hit changed storage or pet ownership", err) + } + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x36510078 || binary.BigEndian.Uint32(packet[16:20]) == 0x58742a0f { + t.Fatal("failed death published removal") + } + } + if _, err := world.db.Exec("DROP TRIGGER reject_pet_death"); err != nil { + t.Fatal(err) + } + world.handlePetCommand(world.clients[1], petAttackRequest()) + world.advanceCombat(pet.nextAttack) + world.advanceCombat(target.nextAttack) + } + cold := newServerForTest(t) + + if world.characters[pet.id] != nil || cold.characters[pet.id] != nil || len(owner.pets) != 0 || len(cold.characters[1].pets) != 0 || + len(world.fighting) != 0 || len(world.petExpiry) != 0 || len(world.corpseExpiry) != 0 || owner.experience != 0 || world.nextNPC != 1000002 { + t.Fatal("lethal retaliation retained pet ownership, combat or generated rewards") + } + owner.nanoRechargeUntil = time.Time{} + world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + cast := world.clients[1].nanoCast + if cast == nil { + t.Fatal("dead pet blocked the next summon") + } + world.advanceNanos(cast.readyAt.Add(time.Nanosecond)) + if len(owner.pets) != 1 || owner.pets[1000002] == nil || owner.nano != 15 { + t.Fatal("replacement summon lost identity or cost") + } + }) + } +} + +func TestPetDamageCreditsTheOwnersTeamAtEachHit(t *testing.T) { + world, _ := newPetAttackWorld(t) + owner, pet, target := world.characters[1], world.characters[1000001], world.characters[1000000] + owner.team = &playerTeam{id: 7} + + world.handlePetCommand(world.clients[1], petAttackRequest()) + world.advanceCombat(pet.nextAttack) + owner.team = nil + // Leave the enemy's actual retaliation in the same shared combat tick. + world.advanceCombat(pet.nextAttack) + + if target.threat[pet.id] != 32 || target.threat[owner.id] != 0 || + target.damageContributors[damageContributor{team: 7}] != 16 || target.damageContributors[damageContributor{player: 1}] != 16 || + target.leadingContributor != (damageContributor{team: 7}) || target.fighting != pet.id { + t.Fatal("pet threat and per-hit owner/team reward credit were conflated", target.threat, target.damageContributors) + } +} + +func TestPetKillRewardFailureRollsBackAndRetries(t *testing.T) { + world, _ := newPetAttackWorld(t) + owner, pet, target := world.characters[1], world.characters[1000001], world.characters[1000000] + target.health = 16 + if _, err := world.db.Exec("CREATE TRIGGER reject_pet_reward BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT,'reward'); END"); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + world.handlePetCommand(world.clients[1], petAttackRequest()) + world.advanceCombat(pet.nextAttack) + after, err := readTestItemStore(world) + if err != nil || !bytes.Equal(before, after) || target.health != 16 || target.corpse != nil || owner.experience != 0 || len(target.damageContributors) != 0 { + t.Fatal("failed pet reward partially committed its kill", err) + } + if _, err := world.db.Exec("DROP TRIGGER reject_pet_reward"); err != nil { + t.Fatal(err) + } + world.handlePetCommand(world.clients[1], petAttackRequest()) + world.advanceCombat(pet.nextAttack) + cold := newServerForTest(t) + + if target.health != 0 || target.corpse.looter != 1 || owner.experience != 100 || cold.characters[1].experience != 100 || cold.characters[1000000].corpse.looter != 1 { + t.Fatal("pet reward retry lost or repeated the kill") + } +} + +func TestPetPursuitInterestReplaysRouteAndCombatAfterSpawn(t *testing.T) { + world, output := newPetAttackWorld(t) + client, pet := world.clients[1], world.characters[1000001] + world.characters[1000000].position = [3]float32{40, 0, 0} + world.handlePetCommand(client, petAttackRequest()) + now := pet.movement.updatedAt.Add(250 * time.Millisecond) + world.advancePlayerMovement(now) + delete(client.npcs, pet.id) + output.packets = nil + + world.advanceNPCs(now) + + spawn, route, attack := -1, -1, -1 + for index, packet := range output.packets { + if binary.BigEndian.Uint32(packet[24:28]) != pet.id { + continue + } + switch binary.BigEndian.Uint32(packet[16:20]) { + case 0x271b3a6b: + spawn = index + case 0x260f3671: + route = index + case 0x28494070: + attack = index + } + } + if spawn < 0 || route <= spawn || attack <= route { + t.Fatal("pet interest omitted or reordered its pursuit route and encounter", spawn, route, attack) + } +} diff --git a/server/pet_follow.go b/server/pet_follow.go @@ -12,10 +12,10 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { if len(body) < 36 { return fmt.Errorf("invalid pet command length") } - // Original unfiltered commands: follow=1, behind=2, wait=4, terminate=10. + // Original unfiltered commands: follow=1, behind=2, wait=4, attack=7, terminate=10. command := binary.BigEndian.Uint32(body[16:20]) if len(body) != 36 || !client.target || binary.BigEndian.Uint32(body[4:8]) != 50000 || - binary.BigEndian.Uint32(body[8:12]) != client.id || command != 1 && command != 2 && command != 4 && command != 10 || + binary.BigEndian.Uint32(body[8:12]) != client.id || command != 1 && command != 2 && command != 4 && command != 7 && command != 10 || binary.BigEndian.Uint32(body[20:24]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 1009 || binary.BigEndian.Uint32(body[28:32]) != 0 || binary.BigEndian.Uint32(body[32:36]) != 0 { return nil @@ -30,6 +30,12 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { } now := time.Now() updates := make(map[*worldClient][][]byte) + target := server.characters[client.selectedTarget[1]] + if command == 7 && (owner.driving() || client.selectedTarget[0] != 50000 || target == nil || !target.npc || + target.pet != nil || target.appearance>>4&7 != 6 || !client.npcs[target.id] || target.health == 0 || target.playfield != owner.playfield) { + server.mutex.Unlock() + return nil + } for _, pet := range owner.pets { if command == 10 { if err := server.retirePet_locked(pet, updates); err != nil { @@ -40,11 +46,25 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { if pet.health == 0 || pet.playfield != owner.playfield || !now.Before(pet.pet.expiresAt) { continue } - if command == 2 || command == 4 { - // Explicit retreat/wait must not reselect the stopped encounter next tick. + if command == 7 { + if pet.fighting == target.id { + continue + } + pet.followTarget = 0 + pet.pet.paused = false + server.queueCombat_locked(updates, pet, owner, petFollowPacket(pet, 0)) + pet.geometry = server.geometry + pet.motion = &npcMotion{home: pet.position} + pet.movement.prepare(pet, now) + pet.movement.updatedAt = now pet.threat = nil server.stopAttack_locked(pet, updates) + server.startAttack_locked(pet, target, now, updates) + continue } + // Follow/behind/wait must not reselect the stopped encounter next tick. + pet.threat = nil + server.stopAttack_locked(pet, updates) if command == 4 { pet.followTarget = 0 pet.pet.paused = false @@ -84,7 +104,22 @@ func petFollowPacket(pet *character, target uint32) []byte { func (server *server) advancePetFollowing_locked(now time.Time, updates map[*worldClient][][]byte) { for _, pet := range server.petExpiry { - if pet.followTarget == 0 || !server.npcActive_locked(pet, now) { + if !server.npcActive_locked(pet, now) { + continue + } + if pet.motion != nil && (pet.fighting != 0 || pet.motion.returning) { + seconds := min(.25, max(0, now.Sub(pet.movement.updatedAt).Seconds())) + pet.movement.updatedAt = now + if !server.combatParticipantAvailable_locked(pet, now) { + server.cancelCombat_locked(pet.id, updates) + server.stopNPCMotion_locked(pet, updates) + pet.motion.returning = false + continue + } + server.advanceNPCPursuit_locked(pet, now, seconds, updates) + continue + } + if pet.followTarget == 0 { continue } seconds := min(.25, max(0, now.Sub(pet.movement.updatedAt).Seconds())) diff --git a/server/pets.go b/server/pets.go @@ -17,6 +17,12 @@ type ownedPet struct { paused bool } +func petCombatProfile() *gamedata.NPCCombatProfile { + // Explicit single-fist PT50 alpha policy; original binding is unresolved. + return &gamedata.NPCCombatProfile{Health: 17, Weapon: [2]uint32{120637, 120638}, AggDef: 75, + Skills: map[uint32]int32{100: 5, 153: 5, 154: 5, 155: 5, 168: 5}} +} + func petSummonNano(program uint32) bool { definition := gamedata.NanoTemplates[program] if program != 43324 || definition == nil || definition.RecordType != 1040005 || definition.Undecoded != nil || len(definition.Sections) != 4 { @@ -77,6 +83,7 @@ func (server *server) summonPet_locked(caster *character, now time.Time) error { position: position, rotation: caster.rotation, appearance: 229, monsterData: 96195, level: 1, npc: true, npcDefinitionID: "pet/PT50", pet: &ownedPet{owner: caster.id, program: 43324, expiresAt: now.Add(600 * time.Second)}} pet.health, pet.nano = pet.maximumHealth(), pet.maximumNano() + pet.combatProfile = petCombatProfile() db, err := server.database() if err != nil { return err @@ -138,6 +145,7 @@ func (server *server) loadPets() error { } entity, owner := server.characters[id], server.characters[pet.owner] entity.pet = pet + entity.combatProfile = petCombatProfile() server.petExpiry = append(server.petExpiry, entity) if owner.pets == nil { owner.pets = make(map[uint32]*character) @@ -184,6 +192,11 @@ func (server *server) retirePet_locked(pet *character, updates map[*worldClient] return err } + server.removePet_locked(pet, updates) + return nil +} + +func (server *server) removePet_locked(pet *character, updates map[*worldClient][][]byte) { server.cancelCombat_locked(pet.id, updates) owner := server.characters[pet.pet.owner] delete(owner.pets, pet.id) @@ -200,5 +213,4 @@ func (server *server) retirePet_locked(pet *character, updates map[*worldClient] updates[client] = append(updates[client], n3Packet(0x36510078, 50000, pet.id, nil)) } } - return nil } diff --git a/tools/client/test_pet_attack.mjs b/tools/client/test_pet_attack.mjs @@ -0,0 +1,84 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {}; +const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id); +try { + for (let index = 0; index < 2; index++) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'pet-cast-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + } + const [owner] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + const command = async text => { + await owner.key('Enter'); + await owner.page.keyboard.type('/pet ' + text); + await owner.key('Enter'); + }; + await Promise.all(games.map(game => game.wait('pets and target visible', () => actor(game, 1000001) && actor(game, 1000002) && actor(game, 1000000)))); + evidence.before = await server(); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + await owner.hold('KeyA', 'face the enemy along the open street', state => owner.local(state).rotation[1] < -0.69); + await owner.click(...await owner.pick(50000, 1000000)); + await owner.wait('enemy selected through native picking', state => state.selected[0] === 50000 && state.selected[1] === 1000000); + await command('attack'); + await Promise.all(games.map(game => game.wait('pet attacking selected enemy', () => actor(game, 1000001).combatTarget === 1000000))); + await command('behind'); + await Promise.all(games.map(game => game.wait('behind cancels attack', () => actor(game, 1000001).combatTarget === 0))); + evidence.retreated = await server(); + assert.equal(evidence.retreated.follow, 1); + assert.equal(evidence.retreated.targetHealth, 32); + await command('wait'); + await owner.waitFor('wait clears owner follow', async () => (await server()).follow === 0); + + await command('attack'); + await owner.waitFor('pet lands first attack and enemy retaliates', async () => { + const state = await server(); + return state.targetHealth === 16 && state.petHealth === 9; + }); + evidence.retaliation = await server(); + assert.equal(evidence.retaliation.targetFighting, 1000001); + assert.equal(evidence.retaliation.ownerHealth, evidence.before.ownerHealth); + await Promise.all(games.map((game, index) => game.save(output + '/combat-' + index))); + await owner.waitFor('pet kill credits owner', async () => (await server()).experience === 100); + evidence.kill = await server(); + assert.equal(evidence.kill.targetHealth, 0); + assert.equal(evidence.kill.looter, 1); + assert.equal(evidence.kill.credits, 5); + assert.equal(evidence.kill.petHealth, 9); + assert.equal(evidence.kill.ownerNano, 25); + await Promise.all(games.map(game => game.wait('native combat ends', () => actor(game, 1000001).combatTarget === 0))); + + await Promise.all(games.map(async game => { await game.page.reload(); await game.ready(); })); + await Promise.all(games.map(game => game.wait('owner membership recovers', () => actor(game, 1000001) && actor(game, 1).stats[458] === 1))); + evidence.reconnected = await server(); + assert.equal(evidence.reconnected.experience, 100); + await command('terminate'); + await Promise.all(games.map(game => game.wait('only owner pet removed', () => !actor(game, 1000001) && actor(game, 1000002) && actor(game, 1).stats[458] === 0))); + evidence.final = await server(); + assert.equal(evidence.final.ownerPets, 0); + assert.equal(evidence.final.peerPets, 1); + for (const game of games) { + assert.deepEqual(game.errors, []); + assert.equal(game.dropped, 0); + } + console.log('PASS: native pet selection/attack, behind/wait, pursuit, retaliation, owner reward, reconnect and termination'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +} diff --git a/tools/client/test_pet_owner_protocol.mjs b/tools/client/test_pet_owner_protocol.mjs @@ -66,6 +66,18 @@ try { evidence.wait = owner.events.find(event => event.sequence > wait && event.direction === 'framesent' && event.opcode === '6b333303'); const waitPacket = Buffer.from(evidence.wait.hex, 'hex'); assert.deepEqual([29, 33, 37, 41, 45].map(offset => waitPacket.readUInt32BE(offset)), [4, 0, 1009, 0, 0]); + // Capture the selected target separately from the implicit owned-pet set. + await owner.click(...await owner.pick(50000, 1000000)); + await owner.wait('selected attack target', state => state.selected[0] === 50000 && state.selected[1] === 1000000); + const attack = owner.sequence; + await owner.key('Enter'); + await owner.page.keyboard.type('/pet attack'); + await owner.key('Enter'); + await owner.wait('native pet attack request', () => owner.events.some(event => + event.sequence > attack && event.direction === 'framesent' && event.opcode === '6b333303')); + evidence.attack = owner.events.find(event => event.sequence > attack && event.direction === 'framesent' && event.opcode === '6b333303'); + const attackPacket = Buffer.from(evidence.attack.hex, 'hex'); + assert.deepEqual([29, 33, 37, 41, 45].map(offset => attackPacket.readUInt32BE(offset)), [7, 0, 1009, 0, 0]); const terminate = owner.sequence; await owner.key('Enter'); await owner.page.keyboard.type('/pet terminate'); @@ -83,7 +95,7 @@ try { evidence.unlinked = counts(); assert(evidence.unlinked.every(value => value.ownerPacked === 1)); assert(games.every(game => game.errors.length === 0)); - console.log('PASS: original owner list, duplicate identity, native report/follow/wait/terminate requests and independent packed counter'); + console.log('PASS: original owner list, duplicate identity, native report/follow/wait/attack/terminate requests and independent packed counter'); } finally { try { await fs.mkdir(output, {recursive: true});