aorecomp

Anarchy Online classic in the browser

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


commit 4021c16555c684e7af96c427b3a3259c30b8a72f
parent 8d5a92e9b348a0ef1a71bd9fe33c7b104a52cc92
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 21:52:39 +0000

Settle return-item missions atomically at their issuing booth

Diffstat:
MTODO.md | 40++++++++++++++++++++++++++++------------
Mdocs/mission-objectives.md | 95++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mdocs/mission-retirement.md | 19++++++++++++++-----
Mserver/gamedata/missions.yaml | 2++
Mserver/item_database.go | 27+++++++++++++++++++++++----
Mserver/main.go | 5++++-
Aserver/mission_completion.go | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_completion_test.go | 449+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/mission_entrance.go | 2+-
Mserver/mission_offers.go | 4++--
Mserver/mission_retirement.go | 124+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mserver/missions.go | 5+++--
Mserver/users.go | 4+++-
Mserver/world.sql | 3++-
14 files changed, 762 insertions(+), 98 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -60,7 +60,9 @@ tool funds; ordinary funding and higher-QL recipe rules remain open. See 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; objective completion and rewards remain open. +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. 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. @@ -1518,7 +1520,8 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). poses and correct owners without applying observer yaw twice. GPU WASM verifies normal acceptance, real exterior entry, both rooms, reconnect and exit without substituting client world packets. The fixed prototype has open native - room links, no enemies and no completion rewards. The approach volume + 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 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. @@ -1548,11 +1551,16 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). contract association and support bound-key entry; native destination metadata remains unimplemented. Cover held, banked, traded, deleted and reclaimed keys; possession of an unrelated template28577 must never admit a player to another mission. -- [ ] [P0] Complete one mission objective. Check: a chosen target or object completes - the mission once, with the expected reward. - Commit completion with XP, credits and any item reward atomically through the - shared progression/inventory paths. Verify full inventory, duplicate completion, - failed writes/commit, disconnect and restart without lost or repeated rewards. +- [x] Complete the fixed return-item objective for its authored cash reward. + The exact spawned book must be used on the original issuing booth through + native action5; a matching template or remote journal action84 cannot redeem it. + Cash, objective consumption, bound-key revocation and completion commit together. + Keep completed private worlds and occupants through the original deadline, + 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. + See [mission settlement](docs/mission-objectives.md#return-item-settlement). - [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. @@ -1568,11 +1576,19 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). effects. The original book's right-click emits GenericCmd action3, while its explicit R/Pick Up emits InventoryMove; preserve that distinction and resolve actual instances before the existing type51005 terminal handling. -- [ ] [P0] Recover objective completion and token/XP eligibility rules. Action19 - matches the objective item's template/QL, but its pickup/inspection/return - trigger remains unverified. The original offer details qualify XP with - "Which you get when you receive a token." Establish that rule before settling - rewards; an arbitrary copy of the objective item must not complete a contract. +- [ ] [P0] Recover token/XP eligibility and implement atomic eligible mission + rewards. The original offer details qualify XP with "Which you get when you + 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, + 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; + banked, unknown and other players' items must stay ineligible. +- [ ] [P2] Recover original completed-instance lifetime and re-entry policy. The + fixed contract keeps existing occupants until its original deadline while + revoking all bound keys; no separate invented timer is introduced. - [x] Abandon an accepted starter contract. Check: the native journal and bound key instances retire atomically without rewards or changes to another owner's contract. Native QuestIIR/version1/action5 follows the original RemoveQuest diff --git a/docs/mission-objectives.md b/docs/mission-objectives.md @@ -58,30 +58,64 @@ Abandonment and expiry destroy remaining floor items with their assignment. Already collected books retain ordinary inventory ownership. Rewards and objective completion are deliberately separate from this ownership transfer. -## Remaining completion rules - -Native `QuestAction_t` action19 matches item template endpoints and QL in -`client/game/kkr.dll/lifted-0057.c`, `sub_360C5960`. Its observed caller belongs -to action84, UseItemOnMission, rather than proving that any book pickup completes -the current contract. The fixed offer's displayed Retrieve label does not -establish whether it corresponds to a historical find-item or return-item -contract. Arbitrary copies of40822 must never redeem an accepted contract. +## Return-item settlement + +The fixed authored contract now explicitly asks for return to its issuing booth. +It is a return-item reconstruction, rather than proof that all native action19 +contracts have this trigger. Action19 itself matches template endpoints and QL; +find-item, inspect and return-item server policies remain distinct. + +With the book held on the cursor, right-clicking the actual booth emits +GenericCmd0x52526858 action5 (UseItemOnItem), data version0, local character +identity, source104/main-inventory slot and target56001/booth ID. Right-clicking +the journal instead emits action84 (UseItemOnMission), target56003/quest ID. +That remote action is denied for this return-item contract. Native requests from +both interactions were captured without WebSocket changes. Raw14.9.1 kkr.dll +N3Msg_UseItemOnItem0x1002a8b0 and N3Msg_UseItemOnMission0x1002c880 independently +confirm the distinct producers. + +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. + +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 +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 +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. + +Completion removes the active journal entry but retains the private assignment, +layout and allocated-objective identity for existing occupants and cold loading. +It does not evacuate players or respawn the book. All keys are revoked and the +next accepted contract receives a separate world. The completed world retires +at its original deadline, evacuating remaining online/offline occupants without +an expired-contract message or another reward. This deadline retention is a +provisional reconstruction; exact original completed-world lifetime and re-entry +policy remain unknown. The original mission details condition displayed XP on receiving a token. [Funcom's14.0 release notes, republished in2002](https://www.gamereactor.no/anarchy-online-oppdaterer-til-v140/) state that token chance rises with kills, without recovering the exact server -formula. The empty prototype therefore does not award unconditional100XP. -The20-credit amount is also authored reconstruction data; completion settlement -has not yet been connected. +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. [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. It also describes killing a mission target after completing find-person, supporting continued occupancy after success. This is near-period player -evidence, not an original14.9.1 server capture. Completion settlement/key -revocation must be separate from abandonment's immediate occupant evacuation. -Exact XP/token eligibility, neutral exceptions and completed-world lifetime -remain explicit fidelity work. +evidence, not an original14.9.1 server capture. ## Verification @@ -111,3 +145,34 @@ A cold server restart also restores the private world, journal and all three inventory identities with no floor-item creation packet. Both ordinary and cold runs have no page exceptions or adapter failures; existing unattributed HTTP404 console messages are retained in the logs rather than counted as game crashes. + +Settlement research, original producer/consumer evidence and native hand-in +captures are retained in `local/mission-completion-research/`. Go settlement +checks cover malformed/forged/remote requests, arbitrary objective copies, +range/vertical/world gates, expired/stale/dead/busy clients, full inventory, +missing keys, exact credit limit, duplicate/concurrent requests, output failure, +copied bank keys, online/offline guests, unrelated and key-bearing trades, +retained-world cold loading, a separate next assignment and deadline evacuation. +Faults cover aborted/ignored item, placement, key, cash and completion writes, +late completion/objective/cash rewrites and deferred commit failure, with retry. + +The settlement GPU WASM run accepts the actual offer, enters through the +original exterior, walks to the book, picks it up with R and returns through +the native exit. Only public booth/door approach positions and initial5-credit +funds are arranged through the control panel; objectives, keys and settlement +are ordinary gameplay requests. Remote journal submission is denied. Holding +the exact book and right-clicking its issuing booth displays "Mission +accomplished.", empties the journal/inventory immediately and changes credits +from4 to24. Captured replies establish success ACK, both slot removals, cash +and QuestEvent2 in that order. Page reconnect and cold server/client restart +retain24 credits, XP0, no owned items and no journal replay or second reward. +A second ordinary acceptance costs one credit and allocates world65537, +key3 and floor book4, independently of completed world65536/book2. + +The broad Go regression passes217 top-level tests/1166 results, with focused +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. diff --git a/docs/mission-retirement.md b/docs/mission-retirement.md @@ -6,6 +6,14 @@ the contract and every item instance bound to it, then publish inventory changes and the native journal removal. Retirement grants no credits, XP or completion rewards. It frees the one-training-mission limit for the next assignment. +Completion shares the bound-item cleanup transaction but preserves its private +world and occupants. It consumes the submitted objective and pays cash, then +removes the active journal while retaining a completed assignment until the +original deadline. Cleanup at that deadline evacuates occupants without sending +an expired-contract notification for the completed journal. See +[return-item settlement](mission-objectives.md#return-item-settlement) for the +native action, transaction and provisional lifetime policy. + ## Native request and reply Original14.9.1 `kkr.dll`, SHA256 @@ -130,9 +138,10 @@ mission key and other mission items, without establishing abandonment behavior: [period report](https://forums-archive.anarchy-online.com/showthread.php?9198-Overflow-inventory=). Do not treat these as proof for14.9.1 abandonment or copied-key edge cases. -Private interior allocation/entry and objective completion remain unimplemented. -Their eventual instance lifecycle must join retirement; the current contract's -exterior entrance is not a private world instance. Destination metadata and -native key duplication also remain open. The fixed narrative, rewards and -48-hour duration remain provisional as documented in +Private interior allocation/entry, bound floor objectives and return-item cash +settlement now share this lifecycle. Abandonment and deadline retirement remove +remaining floor items and evacuate occupants atomically; collected books survive +abandonment, while successful hand-in consumes its exact objective. Destination +metadata and native key duplication remain open. The fixed narrative, rewards +and48-hour duration remain provisional as documented in [mission offers](mission-offers.md). diff --git a/server/gamedata/missions.yaml b/server/gamedata/missions.yaml @@ -6,6 +6,8 @@ Recover the Blue Book of Secrets Locate the Blue Book of Secrets inside the Surveillance Office and recover it. + Return it to the mission booth where you accepted this contract. Pick up the + book in your inventory and use it on that booth to collect your reward. The entrance is in Omni-1 Entertainment Backyard 1, near the mission booth. playfield: 3000 entrance: 3221228472 diff --git a/server/item_database.go b/server/item_database.go @@ -194,8 +194,19 @@ func (server *server) persistItems_locked(store itemStore) error { } if store.updatedMission != nil { mission := store.updatedMission - if err := updateRecord(tx, "missions", mission.id, "objective_id", []any{mission.objective}); err != nil { - return err + var savedID uint32 + if err := tx.QueryRow("UPDATE missions SET objective_id=?, completed=? WHERE id=? AND owner_id=? AND completed=0 RETURNING id", + mission.objective, mission.completed, mission.id, mission.owner).Scan(&savedID); err != nil { + return fmt.Errorf("update mission %d: %w", mission.id, err) + } + if mission.completed { + var remaining int + if err := tx.QueryRow("SELECT count(*) FROM mission_keys WHERE mission_id=?", mission.id).Scan(&remaining); err != nil { + return err + } + if remaining != 0 { + return fmt.Errorf("completed mission %d retains bound keys", mission.id) + } } } if store.removedMission != nil { @@ -247,8 +258,16 @@ func (server *server) persistItems_locked(store itemStore) error { } } if store.updatedMission != nil { - if err := tx.QueryRow("SELECT id FROM missions WHERE id=? AND objective_id=?", store.updatedMission.id, store.updatedMission.objective).Scan(&savedID); err != nil { - return fmt.Errorf("mission objective allocation was not saved: %w", err) + 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 { + return fmt.Errorf("mission update was not saved: %w", err) + } + mission := store.updatedMission + if mission.completed { + if err := tx.QueryRow(`SELECT id FROM players WHERE id=? AND credits=? + AND NOT EXISTS (SELECT 1 FROM mission_keys WHERE mission_id=?) + 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 err := tx.Commit(); err != nil { diff --git a/server/main.go b/server/main.go @@ -536,7 +536,10 @@ func (server *server) serveWorldClient(client *worldClient) error { } case 0x52526858: var err error - if len(body) == 56 && binary.BigEndian.Uint32(body[24:28]) == 5 { + if len(body) == 56 && (binary.BigEndian.Uint32(body[24:28]) == 5 && binary.BigEndian.Uint32(body[48:52]) == 56001 || + binary.BigEndian.Uint32(body[24:28]) == 84 && binary.BigEndian.Uint32(body[48:52]) == 56003) { + err = server.handleMissionReturn(client, body) + } else if len(body) == 56 && binary.BigEndian.Uint32(body[24:28]) == 5 { err = server.handleReload(client, body) } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 101 || binary.BigEndian.Uint32(body[40:44]) == 102 || binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 107 || binary.BigEndian.Uint32(body[40:44]) == 51017) { err = server.handleOwnedItemUse(client, body) diff --git a/server/mission_completion.go b/server/mission_completion.go @@ -0,0 +1,81 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "slices" + "time" +) + +func missionCompletionPacket(owner, id uint32) []byte { + var body []byte + for _, word := range []uint32{1, 56003, id, 2} { + body = binary.BigEndian.AppendUint32(body, word) + } + return n3Packet(0x5f2e1b19, 50000, owner, body) +} + +func (server *server) handleMissionReturn(client *worldClient, body []byte) error { + if len(body) != 56 || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[28:32]) != 0 || + binary.BigEndian.Uint32(body[32:36]) != 50000 || binary.BigEndian.Uint32(body[36:40]) != client.id { + return nil + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id { + server.mutex.Unlock() + return nil + } + sequence := binary.BigEndian.Uint32(body[20:24]) + if sequence <= client.useSequence { + server.mutex.Unlock() + return nil + } + client.useSequence = sequence + reply := slices.Clone(body[16:]) + binary.BigEndian.PutUint32(reply, 2) + + // The authored return-item contract names its issuing booth and exact spawned item. + index := slices.IndexFunc(player.missions, func(mission acceptedMission) bool { + return !mission.completed && mission.offer.booth == binary.BigEndian.Uint32(body[52:56]) && time.Now().Before(mission.expiresAt) + }) + item := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { + return item.Slot >= 64 && item.Slot < 94 && binary.BigEndian.Uint32(body[40:44]) == 104 && item.Slot == binary.BigEndian.Uint32(body[44:48]) + }) + booth, exists := gamedata.MissionBooths[binary.BigEndian.Uint32(body[52:56])] + accepted := binary.BigEndian.Uint32(body[24:28]) == 5 && binary.BigEndian.Uint32(body[48:52]) == 56001 && + index >= 0 && item >= 0 && exists && booth.Playfield == player.playfield && + client.trade == nil && client.shop == nil && client.bank == nil && client.equipment == nil && client.nanoCast == nil + if accepted { + mission, objective := player.missions[index], player.inventory.Items[item] + position := predictedPosition_locked(player, time.Now()) + x, y, z := position[0]-booth.Position[0], position[1]-booth.Position[1], position[2]-booth.Position[2] + accepted = mission.objective != 0 && objective.ID == mission.objective && objective.Template == mission.offer.definition.ObjectiveItem && + 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 { + server.mutex.Unlock() + return client.send(n3Packet(0x52526858, 50000, client.id, reply)) + } + + // Empty prototypes have no qualifying kills for the separately conditional XP/token. + mission := player.missions[index] + updates := make(map[*worldClient][][]byte) + if _, err := server.endMission_locked(mission, true, updates); err != nil { + server.mutex.Unlock() + return err + } + binary.BigEndian.PutUint32(reply, 1) + updates[client] = append([][]byte{n3Packet(0x52526858, 50000, client.id, reply)}, updates[client]...) + cash := binary.BigEndian.AppendUint32(nil, 61) + cash = binary.BigEndian.AppendUint32(cash, player.inventory.Credits) + updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, client.id, cash), missionCompletionPacket(client.id, mission.id)) + server.mutex.Unlock() + server.sendCombatUpdates(updates) + return nil +} diff --git a/server/mission_completion_test.go b/server/mission_completion_test.go @@ -0,0 +1,449 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "reflect" + "slices" + "sync" + "testing" + "time" +) + +func missionReturnRequest(sequence uint32) []byte { + var body []byte + for _, word := range []uint32{0, sequence, 5, 0, 50000, 1, 104, 66, 56001, 3221228472} { + body = binary.BigEndian.AppendUint32(body, word) + } + return n3Packet(0x52526858, 50000, 1, body)[20:] +} + +func newMissionReturnWorld(t *testing.T) (*server, *worldClient, *combatTestConn) { + t.Helper() + world, client, output := enteredObjectiveWorld(t) + if err := world.handleInventory(client, worldPickupRequest(1, 3)); err != nil { + t.Fatal(err) + } + destination := world.characters[1].userData() + destination.Playfield, destination.Position = 3000, gamedata.MissionBooths[3221228472].Position + if err := world.updateUser_locked(destination); err != nil { + t.Fatal(err) + } + world.clients[1], client.ready, client.loading = client, true, false + output.packets = nil + return world, client, output +} + +func TestMissionReturnSettlesOnceAndSurvivesRestart(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + layout := bytes.Clone(world.missionExpiry[0].layout) + + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + player := cold.characters[1] + var keys, items int + if err := cold.db.QueryRow("SELECT count(*) FROM mission_keys").Scan(&keys); err != nil { + t.Fatal(err) + } + if err := cold.db.QueryRow("SELECT count(*) FROM items WHERE id IN (2,3)").Scan(&items); err != nil { + t.Fatal(err) + } + + if player.inventory.Credits != 24 || player.experience != 0 || len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != 1 || + len(player.missions) != 0 || len(cold.missionExpiry) != 1 || !cold.missionExpiry[0].completed || keys != 0 || items != 0 || + cold.missionExpiry[0].objective != 3 || !bytes.Equal(layout, cold.missionExpiry[0].layout) || world.geometry.mission(65536) == nil || + !reflect.DeepEqual(player.inventory, world.characters[1].inventory) { + t.Fatal("settlement lost cash, retained credentials or retired the occupied world", player.inventory, cold.missionExpiry) + } + if len(output.packets) != 5 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 1 || + !bytes.Equal(output.packets[4], targetPacket(missionCompletionPacket(1, 2))) || + binary.BigEndian.Uint32(output.packets[3][29:33]) != 61 || binary.BigEndian.Uint32(output.packets[3][33:37]) != 24 { + t.Fatal("incorrect acknowledgement, reward or completion event", output.packets) + } + + for _, sequence := range []uint32{1, 2} { + if err := world.handleMissionReturn(client, missionReturnRequest(sequence)); err != nil { + t.Fatal(err) + } + } + if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil { + t.Fatal(err) + } + if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil { + t.Fatal(err) + } + cold = reloadMissionEntranceWorld(t) + + if len(cold.characters[1].missions) != 1 || cold.characters[1].missions[0].world != 65537 || + len(cold.missionExpiry) != 2 || cold.characters[1].inventory.Credits != 23 || cold.characters[1].missions[0].id != 4 { + t.Fatal("completion paid twice or prevented an independent next contract", cold.characters[1].missions, cold.missionExpiry) + } + + output.packets = nil + world.advanceMissions(world.missionExpiry[0].expiresAt) + cold = reloadMissionEntranceWorld(t) + + if len(cold.missionExpiry) != 1 || len(cold.characters[1].missions) != 1 || cold.characters[1].missions[0].id != 4 || + cold.characters[1].inventory.Credits != 23 || len(output.packets) != 0 { + t.Fatal("completed-world cleanup retired or notified the newer active contract") + } +} + +func TestMissionReturnRejectsUnavailableAndForgedSubmissions(t *testing.T) { + for _, scenario := range []string{"short", "long", "status", "version", "subject type", "subject id", "actor type", "actor id", "source page", "source slot", "target type", "other booth", "remote journal", "sequence", "expired", "wrong item", "quality", "template", "uncollected", "far", "vertical", "other world", "dead", "loading", "not ready", "stale", "legacy", "trade", "shop", "bank", "equipment", "casting", "cash overflow"} { + t.Run(scenario, func(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + player := world.characters[1] + request := missionReturnRequest(1) + switch scenario { + case "short": + request = request[:55] + case "long": + request = append(request, 0) + case "status": + binary.BigEndian.PutUint32(request[16:], 1) + case "version": + binary.BigEndian.PutUint32(request[28:], 1) + case "subject type": + binary.BigEndian.PutUint32(request[4:], 51005) + case "subject id": + binary.BigEndian.PutUint32(request[8:], 2) + case "actor type": + binary.BigEndian.PutUint32(request[32:], 51005) + case "actor id": + binary.BigEndian.PutUint32(request[36:], 2) + case "source page": + binary.BigEndian.PutUint32(request[40:], 105) + case "source slot": + binary.BigEndian.PutUint32(request[44:], 64) + case "target type": + binary.BigEndian.PutUint32(request[48:], 56006) + case "other booth": + binary.BigEndian.PutUint32(request[52:], 3221228509) + case "remote journal": + binary.BigEndian.PutUint32(request[24:], 84) + binary.BigEndian.PutUint32(request[48:], 56003) + binary.BigEndian.PutUint32(request[52:], 2) + case "sequence": + client.useSequence = 1 + case "expired": + player.missions[0].expiresAt = time.Now().Add(-time.Second) + case "wrong item": + player.missions[0].objective = 99 + case "quality": + player.inventory.Items[2].Quality = 2 + case "template": + player.inventory.Items[2].Template = 121567 + case "uncollected": + player.missions[0].objective = 0 + case "far": + player.position[0] += 5.01 + case "vertical": + player.position[1] += 5.01 + case "other world": + player.playfield = 65536 + case "dead": + player.health = 0 + case "loading": + client.loading = true + case "not ready": + client.ready = false + case "stale": + world.clients[1] = &worldClient{id: 1} + case "legacy": + client.target = false + case "trade": + client.trade = &playerTrade{} + case "shop": + client.shop = &shopTrade{} + case "bank": + client.bank = &bankSession{} + case "equipment": + client.equipment = &equipmentMove{} + case "casting": + client.nanoCast = &nanoCast{} + case "cash overflow": + player.inventory.Credits = 999999981 + } + before := player.inventory + + if err := world.handleMissionReturn(client, request); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if !reflect.DeepEqual(before, player.inventory) || len(player.missions) != 1 || len(cold.characters[1].missions) != 1 || + cold.characters[1].inventory.Credits != 4 || len(cold.items) != 3 || cold.missionExpiry[0].completed || len(output.packets) > 1 || + len(output.packets) == 1 && binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 { + t.Fatal("denied submission changed ownership or paid a reward", output.packets) + } + }) + } +} + +func TestMissionReturnAcceptsFullInventoryMissingKeyAndCreditCeiling(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + player := world.characters[1] + for range 27 { + if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted { + t.Fatal("fill inventory", granted, err) + } + } + if _, err := world.db.Exec("DELETE FROM mission_keys"); err != nil { + t.Fatal(err) + } + inventory := player.inventory + inventory.Credits = 999999980 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + output.packets = nil + + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if cold.characters[1].inventory.Credits != 1000000000 || len(cold.characters[1].inventory.Items) != 29 || + !cold.missionExpiry[0].completed || len(output.packets) != 4 { + t.Fatal("missing key, full inventory or exact credit limit blocked a valid return", cold.characters[1].inventory) + } +} + +func TestMissionReturnRollsBackEverySettlementWriteAndRetries(t *testing.T) { + for _, scenario := range []struct{ name, sql string }{ + {"item abort", "CREATE TRIGGER fail_return BEFORE DELETE ON items BEGIN SELECT RAISE(ABORT,'settlement'); END"}, + {"item ignored", "CREATE TRIGGER fail_return BEFORE DELETE ON items BEGIN SELECT RAISE(IGNORE); END"}, + {"placement ignored", "CREATE TRIGGER fail_return BEFORE DELETE ON item_locations BEGIN SELECT RAISE(IGNORE); END"}, + {"key ignored", "CREATE TRIGGER fail_return BEFORE DELETE ON mission_keys BEGIN SELECT RAISE(IGNORE); END"}, + {"completion abort", "CREATE TRIGGER fail_return BEFORE UPDATE OF completed ON missions BEGIN SELECT RAISE(ABORT,'settlement'); END"}, + {"completion ignored", "CREATE TRIGGER fail_return BEFORE UPDATE OF completed ON missions BEGIN SELECT RAISE(IGNORE); END"}, + {"cash ignored", "CREATE TRIGGER fail_return BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(IGNORE); END"}, + {"late completion rewrite", "CREATE TRIGGER fail_return AFTER UPDATE OF last_item_id ON world BEGIN UPDATE missions SET completed=0; END"}, + {"late objective rewrite", "CREATE TRIGGER fail_return AFTER UPDATE OF last_item_id ON world BEGIN UPDATE missions SET objective_id=0; END"}, + {"late cash rewrite", "CREATE TRIGGER fail_return AFTER UPDATE OF last_item_id ON world BEGIN UPDATE players SET credits=4; END"}, + {"commit", "CREATE TABLE pending_return (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_return AFTER UPDATE OF completed ON missions BEGIN INSERT INTO pending_return VALUES(999999); END"}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + 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 || !reflect.DeepEqual(before, world.characters[1].inventory) || + !reflect.DeepEqual(before, cold.characters[1].inventory) || len(world.characters[1].missions) != 1 || + world.missionExpiry[0].completed || cold.missionExpiry[0].completed || len(cold.items) != 3 { + t.Fatal("failed settlement published reward, removals or completion", failure) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_return"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionReturn(client, missionReturnRequest(2)); err != nil { + t.Fatal(err) + } + cold = reloadMissionEntranceWorld(t) + + if len(cold.characters[1].missions) != 0 || cold.characters[1].inventory.Credits != 24 || len(cold.items) != 1 || len(output.packets) != 5 { + t.Fatal("retry did not settle exactly once") + } + }) + } +} + +func TestMissionReturnConcurrentDuplicatesPayOnce(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + errors := make(chan error, 2) + var workers sync.WaitGroup + + for range 2 { + workers.Add(1) + go func() { defer workers.Done(); errors <- world.handleMissionReturn(client, missionReturnRequest(1)) }() + } + workers.Wait() + close(errors) + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + + if world.characters[1].inventory.Credits != 24 || len(world.characters[1].missions) != 0 || len(output.packets) != 5 { + t.Fatal("duplicate submission paid or completed twice", output.packets) + } +} + +func TestMissionReturnRejectsAnIdenticalUnboundBook(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + if granted, err := world.grantItem_locked(world.characters[1], 40822); err != nil || !granted { + t.Fatal("create identical book", granted, err) + } + request := missionReturnRequest(1) + binary.BigEndian.PutUint32(request[44:], 67) + output.packets = nil + + if err := world.handleMissionReturn(client, request); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if len(cold.characters[1].missions) != 1 || cold.characters[1].inventory.Credits != 4 || len(cold.items) != 4 || + cold.missionExpiry[0].objective != 3 || len(output.packets) != 1 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 { + t.Fatal("an unbound matching template redeemed the contract", output.packets) + } +} + +func TestMissionReturnCompetesAtomicallyWithAbandonmentAndExpiry(t *testing.T) { + world, client, _ := newMissionReturnWorld(t) + deadline := world.missionExpiry[0].expiresAt + errors := make(chan error, 2) + var workers sync.WaitGroup + + workers.Add(3) + go func() { defer workers.Done(); errors <- world.handleMissionReturn(client, missionReturnRequest(1)) }() + go func() { + defer workers.Done() + errors <- world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + }() + go func() { defer workers.Done(); world.advanceMissions(deadline) }() + workers.Wait() + close(errors) + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + cold := reloadMissionEntranceWorld(t) + _, book := cold.items[3] + + if len(cold.missionExpiry) != 0 || len(cold.characters[1].missions) != 0 || + book && (cold.characters[1].inventory.Credits != 4 || len(cold.items) != 2) || + !book && (cold.characters[1].inventory.Credits != 24 || len(cold.items) != 1) { + t.Fatal("competing lifecycle requests partially paid or consumed the objective", cold.characters[1].inventory) + } +} + +func TestMissionReturnOutputFailureKeepsCommittedSettlement(t *testing.T) { + world, client, _ := newMissionReturnWorld(t) + client.conn = &failingCombatConn{} + + world.handleMissionReturn(client, missionReturnRequest(1)) + cold := reloadMissionEntranceWorld(t) + + if cold.characters[1].inventory.Credits != 24 || len(cold.characters[1].missions) != 0 || len(cold.items) != 1 || !cold.missionExpiry[0].completed { + t.Fatal("failed output reversed committed settlement") + } +} + +func TestMissionReturnPreservesGuestsUntilOriginalDeadline(t *testing.T) { + world, client, output := newMissionReturnWorld(t) + deadline := world.missionExpiry[0].expiresAt + for _, id := range []uint32{2, 3} { + data := world.characters[1].userData() + data.ID, data.Name, data.Playfield, data.Position = id, map[uint32]string{2: "Guest", 3: "Offline"}[id], 65536, [3]float32{15, .011, 20} + world.characters[id] = data.character() + if err := world.saveUser_locked(world.characters[id]); err != nil { + t.Fatal(err) + } + } + guestOutput := &combatTestConn{} + guest := &worldClient{id: 2, conn: guestOutput, target: true, ready: true} + world.clients[2] = guest + inventory := world.characters[2].inventory + inventory.LastID = 4 + inventory.Bank = []ownedItem{{ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 8, Count: 1}} + if err := world.saveInventory_locked(world.characters[2], inventory); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("INSERT INTO mission_keys VALUES (4, 2)"); err != nil { + t.Fatal(err) + } + guest.bank = &bankSession{} + output.packets = nil + + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + packets, err := cold.playerPlayfieldPacket_locked(cold.characters[2]) + if err != nil { + t.Fatal(err) + } + + if cold.characters[2].playfield != 65536 || cold.characters[3].playfield != 65536 || world.clients[2] != guest || + len(packets) == 0 || cold.geometry.mission(65536) == nil || len(cold.worldItems) != 0 || len(cold.characters[2].inventory.Bank) != 0 || + len(guestOutput.packets) != 1 || !bytes.Equal(guestOutput.packets[0][16:], targetPacket(characterActionPacket(2, [5]uint32{112, 105, 8}))[16:]) { + t.Fatal("completion evacuated guests, retained a copied key or lost private replay", cold.characters[2].playfield, cold.characters[3].playfield, world.clients[2] == guest, len(packets), cold.geometry.mission(65536) != nil, cold.worldItems, cold.characters[2].inventory.Bank, guestOutput.packets) + } + + output.packets, guestOutput.packets = nil, nil + world.advanceMissions(deadline) + cold = reloadMissionEntranceWorld(t) + + if len(cold.missionExpiry) != 0 || cold.geometry.mission(65536) != nil || cold.characters[2].playfield != 3000 || + cold.characters[3].playfield != 3000 || cold.characters[1].inventory.Credits != 24 || len(output.packets) != 0 || len(guestOutput.packets) != 2 { + t.Fatal("completed-world deadline failed to evacuate guests or sent a false expiry/reward", output.packets, guestOutput.packets) + } +} + +func TestMissionReturnCancelsCopiedKeyTradeOnlyAfterCommit(t *testing.T) { + for _, bound := range []bool{false, true} { + t.Run(map[bool]string{false: "unrelated", true: "copied key"}[bound], func(t *testing.T) { + world, owner, output := newMissionReturnWorld(t) + for _, id := range []uint32{2, 3} { + data := world.characters[1].userData() + data.ID, data.Name, data.Playfield, data.Position = id, map[uint32]string{2: "Guest", 3: "Trader"}[id], 65536, [3]float32{15, .011, 20} + world.characters[id] = data.character() + if err := world.saveUser_locked(world.characters[id]); err != nil { + t.Fatal(err) + } + world.clients[id] = &worldClient{id: id, conn: &combatTestConn{}, target: true, ready: true} + } + inventory := world.characters[2].inventory + inventory.LastID = 4 + key := ownedItem{ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 64, Count: 1} + inventory.Items = []ownedItem{key} + if err := world.saveInventory_locked(world.characters[2], inventory); err != nil { + t.Fatal(err) + } + if bound { + if _, err := world.db.Exec("INSERT INTO mission_keys VALUES (4, 2)"); err != nil { + t.Fatal(err) + } + } + trade := &playerTrade{clients: [2]*worldClient{world.clients[2], world.clients[3]}, items: [2]map[uint32]ownedItem{{0: key}, {}}} + world.clients[2].trade, world.clients[3].trade = trade, trade + if _, err := world.db.Exec("CREATE TRIGGER fail_return BEFORE UPDATE OF completed ON missions BEGIN SELECT RAISE(ABORT,'completion'); END"); err != nil { + t.Fatal(err) + } + output.packets = nil + + failure := world.handleMissionReturn(owner, missionReturnRequest(1)) + + if failure == nil || len(output.packets) != 0 || world.clients[2].trade != trade || world.clients[3].trade != trade || len(world.characters[2].inventory.Items) != 1 { + t.Fatal("failed completion published a trade cancellation", failure) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_return"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionReturn(owner, missionReturnRequest(2)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if (world.clients[2].trade == nil) != bound || (world.clients[3].trade == nil) != bound || + world.characters[2].playfield != 65536 || cold.characters[2].playfield != 65536 || + slices.ContainsFunc(cold.characters[2].inventory.Items, func(item ownedItem) bool { return item.ID == 4 }) == bound { + t.Fatal("completion retained a copied credential or cancelled an unrelated trade", world.clients[2].trade == nil, world.clients[3].trade == nil, world.characters[2].playfield, cold.characters[2].playfield, cold.characters[2].inventory.Items) + } + }) + } +} diff --git a/server/mission_entrance.go b/server/mission_entrance.go @@ -138,7 +138,7 @@ func (server *server) missionDestination_locked(player *character, client *world now := time.Now() for index := range server.missionExpiry { mission := &server.missionExpiry[index] - if mission.offer.definition.Playfield == player.playfield && now.Before(mission.expiresAt) && near(mission.offer.definition.Position) { + if !mission.completed && mission.offer.definition.Playfield == player.playfield && now.Before(mission.expiresAt) && near(mission.offer.definition.Position) { candidates = append(candidates, mission) } } diff --git a/server/mission_offers.go b/server/mission_offers.go @@ -53,8 +53,8 @@ func appendMissionQuest(body []byte, offer missionOffer, id, owner, remaining ui binary.BigEndian.PutUint32(action[0:4], 19) binary.BigEndian.PutUint32(action[4:8], offer.definition.ObjectiveItem) binary.BigEndian.PutUint32(action[8:12], offer.definition.ObjectiveItem) - binary.BigEndian.PutUint32(action[12:16], 1) - binary.BigEndian.PutUint32(action[16:20], 1) + binary.BigEndian.PutUint32(action[12:16], *gamedata.ItemTemplates[offer.definition.ObjectiveItem].Quality) + binary.BigEndian.PutUint32(action[16:20], *gamedata.ItemTemplates[offer.definition.ObjectiveItem].Quality) binary.BigEndian.PutUint32(action[108:112], 40016) binary.BigEndian.PutUint32(action[112:116], offer.definition.Playfield) for index, position := range offer.definition.Position { diff --git a/server/mission_retirement.go b/server/mission_retirement.go @@ -45,7 +45,7 @@ func (server *server) handleMissionRemoval(client *worldClient, body []byte) err return nil } updates := make(map[*worldClient][][]byte) - departures, err := server.retireMission_locked(player.missions[index], updates) + departures, err := server.endMission_locked(player.missions[index], false, updates) server.mutex.Unlock() if err != nil { return err @@ -58,20 +58,20 @@ func (server *server) handleMissionRemoval(client *worldClient, body []byte) err return nil } -func (server *server) retireMission_locked(mission acceptedMission, updates map[*worldClient][][]byte) (map[*worldClient][][]byte, error) { +func (server *server) endMission_locked(mission acceptedMission, completed bool, updates map[*worldClient][][]byte) (map[*worldClient][][]byte, error) { // Resolve credentials by instance binding, including copies held by other players. rows, err := server.db.Query("SELECT item_id FROM mission_keys WHERE mission_id=?", mission.id) if err != nil { return nil, err } - keys := make(map[uint32]bool) + removed := make(map[uint32]bool) for rows.Next() { var id uint32 if err := rows.Scan(&id); err != nil { rows.Close() return nil, err } - keys[id] = true + removed[id] = true } if err := rows.Err(); err != nil { rows.Close() @@ -81,16 +81,22 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ return nil, err } - // Restore affected draft trades in the candidate, before removing their keys. + // Submitted objectives and bound credentials retire in the same transaction. + if completed { + removed[mission.objective] = true + } inventories := make(map[uint32]playerInventory) + if completed { + inventories[mission.owner] = server.characters[mission.owner].inventory + } for id, player := range server.characters { - if !player.npc && slices.ContainsFunc(player.inventory.allItems(), func(item ownedItem) bool { return keys[item.ID] }) { + if !player.npc && slices.ContainsFunc(player.inventory.allItems(), func(item ownedItem) bool { return removed[item.ID] }) { inventories[id] = player.inventory } } - hasKey := func(items map[uint32]ownedItem) bool { + hasRemovedItem := func(items map[uint32]ownedItem) bool { for _, item := range items { - if keys[item.ID] { + if removed[item.ID] { return true } } @@ -98,11 +104,11 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ } shops, trades := make(map[*worldClient]bool), make(map[*playerTrade]bool) for _, client := range server.clients { - if client.shop != nil && (hasKey(client.shop.items) || server.characters[client.id].playfield == mission.world) { + if client.shop != nil && (hasRemovedItem(client.shop.items) || !completed && server.characters[client.id].playfield == mission.world) { shops[client] = true inventories[client.id], _ = restoredTradeInventory(server.characters[client.id].inventory, client.shop.items, tradeSlots(client.shop.items)) } - if client.trade != nil && !trades[client.trade] && (hasKey(client.trade.items[0]) || hasKey(client.trade.items[1]) || server.characters[client.trade.clients[0].id].playfield == mission.world || server.characters[client.trade.clients[1].id].playfield == mission.world) { + if client.trade != nil && !trades[client.trade] && (hasRemovedItem(client.trade.items[0]) || hasRemovedItem(client.trade.items[1]) || !completed && (server.characters[client.trade.clients[0].id].playfield == mission.world || server.characters[client.trade.clients[1].id].playfield == mission.world)) { trades[client.trade] = true for side, participant := range client.trade.clients { inventories[participant.id], _ = restoredTradeInventory(server.characters[participant.id].inventory, client.trade.items[side], tradeSlots(client.trade.items[side])) @@ -132,36 +138,39 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ client := server.clients[id] if client != nil { for _, item := range inventory.Items { - if keys[item.ID] { + if removed[item.ID] { changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 104, item.Slot})) } } if client.bank != nil { for _, item := range inventory.Bank { - if keys[item.ID] { + if removed[item.ID] { changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 105, item.Slot})) } } } for index, handle := range client.backpacks { for _, item := range inventory.Containers[handle.id] { - if keys[item.ID] { + if removed[item.ID] { changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 107, index<<16 | item.Slot})) } } } for index, item := range client.reclaimItems { - if keys[item] { + if removed[item] { changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 106, uint32(index)})) } } } - inventory.Items = slices.DeleteFunc(slices.Clone(inventory.Items), func(item ownedItem) bool { return keys[item.ID] }) - inventory.Bank = slices.DeleteFunc(slices.Clone(inventory.Bank), func(item ownedItem) bool { return keys[item.ID] }) - inventory.Reclaim = slices.DeleteFunc(slices.Clone(inventory.Reclaim), func(item reclaimItem) bool { return keys[item.Item.ID] }) + inventory.Items = slices.DeleteFunc(slices.Clone(inventory.Items), func(item ownedItem) bool { return removed[item.ID] }) + inventory.Bank = slices.DeleteFunc(slices.Clone(inventory.Bank), func(item ownedItem) bool { return removed[item.ID] }) + inventory.Reclaim = slices.DeleteFunc(slices.Clone(inventory.Reclaim), func(item reclaimItem) bool { return removed[item.Item.ID] }) inventory.Containers = maps.Clone(inventory.Containers) for bag, items := range inventory.Containers { - inventory.Containers[bag] = slices.DeleteFunc(slices.Clone(items), func(item ownedItem) bool { return keys[item.ID] }) + inventory.Containers[bag] = slices.DeleteFunc(slices.Clone(items), func(item ownedItem) bool { return removed[item.ID] }) + } + if completed && id == mission.owner { + inventory.Credits += mission.offer.definition.Credits } inventories[id] = inventory store.Players[id] = inventory.references() @@ -169,10 +178,10 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ } for id, record := range store.Items { for _, item := range record.Slots { - if item != nil && keys[*item] { + if item != nil && removed[*item] { record.Slots = maps.Clone(record.Slots) for slot, child := range record.Slots { - if child != nil && keys[*child] { + if child != nil && removed[*child] { record.Slots[slot] = nil } } @@ -183,42 +192,47 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ } corpses := make(map[uint32]bool) for id, items := range store.Corpses { - if slices.ContainsFunc(items, func(item ownedItem) bool { return keys[item.ID] }) { + if slices.ContainsFunc(items, func(item ownedItem) bool { return removed[item.ID] }) { corpses[id] = true - store.Corpses[id] = slices.DeleteFunc(slices.Clone(items), func(item ownedItem) bool { return keys[item.ID] }) + store.Corpses[id] = slices.DeleteFunc(slices.Clone(items), func(item ownedItem) bool { return removed[item.ID] }) } } - for id := range keys { + for id := range removed { delete(store.Items, id) } - for id, item := range store.WorldItems { - if item.mission == mission.id { - delete(store.WorldItems, id) - delete(store.Items, id) - } - } - // Evacuate every occupant in the same transaction that revokes the assignment. - for _, player := range server.characters { - if player.npc || player.playfield != mission.world { - continue - } - destination, err := server.missionReturn_locked(player, &mission) - if err != nil { - return nil, err + if completed { + mission.completed = true + store.updatedMission = &mission + } else { + for id, item := range store.WorldItems { + if item.mission == mission.id { + delete(store.WorldItems, id) + delete(store.Items, id) + } } - updated := destination.character() - updated.inventory = player.inventory - if inventory, changed := inventories[player.id]; changed { - updated.inventory = inventory + // Evacuate every occupant in the same transaction that revokes the assignment. + for _, player := range server.characters { + if player.npc || player.playfield != mission.world { + continue + } + destination, err := server.missionReturn_locked(player, &mission) + if err != nil { + return nil, err + } + updated := destination.character() + updated.inventory = player.inventory + if inventory, changed := inventories[player.id]; changed { + updated.inventory = inventory + } + updated.health, updated.nano, updated.aggDef = player.health, player.nano, player.aggDef + updated.rechargeUntil, updated.nanoRechargeUntil = player.rechargeUntil, player.nanoRechargeUntil + updated.browserTokenHash, updated.resurrectionTerminal = player.browserTokenHash, player.resurrectionTerminal + updated.implantChangesUntil, updated.nextPositionSave = player.implantChangesUntil, player.nextPositionSave + server.prepareUser_locked(player, updated) + store.edited = append(store.edited, updated) } - updated.health, updated.nano, updated.aggDef = player.health, player.nano, player.aggDef - updated.rechargeUntil, updated.nanoRechargeUntil = player.rechargeUntil, player.nanoRechargeUntil - updated.browserTokenHash, updated.resurrectionTerminal = player.browserTokenHash, player.resurrectionTerminal - updated.implantChangesUntil, updated.nextPositionSave = player.implantChangesUntil, player.nextPositionSave - server.prepareUser_locked(player, updated) - store.edited = append(store.edited, updated) - } - store.removedMission = &mission + store.removedMission = &mission + } if err := server.writeItemStore_locked(store); err != nil { return nil, err } @@ -240,12 +254,14 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ changes[client] = append(changes[client], lootInventoryPacket(client.id, server.characters[client.lootCorpse], false)) } for index, item := range client.reclaimItems { - if keys[item] { + if removed[item] { client.reclaimItems[index] = 0 } } } - server.missionExpiry = slices.DeleteFunc(server.missionExpiry, func(other acceptedMission) bool { return other.id == mission.id }) + if !completed { + server.missionExpiry = slices.DeleteFunc(server.missionExpiry, func(other acceptedMission) bool { return other.id == mission.id }) + } for client, packets := range changes { if client.ready && !client.loading { updates[client] = append(updates[client], packets...) @@ -260,7 +276,7 @@ func (server *server) retireMission_locked(mission acceptedMission, updates map[ } player := server.characters[mission.owner] player.missions = slices.DeleteFunc(player.missions, func(other acceptedMission) bool { return other.id == mission.id }) - if server.geometry != nil { + if !completed && server.geometry != nil { server.geometry.removeMission(mission.world) } return departures, nil @@ -273,7 +289,7 @@ func (server *server) expireMissions_locked(now time.Time, updates map[*worldCli index++ continue } - departures, err := server.retireMission_locked(mission, updates) + departures, err := server.endMission_locked(mission, false, updates) if err != nil { return err } @@ -283,7 +299,7 @@ func (server *server) expireMissions_locked(now time.Time, updates map[*worldCli client = leaving } } - if client != nil && (client.ready && !client.loading || departures[client] != nil) { + if !mission.completed && client != nil && (client.ready && !client.loading || departures[client] != nil) { updates[client] = append(updates[client], missionExpiryPacket(mission.owner, mission.id)) } for leaving, packets := range departures { diff --git a/server/missions.go b/server/missions.go @@ -19,16 +19,17 @@ type acceptedMission struct { world uint32 layout []byte objective uint32 + 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" +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" 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.offer.definition.ObjectiveItem, &mission.offer.definition.Credits, &mission.offer.definition.Experience, &mission.expiresAt, &mission.world, &mission.layout, &mission.objective, &mission.completed} } func insertMission(tx *sql.Tx, mission *acceptedMission) error { diff --git a/server/users.go b/server/users.go @@ -167,7 +167,9 @@ func (server *server) loadUsers() error { return err } for _, mission := range server.missionExpiry { - server.characters[mission.owner].missions = append(server.characters[mission.owner].missions, mission) + if !mission.completed { + server.characters[mission.owner].missions = append(server.characters[mission.owner].missions, mission) + } } if err := server.expireMissions_locked(time.Now(), nil); err != nil { return err diff --git a/server/world.sql b/server/world.sql @@ -236,7 +236,8 @@ CREATE TABLE IF NOT EXISTS missions ( expires_at DATETIME NOT NULL, world_id INTEGER NOT NULL UNIQUE CHECK (world_id BETWEEN 65536 AND 4294967295), layout BLOB NOT NULL, - objective_id INTEGER NOT NULL DEFAULT 0 CHECK (objective_id BETWEEN 0 AND 4294967295) + objective_id INTEGER NOT NULL DEFAULT 0 CHECK (objective_id BETWEEN 0 AND 4294967295), + completed INTEGER NOT NULL DEFAULT 0 CHECK (completed IN (0, 1)) ); CREATE TABLE IF NOT EXISTS mission_keys ( item_id INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE,