aorecomp

Anarchy Online classic in the browser

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


commit b455c245ff1066ac9ee63a294626fc8d3c7f036a
parent b97da952b3a56f2918d3cb7be644f2a1e4514d2e
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 23:46:32 +0000

Replicate native team health and nano with observer bonus accounting

Diffstat:
MTODO.md | 18+++++++++++++++++-
Adocs/team-resources.md | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/teams.md | 6++++--
Mserver/equipment.go | 10+++++-----
Mserver/ip_training.go | 10+++++-----
Mserver/regeneration.go | 45++++++++++++++++++++++++++++++++-------------
Mserver/state.go | 6++++++
Aserver/team_resources.go | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/team_resources_test.go | 446+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/teams.go | 9++++++++-
Mserver/teams_test.go | 6+++---
Mserver/world_actions.go | 3+++
12 files changed, 741 insertions(+), 30 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -116,6 +116,15 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). and remains correct after reconnect and removal. - [x] Apply overequipping rules to one weapon. Check: dropping below a verified requirement threshold changes effectiveness at the correct boundary. +- [ ] Apply armor/backpack overequipping to AC and maximum health. Check: + recovered requirement tiers, rounding and restoration agree with the native + client, including after reconnect and in team resource snapshots. A Dust + Collector assigned below its requirements loses its 90 HP/1200 ProjectileAC + bonuses in the original client while the server still grants them; its 90 + maximum-nano bonus remains. Qualifying the wearer restores native agreement. + Captures: `local/team-resources-research/equipped-fresh-solo.json` and + `qualified-solo.json`. Do not generalize one zero-effectiveness case to all + armor tiers or reduce unrelated bonuses without recovering their rules. The supported Metaplast pieces, native appearance, combined AC bonuses and server-side damage checks are recorded in [armor](docs/armor.md). These stat @@ -483,8 +492,15 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). initial level is 1. Later manuals do not establish the original timer. - [x] Transfer team leadership explicitly. Check: only the leader can transfer to an eligible member, both native controls update, and the change persists. -- [ ] Replicate team resources. Check: a teammate's health/nano display updates +- [x] Replicate team resources. Check: a teammate's health/nano display updates correctly without spawning unrelated actors or exposing private inventory. + Native bars follow current/equipped maxima, regeneration, combat and zoning; + resource modifier accounting survives skill training and team departure. + Protocol details and verification: [team resources](docs/team-resources.md). +- [ ] Recover original team-resource publication and prediction timing. Check: + original producer/capture evidence establishes cadence, remote skill inputs + and phase behavior. Current authoritative corrections use the existing + two-second regeneration cadence; intermediate native prediction can differ. - [ ] Share XP from one team kill. Check: a controlled encounter awards the expected shares once and excludes ineligible members. - [ ] Apply one team loot policy. Check: a known two-player loot sequence follows diff --git a/docs/team-resources.md b/docs/team-resources.md @@ -0,0 +1,123 @@ +# Native team health and nano + +Team resources use the original 14.9.1 actor and TeamView paths. The roster +retains names across zoning, but the GUI deliberately empties both bars when +the member's actor is absent. Resource delivery does not create actors, send +inventory, or extend world interest. + +## Original packet and GUI contract + +KKR `10084650` reads TeamMemberInfo, key `28784248`. Its body is exactly +40 bytes, all big-endian 32-bit fields: + +| Field | Meaning | +| --- | --- | +| member type, member ID | Actor identity, normally type 50000 | +| stat 343, stat 342 | HealDelta and HealInterval | +| stat 364, stat 363 | NanoDelta and NanoInterval | +| stat 214, stat 221 | Current and maximum nano | +| stat 1, stat 27 | Maximum and current health | + +Activation `10084740` resolves the body's identity, ignores the local actor, +and drops unresolved actors. It does not establish membership or enforce team +privacy. The server must select authorized recipients. After assigning the +fields, it clears additive maximum-health/nano modifiers through +`100762f0(stat, 0)`, so those two transmitted maxima include equipment effects. + +DDR TeamView `1004a620` polls existing actors for health 27/1 and nano 214/221, +then passes their ratios to the native PowerBars. Missing actors explicitly +produce zero bars while their rows remain. Current HP comes from actor `+0x1b0`, +the same mirror used by delayed weapon impacts. TeamMemberInfo's ordinary stat +27 setter also overwrites that mirror; it is not an independent GUI cache. + +Remote actors perform native regeneration prediction. The packet's deltas are +components, not total recovery: the native loop separately adds effective +BodyDevelopment divided by Rest. It also halves the health interval while +sitting and masks the nano interval to an even value. The current server sends +the native breed delta bases and computed, unhalved Stamina/Psychic intervals. +It does not disable prediction or transmit total gains as delta components. + +Independent original-source audits, DLL identities, import checks and a +read-only TeamView row probe are retained under +`local/team-resources-research/`. They reuse the original artifact identities +recorded in [teams](teams.md). These are static source findings unless explicitly +identified as browser observations below. + +## Delivery and combat ordering + +Accepted formation sends resources after each recipient's roster, leader and +side. Ready/reconnect sends the returning actor's public resources to loaded +teammates after its equipment replay. The returning client receives its peers' +initial snapshots before it can receive their subsequent combat updates. +Repeated ready messages do not replay either snapshot sequence. + +Subsequent updates use the existing two-second regeneration cadence and current +in-memory state. Only ready, loaded members of the same accepted team and +playfield receive them. Loading, disconnected and departed members do not +receive team resource fields. No resource replication writes to the database. + +Outside combat, TeamMemberInfo corrects all eight fields. During outgoing or +incoming combat, ordinary stat packets correct the seven non-HP fields and +leave current HP on the native impact timeline. Each connection records the +direct equipment bonuses absorbed by its last full snapshot. Later stat +corrections use that observer's basis, including after departure from the team: +the native actor retains its folded maxima until it is replaced. Equipment +changes between snapshots can otherwise double or lose bonuses. Actor spawn +and removal reset this basis. Skill training and equipment-derived foundation +changes use the same accounting. Ordinary hit, death, resurrection and quiet +health packets retain their established paths. + +The original server's resource publication frequency and remote prediction +phase were not recovered. Two seconds is the current server's existing cadence, +not an asserted historical constant. Remote actors do not necessarily hold all +of the owning player's private skills, so exact intermediate prediction parity +still needs original producer/capture evidence. Authoritative snapshots correct +the displayed resources; this does not establish every historical timing rule. + +## Verification + +Go regressions cover initial wire order/values, current and equipped maxima, +two-second scheduling without duplicate publication, incoming/outgoing combat +without absolute HP, initial ready during a peer's fight, returning-member +replay, death, departure and loading/offline/other-playfield/unrelated recipients. +Equipped cases use a durably worn Dust Collector and check combat both before +and after a full snapshot. Further regressions cover skill training while +teamed and after leaving, changing to a Pioneer Backpack with ability trickle, +durable item identities/placements, and replacing an actor on reconnect. + +Before implementation, two WASM clients reproduced the missing replication: +Visitor22's own nano maximum was 511 while its teammate used 10 and retained +stale current nano. The captured native caches and PowerBar fractions are in +`local/team-resources-research/red-peer.json` and `red-leader.json`. + +The complete Go server suite passed in 277 seconds. Team, regeneration, +skill-training and backpack regressions passed twice under the race detector +in 163 seconds. No client or adapter change was needed for resource delivery. + +Two WASM clients rendered through the GPU verified control-panel resource +edits, changed maxima, sitting regeneration, combat, shop zoning/return and a +qualified resource backpack. Across two 18-sample fights, both actors' HP +mirrors followed the same damage sequence; equipped maximum HP stayed 2836. +TeamView's scheduled GUI cache briefly lagged at two samples, then converged. +The owning row also retained the preceding maximum in the immediate training +capture while the actor and later peer capture already held the new value. +These observations distinguish native polling from authoritative resource state. + +Native skill training verified successive HP maxima 1201, 1207, 1213 and 1219: +initially equipped, trained while teamed, trained after departure, and trained +again after reconnect. The former observer retained its absorbed bonus after +departure, then rebuilt the normal equipment modifier on actor replacement. +`local/team-resources-research/verification.json` checks 21 native snapshots, +both combat sequences, native packet coverage and conservation of all 192 +original item records and placements. Temporary items were deleted through +the native inventory, the team dissolved and both edited profiles restored. +All owned browser contexts were closed without page/adapter errors. The single +shared LAN preview remains available on HTTPS 8443. + +The equipped fixture also exposed a separate server gap: assigning a Dust +Collector below its requirements leaves native HP and AC bonuses at zero, +while the server grants them. Nano retains its bonus. This occurs in a fresh +solo client too, and qualifying the wearer restores HP/AC. The paired +`equipped-fresh-solo.json` and `qualified-solo.json` captures preserve that +discriminator. Armor/backpack overequipping remains an explicit TODO; resource +transport must not conceal it by modifying the native equipment behavior. diff --git a/docs/teams.md b/docs/teams.md @@ -185,5 +185,7 @@ preview remains available on HTTPS 8443. Team level still uses the native initial value 1. CharacterAction 27 carries level updates, but original progression thresholds, penalties and bonuses are unverified. A later official manual describes time-based growth, but does not -establish a 14.9.1 timer. Team-level progression, remote HP/nano updates, chat, -XP sharing, loot rotation and disconnect expiry remain separate open work. +establish a 14.9.1 timer. [Remote HP/nano updates](team-resources.md) now use the +native resource packet with combat ordering and per-observer modifier accounting. +Team-level progression, chat, XP sharing, loot rotation and disconnect expiry +remain separate open work. diff --git a/server/equipment.go b/server/equipment.go @@ -326,14 +326,14 @@ func (server *server) advanceEquipment(now time.Time) { {22, attackRating, character.attackRating()}, } { if stat[1] != stat[2] { + if stat[0] == 1 || stat[0] == 221 { + server.queueResourceMaximum_locked(updates, character, stat[0], stat[2]) + continue + } body := binary.BigEndian.AppendUint32(nil, stat[0]) body = binary.BigEndian.AppendUint32(body, stat[2]) packet := n3Packet(0x2b333d6e, 50000, character.id, body) - if stat[0] == 221 { - updates[client] = append(updates[client], packet) - } else { - server.queueCombat_locked(updates, character, character, packet) - } + server.queueCombat_locked(updates, character, character, packet) } } if character.health != health { diff --git a/server/ip_training.go b/server/ip_training.go @@ -127,14 +127,14 @@ func (server *server) handleSkillTraining(client *worldClient, body []byte) erro {22, attackRating, player.attackRating()}, } { if stat[1] != stat[2] { + if stat[0] == 1 || stat[0] == 221 { + server.queueResourceMaximum_locked(updates, player, stat[0], stat[2]) + continue + } body := binary.BigEndian.AppendUint32(nil, stat[0]) body = binary.BigEndian.AppendUint32(body, stat[2]) packet := n3Packet(0x2b333d6e, 50000, player.id, body) - if stat[0] == 221 { - updates[client] = append(updates[client], packet) - } else { - server.queueCombat_locked(updates, player, player, packet) - } + server.queueCombat_locked(updates, player, player, packet) } } } diff --git a/server/regeneration.go b/server/regeneration.go @@ -5,6 +5,17 @@ import ( "time" ) +func (player *character) regenerationIntervals() (health, nano uint32) { + // kkr.dll FUN_10074560; posture halves the health interval in the tick loop. + percent := 100.0 + if player.fighting != 0 { + percent = 200 + } + health = uint32(max(1, int((30-float64(player.effectiveAbility(18))*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) + nano = uint32(max(1, int((30-float64(player.effectiveAbility(21))*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) + return +} + func (server *server) advanceRegeneration(now time.Time) { // Serialize resource corrections with hit, stop, death and zone messages. server.updateMutex.Lock() @@ -28,18 +39,18 @@ func (server *server) advanceRegeneration(now time.Time) { client.regenerationAt = client.regenerationAt.Add(intervals * 2 * time.Second) client.regenerationSeconds += 2 player := server.characters[id] - if player.npc || player.health == 0 { + if player.npc { + continue + } + if player.health == 0 { + server.queueTeamResources_locked(updates, player) continue } // kkr.dll FUN_10074560 / FUN_1006ea50, with the native float reciprocal. stats := player.baseStats() - percent := 100.0 - if player.fighting != 0 { - percent = 200 - } - healthInterval := uint32(max(1, int((30-float64(player.effectiveAbility(18))*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) - nanoInterval := uint32(max(1, int((30-float64(player.effectiveAbility(21))*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) &^ 1 + healthInterval, nanoInterval := player.regenerationIntervals() + nanoInterval &^= 1 rest := uint32(100) if player.sitting { rest = 25 @@ -62,6 +73,7 @@ func (server *server) advanceRegeneration(now time.Time) { body := binary.BigEndian.AppendUint32(nil, 214) body = binary.BigEndian.AppendUint32(body, player.nano) updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, id, body)) + server.queueTeamResources_locked(updates, player) } server.mutex.Unlock() server.sendCombatUpdates(updates) @@ -69,14 +81,9 @@ func (server *server) advanceRegeneration(now time.Time) { func (server *server) queueQuietHealth_locked(updates map[*worldClient][][]byte, actor *character) { // Absolute HP must wait until weapon queues have been flushed by StopFight. - if actor.fighting != 0 { + if server.characterInCombat_locked(actor) { return } - for _, attacker := range server.fighting { - if attacker.fighting == actor.id { - return - } - } // HealthDamage assigns absolute HP; a zero change suppresses feedback. var body []byte @@ -85,3 +92,15 @@ func (server *server) queueQuietHealth_locked(updates map[*worldClient][][]byte, } server.queueCombat_locked(updates, actor, actor, n3Packet(0x3710256c, 50000, actor.id, body)) } + +func (server *server) characterInCombat_locked(actor *character) bool { + if actor.fighting != 0 { + return true + } + for _, attacker := range server.fighting { + if attacker.fighting == actor.id { + return true + } + } + return false +} diff --git a/server/state.go b/server/state.go @@ -82,6 +82,7 @@ type worldClient struct { useSequence uint32 selectedTarget [2]uint32 teamInvitation *teamInvitation + absorbedBonuses map[uint32]resourceBonuses } func (client *worldClient) send(packet []byte) error { @@ -202,8 +203,13 @@ func (server *server) broadcast(playfield, exclude uint32, packet []byte) { // Copy the connection list before performing any network writes. server.mutex.Lock() var clients []*worldClient + key := binary.BigEndian.Uint32(packet[20:24]) for id, client := range server.clients { if id != exclude && client.ready && server.characters[id].playfield == playfield { + // A new or removed actor no longer has its previous TeamMemberInfo basis. + if (key == 0x271b3a6b || key == 0x36510078) && binary.BigEndian.Uint32(packet[24:28]) == 50000 { + delete(client.absorbedBonuses, binary.BigEndian.Uint32(packet[28:32])) + } clients = append(clients, client) } } diff --git a/server/team_resources.go b/server/team_resources.go @@ -0,0 +1,89 @@ +package main + +import "encoding/binary" + +// TeamMemberInfo folds these direct modifiers into each observer's raw maxima. +type resourceBonuses struct { + health int32 + nano int32 +} + +func teamResourceStats(member *character) [8][2]uint32 { + healthInterval, nanoInterval := member.regenerationIntervals() + breed := member.appearance >> 4 & 7 + // Native prediction adds BodyDevelopment/rest separately to these breed deltas. + return [8][2]uint32{ + {343, [8]uint32{2, 3, 3, 2, 4, 6, 2, 2}[breed]}, + {342, healthInterval}, + {364, [8]uint32{2, 3, 3, 4, 2, 1, 2, 2}[breed]}, + {363, nanoInterval}, + {214, member.nano}, {221, member.maximumNano()}, + {1, member.maximumHealth()}, {27, member.health}, + } +} + +func (server *server) teamResourcePacket_locked(owner uint32, member *character) []byte { + // TeamMemberInfo resolves the body's member identity and ignores the local actor. + client := server.clients[owner] + if client.absorbedBonuses == nil { + client.absorbedBonuses = make(map[uint32]resourceBonuses) + } + client.absorbedBonuses[member.id] = resourceBonuses{ + health: member.inventory.equipmentBonus(1), nano: member.inventory.equipmentBonus(221), + } + body := binary.BigEndian.AppendUint32(nil, 50000) + body = binary.BigEndian.AppendUint32(body, member.id) + for _, stat := range teamResourceStats(member) { + body = binary.BigEndian.AppendUint32(body, stat[1]) + } + return n3Packet(0x28784248, 50000, owner, body) +} + +func (server *server) queueTeamResources_locked(updates map[*worldClient][][]byte, member *character) { + if member.team == nil { + return + } + for _, id := range member.team.members { + client := server.clients[id] + if id == member.id || client == nil || !client.ready || client.loading || server.characters[id].playfield != member.playfield { + continue + } + if !server.characterInCombat_locked(member) { + updates[client] = append(updates[client], server.teamResourcePacket_locked(id, member)) + continue + } + // Preserve HP's hit-animation timeline and each observer's modifier basis. + for _, stat := range teamResourceStats(member) { + if stat[0] != 27 { + if stat[0] == 1 { + stat[1] += uint32(client.absorbedBonuses[member.id].health - member.inventory.equipmentBonus(1)) + } else if stat[0] == 221 { + stat[1] += uint32(client.absorbedBonuses[member.id].nano - member.inventory.equipmentBonus(221)) + } + body := binary.BigEndian.AppendUint32(nil, stat[0]) + body = binary.BigEndian.AppendUint32(body, stat[1]) + updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, member.id, body)) + } + } + } +} + +func (server *server) queueResourceMaximum_locked(updates map[*worldClient][][]byte, actor *character, stat, base uint32) { + for id, client := range server.clients { + if !client.ready || client.loading || server.characters[id].playfield != actor.playfield || + stat == 221 && id != actor.id && (actor.team == nil || actor.team != server.characters[id].team) { + continue + } + value := base + if id != actor.id { + if stat == 1 { + value += uint32(client.absorbedBonuses[actor.id].health) + } else { + value += uint32(client.absorbedBonuses[actor.id].nano) + } + } + body := binary.BigEndian.AppendUint32(nil, stat) + body = binary.BigEndian.AppendUint32(body, value) + updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, actor.id, body)) + } +} diff --git a/server/team_resources_test.go b/server/team_resources_test.go @@ -0,0 +1,446 @@ +package main + +import ( + "bytes" + "encoding/binary" + "net" + "testing" + "time" +) + +func teamResourceUpdates(packets [][]byte) [][]byte { + var resources [][]byte + for _, packet := range packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x28784248 { + resources = append(resources, packet) + } + } + return resources +} + +func newResourceBackpackTeam(t *testing.T) (*server, []*combatTestConn) { + t.Helper() + world, connections := newTeamWorld(t) + player := world.characters[1] + player.level = 3 + player.stats.Abilities = characterAbilitiesStats{12, 12, 12, 12, 12, 12} + player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy = 98, 848 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, 200461); err != nil || !granted { + t.Fatal("resource backpack grant failed", err) + } + if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 19)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(world.clients[1].equipment.readyAt) + formTestTeam(t, world, 1, 2) + return world, connections +} + +func TestTeamResourcesInitializeTheOtherMemberAfterItsRoster(t *testing.T) { + world, connections := newTeamWorld(t) + world.characters[1].health, world.characters[1].nano = 20, 10 + world.characters[2].health, world.characters[2].nano = 15, 7 + + formTestTeam(t, world, 1, 2) + + for index, conn := range connections[:2] { + packets := teamResourceUpdates(conn.packets) + if len(packets) != 1 { + t.Fatalf("recipient %d got %d resource snapshots", index+1, len(packets)) + } + packet := packets[0] + if len(packet) != 72 || binary.BigEndian.Uint32(packet[24:28]) != uint32(index+1) || + binary.BigEndian.Uint32(packet[29:33]) != 50000 || binary.BigEndian.Uint32(packet[33:37]) != uint32(2-index) { + t.Fatalf("resource identity/envelope: %x", packet) + } + want := [2][8]uint32{{3, 29, 3, 29, 7, 35, 37, 15}, {3, 29, 3, 29, 10, 35, 37, 20}} + for field, value := range want[index] { + if got := binary.BigEndian.Uint32(packet[37+field*4:]); got != value { + t.Fatalf("recipient %d resource %d=%d, want %d", index+1, field, got, value) + } + } + if binary.BigEndian.Uint32(conn.packets[len(conn.packets)-1][16:20]) != 0x28784248 { + t.Fatal("resources must follow the native roster") + } + } + if len(connections[2].packets) != 0 { + t.Fatal("resource snapshot leaked to an unrelated player") + } +} + +func TestTeamResourcesCombatUpdatesPreserveQueuedHP(t *testing.T) { + for _, incoming := range []bool{false, true} { + t.Run(map[bool]string{false: "attacker", true: "victim"}[incoming], func(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + start := time.Unix(100, 0) + for _, client := range world.clients { + client.regenerationAt = start + } + for _, conn := range connections { + conn.packets = nil + } + world.characters[1].health, world.characters[1].nano = 11, 6 + world.characters[1].stats.Body.BodyDevelopment = 100 + world.characters[1].stats.Body.NanoPool = 100 + if incoming { + world.characters[3].fighting = 1 + world.fighting[3] = world.characters[3] + } else { + world.characters[1].fighting = 3 + world.fighting[1] = world.characters[1] + } + + world.advanceRegeneration(start.Add(2 * time.Second)) + + want := map[uint32]uint32{343: 3, 342: 59, 364: 3, 363: 59, 214: 6, 221: 320, 1: 322} + if incoming { + want[342], want[363] = 29, 29 + } + found := make(map[uint32]uint32) + for _, packet := range connections[1].packets { + if binary.BigEndian.Uint32(packet[24:28]) != 1 { + continue + } + if binary.BigEndian.Uint32(packet[16:20]) != 0x2b333d6e { + t.Fatalf("absolute snapshot interrupted queued damage: %x", packet) + } + stat, value := binary.BigEndian.Uint32(packet[29:33]), binary.BigEndian.Uint32(packet[33:37]) + if value != want[stat] || stat == 27 { + t.Fatalf("combat resource %d=%d, expected %v", stat, value, want) + } + found[stat]++ + } + if len(found) != 7 { + t.Fatalf("missing combat resources: %v", found) + } + for _, count := range found { + if count != 1 { + t.Fatal("duplicated combat resource") + } + } + for _, packet := range connections[2].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[24:28]) == 1 { + t.Fatal("private resource fields reached an unrelated observer") + } + } + }) + } +} + +func TestTeamResourcesReadyInitializesAnAlreadyFightingPeer(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + world.characters[1].health = 11 + world.characters[1].fighting = 3 + world.fighting[1] = world.characters[1] + world.clients[2].loading = true + connections[1].packets = nil + + err := world.handleCharacterReady(world.clients[2]) + + packets := teamResourceUpdates(connections[1].packets) + if err != nil || len(packets) != 1 || binary.BigEndian.Uint32(packets[0][65:69]) != 11 || world.clients[2].loading { + t.Fatalf("ready missed the peer's initial HP before combat delivery: %v %x", err, packets) + } +} + +func TestTeamResourcesReadyRefreshesTheReturningMemberForItsPeersOnce(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + world.clients[1].loading = true + world.characters[1].nano = 7 + for _, conn := range connections { + conn.packets = nil + } + + first := world.handleCharacterReady(world.clients[1]) + second := world.handleCharacterReady(world.clients[1]) + + packets := teamResourceUpdates(connections[1].packets) + if first != nil || second != nil || len(packets) != 1 || binary.BigEndian.Uint32(packets[0][33:37]) != 1 || + binary.BigEndian.Uint32(packets[0][53:57]) != 7 { + t.Fatalf("returning member was not initialized exactly once: %v %v %x", first, second, packets) + } + if len(teamResourceUpdates(connections[2].packets)) != 0 { + t.Fatal("returning member's resources leaked outside its team") + } +} + +func TestTeamResourcesUseEquippedMaximumsInAndOutOfCombat(t *testing.T) { + for _, scenario := range []string{"quiet", "combat before snapshot", "combat after snapshot"} { + t.Run(scenario, func(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + player := world.characters[1] + player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy = 98, 848 + if granted, err := world.grantItem_locked(player, 200461); err != nil || !granted { + t.Fatal("resource backpack grant failed", err) + } + if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 19)[20:]); err != nil { + t.Fatal(err) + } + if world.clients[1].equipment == nil { + t.Fatal("resource backpack wear was rejected") + } + world.advanceEquipment(world.clients[1].equipment.readyAt) + start := time.Unix(100, 0) + for _, client := range world.clients { + client.regenerationAt = start + } + if scenario == "combat after snapshot" { + world.advanceRegeneration(start.Add(2 * time.Second)) + start = start.Add(2 * time.Second) + } + if scenario != "quiet" { + player.fighting = 3 + world.fighting[1] = player + } + connections[1].packets = nil + + world.advanceRegeneration(start.Add(2 * time.Second)) + restored := newTestInventoryServer(t).characters[1] + + if restored.maximumHealth() != 127 || restored.maximumNano() != 125 { + t.Fatal("equipped maxima were not durable") + } + if scenario != "quiet" { + found := make(map[uint32]uint32) + for _, packet := range connections[1].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[24:28]) == 1 { + found[binary.BigEndian.Uint32(packet[29:33])] = binary.BigEndian.Uint32(packet[33:37]) + } + } + wantHealth, wantNano := uint32(127), uint32(125) + if scenario == "combat before snapshot" { + wantHealth, wantNano = 37, 35 + } + if found[1] != wantHealth || found[221] != wantNano { + t.Fatalf("combat correction used the wrong native modifier basis: %v", found) + } + } else { + packets := teamResourceUpdates(connections[1].packets) + if len(packets) != 1 || binary.BigEndian.Uint32(packets[0][57:61]) != 125 || binary.BigEndian.Uint32(packets[0][61:65]) != 127 { + t.Fatalf("quiet equipped maxima: %x", packets) + } + } + }) + } +} + +func TestTeamResourcesPublishDeathWithoutRegeneratingTheMember(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + start := time.Unix(100, 0) + for _, client := range world.clients { + client.regenerationAt = start + } + for _, conn := range connections { + conn.packets = nil + } + world.characters[1].health, world.characters[1].nano = 0, 0 + + world.advanceRegeneration(start.Add(2 * time.Second)) + + packets := teamResourceUpdates(connections[1].packets) + if len(packets) != 1 || binary.BigEndian.Uint32(packets[0][65:69]) != 0 || binary.BigEndian.Uint32(packets[0][53:57]) != 0 || + world.characters[1].health != 0 || world.characters[1].nano != 0 { + t.Fatalf("dead team member changed resources: %x", packets) + } +} + +func TestTeamResourceMaximumsKeepTheirNativeBasisAfterLeaving(t *testing.T) { + world, connections := newResourceBackpackTeam(t) + player := world.characters[1] + if err := world.handleTeamAction(world.clients[1], teamRequest(1, 24, 0, 0)); err != nil { + t.Fatal(err) + } + for _, conn := range connections { + conn.packets = nil + } + stats := player.baseStats() + stats.Body.BodyDevelopment = 6 + + err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:]) + + if err != nil || player.stats.Body.BodyDevelopment != 6 || player.maximumHealth() != 142 { + t.Fatalf("training was rejected or changed the equipped total: %v %d", err, player.maximumHealth()) + } + for index, want := range []uint32{52, 142, 52} { + var found []uint32 + for _, packet := range connections[index].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[24:28]) == 1 && binary.BigEndian.Uint32(packet[29:33]) == 1 { + found = append(found, binary.BigEndian.Uint32(packet[33:37])) + } + } + if len(found) != 1 || found[0] != want { + t.Fatalf("observer %d raw maximum=%v, want %d for its native modifier basis", index+1, found, want) + } + } +} + +func TestTeamResourceMaximumsTrainingUpdatesBothCurrentMembers(t *testing.T) { + world, connections := newResourceBackpackTeam(t) + for _, conn := range connections { + conn.packets = nil + } + stats := world.characters[1].baseStats() + stats.Body.BodyDevelopment, stats.Body.NanoPool = 6, 6 + + err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:]) + + if err != nil || world.characters[1].stats.Body.NanoPool != 6 { + t.Fatal("training failed", err) + } + for index, want := range [][2]uint32{{52, 46}, {142, 136}, {52, 0}} { + found := make(map[uint32]uint32) + for _, packet := range connections[index].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[24:28]) == 1 { + found[binary.BigEndian.Uint32(packet[29:33])] = binary.BigEndian.Uint32(packet[33:37]) + } + } + if found[1] != want[0] || found[221] != want[1] { + t.Fatalf("observer %d maxima=%v, want %v", index+1, found, want) + } + } +} + +func TestTeamResourceMaximumsFollowEquipmentAfterAnAbsorbedSnapshot(t *testing.T) { + world, connections := newResourceBackpackTeam(t) + player, client := world.characters[1], world.clients[1] + if granted, err := world.grantItem_locked(player, 152039); err != nil || !granted { + t.Fatal("Pioneer grant failed", err) + } + for _, conn := range connections { + conn.packets = nil + } + + remove := world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) + world.advanceEquipment(client.equipment.readyAt) + wear := world.handleInventory(client, inventoryMovePacket(1, 64, 19)[20:]) + world.advanceEquipment(client.equipment.readyAt) + restored := newTestInventoryServer(t).characters[1] + + if remove != nil || wear != nil || player.maximumHealth() != 52 || restored.maximumHealth() != 52 || + len(restored.inventory.Items) != 2 || restored.inventory.Items[0].ID != 1 || restored.inventory.Items[0].Slot != 65 || + restored.inventory.Items[1].ID != 2 || restored.inventory.Items[1].Slot != 19 { + t.Fatalf("equipment or durable identity changed: %v %v health=%d/%d items=%+v", remove, wear, player.maximumHealth(), restored.maximumHealth(), restored.inventory.Items) + } + for index, want := range []uint32{52, 142, 52} { + var found []uint32 + for _, packet := range connections[index].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[24:28]) == 1 && binary.BigEndian.Uint32(packet[29:33]) == 1 { + found = append(found, binary.BigEndian.Uint32(packet[33:37])) + } + } + if len(found) != 1 || found[0] != want { + t.Fatalf("observer %d equipment raw maximum=%v, want %d", index+1, found, want) + } + } +} + +func TestTeamResourceMaximumBasisResetsWithTheActorOnReconnect(t *testing.T) { + world, connections := newResourceBackpackTeam(t) + if err := world.handleTeamAction(world.clients[1], teamRequest(1, 24, 0, 0)); err != nil { + t.Fatal(err) + } + world.clients[1].conn = &combatInterestConn{} + connections[1].packets = nil + stats := world.characters[1].baseStats() + stats.Body.BodyDevelopment = 6 + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + binary.BigEndian.PutUint16(cookie, 0xdfdf) + input := append(cookie, targetPacket(n3Packet(0x570c2039, 50000, 1, nil))...) + input = append(input, targetPacket(skillTrainingRequest(stats))...) + addressConn, peer := net.Pipe() + t.Cleanup(func() { + addressConn.Close() + peer.Close() + }) + replacement := &combatInterestConn{combatTestConn: combatTestConn{Conn: addressConn}, input: bytes.NewReader(input)} + + err := world.serveWorldClient(&worldClient{conn: replacement, loading: true}) + + var found []uint32 + for _, packet := range connections[1].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 1 { + found = append(found, binary.BigEndian.Uint32(packet[33:37])) + } + } + if err != nil || len(found) != 1 || found[0] != 52 { + t.Fatalf("new actor retained the previous absorbed bonus: %v %v", err, found) + } +} + +func TestTeamResourcesRefreshOnTheRegenerationCadence(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + start := time.Unix(100, 0) + for _, client := range world.clients { + client.regenerationAt = start + } + for _, conn := range connections { + conn.packets = nil + } + world.characters[1].health, world.characters[1].nano = 11, 6 + + world.advanceRegeneration(start.Add(2*time.Second - time.Nanosecond)) + before := len(teamResourceUpdates(connections[1].packets)) + world.advanceRegeneration(start.Add(2 * time.Second)) + world.advanceRegeneration(start.Add(2 * time.Second)) + + packets := teamResourceUpdates(connections[1].packets) + if before != 0 || len(packets) != 1 || binary.BigEndian.Uint32(packets[0][53:57]) != 6 || binary.BigEndian.Uint32(packets[0][65:69]) != 11 { + t.Fatalf("team resource cadence/current values: %x", packets) + } + if len(teamResourceUpdates(connections[0].packets)) != 1 || len(teamResourceUpdates(connections[2].packets)) != 0 { + t.Fatal("resources reached the wrong recipients") + } +} + +func TestTeamResourcesSkipUnavailableOrUnrelatedRecipients(t *testing.T) { + for _, scenario := range []string{"different playfield", "loading recipient", "unready recipient", "offline recipient", "left team", "loading member", "unready member", "offline member"} { + t.Run(scenario, func(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + start := time.Unix(100, 0) + for _, client := range world.clients { + client.regenerationAt = start + } + switch scenario { + case "different playfield": + world.characters[2].playfield = 705 + case "loading recipient": + world.clients[2].loading = true + case "unready recipient": + world.clients[2].ready = false + case "offline recipient": + delete(world.clients, 2) + case "left team": + if err := world.handleTeamAction(world.clients[1], teamRequest(1, 24, 0, 0)); err != nil { + t.Fatal(err) + } + case "loading member": + world.clients[1].loading = true + case "unready member": + world.clients[1].ready = false + case "offline member": + delete(world.clients, 1) + } + for _, conn := range connections { + conn.packets = nil + } + + world.advanceRegeneration(start.Add(2 * time.Second)) + + for _, conn := range connections { + if len(teamResourceUpdates(conn.packets)) != 0 { + t.Fatalf("%s published a team snapshot", scenario) + } + } + }) + } +} diff --git a/server/teams.go b/server/teams.go @@ -129,7 +129,14 @@ func (server *server) teamPackets_locked(owner uint32) [][]byte { body = append(body, name...) packets = append(packets, n3Packet(0x46312d2e, 50000, owner, body)) } - return append(packets, characterActionPacket(owner, [5]uint32{35, 50000, team.leader, 57001, team.id}), server.teamSidePacket_locked(owner)) + packets = append(packets, characterActionPacket(owner, [5]uint32{35, 50000, team.leader, 57001, team.id}), server.teamSidePacket_locked(owner)) + // Ready replay precedes combat delivery; ordinary admission excludes combat. + for _, member := range members[1:] { + if client := server.clients[member]; client != nil && client.ready && !client.loading && server.characters[member].playfield == server.characters[owner].playfield { + packets = append(packets, server.teamResourcePacket_locked(owner, server.characters[member])) + } + } + return packets } func (server *server) teamSidePacket_locked(owner uint32) []byte { diff --git a/server/teams_test.go b/server/teams_test.go @@ -67,11 +67,11 @@ func TestTeamInvitationRequiresAcceptanceAndPublishesNativeRoster(t *testing.T) binary.BigEndian.Uint32(prompt[29:33]) != 26 || binary.BigEndian.Uint32(prompt[37:41]) != 1 { t.Fatalf("native invitation: %x", prompt) } - if len(connections[0].packets) != 4 || len(connections[1].packets) != 5 || len(connections[2].packets) != 0 { + if len(connections[0].packets) != 5 || len(connections[1].packets) != 6 || len(connections[2].packets) != 0 { t.Fatal("roster reached unrelated player or repeated membership") } for index, connection := range connections[:2] { - roster := connection.packets[len(connection.packets)-4:] + roster := connection.packets[len(connection.packets)-5:] if binary.BigEndian.Uint32(roster[0][16:20]) != 0x46312d2e || binary.BigEndian.Uint32(roster[index][45:49]) != 100 || binary.BigEndian.Uint32(roster[0][33:37]) != uint32(index+1) || binary.BigEndian.Uint32(roster[1][33:37]) != uint32(2-index) || binary.BigEndian.Uint32(roster[2][29:33]) != 35 || binary.BigEndian.Uint32(roster[2][37:41]) != 1 || binary.BigEndian.Uint32(roster[2][41:45]) != 57001 { @@ -299,7 +299,7 @@ func TestTeamReadyReplaysRosterOnceAndProfileEditRetainsMembership(t *testing.T) updated.Name = "Renamed member" err := world.updateUser(updated) - if first != nil || second != nil || err != nil || world.characters[1].team != team || world.characters[2].team != team || len(connections[0].packets) != 6 { + if first != nil || second != nil || err != nil || world.characters[1].team != team || world.characters[2].team != team || len(connections[0].packets) != 7 { t.Fatalf("ready replay or profile change lost team: %v %v %v", first, second, err) } } diff --git a/server/world_actions.go b/server/world_actions.go @@ -38,9 +38,11 @@ func (server *server) handleCharacterReady(client *worldClient) error { // Repeated ready messages acknowledge the actor without applying effects twice. var equipment [][]byte var team [][]byte + resources := make(map[*worldClient][][]byte) if client.loading { equipment = equippedItemPackets(server.characters[client.id]) team = server.teamPackets_locked(client.id) + server.queueTeamResources_locked(resources, server.characters[client.id]) } client.loading = false playfield := server.characters[client.id].playfield @@ -51,6 +53,7 @@ func (server *server) handleCharacterReady(client *worldClient) error { for _, packet := range equipment { server.broadcast(playfield, client.id, packet) } + server.sendCombatUpdates(resources) for _, packet := range team { if err := client.send(packet); err != nil { return err