aorecomp

Anarchy Online classic in the browser

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


commit 460cf6b9a26bb8b96dc3fc709ec0373b97169d14
parent c983841a88a6fb9121b3f7a8bd8b0ac2fe15483d
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 07:58:00 +0000

Preserve selected loot QLs through shared item families

Move the eight reviewed interpolation pairs into shared catalog data and use
one quality admission rule for existing equipment and control edits. Require
loot profiles to specify a supported quality and preserve it in atomic death
outcomes instead of substituting the endpoint definition's quality.

Prioritize useful intermediate equipment, loot-quality selection, mission
level/reward generation and authored outdoor hunting ranges. Keep production
Leet rewards and unresolved historical distributions explicit.

Verify selected qualities through attack paths, rollback/retry, pickup,
requirements, equipment and cold recovery, plus native WASM wear/removal.

Diffstat:
MTODO.md | 40+++++++++++++++++++++++++++++++++++++++-
Mdocs/items.md | 9++++++---
Mdocs/mission-offers.md | 7+++++++
Mdocs/npc-loot.md | 56+++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mserver/backpack_equipment.go | 2+-
Aserver/gamedata/item_families.yaml | 13+++++++++++++
Aserver/gamedata/item_quality.go | 13+++++++++++++
Aserver/gamedata/item_quality_test.go | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/load.go | 17+++++++++++++++--
Mserver/gamedata/npc_combat.yaml | 2++
Mserver/gamedata/types.go | 1+
Mserver/item_pages.go | 5++---
Mserver/item_quality.go | 42+++---------------------------------------
Mserver/npc_loot.go | 2+-
Mserver/npc_loot_progression_test.go | 2+-
Aserver/npc_loot_quality_test.go | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npc_loot_test.go | 13+++++++++----
Mserver/stat_equipment.go | 2+-
18 files changed, 379 insertions(+), 57 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -80,7 +80,9 @@ Next execution order: 2. Connect normal creature kills to useful equipment drops, saleable loot and credits through [production loot profiles](#loot-and-credits). Verify ordinary kill XP, level-up and IP purchases together; keep provisional reward arithmetic - explicit. Add a second enemy level so improving the character has a next step. + explicit. Suitable item QLs are a P0 dependency: use reviewed endpoint families + and shared interpolation rather than dropping only QL1/QL200 definitions. + Add a second enemy level so improving the character has a next step. 3. Supply an evidence-backed useful [shop selection](#shops), then sell earned loot, buy an affordable upgrade and equip/use that same instance. Include consumable/ammunition replenishment needed by the chosen starting character. @@ -92,6 +94,9 @@ Next execution order: journal, reachable private interior, objective, exactly-once XP/credit/item reward, return and abandon. Start with one fixed layout, then generation; do not defer missions until all world content or quest chains are complete. + Generated mission level must follow player level and selected difficulty; + select encounter levels and reward QLs from that contract. Outdoor populations + keep their authored area/species level ranges rather than scaling to visitors. 6. Expand early levels, professions, nanos/pets and team progression using those same item, reward and objective rules. Resume deeper fidelity work as its concrete gameplay dependencies arise. @@ -210,6 +215,13 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). - [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. +- [ ] [P0] Supply intermediate-quality equipment for the early progression loop. + Expand reviewed endpoint families through shared data, not item-name matching + or per-family Go branches. Start with useful early armor and a weapon; verify + requirements, bonuses, damage, attack/recharge, ammunition, price and native + low/high template delivery at low, intermediate and boundary QLs. Include + pickup, rejected wear, equip/remove, sale and cold recovery of the same instance. + Existing Metaplast interpolation does not establish generic weapon support. - [x] Equip one implant. Check: its slot, treatment/ability requirements and bonuses work independently of armor and weapon slots. - [x] Verify passive HealDelta343/NanoDelta364 equipment recovery against the @@ -618,6 +630,12 @@ for exact records, protocol, tests and remaining reconstruction assumptions. tick. Reuse the statel/criteria behavior; do not add per-backyard special cases. - [ ] [P1] Add a second species with different behavior or equipment. Check: changing one species' profile does not change the other species. +- [ ] [P1] Connect successive outdoor hunting areas to early progression. Use + original district/species level ranges for mutants and other encounters, + rather than scaling the outdoor world to the visiting player. Check reachable + lower/higher-level areas, distinct combat profiles, suitable loot QLs, earned + upgrades and restart/respawn behavior. Keep uncertain spawn distributions + explicit; exact historical range selection remains a separate fidelity task. - [x] Reconcile recovery for currently unprofiled creatures. Check: a damaged Reet's native HP reconciles with server HP across idle time and reconnect, with no phantom hits or cumulative drift. A Fling test found server HP 87 while @@ -749,6 +767,20 @@ are recorded in [reclaim](docs/reclaim.md). sale route remain open. The mirrored Leets page names Monster Parts but dates to 2010; neither it nor the dated newbie gathering accounts establish 14.9.1 drop chances or cash formulas. See [NPC loot](docs/npc-loot.md). +- [ ] [P0] Generate loot at suitable supported qualities. Separate item-family + membership/chance from quality selection; establish period-supported QL ranges + relative to creature level, allowing fixed-QL exceptions. Use shared endpoint + data and interpolation for the selected QL; never substitute an endpoint's + QL or extrapolate past its reviewed interval. Test different enemy levels, + low/high boundaries, empty rolls, full inventory, transaction failure/retry, + repeated pickup and restart. Label provisional selection rules explicitly. +- [x] Deliver an explicitly selected supported QL through shared death outcomes. + Reviewed endpoint pairs now live in one data table; loot rows require a valid + QL instead of inheriting a shipped endpoint's QL. Controlled profiles verify + intermediate armor through all direct attacks, periodic damage, native packet + endpoints, pickup, rejected wear, equip/remove, full inventory, cold recovery + and two-item SQL failure/retry. Both real Leet profiles still select QL1 Monster + Parts; historical distributions and useful equipment membership remain above. - [x] Follow generated loot through equipment and sale consumers. Check: a controlled weapon drop survives pickup, cold load, rejected wear below its requirements, skill-training requests and wear/remove/wear with one stable identity. @@ -1440,6 +1472,12 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). contract. Recover level/QL, objective, reward and population selection rules; preserve authored style selectors instead of treating them as playfield IDs or faction numbers. Verify distinct settings and original boundary behavior. +- [ ] [P1] Connect mission level to encounters and useful item rewards. Recover + player-level/difficulty selection, encounter-level variation and item-reward + QL rules independently; do not assume each NPC or every reward equals player + level. Use the shared P0 item-quality path, including fixed-QL reward exceptions. + Check low/high player levels, easier/harder missions, supported item ranges, + usable rewards and durable exactly-once delivery after reconnect/restart. ## Teams diff --git a/docs/items.md b/docs/items.md @@ -107,15 +107,18 @@ silently omitting a definition. A definition is not an owned item. The [initial inventory](inventory.md) persists 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. +and portable containers are supported. The reviewed interpolation families are +listed in `server/gamedata/item_families.yaml`: Metaplast armor, Backpack of +Survival and NCU Hacker Interface. Other interpolated 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. The six Metaplast pairs and their native interpolation rules are documented in +pairings from neighboring IDs or matching names. The shared family table supplies +endpoint identity and quality admission to loot generation, equipment, control +edits and native serialization. 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 diff --git a/docs/mission-offers.md b/docs/mission-offers.md @@ -29,6 +29,13 @@ Difficulty1..11 and six signed dimensions in[-100,100] are validated and echoed. They do not yet change this fixed content, its quality or its rewards. Style selectors remain authored data, not invented destination IDs. +The shipped `cd_image/text/help/The Mission Window.txt` explicitly describes +mission difficulty relative to the character's current level. This supports +player-level/difficulty-dependent generation, not a constant level for all +missions. It does not supply the numeric selection curve, encounter variation +or reward-QL rules. Those remain separate TODO checks before replacing the +fixed starter offer; item rewards should use the shared reviewed quality path. + ## Native protocol and evidence REA/Ghidra12.1.2 observations of the original binaries and full provenance are diff --git a/docs/npc-loot.md b/docs/npc-loot.md @@ -4,7 +4,7 @@ Normal deaths generate rewards from the admitted species/level combat profile. Species evidence in the stable definition is required; a matching placeholder body alone does not qualify. See [profile eligibility](npc-profile-eligibility.md). The current production profiles are level 1 and level 2 Leets. Each configured loot row rolls -independently, creates one item at its catalog template's authored quality, and +independently, creates one item at its explicitly configured quality, and places it in a free corpse slot. Cash is selected inclusively from the configured range. Unprofiled creatures do not inherit a universal loot table. @@ -72,6 +72,60 @@ inventory, equipment, containers and shops. Catalog types and qualities are retained; the server does not turn a weapon or bag into a generic simple item. Typed fixture coverage does not establish those items as historical Leet drops. +## Selected item qualities + +Each loot row requires `template`, `quality` and `chance`. Startup rejects a +missing/zero quality, an unknown template and a quality outside the template's +reviewed interval. Fixed-QL items accept only their authored quality. The shared +`server/gamedata/item_families.yaml` lists the eight previously reviewed endpoint +pairs: six Metaplast pieces, Backpack of Survival and NCU Hacker Interface. +Either endpoint identifies a family. No name or neighboring-ID heuristic pairs +additional definitions, and listing a pair does not implement its effects. + +Death generation retains the selected quality in the ordinary item record, +with the same atomic death/reward transaction. Inventory, native packets, +requirements, bonuses, pricing and control edits use that shared family data. +Exact endpoint qualities still serialize their single matching definition; +intermediate qualities serialize both endpoints. Unsupported qualities are +rejected rather than clamped or substituted with a shipped endpoint's QL. + +This separates quality delivery from selecting the historical quality +distribution. The explicit species/level profiles can choose different supported +qualities without a universal `item QL = NPC level` rule. Both production Leet +profiles still choose QL1 Monster Parts. Wider item families, level-relative +selection, useful equipment drop membership and mission rewards remain open. + +The shipped `cd_image/text/help/How do I play this Game Alone.txt` recommends +armor around character QL and a weapon at least at character QL for solo play. +That corroborates the need for level-appropriate equipment progression. It +does not establish creature drop membership or a formula equating loot QL to +creature level. Outdoor district/species ranges are authored population data; +they should not scale to each visiting character. + +`server/npc_loot_quality_test.go` generates QL101 armor through all six direct +attack paths. Other checks follow both stored endpoints through QL2,50,100,101, +199,200 pickup, rejected wear, equip/remove and cold recovery, with hardcoded +requirements and AC expectations. Two-item failures at the second insert, +ignored insert and deferred commit preserve the whole living NPC/reward state; +retry retains both requested qualities. Existing periodic and full-inventory +checks now also exercise generated QL101 armor. These are controlled profiles, +not evidence for Metaplast drops from Leets. + +The shared-family/selected-quality milestone passed the complete Go suite: +1,415 server roots and 23 gamedata roots, with no failures. The focused selection +passed 23 roots/236 results; two concurrent/failure roots passed under the race +detector, and `go vet` passed. An overlay restoring only the old endpoint-quality +assignment failed both new generation/failure roots as expected. + +Headed GPU WASM checks used a controlled QL101 helmet. Strength235 rejected +wear without losing its identity; Strength236 equipped it and added378 Projectile +AC. A cold server/client restart retained its endpoints, QL, placement and effects; +native removal restored zero AC and the same inventory instance. This verifies +the shared data path, not historical drop membership. No page exception or adapter +failure occurred. Only the owned player/item were removed afterward; unrelated +stopped-world rows and database integrity were verified. Logs, six native heap +snapshots and manifests are retained in `local/item-quality-generation/`. + ## Verification `server/npc_loot_test.go` covers the shared damage paths, periodic killing ticks, diff --git a/server/backpack_equipment.go b/server/backpack_equipment.go @@ -4,7 +4,7 @@ import "ao/server/gamedata" func (item ownedItem) isWearableContainer() bool { return item.isPortableContainer() && itemStat(gamedata.ItemTemplates[item.Template], 30)&4 != 0 && - (item.Quality == *gamedata.ItemTemplates[item.Template].Quality || item.isBackpackOfSurvival()) + gamedata.ItemQualitySupported(item.Template, item.Quality) } func (character *character) canWearContainer(item ownedItem) bool { diff --git a/server/gamedata/item_families.yaml b/server/gamedata/item_families.yaml @@ -0,0 +1,13 @@ +# Reviewed interpolation endpoints, ordered by authored quality. +# Pairing is explicit: matching names or neighboring IDs do not establish a family. +# Metaplast: original payload audit and native rounding; docs/armor.md. +- [85512, 85511] +- [85557, 85556] +- [85596, 85595] +- [85638, 85637] +- [85686, 85685] +- [85742, 85741] +# Backpack of Survival: docs/backpacks.md. +- [206730, 206731] +# NCU Hacker Interface: docs/tradeskills.md. +- [158416, 158417] diff --git a/server/gamedata/item_quality.go b/server/gamedata/item_quality.go @@ -0,0 +1,13 @@ +package gamedata + +func ItemQualitySupported(template, quality uint32) bool { + definition := ItemTemplates[template] + if definition == nil || definition.Quality == nil || quality == 0 { + return false + } + if quality == *definition.Quality { + return true + } + pair, ok := ItemFamilies[template] + return ok && quality >= *ItemTemplates[pair[0]].Quality && quality <= *ItemTemplates[pair[1]].Quality +} diff --git a/server/gamedata/item_quality_test.go b/server/gamedata/item_quality_test.go @@ -0,0 +1,49 @@ +package gamedata_test + +import ( + "ao/server/gamedata" + "fmt" + "testing" +) + +func TestReviewedItemFamilyQualityRanges(t *testing.T) { + for _, pair := range [][2]uint32{{85512, 85511}, {85557, 85556}, {85596, 85595}, {85638, 85637}, {85686, 85685}, {85742, 85741}, {206730, 206731}, {158416, 158417}} { + for _, template := range pair { + t.Run(fmt.Sprint(template), func(t *testing.T) { + low, high := uint32(1), uint32(200) + if template == 206730 || template == 206731 { + low, high = 50, 150 + } + + if gamedata.ItemFamilies[template] != pair { + t.Fatal("endpoint does not identify its reviewed family") + } + for _, quality := range []uint32{low, low + 1, (low + high) / 2, high - 1, high} { + if !gamedata.ItemQualitySupported(template, quality) { + t.Fatal("supported quality rejected", quality) + } + } + for _, quality := range []uint32{0, low - 1, high + 1, 4294967295} { + if gamedata.ItemQualitySupported(template, quality) { + t.Fatal("unsupported quality admitted", quality) + } + } + }) + } + } +} + +func TestUnreviewedItemQualityRemainsExact(t *testing.T) { + for _, entry := range []struct { + template, quality uint32 + supported bool + }{{42640, 1, true}, {42640, 2, false}, {209283, 1, true}, {209283, 2, false}, {85557, 0, 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) + + if got != entry.supported { + t.Fatal("quality admission differs", got) + } + }) + } +} diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -25,6 +25,7 @@ var ( MonsterTemplates = make(map[uint32]*Monster) Items ItemCatalog ItemTemplates = make(map[uint32]*Item) + ItemFamilies = make(map[uint32][2]uint32) NanoTemplates = make(map[uint32]*Item) MapCoordinates MapCoordinateData TerrainEvidence TerrainExtractionEvidence @@ -165,6 +166,19 @@ func init() { } } + // Reviewed families retain both endpoints for any supported intermediate QL. + var families [][2]uint32 + loadYAML("item_families.yaml", &families) + for _, pair := range families { + first, second := ItemTemplates[pair[0]], ItemTemplates[pair[1]] + if first == nil || second == nil || first.Quality == nil || second.Quality == nil || + *first.Quality == 0 || *first.Quality >= *second.Quality || first.HeaderWords[0] != second.HeaderWords[0] || + ItemFamilies[pair[0]] != [2]uint32{} || ItemFamilies[pair[1]] != [2]uint32{} { + panic(fmt.Errorf("invalid or overlapping item family %d/%d", pair[0], pair[1])) + } + ItemFamilies[pair[0]], ItemFamilies[pair[1]] = pair, pair + } + // Fixed-QL recipes identify both inputs and which ones their result replaces. loadYAML("item_combinations.yaml", &ItemCombinations) for first, targets := range ItemCombinations { @@ -195,8 +209,7 @@ func init() { panic(fmt.Errorf("NPC combat profile %d/%d has invalid corpse cash", monster, level)) } for _, drop := range profile.Loot { - item := ItemTemplates[drop.Template] - if drop.Chance > 100 || item == nil || item.Quality == nil || *item.Quality == 0 { + if drop.Chance > 100 || !ItemQualitySupported(drop.Template, drop.Quality) { panic(fmt.Errorf("NPC combat profile %d/%d has invalid loot %d", monster, level, drop.Template)) } } diff --git a/server/gamedata/npc_combat.yaml b/server/gamedata/npc_combat.yaml @@ -21,6 +21,7 @@ credits: [1, 5] loot: - template: 42640 + quality: 1 chance: 50 2: # Retained prototype health and the same provisional solo reward, not a scaling formula. @@ -37,4 +38,5 @@ credits: [1, 5] loot: - template: 42640 + quality: 1 chance: 50 diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -59,6 +59,7 @@ type NPCCombatProfile struct { type NPCLoot struct { Template uint32 `yaml:"template"` + Quality uint32 `yaml:"quality"` Chance uint32 `yaml:"chance"` } diff --git a/server/item_pages.go b/server/item_pages.go @@ -288,9 +288,8 @@ func (server *server) editItem(w http.ResponseWriter, r *http.Request) { err = decodeUsers(strings.NewReader(r.FormValue("data")), &record) } definition := gamedata.ItemTemplates[record.Template] - item := ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality} - if err != nil || definition == nil || definition.Quality == nil || record.Type != definition.HeaderWords[0] || record.Quality != *definition.Quality && !item.isMetaplast() && !item.isBackpackOfSurvival() && !item.isNCUHackerInterface() { - http.Error(w, "Invalid item properties; use the catalog type and authored quality, Metaplast or NCU Hacker Interface QL 1 through 200, or Backpack of Survival QL 50 through 150", http.StatusBadRequest) + if err != nil || definition == nil || record.Type != definition.HeaderWords[0] || !gamedata.ItemQualitySupported(record.Template, record.Quality) { + http.Error(w, "Invalid item properties; use the catalog type and authored quality or a reviewed family's quality range", http.StatusBadRequest) return } server.updateMutex.Lock() diff --git a/server/item_quality.go b/server/item_quality.go @@ -2,48 +2,12 @@ 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) isBackpackOfSurvival() bool { - return item.Type == 51017 && (item.Template == 206730 || item.Template == 206731) && item.Quality >= 50 && item.Quality <= 150 -} - -func (item ownedItem) isNCUHackerInterface() bool { - return item.Type == 51022 && (item.Template == 158416 || item.Template == 158417) && item.Quality >= 1 && item.Quality <= 200 -} - func (item ownedItem) templateIDs() (uint32, uint32) { - var low, high uint32 - if item.isMetaplast() { - low, high = metaplastTemplates(item.Template) - } else if item.isBackpackOfSurvival() { - low, high = 206730, 206731 - } else if item.isNCUHackerInterface() { - low, high = 158416, 158417 - } else { + pair, ok := gamedata.ItemFamilies[item.Template] + if !ok || item.Type != gamedata.ItemTemplates[item.Template].HeaderWords[0] || !gamedata.ItemQualitySupported(item.Template, item.Quality) { return item.Template, item.Template } + low, high := pair[0], pair[1] if item.Quality == *gamedata.ItemTemplates[low].Quality { return low, low } diff --git a/server/npc_loot.go b/server/npc_loot.go @@ -36,7 +36,7 @@ func (server *server) rollCorpseLoot_locked(target *character) ([]ownedItem, err } next++ definition := gamedata.ItemTemplates[drop.Template] - item := ownedItem{ID: next, Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality, Slot: slot, Count: 1} + item := ownedItem{ID: next, Type: definition.HeaderWords[0], Template: definition.ID, Quality: drop.Quality, Slot: slot, Count: 1} drops = append(drops, item) target.corpse.items = append(target.corpse.items, item) slot++ diff --git a/server/npc_loot_progression_test.go b/server/npc_loot_progression_test.go @@ -15,7 +15,7 @@ func TestNPCLootWeaponRetainsInstanceAcrossRejectedWearTrainingAndReequip(t *tes } // This controlled table tests weapon delivery, not historical Leet membership. profile := *world.characters[1000000].combatProfile - profile.Loot = []gamedata.NPCLoot{{Template: 209283, Chance: 100}} + profile.Loot = []gamedata.NPCLoot{{Template: 209283, Quality: 1, Chance: 100}} world.characters[1000000].combatProfile = &profile world.combatRoll = func(uint32) uint32 { return 0 } identity := world.nextItem + 1 diff --git a/server/npc_loot_quality_test.go b/server/npc_loot_quality_test.go @@ -0,0 +1,161 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "slices" + "testing" + "time" +) + +func TestNPCDeathGeneratesSelectedArmorQualityAcrossAttackPaths(t *testing.T) { + for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} { + t.Run(attack, func(t *testing.T) { + world, _ := newKillExperienceWorld(t, attack) + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: 85557, Quality: 101, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + identity := world.nextItem + 1 + + attackForExperience(t, world, attack) + world.advanceCombat(time.Now().Add(time.Hour)) + world.advanceNanos(time.Now().Add(time.Hour)) + cold := newTestInventoryServer(t) + + expected := []ownedItem{{ID: identity, Type: 51022, Template: 85557, Quality: 101, Count: 1}} + for _, current := range []*server{world, cold} { + if !slices.Equal(current.characters[1000000].corpse.items, expected) || current.nextItem != identity || + current.items[identity].Quality != 101 || current.itemPlacements[identity] != (itemPlacement{Corpse: 1000000}) { + t.Fatal("generated armor lost selected quality, identity or placement") + } + } + }) + } +} + +func TestNPCLootSelectedArmorQualitySurvivesPickupAndWear(t *testing.T) { + for _, entry := range []struct { + quality uint32 + strength, agility uint16 + armor int32 + }{{2, 10, 11, 7}, {50, 120, 132, 187}, {100, 233, 258, 375}, {101, 236, 261, 378}, {199, 459, 508, 746}, {200, 461, 511, 750}} { + for _, template := range []uint32{85557, 85556} { + t.Run(fmt.Sprintf("%d/%d", template, entry.quality), func(t *testing.T) { + world, conn := newKillExperienceWorld(t, "unarmed") + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 0, 0 + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: template, Quality: entry.quality, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + identity := world.nextItem + 1 + low, high := uint32(85557), uint32(85556) + if entry.quality == 200 { + low = high + } + var wire []byte + for _, value := range []uint32{identity, low, high, entry.quality, 0} { + wire = binary.BigEndian.AppendUint32(wire, value) + } + + attackForExperience(t, world, "unarmed") + if err := world.handleLootUse(client, lootUseRequest(1)); err != nil { + t.Fatal(err) + } + shown := slices.ContainsFunc(conn.packets, func(packet []byte) bool { return bytes.Contains(packet, wire) }) + if err := world.handleInventory(client, lootTakeRequest()); err != nil { + t.Fatal(err) + } + world = newTestInventoryServer(t) + player = world.characters[1] + client = &worldClient{id: 1, conn: conn, target: true, ready: true} + world.clients[1] = client + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 18)[20:]); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + expected := []ownedItem{{ID: identity, Type: 51022, Template: template, Quality: entry.quality, Slot: 64, Count: 1}} + if !shown || client.equipment != nil || !slices.Equal(player.inventory.Items, expected) || + !slices.Equal(cold.characters[1].inventory.Items, expected) || len(cold.characters[1000000].corpse.items) != 0 { + t.Fatal("presentation, pickup or rejected wear changed selected armor") + } + + // Equip and remove the generated instance using its actual interpolated requirements. + player.stats.Abilities.Strength, player.stats.Abilities.Agility = entry.strength, entry.agility + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, move := range [][2]uint32{{64, 18}, {18, 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 armor did not begin qualified move", err) + } + world.advanceEquipment(client.equipment.readyAt) + expected[0].Slot = move[1] + cold = newTestInventoryServer(t) + bonus := int32(0) + if move[1] == 18 { + bonus = entry.armor + } + for _, current := range []*server{world, cold} { + if !slices.Equal(current.characters[1].inventory.Items, expected) || + current.characters[1].inventory.equipmentBonus(90) != bonus || current.nextItem != identity { + t.Fatal("wear, removal or cold recovery lost selected quality or its effects") + } + } + } + }) + } + } +} + +func TestNPCLootSelectedQualityFailureRollsBackTheWholeDeath(t *testing.T) { + for _, fault := range []struct{ name, sql string }{ + {"second item", "CREATE TRIGGER fail_quality BEFORE INSERT ON items WHEN NEW.quality=101 BEGIN SELECT RAISE(FAIL,'second quality'); END"}, + {"ignored second item", "CREATE TRIGGER fail_quality BEFORE INSERT ON items WHEN NEW.quality=101 BEGIN SELECT RAISE(IGNORE); END"}, + {"commit", "CREATE TABLE pending_quality (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_quality AFTER INSERT ON items WHEN NEW.quality=101 BEGIN INSERT INTO pending_quality VALUES(999999); END"}, + } { + t.Run(fault.name, func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: 85557, Quality: 2, Chance: 100}, {Template: 85556, Quality: 101, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + before := world.nextItem + if _, err := world.db.Exec(fault.sql); err != nil { + t.Fatal(err) + } + + attackForExperience(t, world, "unarmed") + cold := newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + if current.characters[1000000].health != 1 || current.characters[1000000].corpse != nil || + current.characters[1].experience != 0 || current.characters[1].inventory.Credits != 0 || + current.nextItem != before || len(current.items) != 0 || len(current.itemPlacements) != 0 { + t.Fatal("failed selected-quality reward leaked part of the death") + } + } + + // Retry through the same attack request after removing the fault. + if _, err := world.db.Exec("DROP TRIGGER fail_quality"); err != nil { + t.Fatal(err) + } + attackForExperience(t, world, "unarmed") + cold = newTestInventoryServer(t) + expected := []ownedItem{{ID: before + 1, Type: 51022, Template: 85557, Quality: 2, Count: 1}, + {ID: before + 2, Type: 51022, Template: 85556, Quality: 101, Slot: 1, Count: 1}} + if !slices.Equal(cold.characters[1000000].corpse.items, expected) || cold.characters[1000000].corpse.credits != 1 || + cold.characters[1].experience != 100 || cold.nextItem != before+2 { + t.Fatal("retry lost or repeated selected-quality rewards") + } + }) + } +} diff --git a/server/npc_loot_test.go b/server/npc_loot_test.go @@ -172,7 +172,7 @@ func TestNPCLootDoesNotDependOnSoloExperienceEligibility(t *testing.T) { func TestNPCLootUsesSharedTypedItemRecords(t *testing.T) { world, _ := newKillExperienceWorld(t, "unarmed") profile := *world.characters[1000000].combatProfile - profile.Loot = []gamedata.NPCLoot{{Template: 42640, Chance: 100}, {Template: 123742, Chance: 100}, {Template: 143832, Chance: 100}} + profile.Loot = []gamedata.NPCLoot{{Template: 42640, Quality: 1, Chance: 100}, {Template: 123742, Quality: 1, Chance: 100}, {Template: 143832, Quality: 1, Chance: 100}} world.characters[1000000].combatProfile = &profile world.combatRoll = func(uint32) uint32 { return 0 } before := world.nextItem @@ -195,7 +195,9 @@ func TestNPCLootPeriodicKillingTickCommitsOnce(t *testing.T) { world.combatRoll = func(uint32) uint32 { return 0 } target := world.characters[1000000] target.health, target.monsterData, target.level = 1, 17655, 1 - target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + profile := *gamedata.NPCCombatProfiles[17655][1] + profile.Loot = []gamedata.NPCLoot{{Template: 85557, Quality: 101, Chance: 100}} + target.combatProfile = &profile before := world.nextItem at := castPeriodicNano(t, world, 43376) @@ -203,7 +205,7 @@ func TestNPCLootPeriodicKillingTickCommitsOnce(t *testing.T) { world.advanceNanos(at.Add(7500 * time.Millisecond)) cold := newTestInventoryServer(t) - if cold.characters[1000000].health != 0 || len(cold.characters[1000000].corpse.items) != 1 || cold.characters[1000000].corpse.credits != 1 || cold.characters[1].experience != 100 || cold.nextItem != before+1 { + if cold.characters[1000000].health != 0 || len(cold.characters[1000000].corpse.items) != 1 || cold.characters[1000000].corpse.items[0].Quality != 101 || cold.characters[1000000].corpse.credits != 1 || cold.characters[1].experience != 100 || cold.nextItem != before+1 { t.Fatal("periodic killing tick lost or repeated its durable rewards") } } @@ -229,7 +231,7 @@ func TestNPCLootIdentityExhaustionRejectsOnlyAnActualDrop(t *testing.T) { world, _ := newKillExperienceWorld(t, "unarmed") world.combatRoll = func(uint32) uint32 { return 0 } profile := *world.characters[1000000].combatProfile - profile.Loot = []gamedata.NPCLoot{{Template: 42640, Chance: chance}} + profile.Loot = []gamedata.NPCLoot{{Template: 42640, Quality: 1, Chance: chance}} world.characters[1000000].combatProfile = &profile world.nextItem = 4294967295 if _, err := world.db.Exec("UPDATE world SET last_item_id=4294967295 WHERE id=1"); err != nil { @@ -277,6 +279,9 @@ func TestNPCLootRespawnAndCheckpointDoNotRegenerateOldRewards(t *testing.T) { func TestNPCLootFullInventoryRetainsGeneratedItem(t *testing.T) { world, _ := newKillExperienceWorld(t, "unarmed") + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: 85557, Quality: 101, Chance: 100}} + world.characters[1000000].combatProfile = &profile world.combatRoll = func(uint32) uint32 { return 0 } for range 30 { if granted, err := world.grantItem_locked(world.characters[1], 42640); err != nil || !granted { diff --git a/server/stat_equipment.go b/server/stat_equipment.go @@ -34,7 +34,7 @@ func (item ownedItem) isStatEquipment() bool { if item.Type != 51022 || definition == nil || definition.HeaderWords[0] != item.Type || definition.Undecoded != nil || (itemStat(definition, 76) != 1 && itemStat(definition, 76) != 2) || itemStat(definition, 30)&4 == 0 || - !item.isMetaplast() && !item.isNCUHackerInterface() && item.Quality != *definition.Quality { + !gamedata.ItemQualitySupported(item.Template, item.Quality) { return false }