aorecomp

Anarchy Online classic in the browser

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


commit ebb24cbcbc335c77259feef6d4c27aee49463023
parent 7b908c80033738b6144dc8b4cbba170a5d4722b7
Author: anon <anon@example.com>
Date:   Thu, 22 Oct 2026 17:54:04 +0000

Support Simple Nano Kit restoration and First Aid locks

Diffstat:
MTODO.md | 4+++-
Mdocs/first-aid.md | 27++++++++++++++++++++++++++-
Mdocs/inventory-stacks.md | 5+++--
Adocs/nano-kit.md | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 5++++-
Mserver/implants.go | 16++++++++++++----
Mserver/implants_test.go | 12++++++------
Mserver/inventory.go | 17+++++++++--------
Mserver/main.go | 5++++-
Aserver/nano_kit.go | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/nano_kit_test.go | 242+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/roaming.go | 2+-
Mserver/stacks.go | 17+++++++++--------
Mserver/stats.go | 3++-
Mserver/world.go | 2+-
15 files changed, 534 insertions(+), 35 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -222,13 +222,15 @@ remaining reward-rule gaps are recorded in [character progression](docs/characte - [ ] Use one First Aid item. Check: it restores the expected health, consumes the applicable quantity/charge and cannot be reused during its skill lock. -- [ ] Use one nano-restoring item. Check: nano recovery, consumption and its lock +- [x] Use one nano-restoring item. Check: nano recovery, consumption and its lock match that item rather than inheriting the health item's behavior. - [ ] Use one sitting treatment kit. Check: it works in the permitted posture and combat state and is rejected outside those conditions without consumption. The First Aid item, native charge protocol and unresolved combat-healing delivery are recorded in [First Aid research](docs/first-aid.md). +Simple Nano Kit restoration, charge persistence, native teammate use and the +shared First Aid lock are recorded in [nano kits](docs/nano-kit.md). ## Character creation diff --git a/docs/first-aid.md b/docs/first-aid.md @@ -105,6 +105,27 @@ while also clearing combat state and timers; it is not a neutral heal synchronization operation. No suitable additive healing message or coherent alternative delivery has yet been established. +A further bounded native pass checked base HP setters, snapshot loaders, +attackable-item damage, maximum-health recalculation and the generic ActionIIR +existing-effect route. That route handles poison-roll bookkeeping, without an +HP write. Damage type 474 selects fall-damage text, so it supplies no healing +exception to NanoAttack. The source audit and retained evidence are in +`local/reports/first-aid-health-write-source-audit.json` and +`first-aid-health-delivery-1491-evidence.json` in the same directory. Dynamic +stat IDs and ActionIIR dispatch to a live SimpleItem's virtual method remain +outside this negative result. + +Public implementation comparisons also leave delivery unresolved. +[CellAO's 2016 Hit implementation](https://github.com/CellAO/CellAO-NightPredator/blob/ca77f375a7dabe3be769da94e6c2a3d093344c2c/CellAO/Server/ZoneEngine/Core/Functions/GameFunctions/hit.cs#L112-L153) +changes the base health stat and relies on an absolute dirty-stat flush; the +inspected snapshot contains no weapon AttackInfo implementation to compare. +[AORebirth's 2026 heal path](https://github.com/subarumike/AORebirth/blob/6ec06bbd45e72496923275dcc8fd4e25fecace73/AORebirth/Server/ZoneEngine_New/Core/Inventory/ItemUseFunctions.cs#L334-L377) +sends positive-change HealthDamage and suppresses a duplicate Stat update, +without compensating for pending weapon animation results. These are emulator +designs, not 14.9.1 server evidence. Pinned source details are retained in +`local/first-aid-smoke/protocol-source-followup.json`; no correlated original +stim/AttackInfo capture was recovered. + A [contemporary October 2002 discussion](https://forums-archive.anarchy-online.com/showthread.php?56578-Question-regarding-weapon-speeds=) describes using First Aid during weapon recharge and other actions being unavailable during attack. It does not establish queuing versus rejection, @@ -114,7 +135,11 @@ activates the item timer immediately and does not drain incoming queues. The implementation patch, fixture, source ledger, timing follow-up, packets, screenshots and traces are retained under `local/first-aid-smoke/`. -`prototype.patch` applies on top of the extent-based range change. Further +`prototype.patch` is preserved against range commit `06830a6`, before the +nano kit's shared First Aid stat, charge and lock support. Further work must resolve combat HP delivery and then verify friendly use, restart lock restoration and last-charge deletion in the actual WASM client before checking off the First Aid milestone. All test-owned processes were closed. +The [nano kit checks](nano-kit.md) now provide a native team fixture for an +eligible friendly recipient; an unteamed ordinary player is rejected locally +by this client's ApplyFriendly gate. diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md @@ -67,7 +67,7 @@ cap remains unresolved. Overflow assembly evidence: Each owned item now has a ushort Count in `inventory.yaml`; pre-quantity saved items and reclaim entries with an absent/zero count load as one individual. -Only the supported Essence can currently have a count above one. FullCharacter, +The supported Essence and QL 1 Simple Nano Kit can have counts above one. FullCharacter, corpse and reclaim entries serialize the quantity rather than a constant one. The existing atomic inventory replacement publishes both changed counts and any newly allocated ID together, after saving successfully. @@ -87,7 +87,8 @@ The server instead rebuilds only the supported ordinary stacks: 1. Preserve all occupied individual-item slots and all equipment. 2. Delete the other ordinary slots using native action 112, removing any - provisional Essence clones. The Essence has no deletion event functions. + provisional supported-stack clones. Neither supported template has deletion + event functions. 3. Add each authoritative stack in slot order using AddTemplate `0x052e2f0c`, body `{low, high, QL, count}`. It chooses the first free ordinary slot. 4. Move it to its saved slot with the existing own-player ContainerAddItem diff --git a/docs/nano-kit.md b/docs/nano-kit.md @@ -0,0 +1,121 @@ +# Simple Nano Kit + +The server supports QL 1 Simple Nano Kit 85366 from ordinary inventory, +for self-use or a living connected friendly player in the same playfield. +The shipped record is `server/gamedata/items/items_004.yaml`, payload SHA-256 +`f9026bb655e6549d9cfc8fb0362c072d2db49c374917e5dd3909823acc857910`. +The [14.7.8 parsed record](https://auno.org/ao/db.php?id=85366&patch=14070800) +corroborates its fields. The exact item and source ledger are retained in +`local/nano-kit-smoke/`. + +## Authored behavior and implementation + +The kit has 25 charges, HasEnergy, UseEmptyDestruct, Stackable and ApplyFriendly. +Its use requires effective FirstAid123 > 7 AND selected-target mask 35. It +restores CurrentNano214 using endpoints 10..12, runs target graphics 13600, +locks the user's FirstAid123 for 40 seconds, and supplies the target text +"Your body tingles with energy." Its description explicitly permits self or +friend. There is no authored sitting or out-of-combat requirement. + +The server checks predicted 3D positions using item range 3 plus both actor +extents, including equality: 7 meters between default players. First Aid's +base value is now persistent, with client default 5 and ability weights +`[0,30,0,30,40,0]` in STR/AGI/STA/INT/SEN/PSY order. Default effective skill is +7 and does not satisfy the kit's requirement. The previous hardcoded native +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 +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. + +The native proxy success ACK consumes one charge; TemplateAction3 separately +runs the item effects. A final zero-charge row needs explicit native action112 +deletion. Kit stacks can split and join only matching template/type/QL rows, +including persisted backpack contents. This kit has no removal-event20 +functions, so rebuilding supported stacks does not run deletion effects. +The 65535 quantity ceiling is representational; the historical merge cap +remains unresolved and the general merge TODO stays open. + +Nano is clamped to its derived maximum and sent privately to the recipient +using StatIIR214. This does not write HP or disturb pending weapon results. +The local Hit53002 and StaticText53044 handlers do not perform these authored +operations; StaticText's dispatch reaches the original RET4 stub at1010def0. +Sending another ApplySpells packet would reach the same stub. +TemplateAction3 constructs its resource from the supplied template pair and +does not require a source inventory row or debit another charge. Broadcasting +it to ready observers where both players exist replicates the target graphics. + +The authored text uses native ChatTextIIR `0x5f4b442a`: uint32 big-endian byte +length, raw text without NUL, category byte0, display-mode byte0. The reader, +writer and activation are original `10042440`, `100424b0` and `10042510`, in +`client/game/kkr.dll/lifted-0021.c` at relocated base `0x36000000`. Original PE +import signatures confirm the 32-bit length and byte-sized final fields; +modern serializers with a 16-bit length and trailing DWORD differ. Activation +does not filter by envelope actor, so delivery is unicast to the recipient. +Category0/mode0 uses normal native text output. For this 30-byte line the +36-byte body is: + +```text +0000001e596f757220626f64792074696e676c6573207769746820656e657267792e0000 +``` + +## Evidence limits + +The inclusive uniform integer restoration roll is a reconstruction choice; +the record establishes endpoints, not distribution. Success at full nano, +absolute lock persistence across server restart, and the supported ordinary +player permission subset are implementation policies. Historical full-nano +consumption, action-phase scheduling, all friendly NPC/PvP categories and +original-server range tolerance remain unproven. Direct use from a backpack +is not implemented; the kit can be moved into ordinary inventory first. +The health-restoring First Aid kit remains disabled pending its separate +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 +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 +`local/reports/team-fixture-protocol-1491-source-audit.json`. + +## Verification + +Go checks cover authored requirements, invalid targets and source items, +the exact 7-meter boundary, use during combat, private recipient nano/text, +observer effect replication, failed-save atomicity, closed-owner output, +replays, concurrent requests, lock expiry, final-charge deletion, maximum +clamping, old-profile defaults and persistent split/join conservation. + +Actual WASM checks are retained under `local/nano-kit-smoke/`: + +- Self-use restored 6 to 16 nano in both server and native state while charges + fell 25 to 24. An immediate repeat during the lock consumed nothing. +- Server restart retained the 24 charges and sent a 17-second remaining + First Aid lock. Native expiry announced that First Aid was available. +- Ctrl-click split 24 into 1 and 23 persistent charges. Using the single-charge + item clamped 34 to 35 nano and removed its native inventory row. The other + stack retained its identity and quantity. +- During combat, a six-damage incoming weapon result remained queued while + the kit restored 6 to 17 nano and consumed one charge. Native and server nano + stayed 17 through the subsequent weapon impacts. Existing health prediction + phase differences did not affect this independent nano update. +- A second client first reproduced the native nonteam rejection with no use + request or consumption. Recovered TeamMember and leader messages then + populated actual native group membership. Use on that teammate restored + 0 to 10 nano, reduced the source stack 21 to 20, locked only the source, + and displayed the authored text on the recipient. A read-only recipient + probe confirmed the native value. Both clients processed the replicated + TemplateAction without a missing adapter or page exception. + +The first restart test recorded expected connection-refused console messages +while the fixture was down. The final two-client run recorded no errors. +All test-owned clients and servers were closed before final automated checks. +The full `go test ./server/...` suite passed, followed by three race-detector +repetitions of the nano-kit, stack and portable-clinic tests. diff --git a/server/backpacks.go b/server/backpacks.go @@ -71,9 +71,12 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error client.useSequence = sequence if binary.BigEndian.Uint32(body[40:44]) == 104 { index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Slot == binary.BigEndian.Uint32(body[44:48]) && item.Template == 43552 + return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366) }) if index >= 0 { + if player.inventory.Items[index].Template == 85366 { + return server.useNanoKit_locked(client, index, body) + } return server.useClinic_locked(client, index, body) } } diff --git a/server/implants.go b/server/implants.go @@ -61,18 +61,18 @@ func (server *server) useClinic_locked(client *worldClient, index int, body []by if err := client.send(n3Packet(0x35505644, 50000, client.id, action)); err != nil { return err } - return client.send(treatmentLockPacket(client.id, 600)) + return client.send(skillLockPacket(client.id, 124, 600)) } -func treatmentLockPacket(owner, seconds uint32) []byte { +func skillLockPacket(owner, stat, seconds uint32) []byte { var body []byte - for _, value := range []uint32{170, 0, 0, 124, seconds} { + for _, value := range []uint32{170, 0, 0, stat, seconds} { body = binary.BigEndian.AppendUint32(body, value) } return n3Packet(0x5e477770, 50000, owner, body) } -func (server *server) advanceClinics(now time.Time) { +func (server *server) advanceItemEffects(now time.Time) { server.updateMutex.Lock() defer server.updateMutex.Unlock() server.mutex.Lock() @@ -96,6 +96,14 @@ func (server *server) advanceClinics(now time.Time) { } updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, id, body)) } + if !player.inventory.FirstAidLockedUntil.IsZero() && !now.Before(player.inventory.FirstAidLockedUntil) { + player.inventory.FirstAidLockedUntil = time.Time{} + var body []byte + for _, value := range []uint32{164, 0, 0, 0, 123} { + body = binary.BigEndian.AppendUint32(body, value) + } + updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, id, body)) + } } server.mutex.Unlock() server.sendCombatUpdates(updates) diff --git a/server/implants_test.go b/server/implants_test.go @@ -125,14 +125,14 @@ func TestImplantRemovalRetainsOtherEquipmentAndNeedsClinic(t *testing.T) { world.advanceEquipment(client.equipment.readyAt) } deadline := player.implantChangesUntil - world.advanceClinics(deadline) + world.advanceItemEffects(deadline) before := player.inventory world.handleInventory(client, itemMovePacket(1, 37, 111)[20:]) if client.equipment != nil || !reflect.DeepEqual(before, player.inventory) || player.inventory.equipmentBonus(91) != 14 { t.Fatal("implant removed after surgery access expired") } - world.advanceClinics(player.treatmentLockedUntil) + world.advanceItemEffects(player.treatmentLockedUntil) world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 2)[20:]) // Removal does not recheck the implant's install requirements. player.stats.Treatment, player.stats.Strength = 0, 1 @@ -234,13 +234,13 @@ func TestPortableClinicCooldownAndExpiry(t *testing.T) { first := append([][]byte(nil), conn.packets...) world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 1)[20:]) world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 2)[20:]) - world.advanceClinics(window.Add(-time.Nanosecond)) + world.advanceItemEffects(window.Add(-time.Nanosecond)) if len(conn.packets) != 4 || !player.implantChangesUntil.Equal(window) || !player.treatmentLockedUntil.Equal(cooldown) { t.Fatal("replay or cooldown use extended clinic effects") } - world.advanceClinics(window) - world.advanceClinics(cooldown) - world.advanceClinics(cooldown.Add(time.Second)) + world.advanceItemEffects(window) + world.advanceItemEffects(cooldown) + world.advanceItemEffects(cooldown.Add(time.Second)) if window.Before(started.Add(30*time.Second)) || window.After(time.Now().Add(30*time.Second)) || cooldown.Sub(window) != 570*time.Second { t.Fatalf("clinic duration: window=%v cooldown=%v", window.Sub(started), cooldown.Sub(started)) diff --git a/server/inventory.go b/server/inventory.go @@ -26,10 +26,11 @@ type reclaimItem struct { } type playerInventory struct { - LastID uint32 `yaml:"last_id"` - Items []ownedItem `yaml:"items"` - Reclaim []reclaimItem `yaml:"reclaim,omitempty"` - Containers map[uint32][]ownedItem `yaml:"containers,omitempty"` + LastID uint32 `yaml:"last_id"` + Items []ownedItem `yaml:"items"` + Reclaim []reclaimItem `yaml:"reclaim,omitempty"` + Containers map[uint32][]ownedItem `yaml:"containers,omitempty"` + FirstAidLockedUntil time.Time `yaml:"first_aid_locked_until,omitempty"` } func (inventory playerInventory) validate() error { @@ -38,7 +39,7 @@ func (inventory playerInventory) validate() error { bags := make(map[uint32]bool) for _, item := range inventory.Items { if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Count == 0 || - (item.Count != 1 && !item.isEssenceStack()) || + (item.Count != 1 && !item.isStackable()) || (item.Slot < 64 && !item.fitsEquipmentSlot(item.Slot)) || item.Slot >= 94 || slots[item.Slot] { return fmt.Errorf("invalid inventory item identity or slot") @@ -56,7 +57,7 @@ func (inventory playerInventory) validate() error { } for _, entry := range inventory.Reclaim { if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Count == 0 || - (entry.Item.Count != 1 && !entry.Item.isEssenceStack()) || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { + (entry.Item.Count != 1 && !entry.Item.isStackable()) || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { return fmt.Errorf("invalid reclaim item identity or slot") } ids[entry.Item.ID] = true @@ -71,7 +72,7 @@ func (inventory playerInventory) validate() error { var occupied [21]bool for _, item := range items { if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Type == 51017 || - item.Count == 0 || (item.Count != 1 && !item.isEssenceStack()) || item.Slot >= 21 || occupied[item.Slot] { + item.Count == 0 || (item.Count != 1 && !item.isStackable()) || item.Slot >= 21 || occupied[item.Slot] { return fmt.Errorf("invalid backpack item identity or slot") } ids[item.ID], occupied[item.Slot] = true, true @@ -116,7 +117,7 @@ func (server *server) grantItem_locked(character *character, template uint32) (b inventory.LastID = server.nextItem + 1 inventory.Items = slices.Clone(character.inventory.Items) item := ownedItem{inventory.LastID, definition.HeaderWords[0], template, *definition.Quality, slot, 1} - if item.isEssenceStack() { + if item.isStackable() { item.Count = uint16(itemStat(definition, 212)) } inventory.Items = append(inventory.Items, item) diff --git a/server/main.go b/server/main.go @@ -332,7 +332,10 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, fullCharacterPacket(character)) updates = append(updates, equippedWeaponPackets(character)...) if remaining := time.Until(character.treatmentLockedUntil); remaining > 0 { - updates = append(updates, treatmentLockPacket(character.id, uint32((remaining+time.Second-1)/time.Second))) + updates = append(updates, skillLockPacket(character.id, 124, uint32((remaining+time.Second-1)/time.Second))) + } + if remaining := time.Until(character.inventory.FirstAidLockedUntil); remaining > 0 { + updates = append(updates, skillLockPacket(character.id, 123, uint32((remaining+time.Second-1)/time.Second))) } updates = append(updates, server.combatInterest_locked(client, nil)...) updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked())) diff --git a/server/nano_kit.go b/server/nano_kit.go @@ -0,0 +1,91 @@ +package main + +import ( + "encoding/binary" + "math/rand/v2" + "slices" + "time" +) + +func (server *server) useNanoKit_locked(client *worldClient, index int, body []byte) error { + player := server.characters[client.id] + item := player.inventory.Items[index] + target := server.characters[client.selectedTarget[1]] + stats := player.baseStats() + now := time.Now() + accepted := item.Type == 51005 && item.Template == 85366 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && + client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 && + target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading && + stats.effectiveSkill(stats.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) > 7 && !now.Before(player.inventory.FirstAidLockedUntil) + if accepted { + first := predictedPosition_locked(player, client, now) + second := predictedPosition_locked(target, server.clients[target.id], now) + x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] + // FUN_1008fda0 adds both actors' physical extents to the item's range. + distance := 3 + player.physicalExtent() + target.physicalExtent() + accepted = x*x+y*y+z*z <= distance*distance + } + if accepted { + // Commit the charge and cooldown together before restoring nano or publishing success. + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[index].Count-- + if inventory.Items[index].Count == 0 { + 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)) + } + reply := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(reply, 2) + if accepted { + binary.BigEndian.PutUint32(reply, 1) + } + if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil { + return err + } + if !accepted { + return nil + } + + // Proxy acknowledgements consume the charge; this action runs the item effects. + var action []byte + for _, value := range []uint32{85366, 85366, 1, 1, 3, 104, item.Slot, 50000, target.id} { + action = binary.BigEndian.AppendUint32(action, value) + } + updates := make(map[*worldClient][][]byte) + server.queueCombat_locked(updates, player, target, n3Packet(0x35505644, 50000, client.id, action)) + server.sendCombatUpdates(updates) + if item.Count == 1 { + var removal []byte + for _, value := range []uint32{112, 104, item.Slot, 85366, 85366} { + removal = binary.BigEndian.AppendUint32(removal, value) + } + if err := client.send(n3Packet(0x5e477770, 50000, client.id, removal)); err != nil { + return err + } + } + if err := client.send(skillLockPacket(client.id, 123, 40)); err != nil { + return err + } + + var nano []byte + for _, value := range []uint32{214, target.nano} { + nano = binary.BigEndian.AppendUint32(nano, value) + } + if err := server.clients[target.id].send(n3Packet(0x2b333d6e, 50000, target.id, nano)); err != nil { + return err + } + + // The local StaticText handler is empty; deliver the authored text to the recipient. + text := "Your body tingles with energy." + feedback := binary.BigEndian.AppendUint32(nil, uint32(len(text))) + feedback = append(feedback, text...) + feedback = append(feedback, 0, 0) + return server.clients[target.id].send(n3Packet(0x5f4b442a, 50000, target.id, feedback)) +} diff --git a/server/nano_kit_test.go b/server/nano_kit_test.go @@ -0,0 +1,242 @@ +package main + +import ( + "encoding/binary" + "os" + "reflect" + "strings" + "sync" + "testing" + "time" +) + +func newNanoKitWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) + world, conn := newCombatWorld() + player := world.characters[1] + player.name, player.level, player.appearance = "Nano Kit Owner", 1, 277 + player.rotation[3], player.stats = 1, defaultCharacterStats() + player.stats.FirstAid = 6 + player.health = player.maximumHealth() - 20 + world.clients[1].selectedTarget = [2]uint32{50000, 1} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, 85366); err != nil || !granted { + t.Fatal(granted, err) + } + return world, conn +} + +func TestNanoKitUseRestoresNanoConsumesAndPersistsLock(t *testing.T) { + world, conn := newNanoKitWorld(t) + player, client := world.characters[1], world.clients[1] + before, started := player.nano, time.Now() + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || player.nano < before+10 || player.nano > before+12 || player.health != 17 || player.inventory.Items[0].Count != 24 { + t.Fatalf("nano kit did not restore nano and consume one charge: nano=%d inventory=%+v err=%v", player.nano, player.inventory, err) + } + if player.inventory.FirstAidLockedUntil.Before(started.Add(40*time.Second)) || player.inventory.FirstAidLockedUntil.After(time.Now().Add(40*time.Second)) || + !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 1 || + !restored.inventory.FirstAidLockedUntil.Equal(player.inventory.FirstAidLockedUntil) || restored.stats.FirstAid != 6 { + t.Fatal("charge, skill or lock deadline did not persist together") + } + if len(conn.packets) != 5 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || + binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x35505644 || binary.BigEndian.Uint32(conn.packets[1][61:65]) != 1 || + binary.BigEndian.Uint32(conn.packets[2][41:45]) != 123 || binary.BigEndian.Uint32(conn.packets[2][45:49]) != 40 || + binary.BigEndian.Uint32(conn.packets[3][29:33]) != 214 || binary.BigEndian.Uint32(conn.packets[3][33:37]) != player.nano || + string(conn.packets[4][33:63]) != "Your body tingles with energy." { + t.Fatalf("nano kit native messages: %x", conn.packets) + } +} + +func TestNanoKitLockRejectsRepeatAndClearsAtDeadline(t *testing.T) { + world, conn := newNanoKitWorld(t) + player, client := world.characters[1], world.clients[1] + + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + deadline, nano := player.inventory.FirstAidLockedUntil, player.nano + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]) + world.advanceItemEffects(deadline.Add(-time.Nanosecond)) + locked := player.inventory.FirstAidLockedUntil + world.advanceItemEffects(deadline) + world.advanceItemEffects(deadline.Add(time.Second)) + + if nano != player.nano || player.inventory.Items[0].Count != 24 || !locked.Equal(deadline) || !player.inventory.FirstAidLockedUntil.IsZero() { + t.Fatal("replay or cooldown use changed nano, charges or expiry") + } + if len(conn.packets) != 7 || binary.BigEndian.Uint32(conn.packets[5][29:33]) != 2 || + binary.BigEndian.Uint32(conn.packets[6][29:33]) != 164 || binary.BigEndian.Uint32(conn.packets[6][45:49]) != 123 { + t.Fatalf("nano kit replay rejection or unlock: %x", conn.packets) + } +} + +func TestNanoKitLastChargeClampsNanoAndRemovesItem(t *testing.T) { + world, conn := newNanoKitWorld(t) + player := world.characters[1] + player.inventory.Items[0].Count = 1 + player.nano = player.maximumNano() - 1 + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || player.nano != 35 || len(player.inventory.Items) != 0 || len(restored.inventory.Items) != 0 || restored.inventory.LastID != 1 { + t.Fatalf("last charge was lost, retained or restored too much nano: nano=%d inventory=%+v err=%v", player.nano, player.inventory, err) + } + if len(conn.packets) != 6 || binary.BigEndian.Uint32(conn.packets[2][29:33]) != 112 || + binary.BigEndian.Uint32(conn.packets[2][37:41]) != 48 || binary.BigEndian.Uint32(conn.packets[4][33:37]) != 35 { + t.Fatalf("last-charge deletion or clamped native nano: %x", conn.packets) + } +} + +func TestNanoKitRejectsInvalidUseAndFailedSave(t *testing.T) { + for _, scenario := range []string{"skill 7", "no target", "noncharacter", "missing", "npc", "dead target", "other zone", "far", "loading target", "foreign owner", "wrong quality", "wrong type", "failed save"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newNanoKitWorld(t) + player, client := world.characters[1], world.clients[1] + target := &character{id: 2, playfield: player.playfield, level: 1, appearance: 277, health: 10} + world.characters[2] = target + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true} + client.selectedTarget = [2]uint32{50000, 2} + request := backpackUseRequest(1, 64, 1)[20:] + switch scenario { + case "skill 7": + player.stats.FirstAid = 5 + case "no target": + client.selectedTarget = [2]uint32{} + case "noncharacter": + client.selectedTarget[0] = 51050 + case "missing": + delete(world.characters, 2) + case "npc": + target.npc = true + case "dead target": + target.health = 0 + case "other zone": + target.playfield = 705 + case "far": + target.position[0] = 7.125 + case "loading target": + world.clients[2].loading = true + case "foreign owner": + binary.BigEndian.PutUint32(request[8:12], 2) + case "wrong quality": + player.inventory.Items[0].Quality = 200 + case "wrong type": + player.inventory.Items[0].Type = 51022 + case "failed save": + os.Remove("data/players/1/inventory.yaml") + os.Mkdir("data/players/1/inventory.yaml", 0700) + } + before, nano := player.inventory, target.nano + + err := world.handleOwnedItemUse(client, request) + + if (err != nil) != (scenario == "failed save") || !reflect.DeepEqual(before, player.inventory) || target.nano != nano { + t.Fatalf("invalid nano kit changed charges, lock or nano: %v", err) + } + }) + } +} + +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} + world.characters[2] = target + friendConn := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: friendConn, target: true, ready: true} + observerConn := &combatTestConn{} + world.characters[3] = &character{id: 3, playfield: player.playfield} + world.clients[3] = &worldClient{id: 3, conn: observerConn, target: true, ready: true} + client.selectedTarget = [2]uint32{50000, 2} + player.fighting = 1000000 + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + + if err != nil || target.nano < 10 || target.nano > 12 || player.nano != 0 || target.health != 10 || player.inventory.Items[0].Count != 24 || + target.fighting != 1000000 || player.fighting != 1000000 || !target.inventory.FirstAidLockedUntil.IsZero() { + t.Fatalf("friend nano recovery changed combat, locked the target or failed its 7m boundary: %+v %v", target, err) + } + if len(friendConn.packets) != 3 || binary.BigEndian.Uint32(friendConn.packets[1][24:28]) != 2 || binary.BigEndian.Uint32(friendConn.packets[1][33:37]) != target.nano || + binary.BigEndian.Uint32(friendConn.packets[2][16:20]) != 0x5f4b442a { + t.Fatalf("friend did not receive nano: %x", friendConn.packets) + } + if len(observerConn.packets) != 1 || binary.BigEndian.Uint32(observerConn.packets[0][16:20]) != 0x35505644 { + t.Fatalf("observer did not receive only the item effects: %x", observerConn.packets) + } +} + +func TestNanoKitAcceptedUseRestoresNanoWhenOwnerOutputIsClosed(t *testing.T) { + world, _ := newNanoKitWorld(t) + client := world.clients[1] + client.writeWake, client.writeClosed = make(chan struct{}, 1), true + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + + player := world.characters[1] + if err == nil || player.nano < 10 || player.nano > 12 || player.inventory.Items[0].Count != 24 || player.inventory.FirstAidLockedUntil.IsZero() { + t.Fatalf("saved charge lost its nano restoration on output failure: nano=%d err=%v", player.nano, err) + } +} + +func TestNanoKitConcurrentUsesConsumeOnce(t *testing.T) { + world, _ := newNanoKitWorld(t) + client := world.clients[1] + var workers sync.WaitGroup + errors := make(chan error, 2) + + for _, sequence := range []uint32{1, 2} { + workers.Go(func() { errors <- world.handleOwnedItemUse(client, backpackUseRequest(1, 64, sequence)[20:]) }) + } + workers.Wait() + close(errors) + + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + if world.characters[1].inventory.Items[0].Count != 24 || world.characters[1].inventory.FirstAidLockedUntil.IsZero() { + t.Fatal("simultaneous use consumed twice or bypassed the lock") + } +} + +func TestNanoKitStacksSplitJoinAndRejectDifferentTemplate(t *testing.T) { + world, _ := newNanoKitWorld(t) + world.grantItem_locked(world.characters[1], 152030) + client := world.clients[1] + + world.handleInventory(client, stackActionPacket(1, 52, 64, 10)[20:]) + world.handleInventory(client, stackActionPacket(1, 53, 64, 65)[20:]) + world.handleInventory(client, stackActionPacket(1, 53, 64, 66)[20:]) + restored := newTestInventoryServer(t).characters[1] + + expected := []ownedItem{{ID: 1, Type: 51005, Template: 85366, Quality: 1, Slot: 64, Count: 25}, {ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 3}} + if !reflect.DeepEqual(restored.inventory.Items, expected) { + t.Fatalf("kit split/join changed template or total: %+v", restored.inventory.Items) + } +} + +func TestNanoKitMissingTrainedSkillUsesNativeDefault(t *testing.T) { + world, _ := newNanoKitWorld(t) + contents, err := os.ReadFile("data/players/1/player.yaml") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile("data/players/1/player.yaml", []byte(strings.ReplaceAll(string(contents), " first_aid: 6\n", "")), 0600); err != nil { + t.Fatal(err) + } + + restored := newTestInventoryServer(t).characters[1] + + if restored.stats.FirstAid != 5 || restored.baseStats().effectiveSkill(restored.stats.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) != 7 || + world.characters[1].stats.FirstAid != 6 { + t.Fatalf("missing First Aid did not retain base5: %+v", restored.stats) + } +} diff --git a/server/roaming.go b/server/roaming.go @@ -23,7 +23,7 @@ func (server *server) roamNPCs() { server.advanceNPCRespawns(now) server.advanceNPCs(now) server.advanceEquipment(now) - server.advanceClinics(now) + server.advanceItemEffects(now) server.advanceCombat(now) server.advanceRegeneration(now) } diff --git a/server/stacks.go b/server/stacks.go @@ -7,8 +7,8 @@ import ( "slices" ) -func (item ownedItem) isEssenceStack() bool { - return item.Type == 51005 && item.Template == 152030 && item.Quality == 42 +func (item ownedItem) isStackable() bool { + return item.Type == 51005 && (item.Template == 152030 && item.Quality == 42 || item.Template == 85366 && item.Quality == 1) } func (server *server) changeStack_locked(client *worldClient, index int, body []byte) error { @@ -21,7 +21,7 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] bag = client.backpacks[binary.BigEndian.Uint32(body[24:28])>>16].id items, first, end = inventory.Containers[bag], 0, 21 } - if !items[index].isEssenceStack() { + if !items[index].isStackable() { return nil } items = slices.Clone(items) @@ -61,7 +61,8 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] otherSlot &= 65535 } other := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == otherSlot }) - if binary.BigEndian.Uint32(body[28:32]) != binary.BigEndian.Uint32(body[20:24]) || other < 0 || other == index || !items[other].isEssenceStack() { + if binary.BigEndian.Uint32(body[28:32]) != binary.BigEndian.Uint32(body[20:24]) || other < 0 || other == index || items[other].Type != items[index].Type || + items[other].Template != items[index].Template || items[other].Quality != items[index].Quality { return nil } count := uint32(items[index].Count) + uint32(items[other].Count) @@ -101,12 +102,12 @@ func (server *server) syncStackPage_locked(client *worldClient, bag uint32) erro } func (server *server) syncStacks_locked(client *worldClient) error { - // Preserve live individual items and equipped modifiers. Only Essence has - // optimistic clones here, and its catalog has no deletion event functions. + // Preserve live individual items and equipped modifiers while rebuilding + // supported stacks and removing any optimistic split clones. player := server.characters[client.id] var occupied [30]bool for _, item := range player.inventory.Items { - if item.Slot >= 64 && !item.isEssenceStack() { + if item.Slot >= 64 && !item.isStackable() { occupied[item.Slot-64] = true } } @@ -127,7 +128,7 @@ func (server *server) syncStacks_locked(client *worldClient) error { items := slices.Clone(player.inventory.Items) slices.SortFunc(items, func(first, second ownedItem) int { return int(first.Slot) - int(second.Slot) }) for _, item := range items { - if !item.isEssenceStack() { + if !item.isStackable() { continue } var body []byte diff --git a/server/stats.go b/server/stats.go @@ -17,10 +17,11 @@ type characterStats struct { NanoPool uint16 `yaml:"nano_pool"` Treatment uint16 `yaml:"treatment"` ComputerLiteracy uint16 `yaml:"computer_literacy"` + FirstAid uint16 `yaml:"first_aid"` } func defaultCharacterStats() characterStats { - return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5} + return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5} } func (character *character) baseStats() characterStats { diff --git a/server/world.go b/server/world.go @@ -163,7 +163,7 @@ func fullCharacterPacket(character *character) []byte { body = binary.BigEndian.AppendUint32(body, 1009) } base := character.baseStats() - stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, 1}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, 100}, {124, uint32(base.Treatment)}, {37, character.titleLevel()}} + stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, 1}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, uint32(base.FirstAid)}, {124, uint32(base.Treatment)}, {37, character.titleLevel()}} stats = append(stats, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{161, uint32(base.ComputerLiteracy)}) if time.Now().Before(character.implantChangesUntil) { stats = append(stats, [2]uint32{224, 16})