aorecomp

Anarchy Online classic in the browser

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


commit 7849adfc2db2dff2f8e351a67f55a0412ecc3bf0
parent f56733cc6da549ffbeae840a6ae6c66c1642d3a5
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 03:21:15 +0000

Commit consumable resource gains with charges and cooldowns

Diffstat:
MTODO.md | 14+++++++++++---
Mdocs/nano-kit.md | 15+++++++++------
Mdocs/treatment-kit.md | 9+++++----
Mdocs/world-state.md | 27+++++++++++++++++++++++++++
Aserver/consumable_outcome_test.go | 311+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/inventory.go | 20++++++++++++++++++++
Mserver/inventory_write_test.go | 2+-
Mserver/item_database.go | 15+++++++++++++++
Mserver/item_store.go | 6++++++
Mserver/nano_kit.go | 11++++++-----
Mserver/nano_kit_test.go | 5++++-
Mserver/treatment_kit.go | 7++++---
12 files changed, 419 insertions(+), 23 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -834,9 +834,11 @@ and server restarts. Turn every reproduced bug into a focused regression test. - [ ] Audit consumables and skill locks. Cover self/friendly/invalid targets, resource boundaries, combat and posture restrictions, last-charge removal, overlapping locks, concurrent requests and restart during a lock. - Nano and treatment kits currently commit charges/locks before restoring the - target's nano/health in memory. Commit restoration with the debit so a crash - after success cannot retain charge loss without the resource gain. + Nano and treatment kits now commit the recipient's nano/health with the charge + and cooldown before acknowledgement. Focused regressions cover self/other + targets, first-packet durability, last charges, resource caps, movement cadence, + ignored/failed writes, failed COMMIT, retry and output failure/restart replay. + See `server/consumable_outcome_test.go`; the broader consumable audit remains. - [ ] Audit nano learning and casting. Cover unmet requirements, duplicates, missing resources, interruption/cancellation, invalid or changing targets, recharge boundaries and interaction with queued weapon results. @@ -851,6 +853,12 @@ and server restarts. Turn every reproduced bug into a focused regression test. - [ ] Audit disconnects, retries and failure handling across these features. Cover transport replacement, stale sessions, action replay, database failures and concurrent requests; success must follow the durable significant change. + Reconcile saved posture with native entry state: a patient sat in native + mode 8, then re-entered in mode 3 after a crash/restart while SQLite retained + `sitting=1`. Verify the original entry policy and synchronize the two states + before relying on seated-only item use and regeneration. Capture: + `local/consumable-outcome-research/after-server-restart.json` and + `after-server-start-database.json`. - [x] Coordinate background checkpoints with server shutdown. Check: shutdown commits current durable state and stops simulation/checkpoint writers before closing SQLite; normal restarts produce no late `database is closed` errors. diff --git a/docs/nano-kit.md b/docs/nano-kit.md @@ -25,9 +25,11 @@ base value is now persistent, with client default 5 and ability weights value 100 is replaced by this actual base stat. See [First Aid research](first-aid.md) for the skill resource and permission evidence. -Successful use saves the decremented charge and absolute lock deadline in -one atomic inventory replacement before acknowledging the use. Failed saves -leave nano, charges and the lock unchanged. Repeated sequence numbers are +Successful use commits the decremented charge, absolute source lock deadline +and recipient nano together in one SQLite transaction before acknowledging +the use. In-memory inventory and recipient vitals change only after commit. +Failed writes or commits leave nano, charges and the lock unchanged. Repeated +sequence numbers are ignored; another sequence during the lock is rejected. Login restores the remaining lock and expiry sends CharacterAction164 for stat123. Treatment124 retains its separate clinic deadline and behavior. @@ -77,9 +79,10 @@ combat HP delivery problem. The native ApplyFriendly gate rejects ordinary unteamed players as attackable in the recovered `10079880` path. Self and matching native team membership -pass this part of the check. The server has no production team management or -PvP system yet, so its connected-player permission policy is broader than -that client gate. No feature bits or native return stubs are changed to bypass +pass this part of the check. Production team rosters provide matching native +membership. The server's connected-player permission policy remains broader +than that client gate pending the full target/PvP audit. No feature bits or +native return stubs are changed to bypass the gate. A native team fixture uses the recovered TeamMember and leader messages to exercise an eligible friendly recipient; the packet schema and source streams are retained in diff --git a/docs/treatment-kit.md b/docs/treatment-kit.md @@ -40,10 +40,11 @@ when the selected patient is unlocked. ## Server and persistence -Accepted use decrements the source charge and saves the patient's absolute -lock deadline in the source inventory's `treatment_locks` map, in one atomic -replacement. Only after this succeeds does the server update health and -publish success. The map can retain distinct patients treated within the +Accepted use commits the source charge, the patient's absolute lock deadline +in the source inventory's `treatment_locks` map, and the recipient's clamped +health together in one SQLite transaction. Only after commit does the server +publish the in-memory inventory, health and lock and acknowledge success. +The map can retain distinct patients treated within the same15-second interval. Expired entries are pruned on the next accepted treatment. Startup combines these receipts with each player's existing clinic deadline, retaining the later deadline. This avoids a partial diff --git a/docs/world-state.md b/docs/world-state.md @@ -37,6 +37,12 @@ the set. Removed entries are deleted only for their owning player. These transactions do not checkpoint unrelated players' routine vitals. An equipment change that limits current health or nano commits that clamp with ownership; explicit character edits and full world flushes retain their resource saves. +Consumable resource effects include a recipient vital update in that same +inventory transaction. The charge, source/patient cooldown and restored health +or nano commit before success reaches the client, including when the last +charge destroys its item instance. A missing or ignored recipient write fails +the transaction. Only the recipient's vital columns are written; positions keep +their normal checkpoint cadence. The vital cache changes only after commit. The world header is updated only when its counters, clock or population-initialization state change. NPC state is checked @@ -134,3 +140,24 @@ player/metadata/item writes or page errors. Both fixture profiles and all 192 item records and placements were restored; the guards and audit table were removed. The final full Go suite and focused race checks pass. Evidence is in `local/inventory-write-research/`, with the final native run in `final/`. + +`server/consumable_outcome_test.go` invokes public item use and reopens SQLite +before a checkpoint. It covers self/other-player resource restoration, a DB +read during the first outgoing success packet, last-charge deletion, failed +charge/lock/resource writes, ignored recipient writes, failed commit, retry, +resource caps, unsaved movement, and output failure followed by restart/replay. +The cache, inventory, cooldown and recipient resources change together. + +Two published WASM clients exercised both kits on a native teammate. The first +received success already had recipient nano 11, a decremented kit and the +source cooldown in SQLite. The treatment success already had recipient health +54, its charge debit and patient lock. Both clients showed those resource +values; ordinary regeneration explains the subsequent increases. After an +ungraceful server stop, SQLite and both reconnected clients agreed on 215 HP, +111 nano and two charges remaining in each fixture kit. Unteamed use was also +rejected by the native client without a server request or debit. No page or +adapter errors occurred. Both profiles, their original item records/placements +and receipts were restored, and the fixture items/team were removed. The full +server suite and focused race checks pass. Evidence is retained in +`local/consumable-outcome-research/`. The saved/native posture mismatch observed +on entry remains a separate TODO. diff --git a/server/consumable_outcome_test.go b/server/consumable_outcome_test.go @@ -0,0 +1,311 @@ +package main + +import ( + "context" + "database/sql" + "encoding/binary" + "testing" + "time" +) + +type consumableCommitConn struct { + combatTestConn + db *sql.DB + target uint32 + observed bool + health uint32 + nano uint32 + count uint16 + firstAid time.Time + patient sql.NullTime + err error +} + +func (conn *consumableCommitConn) Write(packet []byte) (int, error) { + if !conn.observed && binary.BigEndian.Uint32(packet[16:20]) == 0x52526858 && binary.BigEndian.Uint32(packet[29:33]) == 1 { + conn.observed = true + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + conn.err = conn.db.QueryRowContext(ctx, `SELECT recipient.health, recipient.nano, coalesce(debit.count, 0), + healer.first_aid_locked_until, receipt.locked_until + FROM characters recipient JOIN players healer ON healer.id=1 + LEFT JOIN items debit ON debit.id=1 + LEFT JOIN treatment_locks receipt ON receipt.player_id=1 AND receipt.patient_id=recipient.id + WHERE recipient.id=?`, conn.target).Scan(&conn.health, &conn.nano, &conn.count, &conn.firstAid, &conn.patient) + } + return conn.combatTestConn.Write(packet) +} + +func newConsumableOutcomeWorld(t *testing.T, template uint32, other bool) (*server, *character, *combatTestConn) { + t.Helper() + useNPCData(t, testNPCData()) + world := newTestServer(t) + player := world.newCharacter() + if template == 85366 { + player.stats.NanoAiding.FirstAid = 6 + } else { + player.stats.NanoAiding.Treatment = 6 + } + target := player + if other { + target = world.newCharacter() + } + if template == 85366 { + target.nano = 1 + } else { + target.health, target.sitting = 1, true + } + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if other { + if err := world.saveUser_locked(target); err != nil { + t.Fatal(err) + } + } + if granted, err := world.grantItem_locked(player, template); !granted || err != nil { + t.Fatal(granted, err) + } + conn := &combatTestConn{} + world.clients[player.id] = &worldClient{id: player.id, conn: conn, target: true, ready: true, selectedTarget: [2]uint32{50000, target.id}} + if other { + world.clients[target.id] = &worldClient{id: target.id, conn: &combatTestConn{}, target: true, ready: true} + } + return world, target, conn +} + +func TestConsumableResourceGainSurvivesBeforeCheckpoint(t *testing.T) { + for _, use := range []struct { + name string + template uint32 + other bool + }{{"nano self", 85366, false}, {"nano other", 85366, true}, {"health self", 25812, false}, {"health other", 25812, true}} { + t.Run(use.name, func(t *testing.T) { + world, target, _ := newConsumableOutcomeWorld(t, use.template, use.other) + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t) + + if err != nil { + t.Fatal(err) + } + if use.template == 85366 { + if target.nano < 11 || target.nano > 13 || restored.characters[target.id].nano != target.nano || + restored.characters[1].inventory.Items[0].Count != 24 || restored.characters[1].inventory.FirstAidLockedUntil.IsZero() { + t.Fatalf("acknowledged nano gain was not committed with charge/lock: live=%d saved=%d", target.nano, restored.characters[target.id].nano) + } + } else if target.health != 31 || restored.characters[target.id].health != 31 || + restored.characters[1].inventory.Items[0].Count != 49 || restored.characters[target.id].treatmentLockedUntil.IsZero() { + t.Fatalf("acknowledged health gain was not committed with charge/lock: live=%d saved=%d", target.health, restored.characters[target.id].health) + } + }) + } +} + +func TestConsumableLastChargeCommitsBeforeSuccessPacket(t *testing.T) { + for _, use := range []struct { + name string + template uint32 + other bool + }{{"nano self", 85366, false}, {"nano other", 85366, true}, {"health self", 25812, false}, {"health other", 25812, true}} { + t.Run(use.name, func(t *testing.T) { + world, target, _ := newConsumableOutcomeWorld(t, use.template, use.other) + player := world.characters[1] + player.inventory.Items[0].Count = 1 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + conn := &consumableCommitConn{db: world.db, target: target.id} + world.clients[1].conn = conn + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t) + + if err != nil || !conn.observed || conn.err != nil || conn.count != 0 || len(player.inventory.Items) != 0 || + len(restored.items) != 0 || restored.nextItem != 1 || target.savedVitals != target.vitals() { + t.Fatalf("last charge/resource outcome was not durable at first success: observed=%t count=%d, %v %v", conn.observed, conn.count, err, conn.err) + } + if use.template == 85366 { + if conn.nano < 11 || conn.nano > 13 || conn.nano != target.nano || conn.firstAid.IsZero() || conn.patient.Valid { + t.Fatal("first success preceded the nano gain or source cooldown") + } + } else if conn.health != 31 || !conn.patient.Valid || conn.patient.Time.IsZero() || !conn.firstAid.IsZero() { + t.Fatal("first success preceded the health gain or patient lock") + } + }) + } +} + +func TestConsumableFailureRollsBackGainChargeAndLockThenRetries(t *testing.T) { + for _, template := range []uint32{85366, 25812} { + for _, phase := range []string{"charge", "lock", "resource", "ignored resource", "commit"} { + name := "health " + phase + if template == 85366 { + name = "nano " + phase + } + t.Run(name, func(t *testing.T) { + world, target, conn := newConsumableOutcomeWorld(t, template, true) + count := uint16(50) + if template == 85366 { + count = 25 + } + before := target.savedVitals + statement := "CREATE TRIGGER reject_item_effect BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'test resource failure'); END" + switch phase { + case "charge": + statement = "CREATE TRIGGER reject_item_effect BEFORE UPDATE ON items WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test charge failure'); END" + case "lock": + statement = "CREATE TRIGGER reject_item_effect BEFORE INSERT ON treatment_locks WHEN NEW.player_id=1 BEGIN SELECT RAISE(FAIL, 'test patient lock failure'); END" + if template == 85366 { + statement = "CREATE TRIGGER reject_item_effect BEFORE UPDATE ON players WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test first aid lock failure'); END" + } + case "ignored resource": + statement = "CREATE TRIGGER reject_item_effect BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(IGNORE); END" + case "commit": + statement = "CREATE TABLE pending_effect (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_item_effect AFTER UPDATE OF health ON characters WHEN NEW.id=2 BEGIN INSERT INTO pending_effect VALUES (999999); END" + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + failed := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + rolledBack := newTestInventoryServer(t) + player := world.characters[1] + if failed == nil || len(conn.packets) != 0 || player.inventory.Items[0].Count != count || world.items[1].Count != count || + rolledBack.characters[1].inventory.Items[0].Count != count || target.vitals() != before || target.savedVitals != before || + rolledBack.characters[2].health != before.Health || rolledBack.characters[2].nano != before.Nano || + !player.inventory.FirstAidLockedUntil.IsZero() || len(player.inventory.TreatmentLocks) != 0 || !target.treatmentLockedUntil.IsZero() { + t.Fatal("failed item effect changed caches, resources, charge/lock rows or published success", failed) + } + if _, err := world.db.Exec("DROP TRIGGER reject_item_effect"); err != nil { + t.Fatal(err) + } + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) + restored := newTestInventoryServer(t) + + if err != nil || player.inventory.Items[0].Count != count-1 || restored.characters[1].inventory.Items[0].Count != count-1 || + restored.characters[2].health != target.health || restored.characters[2].nano != target.nano || target.savedVitals != target.vitals() { + t.Fatal("retry did not commit one complete item effect", err) + } + if template == 85366 { + if target.nano < 11 || target.nano > 13 || restored.characters[1].inventory.FirstAidLockedUntil.IsZero() { + t.Fatal("retry lost nano restoration or its cooldown") + } + } else if target.health != 31 || restored.characters[2].treatmentLockedUntil.IsZero() { + t.Fatal("retry lost health restoration or its patient lock") + } + }) + } + } +} + +func TestConsumableLastChargeFailurePreservesInstanceAndRecipient(t *testing.T) { + for _, template := range []uint32{85366, 25812} { + t.Run(map[uint32]string{85366: "nano", 25812: "health"}[template], func(t *testing.T) { + world, target, conn := newConsumableOutcomeWorld(t, template, true) + player := world.characters[1] + player.inventory.Items[0].Count = 1 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before := target.vitals() + if _, err := world.db.Exec("CREATE TRIGGER reject_last_effect BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'test last charge resource failure'); END"); err != nil { + t.Fatal(err) + } + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t) + + if err == nil || len(conn.packets) != 0 || len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != 1 || player.inventory.Items[0].Count != 1 || + len(restored.items) != 1 || restored.characters[1].inventory.Items[0].ID != 1 || restored.items[1].Count != 1 || restored.nextItem != 1 || + target.vitals() != before || restored.characters[2].health != before.Health || restored.characters[2].nano != before.Nano || + len(player.inventory.TreatmentLocks) != 0 || !player.inventory.FirstAidLockedUntil.IsZero() { + t.Fatal("failed last-charge effect destroyed its instance or changed the recipient", err) + } + }) + } +} + +func TestConsumableClampsResourceGainWithoutSavingMovement(t *testing.T) { + for _, use := range []struct { + name string + template uint32 + other bool + before uint32 + maximum uint32 + count uint16 + }{ + {"nano self full", 85366, false, 35, 35, 24}, + {"nano other full", 85366, true, 35, 35, 24}, + {"nano self one missing", 85366, false, 34, 35, 24}, + {"nano other one missing", 85366, true, 34, 35, 24}, + {"health self full", 25812, false, 37, 37, 49}, + {"health other full", 25812, true, 37, 37, 49}, + {"health self one missing", 25812, false, 36, 37, 49}, + {"health other one missing", 25812, true, 36, 37, 49}, + } { + t.Run(use.name, func(t *testing.T) { + world, target, _ := newConsumableOutcomeWorld(t, use.template, use.other) + if use.template == 85366 { + target.nano = use.before + } else { + target.health = use.before + } + if err := world.savePosition_locked(target); err != nil { + t.Fatal(err) + } + position := target.position + target.position[0] += 0.5 + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t) + + if err != nil || restored.characters[target.id].position != position || target.savedPosition.Position != position || target.savedVitals != target.vitals() || restored.characters[1].inventory.Items[0].Count != use.count { + t.Fatal("resource effect saved movement early, missed its vital update or lost charge conservation", err) + } + if use.template == 85366 { + if target.nano != use.maximum || restored.characters[target.id].nano != use.maximum { + t.Fatalf("nano maximum: live=%d saved=%d want=%d", target.nano, restored.characters[target.id].nano, use.maximum) + } + } else if target.health != use.maximum || restored.characters[target.id].health != use.maximum { + t.Fatal("health effect exceeded or missed its maximum") + } + }) + } +} + +func TestConsumableOutputFailureKeepsDurableOutcomeAndRestartPreventsReplay(t *testing.T) { + for _, use := range []struct { + name string + template uint32 + other bool + count uint16 + }{{"nano self", 85366, false, 24}, {"nano other", 85366, true, 24}, {"health self", 25812, false, 49}, {"health other", 25812, true, 49}} { + t.Run(use.name, func(t *testing.T) { + world, target, _ := newConsumableOutcomeWorld(t, use.template, use.other) + world.clients[1].writeWake, world.clients[1].writeClosed = make(chan struct{}, 1), true + + failedOutput := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t) + conn := &combatTestConn{} + restored.clients[1] = &worldClient{id: 1, conn: conn, target: true, ready: true, selectedTarget: [2]uint32{50000, target.id}} + if use.other { + restored.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true} + } + replay := restored.handleOwnedItemUse(restored.clients[1], backpackUseRequest(1, 64, 2)[20:]) + + if failedOutput == nil || replay != nil || restored.characters[1].inventory.Items[0].Count != use.count || + restored.characters[target.id].health != target.health || restored.characters[target.id].nano != target.nano || + len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("output failure lost the committed effect or restart let it consume another charge", failedOutput, replay) + } + if use.template == 85366 { + if target.nano < 11 || target.nano > 13 || restored.characters[1].inventory.FirstAidLockedUntil.IsZero() { + t.Fatal("output failure lost nano restoration or its durable source cooldown") + } + } else if target.health != 31 || restored.characters[target.id].treatmentLockedUntil.IsZero() { + t.Fatal("output failure lost health restoration or its durable patient lock") + } + }) + } +} diff --git a/server/inventory.go b/server/inventory.go @@ -115,6 +115,26 @@ func (server *server) saveInventory_locked(character *character, inventory playe return nil } +func (server *server) saveItemEffect_locked(player, target *character, inventory playerInventory, vitals playerVitals) error { + if err := inventory.validate(); err != nil { + return err + } + store, err := server.itemStore_locked(player, inventory) + if err != nil { + return err + } + store.vitalUpdate = &playerVitalUpdate{target.id, vitals} + if err := server.writeItemStore_locked(store); err != nil { + return err + } + + // Publish both participants only after the debit, lock and resource gain commit. + player.inventory = inventory + target.applyVitals(vitals) + target.savedVitals = vitals + return nil +} + func (server *server) grantItem_locked(character *character, template uint32) (bool, error) { // Start with exact catalog qualities; arbitrary QL interpolation is separate. definition := gamedata.ItemTemplates[template] diff --git a/server/inventory_write_test.go b/server/inventory_write_test.go @@ -212,7 +212,7 @@ func TestTreatmentUseDeletesOnlyExpiredPatientLocks(t *testing.T) { !restored.TreatmentLocks[1].Equal(player.inventory.TreatmentLocks[1]) || !restored.TreatmentLocks[3].Equal(deadline) { t.Fatal("treatment use lost a retained lock, kept an expired lock or missed the new lock", err) } - expected := map[string]int{"items/UPDATE": 1, "treatment_locks/INSERT": 1, "treatment_locks/DELETE": 1} + expected := map[string]int{"characters/UPDATE": 1, "items/UPDATE": 1, "treatment_locks/INSERT": 1, "treatment_locks/DELETE": 1} if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, expected) { t.Fatalf("treatment use rewrote retained locks or unrelated state: %v", writes) } diff --git a/server/item_database.go b/server/item_database.go @@ -177,6 +177,21 @@ func (server *server) persistItems_locked(store itemStore) error { return err } } + if store.vitalUpdate != nil { + // A resource effect must reach its existing recipient with the item debit. + assignments := strings.ReplaceAll(vitalColumns, ", ", " = ?, ") + " = ?" + result, err := tx.Exec("UPDATE characters SET "+assignments+" WHERE id=?", append(store.vitalUpdate.Vitals.fields(), store.vitalUpdate.ID)...) + if err != nil { + return err + } + changed, err := result.RowsAffected() + if err != nil { + return err + } + if changed != 1 { + return fmt.Errorf("player %d resource update affected %d rows", store.vitalUpdate.ID, changed) + } + } started := server.clockStarted if started.IsZero() { started = time.Now() diff --git a/server/item_store.go b/server/item_store.go @@ -39,12 +39,18 @@ type characterItemReferences struct { Equipment map[string]*uint32 `yaml:"equipment"` } +type playerVitalUpdate struct { + ID uint32 + Vitals playerVitals +} + type itemStore struct { LastID uint32 `yaml:"last_id"` Items map[uint32]itemRecord `yaml:"items"` Players map[uint32]characterItemReferences `yaml:"players"` Corpses map[uint32][]ownedItem edited *character + vitalUpdate *playerVitalUpdate inventoryPlayer uint32 checkpointAt time.Time flush bool diff --git a/server/nano_kit.go b/server/nano_kit.go @@ -26,7 +26,7 @@ func (server *server) useNanoKit_locked(client *worldClient, index int, body []b accepted = x*x+y*y+z*z <= distance*distance } if accepted { - // Commit the charge and cooldown together before restoring nano or publishing success. + // Commit the charge, cooldown and resource gain before publishing success. inventory := player.inventory inventory.Items = slices.Clone(inventory.Items) inventory.Items[index].Count-- @@ -34,12 +34,13 @@ func (server *server) useNanoKit_locked(client *worldClient, index int, body []b inventory.Items = slices.Delete(inventory.Items, index, index+1) } inventory.FirstAidLockedUntil = now.Add(40 * time.Second) - if err := server.saveInventory_locked(player, inventory); err != nil { - return err - } // The catalog supplies endpoints; uniform inclusive integer rolls remain provisional. - target.nano = min(target.maximumNano(), target.nano+10+rand.Uint32N(3)) + vitals := target.vitals() + vitals.Nano = min(target.maximumNano(), vitals.Nano+10+rand.Uint32N(3)) + if err := server.saveItemEffect_locked(player, target, inventory, vitals); err != nil { + return err + } } reply := append([]byte(nil), body[16:]...) binary.BigEndian.PutUint32(reply, 2) diff --git a/server/nano_kit_test.go b/server/nano_kit_test.go @@ -144,8 +144,11 @@ func TestNanoKitRejectsInvalidUseAndFailedSave(t *testing.T) { func TestNanoKitRestoresFriendAtNativeRangeDuringCombat(t *testing.T) { world, _ := newNanoKitWorld(t) player, client := world.characters[1], world.clients[1] - target := &character{id: 2, playfield: player.playfield, position: [3]float32{7, 0, 0}, level: 1, appearance: 277, health: 10, fighting: 1000000} + target := &character{id: 2, name: "Patient", playfield: player.playfield, position: [3]float32{7, 0, 0}, rotation: [4]float32{0, 0, 0, 1}, level: 1, appearance: 277, stats: defaultCharacterStats(), health: 10, fighting: 1000000} world.characters[2] = target + if err := world.saveUser_locked(target); err != nil { + t.Fatal(err) + } friendConn := &combatTestConn{} world.clients[2] = &worldClient{id: 2, conn: friendConn, target: true, ready: true} observerConn := &combatTestConn{} diff --git a/server/treatment_kit.go b/server/treatment_kit.go @@ -33,7 +33,7 @@ func (server *server) useTreatmentKit_locked(client *worldClient, index int, bod accepted = accepted && x*x+y*y+z*z <= distance*distance } if accepted { - // Save the charge and patient lock together, including uses on another player. + // Save the charge, patient lock and resource gain together. inventory := player.inventory inventory.Items = slices.Clone(inventory.Items) inventory.Items[index].Count-- @@ -50,11 +50,12 @@ func (server *server) useTreatmentKit_locked(client *worldClient, index int, bod } } inventory.TreatmentLocks[target.id] = now.Add(15 * time.Second) - if err := server.saveInventory_locked(player, inventory); err != nil { + vitals := target.vitals() + vitals.Health = min(target.maximumHealth(), vitals.Health+30) + if err := server.saveItemEffect_locked(player, target, inventory, vitals); err != nil { return err } target.treatmentLockedUntil = inventory.TreatmentLocks[target.id] - target.health = min(target.maximumHealth(), target.health+30) } reply := append([]byte(nil), body[16:]...)