aorecomp

Anarchy Online classic in the browser

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


commit a09c08322ae1503adfbfc328fcc5bf9b3cd91ecb
parent 63fd9073adacacf540b6a979385c3540fe821939
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 13:02:40 +0000

Share NPC pursuit across fixed and roaming encounters

Diffstat:
MTODO.md | 22++++++++++++----------
Mdocs/npc-engagement.md | 10+++++-----
Mdocs/npc-pursuit.md | 65++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mdocs/npc-regeneration.md | 5+++--
Mdocs/starter-boss.md | 10++++++----
Mdocs/world-state.md | 3++-
Mserver/combat.go | 12++++++------
Mserver/combat_test.go | 4++--
Mserver/corpse_expiry.go | 4++--
Mserver/corpse_expiry_test.go | 12++++++------
Mserver/database_test.go | 8++++----
Mserver/interest.go | 2+-
Mserver/interest_test.go | 10+++++-----
Mserver/inventory_test.go | 2+-
Mserver/loot_test.go | 2+-
Mserver/nano_buffs.go | 2+-
Mserver/nano_casting.go | 8++++----
Mserver/nano_control_movement_test.go | 44++++++++++++++++++++++----------------------
Mserver/nano_control_test.go | 6+++---
Mserver/npc_engagement_range_test.go | 2+-
Mserver/npc_outcome.go | 2+-
Mserver/npc_pursuit.go | 36+++++++++++++++++++-----------------
Mserver/npc_pursuit_test.go | 29+++++++++++------------------
Aserver/npc_shared_pursuit_test.go | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npcs.go | 7++++---
Mserver/respawn.go | 14+++++++-------
Mserver/respawn_durability_test.go | 4++--
Mserver/respawn_test.go | 14+++++++-------
Mserver/roaming.go | 41+++++++++++++++++++++--------------------
Mserver/roaming_test.go | 44++++++++++++++++++++++----------------------
Mserver/state.go | 18+++++++++---------
Mserver/world.sql | 2+-
Mserver/world_store.go | 33+++++++++++++++++++--------------
33 files changed, 461 insertions(+), 213 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -650,13 +650,14 @@ for exact records, protocol, tests and remaining reconstruction assumptions. separately from Leet equipment, with code/species/level/evidence admission and native verification on two clients. Broader Salamander populations and full boss behavior remain outside this restricted profile. -- [ ] [P0] Extend shared combat pursuit to admitted encounters without idle roaming, - including the fixed Clan Training Salamander Boss. A fixed spawn point is not - evidence that a creature should stand still during combat. Verify approach, - melee range, retreat, target loss, return, roots/snares and reconnect for both - fixed and roaming profiles. Keep idle placement separate from combat movement; - do not add species-specific pursuit branches. Until this is implemented, - ranged kills of the stationary boss do not establish normal encounter balance. +- [x] Share combat pursuit across admitted fixed and roaming encounters, including + the Clan Training Salamander Boss and both Leet levels. Idle wandering is an + independent flag; one path handles approach, retained attack timing, target + handoff, return, roots/snares, cold load and home-based respawn. Two WASM clients + verified ordinary approach, melee, retreat, reconnect and a root-delayed return. + Historical outdoor give-up rules, obstruction handling and species balance + remain open; these checks do not establish canonical boss difficulty. + See [NPC pursuit](docs/npc-pursuit.md). - [x] Keep admitted NPCs engaged while outside weapon range. Check fixed/roaming profiles at both Leet levels and the Salamander Boss, retained swing deadlines, no distant damage or repeated Attack/Stop traffic, valid-range resumption and @@ -719,9 +720,10 @@ Living NPCs use the recovered native NPC health branch, with one retained recovery clock across combat transitions and quiet observer corrections. Its evidence, automated/native checks and original-server policy limits are in [NPC health recovery](docs/npc-regeneration.md). NPC nano recovery remains open. -The mobile level-1 Leet now pursues a moving target and returns after concrete -target loss. Native waypoint routes also drive idle walking. Evidence, checks -and the provisional speed/return policy are in [Leet pursuit](docs/npc-pursuit.md). +Admitted NPC profiles now pursue moving targets and return after concrete +target loss, independently of idle wandering. Native waypoint routes also drive +idle walking. Evidence, checks and the provisional speed/return policy are in +[NPC pursuit](docs/npc-pursuit.md). Historical outdoor give-up timing and obstacle navigation remain open. ## Death and recovery diff --git a/docs/npc-engagement.md b/docs/npc-engagement.md @@ -10,9 +10,8 @@ still determines when a temporarily closed transport becomes unavailable. This rule applies independently of species, level and idle roaming. Appearance stand-ins without an admitted combat profile keep their previous behavior. -Existing level-1 Leet pursuit remains the only implemented approach/return policy. -Fixed profiles and level-2 Leets can retain combat without acquiring new movement. -General pursuit and the original outdoor give-up rules remain open TODOs. +The shared [pursuit policy](npc-pursuit.md) now supplies approach and return +independently of idle placement. The original outdoor give-up rules remain open. ## Recovery and the native mismatch @@ -68,8 +67,9 @@ retained all seventeen owned item instances, learned nanos, the player's 1000 cumulative XP and 18 credits. Both WASM clients reconnected, and the gloves were visible in the native inventory. These encounters used issued equipment, ordinary skill training, recovery and native inputs without edited resources or -rewards. The stationary boss still permits ranged acquisition; full pursuit, -qualified wear and funded equipment upgrades remain separate acceptance checks. +rewards. Those acquisition checks preceded the shared +[pursuit change](npc-pursuit.md); qualified wear and funded equipment upgrades +remain separate acceptance checks. The owner then walked to the original Clan training terminal and offered those gloves for 12 credits. Decline restored the same instance and changed no wallet; diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md @@ -1,12 +1,15 @@ -# Leet pursuit and return +# NPC pursuit and return -The mobile level-1 Leet profile (MonsterData 17655) pursues its current player -target across open ground. Losing melee range no longer discards its attack +Every admitted combat profile pursues its current player target across open +ground, including level-1/2 Leets and the fixed Clan Training Salamander Boss. +Losing melee range does not discard its attack deadline. It can deliver a bite only inside the recovered weapon range, while continuing its approach until the target is within two metres. -A dead, disconnected, loading or different-playfield target ends pursuit. The -living Leet runs back to its retained spawn position, then resumes idle roaming. +A dead, disconnected, loading or different-playfield target is replaced through +the shared threat selector when another eligible participant remains. Otherwise +the living NPC runs back to its retained spawn position. An explicit idle-roaming +flag then selects wandering or remaining at that fixed post. Returning neither refills health nor resets the recovery clock. Another player can engage it during the return; that hit replaces the return route with the normal combat flow. Dead remains never return or continue following. @@ -24,8 +27,8 @@ did not recover those numeric rules for Leets. The server therefore handles concrete target loss without claiming a historical outdoor give-up timer. Distance/time leashing remains unimplemented. Straight routes use the native default RunSpeed 100 and run mode, represented on the -server as 4.5 metres/second. Selecting that default for Leet pursuit and return -is provisional; it is not an original-server Leet speed measurement. The +server as 4.5 metres/second. Selecting that default for admitted pursuit and return +is provisional; it is not an original-server species speed measurement. The close-approach threshold comes from native NPC steering `FUN_10048430`, whose near-target branch checks squared distance below 4 and line of sight. The server currently assumes open ground; it has no obstruction or navigation @@ -35,10 +38,18 @@ spawn offset, and each scheduler step remains capped at 0.25 seconds. Return to the retained spawn is an explicit reconstruction policy. A bounded source search found no period Leet rule proving that exact destination or its timing. Return continues without observers. Health uses the separate -[recovery rule](npc-regeneration.md), including while returning. Fixed posts, -unprofiled creatures, other species and other levels acquire neither pursuit -nor return. Proximity aggression, threat-based target changes, obstruction -rejection and obstacle navigation remain separate TODOs. +[recovery rule](npc-regeneration.md), including while returning. Unprofiled +appearance stand-ins do not acquire combat pursuit. Proximity aggression, +obstruction rejection and obstacle navigation remain separate TODOs. + +Motion state retains home, destination, idle-wandering eligibility and return +progress independently of combat capability. It uses the existing periodic NPC +checkpoint; movement does not write SQLite on each tick. Cold loading restores +the current admitted profile and returns displaced living combatants home before +idling. Transient targets and attack clocks are not restored. Roots hold that +return until expiry, and the normal signed run-speed rule applies to snares. +Dead remains stay where they fell; the separately committed replacement life +starts at home and inherits the same idle policy. ## Native route contract @@ -90,6 +101,38 @@ its NPC/player callers are ## Verification +Shared-profile regressions exercise fixed and roaming level-1/2 Leets and the +Clan Training boss. They check retained deadlines, target loss and remaining +threat, root/snare casts, cold pursuit/return/root/home states, and a displaced +boss's death, separate corpse and replacement life at home. Fixed idle posts +remain stationary after return and cold respawn. Unadmitted profiles retain +their movement exclusions. The new level-2/boss approach and fixed-spawn checks +fail against the previous implementation. + +Two hardware-rendered WASM clients then followed the actual Clan Training boss +from its fixed post through pursuit, player retreat, an 11-point melee hit and +return after an ordinary Options account reconnect. The observer recorded its +run home; both clients then showed a stationary post. A subsequent encounter +applied Malaise of Movement after the boss approached. The player survived a +nine-point bite, ended its attack and reconnected. Both clients held the rooted +boss away from home until the original 15-second effect expired, then displayed +its return and idle post. Neither health nor movement speed was granted or +edited. All sixteen owned item identities, 1000 XP and 30 credits remained; +two issued laboratory charges supported ordinary recovery. + +These checks, the matching original route/steering digests, raw wire streams, +native positions, screenshots and accounting assertions are under +`local/npc-shared-pursuit/`. The published WASM client was unchanged and reported +no browser exceptions. The owned test clients closed after verification. These +encounters establish shared movement behavior, not canonical boss balance, +obstacle routing, historical leash rules or a completed earned-upgrade loop. + +The complete server/gamedata suite passed 1466 test roots and 15114 results +(server 1749.296 seconds). The shared pursuit selection passed 14 roots/34 +results; the broader focused selection passed 65 roots/129 results. Race checks +passed 44 roots/94 results, and vet and the server build passed. The frozen source, +running-server, native-harness and published-client hashes matched afterward. + An isolated native route experiment sent walk and run waypoint routes to two published WASM clients. Both moved the Leet and reached the short route's native arrival threshold, less than one metre from its endpoint. Clearing the diff --git a/docs/npc-regeneration.md b/docs/npc-regeneration.md @@ -95,8 +95,9 @@ fixed spawns. Repeatedly stopping and restarting a ranged target had selected idle recovery on the server while clients' independent phases sometimes checked the brief combat state, accumulating visible HP differences. The shared [engagement rule](npc-engagement.md) preserves the opponent and swing deadline -without dealing an out-of-range hit or changing recovery rates. Fixed-spawn -pursuit remains separate work. +without dealing an out-of-range hit or changing recovery rates. Shared +[pursuit](npc-pursuit.md) now handles admitted fixed and roaming encounters +independently of their idle-wandering policy. A contemporary [March 2003 mission-boss discussion, post 16](https://forums-archive.anarchy-online.com/showthread.php?112679-Finding-GA-Guide-P=) reports substantially faster boss recovery after combat ends. It provides no diff --git a/docs/starter-boss.md b/docs/starter-boss.md @@ -97,10 +97,12 @@ issued instances across the owned characters. Both live native inventories matched SQLite identities, qualities, charges and slots afterward. No browser exceptions occurred; the owned clients closed after verification. -The fixed boss can retaliate inside its effective range but does not yet pursue -a retreating player. Ranged acquisition outside that range therefore cannot -establish canonical encounter balance. Shared pursuit for fixed encounters is -another P0 TODO; no per-species movement exception was added here. +The initial acquisition checks used a stationary boss and therefore cannot +establish canonical encounter balance. The shared [pursuit rule](npc-pursuit.md) +now lets admitted fixed encounters approach and return without adding idle +wandering or a per-species movement branch. Two ordinary native encounters +verified approach, melee, retreat, reconnect and a root-delayed return. Exact +historical boss balance and outdoor give-up rules remain open. The complete Go suite passed 15,084 results across server and gamedata, including 31 results in eight focused boss tests. Ten related race-test roots passed, diff --git a/docs/world-state.md b/docs/world-state.md @@ -8,7 +8,8 @@ The database contains: - `characters`: individual profile, ability/skill, appearance, position and vital columns. - `players`: player identity and credits. - `learned_nanos` and `skill_locks`: one row per learned program or actor/skill lock. -- `npcs`: live NPC poses, health, roaming state, damage contributors, corpse +- `npcs`: live NPC poses, health, motion state, idle-wandering eligibility, + damage contributors, corpse cash/ownership/expiry and respawn deadlines, including expired actors whose replacements are still pending. - `items`: globally unique item IDs, stack counts, loaded ammunition and other diff --git a/server/combat.go b/server/combat.go @@ -290,9 +290,9 @@ func (server *server) startAttack_locked(attacker, target *character, now time.T if attacker.fighting == target.id { return } - if attacker.roaming != nil { + if attacker.motion != nil { server.stopNPCMotion_locked(attacker, updates) - attacker.roaming.returning = false + attacker.motion.returning = false } // AttackIIR submits stand only from helper8, independently of retained posture430. // Source: client/game/kkr.dll/lifted-0035.c, sub_36078FC0. @@ -325,9 +325,9 @@ func (server *server) stopAttack_locked(attacker *character, updates map[*worldC attacker.nextAttack = time.Time{} delete(server.fighting, attacker.id) server.queueCombat_locked(updates, attacker, attacker, stopFightPacket(attacker.id)) - if attacker.roaming != nil && attacker.combatProfile != nil && attacker.monsterData == 17655 && attacker.level == 1 { + if attacker.motion != nil && attacker.combatProfile != nil { server.stopNPCMotion_locked(attacker, updates) - attacker.roaming.returning = attacker.health != 0 && attacker.position != attacker.roaming.home + attacker.motion.returning = attacker.health != 0 && attacker.position != attacker.motion.home } } @@ -525,10 +525,10 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr client.backpacks = nil } server.cancelCombat_locked(target.id, updates) - if target.roaming != nil { + if target.motion != nil { // A returning creature can die without an entry in the combat map. server.stopNPCMotion_locked(target, updates) - target.roaming.returning = false + target.motion.returning = false } server.queueCombat_locked(updates, target, target, deathPacket(target)) if !target.npc && target.experience != previous.experience { diff --git a/server/combat_test.go b/server/combat_test.go @@ -161,7 +161,7 @@ func TestCombatRangeUsesPredictedPlayerPosition(t *testing.T) { func TestCombatKillingHitClampsHealthAndCancelsEveryAttacker(t *testing.T) { world, conn := newCombatWorld() world.characters[1000000].health = 3 - world.characters[1000000].roaming = &npcRoaming{moving: true} + world.characters[1000000].motion = &npcMotion{roaming: true, moving: true} world.characters[2] = &character{id: 2, playfield: 950, health: 100, fighting: 1000000} world.fighting[2] = world.characters[2] world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) @@ -170,7 +170,7 @@ func TestCombatKillingHitClampsHealthAndCancelsEveryAttacker(t *testing.T) { world.advanceCombat(first) world.advanceCombat(first.Add(time.Hour)) - if world.characters[1000000].health != 0 || world.characters[1000000].roaming.moving || len(world.fighting) != 0 || world.characters[2].fighting != 0 { + if world.characters[1000000].health != 0 || world.characters[1000000].motion.moving || len(world.fighting) != 0 || world.characters[2].fighting != 0 { t.Fatal("death did not release every opponent") } if hex.EncodeToString(conn.packets[1][29:57]) != "00000003ffffffff000000000000c350000f42400000000400000004" { diff --git a/server/corpse_expiry.go b/server/corpse_expiry.go @@ -34,8 +34,8 @@ func (server *server) advanceCorpseExpiry(now time.Time) { // Respawn holds its own source reference when its deadline is later. delete(server.characters, corpse.id) - if corpse.roaming != nil { - server.roamingNPCs[corpse.playfield] = slices.DeleteFunc(server.roamingNPCs[corpse.playfield], func(other *character) bool { return other == corpse }) + if corpse.motion != nil { + server.mobileNPCs[corpse.playfield] = slices.DeleteFunc(server.mobileNPCs[corpse.playfield], func(other *character) bool { return other == corpse }) } } server.mutex.Unlock() diff --git a/server/corpse_expiry_test.go b/server/corpse_expiry_test.go @@ -46,7 +46,7 @@ func TestCorpseExpiryClosesLootAndRemovesOnlyTheDeadLifeForBothObservers(t *test t.Fatal("expired corpse retained its actor, loot window, interest or expiry entry") } if len(world.characters) != 3 || world.characters[1000001].health != 100 || - len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0].id != 1000001 { + len(world.mobileNPCs[950]) != 1 || world.mobileNPCs[950][0].id != 1000001 { t.Fatal("corpse removal changed the living replacement") } if len(owner.packets) != 3 || len(other.packets) != 2 || @@ -118,7 +118,7 @@ func TestCorpseExpiryBeforeRespawnWithoutObserversKeepsOneRoamingReplacement(t * conn.packets = nil world.advanceCorpseExpiry(killed.Add(time.Second)) - if world.characters[1000000] != nil || len(world.roamingNPCs[950]) != 0 || len(world.npcRespawns) != 1 { + if world.characters[1000000] != nil || len(world.mobileNPCs[950]) != 0 || len(world.npcRespawns) != 1 { t.Fatal("early corpse expiry retained the dead actor or discarded its pending respawn") } world.advanceNPCRespawns(killed.Add(100 * time.Second)) @@ -130,7 +130,7 @@ func TestCorpseExpiryBeforeRespawnWithoutObserversKeepsOneRoamingReplacement(t * world.advanceNPCs(killed.Add(101 * time.Second)) if len(world.characters) != 2 || world.characters[1000001].health != 100 || len(world.npcRespawns) != 0 || - len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0].id != 1000001 || + len(world.mobileNPCs[950]) != 1 || world.mobileNPCs[950][0].id != 1000001 || len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x271b3a6b || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x1d3c0f1c { t.Fatal("respawn or reentry lost the roaming replacement or restored its expired corpse") @@ -193,14 +193,14 @@ func TestCorpseExpiryRetiresKnownObjectsWhileTheObserverIsLoading(t *testing.T) func TestCorpseExpiryFixedCreatureDoesNotRequireARoamingRoster(t *testing.T) { world, _, killed := newExpiringCorpseWorld(t) - world.characters[1000000].roaming = nil - world.roamingNPCs = nil + world.characters[1000000].motion = nil + world.mobileNPCs = nil world.advanceCorpseExpiry(killed.Add(180 * time.Second)) world.advanceNPCRespawns(killed.Add(181 * time.Second)) if world.characters[1000000] != nil || world.characters[1000001].health != 100 || - world.characters[1000001].roaming != nil || len(world.corpseExpiry) != 0 || len(world.npcRespawns) != 0 { + world.characters[1000001].motion != nil || len(world.corpseExpiry) != 0 || len(world.npcRespawns) != 0 { t.Fatal("fixed corpse cleanup or its replacement required an unrelated roaming roster") } } diff --git a/server/database_test.go b/server/database_test.go @@ -107,7 +107,7 @@ func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { now := time.Now().UTC() npc := world.characters[1000000] npc.health, npc.position = 0, [3]float32{53, 14, 57} - npc.roaming = &npcRoaming{home: [3]float32{52, 14, 56}, destination: [3]float32{54, 14, 58}, nextMove: now.Add(time.Second)} + npc.motion = &npcMotion{roaming: true, home: [3]float32{52, 14, 56}, destination: [3]float32{54, 14, 58}, nextMove: now.Add(time.Second)} npc.corpse = &npcCorpse{looter: 1, credits: 87, expiresAt: now.Add(180 * time.Second), items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} world.corpseExpiry = []*character{npc} @@ -136,7 +136,7 @@ func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { if restored.health != 27 || restored.nano != 11 || !restored.sitting || restored.aggDef != 33 || restored.inventory.Credits != 913 || !restored.nanoRechargeUntil.Equal(player.nanoRechargeUntil) { t.Fatal("player vitals, credits or cooldown were lost") } - if corpse.health != 0 || corpse.position != [3]float32{53, 14, 57} || corpse.roaming.home != [3]float32{52, 14, 56} || + if corpse.health != 0 || corpse.position != [3]float32{53, 14, 57} || corpse.motion.home != [3]float32{52, 14, 56} || corpse.corpse.credits != 87 || corpse.corpse.looter != 1 || len(corpse.corpse.items) != 1 || corpse.corpse.items[0].ID != 17 || restarted.nextItem != 17 { t.Fatal("NPC pose, corpse ownership, loot or identity counter was lost") } @@ -160,7 +160,7 @@ func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) { now := time.Now().UTC() npc := world.characters[1000000] npc.health = 0 - npc.roaming = &npcRoaming{home: [3]float32{52, 14, 56}} + npc.motion = &npcMotion{roaming: true, home: [3]float32{52, 14, 56}} npc.corpse = &npcCorpse{expiresAt: now.Add(time.Second), items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} world.corpseExpiry = []*character{npc} world.npcRespawns = []npcRespawn{{npc, now.Add(3 * time.Second)}} @@ -185,7 +185,7 @@ func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) { defer again.db.Close() if len(again.characters) != 1 || again.characters[1000001] == nil || again.characters[1000001].position != [3]float32{52, 14, 56} || - len(again.npcRespawns) != 0 || len(again.corpseExpiry) != 0 || len(again.roamingNPCs[950]) != 1 || again.nextItem != 17 || again.nextNPC != 1000002 { + len(again.npcRespawns) != 0 || len(again.corpseExpiry) != 0 || len(again.mobileNPCs[950]) != 1 || again.nextItem != 17 || again.nextNPC != 1000002 { t.Fatal("respawn duplicated the source, lost home or reused an identity") } } diff --git a/server/interest.go b/server/interest.go @@ -51,7 +51,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim updates = append(updates, deathPacket(other)) } } - if other.roaming != nil && other.roaming.moving { + if other.motion != nil && other.motion.moving { updates = append(updates, npcRoutePacket(other)) } } diff --git a/server/interest_test.go b/server/interest_test.go @@ -139,11 +139,11 @@ func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { client := connectZoningClient(t, world, false) now := time.Now() world.lastNPCUpdate = now - for _, npc := range world.roamingNPCs[950] { - npc.roaming.moving = true - npc.roaming.nextMove = now - npc.roaming.destination = npc.position - npc.roaming.destination[0] -= 1 + for _, npc := range world.mobileNPCs[950] { + npc.motion.moving = true + npc.motion.nextMove = now + npc.motion.destination = npc.position + npc.motion.destination[0] -= 1 } done := make(chan struct{}) diff --git a/server/inventory_test.go b/server/inventory_test.go @@ -165,7 +165,7 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) { func newTestInventoryServer(t *testing.T) *server { t.Helper() - world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), roamingNPCs: make(map[uint32][]*character), combatRoll: func(limit uint32) uint32 { return limit - 1 }} + world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), combatRoll: func(limit uint32) uint32 { return limit - 1 }} if _, err := world.loadNPCs(); err != nil { t.Fatal(err) } diff --git a/server/loot_test.go b/server/loot_test.go @@ -22,7 +22,7 @@ func newLootWorld(t *testing.T) (*server, *combatTestConn) { id: 1000000, name: "Leet", playfield: player.playfield, position: [3]float32{1, 0, 0}, rotation: [4]float32{0, 0, 0, 1}, appearance: 229, monsterData: 17655, npc: true, health: 1, }} - world.roamingNPCs = nil + world.mobileNPCs = nil conn := &combatTestConn{} world.clients[1] = &worldClient{id: 1, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -386,7 +386,7 @@ func (server *server) removeNano_locked(player *character, index int, now time.T func (server *server) finishResourceChange_locked(updates map[*worldClient][][]byte, player *character, previous character, now time.Time) { if player.npc { - if previous.roaming != nil && previous.roaming.moving && !player.roaming.moving { + if previous.motion != nil && previous.motion.moving && !player.motion.moving { server.queueCombat_locked(updates, player, player, npcRoutePacket(player), npcMovementPacket(player, 22)) } return diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -303,11 +303,11 @@ func (server *server) advanceNanos(now time.Time) { victim.health = min(victim.health, victim.maximumHealth()) } } - if victim.roaming != nil && victim.roaming.moving && victim.movementRestricted() { + if victim.motion != nil && victim.motion.moving && victim.movementRestricted() { // The stopped route and effect must commit together, without shared mutation. - roaming := *victim.roaming - roaming.moving = false - victim.roaming, victim.running = &roaming, false + motion := *victim.motion + motion.moving = false + victim.motion, victim.running = &motion, false } victim.updateMovementPermission(target, now) diff --git a/server/nano_control_movement_test.go b/server/nano_control_movement_test.go @@ -20,11 +20,11 @@ func newControlPursuitWorld(t *testing.T) (*server, *combatTestConn) { player.inventory.LearnedNanos = []uint32{42110, 82518, 82528, 82463} target.monsterData, target.level = 17655, 1 target.combatProfile = gamedata.NPCCombatProfiles[17655][1] - target.roaming = &npcRoaming{home: target.position, destination: player.position, moving: true} + target.motion = &npcMotion{roaming: true, home: target.position, destination: player.position, moving: true} target.running, target.fighting = true, 1 target.nextAttack = time.Now().Add(1750 * time.Millisecond) world.fighting[target.id] = target - world.roamingNPCs = map[uint32][]*character{950: {target}} + world.mobileNPCs = map[uint32][]*character{950: {target}} return world, conn } @@ -41,18 +41,18 @@ func TestControlRootStopsRoamingPursuitAndReturnUntilExpiry(t *testing.T) { target.threat = nil } if mode == "return" { - target.roaming.home = [3]float32{21, 0, 0} - target.roaming.returning = true + target.motion.home = [3]float32{21, 0, 0} + target.motion.returning = true } - target.roaming.nextMove = at + target.motion.nextMove = at before := target.position for tick := 1; tick <= 4; tick++ { world.advanceNPCs(at.Add(time.Duration(tick) * 250 * time.Millisecond)) } - if target.position != before || target.roaming.moving || !target.movementRestricted() { - t.Fatal("root moved in simulation", mode, target.position, target.roaming) + if target.position != before || target.motion.moving || !target.movementRestricted() { + t.Fatal("root moved in simulation", mode, target.position, target.motion) } deadline := target.activeNanos[0].expiresAt world.advanceNanos(deadline) @@ -60,7 +60,7 @@ func TestControlRootStopsRoamingPursuitAndReturnUntilExpiry(t *testing.T) { world.advanceNPCs(deadline.Add(250 * time.Millisecond)) world.advanceNPCs(deadline.Add(500 * time.Millisecond)) if target.movementRestricted() || target.position == before { - t.Fatal("expired root did not resume eligible motion", mode, target.position, target.roaming) + t.Fatal("expired root did not resume eligible motion", mode, target.position, target.motion) } }) } @@ -82,22 +82,22 @@ func TestControlSnareUsesSignedRunningSpeedAndLeavesWalkingUnchanged(t *testing. target.fighting = 0 target.threat = nil delete(world.fighting, target.id) - target.roaming.home = [3]float32{21, 0, 0} - target.roaming.returning = true + target.motion.home = [3]float32{21, 0, 0} + target.motion.returning = true } world.advanceNPCs(at.Add(250 * time.Millisecond)) - if math.Abs(float64(target.position[0])-scenario.position) > 0.00001 || !target.running || !target.roaming.moving || target.movementRestricted() { - t.Fatal("snare did not use native signed run scalar/floor", target.position, target.roaming) + if math.Abs(float64(target.position[0])-scenario.position) > 0.00001 || !target.running || !target.motion.moving || target.movementRestricted() { + t.Fatal("snare did not use native signed run scalar/floor", target.position, target.motion) } target.fighting = 0 target.threat = nil delete(world.fighting, target.id) - target.roaming.returning = false + target.motion.returning = false target.running = false - target.roaming.destination = [3]float32{21, 0, 0} - target.roaming.nextMove = at + target.motion.destination = [3]float32{21, 0, 0} + target.motion.nextMove = at before := target.position[0] world.advanceNPCs(at.Add(500 * time.Millisecond)) if math.Abs(float64(target.position[0]-before)-0.375) > 0.00001 { @@ -142,15 +142,15 @@ func TestFailedRootCastCannotLeakStoppedMovementThroughSharedState(t *testing.T) world.advanceNanos(deadline) - if !target.roaming.moving || !target.running || target.movementRestricted() || len(target.activeNanos) != 0 || len(target.threat) != 0 || player.nano != before || client.nanoCast != nil { - t.Fatal("failed root mutated live movement, taunt, effect or cost", target.roaming, target.activeNanos, target.threat, player.nano, before) + if !target.motion.moving || !target.running || target.movementRestricted() || len(target.activeNanos) != 0 || len(target.threat) != 0 || player.nano != before || client.nanoCast != nil { + t.Fatal("failed root mutated live movement, taunt, effect or cost", target.motion, target.activeNanos, target.threat, player.nano, before) } if _, err := world.db.Exec("DROP TRIGGER fail_root"); err != nil { t.Fatal(err) } castTestBuff(t, world, 1, target.id, 42110) cold := newTestInventoryServer(t).characters[target.id] - if !target.movementRestricted() || !cold.movementRestricted() || target.roaming.moving || cold.roaming.moving || player.nano != before-17 || target.threat[1] != 13 { + if !target.movementRestricted() || !cold.movementRestricted() || target.motion.moving || cold.motion.moving || player.nano != before-17 || target.threat[1] != 13 { t.Fatal("retried root was not committed exactly once", target.activeNanos, target.threat, player.nano) } }) @@ -177,7 +177,7 @@ func TestFailedRootExpiryKeepsAuthoritativeMovementBlockedUntilRemovalCommits(t world.advanceNanos(deadline) world.advanceNPCs(deadline.Add(250 * time.Millisecond)) - if !target.movementRestricted() || target.position != before || target.roaming.moving { + if !target.movementRestricted() || target.position != before || target.motion.moving { t.Fatal("failed removal let an expired root move", target.position, target.activeNanos) } if _, err := world.db.Exec("DROP TRIGGER fail_expiry"); err != nil { @@ -185,7 +185,7 @@ func TestFailedRootExpiryKeepsAuthoritativeMovementBlockedUntilRemovalCommits(t } world.advanceNanos(deadline.Add(500 * time.Millisecond)) world.advanceNPCs(deadline.Add(750 * time.Millisecond)) - if target.movementRestricted() || target.position == before || !target.roaming.moving { + if target.movementRestricted() || target.position == before || !target.motion.moving { t.Fatal("successful retry did not resume pursuit", target.position, target.activeNanos) } if len(newTestInventoryServer(t).characters[target.id].activeNanos) != 0 { @@ -244,7 +244,7 @@ func TestControlRootAndSnareDisappearAtomicallyOnLethalWeaponOutcome(t *testing. world.advanceCombat(player.nextAttack) cold := newTestInventoryServer(t).characters[target.id] - if target.health != 0 || cold.health != 0 || len(target.activeNanos) != 0 || len(cold.activeNanos) != 0 || target.roaming.moving || cold.roaming.moving || target.nanoBonus(156) != 0 || target.movementRestricted() { - t.Fatal("lethal outcome retained a control effect or moving route", target.health, target.activeNanos, cold.activeNanos, target.roaming) + if target.health != 0 || cold.health != 0 || len(target.activeNanos) != 0 || len(cold.activeNanos) != 0 || target.motion.moving || cold.motion.moving || target.nanoBonus(156) != 0 || target.movementRestricted() { + t.Fatal("lethal outcome retained a control effect or moving route", target.health, target.activeNanos, cold.activeNanos, target.motion) } } diff --git a/server/nano_control_test.go b/server/nano_control_test.go @@ -96,7 +96,7 @@ func TestControlNanosUploadCastRestoreAndExpireCompleteEffects(t *testing.T) { player.stats.Abilities = characterAbilitiesStats{10, 10, 10, 10, 10, 10} player.stats.Speed.NanoInitiative = 5 trained := player.baseStats() - target.roaming = &npcRoaming{home: target.position, destination: [3]float32{20, 0, 0}, moving: true} + target.motion = &npcMotion{roaming: true, home: target.position, destination: [3]float32{20, 0, 0}, moving: true} target.running = true target.fighting = 1 world.fighting[target.id] = target @@ -116,12 +116,12 @@ func TestControlNanosUploadCastRestoreAndExpireCompleteEffects(t *testing.T) { t.Fatal("complete control cast lost cost, effect, taunt or damaged the target", player.nano, target.health, target.activeNanos, target.threat) } if fixture.Kind == "root" { - if !target.movementRestricted() || !cold.movementRestricted() || target.roaming.moving || cold.roaming.moving || target.running { + if !target.movementRestricted() || !cold.movementRestricted() || target.motion.moving || cold.motion.moving || target.running { t.Fatal("root did not stop the durable route") } } else { amount := *fixture.Functions[0].Arguments[1].Integer - if target.movementRestricted() || target.nanoBonus(156) != amount || cold.nanoBonus(156) != amount || !target.roaming.moving { + if target.movementRestricted() || target.nanoBonus(156) != amount || cold.nanoBonus(156) != amount || !target.motion.moving { t.Fatal("snare lost its signed speed effect") } } diff --git a/server/npc_engagement_range_test.go b/server/npc_engagement_range_test.go @@ -23,7 +23,7 @@ func TestProfiledNPCRetainsEngagementOutsideWeaponRange(t *testing.T) { npc.monsterData, npc.level, npc.health = profile.monster, profile.level, 100 npc.combatProfile = gamedata.NPCCombatProfiles[profile.monster][profile.level] if roaming { - npc.roaming = &npcRoaming{home: npc.position} + npc.motion = &npcMotion{roaming: true, home: npc.position} } if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil { t.Fatal(err) diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -14,7 +14,7 @@ func (server *server) writeNPCOutcome_locked(tx *sql.Tx, target *character, now } state := target.worldState(true, time.Time{}) if target.health == 0 { - state.Roaming.Moving, state.Roaming.Returning = false, false + state.Motion.Moving, state.Motion.Returning = false, false if target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 { state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second) } diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go @@ -8,17 +8,19 @@ import ( ) func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, seconds float64, updates map[*worldClient][][]byte) bool { - // Other species and levels retain their existing combat and roaming policy. - if npc.combatProfile == nil || npc.monsterData != 17655 || npc.level != 1 || npc.fighting == 0 && !npc.roaming.returning { + // Combat capability selects pursuit independently of idle placement. + if npc.combatProfile == nil || npc.fighting == 0 && !npc.motion.returning { return false } - destination := npc.roaming.home + 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 { - server.stopAttack_locked(npc, updates) - } else { + server.selectNPCTarget_locked(npc, now, updates) + target = server.characters[npc.fighting] + } + if npc.fighting != 0 { destination = predictedPosition_locked(target, now) // Open-ground arrival threshold from NPC steering FUN_10048430. x, y, z := destination[0]-npc.position[0], destination[1]-npc.position[1], destination[2]-npc.position[2] @@ -43,14 +45,14 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se // Match roaming's terrain-height policy without inventing wall navigation. if ground := server.terrain[npc.playfield]; ground != nil { - home, available := ground.elevation(npc.roaming.home[0], npc.roaming.home[2]) + home, available := ground.elevation(npc.motion.home[0], npc.motion.home[2]) if available { height, inside := ground.elevation(position[0], position[2]) if !inside { server.stopNPCMotion_locked(npc, updates) return true } - position[1] = npc.roaming.home[1] + height - home + position[1] = npc.motion.home[1] + height - home } } npc.position = position @@ -62,13 +64,13 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se // Complete the return before allowing another idle roaming destination. if npc.fighting == 0 && distance <= step { server.stopNPCMotion_locked(npc, updates) - npc.roaming.returning = false - npc.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) + npc.motion.returning = false + npc.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) return true } - changed := !npc.roaming.moving || npc.roaming.destination != destination - npc.roaming.destination = destination - npc.roaming.moving = true + changed := !npc.motion.moving || npc.motion.destination != destination + npc.motion.destination = destination + npc.motion.moving = true npc.running = true if changed { server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc)) @@ -77,10 +79,10 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se } func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldClient][][]byte) { - if !npc.roaming.moving { + if !npc.motion.moving { return } - npc.roaming.moving = false + npc.motion.moving = false npc.running = false // Clear the waypoint controller, then restore walking for idle roaming. server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc), npcMovementPacket(npc, 22)) @@ -89,7 +91,7 @@ func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldCli func npcRoutePacket(npc *character) []byte { // 14.9.1 kkr.dll FUN_1007e540 / FUN_1007e690, including the waypoint count. targetType, targetID, control, count := uint32(0), uint32(0), byte(19), uint32(0) - if npc.roaming.moving { + if npc.motion.moving { targetType, targetID, control, count = 50000, npc.id, 22, 2 if npc.running { control = 23 @@ -104,8 +106,8 @@ func npcRoutePacket(npc *character) []byte { body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) } body = binary.BigEndian.AppendUint32(body, count) - if npc.roaming.moving { - for _, position := range [][3]float32{npc.position, npc.roaming.destination} { + if npc.motion.moving { + for _, position := range [][3]float32{npc.position, npc.motion.destination} { for _, value := range position { body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) } diff --git a/server/npc_pursuit_test.go b/server/npc_pursuit_test.go @@ -16,11 +16,11 @@ func newNPCPursuitWorld() (*server, *combatTestConn, time.Time) { npc := world.characters[1000000] npc.monsterData, npc.level = 17655, 1 npc.combatProfile = gamedata.NPCCombatProfiles[17655][1] - npc.roaming = &npcRoaming{home: npc.position} + npc.motion = &npcMotion{roaming: true, home: npc.position} npc.fighting = 1 npc.nextAttack = start.Add(1750 * time.Millisecond) world.fighting[npc.id] = npc - world.roamingNPCs = map[uint32][]*character{950: {npc}} + world.mobileNPCs = map[uint32][]*character{950: {npc}} world.lastNPCUpdate = start return world, conn, start } @@ -43,7 +43,7 @@ func TestNPCPursuitRetainsAttackDeadlineAndOnlyHitsInsideRange(t *testing.T) { world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) } - if world.characters[1].health < 92 || world.characters[1].health > 96 || world.characters[1000000].position != [3]float32{20.125, 0, 0} || world.characters[1000000].roaming.moving || world.characters[1000000].running || world.characters[1000000].fighting != 1 || world.characters[1000000].nextAttack != start.Add(5750*time.Millisecond) { + if world.characters[1].health < 92 || world.characters[1].health > 96 || world.characters[1000000].position != [3]float32{20.125, 0, 0} || world.characters[1000000].motion.moving || world.characters[1000000].running || world.characters[1000000].fighting != 1 || world.characters[1000000].nextAttack != start.Add(5750*time.Millisecond) { t.Fatalf("arrival did not resume normal combat: player=%+v npc=%+v", world.characters[1], world.characters[1000000]) } } @@ -69,7 +69,7 @@ func TestNPCPursuitChangesDirectionForMovingTargetWithoutRestartingAttack(t *tes world.advanceNPCs(start.Add(500 * time.Millisecond)) - if world.characters[1000000].position != [3]float32{2.125, 0, 1.125} || world.characters[1000000].nextAttack != deadline || len(conn.packets) != 2 || world.characters[1000000].roaming.destination != [3]float32{2.125, 0, 20} { + if world.characters[1000000].position != [3]float32{2.125, 0, 1.125} || world.characters[1000000].nextAttack != deadline || len(conn.packets) != 2 || world.characters[1000000].motion.destination != [3]float32{2.125, 0, 20} { t.Fatalf("target direction was not refreshed: %+v packets=%x", world.characters[1000000], conn.packets) } } @@ -94,13 +94,13 @@ func TestNPCPursuitReturnsHomeAfterTargetLossWithoutHealingOrTeleporting(t *test conn.packets = nil world.advanceNPCs(start.Add(750 * time.Millisecond)) - if world.characters[1000000].position != [3]float32{2.125, 0, 0} || !world.characters[1000000].roaming.returning || world.characters[1000000].fighting != 0 || world.characters[1000000].health != 50 { + if world.characters[1000000].position != [3]float32{2.125, 0, 0} || !world.characters[1000000].motion.returning || world.characters[1000000].fighting != 0 || world.characters[1000000].health != 50 { t.Fatal("target loss teleported, healed, or retained the old fight") } world.advanceNPCs(start.Add(time.Second)) world.advanceRegeneration(start.Add(time.Second)) - if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].roaming.returning || world.characters[1000000].roaming.moving || world.characters[1000000].running || world.characters[1000000].health != 50 || len(world.fighting) != 0 || !world.characters[1000000].roaming.nextMove.After(start.Add(time.Second)) { + if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].motion.returning || world.characters[1000000].motion.moving || world.characters[1000000].running || world.characters[1000000].health != 50 || len(world.fighting) != 0 || !world.characters[1000000].motion.nextMove.After(start.Add(time.Second)) { t.Fatalf("return did not finish cleanly: %+v", world.characters[1000000]) } }) @@ -121,7 +121,7 @@ func TestNPCPursuitCanBeEngagedAgainDuringReturn(t *testing.T) { hit := world.characters[1].nextAttack world.advanceCombat(hit) - if err != nil || world.characters[1000000].roaming.returning || world.characters[1000000].roaming.moving || world.characters[1000000].fighting != 1 || world.characters[1000000].health == 100 || len(world.fighting) != 2 { + if err != nil || world.characters[1000000].motion.returning || world.characters[1000000].motion.moving || world.characters[1000000].fighting != 1 || world.characters[1000000].health == 100 || len(world.fighting) != 2 { t.Fatalf("new encounter retained a return route: %+v err=%v", world.characters[1000000], err) } } @@ -147,7 +147,7 @@ func TestNPCPursuitDeathClearsRouteAndNeverReturnsCorpse(t *testing.T) { conn.packets = nil world.advanceNPCs(hit.Add(time.Second)) - if world.characters[1000000].health != 0 || world.characters[1000000].position != position || world.characters[1000000].roaming.returning || world.characters[1000000].roaming.moving || len(conn.packets) != 0 { + if world.characters[1000000].health != 0 || world.characters[1000000].position != position || world.characters[1000000].motion.returning || world.characters[1000000].motion.moving || len(conn.packets) != 0 { t.Fatalf("dead creature moved or retained pursuit: %+v packets=%x", world.characters[1000000], conn.packets) } }) @@ -168,17 +168,14 @@ func TestNPCPursuitJoiningObserverGetsSpawnBeforeRouteAndAttack(t *testing.T) { } } -func TestNPCPursuitDoesNotMoveOtherSpeciesOrLevels(t *testing.T) { - for _, scenario := range []string{"species", "level", "profile"} { +func TestNPCPursuitExcludesUnadmittedProfiles(t *testing.T) { + for _, scenario := range []string{"species", "profile"} { t.Run(scenario, func(t *testing.T) { world, _, start := newNPCPursuitWorld() switch scenario { case "species": world.characters[1000000].monsterData = 17657 world.characters[1000000].combatProfile = nil - case "level": - world.characters[1000000].level = 2 - world.characters[1000000].combatProfile = gamedata.NPCCombatProfiles[17655][2] case "profile": world.characters[1000000].combatProfile = nil } @@ -186,11 +183,7 @@ func TestNPCPursuitDoesNotMoveOtherSpeciesOrLevels(t *testing.T) { world.advanceNPCs(start.Add(250 * time.Millisecond)) world.advanceCombat(start.Add(250 * time.Millisecond)) - wantFighting := uint32(0) - if scenario == "level" { - wantFighting = 1 - } - if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].fighting != wantFighting || world.characters[1000000].roaming.moving { + if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].fighting != 0 || world.characters[1000000].motion.moving { t.Fatalf("unverified profile acquired pursuit: %+v", world.characters[1000000]) } }) diff --git a/server/npc_shared_pursuit_test.go b/server/npc_shared_pursuit_test.go @@ -0,0 +1,197 @@ +package main + +import ( + "ao/server/gamedata" + "fmt" + "testing" + "time" +) + +func TestAdmittedNPCProfilesSharePursuitAndReturn(t *testing.T) { + for _, profile := range []struct { + monster uint32 + level uint16 + }{{17655, 1}, {17655, 2}, {30354, 4}} { + for _, roaming := range []bool{false, true} { + t.Run(fmt.Sprintf("%d/%d/roaming=%t", profile.monster, profile.level, roaming), func(t *testing.T) { + world, _, start := newNPCPursuitWorld() + npc := world.characters[1000000] + npc.monsterData, npc.level = profile.monster, profile.level + npc.combatProfile = gamedata.NPCCombatProfiles[profile.monster][profile.level] + npc.motion.roaming = roaming + deadline := npc.nextAttack + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + + if npc.position != [3]float32{2.125, 0, 0} || !npc.running || !npc.motion.moving || npc.fighting != 1 || npc.nextAttack != deadline { + t.Fatal("admitted profile did not pursue through the shared motion path", npc.position, npc.fighting, npc.nextAttack) + } + + world.characters[1].health = 0 + world.advanceNPCs(start.Add(500 * time.Millisecond)) + world.advanceNPCs(start.Add(750 * time.Millisecond)) + + if npc.position != [3]float32{1, 0, 0} || npc.running || npc.motion.moving || npc.motion.returning || npc.fighting != 0 || !npc.nextAttack.IsZero() { + t.Fatal("admitted profile did not stop and return to its retained home", npc.position, npc.motion, npc.fighting) + } + + world.advanceNPCs(start.Add(time.Minute)) + + if npc.position != [3]float32{1, 0, 0} || npc.motion.moving != roaming || npc.running { + t.Fatal("return did not preserve its idle placement policy") + } + }) + } + } +} + +func newFixedBossPursuitWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newControlPursuitWorld(t) + npc := world.characters[1000000] + npc.monsterData, npc.level, npc.npcDefinitionID = 30354, 4, "952/district/5/fixed/0" + npc.combatProfile = gamedata.NPCCombatProfiles[30354][4] + npc.motion.roaming = false + npc.playfield, world.characters[1].playfield = 952, 952 + world.mobileNPCs = map[uint32][]*character{952: {npc}} + return world, conn +} + +func TestFixedNPCPursuitUsesRemainingThreatAfterTargetLoss(t *testing.T) { + world, _, start := newNPCPursuitWorld() + npc := world.characters[1000000] + npc.motion.roaming = false + npc.threat = map[uint32]int64{1: 20, 2: 10} + world.characters[2] = &character{id: 2, playfield: 950, position: [3]float32{2.125, 0, 20}, health: 100} + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + deadline := npc.nextAttack + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.characters[1].health = 0 + + world.advanceNPCs(start.Add(500 * time.Millisecond)) + + if npc.position != [3]float32{2.125, 0, 1.125} || npc.fighting != 2 || npc.nextAttack != deadline || npc.motion.returning || !npc.running { + t.Fatal("motion discarded remaining threat or restarted its attack clock", npc.position, npc.fighting, npc.nextAttack) + } +} + +func TestFixedNPCPursuitRespectsRootAndSnare(t *testing.T) { + for _, program := range []uint32{42110, 82518} { + t.Run(fmt.Sprint(program), func(t *testing.T) { + world, _ := newFixedBossPursuitWorld(t) + if program == 82518 { + world.characters[1].profession = 4 + } + npc := world.characters[1000000] + at := castTestBuff(t, world, 1, npc.id, program) + world.lastNPCUpdate = at + + world.advanceNPCs(at.Add(250 * time.Millisecond)) + + want := float32(2) + if program == 42110 { + want = 1 + } + if npc.position != [3]float32{want, 0, 0} || npc.motion.moving != (program != 42110) || npc.fighting != 1 { + t.Fatal("fixed encounter bypassed the shared movement control", npc.position, npc.motion) + } + if program == 42110 { + deadline := npc.activeNanos[0].expiresAt + world.advanceNanos(deadline) + world.lastNPCUpdate = deadline + world.advanceNPCs(deadline.Add(250 * time.Millisecond)) + + if npc.position != [3]float32{2.125, 0, 0} || !npc.motion.moving || !npc.running { + t.Fatal("root expiry did not resume fixed-encounter pursuit", npc.position, npc.motion) + } + } + }) + } +} + +func TestFixedNPCColdLoadReturnsWithoutRestoringCombat(t *testing.T) { + for _, state := range []string{"pursuit", "return", "rooted", "home"} { + t.Run(state, func(t *testing.T) { + world, _ := newFixedBossPursuitWorld(t) + npc := world.characters[1000000] + npc.health = 50 + if state != "home" { + npc.position = [3]float32{5.5, 0, 0} + } + npc.motion.returning = state == "return" + if state == "return" || state == "home" { + npc.fighting = 0 + delete(world.fighting, npc.id) + } + if state == "rooted" { + castTestBuff(t, world, 1, npc.id, 42110) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + before := npc.position + + cold := newTestInventoryServer(t) + cold.lastNPCUpdate = time.Now() + cold.advanceNPCs(cold.lastNPCUpdate.Add(250 * time.Millisecond)) + + restored := cold.characters[npc.id] + want := float32(4.375) + if state == "home" { + want = 1 + } + if state == "rooted" { + want = 5.5 + } + if restored.motion == nil || restored.motion.roaming || restored.motion.home != [3]float32{1, 0, 0} || restored.fighting != 0 || + restored.position != [3]float32{want, 0, 0} || restored.health != 50 || restored.motion.returning != (before != restored.motion.home) || len(cold.mobileNPCs[952]) != 1 { + t.Fatal("cold fixed encounter lost home, moved through a root or resumed stale combat", restored.position, restored.motion, restored.fighting) + } + }) + } +} + +func TestFixedNPCRespawnUsesHomeAndKeepsIdlePolicy(t *testing.T) { + world, _ := newFixedBossPursuitWorld(t) + world.nextNPC = 1000001 + npc, player := world.characters[1000000], world.characters[1] + npc.position, npc.health = [3]float32{3, 0, 0}, 1 + player.position = npc.position + if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack) + if len(world.npcRespawns) != 1 { + t.Fatal("moved fixed encounter did not die") + } + deadline := world.npcRespawns[0].at + + world.advanceNPCRespawns(deadline) + cold := newTestInventoryServer(t) + cold.lastNPCUpdate = deadline + cold.advanceNPCs(deadline.Add(time.Minute)) + + replacement := cold.characters[world.nextNPC-1] + if replacement == nil || replacement.id == npc.id || replacement.position != [3]float32{1, 0, 0} || replacement.motion.roaming || + replacement.motion.moving || replacement.motion.returning || replacement.health != 100 || len(cold.mobileNPCs[952]) != 1 || cold.characters[npc.id].health != 0 { + t.Fatal("fixed respawn reused corpse position, wandered or lost its separate life", replacement) + } +} + +func TestAuthoredFixedBossHasCombatMotion(t *testing.T) { + spawns, err := readNPCSpawns() + if err != nil { + t.Fatal(err) + } + + for _, npc := range spawns { + if npc.npcDefinitionID != "952/district/5/fixed/0" { + continue + } + if npc.motion == nil || npc.motion.home != npc.position || npc.motion.roaming { + t.Fatal("fixed boss has no retained home and combat motion") + } + return + } + t.Fatal("authored fixed boss missing") +} diff --git a/server/npcs.go b/server/npcs.go @@ -48,9 +48,10 @@ func readNPCSpawns() ([]character, error) { npcDefinitionID: group.ID, } spawn.health = spawn.maximumHealth() - // Fixed posts and human placeholders have no inferred roaming behavior. - if group.PlacementStatus != "fixed_point" && group.Appearance>>4&7 == 6 { - spawn.roaming = &npcRoaming{home: position} + // Idle placement is independent of admitted combat movement. + roaming := group.PlacementStatus != "fixed_point" && group.Appearance>>4&7 == 6 + if roaming || spawn.combatProfile != nil { + spawn.motion = &npcMotion{roaming: roaming, home: position} } spawns = append(spawns, spawn) } diff --git a/server/respawn.go b/server/respawn.go @@ -33,9 +33,9 @@ func (server *server) advanceNPCRespawns(now time.Time) { combatProfile: npcCombatProfile(respawn.npc.npcDefinitionID, respawn.npc.monsterData, respawn.npc.level), npcDefinitionID: respawn.npc.npcDefinitionID, } npc.health = npc.maximumHealth() - if respawn.npc.roaming != nil { - npc.position = respawn.npc.roaming.home - npc.roaming = &npcRoaming{home: npc.position} + if respawn.npc.motion != nil { + npc.position = respawn.npc.motion.home + npc.motion = &npcMotion{roaming: respawn.npc.motion.roaming, home: npc.position} } if err := server.saveNPCRespawn_locked(respawn.npc, npc, now); err != nil { log.Printf("Respawn: %v", err) @@ -45,12 +45,12 @@ func (server *server) advanceNPCRespawns(now time.Time) { // Publish the committed life and update its roaming worker only once. server.nextNPC++ - if npc.roaming != nil { - index := slices.Index(server.roamingNPCs[npc.playfield], respawn.npc) + if npc.motion != nil { + index := slices.Index(server.mobileNPCs[npc.playfield], respawn.npc) if index < 0 { - server.roamingNPCs[npc.playfield] = append(server.roamingNPCs[npc.playfield], npc) + server.mobileNPCs[npc.playfield] = append(server.mobileNPCs[npc.playfield], npc) } else { - server.roamingNPCs[npc.playfield][index] = npc + server.mobileNPCs[npc.playfield][index] = npc } } server.characters[npc.id] = npc diff --git a/server/respawn_durability_test.go b/server/respawn_durability_test.go @@ -83,7 +83,7 @@ func TestNPCRespawnFailureKeepsPendingLifeAndRetriesOnce(t *testing.T) { restored := newTestInventoryServer(t) if world.characters[1000001] != nil || world.nextNPC != 1000001 || len(world.npcRespawns) != 1 || !world.npcRespawns[0].at.Equal(due) || !reflect.DeepEqual(world.savedNPCs[1000000], before) || - len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0] != source || len(conn.packets) != 0 || + len(world.mobileNPCs[950]) != 1 || world.mobileNPCs[950][0] != source || len(conn.packets) != 0 || restored.characters[1000001] != nil || restored.nextNPC != 1000001 || len(restored.npcRespawns) != 1 || !restored.npcRespawns[0].at.Equal(due) { t.Fatal("failed transaction changed live or durable respawn state, or published an actor") @@ -96,7 +96,7 @@ func TestNPCRespawnFailureKeepsPendingLifeAndRetriesOnce(t *testing.T) { afterRetry := newTestInventoryServer(t) if world.characters[1000001] == nil || world.characters[1000001].health != 100 || len(world.npcRespawns) != 0 || - world.nextNPC != 1000002 || world.roamingNPCs[950][0].id != 1000001 || len(conn.packets) != 2 || + world.nextNPC != 1000002 || world.mobileNPCs[950][0].id != 1000001 || len(conn.packets) != 2 || afterRetry.characters[1000001] == nil || len(afterRetry.npcRespawns) != 0 || afterRetry.nextNPC != 1000002 { t.Fatal("retry did not create and commit exactly one fresh life") } diff --git a/server/respawn_test.go b/server/respawn_test.go @@ -38,8 +38,8 @@ func TestNPCRespawnCreatesOneFreshLifeAtHomeForBothObservers(t *testing.T) { npc := world.characters[1000000] npc.position[0]++ npc.rotation = [4]float32{0, 1, 0, 0} - npc.roaming.moving = true - npc.roaming.destination = [3]float32{55, 14, 56} + npc.motion.moving = true + npc.motion.destination = [3]float32{55, 14, 56} npc.rechargeUntil = time.Now().Add(time.Hour) world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]) @@ -63,11 +63,11 @@ func TestNPCRespawnCreatesOneFreshLifeAtHomeForBothObservers(t *testing.T) { if replacement.health != 100 || replacement.corpse != nil || replacement.fighting != 0 || !replacement.nextAttack.IsZero() || !replacement.rechargeUntil.IsZero() || replacement.position != [3]float32{52, 14, 56} || replacement.rotation != [4]float32{0, 0, 0, 1} || - replacement.roaming.home != [3]float32{52, 14, 56} || replacement.roaming.moving || !replacement.roaming.nextMove.IsZero() || + replacement.motion.home != [3]float32{52, 14, 56} || replacement.motion.moving || !replacement.motion.nextMove.IsZero() || replacement.combatProfile != npc.combatProfile || replacement.npcDefinitionID != "test/npc" { t.Fatalf("replacement retained dead-life state: %+v", replacement) } - if len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0] != replacement || + if len(world.mobileNPCs[950]) != 1 || world.mobileNPCs[950][0] != replacement || npc.health != 0 || npc.corpse == nil || npc.fighting != 0 || len(world.fighting) != 0 || world.clients[1].lootCorpse != npc.id { t.Fatal("respawn changed the corpse, active loot window or roaming population") } @@ -113,8 +113,8 @@ func TestNPCRespawnWithoutObserversThenReentryAndRestart(t *testing.T) { t.Fatalf("reentry lost the living replacement or old corpse: %d/%d/%d", spawns, corpses, profiles) } if len(restarted.characters) != 3 || restarted.characters[1000001].health != 100 || - restarted.characters[1000000].corpse == nil || len(restarted.npcRespawns) != 0 || len(restarted.roamingNPCs[950]) != 1 || - restarted.roamingNPCs[950][0].id != 1000001 { + restarted.characters[1000000].corpse == nil || len(restarted.npcRespawns) != 0 || len(restarted.mobileNPCs[950]) != 1 || + restarted.mobileNPCs[950][0].id != 1000001 { t.Fatal("restart lost the living replacement, old remains or consumed respawn deadline") } } @@ -178,7 +178,7 @@ func TestNPCRespawnKeepsOldLootSeparateAcrossTwoKills(t *testing.T) { world.advanceNPCRespawns(secondKill.Add(time.Hour)) if len(world.characters) != 4 || world.characters[1000002].health != 100 || world.characters[1000002].corpse != nil || - len(world.npcRespawns) != 0 || len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0].id != 1000002 { + len(world.npcRespawns) != 0 || len(world.mobileNPCs[950]) != 1 || world.mobileNPCs[950][0].id != 1000002 { t.Fatal("a second death did not produce exactly one fresh living replacement") } if world.characters[1000000].corpse == world.characters[1000001].corpse || diff --git a/server/roaming.go b/server/roaming.go @@ -8,7 +8,8 @@ import ( "time" ) -type npcRoaming struct { +type npcMotion struct { + roaming bool home [3]float32 destination [3]float32 nextMove time.Time @@ -50,9 +51,9 @@ func (server *server) advanceNPCs(now time.Time) { } // Idle roaming needs observers; active pursuit and returning home do not. - for zone, characters := range server.roamingNPCs { + for zone, characters := range server.mobileNPCs { for _, character := range characters { - if character.health == 0 || !zones[zone] && character.fighting == 0 && !character.roaming.returning { + if character.health == 0 || !zones[zone] && character.fighting == 0 && !character.motion.returning { continue } if character.movementRestricted() { @@ -62,30 +63,30 @@ func (server *server) advanceNPCs(now time.Time) { if server.advanceNPCPursuit_locked(character, now, seconds, clients) { continue } - if !zones[zone] || character.fighting != 0 { + if !zones[zone] || character.fighting != 0 || !character.motion.roaming { continue } - if character.roaming.nextMove.IsZero() { - character.roaming.nextMove = now.Add(time.Duration(1+character.id%32) * 250 * time.Millisecond) + if character.motion.nextMove.IsZero() { + character.motion.nextMove = now.Add(time.Duration(1+character.id%32) * 250 * time.Millisecond) } - if now.Before(character.roaming.nextMove) { + if now.Before(character.motion.nextMove) { continue } // Pick a nearby destination relative to home, so repeated walks never drift. - started := !character.roaming.moving - if !character.roaming.moving { + started := !character.motion.moving + if !character.motion.moving { angle := rand.Float64() * 2 * math.Pi distance := 4 * math.Sqrt(rand.Float64()) - character.roaming.destination = [3]float32{ - character.roaming.home[0] + float32(math.Sin(angle)*distance), - character.roaming.home[1], - character.roaming.home[2] + float32(math.Cos(angle)*distance), + character.motion.destination = [3]float32{ + character.motion.home[0] + float32(math.Sin(angle)*distance), + character.motion.home[1], + character.motion.home[2] + float32(math.Cos(angle)*distance), } - character.roaming.moving = true + character.motion.moving = true } - x := float64(character.roaming.destination[0] - character.position[0]) - z := float64(character.roaming.destination[2] - character.position[2]) + x := float64(character.motion.destination[0] - character.position[0]) + z := float64(character.motion.destination[2] - character.position[2]) distance := math.Hypot(x, z) angle := math.Atan2(x, z) character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))} @@ -100,7 +101,7 @@ func (server *server) advanceNPCs(now time.Time) { arrived := distance <= step position := character.position if distance <= step { - position = character.roaming.destination + position = character.motion.destination } else { position[0] += float32(x / distance * step) position[2] += float32(z / distance * step) @@ -108,11 +109,11 @@ func (server *server) advanceNPCs(now time.Time) { // Follow changes in terrain height while preserving the authored ground offset. if ground := server.terrain[character.playfield]; ground != nil { - home, available := ground.elevation(character.roaming.home[0], character.roaming.home[2]) + home, available := ground.elevation(character.motion.home[0], character.motion.home[2]) if available { height, inside := ground.elevation(position[0], position[2]) if inside { - position[1] = character.roaming.home[1] + height - home + position[1] = character.motion.home[1] + height - home } else { position = character.position arrived = true @@ -122,7 +123,7 @@ func (server *server) advanceNPCs(now time.Time) { character.position = position if arrived { server.stopNPCMotion_locked(character, clients) - character.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) + character.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) } } } diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -104,7 +104,7 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { if world.characters[1000001].position != [3]float32{54, 14, 56} || world.characters[1000002].position != [3]float32{100, 14, 100} { t.Fatal("human or unoccupied-zone NPC moved") } - if math.Hypot(float64(world.characters[1000000].roaming.destination[0]-52), float64(world.characters[1000000].roaming.destination[2]-56)) > 4.001 { + if math.Hypot(float64(world.characters[1000000].motion.destination[0]-52), float64(world.characters[1000000].motion.destination[2]-56)) > 4.001 { t.Fatal("destination escaped the home radius") } } @@ -137,9 +137,9 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) { } now := time.Now() world.lastNPCUpdate = now - world.characters[1000000].roaming.destination = [3]float32{53.5, 14, 56} - world.characters[1000000].roaming.moving = true - world.characters[1000000].roaming.nextMove = now + world.characters[1000000].motion.destination = [3]float32{53.5, 14, 56} + world.characters[1000000].motion.moving = true + world.characters[1000000].motion.nextMove = now var packets [][]byte done := make(chan struct{}) go func() { @@ -177,8 +177,8 @@ func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) { useNPCData(t, data) world := newTestServer(t) world.characters[1000000].position = [3]float32{53, 14, 56} - world.characters[1000000].roaming.destination = [3]float32{54.5, 14, 56} - world.characters[1000000].roaming.moving = true + world.characters[1000000].motion.destination = [3]float32{54.5, 14, 56} + world.characters[1000000].motion.moving = true player := world.newCharacter() client, connection := net.Pipe() defer client.Close() @@ -226,9 +226,9 @@ func TestRoamingStopsAndPausesAtDestination(t *testing.T) { t.Fatal(err) } now := time.Now() - world.characters[1000000].roaming.destination = [3]float32{52.125, 14, 56} - world.characters[1000000].roaming.moving = true - world.characters[1000000].roaming.nextMove = now + world.characters[1000000].motion.destination = [3]float32{52.125, 14, 56} + world.characters[1000000].motion.moving = true + world.characters[1000000].motion.nextMove = now done := make(chan struct{}) go func() { world.advanceNPCs(now); close(done) }() @@ -243,10 +243,10 @@ func TestRoamingStopsAndPausesAtDestination(t *testing.T) { <-done world.advanceNPCs(now.Add(250 * time.Millisecond)) - if binary.BigEndian.Uint32(packet[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packet[61:65]) != 0 || binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{52.125, 14, 56} || world.characters[1000000].roaming.moving { + if binary.BigEndian.Uint32(packet[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packet[61:65]) != 0 || binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{52.125, 14, 56} || world.characters[1000000].motion.moving { t.Fatal("NPC did not stop at its destination") } - if world.characters[1000000].roaming.nextMove.Before(now.Add(3 * time.Second)) { + if world.characters[1000000].motion.nextMove.Before(now.Add(3 * time.Second)) { t.Fatal("NPC did not pause between walks") } } @@ -256,7 +256,7 @@ func TestFixedCreatureDoesNotRoam(t *testing.T) { world := newTestServer(t) - if world.characters[1000000].roaming != nil { + if world.characters[1000000].motion != nil { t.Fatal("fixed creature received roaming behavior") } } @@ -267,9 +267,9 @@ func TestRoamingPausesWithoutPlayers(t *testing.T) { useNPCData(t, data) world := newTestServer(t) now := time.Now() - world.characters[1000000].roaming.moving = true - world.characters[1000000].roaming.nextMove = now - world.characters[1000000].roaming.destination = [3]float32{55, 14, 56} + world.characters[1000000].motion.moving = true + world.characters[1000000].motion.nextMove = now + world.characters[1000000].motion.destination = [3]float32{55, 14, 56} world.advanceNPCs(now.Add(time.Hour)) @@ -299,9 +299,9 @@ func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) { t.Fatal(err) } now := time.Now() - world.characters[1000000].roaming.destination = [3]float32{52.25, 14, 56} - world.characters[1000000].roaming.moving = true - world.characters[1000000].roaming.nextMove = now + world.characters[1000000].motion.destination = [3]float32{52.25, 14, 56} + world.characters[1000000].motion.moving = true + world.characters[1000000].motion.nextMove = now done := make(chan struct{}) go func() { world.advanceNPCs(now); close(done) }() @@ -342,9 +342,9 @@ func TestRoamingStopsAtTerrainBoundary(t *testing.T) { } now := time.Now() world.characters[1000000].position = [3]float32{64, 20, 56} - world.characters[1000000].roaming.destination = [3]float32{64.25, 14, 56} - world.characters[1000000].roaming.moving = true - world.characters[1000000].roaming.nextMove = now + world.characters[1000000].motion.destination = [3]float32{64.25, 14, 56} + world.characters[1000000].motion.moving = true + world.characters[1000000].motion.nextMove = now done := make(chan struct{}) go func() { world.advanceNPCs(now); close(done) }() @@ -358,7 +358,7 @@ func TestRoamingStopsAtTerrainBoundary(t *testing.T) { } <-done - if binary.BigEndian.Uint32(packet[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packet[61:65]) != 0 || binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{64, 20, 56} || world.characters[1000000].roaming.moving { + if binary.BigEndian.Uint32(packet[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packet[61:65]) != 0 || binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{64, 20, 56} || world.characters[1000000].motion.moving { t.Fatal("NPC walked beyond the terrain grid") } } diff --git a/server/state.go b/server/state.go @@ -49,7 +49,7 @@ type character struct { returnDoor *doorOrigin npc bool npcDefinitionID string - roaming *npcRoaming + motion *npcMotion damageContributors map[damageContributor]uint32 leadingContributor damageContributor @@ -129,7 +129,7 @@ type server struct { nextItem uint32 items map[uint32]itemRecord characters map[uint32]*character - roamingNPCs map[uint32][]*character + mobileNPCs map[uint32][]*character npcRespawns []npcRespawn corpseExpiry []*character missionExpiry []acceptedMission @@ -152,11 +152,11 @@ func newServer() *server { loginPort: 7500, worldPort: 7501, httpPort: 8080, baseURL: "/", gameSeconds: 48600, clockStarted: time.Now(), - characters: make(map[uint32]*character), - roamingNPCs: make(map[uint32][]*character), - clients: make(map[uint32]*worldClient), - fighting: make(map[uint32]*character), - chats: make(map[uint32]*chatClient), + characters: make(map[uint32]*character), + mobileNPCs: make(map[uint32][]*character), + clients: make(map[uint32]*worldClient), + fighting: make(map[uint32]*character), + chats: make(map[uint32]*chatClient), } ground, err := readTerrain() if err != nil { @@ -187,8 +187,8 @@ func newServer() *server { for _, spawn := range spawns { server.characters[spawn.id] = &spawn server.nextNPC = max(server.nextNPC, spawn.id+1) - if spawn.roaming != nil { - server.roamingNPCs[spawn.playfield] = append(server.roamingNPCs[spawn.playfield], &spawn) + if spawn.motion != nil { + server.mobileNPCs[spawn.playfield] = append(server.mobileNPCs[spawn.playfield], &spawn) } } } diff --git a/server/world.sql b/server/world.sql @@ -167,7 +167,7 @@ CREATE TABLE IF NOT EXISTS npcs ( respawn_at DATETIME NOT NULL, leading_contributor INTEGER NOT NULL, leading_team INTEGER NOT NULL, - has_roaming INTEGER NOT NULL, + idle_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, next_move DATETIME NOT NULL, diff --git a/server/world_store.go b/server/world_store.go @@ -7,7 +7,7 @@ import ( "time" ) -type roamingState struct { +type motionState struct { Home [3]float32 Destination [3]float32 NextMove time.Time @@ -25,8 +25,8 @@ type corpseState struct { type npcState struct { Character characterRecord Definition string - Roaming roamingState - HasRoaming bool + Motion motionState + IdleRoaming bool Corpse corpseState HasCorpse bool Present bool @@ -40,21 +40,21 @@ type savedNPC struct { NextSave time.Time } -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" +const npcColumns = "definition, present, respawn_at, leading_contributor, leading_team, idle_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.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.Team, &state.Corpse.Credits, &state.Corpse.ExpiresAt} + return []any{&state.Definition, &state.Present, &state.RespawnAt, &state.LeadingContributor.player, &state.LeadingContributor.team, &state.IdleRoaming, + &state.Motion.Home[0], &state.Motion.Home[1], &state.Motion.Home[2], &state.Motion.Destination[0], &state.Motion.Destination[1], &state.Motion.Destination[2], + &state.Motion.NextMove, &state.Motion.Moving, &state.Motion.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 { state := npcState{Character: npc.record(), Definition: npc.npcDefinitionID, Present: present, RespawnAt: respawnAt, LeadingContributor: npc.leadingContributor} state.Character.Profile.Stats, state.Character.Profile.Profession = npc.stats, npc.profession - if npc.roaming != nil { - state.HasRoaming = true - state.Roaming = roamingState{npc.roaming.home, npc.roaming.destination, npc.roaming.nextMove, npc.roaming.moving, npc.roaming.returning} + if npc.motion != nil { + state.IdleRoaming = npc.motion.roaming + state.Motion = motionState{npc.motion.home, npc.motion.destination, npc.motion.nextMove, npc.motion.moving, npc.motion.returning} } if npc.corpse != nil { state.HasCorpse = true @@ -187,16 +187,21 @@ func (server *server) loadNPCs() (bool, error) { npc.stats, npc.profession = state.Character.Profile.Stats, state.Character.Profile.Profession npc.combatProfile = npcCombatProfile(npc.npcDefinitionID, npc.monsterData, npc.level) npc.leadingContributor = state.LeadingContributor - if state.HasRoaming { - npc.roaming = &npcRoaming{state.Roaming.Home, state.Roaming.Destination, state.Roaming.NextMove, state.Roaming.Moving, state.Roaming.Returning} + if state.IdleRoaming || npc.combatProfile != nil { + npc.motion = &npcMotion{state.IdleRoaming, state.Motion.Home, state.Motion.Destination, state.Motion.NextMove, state.Motion.Moving, state.Motion.Returning} + // Combat targets are transient; displaced combatants return before idling. + if npc.combatProfile != nil && npc.health != 0 { + npc.motion.moving, npc.running = false, false + npc.motion.returning = npc.position != npc.motion.home + } } if state.HasCorpse { 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 - if npc.roaming != nil && npc.health != 0 { - server.roamingNPCs[npc.playfield] = append(server.roamingNPCs[npc.playfield], npc) + if npc.motion != nil && npc.health != 0 { + server.mobileNPCs[npc.playfield] = append(server.mobileNPCs[npc.playfield], npc) } if npc.corpse != nil && !npc.corpse.expiresAt.IsZero() { server.corpseExpiry = append(server.corpseExpiry, npc)