aorecomp

Anarchy Online classic in the browser

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


commit cc5183789544e1d55e8884cd441658941085197b
parent 9670614d764e77c2f55914c3c0f32ec8fe940571
Author: anon <anon@example.com>
Date:   Wed, 28 Oct 2026 19:16:15 +0000

Add an earned intermediate-quality melee upgrade

Admit the reviewed QL1..20 Advanced Baseballbat family through shared item
consumers. Select a concrete QL2 glove or bat when the fixed starter mission
is advertised and retain the choice through acceptance and restart. Keep the
small reward pool explicitly provisional.

Cover strict wear boundaries, selected damage, fee rollback and reward capacity.
Document original-record evidence and ordinary WASM earning, IP training,
equip/remove, combat, canceled sale and cold recovery. Record the observed
outdoor fallback-placement problem for follow-up.

Diffstat:
MTODO.md | 29+++++++++++++++++++++++++----
Adocs/early-melee.md | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/early_melee_test.go | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/item_families.yaml | 2++
Mserver/gamedata/load.go | 9+++++++--
Mserver/gamedata/mission_booths_test.go | 3++-
Mserver/gamedata/missions.yaml | 4++--
Mserver/gamedata/types.go | 3++-
Mserver/mission_item_rewards_test.go | 20++++++++++++--------
Mserver/mission_offers.go | 8++++++++
Mserver/mission_offers_test.go | 1+
Aserver/mission_reward_pool_test.go | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/missions.go | 3++-
13 files changed, 446 insertions(+), 19 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -62,7 +62,7 @@ with durable journals and bound keys. A fixed private interior supports real entry, traversal, reconnect and return. Its bound book can be collected and survives restart without respawning. Returning that exact book to its issuing booth now completes the fixed contract and atomically grants authored cash -and a selected-quality equipment reward. The fixed selection is provisional; +and a selected-quality equipment reward. The small reward pool is provisional; the fixed mission now has five level-1 Leets using shared combat and loot. Indoor combatants now use shared body/collision probes to plan bounded detours; native movement timing still needs refinement. An earned level-2 Enforcer can @@ -259,8 +259,11 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). Metaplast and one reviewed QL1..11 Rusty pistol family now use the shared QL path. Reviewed Low-Tech gloves now add QL1/2 basic-shop upgrades through the same consumers, with an ordinary earned sale-funded purchase and wear now - verified. Useful loot pools and wider early families remain. See - [early armor](docs/early-armor.md). + verified. A QL2 Advanced Baseballbat now also passes ordinary mission earning, + rejected wear, earned IP training, equip/remove, a full-health kill, canceled + sale and cold retention. Useful creature equipment pools and wider early + families remain. See [early armor](docs/early-armor.md) and + [early melee](docs/early-melee.md). - [x] Verify one intermediate-quality weapon family through shared consumers. Check: Rusty pistol endpoints 123742/123743 at QL1,2,5,6,10,11 preserve selected damage, criticals, strict requirements, OE, delays, ammo, price and native @@ -270,6 +273,14 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). and cold recovery; failed wear/shot/reload preserves ownership and permits retry. Historical drop/stock membership and level-relative QL selection remain separate P0 work. See [catalog weapons](docs/catalog-weapons.md). +- [x] Admit one early 1h Blunt upgrade through shared selected-quality consumers. + The reviewed Advanced Baseballbat 122691/122692 family covers QL1..20, + five strict wear criteria, damage/criticals, delays, unlimited ammunition, + Multi Melee, value and native endpoint delivery. The fixed starter mission + selects a concrete QL2 glove or bat at advertisement and retains it through + acceptance and restart. Pool membership, probability and QL are provisional; + broader useful loot and level-relative mission generation remain open. See + [early melee](docs/early-melee.md). - [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 @@ -584,6 +595,14 @@ for exact records, protocol, tests and remaining reconstruction assumptions. ## NPC profiles and behavior +- [ ] [P1] Verify playable placement for generated district-center fallbacks. + A native melee attempt against `950/district/5/group/0/district_center_fallback` + near X138/Z98 left the player around Y13.45 and the NPC around Y10.8, with no + damage during the attempt. Check the actual terrain/static geometry and + fallback population layout, distinguish an inaccessible ledge from an invalid + spawn height, and verify ordinary selection, approach and melee after repair. + Preserve authored placement evidence and use shared placement rules. Evidence: + `local/early-melee/runtime/pair-earned-bat-normal-combat.json`. - [ ] [P1] Incorporate the reviewed NPC mappings from the NPC mapping research. Read its `README.md` and `reports/all-npc-code-assignments.json`, then merge relevant changes surgically into the current checkout. Preserve per-context @@ -1834,10 +1853,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 +- [ ] [P0] 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. + The shipped `text/help/The Mission Window.txt` explicitly makes difficulty + relative to current player level, without specifying a numerical formula. Check low/high player levels, easier/harder missions, supported item ranges, usable rewards and durable exactly-once delivery after reconnect/restart. diff --git a/docs/early-melee.md b/docs/early-melee.md @@ -0,0 +1,106 @@ +# An earned early melee upgrade + +The reviewed Advanced Baseballbat family (122691/122692, QL1..20) uses the +existing selected-quality, requirements, weapon, price and native item consumers. +There is no bat-specific gameplay branch. The fixed starter mission now chooses +one QL2 reward from Metaplast gloves and this weapon when advertising its offer. +Acceptance and cold load retain that concrete choice; completing the contract +uses the existing atomic objective/key/reward transaction. + +## Original records and reconstruction policy + +Both complete 14.9.1 records have matching section/action/function layouts. +They specify melee AC, two-metre range, melee initiative, unlimited ammunition, +150-centisecond attack/equip and 114-centisecond recharge. Minimum damage is 3. +Five strict wear requirements cover 1h Blunt, Sneak Attack, Fast Attack, Brawling +and Dimach. The only function is the identical event-10 presentation function +53076; there are no additional on-hit or wear effects to implement. + +| QL | Maximum / critical bonus | Base value | Multi Melee | Minimum passing skills in that order | +| --- | --- | ---: | ---: | --- | +| 1 | 8 / 11 | 2848 | 22 | 6 / 6 / 6 / 6 / 6 | +| 2 | 9 / 12 | 2863 | 23 | 11 / 8 / 8 / 9 / 7 | +| 10 | 17 / 16 | 4062 | 31 | 48 / 27 / 27 / 31 / 14 | +| 11 | 18 / 17 | 4347 | 31 | 53 / 29 / 29 / 34 / 15 | +| 19 | 26 / 21 | 7704 | 39 | 90 / 48 / 48 / 56 / 22 | +| 20 | 27 / 22 | 8259 | 40 | 95 / 50 / 50 / 59 / 23 | + +Original payload SHA-256: + +- 122691: `2ef7740a681044d4adef1e0fd94aec583ae40a3e71f1e8a9bef5b53d1f667e4b`. +- 122692: `958990f203fc4f5215c5bde4ebb3a6fcfc1cb8156cbadead8ce2084569d407f1`. + +`local/early-melee/audit.json` preserves both decoded records, original offsets, +index digest, complete scalar differences and exact maintained-catalog equality. +Original byte payloads are retained alongside it. The +[Auno interpolation page](https://auno.org/ao/db.php?id=122691&ql=5) independently +identifies these endpoints; its contemporary values do not replace period data. + +Pool membership, uniform probability and fixed QL2 are explicit reconstruction +policy. This does not establish historical terminal selection or creature drops. +Authored prices and requirements are preserved. Level/difficulty-based missions, +broader equipment pools, completion XP/token eligibility and multiweapon combat +remain separate work. + +## Automated verification + +Public inventory handlers cover both anchors at six qualities, equality rejection +for each of five requirements, successful wear, exact identity/slot after cold +load, endpoint delivery, damage, criticals, delays, value, Multi Melee and unlimited +ammunition. Unsupported qualities and an unreviewed adjacent template retain +ownership. Normal and Fast Attack exercise the shared selected-quality damage. + +Mission tests retain both advertised choices through acceptance and restart, +including edits to the generating pool after advertisement. Failed fee writes, +ignored updates and deferred commit failures keep the previous offer and wallet; +retry charges once. Bat rewards join the existing completion lifecycle and +zero/one/two-free-slot inventory checks. Cash-only contracts do not draw an item. +Focused regression passed 16 roots / 131 results; race checks passed 8 roots / +106 results. The complete server/export regression passed 1,649 roots / 16,259 +results. Vet and the development-server build passed. + +## Ordinary WASM progression + +The retained, normally created level-2 Atrox Enforcer started with 52 credits, +5139 IP and eleven owned instances. Two ordinary two-credit requests advertised +a glove and then a bat. Accepting the second contract, entering its private room, +collecting its exact book and returning it awarded 20 credits and bat instance 72 +at QL2. The key/book were consumed once; wallet became 68 and inventory twelve. +No character stats, money, enemy resources or reward choices were provisioned. + +The first book pickup was just beyond the five-metre distance limit and retained +the world item. Moving closer allowed normal R/Pick Up. Native inventory scrolling +exposed the book for the ordinary terminal hand-in. + +Untrained wear reported Sneak Attack 8, Fast Attack 8, Brawling 9 and Dimach 7 and +retained the bat. Earned IP raised raw Sneak/Fast 5->7 and Brawling 5->6. Native +Dimach training correctly refused the attempt at Sense 3; raising Sense 3->5 then +Dimach 5->7 qualified it. The total expenditure was 109 IP, leaving 5030. The bat +wore, removed and re-wore in the right hand; issued bat 19 remained in inventory. +Native slot 6 retained instance 72, QL2 and endpoints 122691/122692. + +An attempt at district-center fallback spawn 1067352 near X138/Z98 caused no +damage. The player stood around Y13.45 while the NPC remained near Y10.8. This +is recorded as a placement follow-up, not a passing fight. Ordinary authored +spawn 1067312 then began at full 100 HP and died through normal bat attacks. +The character survived, gained 100 XP (1150 within level 2; native cumulative 2600) +and used two purchased laboratory charges to recover to 91 HP. Twenty-four charges +remained. Page reconnect retained the weapon, twelve items, trained skills, +68 credits and earned progression. + +At the ordinarily reached training shop, removing bat 72 and placing it in Sell +quoted 143 credits. Decline retained the same instance and wallet; it re-wore +afterward. This is a canceled sale check; accepted-sale behavior for this exact +earned bat has not been claimed. The retained upgrade remains available to play. +The browser used the GPU OpenGL renderer and closed after the run. Screenshots, +read-only native snapshots, wire captures and SQLite checkpoints are retained in +`local/early-melee/`. + +Restarting the sole preview retained the exact earned character, all twelve +instances, learned nanos and all fifteen saved mission encounter rows (nine +previous deaths). A fresh GPU WASM session retained worn bat 72 with the same +QL/endpoints, issued bat 19 in inventory, 24 laboratory charges, 68 credits, +5030 IP, native cumulative 2600 XP, 91/91 HP and 24 nano. A read-only verifier +accounts for every baseline item and the one new reward, exact skill changes, +the consumed key/book and SQLite integrity. No browser exception was recorded. +Both owned browser runs closed, leaving one preview on the default ports. diff --git a/server/early_melee_test.go b/server/early_melee_test.go @@ -0,0 +1,158 @@ +package main + +import ( + "encoding/binary" + "fmt" + "testing" + "time" +) + +func TestAdvancedBaseballbatQualitiesEnforceEveryWearBoundaryAndRecover(t *testing.T) { + for _, template := range []uint32{122691, 122692} { + for _, scenario := range []struct { + quality, maximum, critical, value, multi uint32 + blunt, sneak, fast, brawling, dimach uint16 + }{ + {1, 8, 11, 2848, 22, 6, 6, 6, 6, 6}, + {2, 9, 12, 2863, 23, 11, 8, 8, 9, 7}, + {10, 17, 16, 4062, 31, 48, 27, 27, 31, 14}, + {11, 18, 17, 4347, 31, 53, 29, 29, 34, 15}, + {19, 26, 21, 7704, 39, 90, 48, 48, 56, 22}, + {20, 27, 22, 8259, 40, 95, 50, 50, 59, 23}, + } { + for _, failed := range []uint32{0, 102, 146, 147, 142, 144} { + t.Run(fmt.Sprintf("%d/QL%d/below%d", template, scenario.quality, failed), func(t *testing.T) { + world, output := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = scenario.blunt, scenario.sneak, scenario.fast + player.stats.Body.Brawling, player.stats.Body.Dimach = scenario.brawling, scenario.dimach + switch failed { + case 102: + player.stats.Melee.OneHandBlunt-- + 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, scenario.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) + } + + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment != nil { + world.advanceEquipment(client.equipment.readyAt) + } + cold := newTestInventoryServer(t) + + item := cold.characters[1].inventory.Items[0] + if item.ID != 1 || item.Template != template || item.Quality != scenario.quality || item.Count != 1 { + t.Fatal("wear changed the selected instance", item) + } + if failed != 0 { + if item.Slot != 64 || player.inventory.Items[0].Slot != 64 || client.equipment != nil { + t.Fatal("equality at one wear threshold equipped the weapon", failed, item) + } + return + } + weapon := cold.characters[1].attackWeapon() + if item.Slot != 6 || weapon == nil || itemStat(weapon, 286) != 3 || itemStat(weapon, 285) != scenario.maximum || + itemStat(weapon, 284) != scenario.critical || itemStat(weapon, 101) != scenario.multi || item.shopPrice() != scenario.value || + itemStat(weapon, 294) != 150 || itemStat(weapon, 210) != 114 || itemStat(weapon, 211) != 150 || item.usesAmmo() { + t.Fatal("selected weapon lost its original damage, delays, value or ammunition contract", weapon, item) + } + low, high := uint32(122691), uint32(122692) + if scenario.quality == 1 { + high = low + } else if scenario.quality == 20 { + low = high + } + found := false + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x3b1d2268 { + found = len(packet) >= 91 && binary.BigEndian.Uint32(packet[71:75]) == scenario.quality && + binary.BigEndian.Uint32(packet[79:83]) == low && binary.BigEndian.Uint32(packet[87:91]) == high + } + } + if !found { + t.Fatal("native wear delivery lost the selected endpoints") + } + }) + } + } + } +} + +func TestAdvancedBaseballbatRejectsUnsupportedQualitiesWithoutLosingTheItem(t *testing.T) { + for _, selection := range [][2]uint32{{122691, 0}, {122691, 21}, {122692, 0}, {122692, 21}, {122693, 2}} { + t.Run(fmt.Sprint(selection), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player := world.characters[1] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 1000, 1000, 1000 + player.stats.Body.Brawling, player.stats.Body.Dimach = 1000, 1000 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality = selection[0], selection[1] + + if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + + if world.clients[1].equipment != nil || player.inventory.Items[0].ID != 1 || player.inventory.Items[0].Slot != 64 || + player.inventory.Items[0].Template != selection[0] || player.inventory.Items[0].Quality != selection[1] { + t.Fatal("unsupported interpolation consumed or equipped an item", selection) + } + }) + } +} + +func TestAdvancedBaseballbatUsesSelectedNormalAndFastDamageWithoutAmmunition(t *testing.T) { + for _, action := range []string{"normal", "fast"} { + for _, critical := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/critical=%v", action, critical), func(t *testing.T) { + world, _ := newRangedWorld(t) + player, npc := world.characters[1], world.characters[1000000] + npc.position = [3]float32{1, 0, 0} + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandBlunt, player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 11, 8, 8 + player.stats.Body.Brawling, player.stats.Body.Dimach = 9, 7 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality, player.inventory.Items[0].Ammo = 122691, 2, 0 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.combatRoll = func(bound uint32) uint32 { + if critical { + return 0 + } + return bound - 1 + } + + if action == "fast" { + if err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + } else { + if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack.Add(time.Nanosecond)) + } + + if !critical && npc.health != 991 || critical && npc.health != 979 || player.inventory.Items[0].Ammo != 0 || player.inventory.Items[1].Count != 100 { + t.Fatal("melee damage used an endpoint or consumed bullets", npc.health, player.inventory.Items) + } + }) + } + } +} diff --git a/server/gamedata/item_families.yaml b/server/gamedata/item_families.yaml @@ -13,6 +13,8 @@ - [158416, 158417] # Rusty OT M-10 Flechette Pistol: docs/catalog-weapons.md. - [123742, 123743] +# Unbalanced Advanced Baseballbat: original payload audit; docs/early-melee.md. +- [122691, 122692] # Monster Parts: complete original descriptor audit; docs/npc-loot.md. - [42640, 42641] # Low-Tech gloves: complete original descriptor audit; docs/early-armor.md. diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -196,8 +196,13 @@ func init() { if ItemTemplates[mission.PassageDoor] == nil || ItemTemplates[mission.PassageDoor].HeaderWords[0] != 51016 { panic(fmt.Errorf("invalid mission door %d: template %d", booth, mission.PassageDoor)) } - if (mission.RewardItem != 0 || mission.RewardQuality != 0) && !ItemQualitySupported(mission.RewardItem, mission.RewardQuality) { - panic(fmt.Errorf("invalid mission reward %d: template %d quality %d", booth, mission.RewardItem, mission.RewardQuality)) + if len(mission.RewardItems) == 0 && mission.RewardQuality != 0 { + panic(fmt.Errorf("mission %d reward quality has no item pool", booth)) + } + for _, template := range mission.RewardItems { + if !ItemQualitySupported(template, mission.RewardQuality) { + panic(fmt.Errorf("invalid mission reward %d: template %d quality %d", booth, template, mission.RewardQuality)) + } } } diff --git a/server/gamedata/mission_booths_test.go b/server/gamedata/mission_booths_test.go @@ -88,7 +88,8 @@ func TestStarterMissionTemplateReferencesOriginalAssets(t *testing.T) { item := ItemTemplates[definition.ObjectiveItem] if definition.Playfield != booth.Playfield || definition.Playfield != 3000 || definition.Entrance != 3221228472 || - definition.RewardItem != 85596 || definition.RewardQuality != 2 || !ItemQualitySupported(definition.RewardItem, definition.RewardQuality) || definition.PassageDoor != 41565 || + len(definition.RewardItems) != 2 || definition.RewardItems[0] != 85596 || definition.RewardItems[1] != 122691 || definition.RewardQuality != 2 || + !ItemQualitySupported(85596, 2) || !ItemQualitySupported(122691, 2) || definition.PassageDoor != 41565 || definition.Position != [3]float32{89.30216217041016, 115.14443969726562, 151.16087341308594} || item == nil || item.ID != 40822 || item.Quality == nil || *item.Quality != 1 || item.PayloadSHA256 != "645b946ec12830a3695e1c27659dc37676dbc2b884cb1f19e4fda1692e7066fe" { diff --git a/server/gamedata/missions.yaml b/server/gamedata/missions.yaml @@ -16,8 +16,8 @@ credits: 20 experience: 100 - # A fixed reconstruction selection; original mission reward-pool selection is unresolved. - reward_item: 85596 + # Fixed reconstruction pool; original membership and probabilities are unresolved. + reward_items: [85596, 122691] reward_quality: 2 # Native-tested open passage; historical mission-style selection is unresolved. diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -28,7 +28,8 @@ type MissionTemplate struct { ObjectiveItem uint32 `yaml:"objective_item"` Credits uint32 `yaml:"credits"` Experience uint32 `yaml:"experience"` - RewardItem uint32 `yaml:"reward_item"` + RewardItem uint32 `yaml:"-"` // Concrete choice saved with an advertised contract. + RewardItems []uint32 `yaml:"reward_items"` RewardQuality uint32 `yaml:"reward_quality"` Encounters []MissionEncounter `yaml:"encounters"` PassageDoor uint32 `yaml:"passage_door"` diff --git a/server/mission_item_rewards_test.go b/server/mission_item_rewards_test.go @@ -28,14 +28,14 @@ func TestMissionItemRewardAdvertisedSelectionSurvivesAcceptanceAndRestart(t *tes world, output := newMissionOfferWorld(t) client := world.clients[1] definition := gamedata.MissionTemplates[3221228472] - definition.RewardItem, definition.RewardQuality = 85596, 2 + definition.RewardItems, definition.RewardQuality = []uint32{85596}, 2 gamedata.MissionTemplates[3221228472] = definition if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil { t.Fatal(err) } offer := *client.missionOffer - definition.RewardItem, definition.RewardQuality = 123742, 5 + definition.RewardItems, definition.RewardQuality = []uint32{123742}, 5 gamedata.MissionTemplates[3221228472] = definition if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(offer)); err != nil { t.Fatal(err) @@ -64,7 +64,7 @@ func TestMissionItemRewardSelectionFailureCannotPublishAcceptance(t *testing.T) world, output := newMissionOfferWorld(t) client := world.clients[1] definition := gamedata.MissionTemplates[3221228472] - definition.RewardItem, definition.RewardQuality = 85596, 2 + definition.RewardItems, definition.RewardQuality = []uint32{85596}, 2 gamedata.MissionTemplates[3221228472] = definition if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil { t.Fatal(err) @@ -126,6 +126,7 @@ func TestMissionItemRewardGrantsOneSelectedQualityInstance(t *testing.T) { {"armor intermediate", 85596, 2, 0x052e2f0c, 85596, 85595}, {"armor high", 85595, 200, 0x052e2f0c, 85595, 85595}, {"weapon intermediate", 123742, 2, 0x3b1d2268, 123742, 123743}, + {"melee intermediate", 122691, 2, 0x3b1d2268, 122691, 122692}, {"backpack intermediate", 206730, 51, 0x465a5d73, 206730, 206731}, } { t.Run(scenario.name, func(t *testing.T) { @@ -171,11 +172,14 @@ func TestMissionItemRewardGrantsOneSelectedQualityInstance(t *testing.T) { } func TestMissionItemRewardRequiresTwoFreeSlotsWithoutConsumingAnything(t *testing.T) { - for _, free := range []int{0, 1, 2} { - t.Run(map[int]string{0: "full", 1: "one slot", 2: "two slots"}[free], func(t *testing.T) { - world, client, output := newMissionItemRewardWorld(t, 85596, 2) + for _, scenario := range []struct { + template uint32 + free int + }{{85596, 0}, {85596, 1}, {85596, 2}, {122691, 0}, {122691, 1}, {122691, 2}} { + t.Run(fmt.Sprintf("%d/%d slots", scenario.template, scenario.free), func(t *testing.T) { + world, client, output := newMissionItemRewardWorld(t, scenario.template, 2) player := world.characters[1] - for range 27 - free { + for range 27 - scenario.free { if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted { t.Fatal(granted, err) } @@ -188,7 +192,7 @@ func TestMissionItemRewardRequiresTwoFreeSlotsWithoutConsumingAnything(t *testin } cold := reloadMissionEntranceWorld(t) - if free < 2 { + if scenario.free < 2 { if !reflect.DeepEqual(before, player.inventory) || !reflect.DeepEqual(before, cold.characters[1].inventory) || len(player.missions) != 1 || len(output.packets) != 2 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 || binary.BigEndian.Uint32(output.packets[1][16:20]) != 0x50544d19 || binary.BigEndian.Uint32(output.packets[1][29:33]) != 33 { diff --git a/server/mission_offers.go b/server/mission_offers.go @@ -126,6 +126,14 @@ func (server *server) handleMissionOffers(client *worldClient, body []byte) erro // Charge only a validated generation, committing the wallet before its reply. offer := missionOffer{seed: rand.Uint32N(math.MaxUint32) + 1, booth: boothID, difficulty: body[17], originator: body[28], definition: definition} copy(offer.dimensions[:], body[18:24]) + // Select the advertised reward once; acceptance retains that concrete choice. + if len(definition.RewardItems) != 0 { + roll := server.combatRoll + if roll == nil { + roll = rand.Uint32N + } + offer.definition.RewardItem = definition.RewardItems[roll(uint32(len(definition.RewardItems)))] + } inventory := player.inventory inventory.Credits -= uint32(player.level) if err := server.saveInventory_locked(player, inventory); err != nil { diff --git a/server/mission_offers_test.go b/server/mission_offers_test.go @@ -245,6 +245,7 @@ func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) { definition := gamedata.MissionTemplates[3221228472] cashOnly := definition cashOnly.RewardItem, cashOnly.RewardQuality = 0, 0 + cashOnly.RewardItems = nil cashOnly.Encounters = nil gamedata.MissionTemplates[3221228472] = cashOnly t.Cleanup(func() { gamedata.MissionTemplates[3221228472] = definition }) diff --git a/server/mission_reward_pool_test.go b/server/mission_reward_pool_test.go @@ -0,0 +1,119 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "reflect" + "testing" +) + +func TestMissionRewardPoolRetainsItsAdvertisedChoiceThroughAcceptanceAndColdLoad(t *testing.T) { + for _, choice := range []uint32{0, 1} { + t.Run(fmt.Sprint(choice), func(t *testing.T) { + world, output := newMissionOfferWorld(t) + definition := gamedata.MissionTemplates[3221228472] + definition.RewardItems, definition.RewardQuality = []uint32{85596, 122691}, 2 + gamedata.MissionTemplates[3221228472] = definition + draws := 0 + world.combatRoll = func(bound uint32) uint32 { + if bound != 2 { + t.Fatal("reward pool used an unexpected choice bound", bound) + } + draws++ + return choice + } + + if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { + t.Fatal(err) + } + offer := *world.clients[1].missionOffer + // Editing the generation pool cannot change the already advertised reward. + definition.RewardItems[choice] = 123742 + definition.RewardQuality = 11 + gamedata.MissionTemplates[3221228472] = definition + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(offer)); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + low, high := uint32(85596), uint32(85595) + if choice == 1 { + low, high = 122691, 122692 + } + var item []byte + for _, word := range []uint32{2018, low, high, 2, 0} { + item = binary.BigEndian.AppendUint32(item, word) + } + mission := cold.characters[1].missions[0] + if draws != 1 || offer.definition.RewardItem != low || mission.offer.definition.RewardItem != low || mission.offer.definition.RewardQuality != 2 || + len(mission.offer.definition.RewardItems) != 0 || !bytes.Contains(output.packets[1], item) || + !bytes.Contains(missionJournalPacket(mission, mission.expiresAt), item) || len(cold.items) != 2 || cold.nextItem != 2 { + t.Fatal("advertised reward was rerolled, lost its endpoints or allocated before completion", draws, mission.offer.definition) + } + }) + } +} + +func TestMissionRewardPoolFailureRetainsTheWalletAndPreviousOfferForRetry(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_reward_offer BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(FAIL,'offer'); END", + "CREATE TRIGGER fail_reward_offer BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(IGNORE); END", + "CREATE TABLE pending_offer (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_reward_offer AFTER UPDATE OF credits ON players BEGIN INSERT INTO pending_offer VALUES(999999); END", + } { + t.Run(statement, func(t *testing.T) { + world, output := newMissionOfferWorld(t) + definition := gamedata.MissionTemplates[3221228472] + definition.RewardItems, definition.RewardQuality = []uint32{85596}, 2 + gamedata.MissionTemplates[3221228472] = definition + if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { + t.Fatal(err) + } + before := *world.clients[1].missionOffer + definition.RewardItems = []uint32{85596, 122691} + gamedata.MissionTemplates[3221228472] = definition + world.combatRoll = func(uint32) uint32 { return 1 } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + output.packets = nil + + failure := world.handleMissionOffers(world.clients[1], missionOffersRequest()) + cold := newTestInventoryServer(t) + + if failure == nil || !reflect.DeepEqual(before, *world.clients[1].missionOffer) || len(output.packets) != 0 || + world.characters[1].inventory.Credits != 4 || cold.characters[1].inventory.Credits != 4 || world.nextItem != 1 || cold.nextItem != 1 { + t.Fatal("failed generation charged, replaced the advertised choice or allocated an item", failure) + } + if _, err := world.db.Exec("DROP TRIGGER fail_reward_offer"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { + t.Fatal(err) + } + cold = newTestInventoryServer(t) + if world.clients[1].missionOffer.definition.RewardItem != 122691 || world.characters[1].inventory.Credits != 3 || + cold.characters[1].inventory.Credits != 3 || len(output.packets) != 2 || world.nextItem != 1 { + t.Fatal("retry failed to advertise the new choice with exactly one fee") + } + }) + } +} + +func TestMissionRewardPoolCashOnlyContractDoesNotDrawAnItem(t *testing.T) { + world, _ := newMissionOfferWorld(t) + world.combatRoll = func(uint32) uint32 { + t.Fatal("cash-only generation requested an item choice") + return 0 + } + + if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { + t.Fatal(err) + } + + if world.clients[1].missionOffer.definition.RewardItem != 0 || world.clients[1].missionOffer.definition.RewardQuality != 0 || + world.characters[1].inventory.Credits != 4 || world.nextItem != 1 { + t.Fatal("cash-only generation promised an item or changed its ordinary fee") + } +} diff --git a/server/missions.go b/server/missions.go @@ -152,7 +152,8 @@ func (server *server) handleMissionAcceptance(client *worldClient, body []byte) if err != nil { return err } - // Retain concrete world objects after acceptance, rather than their recipes. + // Retain selected rewards and concrete world objects with the accepted contract. + mission.offer.definition.RewardItems = nil mission.offer.definition.Encounters = nil mission.offer.definition.PassageDoor = 0 if err := server.writeItemStore_locked(store); err != nil {