aorecomp

Anarchy Online classic in the browser

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


commit cc824872af0457c8f5832fd8ab49536c7fb4cdc6
parent 7ef3f093e9e4ea2f18a1479f791a612f9e7a6f70
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 14:48:22 +0000

Restore equipped attack rating after bootstrap

Diffstat:
MTODO.md | 16++++++++++++++++
Mdocs/combat-attack-rating.md | 9+++++----
Adocs/concrete-cushion.md | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_concrete_cushion_test.go | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/concrete_cushion_quality_test.go | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/item_families.yaml | 2++
Mserver/gamedata/item_quality_test.go | 4++--
Mserver/main.go | 4++--
Mserver/world_loading_test.go | 43+++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_concrete_cushion.mjs | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 812 insertions(+), 8 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -418,6 +418,13 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). identity. Two native clients verify QL2/10/11 wear, QL12 refusal, ordinary melee, exact cancelled/accepted sale and page/fresh-server retention. Acquisition remains open; see [Sledgehammer contracts](docs/sledgehammer.md). + The audited Concrete Cushion pair now admits QL10..159, fixing qualified + QL11 refusal through shared quality/modifier consumers. Both anchors, six + strict skill gates, mixed 1h Blunt/Heavy Weapons rating, selected damage/delays, + pickup, exactly-once Strength/Stamina bonuses, sale and cold ownership pass. + Two native clients verify QL11/84/85 wear, QL86 refusal, one hit and exact + page/fresh-server retention. Acquisition and offhand scheduling remain open; + see [Cushion contracts](docs/concrete-cushion.md). The reviewed Original Electronicum pair now admits QL1..98 through shared quality and modifier consumers, fixing qualified QL2 rejection. Focused public-handler checks cover Pistol gates, selected damage/timing/value, @@ -4059,6 +4066,15 @@ and server restarts. Turn every reproduced bug into a focused regression test. regression and a short native death/reclaim/recovery/cold check now verify the correction without changing current resources or duplicating bonuses. See [weapon reclaim](docs/inventory.md#retained-weapon-death-and-reclaim). +- [x] [P0] Restore equipped ability-derived attack rating after bootstrap. + A retained Concrete Cushion's +8 Strength/Stamina gave native 1h Blunt289/ + Heavy Weapons192, but page replay cached rating255 instead of weighted256. + Publish final owner stat22 after weapon/nano replay. A failing public socket + regression uses the original exact-QL10 record; two native clients now retain + rating256 through page/cold replay before opening any skill form. Raw skills, + visible exactly-once bonuses, resource foundations, items and cash remain + correct; observer skill publication is unchanged. See + [attack-rating bootstrap](docs/concrete-cushion.md#attack-rating-bootstrap). - [ ] [P0] Audit corpse loot, credits and expiry. Cover entitled/unrelated players, simultaneous pickup, partial looting, full inventory, stale windows, expiry, repeat requests and persistence of both sides of each transfer. diff --git a/docs/combat-attack-rating.md b/docs/combat-attack-rating.md @@ -18,10 +18,11 @@ formula, including ratings above 1000. The client-side rating calculation is established separately in [client stat research](combat-client-stats.md): `FUN_1008f1f0` weights attack skills and adds stat 276 to a positive rating; `FUN_1007c120` selects the -weapon's rating or Martial Arts when unarmed. The currently supported gear -has no Add All Offense modifiers or mixed attack-skill weights. The server -therefore uses effective 1-Hand Edged with the axe and effective Martial Arts -with fists, without introducing a generic stat-effect interpreter. +weapon's rating or Martial Arts when unarmed. The server shares this weighted +calculation across admitted weapons. The +[Concrete Cushion](concrete-cushion.md) uses 67% 1-Hand Blunt and 33% Heavy +Weapons, including trickle from its Strength/Stamina modifiers. Fists retain +their authored Martial Arts weight. Normal player hits follow this order, after any supported axe [overequipping adjustment](overequipping.md) to its base endpoints: diff --git a/docs/concrete-cushion.md b/docs/concrete-cushion.md @@ -0,0 +1,109 @@ +# Concrete Cushion selected qualities + +The original pair 125456/125457 admits QL10..159 through the shared quality, +wear, modifier, combat and price consumers. A qualified QL11 native wear request +previously left its instance in inventory. Production adds the reviewed +family and restores the owner's final attack-rating cache after bootstrap; the Creviced and Exellent intervals remain exact-QL only. + +## Original records + +Both complete 14.9.1 records independently reparse to the maintained catalog, +including hashes, offsets, text, headers, sections and presentation. Only quality, +maximum damage, critical bonus, attack/recharge, value, Multi Melee and the six +strict skill thresholds vary. Both endpoints have the same unconditional +OnWear53045 effects: +8 Strength and +8 Stamina. The shared modifier consumer +applies those effects without changing the raw trained abilities. + +Attack uses 67% 1h Blunt (102) and 33% Heavy Weapons (110), truncating each +contribution separately; defense uses 100% Evade Close (155). All qualities have +minimum damage1, Melee damage91, two-metre range, Melee Initiative118, +unlimited ammunition, 780cs equip, mesh95784 and icon85162. + +The requirements column lists minimum 1h Blunt/Heavy Weapons/Sneak Attack/ +Fast Attack/Brawling/Dimach. These are one more than each authored strict gate. + +| QL | Maximum/critical | Attack/recharge cs | Requirements | Multi Melee | Value | +| --- | --- | --- | --- | --- | --- | +| 10 | 11/17 | 126/140 | 35/23/22/22/25/12 | 15 | 851 | +| 11 | 11/18 | 126/140 | 38/25/24/24/27/13 | 18 | 854 | +| 84 | 30/81 | 93/136 | 283/189/160/160/190/66 | 269 | 18978 | +| 85 | 30/81 | 92/136 | 287/191/161/161/193/66 | 272 | 19471 | +| 158 | 49/144 | 59/132 | 532/355/297/297/356/119 | 523 | 73359 | +| 159 | 49/145 | 59/132 | 535/357/299/299/358/120 | 526 | 74342 | + +Original payload SHA-256: + +- 125456: `a5af73a55ee84865a4ed44f818b5260caf67af22405e0a600b63a216e4d0d064`. +- 125457: `66fecb56bd5fde404c5f5ebf91cd88e77e84bd3a5d7a2f52720f48510de8b3cb`. + +Raw bytes, the index digest and a complete independent audit are under +`local/concrete-cushion/original/`. The later local Fandom `Abilities` page agrees +with +8 at QL10 and distinguishes the +20 QL160 interval. Its 2007 pillow guide +calls the Cushion mission loot. The [indexed QL10 rolling report](https://forums.somethingawful.com/showthread.php?pagenumber=8&perpage=40&threadid=3023465&userid=0) +is from 2009; the nearby 2002 date is a member's registration date. Neither establishes +14.9.1 mission membership, distribution or backyard availability. Acquisition +remains open and production stock, missions and creature drops are unchanged. + +## Focused verification + +Public inventory handlers cover both stored anchors at six qualities, refusal +at each of the six strict thresholds, the equip deadline, selected properties, +native endpoints and cold ownership. Successful wear retains raw abilities1 +while effective Strength/Stamina become9. Controlled ordinary maximum/critical +hits check selected damage, original delays and the shared one-second speed +floor. Reversing the two attack-skill allocations yields ratings569/332 and +actual ordinary hits26/20, checking both weighted contributions. Controlled +QL11/85 drops retain their exact identity through repeated pickup, refused wear, +wear/remove/rewear, cancelled sale, accepted/repeated sale and cold loading. +Removal and sale leave no ability bonus. Those fixtures isolate contracts and +do not establish earned training or historical drop membership. + +`TestBrowserConcreteCushionQualities` uses two controlled WASM clients. The +level200 checkpoint has abilities200 and raw skills238/142/112/112/144/17 in the +requirements order above. Each raw field is checked against its native training +cap399; effective unequipped skills are287/191/161/161/193/66. Real input wears +and removes QL11/84, wears QL85, and refuses QL86 despite the currently worn +ability bonuses. Each wear must produce effective Strength/Stamina208 and +mixed attack rating256, with raw abilities unchanged. In this snapshot, ability +trickle increases maximum health by6 and nano by3; removal restores the original +maxima. The owner receives its nano maximum and cached attack rating; nearby observers +receive HP and the weapon replay. A single ordinary hit consumes no ammunition. Cancelling and +then accepting the QL11 sale pays42 credits. Page and fresh-server recovery must +retain the same three surviving identities, selected qualities, slots and +exactly-once bonuses, with no observer ownership leak. This is controlled +verification, not earned progression. Offhand scheduling remains a separate +open dual-wield TODO. + +## Attack-rating bootstrap + +The first native run passed wear/removal, bonuses, the hit and the sale, then +failed after page replay: the owner cached rating255 while the server retained +256. A separate equipped-bootstrap probe showed actual native 1h Blunt289 and +Heavy Weapons192 in the skill form. Their separately truncated 67/33 terms are +193+63=256. The unchanged raw skills do not explain rating255; that value matches +the unboosted skills287/191 before weapon OnWear. + +The owner bootstrap now publishes stat22 after both nano and weapon replay, +alongside its existing final resource foundations. It uses the same scalar +message as live equipment changes. No item-name branch, raw-skill mutation, +weapon-clock reset, extra OnWear effect or observer skill publication is added. +A failing public socket regression uses the original exact-QL10 record, +independently of the new family. The native completion check requires the +correct owner cache before opening any skill form, with retained raw abilities, +HP/nano foundations, ownership and visible exactly-once ability bonuses. + +The accepted native run is `local/concrete-cushion/20261103-064215/`: 105.33s +(warm 78.62, cold 26.70), or 112.926s including Go. All fourteen traces have empty +error lists and zero dropped events. Reviewed fresh-server abilities show +Strength208/Stamina208 with all other abilities200. The retained prototype +under `local/concrete-cushion-probe/20261103-063850/` supplies the independent +native skill-form check for the stale-cache diagnosis. It is a negative probe, +not a passing maintained regression. + +The final normal selections pass 21 top-level tests and 326 individual results: +16 roots/309 results across server 29.181s and gamedata 7.677s, plus five related +world-entry roots/17 results in 8.527s. All four new family roots and both bootstrap +roots pass under the race detector: 108 results in 122.905s. Vet, JavaScript syntax, +gofmt and whitespace checks pass. The independent verifier retains the original +hashes, qualified refusal, cached255 baseline, final256 packet ordering and exact +native/server ledgers in `local/concrete-cushion/verification.json`. diff --git a/server/browser_concrete_cushion_test.go b/server/browser_concrete_cushion_test.go @@ -0,0 +1,141 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserConcreteCushionQualities(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused native ConcreteCushion check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/concrete-cushion", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + for _, phase := range []string{"warm", "cold"} { + t.Run(phase, func(t *testing.T) { + world := newServerForTest(t) + var target *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { + target = actor + } + } + if phase == "warm" { + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.appearance = fmt.Sprint("ConcreteCushion", index), 0x515 + player.position = [3]float32{60 - float32(index)*3, 14.75, 53} + player.rotation = [4]float32{0, 1, 0, 0} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("concrete_cushion-", index)))) + player.level = 200 + player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200} + player.stats.Melee.OneHandBlunt, player.stats.MiscWeapons.HeavyWeapons = 238, 142 + player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 112, 112 + player.stats.Body.Brawling, player.stats.Body.Dimach = 144, 17 + for stat, raw := range map[uint32]uint16{102: player.stats.Melee.OneHandBlunt, 110: player.stats.MiscWeapons.HeavyWeapons, 146: player.stats.Melee.SneakAttack, 147: player.stats.Melee.FastAttack, 142: player.stats.Body.Brawling, 144: player.stats.Body.Dimach} { + if uint32(raw) > player.trainingMaximum(stat) { + t.Fatal("controlled raw skill exceeds its cap", stat, raw, player.trainingMaximum(stat)) + } + } + for stat, expected := range map[uint32]int32{102: 287, 110: 191, 146: 161, 147: 161, 142: 193, 144: 66} { + if actual, _ := player.effectiveStat(stat); actual != expected { + t.Fatal("controlled effective skill differs", stat, actual) + } + } + player.health, player.nano = player.maximumHealth(), player.maximumNano() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + // Controlled contracts and a nearby original Leet isolate the weapon check. + for _, item := range []struct{ template, quality uint32 }{ + {125456, 11}, {125457, 84}, {125457, 85}, {125456, 86}, + } { + if granted, err := world.grantItem_locked(world.characters[1], item.template); err != nil || !granted { + t.Fatal(granted, err) + } + world.characters[1].inventory.Items[len(world.characters[1].inventory.Items)-1].Quality = item.quality + } + if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil { + t.Fatal(err) + } + target.position, target.motion.home = [3]float32{61, 14.75, 51.5}, [3]float32{61, 14.75, 51.5} + world.combatRoll = func(limit uint32) uint32 { + if limit == 100 { + return 99 + } + return 0 + } + } + owner, watcher := world.characters[1], world.characters[2] + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + json.NewEncoder(w).Encode(map[string]any{"inventory": owner.inventory, "observer": watcher.inventory, + "target": target.id, "health": target.health, "fighting": owner.fighting, "ownerHealth": owner.health, + "abilities": [2]int32{owner.effectiveAbility(16), owner.effectiveAbility(18)}, "rating": owner.attackRating(), + "maxHealth": owner.maximumHealth(), "maxNano": owner.maximumNano()}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advanceEquipment(now) + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_concrete_cushion.mjs"), host.URL, filepath.Join(output, phase)) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + cancel() + <-stopped + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + expected := []ownedItem{ + {ID: 2, Type: 51018, Template: 125457, Quality: 84, Slot: 65, Count: 1}, + {ID: 3, Type: 51018, Template: 125457, Quality: 85, Slot: 6, Count: 1}, + {ID: 4, Type: 51018, Template: 125456, Quality: 86, Slot: 67, Count: 1}, + } + if !slices.Equal(owner.inventory.Items, expected) || owner.inventory.Credits != 42 || owner.health == 0 || + len(watcher.inventory.Items) != 0 || + watcher.inventory.Credits != 0 || world.nextItem != 4 || owner.equipmentBonus(16) != 8 || owner.equipmentBonus(18) != 8 { + t.Fatal("native wear, sale or cold recovery lost an instance or cash", owner.inventory) + } + }) + if t.Failed() { + return + } + } +} diff --git a/server/concrete_cushion_quality_test.go b/server/concrete_cushion_quality_test.go @@ -0,0 +1,321 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "slices" + "testing" + "time" +) + +func TestConcreteCushionQualitiesEnforceWearBoundariesAndRecover(t *testing.T) { + for _, template := range []uint32{125456, 125457} { + for _, row := range []struct { + quality, maximum, critical, value, attack, recharge, multi uint32 + blunt, heavy, sneak, fast, brawling, dimach uint16 + }{ + {10, 11, 17, 851, 126, 140, 15, 35, 23, 22, 22, 25, 12}, + {11, 11, 18, 854, 126, 140, 18, 38, 25, 24, 24, 27, 13}, + {84, 30, 81, 18978, 93, 136, 269, 283, 189, 160, 160, 190, 66}, + {85, 30, 81, 19471, 92, 136, 272, 287, 191, 161, 161, 193, 66}, + {158, 49, 144, 73359, 59, 132, 523, 532, 355, 297, 297, 356, 119}, + {159, 49, 145, 74342, 59, 132, 526, 535, 357, 299, 299, 358, 120}, + } { + for _, failed := range []uint32{0, 102, 110, 146, 147, 142, 144} { + t.Run(fmt.Sprintf("%d/QL%d/below%d", template, row.quality, failed), func(t *testing.T) { + world, output := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.appearance = 0x515 + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.MiscWeapons.HeavyWeapons = row.blunt, row.heavy + player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = row.sneak, row.fast + player.stats.Body.Brawling, player.stats.Body.Dimach = row.brawling, row.dimach + switch failed { + case 102: + player.stats.Melee.OneHandBlunt-- + case 110: + player.stats.MiscWeapons.HeavyWeapons-- + case 146: + player.stats.Melee.SneakAttack-- + case 147: + player.stats.Melee.FastAttack-- + case 142: + player.stats.Body.Brawling-- + case 144: + player.stats.Body.Dimach-- + } + player.inventory.Items[0].Template, player.inventory.Items[0].Quality = template, row.quality + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + started := time.Now() + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment != nil { + finish := client.equipment.readyAt + if finish.Before(started.Add(7800*time.Millisecond)) || finish.After(time.Now().Add(7800*time.Millisecond)) { + t.Fatal("ConcreteCushion did not retain its original equip delay") + } + world.advanceEquipment(finish.Add(-time.Nanosecond)) + if player.inventory.Items[0].Slot != 64 { + t.Fatal("weapon moved before its equip deadline") + } + world.advanceEquipment(finish) + } + cold := newTestInventoryServer(t).characters[1] + + expected := ownedItem{ID: 1, Type: 51018, Template: template, Quality: row.quality, Slot: 64, Count: 1} + if failed == 0 { + expected.Slot = 6 + } + if !slices.Equal(player.inventory.Items, []ownedItem{expected}) || !slices.Equal(cold.inventory.Items, []ownedItem{expected}) { + t.Fatal("wear boundary lost the selected instance or placement", player.inventory.Items, cold.inventory.Items) + } + if failed != 0 { + return + } + if cold.effectiveAbility(16) != 9 || cold.effectiveAbility(18) != 9 || + cold.stats.Abilities != (characterAbilitiesStats{1, 1, 1, 1, 1, 1}) { + t.Fatal("selected weapon lost or duplicated its ability bonuses") + } + weapon := cold.attackWeapon() + if weapon == nil || itemStat(weapon, 286) != 1 || itemStat(weapon, 285) != row.maximum || itemStat(weapon, 284) != row.critical || + itemStat(weapon, 294) != row.attack || itemStat(weapon, 210) != row.recharge || itemStat(weapon, 211) != 780 || itemStat(weapon, 287) != 2 || + itemStat(weapon, 440) != 118 || itemStat(weapon, 101) != row.multi || expected.usesAmmo() || expected.shopPrice() != row.value { + t.Fatal("selected quality lost damage, timing, ammo, range, damage type or value", weapon) + } + low, high := uint32(125456), uint32(125457) + if row.quality == 10 { + high = low + } else if row.quality == 159 { + low = high + } + var delivered []byte + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x3b1d2268 { + delivered = packet + } + } + if len(delivered) < 91 || binary.BigEndian.Uint32(delivered[71:75]) != row.quality || + binary.BigEndian.Uint32(delivered[79:83]) != low || binary.BigEndian.Uint32(delivered[87:91]) != high { + t.Fatal("native weapon delivery lost the selected endpoints") + } + }) + } + } + } +} + +func TestConcreteCushionSelectedDamageAndTimingWithoutAmmunition(t *testing.T) { + for _, row := range []struct{ quality, normal, critical, attack, recharge uint32 }{ + {10, 33, 84, 126, 140}, {11, 33, 87, 126, 140}, {84, 90, 333, 100, 136}, {85, 90, 333, 100, 136}, {158, 147, 579, 100, 132}, {159, 147, 582, 100, 132}, + } { + for _, critical := range []bool{false, true} { + t.Run(fmt.Sprintf("QL%d/critical%v", row.quality, critical), func(t *testing.T) { + world, output := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.appearance = 0x515 + target.position = [3]float32{1, 0, 0} + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.MiscWeapons.HeavyWeapons = 799, 799 + player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 300, 300 + player.stats.Body.Brawling, player.stats.Body.Dimach = 400, 120 + player.stats.Speed.MeleeInitiative, player.aggDef = 0, 75 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality, player.inventory.Items[0].Ammo = 125456, row.quality, 0 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.combatRoll = func(limit uint32) uint32 { + if limit == 10000 || limit == 100 && critical { + return 0 + } + return limit - 1 + } + + if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + hit := player.nextAttack + world.advanceCombat(hit) + cold := newTestInventoryServer(t) + + damage := row.normal + if critical { + damage = row.critical + } + if target.health != 1000-damage || player.attackRating() != 800 || player.rechargeUntil.Sub(hit) != time.Duration(row.recharge)*10*time.Millisecond || player.nextAttack.Sub(hit) != time.Duration(row.recharge+row.attack)*10*time.Millisecond || + player.inventory.Items[0].Ammo != 0 || cold.characters[1].inventory.Items[0].Ammo != 0 || player.inventory.Items[1].Count != 100 { + t.Fatal("selected ConcreteCushion damage, cadence or ammunition differs", target.health, player.inventory) + } + found := false + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 && binary.BigEndian.Uint32(packet[24:28]) == player.id { + found = binary.BigEndian.Uint32(packet[33:37]) == 0xffffffff + } + } + if !found { + t.Fatal("melee result lost its unlimited-ammunition sentinel") + } + }) + } + } +} + +func TestConcreteCushionGeneratedPickupEquipRemoveAndSale(t *testing.T) { + for _, scenario := range []struct { + template, quality uint32 + blunt, heavy, sneak, fast, brawling, dimach uint16 + credits uint32 + }{ + {125456, 11, 38, 25, 24, 24, 27, 13, 43}, {125457, 11, 38, 25, 24, 24, 27, 13, 43}, + {125456, 85, 287, 191, 161, 161, 193, 66, 974}, {125457, 85, 287, 191, 161, 161, 193, 66, 974}, + } { + t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + // Controlled membership tests delivery, not historical Leet equipment drops. + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: scenario.template, Quality: [2]uint32{scenario.quality, scenario.quality}, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + identity := world.nextItem + 1 + + attackForExperience(t, world, "unarmed") + if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil { + t.Fatal(err) + } + } + world = newTestInventoryServer(t) + player := world.characters[1] + player.appearance = 0x515 + client := &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true} + world.clients[1] = client + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.MiscWeapons.HeavyWeapons = scenario.blunt-1, scenario.heavy + player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = scenario.sneak, scenario.fast + player.stats.Body.Brawling, player.stats.Body.Dimach = scenario.brawling, scenario.dimach + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment != nil || + len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != identity || player.inventory.Items[0].Slot != 64 { + t.Fatal("rejected wear lost the picked-up instance", err) + } + player.stats.Melee.OneHandBlunt++ + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, move := range [][2]uint32{{64, 6}, {6, 64}, {64, 6}, {6, 64}} { + request := inventoryMovePacket(1, move[0], move[1]) + if move[0] < 64 { + request = itemMovePacket(1, move[0], move[1]) + } + if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil { + t.Fatal("generated selected-quality weapon did not move", err) + } + world.advanceEquipment(client.equipment.readyAt) + cold := newTestInventoryServer(t) + expected := []ownedItem{{ID: identity, Type: 51018, Template: scenario.template, Quality: scenario.quality, Slot: move[1], Count: 1}} + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + len(cold.characters[1000000].corpse.items) != 0 || cold.characters[1].inventory.Credits != 1 || cold.nextItem != identity { + t.Fatal("pickup, repeated wear or cold recovery lost or duplicated the weapon") + } + } + + // Sell that same instance after cancellation and a cold reconnect. + player.appearance = 0x515 + player.position = [3]float32{60, 14.75, 53} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleShopUse(client, shopUseRequest(1)); err != nil { + t.Fatal(err) + } + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + if len(cold.characters[1].inventory.Items) != 1 || cold.characters[1].inventory.Credits != 1 { + t.Fatal("cancelled sale lost the selected-quality weapon") + } + world, player = cold, cold.characters[1] + client = &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true} + world.clients[1] = client + if err := world.handleShopUse(client, shopUseRequest(1)); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + } + cold = newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + if len(current.characters[1].inventory.Items) != 0 || current.characters[1].inventory.Credits != scenario.credits || + current.characters[1].experience != 100 || current.nextItem != identity || current.characters[1].equipmentBonus(16) != 0 || current.characters[1].equipmentBonus(18) != 0 { + t.Fatal("selected-quality sale lost or repeated value, rewards or an instance", current.characters[1].inventory) + } + if _, exists := current.items[identity]; exists { + t.Fatal("sold weapon returned in the shared cache") + } + } + }) + } +} + +func TestConcreteCushionWeightsBothAttackSkills(t *testing.T) { + for _, row := range []struct { + blunt, heavy uint16 + rating int32 + damage uint32 + }{{799, 100, 569, 26}, {100, 799, 332, 20}} { + t.Run(fmt.Sprint(row.blunt), func(t *testing.T) { + world, _ := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.MiscWeapons.HeavyWeapons = row.blunt, row.heavy + player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 100, 100 + player.stats.Body.Brawling, player.stats.Body.Dimach = 100, 100 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality, player.inventory.Items[0].Ammo = 125456, 11, 0 + target.position = [3]float32{1, 0, 0} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.combatRoll = func(limit uint32) uint32 { + if limit == 10000 { + return 0 + } + return limit - 1 + } + + if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack) + + if player.attackRating() != row.rating || target.health != 1000-row.damage { + t.Fatal("mixed skill weights did not reach ordinary damage", player.attackRating(), target.health) + } + }) + } +} diff --git a/server/gamedata/item_families.yaml b/server/gamedata/item_families.yaml @@ -30,6 +30,8 @@ - [122905, 122906] # Cracked Sledgehammer: original descriptor audit; docs/sledgehammer.md. - [129026, 129027] +# Concrete Cushion: original descriptor audit; docs/concrete-cushion.md. +- [125456, 125457] # Katana: original descriptor audits; docs/katana.md. - [121969, 121970] - [121971, 121972] diff --git a/server/gamedata/item_quality_test.go b/server/gamedata/item_quality_test.go @@ -18,7 +18,7 @@ func TestReviewedItemFamilyQualityRanges(t *testing.T) { {121969, 121970, 1, 20}, {121971, 121972, 21, 40}, {121973, 121974, 41, 60}, {209283, 209284, 1, 24}, {122905, 122906, 1, 20}, {129026, 129027, 1, 20}, - {160288, 160289, 1, 98}, + {160288, 160289, 1, 98}, {125456, 125457, 10, 159}, {124256, 124257, 1, 4}, {124258, 124259, 5, 69}, {124260, 124261, 70, 179}, {70558, 85640, 1, 200}, {70559, 85689, 1, 200}, {70560, 85688, 1, 200}, {70561, 85744, 1, 200}, {70562, 85597, 1, 200}, {70563, 85558, 1, 200}, {70564, 85515, 1, 200}, {70565, 85514, 1, 200}, @@ -59,7 +59,7 @@ func TestUnreviewedItemQualityRemainsExact(t *testing.T) { }{{209285, 25, true}, {209285, 26, false}, {85557, 0, false}, {161966, 200, true}, {161966, 199, false}, {160417, 1, true}, {160417, 2, false}, {124262, 180, true}, {124262, 179, false}, {124262, 181, false}, - {129028, 21, true}, {129028, 22, false}, {160290, 99, true}, {160290, 100, false}, {4294967295, 1, false}} { + {125458, 160, true}, {125458, 161, false}, {129028, 21, true}, {129028, 22, false}, {160290, 99, true}, {160290, 100, false}, {4294967295, 1, false}} { t.Run(fmt.Sprintf("%d/%d", entry.template, entry.quality), func(t *testing.T) { got := gamedata.ItemQualitySupported(entry.template, entry.quality) diff --git a/server/main.go b/server/main.go @@ -413,8 +413,8 @@ func (server *server) serveWorldClient(client *worldClient) error { } updates = append(updates, activeNanoPackets(character, time.Now())...) updates = append(updates, equippedWeaponPackets(character)...) - // FullCharacter rebuilds maxima before the later nano/weapon OnWear replay. - for _, stat := range [][2]uint32{{1, character.maximumHealth() - uint32(character.equipmentBonus(1)+character.nanoBonus(1))}, {221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}} { + // Publish derived foundations and attack rating after nano/weapon OnWear replay. + for _, stat := range [][2]uint32{{1, character.maximumHealth() - uint32(character.equipmentBonus(1)+character.nanoBonus(1))}, {221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}, {22, uint32(character.attackRating())}} { body := binary.BigEndian.AppendUint32(nil, stat[0]) body = binary.BigEndian.AppendUint32(body, stat[1]) updates = append(updates, n3Packet(0x2b333d6e, 50000, character.id, body)) diff --git a/server/world_loading_test.go b/server/world_loading_test.go @@ -145,3 +145,46 @@ func TestWorldLoadingObserverReceivesResourceMaximumChanges(t *testing.T) { } } } + +func TestWorldLoadingPublishesAttackRatingAfterWeaponReplay(t *testing.T) { + world := newTestServer(t) + player := world.newCharacter() + player.level, player.appearance = 200, 0x515 + player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200} + player.stats.Melee.OneHandBlunt, player.stats.MiscWeapons.HeavyWeapons = 238, 142 + player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 112, 112 + player.stats.Body.Brawling, player.stats.Body.Dimach = 144, 17 + player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 125456, Quality: 10, Slot: 6, Count: 1}} + client, connection := net.Pipe() + defer client.Close() + client.SetDeadline(time.Now().Add(5 * time.Second)) + go func() { defer connection.Close(); world.serveWorldConnection(connection) }() + + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + binary.BigEndian.PutUint16(cookie, 0xdfdf) + if _, err := client.Write(cookie); err != nil { + t.Fatal(err) + } + weaponSeen := false + var rating uint32 + for { + packet, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + key := binary.BigEndian.Uint32(packet[16:20]) + if key == 0x3b1d2268 { + weaponSeen = true + } + if weaponSeen && key == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 22 { + rating = binary.BigEndian.Uint32(packet[33:37]) + } + if key == 0x5f52412e { + break + } + } + + if !weaponSeen || rating != 256 || player.attackRating() != 256 { + t.Fatalf("equipped attack rating was not restored after weapon replay: %d", rating) + } +} diff --git a/tools/client/test_concrete_cushion.mjs b/tools/client/test_concrete_cushion.mjs @@ -0,0 +1,171 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', headless: false, + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {}; +async function bagClick(game, id) { + await game.wait('native equipment action finishes', state => + !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + const cell = game.local().inventory.find(item => item.id === id).slot - 48; + assert(cell >= 0 && cell < 9); + await game.click(681 + cell % 3 * 54, 45 + Math.floor(cell / 3) * 54, 'right'); +} +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'concrete_cushion-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + evidence.initial = await state(); + if (evidence.initial.inventory.Items.length === 4) { + assert.equal(owner.local().stats[4], 1); + assert.equal(owner.local().stats[102], 238); + assert.equal(owner.local().stats[110], 142); + assert.equal(owner.local().stats[146], 112); + assert.equal(owner.local().stats[147], 112); + assert.equal(owner.local().stats[142], 144); + assert.equal(owner.local().stats[144], 17); + await owner.key('KeyI'); + await owner.page.keyboard.press('Control+1'); + for (const id of [1, 2, 3]) { + const sequence = observer.sequence; + await bagClick(owner, id); + await owner.wait('selected Concrete Cushion worn', snapshot => owner.local(snapshot).inventory.some(item => item.id === id && item.slot === 6)); + await observer.wait('observer receives selected Concrete Cushion', () => observer.events.some(event => + event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '3b1d2268' && + event.actor[0] === 51018 && event.actor[1] === id)); + const event = observer.events.find(event => event.sequence > sequence && event.direction === 'framereceived' && + event.opcode === '3b1d2268' && event.actor[0] === 51018 && event.actor[1] === id); + const packet = Buffer.from(event.hex, 'hex'), stats = new Map(); + for (let offset = 59; offset < packet.readUInt16BE(6) - 4; offset += 8) + stats.set(packet.readUInt32BE(offset), packet.readUInt32BE(offset + 4)); + const [quality, definition, minimum, maximum, critical, value, attack] = { + 1: [11, 125456, 1, 11, 18, 854, 126], 2: [84, 125456, 1, 30, 81, 18978, 93], + 3: [85, 125457, 1, 30, 81, 19471, 92], + }[id]; + assert.equal(stats.get(23), definition); + const base = { + 125456: {74: 851, 284: 17, 285: 11, 286: 1, 294: 126}, + 125457: {74: 74342, 284: 145, 285: 49, 286: 1, 294: 59}, + }[definition]; + for (const [stat, expected] of Object.entries({74: value, 284: critical, 285: maximum, 286: minimum, 294: attack, + 701: quality, 702: 125456, 703: 125457})) + assert.equal(stats.get(Number(stat)) ?? base[stat], expected, 'selected native Concrete Cushion stat ' + stat); + evidence['worn' + id] = {native: owner.local().inventory, server: await state()}; + const worn = await state(); + assert.deepEqual(worn.abilities, [208, 208]); + assert.equal(worn.rating, 256); + assert.equal(worn.maxHealth, evidence.initial.maxHealth + 6); + assert.equal(worn.maxNano, evidence.initial.maxNano + 3); + await Promise.all(games.map(game => game.wait('ability-derived native foundations', snapshot => + snapshot.actors.some(actor => actor.id === 1 && actor.stats[1] === worn.maxHealth && + (game !== owner || actor.stats[221] === worn.maxNano && actor.stats[22] === 256))))); + await owner.save(output + '/worn-' + id); + if (id !== 3) { + await owner.click(867, 206, 'right'); + await owner.wait('same Concrete Cushion removed', snapshot => owner.local(snapshot).inventory.some(item => item.id === id && item.slot >= 48)); + const removed = await state(); + assert.deepEqual(removed.abilities, [200, 200]); + assert.equal(removed.maxHealth, evidence.initial.maxHealth); + assert.equal(removed.maxNano, evidence.initial.maxNano); + } + } + await owner.key('KeyU'); + await owner.save(output + '/abilities'); + await owner.key('KeyU'); + const rejected = await state(), rejectionSequence = owner.sequence; + await bagClick(owner, 4); + await owner.save(output + '/rejected-86'); + assert(!owner.events.some(event => event.sequence > rejectionSequence && event.direction === 'framesent' && event.opcode === '47537a24')); + assert.deepEqual((await state()).inventory, rejected.inventory); + + // An ordinary Q attack uses the selected QL85 damage and consumes no ammunition. + const deadline = Date.now() + 10000; + while (owner.state.selected[0] !== 50000 || owner.state.selected[1] !== rejected.target) { + assert(Date.now() < deadline, 'Native Tab did not select the controlled Leet'); + const selected = owner.state.selected; + await owner.key('Tab'); + await owner.wait('native target cycle advances', snapshot => snapshot.selected[0] !== selected[0] || snapshot.selected[1] !== selected[1]); + } + const attack = owner.sequence; + await owner.key('KeyQ'); + await owner.wait('ordinary selected-quality hit', () => owner.events.some(event => event.sequence > attack && + event.direction === 'framereceived' && event.opcode === '46002f16' && event.actor[1] === owner.local().id)); + const result = owner.events.find(event => event.sequence > attack && event.direction === 'framereceived' && + event.opcode === '46002f16' && event.actor[1] === owner.local().id); + assert.equal(Buffer.from(result.hex, 'hex').readUInt32BE(33), 0xffffffff); + await owner.key('KeyQ'); + await Promise.all(games.map(game => game.wait('native selected-quality impact', snapshot => + snapshot.actors.some(actor => actor.id === rejected.target && actor.stats[27] === 99)))); + evidence.hit = await state(); + assert.equal(evidence.hit.health, 99); + assert.equal(evidence.hit.fighting, 0); + assert.equal(evidence.hit.inventory.Items[2].Ammo, 0); + await owner.save(output + '/hit'); + + // Cancel, then accept the QL11 instance's sale at the original training machine. + await owner.page.keyboard.press('Control+1'); + await owner.wait('weapon panel closed', snapshot => !snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 360)); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + const offered = await state(); + for (let attempt = 0; attempt < 2; ++attempt) { + await owner.click(...await owner.pick(51035, 3221226422), 'right'); + await owner.wait('training machine open', snapshot => snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 494)); + const cell = owner.local().inventory.find(item => item.id === 1).slot - 48; + await owner.click(681 + cell % 3 * 54, 45 + Math.floor(cell / 3) * 54); + const sequence = owner.sequence; + await owner.click(864, 416); + await owner.wait('sale offered', () => owner.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '36284f6e')); + assert.deepEqual((await state()).inventory, offered.inventory); + await owner.save(output + '/sale-offer-' + attempt); + if (attempt === 0) { + await owner.click(945, 475); + await owner.wait('cancelled Concrete Cushion restored', snapshot => owner.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 48)); + assert.deepEqual((await state()).inventory, offered.inventory); + } + } + await owner.click(874, 475); + await owner.wait('exact selected-quality sale', snapshot => owner.local(snapshot).stats[61] === 42); + evidence.sale = await state(); + await owner.page.reload(); + await owner.ready(); + } + assert.deepEqual(owner.local().inventory.map(item => [item.id, item.slot, item.quality, ...item.templates, item.count]).sort((a, b) => a[0] - b[0]), [ + [2, 49, 84, 125456, 125457, 1], [3, 6, 85, 125456, 125457, 1], [4, 51, 86, 125456, 125457, 1], + ]); + const retained = await state(); + assert.deepEqual(retained.abilities, [208, 208]); + assert.equal(retained.rating, 256); + await Promise.all(games.map(game => game.wait('retained native foundations', snapshot => snapshot.actors.some(actor => + actor.id === 1 && actor.stats[1] === retained.maxHealth && (game !== owner || actor.stats[221] === retained.maxNano && actor.stats[22] === 256))))); + assert.equal(owner.local().stats[61], 42); + assert.deepEqual(observer.local().inventory, []); + await owner.key('KeyU'); + await owner.save(output + '/retained-abilities'); + await owner.key('KeyU'); + evidence.final = {native: owner.local().inventory, server: await state()}; + assert.equal(evidence.final.server.inventory.Items[1].Ammo, 0); + assert(evidence.final.server.ownerHealth > 0); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: native Concrete Cushion qualities, wear/removal, strict refusal, ordinary melee, exact sale and page/cold ownership'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2)); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +}