aorecomp

Anarchy Online classic in the browser

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


commit 988fef53a6ff1d871965a4994d2692aee01d87ed
parent 0f6b2f5e8f5764bbca6568c3d04bb07685de9f5c
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 17:11:30 +0000

Interpolate Metaplast armor qualities with native endpoint rules

Diffstat:
MTODO.md | 9++++++++-
Mdocs/armor.md | 117++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mdocs/inventory.md | 11++++++-----
Mdocs/items.md | 10++++++----
Aserver/armor_quality_persistence_test.go | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/armor_quality_test.go | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 6++++--
Mserver/control_inventory.go | 3++-
Mserver/equipment.go | 47++++++++++++++++++++++++++++++-----------------
Mserver/inventory.go | 5+++--
Mserver/item_pages.go | 11++++++-----
Aserver/item_quality.go | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/loot.go | 3++-
Mserver/metaplast_test.go | 2+-
Mserver/reclaim.go | 3++-
Mserver/world.go | 3++-
16 files changed, 631 insertions(+), 45 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -92,7 +92,7 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). helmet, body, two sleeves, gloves, pants and boots use their authored slots, requirements, effects and delays; each instance survives removal, reconnect and restart, and unsupported equipment is explicitly rejected. -- [ ] Interpolate one armor family's intermediate qualities. Check: native +- [x] Interpolate one armor family's intermediate qualities. Check: native template endpoints, requirements, AC and visuals agree at representative qualities and rounding boundaries, including after equip/remove and restart. - [x] Equip one implant. Check: its slot, treatment/ability requirements and @@ -611,6 +611,13 @@ and server restarts. Turn every reproduced bug into a focused regression test. locked slots, occupied destinations, swaps, repeated actions, interruptions, full inventory and attempts to manipulate another player's items. Rejection must restore a usable native UI without losing or duplicating an item. +- [ ] Audit rapid native equipment input after online ability edits and + reconnects. Check: an existing item becomes immediately usable when its wear + requirements are met. Some scripted right-clicks emitted no request during + profile-edit/reconnect sequences; explicit placement and settled repeated + actions worked. Retesting with explicit tab focus and pointer movement worked. + Isolate product behavior from test timing, including focus, pointer lock, hit + regions and stale item state. Captures: `local/armor-quality-smoke/`. - [ ] Audit item creation, assignment, movement and deletion. Cover exact instance identity, full inventory, stale references, repeat requests, failed saves, simultaneous actions and ownership checks across restart. diff --git a/docs/armor.md b/docs/armor.md @@ -1,9 +1,9 @@ # Metaplast armor in 14.9.1 -All six Metaplast armor families support their exact QL 1 and QL 200 catalog -endpoints. Their native identity type is 51022. Acquisition remains -fixture-controlled, like the first weapon and corpse items. Intermediate -qualities still require interpolation. +All six Metaplast armor families support QL 1 through 200 using their reviewed +catalog endpoint pairs. Their native identity type is 51022. Acquisition remains +fixture-controlled, like the first weapon and corpse items. The item editor can +set an intermediate quality while retaining the instance ID. | Piece | Worn, QL 1 | High-Quality, QL 200 | Native slots | Catalog shard | | --- | --- | --- | --- | --- | @@ -249,3 +249,112 @@ inventory-model entries matched SQLite exactly in identity, type, quality, template endpoints, count and slot. No page, adapter or socket errors occurred. The full Go server suite passed, as did the focused race run covering Metaplast, equipment, armor, inventory and ground/flying vehicles. + + +## Intermediate Metaplast qualities + +The six pairs listed above have matching slot masks, default positions, equip +delays, wear-requirement layout, AC-effect ordering and complete visual effects. +`local/armor-interpolation-research/pairs.json` retains the catalog audit; its +input records were already verified against all twelve original database +payloads in `local/metaplast-smoke/tmp_original.py`. Pairing is explicit for +these six families and is not inferred from neighboring catalog IDs. + +An owned instance still stores a catalog template and its requested quality. +Either authored endpoint identifies its reviewed family. Intermediate values +emit the actual low/high pair in FullCharacter, TemplateAction, container, loot +and reclaim messages. At an authored endpoint the wire can use that definition +alone. This adds no new database fields or development-version compatibility +paths. Both deletion request paths verify the emitted endpoint pair before +removing an instance. + +Native `kkr.dll` constructor `100894c0` selects the nearer endpoint for properties +that are not interpolated; an equal distance selects the second endpoint. For +this 1..200 range, QL 100 selects the Worn name and QL 101 selects High-Quality. +The control panel uses the same rule for names and catalog presentation. +Numeric scalar helper `100eff20` adds 0.5 before truncating the scaled difference; +it does not use ties-to-even rounding. Its ascending branch is: + +```text +low + trunc((quality - lowQL) * (high - low) / (highQL - lowQL) + 0.5) +``` + +The helper returns authored values directly at endpoints and has a separate +branch for descending values. The server follows its operation order. Native +`100effe0` interpolates action requirements. `100f00a0` handles matching effect +lists and calls `100f0a00` for effect requirements. For Modify 53045, table +`10175284` contains argument key 39 followed by terminator 10000: the modifier +amount is interpolated, while its stat identifier remains unchanged. +`100f0aa0` applies that scalar calculation to the selected argument. +The 0.5 constant at `10170464` is the exact single-precision bytes `0000003f`. + +The retained ten-record native bundle is +`local/armor-interpolation-research/native-evidence.json`. Relevant Evidence IDs: + +- Scalar and its complete assembly: `ev_667a05589d42f58fa43936246872fad5c7daed705248804b1ba0fa01270eea85`. +- Nearest endpoint: `ev_49f13d6cc114253e94f96f0f7bd4c0977c8796830bbe1ab381cf2e113b2f3691`. +- Section dispatch: `ev_549265027d34d96cf4e2cf076398902206ce867c8c4eb5a7541f50c456bd2f87`. +- Action requirements: `ev_14cf2309684b4ab2714420a732399bab6087b0097c78d8dc889fcc202ab630cf`. +- Effect requirements: `ev_fcd99e8d3d19d97d96e49190e9f50909cb7b800c400a2d3d9427d08b7d5ca214`. +- Effect arguments: `ev_253e905f2f165c536229708e03ecffe2fc4f07011f372fad8150d6382098800c`. +- Constant and argument-table bytes: `ev_d21e8be18d56033255409bba632b066eaf5f48b20aa646e2c6bc427c0294ff91`, + `ev_c8605fe9856900142bbf8701c4fb02c9942e89d6946d48ad2d191fb8d306e334`. + +Native generic loading accepts a wider quality representation; this server +supports only the authored Metaplast 1..200 interval and rejects extrapolation. +Other armor families and their quality ranges remain separate work. Auno's +historical item pages were inaccessible during this investigation; the original +catalog, native code and runtime checks provide the evidence here. + +`server/armor_quality_test.go` checks QL 2, 50, 100, 101, 150 and 199 for every +piece and both sleeve positions. Hardcoded expected AC and ability thresholds +cover rounding and the name-selection boundary. It checks equip/remove, +initialization, restart, both endpoint anchors, invalid qualities, unsupported +armor and exact requirement rejection. `server/armor_quality_persistence_test.go` +checks container snapshots, forged/correct deletion, real corpse pickup, +reclaim, requirement changes during equip delay and failed transactions. +The focused quality/lifecycle checks passed in 63.148s. The full Go suite passed +(`ao/server` 250.820s), and focused quality/equipment race checks passed in +151.591s. The native session was exported and closed before browser testing. + + +The normal HTTPS preview was exercised by owned visitors 14 and 15. The native +QL 100 helmet reported minimum Strength 233 and Agility 258. Separate attempts +at 232/258 and 233/257 retained the item and zero AC, while 233/258 equipped it. +Its native AC was `[375,328,375,281,56,56,56,56]` for both owner and observer; +removal restored zero. The native Stats window independently showed the first +three computed protections. Read-only probes combine the base stat table with +the additive map at modifier helper `SimpleChar + 0x154`, map field `+8`; +reading only the base table would incorrectly report zero equipment AC. +The helper/map layout is established by the retained modifier analysis in +`local/reports/combat-client-decompiles-21.json`, `100bd600`, `10074730`, and +generated `kkr.dll/lifted-0020.c`, `sub_3603E790`. + +A complete suit used Helmet 100, Pants 50, Gloves 101, Boots 150, Body 199, +Sleeve 2 and Sleeve 101, including independent instances in both arms. Both +clients calculated `[2061,1804,2061,1545,310,310,310,310]`. Replacing only the +helmet with QL 101 produced `[2064,1807,2064,1548,311,311,311,311]`, again in +both views. A normal server restart restored the exact item records and +locations, complete appearance, template pairs and those totals without doubled +modifiers. Every piece was subsequently removed; all eight instances remained +in ordinary inventory and both clients reported eight zero protections. + +`local/armor-quality-smoke/tmp_verify.py` passed 18 native/persistence checks. +It checks every instance's type, QL, low/high pair, quantity and placement, +owner/observer AC, exact ability boundaries, restart snapshots and final +ownership. All 148 preexisting item records and locations were unchanged. +No page exception or unimplemented adapter call was recorded. Both owned +browser runs closed their contexts in `finally`; the single normal HTTPS +preview stayed available on port 8443. + +The first input driver sometimes emitted no request for an automatic action +following online edits or reconnects. Explicit placement worked, as did +constant-stat remove/auto-wear. A retest that established tab focus, moved the +pointer before clicking and allowed the world to settle completed the remaining +automatic removals. Those missed gestures are not counted as successful tests; +the root TODO retains a focused input audit to separate product input routing, +item state and test timing. The verified final snapshots are +`all-ordinary-final-native.json` and `observer-all-ordinary-final-native.json`; +earlier partial-removal snapshots deliberately retain their actual nonzero AC. +The verifier, `verification.json`, SQLite snapshots, screenshots and the empty +`errors.json` are retained alongside the driver. diff --git a/docs/inventory.md b/docs/inventory.md @@ -45,14 +45,15 @@ succeeds. The shared store preserves the allocation high-water mark even after t last item has been deleted. Profile edits and zoning preserve inventory independently of profile fields. -Items use exact catalog qualities with identical template endpoints. Essence +Most supported items use exact catalog qualities with identical template +endpoints. Metaplast armor supports its reviewed QL 1..200 endpoint pairs. Essence of Pure Jealousy now supports persistent [native stacks](inventory-stacks.md), including merge, split and rejected-split correction. Its historical server merge cap remains unresolved. [All 37 portable containers](backpacks.md) now provide their -native 21-slot inventories and persistent contents. Arbitrary-quality interpolation +native 21-slot inventories and persistent contents. Other item families and starter loadouts remain separate milestones. Native corpse pickup is described in [the corpse and loot protocol](corpse-loot.md). QL 1 Kinetic Axe equipment -is described below. All six Metaplast families at exact QL 1/200 use the +is described below. All six Metaplast families at QL 1 through 200 use the [native armor path](armor.md). Other equipment remains unsupported. ## Native messages @@ -66,8 +67,8 @@ encoded length is `(items + 1) * 1009`. Each entry has these network-order field | Entry flags | 2 | 1 for template items; 2 for separate live item identities | | Count | 2 | 1 | | Instance type and ID | 8 | Template type and persistent server ID | -| Low and high template | 8 | Same exact template ID | -| Quality | 4 | Catalog quality | +| Low and high template | 8 | Exact definition or a supported interpolation pair | +| Quality | 4 | Requested instance quality | | Auxiliary value | 4 | 0 | The maintained client source establishes the 32-byte wire entry: diff --git a/docs/items.md b/docs/items.md @@ -106,16 +106,18 @@ silently omitting a definition. ## Definitions versus owned items A definition is not an owned item. The [initial inventory](inventory.md) persists -instance identity, owner, slot and exact-template quality for individual items. -Stacks, containers and interpolated qualities remain separate milestones. +instance identity, owner, slot and quality for individual items. Known stacks +and portable containers are supported; Metaplast armor also uses its reviewed +QL 1..200 endpoint pairs. Other interpolated item families remain open. CellAO's `Item` constructor takes **quality, low template ID and high template ID**, and its item implementation interpolates properties between the templates. Consequently, one row per extracted ID is not sufficient to represent every possible quality level. The catalog preserves the endpoint definitions; it does not guess template -pairings from neighboring IDs or matching names. Recover the pairing and -interpolation rules before generating arbitrary-quality equipment. The server +pairings from neighboring IDs or matching names. The six Metaplast pairs and their native interpolation rules are documented in +[armor](armor.md). Recover each additional pairing and its applicable fields +before generating arbitrary-quality equipment. The server will also need to enforce action requirements and effect behavior rather than relying on the client's displayed description. diff --git a/server/armor_quality_persistence_test.go b/server/armor_quality_persistence_test.go @@ -0,0 +1,176 @@ +package main + +import ( + "bytes" + "encoding/binary" + "reflect" + "slices" + "testing" + "time" +) + +func TestInterpolatedArmorBagSnapshotAndDeletion(t *testing.T) { + for _, source := range []string{"ordinary", "container"} { + t.Run(source, func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + world.grantItem_locked(player, 85557) + world.grantItem_locked(player, 99228) + player.inventory.Items[1].Quality = 101 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + page, slot := uint32(104), uint32(65) + if source == "container" { + world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]) + world.handleInventory(client, backpackMoveRequest(104, 65, 51017, 3, 111)[20:]) + world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]) + conn.packets = nil + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 3)[20:]); err != nil { + t.Fatal(err) + } + var entry []byte + for _, v := range []uint32{2, 85557, 85556, 101, 0} { + entry = binary.BigEndian.AppendUint32(entry, v) + } + if len(conn.packets) != 2 || !bytes.Contains(conn.packets[1], entry) { + t.Fatal("contained snapshot lost interpolation endpoints") + } + page, slot = 107, 1<<16 + } + var body []byte + for _, v := range []uint32{112, page, slot, 85557, 85557} { + body = binary.BigEndian.AppendUint32(body, v) + } + wrong := n3Packet(0x5e477770, 50000, 1, body)[20:] + correct := bytes.Clone(wrong) + binary.BigEndian.PutUint32(correct[32:36], 85556) + before, _ := readTestItemStore(world) + packets := len(conn.packets) + + err := world.handleInventory(client, wrong) + rejected, readErr := readTestItemStore(world) + + if err != nil || readErr != nil || !bytes.Equal(before, rejected) || len(conn.packets) != packets { + t.Fatal("forged endpoint pair deleted or changed armor", err, readErr) + } + + err = world.handleInventory(client, correct) + restarted := newTestInventoryServer(t) + + if err != nil || len(restarted.items) != 2 || restarted.nextItem != 3 || len(restarted.characters[1].inventory.Containers) != 0 { + t.Fatal("correct native deletion lost another instance", err) + } + if _, present := restarted.items[2]; present { + t.Fatal("deleted armor returned after restart") + } + }) + } +} + +func TestInterpolatedArmorLootRetainsQuality(t *testing.T) { + world, conn := newLootWorld(t) + corpse := world.characters[1000000] + corpse.corpse.items = []ownedItem{{ID: 17, Type: 51022, Template: 85557, Quality: 101, Count: 1}} + var entry []byte + for _, v := range []uint32{17, 85557, 85556, 101, 0} { + entry = binary.BigEndian.AppendUint32(entry, v) + } + + err := world.handleLootUse(world.clients[1], lootUseRequest(1)) + shown := false + for _, packet := range conn.packets { + shown = shown || bytes.Contains(packet, entry) + } + if err == nil { + err = world.handleInventory(world.clients[1], lootTakeRequest()) + } + restarted := newTestInventoryServer(t) + + if err != nil || !shown || len(corpse.corpse.items) != 0 || !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{ID: 17, Type: 51022, Template: 85557, Quality: 101, Slot: 64, Count: 1}}) { + t.Fatal("loot presentation or pickup lost interpolated armor", err) + } + if !bytes.Contains(targetPacket(fullCharacterPacket(restarted.characters[1])), entry) { + t.Fatal("looted armor lost its pair on initialization") + } +} + +func TestInterpolatedArmorReclaimRetainsQuality(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + world.grantItem_locked(player, 85557) + player.inventory.Items[1].Quality = 101 + player.level = 10 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + + defeatReclaimPlayer(t, world) + player.health = 1 + player.playfield, player.position = 705, [3]float32{918, 20.7, 578} + for i := range player.inventory.Reclaim { + player.inventory.Reclaim[i].AvailableAt = time.Now().Add(-time.Second) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + conn.packets = nil + err := world.handleReclaim(client, reclaimRequest(109)) + var entry []byte + for _, v := range []uint32{2, 85557, 85556, 101, 0} { + entry = binary.BigEndian.AppendUint32(entry, v) + } + shown := false + for _, packet := range conn.packets { + shown = shown || bytes.Contains(packet, entry) + } + armorSlot := slices.Index(client.reclaimItems, uint32(2)) + if armorSlot < 0 { + t.Fatal("armor missing from reclaim window") + } + if err == nil { + err = world.handleInventory(client, reclaimTakeRequest(uint32(armorSlot))) + } + restarted := newTestInventoryServer(t) + + if err != nil || !shown || !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{ID: 2, Type: 51022, Template: 85557, Quality: 101, Slot: 64, Count: 1}}) { + t.Fatal("reclaim lost the armor pair, quality or identity", err) + } +} + +func TestInterpolatedArmorPendingWearRechecksAndRollsBack(t *testing.T) { + for _, scenario := range []string{"changed requirement", "failed save"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 236, 261 + world.grantItem_locked(player, 85557) + player.inventory.Items[1].Quality = 101 + world.saveInventory_locked(player, player.inventory) + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 18)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("qualified intermediate wear did not start") + } + if scenario == "changed requirement" { + player.stats.Abilities.Strength = 235 + } else { + if _, err := world.db.Exec("CREATE TRIGGER reject_interpolated_wear BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil { + t.Fatal(err) + } + } + before, _ := readTestItemStore(world) + + world.advanceEquipment(client.equipment.readyAt) + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || player.inventory.Items[1].Slot != 65 || player.inventory.equipmentBonus(90) != 0 || len(conn.packets) != 2 { + t.Fatal("interrupted or failed wear moved armor or applied effects", err) + } + }) + } +} diff --git a/server/armor_quality_test.go b/server/armor_quality_test.go @@ -0,0 +1,206 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "testing" +) + +var metaplastQualityCases = []struct { + low, high, slot, quality uint32 + strength, agility uint16 + armor [8]uint32 +}{ + {85512, 85511, 27, 2, 10, 11, [8]uint32{6, 6, 6, 5, 1, 1, 1, 1}}, + {85557, 85556, 18, 2, 10, 11, [8]uint32{7, 6, 7, 6, 2, 2, 2, 2}}, + {85596, 85595, 24, 2, 10, 11, [8]uint32{2, 2, 2, 2, 1, 1, 1, 1}}, + {85638, 85637, 30, 2, 10, 11, [8]uint32{3, 3, 3, 2, 1, 1, 1, 1}}, + {85686, 85685, 21, 2, 10, 11, [8]uint32{10, 9, 10, 9, 2, 2, 2, 2}}, + {85742, 85741, 23, 2, 10, 11, [8]uint32{2, 2, 2, 2, 1, 1, 1, 1}}, + {85742, 85741, 25, 2, 10, 11, [8]uint32{2, 2, 2, 2, 1, 1, 1, 1}}, + {85512, 85511, 27, 50, 120, 132, [8]uint32{156, 137, 156, 117, 24, 24, 24, 24}}, + {85557, 85556, 18, 50, 120, 132, [8]uint32{187, 164, 187, 141, 28, 28, 28, 28}}, + {85596, 85595, 24, 50, 120, 132, [8]uint32{62, 54, 62, 47, 10, 10, 10, 10}}, + {85638, 85637, 30, 50, 120, 132, [8]uint32{93, 82, 93, 70, 15, 15, 15, 15}}, + {85686, 85685, 21, 50, 120, 132, [8]uint32{250, 219, 250, 188, 38, 38, 38, 38}}, + {85742, 85741, 23, 50, 120, 132, [8]uint32{62, 54, 62, 47, 10, 10, 10, 10}}, + {85742, 85741, 25, 50, 120, 132, [8]uint32{62, 54, 62, 47, 10, 10, 10, 10}}, + {85512, 85511, 27, 100, 233, 258, [8]uint32{312, 273, 312, 234, 47, 47, 47, 47}}, + {85557, 85556, 18, 100, 233, 258, [8]uint32{375, 328, 375, 281, 56, 56, 56, 56}}, + {85596, 85595, 24, 100, 233, 258, [8]uint32{125, 109, 125, 94, 19, 19, 19, 19}}, + {85638, 85637, 30, 100, 233, 258, [8]uint32{187, 164, 187, 140, 28, 28, 28, 28}}, + {85686, 85685, 21, 100, 233, 258, [8]uint32{500, 438, 500, 376, 75, 75, 75, 75}}, + {85742, 85741, 23, 100, 233, 258, [8]uint32{125, 109, 125, 94, 19, 19, 19, 19}}, + {85742, 85741, 25, 100, 233, 258, [8]uint32{125, 109, 125, 94, 19, 19, 19, 19}}, + {85512, 85511, 27, 101, 236, 261, [8]uint32{316, 276, 316, 237, 47, 47, 47, 47}}, + {85557, 85556, 18, 101, 236, 261, [8]uint32{378, 331, 378, 284, 57, 57, 57, 57}}, + {85596, 85595, 24, 101, 236, 261, [8]uint32{126, 110, 126, 94, 19, 19, 19, 19}}, + {85638, 85637, 30, 101, 236, 261, [8]uint32{189, 165, 189, 142, 29, 29, 29, 29}}, + {85686, 85685, 21, 101, 236, 261, [8]uint32{505, 442, 505, 379, 76, 76, 76, 76}}, + {85742, 85741, 23, 101, 236, 261, [8]uint32{126, 110, 126, 94, 19, 19, 19, 19}}, + {85742, 85741, 25, 101, 236, 261, [8]uint32{126, 110, 126, 94, 19, 19, 19, 19}}, + {85512, 85511, 27, 150, 347, 385, [8]uint32{469, 410, 469, 351, 70, 70, 70, 70}}, + {85557, 85556, 18, 150, 347, 385, [8]uint32{562, 492, 562, 422, 84, 84, 84, 84}}, + {85596, 85595, 24, 150, 347, 385, [8]uint32{187, 163, 187, 140, 28, 28, 28, 28}}, + {85638, 85637, 30, 150, 347, 385, [8]uint32{281, 246, 281, 211, 42, 42, 42, 42}}, + {85686, 85685, 21, 150, 347, 385, [8]uint32{750, 656, 750, 563, 113, 113, 113, 113}}, + {85742, 85741, 23, 150, 347, 385, [8]uint32{187, 163, 187, 140, 28, 28, 28, 28}}, + {85742, 85741, 25, 150, 347, 385, [8]uint32{187, 163, 187, 140, 28, 28, 28, 28}}, + {85512, 85511, 27, 199, 459, 508, [8]uint32{622, 543, 622, 466, 93, 93, 93, 93}}, + {85557, 85556, 18, 199, 459, 508, [8]uint32{746, 653, 746, 559, 111, 111, 111, 111}}, + {85596, 85595, 24, 199, 459, 508, [8]uint32{249, 217, 249, 186, 37, 37, 37, 37}}, + {85638, 85637, 30, 199, 459, 508, [8]uint32{373, 326, 373, 280, 56, 56, 56, 56}}, + {85686, 85685, 21, 199, 459, 508, [8]uint32{995, 871, 995, 746, 149, 149, 149, 149}}, + {85742, 85741, 23, 199, 459, 508, [8]uint32{249, 217, 249, 186, 37, 37, 37, 37}}, + {85742, 85741, 25, 199, 459, 508, [8]uint32{249, 217, 249, 186, 37, 37, 37, 37}}, +} + +func TestMetaplastIntermediateWearRemoveAndRestart(t *testing.T) { + for _, piece := range metaplastQualityCases { + t.Run(fmt.Sprintf("%d/QL%d/slot%d", piece.low, piece.quality, piece.slot), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Strength, player.stats.Abilities.Agility = piece.strength, piece.agility + if granted, err := world.grantItem_locked(player, piece.low); err != nil || !granted { + t.Fatal(granted, err) + } + player.inventory.Items[1].Quality = piece.quality + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + if err := world.handleInventory(client, inventoryMovePacket(1, 65, piece.slot)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("intermediate quality was rejected") + } + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t) + snapshot := targetPacket(fullCharacterPacket(restarted.characters[1])) + + expected := ownedItem{ID: 2, Type: 51022, Template: piece.low, Quality: piece.quality, Slot: piece.slot, Count: 1} + if !reflect.DeepEqual(restarted.characters[1].inventory.Items[1], expected) { + t.Fatal("quality or identity did not persist") + } + for i, armor := range piece.armor { + if got := restarted.characters[1].inventory.equipmentBonus(90 + uint32(i)); got != armor { + t.Fatalf("AC%d: got %d, want %d", 90+i, got, armor) + } + } + var action, entry []byte + for _, v := range []uint32{piece.low, piece.high, piece.quality, 1, 6, 102, piece.slot, 0, 0} { + action = binary.BigEndian.AppendUint32(action, v) + } + for _, v := range []uint32{2, piece.low, piece.high, piece.quality, 0} { + entry = binary.BigEndian.AppendUint32(entry, v) + } + if len(conn.packets) != 2 || !bytes.Equal(conn.packets[1][29:65], action) || !bytes.Contains(snapshot, entry) { + t.Fatal("native wear or initialization lost the endpoint pair") + } + + if err := world.handleInventory(client, itemMovePacket(1, piece.slot, 111)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("intermediate removal rejected") + } + world.advanceEquipment(client.equipment.readyAt) + removed := newTestInventoryServer(t) + + expected.Slot = 65 + if removed.characters[1].inventory.Items[1] != expected { + t.Fatal("removal changed instance or quality") + } + for stat := uint32(90); stat < 98; stat++ { + if removed.characters[1].inventory.equipmentBonus(stat) != 0 { + t.Fatal("removal retained an interpolated bonus") + } + } + }) + } +} + +func TestMetaplastIntermediateRequirementBoundaries(t *testing.T) { + for _, piece := range metaplastQualityCases { + if piece.low != 85557 { + continue + } + for _, ability := range []string{"strength", "agility"} { + t.Run(fmt.Sprintf("QL%d/%s", piece.quality, ability), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Strength, player.stats.Abilities.Agility = piece.strength, piece.agility + if ability == "strength" { + player.stats.Abilities.Strength-- + } else { + player.stats.Abilities.Agility-- + } + world.grantItem_locked(player, piece.low) + player.inventory.Items[1].Quality = piece.quality + world.saveInventory_locked(player, player.inventory) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + err = world.handleInventory(client, inventoryMovePacket(1, 65, 18)[20:]) + after, readErr := readTestItemStore(world) + + if err != nil || readErr != nil || client.equipment != nil || !bytes.Equal(before, after) || len(conn.packets) != 2 { + t.Fatal("requirement boundary accepted or lost its source", err, readErr) + } + }) + } + } +} + +func TestControlMetaplastIntermediateQualityAndNames(t *testing.T) { + for _, scenario := range []struct { + template, quality uint32 + status int + name string + }{ + {85557, 100, 303, "Worn Metaplast Armor Helmet"}, + {85557, 101, 303, "High-Quality Metaplast Armor Helmet"}, + {85556, 100, 303, "Worn Metaplast Armor Helmet"}, + {85556, 101, 303, "High-Quality Metaplast Armor Helmet"}, + {85557, 0, 400, ""}, {85557, 201, 400, ""}, {85556, 511, 400, ""}, + {85535, 100, 400, ""}, + } { + t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + postControlForm(world, "/control/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) + data := fmt.Sprintf("type: 51022\ntemplate: %d\nquality: %d\ncount: 1\n", scenario.template, scenario.quality) + before, _ := readTestItemStore(world) + + response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + after, err := readTestItemStore(world) + page := httptest.NewRecorder() + world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/1", nil)) + + if response.Code != scenario.status || err != nil { + t.Fatal(response.Code, response.Body.String(), err) + } + if response.Code == http.StatusBadRequest { + if !bytes.Equal(before, after) { + t.Fatal("rejected quality changed the store") + } + return + } + restarted := newTestInventoryServer(t) + if restarted.items[1].Quality != scenario.quality || !strings.Contains(page.Body.String(), "<h2>"+scenario.name+"</h2>") { + t.Fatal("interpolated quality or nearest endpoint name was lost") + } + }) + } +} diff --git a/server/backpacks.go b/server/backpacks.go @@ -36,7 +36,8 @@ func backpackPacket(owner, playfield uint32, item ownedItem) []byte { func backpackInventoryPacket(owner, bag, index uint32, items []ownedItem) []byte { body := binary.BigEndian.AppendUint32(nil, uint32(len(items)+1)*1009) for _, item := range items { - for _, value := range []uint32{item.Slot, 0x00030000 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + low, high := item.templateIDs() + for _, value := range []uint32{item.Slot, 0x00030000 | uint32(item.Count), item.Type, item.ID, low, high, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } } @@ -250,7 +251,8 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by if action == 52 || action == 53 { return server.changeStack_locked(client, index, body) } - if action != 112 || binary.BigEndian.Uint32(body[28:32]) != items[index].Template || binary.BigEndian.Uint32(body[32:36]) != items[index].Template { + low, high := items[index].templateIDs() + if action != 112 || binary.BigEndian.Uint32(body[28:32]) != low || binary.BigEndian.Uint32(body[32:36]) != high { return nil } inventory := player.inventory diff --git a/server/control_inventory.go b/server/control_inventory.go @@ -15,7 +15,8 @@ func (server *server) itemTableRow_locked(w io.Writer, slot string, id *uint32) fmt.Fprint(w, "Empty") } else { name := "Unknown template" - if definition := gamedata.ItemTemplates[server.items[*id].Template]; definition != nil { + record := server.items[*id] + if definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition(); definition != nil { name = definition.Name } fmt.Fprintf(w, "<a href='control/items/%d'>%s (ID %d)</a>", *id, html.EscapeString(name), *id) diff --git a/server/equipment.go b/server/equipment.go @@ -20,15 +20,6 @@ func (item ownedItem) isKineticAxe() bool { return item.Type == 51018 && item.Template == 209283 && item.Quality == 1 } -func (item ownedItem) isMetaplast() bool { - // Only the shipped endpoints are supported; intermediate qualities need interpolation. - switch item.Template { - case 85511, 85512, 85556, 85557, 85595, 85596, 85637, 85638, 85685, 85686, 85741, 85742: - return item.Type == 51022 && item.Quality == *gamedata.ItemTemplates[item.Template].Quality - } - return false -} - func (item ownedItem) fitsEquipmentSlot(slot uint32) bool { if item.isKodaik() || item.isYalmaha() { return slot == 1 @@ -79,11 +70,30 @@ func (character *character) canEquip(item ownedItem) bool { return stats.effectiveSkill(stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) > 5 && stats.effectiveSkill(stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0}) > 5 } - if item.isMetaplast() && item.Quality == 200 { - return character.baseStats().Abilities.Strength > 460 && character.baseStats().Abilities.Agility > 510 + if item.isMetaplast() { + low, high := item.templateIDs() + first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] + // These authored wear lists require Strength and Agility with strict bounds. + for sectionIndex, section := range first.Sections { + if section.Actions == nil { + continue + } + for actionIndex, action := range *section.Actions { + if action.Type != 6 { + continue + } + for index, requirement := range action.Requirements { + value := interpolateItemValue(requirement.Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) + if requirement.Stat == 16 && int32(character.baseStats().Abilities.Strength) <= value || + requirement.Stat == 17 && int32(character.baseStats().Abilities.Agility) <= value { + return false + } + } + } + } + return true } - // All QL 1 Metaplast pieces require Strength and Agility greater than 7. - return character.baseStats().Abilities.Strength > 7 && character.baseStats().Abilities.Agility > 7 + return false } func (inventory playerInventory) equipmentBonus(stat uint32) uint32 { @@ -93,13 +103,15 @@ func (inventory playerInventory) equipmentBonus(stat uint32) uint32 { if !item.fitsEquipmentSlot(item.Slot) { continue } - for _, section := range gamedata.ItemTemplates[item.Template].Sections { + low, high := item.templateIDs() + first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] + for sectionIndex, section := range first.Sections { if section.Type != 2 || section.Subtype != 14 { continue } - for _, function := range *section.Functions { + for index, function := range *section.Functions { if function.ID == 53045 && uint32(*function.Arguments[0].Integer) == stat { - bonus += uint32(*function.Arguments[1].Integer) + bonus += uint32(interpolateItemValue(*function.Arguments[1].Integer, *(*second.Sections[sectionIndex].Functions)[index].Arguments[1].Integer, *first.Quality, *second.Quality, item.Quality)) } } } @@ -344,7 +356,8 @@ func equipmentActionPacket(owner uint32, item ownedItem, action uint32) []byte { page = 103 } var body []byte - for _, value := range []uint32{item.Template, item.Template, item.Quality, 1, action, page, item.Slot, 0, 0} { + low, high := item.templateIDs() + for _, value := range []uint32{low, high, item.Quality, 1, action, page, item.Slot, 0, 0} { body = binary.BigEndian.AppendUint32(body, value) } return n3Packet(0x35505644, 50000, owner, body) diff --git a/server/inventory.go b/server/inventory.go @@ -216,8 +216,9 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } inventory.Items[index].Slot = destination } else { - if binary.BigEndian.Uint32(body[28:32]) != inventory.Items[index].Template || - binary.BigEndian.Uint32(body[32:36]) != inventory.Items[index].Template { + low, high := inventory.Items[index].templateIDs() + if binary.BigEndian.Uint32(body[28:32]) != low || + binary.BigEndian.Uint32(body[32:36]) != high { return nil } inventory.Items = slices.Delete(inventory.Items, index, index+1) diff --git a/server/item_pages.go b/server/item_pages.go @@ -85,7 +85,8 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { ids := slices.Sorted(maps.Keys(records)) ids = slices.DeleteFunc(ids, func(id uint32) bool { name := "Unknown template" - if definition := gamedata.ItemTemplates[records[id].Template]; definition != nil { + record := records[id] + if definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition(); definition != nil { name = definition.Name } owner := "Unassigned" @@ -101,7 +102,7 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "<table><tr><th>ID</th><th>Name</th><th>QL</th><th>Count</th><th>Owner</th><th>Location</th></tr>") for _, id := range ids[start:end] { record := records[id] - definition := gamedata.ItemTemplates[record.Template] + definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition() name := "Unknown template" if definition != nil { name = definition.Name @@ -220,7 +221,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - definition := gamedata.ItemTemplates[record.Template] + definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition() w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Item %d</title></head><body><p><a href='control/items'>All items</a></p><h1>Item %d</h1>", html.EscapeString(server.baseURL), id, id) if definition != nil { @@ -284,8 +285,8 @@ func (server *server) editItem(w http.ResponseWriter, r *http.Request) { err = decodeUsers(strings.NewReader(r.FormValue("data")), &record) } definition := gamedata.ItemTemplates[record.Template] - if err != nil || definition == nil || definition.Quality == nil || record.Type != definition.HeaderWords[0] || record.Quality != *definition.Quality { - http.Error(w, "Invalid item properties; use an exact catalog template, type and quality", http.StatusBadRequest) + if err != nil || definition == nil || definition.Quality == nil || record.Type != definition.HeaderWords[0] || record.Quality != *definition.Quality && !(ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).isMetaplast() { + http.Error(w, "Invalid item properties; use a catalog template and type, with an authored quality or supported Metaplast QL 1 through 200", http.StatusBadRequest) return } server.updateMutex.Lock() diff --git a/server/item_quality.go b/server/item_quality.go @@ -0,0 +1,64 @@ +package main + +import "ao/server/gamedata" + +func metaplastTemplates(template uint32) (uint32, uint32) { + switch template { + case 85511, 85512: + return 85512, 85511 + case 85556, 85557: + return 85557, 85556 + case 85595, 85596: + return 85596, 85595 + case 85637, 85638: + return 85638, 85637 + case 85685, 85686: + return 85686, 85685 + case 85741, 85742: + return 85742, 85741 + } + return 0, 0 +} + +func (item ownedItem) isMetaplast() bool { + low, _ := metaplastTemplates(item.Template) + return item.Type == 51022 && low != 0 && item.Quality >= 1 && item.Quality <= 200 +} + +func (item ownedItem) templateIDs() (uint32, uint32) { + if !item.isMetaplast() { + return item.Template, item.Template + } + low, high := metaplastTemplates(item.Template) + if item.Quality == 1 { + return low, low + } + if item.Quality == 200 { + return high, high + } + return low, high +} + +func (item ownedItem) templateDefinition() *gamedata.Item { + low, high := item.templateIDs() + first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] + // kkr.dll FUN_100894c0 selects the nearer endpoint for nonnumeric properties. + if low != high && item.Quality-*first.Quality >= *second.Quality-item.Quality { + return second + } + return first +} + +func interpolateItemValue(first, second int32, firstQuality, secondQuality, quality uint32) int32 { + // kkr.dll FUN_100eff20 adds 0.5 before truncating the interpolated difference. + if first == second || firstQuality == secondQuality || quality == firstQuality { + return first + } + if quality == secondQuality { + return second + } + if first < second { + return first + int32(float64(int32(quality)-int32(firstQuality))*float64(second-first)/float64(int32(secondQuality)-int32(firstQuality))+0.5) + } + return second + int32(float64(int32(quality)-int32(secondQuality))*float64(first-second)/float64(int32(firstQuality)-int32(secondQuality))+0.5) +} diff --git a/server/loot.go b/server/loot.go @@ -60,7 +60,8 @@ func lootInventoryPacket(owner uint32, corpse *character, open bool) []byte { body := binary.BigEndian.AppendUint32(nil, uint32(len(corpse.corpse.items)+1)*1009) for _, item := range corpse.corpse.items { // Bit 0 selects the native template-proxy transfer path. - for _, value := range []uint32{item.Slot, 0x00030000 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + low, high := item.templateIDs() + for _, value := range []uint32{item.Slot, 0x00030000 | uint32(item.Count), item.Type, item.ID, low, high, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } } diff --git a/server/metaplast_test.go b/server/metaplast_test.go @@ -134,7 +134,7 @@ func TestMetaplastRejectedWearPreservesOwnedItem(t *testing.T) { case "agility": player.stats.Abilities.Agility = agility case "quality": - player.inventory.Items[1].Quality++ + player.inventory.Items[1].Quality = 201 case "identity": player.inventory.Items[1].Type = 51018 case "wrong slot": diff --git a/server/reclaim.go b/server/reclaim.go @@ -42,7 +42,8 @@ func reclaimInventoryPacket(player *character, slots []uint32) []byte { for slot, id := range slots { index := slices.IndexFunc(player.inventory.Reclaim, func(entry reclaimItem) bool { return entry.Item.ID == id }) item := player.inventory.Reclaim[index].Item - for _, value := range []uint32{uint32(slot), 0x00030000 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + low, high := item.templateIDs() + for _, value := range []uint32{uint32(slot), 0x00030000 | uint32(item.Count), item.Type, item.ID, low, high, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } } diff --git a/server/world.go b/server/world.go @@ -178,7 +178,8 @@ func fullCharacterPacket(character *character) []byte { if item.isPortableContainer() || (item.isKineticAxe() || item.isFlechettePistol()) && item.Slot == 6 { flags = 2 } - for _, value := range []uint32{item.Slot, flags<<16 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + low, high := item.templateIDs() + for _, value := range []uint32{item.Slot, flags<<16 | uint32(item.Count), item.Type, item.ID, low, high, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } }