aorecomp

Anarchy Online classic in the browser

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


commit bc169a87641600c97b2fb8bf932c9187c3385d3f
parent a287ed32e13ebf2461cea7c5b20b516e7ccb6e84
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 08:31:02 +0000

Support basic ability nano families and NCU capacity checks

Diffstat:
MTODO.md | 16+++++++++-------
Mdocs/nano-buffs.md | 97++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mdocs/nano-learning.md | 5++++-
Aserver/ability_nano_learning_test.go | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/ability_nano_test.go | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 4++--
Mserver/main.go | 8++++++++
Mserver/nano_buffs.go | 48++++++++++++++++++++++++++++++++++++++++++++++--
Mserver/nano_casting.go | 16++++++++++------
Mserver/nano_learning.go | 27+++++++++++++++++++++------
Mtools/data/extract_nano_learning.py | 9++++++---
11 files changed, 492 insertions(+), 40 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -434,21 +434,23 @@ checks are recorded in [treatment kits](docs/treatment-kit.md). 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. - Strength Boost and Augment Strength share catalog-driven casting, stat/NCU - contributions and durable add/remove state. See + All six basic ability Boosts and Augment Strength share catalog-driven + crystal uploads, casting, stat/NCU contributions and durable add/remove state. See [temporary nanos](docs/nano-buffs.md) for verification and policy limits. -- [ ] Enforce NCU capacity. Check: a buff fitting the available NCU succeeds and +- [x] Enforce NCU capacity. Check: a buff fitting the available NCU succeeds and one exceeding it is rejected without charging resources incorrectly. - Admission now accounts for active effects and same-strain replacement, but - a natural full-capacity case needs more than the enabled Strength strain. + Native checks cover exact fit at 8/8, rejecting a 9-NCU replacement without + debit, refresh at capacity, freeing NCU and 9/10 after installing memory. + Completion rechecks capacity and refunds if another cast filled the target. - [x] Replace or reject a conflicting buff. Check: one known nano-line pair 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. -- [ ] Verify temporary nano lifecycle policies beyond the first strain. Check: +- [ ] Verify remaining temporary nano lifecycle policies. Check: historical offline timing, death cleanup, duration scaling, cross-side/team eligibility, dungeon line of sight and completion target gates. Exercise - zoning/restart, full NCU and replacement at capacity with native clients. + interrupted zoning, additional strain rules and historical NCU replacement + admission policy. Current replacement uses the final allocation after removal. - [ ] Apply one damage-over-time effect. Check: the expected number of ticks occurs and stopping/removing the effect prevents further ticks. - [ ] Apply one heal-over-time effect. Check: recovery ticks stop at expiration diff --git a/docs/nano-buffs.md b/docs/nano-buffs.md @@ -1,9 +1,8 @@ # Temporary nano research for 14.9.1 -Strength Boost 27169 and Augment Strength 26360 share one timed-effect path. -Strength Boost's crystal can be learned through the native upload route; -Augment Strength currently needs an existing learned-program entry. Learning -and casting are separate operations. +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. ## Authored effect @@ -21,6 +20,24 @@ least 41. Stat 122 is Sensory Improvement and is not required. The original registration strings at `10038a90`, `10038a5e` and `10038b58`, respectively, establish those skill names independently of later database labels. +The same original-record audit covers the complete basic ability family: + +| Program | Program ID | Crystal ID | Ability stat | Strain | Crystal QL | +| --- | --- | --- | --- | --- | --- | +| Agility Boost | 26342 | 26469 | 17 | 29 | 7 | +| Intelligence Boost | 27086 | 27217 | 19 | 30 | 7 | +| Psychic Boost | 27134 | 27270 | 21 | 31 | 7 | +| Sense Boost | 27154 | 27290 | 20 | 32 | 7 | +| Stamina Boost | 27168 | 27304 | 18 | 33 | 7 | +| Strength Boost | 27169 | 27305 | 16 | 34 | 7 | +| Augment Strength | 26360 | 26487 | 16 | 34 | 4 | + +Each Boost has program QL 3, one +12 modifier, 3 NCU and the same requirements, +timing, range and nano cost as Strength Boost. Augment Strength has program +QL 2 and the lower requirements and costs below. Crystal upload reads the +verified LearnNano function, authored quality and MM/BM requirements from its +own record. A single catalog-based requirement check serves upload and cast. + ## Native delivery The inspected target is original `kkr.dll`, SHA-256 @@ -59,12 +76,12 @@ populate the snapshot list without changing that replay path. ## Server lifecycle -The selected programs read their modifier, strain, NCU cost, duration, range, +The supported programs read their modifier, strain, NCU cost, duration, range, cast time, recharge and MM/BM 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; -Strength Boost debits 44. Both affect effective Strength and skill trickle-down +Each Boost debits 44. They affect effective abilities and skill trickle-down without editing trained base values. Admission reserves nano once. Completion atomically retires that reservation, @@ -83,6 +100,34 @@ player checkpoint; timer-only saves do not rewrite unchanged character data. The saved remaining duration resumes on login. Ordinary observer updates do not add duplicate stat snapshots or modifier streams. +## Derived resources + +The native stat getters read cached maximum HP 1 and maximum nano 221. +Modify 53045 for an ability does not mark them for recomputation: Stamina +and Psychic dirty flag 0x80 recomputes regeneration, while flag 0x40 is the +separate maximum-resource path for direct Body Development/Nano Pool changes. +Original functions `10074730`, `10074b00`, `100714a0` and `10075910` establish +that distinction. Send the changed resource foundation after 177 or 65 using +the existing equipment resource-maximum path; do not add another modifier. + +FullCharacter activation `1007eea0` calls `10072180 -> 10075910` before a +subsequent 177 replay. That can overwrite already serialized buffed maxima +with pre-buff values. The owner therefore receives explicit foundations after +replay. Observer SimpleChar uses its serialized maximum and does not enter +the local recomputation path. Existing observed native attack-rating updates +need no additional stat 22 packet. + +Additions do not grant current HP or nano. Removal clamps current resources +to the resulting maxima, committing the clamp with effect removal before any +65, maximum correction or current-resource packet. This follows the server's +equipment-removal policy; the exact historical server clamp policy is not +established by these client paths. A maximum-HP change anchors a moving +recipient's prior segment before the wounded-speed calculation changes. + +Complete 38-record native evidence and the finding ledger are retained under +`local/ability-buff-research/`. This is static evidence, with runtime agreement +checked separately in the published WASM client. + ## Reconstruction policies and remaining checks On normal session departure, remaining duration is checkpointed and paused. @@ -103,10 +148,12 @@ line-of-sight implementation. NCU admission uses available capacity after subtracting the replaced strain. The client paths inspected do not establish the original server's full-cost -versus replacement-delta capacity rule. The two enabled programs share one -strain and each fit the base 8 NCU; a natural full-capacity rejection case -still needs additional independently verified program families. Keep that -TODO open. Stat 464 duration scaling and death cleanup also remain open. +versus replacement-delta capacity rule. The family permits natural exact-fit +and overflow tests: Augment Strength 2 + Agility 3 + Intelligence 3 fits 8 NCU; upgrading Strength would require 9 +and is rejected without debit. Refreshing a present 3-NCU program at 8 NCU +retains one contribution. A 2-NCU memory raises capacity to 10, allowing a +previously rejected third 3-NCU program. Stat 464 duration scaling and death +cleanup remain open. ## Verification @@ -137,6 +184,30 @@ SQLite row; both native representations lost the modifier and NCU, and the owner's icon disappeared. This verifies shortened replay expiration, not a 20-minute manual wait. The authored 20-minute boundary is covered in Go. -The full server/gamedata suites, focused race checks and vet passed. Owned -browser clients were closed and test characters removed; unrelated database -rows were checked unchanged. The published WASM bundle needed no changes. +## Ability-family verification + +Seven actual crystal uploads produced the seven native program entries and +consumed each source once. Two hardware WASM clients verified the natural NCU +boundary cases above, all six +12 effects, and the 2-NCU memory expansion. +The combined Stamina/Psychic/Intelligence case reached maximum HP 46 and nano +629. Those maxima, current resources and one copy of every contribution +survived owner and late-observer reconnects. + +With current resources filled through the ordinary control editor, removing +Intelligence clamped nano 629 to 626, removing Stamina clamped HP 46 to 37, +and removing Psychic clamped nano 626 to 620. SQLite and native owner values +agreed after each removal; observer HP agreed as well. Non-team observers do +not receive another player's private nano-resource state. + +Additional Go tests cover every family independently, upload thresholds and +qualities, exact/overflow NCU, memory expansion, refresh/replacement at +capacity, capacity becoming unavailable during a cast, failed clamp writes, +expiration clamps, startup restoration and the wounded movement-speed boundary. + +The final two-client check cast Stamina on a recipient with 4 HP while they +moved toward the caster. Maximum HP changed from 37 to 46, current HP stayed +4, and the owner/observer final positions agreed within native coordinate +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. diff --git a/docs/nano-learning.md b/docs/nano-learning.md @@ -16,7 +16,10 @@ and is not a requirement. The original client's inspection window and skill registration strings independently confirm these labels. The upload action uses `{27305,27305,7,1,3,104,sourceSlot,50000,ownerID}`: the crystal's authored quality is distinct from its program's quality. Timed buff casting remains -separate from learning; see [temporary nano research](nano-buffs.md). +separate from learning; see [temporary nanos](nano-buffs.md). The other five +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. ## Requirements and character data diff --git a/server/ability_nano_learning_test.go b/server/ability_nano_learning_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "encoding/binary" + "fmt" + "reflect" + "slices" + "testing" +) + +func TestAbilityNanoCrystalsLearnTheirAuthoredPrograms(t *testing.T) { + for _, nano := range []struct{ crystal, program, quality uint32 }{ + {26469, 26342, 7}, {26487, 26360, 4}, {27217, 27086, 7}, {27270, 27134, 7}, + {27290, 27154, 7}, {27304, 27168, 7}, {27305, 27169, 7}, + } { + t.Run(fmt.Sprint(nano.crystal), func(t *testing.T) { + world, conn := newNanoLearningWorld(t) + player := world.characters[1] + player.profession = 1 + player.stats.NanoAiding.MatterMetamorphosis, player.stats.NanoAiding.BiologicalMetamorphosis = 39, 33 + player.inventory.Items = nil + if granted, err := world.grantItem_locked(player, nano.crystal); err != nil || !granted { + t.Fatal(granted, err) + } + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || !slices.Equal(restored.inventory.LearnedNanos, []uint32{nano.program}) || len(restored.inventory.Items) != 0 || + len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || + binary.BigEndian.Uint32(conn.packets[1][29:33]) != nano.crystal || binary.BigEndian.Uint32(conn.packets[1][37:41]) != nano.quality { + t.Fatalf("crystal %d did not upload its authored program and quality: %v, %+v", nano.crystal, err, restored.inventory) + } + }) + } +} + +func TestAbilityNanoCrystalRequirementsAndDuplicateDoNotConsume(t *testing.T) { + for _, crystal := range []uint32{26469, 26487, 27217, 27270, 27290, 27304, 27305} { + for _, scenario := range []string{"MM", "BM", "quality", "duplicate"} { + t.Run(fmt.Sprintf("%d/%s", crystal, scenario), func(t *testing.T) { + world, conn := newNanoLearningWorld(t) + player := world.characters[1] + player.inventory.Items = nil + player.stats.NanoAiding.MatterMetamorphosis, player.stats.NanoAiding.BiologicalMetamorphosis = 39, 33 + if crystal == 26487 { + player.stats.NanoAiding.MatterMetamorphosis, player.stats.NanoAiding.BiologicalMetamorphosis = 23, 20 + } + if granted, err := world.grantItem_locked(player, crystal); err != nil || !granted { + t.Fatal(granted, err) + } + switch scenario { + case "MM": + player.stats.NanoAiding.MatterMetamorphosis-- + case "BM": + player.stats.NanoAiding.BiologicalMetamorphosis-- + case "quality": + player.inventory.Items[0].Quality-- + case "duplicate": + player.inventory.LearnedNanos = []uint32{26342, 26360, 27086, 27134, 27154, 27168, 27169} + } + before := player.inventory + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + + if err != nil || !reflect.DeepEqual(before, player.inventory) || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatalf("rejected crystal %d was consumed: %v", crystal, err) + } + }) + } + } +} diff --git a/server/ability_nano_test.go b/server/ability_nano_test.go @@ -0,0 +1,230 @@ +package main + +import ( + "encoding/binary" + "fmt" + "slices" + "testing" + "time" +) + +func TestAbilityNanoFamiliesApplyAndRemoveOneContribution(t *testing.T) { + for _, nano := range []struct{ program, stat, health, points uint32 }{ + {26342, 17, 37, 620}, {27086, 19, 37, 620}, {27134, 21, 37, 626}, + {27154, 20, 37, 620}, {27168, 18, 46, 620}, {27169, 16, 37, 620}, + } { + t.Run(fmt.Sprint(nano.program), func(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player := world.characters[1] + player.inventory.LearnedNanos = []uint32{nano.program} + + castTestBuff(t, world, 1, 1, nano.program) + restored := newTestInventoryServer(t).characters[1] + + if player.effectiveAbility(nano.stat) != 22 || player.usedNCU() != 3 || player.maximumHealth() != nano.health || player.maximumNano() != nano.points || + restored.effectiveAbility(nano.stat) != 22 || restored.maximumHealth() != nano.health || restored.maximumNano() != nano.points || player.health != 37 || player.nano != 56 { + t.Fatal("ability changed the wrong contribution, maximum or current resource", player.maximumHealth(), player.maximumNano()) + } + if err := world.handleNanoRemoval(world.clients[1], characterActionPacket(1, [5]uint32{65, 0, 0, 53019, nano.program})[20:]); err != nil { + t.Fatal(err) + } + if player.effectiveAbility(nano.stat) != 10 || player.maximumHealth() != 37 || player.maximumNano() != 620 || player.usedNCU() != 0 { + t.Fatal("removal retained a derived contribution") + } + }) + } +} + +func TestAbilityNanoNCUExactFitRefreshAndReplacement(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.LearnedNanos = []uint32{26342, 26360, 27086, 27169} + player.nano = 300 + for _, program := range []uint32{26342, 27086, 26360} { + player.nanoRechargeUntil = time.Time{} + castTestBuff(t, world, 1, 1, program) + } + before, packets := player.nano, len(conn.packets) + player.nanoRechargeUntil = time.Time{} + + err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:]) + + if err != nil || player.usedNCU() != 8 || player.maximumNCU() != 8 || player.nano != before || client.nanoCast != nil || len(conn.packets) != packets+1 || + player.effectiveAbility(16) != 16 || player.effectiveAbility(17) != 22 || player.effectiveAbility(19) != 22 { + t.Fatal("over-capacity replacement was charged or installed", err) + } + castTestBuff(t, world, 1, 1, 26342) + if player.usedNCU() != 8 || len(player.activeNanos) != 3 || player.nano != before-44 { + t.Fatal("refresh at capacity stacked or required the full cost twice") + } + if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 27086})[20:]); err != nil { + t.Fatal(err) + } + player.nanoRechargeUntil = time.Time{} + castTestBuff(t, world, 1, 1, 27169) + if player.usedNCU() != 6 || player.effectiveAbility(16) != 22 || len(player.activeNanos) != 2 || newTestInventoryServer(t).characters[1].usedNCU() != 6 { + t.Fatal("freeing NCU did not allow one durable same-line upgrade") + } +} + +func TestAbilityNanoNCUMemoryAllowsPreviouslyRejectedProgram(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + player.nano = 300 + player.inventory.LearnedNanos = []uint32{26342, 27086, 27169} + for _, program := range []uint32{26342, 27086} { + player.nanoRechargeUntil = time.Time{} + castTestBuff(t, world, 1, 1, program) + } + player.nanoRechargeUntil = time.Time{} + request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:] + if err := world.handleNanoCast(client, request); err != nil || client.nanoCast != nil || player.nano != 212 || player.usedNCU() != 6 { + t.Fatal("third 3-NCU program fitted into 8 NCU", err) + } + for _, template := range []uint32{36783, 36779} { + if granted, err := world.grantItem_locked(player, template); err != nil || !granted { + t.Fatal(granted, err) + } + } + + for _, move := range [][2]uint32{{64, 7}, {65, 9}} { + if err := world.handleInventory(client, inventoryMovePacket(1, move[0], move[1])[20:]); err != nil || client.equipment == nil { + t.Fatal("belt or memory was not admitted", err) + } + world.advanceEquipment(client.equipment.readyAt.Add(time.Nanosecond)) + } + castTestBuff(t, world, 1, 1, 27169) + restored := newTestInventoryServer(t).characters[1] + + if player.maximumNCU() != 10 || player.usedNCU() != 9 || player.nano != 168 || restored.maximumNCU() != 10 || restored.usedNCU() != 9 || + player.effectiveAbility(16) != 22 || !slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.Template == 36779 && item.Slot == 9 }) { + t.Fatal("NCU memory did not allow the previously rejected program") + } +} + +func TestAbilityNanoResourceClampAndRemovalCommitTogether(t *testing.T) { + for _, program := range []uint32{27168, 27134} { + t.Run(fmt.Sprint(program), func(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player := world.characters[1] + player.inventory.LearnedNanos = []uint32{program} + castTestBuff(t, world, 1, 1, program) + player.health, player.nano = player.maximumHealth(), player.maximumNano() + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("CREATE TRIGGER fail_clamp BEFORE UPDATE OF health,nano ON characters BEGIN SELECT RAISE(FAIL, 'test clamp'); END"); err != nil { + t.Fatal(err) + } + conn.packets = nil + request := characterActionPacket(1, [5]uint32{65, 0, 0, 53019, program})[20:] + + err := world.handleNanoRemoval(world.clients[1], request) + + restored := newTestInventoryServer(t).characters[1] + if err == nil || len(conn.packets) != 0 || len(player.activeNanos) != 1 || len(restored.activeNanos) != 1 || + restored.health != player.health || restored.nano != player.nano { + t.Fatalf("failed clamp state: error=%v packets=%d effects=%d/%d resources=%d,%d/%d,%d", err, len(conn.packets), len(player.activeNanos), len(restored.activeNanos), player.health, player.nano, restored.health, restored.nano) + } + if _, err := world.db.Exec("DROP TRIGGER fail_clamp"); err != nil { + t.Fatal(err) + } + if err := world.handleNanoRemoval(world.clients[1], request); err != nil { + t.Fatal(err) + } + restored = newTestInventoryServer(t).characters[1] + if len(restored.activeNanos) != 0 || player.health != 37 || player.nano != 620 || restored.health != 37 || restored.nano != 620 || player.savedVitals != player.vitals() { + t.Fatal("removal and resource clamp did not persist together") + } + maximum := uint32(0) + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e { + stat := binary.BigEndian.Uint32(packet[29:33]) + if program == 27168 && stat == 1 || program == 27134 && stat == 221 { + maximum = binary.BigEndian.Uint32(packet[33:37]) + } + } + } + if program == 27168 && maximum != 37 || program == 27134 && maximum != 620 { + t.Fatal("native cached maximum was not corrected", maximum) + } + }) + } +} + +func TestAbilityNanoExpiryClampsFullResources(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player := world.characters[1] + player.nano = 300 + player.inventory.LearnedNanos = []uint32{27168, 27134} + castTestBuff(t, world, 1, 1, 27168) + player.nanoRechargeUntil = time.Time{} + castTestBuff(t, world, 1, 1, 27134) + player.health, player.nano = 46, 626 + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + + world.advanceNanos(time.Now().Add(time.Hour)) + restored := newTestInventoryServer(t).characters[1] + + if len(player.activeNanos) != 0 || player.health != 37 || player.nano != 620 || len(restored.activeNanos) != 0 || restored.health != 37 || restored.nano != 620 { + t.Fatal("expired ability buffs retained their maxima or over-cap resources") + } +} + +func TestAbilityNanoAnchorsWoundedRecipientsHeldMovement(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player := world.characters[1] + player.inventory.LearnedNanos = []uint32{27168} + recipient := *player + recipient.id, recipient.name, recipient.health, recipient.running = 2, "Recipient", 4, true + recipient.position, recipient.rotation = [3]float32{0, 0, 3}, [4]float32{0, 0, 0, 1} + world.characters[2], world.nextCharacter = &recipient, 2 + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true, forward: 1, movementStarted: time.Now()} + if err := world.saveUser_locked(&recipient); err != nil { + t.Fatal(err) + } + if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 27168})[20:]); err != nil { + t.Fatal(err) + } + at := world.clients[1].nanoCast.readyAt.Add(time.Nanosecond) + world.clients[2].movementStarted = at.Add(-time.Second) + + world.advanceNanos(at) + position := predictedPosition_locked(&recipient, world.clients[2], at.Add(time.Second)) + + if recipient.maximumHealth() != 46 || world.clients[2].movementStarted != at || recipient.position[2] < 6.661 || recipient.position[2] > 6.663 || + position[2] < 9.900 || position[2] > 9.903 { + t.Fatal("ability buff repriced the earlier wounded movement segment", recipient.position, position) + } +} + +func TestAbilityNanoCompletionRefundsWhenRecipientNCUFills(t *testing.T) { + world, _ := newNanoBuffWorld(t) + recipient := *world.characters[1] + recipient.id, recipient.name = 2, "Recipient" + recipient.inventory.LearnedNanos = []uint32{26342, 27086} + world.characters[2], world.nextCharacter = &recipient, 2 + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true} + if err := world.saveUser_locked(&recipient); err != nil { + t.Fatal(err) + } + castTestBuff(t, world, 2, 2, 26342) + recipient.nanoRechargeUntil, recipient.aggDef = time.Time{}, 100 + client := world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 27169})[20:]); err != nil { + t.Fatal(err) + } + deadline := client.nanoCast.readyAt + + castTestBuff(t, world, 2, 2, 27086) + world.advanceNanos(deadline.Add(time.Nanosecond)) + world.advanceNanos(deadline.Add(time.Second)) + restored := newTestInventoryServer(t) + + if client.nanoCast != nil || world.characters[1].nano != 100 || restored.characters[1].nano != 100 || + recipient.usedNCU() != 6 || len(recipient.activeNanos) != 2 || recipient.effectiveAbility(16) != 10 || restored.characters[2].usedNCU() != 6 { + t.Fatal("cast completed beyond NCU capacity or failed to refund once") + } +} diff --git a/server/backpacks.go b/server/backpacks.go @@ -80,10 +80,10 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error client.useSequence = sequence if binary.BigEndian.Uint32(body[40:44]) == 104 { index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812 || item.Template == 43330 || item.Template == 29625 || item.Template == 27305) + return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812 || item.Template == 43330 || item.Template == 29625 || abilityNanoCrystalProgram(item.Template) != 0) }) if index >= 0 { - if player.inventory.Items[index].Template == 43330 || player.inventory.Items[index].Template == 29625 || player.inventory.Items[index].Template == 27305 { + if player.inventory.Items[index].Template == 43330 || player.inventory.Items[index].Template == 29625 || abilityNanoCrystalProgram(player.inventory.Items[index].Template) != 0 { return server.learnNano_locked(client, index, body) } if player.inventory.Items[index].Template == 85366 { diff --git a/server/main.go b/server/main.go @@ -376,6 +376,14 @@ func (server *server) serveWorldClient(client *worldClient) error { } updates = append(updates, fullCharacterPacket(character)) updates = append(updates, activeNanoPackets(character, time.Now())...) + if len(character.activeNanos) != 0 { + // FullCharacter recomputes maxima before the later ability replay. + for _, stat := range [][2]uint32{{1, character.maximumHealth() - uint32(character.equipmentBonus(1))}, {221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}} { + body := binary.BigEndian.AppendUint32(nil, stat[0]) + body = binary.BigEndian.AppendUint32(body, stat[1]) + updates = append(updates, n3Packet(0x2b333d6e, 50000, character.id, body)) + } + } updates = append(updates, equippedWeaponPackets(character)...) if remaining := time.Until(character.treatmentLockedUntil); remaining > 0 { updates = append(updates, skillLockPacket(character.id, 124, uint32((remaining+time.Second-1)/time.Second))) diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -19,7 +19,11 @@ type activeNano struct { } func abilityNano(program uint32) bool { - return program == 27169 || program == 26360 + switch program { + case 26342, 26360, 27086, 27134, 27154, 27168, 27169: + return true + } + return false } func (effect activeNano) remainingAt(now time.Time) time.Duration { @@ -136,21 +140,61 @@ func (server *server) saveActiveNanos_locked(player *character, now time.Time) e if err := writeActiveNanos(tx, player, now); err != nil { return err } - return tx.Commit() + previous := server.characters[player.id] + if player.health != previous.health || player.nano != previous.nano { + if err := updateRecord(tx, "characters", player.id, "health, nano", []any{player.health, player.nano}); err != nil { + return err + } + } + if err := tx.Commit(); err != nil { + return err + } + if player.health != previous.health || player.nano != previous.nano { + player.savedVitals.Health, player.savedVitals.Nano = player.health, player.nano + } + return nil } func (server *server) removeNano_locked(player *character, index int, now time.Time, updates map[*worldClient][][]byte) error { candidate := *player effect := candidate.activeNanos[index] candidate.activeNanos = slices.Delete(slices.Clone(candidate.activeNanos), index, index+1) + candidate.health, candidate.nano = min(candidate.health, candidate.maximumHealth()), min(candidate.nano, candidate.maximumNano()) if err := server.saveActiveNanos_locked(&candidate, now); err != nil { return err } + previous := *player *player = candidate server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{65, 0, 0, effect.caster, effect.program})) + server.finishNanoEffect_locked(updates, player, previous, now) return nil } +func (server *server) finishNanoEffect_locked(updates map[*worldClient][][]byte, player *character, previous character, now time.Time) { + // A maximum-health change can change a wounded player's held movement speed. + if client := server.clients[player.id]; client != nil && previous.maximumHealth() != player.maximumHealth() { + player.position = predictedPosition_locked(&previous, client, now) + client.movementStarted = now + } + + // Ability modifiers do not invalidate the native client's cached resource maxima. + for _, stat := range [][3]uint32{ + {1, previous.maximumHealth() - uint32(previous.inventory.equipmentBonus(1)), player.maximumHealth() - uint32(player.inventory.equipmentBonus(1))}, + {221, previous.maximumNano() - uint32(previous.inventory.equipmentBonus(221)), player.maximumNano() - uint32(player.inventory.equipmentBonus(221))}, + } { + if stat[1] != stat[2] { + server.queueResourceMaximum_locked(updates, player, stat[0], stat[2]) + } + } + if player.health != previous.health { + server.queueQuietHealth_locked(updates, player) + } + if player.nano != previous.nano && server.clients[player.id] != nil { + updates[server.clients[player.id]] = append(updates[server.clients[player.id]], nanoPointsPacket(player)) + } + server.queueTeamResources_locked(updates, player) +} + func (server *server) pauseActiveNanos_locked(player *character, now time.Time) error { if len(player.activeNanos) == 0 { return nil diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -50,16 +50,18 @@ func (player *character) nanoCastDelay(program uint32) time.Duration { } func (player *character) nanoRequirementsMet(program uint32) bool { - stats := player.baseStats() if program == 29618 { + stats := player.baseStats() 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 } - if !abilityNano(program) { - return false - } - // Both supported ability programs author only MM/BM thresholds and a zero flag mask. - for _, section := range gamedata.NanoTemplates[program].Sections { + return abilityNano(program) && player.abilityNanoRequirementsMet(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. + for _, section := range definition.Sections { if section.Actions == nil { continue } @@ -240,11 +242,13 @@ func (server *server) advanceNanos(now time.Time) { server.abortNano_locked(client, now, updates) continue } + previous := *target *player, *target = caster, victim client.nanoCast = nil if program != 29618 { server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program})) server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{177, 53019, program, player.id, itemStat(gamedata.NanoTemplates[program], 8)})) + server.finishNanoEffect_locked(updates, target, previous, now) continue } body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) diff --git a/server/nano_learning.go b/server/nano_learning.go @@ -1,10 +1,28 @@ package main import ( + "ao/server/gamedata" "encoding/binary" "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) + } + } + } + } + } + return 0 +} + func (server *server) learnNano_locked(client *worldClient, index int, body []byte) error { player := server.characters[client.id] item := player.inventory.Items[index] @@ -22,13 +40,10 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by accepted = accepted && item.Quality == 1 && player.profession == 12 && 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 - case 27305: - program = 27169 - accepted = accepted && item.Quality == 7 && - player.effectiveSkill(128, stats.NanoAiding.BiologicalMetamorphosis, [6]uint32{0, 0, 0, 80, 0, 20}) > 34 && - player.effectiveSkill(127, stats.NanoAiding.MatterMetamorphosis, [6]uint32{0, 0, 0, 80, 0, 20}) > 40 default: - accepted = false + program = abilityNanoCrystalProgram(item.Template) + accepted = accepted && program != 0 && item.Quality == *gamedata.ItemTemplates[item.Template].Quality && + player.abilityNanoRequirementsMet(gamedata.ItemTemplates[item.Template]) } accepted = accepted && !slices.Contains(player.inventory.LearnedNanos, program) if accepted { diff --git a/tools/data/extract_nano_learning.py b/tools/data/extract_nano_learning.py @@ -15,17 +15,20 @@ def main(): # Retain each supported crystal and the program it uploads. records = [] for kind, identity in ((1000020, 43330), (1040005, 43324), (1000020, 29625), (1040005, 29618), - (1000020, 27305), (1040005, 27169)): + (1000020, 27305), (1040005, 27169), (1000020, 26469), (1040005, 26342), + (1000020, 26487), (1040005, 26360), (1000020, 27217), (1040005, 27086), + (1000020, 27270), (1040005, 27134), (1000020, 27290), (1040005, 27154), + (1000020, 27304), (1040005, 27168)): raw = database.read(kind, identity) item = extract_items.parse_item(raw, kind, identity) records.append(dict(record=item, payload_sha256=hashlib.sha256(raw).hexdigest())) - assert [record['record']['quality'] for record in records] == [1, 1, 1, 1, 7, 3] + assert [record['record']['quality'] for record in records] == [1, 1, 1, 1, 7, 3, 7, 3, 4, 2, 7, 3, 7, 3, 7, 3, 7, 3] assert records[0]['record']['header_words'][0] == 51005 assert records[1]['record']['header_words'][0] == 51051 # Keep the supported nano skill and initiative ability weights. weights = {} - for stat in (127, 128, 129, 130, 131, 149): + for stat in (127, 128, 129, 130, 131, 132, 149, 152): raw = database.read(1000204, stat) weights[stat] = dict(weights=struct.unpack('<6i', raw), payload_hex=raw.hex(), payload_sha256=hashlib.sha256(raw).hexdigest())