aorecomp

Anarchy Online classic in the browser

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


commit 5b9e25d7898a0c09320d376eaf8790a19b81e0de
parent 4021c16555c684e7af96c427b3a3259c30b8a72f
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 22:35:30 +0000

Grant selected-quality mission rewards atomically and fix terminal bitmap abort

Diffstat:
MTODO.md | 48+++++++++++++++++++++++++++++++++---------------
Mclient/Makefile.linux | 8++++++++
Mclient/Makefile.wasm | 4++++
Mclient/game/bbr.dll/lifted-0040.c | 5++++-
Aclient/tests/bitmap_clear.c | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/mission-objectives.md | 143++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mserver/gamedata/load.go | 7+++++++
Mserver/gamedata/mission_booths_test.go | 1+
Mserver/gamedata/missions.yaml | 4++++
Mserver/gamedata/types.go | 2++
Aserver/item_addition.go | 20++++++++++++++++++++
Mserver/item_database.go | 17++++++++++++++++-
Mserver/mission_completion.go | 24+++++++++++++++++++++++-
Aserver/mission_item_rewards_test.go | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/mission_offers.go | 18+++++++++++++++---
Mserver/mission_offers_test.go | 7+++++++
Mserver/mission_retirement.go | 19+++++++++++++++++++
Mserver/missions.go | 8++++++--
Mserver/shops.go | 21+--------------------
Mserver/world.sql | 2++
20 files changed, 725 insertions(+), 51 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -61,8 +61,9 @@ Starter mission contracts can now be browsed, accepted, abandoned and expired, 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 pays its authored cash reward once. -Mission enemies, conditional token/XP and item rewards remain open. +booth now completes the fixed contract and atomically grants authored cash +and a selected-quality equipment reward. The fixed selection is provisional; +mission enemies, conditional token/XP and historical reward generation remain open. After fixing an inactive-mesh projectile that blocked repeated native casts, a fresh Atrox Nano-Technician completed fifteen ordinary Leet kills without a death, reaching level 2 with 1500 cumulative XP and exactly 4000 new IP. @@ -1521,7 +1522,7 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). verifies normal acceptance, real exterior entry, both rooms, reconnect and exit without substituting client world packets. The fixed prototype has open native room links and no enemies. Returning its objective pays the authored cash - reward; qualifying token/XP and item rewards remain open. The approach volume + and selected-quality item reward; qualifying token/XP remains open. The approach volume and 2.5-unit arrival offsets remain provisional. See [mission interiors](docs/mission-interiors.md#key-gated-live-entry-and-atomic-return). - [ ] [P0] Verify private-instance boundaries across the complete playable loop. @@ -1559,8 +1560,21 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). separately from the active journal; this retention policy remains provisional. Full inventory, credit limits, copied keys, guest/trade isolation, duplicates, failed/ignored writes and commit, output failure and cold recovery are covered. - Conditional XP/token and future item rewards remain separate P0 work below. + Conditional XP/token and historical item selection remain separate P0 work below. See [mission settlement](docs/mission-objectives.md#return-item-settlement). +- [x] Advertise and atomically grant a selected-quality mission item reward. + RewardBox's original ACG list retains both endpoints and QL; acceptance stores + that promise independently of YAML/level changes. Completion consumes the + objective/keys and commits one new instance, cash and completed state together. + Shop and mission delivery share typed weapon/container and armor-proxy rules. + The fixed QL2 glove is reconstruction selection, not historical reward-pool or + difficulty/QL generation. Cover strict wear, duplicate/Unique/capacity rejection, + failures/retry, ID conservation and cold recovery; see + [mission item rewards](docs/mission-objectives.md#selected-quality-item-rewards). +- [ ] [P2] Recover the exact original mission-reward capacity predicate. Original + feedback33 requests two free slots and pending completion; current item rewards + apply that pre-submission gate. Establish whether consumed book/key slots count, + which cash/item/token combinations require space, and any automatic retry rule. - [x] Spawn and collect the fixed mission's bound objective instance. Check: first entry atomically allocates one original Blue Book on the native room floor; reconnect and reentry retain it without respawning collected items. @@ -1581,7 +1595,7 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). receive a token." Period notes increase token chance with kills; the empty prototype grants cash only. Establish the kill threshold/formula, faction exceptions and XP arithmetic before awarding XP/tokens. Add mission enemies - and useful item rewards through shared progression/inventory settlement, + and generated useful item rewards through shared progression/inventory settlement, including full-inventory and failed-commit/retry checks. - [ ] [P1] Extend return-item submission to native carried-backpack sources after verifying their original producer/callback. Main-inventory hand-in is verified; @@ -2501,16 +2515,20 @@ current SQLite storage when applying these findings. ## Thorough gameplay regression testing -- [ ] [P0] Reproduce and diagnose the intermittent WASM abort while opening the - starter mission terminal. One owned GPU run stopped before generation or - acceptance with ErrorEvent/Aborted and an empty "Stopped:" reason. A cold - same-binary retry opened the booth and accepted normally; five subsequent - isolated cold terminal-opening runs also passed. Preserve full native - console output and worker error details; the initial recorder omitted - console.log, including Module.printErr. Its last sampled BBR function is not - a crash stack or proof of a missing adapter. Captures/profile: - `local/mission-retirement/event-crash-*`; successful retry: - `local/mission-retirement/event-retry-*`. +- [x] Fix the reproducible bitmap-clear WASM abort found when reopening the + mission terminal. The 16-bit fill translated a one-past address for a + zero-count REP STOSW; skip translation when no trailing pixel exists. A + page-ending 480x480 fixture aborts with the old code in paged native memory + and WASM, then passes with the fix. Cover odd/even widths, padding, empty + bitmaps, alpha and preserved calling convention in both native memory modes. + Evidence: `local/mission-item-reward-research/client-crash-audit.md` and + `bitmap-before*.log`. The earlier incomplete ErrorEvent capture in + `local/mission-retirement/event-crash-*` cannot independently establish that + historical run's cause; retain it separately from this reproducible failure. +- [ ] [P1] Audit other lifted zero-count bulk operations that translate an + address before checking the count. Check concrete page-boundary failures; + preserve the original no-access semantics without weakening guest memory + validation. The mission terminal's trailing REP STOSW has a focused fix. - [ ] [P1] Close fixture SQLite handles after every test and table case, including failure paths. The comprehensive mission-movement regression run completed over 15,000 results, but its timeout dump retained many database/sql connection diff --git a/client/Makefile.linux b/client/Makefile.linux @@ -172,6 +172,8 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric ./build/linux/native-input ./build/linux/team-header ./build/linux/character-reference + ./build/linux/bitmap-clear + ./build/linux/bitmap-clear-paged ./build/linux/reference-persistence ./build/linux/weapon-range ./build/linux/ip-training @@ -703,3 +705,9 @@ build/linux/reference-persistence: tests/reference_persistence.c game/or.dll/lif $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -pthread -lm -o $@ test: build/linux/reference-persistence + +build/linux/bitmap-clear build/linux/bitmap-clear-paged: tests/bitmap_clear.c game/bbr.dll/lifted-0040.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(if $(filter %-paged,$@),-U__linux__) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ + +test: build/linux/bitmap-clear build/linux/bitmap-clear-paged diff --git a/client/Makefile.wasm b/client/Makefile.wasm @@ -233,6 +233,10 @@ build/wasm/jpeg-idct.js: tests/jpeg_idct.c game/bbr.dll/lifted-0042.c runtime/gu @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ +build/wasm/bitmap-clear.js: tests/bitmap_clear.c game/bbr.dll/lifted-0040.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -o $@ + build/wasm/inflate-fast.js: tests/inflate_fast.c game/bbr.dll/lifted-0044.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ diff --git a/client/game/bbr.dll/lifted-0040.c b/client/game/bbr.dll/lifted-0040.c @@ -1997,7 +1997,10 @@ L_250AF4E8: ecx = _aa + _ab + _ac; _flag_a = recomp_flags_adc(_aa, _ab, _ac); _flag_b = 0; _flag_k = FK_EFLAGS; _cf = _flag_a & 1u; } - { uint32_t _n = ecx, _b = _n * 2u; /* 0x250AF503: rep stosw word ptr es:[edi], ax */ if (_df > 0) { MEMSET16((void*)ADDR(edi), (uint16_t)LO16(eax), _n); edi += _b; } else { MEMSET16((void*)ADDR(edi - _b + 2u), (uint16_t)LO16(eax), _n); edi -= _b; } ecx = 0; } + /* Zero-count REP must not translate the one-past bitmap address. */ + if (ecx) { + { uint32_t _n = ecx, _b = _n * 2u; /* 0x250AF503: rep stosw word ptr es:[edi], ax */ if (_df > 0) { MEMSET16((void*)ADDR(edi), (uint16_t)LO16(eax), _n); edi += _b; } else { MEMSET16((void*)ADDR(edi - _b + 2u), (uint16_t)LO16(eax), _n); edi -= _b; } ecx = 0; } + } L_250AF506: ecx = MEM32(ebp + (-0x4)); /* 0x250AF506: mov ecx, dword ptr [ebp - 4] */ eax = MEM32(ebp + 0x10); /* 0x250AF509: mov eax, dword ptr [ebp + 0x10] */ diff --git a/client/tests/bitmap_clear.c b/client/tests/bitmap_clear.c @@ -0,0 +1,72 @@ +#include "recomp_types.h" +#include <assert.h> + +void sub_250AF340(void); + +/* Color conversion is independent of the bitmap's addressing and row fills. */ +static void convert_color(void) +{ + g_eax = MEM32(g_esp + 4); + g_esp += 8; +} +recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; } +recomp_func_t recomp_lookup_import(uint32_t address) { abort(); } +recomp_func_t recomp_lookup(uint32_t address) +{ + assert(address == 0x250d84e0); + return convert_color; +} + +int main(void) +{ + assert(guest_map("bitmap pixels", 0x50000000, 0x80000)); + assert(guest_map("bitmap and stack", 0x51000000, 0x10000)); + const struct { + unsigned width, height, pitch, depth, format, opaque, expected; + } cases[] = { + {480, 480, 960, 2, 0, 1, 0x1234}, + {2, 2, 4, 2, 0, 1, 0x1234}, + {1, 2, 2, 2, 0, 1, 0x1234}, + {3, 2, 6, 2, 0, 1, 0x1234}, + {2, 2, 8, 2, 0, 1, 0x1234}, + {2, 2, 4, 2, 2, 0, 0x9234}, + {2, 2, 4, 2, 2, 1, 0x1234}, + {2, 2, 8, 4, 0, 1, 0x1234}, + {2, 2, 16, 4, 0, 1, 0x1234}, + {0, 2, 0, 2, 0, 1, 0x1234}, + {2, 0, 4, 2, 0, 1, 0x1234}, + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + unsigned size = cases[i].height * cases[i].pitch; + uint32_t pixels = 0x50080000 - size; + memset((void *)ADDR(0x50000000), 0xa5, 0x80000); + MEM32(0x51000000) = pixels; + MEM32(0x51000008) = cases[i].height; + MEM32(0x5100000c) = cases[i].width; + MEM32(0x51000020) = cases[i].pitch; + MEM32(0x51000024) = cases[i].depth; + MEM32(0x5100002c) = cases[i].format; + g_ecx = 0x51000000; + g_esp = 0x5100ff00; + g_ebp = 123; g_ebx = 234; g_esi = 345; g_edi = 456; + MEM32(g_esp + 4) = 0; + MEM32(g_esp + 8) = 0x1234; + MEM32(g_esp + 12) = cases[i].opaque; + + sub_250AF340(); + + assert(g_esp == 0x5100ff10 && g_ebp == 123); + assert(g_ebx == 234 && g_esi == 345 && g_edi == 456); + assert(MEM8(pixels - 1) == 0xa5); + for (unsigned y = 0; y < cases[i].height; ++y) { + for (unsigned x = 0; x < cases[i].width; ++x) { + uint32_t pixel = pixels + y * cases[i].pitch + x * cases[i].depth; + if (cases[i].depth == 2) assert(MEM16(pixel) == cases[i].expected); + else assert(MEM32(pixel) == cases[i].expected); + } + for (unsigned x = cases[i].width * cases[i].depth; x < cases[i].pitch; ++x) + assert(MEM8(pixels + y * cases[i].pitch + x) == 0xa5); + } + } + puts("bitmap clear: page boundary, odd/even widths, row padding, empty images and alpha passed"); +} diff --git a/docs/mission-objectives.md b/docs/mission-objectives.md @@ -78,19 +78,22 @@ Submission requires the current ready living client, increasing use sequence, the active unexpired contract, its exact allocated book instance and authored QL/template, its actual issuing booth in the same public playfield, the booth's original use requirements and a five-metre three-dimensional range. Pending -inventory interactions/casts and credit overflow reject the operation. Full -inventory is allowed: this fixed cash-only reward creates no new item. +inventory interactions/casts and credit overflow reject the operation. Cash-only +contracts allow full inventory. Item-bearing contracts require two free main +slots before submission and return native feedback33 while leaving completion +pending if that gate fails; its exact historical scope is discussed below. A single inventory transaction consumes the book, removes every bound key -across all locations and owners, adds the authored20 credits and changes the -contract from active to completed exactly once. The final SQL checks verify +across all locations and owners, adds the authored20 credits, creates its +promised selected-quality reward and changes the contract from active to completed exactly once. The final SQL checks verify cash, book destruction, key revocation and completion before commit, including ignored writes and late trigger rewrites. Unrelated items and cash remain intact. Only key-bearing trade drafts are cancelled. Failed persistence leaves live inventories, drafts, journal and messages untouched for retry. After commit the server sends GenericCmd success before deleting the source -from the native inventory, then the credit stat and QuestEvent2. The original +from the native inventory, then the new reward, credit stat and QuestEvent2. +The original kkr.dll0x1006c060 completion consumer removes the journal, reports "Mission accomplished!" and emits the waypoint-clear UI event. A lost reply cannot restore the submitted item or pay the reward again. @@ -109,7 +112,8 @@ The original mission details condition displayed XP on receiving a token. state that token chance rises with kills, without recovering the exact server formula. The empty prototype therefore awards no unconditional100XP or token. The20-credit amount, narrative and48-hour duration are authored reconstruction -data. Useful item rewards and eligible XP/token settlement remain open. +data. The fixed item selection below is also reconstruction data; eligible XP/token +settlement and historical reward selection remain open. [Meiyen's2004 guide, preserved as an unedited repost](https://forums.funcom.com/t/rubi-ka-mission-settings-101/6664) distinguishes finding/picking up an item from returning it to the issuing booth. @@ -174,5 +178,128 @@ settlement and competing lifecycle race checks and `go vet ./server/...`. Separate native wire/state checks verify the exact request, response ordering, SQLite integrity, cold inventory/journal and preserved credit balance. Both successful native runs have no page exceptions or adapter failures; ordinary -HTTP404 console messages are retained separately. This is verification of the -fixed cash-only contract, not completion of mission-generated progression. +HTTP404 console messages are retained separately. That run verified the +cash-only contract. The selected-quality item-reward path is documented below; +mission-generated progression remains incomplete. + + +## Selected-quality item rewards + +The fixed contract advertises one QL2 Metaplast glove, using original reviewed +endpoints85596/85595. Its pool membership, fixed quality and guaranteed selection +are authored reconstruction policy, rather than a recovered historical mission +reward table or player-level/difficulty formula. The item itself retains original +requirements, value, wear effects and interpolation: Strength10, Agility11 and +ACs2/2/2/2/1/1/1/1 in stat90..97 order. It can be kept for wear or sold through the +existing inventory/shop consumers. XP and tokens remain separately conditional. + +RewardBox5's third encoded list is an ACGItem list. Original kkr.dll1009bcb0 +reads its two identity lists before calling10001080 for that list; +N3Msg_GetItemRewardList10021040 returns the resulting RewardBox+3c member. +Each serialized item is four DWORDs: low template, high template, selected QL, +unused auxiliary0. The native in-memory order differs. A nonempty one-item list +uses2018; a cash-only contract retains1009. The original100011b0 reader and the +actual mission details corroborate this layout. Advertised items include their +original type when resolving shared endpoint families, so an intermediate reward +cannot accidentally be advertised as a fixed endpoint. + +The offered selection is copied into the accepted contract and persisted as +reward template and selected QL. Cold loading validates that exact supported +selection, rather than recomputing it from changed YAML, player level or the +nearest endpoint. Merely browsing or accepting allocates no reward instance. +The completed flag is the durable exactly-once guard; no separate reward ledger, +migration or compatibility reader is needed. + +On successful hand-in, the existing detached inventory transaction removes the +book/keys, allocates one new global ID, chooses the first free main slot, adds +cash and persists the selected item and completion together. Final SQL checks +verify the promised selection, actual item/type/QL/count/ammo, placement and +counter before success can be published. Failures preserve the contract, book, +keys, cash, ID counter and live inventory for retry. Carry and family-aware Unique +checks apply independently of wear eligibility. Receiving an item never bypasses +its later equip requirements. + +Completion's native event only removes the quest and reports accomplishment; +it does not materialize advertised reward items. Delivery therefore shares the +shop addition builder: weapons and bags receive typed live FullUpdates with +instance identity and sentinel111; ordinary supported armor receives one +AddTemplate with exact endpoints, QL and count. Do not send both representations. +The successful GenericCmd reply precedes source/key deletion, followed by that +single addition, cash and QuestEvent2. Native equipment and cold reconstruction +then consume the same durable reward instance. + +Original kkr.dll's feedback dictionary10040b00 maps33 to the warning that two +free slots are needed and completion is pending. The prototype uses that +pre-submission gate for item rewards, without consuming anything on rejection. +The dictionary is original evidence for the message, not a recovered server +predicate: whether the original server counts slots freed by objective/key +consumption, and which reward combinations require this gate, remain explicit +fidelity work. No pending-reward queue or silent loss is introduced. + +Evidence is in `local/mission-item-reward-research/`: raw kkr.dll analysis, +`native-rules.md`, the independent server audit and automation/runtime logs. +Tests cover immutable advertisement/acceptance/replay, low/intermediate/high QLs, +weapon/container/armor delivery, two-free-slot and Unique rejection, strict wear +boundaries, equipment effects, duplicate/concurrent requests, lost output and +cold recovery. Injection covers failed/ignored reward creation and placement, +key cleanup, completion and allocation writes, changed promises, late item or +placement rewrites and deferred commit failure, followed by successful retry. + + +## WASM terminal bitmap boundary + +Reopening the terminal after native reward/equipment testing produced an +unmapped-address abort at0x63880000, with a stack through BBR250af340 and +DDR2b085270/2b086bc0. The served module's decoded SHA256 matched the tested +build. The original DDR constructor allocates and clears a480x480 bitmap +before displaying the terminal; retained analysis is in +`local/mission-item-reward-research/ddr-evidence.json`. + +The maintained 16-bit fill translates its trailing REP STOSW destination even +when the repeat count is zero. For an even-width bitmap ending at an unmapped +page, that translation aborts despite there being no remaining pixel to write. +The repair skips that zero-count operation, retaining the existing color, +clipping, pitch and calling convention behavior. + +The actual bitmap-clear entry point now has a480x480 boundary-ending regression +that reproduces the old unmapped-address failure in paged native memory and +WASM. It passes after repair, alongside odd/even widths, row padding, empty +images, alpha behavior and preserved callee registers. The ordinary Linux +mapping mode also passes. This identifies a concrete defect in the captured +call path; it does not retrospectively identify the cause of older captures +that omitted the native console and crash stack. + +## Item-reward native verification + +An owned GPU Chromium run opened the original mission details and reward +icon: both advertised and delivered gloves showed QL2, Strength10, Agility11 and +original interpolated ACs. The normal return-item action consumed book2/key1, +added glove3 and changed cash4 to24. Independent wire checks verify success, +source/key deletion, one AddTemplate85596/85595/QL2/count1, cash and QuestEvent2 +in that order. Rejected wear retained the item; qualified wear, removal and +re-wear retained ID3 and applied/removed the expected ACs. Ability values10/11 +were arranged through the control panel; this does not verify IP training. + +After a cold server/client restart, ID3 remained equipped with its AC effects. +Five terminal reopenings succeeded before another ordinary acceptance and +native room entry, walking, R pickup and exit. With all30 main slots occupied, +returning book5 produced feedback33 and left durable state identical. Freeing +two slots through the control panel and retrying consumed book5/key4, granted +only glove34 and changed cash23 to43. Explicitly removing glove3 and wearing +glove34 retained both instances and the expected armor effects. Reopening the +terminal after reward and equipment processing also succeeded. This repaired +client run has no page exceptions; its two HTTP404 console messages are retained +in the capture. Only owned temporary inventory fillers were removed afterward. + +The server regression passes170 top-level tests/964 results, focused race +checks pass15 top-level tests/40 results, and `go vet ./server/...` passes. +The bitmap boundary fixture passes11 cases in WASM and both native memory +modes; publisher checks also pass. Captures and independent wire/SQLite/native +inventory verifiers are in `local/mission-item-reward-research/`. + +A final cold server/client restart reconstructs exactly two native items: +glove34 in hands and glove3 in main inventory. Their original endpoints, QL2, +43 credits and armor effects survive; neither completed contract replays into +the journal, and no repeated completion event or reward is sent. SQLite +integrity and foreign keys remain valid. The owned browser is closed after +verification, leaving one LAN preview process on the default ports. diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -191,6 +191,13 @@ func init() { } } + // Accepted contracts retain the advertised selected quality, including intermediates. + for booth, mission := range MissionTemplates { + 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)) + } + } + // Fixed-QL recipes identify both inputs and which ones their result replaces. loadYAML("item_combinations.yaml", &ItemCombinations) for first, targets := range ItemCombinations { diff --git a/server/gamedata/mission_booths_test.go b/server/gamedata/mission_booths_test.go @@ -88,6 +88,7 @@ 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.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 @@ -15,3 +15,7 @@ objective_item: 40822 credits: 20 experience: 100 + + # A fixed reconstruction selection; original mission reward-pool selection is unresolved. + reward_item: 85596 + reward_quality: 2 diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -28,6 +28,8 @@ type MissionTemplate struct { ObjectiveItem uint32 `yaml:"objective_item"` Credits uint32 `yaml:"credits"` Experience uint32 `yaml:"experience"` + RewardItem uint32 `yaml:"reward_item"` + RewardQuality uint32 `yaml:"reward_quality"` } type ItemCombination struct { diff --git a/server/item_addition.go b/server/item_addition.go @@ -0,0 +1,20 @@ +package main + +import "encoding/binary" + +func inventoryAdditionPacket(player *character, item ownedItem) []byte { + // Live weapons/containers need their original subclass and first-free sentinel. + item.Slot = 111 + if item.isPortableContainer() { + return backpackPacket(player.id, player.playfield, item, 104) + } + if item.Type == 51018 { + return weaponPacket(player.id, player.playfield, item, 104) + } + var body []byte + low, high := item.templateIDs() + for _, value := range []uint32{low, high, item.Quality, uint32(item.Count)} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x052e2f0c, 50000, player.id, body) +} diff --git a/server/item_database.go b/server/item_database.go @@ -256,9 +256,15 @@ func (server *server) persistItems_locked(store itemStore) error { if err := tx.QueryRow("SELECT id FROM world WHERE id=1 AND last_playfield_id=?", store.mission.world).Scan(&savedID); err != nil { return fmt.Errorf("mission world allocation was not saved: %w", err) } + if err := tx.QueryRow("SELECT id FROM missions WHERE id=? AND reward_item=? AND reward_quality=?", store.mission.id, + store.mission.offer.definition.RewardItem, store.mission.offer.definition.RewardQuality).Scan(&savedID); err != nil { + return fmt.Errorf("mission item reward selection was not saved: %w", err) + } } if store.updatedMission != nil { - if err := tx.QueryRow("SELECT id FROM missions WHERE id=? AND objective_id=? AND completed=?", store.updatedMission.id, store.updatedMission.objective, store.updatedMission.completed).Scan(&savedID); err != nil { + if err := tx.QueryRow("SELECT id FROM missions WHERE id=? AND objective_id=? AND completed=? AND reward_item=? AND reward_quality=?", + store.updatedMission.id, store.updatedMission.objective, store.updatedMission.completed, + store.updatedMission.offer.definition.RewardItem, store.updatedMission.offer.definition.RewardQuality).Scan(&savedID); err != nil { return fmt.Errorf("mission update was not saved: %w", err) } mission := store.updatedMission @@ -268,6 +274,15 @@ func (server *server) persistItems_locked(store itemStore) error { AND NOT EXISTS (SELECT 1 FROM items WHERE id=?)`, mission.owner, store.Players[mission.owner].Credits, mission.id, mission.objective).Scan(&savedID); err != nil { return fmt.Errorf("mission settlement was not saved: %w", err) } + if mission.offer.definition.RewardItem != 0 { + // The promised instance is the settlement's only new allocation. + reward := store.Items[store.LastID] + if err := tx.QueryRow(`SELECT items.id FROM items JOIN item_locations ON item_id=items.id + WHERE items.id=? AND (type, template, quality, count, ammo) IS (?, ?, ?, 1, 0) + AND player_id=? AND slot=? AND reclaim_at IS NULL`, store.LastID, reward.Type, reward.Template, reward.Quality, mission.owner, placements[store.LastID].Slot).Scan(&savedID); err != nil { + return fmt.Errorf("mission item reward was not saved: %w", err) + } + } } } if err := tx.Commit(); err != nil { diff --git a/server/mission_completion.go b/server/mission_completion.go @@ -37,6 +37,7 @@ func (server *server) handleMissionReturn(client *worldClient, body []byte) erro client.useSequence = sequence reply := slices.Clone(body[16:]) binary.BigEndian.PutUint32(reply, 2) + feedback := uint32(0) // The authored return-item contract names its issuing booth and exact spawned item. index := slices.IndexFunc(player.missions, func(mission acceptedMission) bool { @@ -57,10 +58,31 @@ func (server *server) handleMissionReturn(client *worldClient, body []byte) erro objective.Quality == *gamedata.ItemTemplates[mission.offer.definition.ObjectiveItem].Quality && x*x+y*y+z*z <= 25 && player.templateUseRequirementsMet(gamedata.ItemTemplates[booth.Template]) && uint64(player.inventory.Credits)+uint64(mission.offer.definition.Credits) <= 1000000000 + if accepted && mission.offer.definition.RewardItem != 0 { + // Feedback33 asks for two free slots before delivering a pending reward. + free := 30 + for _, held := range player.inventory.Items { + if held.Slot >= 64 { + free-- + } + } + if free < 2 { + accepted, feedback = false, 33 + } + reward := ownedItem{Type: gamedata.ItemTemplates[mission.offer.definition.RewardItem].HeaderWords[0], Template: mission.offer.definition.RewardItem, Quality: mission.offer.definition.RewardQuality} + accepted = accepted && itemStat(reward.templateDefinition(), 30)&1 != 0 && + (itemStat(reward.templateDefinition(), 0)&0x08000000 == 0 || !player.inventory.carriesUnique(reward)) + } } if !accepted { server.mutex.Unlock() - return client.send(n3Packet(0x52526858, 50000, client.id, reply)) + if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil { + return err + } + if feedback != 0 { + return client.send(n3Packet(0x50544d19, 50000, client.id, binary.BigEndian.AppendUint32(nil, feedback))) + } + return nil } // Empty prototypes have no qualifying kills for the separately conditional XP/token. diff --git a/server/mission_item_rewards_test.go b/server/mission_item_rewards_test.go @@ -0,0 +1,346 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "sync" + "testing" +) + +func newMissionItemRewardWorld(t *testing.T, template, quality uint32) (*server, *worldClient, *combatTestConn) { + t.Helper() + world, client, output := newMissionReturnWorld(t) + // Set up a saved accepted selection independently of the production reward pool. + world.characters[1].missions[0].offer.definition.RewardItem = template + world.characters[1].missions[0].offer.definition.RewardQuality = quality + world.missionExpiry[0] = world.characters[1].missions[0] + if _, err := world.db.Exec("UPDATE missions SET reward_item=?, reward_quality=?", template, quality); err != nil { + t.Fatal(err) + } + return world, client, output +} + +func TestMissionItemRewardAdvertisedSelectionSurvivesAcceptanceAndRestart(t *testing.T) { + world, output := newMissionOfferWorld(t) + client := world.clients[1] + definition := gamedata.MissionTemplates[3221228472] + definition.RewardItem, definition.RewardQuality = 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 + gamedata.MissionTemplates[3221228472] = definition + if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(offer)); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + mission := cold.characters[1].missions[0] + journal := targetPacket(missionJournalPacket(mission, mission.expiresAt)) + var selection []byte + for _, word := range []uint32{2018, 85596, 85595, 2, 0} { + selection = binary.BigEndian.AppendUint32(selection, word) + } + + if mission.offer.definition.RewardItem != 85596 || mission.offer.definition.RewardQuality != 2 || + !bytes.Contains(output.packets[1], selection) || !bytes.Contains(journal, selection) || + len(cold.items) != 2 || cold.nextItem != 2 || len(cold.characters[1].inventory.Items) != 2 { + t.Fatal("reward changed after advertisement, lost its QL/endpoints or was allocated before completion", mission, output.packets) + } +} + +func TestMissionItemRewardSelectionFailureCannotPublishAcceptance(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_selection AFTER INSERT ON missions BEGIN UPDATE missions SET reward_quality=1 WHERE id=NEW.id; END", + "CREATE TRIGGER fail_selection AFTER UPDATE OF last_item_id ON world BEGIN UPDATE missions SET reward_item=123742; END", + } { + t.Run(statement, func(t *testing.T) { + world, output := newMissionOfferWorld(t) + client := world.clients[1] + definition := gamedata.MissionTemplates[3221228472] + definition.RewardItem, definition.RewardQuality = 85596, 2 + gamedata.MissionTemplates[3221228472] = definition + if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil { + t.Fatal(err) + } + request := missionAcceptanceRequest(*client.missionOffer) + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + output.packets = nil + + failure := world.handleMissionAcceptance(client, request) + cold := newTestInventoryServer(t) + + if failure == nil || client.missionOffer == nil || len(output.packets) != 0 || world.nextItem != 1 || cold.nextItem != 1 || + len(world.characters[1].missions) != 0 || len(cold.characters[1].missions) != 0 { + t.Fatal("changed reward selection was advertised as accepted", failure) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_selection"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionAcceptance(client, request); err != nil { + t.Fatal(err) + } + cold = newTestInventoryServer(t) + + if cold.characters[1].missions[0].offer.definition.RewardItem != 85596 || cold.characters[1].missions[0].offer.definition.RewardQuality != 2 || + cold.nextItem != 2 || len(output.packets) != 2 { + t.Fatal("retry did not retain the advertised selection") + } + }) + } +} + +func TestMissionItemRewardColdLoadRejectsUnsupportedSelections(t *testing.T) { + for _, pair := range [][2]uint32{{0, 2}, {85596, 0}, {85596, 201}, {123742, 12}, {9999999, 1}} { + t.Run(fmt.Sprintf("%d/QL%d", pair[0], pair[1]), func(t *testing.T) { + world, _, _ := newMissionItemRewardWorld(t, 85596, 2) + if _, err := world.db.Exec("UPDATE missions SET reward_item=?, reward_quality=?", pair[0], pair[1]); err != nil { + t.Fatal(err) + } + cold := &server{db: world.db} + + failure := cold.loadUsers() + + if failure == nil || len(cold.missionExpiry) != 0 { + t.Fatal("cold load replaced an unsupported promised reward", failure) + } + }) + } +} + +func TestMissionItemRewardGrantsOneSelectedQualityInstance(t *testing.T) { + for _, scenario := range []struct { + name string + template, quality, packet, low, high uint32 + }{ + {"armor low", 85596, 1, 0x052e2f0c, 85596, 85596}, + {"armor intermediate", 85596, 2, 0x052e2f0c, 85596, 85595}, + {"armor high", 85595, 200, 0x052e2f0c, 85595, 85595}, + {"weapon intermediate", 123742, 2, 0x3b1d2268, 123742, 123743}, + {"backpack intermediate", 206730, 51, 0x465a5d73, 206730, 206731}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, client, output := newMissionItemRewardWorld(t, scenario.template, scenario.quality) + + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + reward := cold.characters[1].inventory.Items[1] + for _, sequence := range []uint32{1, 2} { + if err := world.handleMissionReturn(client, missionReturnRequest(sequence)); err != nil { + t.Fatal(err) + } + } + + if reward.ID != 4 || reward.Template != scenario.template || reward.Quality != scenario.quality || reward.Slot != 65 || reward.Count != 1 || reward.Ammo != 0 || + cold.nextItem != 4 || len(cold.items) != 2 || cold.characters[1].inventory.Credits != 24 || len(cold.characters[1].missions) != 0 || + !reflect.DeepEqual(cold.characters[1].inventory, world.characters[1].inventory) || len(output.packets) != 7 || + binary.BigEndian.Uint32(output.packets[3][16:20]) != scenario.packet { + t.Fatal("reward was lost, duplicated, changed QL or delivered with the wrong native class", reward, output.packets) + } + packet := output.packets[3] + if scenario.packet == 0x052e2f0c { + for index, word := range []uint32{scenario.low, scenario.high, scenario.quality, 1} { + if binary.BigEndian.Uint32(packet[29+index*4:]) != word { + t.Fatal("reward proxy lost its advertised endpoints, quality or count", packet) + } + } + } else { + if binary.BigEndian.Uint32(packet[24:28]) != 4 || binary.BigEndian.Uint32(packet[33:37]) != 50000 || + binary.BigEndian.Uint32(packet[37:41]) != 1 || packet[53] != 104 || packet[54] != 111 { + t.Fatal("live reward lost its identity, parent or first-free sentinel", packet) + } + for index, word := range []uint32{701, scenario.quality, 702, scenario.low, 703, scenario.high} { + if binary.BigEndian.Uint32(packet[67+index*4:]) != word { + t.Fatal("live reward lost its advertised endpoints or quality", packet) + } + } + } + }) + } +} + +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) + player := world.characters[1] + for range 27 - free { + if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted { + t.Fatal(granted, err) + } + } + before := player.inventory + output.packets = nil + + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if 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 { + t.Fatal("pending completion lost items/cash or omitted native capacity feedback", output.packets) + } + } else if player.inventory.Credits != 24 || len(player.missions) != 0 || len(player.inventory.Items) != 27 || len(output.packets) != 6 { + t.Fatal("two free slots rejected a valid item reward", player.inventory, output.packets) + } + }) + } +} + +func TestMissionItemRewardUniqueConflictKeepsContractPending(t *testing.T) { + world, client, output := newMissionItemRewardWorld(t, 43328, 1) + if granted, err := world.grantItem_locked(world.characters[1], 43328); err != nil || !granted { + t.Fatal(granted, err) + } + before := world.characters[1].inventory + output.packets = nil + + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if !reflect.DeepEqual(before, world.characters[1].inventory) || !reflect.DeepEqual(before, cold.characters[1].inventory) || + len(cold.characters[1].missions) != 1 || len(output.packets) != 1 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 { + t.Fatal("Unique reward conflict consumed the contract or granted a duplicate") + } +} + +func TestMissionItemRewardFailureRollsBackRewardCashKeysAndObjective(t *testing.T) { + for _, scenario := range []struct{ name, sql string }{ + {"item abort", "CREATE TRIGGER fail_reward BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(ABORT,'reward'); END"}, + {"item ignored", "CREATE TRIGGER fail_reward BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(IGNORE); END"}, + {"placement ignored", "CREATE TRIGGER fail_reward BEFORE INSERT ON item_locations WHEN NEW.item_id=4 BEGIN SELECT RAISE(IGNORE); END"}, + {"key ignored", "CREATE TRIGGER fail_reward BEFORE DELETE ON mission_keys BEGIN SELECT RAISE(IGNORE); END"}, + {"completion ignored", "CREATE TRIGGER fail_reward BEFORE UPDATE OF completed ON missions BEGIN SELECT RAISE(IGNORE); END"}, + {"late reward rewrite", "CREATE TRIGGER fail_reward AFTER UPDATE OF last_item_id ON world BEGIN UPDATE items SET quality=1 WHERE id=4; END"}, + {"late placement removal", "CREATE TRIGGER fail_reward AFTER UPDATE OF last_item_id ON world BEGIN DELETE FROM item_locations WHERE item_id=4; END"}, + {"late promise rewrite", "CREATE TRIGGER fail_reward AFTER UPDATE OF last_item_id ON world BEGIN UPDATE missions SET reward_quality=1; END"}, + {"allocation ignored", "CREATE TRIGGER fail_reward BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(IGNORE); END"}, + {"commit", "CREATE TABLE pending_reward (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_reward AFTER INSERT ON items WHEN NEW.id=4 BEGIN INSERT INTO pending_reward VALUES(999999); END"}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, client, output := newMissionItemRewardWorld(t, 85596, 2) + before := world.characters[1].inventory + if _, err := world.db.Exec(scenario.sql); err != nil { + t.Fatal(err) + } + + failure := world.handleMissionReturn(client, missionReturnRequest(1)) + cold := reloadMissionEntranceWorld(t) + + if failure == nil || len(output.packets) != 0 || world.nextItem != 3 || cold.nextItem != 3 || len(cold.items) != 3 || + !reflect.DeepEqual(before, world.characters[1].inventory) || !reflect.DeepEqual(before, cold.characters[1].inventory) || + len(world.characters[1].missions) != 1 || len(cold.characters[1].missions) != 1 || cold.missionExpiry[0].completed { + t.Fatal("failed reward published allocation or partial settlement", failure) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_reward"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionReturn(client, missionReturnRequest(2)); err != nil { + t.Fatal(err) + } + cold = reloadMissionEntranceWorld(t) + + if cold.nextItem != 4 || cold.characters[1].inventory.Items[1].ID != 4 || cold.characters[1].inventory.Items[1].Quality != 2 || + cold.characters[1].inventory.Credits != 24 || len(cold.characters[1].missions) != 0 || len(output.packets) != 6 { + t.Fatal("retry did not allocate and settle exactly once") + } + }) + } +} + +func TestMissionItemRewardConcurrentSubmissionAllocatesOnce(t *testing.T) { + world, client, output := newMissionItemRewardWorld(t, 123742, 2) + var workers sync.WaitGroup + failures := make(chan error, 2) + + for range 2 { + workers.Add(1) + go func() { defer workers.Done(); failures <- world.handleMissionReturn(client, missionReturnRequest(1)) }() + } + workers.Wait() + close(failures) + for err := range failures { + if err != nil { + t.Fatal(err) + } + } + cold := reloadMissionEntranceWorld(t) + + if len(cold.items) != 2 || cold.nextItem != 4 || len(cold.characters[1].inventory.Items) != 2 || cold.characters[1].inventory.Items[1].ID != 4 || + len(output.packets) != 6 || cold.characters[1].inventory.Credits != 24 { + t.Fatal("concurrent reward allocated twice", output.packets) + } +} + +func TestMissionItemRewardOutputFailureKeepsCommittedInstance(t *testing.T) { + world, client, _ := newMissionItemRewardWorld(t, 85596, 2) + client.conn = &failingCombatConn{} + + world.handleMissionReturn(client, missionReturnRequest(1)) + cold := reloadMissionEntranceWorld(t) + + if cold.nextItem != 4 || len(cold.items) != 2 || cold.characters[1].inventory.Credits != 24 || + len(cold.characters[1].missions) != 0 || cold.characters[1].inventory.Items[1].ID != 4 || cold.characters[1].inventory.Items[1].Quality != 2 { + t.Fatal("lost reply reversed or lost the committed reward") + } +} + +func TestMissionItemRewardPreservesInstanceThroughRejectedWearAndEquipment(t *testing.T) { + world, client, _ := newMissionItemRewardWorld(t, 85596, 2) + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + player := world.characters[1] + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 9, 10 + + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 24)[20:]); err != nil { + t.Fatal(err) + } + + if client.equipment != nil || player.inventory.Items[1].ID != 4 || player.inventory.Items[1].Slot != 65 { + t.Fatal("rejected reward wear lost its instance") + } + + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 10, 11 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, move := range [][2]uint32{{65, 24}, {24, 65}, {65, 24}} { + 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("reward equipment did not start", err) + } + world.advanceEquipment(client.equipment.readyAt) + cold := reloadMissionEntranceWorld(t) + armor := int32(0) + if move[1] == 24 { + armor = 2 + } + + if len(cold.items) != 2 || cold.nextItem != 4 || cold.characters[1].inventory.Items[1].ID != 4 || cold.characters[1].inventory.Items[1].Slot != move[1] || + cold.characters[1].inventory.Credits != 24 || player.equipmentBonus(90) != armor || cold.characters[1].equipmentBonus(90) != armor || + !slices.Equal(player.inventory.Items, cold.characters[1].inventory.Items) { + t.Fatal("reward changed identity during equipment or cold recovery", cold.characters[1].inventory) + } + } +} diff --git a/server/mission_offers.go b/server/mission_offers.go @@ -40,9 +40,21 @@ func appendMissionQuest(body []byte, offer missionOffer, id, owner, remaining ui body = append(body, offer.definition.Description...) body = append(body, 0) - // Quest creator, RewardBox5 (cash/XP and empty item lists), and quest metadata. - for _, word := range []uint32{56001, offer.booth, 5, offer.definition.Credits, 0, offer.definition.Experience, - 1009, 1009, 1009, 0, 0, 0, 0, 0, 0, 0, + // Quest creator, RewardBox5 and the advertised cash/conditional XP/item reward. + for _, word := range []uint32{56001, offer.booth, 5, offer.definition.Credits, 0, offer.definition.Experience, 1009, 1009} { + body = binary.BigEndian.AppendUint32(body, word) + } + if offer.definition.RewardItem == 0 { + body = binary.BigEndian.AppendUint32(body, 1009) + } else { + // RewardBox's third list contains ACGItem: low/high templates, QL and auxiliary DWORD. + reward := ownedItem{Type: gamedata.ItemTemplates[offer.definition.RewardItem].HeaderWords[0], Template: offer.definition.RewardItem, Quality: offer.definition.RewardQuality} + low, high := reward.templateIDs() + for _, word := range []uint32{2018, low, high, reward.Quality, 0} { + body = binary.BigEndian.AppendUint32(body, word) + } + } + for _, word := range []uint32{0, 0, 0, 0, 0, 0, 0, itemStat(gamedata.ItemTemplates[offer.definition.ObjectiveItem], 79), 0, remaining, 2018} { body = binary.BigEndian.AppendUint32(body, word) } diff --git a/server/mission_offers_test.go b/server/mission_offers_test.go @@ -1,6 +1,7 @@ package main import ( + "ao/server/gamedata" "bytes" "encoding/binary" "fmt" @@ -240,6 +241,12 @@ func TestMissionOfferConcurrentRequestsCannotOverdrawTheWallet(t *testing.T) { func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() + // Keep the cash-only contract available to isolate journal and world lifecycle. + definition := gamedata.MissionTemplates[3221228472] + cashOnly := definition + cashOnly.RewardItem, cashOnly.RewardQuality = 0, 0 + gamedata.MissionTemplates[3221228472] = cashOnly + t.Cleanup(func() { gamedata.MissionTemplates[3221228472] = definition }) world, output := newEquipmentWorld(t) player := world.characters[1] player.playfield, player.position = 3000, [3]float32{100, 115.75, 145} diff --git a/server/mission_retirement.go b/server/mission_retirement.go @@ -1,7 +1,9 @@ package main import ( + "ao/server/gamedata" "encoding/binary" + "fmt" "log" "maps" "slices" @@ -171,6 +173,23 @@ func (server *server) endMission_locked(mission acceptedMission, completed bool, } if completed && id == mission.owner { inventory.Credits += mission.offer.definition.Credits + if mission.offer.definition.RewardItem != 0 { + if store.LastID == ^uint32(0) { + return nil, fmt.Errorf("mission reward item identities exhausted") + } + store.LastID++ + definition := gamedata.ItemTemplates[mission.offer.definition.RewardItem] + reward := ownedItem{ID: store.LastID, Type: definition.HeaderWords[0], Template: definition.ID, Quality: mission.offer.definition.RewardQuality, Slot: 64, Count: 1} + for slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == reward.Slot }) { + reward.Slot++ + } + inventory.LastID = reward.ID + inventory.Items = append(inventory.Items, reward) + store.Items[reward.ID] = recordItem(reward, nil) + if client != nil { + changes[client] = append(changes[client], inventoryAdditionPacket(server.characters[id], reward)) + } + } } inventories[id] = inventory store.Players[id] = inventory.references() diff --git a/server/missions.go b/server/missions.go @@ -22,14 +22,14 @@ type acceptedMission struct { completed bool } -const missionColumns = "owner_id, booth_id, seed, difficulty, dimension_0, dimension_1, dimension_2, dimension_3, dimension_4, dimension_5, originator, description, playfield, entrance, position_x, position_y, position_z, objective_item, credits, experience, expires_at, world_id, layout, objective_id, completed" +const missionColumns = "owner_id, booth_id, seed, difficulty, dimension_0, dimension_1, dimension_2, dimension_3, dimension_4, dimension_5, originator, description, playfield, entrance, position_x, position_y, position_z, objective_item, credits, experience, reward_item, reward_quality, expires_at, world_id, layout, objective_id, completed" func (mission *acceptedMission) fields() []any { return []any{&mission.owner, &mission.offer.booth, &mission.offer.seed, &mission.offer.difficulty, &mission.offer.dimensions[0], &mission.offer.dimensions[1], &mission.offer.dimensions[2], &mission.offer.dimensions[3], &mission.offer.dimensions[4], &mission.offer.dimensions[5], &mission.offer.originator, &mission.offer.definition.Description, &mission.offer.definition.Playfield, &mission.offer.definition.Entrance, &mission.offer.definition.Position[0], &mission.offer.definition.Position[1], &mission.offer.definition.Position[2], - &mission.offer.definition.ObjectiveItem, &mission.offer.definition.Credits, &mission.offer.definition.Experience, &mission.expiresAt, &mission.world, &mission.layout, &mission.objective, &mission.completed} + &mission.offer.definition.ObjectiveItem, &mission.offer.definition.Credits, &mission.offer.definition.Experience, &mission.offer.definition.RewardItem, &mission.offer.definition.RewardQuality, &mission.expiresAt, &mission.world, &mission.layout, &mission.objective, &mission.completed} } func insertMission(tx *sql.Tx, mission *acceptedMission) error { @@ -60,6 +60,10 @@ func (server *server) loadMissions() error { if err := rows.Scan(append([]any{&mission.id}, mission.fields()...)...); err != nil { return err } + if (mission.offer.definition.RewardItem != 0 || mission.offer.definition.RewardQuality != 0) && + !gamedata.ItemQualitySupported(mission.offer.definition.RewardItem, mission.offer.definition.RewardQuality) { + return fmt.Errorf("mission %d has unsupported item reward", mission.id) + } if _, err := decodeMissionLayout(mission.layout); err != nil { return fmt.Errorf("mission %d layout: %w", mission.id, err) } diff --git a/server/shops.go b/server/shops.go @@ -408,26 +408,7 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { } // Deliver first-free rows in the same order as the durable allocation. for _, item := range purchased { - // The native first-free sentinel creates a row with the live identity. - if item.Type == 51018 || item.isPortableContainer() { - item.Slot = 111 - var packet []byte - if item.isPortableContainer() { - packet = backpackPacket(player.id, player.playfield, item, 104) - } else { - packet = weaponPacket(player.id, player.playfield, item, 104) - } - if err := client.send(packet); err != nil { - return err - } - continue - } - var body []byte - low, high := item.templateIDs() - for _, value := range []uint32{low, high, item.Quality, uint32(item.Count)} { - body = binary.BigEndian.AppendUint32(body, value) - } - if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, body)); err != nil { + if err := client.send(inventoryAdditionPacket(player, item)); err != nil { return err } } diff --git a/server/world.sql b/server/world.sql @@ -233,6 +233,8 @@ CREATE TABLE IF NOT EXISTS missions ( objective_item INTEGER NOT NULL, credits INTEGER NOT NULL, experience INTEGER NOT NULL, + reward_item INTEGER NOT NULL, + reward_quality INTEGER NOT NULL, expires_at DATETIME NOT NULL, world_id INTEGER NOT NULL UNIQUE CHECK (world_id BETWEEN 65536 AND 4294967295), layout BLOB NOT NULL,