aorecomp

Anarchy Online classic in the browser

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


commit a287ed32e13ebf2461cea7c5b20b516e7ccb6e84
parent 6f21f1c54c082d68324a8cd5f530cbdba8113949
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 08:00:05 +0000

Support temporary Strength nano effects

Diffstat:
MTODO.md | 19++++++++++++-------
Mdocs/nano-buffs.md | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mserver/control.go | 1+
Mserver/main.go | 14++++++++++++++
Aserver/nano_buffs.go | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/nano_buffs_test.go | 378+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_casting.go | 120++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mserver/nano_casting_test.go | 2+-
Mserver/npc_outcome.go | 17+++++++++++++----
Mserver/state.go | 1+
Mserver/stats.go | 2+-
Mserver/users.go | 18+++++++++++++-----
Mserver/world.sql | 7+++++++
Mserver/world_actions.go | 1+
14 files changed, 832 insertions(+), 60 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -432,18 +432,23 @@ checks are recorded in [treatment kits](docs/treatment-kit.md). is followed and no delayed heal or duplicate result occurs. - [x] Cast one direct-damage program on a creature. Check: target validation, damage and death handling work without starting an unintended weapon attack. -- [ ] Apply one temporary stat buff. Check: the native effect appears, the stat +- [x] Apply one temporary stat buff. Check: the native effect appears, the stat changes once, and expiration removes exactly that contribution. - Strength Boost's QL 7 crystal now uploads its program with verified MM/BM - requirements, duplicate rejection and native restart persistence. Its timed - effect is not enabled yet. Catalog and add/remove protocol findings are in - [temporary nano research](docs/nano-buffs.md). + Strength Boost and Augment Strength share catalog-driven 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 one exceeding it is rejected without charging resources incorrectly. -- [ ] Replace or reject a conflicting buff. Check: one known nano-line pair + Admission now accounts for active effects and same-strain replacement, but + a natural full-capacity case needs more than the enabled Strength strain. +- [x] Replace or reject a conflicting buff. Check: one known nano-line pair follows its evidenced stacking rule without retaining both bonuses. -- [ ] Cancel one active buff manually. Check: its effect, stat contribution and +- [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: + 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. - [ ] 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,8 +1,9 @@ # Temporary nano research for 14.9.1 -The timed-buff milestones remain open. Strength Boost is the selected first -case; its crystal can be learned through the existing native upload route. -No timed stat effect or NCU allocation is enabled by learning it. +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. ## Authored effect @@ -50,20 +51,92 @@ path, not stacking priority. The active-program snapshot belongs to SimpleCharFullUpdate `271b3a6b`, reader `10082da0`, rather than FullCharacter `29304349`. It contains an encoded count and five DWORDs per record: program identity, start time and -two duration fields. Snapshot activation applies effects and NCU. Replaying -action 177 as well would double-apply them; initialization order needs an -actual WASM check before either replay path is enabled. +two duration fields. Snapshot activation applies effects and NCU. The server +leaves this list empty and replays action 177 after FullCharacter for the +owner, and after spawn/equipment for observers. Two actual WASM clients +restored one contribution on recipient and observer reconnects. Do not also +populate the snapshot list without changing that replay path. -## Remaining checks +## Server lifecycle -Implement and test one authoritative cast/add/expire/cancel lifecycle, NCU -admission, same-program refresh and the known same-strain pair. Verify owner, -observer, reconnect, zoning and restart behavior without duplicate modifiers. -Stat 464 duration scaling, exact offline timer policy, death cleanup, -friendly eligibility and original server message ordering remain unresolved. -Neither wall-clock expiry nor paused offline time is established by this -static evidence. +The selected 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 +without editing trained base values. + +Admission reserves nano once. Completion atomically retires that reservation, +saves recharge and the recipient's active record, then sends 107 and 177. +A failed outcome cancels and refunds through the existing reservation path. +The stronger same-strain record wins by NCU cost. An equal-strength refresh +replaces its source and deadline, retaining one modifier and one NCU charge. +A weaker program is rejected before charging; a stronger effect arriving +mid-cast causes completion to abort and refund. + +Cancellation validates the current recipient session, owned character and +exact program identity. Cancellation and expiration commit removal before +sending 65. Failed removal keeps the contribution and NCU until a retry can +commit. Active timers use in-memory deadlines and the existing periodic +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. + +## Reconstruction policies and remaining checks + +On normal session departure, remaining duration is checkpointed and paused. +Login resumes it; zoning and overlapping replacement sessions retain the +current deadline. This is an explicit provisional policy: neither wall-clock +expiry nor paused offline time is established by the retained static evidence. The WebSocket reconnect +grace period still counts as a live server session. A crash can recover the +last periodic checkpoint, while an orderly shutdown saves current remaining +time. Add, replacement and removal are immediate durable changes. + +The current friendly path accepts self or connected, ready, living same-side +players in the same playfield and authored centre-to-centre 3D range. It +rechecks target validity, range and NCU at completion. Same-side eligibility +and the native completion's stronger-program check have native evidence; +cross-side fight-mode/team exceptions and historical server completion gates +remain unresolved. The selected programs have no verified general dungeon +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. + +## Verification + +Focused Go regressions cover self/other casts, exact range, MM/BM thresholds, +missing resources, invalid recipients, base-stat preservation and trickle-down, +refresh/upgrade/downgrade, stronger effects arriving mid-cast, owned/foreign +cancellation, duplicate removal, exact-deadline expiration, statement and +COMMIT failure, refund, removal retry, checkpoint cadence, offline duration +and repeated ready messages. + +Two hardware Chromium clients using the published WASM verified +6/2 NCU, ++12/3 NCU, replacement, refresh, weaker rejection, recipient-only allocation, +native icon cancellation and recipient/observer reconnect replay. Native +record durations truncate 120000 to 119999 through their float conversion; +the server expiration deadline uses the authored 120000 centiseconds. Full selected records, original skill resources, native registration bytes, -69 complete REA records and the finding ledger are retained under -`local/nano-buff-research/`. The owned native analysis session was closed. +complete REA records and the finding ledgers are retained under +`local/nano-buff-research/`. Native test probes, screenshots and wire captures +are under `local/nano-buff-smoke/`. Owned native analysis sessions were closed. + +The final native run restored a real cast after server restart with its saved +remaining duration, about 15 minutes 39 seconds, rather than refreshing it to +20 minutes. The recipient canceled that other player's contribution through +the ordinary effect icon. A separate, explicitly seeded 90-second replay +fixture then expired: the server sent one 65 to each observer and removed its +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. diff --git a/server/control.go b/server/control.go @@ -310,6 +310,7 @@ func (server *server) updateUser_locked(destination userData) error { func (server *server) prepareUser_locked(character, updated *character) { updated.specialAttackLocks = character.specialAttackLocks + updated.activeNanos = character.activeNanos updated.team = character.team // Reconnection cancels a pending cast; preserve its refund unless nano was edited. if updated.nano == character.nano { diff --git a/server/main.go b/server/main.go @@ -272,6 +272,9 @@ func (server *server) serveWorldClient(client *worldClient) error { client.ready = false updates := make(map[*worldClient][][]byte) server.cancelCombat_locked(character.id, updates) + if err := server.pauseActiveNanos_locked(character, time.Now()); err != nil { + log.Printf("Saving nano durations: %v", err) + } delete(server.clients, character.id) playfield := character.playfield server.mutex.Unlock() @@ -337,6 +340,11 @@ func (server *server) serveWorldClient(client *worldClient) error { } } server.clients[character.id] = client + for index := range character.activeNanos { + if character.activeNanos[index].expiresAt.IsZero() { + character.activeNanos[index].expiresAt = time.Now().Add(character.activeNanos[index].remaining) + } + } character.sitting = false client.regenerationAt = time.Now() client.regenerationSeconds = 0 @@ -354,6 +362,7 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, characterPacket(other)) if !server.clients[id].loading { updates = append(updates, equippedItemPackets(other)...) + updates = append(updates, activeNanoPackets(other, time.Now())...) } if other.health == 0 { updates = append(updates, deathPacket(other)) @@ -366,6 +375,7 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, server.chatServerPacket(conn)) } updates = append(updates, fullCharacterPacket(character)) + updates = append(updates, activeNanoPackets(character, time.Now())...) 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))) @@ -521,6 +531,10 @@ func (server *server) serveWorldClient(client *worldClient) error { if err := server.handleNanoCast(client, body); err != nil { return err } + case 65: + if err := server.handleNanoRemoval(client, body); err != nil { + return err + } case 106: if err := server.handleReload(client, body); err != nil { return err diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -0,0 +1,207 @@ +package main + +import ( + "ao/server/gamedata" + "database/sql" + "encoding/binary" + "fmt" + "log" + "slices" + "strings" + "time" +) + +type activeNano struct { + program uint32 + caster uint32 + remaining time.Duration + expiresAt time.Time +} + +func abilityNano(program uint32) bool { + return program == 27169 || program == 26360 +} + +func (effect activeNano) remainingAt(now time.Time) time.Duration { + if effect.expiresAt.IsZero() { + return effect.remaining + } + return max(0, effect.expiresAt.Sub(now)) +} + +func (player *character) nanoBonus(stat uint32) int32 { + var bonus int32 + for _, effect := range player.activeNanos { + for _, section := range gamedata.NanoTemplates[effect.program].Sections { + if section.Type != 2 || section.Subtype != 0 { + continue + } + for _, function := range *section.Functions { + if function.ID == 53045 && uint32(*function.Arguments[0].Integer) == stat { + bonus += *function.Arguments[1].Integer + } + } + } + } + return bonus +} + +func (player *character) usedNCU() uint32 { + var used uint32 + for _, effect := range player.activeNanos { + used += itemStat(gamedata.NanoTemplates[effect.program], 54) + } + return used +} + +func (player *character) acceptsNano(program uint32) bool { + definition := gamedata.NanoTemplates[program] + used := player.usedNCU() + for _, effect := range player.activeNanos { + previous := gamedata.NanoTemplates[effect.program] + if itemStat(previous, 75) == itemStat(definition, 75) { + if itemStat(previous, 54) > itemStat(definition, 54) { + return false + } + used -= itemStat(previous, 54) + } + } + return used+itemStat(definition, 54) <= player.maximumNCU() +} + +func activeNanoPackets(player *character, now time.Time) [][]byte { + var packets [][]byte + for _, effect := range player.activeNanos { + if remaining := effect.remainingAt(now); remaining > 0 { + centiseconds := uint32((remaining + 10*time.Millisecond - 1) / (10 * time.Millisecond)) + packets = append(packets, characterActionPacket(player.id, [5]uint32{177, 53019, effect.program, effect.caster, centiseconds})) + } + } + return packets +} + +func writeActiveNanos(tx *sql.Tx, player *character, now time.Time) error { + programs := []any{player.id} + for _, effect := range player.activeNanos { + programs = append(programs, effect.program) + if _, err := tx.Exec(`INSERT INTO active_nanos (player_id, program_id, caster_id, remaining_ns) VALUES (?, ?, ?, ?) + ON CONFLICT(player_id, program_id) DO UPDATE SET caster_id=excluded.caster_id, remaining_ns=excluded.remaining_ns + WHERE (caster_id, remaining_ns) IS NOT (excluded.caster_id, excluded.remaining_ns)`, + player.id, effect.program, effect.caster, effect.remainingAt(now)); err != nil { + return err + } + } + remove := "DELETE FROM active_nanos WHERE player_id=?" + if len(programs) > 1 { + remove += " AND program_id NOT IN (" + strings.TrimSuffix(strings.Repeat("?,", len(programs)-1), ",") + ")" + } + _, err := tx.Exec(remove, programs...) + return err +} + +func (server *server) loadActiveNanos() error { + db, err := server.database() + if err != nil { + return err + } + rows, err := db.Query("SELECT player_id, program_id, caster_id, remaining_ns FROM active_nanos ORDER BY player_id, program_id") + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var id uint32 + var effect activeNano + if err := rows.Scan(&id, &effect.program, &effect.caster, &effect.remaining); err != nil { + return err + } + if !abilityNano(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) + } + return rows.Err() +} + +func (server *server) saveActiveNanos_locked(player *character, now time.Time) error { + db, err := server.database() + if err != nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if err := writeActiveNanos(tx, player, now); err != nil { + return err + } + return tx.Commit() +} + +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) + if err := server.saveActiveNanos_locked(&candidate, now); err != nil { + return err + } + *player = candidate + server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{65, 0, 0, effect.caster, effect.program})) + return nil +} + +func (server *server) pauseActiveNanos_locked(player *character, now time.Time) error { + if len(player.activeNanos) == 0 { + return nil + } + // Remaining duration is simulation state; checkpoints retry a failed logout save. + player.activeNanos = slices.Clone(player.activeNanos) + for index := range player.activeNanos { + player.activeNanos[index].remaining = player.activeNanos[index].remainingAt(now) + player.activeNanos[index].expiresAt = time.Time{} + } + return server.saveActiveNanos_locked(player, now) +} + +func (server *server) handleNanoRemoval(client *worldClient, body []byte) error { + if len(body) != 36 { + return fmt.Errorf("invalid nano removal length") + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + defer server.mutex.Unlock() + if server.clients[client.id] != client || !client.ready || client.loading || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[16:20]) != 65 || binary.BigEndian.Uint64(body[20:28]) != 0 || binary.BigEndian.Uint32(body[28:32]) != 53019 { + return nil + } + player := server.characters[client.id] + index := slices.IndexFunc(player.activeNanos, func(effect activeNano) bool { return effect.program == binary.BigEndian.Uint32(body[32:36]) }) + if index < 0 { + return nil + } + updates := make(map[*worldClient][][]byte) + if err := server.removeNano_locked(player, index, time.Now(), updates); err != nil { + return err + } + server.sendCombatUpdates(updates) + return nil +} + +func (server *server) advanceNanoBuffs_locked(now time.Time, updates map[*worldClient][][]byte) { + for id := uint32(1); id <= server.nextCharacter; id++ { + player := server.characters[id] + if player == nil { + continue + } + for index := len(player.activeNanos) - 1; index >= 0; index-- { + if player.activeNanos[index].remainingAt(now) == 0 { + if err := server.removeNano_locked(player, index, now, updates); err != nil { + log.Printf("Nano expiration: %v", err) + } + } + } + } +} diff --git a/server/nano_buffs_test.go b/server/nano_buffs_test.go @@ -0,0 +1,378 @@ +package main + +import ( + "encoding/binary" + "slices" + "testing" + "time" +) + +func newNanoBuffWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newNanoCastingWorld(t) + world.nextCharacter = 1 + player := world.characters[1] + player.stats.Abilities.Strength = 10 + player.stats.Body.NanoPool = 200 + player.stats.NanoAiding.MatterMetamorphosis = 39 + player.stats.NanoAiding.BiologicalMetamorphosis = 33 + player.nano = 100 + player.inventory.LearnedNanos = []uint32{27169, 26360} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + return world, conn +} + +func castTestBuff(t *testing.T, world *server, caster, target, program uint32) time.Time { + t.Helper() + client := world.clients[caster] + if err := world.handleNanoCast(client, characterActionPacket(caster, [5]uint32{19, 50000, target, 53019, program})[20:]); err != nil { + t.Fatal(err) + } + if client.nanoCast == nil { + t.Fatal("cast was not admitted") + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + world.advanceNanos(at) + return at +} + +func TestNanoBuffSelfCastCommitsOneContributionAndExpires(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:] + + if err := world.handleNanoCast(client, request); err != nil { + t.Fatal(err) + } + deadline := client.nanoCast.readyAt + world.advanceNanos(deadline) + if len(player.activeNanos) != 0 || player.nano != 56 || player.nanoReserved != 44 { + t.Fatal("effect applied before completion or incorrect reservation") + } + world.advanceNanos(deadline.Add(time.Nanosecond)) + world.advanceNanos(deadline.Add(time.Second)) + restored := newTestInventoryServer(t).characters[1] + + if player.effectiveAbility(16) != 22 || player.usedNCU() != 3 || len(player.activeNanos) != 1 || player.nanoReserved != 0 || + restored.effectiveAbility(16) != 22 || restored.usedNCU() != 3 || restored.nano != 56 || restored.activeNanos[0].remaining != 20*time.Minute { + t.Fatalf("cast did not commit exactly one effect: %+v, restored %+v", player.activeNanos, restored.activeNanos) + } + if len(conn.packets) != 4 || binary.BigEndian.Uint32(conn.packets[2][29:33]) != 107 || + !slices.Equal(conn.packets[3], targetPacket(characterActionPacket(1, [5]uint32{177, 53019, 27169, 1, 120000}))) { + t.Fatalf("unexpected native buff delivery: %x", conn.packets) + } + world.advanceNanos(player.activeNanos[0].expiresAt) + world.advanceNanos(deadline.Add(time.Hour)) + if player.effectiveAbility(16) != 10 || player.usedNCU() != 0 || len(player.activeNanos) != 0 || len(conn.packets) != 5 || + !slices.Equal(conn.packets[4], targetPacket(characterActionPacket(1, [5]uint32{65, 0, 0, 1, 27169}))) || + len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("expiration did not remove exactly one durable contribution") + } +} + +func TestNanoBuffFriendlyTargetAndObserverReceiveRecipientEffect(t *testing.T) { + world, casterConn := newNanoBuffWorld(t) + player := world.characters[1] + recipient := *player + recipient.id, recipient.name, recipient.position = 2, "Recipient", [3]float32{0, 0, 12} + world.characters[2], world.nextCharacter = &recipient, 2 + recipientConn := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: recipientConn, ready: true, target: true} + if err := world.saveUser_locked(&recipient); err != nil { + t.Fatal(err) + } + + castTestBuff(t, world, 1, 2, 27169) + + if player.effectiveAbility(16) != 10 || player.usedNCU() != 0 || player.nano != 56 || + recipient.effectiveAbility(16) != 22 || recipient.usedNCU() != 3 || recipient.nano != 100 || + newTestInventoryServer(t).characters[2].activeNanos[0].caster != 1 { + t.Fatal("buff was charged or applied to the wrong actor") + } + for _, conn := range []*combatTestConn{casterConn, recipientConn} { + if !slices.Equal(conn.packets[len(conn.packets)-1][16:], targetPacket(characterActionPacket(2, [5]uint32{177, 53019, 27169, 1, 120000}))[16:]) { + t.Fatalf("wrong recipient/source: %x", conn.packets) + } + } +} + +func TestNanoBuffRejectsInvalidAdmission(t *testing.T) { + for _, scenario := range []string{"MM", "BM", "nano", "unlearned", "no target", "NPC", "cross side", "range", "loading recipient"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + recipient := *player + recipient.id = 2 + world.characters[2] = &recipient + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true} + target := uint32(2) + switch scenario { + case "MM": + player.stats.NanoAiding.MatterMetamorphosis = 38 + case "BM": + player.stats.NanoAiding.BiologicalMetamorphosis = 32 + case "nano": + player.nano = 43 + case "unlearned": + player.inventory.LearnedNanos = nil + case "no target": + target = 0 + case "NPC": + target = 1000000 + case "cross side": + recipient.appearance ^= 1 << 9 + case "range": + recipient.position = [3]float32{0, 12.001, 0} + case "loading recipient": + world.clients[2].loading = true + } + before := player.nano + + err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target, 53019, 27169})[20:]) + + if err != nil || client.nanoCast != nil || player.nano != before || len(player.activeNanos) != 0 || len(recipient.activeNanos) != 0 { + t.Fatal("invalid buff spent nano or applied an effect", err) + } + }) + } +} + +func TestNanoBuffSameStrainUpgradeRefreshAndDowngrade(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player := world.characters[1] + castTestBuff(t, world, 1, 1, 26360) + if player.effectiveAbility(16) != 16 || player.usedNCU() != 2 || player.nano != 76 { + t.Fatal("Augment Strength values") + } + player.nanoRechargeUntil = time.Time{} + + castTestBuff(t, world, 1, 1, 27169) + player.nano, player.nanoRechargeUntil = 100, time.Time{} + castTestBuff(t, world, 1, 1, 27169) + before := len(conn.packets) + player.nanoRechargeUntil = time.Time{} + err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 26360})[20:]) + + if err != nil || len(player.activeNanos) != 1 || player.activeNanos[0].program != 27169 || + player.effectiveAbility(16) != 22 || player.usedNCU() != 3 || player.nano != 56 || world.clients[1].nanoCast != nil || len(conn.packets) != before+1 { + t.Fatal("same-strain replacement retained an old bonus, stacked or charged a rejected downgrade", err) + } + if restored := newTestInventoryServer(t).characters[1]; len(restored.activeNanos) != 1 || restored.activeNanos[0].program != 27169 || restored.effectiveAbility(16) != 22 { + t.Fatal("replacement did not persist atomically") + } +} + +func TestNanoBuffRemovalRejectsForeignAndMalformedRequests(t *testing.T) { + for _, scenario := range []string{"valid", "foreign", "wrong identity", "wrong program", "extra arguments", "loading", "stale"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + castTestBuff(t, world, 1, 1, 27169) + owner, fields := uint32(1), [5]uint32{65, 0, 0, 53019, 27169} + switch scenario { + case "foreign": + owner = 2 + case "wrong identity": + fields[3] = 1040005 + case "wrong program": + fields[4] = 26360 + case "extra arguments": + fields[1] = 1 + case "loading": + client.loading = true + case "stale": + world.clients[1] = &worldClient{id: 1} + } + before := len(conn.packets) + + for range 2 { + if err := world.handleNanoRemoval(client, characterActionPacket(owner, fields)[20:]); err != nil { + t.Fatal(err) + } + } + + if scenario == "valid" { + if len(player.activeNanos) != 0 || player.effectiveAbility(16) != 10 || len(conn.packets) != before+1 || len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("cancel did not remove the contribution exactly once") + } + } else if len(player.activeNanos) != 1 || player.effectiveAbility(16) != 22 || len(conn.packets) != before { + t.Fatal("invalid cancellation changed state") + } + }) + } +} + +func TestNanoBuffFailedEffectCommitRefundsAndFailedRemovalRetries(t *testing.T) { + for _, operation := range []string{"add", "cancel", "expire"} { + t.Run(operation, func(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:] + if err := world.handleNanoCast(client, request); err != nil { + t.Fatal(err) + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + statement := "CREATE TRIGGER fail_buff BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(FAIL, 'test add'); END" + if operation != "add" { + world.advanceNanos(at) + at = player.activeNanos[0].expiresAt + statement = "CREATE TRIGGER fail_buff BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(FAIL, 'test remove'); END" + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + before := len(conn.packets) + + var err error + if operation == "cancel" { + err = world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 27169})[20:]) + } else { + world.advanceNanos(at) + } + + if operation == "add" { + if player.nano != 100 || player.nanoReserved != 0 || len(player.activeNanos) != 0 || client.nanoCast != nil || len(conn.packets) != before+2 || + len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("failed effect was published or cost was not refunded") + } + } else { + if operation == "cancel" && err == nil || len(player.activeNanos) != 1 || player.usedNCU() != 3 || len(conn.packets) != before || len(newTestInventoryServer(t).characters[1].activeNanos) != 1 { + t.Fatal("failed removal was published or changed durable state", err) + } + if _, err := world.db.Exec("DROP TRIGGER fail_buff"); err != nil { + t.Fatal(err) + } + world.advanceNanos(at.Add(time.Second)) + if len(player.activeNanos) != 0 || len(conn.packets) != before+1 { + t.Fatal("expiration did not retry the durable removal") + } + } + }) + } +} + +func TestNanoBuffTimersCheckpointAndPauseWithoutRoutineActorWrites(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player := world.characters[1] + at := castTestBuff(t, world, 1, 1, 27169) + auditCheckpointWrites(t, world) + if _, err := world.db.Exec("CREATE TRIGGER audit_buff AFTER UPDATE ON active_nanos BEGIN INSERT INTO checkpoint_writes VALUES ('active_nanos','UPDATE'); END"); err != nil { + t.Fatal(err) + } + player.nextPositionSave = at.Add(20 * time.Second) + + for second := 1; second < 20; second++ { + world.advanceNanos(at.Add(time.Duration(second) * time.Second)) + if err := world.flushPositions(at.Add(time.Duration(second) * time.Second)); err != nil { + t.Fatal(err) + } + } + if writes := checkpointWrites(t, world); len(writes) != 0 { + t.Fatal("buff ticks wrote to SQLite", writes) + } + if err := world.flushPositions(at.Add(20 * time.Second)); err != nil { + t.Fatal(err) + } + if err := world.pauseActiveNanos_locked(player, at.Add(time.Minute)); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1] + world.advanceNanos(at.Add(24 * time.Hour)) + + if restored.activeNanos[0].remaining != 19*time.Minute || !restored.activeNanos[0].expiresAt.IsZero() || len(player.activeNanos) != 1 || + player.activeNanos[0].remaining != 19*time.Minute || player.effectiveAbility(16) != 22 || + checkpointWrites(t, world)["characters/UPDATE"] != 0 || checkpointWrites(t, world)["active_nanos/UPDATE"] != 2 { + t.Fatal("offline timer or checkpoint cadence changed the wrong state", restored.activeNanos, checkpointWrites(t, world)) + } +} + +func TestNanoBuffCompletionRejectsNewStrongerEffectAndRefunds(t *testing.T) { + world, conn := newNanoBuffWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 26360})[20:]); err != nil { + t.Fatal(err) + } + deadline := client.nanoCast.readyAt + // Another caster's stronger contribution arrives while this cast is pending. + player.activeNanos = []activeNano{{program: 27169, caster: 2, remaining: time.Minute, expiresAt: deadline.Add(time.Minute)}} + if err := world.saveActiveNanos_locked(player, deadline); err != nil { + t.Fatal(err) + } + conn.packets = nil + + world.advanceNanos(deadline.Add(time.Nanosecond)) + world.advanceNanos(deadline.Add(time.Second)) + + if client.nanoCast != nil || player.nano != 100 || player.nanoReserved != 0 || player.effectiveAbility(16) != 22 || + len(player.activeNanos) != 1 || player.activeNanos[0].caster != 2 || len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 { + t.Fatal("late weaker effect overwrote the stronger buff or lost its refund") + } +} + +func TestNanoBuffStrengthTricklesIntoSkillsWithoutChangingBase(t *testing.T) { + world, _ := newNanoBuffWorld(t) + player := world.characters[1] + before := player.effectiveSkill(142, 5, [6]uint32{60, 0, 40, 0, 0, 0}) + + castTestBuff(t, world, 1, 1, 27169) + after := player.effectiveSkill(142, 5, [6]uint32{60, 0, 40, 0, 0, 0}) + if err := world.handleNanoRemoval(world.clients[1], characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 27169})[20:]); err != nil { + t.Fatal(err) + } + + if before != 7 || after != 9 || player.baseStats().Abilities.Strength != 10 || player.effectiveSkill(142, 5, [6]uint32{60, 0, 40, 0, 0, 0}) != 7 { + t.Fatal("temporary ability changed the base stat or failed to affect trickle-down", before, after) + } +} + +func TestNanoBuffReadyBroadcastReplaysOnceToObservers(t *testing.T) { + world, conn := newNanoBuffWorld(t) + castTestBuff(t, world, 1, 1, 27169) + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 1} + world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[1].loading = true + conn.packets = nil + + for range 2 { + if err := world.handleCharacterReady(world.clients[1]); err != nil { + t.Fatal(err) + } + } + + var adds int + for _, packet := range observer.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 177 { + adds++ + } + } + if adds != 1 || len(conn.packets) != 2 || world.characters[1].effectiveAbility(16) != 22 || world.characters[1].usedNCU() != 3 { + t.Fatal("repeated ready stacked a contribution or replayed it to its owner", adds, len(conn.packets)) + } +} + +func TestNanoBuffFailedCommitPublishesNoEffectAndRefunds(t *testing.T) { + world, conn := newNanoBuffWorld(t) + client, player := world.clients[1], world.characters[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:]); err != nil { + t.Fatal(err) + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + if _, err := world.db.Exec(`CREATE TABLE pending_buff (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); + CREATE TRIGGER fail_buff AFTER INSERT ON active_nanos BEGIN INSERT INTO pending_buff VALUES (999999); END`); err != nil { + t.Fatal(err) + } + conn.packets = nil + + world.advanceNanos(at) + + if player.nano != 100 || player.nanoReserved != 0 || !player.nanoRechargeUntil.IsZero() || len(player.activeNanos) != 0 || len(conn.packets) != 2 || + binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 || len(newTestInventoryServer(t).characters[1].activeNanos) != 0 { + t.Fatal("failed COMMIT charged a cast or published an effect") + } +} diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -11,6 +11,7 @@ import ( ) type nanoCast struct { + program uint32 target uint32 readyAt time.Time cancelled bool @@ -30,12 +31,12 @@ func nanoPointsPacket(player *character) []byte { return n3Packet(0x2b333d6e, 50000, player.id, body) } -func winterBiteCost() uint32 { +func nanoCost(program uint32) uint32 { // Native default cost modifier 318 is 100; retain the x87 float32 constant. - return uint32(float64(itemStat(gamedata.NanoTemplates[29618], 407)*100) * float64(float32(0.01))) + return uint32(float64(itemStat(gamedata.NanoTemplates[program], 407)*100) * float64(float32(0.01))) } -func (player *character) winterBiteCastDelay() time.Duration { +func (player *character) nanoCastDelay(program uint32) time.Duration { // kkr.dll 100651b4..1006526b stores initiative reduction before the final duration. stats := player.baseStats() initiative := player.effectiveSkill(149, stats.Speed.NanoInitiative, [6]uint32{0, 40, 0, 0, 60, 0}) @@ -43,19 +44,66 @@ func (player *character) winterBiteCastDelay() time.Duration { if initiative > 1200 { reduction = float32(600 + float64(initiative-1200)*float64(float32(1.0/6))) } - delay := float32(float64(itemStat(gamedata.NanoTemplates[29618], 294))*float64(float32(0.01)) - + delay := float32(float64(itemStat(gamedata.NanoTemplates[program], 294))*float64(float32(0.01)) - float64(reduction)*float64(float32(0.01)) - float64(player.aggDef/100)) return time.Duration(float64(delay) * float64(time.Second)) } -func (server *server) winterBiteTarget_locked(player, target *character, client *worldClient, now time.Time) bool { - if target == nil || !target.npc || target.appearance>>4&7 != 6 || !client.npcs[target.id] || - target.health == 0 || target.playfield != player.playfield { +func (player *character) nanoRequirementsMet(program uint32) bool { + stats := player.baseStats() + if program == 29618 { + 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 { + if section.Actions == nil { + continue + } + for _, action := range *section.Actions { + 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 int32(player.effectiveSkill(uint32(requirement.Stat), base, [6]uint32{0, 0, 0, 80, 0, 20})) <= requirement.Value { + return false + } + } + } + } + return true +} + +func (server *server) nanoTarget_locked(player, target *character, client *worldClient, program uint32, now time.Time) bool { + if target == nil || target.health == 0 || target.playfield != player.playfield { return false } - position := predictedPosition_locked(player, client, now) - x, y, z := position[0]-target.position[0], position[1]-target.position[1], position[2]-target.position[2] - return x*x+y*y+z*z <= 25*25 + second := target.position + if program == 29618 { + if !target.npc || target.appearance>>4&7 != 6 || !client.npcs[target.id] { + return false + } + } else { + recipient := server.clients[target.id] + if target.npc || target.appearance>>9&3 != player.appearance>>9&3 || recipient == nil || !recipient.ready || recipient.loading || !target.acceptsNano(program) { + return false + } + second = predictedPosition_locked(target, recipient, now) + } + first := predictedPosition_locked(player, client, now) + x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] + distance := float32(itemStat(gamedata.NanoTemplates[program], 287)) + return x*x+y*y+z*z <= distance*distance } func (server *server) handleNanoCast(client *worldClient, body []byte) error { @@ -87,15 +135,14 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error { return nil } - // Admit only the learned QL 1 program against a visible living creature. + // Validate the learned program, shared action gates and its authored requirements. + program := binary.BigEndian.Uint32(body[32:36]) target := server.characters[binary.BigEndian.Uint32(body[24:28])] - stats := player.baseStats() accepted := binary.BigEndian.Uint32(body[20:24]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == 53019 && - binary.BigEndian.Uint32(body[32:36]) == 29618 && slices.Contains(player.inventory.LearnedNanos, 29618) && - 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 && player.nano >= winterBiteCost() && + slices.Contains(player.inventory.LearnedNanos, program) && player.nanoRequirementsMet(program) && player.nano >= nanoCost(program) && !player.sitting && !player.driving() && client.forward == 0 && !client.strafing && !client.turning && client.equipment == nil && - (player.fighting == 0 || now.Before(player.rechargeUntil)) && server.winterBiteTarget_locked(player, target, client, now) + (player.fighting == 0 || now.Before(player.rechargeUntil)) && server.nanoTarget_locked(player, target, client, program, now) + if !accepted { updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{108})) server.mutex.Unlock() @@ -105,19 +152,19 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error { // Reserve the cost once; the server releases the native effect gate at the deadline. candidate := *player - candidate.nanoReserved = winterBiteCost() + candidate.nanoReserved = nanoCost(program) candidate.nano -= candidate.nanoReserved if err := server.saveNanoBalance_locked(&candidate); err != nil { server.mutex.Unlock() return err } *player = candidate - client.nanoCast = &nanoCast{target: target.id, readyAt: now.Add(player.winterBiteCastDelay())} + client.nanoCast = &nanoCast{program: program, target: target.id, readyAt: now.Add(player.nanoCastDelay(program))} if player.fighting != 0 && client.nanoCast.readyAt.After(player.rechargeUntil) { attack, _ := player.attackDelays() player.nextAttack = client.nanoCast.readyAt.Add(attack) } - server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{18, 50000, target.id, 0, 29618})) + server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{18, 50000, target.id, 0, program})) updates[client] = append(updates[client], nanoPointsPacket(player)) server.mutex.Unlock() server.sendCombatUpdates(updates) @@ -154,31 +201,52 @@ func (server *server) advanceNanos(now time.Time) { defer server.updateMutex.Unlock() server.mutex.Lock() updates := make(map[*worldClient][][]byte) + server.advanceNanoBuffs_locked(now, updates) for id, client := range server.clients { if client.nanoCast == nil || !now.After(client.nanoCast.readyAt) { continue } player := server.characters[id] + program := client.nanoCast.program target := server.characters[client.nanoCast.target] - if client.nanoCast.cancelled || !client.ready || client.loading || player.health == 0 || !server.winterBiteTarget_locked(player, target, client, now) { + if client.nanoCast.cancelled || !client.ready || client.loading || player.health == 0 || !server.nanoTarget_locked(player, target, client, program, now) { server.abortNano_locked(client, now, updates) continue } - // Only this result changes HP; the native Hit effect is server-owned. - damage := min(10+rand.Uint32N(14), target.health) - victim := prepareDamage(player, target, damage, now) caster := *player caster.nanoReserved = 0 - recharge := float64(itemStat(gamedata.NanoTemplates[29618], 210)) * float64(float32(0.01)) + recharge := float64(itemStat(gamedata.NanoTemplates[program], 210)) * float64(float32(0.01)) caster.nanoRechargeUntil = now.Add(time.Duration(recharge * float64(time.Second))) - if err := server.saveNanoHit_locked(&caster, &victim, now); err != nil { - log.Printf("Nano damage: %v", err) + victim := *target + if target == player { + victim = caster + } + var damage uint32 + if program == 29618 { + damage = min(10+rand.Uint32N(14), target.health) + victim = prepareDamage(player, target, damage, now) + } else { + // A strain has one contribution; a refresh replaces its deadline and caster. + victim.activeNanos = slices.DeleteFunc(slices.Clone(victim.activeNanos), func(effect activeNano) bool { + return itemStat(gamedata.NanoTemplates[effect.program], 75) == itemStat(gamedata.NanoTemplates[program], 75) + }) + duration := time.Duration(itemStat(gamedata.NanoTemplates[program], 8)) * 10 * time.Millisecond + victim.activeNanos = append(victim.activeNanos, activeNano{program: program, caster: player.id, remaining: duration, expiresAt: now.Add(duration)}) + } + + if err := server.saveNanoOutcome_locked(&caster, &victim, now); err != nil { + log.Printf("Nano outcome: %v", err) server.abortNano_locked(client, now, updates) continue } *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)})) + continue + } body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) body = binary.BigEndian.AppendUint32(body, 95) server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, 29618})) diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -146,7 +146,7 @@ func TestWinterBiteNativeTimingAndRangeBoundary(t *testing.T) { err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) after := time.Now() if err != nil || client.nanoCast == nil || client.nanoCast.readyAt.Before(before.Add(scenario.delay)) || client.nanoCast.readyAt.After(after.Add(scenario.delay)) { - t.Fatal("native timing/range", err, client.nanoCast, player.winterBiteCastDelay()) + t.Fatal("native timing/range", err, client.nanoCast, player.nanoCastDelay(29618)) } }) } diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -116,7 +116,7 @@ func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now return nil } -func (server *server) saveNanoHit_locked(player, target *character, now time.Time) error { +func (server *server) saveNanoOutcome_locked(player, target *character, now time.Time) error { db, err := server.database() if err != nil { return err @@ -127,7 +127,7 @@ func (server *server) saveNanoHit_locked(player, target *character, now time.Tim } defer tx.Rollback() - // Commit the completed cast's cost and recharge with its damage and death state. + // Commit the completed cast's cost and recharge with its authoritative effect. result, err := tx.Exec("UPDATE characters SET nano=?, nano_reserved=?, nano_recharge_until=? WHERE id=?", player.nano, player.nanoReserved, player.nanoRechargeUntil, player.id) if err != nil { return err @@ -139,7 +139,12 @@ func (server *server) saveNanoHit_locked(player, target *character, now time.Tim if changed != 1 { return fmt.Errorf("caster %d nano update affected %d rows", player.id, changed) } - state, err := writeNPCOutcome_locked(tx, target, now) + var state npcState + if target.npc { + state, err = writeNPCOutcome_locked(tx, target, now) + } else { + err = writeActiveNanos(tx, target, now) + } if err != nil { return err } @@ -149,6 +154,10 @@ func (server *server) saveNanoHit_locked(player, target *character, now time.Tim player.savedVitals.Nano, player.savedVitals.NanoRechargeUntil = player.nano, player.nanoRechargeUntil player.savedVitals.NanoReserved = player.nanoReserved - server.rememberNPCOutcome_locked(target, state, now) + if target.npc { + server.rememberNPCOutcome_locked(target, state, now) + } else if target.id == player.id { + target.savedVitals = player.savedVitals + } return nil } diff --git a/server/state.go b/server/state.go @@ -50,6 +50,7 @@ type character struct { treatmentLockedUntil time.Time nanoRechargeUntil time.Time specialAttackLocks map[uint32]time.Time + activeNanos []activeNano regenerationAt time.Time regenerationSeconds uint32 savedProfile playerProfile diff --git a/server/stats.go b/server/stats.go @@ -153,7 +153,7 @@ func (character *character) baseStats() characterStats { func (character *character) effectiveAbility(stat uint32) uint32 { abilities := character.baseStats().Abilities values := [6]uint16{abilities.Strength, abilities.Agility, abilities.Stamina, abilities.Intelligence, abilities.Sense, abilities.Psychic} - return uint32(int32(values[stat-16]) + character.inventory.equipmentBonus(stat)) + return uint32(int32(values[stat-16]) + character.inventory.equipmentBonus(stat) + character.nanoBonus(stat)) } func (character *character) effectiveSkill(stat uint32, base uint16, weights [6]uint32) uint32 { diff --git a/server/users.go b/server/users.go @@ -129,6 +129,9 @@ func (server *server) loadUsers() error { if err := server.loadPlayers(); err != nil { return err } + if err := server.loadActiveNanos(); err != nil { + return err + } if err := server.loadItems(); err != nil { return err } @@ -206,7 +209,7 @@ func (server *server) saveUser_locked(character *character) error { func (server *server) savePosition_locked(character *character) error { position := playerPosition{character.playfield, character.position, character.rotation, character.returnDoor} vitals := character.vitals() - if position == character.savedPosition && vitals == character.savedVitals { + if position == character.savedPosition && vitals == character.savedVitals && len(character.activeNanos) == 0 { return nil } db, err := server.database() @@ -218,11 +221,16 @@ func (server *server) savePosition_locked(character *character) error { return err } defer tx.Rollback() - if err := insertPlayer(tx, character); err != nil { - return err + if position != character.savedPosition || vitals != character.savedVitals { + if err := insertPlayer(tx, character); err != nil { + return err + } + record := character.record() + if err := updateRecord(tx, "characters", character.id, positionColumns+", "+vitalColumns, append(record.Position.fields(), vitals.fields()...)); err != nil { + return err + } } - record := character.record() - if err := updateRecord(tx, "characters", character.id, positionColumns+", "+vitalColumns, append(record.Position.fields(), vitals.fields()...)); err != nil { + if err := writeActiveNanos(tx, character, time.Now()); err != nil { return err } if err := tx.Commit(); err != nil { diff --git a/server/world.sql b/server/world.sql @@ -142,6 +142,13 @@ CREATE TABLE IF NOT EXISTS learned_nanos ( nano_id INTEGER NOT NULL, PRIMARY KEY (player_id, nano_id) ); +CREATE TABLE IF NOT EXISTS active_nanos ( + player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE, + program_id INTEGER NOT NULL, + caster_id INTEGER NOT NULL, + remaining_ns INTEGER NOT NULL CHECK (remaining_ns >= 0), + PRIMARY KEY (player_id, program_id) +); CREATE TABLE IF NOT EXISTS npcs ( id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id >= 1000000), definition TEXT NOT NULL, diff --git a/server/world_actions.go b/server/world_actions.go @@ -41,6 +41,7 @@ func (server *server) handleCharacterReady(client *worldClient) error { resources := make(map[*worldClient][][]byte) if client.loading { equipment = equippedItemPackets(server.characters[client.id]) + equipment = append(equipment, activeNanoPackets(server.characters[client.id], time.Now())...) team = server.teamPackets_locked(client.id) server.queueTeamResources_locked(resources, server.characters[client.id]) }