aorecomp

Anarchy Online classic in the browser

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


commit 929583fac45c4e5db2a8ba890e3e4ae87d452087
parent 8662590ea289ee764580eaa6b19d2c075630f0df
Author: anon <anon@example.com>
Date:   Sun, 25 Oct 2026 01:23:20 +0000

Support complete ordinary stat buffs and regeneration nanos

Diffstat:
MTODO.md | 31+++++++++++++++++++------------
Mdocs/combat-regeneration.md | 6+++---
Mdocs/nano-buffs.md | 131++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mdocs/nano-learning.md | 6++++++
Mserver/backpacks.go | 2+-
Mserver/item_requirements.go | 86++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Mserver/nano_buffs.go | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mserver/nano_casting.go | 19++++---------------
Mserver/nano_learning.go | 47++++++++++++++++++++++++++++++++++-------------
Aserver/regeneration_nano_test.go | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/stat_buff_catalog_test.go | 306+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/weapon_stats.go | 2+-
12 files changed, 759 insertions(+), 94 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -589,17 +589,24 @@ introduction and starting-item gameplay remain open below. damage and death handling work without starting an unintended weapon attack. - [x] Apply one temporary stat buff. Check: the native effect appears, the stat changes once, and expiration removes exactly that contribution. - All six basic ability Boosts and Augment Strength share catalog-driven - crystal uploads, casting, stat/NCU contributions and durable add/remove state. See + All six basic ability Boosts, six Augments, Enhanced Senses, Feline Grace + and Prodigious Strength share complete-contract crystal uploads, authored + postfix requirements, stat/NCU contributions and durable add/remove state. See [temporary nanos](docs/nano-buffs.md) for verification and policy limits. -- [ ] Audit and admit complete passive regeneration nano programs, beginning - with Regeneration27144 and Nano Restoration27118. The original catalog audit - retains13 delta programs in `local/regeneration-delta-research/catalog/`. - Check full casting requirements, cost, NCU/strain, duration, cancellation, - expiry, death and cold restore, plus additive equipment contributions. - The343/364 consumers are implemented; these programs remain uncastable until - their complete contracts qualify. Keep passive delta modifiers distinct from - periodic heal-over-time functions. +- [x] Audit and admit complete ordinary passive regeneration programs. + Regeneration27144, Nano Restoration27118, Hearty Constitution28663, + Continuous Reconstruction28651, Bot Reproduction29200 and Soothing Calm30095 + share authored casting criteria, NCU/strain, cost and duration. Tests cover + cancellation, exact expiry, death, failed persistence and cold restore with + additive equipment. See [temporary nanos](docs/nano-buffs.md). +- [ ] Complete the seven remaining delta programs from the13-program audit. + Titan Physique29254 and95693..95697 also modify MaxHealth1 and need the complete + direct nano maximum-health consumer, clamps and their authored flags/lifecycle. + Blood Circle27803 has special flags, no strain and zero casting cost/timing; + research its actual delivery path. The complete original records are retained + in `local/regeneration-nano-research/catalog/`. Never grant just a supported + subset of an unfinished program. Keep passive deltas distinct from periodic + heal-over-time functions. - [x] Enforce NCU capacity. Check: a buff fitting the available NCU succeeds and one exceeding it is rejected without charging resources incorrectly. Native checks cover exact fit at 8/8, rejecting a 9-NCU replacement without @@ -609,8 +616,8 @@ introduction and starting-item gameplay remain open below. follows its evidenced stacking rule without retaining both bonuses. - [x] Cancel one active buff manually. Check: its effect, stat contribution and NCU use disappear together. -- [x] Remove supported ability buffs on player death. Check: lethal combat - commits health, pending cast refund, buff removal and reclaim together; +- [x] Remove supported ordinary ability/regeneration buffs on player death. + Check: lethal combat commits health, pending cast refund, buff removal and reclaim together; owner and observer lose modifiers and NCU, including after resurrection. Statement and COMMIT failures preserve the living state and item ownership. - [ ] Verify remaining temporary nano lifecycle policies. Check: diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md @@ -115,9 +115,9 @@ cover the negative consumer independently of catalog admission. The complete implant audit adds 1,596 definitions whose remaining consumers are these two deltas. Implants with another unsupported effect still reject -as whole items. Original Regeneration27144 and Nano Restoration27118 provide -active-effect fixtures for the shared nano modifier calculation; this does -not add them to the list of castable programs. See [implants](implants.md). +as whole items; see [implants](implants.md). Six complete ordinary delta programs +support native crystal learning and casting through the same recovery consumers; +see [temporary nanos](nano-buffs.md#passive-regeneration-programs). Recovery stays in memory until a vitals checkpoint; equipping or removing these implants persists placement immediately without forcing unrelated vitals updates when the resource caps are unchanged. diff --git a/docs/nano-buffs.md b/docs/nano-buffs.md @@ -1,8 +1,81 @@ # Temporary nano research for 14.9.1 -The six +12 ability Boosts and Augment Strength share one timed-effect path. -All seven crystals use the native upload route. Learning and casting remain -separate operations; arbitrary nano functions are not enabled by this family. +Ordinary ability and passive regeneration buffs share one timed-effect path. +Complete-contract checks admit 21 original programs and their 21 crystals. +Learning and casting remain separate operations; arbitrary nano functions are +not enabled by this family. + +## Complete contract admission + +Programs require native header51051, ItemType0, Can0 and the audited raw +Flags0 value `0x80010000`. Duration, NCU, strain, cost, range, attack and recharge +must be positive finite values. Every effect is unconditional OnUse53045, +target3, tick1/interval0, with two integer arguments and an implemented consumer. +Positive ability16..21, HealDelta343 and NanoDelta364 modifiers qualify. +Signed SkillLockModifier382 also has a verified consumer, but no original +nano uses it; its synthetic lifecycle fixtures remain separate from content. + +The checker validates ordinary attack-weight dictionaries4/4 and getter-mode +maps6/27, plus action3 criteria22/36. Unknown metadata, additional effects, +other events, conditions or repetition reject the whole program. An ordinary +crystal requires header51005, Flags0=`0x80400203`, Can30=`0x29`, Count26=1 and +exactly one unconditional OnUse LearnNano53019, target2, for an admitted program. +Only its original authored quality is accepted; bulk TESTITEM uploads reject. + +Casting and crystal use evaluate the complete authored postfix expression +through the shared native requirement evaluator. Biological Metamorphosis128, +Matter Metamorphosis127, Psychological Modification129 and Matter Creation130 +use their actual trained values and ability weights. Real Profession60 and +VisualProfession368 criteria are distinct IDs; both currently read the saved +profession because false-profession effects are not implemented. Unsupported +predicates fail closed, including inside OR expressions. + +The complete audit covers all4,366 decoded nanos and re-parses62 selected +program/crystal payloads from the original ResourceDatabase. Raw records, +hashes, exact RPN criteria and the 21-program admission boundary are in +`local/regeneration-nano-research/catalog/`. Raw flags identify this bounded +content class; they are not reinterpreted as evidence of historical death or +offline-clock rules. + +## Passive regeneration programs + +| Program | Crystal/QL | Modifier | Strain | NCU | Duration | +| --- | --- | --- | ---: | ---: | --- | +|Nano Restoration27118|27253/10|364 +2|97|4|20min| +|Regeneration27144|27280/14|343 +3|111|5|20min| +|Continuous Reconstruction28651|28764/146|343 +14|203|45|60min| +|Hearty Constitution28663|28776/76|343 +8|203|24|30min| +|Bot Reproduction29200|29202/37|364 +6|201|12|30min| +|Soothing Calm30095|30140/90|364 +12|201|28|45min| + +These modify the shared [regeneration calculation](combat-regeneration.md); +they are not independent periodic Hit functions. Generic Regeneration stacks +with the Doctor203 line, while the two Doctor programs replace each other. +Nano Restoration97 stacks with Bureaucrat201; the two Bureaucrat programs +replace each other. Refresh retains one contribution and NCU allocation. +Equipment and different strains add their deltas once. Cancellation, expiry +and the current ordinary-buff death policy remove each contribution through65. + +Blood Circle27803 and the special Iron Circle42052 contract do not qualify. +The other six delta programs combine MaxHealth1 with343; that direct nano +maximum-health consumer remains unfinished, so the entire program and its +crystal remain unavailable. No partial delta effect is granted. + +## Additional ability programs + +The same complete-contract check also covers the five remaining +6 Augments, +Enhanced Senses, Feline Grace and Prodigious Strength: + +| Program | Crystal/QL | Effect | Caster requirement | +| --- | --- | --- | --- | +|Augment Agility26355|26482/4|Agility +6|MM/BM| +|Augment Intelligence26356|26483/4|Intelligence +6|MM/BM| +|Augment Psychic26357|26484/4|Psychic +6|MM/BM| +|Augment Sense26358|26485/4|Sense +6|MM/BM| +|Augment Stamina26359|26486/4|Stamina +6|MM/BM| +|Enhanced Senses25988|26207/27|Sense +15|BM/PM, real Agent5| +|Feline Grace25989|26206/53|Agility +25|BM/PM, real Agent5| +|Prodigious Strength29652|29814/136|Strength +40|BM/MM, visual Enforcer9| ## Authored effect @@ -77,7 +150,7 @@ populate the snapshot list without changing that replay path. ## Server lifecycle The supported programs read their modifier, strain, NCU cost, duration, range, -cast time, recharge and MM/BM requirements from the original catalog. Augment +cast time, recharge and complete action3 requirements from the original catalog. Augment Strength gives +6 Strength, costs 2 NCU, has 120000 centiseconds duration, 25 authored nano cost, 200 execution, 50 recharge and 15 metre range. Its MM/BM thresholds are 25/22. The selected-client arithmetic debits 24 nano; @@ -177,7 +250,7 @@ checks prevent duplicate subtraction. Resurrection and reconnect replay no removed program. The complete 96-record evidence export and limitations are in `local/nano-death-research/wire.md` and its adjacent evidence file. -Removal of these ordinary ability programs is a selected server policy, not +Removal of these ordinary ability and regeneration programs is a selected server policy, not a historical server capture. The client determines the removal protocol but does not establish which other programs survive death. Death-persistent exceptions, resurrection shock and the exact historical resource reset remain @@ -250,3 +323,51 @@ rounding. A preceding moving-away case crossed the completion range and aborted with a refund. The full Go suite, focused race checks and vet passed. Test fixtures were removed with unrelated rows verified unchanged, and the published WASM bundle remained unchanged. + +## Complete ordinary-buff verification + +The independent catalog audit admits exactly21 programs and21 crystals. +Public upload/cast/cancel tests exercise every one, including original crystal +qualities, exact nano debit, NCU, complete modifiers and cold recovery. Additional +cases cover strict skill equality/below/above, real/visual profession gates, +unsupported metadata/effects, conditions, repetition and partial contracts. +All six delta programs have exact authored-deadline and lethal-combat coverage. +Failed expiry persistence retains its effect until a durable retry, then sends +one removal. Shared strain tests cover equipment stacking, refresh, capacity, +upgrade and weaker rejection. + +The full Go suite passed in563.553 seconds, with gamedata in7.710 seconds; +focused race checks passed in115.872 seconds and vet was clean. The surgery +feature correction additionally passed focused checks in24.742 seconds and +race checks in94.531 seconds. Logs are in `local/regeneration-nano-checks/`. + +Two actual Chromium WASM clients used GPU/OpenGL4.5 hardware rendering. +Native crystal use learned all six delta programs and consumed each source +once. Regeneration, Nano Restoration, Hearty Constitution and Bot Reproduction +stacked with the worn implants at45/47 NCU, HealDelta22 and NanoDelta13. +An over-capacity Soothing Calm upgrade failed without debit. Canceling Hearty +freed24 NCU, allowing Calm to replace Bot:37/47 NCU, HealDelta14/NanoDelta19. +Both weaker-line attempts failed. Refresh, recipient/observer reload and an +actual server restart retained one contribution per program. Cold replay used +saved remaining durations, not fresh authored durations. + +Complete world-stream parsing verifies four recovery windows:23HP/14nano, +15HP/20nano before and after restart, and26HP/6nano with Continuous +Reconstruction alone. Each number is the gain on an eligible recovery check; +health and nano have independent intervals. Final native cancellation restored +only the installed gear's11/5 deltas and zero used NCU in both clients. +Enhanced Senses rejected the Doctor's crystal use without consuming it. +No browser exceptions or adapter failures occurred. Screenshots, native heap +snapshots, SQLite snapshots and parsed actions are retained in +`local/regeneration-nano-smoke/verification.json` and adjacent files. + +The high skills, worn QL300 NCU ear and QL1 recovery implants were explicit GM +fixtures. The ordinary acquisition gates for that equipment were bypassed; +all crystal learning, casting and cancellation used the native UI. Resources +were reset once through the control editor to keep recovery below the caps. +The surgery window was shortened separately to verify Features22 reverting +to6 while preserving casting; see [surgery access](implants.md#surgery-permission-and-cooldown). +Nano durations and recharge deadlines were not shortened. Original20-60 minute +expiry boundaries were tested in Go, rather than waiting them out manually. +Cleanup removed only the two owned characters and five remaining items, with +all unrelated table hashes unchanged and SQLite FK/integrity checks passing. diff --git a/docs/nano-learning.md b/docs/nano-learning.md @@ -26,6 +26,12 @@ basic ability Boost crystals and QL 4 Augment Strength now share this upload path. Their exact crystal/program IDs and qualities are tabulated there; each uses its authored LearnNano function and requirements. +Complete-contract admission now covers21 ordinary ability/regeneration crystals. +Both upload and casting use the shared postfix requirement evaluator, including +the authored BM/MM/PM/MC thresholds and real or visual profession predicates. +The full program, crystal and quality tables are in +[temporary nanos](nano-buffs.md#complete-contract-admission). + ## Requirements and character data The Meta-Physicist crystal's Use action requires effective Matter Creation 130 greater than 7, diff --git a/server/backpacks.go b/server/backpacks.go @@ -107,7 +107,7 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error 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 { + if statBuffCrystalProgram(player.inventory.Items[index].Template) != 0 { return server.learnNano_locked(client, index, body) } } diff --git a/server/item_requirements.go b/server/item_requirements.go @@ -1,6 +1,9 @@ package main -import "ao/server/gamedata" +import ( + "ao/server/gamedata" + "slices" +) func (item ownedItem) requirementsMet(actionType uint32, evaluate func(gamedata.ItemRequirement) (bool, bool)) bool { low, high := item.templateIDs() @@ -14,44 +17,11 @@ func (item ownedItem) requirementsMet(actionType uint32, evaluate func(gamedata. 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) - } + requirements := slices.Clone(action.Requirements) + for index := range requirements { + requirements[index].Value = interpolateItemValue(requirements[index].Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) } - // Native evaluation accepts an empty list and returns the final top value. - if len(stack) != 0 && !stack[len(stack)-1] { + if !requirementsMet(requirements, evaluate) { return false } } @@ -59,6 +29,46 @@ func (item ownedItem) requirementsMet(actionType uint32, evaluate func(gamedata. return true } +func requirementsMet(requirements []gamedata.ItemRequirement, evaluate func(gamedata.ItemRequirement) (bool, bool)) bool { + // kkr.dll 100056e0 evaluates postfix operators without short circuiting. + var stack []bool + for _, requirement := range 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: + 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. + return len(stack) == 0 || stack[len(stack)-1] +} + 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 diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -18,12 +18,81 @@ type activeNano struct { expiresAt time.Time } -func abilityNano(program uint32) bool { - switch program { - case 26342, 26360, 27086, 27134, 27154, 27168, 27169: - return true +func statBuffNano(program uint32) bool { + definition := gamedata.NanoTemplates[program] + if definition == nil || definition.RecordType != 1040005 || definition.HeaderWords[0] != 51051 || definition.Undecoded != nil || + itemStat(definition, 76) != 0 || itemStat(definition, 30) != 0 || itemStat(definition, 0) != 0x80010000 { + return false + } + // Ordinary timed buffs have finite duration, NCU, strain, range and casting costs. + for _, stat := range []uint32{8, 54, 75, 210, 287, 294, 407} { + if value := itemStat(definition, stat); value == 0 || value >= 0x80000000 { + return false + } + } + + hasEffect := false + for _, section := range definition.Sections { + switch section.Type { + case 4: + // Admit the ordinary attack-weight dictionary carried by these buffs. + if section.Subtype != 4 || section.Entries == nil || len(*section.Entries) != 1 { + return false + } + entry := (*section.Entries)[0] + if entry.Type == nil || *entry.Type != 12 || entry.Stats == nil { + return false + } + var total uint32 + for _, weight := range *entry.Stats { + if weight[0] < 100 || weight[0] > 168 || weight[1] == 0 || weight[1] > 100 { + return false + } + total += weight[1] + } + if total != 100 { + return false + } + case 6: + if section.Subtype != 27 || section.Stats == nil || !slices.Equal(*section.Stats, [][2]uint32{{12, 0}}) { + return false + } + case 22: + if section.Subtype != 36 || section.Actions == nil { + return false + } + for _, action := range *section.Actions { + if action.Type != 3 { + return false + } + } + case 2: + if section.Subtype != 0 || section.Functions == nil { + return false + } + for _, function := range *section.Functions { + if function.ID != 53045 || function.Target != 3 || len(function.Requirements) != 0 || + function.TickCount != 1 || function.TickInterval != 0 || len(function.Arguments) != 2 || + function.Arguments[0].Integer == nil || function.Arguments[1].Integer == nil { + return false + } + stat, value := *function.Arguments[0].Integer, *function.Arguments[1].Integer + switch stat { + case 16, 17, 18, 19, 20, 21, 343, 364: + if value <= 0 { + return false + } + case 382: + default: + return false + } + hasEffect = true + } + default: + return false + } } - return false + return hasEffect } func (effect activeNano) remainingAt(now time.Time) time.Duration { @@ -119,7 +188,7 @@ func (server *server) loadActiveNanos() error { if err := rows.Scan(&id, &effect.program, &effect.caster, &effect.remaining); err != nil { return err } - if !abilityNano(effect.program) || effect.remaining < 0 { + if !statBuffNano(effect.program) || effect.remaining < 0 { return fmt.Errorf("player %d has an unsupported active nano %d", id, effect.program) } server.characters[id].activeNanos = append(server.characters[id].activeNanos, effect) diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -55,12 +55,10 @@ func (player *character) nanoRequirementsMet(program uint32) bool { return player.profession == 8 && player.effectiveSkill(129, stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 && player.effectiveSkill(130, stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 } - return abilityNano(program) && player.abilityNanoRequirementsMet(gamedata.NanoTemplates[program]) + return statBuffNano(program) && player.nanoTemplateRequirementsMet(gamedata.NanoTemplates[program]) } -func (player *character) abilityNanoRequirementsMet(definition *gamedata.Item) bool { - stats := player.baseStats() - // The audited crystals and programs use MM/BM thresholds and a zero flag mask. +func (player *character) nanoTemplateRequirementsMet(definition *gamedata.Item) bool { for _, section := range definition.Sections { if section.Actions == nil { continue @@ -69,17 +67,8 @@ func (player *character) abilityNanoRequirementsMet(definition *gamedata.Item) b if action.Type != 3 { continue } - for _, requirement := range action.Requirements { - if requirement.Stat == 0 { - continue - } - base := stats.NanoAiding.MatterMetamorphosis - if requirement.Stat == 128 { - base = stats.NanoAiding.BiologicalMetamorphosis - } - if player.effectiveSkill(uint32(requirement.Stat), base, [6]uint32{0, 0, 0, 80, 0, 20}) <= requirement.Value { - return false - } + if !requirementsMet(action.Requirements, player.meetsStatRequirement) { + return false } } } diff --git a/server/nano_learning.go b/server/nano_learning.go @@ -6,21 +6,42 @@ import ( "slices" ) -func abilityNanoCrystalProgram(template uint32) uint32 { - switch template { - case 26469, 26487, 27217, 27270, 27290, 27304, 27305: - // The audited crystals each contain one OnUse LearnNano function. - for _, section := range gamedata.ItemTemplates[template].Sections { - if section.Type == 2 && section.Subtype == 0 { - for _, function := range *section.Functions { - if function.ID == 53019 { - return uint32(*function.Arguments[0].Integer) - } +func statBuffCrystalProgram(template uint32) uint32 { + definition := gamedata.ItemTemplates[template] + if definition == nil || definition.RecordType != 1000020 || definition.HeaderWords[0] != 51005 || definition.Undecoded != nil || definition.Quality == nil || + itemStat(definition, 0) != 0x80400203 || itemStat(definition, 30) != 0x29 || itemStat(definition, 26) != 1 { + return 0 + } + + // A complete ordinary crystal uploads exactly one supported program. + var program uint32 + for _, section := range definition.Sections { + if section.Type == 22 && section.Subtype == 36 { + if section.Actions == nil { + return 0 + } + for _, action := range *section.Actions { + if action.Type != 3 { + return 0 } } + continue + } + if section.Type != 2 || section.Subtype != 0 || section.Functions == nil { + return 0 + } + for _, function := range *section.Functions { + if program != 0 || function.ID != 53019 || function.Target != 2 || len(function.Requirements) != 0 || + function.TickCount != 1 || function.TickInterval != 0 || len(function.Arguments) != 1 || function.Arguments[0].Integer == nil { + return 0 + } + program = uint32(*function.Arguments[0].Integer) + if !statBuffNano(program) { + return 0 + } } } - return 0 + return program } func (server *server) learnNano_locked(client *worldClient, index int, body []byte) error { @@ -46,9 +67,9 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by player.effectiveSkill(130, stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && player.effectiveSkill(131, stats.NanoAiding.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7 default: - program = abilityNanoCrystalProgram(item.Template) + program = statBuffCrystalProgram(item.Template) accepted = accepted && program != 0 && item.Quality == *gamedata.ItemTemplates[item.Template].Quality && - player.abilityNanoRequirementsMet(gamedata.ItemTemplates[item.Template]) + player.nanoTemplateRequirementsMet(gamedata.ItemTemplates[item.Template]) } accepted = accepted && !slices.Contains(player.inventory.LearnedNanos, program) if accepted { diff --git a/server/regeneration_nano_test.go b/server/regeneration_nano_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "encoding/binary" + "fmt" + "slices" + "testing" + "time" +) + +func TestRegenerationNanoStrainsStackAndReplaceWithinFinalNCUCapacity(t *testing.T) { + world, _ := newStatBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.profession = 10 + player.inventory.LearnedNanos = []uint32{27118, 27144, 28663, 28651} + for _, program := range []uint32{27144, 27118, 28663, 27144} { + player.nanoRechargeUntil = time.Time{} + castTestBuff(t, world, 1, 1, program) + } + before := player.nano + player.nanoRechargeUntil = time.Time{} + + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 28651})[20:]); err != nil { + t.Fatal(err) + } + if client.nanoCast != nil || player.nano != before || player.usedNCU() != 33 || player.nanoBonus(343) != 11 || player.nanoBonus(364) != 2 || + len(player.activeNanos) != 3 { + t.Fatal("over-capacity upgrade debited resources or generic regeneration failed to stack/refresh") + } + for _, program := range []uint32{27144, 27118} { + if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, program})[20:]); err != nil { + t.Fatal(err) + } + } + castTestBuff(t, world, 1, 1, 28651) + player.nanoRechargeUntil = time.Time{} + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 28663})[20:]); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t).characters[1] + start := time.Unix(100, 0) + client.regenerationAt, client.regenerationSeconds = start, 810 + world.advanceRegeneration(start.Add(2 * time.Second)) + + if client.nanoCast != nil || player.health != 37 || player.nano != 225 || player.nanoBonus(343) != 14 || player.nanoBonus(364) != 0 || + player.usedNCU() != 45 || len(player.activeNanos) != 1 || player.activeNanos[0].program != 28651 || + cold.nano != 222 || cold.nanoBonus(343) != 14 || cold.usedNCU() != 45 { + t.Fatal("same-strain replacement, weaker rejection, recovery or cold restore changed more than one contribution", player.activeNanos, player.health, player.nano) + } +} + +func TestRegenerationNanoFailedExpiryRetainsContributionUntilDurableRetry(t *testing.T) { + world, conn := newStatBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.LearnedNanos = []uint32{27144} + castTestBuff(t, world, 1, 1, 27144) + deadline := player.activeNanos[0].expiresAt + if _, err := world.db.Exec("CREATE TRIGGER reject_expiry BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(FAIL, 'test expiry'); END"); err != nil { + t.Fatal(err) + } + conn.packets = nil + + world.advanceNanos(deadline) + if len(conn.packets) != 0 || player.nanoBonus(343) != 3 || player.usedNCU() != 5 || len(newTestInventoryServer(t).characters[1].activeNanos) != 1 { + t.Fatal("failed expiry published removal or lost the contribution") + } + start := time.Unix(100, 0) + client.regenerationAt, client.regenerationSeconds = start, 810 + world.advanceRegeneration(start.Add(2 * time.Second)) + if player.health != 26 || player.nano != 979 { + t.Fatal("failed expiry removed regeneration before commit", player.health, player.nano) + } + if _, err := world.db.Exec("DROP TRIGGER reject_expiry"); err != nil { + t.Fatal(err) + } + world.advanceNanos(deadline.Add(time.Second)) + world.advanceNanos(deadline.Add(2 * time.Second)) + client.regenerationSeconds = 1622 + world.advanceRegeneration(start.Add(4 * time.Second)) + + if player.health != 29 || player.nano != 982 || player.nanoBonus(343) != 0 || player.usedNCU() != 0 || + len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("durable expiry did not retire precisely its own contribution") + } + removed := 0 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 65 { + removed++ + } + } + if removed != 1 { + t.Fatal("expiry replayed its native removal", removed) + } +} + +func TestRegenerationNanoDeathRemovesEffectsBeforeFurtherRecovery(t *testing.T) { + for _, fixture := range []struct { + program uint32 + profession uint16 + }{ + {27118, 1}, {27144, 1}, {28651, 10}, {28663, 10}, {29200, 8}, {30095, 8}, + } { + t.Run(fmt.Sprint(fixture.program), func(t *testing.T) { + world, owner := newStatBuffWorld(t) + player := world.characters[1] + player.profession = fixture.profession + player.inventory.LearnedNanos = []uint32{fixture.program} + castTestBuff(t, world, 1, 1, fixture.program) + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + owner.packets = nil + + fatal := defeatReclaimPlayer(t, world) + world.advanceNanos(fatal.Add(time.Hour)) + world.advanceRegeneration(fatal.Add(time.Hour)) + cold := newTestInventoryServer(t).characters[1] + + if player.health != 0 || cold.health != 0 || player.usedNCU() != 0 || len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || + player.nanoBonus(343) != 0 || player.nanoBonus(364) != 0 || len(cold.inventory.Items) != 1 || cold.inventory.Items[0].Template != 173155 { + t.Fatal("death left a passive effect, revived the player or lost equipment", player.activeNanos, cold.inventory) + } + for _, conn := range []*combatTestConn{owner, observer} { + var removed []uint32 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 65 { + removed = append(removed, binary.BigEndian.Uint32(packet[45:49])) + } + } + if !slices.Equal(removed, []uint32{fixture.program}) { + t.Fatal("death did not remove one native contribution for owner and observer", removed) + } + } + }) + } +} diff --git a/server/stat_buff_catalog_test.go b/server/stat_buff_catalog_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "reflect" + "slices" + "testing" + "time" +) + +func newStatBuffWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newNanoBuffWorld(t) + player := world.characters[1] + player.level, player.health, player.nano = 100, 20, 1000 + player.stats.Body.NanoPool = 400 + player.stats.NanoAiding.MatterMetamorphosis = 900 + player.stats.NanoAiding.BiologicalMetamorphosis = 900 + player.stats.NanoAiding.PsychologicalModification = 900 + player.stats.NanoAiding.MatterCreation = 900 + player.inventory.LearnedNanos = nil + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + + // A GM-placed original Ear implant supplies 47 total NCU for these cast tests. + if granted, err := world.grantItem_locked(player, 173155); err != nil || !granted { + t.Fatal(granted, err) + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[0].Slot = 35 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + conn.packets = nil + return world, conn +} + +func TestStatBuffCatalogAdmitsOnlyCompleteOrdinaryContracts(t *testing.T) { + var programs, crystals []uint32 + + for program := range gamedata.NanoTemplates { + if statBuffNano(program) { + programs = append(programs, program) + } + } + for crystal := range gamedata.ItemTemplates { + if statBuffCrystalProgram(crystal) != 0 { + crystals = append(crystals, crystal) + } + } + slices.Sort(programs) + slices.Sort(crystals) + + // Exact IDs come from the independent complete-original-record catalog audit. + if !slices.Equal(programs, []uint32{25988, 25989, 26342, 26355, 26356, 26357, 26358, 26359, 26360, 27086, + 27118, 27134, 27144, 27154, 27168, 27169, 28651, 28663, 29200, 29652, 30095}) { + t.Fatal("buff admission differs from the complete effect/metadata audit", programs) + } + if !slices.Equal(crystals, []uint32{26206, 26207, 26469, 26482, 26483, 26484, 26485, 26486, 26487, 27217, + 27253, 27270, 27280, 27290, 27304, 27305, 28764, 28776, 29202, 29814, 30140}) { + t.Fatal("crystal admission differs from the complete upload audit", crystals) + } +} + +func TestStatBuffCrystalsLearnCastRestoreAndCancelTheirCompleteEffects(t *testing.T) { + for _, fixture := range []struct { + crystal, program, quality uint32 + profession uint16 + stat uint32 + bonus int32 + ncu, debit uint32 + }{ + {26206, 25989, 53, 5, 17, 25, 17, 176}, {26207, 25988, 27, 5, 20, 15, 9, 99}, + {26469, 26342, 7, 1, 17, 12, 3, 44}, {26482, 26355, 4, 1, 17, 6, 2, 24}, + {26483, 26356, 4, 1, 19, 6, 2, 24}, {26484, 26357, 4, 1, 21, 6, 2, 24}, + {26485, 26358, 4, 1, 20, 6, 2, 24}, {26486, 26359, 4, 1, 18, 6, 2, 24}, + {26487, 26360, 4, 1, 16, 6, 2, 24}, {27217, 27086, 7, 1, 19, 12, 3, 44}, + {27253, 27118, 10, 1, 364, 2, 4, 24}, {27270, 27134, 7, 1, 21, 12, 3, 44}, + {27280, 27144, 14, 1, 343, 3, 5, 24}, {27290, 27154, 7, 1, 20, 12, 3, 44}, + {27304, 27168, 7, 1, 18, 12, 3, 44}, {27305, 27169, 7, 1, 16, 12, 3, 44}, + {28764, 28651, 146, 10, 343, 14, 45, 478}, {28776, 28663, 76, 10, 343, 8, 24, 228}, + {29202, 29200, 37, 8, 364, 6, 12, 112}, {29814, 29652, 136, 9, 16, 40, 42, 548}, + {30140, 30095, 90, 8, 364, 12, 28, 313}, + } { + t.Run(fmt.Sprint(fixture.program), func(t *testing.T) { + world, conn := newStatBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.profession = fixture.profession + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, fixture.crystal); err != nil || !granted { + t.Fatal(granted, err) + } + + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[1][37:41]) != fixture.quality { + t.Fatal("upload used the wrong original crystal quality", conn.packets) + } + castTestBuff(t, world, 1, 1, fixture.program) + cold := newTestInventoryServer(t).characters[1] + + if player.nanoBonus(fixture.stat) != fixture.bonus || cold.nanoBonus(fixture.stat) != fixture.bonus || + player.usedNCU() != fixture.ncu || cold.usedNCU() != fixture.ncu || player.nano != 1000-fixture.debit || cold.nano != player.nano || + len(cold.inventory.Items) != 1 || cold.inventory.Items[0].Template != 173155 || + !slices.Equal(cold.inventory.LearnedNanos, []uint32{fixture.program}) { + t.Fatal("upload/cast/restore changed the wrong effect, resource, NCU or item", cold.inventory, player.activeNanos, player.nano, cold.nano) + } + if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, fixture.program})[20:]); err != nil { + t.Fatal(err) + } + if player.nanoBonus(fixture.stat) != 0 || player.usedNCU() != 0 || len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("cancellation retained the effect or its NCU") + } + }) + } +} + +func TestRegenerationNanosExpireAtTheirAuthoredDeadline(t *testing.T) { + for _, fixture := range []struct { + program, stat uint32 + bonus int32 + minutes time.Duration + }{ + {27118, 364, 2, 20}, {27144, 343, 3, 20}, {28651, 343, 14, 60}, + {28663, 343, 8, 30}, {29200, 364, 6, 30}, {30095, 364, 12, 45}, + } { + t.Run(fmt.Sprint(fixture.program), func(t *testing.T) { + world, _ := newStatBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.profession = 1 + if fixture.program == 28651 || fixture.program == 28663 { + player.profession = 10 + } else if fixture.program == 29200 || fixture.program == 30095 { + player.profession = 8 + } + player.inventory.LearnedNanos = []uint32{fixture.program} + castTestBuff(t, world, 1, 1, fixture.program) + deadline := player.activeNanos[0].expiresAt + beforeNano := player.nano + start := time.Unix(100, 0) + client.regenerationAt, client.regenerationSeconds = start, 810 + + world.advanceRegeneration(start.Add(2 * time.Second)) + if fixture.stat == 343 && (player.health != uint32(23+fixture.bonus) || player.nano != beforeNano+3) || + fixture.stat == 364 && (player.health != 23 || player.nano != beforeNano+uint32(3+fixture.bonus)) { + t.Fatal("active delta did not affect the eligible recovery check", player.health, player.nano) + } + world.advanceNanos(deadline.Add(-time.Nanosecond)) + if len(player.activeNanos) != 1 || player.activeNanos[0].remaining != fixture.minutes*time.Minute { + t.Fatal("effect expired early or used the wrong authored duration", player.activeNanos) + } + world.advanceNanos(deadline) + health, nano := player.health, player.nano + client.regenerationSeconds = 1622 + world.advanceRegeneration(start.Add(4 * time.Second)) + + if player.health != health+3 || player.nano != nano+3 || len(player.activeNanos) != 0 || player.usedNCU() != 0 || + len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("expired delta survived into another tick or cold load", player.activeNanos, player.health, player.nano) + } + }) + } +} + +func TestStatBuffCrystalAndCastEnforceAuthoredSkillAndProfessionCriteria(t *testing.T) { + for _, fixture := range []struct { + crystal, program uint32 + profession uint16 + field string + base uint16 + }{ + {26207, 25988, 5, "PM", 131}, {26206, 25989, 5, "PM", 249}, + {27253, 27118, 1, "MM", 55}, {27280, 27144, 1, "BM", 58}, + {28764, 28651, 10, "MC", 617}, {28776, 28663, 10, "MC", 324}, + {29202, 29200, 8, "PM", 176}, {30140, 30095, 8, "PM", 423}, + {29814, 29652, 9, "MM", 632}, + } { + for _, scenario := range []string{"skill equality", "skill below", "one above", "profession mismatch"} { + if scenario == "profession mismatch" && fixture.profession == 1 { + continue + } + t.Run(fmt.Sprintf("%d/%s", fixture.program, scenario), func(t *testing.T) { + world, conn := newStatBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.profession = fixture.profession + if scenario == "profession mismatch" { + player.profession = 1 + } else { + base := fixture.base + if scenario == "one above" { + base++ + } else if scenario == "skill below" { + base-- + } + switch fixture.field { + case "PM": + player.stats.NanoAiding.PsychologicalModification = base + case "MC": + player.stats.NanoAiding.MatterCreation = base + case "MM": + player.stats.NanoAiding.MatterMetamorphosis = base + case "BM": + player.stats.NanoAiding.BiologicalMetamorphosis = base + } + } + if granted, err := world.grantItem_locked(player, fixture.crystal); err != nil || !granted { + t.Fatal(granted, err) + } + before := slices.Clone(player.inventory.Items) + + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + player.inventory.LearnedNanos = []uint32{fixture.program} + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, fixture.program})[20:]); err != nil { + t.Fatal(err) + } + + if scenario == "one above" { + if client.nanoCast == nil { + t.Fatal("criterion one point above the strict threshold rejected a cast") + } + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + if len(player.activeNanos) != 1 || player.activeNanos[0].program != fixture.program || len(player.inventory.Items) != 1 || + !slices.Equal(newTestInventoryServer(t).characters[1].inventory.LearnedNanos, []uint32{fixture.program}) { + t.Fatal("criterion one point above the strict threshold failed upload or completion") + } + return + } + if client.nanoCast != nil || player.nano != 1000 || len(player.activeNanos) != 0 || !reflect.DeepEqual(player.inventory.Items, before) || + len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 || binary.BigEndian.Uint32(conn.packets[1][29:33]) != 108 { + t.Fatal("skill/profession rejection consumed a crystal or reserved nano", conn.packets, player.inventory) + } + }) + } + } +} + +func TestStatBuffCastRejectsIncompleteOrSpecialContractsWithoutDebit(t *testing.T) { + for _, scenario := range []string{"extra effect", "unsupported stat", "negative ability", "conditional effect", "repeated effect", "interval", + "wrong target", "unknown section", "wrong mode", "bad weights", "special flags", "zero duration", "missing effect", "wrong arguments"} { + t.Run(scenario, func(t *testing.T) { + original := gamedata.NanoTemplates[27144] + definition := *original + definition.Sections, definition.Stats = slices.Clone(original.Sections), slices.Clone(original.Stats) + functions := slices.Clone(*definition.Sections[2].Functions) + functions[0].Arguments = slices.Clone(functions[0].Arguments) + definition.Sections[2].Functions = &functions + switch scenario { + case "extra effect": + functions = append(functions, gamedata.ItemFunction{ID: 53002}) + case "unsupported stat": + functions[0].Arguments[0].Integer = new(int32(1)) + case "negative ability": + functions[0].Arguments[0].Integer, functions[0].Arguments[1].Integer = new(int32(16)), new(int32(-3)) + case "conditional effect": + functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Operator: 2, Value: 1}} + case "repeated effect": + functions[0].TickCount = 2 + case "interval": + functions[0].TickInterval = 100 + case "wrong target": + functions[0].Target = 2 + case "unknown section": + definition.Sections = append(definition.Sections, gamedata.ItemSection{Type: 20}) + case "wrong mode": + modes := [][2]uint32{{12, 3}} + definition.Sections[1].Stats = &modes + case "bad weights": + weights := [][2]uint32{{127, 55}, {128, 55}} + entries := slices.Clone(*definition.Sections[0].Entries) + entries[0].Stats = &weights + definition.Sections[0].Entries = &entries + case "special flags", "zero duration": + for index, stat := range definition.Stats { + if scenario == "special flags" && stat[0] == 0 || scenario == "zero duration" && stat[0] == 8 { + definition.Stats[index][1] = 0 + } + } + case "missing effect": + functions = nil + case "wrong arguments": + functions[0].Arguments = nil + } + gamedata.NanoTemplates[27144] = &definition + t.Cleanup(func() { gamedata.NanoTemplates[27144] = original }) + world, conn := newStatBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.LearnedNanos = []uint32{27144} + + err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27144})[20:]) + + if err != nil || client.nanoCast != nil || player.nano != 1000 || player.nanoReserved != 0 || len(player.activeNanos) != 0 || + len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 { + t.Fatal("an incomplete buff reserved nano or applied partial effects", err, conn.packets) + } + }) + } +} diff --git a/server/weapon_stats.go b/server/weapon_stats.go @@ -25,7 +25,7 @@ func (character *character) effectiveStat(stat uint32) (int32, bool) { return int32(character.titleLevel()), true case 54: return int32(character.level), true - case 60: + case 60, 368: return int32(character.profession), true } stats := character.baseStats()