aorecomp

Anarchy Online classic in the browser

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


commit 0e9711f1487e1ce3f2ebd846eea5364f2bf7839d
parent 9aa5131b632e7d674260a4348cebff6b241eff76
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 23:05:58 +0000

Support catalog medical consumables and atomic dual recovery

Diffstat:
MTODO.md | 18+++++++++++++++++-
Mdocs/first-aid.md | 18++++++++++++++++++
Adocs/medical-consumables.md | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/nano-kit.md | 4+++-
Mdocs/treatment-kit.md | 11++++++++---
Mserver/backpacks.go | 7+++----
Mserver/equipment.go | 4++--
Dserver/equipment_requirements.go | 73-------------------------------------------------------------------------
Aserver/item_requirements.go | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dserver/nano_kit.go | 92-------------------------------------------------------------------------------
Aserver/resource_kit.go | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/resource_kit_test.go | 390+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dserver/treatment_kit.go | 96-------------------------------------------------------------------------------
13 files changed, 893 insertions(+), 272 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -445,6 +445,19 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train match that item rather than inheriting the health item's behavior. - [x] Use one sitting treatment kit. Check: it works in the permitted posture and combat state and is rejected outside those conditions without consumption. +- [x] Execute the issued startup laboratory's complete effect. Check: its lower + Treatment threshold works, both health and nano recover by 15, one charge is + consumed, and the sitting patient's 15-second Treatment lock persists with + both resources atomically. Shared catalog rules also cover the three authored + qualities of ordinary health laboratories and nano stims; see + [medical consumables](docs/medical-consumables.md). +- [ ] Generalize persistent skill locks for Nano Rechargers and other SkillTime + effects. Check: patient TimeSpace131 locks remain distinct from Treatment124 + and user FirstAid123, survive restart and expire correctly. Apply the native + SkillLockModifier382 formula coherently on use and on lock reconstruction, + including equipment/nano modifiers and timing boundaries; avoid scaling the + remaining duration twice at login. Use the same rule across kits, clinics + and specials where their recovered contracts agree. The First Aid item, native charge protocol and unresolved combat-healing delivery are recorded in [First Aid research](docs/first-aid.md). @@ -478,7 +491,7 @@ introduction and starting-item gameplay remain open below. shared catalog rules, including Meta Shield AC and solar Fling. Omni shirt and basic boards now wear through shared catalog clothing rules; owner/observer appearance/AC, faction rejection and cold recovery are verified. - Startup crystals, healing-kit use, maps, shell, board upgrades and remaining + Startup crystals, First Aid use, maps, shell, board upgrades and remaining weapon specials (Burst, Aimed Shot, Brawl and Dimach) still need gameplay support. Verify those actions and each starting profession in its real training ground. Corroborate the four provisional pistol allocations, MA Oak Bo allocation, @@ -497,6 +510,9 @@ introduction and starting-item gameplay remain open below. placeholder names using period evidence. Original door transforms and usable entry checks are in [character creation](docs/character-creation.md) and [player appearance](docs/character-appearance.md). + Check spawn clearance after native collision settles: the current Omni + starting position can leave standing/seated characters on the Exit to City + portal's base. Confirm the authored arrival position before changing it. Audit first death, reclaim and resurrection in every faction's training ground, including characters that have never used an insurance scanner. - [x] Populate a new player's action bar with the default actions. Check: a diff --git a/docs/first-aid.md b/docs/first-aid.md @@ -74,6 +74,24 @@ in `local/reports/combat-client-decompiles-19.json`. ## Prototype checks and remaining delivery gap +A native UI-consumer audit confirms that the discrepancy reaches both health +displays. Local StatView100424d0 reads Health27 through the mode2 skill getter. +Target indicators10062fd0/10065960 read the actor's HP mirror at+0x1b0, but +ordinary setter1006e030 synchronizes that mirror with Health27 on each write. +The retained combat samples show both157->149 after a queued8-damage impact; +there is no independent authoritative health bar protecting the display. +Native death entry instead checks Flags0 bit0x10, normally supplied by +CharacterAction99. An incorrect zero alone does not establish false death. +Full DDR/KKR evidence, exact consumers and a reproducible trace extraction are +under `local/starter-consumable-research/health-consumers/`. + +Startup First-Aid Kit116629 has the same delivery dependency. Its authored +effects restore both Health27 and Nano214 by5..7, lock the user's FirstAid123 +for40 seconds, require FirstAid>5 and explicitly permit combat. Supporting +only its nano half or adding an out-of-combat restriction would change the +item's contract. Its complete record was reverified against the original DB; +see [medical consumables](medical-consumables.md). + The local prototype stores charge debit and a 40-second deadline in one atomic inventory write, restores the remaining lock on login, and supports ordinary living connected friendly players. Its uniform inclusive heal roll, diff --git a/docs/medical-consumables.md b/docs/medical-consumables.md @@ -0,0 +1,110 @@ +# Catalog medical consumables + +The server decodes immediate resource kits from their catalog functions, +requirements, quality, range and lock metadata. There are no template-ID +branches for medical use. The full catalog admission test currently identifies +these seven definitions: + +| Template / authored QL | Item | Health | Nano | Lock | +| --- | --- | ---: | ---: | --- | +| 25812 / 1 | Treatment Laboratory | 30 | 0 | Patient Treatment 124, 15s | +| 25811 / 200 | HQ Health Treatment Laboratory | 1500 | 0 | Patient Treatment 124, 15s | +| 160277 / 400 | Superb Quality Health Treatment Laboratory | 5000 | 0 | Patient Treatment 124, 15s | +| 116628 / 1 | Startup Treatment Laboratory | 15 | 15 | Patient Treatment 124, 15s | +| 85366 / 1 | Simple Nano Kit | 0 | 10..12 | User First Aid 123, 40s | +| 85367 / 200 | Sophisticated Nano Kit | 0 | 1000 | User First Aid 123, 40s | +| 160295 / 400 | Ultra Sophisticated Nano Kit | 0 | 1500 | User First Aid 123, 40s | + +Exact qualities are supported; no new interpolation endpoints are inferred. +The startup laboratory requires Treatment strictly greater than 5, while +ordinary QL1 labs require greater than 7. Startup issue quantity 25 is separate +from catalog capacity 200. Neither value changes during reconnect. + +## Shared interpretation + +Equipment and kit actions share the recovered postfix boolean evaluator. +Kit use additionally interprets OnTarget18, the known SelectedTarget431 mask35, +patient Sitting430==2 and zero/nonzero combat410. Unknown predicates fail the +whole expression, including inside OR/NOT. The server's combat producer remains +the documented outgoing/incoming-attack reconstruction policy. Ordinary living, +connected player targets retain the existing permission subset; the native +client additionally applies its friendly/team gate. General NPC/PvP permissions +remain unresolved. + +Use functions must be unconditional with one tick and zero interval. Supported +Hit53002 effects restore positive Health27 or Nano214 to the selected patient, +with valid endpoints and no additional hit flags. The native TemplateAction +runs GfxEffect53030; the server supplies the actual resource gains. StaticText +53044 is delivered privately through ChatTextIIR. SkillTime53033 determines +the lock skill and raw duration; native loader1008ede0 selects user/patient +from stat371. Activate10 AddSkill53028 initializes item skill-list metadata +and does not buff the player's Treatment or First Aid. + +Every effect is inspected before admission. Unknown functions, conditional or +repeating effects, different recipients, unsupported lock skills and positive +attack delays remain unsupported. The startup First-Aid Kit116629 must restore +both health and nano during combat; it is not admitted as a nano-only item or +given a new combat prohibition. See [First Aid delivery](first-aid.md). + +Accepted use commits both resource values, one source charge and the proper +actor's cooldown in the same SQLite transaction before success. Current values +clamp independently to their maxima. Rejected uses consume nothing. Exhaustion +removes the persisted item and sends native CharacterAction112 after the +success ACK. TemplateAction uses the actual template, quality and source slot; +it does not debit another charge. Nano and cooldown messages go only to their +respective recipients, while graphics and quiet health reach ready observers. +Failure of the healer's connection after commit does not suppress a healthy +patient's resource and cooldown updates. + +## Evidence and remaining work + +All 30 named medical candidates were reparsed directly from the original 14.9.1 +ResourceDatabase.dat and matched the catalog's complete functions, requirements, +stats, quality, native type and payload hashes. The family inventory, exclusions, +five-record comparison and reused native evidence are retained under +`local/starter-consumable-research/`. The original kkr.dll SHA-256 is +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +The named search bounds the research; the Go admission test scans all templates. + +Uniform inclusive rolls, full-resource consumption and absolute persisted lock +lifetimes remain reconstruction policies. SkillLockModifier382 and raw-duration +reconstruction on login need a shared cooldown audit. Nano Rechargers +25820/25821/160278 require patient TimeSpace131 locks, beyond the current +Treatment receipts. Emergency laboratories add53051; Purge kits add53177 and +different lock semantics. These functions must be implemented as complete +contracts before those items are admitted. General use from inside backpacks +and other quality families remain open. + +## Verification + +Public item-use tests cover all seven admitted definitions, exact qualities, +strict skill thresholds, posture, incoming/outgoing combat, inclusive range, +dead/loading/missing targets, unknown effects and predicates, independent +resource clamps, last-charge removal, replay and concurrent use. Injected +SQLite failures in the charge, cooldown and each resource leave the entire +outcome unchanged. Cold reopen and failed-healer-output tests verify that the +healthy patient's two resources and lock survive together. Unsupported health +and dual-resource First Aid kits reject the whole action without consumption. +The full Go suite, focused race tests and vet pass. Counterfactual tests fail +against the preceding hardcoded handlers. + +Two actual GPU/OpenGL WASM clients verified an issued Doctor laboratory. +Self-use raised health and nano by exactly 15 and reduced the stack from 25 +to 24; an immediate repeat during the 15-second lock consumed nothing. +Standing-patient attempts also consumed nothing. After joining through the +native team UI, a standing healer treated a seated teammate: both resources +rose from 10 to 25, only the patient received Treatment124, and the stack +fell to 23. Another use after the lock expired left 22 charges and clamped +each resource to its own maximum. + +For the cold WASM check, the existing patient's receipt was extended through +the control panel to outlast loading both clients. Restart restored the lock +only to that patient, preserved item instance120 and all 22 charges, and +rejected use against the locked, seated patient without another debit. The +authored 15-second deadline is checked separately by Go cold-reopen tests. +A control-panel count adjustment to one then verified native and SQLite +last-charge deletion while preserving all seven other starter item instances. +Passive regeneration remained enabled; short read-only native traces isolate +the kit's gains from regeneration ticks. Screenshots, WebSocket captures, +native observations, SQLite snapshots and fixture adjustments are retained +under `local/starter-laboratory-smoke/`. Both browser error lists were empty. diff --git a/docs/nano-kit.md b/docs/nano-kit.md @@ -1,6 +1,8 @@ # Simple Nano Kit -The server supports QL 1 Simple Nano Kit 85366 from ordinary inventory, +The server supports exact-QL Nano Kits 85366/QL1, 85367/QL200 and 160295/QL400 +through shared [medical consumable rules](medical-consumables.md). +The QL1 Simple Nano Kit 85366 is usable 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`. diff --git a/docs/treatment-kit.md b/docs/treatment-kit.md @@ -1,6 +1,10 @@ # Treatment Laboratory -The supported item is Treatment Laboratory25812, QL1, from the selected +Supported labs are Treatment Laboratory 25812/QL1, 25811/QL200, 160277/QL400 and +Startup Treatment Laboratory 116628/QL1. Shared catalog decoding and the +startup kit's combined 15-HP/15-nano recovery are described in +[medical consumables](medical-consumables.md). The following reference is +Treatment Laboratory25812, QL1, from the selected 14.9.1 database. Its record is at offset128476411 with payload SHA256 `216cf2dc3a20028e17b718895a17f7ae746f6912192ba37d374086f4279e9dff`. @@ -42,8 +46,9 @@ when the selected patient is unlocked. 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. +health and any authored nano gain 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 diff --git a/server/backpacks.go b/server/backpacks.go @@ -101,13 +101,12 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error return server.useRemoteBank_locked(client, player.inventory.Items[index], body) case 43330, 29625, 28778: return server.learnNano_locked(client, index, body) - case 85366: - return server.useNanoKit_locked(client, index, body) - case 25812: - return server.useTreatmentKit_locked(client, index, body) case 43552: return server.useClinic_locked(client, index, body) default: + if kit, supported := player.inventory.Items[index].resourceKit(); supported { + return server.useResourceKit_locked(client, index, body, kit) + } if abilityNanoCrystalProgram(player.inventory.Items[index].Template) != 0 { return server.learnNano_locked(client, index, body) } diff --git a/server/equipment.go b/server/equipment.go @@ -65,10 +65,10 @@ func (character *character) canEquip(item ownedItem) bool { return character.effectiveAbility(16) > 5 && character.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 10 } if item.isWieldableWeapon() { - return character.equipmentRequirementsMet(item, 8) + return item.requirementsMet(8, character.meetsStatRequirement) } if item.isClothing() { - return character.equipmentRequirementsMet(item, 6) + return item.requirementsMet(6, character.meetsStatRequirement) } return false } diff --git a/server/equipment_requirements.go b/server/equipment_requirements.go @@ -1,73 +0,0 @@ -package main - -import "ao/server/gamedata" - -func (character *character) equipmentRequirementsMet(item ownedItem, actionType uint32) bool { - low, high := item.templateIDs() - first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] - for sectionIndex, section := range first.Sections { - if section.Actions == nil { - continue - } - for actionIndex, action := range *section.Actions { - if action.Type != actionType { - continue - } - - // kkr.dll 100056e0 evaluates postfix operators without short circuiting. - var stack []bool - for index, requirement := range action.Requirements { - switch requirement.Operator { - case 3, 4: - if len(stack) < 2 { - return false - } - last := len(stack) - 1 - if requirement.Operator == 3 { - stack[last-1] = stack[last-1] || stack[last] - } else { - stack[last-1] = stack[last-1] && stack[last] - } - stack = stack[:last] - case 42: - if len(stack) == 0 { - return false - } - stack[len(stack)-1] = !stack[len(stack)-1] - case 0, 1, 2, 24: - // Unequal uses getter mode 2. Only intrinsic stats have proven parity. - if requirement.Operator == 24 { - switch requirement.Stat { - case 4, 33, 37, 54, 59, 60, 89: - default: - return false - } - } - actual, known := character.effectiveStat(uint32(requirement.Stat)) - if !known { - return false - } - value := interpolateItemValue(requirement.Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) - passed := actual == value - switch requirement.Operator { - case 1: - passed = actual < value - case 2: - passed = actual > value - case 24: - passed = actual != value - } - stack = append(stack, passed) - default: - // Unknown predicates cannot grant equipment, including inside OR/NOT. - return false - } - } - // Native evaluation accepts an empty list and returns the final top value. - if len(stack) != 0 && !stack[len(stack)-1] { - return false - } - } - } - return true -} diff --git a/server/item_requirements.go b/server/item_requirements.go @@ -0,0 +1,87 @@ +package main + +import "ao/server/gamedata" + +func (item ownedItem) requirementsMet(actionType uint32, evaluate func(gamedata.ItemRequirement) (bool, bool)) bool { + low, high := item.templateIDs() + first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] + for sectionIndex, section := range first.Sections { + if section.Actions == nil { + continue + } + for actionIndex, action := range *section.Actions { + if action.Type != actionType { + continue + } + + // kkr.dll 100056e0 evaluates postfix operators without short circuiting. + var stack []bool + for index, requirement := range action.Requirements { + switch requirement.Operator { + case 3, 4: + if len(stack) < 2 { + return false + } + last := len(stack) - 1 + if requirement.Operator == 3 { + stack[last-1] = stack[last-1] || stack[last] + } else { + stack[last-1] = stack[last-1] && stack[last] + } + stack = stack[:last] + case 42: + if len(stack) == 0 { + return false + } + stack[len(stack)-1] = !stack[len(stack)-1] + default: + requirement.Value = interpolateItemValue(requirement.Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) + passed, known := evaluate(requirement) + if !known { + return false + } + if requirement.Operator == 18 { + // OnTarget changes subject without pushing a boolean operand. + if !passed { + return false + } + continue + } + stack = append(stack, passed) + } + } + // Native evaluation accepts an empty list and returns the final top value. + if len(stack) != 0 && !stack[len(stack)-1] { + return false + } + } + } + return true +} + +func (character *character) meetsStatRequirement(requirement gamedata.ItemRequirement) (bool, bool) { + if requirement.Operator != 0 && requirement.Operator != 1 && requirement.Operator != 2 && requirement.Operator != 24 { + return false, false + } + // Unequal uses getter mode 2. Only intrinsic stats have proven parity. + if requirement.Operator == 24 { + switch requirement.Stat { + case 4, 33, 37, 54, 59, 60, 89: + default: + return false, false + } + } + actual, known := character.effectiveStat(uint32(requirement.Stat)) + if !known { + return false, false + } + switch requirement.Operator { + case 1: + return actual < requirement.Value, true + case 2: + return actual > requirement.Value, true + case 24: + return actual != requirement.Value, true + } + return actual == requirement.Value, true +} diff --git a/server/nano_kit.go b/server/nano_kit.go @@ -1,92 +0,0 @@ -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 && - player.effectiveSkill(123, stats.NanoAiding.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, cooldown and resource gain before 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) - - // The catalog supplies endpoints; uniform inclusive integer rolls remain provisional. - 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) - 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/resource_kit.go b/server/resource_kit.go @@ -0,0 +1,255 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "maps" + "math/rand/v2" + "slices" + "time" +) + +type resourceKit struct { + health [2]uint32 + nano [2]uint32 + lockSkill uint32 + lockSeconds uint32 + text string +} + +func (item ownedItem) resourceKit() (resourceKit, bool) { + definition := gamedata.ItemTemplates[item.Template] + kit := resourceKit{} + if item.Type != 51005 || definition == nil || definition.HeaderWords[0] != item.Type || + item.Quality != *definition.Quality || itemStat(definition, 76) != 0 || + itemStat(definition, 30)&40 != 40 || itemStat(definition, 212) == 0 || itemStat(definition, 294) != 0 { + return kit, false + } + + // Decode the complete immediate-use contract, including activation metadata. + var metadataSkill uint32 + for _, section := range definition.Sections { + if section.Type != 2 { + continue + } + for _, function := range *section.Functions { + if len(function.Requirements) != 0 || function.TickCount != 1 || function.TickInterval != 0 { + return kit, false + } + if section.Subtype == 10 { + if function.ID != 53028 || len(function.Arguments) != 3 || + *function.Arguments[0].Integer != 3 || *function.Arguments[2].BytesHex != "01000000" || + (function.Target != 1 && function.Target != 3) || metadataSkill != 0 { + return kit, false + } + metadataSkill = uint32(*function.Arguments[1].Integer) + continue + } + if section.Subtype != 0 { + return kit, false + } + switch function.ID { + case 53002: + if function.Target != 3 || len(function.Arguments) != 4 || *function.Arguments[1].Integer <= 0 || + *function.Arguments[2].Integer < *function.Arguments[1].Integer || *function.Arguments[3].Integer != 0 { + return kit, false + } + values := [2]uint32{uint32(*function.Arguments[1].Integer), uint32(*function.Arguments[2].Integer)} + switch *function.Arguments[0].Integer { + case 27: + if kit.health[1] != 0 { + return kit, false + } + kit.health = values + case 214: + if kit.nano[1] != 0 { + return kit, false + } + kit.nano = values + default: + return kit, false + } + case 53030: + if function.Target != 3 { + return kit, false + } + case 53033: + if kit.lockSkill != 0 || len(function.Arguments) != 3 || *function.Arguments[0].BytesHex != "09000000" || *function.Arguments[2].Integer <= 0 { + return kit, false + } + kit.lockSkill, kit.lockSeconds = uint32(*function.Arguments[1].Integer), uint32(*function.Arguments[2].Integer) + case 53044: + if function.Target != 3 || kit.text != "" || len(function.Arguments) != 2 || *function.Arguments[1].BytesHex != "0000000000000000000000000000000000000000" { + return kit, false + } + kit.text = *function.Arguments[0].String + default: + return kit, false + } + } + } + + // SkillTime's target is rewritten from stat 371 by the native resource loader. + if metadataSkill != kit.lockSkill || kit.health[1] == 0 && kit.nano[1] == 0 { + return kit, false + } + if kit.lockSkill == 123 && itemStat(definition, 371) == 0 { + // Combat HP delivery is unresolved; do not consume only a stim's nano half. + return kit, kit.health[1] == 0 + } + return kit, kit.lockSkill == 124 && itemStat(definition, 371) != 0 +} + +func (server *server) itemUseRequirementsMet_locked(player, target *character, item ownedItem) bool { + subject := player + return item.requirementsMet(3, func(requirement gamedata.ItemRequirement) (bool, bool) { + if requirement.Operator == 18 { + subject = target + return true, true + } + switch requirement.Stat { + case 410: + // The current combat producer establishes zero/nonzero, not an exact count. + if requirement.Operator == 0 && requirement.Value == 0 { + return !server.characterInCombat_locked(subject), true + } + return false, false + case 430: + if requirement.Operator == 0 && requirement.Value == 2 { + return subject.sitting, true + } + return false, false + case 431: + // The caller has validated the selected living, connected player subset. + if subject != player || requirement.Operator != 22 || requirement.Value != 35 { + return false, false + } + return true, true + } + return subject.meetsStatRequirement(requirement) + }) +} + +func (server *server) useResourceKit_locked(client *worldClient, index int, body []byte, kit resourceKit) error { + player := server.characters[client.id] + item := player.inventory.Items[index] + target := server.characters[client.selectedTarget[1]] + now := time.Now() + accepted := 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 + if accepted { + accepted = server.itemUseRequirementsMet_locked(player, target, item) + if kit.lockSkill == 123 { + accepted = accepted && !now.Before(player.inventory.FirstAidLockedUntil) + } else { + accepted = accepted && !now.Before(target.treatmentLockedUntil) + } + 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] + distance := float32(itemStat(gamedata.ItemTemplates[item.Template], 287)) + player.physicalExtent() + target.physicalExtent() + accepted = accepted && x*x+y*y+z*z <= distance*distance + } + if accepted { + // Commit both resources, charge and the correct actor's cooldown together. + 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) + } + deadline := now.Add(time.Duration(kit.lockSeconds) * time.Second) + if kit.lockSkill == 123 { + inventory.FirstAidLockedUntil = deadline + } else { + inventory.TreatmentLocks = maps.Clone(inventory.TreatmentLocks) + if inventory.TreatmentLocks == nil { + inventory.TreatmentLocks = make(map[uint32]time.Time) + } + for id, until := range inventory.TreatmentLocks { + if !now.Before(until) { + delete(inventory.TreatmentLocks, id) + } + } + inventory.TreatmentLocks[target.id] = deadline + } + vitals := target.vitals() + // Uniform inclusive endpoint rolls remain a reconstruction policy. + if kit.health[1] != 0 { + vitals.Health = min(target.maximumHealth(), vitals.Health+kit.health[0]+rand.Uint32N(kit.health[1]-kit.health[0]+1)) + } + if kit.nano[1] != 0 { + vitals.Nano = min(target.maximumNano(), vitals.Nano+kit.nano[0]+rand.Uint32N(kit.nano[1]-kit.nano[0]+1)) + } + if err := server.saveItemEffect_locked(player, target, inventory, vitals); err != nil { + return err + } + if kit.lockSkill == 124 { + target.treatmentLockedUntil = deadline + } + } + + reply := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(reply, 2) + if accepted { + binary.BigEndian.PutUint32(reply, 1) + } + ackError := client.send(n3Packet(0x52526858, 50000, client.id, reply)) + if !accepted { + return ackError + } + + // The ACK debits one native charge; TemplateAction runs the authored graphics. + var action []byte + low, high := item.templateIDs() + for _, value := range []uint32{low, high, item.Quality, 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)) + if kit.health[1] != 0 { + server.queueQuietHealth_locked(updates, target) + } + if item.Count == 1 { + var removal []byte + for _, value := range []uint32{112, 104, item.Slot, low, high} { + removal = binary.BigEndian.AppendUint32(removal, value) + } + updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, client.id, removal)) + } + lockRecipient := player + if kit.lockSkill == 124 { + lockRecipient = target + } + lockClient := server.clients[lockRecipient.id] + updates[lockClient] = append(updates[lockClient], skillLockPacket(lockRecipient.id, kit.lockSkill, kit.lockSeconds)) + if kit.nano[1] != 0 { + var nano []byte + for _, value := range []uint32{214, target.nano} { + nano = binary.BigEndian.AppendUint32(nano, value) + } + updates[server.clients[target.id]] = append(updates[server.clients[target.id]], n3Packet(0x2b333d6e, 50000, target.id, nano)) + } + if kit.text != "" { + // StaticText's local handler is empty; deliver the authored recipient text. + feedback := binary.BigEndian.AppendUint32(nil, uint32(len(kit.text))) + feedback = append(feedback, kit.text...) + feedback = append(feedback, 0, 0) + updates[server.clients[target.id]] = append(updates[server.clients[target.id]], n3Packet(0x5f4b442a, 50000, target.id, feedback)) + } + + // A failed healer connection must not suppress the healthy patient's outcome. + sourcePackets := updates[client] + delete(updates, client) + server.sendCombatUpdates(updates) + if ackError != nil { + return ackError + } + for _, packet := range sourcePackets { + if err := client.send(packet); err != nil { + return err + } + } + return nil +} diff --git a/server/resource_kit_test.go b/server/resource_kit_test.go @@ -0,0 +1,390 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "sync" + "testing" + "time" +) + +func TestResourceKitCatalogAdmission(t *testing.T) { + var admitted []uint32 + + for _, definition := range gamedata.ItemTemplates { + if definition.Quality == nil { + continue + } + item := ownedItem{Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality} + if _, supported := item.resourceKit(); supported { + admitted = append(admitted, definition.ID) + } + } + slices.Sort(admitted) + + if !reflect.DeepEqual(admitted, []uint32{25811, 25812, 85366, 85367, 116628, 160277, 160295}) { + t.Fatal("unexpected medical use contract in the full catalog", admitted) + } +} + +func newStartupLaboratoryWorld(t *testing.T, other bool) (*server, *character, *combatTestConn) { + t.Helper() + world, target, conn := newConsumableOutcomeWorld(t, 25812, other) + player := world.characters[1] + player.inventory.Items[0].Template, player.inventory.Items[0].Count = 116628, 25 + player.stats.NanoAiding.Treatment = 4 + target.nano = 1 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + // Persist the fixture's source quantity and both patient resources. + if err := world.saveItemEffect_locked(player, target, player.inventory, target.vitals()); err != nil { + t.Fatal(err) + } + return world, target, conn +} + +func TestCatalogResourceKitsUseAuthoredQualityAmountsAndLocks(t *testing.T) { + for _, scenario := range []struct { + template, quality, count uint32 + health, nanoLow, nanoHigh uint32 + }{ + {25812, 1, 50, 30, 0, 0}, {25811, 200, 50, 1500, 0, 0}, + {160277, 400, 50, 5000, 0, 0}, {85366, 1, 25, 0, 10, 12}, + {85367, 200, 25, 0, 1000, 1000}, {160295, 400, 25, 0, 1500, 1500}, + {116628, 1, 25, 15, 15, 15}, + } { + t.Run(fmt.Sprint(scenario.template), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.level = 200 + player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 60000, 60000 + player.stats.NanoAiding.Treatment, player.stats.NanoAiding.FirstAid = 5000, 5000 + player.health, player.nano, player.sitting = 1, 1, true + player.inventory.Items[0] = ownedItem{ID: 1, Type: 51005, Template: scenario.template, Quality: scenario.quality, Slot: 64, Count: uint16(scenario.count)} + client.selectedTarget = [2]uint32{50000, 1} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + started := time.Now() + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || player.health != 1+scenario.health || player.nano < 1+scenario.nanoLow || player.nano > 1+scenario.nanoHigh || + restored.health != player.health || restored.nano != player.nano || player.inventory.Items[0].Count != uint16(scenario.count-1) || + !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || + binary.BigEndian.Uint32(conn.packets[1][29:33]) != scenario.template || binary.BigEndian.Uint32(conn.packets[1][37:41]) != scenario.quality { + t.Fatal("catalog restoration, quality, charge or persistence mismatch", err) + } + deadline, seconds := player.treatmentLockedUntil, 15*time.Second + if scenario.health == 0 { + deadline, seconds = player.inventory.FirstAidLockedUntil, 40*time.Second + } + if deadline.Before(started.Add(seconds)) || deadline.After(time.Now().Add(seconds)) { + t.Fatal("cooldown differs from the authored SkillTime") + } + }) + } +} + +func TestStartupLaboratoryCommitsBothResourcesBeforeSuccess(t *testing.T) { + for _, other := range []bool{false, true} { + for _, count := range []uint16{1, 25} { + t.Run(fmt.Sprintf("other%t/count%d", other, count), func(t *testing.T) { + world, target, _ := newStartupLaboratoryWorld(t, other) + player := world.characters[1] + player.inventory.Items[0].Count = count + 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.health != 16 || conn.nano != 16 || conn.count != count-1 || + !conn.patient.Valid || conn.patient.Time.IsZero() || !conn.firstAid.IsZero() || + target.health != 16 || target.nano != 16 || restored.characters[target.id].health != 16 || restored.characters[target.id].nano != 16 || + !restored.characters[target.id].treatmentLockedUntil.Equal(target.treatmentLockedUntil) { + t.Fatal("success preceded an atomic dual-resource/charge/patient-lock commit", err, conn.err) + } + if count == 1 { + if len(player.inventory.Items) != 0 || len(restored.items) != 0 { + t.Fatal("exhausted startup laboratory remained in the item store") + } + removed := slices.ContainsFunc(conn.packets, func(packet []byte) bool { + return binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 112 && + binary.BigEndian.Uint32(packet[41:45]) == 116628 && binary.BigEndian.Uint32(packet[45:49]) == 116628 + }) + if !removed { + t.Fatal("last charge did not remove the native startup row") + } + } else if len(restored.items) != 1 || restored.characters[1].inventory.Items[0].Count != 24 { + t.Fatal("startup quantity or identity changed unexpectedly") + } + }) + } + } +} + +func TestStartupLaboratoryRollbackPreservesBothResourcesAndRetries(t *testing.T) { + for _, phase := range []string{"charge", "lock", "health", "nano"} { + t.Run(phase, func(t *testing.T) { + world, target, conn := newStartupLaboratoryWorld(t, true) + player := world.characters[1] + statement := "CREATE TRIGGER reject_startup BEFORE UPDATE ON items BEGIN SELECT RAISE(FAIL, 'charge'); END" + switch phase { + case "lock": + statement = "CREATE TRIGGER reject_startup BEFORE INSERT ON treatment_locks BEGIN SELECT RAISE(FAIL, 'lock'); END" + case "health": + statement = "CREATE TRIGGER reject_startup BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'health'); END" + case "nano": + statement = "CREATE TRIGGER reject_startup BEFORE UPDATE OF nano ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'nano'); END" + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + after, _ := readTestItemStore(world) + var savedHealth, savedNano uint32 + if queryErr := world.db.QueryRow("SELECT health,nano FROM characters WHERE id=2").Scan(&savedHealth, &savedNano); queryErr != nil { + t.Fatal(queryErr) + } + if err == nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 25 || + savedHealth != 1 || savedNano != 1 || len(player.inventory.TreatmentLocks) != 0 || !target.treatmentLockedUntil.IsZero() || len(conn.packets) != 0 { + t.Fatal("failed dual restoration left a partial gain, debit or cooldown", err) + } + if _, err := world.db.Exec("DROP TRIGGER reject_startup"); err != nil { + t.Fatal(err) + } + err = world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) + restored := newTestInventoryServer(t) + + if err != nil || target.health != 16 || target.nano != 16 || player.inventory.Items[0].Count != 24 || + restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].treatmentLockedUntil.IsZero() { + t.Fatal("rolled-back startup use could not retry atomically", err) + } + }) + } +} + +func TestStartupLaboratoryRejectsInvalidStateAndRetainsBothResources(t *testing.T) { + for _, scenario := range []string{"standing patient", "skill equality", "patient lock", "healer attacking", "patient attacking", "incoming healer", "incoming patient", "far", "loading", "dead", "npc", "other zone", "no target", "wrong quality", "wrong type", "unknown predicate", "unknown negated predicate", "unsupported function", "conditional effect", "repeating effect", "wrong effect target"} { + t.Run(scenario, func(t *testing.T) { + world, target, conn := newStartupLaboratoryWorld(t, true) + player, client := world.characters[1], world.clients[1] + original := gamedata.ItemTemplates[116628] + definition := *original + definition.Sections = slices.Clone(original.Sections) + switch scenario { + case "standing patient": + target.sitting = false + case "skill equality": + player.stats.NanoAiding.Treatment = 3 + case "patient lock": + target.treatmentLockedUntil = time.Now().Add(time.Minute) + case "healer attacking": + player.fighting = 1000000 + case "patient attacking": + target.fighting = 1000000 + case "incoming healer", "incoming patient": + attacker := &character{id: 1000000, npc: true, fighting: 1} + if scenario == "incoming patient" { + attacker.fighting = 2 + } + world.fighting[attacker.id] = attacker + case "far": + target.position[0] = player.position[0] + 7.125 + case "loading": + world.clients[2].loading = true + case "dead": + target.health = 0 + case "npc": + target.npc = true + case "other zone": + target.playfield = 705 + case "no target": + client.selectedTarget = [2]uint32{} + case "wrong quality": + player.inventory.Items[0].Quality = 2 + case "wrong type": + player.inventory.Items[0].Type = 51022 + case "unknown predicate", "unknown negated predicate": + requirements := []gamedata.ItemRequirement{{Stat: 9999, Value: 0, Operator: 0}} + if scenario == "unknown negated predicate" { + requirements = append(requirements, gamedata.ItemRequirement{Operator: 42}) + } + actions := []gamedata.ItemAction{{Type: 3, Requirements: requirements}} + definition.Sections[2].Actions = &actions + case "unsupported function", "conditional effect", "repeating effect", "wrong effect target": + functions := slices.Clone(*definition.Sections[0].Functions) + switch scenario { + case "unsupported function": + functions[0].ID = 53051 + case "conditional effect": + functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 0, Operator: 2}} + case "repeating effect": + functions[0].TickCount = 2 + case "wrong effect target": + functions[0].Target = 2 + } + definition.Sections[0].Functions = &functions + } + gamedata.ItemTemplates[116628] = &definition + t.Cleanup(func() { gamedata.ItemTemplates[116628] = original }) + before, _ := readTestItemStore(world) + health, nano := target.health, target.nano + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || player.inventory.Items[0].Count != 25 || target.health != health || target.nano != nano || + len(player.inventory.TreatmentLocks) != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("rejected startup use consumed a charge or partially restored a resource", err) + } + }) + } +} + +func TestStartupLaboratoryConcurrentReplayRestoresBothResourcesOnce(t *testing.T) { + world, target, _ := newStartupLaboratoryWorld(t, true) + var group sync.WaitGroup + errors := make(chan error, 16) + + for sequence := uint32(1); sequence <= 16; sequence++ { + group.Go(func() { + errors <- world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, sequence)[20:]) + }) + } + group.Wait() + close(errors) + restored := newTestInventoryServer(t) + + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + if target.health != 16 || target.nano != 16 || world.characters[1].inventory.Items[0].Count != 24 || + restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[1].inventory.Items[0].Count != 24 { + t.Fatal("racing/replayed uses applied a partial or duplicate restoration") + } +} + +func TestStartupLaboratoryClampsEachResourceIndependently(t *testing.T) { + for _, scenario := range []string{"both full", "health full", "nano full", "one missing"} { + t.Run(scenario, func(t *testing.T) { + world, target, _ := newStartupLaboratoryWorld(t, false) + health, nano := uint32(16), uint32(16) + switch scenario { + case "both full": + target.health, target.nano = target.maximumHealth(), target.maximumNano() + health, nano = target.maximumHealth(), target.maximumNano() + case "health full": + target.health, health = target.maximumHealth(), target.maximumHealth() + case "nano full": + target.nano, nano = target.maximumNano(), target.maximumNano() + case "one missing": + target.health, target.nano = target.maximumHealth()-1, target.maximumNano()-1 + health, nano = target.maximumHealth(), target.maximumNano() + } + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || target.health != health || target.nano != nano || restored.health != health || restored.nano != nano || + target.inventory.Items[0].Count != 24 || restored.inventory.Items[0].Count != 24 { + t.Fatal("dual restoration clamped the wrong resource or failed to consume once", err) + } + }) + } +} + +func TestStartupLaboratoryPatientCooldownRangeBoundaryAndPrivateNano(t *testing.T) { + world, target, _ := newStartupLaboratoryWorld(t, true) + player := world.characters[1] + player.sitting = false + player.treatmentLockedUntil = time.Now().Add(600 * time.Second) + healerLock := player.treatmentLockedUntil + target.position = player.position + target.position[0] += 7 + observer := &combatTestConn{} + world.characters[3] = &character{id: 3, playfield: player.playfield, position: player.position, health: 100} + world.clients[3] = &worldClient{id: 3, conn: observer, target: true, ready: true} + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + deadline := target.treatmentLockedUntil + world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) + if player.inventory.Items[0].Count != 24 || target.health != 16 || target.nano != 16 { + t.Fatal("patient cooldown admitted the immediate repeat") + } + world.advanceItemEffects(deadline) + world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 3)[20:]) + + if err != nil || target.health != 31 || target.nano != 31 || player.inventory.Items[0].Count != 23 || + !player.treatmentLockedUntil.Equal(healerLock) || len(observer.packets) != 4 { + t.Fatal("standing, locked healer failed at the inclusive range boundary or patient expiry", err) + } + for _, packet := range observer.packets { + key := binary.BigEndian.Uint32(packet[16:20]) + if key != 0x35505644 && key != 0x3710256c { + t.Fatal("observer received the patient's private nano or cooldown state") + } + } +} + +func TestStartupLaboratoryOutputFailurePreservesBothGainsAndPatientLock(t *testing.T) { + world, target, _ := newStartupLaboratoryWorld(t, true) + world.clients[1].writeWake, world.clients[1].writeClosed = make(chan struct{}, 1), true + + failedOutput := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + patientPackets := world.clients[2].conn.(*combatTestConn).packets + restored := newTestInventoryServer(t) + conn := &combatTestConn{} + restored.clients[1] = &worldClient{id: 1, conn: conn, target: true, ready: true, selectedTarget: [2]uint32{50000, 2}} + restored.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true} + replay := restored.handleOwnedItemUse(restored.clients[1], backpackUseRequest(1, 64, 2)[20:]) + + if failedOutput == nil || replay != nil || target.health != 16 || target.nano != 16 || + restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].treatmentLockedUntil.IsZero() || + restored.characters[1].inventory.Items[0].Count != 24 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("output failure lost part of the committed effect or allowed another debit", failedOutput, replay) + } + if len(patientPackets) != 4 || binary.BigEndian.Uint32(patientPackets[2][41:45]) != 124 || + binary.BigEndian.Uint32(patientPackets[3][29:33]) != 214 || binary.BigEndian.Uint32(patientPackets[3][33:37]) != 16 { + t.Fatal("failed healer output suppressed the healthy patient's resource/lock replication") + } +} + +func TestUnimplementedFirstAidNeverConsumesOnlyPartOfItsEffect(t *testing.T) { + for _, template := range []uint32{23314, 116629} { + t.Run(fmt.Sprint(template), func(t *testing.T) { + world, target, conn := newStartupLaboratoryWorld(t, true) + player := world.characters[1] + player.inventory.Items[0].Template, player.inventory.Items[0].Count = template, 1 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 1 || + !player.inventory.FirstAidLockedUntil.IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("unsupported First Aid partially restored a resource, consumed its last charge or started a lock", err) + } + }) + } +} diff --git a/server/treatment_kit.go b/server/treatment_kit.go @@ -1,96 +0,0 @@ -package main - -import ( - "encoding/binary" - "maps" - "slices" - "time" -) - -func (server *server) useTreatmentKit_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 == 25812 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && - client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 && target.sitting && - target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading && - player.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 7 && !now.Before(target.treatmentLockedUntil) && - player.fighting == 0 && target.fighting == 0 - if accepted { - // InBattle includes incoming combat; its original server producer is unknown. - for _, attacker := range server.fighting { - if attacker.fighting == player.id || attacker.fighting == target.id { - accepted = false - break - } - } - 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] - distance := 3 + player.physicalExtent() + target.physicalExtent() - accepted = accepted && x*x+y*y+z*z <= distance*distance - } - if accepted { - // Save the charge, patient lock and resource gain together. - 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.TreatmentLocks = maps.Clone(inventory.TreatmentLocks) - if inventory.TreatmentLocks == nil { - inventory.TreatmentLocks = make(map[uint32]time.Time) - } - for id, deadline := range inventory.TreatmentLocks { - if !now.Before(deadline) { - delete(inventory.TreatmentLocks, id) - } - } - inventory.TreatmentLocks[target.id] = now.Add(15 * time.Second) - 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] - } - - 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 - } - - // Native success consumes one charge; the template action supplies the graphics. - var action []byte - for _, value := range []uint32{25812, 25812, 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)) - var health []byte - for _, value := range []uint32{target.health, 0, 0, 0} { - health = binary.BigEndian.AppendUint32(health, value) - } - server.queueCombat_locked(updates, target, target, n3Packet(0x3710256c, 50000, target.id, health)) - server.sendCombatUpdates(updates) - if item.Count == 1 { - var removal []byte - for _, value := range []uint32{112, 104, item.Slot, 25812, 25812} { - removal = binary.BigEndian.AppendUint32(removal, value) - } - if err := client.send(n3Packet(0x5e477770, 50000, client.id, removal)); err != nil { - return err - } - } - return server.clients[target.id].send(skillLockPacket(target.id, 124, 15)) -}