commit f9f283a91e79c063db1ff1a97e7bee188c721a1a
parent 7f4c6e2167034a597faa60a6e86661e9b0d1eca4
Author: anon <anon@example.com>
Date: Wed, 21 Oct 2026 21:02:31 +0000
Implement client-derived PvE combat and isolate slow clients
Add authoritative combat resources, editable base stats, native timing and protocol behavior, and documented reverse-engineering evidence with explicit balance limitations.
Serialize lifecycle updates and give world and chat sessions bounded FIFO writers with asynchronous disconnects. Cover combat, regeneration, persistence, recipient isolation, transport shutdown, and expired browser sessions with regression and stress tests.
Diffstat:
44 files changed, 5543 insertions(+), 157 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -110,6 +110,16 @@ Normal speech reaches 10 metres, whisper 1.5 metres and shout 60 metres, within
the same playfield. New chat is live: players do not receive conversations
that happened while they were absent or outside vicinity range.
+World and chat sessions each have a dedicated FIFO output writer. Shared
+broadcast paths only enqueue owned packet bytes; they never wait for a
+recipient's socket. Pending output is capped at 8 MiB per connection, plus
+one packet being written. Queue overflow or a failed, short or timed-out write
+disconnects that connection. Writes have a five-second deadline and run outside
+shared state locks, so a slow recipient cannot stall other players' updates.
+Forced disconnects discard queued output and wake the connection's writer;
+socket shutdown also runs there, so a transport close handshake cannot delay
+shared work or a replacement session.
+
The server saves each player's sent and received messages in
`data/players/<id>/chat.ndjson`, alongside `player.yaml` and `position.yaml`.
Shared messages are duplicated into each participant's history. Records
@@ -133,6 +143,30 @@ the server log while live chat remains available.
[Server controls](http://127.0.0.1:8080/control)
provide character editing, teleporting and time controls.
+Basic unarmed PvE combat is available against creature NPCs. Stand within four
+metres, select one with Tab or a click, then press Q (or the mobile Attack
+button). Q stops your own attacks, while an opponent already retaliating
+continues until you leave melee range. Player fists use the shipped QL 1
+3-5 damage range and native initiative/AggDef timing: 1.98 seconds attack plus
+1.97 seconds recharge at centered aggression, or one second each at full
+aggression. The Stats window's DEF/AGG slider changes this setting. Player
+health uses breed/level/Body Development and Soldier title data (37 HP for the
+default level 1 Solitus). Six abilities and four combat skills are editable in
+the character page's stats section and persist in player.yaml. Health, nano,
+initiative timing and regeneration derive from those base values. Absolute
+resource corrections reconcile client prediction outside active weapon queues;
+see [regeneration and stats](docs/combat-regeneration.md). NPCs still have 100 HP and hit for 5 with one-second
+attack/recharge phases. Those NPC profiles, fixed fist QL, always-hit attacks
+and the four-meter range are reconstruction choices. See
+[combat rules and evidence](docs/combat-rules.md) for the remaining gaps.
+Human NPCs and players are protected. Defeated creatures remain dead
+until the server restarts; reload the game to revive a defeated player. Weapon
+equipment, specials, nanos, loot and XP are not implemented.
+
+The [client combat reconstruction](docs/combat-client-reconstruction.md) maps
+native formulas, action scheduling, messages and effects to server obligations
+and records the remaining gaps.
+
Bronto Burger, Lush Fields and Newland have passed browser rendering, movement,
inventory/map, audio and connection checks. Performance work and broader
gameplay validation continue.
diff --git a/docs/combat-client-effect-handlers.md b/docs/combat-client-effect-handlers.md
@@ -0,0 +1,291 @@
+# Client effect handlers and skill locks in 14.9.1
+
+This continues the [effect inventory](combat-client-effects.md) using the
+same original kkr.dll and matching resource database. Original addresses use
+base `0x10000000`; generated C uses `0x36000000`. Function names below come
+from native registrations where available. Unnamed IDs retain their numbers;
+behavioral descriptions do not assign modern function names to them.
+
+All 47 observed IDs admitted by `100bfb40` now have a dispatch classification
+below. This is complete coverage of that intersection, with explicitly partial
+semantics for deeper rendering, AI and item-data consumers. The other 25
+observed IDs are rejected by this executor. Neither the gate nor the inventory
+establishes original server execution rules.
+
+## Application, scheduling and removal
+
+SimpleChar's constructor at `1006d5f1` sets its Beholder interface vtable to
+`1017139c`. Vtable entry `+0x34` is `10002370`, the common effect-list apply
+routine. It clones each effect with `100bfc30`, then sets flag mask `0x1` for a
+nonzero third argument and clears it for zero. For ordinary modifier handlers,
+mask `0x1` selects removal. This independently resolves the ApplySpells wire byte:
+byte 1 becomes argument 0 and adds; byte 0 becomes argument 1 and removes.
+SpellList activation passes zero and adds. Exact packets and function bodies
+are in the [protocol report](combat-client-protocol.md).
+
+The routine copies the source identity, initializes the clone, and chooses
+the target using argument key 32. Target 2 resolves the receiving character,
+target 3 uses the supplied subject; other target modes have additional context.
+TimedEffect, a remaining count above 1, or a positive interval causes insertion
+into the target's effect list, category 9, through `100027e0`. Ordinary immediate
+effects call `100be8e0` directly. A count of -1 takes a separate cleanup path
+here; it must not be assumed to mean an infinite effect in every entry point.
+
+The queued actor path calls `100021f0` from the two-second GameTime branch
+of `1006ea50`. It visits the queued effects, invokes `100be8e0`, and removes
+finished entries. The executor advances elapsed time by 200 each accepted
+visit. Together these establish **centiseconds with two-second scheduling
+resolution** for this path. Item and visual consumers can have other entry
+points; this is not proof of server scheduler resolution.
+
+`100be8e0` first applies the gate and criteria. A rejected function clears its
+remaining count. A failed criterion decrements the count and returns before
+advancing elapsed time. An ordinary successful tick waits for interval key 4,
+resets elapsed time to zero, decrements a positive remaining count and dispatches.
+This discards excess elapsed time rather than carrying it into the next tick.
+Removal requests for queued effects are initialized with one remaining tick.
+
+TimedEffect 53014 has its own branch before the switch:
+
+```
+if remaining == 0 or criteria fail: stop before this branch
+elapsed += 200
+if elapsed < delay4: return
+if flags & 1: return
+if not (flags & 2):
+ flags |= 2
+ apply_additive_modifier(stat0, amount39)
+ timed_total[stat0] += amount39
+if elapsed < delay4 + duration25: return
+flags |= 1
+remove_additive_modifier(stat0, amount39)
+flags &= ~1
+remaining = 0
+timed_total[stat0] -= amount39
+```
+
+The add/remove wrapper is `100bd370 -> 100bd600`; `10071700` and `10071770`
+maintain the separate totals map at actor `+0x14c`. The Riposte Item resource
+42031 supplies `(stat=227, amount=55, key11=1, key46=0, duration=4000)`, so
+the raw duration is 40 seconds in this actor path. Keys 11 and 46 are decoded
+and preserved, but this branch does not use them to calculate its duration.
+
+The early `flags & 1` return is significant: replaying TimedEffect through the
+generic removal entry point does not perform the internal expiry subtraction.
+Likewise, criterion failure can finish a queued effect before its internal
+expiry branch. These are observed client branches, not a complete cancellation
+or stacking policy for a server to invent around.
+
+## Numeric handlers
+
+`Skill` 53012 and `Modify` 53045 both reach `100bd600`; Modify uses the wrapper
+`100bd4d0`. The target must support SimpleChar. Argument key 0 is the stat and
+key 39 the signed amount. Addition calls `10074730`, removal `10074b00`.
+Their modifier map is separate from the base stat. The latter removes an
+entry when its sum becomes zero. Removing maximum health stat 1 clamps
+current health to the resulting final maximum in this call path.
+
+Dependencies are invalidated and consumers notified, including initiative
+timing, ability trickle, health/nano foundations, regeneration and physical
+scale. The [effect report](combat-client-effects.md) details those calls.
+For an authoritative buff implementation, retaining each applied effect and
+its amount is necessary to remove it once; overwriting the base stat would
+not reproduce this additive behavior.
+
+`Set` 53026 (`100bd380`) is different. It requests stat key 0 and value key 39,
+then uses the subject's setter/definition operations. Stat 0 takes a flag
+operation. It diverts IDs 4, 27, 37, 47, 49, 59, 60, 214, 365 and 131072 to
+a restricted character branch, which only implements selected cases: profession
+60, fatness 47, the stat-49 stub call, and 131072. The other diverted IDs do
+not simply fall through to a generic assignment. This is not permission to
+use Set for arbitrary authoritative health changes.
+
+`AddSkill` 53028 (`100bd550`) requires DummyItemBase, not SimpleChar. Its three
+arguments decode as keys 55, 0 and 39. `1008f590` selects item list key 55 and
+updates the pair whose key equals argument 0, or appends that pair when absent.
+The stored value is argument 39. This changes an item's skill/weight list;
+it does not grant that skill amount to a character. The First-Aid Kit example
+has `(55=3, 0=123, 39=1)`.
+
+Unnamed 53110 (`100c2000`) temporarily replaces a base stat. On apply,
+`100760c0` saves the mode-2 value once in a map at the stat helper's `+0x0c`,
+then writes the requested value. Further applications update the value while
+preserving the first saved original. On removal, `10076180` restores that
+original and erases its entry. There is no percentage calculation here.
+It is not a stack of independent replacement effects. The Mid's resource
+96078 uses stat 360 and value 20.
+
+Unnamed 53175 (`100c3050`) applies an additive amount calculated as
+`trunc(level54 * amount39 * 0.005)`. The original single-precision multiplier
+at `10170e9c` is 0.004999999888241291. Removal recalculates that amount using
+the current level and calls the same modifier removal helper; it does not
+retrieve a previously saved amount. This matters if level changes while
+the effect is active. This observation does not establish the complete server
+organization-advantage scaling policy.
+
+Unnamed 53139/53140 (`100c2980`/`100c29e0`) set/clear one bit in a supported
+stat. They read the stat in mode 2 and use
+`1 << (amount39 & 31)`. These handlers do not consult the removal flag.
+Unnamed 53067/53068 operate on feature-mask key 73 through `10059930` and
+`10059a80`, reversing those calls on removal. Those helpers maintain a byte
+reference count per bit and update Features stat 224. They also notify
+movement/animation consumers. A positive duration schedules inverse events
+128 or 64 respectively through `1002ee20`. This is a distinct mask/count
+mechanism, not the additive skill map.
+
+## Skill locks are a separate mechanism
+
+SkillTime 53033 is admitted but dispatches `ATR_t::ActivateTestArgument` at
+`1010def0`. Its entire body is `ret 4`. Its three serialized arguments are
+keys 55, 0 and 39; decoding them does not start a client lock.
+
+The actual lock state is a vector of eight-byte `(skill, remaining_seconds)`
+pairs behind the first pointer in the actor's stat helper at `+0x154`:
+
+| Function | Behavior |
+| --- | --- |
+| `100738e0(skill)` | Tests membership. |
+| `10073ab0(skill)` | Returns remaining seconds, or zero when absent. |
+| `10073ae0(skill, raw_duration)` | Ignores an already-present skill. Otherwise appends a lock after the duration calculation below, then calls `100572b0` for consumers. That helper marks the found skill/action entry dirty and emits its UI notification only for the local player. |
+| `10073d00()` | Decrements each remaining duration by one and erases entries reaching zero. Called from the one-second GameTime branch at `1006ef69`. |
+
+```
+duration = trunc(raw_duration + raw_duration * effective_SkillLockModifier382 * 0.01)
+```
+
+The multiplication of the two integers precedes the floating-point scaling
+in the original instructions. The setter does not refresh an existing lock,
+and does not explicitly clamp its newly computed duration. Global tick phase
+affects the first decrement. Native `fStatToString` registration at `100318a8`
+names stat 382 `SkillLockModifier`.
+
+Replication is **CharacterAction**, class `0x5e477770`, action **170**. Its
+second identity supplies `(type=skill, instance=raw_duration)`; the first
+identity is unused by this branch. Reader `1007d5c0`, activation `1007d640`
+and actor callback `1006fa30` establish that route. The callback's original
+compressed tables at `10070d6c` and `10070c08` map action 170 to `10070a5a`,
+which calls `10073ae0`. Generic SkillIIR assignments do not create this vector.
+This supports separate server lock state and expiry plus the native notification,
+without pretending that the SkillTime local handler executes the lock.
+
+## All observed admitted handlers
+
+"Decoded" below means the immediate numeric or stub behavior is established.
+"Partial" identifies a classified path whose deeper consumer or full policy
+remains outside this pass. Presentation classifications require a concrete
+render/text/appearance call; an evocative name alone was not enough.
+
+| ID / native name | Dispatch | Classification and coverage |
+| --- | --- | --- |
+| 53012 Skill | `100bd600` | Decoded: additive character modifier. |
+| 53014 TimedEffect | special branch, `100bd370` | Decoded core: timed modifier and internal expiry; cancellation boundary above. |
+| 53019 Nano | `100be540` | Decoded immediate path: learned nano-list lookup/add/remove helpers `10064eb0`/`10064dd0`/`10064e60`, messages; not a cast/damage outcome. Guard behavior remains as written. |
+| 53026 Set | `100bd380` | Decoded: subject stat setter with restricted cases. |
+| 53028 AddSkill | `100bd550` | Decoded: item skill-list pair insertion/update. |
+| 53030 GfxEffect | `100be720` | Partial presentation: creates/deletes visual effects, stores effect identity and duration. |
+| 53032 SaveChar | `100c1da0` | Decoded no-op: calls return-only `1010ba00`. |
+| 53033 SkillTime | `1010def0` | Decoded no-op; actual lock route above. |
+| 53035 HeadMesh | `100bd9a0` | Partial presentation: mesh/category attach/remove. |
+| 53037 BackMesh | `100bd9a0` | Partial presentation: same handler. |
+| 53038 ShoulderMesh | `100bd9a0` | Partial presentation: same handler. |
+| 53039 Texture | `100bdbd0` | Partial presentation: texture/appearance calls and tracking. |
+| 53044 StaticText | `1010def0` | Decoded no-op in this executor. |
+| 53045 Modify | `100bd4d0` | Decoded: wrapper for additive modifier. |
+| 53051 unnamed | `1000c340` | Decoded no-op; shared exported aliases do not change return-only body. |
+| 53054 BodyCatMesh | `100c1350` | Partial presentation: actor mesh/category add/remove. |
+| 53055 AttractorMesh | `100c13b0` | Partial presentation: mesh attachment add/remove. |
+| 53057 HeadText | `100c14e0` | Decoded presentation: text notification on application. |
+| 53060 unnamed | `100c1540` | Partial: conditional stat-359 assignment/clear, actor refresh and duration event 32. No invented stat name. |
+| 53065 unnamed | `100c1620` | Partial item data: four fields through item virtual method, selector 0. |
+| 53066 unnamed | `100c16e0` | Decoded no-op after argument/context reads: calls return-only `1000c340`. |
+| 53067 unnamed | `100c1730` | Decoded core: reference-counted feature mask addition/removal, inverse event 128. |
+| 53068 unnamed | `100c17f0` | Decoded core: inverse feature-mask operation, inverse event 64. |
+| 53069 NextHead | `100c2aa0` | Decoded no-op through `1010ba00`. |
+| 53070 PrevHead | `100c2aa0` | Decoded no-op through `1010ba00`. |
+| 53075 unnamed | `100c18f0` | Partial item data: same four-field virtual operation, selector 1. |
+| 53076 unnamed | `100c19b0` | Partial item data: same operation, selector 2. |
+| 53079 unnamed | `100c1a70` | Decoded presentation: visual effect create/delete and duration. |
+| 53086 unnamed | `100c1da0` | Decoded no-op through `1010ba00`. |
+| 53087 unnamed | `100c2d60` | Decoded no-op after context reads: `1000c310` is return-only. |
+| 53100 unnamed | `100c1e70` | Decoded no-op after context reads: `1000c310` and `1010ba00` return. |
+| 53110 unnamed | `100c2000` | Decoded: temporary base-stat replacement/restore. |
+| 53115 unnamed | `100c20a0` | Partial presentation: local-player message with string and two arguments. |
+| 53117 unnamed | `100c2100` | Partial: target eligibility checks/messages; no demonstrated damage/hate mutation. |
+| 53118 unnamed | `100c2330` | Partial: NPC restriction and controller state 3; updates feature bits. |
+| 53121 unnamed | `100c2480` | Partial: native text identifies fear; NPC controller state 2 apply/reset. |
+| 53127 unnamed | `100c2680` | Partial: native text identifies mind control; NPC controller state 4 apply/reset. |
+| 53128 unnamed | `100c2760` | Partial: native text identifies daze; NPC controller state 5 and feature bit 0x200. |
+| 53130 unnamed | `100c2810` | Partial: invokes `10061bc0`, clearing a controller identity via `1005f270`. |
+| 53132 GenerateName | `100bdf60` | Decoded presentation: applies supplied name strings through `10070f40`. |
+| 53134 unnamed | `100c2840` | Decoded presentation: text to local actor or within an argument-specified 3D radius. |
+| 53138 unnamed | `100c1cc0` | Partial presentation: actor animation/state notifications 27 and 35. |
+| 53139 unnamed | `100c2980` | Decoded: set a bit in a stat. |
+| 53140 unnamed | `100c29e0` | Decoded: clear a bit in a stat. |
+| 53162 unnamed | `100c2aa0` | Decoded no-op through `1010ba00`. |
+| 53175 unnamed | `100c3050` | Decoded numeric: level-scaled additive modifier. |
+| 53177 unnamed | `100c3170` | Decoded no-op after argument/context reads: calls `1000c340`. |
+
+WeaponItem vtable `101745cc + 0xc0` resolves to `100ae2e0` for the four-field
+item operation. Selectors 1 and 2 replace stored four-word descriptors at
+`+0x1d0` and `+0x1cc`; selector 0 delegates to `1009f2a0`. This storage alone
+does not establish combat damage arithmetic. Their complete later consumer
+is left partial rather than labeling all three as harmless cosmetics.
+
+The NPC controller helpers `1005b010` through `1005b19c` establish those state
+and feature changes. They do not supply an NPC hate table or authoritative
+taunt formula. No such formula was recovered in the inspected admitted paths.
+
+## Rejected and unresolved boundaries
+
+The 25 observed IDs rejected before this local dispatch are:
+
+```
+53002 53016 53063 53064 53073 53083 53089 53092 53105 53107
+53109 53124 53126 53133 53137 53144 53153 53154 53155 53166
+53167 53173 53178 53181 53185
+```
+
+Hit 53002 therefore does not produce local healing, damage, HoT or DoT ticks
+through this executor. Its definitions remain readable data. Rejected effects
+may have server execution or other client readers; the gate is not a global
+absence proof. No independent heal RNG, armor/reflect outcome, ammunition
+consumption or hate calculation was found in the admitted handler bodies
+inspected here. [Combat stats](combat-client-stats.md) separately covers nano
+cost eligibility/refund, regeneration and pool caps; those must not be
+invented from effect names.
+
+Server buff stacking priorities, nanoline replacement, cancellation,
+reconnect replay and server-authoritative periodic damage remain separate
+contracts. The recovered minimal building blocks are additive modifiers with
+explicit removal, a distinct temporary base replacement mechanism, timed
+client prediction, and CharacterAction skill locks. Implementing every item
+effect by calling the additive helper would be incorrect.
+
+## Retained evidence
+
+The catalog and gate are in `local/reports/combat-item-effects-inventory.json`.
+`local/reports/combat-client-effect-handler-map.json` maps the 72 observed IDs
+to gate status and targets; TimedEffect has an explicit special-branch note
+rather than being treated as a switch case. The original executor/gate
+are in decompile batch 19 and modifiers in batch 21.
+
+The continuation evidence is in
+`local/reports/combat-client-pass2-decompiles-*.json`:
+
+| Batch | Evidence ID | Relevant coverage |
+| --- | --- | --- |
+| 2 | `ev_b36e6b8b14d9f960dd1705c8d5cd0779c3be3306d575aa456b07008bdb956f40` | Core numeric handlers, TimedEffect totals and SkillTime stub. |
+| 3 | `ev_3c35ce2d6454b2e9f741c25a66383f242d46fbb8029551ab3e61d2121e188deb` | Nano-list handler and item/visual classifications. |
+| 4 | `ev_80beaf091eb5a5d73960b97b09e3dd3afded2f2ee46f14ff090b6de347cb12ed` | Lock getters, setter, expiry and actor callback. |
+| 5 | `ev_74b850319e01a5d695961489586fe30fa511941488693d18d9ceb3bd4ce83148` | Remaining admitted handlers and temporary base-stat map. |
+| 9 | `ev_21b6bf56ea3b01fefafecdb673e392142538e12a995ac4070c4b8a8f1a26f59b` | Common application, queued insertion, feature helpers and empty stubs. |
+| 10 | `ev_1a3cb7e77a4267701716a4ec28b32bf1ad4e1f9c934ef18e59cc10785519c56f` | Skill-lock consumer notification. |
+| 12 | `ev_6c81309872313c894024f13d5290bf165ffea1c85cbbce3ba560840d5824fc13` | Legacy mesh, texture and visual-effect handlers. |
+| 14 | `ev_700456d500ded1b651bc8f770dbe843118f6c6286ca349ae445f40ef86a4e8c5` | Queued effect tick, item descriptors and learned nano-list helpers. |
+
+Generated source for the effect executor is `lifted-0056.c`; continued handlers
+are in `lifted-0057.c`, common application in `lifted-0000.c`, skill locks and
+stat maps in `lifted-0034.c`, and the actor callback/tick in `lifted-0033.c`.
+The level scaling and important time/bit branches were also checked against
+their original instruction comments and constants. This is static evidence;
+live buff/expiry/lock replay has not yet been validated by this investigation.
diff --git a/docs/combat-client-effects.md b/docs/combat-client-effects.md
@@ -0,0 +1,140 @@
+# Item effects and client prediction in 14.9.1
+
+The client has more than weapon animations. It reads item/nano requirements
+and effect definitions, executes selected local effect handlers, maintains
+stat modifiers, and predicts resource recovery. These paths must be separated
+from server-supplied damage outcomes.
+
+This report uses the original engine image and hash identified in the
+[reconstruction index](combat-client-reconstruction.md). Original addresses
+use base `0x10000000`; generated kkr C uses `0x36000000`.
+
+## Shipped data coverage
+
+The matching database catalog contains 83,245 item records (type 1000020) and
+4,366 nano records (1040005). Its index digest was checked against the original
+database before this inventory. Across those definitions there are 223,338
+effect references using 72 distinct function IDs. Three item records retain
+one undecoded trailing zero byte each: 120802, 120827 and 203911. Those bytes
+were preserved, not silently discarded.
+
+`tools/data/extract_items.py` preserves each effect's function ID, header words,
+requirements, tick count, tick interval, target, argument header, typed
+arguments and skipped bytes. Its argument layouts originated in CellAO's
+extractor; successful framing and complete byte coverage do not independently
+prove every argument's meaning or effect behavior. Server execution should
+not be inferred from those layout names alone.
+
+Native `StateParse_t` name registrations in generated `lifted-0048.c` identify
+22 of the 72 observed IDs. Selected examples are:
+
+| Function ID | Native registered name | Data example / boundary |
+| --- | --- | --- |
+| 53002 | Hit | Simple First-Aid Kit 23314 has arguments 27, 10, 12, 0; reading endpoints does not perform the health outcome. |
+| 53012 | Skill | Present in equipment/nano definitions; exact effect flags and argument semantics still matter. |
+| 53019 | Nano | A registered name, not proof of a complete server nano-cast implementation. |
+| 53028 | AddSkill | Separate function identity from Modify. |
+| 53033 | SkillTime | First-Aid Kit 23314 carries three serialized integers, 9, 123, 40. Its local handler is a no-op; actual skill locks use CharacterAction 170. |
+| 53045 | Modify | 160,911 references, including armor stat additions. Local modifier execution is traced below. |
+
+All counts, registration string/assignment addresses, example definitions and
+requirement-operator frequencies are retained in
+`local/reports/combat-item-effects-inventory.json`. The second pass maps all
+47 observed IDs admitted by the tick gate in the
+[handler report](combat-client-effect-handlers.md), with remaining semantic
+gaps identified there. Exact core wire fields are documented in the
+[spell stream report](combat-client-spell-stream.md).
+
+## The local tick gate
+
+`FUN_100be8e0` processes a data-driven effect. It first calls
+`FUN_100bfb40` with the function ID. A rejected ID clears the remaining
+tick count and returns before the effect dispatch. The gate's raw byte table is
+at `0x100bfb70`, covering 182 IDs starting at 53002; its jump table is at
+`0x100bfb64`. The complete native allowlist contains 87 IDs, of which 47 occur
+in this database's 72-ID effect inventory.
+
+Crucially, **Hit 53002 is rejected by this local tick path**, while Modify
+53045 is admitted. Hit definitions can still be read for tooltips:
+`N3Msg_GetDamageString` at `0x10024300` reads negative health-effect endpoints
+in its nano branch. Reading that definition is separate from selecting and
+applying a damage/heal result. Queued weapon results and health messages are
+covered in the [protocol report](combat-client-protocol.md).
+
+The allowed path checks remaining ticks and requirements through
+`FUN_100056e0`, accumulates elapsed time, and dispatches by effect ID once
+the interval is reached. This establishes a local executor and its gate; it
+does not prove that every admitted handler changes a stat, that every effect
+is client-authoritative, or that rejected functions have no other read paths.
+Some dispatch entries invoke a test-argument handler or presentation machinery.
+
+REA batch 19, evidence
+`ev_f28cc89d25d840908ea753e766d4e2d1a718ef5138b04f190e82062755593b1d`,
+contains the complete gate and executor. It is retained in
+`local/reports/combat-client-decompiles-19.json` and the full state evidence
+bundle. Table decoding was checked against the original image bytes.
+
+## Modifier application and removal
+
+The Modify case dispatches through `FUN_100bd4d0` to `FUN_100bd600`. The latter
+requires a SimpleChar target and reads the stat key and adjustment from its
+effect arguments. Effect flag mask `0x1` selects removal rather than addition:
+
+```
+if (effect.flags & 1) == 0:
+ add_modifier(stat, amount) # FUN_10074730
+else:
+ remove_modifier(stat, amount) # FUN_10074b00, final argument zero
+```
+
+The add helper increments the stat's modifier-map value. The removal helper
+subtracts it and erases a zero-valued entry. Removing a health-max modifier
+(stat 1) also clamps current health 27 to the reduced final maximum when its
+third argument is zero. Both helpers invalidate/recompute affected state and
+notify consumers. Concrete dependencies include:
+
+- Stamina/Psychic: mark regeneration interval calculations dirty.
+- AggDef and the three weapon initiatives: update weapon timing when the
+ holder is not idle.
+- Body Development/Nano Pool: mark health/nano foundations dirty.
+- Scale 360: refresh physical/appearance extent through `FUN_1005a790`.
+
+The first observed handler also emits a stat-change notification using the
+old and resulting values. Sending a raw base-stat assignment is therefore
+not equivalent to applying and later removing a temporary modifier.
+
+REA batch 21, evidence
+`ev_27c953512839b1cff0ac854ff041eb3e0813c2df061a8858060432f10da08405`,
+contains the three modifier functions and the criteria evaluator. The selected
+generated instruction bodies are in `lifted-0056.c` and `lifted-0034.c`.
+
+## Criteria and remaining boundaries
+
+Item action and effect requirements use `(stat, value, operator)` triples.
+Eighteen operator values occur in the catalog: 0, 1, 2, 3, 4, 18, 22, 24, 26,
+42, 66, 80, 83, 85, 88, 89, 92 and 93. The
+[requirement report](combat-client-requirements.md) maps every observed value
+to its native branch or explicit rejection, including subject switching,
+getter modes, boolean stack semantics and caller flags. The basic cases are:
+
+| Operator | Recovered operation |
+| --- | --- |
+| 0 | Equality, after checking that the subject supports the stat; getter mode 3. |
+| 1 | The evaluated comparison is strictly less than the raw required value. |
+| 2 | The evaluated comparison is strictly greater than the raw required value; failure text adds 1 to the raw threshold. |
+| 3 | Pop two booleans and push OR. |
+| 4 | Pop two booleans and push AND. |
+
+Boolean stack underflow returns false. There is no implicit AND across leftover
+stack values. Strict comparisons deliberately pass for a nonlocal initial
+subject, and a null initial subject passes the list. Do not copy these client
+visibility shortcuts into server validation, or translate raw operator 2 into
+an unconditional greater-than-or-equal test. Operators 92 and 93 reject the
+entire evaluation in this executable despite appearing in the shipped data.
+
+This pass does not fully recover all 72 observed effect handlers, temporary
+effect stacking/replacement rules, the delegated land-control service, or the
+server's decision to apply an effect. An inventory of definitions is not an
+executable server rules engine. The immediate implementation consequence is to preserve
+base stats, temporary modifiers, active effects and authoritative health as
+distinct state, and replicate coherent effect application/removal to the client.
diff --git a/docs/combat-client-protocol.md b/docs/combat-client-protocol.md
@@ -0,0 +1,282 @@
+# Combat protocol in the 14.9.1 client
+
+This is a static inventory of the selected original client, not a capture of
+the historical Funcom server. It records what the client can send, decode,
+and apply. [Combat rules](combat-rules.md) covers the current reconstruction
+and timing formulas; [starting stats](combat-starting-stats.md) covers health
+and Agg/Def. The [state-machine investigation](combat-client-state-machine.md)
+covers scheduling, weapon selection, reload clocks, and dual wielding.
+
+## Evidence and boundaries
+
+The target is `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Addresses below use its original image base `0x10000000`. Generated C in
+`client/game/kkr.dll/` uses base `0x36000000`; subtract `0x26000000`.
+
+The inventory follows exact class-name references through registration
+factories or request constructors into their vtable stores. Original PE
+vtable slots 2, 6, and 7 identify activation, payload reading, and payload
+writing respectively. The local retained inventory is
+`local/reports/combat-client-protocol-vtables.json`. Export-name discovery
+and all 88 exact ASCII IIR class names are retained in
+`combat-export-inventory.json` and `combat-iir-name-inventory.json` in the
+same directory. Export names alone do not establish behavior.
+
+The numeric keys in the tables are **class-derived IDs**: the class-name XOR
+calculation reproduces the already exercised attack, stop, and Agg/Def IDs.
+Finding a class and its serializer does not establish that its ID appeared
+in a live session. Do not describe the other IDs as captured traffic.
+
+Payloads below exclude the common N3 prefix: big-endian message key, actor
+identity `(u32 type, u32 instance)`, and byte pass-on flag. An `identity` is
+eight bytes. `i32`, `u32`, and byte widths describe serialized values, not
+the size of the containing C++ object. Integer signedness is stated only
+when the receiver uses it. TCP padding is outside the payload.
+
+Coverage is deliberately narrower than a complete combat implementation:
+
+| Area | Wire coverage | Effect coverage |
+| --- | --- | --- |
+| Attack, stop, Agg/Def, generic special | Complete subclass layouts | Target/stop/stat/weapon routing traced; server eligibility policy unresolved. |
+| Nine damage/result families | Complete subclass layouts | Health, ammo, miss, critical, death-reason and feedback effects traced. Other result enum values unresolved. |
+| Reload, equipped-weapon list | Complete subclass layouts | Handler routing traced; clocks detailed in the state-machine document. |
+| Skill, Action, Resurrect, LookAt | Complete subclass layouts | Direct stat assignment / dispatch / no-op traced; individual action and resurrection lifecycle partial. |
+| CharacterAction | Complete envelope layout | Combat branches below traced; the full action enum remains partial. |
+| SpellList, ApplySpells | Container framing, outer layouts and six combat argument layouts complete | Add/remove mode and actual lock notification recovered; other variable effect bodies remain outside the documented subset. |
+
+That is 22 class families: 20 complete subclass layouts, plus two spell-container
+families whose combat encoding subset is detailed in the
+[spell-stream contract](combat-client-spell-stream.md).
+"Complete layout" does not imply historical traffic was observed or that
+all rules behind that message have been reconstructed.
+
+## Request and state surfaces
+
+`C -> S` means a client sender was traced. `S -> C` means a client activation
+handler was inspected; it does not assert that the original server emitted
+the message in a particular situation. A class can support both directions.
+
+| Surface | Class-derived ID | Direction | Payload / coverage |
+| --- | --- | --- | --- |
+| Start attack | `AttackIIR_t`, `0x28494070` | C -> S and S -> C | `identity target`, byte mode. Exact layout and target activation. |
+| Stop attack | `StopFightIIR_t`, `0x4a41203e` | C -> S and S -> C | u32 boolean. Exact layout; stop activation inspected. |
+| Agg/Def | `SetAggDefIIR_t`, `0x76793f0d` | C -> S and S -> C | i32 value, validated -100..100, applied to stat 51. |
+| Secondary special | `CharSecSpecAttackIIR_t`, `0x51492120` | C -> S and S -> C | `identity target`, i32 special StatEnum. Exact layout and WeaponHolder routing. |
+| Character action | `CharacterActionIIR_t`, `0x5e477770` | C -> S and S -> C | i32 action, identity A, identity B. Shared cast, abort, death, parry, and special-feedback envelope. |
+| Target selection | `N3Msg_SelectedTarget`, `0x10023110` | Local path inspected | Updates camera/selected-target state; can call item interactions. It is not itself proof of an attack request. |
+| Assist | `N3Msg_AssistFight`, `0x1002cc30` | Local path inspected | Rejects missing/self/non-fighting target, then selects the assisted character's fighting target. No separate assist packet was found in this path. |
+| Look at | `LookAtIIR_t`, `0x2252445f` | Constructor/reader inspected | identity plus i32 mode validated 0..2; its activation slot resolves to a no-op. This does not establish combat authorization. |
+| Equip / unequip | `N3Msg_MoveItemToInventory`, `0x1002a1f0` | C -> S | Checks wear/unwear locally, prepares inventory move through `0x100425c0`, sends IIR. Full inventory-message layout is outside this combat inventory. |
+| Use / reload | `N3Msg_UseItem`, `0x1002acd0` | C -> S | Includes CharacterAction 106 with null identities. Other branches route item use and inventory moves; branch eligibility belongs to item/equipment state. |
+
+Attack payload reader/writer: `0x10087700` / `0x10087740`; activation
+`0x100876a0` selects the target through the actor's WeaponHolder. Stop reader
+`0x10084330` converts a u32 to boolean; writer `0x10084310` writes a u32.
+Its activation `0x100842f0` calls the stop virtual method with argument 1
+without consulting that decoded boolean.
+Secondary-special reader `0x1007d9f0`, activation `0x1007da30`, and sender
+`N3Msg_SecondarySpecialAttack` at `0x1002c090` establish a generic special
+request. Separate Brawl, Burst, and Full Auto request classes were not found
+among the 88 class-name strings. This bounded search does not prove there
+are no other request paths.
+
+The secondary-special sender checks existing fighting/selected target,
+skill-lock state, available weapons, special availability, and range before
+sending. These checks improve the UI; the server must perform its own
+validation and own the resulting locks and recharge.
+
+The special argument is a skill stat ID, not an action enum. Native skill-name
+initializer `0x10036490` in `lifted-0019.c` establishes:
+
+| Special | Stat ID | Special | Stat ID |
+| --- | --- | --- | --- |
+| Brawling | 142 | Dimach | 144 |
+| Riposte | 143 | Parry | 145 |
+| Sneak Attack | 146 | Fast Attack | 147 |
+| Fling Shot | 150 | Aimed Shot | 151 |
+| Burst | 148 | Full Auto | 167 |
+
+Exact store/string addresses and independent short/long-name matches are
+retained in `local/reports/combat-client-special-stat-names.json`. This mapping
+does not establish that every skill can be requested with every weapon.
+
+The GUI also has distinct state. `ddr.dll!0x10057740` dispatches the attack
+button's action 11; `eer.dll!0x10002e00` obtains a GUI event target before
+calling the engine attack entry. Range-indicator handlers in ddr at
+`0x10063970` / `0x10063980` only toggle a targeting-module byte. A lit range
+indicator is not a server-side range or line-of-sight decision.
+
+`N3Msg_GetDistrictFightMode` at `0x10026ae0` is a local district-resource
+query through `0x100534c0`. It returns -1 without a client character and
+uses numeric fallback 2 when its resource/district lookup fails. This path
+does not recover the server's PvP permission rules, suppression-gas timing,
+NPC hostility, hate list, taunts, or aggro target selection. The visual fight
+states and client line-of-sight checks are described in the state-machine
+document and likewise do not establish authoritative server permission.
+
+## Result messages and their effects
+
+Offsets such as `+0x24` name C++ object fields. They prevent an unknown field
+from acquiring a speculative semantic name. Payload order follows the reader,
+which can differ from object-field order.
+
+| Class / class-derived ID | Serialized payload in order | Activation and coverage |
+| --- | --- | --- |
+| AttackInfo / `0x46002f16` | i32 damage `+24`, i32 ammo `+28`, i32 weapon slot `+20`, target identity `+2c`, i32 death reason `+34`, i32 result `+38` | `0x100aec00` / `0x100aecb0`. Routes hit/result to the actor's weapon holder; missing-actor fallback updates a local target. Exact layout and health/chat effects. |
+| MissedAttackInfo / `0x5c654b28` | i32 ammo `+24`, i32 slot `+20`, identity `+28`, identity `+30` | Reader `0x100b1460`, activation `0x100b14f0` -> `0x1007c050`. Emits miss feedback and delivers zero damage/result 3 through the attack path. |
+| HealthDamage / `0x3710256c` | i32 absolute health `+20`, i32 signed change `+24`, i32 damage type `+28`, i32 death reason `+2c` | `0x100b09c0` / `0x100b0a50`. Sets stat 27 to the supplied absolute value; negative change displays damage, positive change displays healing for the local character. |
+| ReflectAttack / `0x1c3a4f77` | i32 amount `+28`, identity other `+20`, i32 death reason `+2c` | Shared reader `0x100b1ef0`, activation `0x100b1df0`. Subtracts amount from the envelope actor's health and emits reflect feedback. |
+| ShieldAttack / `0x25192476` | Same layout as ReflectAttack | Activation `0x100b1f40`. Subtracts amount from envelope actor's health; separate shield-feedback categories. |
+| Absorb / `0x264e5f61` | i32 absorbed amount `+20`, i32 damage type `+24` | Shared reader `0x100b08d0`, activation `0x100ae990`. Emits absorb feedback; this activation does not subtract health. |
+| FullAuto / `0x5c4a493a` | i32 bullet count `+20`, i32 unresolved `+24` | Shared reader `0x100b08d0`, activation `0x100b0910`. Prints the bullet-count message. This activation does not apply weapon damage. |
+| SpecialAttackInfo / `0x754f1115` | i32 slot `+28`, i32 damage `+2c`, i32 ammo `+30`, target identity `+20`, i32 special StatEnum `+34`, i32 death reason `+38` | `0x100b2c00` / `0x100b2cb0`. Emits named-special feedback, subtracts damage from target health, processes death, updates the selected slot's ammo. |
+| NanoAttack / `0x4727213e` | i32 signed health change `+24`, i32 damage type `+20` | `0x100b1590` / `0x100b1600`. Adds signed change to envelope actor's health; displays its absolute magnitude through nano-hit feedback. Unlike HealthDamage, it carries no absolute health. |
+| Reload / `0x26515e61` | identity `+20`, identity `+28`, i32 `+30`, i32 `+34`, u32 boolean `+38` | `0x10080bf0` / `0x10080ca0` -> `0x1007bca0`. Exact wire widths; weapon/ammo/timer interpretation traced in the state-machine investigation. |
+| SpecialAttackWeapon / `0x1d3c0f1c` | encoded weapon list, five i32 values `+24..+34` | Reader `0x10083f00`. Activation `0x10083fb0` rebuilds available weapon state and applies stats 118,119,120,149,51 (initiatives and Agg/Def). List layout described below. |
+| Skill / `0x3e205660` | i32 count, then count pairs `(i32 stat, i32 value)` | `0x10083d30` -> `0x10008c90`; activation `0x10083d80` assigns each stat. This is not evidence that a plain stat assignment starts a skill-lock countdown. |
+| Action / `0x2049527c` | i32 version **1**, i32 action `+20`, identity argument `+24` | Reader `0x100aea40`; activation `0x100aeaa0` dispatches to the actor/item action handler. Receiver rejects another version. Individual action contracts remain partial. |
+| Resurrect / `0x445f2a0b` | two i32 values `+20,+24` | Reader `0x100b08d0`; activation `0x10080e20` assigns these to stats 27 and 214, then calls `0x10053230`. Full reclaim and resurrection behavior remain unresolved. |
+
+`SpecialAttackWeapon` uses `0x100767d0`: an encoded count of
+`1009 * (count + 1)`, then four i32 values per entry. The reader stores these
+at object offsets `0,4,12,8`, respectively. Weapon-building code consumes the
+endpoint templates, QL, and slot fields; use the state-machine evidence before
+assigning those semantic names to every serialized position.
+
+The result field is not an independently rolled client attack outcome.
+`0x1007a660` queues damage and result; `0x100ab5a0` consumes that queue when
+processing the weapon effect. `0x1001d0b0` appends the critical-hit text when
+the result equals **5**. The miss path supplies **3**, and exercised normal
+hits use **4**. Other result values and the original server's selection
+probabilities remain unresolved. Do not turn these three values into an
+invented complete enum.
+
+Reflect and shield results apply damage to the **envelope actor**, while
+SpecialAttackInfo applies it to its **payload target**. HealthDamage supplies
+an absolute value; NanoAttack supplies a signed delta. Treating these as one
+generic damage packet would change the wrong character or apply damage twice.
+AttackInfo can apply damage through an animation queue; its fallback behavior
+when the attacker is absent is also significant for observer interest.
+
+## Nano actions, interruption, and death
+
+`N3Msg_CastNanoSpell` at `0x10022180` first calls a local nano validation path,
+then constructs CharacterAction **19** with target identity A and nano
+identity B. `N3Msg_TryAbortNanoFormula` at `0x10027e60` reaches
+`0x100667b0`, which sends CharacterAction **108** with null identities when
+its local-character condition holds. A client request is not authoritative
+proof of successful casting, interruption, resource consumption, or effect
+application.
+
+The CharacterAction receiver `0x1007d640` routes to SimpleChar action handler
+`0x1006fa30`. Confirmed combat branches include:
+
+| Action | Client effect | Remaining boundary |
+| --- | --- | --- |
+| 18 | Calls nano success/application path `0x10064bc0` with nano ID from identity B's instance and target A. | Server must select successful effects and authoritative costs. |
+| 20 | Calls nano failure path `0x10064d70`; reason 2 displays insufficient nano energy, reason 6 insufficient level; 3 and 4 suppress this generic failure text. | Other reasons and exact server failure ordering unresolved. |
+| 65 | Calls nano termination/removal path `0x10064ee0` using identity B. It emits termination text, can reduce used NCU stat 180, and removes the effect. | Exact server expiry, dispel and replacement policies remain unresolved. |
+| 77 | Displays parry feedback, with different text for attacker and defender. | Does not establish parry probability or server availability rules. |
+| 80 | Displays Brawl when identity B's type is 142 and Dimach when it is 144. | Presentation feedback is separate from the generic special request and damage result. |
+| 99 | Sets corpse/death presentation, using identity B's instance for animation. | Does not implement corpse rights, reclaim, XP loss, resurrection sickness, or respawn. |
+| 106 / 108 | Outgoing reload / abort requests found in client senders. | Do not echo them as successful completion without tracing the reply/effect contract. |
+| 170 | Starts a skill lock from identity B `(skill ID, raw seconds)`, through `0x10073ae0`. | Duplicate starts do not refresh the lock. The client counts it down separately from weapon and nano timers; server eligibility remains authoritative. |
+
+Death-reason handling `0x10072340` sets health to zero. Its local-character
+messages distinguish 1 self termination, 2 reflected damage, 3 shield damage,
+4 weapon damage, 5 nano damage, 6 falling, and 7 liquid damage. A death reason
+inside a damage result and CharacterAction 99's presentation are distinct
+effects.
+
+Two further classes carry persistent spell/effect state:
+
+| Class / class-derived ID | Recovered contract | Coverage |
+| --- | --- | --- |
+| SpellList / `0x4d450114` | Reader `0x100c3350` allocates a spell container, decodes through `0x100bd000`; activation `0x100c33f0` applies it to the actor's stat/effect holder in addition mode. | Six combat argument layouts and an exact Modify plus SkillTime payload are documented in the spell-stream contract. |
+| ApplySpells / `0x342c1d1d` | Reader `0x10156b40` decodes spell container, identity, and one-byte boolean; activation `0x10156ae0` looks up its payload identity and applies the container. Wire byte 1 adds; 0 removes. | Same documented combat argument subset; other variable bodies remain unreviewed. |
+
+The common spell-container decoder `0x100bd000` requires a positive i32
+divisible by 1009 and obtains `count = value / 1009 - 1`, with count below
+1000. Each entry begins with an identity, followed by a variable effect body
+decoded by `0x100b9530`. That decoder contains a large effect-kind dispatch;
+the outer count and identity must not be mistaken for the full per-effect
+layout. Invalid container framing marks the stream bad. The
+[spell-stream contract](combat-client-spell-stream.md) now specifies common
+headers, requirements, native reader/writer branches and the six relevant
+argument layouts. SkillTime decoding is distinct from actual CharacterAction
+170 lock creation.
+
+Nano success action 18 calls `0x10064bc0`, which resolves the nano template
+and target and routes execution through `0x100650f0` in mode 1. Failure
+action 20 calls `0x10064d70`, which routes the same template path in mode 3.
+Action 65's `0x10064ee0` is termination, not a cast-start notification.
+
+## Server responsibility contract
+
+The client owns target selection UI, tentative eligibility feedback, weapon
+animation, local timers, effect presentation, and interpretation of received
+state. These are useful compatibility obligations, not trusted combat results.
+The server must own:
+
+1. Current actor/target identities, visibility, life state, zone, attack
+ eligibility, range and line of sight, fighting target, and session lifetime.
+2. Weapon and special selection, authoritative attack/recharge and skill/action
+ locks, ammo, reload completion, equipment transitions, and cancellation.
+3. Hit/miss/critical/parry outcomes, damage type, defenses, armor, absorbs,
+ reflect and shields, resource changes, and exactly one authoritative health
+ change for each result.
+4. Nano validation, costs, execution and recharge, interruptions and abort
+ outcomes, effect durations, stacking, removal, and replication to observers.
+5. Death and corpse lifecycle, opponent cancellation, ownership, reclaim,
+ resurrection and respawn. Presentation packets alone do not supply these.
+
+Send participant spawns before fighting/results, preserve packet order within
+a connection, and replay current state for a late observer. Replaying historical
+damage or replaying a subtractive result after an absolute-health update can
+corrupt client health. Preserve the difference between current-health state
+and one-time combat effects.
+
+## Retained evidence and remaining work
+
+The earlier portable bundle `local/reports/combat-1491-evidence.json` contains
+exact attack, hit, health, death, and CharacterAction decoding. In particular:
+
+- `ev_8687fd6e603c302e4ab3fee7b405ea3e5c9a615e0f56bff18dd20ff949da8d4c`:
+ AttackInfo, HealthDamage, attack effect routing, character update.
+- `ev_991bfd8cce8e805d213a8eacd30750d0ec75ec71d96721a722e4ea4eff928c7a`:
+ CharacterAction and SimpleChar action switch.
+- `ev_eb20a4ca58374e72da2f8326ccfd51f83f77758fcff01da9626fa192429b926d`:
+ attack target activation, damage application, death reasons, critical text.
+
+New REA batches retained as `local/reports/combat-client-decompiles-*.json`:
+
+- Batch 7,
+ `ev_065aec48e84d7bcfd376705ec06f50ef9f1ffd1b50711ff79c65ede2a927eec6`:
+ miss, reflect, shield, absorb, Full Auto, special result, nano delta, reload,
+ weapon-list and action readers/activations.
+- Batch 12,
+ `ev_a063bfcb51a54d2dc54c5b4be9e190258148e173c7fd0217122b8b417527af80`:
+ common two-int reader, miss effects, ammo update, fight-result lookup,
+ CharacterAction abort, spell-list reader, and generic special activation.
+- Batch 14,
+ `ev_9b6945a8f0e6e5dbb13ee803a3d432352ef04c48d131fc12032c7c52941d74ef`:
+ ApplySpells/Skill readers, Skill activation, cast/special/assist/selected-target
+ and equipment-move senders.
+- Batch 19,
+ `ev_f28cc89d25d840908ea753e766d4e2d1a718ef5138b04f190e82062755593b1d`:
+ spell-container framing, counted stat pairs, nano success, failure, and
+ termination helpers.
+
+Ghidra did not resolve procedures at `0x10083fb0`, `0x100aeaa0`,
+`0x100842f0`, `0x100c33f0`, or `0x10156ae0` in these batches. Their generated
+C boundaries and original-instruction comments were inspected directly
+(`lifted-0038.c`, `lifted-0051.c`, `lifted-0057.c`, `lifted-0099.c`). This
+is a stated decompiler limitation, not absence of their handlers.
+
+This pass does not exhaust InventoryUpdate/InventoryUpdated, full nested
+spell effects, every CharacterAction code, combat feedback/error codes, or
+every inventory use branch. It does not recover unavailable server hit rolls,
+NPC combat profiles, taunt/hate selection, PvP eligibility, or progression.
+Those gaps remain explicit implementation work, even where a compatible
+client-facing message shape is now known.
diff --git a/docs/combat-client-reconstruction.md b/docs/combat-client-reconstruction.md
@@ -0,0 +1,215 @@
+# Reconstructing combat from the 14.9.1 client
+
+This investigation targets the original pre-Shadowlands 14.9.1 client. Its
+purpose is to recover the client/server combat contract and distinguish rules
+the client calculates from decisions it receives. Matching a client timer is
+not proof of the original server's scheduler or random rolls.
+
+## Sources and search boundary
+
+The primary engine image is `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Original addresses use image base `0x10000000`; generated C uses `0x36000000`.
+The matching `eer.dll` interface and `ddr.dll` GUI are additional entry-point
+evidence. Generated code is disassembly-derived, not original Funcom source;
+REA decompilation and assembly checks establish the important arithmetic and
+branches independently.
+
+The retained discovery files are:
+
+- `local/reports/combat-export-inventory.json`: matching-hash export inventory
+ across the shipped modules, including all N3Msg exports. There are 303 engine
+ and 231 interface export-name candidates. Names alone do not establish behavior.
+- `local/reports/combat-iir-name-inventory.json`: all 88 exact ASCII IIR class
+ names found in the engine, with original addresses and file offsets.
+ Name-derived hashes remain candidates until constructor/serializer/registration
+ traces establish them; a class name alone does not prove a live message.
+- `local/reports/combat-1491-evidence.json`: initial packet and presentation
+ evidence, including attack, damage, stat, stop and death handling.
+- `local/reports/combat-rules-1491-evidence.json`: item interpolation, timing,
+ starting stats and physical-range evidence.
+- `local/reports/combat-client-state-evidence.json`: 148 evidence records from
+ the expanded state, numeric and protocol investigation. Its reusable snapshot
+ is `local/reports/combat-client-state-1491.snapshot.json`; REA was closed.
+- `local/reports/combat-item-effects-inventory.json`: all 72 observed item/nano
+ function IDs, usage counts, native name-registration candidates and local
+ effect-tick gate membership.
+- `local/reports/combat-client-requirements-evidence.json`: 171 second-pass
+ evidence records covering requirements, effect handlers, spell streams and
+ skill locks. The matching `combat-client-requirements-1491.snapshot.json`
+ preserves 37 workflows. The REA target was closed after export.
+- `local/reports/combat-client-requirement-inventory.json`: 305,917 requirement
+ references across action/effect lists, using 18 distinct operators.
+
+Period player experiments are supplementary evidence, especially for rules
+the client does not calculate. Later CellAO behavior is a useful comparison,
+but does not override conflicting shipped-client evidence or establish a
+14.9.1 server formula.
+
+## Investigation checklist
+
+The detailed reports maintain exact symbols, pseudocode, evidence and remaining
+unknowns for each area:
+
+| Area | Questions | Detailed report |
+| --- | --- | --- |
+| Attack controller | Start/stop, phase transitions, queued results, interrupts, multiple weapons, target changes | [State machine](combat-client-state-machine.md) |
+| Spatial checks | Item range, physical extents, target availability, playfield and line of sight | [State machine](combat-client-state-machine.md) |
+| Numeric rules | Initiative/AggDef, item interpolation, attack/defense weights, overequipping, health/nano and regeneration | [Stats and items](combat-client-stats.md) |
+| Results | Normal hits, criticals, misses, reflects, shields, absorbs, full auto, health changes and death | [Protocol](combat-client-protocol.md) |
+| Specials and nanos | Requests, client eligibility, skill codes, locks, cast/recharge/cancel and result channels | [Protocol](combat-client-protocol.md), [stats](combat-client-stats.md) |
+| Data and creation defaults | Base skills, trickle, breed/profession/title data and the fixture's limitations | [Starting stats](combat-starting-stats.md) |
+| Effects | Client prediction versus server results; all 47 observed locally admitted IDs and 25 rejected IDs | [Overview](combat-client-effects.md), [handler map](combat-client-effect-handlers.md) |
+| Requirements | All 18 observed operators, subject context, getter modes and client-only shortcuts | [Requirement interpreter](combat-client-requirements.md) |
+| Effect replication | SpellList/ApplySpells envelopes, six typed effect bodies, add/remove direction and actual skill locks | [Spell streams](combat-client-spell-stream.md) |
+| Current server | Implemented behavior versus recovered rules and unresolved authority | Coverage ledger below |
+| Resource synchronization and editable stats | Persistent base stats, derived resources, posture, recovery and safe correction timing | [Regeneration implementation](combat-regeneration.md) |
+| Creature balance research | Local wiki search, shipped Leet Bite endpoints and historical HP gaps | [NPC balance evidence](combat-npc-balance.md) |
+
+## Current server coverage
+
+| Rule or behavior | Evidence status | Current server |
+| --- | --- | --- |
+| Attack, stop and basic hit layouts | Native reader/writer/activation plus runtime | Implemented and covered by native-wire tests |
+| Health/death presentation and ordering | Native handlers plus browser encounters | Implemented for basic PvE; reload revival remains local |
+| Weapon initiative/AggDef formulas | Exact native arithmetic and integer conversion | QL 1 fists, editable Physical Initiative and ability trickle; 250 ms resolution tick |
+| AggDef request and stat update | Native request/serializer plus real slider request | Implemented; scheduled swing keeps its deadline |
+| QL 1 fist damage endpoints | Shipped item record | Normal uniform 3-5 roll; distribution and always-hit policy are local |
+| Player max/current health and nano | Native formula, breed/title resources, browser 37/37 | Derived from editable abilities and base Body Development/Nano Pool; Soldier profession |
+| Martial Arts selecting fist QL | Period observation; exact native selector not found | Fixed QL 1, not a recovered MA-to-QL selection rule |
+| NPC health, damage and weapons | Historical per-species profiles unresolved | Local 100 HP, 5 damage, 1s/1s phases |
+| Armor, evade/critical rolls and damage modifiers | Client data/handlers do not alone establish authoritative calculation | Not implemented |
+| Range and physical extents | Native formula recovered; instance extent construction needs full reconciliation | Four-meter center-distance approximation |
+| Line of sight | Client checks cannot establish original server validation | Not implemented on the server |
+| Dual wield, ammunition/reload, specials and nanos | Scheduling, core effect streams and skill-lock contract recovered; full effect semantics remain partial | Not implemented |
+| Resource regeneration | Native prediction formulas and injured-client probes | Authoritative player recovery; absolute quiet corrections reconcile prediction |
+| XP, loot, reclaim and respawn | Separate rules and state required | Not implemented |
+
+## Implementation order and acceptance checks
+
+The recovered boundary is:
+
+```mermaid
+flowchart LR
+ A[Client action request] --> B[Server validation]
+ B --> C[Authoritative action clock]
+ C --> D[Server outcome and health]
+ D --> E[Ordered result messages]
+ E --> F[Client result queue]
+ F --> G[Animation keyframe and displayed health]
+ H[Item and stat data] --> C
+ H --> I[Client timers and prediction]
+```
+
+Client timers and prediction are compatibility requirements. They do not
+authorize the request or produce the server outcome. The next implementation
+steps should follow this order:
+
+1. **Stat and weapon foundations.** Use the shipped endpoint/QL records,
+ base skills, ability trickle, rating weights and temporary modifiers.
+ Editable base abilities and four combat skills now feed timing and resources;
+ keep the Soldier profession and missing IP progression explicit. Verify with native item endpoints, interpolation
+ boundaries, separate weighted-term truncation and modifier removal/clamping.
+2. **One action controller per actor.** Represent attack/recharge and the
+ coordination between weapons, nanos, item use and reload. Multiple weapons
+ share attack scheduling; simply giving each weapon an independent repeating
+ timer would contradict the client controller. Verify phase ordering,
+ stop/restart, weapon swaps, interruption and late ticks. Keep client startup
+ randomness separate from the unresolved original-server first-hit policy.
+3. **Resource/effect state.** Maintain authoritative health/nano, active effects,
+ modifier addition/removal, expiration and regeneration. Match the recovered
+ prediction where validated and replicate absolute corrections coherently.
+ Verify injured idle and fighting actors, odd interval phase, sitting/rest
+ behavior, expiry and lowered maximums; do not apply player formulas to NPCs.
+4. **Outcome resolution.** Add the correct miss/critical/special/type channels,
+ then armor, absorb, reflect and shields once their arithmetic/order has
+ evidence. The client supplies result interpretation, not a recovered hit-
+ chance or full damage equation. Period research and any original-server
+ captures are needed for those gaps; do not label an emulator formula proven.
+5. **Full replication and lifecycle.** Exercise every result's actor/target and
+ absolute-versus-delta semantics in the real client, including absent actors,
+ late observers, transport resume, death and resurrection. Full Auto's bullet
+ count and absorb feedback do not independently apply health damage.
+
+The current prototype remains intentionally limited while this contract is
+used to guide changes. This report is a broad source-backed pass, not a claim
+that every effect handler, criteria context, inventory transaction, combat
+feedback code or historical server rule has been completely recovered. Each
+specialist report identifies the concrete remaining searches and limitations.
+
+## Validation already retained
+
+The maintained Go packages pass. The full `go test -race ./server/...` run
+passed (server 441.553 seconds, gamedata 106.782 seconds). Additional focused
+race checks cover duplicate cookies, replaced-session movement/posture/loading,
+and actual socket write timeouts. There are now 63 combat, stat, regeneration
+and output tests. These include simultaneous attackers, one killing blow,
+target changes, recharge preservation, stale sessions, zoning, disconnects,
+late observers, malformed slider requests, and breed/title health boundaries.
+After manual teleports were brought under the same snapshot/commit lock, the
+maintained suite passed again (server 68.688 seconds), and focused profile,
+stat-persistence and automatic/manual zoning race checks passed in 111.453
+seconds.
+
+Lifecycle and queue stress passed 25 runs under the race detector, including
+10,000 packets from concurrent producers. Every live world and chat connection
+uses the same bounded FIFO writer, so socket writes do not hold shared locks. Queue
+overflow, write timeout and short write disconnect the affected recipient.
+State changes and packet enqueue batches share one update lock, with candidate
+profile saves and old-playfield fight cancellation before character replacement.
+The [resource design](combat-regeneration.md#state-and-delivery-ordering)
+documents lock order, session ownership, join ordering and shutdown behavior.
+The shared world/chat writer and asynchronous disconnect checks pass with the
+maintained suite (server 68.185 seconds) and focused race checks (105.120
+seconds). Three isolation regressions passed 100 repetitions each: unread
+vicinity recipient, unread Global recipient with subsequent sender request,
+and replacement while the old transport's Close operation is blocked.
+
+Browser checks use the published Chromium/WASM client in isolated fixtures:
+native Q/Tab, punches/kicks, weapon text, health bars, corpse/death presentation,
+and the aggression slider. One two-client run had the second player join an
+injured NPC, reconnect both browser transports, continue attacking and kill
+the NPC after the first player's death. No page errors were observed. That
+run used the earlier 100-HP player fixture; it is transport/ordering evidence,
+not validation of the final health formula.
+
+A separate run verified the corrected 37/37 player display, native attack
+rating 7, and slider value +71 reaching server state and changing cadence.
+It stopped with server player health 7 and NPC health 3; client health changes
+remain delayed until the queued weapon animation resolves. Local screenshots,
+packet captures and summaries are under `local/combat-smoke/`, notably
+`health-before-fix.png`, `multi-health-fixed.png`,
+`multi-native-canonical-health-fight.png`, `multiclient-first-summary.json` and
+`multiclient-summary.json`. Test clients and temporary servers were closed.
+
+These checks establish the described behavior in the tested fixtures. They
+do not establish historical NPC balance, original server RNG, outdoor collision
+validation, or complete combat-system correctness.
+
+An additional idle-client probe initialized player health to 20/37, put the NPC
+outside melee range, and made no attacks. Screenshots separated by roughly
+30 seconds showed client health 20, 20, 23, 23 and nano 3, 6, 9, 12, while the
+server remained at 20 HP throughout. This corroborates local resource
+prediction and demonstrates current server/client drift without authoritative
+regeneration in that earlier implementation. It does not independently establish the exact initial counter
+phase or original server cadence. The retained images are
+`local/combat-smoke/injured-regeneration-sequence.png` and
+`multi-injured-regen-{0,30,60,90}.png`, with
+`injured-regeneration-events.json`. The browser/server were closed afterward.
+
+The recovered spell stream was also exercised directly. An exact 88-byte
+SpellList container added 5 to Martial Arts; the native skill panel changed
+from 7 to 12. The matching ApplySpells removal restored 7. Two add/remove rounds
+were captured without page errors. This validates the tested modifier stream,
+while the stats summary's attack rating remained 7 and needs a separate
+refresh/binding investigation. Captures and screenshots are retained as
+`local/combat-smoke/effect-modifier-{events,summary}.json` and
+`multi-effect-probe-body-{before,add,removed}.png`. Test resources were closed.
+
+Authoritative regeneration and editable stats are now implemented. A default
+idle probe ended with server and client both at 26/37 HP and 12/35 nano. An
+edited profile verified effective skills and 658/380 resource maximums, then
+standing/sitting recovery and a sustained fight. Combat accounting included
+310 incoming damage and 5 recovered HP. After walking out of melee range,
+both sides matched at 122/658 HP and 42/380 nano, with zero page errors. See
+[regeneration verification](combat-regeneration.md) for captures and limits.
diff --git a/docs/combat-client-requirements.md b/docs/combat-client-requirements.md
@@ -0,0 +1,233 @@
+# 14.9.1 client requirement evaluation
+
+The shipped client has a postfix requirement interpreter. Its result controls
+local item actions, equipment checks and predicted item/nano effects. It is
+not sufficient as authoritative server validation: strict skill comparisons
+deliberately pass when the initial subject is not the local player, a null
+initial subject passes the entire list, and some shipped database operators
+are unsupported by this executable.
+
+## Evidence and coverage
+
+Target: `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Addresses here are original VAs based at `0x10000000`; generated C in
+`client/game/kkr.dll/` is relocated by `+0x26000000`.
+
+The principal evidence is evaluator `0x100056e0`, retained as
+`local/reports/combat-client-criteria.txt` and instruction-for-instruction
+`local/reports/combat-client-criteria.asm`. The assembly evidence ID is
+`ev_766b14bab9ca66a483cc487e7daa79d93f1790c34718cedc6ad768caac1acc3d`.
+Related native queries are retained in
+`local/reports/combat-client-pass2-decompiles-1.json` through `-15.json`.
+The second-pass bundle is `local/reports/combat-client-requirements-evidence.json`.
+
+The matched database inventory contains 305917 requirement references and
+18 distinct operator values. Counts below are references across action and
+function lists, including separate item/QL records, rather than distinct
+game rules. Reproducible counts and full example lists are retained in
+`local/reports/combat-client-requirement-inventory.json`.
+
+| Coverage question | Result |
+| --- | --- |
+| All 18 observed opcode values | Every value mapped to an exact native branch or explicit rejection |
+| Basic comparisons, boolean stack and getter modes | Recovered, including strict boundaries and local-player bypass |
+| Subject switching and missing subject | Recovered for observed selectors 2/3 |
+| Item placement and falling checks | Recovered integer predicates |
+| Packed pet-count comparison | Recovered bit extraction and signed threshold encoding |
+| Tower predicates 80/83 | Exact delegation and return test recovered; concrete derived land-control service implementation remains outside this bounded pass |
+| Caller flags and effect execution gate | Recovered for normal wear/use/effect callers; unusual comparison rewrite flag documented separately |
+| Original server validation | Unavailable from the client |
+
+## Record layout and call contract
+
+Criterion reader `0x10008150` reads three stream `int32` values in order:
+stat/operand, value, operator. There is no operator translation in this
+reader. A criterion payload is therefore 12 bytes. A native linked-list
+node has next/previous links at `+0/+4`, then those three values at
+`+8/+0xc/+0x10`. The containing list has a sentinel at `list+4` and count
+at `list+8`; `0x100056e0` receives a pointer to the list pointer.
+
+The wrapper `0x10005680` uses a criteria object's list at `this+4` and
+forwards an initial Beholder/stat interface, a diagnostic flag, and a
+comparison-rewrite flag. Its copied two-word identity context is not an
+extra boolean operand. `0x100056c0` copies those two identity words without
+transforming requirement records.
+
+The evaluator creates an empty local byte stack. It initializes current
+subject to the supplied interface and determines a separate
+`initial_is_local_character` byte once: initial subject must cast to
+`SimpleChar`, must not cast to `SimpleItem`, and character `+0x128` must be
+nonzero. Switching the current subject does not recompute this byte.
+
+The stat getter is interface vtable `+4`; presence test is vtable `+0x10`.
+Keep getter modes numeric when implementing or comparing these rules:
+mode 0 is the effective-skill path in the recovered skill code, mode 2
+reads stored/base values in focused paths, and mode 3 includes final
+stat-specific computations. These labels are not proven universal for
+every stat. [combat-client-stats.md](combat-client-stats.md) gives the
+recovered stat-specific formulas.
+
+## Observed opcode table
+
+Names for 0..4,18,22,24,26 are first-party strings registered by
+`0x10039cf0` and returned by `fOperatorToString`, `0x1003dd90`. Other
+descriptions below name the recovered behavior, rather than importing a
+later emulator's enum.
+
+| Opcode | References | Exact observed behavior |
+| --- | ---: | --- |
+| 0 Equal | 15973 | Push false if current subject lacks stat; otherwise push `get(stat,3) == value`. |
+| 1 Less | 355 | If initial subject was the local character, push signed `get(stat,0) < value`; otherwise push true. |
+| 2 Larger | 170679 | If initial subject was the local character, push signed `get(stat,0) > value`; otherwise push true. A requirement value 7 therefore needs at least 8. |
+| 3 Or | 139 | Pop two boolean bytes, push their logical OR; fewer than two fails the entire evaluation. |
+| 4 And | 117200 | Pop two boolean bytes, push their logical AND; fewer than two fails the entire evaluation. |
+| 18 OnTarget | 270 | Replace current subject with selector 3 of the original initial interface. Missing result fails entire evaluation. No boolean is pushed. |
+| 22 BitAnd | 347 | Push `(get(stat,2) & value) != 0`, testing any common bit rather than requiring all bits of the mask. |
+| 24 Unequal | 378 | Push false if stat is absent; otherwise push `get(stat,2) != value`. |
+| 26 OnUser | 14 | Replace current subject with selector 2 of original initial interface. Missing result fails entire evaluation. No boolean is pushed. |
+| 42 logical NOT | 133 | Invert top boolean byte in place; empty stack fails entire evaluation. |
+| 66 packed pet count | 229 | Read stat 251 in mode 2. Let `a=abs(value)`, `index=(a/1000)&7`, `limit=a%1000`, `count=(stat251>>(4*index))&15`. Push `count < limit` when value is nonnegative; push `count >= limit` when negative. Stat operand is unused. |
+| 80 tower placement eligibility | 118 | Obtain user via selector 2, cast to character, obtain identity at its ATR helper `+0xe4/+0xe8`, resolve item, call item placement validation `0x10058520`; push true iff returned error mask is zero. Missing item pushes false. See delegation below. |
+| 83 defense shield check | 3 | Resolve the same ATR identity for the current cached character; push whether an item resolves. Separately invoke land-control service vtable `+0x10` for a result and `+8` to format it. That result does not replace the pushed existence boolean. |
+| 85 same target stat | 5 | Cast current subject to character, obtain target identity from its interaction helper `0x10072000` at `+0x70`, resolve target Beholder; push whether `target.get(stat,2) == character.get(stat,2)`. Missing character/target pushes false. `value` is unused. |
+| 88 item placement class | 20 | For cached character, use ATR helper `+0x150`; `0x100635a0(value,stat)` tests identity type at helper `+0xe4`. True if `(value&1 && type in {101,102,103}) || (value&2 && type==104) || (value&4 && signed(type)>250)`. The second parameter is unused. Missing character pushes false. |
+| 89 falling | 24 | Cast current subject to character; push its vehicle's `IsFalling()` result, or false if no character. Falling also queues the "can't do this while falling" diagnostic. Lists that forbid falling explicitly follow with opcode 42. |
+| 92 | 1 | Unsigned operator exceeds 89: fail entire evaluation immediately. Intended server meaning unknown. |
+| 93 | 29 | Same immediate rejection as 92. Intended server meaning unknown. |
+
+The exact opcode-to-branch index is a compressed byte table at
+`0x10007ffc`, followed by the jump table at `0x10007f10`. The bound check
+is `CMP opcode,0x59; JA failure` at `0x10005835`. In particular, 42 maps
+to decompiler case `0x23`, 66 to `0x2b`, and 80 to `0x33`: decompiler
+case numbers are not database operator IDs. Raw table evidence:
+`ev_7c9145dc05f2a6dd3ea769a7df32d9fcd9f2140b7fc1b87a17d84863fe6e2fd6`.
+
+The pet-count index extraction is unsigned after the absolute-value
+arithmetic. Valid observed data uses ordinary positive/negative small
+values; this does not establish desirable behavior for malformed `INT_MIN`.
+
+## Subject and context resolution
+
+`0x10002e60` resolves selectors relative to the original initial interface,
+not the current switched subject. First-party names distinguish OnTarget
+(18 -> selector 3) and OnUser (26 -> selector 2):
+
+| Initial object | Selector 2 | Selector 3 |
+| --- | --- | --- |
+| SimpleItem | Resolve identity at Beholder `+0x24/+0x28` using `0x10002750` | Null |
+| SimpleChar | Same interface-relative user identity lookup | NPC: identity at Beholder `+0x2c/+0x30` via `0x100027b0`; player: identity at interaction helper `+0x70/+0x74` |
+
+For either selector the candidate must also cast to a dynel, share the
+initial object's playfield, and have dynel byte `+0x94 != 1`; otherwise
+resolution returns null. Initial playfield is item `+0x104` or character
+`+0x78`. The routine accepts selectors 1..22 as input but only concrete
+1..4 branches exist for a character and 1..2 for an item. Selector 1
+returns the initial interface; selector 4 resolves an item using stats
+82/83 in mode 2. These extra selectors are documented to explain the
+resolver, not included in the observed-opcode coverage count.
+
+The cached character used by some advanced predicates starts as the
+initial character, and certain character-casting branches overwrite it.
+It is not a fresh dynamic cast for every predicate; opcode 88 uses the
+cached character while opcode 89 explicitly casts current subject again.
+Do not silently substitute the original player in all advanced branches.
+
+Tower predicates delegate to the service returned by `0x10157b10`, global
+`0x1030db44`. Its base constructor `0x10157ad0` installs vtable
+`0x10178d64`; derived service behavior must be established before claiming
+complete tower validation. `0x10058520` builds an item description from
+stats 701,702,703 (mode 2), replacing zero high template with low template,
+then calls service vtable `+0xc` with the character pointer from interaction
+helper `+0x10` and that item description. The
+returned error mask is what opcode 80 tests. Formatting paths include
+land-control, organization, tower spacing and shield error messages;
+strings alone do not recover those rules. Opcode 83's database examples
+are the Emergency Defense Shield Neutralizer and its test item.
+
+## Evaluation order and final result
+
+For the observed operators with the rewrite flag false, the central
+algorithm is:
+
+```text
+if initial subject is null: return true
+current = initial
+stack = []
+initial_is_local_character = classify(initial)
+
+for criterion in stored order:
+ if unsigned(criterion.operator) > 89: return false
+ if predicate: append its result as specified above
+ if AND/OR: require two entries, reduce them to one
+ if NOT: require one entry, invert it
+ if OnTarget/OnUser: replace current; fail if missing
+
+if stack is empty: return true
+result = pop top
+if stack is not empty: discard extras and produce diagnostic list
+return result
+```
+
+There is no implicit AND across leftover stack entries. Native helper
+`0x100080c0` tests count==0, `0x10008110` peeks, `0x10008100` pops,
+`0x100080d0` clears, and `0x100080e0` pushes. At `0x10007c62..0x10007c94`
+the function preserves the top byte before discarding extras and printing
+the criteria list. Malformed postfix lists therefore have observable
+behavior that differs from an all-requirements conjunction.
+
+There is no boolean short circuit: every list node is visited until an
+explicit fatal condition. False predicates can therefore still be
+followed by context switches or diagnostics. An empty list, or a list
+containing only successful context switches, returns true.
+
+Example: Basic Nano Recharger 25820 requires Treatment >7, TimeSpace >7,
+then AND; it tests a movement mask and combines that result, switches
+OnTarget, checks target posture and a zero-valued stat, and combines those
+results explicitly. Symbio-Graft: Detain Suspect 93655 uses 89,42,4 to
+require not falling in addition to its skill/profession checks.
+
+## Caller flags and local prediction limits
+
+Normal wear/unwear/item action callers `0x10090970`, `0x10090b70`,
+`0x10090c70`, `0x10090d10`, `0x10090fe0` and `0x100ace70` pass rewrite
+flag zero. Their criteria lists come from item action records (for
+example action 6 wear,7 unwear,3 use). Passing character `+0xe4` supplies
+its stat-interface subobject. Callers skip evaluation when their action
+or list is absent; other item flags and wear restrictions are checked
+outside the interpreter.
+
+Predicted spell executor `0x100be8e0` first checks client-effect allowlist
+`0x100bfb40`, then evaluates the effect's criteria with diagnostic and
+rewrite flags both zero. A false result decrements remaining ticks and
+returns without applying that tick. Thus an unsupported operator in a
+client-admitted Modify effect can suppress local prediction. The original
+server may understand a broader operator set; client rejection does not
+prove that an intended original-server effect never happens.
+
+The nonzero rewrite flag has an unusual verified implementation. For
+operators 0,1,2,24 and stat in {367,4,368,60,33}, it loads local registers
+with stat54/current level and forces dispatch opcode 0 at
+`0x100057fa..0x10005833`. However, the equality branch at
+`0x100058d3..0x1000590e` reloads the original node's stat and value. It
+therefore changes dispatch to the original equality predicate rather
+than reliably bypassing those restrictions. The original list is not
+mutated. Do not label this flag "ignore profession/side requirements"
+without accounting for that assembly behavior. `0x1008fc40` forwards an
+external flag here; the normal callers and predicted-effect path above
+use zero.
+
+The two unsupported database cases are concrete:
+
+- Operator92 occurs on item215391,
+ `RINGEVENT_AnunBloodreaverInvasion_containernano`, action3, value565,
+ followed by NOT and AND.
+- Operator93 occurs29 times, including Radiation AC Cluster - Faded
+ (Right-Arm)101371, in a Modify53045 requirement with value149; Bright
+ (Left-Arm)101372 combines values145 and146 with NOT/AND.
+
+These records must remain explicitly unresolved for server behavior.
+Do not reinterpret 92/93 as a later enum merely because the data contains
+them. Full original-server correctness additionally needs authoritative
+subject ownership, inventory state, skill locks, range/LOS and action
+permissions; the client supplies only the local paths described here.
diff --git a/docs/combat-client-spell-stream.md b/docs/combat-client-spell-stream.md
@@ -0,0 +1,293 @@
+# Combat spell streams in 14.9.1
+
+This closes the nested wire-layout gap for the combat effects below inside
+`SpellListIIR_t` and `ApplySpellsIIR_t`. It also distinguishes those effects
+from the actual skill-lock notification. The selected original kkr.dll is
+SHA-256 `a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Addresses use original base `0x10000000`; generated C uses `0x36000000`.
+
+Both the native reader and writer were inspected. This is a network stream
+contract: integers below are **big endian**. The item database's little-endian
+storage and an extractor's `4x` labels must not be copied into a network
+encoder. Several apparently unused database words are explicitly read and
+written as fields by this client.
+
+## The two envelopes
+
+These layouts exclude the common N3 prefix and TCP padding, described in the
+[protocol inventory](combat-client-protocol.md).
+
+```text
+SpellListIIR_t, class-derived ID 0x4d450114:
+ spell_container
+
+ApplySpellsIIR_t, class-derived ID 0x342c1d1d:
+ spell_container
+ u32 target_identity_type
+ u32 target_identity_instance
+ u8 add_mode
+```
+
+SpellList applies its container to the envelope actor, with addition mode.
+ApplySpells resolves the appended target identity and uses byte **1 to add**
+and byte **0 to remove**. The reader normalizes any nonzero byte to true;
+an encoder should send 0 or 1. Its activation inverts that boolean before
+calling the common application method.
+
+This direction is established by `0x10002370`: its third argument sets
+effect-object flag bit 0 when nonzero (removal), and clears it when zero
+(addition). Modify's executor then adds or subtracts the amount according to
+that flag. The application mode is not an extra DWORD inside each effect.
+
+Envelope readers/writers are `0x100c3350` / `0x100c33d0` for SpellList and
+`0x10156b40` / `0x10156b90` for ApplySpells. Common list reader/writer are
+`0x100bd000` / `0x100bcf40`.
+
+## Container and effect header
+
+```text
+spell_container:
+ i32 encoded_count # 1009 * (number_of_effects + 1)
+ repeat number_of_effects:
+ u32 function_kind # e.g. 53045 Modify
+ u32 function_instance # preserved by constructor; 0 in the example
+ effect_body
+
+effect_body:
+ i32 version # must be 4
+ i32 requirement_count
+ repeat requirement_count:
+ i32 stat
+ i32 value
+ i32 operator
+ i32 tick_count # internal field 3
+ i32 tick_interval # internal field 4
+ i32 target_selector # internal field 32
+ i32 argument_header # internal field 35
+ function-specific arguments
+```
+
+The list reader accepts a positive encoded count divisible by 1009 and a
+decoded count below 1000: 1009 is an empty container; 2018 is one effect;
+3027 is two effects; the largest admitted count is 999 effects. This count
+is not the number of DWORDs or the payload length.
+
+`0x100b44b0` stores the two identity words on the effect object and constructs
+its field/requirement storage. They identify the function; they are not the
+caster's character identity. Native resources use instance 0 in the examples
+below. Preserve a received/source instance rather than inventing an actor ID.
+
+Effect reader/writer `0x100b9530` / `0x100b7d80` both use version **4**.
+Original constant `0x101c8d28` contains bytes `04 00 00 00`. Requirements
+are three DWORDs, in the order above, proved by `0x10008150` / `0x10008120`.
+The reader rejects requirement counts greater than 999. Its signed test
+allows a negative count to behave like zero; an encoder should use 0..999.
+The writer emits the actual requirement-list length.
+
+The four common fields are not an encoded list. Their native writer obtains
+fields 3, 4, 32, 35 and writes them directly. Common shipped values for a
+single immediate self effect are `1, 0, 2, 9`; version 4 and argument header
+9 are separate fields. The decoder stores the argument header without the
+version check applied to the leading version.
+
+For zero requirements, the identity and common effect header occupy **32
+bytes** before the function-specific arguments. Add 12 bytes per requirement.
+There is no length prefix around an individual effect: its function kind
+selects exactly how many argument fields are consumed.
+
+## Combat argument layouts
+
+Field numbers below are the native effect's internal numeric keys, not actor
+stat IDs. For example, internal key 0 contains the actor stat to modify.
+Names are supported by the native StateParse registration and effect handlers;
+opaque fields remain numeric.
+
+| Kind | Native name | Arguments in wire order | Zero-requirement entry size |
+| --- | --- | --- | --- |
+| 53002 | Hit | i32 stat `[0]`, i32 minimum `[2]`, i32 maximum `[37]`, i32 damage type `[71]` | 48 bytes |
+| 53012 | Skill | i32 stat `[0]`, i32 amount `[39]`, i32 opaque `[24]` | 44 bytes |
+| 53014 | TimedEffect | i32 stat `[0]`, i32 amount `[39]`, i32 flag `[11]`, i32 opaque `[46]`, i32 duration in centiseconds `[25]` | 52 bytes |
+| 53028 | AddSkill | i32 section `[55]`, i32 stat `[0]`, i32 value `[39]` | 44 bytes |
+| 53033 | SkillTime | i32 opaque `[55]`, i32 skill `[0]`, i32 value `[39]` | 44 bytes |
+| 53045 | Modify | i32 stat `[0]`, i32 amount `[39]` | 40 bytes |
+
+Reader and writer independently select these branches:
+
+| Kind | Reader branch | Writer branch |
+| --- | --- | --- |
+| 53002 | `0x100b9740` | `0x100b7f98` |
+| 53012 | `0x100b9aab` | `0x100b8039` |
+| 53014 | `0x100bb016` | `0x100b8582` |
+| 53028 / 53033 | `0x100b9999` | `0x100b7ffe` |
+| 53045 | `0x100b9938` | `0x100b800c` |
+
+For SkillTime and AddSkill, all three arguments are actual serialized
+integers. The leading word is not padding. Skill likewise has a third
+serialized integer. The two words between TimedEffect's amount and duration
+are serialized too. Their exact layouts therefore come from the native
+reader/writer rather than the older extractor's uninterpreted-byte labels.
+
+Wire compatibility is separate from execution. Modify and Skill route to the
+character modifier handler, while AddSkill modifies item state. SkillTime's
+admitted executor reaches a no-op in this client; it does **not** create a
+client skill lock. TimedEffect has a scheduled add/remove path. Hit has a
+local execution gate, including tick restrictions described in
+[effect/stat findings](combat-client-stats.md). Do not use receipt of an effect
+container as proof that the client will perform authoritative damage ticks.
+TimedEffect's queued executor advances elapsed time by 200 on the client's
+two-second update, so raw duration 4000 corresponds to 40 seconds with that
+update's quantization. This establishes client presentation/execution timing,
+not the original server's exact expiry policy.
+
+A periodic Hit/DoT entry uses the same common tick fields and four Hit
+arguments; it does not acquire a different opaque byte layout. Its admission
+and local execution restrictions remain separate. In particular, a decoded
+multi-tick Hit is not evidence that the server can delegate damage timing to
+this client. The server must schedule its authoritative ticks and replicate
+the resulting health changes through the result contracts in the protocol
+inventory.
+
+Hit's reader also marks its internal validity field 999 false when both
+minimum and maximum are zero, and for a negative health hit with damage type
+zero. A server must provide an appropriate nonzero damage type for such a
+damage effect. An accepted stream is not proof of a valid server-side effect
+or permission to alter a particular stat.
+
+## An exact Modify plus SkillTime payload
+
+The following creates a syntactically complete SpellList container with two
+entries: Modify Martial Arts stat 100 by +5, then a SkillTime entry carrying
+first argument 9, First Aid stat 123, and value 40. These operands are an explicit
+example, not a new combat balance rule. Instance 0, version 4, empty
+requirements, and common fields `1,0,2,9` follow the recovered layout and
+shipped effect records.
+
+```python
+import struct
+
+# Encoded count followed by complete function identities, headers and arguments.
+words = [
+ 3027,
+ 53045, 0, 4, 0, 1, 0, 2, 9, 100, 5,
+ 53033, 0, 4, 0, 1, 0, 2, 9, 9, 123, 40,
+]
+payload = struct.pack(">22i", *words)
+assert len(payload) == 88
+```
+
+The exact 88 bytes, grouped into DWORDs:
+
+```text
+00000bd3
+0000cf35 00000000 00000004 00000000 00000001
+00000000 00000002 00000009 00000064 00000005
+0000cf29 00000000 00000004 00000000 00000001
+00000000 00000002 00000009 00000009 0000007b 00000028
+```
+
+Place these bytes after the common N3 prefix for class-derived ID
+`0x4d450114`, with the receiving character as envelope actor. For an
+ApplySpells addition to character 1, use class-derived ID `0x342c1d1d` and
+append `0000c350 00000001 01` to the container: target identity `(50000,1)`
+and byte add mode 1. Its subclass payload is 97 bytes. Removal uses the same
+container and target, with the final byte 0; it must correspond to an effect
+that the server previously applied.
+
+The encoded fixture is retained as
+`local/reports/combat-spelllist-modify-skilltime.bin`, with words, hex, target
+digest and validation limits in the adjacent `.json`. Its SHA-256 is
+`f0289e06873cfca712d5445596ee83cedb17b8ed9ede9399bb4265177190d0c9`.
+Length and integer roundtrip were checked. A subsequent isolated browser probe
+sent this exact SpellList payload to character 1. The native skill panel showed
+Martial Arts change from 7 to 12; sending the corresponding ApplySpells removal
+returned it to 7. Two complete add/remove rounds were captured, with no browser
+page errors. This validates the tested framing and modifier direction in the
+published Chromium/WASM client.
+
+Screenshots are `local/combat-smoke/multi-effect-probe-body-before.png`,
+`multi-effect-probe-body-add.png` and `multi-effect-probe-body-removed.png`;
+the retained capture and summary are `effect-modifier-events.json` and
+`effect-modifier-summary.json`. The stats summary's attack rating stayed at 7
+while the skill panel showed 12; its refresh/binding behavior needs a separate
+probe. No skill-lock UI behavior is asserted by this test. The temporary server
+and browser were closed afterward.
+
+## Actual skill-lock notification
+
+To start the corresponding client lock, the server uses CharacterAction
+**170**, not the no-op SkillTime executor:
+
+```text
+class-derived ID: 0x5e477770, envelope actor = locked character
+u32 action = 170
+identity A = (0, 0) # unused by this receiver branch
+identity B = (skill, raw_seconds) # numeric arguments in identity-shaped fields
+```
+
+For First Aid 123 and raw duration 40, the entire 20-byte subclass payload is:
+
+```text
+000000aa 00000000 00000000 0000007b 00000028
+```
+
+`0x1007d5c0` decodes this envelope, `0x1007d640` resolves its actor, and
+`0x1006fa30` case 170 passes identity B's two words to `0x10073ae0`.
+The skill controller stores `(skill, remaining)` pairs. A new lock's duration
+is `trunc(raw_seconds + effective_stat_382 * raw_seconds * .01)`.
+The setter ignores an already locked skill; resending the notification does
+not refresh its remaining time. A one-second GameTime update decrements each
+remaining value and removes entries at zero or below through `0x10073d00`.
+The setter also calls `0x100572b0` for the UI update.
+
+The server must own the actual deadline, skill eligibility and action result.
+The client countdown is separate from weapon attack/recharge and nano shared
+timers. No explicit early-unlock/reset message has been established by this
+path; do not invent a negative-duration reset or assume that a second start
+refreshes it. Reconnect/late-session lock resynchronization needs a deliberate
+server contract based on remaining time and the client's duplicate behavior.
+
+## Coverage and retained evidence
+
+The native argument reader and writer each dispatch kinds **53002..53192**.
+The following in-range kinds select the rejection path in both jump tables:
+53007, 53020, 53021, 53022, 53046, 53112, 53182, 53184, 53185, 53186,
+53187, 53188, 53189, 53190. Out-of-range kinds likewise mark the stream bad.
+The database catalog contains later IDs; their presence is not permission to
+send an unsupported function to this client.
+
+This document fully specifies the six combat argument layouts above and both
+envelopes. Other admitted function bodies can contain strings, identities,
+requirements or other typed structures and are not covered by this encoder
+subset. No generic "skip the unknown effect" operation is safe: there is no
+per-effect byte length. Tick execution, effect duration/stacking and server
+resource policy remain distinct from the byte contract.
+
+Retained REA records in `local/reports/combat-client-pass2-decompiles-*.json`:
+
+- Batch 1,
+ `ev_19082dbcfc4a2c549129a10d22647431c814e3a63ef640a7ab02206ae9fe5342`:
+ full effect decoder `0x100b9530` and effect construction.
+- Batch 3,
+ `ev_3c35ce2d6454b2e9f741c25a66383f242d46fbb8029551ab3e61d2121e188deb`:
+ requirement reader `0x10008150`.
+- Batch 4,
+ `ev_80beaf091eb5a5d73960b97b09e3dd3afded2f2ee46f14ff090b6de347cb12ed`:
+ full effect writer `0x100b7d80`, list writer `0x100bcf40`, skill-lock
+ membership, remaining-time, setter and countdown methods.
+- Batch 9,
+ `ev_21b6bf56ea3b01fefafecdb673e392142538e12a995ac4070c4b8a8f1a26f59b`:
+ common container application `0x10002370`, including add/remove flag handling
+ and immediate versus queued effect routing.
+- Batch 10,
+ `ev_1a3cb7e77a4267701716a4ec28b32bf1ad4e1f9c934ef18e59cc10785519c56f`:
+ skill-lock UI callback `0x100572b0`, which marks an existing action and emits
+ its event when the owner is the local character.
+
+The original PE reader/writer jump tables are at `0x100bcc40` and
+`0x100b9234`. Their independent selected branches were checked against the
+generated original-instruction comments in `lifted-0055.c` and
+`lifted-0054.c`. Requirements are in `lifted-0002-01.c`; common containers in
+`lifted-0056.c`; SpellList wrappers in `lifted-0057.c`; ApplySpells wrappers
+in `lifted-0099.c`. The ApplySpells mode inversion,
+container outer framing, and CharacterAction dispatch also reuse the earlier
+evidence linked in the protocol inventory.
diff --git a/docs/combat-client-state-machine.md b/docs/combat-client-state-machine.md
@@ -0,0 +1,376 @@
+# 14.9.1 combat client state machine
+
+This records what the shipped client computes, requests, and displays. It is
+not the missing Funcom server implementation. A server can reproduce these
+contracts without pretending that animation timers determine authoritative
+hit rolls. Related findings are in [combat-rules.md](combat-rules.md),
+[combat-client-stats.md](combat-client-stats.md), and
+[combat-client-protocol.md](combat-client-protocol.md).
+
+## Target, method, and coverage
+
+Target: `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Addresses below are original virtual addresses based at `0x10000000`.
+Matching generated C in `client/game/kkr.dll/` is relocated to `0x36000000`;
+subtract `0x26000000` to compare its instruction comments with these addresses.
+REA uses Ghidra 12.1.2. Pseudocode is decompiler output, not original source.
+Important x87 rounding, flag transitions, and range branches were also read
+in assembly. There was no live original-server traffic or original-server
+execution in this investigation.
+
+Coverage checklist:
+
+| Question | Status | Boundary |
+| --- | --- | --- |
+| Character/holder/weapon/timer object links | Answered | Relevant fields and vtables below |
+| Timer initialization, soft cap, AggDef, conversion | Answered | Client clock only |
+| Startup random offset | Answered | Exact client arithmetic, server timing unknown |
+| Attack/recharge phases, shared scheduler | Answered | Including flag tests, ordering and discarded overshoot |
+| UI timer events | Answered | Categories and show/hide/start events; widget drawing outside scope |
+| Attack request, acknowledgement, stop | Answered | Holder state changes and result queue |
+| Dual wield and unarmed binding | Partial | Binding/requirements recovered; MA-to-QL server policy unknown |
+| Range and physical extent computation | Answered | Client UI/special checks, not ordinary server hit validation |
+| Line of sight and movement/casting interruptions | Partial | Concrete client branches; original server checks unknown |
+| Reload and interrupting shared attack timer | Answered | Client completion and ammo fields; server inventory policy unknown |
+| Damage/critical presentation versus authoritative damage | Answered | Client queue consumes server supplied damage/result |
+| Death and recovery visual state | Partial | Stops fighting and runs death state; reclaim/respawn server rules unknown |
+
+The call graph was followed from public attack/stop requests, the holder
+vtable, shared timer callers, received hit results, the fight visual state's
+update, and equipment/unarmed binding. This is a bounded combat-state
+investigation, not a claim that every indirect callback or every unrelated
+character-state branch has been recovered.
+
+## Object links and layouts
+
+`SimpleChar` constructor `0x1006cc80` allocates these helpers:
+
+| Character offset | Meaning | Constructor |
+| --- | --- | --- |
+| `+0xe4` | Stat interface subobject, not a pointer to an independent stat interface | Character vtable |
+| `+0x128` | Local player byte | Set during client character selection |
+| `+0x154` | Skill/stat helper | `0x10073500` |
+| `+0x16c` | `WeaponHolder_t *` | `0x100783e0`, allocation `0x7c` |
+| `+0x174` | Animation/character-state controller | `0x1004fd60`, allocation `0xcc` |
+| `+0x178` | Activity helper; bytes `+4/+5` consulted by fight state | `0x1006b380` |
+| `+0x184` | Shared timer controller, allocated lazily | `0x10071d60` -> `0x10052450` |
+| `+0x188` | Physical/appearance helper | `0x10059770`, allocation `0x68` |
+| `+0x1b4` | NPC byte | Distinguishes observed NPC/player branches |
+
+For a runtime read with an already known engine instance, its `+0x88`
+points to the local `SimpleChar`; `*(character + 0x188) + 0x30` is the
+physical extent used by the range routine. The current target identity is
+at `*(character + 0x16c) + 0x58/+0x5c`. Use the dynel registry to resolve
+that identity, then the same physical-helper chain for the target. Runtime
+values were not read during this static investigation.
+
+Relevant holder fields, initialized by `0x100783e0`:
+
+| Holder offset | Observed use |
+| --- | --- |
+| `+0x04` | Owning character |
+| `+0x08` | Skill-keyed map of server supplied special/unarmed items |
+| `+0x0c .. +0x48` | Sixteen weapon pointers; slot 0 fists, slots 6/8 equipped hands |
+| `+0x4c` | Received special-weapon template binding records |
+| `+0x50` | State: 1 idle, 2 fighting; other numeric values are not fully named |
+| `+0x54` | Initialized/reset to 1 |
+| `+0x58/+0x5c` | Fighting target identity |
+| `+0x68/+0x6c` | Cleared on acknowledged attack start |
+| `+0x70` | Cached UI range indicator byte |
+| `+0x71` | Attack request outstanding byte |
+| `+0x74` | Received death reason |
+| `+0x78` | Reload timer index, initially -1 |
+
+Holder vtable `0x10171500` binds `+0x30` to equip `0x10078e80`, `+0x34`
+to range predicate `0x10078cb0`, `+0x38` to slot-range wrapper
+`0x10078c70`, `+0x40` to start `0x10078fc0`, `+0x44` to stop
+`0x10079250`, and `+0x64` to queued special action consumption
+`0x10079700`. Raw vtable evidence:
+`ev_7d6762ab9ca524bf50401534ef85eca9805b9846bad1e09ab7cb11cf7c885c93`.
+The target lookup helpers at `0x10079540`, `0x100795b0`, and
+`0x100795e0` are present in generated assembly, although Ghidra did not
+admit them as procedures. This is a disassembler coverage limitation, not
+an absent client feature.
+
+`WeaponBase` constructor `0x100aac50` allocates a timer and a ring of 50
+damage/result pairs. Its fields include timer pointer `+4`, weapon slot
+`+8`, blocked-retry counter `+0xc`, result-ring vector `+0x10`, write/read
+indices `+0x14/+0x18`, item stat object `+0x1c`, actual inventory item
+`+0x20`, cached original min/max/crit `+0x24/+0x28/+0x2c`, and owner
+identity `+0x30/+0x34`. `0x100ab4c0` appends one server supplied pair and
+wraps the write index at 50; `0x100ab580` reports write != read. There is
+no overflow detection in this helper, so large bursts of result messages
+can overwrite unread visual results. This is not an authoritative server
+combat log.
+
+## Shared timer and phase transitions
+
+The controller at character `+0x184` has owner `+0`, allocated slot count
+`+4`, timer vector `+8`, active attacking index `+0xc` (-1 means none).
+Each timer is `0x20` bytes:
+
+| Offset | Type and meaning |
+| --- | --- |
+| `+0x00` | Float remaining centiseconds |
+| `+0x04` | Attack duration, stored integer bits |
+| `+0x08` | Recharge duration, stored integer bits |
+| `+0x0c/+0x10` | Pending replacement attack/recharge durations |
+| `+0x14` | Flags |
+| `+0x18` | Category: weapon 1, nano 3, item use 4, reload 5 |
+| `+0x1c` | UI timer slot/index |
+
+These flag names describe observed tests, not recovered enum identifiers:
+
+| Mask | Observed effect |
+| --- | --- |
+| `0x01` | Set at insertion; no additional meaning established |
+| `0x02` | Attack phase; clear means recharge |
+| `0x08` | Enabled for repeated timer transitions |
+| `0x20` | Hold/completed-attack latch; blocks automatic recharge decrement |
+| `0x40` | Set when recharge completes |
+| `0x80` | Controller owns/deletes allocated temporary timer |
+| `0x100` | Suppresses setting `0x20` at attack completion |
+| `0x200` | Remove the timer after recharge completion |
+| `0x400` | Suppresses recharge-start UI event |
+
+`0x10052550` first detaches an existing occurrence of a timer, finds a free
+vector slot, sets remaining to the integer attack duration, stores both
+durations/category/index, sets flags `0x03`, and selects an active timer
+if none exists. `0x1007a940` subsequently enables weapon timers with
+`flags |= 0x08`. `0x10052630` allocates an owned temporary timer and sets
+`0x80`; weapon timers belong to their `WeaponBase` instead.
+
+Per character frame `0x1006ea50` passes `engine.deltaSeconds * 100` to
+`0x100527c0`. The exact update order is:
+
+```text
+if an active attacking slot exists:
+ subtract delta from that timer only
+ if remaining <= 0:
+ if !(flags & 0x100): flags |= 0x20
+ remaining = integer recharge duration
+ flags &= ~0x02
+ active = -1
+ send recharge UI event unless category 3 or flags & 0x400
+ scan slots in increasing index order:
+ choose first enabled attack-phase timer without 0x20
+ apply its pending durations if pending attack != 0
+ make it active and stop scanning
+
+if an active slot exists: return
+for each timer in increasing slot order:
+ if enabled AND !attack-phase AND remaining > 0 AND !(flags & 0x20):
+ subtract delta
+ if remaining <= 0:
+ flags |= 0x42
+ remaining = integer attack duration
+ select it if no active slot exists
+ send attack UI event unless category 3
+ remove it if flags & 0x200
+```
+
+The loop does not carry negative remaining time into the next phase or
+replay multiple elapsed cycles. It can advance a newly recharging timer
+by the same frame delta used to complete its attack. It can also complete
+multiple recharges in one scan even after selecting the first active
+attack, because the active-index guard precedes that loop. Those ordering
+details matter when matching frame observations.
+
+Only one weapon attack phase progresses at a time. Recharge phases pause
+while another attack remains active. Ready weapons can therefore attack
+in sequence and then recharge together. Treating dual-wielded weapons as
+independent repeating hit clocks does not reproduce this client scheduler.
+This still does not establish whether the original server used precisely
+the same frame granularity or the same first-hit policy.
+
+`0x100529a0` forces a temporary timer active, resets the previous active
+weapon's remaining time to its attack duration, clears its hold flag, and
+sets enabled. `0x10077300` installs pending durations and clears pending
+fields. A stats/AggDef refresh during combat `0x100714a0` uses
+`0x1007a940(0)` to stage new durations rather than restart every attack.
+Equipment changes and acknowledged fight start instead use argument 1.
+
+Timing formulas and base skills are in [combat-rules.md](combat-rules.md).
+`0x1007aa30` truncates both positive centisecond durations through `_ftol`.
+For start/reset argument 1, its additional exact arithmetic is:
+
+```text
+remaining = attackCs + 50 - trunc(rand() * attackCs * 0.5 / 32767)
+```
+
+Assembly evidence `ev_5d76845488e6c317cf130db5dd72edbe2112b0035e32421273f730ecb8fa9b4f`;
+double constant `0x101708c0` equals `1/32767`, verified by bytes
+`80 00 40 00 20 00 00 3f`, evidence
+`ev_1243488403d024a9a63cef7633f85c2c02e3c6f7a7970ff3fe58953cc3fc156d`.
+With MSVCRT's 0..32767 `rand`, attackCs 198 starts at 149..248 cs. This is
+client animation/attack-bar startup behavior. It is not proof that server
+damage should be delayed by a matching random value.
+
+Timer update and UI-event evidence:
+`ev_54c8e5911c3ccf91ab6ce87b5b2df8506f06ab9850e3ae78da5b0cb38fc13d7c`,
+assembly `ev_2ce2af1831dd11b56b74c0ec2e1f96cda73af25e4f1af2dc62d5e1a8b22caead`.
+
+## Requests, acknowledgement, results, and stop
+
+`N3Msg_DefaultAttack` `0x1002b2b0` requests a stop if already fighting,
+checks the current action/state and `0x10079880` target eligibility,
+rejects while previous fight/action is pending, then calls `0x1007bee0`.
+That helper sets holder pending byte `+0x71` and sends `AttackIIR_t` with
+target identity and a byte. The request path does not call the range
+predicate. Eligibility checks include self, nonexistent target, target
+status/death, swimming/state restrictions, surrender ownership, and
+playfield/gas/team conditions; full original PvP policy is not implied by
+these client checks.
+
+On received start, `0x10078fc0` clears pending, resets existing fight state
+if necessary, resets weapon timers with randomized startup, sets target,
+changes state to 2, emits attack text/UI events, and suppresses normal
+hand recharge UI using timer `0x400`. `N3Msg_StopAttack` `0x1002b180`
+sends a StopFight request only if currently attacking. The returned
+StopFight activation invokes holder stop; it is not just a local target
+clear when the key is pressed.
+
+`0x10079250` attempts to drain already received damage/result queues,
+clears queued special actions and UI attack state, restores idle state 1,
+clears target, resets the animation controller, and clears hand timer
+`0x400`. Death visual constructor `0x10085d60` also calls holder stop when
+needed before locking/playing death state. Disconnect/zoning authoritative
+cleanup is the server's responsibility; client visual cleanup alone does
+not establish correct multiplayer state.
+
+`AttackInfo` supplies damage, slot, target, death reason and result. The
+client queues the supplied damage/result through `0x1007a660` ->
+`0x100ab4c0`. The fight state's `0x10086390` calls `0x1007b2d0`, which
+plays attacks with pending server results and clears completed timer
+holds. `0x100ab5a0` consumes the queue, prints combat text and subtracts
+the supplied amount from target health at the visual hit point. Result 5
+adds `Critical hit!`; the missed-attack path supplies zero damage and
+result 3. There is no local random hit/damage/critical calculation here.
+Missing-attacker fallback and absolute-health messages have different
+health-update paths; see the protocol document before emitting redundant
+damage notifications.
+
+The ring/animation queue can outlive a stop; stop intentionally drains it
+when an opponent and pending results remain. Consequently, an already
+announced hit can appear while the stop animation finishes. A server must
+distinguish cancelling future swings from retracting previously sent hits.
+
+## Range, line of sight, and movement
+
+`0x10078cb0` is the holder range predicate. For a character target it
+computes 3D center distance `d`, actor extent `ra`, target extent `rt`, and
+effective weapon range `r`. It first accepts `d < r + ra`; otherwise it
+accepts `d <= r + 2*ra + rt`. The doubled actor extent is present in both
+assembly and pseudocode; do not silently simplify it to a conventional
+sum of two radii. Item targets instead use `d < r`.
+
+`0x100aae10` supplies `r = min(40, trunc(itemRange *
+(1 + WeaponRangeIncreaser380/100)))`. Physical extent starts at 1.0 in
+`0x10059770`, then `0x1005a790` replaces it with
+`max(1, MonsterScale360(mode3)) * CharRadius421(mode2) * .01`. It also
+applies `MonsterScale*.01` to body scale. A default constructor value is
+not evidence that every spawned Leet retains radius 1.0. In fact the stat
+initializer `0x10072760` sets CharRadius421 to 2 and MonsterScale360 to
+100, giving extent 2.0 after this refresh when neither stat is replaced.
+Even those stat defaults must not be substituted for actual NPC values or
+treated as proof of an original-server melee hit threshold.
+
+The predicate has two established uses: special-attack validation
+`0x10078990` and selected-target range UI via `0x10078c70` ->
+`0x1007acf0` -> events `0x1001c910/0x1001c930`. It also supports range
+failure feedback. Ordinary attack request and received-hit application do
+not run this predicate. Thus the formula establishes client UI/special
+range, not the original server's normal-attack distance policy.
+
+`0x100721d0` returns false for null targets, different playfields, or no
+playfield; true for self and for non-dungeon playfields; and for dungeons
+calls `n3Playfield_t::LineOfSight` between actor/target global positions
+with +1.6 vertical offsets and actor zone-instance ID. Outdoors this
+specific helper performs no raycast. That does not prove the original
+server allowed attacks through outdoor walls.
+
+When timer hold `0x20` is set, `0x100ab740` increments a retry counter
+modulo 5 and, only when it becomes 1, checks target line of sight. It
+returns false at other retries. `0x100ab7a0` clears the hold. These are
+presentation scheduling checks around received results, not substitutes
+for authoritative server validation.
+
+Fight visual `CharFight_t` `0x10086300/0x10086390` uses category/state 10.
+It can transition to state 0 (idle), 11 (dead), 4 (activity byte +4),
+5 (activity byte +5, associated with casting), or 7 (turning). It runs
+received-result animation pumping before those checks. Every 0.67 seconds,
+when the numeric state/vehicle predicates permit it, it compares facing
+with target direction; angle greater than 0.26 radians transitions to
+turning state 7. Unnamed vehicle/state helper predicates remain numeric
+in the retained pseudocode rather than being guessed as universal
+moving/ranged/melee rules. No complete server movement-interruption rule
+was recovered from this visual state.
+
+Range assembly: `ev_9862c91fdfb306342e1a4bada390db357a4002667850e7704ed97713cc8510be`.
+Physical extent/fight state:
+`ev_3e82ca2665af85fa3448bff637a94ef4494a0c5d51260223b3f4fbe14daf4dae`.
+LOS/retry: `ev_c6476a44ff6f2acef524789bf74ebddd3ea49bab979bdff76f495ac32a5de6b8`
+and `ev_9081c9ee969a3f64c9cfb5aec6a5d90477aa638090d6ed38e5791a3d0d58eeda`.
+
+## Equipment, unarmed binding, and reload
+
+Slot binding `0x1007a340` rejects deleted item state, stores one of sixteen
+weapon pointers, records owner identity, and updates attack-weapon flags
+stat 274 from fists/ranged/melee/energy categories. Equipping
+`0x10078e80` clears fists when equipping a nonzero slot unless character
+status bit `0x800` permits combined MA attacks; a combat equip resets all
+weapon clocks with startup randomization. Unequipping `0x10078f00`
+detaches the old timer and restores the skill-100 item as fists if no
+weapons remain, then resets clocks if still fighting.
+
+`0x1007a4c0` checks dual-wield eligibility against the other equipped hand.
+For ordinary single-hand categories it compares the character's
+MeleeMultiple 101 or LR_MultipleWeapon 134 against the smaller of the two
+items' requirements. Zero and missing (`0x499602d2`) requirements fail.
+`0x10091060` identifies weapon mesh categories 2, 3, and 6 as excluded
+from this ordinary check. `0x10091090` classifies ammo type <1 as the
+melee side of that distinction. The complete inventory/equip transaction
+still requires server validation.
+
+`0x1007b9a0` reads server supplied low/high endpoint IDs and skill key,
+interpolates an item, inserts it into the skill map, and binds skill 100
+as fists when no weapons are equipped, fists already occupy slot 0, or
+combined-MA status permits it. It does not recover MA-skill-to-fist-QL
+selection: that endpoint/quality policy must be supplied by the server.
+The item interpolation itself is covered in the rules/stats documents.
+
+Reload eligibility `0x1007bba0` requires a WeaponItem, no existing reload
+index, matching weapon/ammo stat 420, ammo ItemType76 == 0, and a weapon
+not already at capacity stat 212. On accepted server reply `0x1007bca0`,
+the client changes ammo stat 26 to the provided value, allocates category
+5 timer with attack and recharge both set to the weapon's raw
+RechargeDelay210, forces it active, and prints `Reloading`. Thus this
+reload UI timer is not the adjusted physical-initiative weapon timer.
+`0x1007bdf0` removes it after its completion/hold flag appears, resets
+reload index to -1, and prints completion. Ammo/inventory data is supplied
+by the server; completing a UI timer alone does not authorize ammunition.
+
+## Evidence and implementation boundary
+
+New evidence is exported to
+`local/reports/combat-client-state-evidence.json`; readable selected
+decompilations are in `local/reports/combat-client-decompiles-*.json`.
+The matching reusable REA snapshot is
+`local/reports/combat-client-state-1491.snapshot.json` (148 evidence records,
+21 retained batch workflows). The native analysis session was closed after
+the state, stats and protocol investigations finished.
+Earlier evidence remains in `combat-rules-1491-evidence.json` and
+`combat-1491-evidence.json` in that directory. Batch records contain the
+exact requested selector, canonical entry, successful pseudocode, and
+explicit failed entries. Do not reinterpret failed disassembler coverage
+as proof that a generated function is missing from the client.
+
+The server should send coherent target/slot/result/health events and
+maintain authoritative combat state independently of client render rate.
+The client supplies a much better timing, equipment, range-UI and message
+contract than the initial fixed-damage prototype. It does not contain the
+lost server's hit chance, NPC stat curves, aggro/chase policy, line-of-sight
+authority, PvP balance, first-hit scheduling, loot, XP, or reclaim policy.
+Those remain explicit reconstruction work and must not be described as
+verified canonical rules.
diff --git a/docs/combat-client-stats.md b/docs/combat-client-stats.md
@@ -0,0 +1,344 @@
+# Combat calculations in the 14.9.1 client
+
+The shipped client calculates item stats, skill ratings, action deadlines,
+range checks and local health/nano updates. These calculations provide strong
+evidence for reproducing its behavior. They do not recover the original
+server's hit, critical, armor or damage rolls.
+
+This report uses the original `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`,
+and the database shipped with that client. Addresses below use its original
+image base `0x10000000`; generated C symbols use base `0x36000000`.
+`FUN_10074560`, for example, corresponds to generated `sub_36074560`.
+Integer division and `trunc` mean truncation toward zero. Floating-point
+constants and x87 operation order matter at boundaries.
+
+## Evidence and entry points
+
+| Calculation | Original symbols | Generated source | Evidence |
+| --- | --- | --- | --- |
+| Default skills, ability trickle, health/nano foundations | `10072760`, `10073fa0`, `10075c60`, `10075910` | `client/game/kkr.dll/lifted-0034.c` | [Starting stats](combat-starting-stats.md); original rules evidence bundle |
+| Weighted attack/defense ratings | `1008f1f0`, `1008f2f0`, `1007c120` | `lifted-0042.c`, `lifted-0036.c` | Decompile batch 1 and original rules bundle |
+| Damage tooltip and skill percentage strings | `10024300`, `100271b0`, `100272d0` | `lifted-0015.c` | Decompile batch 1 |
+| Weapon damage cache/type/OE adjustment | `100ab920`, `100ab7b0`, `100ab8a0`, `10090f10`, `10062f60` | `lifted-0051.c`, `lifted-0042.c`, `lifted-0029.c` | Decompile batches 1 and 3; generated assembly for OE arithmetic |
+| Item construction and QL interpolation | `100894c0`, `100f1200`, `100f00a0`, `100eff20`, `100f0c80` | `lifted-0040.c`, `lifted-0070.c` | Original rules bundle |
+| Weapon initiative/AggDef deadlines | `1007ab40`, `1007ac10`, `1007aa30`, `1007aad0` | `lifted-0035.c` | [Rules](combat-rules.md); original rules bundle |
+| Nano casting deadline | `100650f0` | `lifted-0030.c` | Decompile batch 5; assembly at `100651b4` through `1006526b` |
+| Nano cost eligibility and interrupted-cast refund | `100646a0`, `10098bd0`, `10066b20` | `lifted-0030.c`, `lifted-0046.c` | Decompile batch 20; assembly at `10064839` through `1006488d` |
+| Weapon/nano range | `100aae10`, `10098c10`; spatial caller `10078cb0` | `lifted-0051.c`, `lifted-0046.c`, `lifted-0035.c` | Original rules bundle and decompile batch 5 |
+| Regeneration intervals/deltas/update | `10074560`, `10074690`, `1006ea50`, `10059bd0` | `lifted-0034.c`, `lifted-0033.c`, `lifted-0027.c` | Decompile batch 3; generated assembly for floating-point math and nano clamp |
+| Clock gating regeneration | `GameTime_t::RunFunction`, `1000c3c0` | `lifted-0004.c` | Generated assembly at `1000c487` through `1000c516` |
+
+Local evidence files are `local/reports/combat-rules-1491-evidence.json` and
+`local/reports/combat-client-decompiles-*.json`. Batch 1 has evidence ID
+`ev_54c8e5911c3ccf91ab6ce87b5b2df8506f06ab9850e3ae78da5b0cb38fc13d7c`,
+batch 3 `ev_839516fbf9737749e969200bc7698259fa6decf43f39b3025dc440c60acd95f3`,
+and batch 5 `ev_9081c9ee969a3f64c9cfb5aec6a5d90477aa638090d6ed38e5791a3d0d58eeda`.
+Batch 18 confirms the OE criterion traversal and nano clamp, evidence ID
+`ev_2e782b554a0744a2121ba66adcdbff1f2ad2d35876b1d82851d18fbd718368d1`.
+Batch 20 confirms nano cost and clock gating, evidence ID
+`ev_b222a29a2449ed800e75228fac8a9ad597f8c73dce740b461b7fae780389796b`.
+Some requested addresses are interior aliases: the update requested as
+`1006f0a0` or `1006ee30` is the canonical function `1006ea50`.
+Generated aliases may likewise contain a larger shared body.
+
+## Skills and attack/defense ratings
+
+Ability trickle is a weighted sum divided by four, converted to integer before
+adding the base skill. The database supplies six integer ability percentages
+per skill, resource type 1000204. Defaults and exact weights for the current
+fixture are in [starting stats](combat-starting-stats.md). This yields Martial
+Arts 7 and Physical Initiative 7 for its six abilities of 10.
+
+The exact final scaling is `weighted_sum * float32(.01) * .25` before
+truncation. The first constant is 0.009999999776482582 (`0x10170894`), so an
+integer division by 400 changes exact boundary results. A live edited-stat
+probe confirmed effective Body Development 214 and Nano Pool 122 where that
+integer simplification predicted 215 and 123. See
+[resource synchronization](combat-regeneration.md) for the implementation and
+`local/reports/combat-trickle-float-constants.json` for original image bytes.
+
+`1008f1f0` reads item section 12, a sequence of `(skill stat, percentage)` pairs.
+`1008f2f0` does the same for section 13:
+
+```
+rating = sum(trunc(skill_value * percentage / 100))
+if rating > 0:
+ rating += modifier
+```
+
+The attack modifier is stat 276, defense modifier 277. Each term is divided
+separately; rounding the final sum would change results. For player characters
+these functions request getter mode 0 for skills. An NPC flag at actor offset
+`+0x1b4` selects mode 2 instead. The modifiers use mode 0 in both branches.
+A missing actor returns zero; an empty or nonpositive weighted sum does not gain the
+modifier. The item lists can be populated lazily before iteration.
+
+WeaponItem's vtable at `101745cc` connects offsets `+0x84` and `+0x88` to these
+functions. `1007c120` selects weapon slot 6, then slot 8, and computes attack
+rating through `+0x84`. Without a weapon it uses Martial Arts 100 plus modifier
+276, then stores attack rating in stat 22. The exported attack/defense string
+functions format the item weights; they do not run an evade or hit roll.
+
+Native skill-name tables independently establish the special skill IDs:
+
+| Skill | Stat | Name-table store in `10036490` |
+| --- | --- | --- |
+| Brawling | 142 | `10036974` |
+| Riposte | 143 | `100369d8` |
+| Dimach | 144 | `100369a6` |
+| Parry | 145 | `10036b9a` |
+| Sneak Attack | 146 | `10036bcc` |
+| Fast Attack | 147 | `10036c30` |
+| Burst | 148 | `10036eba` |
+| Fling Shot | 150 | `10036e56` |
+| Aimed Shot | 151 | `10036e88` |
+| Full Auto | 167 | `10036eec` |
+
+These are stat IDs, separate from action codes and packet opcodes. The long
+and short skill tables agree; exact string addresses are retained in
+`local/reports/combat-client-special-stat-names.json`. Descriptive skill text
+is not evidence that its historical prose accurately specifies server math.
+
+## Item QL and damage fields
+
+Item construction receives a packed QL and two template identities.
+`100894c0` selects the nearer template by absolute distance between requested
+low-16-bit QL and endpoint stat 54. An equal distance chooses the second
+endpoint. This selects the base template for properties that are not
+interpolated. Stats 702 and 703 retain the endpoints; stat 701 retains packed
+QL. This is not a recovered rule for selecting fist QL from Martial Arts.
+
+`100f1200` replaces stat 701 with 1 when its low 16 bits are zero or above
+511. It loads resource type 1000020 endpoints, copies a single endpoint when
+both identities match, and otherwise invokes `100f00a0`. That routine checks
+endpoint QLs and list compatibility before interpolating supported fields.
+`100eff20` performs the scalar operation:
+
+```
+if v1 == v2 or q1 == q2 or q == q1: return v1
+if q == q2: return v2
+if v1 < v2:
+ return v1 + trunc((q-q1) * (v2-v1) / (q2-q1) + 0.5)
+return v2 + trunc((q-q2) * (v1-v2) / (q1-q2) + 0.5)
+```
+
+This is floating-point interpolation with a 0.5 offset before integer
+conversion. It should not be replaced indiscriminately with language-default
+rounding, especially for descending endpoints or negative values. Scalar
+stat dispatch `100f0c80` supports IDs 1, 2, 26, 27, 36, 45, 73, 74, 75, 101,
+134, 210, 211, 212, 236, 250, 284, 285, 286, 287, 289, 294, 297, 299, 341 and
+422. Stat 74 receives an additional bit-mask transformation in `100f1320`.
+Other sections have their own interpolation processing in `100f00a0`.
+
+Weapon fields are minimum damage 286, maximum damage 285 and critical damage
+284. `100ab920` caches them. `N3Msg_GetDamageString` (`10024300`) formats these
+fields for a weapon, including the critical field in parentheses. Its nano
+branch formats negative health-effect ranges from effect data. Neither path
+combines attack rating, target armor, evade or critical chance into an outcome.
+The shipped QL 1 fist endpoints and interpolation evidence are also described
+in [combat rules](combat-rules.md).
+
+The client does calculate an overequipping adjustment. `100ab8a0` asks
+`10090f10` to examine requirement section 8, then adjusts each cached damage
+field with `10062f60`:
+
+```
+tier = 0
+for requirement with operator code 2:
+ ratio = effective_skill / requirement_value
+ if ratio < 1:
+ tier = max(tier, trunc((10 - ratio*10) * 0.5))
+tier = clamp(tier, 0, 4)
+adjusted_field = cached_field - trunc(cached_field * tier * 0.25)
+```
+
+The client uses effective getter mode 0 for these skills. Arithmetic and tier
+boundaries follow x87 floating-point operations, not a substituted modern
+percentage rule. This establishes a client item-field adjustment; it still
+does not establish the server's full damage formula or when it recalculates OE.
+
+Damage type comes from item stat 436 in `100ab7b0`. Accepted values are armor
+stat IDs 90 through 97 and 168; other values fall back to 90. This selects a
+type. It does not show how much armor subtracts or which order reflect,
+absorb, shields and added damage take. Result presentation and queued damage
+application are covered in the [protocol report](combat-client-protocol.md).
+
+## Weapon and nano timing
+
+Weapon attack and recharge use the initiative selected by item stat 440.
+The fallback for an out-of-range stat ID is Melee Initiative 118. Melee 118,
+Ranged 119 and Physical 120 therefore feed the same recovered weapon formula;
+the item chooses which skill applies. With `I` the effective initiative:
+
+```
+effective_init = I if I <= 1200 else 1200 + (I-1200)/3
+attack_cs = max(100, ItemDelay294 + 75 - effective_init/6 - AggDef51)
+recharge_cs = max(100, RechargeDelay210 + 75 - effective_init/3 - AggDef51)
+```
+
+The scheduler converts the positive centisecond results to integers by
+truncation. These functions and initial phase scheduling are traced in
+[combat rules](combat-rules.md) and the [state machine](combat-client-state-machine.md).
+For 125-centisecond fists, initiative 7 and centered AggDef 0 this gives
+198-centisecond attack and 197-centisecond recharge. Client deadlines do not
+establish server tick resolution.
+
+For exact boundary behavior, retain the native single-precision constants and
+intermediate store before AggDef subtraction. The original instructions use
+`init * .5`, then the float constant for 1/3 or 2/3; above 1200 the first
+expression becomes `600 + (init-1200) * float32(1/6)`. At initiative 387 and
+AggDef -100, the recharge intermediate falls just below 71 before adding 100,
+so truncation yields 170 cs. The server regression preserves this case.
+
+Nano casting has a separate calculation in `100650f0`. It uses Nano Initiative
+149 in mode 0 and AggDef 51 in mode 2:
+
+```
+effective_init = I if I <= 1200 else 1200 + (I-1200)/3
+cast_seconds = ItemDelay294/100 - effective_init/200 - trunc(AggDef51/100)
+deadline = GameTime.GetNormalTime() + cast_seconds
+```
+
+AggDef division here is integer division. Within the ordinary signed -100 to
+100 slider range, only its extremes contribute -1 or +1 to that term. The
+recovered function does not apply the weapon one-second floor. Item flag
+`0x80000` overrides the stored deadline to zero. The surrounding cast controller
+and restrictions still matter; this expression alone does not prove every
+nano can execute with a negative duration or that recharge uses Nano Initiative.
+
+Nano eligibility in `100646a0` calculates
+`trunc(effective_stat318 * base_cost407 * 0.01)` and requires at least that
+much current nano 214. `10098bd0` reads item stat 407. There is no reduction
+cap in this arithmetic. `10066b20`, accompanied by the interrupted-execution
+message, adds the same cost back to current nano; this refund path writes the
+stat directly without invoking the regeneration clamp. The exported
+`N3Msg_GetRechargeTime` (`10026240`) returns the nano object's float field
+`+0x88`, or zero if the object is absent. This display getter does not itself
+derive recharge from initiative. Complete cost/stat caps and initialization
+of that recharge field require their own call-chain proof.
+
+## Range and physical extent
+
+`100aae10` computes weapon range from item 287 and effective actor stat 380;
+`10098c10` computes nano range using effective actor stat 381:
+
+```
+range = min(40, trunc(item_range + item_range * range_modifier * 0.01))
+```
+
+The minimum is not clamped in these helpers. A weapon's controller range check
+`10078cb0` compares 3D center distance with effective weapon range plus twice
+the attacker's physical extent and once the target's extent. Its extent input
+comes from the actor helper at `+0x188`, field `+0x30`. Reproducing that field
+for every model needs the spatial construction trace; a flat four-meter
+center-distance rule is only an approximation. The exported optimum-range
+getter uses half the unmodified item range for its selected weapon. Further
+target and line-of-sight checks are in the state-machine report.
+
+## Health, nano and regeneration
+
+`10075910` builds the health stat 1 and maximum nano stat 221:
+
+```
+health = breed600 + level * breed601 + effective_BodyDevelopment152 * breed602
+ + level * profession_title_health_bonus
+max_nano = breed603 + level * breed604 + effective_NanoPool132 * breed605
+ + level * profession_title_nano_bonus
+```
+
+The profession/title row's health coefficient is at `+8`, nano coefficient at
+`+4`; missing rows contribute zero. Breed resource 1000203 supplies stats
+600 through 605. The function only recalculates for the local player and
+skips NPCs, so applying the player formula to all creatures would be
+unjustified. Full health data,
+Soldier title thresholds and missing-breed fallback are in
+[starting stats](combat-starting-stats.md). Nano coefficients are:
+
+| Breed resource | Base nano 603 | Per level 604 | Per Nano Pool 605 |
+| --- | --- | --- | --- |
+| Solitus 1 | 10 | 4 | 3 |
+| Opifex 2 | 10 | 3 | 3 |
+| Nanomage 3 | 15 | 5 | 4 |
+| Atrox 4 | 8 | 2 | 2 |
+| Resource 5 | 50 | 2 | 1 |
+
+`10074560(percent)` recalculates intervals only for the local player:
+
+```
+HealInterval342 = max(1, trunc((30 - Stamina18 * (float)(1/30)) * percent * 0.01))
+NanoInterval363 = max(1, trunc((30 - Psychic21 * (float)(1/30)) * percent * 0.01))
+```
+
+The literal reciprocal is the single-precision value 0.03333333507180214.
+Initialization and equipment refresh pass 100. Attack start at `10079093`
+passes 200; stop at `10079405` restores 100. `10074690` seeds HealDelta343
+from breed coefficient 602 and NanoDelta364 from 605. Its NPC branch uses
+breed resource 4 for these two defaults; that does not recover creature
+archetype regeneration.
+
+The `1006ea50` actor update runs regeneration when GameTime flag `+0x1d` is
+set. `GameTime_t::RunFunction` sets a one-second flag `+0x1c` and alternates
+`+0x1d` and `+0x1e` on those ticks; normal regeneration is therefore checked
+every two seconds. The actor's counter advances by two at each such check.
+This is not an independent timer restarted after each heal.
+
+For players, the health branch reads final interval 342 and delta 343. When
+RestModifier425 equals 25 it halves an interval above 1 using an integer
+right shift. If injured, enabled and `counter % interval == 0`, it applies:
+
+```
+health_gain = trunc(effective_BodyDevelopment152 / base_RestModifier425)
+ + final_HealDelta343
+health = min(final_health_stat1, current_health + health_gain)
+```
+
+The nano branch rounds final NanoInterval363 down to an even integer with
+`interval & ~1`. An interval of zero passes every check; otherwise it requires
+`counter % interval == 0`. When below maximum nano, or when the delta is
+negative, the change is:
+
+```
+nano_gain = trunc(effective_BodyDevelopment152 / base_RestModifier425)
+ + final_NanoDelta364
+nano214 = clamp(nano214 + nano_gain, 0, final_MaxNano221)
+```
+
+`10059bd0` implements that nano clamp. Both regeneration paths are disabled
+by actor flag `0x10` at `+0x11c`. The default RestModifier is 100 in
+`10072760`; value 25 changes both the integer skill contribution and health
+interval. The source explicitly uses Body Development in the nano gain as
+well. Substituting Nano Pool would change native behavior.
+
+Counter phase and odd intervals matter: an unmodified interval of 29 does
+not simply schedule one event every 29 seconds when tested against a counter
+that increases by two. An isolated idle-client probe showed health 20, 20, 23,
+23 and nano 3, 6, 9, 12 in snapshots roughly 30 seconds apart, while server
+health remained 20. This corroborates local prediction; it does not determine
+the initial counter phase or validate original-server correction cadence.
+Evidence is linked from the [reconstruction index](combat-client-reconstruction.md).
+The NPC update also contains
+separate combat-state/stat-519 branches and must not be reduced to the player
+formula. None of this establishes original server regeneration authority.
+
+## Bounded unresolved questions
+
+| Question | What was checked | Result and limit |
+| --- | --- | --- |
+| Attack versus defense hit probability | Weighted getters, attack-rating setter, attack/defense UI strings and queued result handling | Ratings recovered; no authoritative probability formula recovered in these paths. |
+| Normal damage scaling and critical amount | Item interpolation, damage cache, OE adjustment, damage tooltip, type getter and queued damage application | Fields and OE recovered; no demonstrated AR-to-damage multiplier, damage RNG or critical-outcome equation. |
+| Armor, added damage, reflect, shield and absorb order | Numeric stat push scan across all generated kkr C, followed by inspected damage/type/result paths; protocol report covers message handlers | No complete arithmetic/order trace. Generic data-driven accesses and other modules remain outside the negative claim. |
+| Critical chance | Same scan for candidate stats 379 and 391, plus inspected attack/defense and damage getters | No literal pushes for those two IDs in that scan; this does not prove their absence from dynamic item/effect logic. |
+| Martial Arts selecting fist QL | Item/template constructor, interpolation and unarmed attack-rating paths | Packed QL consumption recovered; no native MA-to-fist-QL selection recovered. |
+| Nano recharge and cost caps | Cast deadline, eligibility, interrupted-execution refund, recharge getter, nano resource update and range helper | Cast timing, cost multiplication, refund, pool clamp and range cap recovered. A complete recharge/cost reduction/cap chain remains unresolved here. |
+| Original server health and regeneration | Player foundation, breed/profession resources and local actor update | Client formulas recovered. Historical creature profiles, authoritative correction cadence and live regen confirmation remain unresolved. |
+
+The retained literal scan is
+`local/reports/combat-client-stat-constant-scan.json`. It deduplicates exact
+`push immediate` instruction addresses and found 108 armor candidates, 6
+reflect candidates, 16 shield candidates, 11 absorb candidates, 4 added-damage
+candidates, 0 critical candidates, 26 regeneration candidates, 63 initiative
+candidates and 98 offense/defense candidates. These are discovery counts,
+not all confirmed stat reads: immediate values can instead be lengths,
+opcodes or unrelated constants. Symbol names and negative search results
+must not be promoted into server rules without a concrete calculation trace.
diff --git a/docs/combat-npc-balance.md b/docs/combat-npc-balance.md
@@ -0,0 +1,71 @@
+# NPC balance evidence for 14.9.1
+
+The local wiki database provides useful weapon and behavior leads, but it does
+not supply a complete set of historical creature health, ratings and armor.
+The server's universal 100 HP and 5 damage remain prototype values.
+
+## Local wiki search
+
+Read-only source: `~/tmp/fandom-scraper/anarchyonline.db`, 879 pages,
+with HTML, plaintext, categories and last-touched metadata. The bounded search
+covered all page titles, the 77 pages categorized as Mobs, and numeric
+health/HP expressions throughout the plaintext. Equipment, player builds,
+pets and hypothetical combat examples must not become creature health records.
+
+The [Leets page](https://anarchyonline.fandom.com/wiki/Leets), last touched
+2010-04-25 in this scrape, identifies two Leet Bite weapons, 100% Martial Arts
+attack, 100% Evade Close defense, 1.75s/1.75s, melee damage and two-meter range.
+It also says weapon QL equals creature level. That is a useful community
+observation, not proof of the original 2003 server's template binding, skills,
+initiative or aggression setting. It gives no leet health value.
+
+Saved search evidence is in `local/reports/npc-balance-wiki-extract.json` and
+`npc-balance-wiki-candidates.json`. The scrape is small enough that failure
+to find a number here does not establish that no historical source exists.
+
+## Shipped Leet Bite records
+
+The matching resource database provides stronger evidence for the weapon
+endpoints. The catalog index digest is
+`46e5dc54af9358cc9bff05f4358e86af630e497bc677f361c133c88073b84d71`.
+Exact records are retained in `local/reports/leet-bite-1491-records.json`.
+
+| Templates | QL endpoints | Base damage | Critical bonus | Base attack/recharge |
+| --- | --- | --- | --- | --- |
+| LeetBite1, 120910 / 120911 | 1 / 400 | 4-8 / 94-406 | 4 / 55 | 175 / 175 centiseconds |
+| LeetBite2, 120913 / 120914 | 1 / 400 | 4-8 / 94-406 | 4 / 55 | 175 / 175 centiseconds |
+| RagingLeetBite, 171193 / 171200 | 1 / 400 | 12-21 / 585-1008 | 12 / 520 | 80 / 80 centiseconds |
+
+Damage stat IDs are minimum 284, maximum 285 and critical bonus 286. Delay
+294 is attack, 210 recharge, 287 range, and 436 damage type. All six endpoint
+records use range 2 and damage type 91 (MeleeAC). Section 12 weights Martial
+Arts 100 at 100%; section 13 weights Evade Close 155 at 100%. The two ordinary
+variants have different animation references (1034 and 1037), despite equal
+numeric endpoint values. Equip records 120912 and 120915 reference LEW1 and
+LEW2. The raging variant must not silently replace ordinary leet balance.
+
+These are weapon definitions, not complete final hit amounts. Actor attack
+rating, initiative, AggDef, armor, modifiers and outcome selection still matter.
+Likewise the presence of an Equip record does not establish which live spawn
+receives it, which hand/variant it uses, or whether the historical server had
+additional overrides. Applying 4-8 as a universal NPC damage roll would replace
+one unsupported rule with another.
+
+## Online search and limits
+
+The web search cross-checked the Leets page and searched exact leet health/HP
+terms and broader monster-health references. A
+[2018 Funcom forum discussion](https://forums.funcom.com/t/resource-for-finding-out-how-much-health-enemies-have/28577)
+recommends combat-log parsing and the game's Information Tool - Life and Nano
+Points for measuring live creature resources. These are concrete measurement
+routes, but modern measurements alone cannot establish 14.9.1 balance.
+
+Some current raid guides provide exact-looking health values, but their pages
+mix later encounters and equipment. Those numbers need dated provenance before
+they can enter this server's historical profiles. No verified ordinary-leet HP
+or full per-species 14.9.1 balance table was recovered in this pass.
+
+Next useful evidence is an original combat/inspection capture identifying
+species, level, equipped endpoint/QL, absolute resources and effective ratings.
+A damage log without regeneration, shields, overkill and encounter boundaries
+accounted for does not by itself recover maximum HP or base weapon damage.
diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md
@@ -0,0 +1,204 @@
+# Authoritative resources and editable stats
+
+Player health and nano now regenerate on the server using the recovered
+14.9.1 client arithmetic. Quiet clients receive absolute corrections every
+two seconds, so local prediction no longer accumulates independently of server
+state. This matches the recovered client rules; the unavailable original
+server's scheduler is not established by those rules.
+
+## Character data
+
+The existing character editor at `/users/<id>` includes a persistent `stats`
+section. All six abilities and four currently used combat skills are editable:
+
+```yaml
+stats:
+ strength: 10
+ agility: 10
+ stamina: 60
+ intelligence: 10
+ sense: 10
+ psychic: 120
+ martial_arts: 100
+ physical_initiative: 600
+ body_development: 200
+ nano_pool: 100
+```
+
+Skills here are trained/base values. Effective skill adds the integer ability
+contribution from the shipped resource type 1000204. Weights follow Strength,
+Agility, Stamina, Intelligence, Sense, Psychic:
+
+| Skill | Weights |
+| --- | --- |
+| Martial Arts 100 | 20,50,0,0,0,30 |
+| Physical Initiative 120 | 0,10,0,10,60,20 |
+| Body Development 152 | 0,0,100,0,0,0 |
+| Nano Pool 132 | 0,0,10,10,10,70 |
+
+Ability trickle is `trunc(weighted_sum * float32(.01) * .25)`. The native
+percentage is 0.009999999776482582, so replacing the expression with integer
+division by 400 changes exact integer boundaries. The example has effective
+Martial Arts 110, Physical Initiative 607, Body Development 214 and Nano Pool
+122. At level 1, Solitus and the current Soldier profession it
+produces 658 maximum HP, 380 maximum nano and one-second fist attack/recharge
+at centered AggDef. The client receives the base values and performs its own
+ability calculation.
+
+Weapon timing also preserves the native float constants and the intermediate
+float store before AggDef subtraction. At effective initiative 387 and AggDef
+-100, recharge truncates to 170 centiseconds; the algebraically simplified
+division would give 171. This boundary is covered by a regression test.
+
+Older profiles with no stats retain abilities 10 and these four base skills 5.
+Saving writes the explicit stats to `data/players/<id>/player.yaml`. Values
+survive profile edits, teleporting and restart; location saving still writes
+only `position.yaml`. Lowering resource maximums clamps current health/nano.
+Resources remain session state: restart initializes full health and zero nano.
+
+This does not implement native IP spending, profession selection, equipment
+modifiers or MA selecting fist QL. Other skills still use the existing client
+and fixture defaults. Increasing Martial Arts must not be presented as a
+complete server damage-scaling implementation while that calculation remains
+unresolved.
+
+## Recovery and replication
+
+The server checks each ready player once every two seconds. A per-client
+counter advances by two. The check uses the native single-precision reciprocal
+of 30 in the interval arithmetic, then truncates the result:
+
+```text
+percent = 200 while attacking, otherwise 100
+health_interval = max(1, trunc((30 - Stamina * float32(1/30)) * percent * float32(.01)))
+nano_interval = max(1, trunc((30 - Psychic * float32(1/30)) * percent * float32(.01))) & ~1
+rest = 25 sitting, otherwise 100
+if sitting and health_interval > 1: health_interval >>= 1
+health_gain = effective_BodyDevelopment / rest + breed_HealDelta
+nano_gain = effective_BodyDevelopment / rest + breed_NanoDelta
+```
+
+Integer division truncates. Health recovery requires the counter to be divisible
+by its interval. Nano recovery uses the same check, or every visit when its
+rounded interval is zero. Maximums clamp both resources. In this client the nano
+gain uses Body Development too; substituting Nano Pool changes the result.
+Exact sources and breed coefficients are in [client stats](combat-client-stats.md).
+
+For the old default Solitus stats, standing recovery is 3 HP at counter 58,
+and 3 nano at counters 28 and 56. Sitting halves the health interval from 29
+to 14. Attacking recalculates intervals to 59, with health at counter 118 and
+nano every 58. Stopping an attack changes the interval without restarting the
+counter. The edited example's standing interval is 27, not 28, because the
+native float reciprocal places the result just below the integer boundary.
+
+Dead, offline, loading and NPC characters do not receive this player recovery.
+A new connection resets the prediction counter and posture; stopping an attack
+or sitting does not. Late scheduler visits advance one native-style check,
+without replaying an offline/stalled backlog. The two-second deadline stays
+anchored to its original phase, so small scheduling delays do not accumulate.
+Historical NPC regeneration is a
+separate unresolved rule.
+
+Absolute health is sent only when neither the player nor an enemy targeting
+that player is attacking. StopFight flushes queued weapon outcomes before the
+correction can be sent. This prevents an absolute snapshot from pre-applying
+health damage that a later animation keyframe would subtract again. Quiet
+observers also receive corrected health; current nano is private to its owner.
+During combat, recovered regeneration advances authoritatively and the client
+predicts it; native animation timing and prediction phase can still temporarily
+differ from server state. The next quiet correction reconciles the display.
+
+## State and delivery ordering
+
+The state lock protects actors and current session ownership. The update lock
+is acquired before the state lock and covers each state change through its
+packet enqueue batch. Combat, recovery, movement, posture, joining, disconnects
+and zoning use this order. A joining actor's spawn is queued to existing
+observers before another update can announce that actor's combat or resources.
+Manual teleport snapshots and automatic portal selection keep this lock through
+their commit so an intervening profile edit cannot be overwritten by an older
+location-change snapshot.
+
+Every live world and chat connection starts one output writer before becoming
+visible to other sessions. Both use the same bounded writer implementation.
+Sending copies packet bytes, applies the recipient's protocol conversion
+and identity, then enqueues them in FIFO order under the connection lock. Socket
+writes run outside both world locks, with a five-second write deadline. Pending
+output is bounded at 8 MiB per connection plus one packet in flight; overflow
+or a failed/short write closes that connection. A stalled recipient therefore
+cannot hold up combat or regeneration for other players. Accepted output drains
+when the reader session ends; connection cleanup cancels combat and releases
+world locks before waiting for its writer.
+Forced disconnects instead discard pending output and wake the writer, which
+also owns socket shutdown. An in-flight write has the existing five-second
+deadline. Shared work and replacement sessions do not wait for a transport's
+close handshake.
+
+Profile edits save a candidate before changing the live actor. On success,
+both sides of the old fight receive StopFight in the original playfield before
+despawn and reconnect. Current resources are preserved up to their new maximums.
+A failed save leaves the actor, resources and fight intact. Replaced sessions
+cannot move, change posture or finish loading for the current session. A second
+world cookie on an initialized connection is rejected rather than resetting its
+actor or recovery clock.
+
+These are ordering guarantees for the basic PvE implementation. They do not
+establish historical NPC balance or a general action controller for equipment,
+special attacks and nanos.
+
+## Verification
+
+Tests cover default and edited abilities, standing/sitting/combat intervals,
+phase preservation when stopping attacks, minimum intervals, both resource
+maximums, incoming-only fights, owner/observer correction layouts, dead/loading/
+offline/NPC exclusions, native posture requests, FullCharacter base stats and
+profile persistence. The maintained package suite and race checks are recorded
+in the [reconstruction index](combat-client-reconstruction.md).
+
+Lifecycle regressions cover old-playfield cancellation, failed profile saves,
+replaced-session actions, duplicate world cookies, scheduler jitter and a live
+recipient that stops reading. Output tests cover FIFO order, independent packet
+ownership, concurrent producers, queue overflow, short writes, actual write
+timeouts and draining accepted output during shutdown. The queue/lifecycle
+stress selection passed 25 runs under the race detector, including 10,000
+packets from concurrent producers.
+Chat regressions also leave one recipient unread while checking that vicinity
+and Global messages still reach a healthy recipient and the sender can issue
+and receive its next request. Login and history enqueue before live delivery.
+A replacement-session regression deliberately blocks the old transport's Close
+operation and verifies that the new session can finish independently.
+These three isolation regressions passed 100 repetitions each after the shared
+writer and asynchronous disconnect changes.
+
+An isolated browser run with the default profile ended at server and client
+health 26/37 and nano 12/35 after two health recoveries. Earlier the same kind
+of probe left server health at 20 while the client healed itself. The new
+capture is `local/combat-smoke/regeneration-default-events.json`, with
+`multi-regen-fixed-{start,30,end}.png`. Client and temporary server were closed.
+
+The edited-profile probe verified the native ability/skill panels at effective
+Body Development 214, Nano Pool 122, Physical Initiative 607 and attack rating
+110. Standing server/client resources matched at 405/658 HP and 10/380 nano;
+sitting matched at 416/658 and 21/380 after an 11-point recovery. A sustained
+fight delivered 310 incoming damage and recovered 5 HP authoritatively during
+combat. Walking out of range stopped both actors; server and client then
+matched at 122/658 HP and 42/380 nano. No page errors were recorded.
+
+The capture and checked accounting are
+`local/combat-smoke/regeneration-variable-{events,summary}.json`. Screenshots
+include `multi-regen-variable-fixed-{resources,speed,idle-healed}.png`,
+`multi-regen-variable-sitting.png`, `multi-regen-variable-combat-recovery.png`
+and `multi-regen-variable-reconciled.png`. The fixture used a local 1000-HP
+creature to sustain the encounter; it is not evidence of historical leet
+balance. Test client and server were closed afterward.
+
+A further two-client probe joined an ongoing fight, then changed the attacker's
+base Body Development from 200 to 250 through the actual profile editor route.
+The observer received both participant spawns before combat replay, both
+StopFight messages before the player's despawn, and the player's new spawn
+after reconnect. Seventy incoming damage reduced the player from 405 to 335 HP.
+The edit preserved 335 HP and 10 nano while raising maximum HP from 658 to 808;
+the native display matched 335/808 HP and 10/380 nano. No page errors were
+recorded. Captures are `local/combat-smoke/lifecycle-{events,summary}.json`, with
+`multi-lifecycle-{joined,reconnected,observer}.png`. Both clients and the
+temporary server were closed after the probe.
diff --git a/docs/combat-rules.md b/docs/combat-rules.md
@@ -0,0 +1,185 @@
+# Combat rules and evidence
+
+Target: the shipped 14.9.1 client, before Shadowlands. Client code proves
+client calculations and message interpretation, not the unavailable original
+server's hit rolls, NPC profiles, or scheduling. Period player experiments are
+useful primary observations but are not Funcom specifications.
+
+The REA records cited below are exported locally in
+`local/reports/combat-rules-1491-evidence.json`.
+
+## Current implementation boundary
+
+Player fists now roll 3-5 normal damage from the shipped QL 1 record and use
+the native initiative/AggDef calculation below. Starting effective Physical
+Initiative is 7. The native slider request updates server stat 51, and that
+setting survives zoning and reconnection within the running server. A swing
+already scheduled keeps its deadline; subsequent phases use the new setting.
+Recharge survives stopping or switching targets, so those actions cannot
+accelerate the next swing. The first swing uses an attack phase without a
+random offset; the server's 250 ms tick can delay resolution.
+
+Player maximum/current health now follows the shipped breed, level, Body
+Development and Soldier title formula, including matching profession 60 and
+title 37 in FullCharacter. The default level 1 Solitus has 37 HP. See
+[starting stats](combat-starting-stats.md) for the resource values.
+
+Six abilities and four combat skills are now persistent, editable character
+data. Health, nano, attack timing and regeneration derive from those values
+and native ability trickle. Player recovery is authoritative, with absolute
+quiet corrections to reconcile the client's prediction. See
+[resource synchronization](combat-regeneration.md) for the rules and scope.
+
+The server still selects QL 1 regardless of MA skill, omits hit/critical
+rolls and armor, and uses NPC 100 health and 5 damage with 1s/1s timing.
+The uniform normal-damage roll is a reconstruction choice; the item establishes
+the endpoints, not the historical server's random distribution. The four-meter
+range approximates physical extents, and there is no server line-of-sight
+test. Equipment, nanos, specials, aggression/taunt AI, reclaim, loot, XP and
+respawn are not implemented. Reload revival is a local test convenience.
+These limitations prevent a claim of canonical combat balance.
+The [NPC balance search](combat-npc-balance.md) identifies authentic Leet Bite
+weapon endpoints, but does not establish historical creature HP or final damage.
+
+## Shipped unarmed weapon records
+
+The extracted database contains three records named `Martial Arts Item`:
+
+| ID | QL | Minimum | Maximum | Critical bonus | Attack | Recharge | Item range |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| 43712 | 1 | 3 | 5 | 3 | 125 cs | 125 cs | 2 |
+| 144745 | 100 | 25 | 60 | 50 | 125 cs | 125 cs | 2 |
+| 43713 | 500 | 65 | 280 | 500 | 145 cs | 145 cs | 2 |
+
+Sources: `server/gamedata/items/items_002.yaml` records 43712/43713 and
+`server/gamedata/items/items_065.yaml` record 144745. Stat IDs: minimum 286,
+maximum 285, critical bonus 284, attack ItemDelay 294, RechargeDelay 210,
+AttackRange 287, InitiativeType 440. Each record selects Physical Prowess
+Initiative 120, 100% Martial Arts 100 for attack, and 100% Evade Close Combat
+155 for defense.
+
+The QL 100 endpoint matters: interpolating directly between QL 1 and QL 500
+does not reproduce the three-point database curve. The
+[May 2002 player investigation](https://forums-archive.anarchy-online.com/showthread.php?24406-What-weapon-stats-are-my-Fists=)
+reports fist QL equal to half MA skill and identifies these three endpoints.
+The exact selection and odd-skill rounding have not been recovered from the
+client. No literal 43712/43713/144745 selector was found in the lifted client;
+the client receives QL and endpoint IDs from the server. Do not apply later
+profession-specific MA/Shade templates to this target.
+
+## Exact client timing calculations
+
+The original `anarchy-vanilla-14.9.1/kkr.dll` has SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+REA/Ghidra 12.1.2 recovered these functions:
+
+```text
+effectiveInit = init if init <= 1200
+effectiveInit = 1200 + (init - 1200) / 3 otherwise
+attackCs = max(100, ItemDelay + 75 - effectiveInit/6 - AggDef)
+rechargeCs = max(100, RechargeDelay + 75 - effectiveInit/3 - AggDef)
+```
+
+`FUN_1007ab40` computes attack; REA evidence
+`ev_21c1372bacdbc7004b457db2404aa2ed02280acc134e083eae1b7a9a40bda585`.
+`FUN_1007ac10` computes recharge; evidence
+`ev_f0a6eb43ce093bedd8441f5005121c5051f9c78730fae2652fe59a26e37079b6`.
+They use the weapon's InitiativeType and character AggDef stat 51 in getter
+mode 0. `FUN_1007aad0` and `FUN_1007aa30` truncate the resulting positive
+centiseconds through `_ftol` when setting client timers. This is distinct
+from rounding the interpolated weapon stats.
+
+AggDef is a direct integer contribution. At zero initiative, QL 1 fists give
+2.00/2.00 seconds at AggDef 0; 1.25/1.25 at AggDef 75; and the 1.00/1.00
+minimum at AggDef 100. AggDef -100 gives 3.00/3.00. Full aggression does not
+mean the midpoint 0. The client formula is continuous over the integer stat;
+it does not establish the eight-position slider quantization claimed by
+some later guides.
+
+`FUN_10072760` initializes base Martial Arts 100, Physical Initiative 120,
+and Body Development 152 to 5. Evidence:
+`ev_262150600e8d5205a324934ce17968bf1440814efc918e5344b3ad29103466e9`.
+`FUN_10073fa0` computes ability contribution as weighted abilities multiplied
+by `float32(.01)` and `.25`; callers truncate before adding to base skill.
+The native inexact percentage matters at integer boundaries. Evidence:
+`ev_a4aca3401a3fced81dd6fffbccb18d260de0511d1bef5ce01cbf5393180106f8`.
+With all six abilities 10, weights summing to 100 yield contribution 2 and
+total skill 7. Thus current untrained player Physical Initiative is 7,
+not 0. QL 1 fists at AggDef 0 then give 198 cs attack and 197 cs recharge
+after timer truncation, a nominal 3.95-second cycle.
+
+The algebraic timing description omits intermediate float rounding. The server
+now preserves the original float constants and the store before subtracting
+AggDef. For example initiative 387 at AggDef -100 gives 170 cs recharge,
+where simplifying to division by three would incorrectly give 171 cs.
+
+The stat agent independently read the matching database ability weights:
+record type 1000204, Martial Arts record 100 `(20,50,0,0,0,30)`, Physical
+Initiative record 120 `(0,10,0,10,60,20)`, Body Development record 152
+`(0,0,100,0,0,0)`, in Strength/Agility/Stamina/Intelligence/Sense/Psychic
+order. This agrees with the client formula without importing modern tables.
+
+`N3Msg_GetAggDef` at `0x1002b570` reads stat 51; `N3Msg_SetAggDef` at
+`0x1002b5b0` constructs and sends a server request. The UI's state needs to
+be carried by the server for these timing rules to matter.
+
+The nominal single-weapon cycle is attack plus recharge. Native startup
+`FUN_1007aa30` also applies an initial random timer offset. Exact historical
+server first-hit timing, network latency, tick rounding, and animation
+keyframe timing are not established by these formulas. An attack-phase
+first hit without that offset is an explicit reconstruction choice.
+
+## Exact client item interpolation
+
+`FUN_100f1200` loads the two server-selected endpoint templates and applies
+`FUN_100f00a0`. The combat-stat whitelist `FUN_100f0c80` includes 284, 285,
+286, 287, 294 and 210. For increasing, nonnegative endpoint values:
+
+```text
+value = low + trunc((QL - lowQL) * (high - low) / (highQL - lowQL) + 0.5)
+```
+
+Endpoints return their exact stored values. This is nearest rounding, not
+flooring the whole interpolated value. `FUN_100eff20` assembly evidence:
+`ev_8e74e096cabced73783a68d8f7822845dee9aa35efedfd48f6bca271bfae0bae`.
+The referenced `0x10170464` is the float 0.5, bytes `00 00 00 3f`;
+evidence `ev_d21e8be18d56033255409bba632b066eaf5f48b20aa646e2c6bc427c0294ff91`.
+
+## Range is not a two-meter center-distance test
+
+The item stat is 2, but `WeaponHolder` virtual method at `0x10078cb0`
+includes actor/target physical extents in its range check. It reads floats
+at `*(character + 0x188) + 0x30`, measures 3D center distance, and compares
+against effective item range plus those extents. Its outer check actually
+adds the actor extent twice and target extent once; confirmed in assembly
+`ev_9862c91fdfb306342e1a4bada390db357a4002667850e7704ed97713cc8510be`.
+The physical meaning and construction of these extents remain unresolved.
+
+`FUN_100aae10` computes effective item range as the truncated value of
+`range * (1 + WeaponRangeIncreaser380 / 100)`, capped at 40. Its assembly is
+`ev_caffa5ac96df90e71084d5f068e035270b37d97a28beb95abb889dd010d2527d`.
+A fixed four-meter center limit is an approximation; simply replacing it
+with two meters would not match the shipped client's range calculation.
+
+## Damage and unresolved server rules
+
+The
+[July 2002 damage experiments](https://forums-archive.anarchy-online.com/printthread.php?page=1&pp=20&t=36008)
+report attack-rating scaling `1 + AR/400`, critical base damage equal to
+maximum plus critical bonus, damage additions after scaling, and armor
+reducing damage by one point per ten AC. They explicitly say the evade
+probability formula is unknown. This supports the broad pre-Shadowlands
+damage model, but not exact integer ordering, minimum-damage treatment in
+every case, hit probability, critical probability, or NPC attack stats.
+
+The
+[May 2003 timing discussion](https://forums-archive.anarchy-online.com/showthread.php?138367-Weapon-Attack-Recharge=)
+also records initiative reducing attack by 1 second and recharge by 2
+seconds per 600, with separate one-second floors. An earlier reply gives
+conflicting recharge advice; the shipped implementation above resolves it.
+
+Do not label fixed NPC damage, NPC health, always-hit attacks, arbitrary
+critical rolls, missing armor/reflect behavior, resurrection on reload, or
+respawn on server restart as canonical. NPC combat profiles, exact hit/crit
+rolls, line of sight, player death/reclaim and progression need separate
+evidence and implementation.
diff --git a/docs/combat-starting-stats.md b/docs/combat-starting-stats.md
@@ -0,0 +1,114 @@
+# Combat starting stats in 14.9.1
+
+These values come from the selected original 14.9.1 client and its resource
+database. They establish client calculations and defaults, not historical
+server NPC stats or a complete character creation implementation.
+
+Original addresses below use kkr.dll's image base `0x10000000`; generated
+symbols use the relocated base `0x36000000`.
+
+| Finding | First-party evidence |
+| --- | --- |
+| Martial Arts (100) defaults to base 5 | `kkr.dll!FUN_10072760`, store at `0x1007276d`; generated `sub_36072760` in `client/game/kkr.dll/lifted-0034.c` writes 5 to default-stat array offset `100 * 4`. |
+| Physical Initiative (120) defaults to base 5 | Same function, store at `0x1007283c`, array offset `120 * 4`. |
+| Body Development (152) defaults to base 5 | Same function, store at `0x1007295c`, array offset `152 * 4`. |
+| Agg/Def (51) defaults to 0 | Same function, store at `0x1007308d`, array offset `51 * 4`. This is the center of the signed -100 to 100 range. |
+| Effective skill includes ability trickle | `FUN_10075c60` adds the base skill to the integer conversion of `FUN_10073fa0(skill, 1)`. Generated symbols are in `lifted-0034.c`. |
+| Trickle is weighted abilities divided by 4 | `FUN_10073fa0` multiplies the sum of ability values times integer percentages by 0.01 and 0.25. `FUN_100ec8e0` supplies the weights. |
+
+The six ability weights are ordered Strength, Agility, Stamina, Intelligence,
+Sense, Psychic. Resource type **1000204** contains six little-endian signed
+32-bit integers per skill:
+
+| Resource identity | Weights |
+| --- | --- |
+| 100, Martial Arts | 20, 50, 0, 0, 0, 30 |
+| 120, Physical Initiative | 0, 10, 0, 10, 60, 20 |
+| 152, Body Development | 0, 0, 100, 0, 0, 0 |
+
+`FUN_100ecfd0` requests resource type `0x000f430c` (1000204), and
+`FUN_100ed060` reads the six integers. These generated functions are in
+`client/game/kkr.dll/lifted-0068.c`. The records can be read with
+`tools/data/ao_database.py` from
+`anarchy-vanilla-14.9.1/cd_image/data/db/ResourceDatabase.dat` and its index.
+
+For the local character fixture's six abilities of 10, each of these skills
+receives 2 points of trickle after integer conversion: base 5 plus trickle 2
+gives **7 Martial Arts, 7 Physical Initiative, and 7 Body Development**.
+Abilities of 10 are a local fixture choice; this does not establish the
+historical starting abilities of a newly created character.
+
+The percentage multiplication uses float constant `0x10170894`, value
+0.009999999776482582, followed by exactly 0.25 at `0x10170e78`. Thus the exact
+expression is `trunc(weighted_sum * float32(.01) * .25)`, not integer division
+by 400 at boundary values. An edited-stat browser probe with Stamina 60 and
+base Body Development 200 gives effective Body Development 214, not 215;
+the level 1 Solitus maximum is 658 HP. Constant bytes are retained in
+`local/reports/combat-trickle-float-constants.json`. The
+[editable stats implementation](combat-regeneration.md) preserves that arithmetic.
+
+## Health foundation
+
+`kkr.dll!FUN_10075910` calculates health from breed data, profession/title data,
+level, and effective Body Development. For a level 1 Solitus Soldier at title
+level 1:
+
+```
+maximum health = 10 + level * (6 + 0) + Body Development * 3
+ = 10 + 1 * 6 + 7 * 3
+ = 37
+```
+
+Resource type **1000203**, identity **1** (Solitus), contains the six
+little-endian integers `10, 6, 3, 10, 4, 3`. `FUN_100e4840` maps these to stats
+600 through 605, respectively. The first three are base health, health per
+level, and health per Body Development. Generated source is
+`client/game/kkr.dll/lifted-0065.c`.
+
+Resource type **1000200**, identity **1** (Soldier), begins with the first title
+row `1, 0, 0, 4000`. The additional health contribution for this row is 0.
+`FUN_100e60f0` reads these rows and `FUN_100e6050` selects the title row;
+generated source is `client/game/kkr.dll/lifted-0066.c`.
+
+The value 37 is conditional on the local fixture above. Runtime browser
+inspection confirmed attack rating 7 and maximum health 37. The server now
+uses this formula for players and sends matching profession (60), title (37),
+side (33), and fatness (47) stats. This fixes the observed 100/37 HP display.
+Current health is clamped when profile edits lower the maximum.
+
+The first three coefficients for breed resources 1 through 5 are:
+
+| Breed | Base | Per level | Per Body Development |
+| --- | --- | --- | --- |
+| Solitus (1) | 10 | 6 | 3 |
+| Opifex (2) | 15 | 5 | 3 |
+| Nanomage (3) | 10 | 5 | 2 |
+| Atrox (4) | 25 | 6 | 4 |
+| Resource 5 | 15 | 8 | 6 |
+
+Missing breed records use 2 for each coefficient in `FUN_100e4780`; this is
+a client fallback, not a creature combat profile. Soldier resource 1000200/1
+has six title rows: starting levels 1, 15, 50, 100, 150 and 190, with health
+bonuses per level 0, 1, 2, 3, 4 and 5 respectively. The client reads stored
+TitleLevel 37. The server supplies the title corresponding to level, so the
+same health formula applies on both ends. Levels above 200 remain a local
+extension. This calculation does not establish historical starting abilities,
+creature health, regeneration, death recovery, or progression.
+
+## Agg/Def slider request
+
+`n3EngineClientAnarchy_t::N3Msg_SetAggDef`, original `0x1002b5b0`, creates
+`SetAggDefIIR_t` through `FUN_10080f10`. Its class-name XOR key is
+**`0x76793f0d`**. The same four-byte string-XOR calculation reproduces the known
+`AttackIIR_t` and `StopFightIIR_t` keys.
+
+The subclass payload is one signed 32-bit integer, in the protocol's big-endian
+order, following the common N3 prefix. `FUN_10081050` reads that integer
+and validates **-100 through 100**. `FUN_10080ff0` applies it to stat **51**.
+These functions are in `client/game/kkr.dll/lifted-0038.c`; the setter is in
+`lifted-0016.c`.
+
+This slider request is distinct from the generic `SetStat` message
+`0x6e5f566e`. The opcode and layout above are established by static client
+evidence. Chromium/WASM additionally emitted this exact opcode with value 0
+on login; the isolated browser packet log provides the separate runtime check.
diff --git a/docs/protocol.md b/docs/protocol.md
@@ -558,3 +558,116 @@ connection; it cannot claim a browser character. Original account encryption,
private groups, buddy state and channel subscription preferences are not
implemented. Tests cover malformed frames, identity spoofing, distance and
playfield filtering, and identical complete/fragmented WebSocket streams.
+
+## Combat in 14.9.1
+
+These layouts come from static inspection of shipped `kkr.dll`, SHA256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+The retained REA bundle is `local/reports/combat-1491-evidence.json`.
+Addresses below use the original image base `0x10000000`; the translated C
+uses `0x36000000`. All listed body integers are big-endian uint32 unless
+specified otherwise, and bodies exclude the common IIR prefix.
+
+| Message | Key | Body |
+| --- | --- | --- |
+| AttackIIR_t | `0x28494070` | Target identity, byte action |
+| StopFightIIR_t | `0x4a41203e` | Four-byte boolean |
+| SetAggDefIIR_t | `0x76793f0d` | Signed int32, -100 through 100 |
+| AttackInfoIIR_t | `0x46002f16` | Damage, ammunition, weapon slot, target identity, death reason, result |
+| HealthDamageIIR_t | `0x3710256c` | Current health, signed health change, damage type, death reason |
+| StatIIR_t | `0x2b333d6e` | Stat ID, value |
+
+Attack uses the header identity as attacker. Its activation selects the body
+target in the weapon controller; the action byte is read but not consulted.
+Readers/writers are `0x10087700`/`0x10087740`, activation `0x100876a0`.
+StopFight uses the header actor and invokes controller stop; reader/writer
+`0x10084330`/`0x10084310`, activation `0x100842f0`. The controller's stop
+function `0x10079250` resolves queued hits before clearing the fighting target.
+
+SetAggDef is sent by `N3Msg_SetAggDef` at `0x1002b5b0`; serializer
+`0x10081050` reads one signed integer and activation `0x10080ff0` applies
+stat 51. The server acknowledges it through StatIIR_t. Runtime Chromium/WASM
+captured the same request key on login. Native initiative/AggDef timings,
+item damage records and player health calculations are documented separately
+in [combat rules](combat-rules.md) and [starting stats](combat-starting-stats.md).
+
+AttackInfo's 28-byte body is read by `0x100aec00`, activated by `0x100aecb0`,
+and dispatched by `0x1007a660`. Slot 0 selects the unarmed weapon. Its damage
+queue resolves in `0x100ab5a0`, producing weapon combat text and subtracting
+damage from the target's health stat 27. Result 4 is success and 5 is critical
+success. Death reason 4 selects weapon death in `0x10072340` and sets health
+to zero. An immediate authoritative health update can race this queued
+subtraction, so each swing should not also send the already-reduced health.
+
+The corpse pose needs a separate `CharacterActionIIR_t` (`0x5e477770`) for
+the victim. Its body is five uint32 values: `99, 0, 0, 0, animationKey`.
+Reader `0x1007d5c0` reads the action and two identities; activation
+`0x1007d640` dispatches to the character's action handler `0x1006fa30`.
+Action 99 reaches `0x10070327`, sets visual flag `0x10`, writes the final
+body word to stat 387 (`DieAnim`), and refreshes the visual state. The death
+state constructor `0x10085d60` reads that stat at `0x10085ecc` and requests
+the animation. The animation registry `0x100dda40` maps key 500 to
+`die-knees` and key 503 to `die-shot` (`0x100de20c` and `0x100de2a2`).
+The local implementation sends 500 for players and 503 for NPCs after
+StopFight has flushed the killing hit. It also supplies the corpse action
+after a dead character's spawn for an observer joining later. Health zero
+and AttackInfo's death reason establish health/text but do not select this
+corpse pose by themselves.
+
+HealthDamage uses the header victim. Negative health changes produce nano
+damage text; change zero silently synchronizes health. The damage-type mapping
+in `0x10039cf0` assigns melee to 91. Reader `0x100b09c0` and activation
+`0x100b0a50` establish the 16-byte layout. Stat has no count prefix:
+`0x100b2e10` reads exactly two integers and `0x100b2e60` applies the value.
+Updating health through Stat also produces nano/heal text for a nonzero delta.
+
+SCFU's ordinary uint32 health fields are maximum health then current health.
+Only flag `0x4000` changes the second field to a byte deficit. Reader
+`0x10082da0` and initialization `0x10082ad0` establish those semantics.
+Flag `0x100` supplies weapon templates after the final encoded list, following
+the three byte-counted appearance groups. A single template list is uint32
+2018 followed by low template ID, high template ID, slot and quality.
+`0x10076740` reads those four fields, `0x100767d0` reads the encoded list, and
+`0x1007b9a0` installs template slot 100 into weapon-controller slot 0.
+The extracted `Martial Arts Item` templates are IDs 43712/43713; quality 1
+provides the basic unarmed presentation without an inventory item.
+
+NPC SCFU also needs flag `0x2` to set stat 194 (`InPlay`) in initialization
+`0x10082ad0`. Tab selection through `N3Msg_GetCloseTarget` at `0x10026320`
+skips candidates whose InPlay stat is zero (`0x100264c5` through
+`0x100264d3`). This check is retained in
+`client/game/kkr.dll/lifted-0015.c`, function `sub_36026320`.
+The same function compares stat 33 (`Side`): ordinary enemy targeting excludes
+the player's own side, while its friendly-targeting mode requires that side.
+Appearance's low two bits become the side field in the 14.9.1 packed value;
+NPC side 0 and player side 2 satisfy the enemy-targeting comparison.
+The local PvE implementation assigns side 3 to creature NPCs when converting
+SCFU for 14.9.1, preserving their remaining appearance fields and human NPC
+factions. This enables normal enemy Tab selection against the default player;
+it is an explicit local combat policy, not a recovered historical faction.
+
+Core packet evidence:
+`ev_8687fd6e603c302e4ab3fee7b405ea3e5c9a615e0f56bff18dd20ff949da8d4c`.
+Stat and stop-controller evidence:
+`ev_613804f50c4ecd636e465f8b8b36fa81063f090d7cd60fe8bfda4aea09da8b57`.
+Damage resolution and text evidence:
+`ev_eb20a4ca58374e72da2f8326ccfd51f83f77758fcff01da9626fa192429b926d`.
+Weapon templates and death evidence:
+`ev_064ab8210635946d089794871b617ead5688e414b4d0ad822d928d28c1ca02e3`.
+Corpse action, visual-state transition and Tab targeting evidence:
+`ev_991bfd8cce8e805d213a8eacd30750d0ec75ec71d96721a722e4ea4eff928c7a`.
+Animation-key registry evidence:
+`ev_1c9b57d5fe06d2a1b8e6f723ca8bf6f13f779bbcb65b23c83e160e79d473a1b0`.
+These are decompiled static observations. Isolated Chromium/WASM checks with
+the published client additionally verified Tab selection, Q attack/stop,
+unarmed punches and kicks, melee damage text, health bars, NPC retaliation,
+the NPC corpse pose and the player's white death fade. A ten-hit encounter
+ended with NPC health 0 and player health 55. Separate weakened-player and
+weakened-NPC fixtures verified player death after stopping attacks and the
+native refusal to attack a corpse. Screenshots and state logs are retained
+under `local/combat-smoke/`: `unarmed-hit.png`, `npc-corpse.png`,
+`player-death.png` and the corresponding event JSON files. The inspected
+`game.wasm.br` SHA256 was
+`d4c293854c1e030f0f2f9036fbd3086d4d22310a694b626e97bac3d18aa5a27c`.
+These checks establish the tested client presentation, not historical combat
+balance, per-species weapon templates, corpse inventories or resurrection rules.
diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go
@@ -8,6 +8,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
+ "net"
"net/http"
"net/http/httptest"
"testing"
@@ -415,3 +416,90 @@ func TestBrowserDisconnectedStreamExpiresAndRejectsResume(t *testing.T) {
t.Fatalf("expired stream was accepted: %v", err)
}
}
+
+func TestExpiredBrowserWorldSessionRemovesPlayerFromOtherClients(t *testing.T) {
+ world := newTestServer(t)
+ closeTestBrowserStreams(t, world)
+ world.newCharacter()
+ world.newCharacter().browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("visitor-token")))
+ observer := connectZoningClient(t, world, false)
+ host := httptest.NewServer(http.HandlerFunc(world.browserWorld))
+ defer host.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ socket, _, err := websocket.Dial(ctx, host.URL, &websocket.DialOptions{
+ HTTPHeader: http.Header{"Cookie": {"ao_client=visitor-token"}}, Subprotocols: []string{"ao-stream-v1"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer socket.CloseNow()
+ if err := socket.Write(ctx, websocket.MessageText, []byte(`{"stream":"00000000-0000-0000-0000-000000000002","received":"0","acknowledged":"0"}`)); err != nil {
+ t.Fatal(err)
+ }
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0})
+ if err := socket.Write(ctx, websocket.MessageBinary, append(make([]byte, 8), cookie...)); err != nil {
+ t.Fatal(err)
+ }
+ spawn, err := readPacket(observer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(spawn[20:24]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:32]) != 2 {
+ t.Fatalf("observer did not receive browser player: %x", spawn)
+ }
+ world.mutex.Lock()
+ client := world.clients[2]
+ world.mutex.Unlock()
+
+ socket.CloseNow()
+ for {
+ client.stream.mutex.Lock()
+ detached := client.stream.expiry != nil
+ if detached {
+ // Advance the reconnect grace period without waiting two minutes.
+ client.stream.expiry.Reset(0)
+ }
+ client.stream.mutex.Unlock()
+ if detached {
+ break
+ }
+ select {
+ case <-ctx.Done():
+ t.Fatal("world stream did not detach")
+ case <-time.After(time.Millisecond):
+ }
+ }
+ despawn, err := readPacket(observer)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Join after expiry to check that the saved character is not spawned again.
+ world.newCharacter()
+ late, connection := net.Pipe()
+ defer late.Close()
+ late.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ if _, err := late.Write(systemPacket(0x1b, []byte{0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0})); err != nil {
+ t.Fatal(err)
+ }
+ initial := readWorldUpdates(t, late)
+ if _, err := readPacket(observer); err != nil {
+ t.Fatal(err)
+ }
+
+ if binary.BigEndian.Uint32(despawn[20:24]) != 0x36510078 || binary.BigEndian.Uint32(despawn[28:32]) != 2 {
+ t.Fatalf("expired player was not removed: %x", despawn)
+ }
+ for _, packet := range initial {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[28:32]) == 2 {
+ t.Fatal("new observer received expired player")
+ }
+ }
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.clients[2] != nil || world.characters[2] == nil {
+ t.Fatal("expiry should remove the connection and retain the saved character")
+ }
+}
diff --git a/server/chat.go b/server/chat.go
@@ -8,14 +8,12 @@ import (
"log"
"net"
"strings"
- "sync"
- "time"
)
type chatClient struct {
+ clientOutput
conn net.Conn
stream *browserStream
- mutex sync.Mutex
id uint32
}
@@ -63,23 +61,7 @@ func (client *chatClient) send(packet []byte) error {
}
func (client *chatClient) send_locked(packet []byte) error {
- // Bound a slow recipient without holding the shared world-state lock.
- if err := client.conn.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
- return err
- }
- for len(packet) != 0 {
- written, err := client.conn.Write(packet)
- if err != nil {
- client.conn.Close()
- return err
- }
- if written == 0 {
- client.conn.Close()
- return io.ErrShortWrite
- }
- packet = packet[written:]
- }
- return nil
+ return client.enqueue_locked(client.conn, append([]byte(nil), packet...))
}
func chatNamePacket(id uint32, name string) []byte {
@@ -111,7 +93,7 @@ func (server *server) initializeChat(client *chatClient, id uint32) error {
history, err := server.chatHistory_locked(id)
server.chatLogMutex.Unlock()
if previous != nil {
- previous.conn.Close()
+ previous.disconnect(previous.conn)
}
if err != nil {
log.Printf("Restore chat history for character %d: %v", id, err)
@@ -132,7 +114,8 @@ func (server *server) initializeChat(client *chatClient, id uint32) error {
}
func (server *server) serveChatClient(client *chatClient) error {
- defer client.conn.Close()
+ client.startWriter(client.conn)
+ defer client.finishWriter()
defer func() {
server.mutex.Lock()
if server.chats[client.id] == client {
diff --git a/server/chat_output_test.go b/server/chat_output_test.go
@@ -0,0 +1,70 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func TestChatSlowRecipientDoesNotBlockVicinityDelivery(t *testing.T) {
+ world := chatTestServer(t)
+ alice := loginChatTest(t, world, 1)
+ bob := loginChatTest(t, world, 2)
+ done := make(chan struct{})
+ t.Cleanup(func() { alice.Close(); bob.Close(); <-done })
+
+ go func() { world.sendVicinity(1, 0, "hello"); close(done) }()
+
+ select {
+ case <-done:
+ case <-time.After(250 * time.Millisecond):
+ t.Fatal("a recipient that stopped reading blocked vicinity delivery")
+ }
+ for _, expected := range []uint16{20, 34} {
+ kind, _, err := readChatPacket(alice)
+ if err != nil || kind != expected {
+ t.Fatalf("healthy recipient: kind=%d expected=%d error=%v", kind, expected, err)
+ }
+ }
+}
+
+func TestChatSlowRecipientDoesNotBlockGlobalDeliveryOrSender(t *testing.T) {
+ world := chatTestServer(t)
+ world.characters[3] = &character{id: 3, name: "Carol", playfield: 710}
+ world.clients[3] = &worldClient{id: 3, ready: true}
+ alice := loginChatTest(t, world, 1)
+ bob := loginChatTest(t, world, 2)
+ carol := loginChatTest(t, world, 3)
+ message := binary.BigEndian.AppendUint32([]byte{0x87}, 1)
+ message = appendChatString(appendChatString(message, "hello"), "")
+ ping := chatPacket(100, []byte{1, 2, 3})
+ done := make(chan error, 1)
+ t.Cleanup(func() { alice.Close(); bob.Close(); carol.Close() })
+
+ go func() {
+ _, err := alice.Write(append(chatPacket(65, message), ping...))
+ done <- err
+ }()
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(250 * time.Millisecond):
+ t.Fatal("a slow recipient blocked the sender's next request")
+ }
+ for _, expected := range []uint16{20, 65} {
+ kind, _, err := readChatPacket(carol)
+ if err != nil || kind != expected {
+ t.Fatalf("healthy recipient: kind=%d expected=%d error=%v", kind, expected, err)
+ }
+ }
+ for _, expected := range []uint16{20, 65, 100} {
+ kind, body, err := readChatPacket(alice)
+ if err != nil || kind != expected || kind == 100 && !bytes.Equal(body, []byte{1, 2, 3}) {
+ t.Fatalf("sender response: kind=%d expected=%d body=%x error=%v", kind, expected, body, err)
+ }
+ }
+}
diff --git a/server/client_output.go b/server/client_output.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "sync"
+ "time"
+)
+
+type clientOutput struct {
+ mutex sync.Mutex
+ outgoing [][]byte
+ outgoingBytes int
+ writeWake chan struct{}
+ writeDone chan struct{}
+ writeClosed bool
+}
+
+func (client *clientOutput) startWriter(conn net.Conn) {
+ // Start once, before this connection is published to other sessions.
+ client.writeWake = make(chan struct{}, 1)
+ client.writeDone = make(chan struct{})
+ go client.writePackets(conn)
+}
+
+func (client *clientOutput) finishWriter() {
+ client.mutex.Lock()
+ client.writeClosed = true
+ select {
+ case client.writeWake <- struct{}{}:
+ default:
+ }
+ client.mutex.Unlock()
+ <-client.writeDone
+}
+
+func (client *clientOutput) disconnect(conn net.Conn) {
+ client.mutex.Lock()
+ defer client.mutex.Unlock()
+ // Standalone protocol fixtures have no writer; live sessions start one first.
+ if client.writeWake == nil {
+ conn.Close()
+ return
+ }
+ client.discard_locked()
+}
+
+func (client *clientOutput) discard_locked() {
+ // The writer owns socket shutdown, including any transport close handshake.
+ client.writeClosed = true
+ client.outgoing = nil
+ client.outgoingBytes = 0
+ select {
+ case client.writeWake <- struct{}{}:
+ default:
+ }
+}
+
+func writeClientPacket(conn net.Conn, packet []byte) error {
+ if err := conn.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
+ return err
+ }
+ count, err := conn.Write(packet)
+ if err == nil && count != len(packet) {
+ return io.ErrShortWrite
+ }
+ return err
+}
+
+func (client *clientOutput) enqueue_locked(conn net.Conn, packet []byte) error {
+ // The caller holds mutex and transfers ownership of the packet bytes.
+ // Standalone protocol fixtures have no writer; live sessions start one first.
+ if client.writeWake == nil {
+ return writeClientPacket(conn, packet)
+ }
+ if client.writeClosed {
+ return net.ErrClosed
+ }
+ // Bound queued bytes just as the browser transport bounds retained output.
+ if client.outgoingBytes+len(packet) > 8*1024*1024 {
+ client.discard_locked()
+ return fmt.Errorf("client output queue full")
+ }
+ client.outgoing = append(client.outgoing, packet)
+ client.outgoingBytes += len(packet)
+ select {
+ case client.writeWake <- struct{}{}:
+ default:
+ }
+ return nil
+}
+
+func (client *clientOutput) writePackets(conn net.Conn) {
+ defer func() {
+ client.mutex.Lock()
+ client.writeClosed = true
+ client.outgoing = nil
+ client.outgoingBytes = 0
+ client.mutex.Unlock()
+ conn.Close()
+ close(client.writeDone)
+ }()
+
+ // One writer preserves packet order without holding shared server locks on I/O.
+ for range client.writeWake {
+ for {
+ client.mutex.Lock()
+ if len(client.outgoing) == 0 {
+ closed := client.writeClosed
+ client.mutex.Unlock()
+ if closed {
+ return
+ }
+ break
+ }
+ packet := client.outgoing[0]
+ client.outgoing[0] = nil
+ client.outgoing = client.outgoing[1:]
+ client.outgoingBytes -= len(packet)
+ client.mutex.Unlock()
+ if err := writeClientPacket(conn, packet); err != nil {
+ log.Printf("Client output: %v", err)
+ return
+ }
+ }
+ }
+}
diff --git a/server/combat.go b/server/combat.go
@@ -0,0 +1,286 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "log"
+ "math/rand/v2"
+ "sort"
+ "time"
+)
+
+func attackPacket(attacker, target uint32) []byte {
+ body := binary.BigEndian.AppendUint32(nil, 50000)
+ body = binary.BigEndian.AppendUint32(body, target)
+ body = append(body, 1)
+ return n3Packet(0x28494070, 50000, attacker, body)
+}
+
+func stopFightPacket(attacker uint32) []byte {
+ return n3Packet(0x4a41203e, 50000, attacker, []byte{0, 0, 0, 1})
+}
+
+func (server *server) handleCombat(client *worldClient, body []byte) error {
+ key := binary.BigEndian.Uint32(body)
+ if key == 0x28494070 && len(body) < 25 || (key == 0x4a41203e || key == 0x76793f0d) && len(body) < 20 {
+ return fmt.Errorf("short combat message")
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ player := server.characters[client.id]
+ if server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 {
+ server.mutex.Unlock()
+ return nil
+ }
+
+ updates := make(map[*worldClient][][]byte)
+ if key == 0x76793f0d {
+ // SetAggDefIIR_t carries one signed integer in the range -100..100.
+ value := int32(binary.BigEndian.Uint32(body[16:20]))
+ if value >= -100 && value <= 100 {
+ player.aggDef = value
+ stats := binary.BigEndian.AppendUint32(nil, 51)
+ stats = binary.BigEndian.AppendUint32(stats, uint32(value))
+ updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, player.id, stats))
+ }
+ } else if key == 0x4a41203e || binary.BigEndian.Uint32(body[20:24]) == 0 {
+ server.stopAttack_locked(player, updates)
+ } else {
+ // Only visible creatures participate in this initial unarmed PvE loop.
+ target := server.characters[binary.BigEndian.Uint32(body[20:24])]
+ now := time.Now()
+ if binary.BigEndian.Uint32(body[16:20]) == 50000 && target != nil && target.npc &&
+ target.appearance>>4&7 == 6 && client.npcs[target.id] && target.health > 0 &&
+ target.playfield == player.playfield && server.combatInRange_locked(player, target, now) {
+ server.startAttack_locked(player, target, now, updates)
+ } else {
+ if player.fighting == 0 {
+ updates[client] = append(updates[client], stopFightPacket(player.id))
+ } else {
+ server.stopAttack_locked(player, updates)
+ }
+ }
+ }
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+ return nil
+}
+
+func unarmedDelays(initiative, aggDef int32) (time.Duration, time.Duration) {
+ // kkr.dll FUN_1007ab40/FUN_1007ac10, QL 1 fist ItemDelay/RechargeDelay 125.
+ effective := float64(initiative) * 0.5
+ if initiative > 1200 {
+ effective = 600 + float64(initiative-1200)*float64(float32(1.0/6))
+ }
+ // Native float stores precede AggDef subtraction and centisecond truncation.
+ attack := float64(float32(200-effective*float64(float32(1.0/3)))) - float64(aggDef)
+ recharge := float64(float32(200-effective*float64(float32(2.0/3)))) - float64(aggDef)
+ return time.Duration(max(100, int(attack))) * 10 * time.Millisecond, time.Duration(max(100, int(recharge))) * 10 * time.Millisecond
+}
+
+func (character *character) attackDelays() (time.Duration, time.Duration) {
+ if character.npc {
+ return time.Second, time.Second
+ }
+ stats := character.baseStats()
+ initiative := stats.effectiveSkill(stats.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20})
+ return unarmedDelays(int32(initiative), character.aggDef)
+}
+
+func (character *character) titleLevel() uint32 {
+ title := uint32(1)
+ for _, threshold := range []uint16{15, 50, 100, 150, 190} {
+ if character.level >= threshold {
+ title++
+ }
+ }
+ return title
+}
+
+func (character *character) maximumHealth() uint32 {
+ if character.npc {
+ return 100
+ }
+ // kkr.dll FUN_10075910; breed resources 1000203, Soldier titles 1000200/1.
+ stats := [8][3]uint32{{2, 2, 2}, {10, 6, 3}, {15, 5, 3}, {10, 5, 2}, {25, 6, 4}, {15, 8, 6}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7]
+ base := character.baseStats()
+ bodyDevelopment := base.effectiveSkill(base.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0})
+ return stats[0] + uint32(character.level)*(stats[1]+character.titleLevel()-1) + bodyDevelopment*stats[2]
+}
+
+func (character *character) maximumNano() uint32 {
+ // kkr.dll FUN_10075910; Soldier title rows contribute no extra nano.
+ stats := [8][3]uint32{{2, 2, 2}, {10, 4, 3}, {10, 3, 3}, {15, 5, 4}, {8, 2, 2}, {50, 2, 1}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7]
+ base := character.baseStats()
+ nanoPool := base.effectiveSkill(base.NanoPool, [6]uint32{0, 0, 10, 10, 10, 70})
+ return stats[0] + uint32(character.level)*stats[1] + nanoPool*stats[2]
+}
+
+func (server *server) combatInRange_locked(attacker, target *character, now time.Time) bool {
+ first, second := attacker.position, target.position
+ if !attacker.npc {
+ first = predictedPosition_locked(attacker, server.clients[attacker.id], now)
+ }
+ if !target.npc {
+ second = predictedPosition_locked(target, server.clients[target.id], now)
+ }
+ x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2]
+ return x*x+y*y+z*z <= 4*4
+}
+
+func (server *server) startAttack_locked(attacker, target *character, now time.Time, updates map[*worldClient][][]byte) {
+ // Repeated requests must not restart or accelerate the attack clock.
+ if attacker.fighting == target.id {
+ return
+ }
+ attacker.fighting = target.id
+ attacker.nextAttack = now
+ if attacker.nextAttack.Before(attacker.rechargeUntil) {
+ attacker.nextAttack = attacker.rechargeUntil
+ }
+ attack, _ := attacker.attackDelays()
+ attacker.nextAttack = attacker.nextAttack.Add(attack)
+ server.fighting[attacker.id] = attacker
+ if attacker.roaming != nil && attacker.roaming.moving {
+ attacker.roaming.moving = false
+ server.queueCombat_locked(updates, attacker, attacker, npcMovementPacket(attacker, 2))
+ }
+ server.queueCombat_locked(updates, attacker, target, attackPacket(attacker.id, target.id))
+}
+
+func (server *server) stopAttack_locked(attacker *character, updates map[*worldClient][][]byte) {
+ if attacker.fighting == 0 {
+ delete(server.fighting, attacker.id)
+ return
+ }
+ attacker.fighting = 0
+ attacker.nextAttack = time.Time{}
+ delete(server.fighting, attacker.id)
+ server.queueCombat_locked(updates, attacker, attacker, stopFightPacket(attacker.id))
+}
+
+func (server *server) cancelCombat_locked(id uint32, updates map[*worldClient][][]byte) {
+ // Leaving or dying also releases every opponent targeting this character.
+ for _, attacker := range server.fighting {
+ if attacker.id == id || attacker.fighting == id {
+ server.stopAttack_locked(attacker, updates)
+ }
+ }
+}
+
+func (server *server) advanceCombat(now time.Time) {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ updates := make(map[*worldClient][][]byte)
+
+ // Resolve simultaneous swings in identity order, without replaying missed ticks.
+ ids := make([]uint32, 0, len(server.fighting))
+ for id := range server.fighting {
+ ids = append(ids, id)
+ }
+ sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
+ for _, id := range ids {
+ attacker := server.fighting[id]
+ if attacker == nil {
+ continue
+ }
+ target := server.characters[attacker.fighting]
+ if target == nil || attacker.health == 0 || target.health == 0 || attacker.playfield != target.playfield {
+ server.stopAttack_locked(attacker, updates)
+ continue
+ }
+ // Require each player to still have a ready connection in this playfield.
+ available := true
+ for _, character := range []*character{attacker, target} {
+ if !character.npc {
+ client := server.clients[character.id]
+ available = available && client != nil && client.ready && !client.loading
+ }
+ }
+ if !available || !server.combatInRange_locked(attacker, target, now) {
+ server.stopAttack_locked(attacker, updates)
+ continue
+ }
+ if now.Before(attacker.nextAttack) {
+ continue
+ }
+
+ // Shipped QL 1 fists have 3..5 base damage; NPC profiles remain local.
+ damage := rand.Uint32N(3) + 3
+ if attacker.npc {
+ damage = 5
+ }
+ damage = min(damage, target.health)
+ target.health -= damage
+ attack, recharge := attacker.attackDelays()
+ attacker.rechargeUntil = now.Add(recharge)
+ attacker.nextAttack = attacker.rechargeUntil.Add(attack)
+ server.queueCombat_locked(updates, attacker, target, hitPacket(attacker, target, damage))
+ if target.health == 0 {
+ if target.roaming != nil && target.roaming.moving {
+ target.roaming.moving = false
+ server.queueCombat_locked(updates, target, target, npcMovementPacket(target, 2))
+ }
+ if !target.npc {
+ client := server.clients[target.id]
+ target.position = predictedPosition_locked(target, client, now)
+ client.forward = 0
+ }
+ server.cancelCombat_locked(target.id, updates)
+ server.queueCombat_locked(updates, target, target, deathPacket(target))
+ } else if target.npc && target.fighting == 0 {
+ server.startAttack_locked(target, attacker, now, updates)
+ }
+ }
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+}
+
+func (server *server) queueCombat_locked(updates map[*worldClient][][]byte, character, target *character, packets ...[]byte) {
+ // Never announce an NPC before this observer has received its spawn.
+ for id, client := range server.clients {
+ if client.ready && !client.loading && server.characters[id].playfield == character.playfield &&
+ (!character.npc || client.npcs[character.id]) && (!target.npc || client.npcs[target.id]) {
+ updates[client] = append(updates[client], packets...)
+ }
+ }
+}
+
+func (server *server) sendCombatUpdates(updates map[*worldClient][][]byte) {
+ for client, packets := range updates {
+ for _, packet := range packets {
+ if err := client.send(packet); err != nil {
+ log.Printf("Combat: %v", err)
+ client.disconnect(client.conn)
+ break
+ }
+ }
+ }
+}
+
+func hitPacket(attacker, target *character, damage uint32) []byte {
+ // kkr.dll 0x100aec00: damage, ammo, slot, target identity, death reason and result.
+ body := binary.BigEndian.AppendUint32(nil, damage)
+ for _, value := range []uint32{0xffffffff, 0, 50000, target.id, 0, 4} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ if target.health == 0 {
+ binary.BigEndian.PutUint32(body[20:24], 4)
+ }
+ return n3Packet(0x46002f16, 50000, attacker.id, body)
+}
+
+func deathPacket(character *character) []byte {
+ // kkr.dll 0x10070327: action 99 sets the corpse visual flag and death animation.
+ animation := uint32(500)
+ if character.npc {
+ animation = 503
+ }
+ var body []byte
+ for _, value := range []uint32{99, 0, 0, 0, animation} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x5e477770, 50000, character.id, body)
+}
diff --git a/server/combat_interest.go b/server/combat_interest.go
@@ -0,0 +1,19 @@
+package main
+
+func (server *server) combatInterest_locked(client *worldClient, spawned map[uint32]bool) [][]byte {
+ // Both participants must exist in this observer's client before target selection.
+ var updates [][]byte
+ for _, attacker := range server.fighting {
+ target := server.characters[attacker.fighting]
+ if target == nil || attacker.playfield != server.characters[client.id].playfield ||
+ target.playfield != attacker.playfield ||
+ (attacker.npc && !client.npcs[attacker.id]) || (target.npc && !client.npcs[target.id]) {
+ continue
+ }
+ if spawned != nil && !spawned[attacker.id] && !spawned[target.id] {
+ continue
+ }
+ updates = append(updates, attackPacket(attacker.id, target.id))
+ }
+ return updates
+}
diff --git a/server/combat_interest_test.go b/server/combat_interest_test.go
@@ -0,0 +1,141 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+type combatInterestConn struct {
+ combatTestConn
+ input *bytes.Reader
+ onWrite func([]byte)
+}
+
+func (conn *combatInterestConn) Read(buffer []byte) (int, error) {
+ return conn.input.Read(buffer)
+}
+
+func (conn *combatInterestConn) Write(packet []byte) (int, error) {
+ if conn.onWrite != nil {
+ conn.onWrite(packet)
+ }
+ return conn.combatTestConn.Write(packet)
+}
+
+func (conn *combatInterestConn) Close() error {
+ return nil
+}
+
+func TestCombatLateLoginReceivesTargetsAfterParticipantSpawns(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+ world.characters[2] = &character{id: 2, name: "Observer", playfield: 950, health: 100}
+ conn := &combatInterestConn{input: bytes.NewReader(systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}))}
+
+ if err := world.serveWorldClient(&worldClient{conn: conn}); err != nil {
+ t.Fatal(err)
+ }
+
+ seen := make(map[uint32]bool)
+ attacks := 0
+ for _, packet := range conn.packets {
+ switch binary.BigEndian.Uint32(packet[20:24]) {
+ case 0x271b3a6b:
+ seen[binary.BigEndian.Uint32(packet[28:32])] = true
+ case 0x28494070:
+ attacker := binary.BigEndian.Uint32(packet[28:32])
+ target := binary.BigEndian.Uint32(packet[40:44])
+ if !seen[attacker] || !seen[target] {
+ t.Fatalf("attack %d -> %d preceded a participant spawn", attacker, target)
+ }
+ attacks++
+ }
+ }
+ if attacks != 2 {
+ t.Fatalf("ongoing attacks replayed: %d", attacks)
+ }
+}
+
+func TestCombatNPCInterestReplaysTargetsOnceAfterSpawning(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ conn := &combatTestConn{}
+ world.clients[2] = &worldClient{id: 2, conn: conn, ready: true, npcs: make(map[uint32]bool)}
+ now := time.Now()
+
+ world.advanceNPCs(now)
+ world.advanceNPCs(now.Add(time.Second))
+
+ if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[0][20:24]) != 0x271b3a6b {
+ t.Fatalf("expected one spawn before two attack targets: %x", conn.packets)
+ }
+ seen := make(map[uint32]uint32)
+ for _, packet := range conn.packets[1:] {
+ if binary.BigEndian.Uint32(packet[20:24]) != 0x28494070 {
+ t.Fatalf("missing attack target: %x", packet)
+ }
+ seen[binary.BigEndian.Uint32(packet[28:32])] = binary.BigEndian.Uint32(packet[40:44])
+ }
+ if seen[1] != 1000000 || seen[1000000] != 1 {
+ t.Fatalf("replayed combat targets: %v", seen)
+ }
+}
+
+func TestCombatInterestWaitsForBothNPCParticipants(t *testing.T) {
+ world, conn := newCombatWorld()
+ world.clients[1].npcs = make(map[uint32]bool)
+ world.characters[1000000].fighting = 1000001
+ world.fighting[1000000] = world.characters[1000000]
+ world.characters[1000001] = &character{id: 1000001, npc: true, playfield: 950, position: [3]float32{1000, 0, 0}, health: 100}
+ now := time.Now()
+
+ world.advanceNPCs(now)
+ world.characters[1000001].position[0] = 2
+ world.advanceNPCs(now.Add(time.Second))
+
+ if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x271b3a6b ||
+ binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x271b3a6b || binary.BigEndian.Uint32(conn.packets[2][16:20]) != 0x28494070 {
+ t.Fatalf("attack preceded both NPC spawns: %x", conn.packets)
+ }
+}
+
+func TestCombatSessionReplacementCancelsBeforeInitialization(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.clients[1].conn = &combatInterestConn{}
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ observer := &combatTestConn{}
+ world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, npcs: map[uint32]bool{1000000: true}}
+ activeAtInitialization := -1
+ conn := &combatInterestConn{
+ input: bytes.NewReader(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})),
+ onWrite: func(packet []byte) {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x5f52412e {
+ activeAtInitialization = len(world.fighting)
+ }
+ },
+ }
+
+ if err := world.serveWorldClient(&worldClient{conn: conn}); err != nil {
+ t.Fatal(err)
+ }
+
+ if activeAtInitialization != 0 || world.characters[1].fighting != 0 || world.characters[1000000].fighting != 0 {
+ t.Fatal("replaced connection retained an active fight")
+ }
+ if len(observer.packets) < 2 || binary.BigEndian.Uint32(observer.packets[0][20:24]) != 0x4a41203e ||
+ binary.BigEndian.Uint32(observer.packets[1][20:24]) != 0x4a41203e {
+ t.Fatalf("observer did not receive both stop messages: %x", observer.packets)
+ }
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x28494070 {
+ t.Fatal("replacement restored a cancelled attack")
+ }
+ }
+}
diff --git a/server/combat_lifecycle_test.go b/server/combat_lifecycle_test.go
@@ -0,0 +1,162 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestCombatReplacedSessionCannotMoveRestOrFinishLoading(t *testing.T) {
+ world, currentOutput := newCombatWorld()
+ world.clients[1].loading = true
+ oldOutput := &combatTestConn{}
+ old := &worldClient{id: 1, conn: oldOutput, ready: true}
+ posture := make([]byte, 36)
+ binary.BigEndian.PutUint32(posture[16:20], 86)
+ movement := make([]byte, 48)
+ binary.BigEndian.PutUint32(movement[20:24], 0x41200000)
+
+ if err := world.handleCharacterReady(old); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handlePosture(old, posture); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMovement(old, movement); err != nil {
+ t.Fatal(err)
+ }
+
+ if !world.clients[1].loading || world.characters[1].sitting || world.characters[1].position != [3]float32{} ||
+ len(currentOutput.packets) != 0 || len(oldOutput.packets) != 0 {
+ t.Fatalf("replaced session changed the live actor: player=%+v client=%+v", world.characters[1], world.clients[1])
+ }
+}
+
+func TestCombatRepeatedWorldCookieCannotReinitializeTheActor(t *testing.T) {
+ world, _ := newCombatWorld()
+ delete(world.clients, 1)
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ conn := &combatInterestConn{input: bytes.NewReader(append(cookie, cookie...))}
+
+ err := world.serveWorldClient(&worldClient{conn: conn, loading: true})
+
+ if err == nil || !strings.Contains(err.Error(), "already initialized") {
+ t.Fatalf("repeated cookie accepted: %v", err)
+ }
+ spawns := 0
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[28:32]) == 1 {
+ spawns++
+ }
+ }
+ if spawns != 1 || world.clients[1] != nil {
+ t.Fatalf("repeated initialization changed lifecycle: spawns=%d client=%v", spawns, world.clients[1])
+ }
+}
+
+func TestCombatProfileEditStopsBothActorsInTheirOriginalPlayfield(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ destination := world.characters[1].userData()
+ destination.Playfield = 705
+
+ err := world.updateUser(destination)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ stopped := make(map[uint32]bool)
+ for _, packet := range observer.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x4a41203e {
+ stopped[binary.BigEndian.Uint32(packet[24:28])] = true
+ }
+ }
+ if !stopped[1] || !stopped[1000000] || len(world.fighting) != 0 {
+ t.Fatalf("profile edit did not flush both old-zone actors: stops=%v fighting=%v", stopped, world.fighting)
+ }
+}
+
+func TestCombatFailedProfileEditPreservesBothActorsAndResources(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, conn := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+ before := *world.characters[1]
+ destination := before.userData()
+ destination.Playfield = 705
+ if err := os.WriteFile("data", []byte("blocked"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+
+ err := world.updateUser(destination)
+
+ if err == nil || world.characters[1].playfield != before.playfield || world.characters[1].health != before.health ||
+ world.characters[1].fighting != 1000000 || world.characters[1000000].fighting != 1 || len(world.fighting) != 2 || len(conn.packets) != 0 {
+ t.Fatalf("failed edit changed live combat: player=%+v packets=%x error=%v", world.characters[1], conn.packets, err)
+ }
+}
+
+func TestRegenerationSchedulerJitterDoesNotAccumulate(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+
+ for second := 2; second <= 58; second += 2 {
+ jitter := time.Millisecond
+ if second%4 != 0 {
+ jitter = 20 * time.Millisecond
+ }
+ world.advanceRegeneration(start.Add(time.Duration(second)*time.Second + jitter))
+ }
+
+ if world.characters[1].health != 23 || world.clients[1].regenerationAt != start.Add(58*time.Second) {
+ t.Fatalf("scheduler jitter changed recovery phase: hp=%d phase=%v", world.characters[1].health, world.clients[1].regenerationAt)
+ }
+}
+
+func TestCombatSlowLiveRecipientDoesNotBlockWorldTick(t *testing.T) {
+ world, _ := newCombatWorld()
+ delete(world.clients, 1)
+ peer := connectZoningClient(t, world, true)
+ if _, err := peer.Write(targetPacket(attackPacket(1, 1000000))); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readPacket(peer); err != nil {
+ t.Fatal(err)
+ }
+ world.mutex.Lock()
+ first := world.characters[1].nextAttack
+ world.mutex.Unlock()
+ tickDone, motionDone := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() {
+ peer.Close()
+ <-tickDone
+ <-motionDone
+ })
+
+ go func() { world.advanceCombat(first); close(tickDone) }()
+ deadline := time.Now().Add(time.Second)
+ for {
+ world.mutex.Lock()
+ hit := world.characters[1000000].health < 100
+ world.mutex.Unlock()
+ if hit || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+ go func() { world.advanceNPCs(time.Now()); close(motionDone) }()
+
+ select {
+ case <-motionDone:
+ case <-time.After(250 * time.Millisecond):
+ t.Fatal("a live recipient that stopped reading blocked the shared world")
+ }
+}
diff --git a/server/combat_stats_test.go b/server/combat_stats_test.go
@@ -0,0 +1,51 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+)
+
+func TestCombatPlayerHealthMatchesBreedAndSoldierTitle(t *testing.T) {
+ for _, scenario := range []struct {
+ breed uint16
+ level uint16
+ title uint32
+ health uint32
+ }{
+ {1, 1, 1, 37}, {2, 1, 1, 41}, {3, 1, 1, 29}, {4, 1, 1, 59},
+ {5, 1, 1, 65}, {0, 1, 1, 18}, {6, 1, 1, 18}, {7, 1, 1, 18},
+ {1, 14, 1, 115}, {1, 15, 2, 136}, {1, 49, 2, 374},
+ {1, 50, 3, 431}, {1, 99, 3, 823}, {1, 100, 4, 931},
+ {1, 149, 4, 1372}, {1, 150, 5, 1531}, {1, 189, 5, 1921},
+ {1, 190, 6, 2121}, {1, 200, 6, 2231},
+ } {
+ data := userData{ID: 1, Level: scenario.level, Appearance: scenario.breed << 4}
+
+ player := data.character()
+ packet := fullCharacterPacket(player)
+ stats := make(map[uint32]uint32)
+ count := binary.BigEndian.Uint32(packet[64:68])/1009 - 1
+ for offset := 68; offset < 68+int(count)*8; offset += 8 {
+ stats[binary.BigEndian.Uint32(packet[offset:offset+4])] = binary.BigEndian.Uint32(packet[offset+4 : offset+8])
+ }
+
+ if player.health != scenario.health || stats[27] != scenario.health || stats[1] != scenario.health || stats[37] != scenario.title || stats[60] != 1 {
+ t.Fatalf("breed %d level %d: health=%d stats=%v", scenario.breed, scenario.level, player.health, stats)
+ }
+ }
+}
+
+func TestCombatProfileEditClampsHealthToNewMaximum(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCombatWorld()
+ world.characters[1].health = 59
+ destination := world.characters[1].userData()
+ destination.Level = 1
+ destination.Appearance = 3 << 4
+
+ err := world.updateUser(destination)
+
+ if err != nil || world.characters[1].health != 29 {
+ t.Fatalf("profile edit left health over its maximum: %d, %v", world.characters[1].health, err)
+ }
+}
diff --git a/server/combat_stress_test.go b/server/combat_stress_test.go
@@ -0,0 +1,259 @@
+package main
+
+import (
+ "encoding/binary"
+ "io"
+ "net"
+ "sync"
+ "testing"
+ "time"
+)
+
+type failingCombatConn struct {
+ combatTestConn
+ closed bool
+}
+
+func (conn *failingCombatConn) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }
+func (conn *failingCombatConn) Close() error {
+ conn.closed = true
+ return nil
+}
+
+type stalledCombatConn struct {
+ net.Conn
+ started chan struct{}
+ once sync.Once
+}
+
+func (conn *stalledCombatConn) Write(packet []byte) (int, error) {
+ conn.once.Do(func() { close(conn.started) })
+ return conn.Conn.Write(packet)
+}
+
+func TestCombatSharedNPCKillingBlowIsResolvedOnce(t *testing.T) {
+ world, first := newCombatWorld()
+ second := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: second, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ world.characters[1000000].health = 6
+ for _, id := range []uint32{1, 2} {
+ if err := world.handleCombat(world.clients[id], attackPacket(id, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ when := world.characters[2].nextAttack
+
+ world.advanceCombat(when)
+ world.advanceCombat(when.Add(time.Hour))
+
+ if world.characters[1000000].health != 0 || len(world.fighting) != 0 || world.characters[1].health != 100 || world.characters[2].health != 100 {
+ t.Fatal("shared NPC death left an attacker active or allowed retaliation")
+ }
+ for _, conn := range []*combatTestConn{first, second} {
+ var hits, deaths int
+ var killer uint32
+ for _, packet := range conn.packets {
+ switch binary.BigEndian.Uint32(packet[16:20]) {
+ case 0x46002f16:
+ hits++
+ if binary.BigEndian.Uint32(packet[49:53]) == 4 {
+ killer = binary.BigEndian.Uint32(packet[24:28])
+ }
+ case 0x5e477770:
+ deaths++
+ }
+ }
+ if hits != 2 || deaths != 1 || killer != 2 {
+ t.Fatalf("shared death announcements: hits=%d deaths=%d killer=%d", hits, deaths, killer)
+ }
+ }
+}
+
+func TestCombatSwitchingTargetsLeavesExistingRetaliation(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[1000001] = &character{id: 1000001, npc: true, appearance: 229, playfield: 950, position: [3]float32{2, 0, 0}, health: 100}
+ world.clients[1].npcs[1000001] = true
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ first := world.characters[1].nextAttack
+ world.advanceCombat(first)
+ originalHealth := world.characters[1000000].health
+
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000001)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+
+ if world.characters[1].fighting != 1000001 || world.characters[1000000].health != originalHealth || world.characters[1000001].health < 95 || world.characters[1000001].health > 97 || world.characters[1].health != 95 || world.characters[1000000].fighting != 1 {
+ t.Fatal("target switch reused the old target or pacified its retaliation")
+ }
+}
+
+func TestCombatRepeatedStartStopDoesNotLeaveScheduledSwings(t *testing.T) {
+ world, _ := newCombatWorld()
+
+ for range 100 {
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleCombat(world.clients[1], stopFightPacket(1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ world.advanceCombat(time.Now().Add(time.Hour))
+
+ if len(world.fighting) != 0 || !world.characters[1].nextAttack.IsZero() || world.characters[1].health != 100 || world.characters[1000000].health != 100 {
+ t.Fatal("start/stop requests retained a scheduled attack")
+ }
+}
+
+func TestCombatChangingTargetsCannotBypassRecharge(t *testing.T) {
+ for _, action := range []string{"switch target", "stop and restart"} {
+ t.Run(action, func(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[1000001] = &character{id: 1000001, npc: true, appearance: 229, playfield: 950, position: [3]float32{2, 0, 0}, health: 100}
+ world.clients[1].npcs[1000001] = true
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+ next := world.characters[1].nextAttack
+
+ target := uint32(1000001)
+ if action == "stop and restart" {
+ if err := world.handleCombat(world.clients[1], stopFightPacket(1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ target = 1000000
+ }
+ if err := world.handleCombat(world.clients[1], attackPacket(1, target)[20:]); err != nil {
+ t.Fatal(err)
+ }
+
+ if world.characters[1].nextAttack.Before(next) {
+ t.Fatalf("%s advanced the next attack from %s to %s", action, next, world.characters[1].nextAttack)
+ }
+ })
+ }
+}
+
+func TestCombatFailedObserverDoesNotSuppressOtherObservers(t *testing.T) {
+ world, healthy := newCombatWorld()
+ failed := &failingCombatConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: failed, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+
+ if !failed.closed || len(healthy.packets) != 3 || world.characters[1000000].health < 95 || world.characters[1000000].health > 97 {
+ t.Fatal("failed observer suppressed a healthy observer's combat updates")
+ }
+}
+
+func TestCombatLateObserverReceivesInjuredNPCBeforeFight(t *testing.T) {
+ world, _ := newCombatWorld()
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)}
+
+ world.advanceNPCs(time.Now())
+
+ if len(observer.packets) != 3 || binary.BigEndian.Uint32(observer.packets[0][16:20]) != 0x271b3a6b || binary.BigEndian.Uint32(observer.packets[0][83:87]) != world.characters[1000000].health {
+ t.Fatalf("late observer did not receive the injured NPC first: %x", observer.packets)
+ }
+ for _, packet := range observer.packets[1:] {
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x28494070 {
+ t.Fatalf("late observer received historical damage instead of fighting targets: %x", packet)
+ }
+ }
+}
+
+func TestCombatStalledObserverCannotFreezeWorldUpdates(t *testing.T) {
+ world, _ := newCombatWorld()
+ peer, connection := net.Pipe()
+ if err := peer.SetReadDeadline(time.Now().Add(8 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ stalled := &stalledCombatConn{Conn: connection, started: make(chan struct{})}
+ world.clients[1].conn = stalled
+ attackDone, tickDone := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() {
+ peer.Close()
+ connection.Close()
+ <-attackDone
+ <-tickDone
+ })
+
+ go func() {
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ close(attackDone)
+ }()
+ <-stalled.started
+ go func() {
+ world.advanceNPCs(time.Now())
+ close(tickDone)
+ }()
+
+ select {
+ case <-tickDone:
+ case <-time.After(6 * time.Second):
+ t.Fatal("a peer that stopped reading blocked unrelated world updates")
+ }
+ if _, err := peer.Read(make([]byte, 1)); err != io.EOF {
+ t.Fatalf("stalled peer was not disconnected: %v", err)
+ }
+}
+
+func TestCombatConcurrentDisconnectAndTicksReleaseBothSides(t *testing.T) {
+ world, _ := newCombatWorld()
+ delete(world.clients, 1)
+ client := connectZoningClient(t, world, false)
+ if _, err := client.Write(attackPacket(1, 1000000)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
+ world.mutex.Lock()
+ first := world.characters[1].nextAttack
+ world.mutex.Unlock()
+ done := make(chan struct{})
+ t.Cleanup(func() {
+ client.Close()
+ <-done
+ })
+
+ go func() {
+ for offset := range 100 {
+ world.advanceCombat(first.Add(time.Duration(offset) * time.Second))
+ }
+ close(done)
+ }()
+ client.Close()
+ <-done
+ deadline := time.Now().Add(time.Second)
+ for {
+ world.mutex.Lock()
+ disconnected := world.clients[1] == nil
+ world.mutex.Unlock()
+ if disconnected || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.clients[1] != nil || len(world.fighting) != 0 || world.characters[1].fighting != 0 || world.characters[1000000].fighting != 0 {
+ t.Fatal("disconnect racing combat ticks retained a connection or fighting target")
+ }
+}
diff --git a/server/combat_test.go b/server/combat_test.go
@@ -0,0 +1,423 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/hex"
+ "net"
+ "testing"
+ "time"
+)
+
+type combatTestConn struct {
+ net.Conn
+ packets [][]byte
+}
+
+func (conn *combatTestConn) SetWriteDeadline(time.Time) error { return nil }
+
+func (conn *combatTestConn) Write(packet []byte) (int, error) {
+ conn.packets = append(conn.packets, append([]byte(nil), packet...))
+ return len(packet), nil
+}
+
+func newCombatWorld() (*server, *combatTestConn) {
+ conn := &combatTestConn{}
+ return &server{
+ characters: map[uint32]*character{
+ 1: {id: 1, playfield: 950, health: 100},
+ 1000000: {id: 1000000, playfield: 950, position: [3]float32{1, 0, 0}, appearance: 229, npc: true, health: 100},
+ },
+ clients: map[uint32]*worldClient{
+ 1: {id: 1, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}},
+ },
+ fighting: make(map[uint32]*character),
+ }, conn
+}
+
+func TestCombatTimesSwingsAndRetaliation(t *testing.T) {
+ world, conn := newCombatWorld()
+ player, npc := world.characters[1], world.characters[1000000]
+
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ first := player.nextAttack
+ world.advanceCombat(first.Add(-time.Nanosecond))
+ if npc.health != 100 || len(conn.packets) != 1 {
+ t.Fatal("attack landed before its attack phase ended")
+ }
+ world.advanceCombat(first)
+ world.advanceCombat(first.Add(time.Second))
+ world.advanceCombat(first.Add(3950 * time.Millisecond))
+
+ if npc.health < 90 || npc.health > 94 || player.health != 90 || player.fighting != 1000000 || npc.fighting != 1 {
+ t.Fatalf("combat state: player=%+v npc=%+v", player, npc)
+ }
+ if len(conn.packets) != 6 || hex.EncodeToString(conn.packets[1][33:57]) != "ffffffff000000000000c350000f42400000000000000004" {
+ t.Fatalf("unarmed hit layout or cycle: %x", conn.packets)
+ }
+}
+
+func TestCombatRepeatedRequestsDoNotResetClockOrCatchUpTicks(t *testing.T) {
+ world, conn := newCombatWorld()
+ request := attackPacket(1, 1000000)[20:]
+ world.handleCombat(world.clients[1], request)
+ first := world.characters[1].nextAttack
+
+ world.handleCombat(world.clients[1], request)
+ if world.characters[1].nextAttack != first || len(conn.packets) != 1 {
+ t.Fatal("repeated attack changed the clock or replayed the acknowledgement")
+ }
+ world.advanceCombat(first.Add(time.Hour))
+
+ if world.characters[1000000].health < 95 || world.characters[1000000].health > 97 || world.characters[1].nextAttack != first.Add(time.Hour+3950*time.Millisecond) {
+ t.Fatal("a late tick replayed missed attacks")
+ }
+}
+
+func TestCombatRejectsInvalidTargetsAndSessions(t *testing.T) {
+ for _, scenario := range []string{"player", "human NPC", "dead", "other zone", "unknown", "hidden", "far", "loading", "replaced"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newCombatWorld()
+ npc, client := world.characters[1000000], world.clients[1]
+ switch scenario {
+ case "player":
+ npc.npc = false
+ case "human NPC":
+ npc.appearance = 789
+ case "dead":
+ npc.health = 0
+ case "other zone":
+ npc.playfield = 952
+ case "unknown":
+ delete(world.characters, 1000000)
+ case "hidden":
+ delete(client.npcs, 1000000)
+ case "far":
+ npc.position[0] = 5
+ case "loading":
+ client.loading = true
+ case "replaced":
+ world.clients[1] = &worldClient{id: 1}
+ }
+
+ err := world.handleCombat(client, attackPacket(1, 1000000)[20:])
+
+ if err != nil || len(world.fighting) != 0 || world.characters[1].fighting != 0 {
+ t.Fatalf("invalid attack accepted: %s, %v", scenario, err)
+ }
+ })
+ }
+}
+
+func TestCombatStopLeavesRetaliatingNPCActive(t *testing.T) {
+ world, conn := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ first := world.characters[1].nextAttack
+ world.advanceCombat(first)
+
+ world.handleCombat(world.clients[1], stopFightPacket(1)[20:])
+ world.advanceCombat(first.Add(3 * time.Second))
+
+ if world.characters[1].fighting != 0 || world.characters[1000000].fighting != 1 || world.characters[1000000].health < 95 || world.characters[1000000].health > 97 || world.characters[1].health != 95 {
+ t.Fatal("stopping an attack also pacified the opponent")
+ }
+ if hex.EncodeToString(conn.packets[3][16:33]) != "4a41203e0000c350000000010000000001" {
+ t.Fatalf("stop layout: %x", conn.packets[3])
+ }
+}
+
+func TestCombatRangeUsesPredictedPlayerPosition(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ first := world.characters[1].nextAttack
+ world.characters[1].rotation = [4]float32{0, 0, 0, 1}
+ world.clients[1].forward = 1
+ world.clients[1].movementStarted = first.Add(-4 * time.Second)
+
+ world.advanceCombat(first)
+
+ if len(world.fighting) != 0 || world.characters[1000000].health != 100 {
+ t.Fatal("an out-of-range predicted position still dealt damage")
+ }
+}
+
+func TestCombatKillingHitClampsHealthAndCancelsEveryAttacker(t *testing.T) {
+ world, conn := newCombatWorld()
+ world.characters[1000000].health = 3
+ world.characters[1000000].roaming = &npcRoaming{moving: true}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100, fighting: 1000000}
+ world.fighting[2] = world.characters[2]
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ first := world.characters[1].nextAttack
+
+ world.advanceCombat(first)
+ world.advanceCombat(first.Add(time.Hour))
+
+ if world.characters[1000000].health != 0 || world.characters[1000000].roaming.moving || len(world.fighting) != 0 || world.characters[2].fighting != 0 {
+ t.Fatal("death did not release every opponent")
+ }
+ if hex.EncodeToString(conn.packets[1][29:57]) != "00000003ffffffff000000000000c350000f42400000000400000004" {
+ t.Fatalf("killing hit: %x", conn.packets[1])
+ }
+ if hex.EncodeToString(conn.packets[len(conn.packets)-1][29:49]) != "00000063000000000000000000000000000001f7" {
+ t.Fatal("NPC death animation was not announced after the final hit")
+ }
+}
+
+func TestCombatPacketsOnlyReachObserversWhoKnowTheNPC(t *testing.T) {
+ world, _ := newCombatWorld()
+ near, hidden, elsewhere := &combatTestConn{}, &combatTestConn{}, &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.characters[3] = &character{id: 3, playfield: 950, health: 100}
+ world.characters[4] = &character{id: 4, playfield: 952, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: near, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ world.clients[3] = &worldClient{id: 3, conn: hidden, target: true, ready: true}
+ world.clients[4] = &worldClient{id: 4, conn: elsewhere, target: true, ready: true}
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+
+ world.advanceCombat(world.characters[1].nextAttack)
+
+ if len(near.packets) != 3 || len(hidden.packets) != 0 || len(elsewhere.packets) != 0 {
+ t.Fatalf("combat visibility: near=%d hidden=%d elsewhere=%d", len(near.packets), len(hidden.packets), len(elsewhere.packets))
+ }
+ for _, packet := range hidden.packets {
+ if binary.BigEndian.Uint32(packet[24:28]) == 1000000 {
+ t.Fatal("hidden NPC announced before its spawn")
+ }
+ }
+}
+
+func TestCombatAcceptsNativeWorldMessagesAndCancelsOnDisconnect(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ world.newCharacter()
+ client := connectZoningClient(t, world, true)
+
+ if _, err := client.Write(targetPacket(attackPacket(1, 1000000))); err != nil {
+ t.Fatal(err)
+ }
+ ack, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ world.mutex.Lock()
+ first := world.characters[1].nextAttack
+ world.mutex.Unlock()
+ done := make(chan struct{})
+ go func() { world.advanceCombat(first); close(done) }()
+ for range 2 {
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
+ }
+ <-done
+ client.Close()
+ deadline := time.Now().Add(time.Second)
+ for {
+ world.mutex.Lock()
+ connected := world.clients[1] != nil
+ world.mutex.Unlock()
+ if !connected || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if !bytes.Equal(ack[16:38], targetPacket(attackPacket(1, 1000000))[16:38]) || len(world.fighting) != 0 || world.clients[1] != nil || world.characters[1000000].health < 95 || world.characters[1000000].health > 97 {
+ t.Fatalf("native attack/disconnect: ack=%x fighting=%v", ack, world.fighting)
+ }
+}
+
+func TestCombatPlayerDeathStopsMovementAndFurtherAttacks(t *testing.T) {
+ world, conn := newCombatWorld()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ first := world.characters[1].nextAttack
+ world.advanceCombat(first)
+ world.characters[1].health = 3
+ world.characters[1].rotation = [4]float32{0, 0, 0, 1}
+ world.clients[1].forward = 1
+ world.clients[1].movementStarted = first
+
+ world.advanceCombat(first.Add(time.Second))
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(first.Add(time.Hour))
+
+ if world.characters[1].health != 0 || world.clients[1].forward != 0 || world.characters[1].position != [3]float32{0, 0, 1.5} || len(world.fighting) != 0 {
+ t.Fatal("dead player kept moving or fighting")
+ }
+ if hex.EncodeToString(conn.packets[3][29:57]) != "00000003ffffffff000000000000c350000000010000000400000004" {
+ t.Fatalf("lethal NPC strike: %x", conn.packets[3])
+ }
+ if hex.EncodeToString(conn.packets[len(conn.packets)-1][29:49]) != "00000063000000000000000000000000000001f4" {
+ t.Fatal("player death animation was not announced after the final hit")
+ }
+}
+
+func TestCombatLateObserverSeesDeadNPC(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[1000000].health = 3
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ conn := &combatTestConn{}
+ world.clients[2] = &worldClient{id: 2, conn: conn, target: true, ready: true, npcs: make(map[uint32]bool)}
+
+ world.advanceNPCs(time.Now())
+
+ if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x271b3a6b || hex.EncodeToString(conn.packets[1][29:49]) != "00000063000000000000000000000000000001f7" {
+ t.Fatalf("late observer did not receive the NPC corpse: %x", conn.packets)
+ }
+}
+
+func TestCombatZoningCancelsOpponentsAndPreservesHealth(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCombatWorld()
+ world.characters[1].appearance = 0x315
+ world.characters[1].level = 1
+ world.characters[1].health = 37
+ world.characters[1].aggDef = 75
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ first := world.characters[1].nextAttack
+ world.advanceCombat(first)
+ world.advanceCombat(first.Add(time.Second))
+ destination := world.characters[1].userData()
+ destination.Playfield = 952
+
+ err := world.updateUser(destination)
+ world.advanceCombat(first.Add(time.Hour))
+
+ if err != nil || world.characters[1].playfield != 952 || world.characters[1].health != 32 || world.characters[1].aggDef != 75 || world.characters[1].rechargeUntil != first.Add(1220*time.Millisecond) || world.characters[1000000].fighting != 0 || len(world.fighting) != 0 {
+ t.Fatalf("combat survived zoning or health reset: %v", err)
+ }
+}
+
+func TestCombatMalformedPacketsAreRejected(t *testing.T) {
+ for _, packet := range [][]byte{attackPacket(1, 1000000)[:44], stopFightPacket(1)[:39], n3Packet(0x76793f0d, 50000, 1, []byte{0, 0, 0})[:39]} {
+ world, _ := newCombatWorld()
+
+ err := world.handleCombat(world.clients[1], packet[20:])
+
+ if err == nil || len(world.fighting) != 0 {
+ t.Fatal("short combat packet was accepted")
+ }
+ }
+}
+
+func TestCombatAggDefControlsNativeFistTimings(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ value int32
+ attack time.Duration
+ recharge time.Duration
+ }{
+ {"center", 0, 1980 * time.Millisecond, 1970 * time.Millisecond},
+ {"base speed", 75, 1230 * time.Millisecond, 1220 * time.Millisecond},
+ {"full aggression", 100, time.Second, time.Second},
+ {"full defense", -100, 2980 * time.Millisecond, 2970 * time.Millisecond},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, conn := newCombatWorld()
+ request := n3Packet(0x76793f0d, 50000, 1, binary.BigEndian.AppendUint32(nil, uint32(scenario.value)))
+
+ if err := world.handleCombat(world.clients[1], request[20:]); err != nil {
+ t.Fatal(err)
+ }
+ before := time.Now()
+ world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
+ after := time.Now()
+ first := world.characters[1].nextAttack
+ world.advanceCombat(first)
+
+ if first.Before(before.Add(scenario.attack)) || first.After(after.Add(scenario.attack)) ||
+ world.characters[1].nextAttack != first.Add(scenario.attack+scenario.recharge) ||
+ world.characters[1].rechargeUntil != first.Add(scenario.recharge) {
+ t.Fatal("attack/recharge differs from native centisecond calculation")
+ }
+ if world.characters[1].aggDef != scenario.value || binary.BigEndian.Uint16(conn.packets[0][6:8]) != 37 ||
+ binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x2b333d6e ||
+ binary.BigEndian.Uint32(conn.packets[0][29:33]) != 51 ||
+ int32(binary.BigEndian.Uint32(conn.packets[0][33:37])) != scenario.value {
+ t.Fatal("slider value was not acknowledged through the native stat layout")
+ }
+ })
+ }
+}
+
+func TestCombatAggDefRejectsInvalidValuesAndReplacedSessions(t *testing.T) {
+ for _, value := range []int32{-101, 101, -2147483648, 2147483647, 75} {
+ world, conn := newCombatWorld()
+ client := world.clients[1]
+ if value == 75 {
+ world.clients[1] = &worldClient{id: 1}
+ }
+ request := n3Packet(0x76793f0d, 50000, 1, binary.BigEndian.AppendUint32(nil, uint32(value)))
+
+ err := world.handleCombat(client, request[20:])
+
+ if err != nil || world.characters[1].aggDef != 0 || len(conn.packets) != 0 {
+ t.Fatalf("invalid slider request accepted: %d, %v", value, err)
+ }
+ }
+}
+
+func TestCombatAggDefUsesNativeWorldRequest(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ world.newCharacter()
+ client := connectZoningClient(t, world, true)
+ request := n3Packet(0x76793f0d, 50000, 1, []byte{0xff, 0xff, 0xff, 0x9c})
+
+ if _, err := client.Write(targetPacket(request)); err != nil {
+ t.Fatal(err)
+ }
+ ack, err := readPacket(client)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if hex.EncodeToString(ack[16:37]) != "2b333d6e0000c350000000010000000033ffffff9c" {
+ t.Fatalf("native slider reply: %x", ack)
+ }
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.characters[1].aggDef != -100 {
+ t.Fatal("native request did not reach the player's combat state")
+ }
+}
+
+func TestCombatDeadPlayerCannotCrossZoneTriggers(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[1].health = 0
+ world.characters[1].rotation = [4]float32{0, 0, 0, 1}
+ world.clients[1].forward = 1
+ now := time.Now()
+ world.clients[1].movementStarted = now
+ world.zoneLinks = map[string]map[uint32]zoneLinks{"target": {
+ 950: {Doors: []zoneDoor{{ID: 1, Destination: 952, DestinationDoor: 2}}},
+ 952: {Doors: []zoneDoor{{ID: 2, Position: [3]float32{10, 0, 10}}}},
+ }}
+
+ world.advanceZoneCrossings(now)
+
+ if world.characters[1].playfield != 950 || !world.clients[1].ready {
+ t.Fatal("dead player crossed a zone trigger")
+ }
+}
+
+func TestCombatReconnectRevivesDefeatedPlayer(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ world.newCharacter().health = 0
+
+ connectZoningClient(t, world, true)
+
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.characters[1].health != 37 || world.characters[1].fighting != 0 {
+ t.Fatal("reconnecting did not revive the defeated player")
+ }
+}
diff --git a/server/control.go b/server/control.go
@@ -69,6 +69,7 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>%s</h1><p>User %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected)
controlMap(w, data.ID)
fmt.Fprintf(w, "<h2>Character data</h2><p>ID is fixed. Position is XYZ; rotation is XYZW. Saving reconnects an online character to apply the data.</p><form method='post' action='users/%d'><textarea name='data' rows='20' cols='80' required>%s</textarea><p><button>Save character</button></p></form>", data.ID, html.EscapeString(string(contents)))
+ fmt.Fprint(w, "<p>The stats section contains base abilities and trained skills. Displayed skills also include bonuses from abilities.</p>")
fmt.Fprint(w, "</body></html>")
}
@@ -153,7 +154,7 @@ func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) {
for _, client := range clients {
if err := client.send(gameTimePacket(client.id, float64(hour*3600+minute*60))); err != nil {
log.Printf("Game time: %v", err)
- client.conn.Close()
+ client.disconnect(client.conn)
}
}
http.Redirect(w, r, server.baseURL+"control", http.StatusSeeOther)
@@ -172,6 +173,8 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
return
}
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
server.mutex.Lock()
character := server.characters[uint32(id)]
if character == nil || character.npc {
@@ -208,7 +211,7 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
}
destination.Rotation = [4]float32{0, 0, 0, 1}
destination.ReturnDoor = nil
- if err := server.updateUser(destination); err != nil {
+ if err := server.updateUser_locked(destination); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
@@ -216,34 +219,46 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
}
func (server *server) updateUser(destination userData) error {
- // Save profile changes before refreshing an online client's complete character.
- server.npcUpdateMutex.RLock()
- defer server.npcUpdateMutex.RUnlock()
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ return server.updateUser_locked(destination)
+}
+
+func (server *server) updateUser_locked(destination userData) error {
+ // Hold updateMutex; save the candidate before changing any live actor state.
server.mutex.Lock()
character := server.characters[destination.ID]
if character == nil || character.npc {
server.mutex.Unlock()
return fmt.Errorf("unknown user")
}
- previous := *character
- *character = *destination.character()
- character.browserTokenHash = previous.browserTokenHash
- character.savedProfile = previous.savedProfile
- character.savedPosition = previous.savedPosition
- character.nextPositionSave = previous.nextPositionSave
- if err := server.saveUser_locked(character); err != nil {
- *character = previous
+ previousPlayfield := character.playfield
+ updated := destination.character()
+ updated.browserTokenHash = character.browserTokenHash
+ updated.savedProfile = character.savedProfile
+ updated.savedPosition = character.savedPosition
+ updated.nextPositionSave = character.nextPositionSave
+ updated.health = min(character.health, updated.maximumHealth())
+ updated.nano = min(character.nano, updated.maximumNano())
+ updated.aggDef = character.aggDef
+ updated.rechargeUntil = character.rechargeUntil
+ if err := server.saveUser_locked(updated); err != nil {
server.mutex.Unlock()
return err
}
+ updates := make(map[*worldClient][][]byte)
+ server.cancelCombat_locked(character.id, updates)
+ *character = *updated
client := server.clients[character.id]
if client == nil || !client.ready {
server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
return nil
}
client.ready = false
delete(server.clients, character.id)
server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
// Original n3Teleport uses XYZ, a zone flag, two identities, and a stream.
var body []byte
@@ -254,15 +269,15 @@ func (server *server) updateUser(destination userData) error {
body = binary.BigEndian.AppendUint32(body, value)
}
if err := client.send(n3Packet(0x43197d22, 50000, destination.ID, body)); err != nil {
- client.conn.Close()
- server.broadcast(previous.playfield, destination.ID, n3Packet(0x36510078, 50000, destination.ID, nil))
+ client.disconnect(client.conn)
+ server.broadcast(previousPlayfield, destination.ID, n3Packet(0x36510078, 50000, destination.ID, nil))
return err
}
- server.broadcast(previous.playfield, destination.ID, n3Packet(0x36510078, 50000, destination.ID, nil))
+ server.broadcast(previousPlayfield, destination.ID, n3Packet(0x36510078, 50000, destination.ID, nil))
body = binary.BigEndian.AppendUint16([]byte{127, 0, 0, 1}, uint16(server.worldPort))
err := client.send(systemPacket(0x3c, body))
if err != nil {
- client.conn.Close()
+ client.disconnect(client.conn)
}
return err
}
diff --git a/server/interest.go b/server/interest.go
@@ -22,6 +22,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
}
// Send current state before motion when an NPC enters this observer's vicinity.
+ spawned := make(map[uint32]bool)
for id, other := range server.characters {
if !other.npc || other.playfield != player.playfield || client.npcs[id] {
continue
@@ -31,10 +32,18 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
continue
}
client.npcs[id] = true
+ spawned[id] = true
updates = append(updates, characterPacket(other))
+ if other.health == 0 {
+ updates = append(updates, deathPacket(other))
+ }
if other.roaming != nil && other.roaming.moving {
updates = append(updates, npcMovementPacket(other, 1))
}
}
+ if client.ready && len(spawned) != 0 {
+ // Rebuild fighting targets only after every new participant has spawned.
+ updates = append(updates, server.combatInterest_locked(client, spawned)...)
+ }
return updates
}
diff --git a/server/main.go b/server/main.go
@@ -9,7 +9,6 @@ import (
"io"
"io/fs"
"log"
- "math"
"net"
"net/http"
"os"
@@ -231,20 +230,28 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
func (server *server) serveWorldClient(client *worldClient) error {
conn := client.conn
+ client.startWriter(client.conn)
+ defer client.finishWriter()
var character *character
loggingOut := false
defer func() {
if character == nil {
return
}
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
server.mutex.Lock()
if server.clients[character.id] != client {
server.mutex.Unlock()
return
}
+ client.ready = false
+ updates := make(map[*worldClient][][]byte)
+ server.cancelCombat_locked(character.id, updates)
delete(server.clients, character.id)
playfield := character.playfield
server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
server.broadcast(playfield, character.id, n3Packet(0x36510078, 50000, character.id, nil))
}()
for {
@@ -263,41 +270,56 @@ func (server *server) serveWorldClient(client *worldClient) error {
switch binary.BigEndian.Uint16(packet[2:4]) {
case 1:
if binary.BigEndian.Uint32(packet[16:20]) == 0x1b {
+ if character != nil {
+ return fmt.Errorf("world character already initialized")
+ }
id := binary.BigEndian.Uint32(packet[20:24])
if client.id != 0 && client.id != id {
return fmt.Errorf("world character does not match session")
}
// The recovered 14.9.1 client identifies its cookie with 0xdfdf.
client.target = binary.BigEndian.Uint16(packet[0:2]) == 0xdfdf
- server.npcUpdateMutex.RLock()
+ server.updateMutex.Lock()
server.mutex.Lock()
character = server.characters[binary.BigEndian.Uint32(packet[20:24])]
if character == nil || character.npc {
server.mutex.Unlock()
- server.npcUpdateMutex.RUnlock()
+ server.updateMutex.Unlock()
return fmt.Errorf("unknown world character %d", binary.BigEndian.Uint32(packet[20:24]))
}
if character.browserTokenHash != "" && client.id == 0 {
server.mutex.Unlock()
- server.npcUpdateMutex.RUnlock()
+ server.updateMutex.Unlock()
return fmt.Errorf("browser character requires a browser credential")
}
+ combatUpdates := make(map[*worldClient][][]byte)
if previous := server.clients[character.id]; previous != nil {
previous.ready = false
+ server.cancelCombat_locked(character.id, combatUpdates)
if previous.stream != nil {
previous.stream.mutex.Lock()
previous.stream.replaced = true
previous.stream.mutex.Unlock()
}
- previous.conn.Close()
+ previous.disconnect(previous.conn)
}
server.clients[character.id] = client
+ character.sitting = false
+ client.regenerationAt = time.Now()
+ client.regenerationSeconds = 0
+ // Health is session state; reconnecting revives a defeated player.
+ if character.health == 0 {
+ character.health = character.maximumHealth()
+ }
client.id = character.id
client.npcs = make(map[uint32]bool)
updates := [][]byte{playfieldPacket(character), characterPacket(character)}
for id, other := range server.characters {
if id != character.id && other.playfield == character.playfield && server.clients[id] != nil {
updates = append(updates, characterPacket(other))
+ if other.health == 0 {
+ updates = append(updates, deathPacket(other))
+ }
updates = append(updates, n3Packet(0x570c2039, 50000, other.id, nil))
}
}
@@ -306,22 +328,24 @@ func (server *server) serveWorldClient(client *worldClient) error {
updates = append(updates, server.chatServerPacket(conn))
}
updates = append(updates, fullCharacterPacket(character))
+ updates = append(updates, server.combatInterest_locked(client, nil)...)
updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked()))
spawn := characterPacket(character)
playfield := character.playfield
server.mutex.Unlock()
+ server.sendCombatUpdates(combatUpdates)
for _, update := range updates {
traceLog.Printf("World S2C: %x", update)
if err := client.send(update); err != nil {
- server.npcUpdateMutex.RUnlock()
+ server.updateMutex.Unlock()
return err
}
}
server.mutex.Lock()
client.ready = true
server.mutex.Unlock()
- server.npcUpdateMutex.RUnlock()
server.broadcast(playfield, character.id, spawn)
+ server.updateMutex.Unlock()
}
case 5:
// TextMessage_t wraps a length-prefixed, NUL-terminated string.
@@ -371,6 +395,10 @@ func (server *server) serveWorldClient(client *worldClient) error {
return fmt.Errorf("N3 message before character initialization")
}
switch binary.BigEndian.Uint32(body[0:4]) {
+ case 0x28494070, 0x4a41203e, 0x76793f0d:
+ if err := server.handleCombat(client, body); err != nil {
+ return err
+ }
case 0x3b132d64, 0x2103247d, 0x270a4c62:
if err := server.handleNPCDialogue(client, body); err != nil {
return err
@@ -388,11 +416,9 @@ func (server *server) serveWorldClient(client *worldClient) error {
return err
}
}
- response = n3Packet(0x5e477770, 50000, character.id, body[16:])
- server.mutex.Lock()
- playfield := character.playfield
- server.mutex.Unlock()
- server.broadcast(playfield, character.id, response)
+ if err := server.handlePosture(client, body); err != nil {
+ return err
+ }
case 120:
// Close the world connection when the client's logout countdown ends.
loggingOut = true
@@ -406,62 +432,13 @@ func (server *server) serveWorldClient(client *worldClient) error {
}
}
case 0x570c2039:
- response = n3Packet(0x570c2039, 50000, character.id, nil)
- server.mutex.Lock()
- client.loading = false
- playfield := character.playfield
- server.mutex.Unlock()
- server.broadcast(playfield, character.id, response)
- case 0x54111123:
- if client.target {
- if len(body) < 33 {
- return fmt.Errorf("short 14.9.1 movement message")
- }
- body = append(body[:16:16], decodeMovement1491(body[16:33])...)
- }
- if len(body) < 48 {
- return fmt.Errorf("short character movement message")
- }
- server.mutex.Lock()
- // Portal attempts can report the old position while a new zone loads.
- if !client.ready || client.loading {
- server.mutex.Unlock()
- continue
- }
- for i := range character.position {
- character.position[i] = math.Float32frombits(binary.BigEndian.Uint32(body[20+i*4:]))
- }
- for i := range character.rotation {
- character.rotation[i] = math.Float32frombits(binary.BigEndian.Uint32(body[32+i*4:]))
- }
- playfield := character.playfield
- client.movementStarted = time.Now()
- switch binary.BigEndian.Uint32(body[16:20]) {
- case 1:
- client.forward = 1
- case 3:
- client.forward = -1
- case 2, 4:
- client.forward = 0
- case 22, 23:
- character.running = binary.BigEndian.Uint32(body[16:20]) == 23
- }
- traceLog.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position)
- destination := server.zoneDestination_locked(character, client)
- if destination != nil {
- server.mutex.Unlock()
- traceLog.Printf("Character %d zoning %d -> %d", character.id, playfield, destination.Playfield)
- if err := server.updateUser(*destination); err != nil {
- return err
- }
- continue
+ if err := server.handleCharacterReady(client); err != nil {
+ return err
}
- if err := server.saveUser_locked(character); err != nil {
- server.mutex.Unlock()
+ case 0x54111123:
+ if err := server.handleMovement(client, body); err != nil {
return err
}
- server.mutex.Unlock()
- server.broadcast(playfield, character.id, n3Packet(0x54111123, 50000, character.id, body[16:]))
}
case 11:
// Return the client's ping with the reply subtype.
diff --git a/server/main_test.go b/server/main_test.go
@@ -229,6 +229,10 @@ func TestSitAndStandAreAcknowledged(t *testing.T) {
cookie, _ := hex.DecodeString("000400010001002000000001000000020000001b000000010000000000000000")
client.Write(cookie)
readWorldUpdates(t, client)
+ client.Write(n3Packet(0x570c2039, 50000, 1, nil))
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
sit, _ := hex.DecodeString("02eb000a0001002e000000010000000200000024789c8b732f2f6060381cc0c0c0c0cc0001610c6800005b3a02f90000")
stand, _ := hex.DecodeString("0000005700000000000000000000000000000000")
diff --git a/server/npcs.go b/server/npcs.go
@@ -26,7 +26,7 @@ func readNPCSpawns() ([]character, error) {
spawn := character{
id: 1000000 + uint32(len(spawns)), name: group.Name,
playfield: playfield.ID, position: position, rotation: [4]float32{0, 0, 0, 1},
- appearance: group.Appearance, monsterData: group.MonsterData, level: group.Level, npc: true,
+ appearance: group.Appearance, monsterData: group.MonsterData, level: group.Level, npc: true, health: 100,
npcDefinitionID: group.ID,
}
// Fixed posts and human placeholders have no inferred roaming behavior.
diff --git a/server/regeneration.go b/server/regeneration.go
@@ -0,0 +1,79 @@
+package main
+
+import (
+ "encoding/binary"
+ "time"
+)
+
+func (server *server) advanceRegeneration(now time.Time) {
+ // Serialize resource corrections with hit, stop, death and zone messages.
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ updates := make(map[*worldClient][][]byte)
+ for id, client := range server.clients {
+ if !client.ready || client.loading {
+ continue
+ }
+ if client.regenerationAt.IsZero() {
+ client.regenerationAt = now
+ continue
+ }
+ if now.Sub(client.regenerationAt) < 2*time.Second {
+ continue
+ }
+ // Keep the two-second phase through ordinary scheduler jitter; skip backlogs.
+ intervals := now.Sub(client.regenerationAt) / (2 * time.Second)
+ client.regenerationAt = client.regenerationAt.Add(intervals * 2 * time.Second)
+ client.regenerationSeconds += 2
+ player := server.characters[id]
+ if player.npc || player.health == 0 {
+ continue
+ }
+
+ // kkr.dll FUN_10074560 / FUN_1006ea50, with the native float reciprocal.
+ stats := player.baseStats()
+ percent := 100.0
+ if player.fighting != 0 {
+ percent = 200
+ }
+ healthInterval := uint32(max(1, int((30-float64(stats.Stamina)*float64(float32(1.0/30)))*percent*float64(float32(0.01)))))
+ nanoInterval := uint32(max(1, int((30-float64(stats.Psychic)*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) &^ 1
+ rest := uint32(100)
+ if player.sitting {
+ rest = 25
+ if healthInterval > 1 {
+ healthInterval >>= 1
+ }
+ }
+ bodyDevelopment := stats.effectiveSkill(stats.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0})
+ breed := player.appearance >> 4 & 7
+ if client.regenerationSeconds%healthInterval == 0 {
+ gain := bodyDevelopment/rest + [8]uint32{2, 3, 3, 2, 4, 6, 2, 2}[breed]
+ player.health = min(player.maximumHealth(), player.health+gain)
+ }
+ if nanoInterval == 0 || client.regenerationSeconds%nanoInterval == 0 {
+ gain := bodyDevelopment/rest + [8]uint32{2, 3, 3, 4, 2, 1, 2, 2}[breed]
+ player.nano = min(player.maximumNano(), player.nano+gain)
+ }
+
+ // Absolute HP must wait until weapon queues have been flushed by StopFight.
+ quiet := player.fighting == 0
+ for _, attacker := range server.fighting {
+ if attacker.fighting == player.id {
+ quiet = false
+ break
+ }
+ }
+ if quiet {
+ body := binary.BigEndian.AppendUint32(nil, 27)
+ body = binary.BigEndian.AppendUint32(body, player.health)
+ server.queueCombat_locked(updates, player, player, n3Packet(0x2b333d6e, 50000, id, body))
+ }
+ body := binary.BigEndian.AppendUint32(nil, 214)
+ body = binary.BigEndian.AppendUint32(body, player.nano)
+ updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, id, body))
+ }
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+}
diff --git a/server/regeneration_test.go b/server/regeneration_test.go
@@ -0,0 +1,226 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func newRegenerationWorld() (*server, *combatTestConn, time.Time) {
+ world, conn := newCombatWorld()
+ world.characters[1].appearance = 1 << 4
+ world.characters[1].level = 1
+ world.characters[1].health = 20
+ start := time.Unix(100, 0)
+ world.clients[1].regenerationAt = start
+ return world, conn, start
+}
+
+func TestRegenerationStandingUsesNativeCounterAndNanoInterval(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+
+ for second := 2; second <= 56; second += 2 {
+ world.advanceRegeneration(start.Add(time.Duration(second) * time.Second))
+ }
+ world.advanceRegeneration(start.Add(58*time.Second - time.Nanosecond))
+ if world.characters[1].health != 20 || world.characters[1].nano != 6 {
+ t.Fatalf("before health tick: %+v", world.characters[1])
+ }
+ world.advanceRegeneration(start.Add(58 * time.Second))
+
+ if world.characters[1].health != 23 || world.characters[1].nano != 6 {
+ t.Fatalf("standing recovery: %+v", world.characters[1])
+ }
+}
+
+func TestRegenerationSittingHalvesHealthInterval(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+ world.characters[1].sitting = true
+
+ for second := 2; second <= 14; second += 2 {
+ world.advanceRegeneration(start.Add(time.Duration(second) * time.Second))
+ }
+
+ if world.characters[1].health != 23 || world.characters[1].nano != 0 {
+ t.Fatalf("sitting recovery: %+v", world.characters[1])
+ }
+}
+
+func TestRegenerationCombatUsesLongerIntervalsWithoutAbsoluteHealth(t *testing.T) {
+ world, conn, start := newRegenerationWorld()
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+
+ for second := 2; second <= 116; second += 2 {
+ world.advanceRegeneration(start.Add(time.Duration(second) * time.Second))
+ }
+ if world.characters[1].health != 20 || world.characters[1].nano != 6 {
+ t.Fatalf("before combat health tick: %+v", world.characters[1])
+ }
+ world.advanceRegeneration(start.Add(118 * time.Second))
+
+ if world.characters[1].health != 23 || world.characters[1].nano != 6 {
+ t.Fatalf("combat recovery: %+v", world.characters[1])
+ }
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[29:33]) != 214 {
+ t.Fatalf("combat recovery changed queued health: %x", packet)
+ }
+ }
+}
+
+func TestRegenerationDoesNotCorrectHealthWhileOnlyTheEnemyAttacks(t *testing.T) {
+ world, conn, start := newRegenerationWorld()
+ world.characters[1000000].fighting = 1
+ world.fighting[1000000] = world.characters[1000000]
+
+ world.advanceRegeneration(start.Add(2 * time.Second))
+
+ if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 214 {
+ t.Fatalf("absolute HP interrupted an incoming hit: %x", conn.packets)
+ }
+}
+
+func TestRegenerationCorrectsAbsoluteIdleResourcesForOwnerAndObserver(t *testing.T) {
+ world, conn, start := newRegenerationWorld()
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950}
+ world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true}
+
+ world.advanceRegeneration(start.Add(2 * time.Second))
+
+ if len(conn.packets) != 2 || len(observer.packets) != 1 {
+ t.Fatalf("resource recipients: owner=%x observer=%x", conn.packets, observer.packets)
+ }
+ if binary.BigEndian.Uint32(conn.packets[0][29:33]) != 27 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 20 ||
+ binary.BigEndian.Uint32(conn.packets[1][29:33]) != 214 || binary.BigEndian.Uint32(conn.packets[1][33:37]) != 0 {
+ t.Fatalf("absolute resource correction: %x", conn.packets)
+ }
+}
+
+func TestRegenerationClampsHealthAndNanoToNativeMaximums(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+ world.characters[1].health = 36
+ world.characters[1].nano = 34
+ world.clients[1].regenerationSeconds = 810
+
+ world.advanceRegeneration(start.Add(2 * time.Second))
+
+ if world.characters[1].health != 37 || world.characters[1].nano != 35 {
+ t.Fatalf("resource overflow: %+v", world.characters[1])
+ }
+}
+
+func TestRegenerationSkipsDeadLoadingOfflineAndNPCCharacters(t *testing.T) {
+ for _, scenario := range []string{"dead", "loading", "not ready", "offline", "NPC"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn, start := newRegenerationWorld()
+ world.clients[1].regenerationSeconds = 810
+ switch scenario {
+ case "dead":
+ world.characters[1].health = 0
+ case "loading":
+ world.clients[1].loading = true
+ case "not ready":
+ world.clients[1].ready = false
+ case "offline":
+ delete(world.clients, 1)
+ case "NPC":
+ world.characters[1].npc = true
+ }
+ health := world.characters[1].health
+
+ world.advanceRegeneration(start.Add(2 * time.Second))
+
+ if world.characters[1].health != health || world.characters[1].nano != 0 || len(conn.packets) != 0 {
+ t.Fatalf("%s regenerated: %+v packets=%x", scenario, world.characters[1], conn.packets)
+ }
+ })
+ }
+}
+
+func TestRegenerationLateUpdateDoesNotReplayMissedTicks(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+
+ world.advanceRegeneration(start.Add(time.Hour))
+ world.advanceRegeneration(start.Add(time.Hour))
+
+ if world.characters[1].health != 20 || world.characters[1].nano != 0 || world.clients[1].regenerationSeconds != 2 {
+ t.Fatalf("late update replayed recovery: %+v", world.characters[1])
+ }
+}
+
+func TestRegenerationStoppingAttackPreservesCounterPhase(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ for second := 2; second <= 56; second += 2 {
+ world.advanceRegeneration(start.Add(time.Duration(second) * time.Second))
+ }
+
+ if err := world.handleCombat(world.clients[1], stopFightPacket(1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceRegeneration(start.Add(58 * time.Second))
+
+ if world.characters[1].health != 23 || world.clients[1].regenerationSeconds != 58 {
+ t.Fatalf("attack stop restarted resource recovery: %+v", world.characters[1])
+ }
+}
+
+func TestRegenerationNativeSitAndStandRequestsChangeRecovery(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ world.newCharacter().health = 20
+ client := connectZoningClient(t, world, true)
+ defer client.Close()
+
+ for _, action := range []uint32{86, 87} {
+ body := binary.BigEndian.AppendUint32(nil, action)
+ body = append(body, make([]byte, 16)...)
+ if _, err := client.Write(targetPacket(n3Packet(0x5e477770, 50000, 1, body))); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
+ world.mutex.Lock()
+ sitting := world.characters[1].sitting
+ world.mutex.Unlock()
+ if sitting != (action == 86) {
+ t.Fatalf("native posture action %d: sitting=%t", action, sitting)
+ }
+ }
+
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.characters[1].sitting || world.characters[1].health != 20 {
+ t.Fatal("posture requests changed resources or failed to stand")
+ }
+}
+
+func TestRegenerationFullCharacterPreservesNanoAndBreedMaximum(t *testing.T) {
+ for _, scenario := range []struct {
+ breed uint16
+ nano uint32
+ }{
+ {0, 18}, {1, 35}, {2, 34}, {3, 48}, {4, 24}, {5, 59}, {6, 18}, {7, 18},
+ } {
+ player := (&userData{ID: 1, Appearance: scenario.breed << 4, Level: 1}).character()
+ player.nano = 11
+
+ packet := fullCharacterPacket(player)
+ stats := make(map[uint32]uint32)
+ count := binary.BigEndian.Uint32(packet[64:68])/1009 - 1
+ for offset := 68; offset < 68+int(count)*8; offset += 8 {
+ stats[binary.BigEndian.Uint32(packet[offset:offset+4])] = binary.BigEndian.Uint32(packet[offset+4 : offset+8])
+ }
+
+ if stats[214] != 11 || stats[221] != scenario.nano {
+ t.Fatalf("breed %d: nano=%d max=%d", scenario.breed, stats[214], stats[221])
+ }
+ }
+}
diff --git a/server/roaming.go b/server/roaming.go
@@ -20,13 +20,15 @@ func (server *server) roamNPCs() {
defer ticker.Stop()
for now := range ticker.C {
server.advanceNPCs(now)
+ server.advanceCombat(now)
+ server.advanceRegeneration(now)
}
}
func (server *server) advanceNPCs(now time.Time) {
// Keep motion packets ordered with zone initialization.
- server.npcUpdateMutex.Lock()
- defer server.npcUpdateMutex.Unlock()
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
server.mutex.Lock()
seconds := math.Min(now.Sub(server.lastNPCUpdate).Seconds(), 0.25)
server.lastNPCUpdate = now
@@ -48,6 +50,9 @@ func (server *server) advanceNPCs(now time.Time) {
updates := make(map[uint32][]byte)
for zone := range zones {
for _, character := range server.roamingNPCs[zone] {
+ if character.fighting != 0 || character.health == 0 {
+ continue
+ }
if character.roaming.nextMove.IsZero() {
character.roaming.nextMove = now.Add(time.Duration(1+character.id%32) * 250 * time.Millisecond)
}
@@ -131,7 +136,7 @@ func (server *server) advanceNPCs(now time.Time) {
for _, packet := range packets {
if err := client.send(packet); err != nil {
log.Printf("NPC roaming: %v", err)
- client.conn.Close()
+ client.disconnect(client.conn)
break
}
}
diff --git a/server/roaming_test.go b/server/roaming_test.go
@@ -104,6 +104,13 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) {
binary.BigEndian.PutUint32(cookie, player.id)
client.Write(systemPacket(0x1b, cookie))
readWorldUpdates(t, client)
+ // A reply after initialization also synchronizes the live fixture state.
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+ client.Write(ping)
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
now := time.Now()
world.lastNPCUpdate = now
world.characters[1000000].roaming.destination = [3]float32{53.5, 14, 56}
@@ -118,6 +125,9 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) {
if err != nil {
return
}
+ if binary.BigEndian.Uint16(packet[2:4]) == 11 {
+ return
+ }
packets = append(packets, packet)
}
}()
@@ -125,7 +135,8 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) {
for tick := 1; tick <= 4; tick++ {
world.advanceNPCs(now.Add(time.Duration(tick) * 250 * time.Millisecond))
}
- client.Close()
+ // Drain all accepted movement before closing the asynchronous connection.
+ client.Write(ping)
<-done
if len(packets) != 1 || binary.BigEndian.Uint32(packets[0][36:40]) != 2 {
diff --git a/server/state.go b/server/state.go
@@ -19,6 +19,14 @@ type character struct {
appearance uint16
monsterData uint32
level uint16
+ stats characterStats
+ health uint32
+ nano uint32
+ sitting bool
+ aggDef int32
+ fighting uint32
+ nextAttack time.Time
+ rechargeUntil time.Time
running bool
returnDoor *doorOrigin
npc bool
@@ -32,17 +40,19 @@ type character struct {
}
type worldClient struct {
- conn net.Conn
- stream *browserStream
- mutex sync.Mutex
- ready bool
- loading bool
- id uint32
- target bool
- forward float32
- movementStarted time.Time
- npcs map[uint32]bool
- dialogue *npcDialogue
+ clientOutput
+ conn net.Conn
+ stream *browserStream
+ ready bool
+ loading bool
+ id uint32
+ target bool
+ forward float32
+ movementStarted time.Time
+ regenerationAt time.Time
+ regenerationSeconds uint32
+ npcs map[uint32]bool
+ dialogue *npcDialogue
}
func (client *worldClient) send(packet []byte) error {
@@ -54,21 +64,22 @@ func (client *worldClient) send(packet []byte) error {
packet = targetPacket(packet)
}
binary.BigEndian.PutUint32(packet[12:16], client.id)
- _, err := client.conn.Write(packet)
- return err
+ return client.enqueue_locked(client.conn, packet)
}
type server struct {
- loginPort int
- worldPort int
- httpPort int
- baseURL string
- mutex sync.Mutex
- npcUpdateMutex sync.RWMutex
+ loginPort int
+ worldPort int
+ httpPort int
+ baseURL string
+ mutex sync.Mutex
+ // Order entity-state packet batches; acquire before mutex.
+ updateMutex sync.Mutex
nextCharacter uint32
characters map[uint32]*character
roamingNPCs map[uint32][]*character
clients map[uint32]*worldClient
+ fighting map[uint32]*character
chats map[uint32]*chatClient
chatLogMutex sync.Mutex
browserStreams map[string]*browserStream
@@ -87,6 +98,7 @@ func newServer() *server {
characters: make(map[uint32]*character),
roamingNPCs: make(map[uint32][]*character),
clients: make(map[uint32]*worldClient),
+ fighting: make(map[uint32]*character),
chats: make(map[uint32]*chatClient),
}
ground, err := readTerrain()
@@ -133,7 +145,9 @@ func (server *server) newCharacter_locked() *character {
id: server.nextCharacter, name: fmt.Sprintf("Local Explorer %d", server.nextCharacter),
playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((server.nextCharacter-1)%4)*3},
rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1,
+ stats: defaultCharacterStats(),
}
+ character.health = character.maximumHealth()
server.characters[character.id] = character
return character
}
@@ -152,7 +166,7 @@ func (server *server) broadcast(playfield, exclude uint32, packet []byte) {
for _, client := range clients {
if err := client.send(packet); err != nil {
log.Printf("World broadcast: %v", err)
- client.conn.Close()
+ client.disconnect(client.conn)
}
}
}
diff --git a/server/stats.go b/server/stats.go
@@ -0,0 +1,37 @@
+package main
+
+type characterStats struct {
+ Strength uint16 `yaml:"strength"`
+ Agility uint16 `yaml:"agility"`
+ Stamina uint16 `yaml:"stamina"`
+ Intelligence uint16 `yaml:"intelligence"`
+ Sense uint16 `yaml:"sense"`
+ Psychic uint16 `yaml:"psychic"`
+ MartialArts uint16 `yaml:"martial_arts"`
+ PhysicalInitiative uint16 `yaml:"physical_initiative"`
+ BodyDevelopment uint16 `yaml:"body_development"`
+ NanoPool uint16 `yaml:"nano_pool"`
+}
+
+func defaultCharacterStats() characterStats {
+ return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5}
+}
+
+func (character *character) baseStats() characterStats {
+ // Profiles saved before stats were editable retain their original defaults.
+ if character.stats == (characterStats{}) {
+ return defaultCharacterStats()
+ }
+ return character.stats
+}
+
+func (stats characterStats) effectiveSkill(base uint16, weights [6]uint32) uint32 {
+ // kkr.dll FUN_10073fa0, weights from resource type 1000204.
+ abilities := [6]uint16{stats.Strength, stats.Agility, stats.Stamina, stats.Intelligence, stats.Sense, stats.Psychic}
+ var weighted uint32
+ for index, ability := range abilities {
+ weighted += uint32(ability) * weights[index]
+ }
+ // Preserve the native float constants before truncating at integer boundaries.
+ return uint32(base) + uint32(float64(weighted)*float64(float32(0.01))*0.25)
+}
diff --git a/server/stats_test.go b/server/stats_test.go
@@ -0,0 +1,112 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func TestCharacterStatsDeriveHealthNanoAndAttackTiming(t *testing.T) {
+ stats := defaultCharacterStats()
+ stats.Stamina, stats.Psychic = 60, 120
+ stats.BodyDevelopment, stats.NanoPool = 200, 100
+ stats.MartialArts, stats.PhysicalInitiative = 100, 100
+ data := userData{ID: 1, Level: 1, Appearance: 1 << 4, Stats: stats}
+
+ player := data.character()
+ attack, recharge := player.attackDelays()
+ packet := fullCharacterPacket(player)
+ values := make(map[uint32]uint32)
+ count := binary.BigEndian.Uint32(packet[64:68])/1009 - 1
+ for offset := 68; offset < 68+int(count)*8; offset += 8 {
+ values[binary.BigEndian.Uint32(packet[offset:offset+4])] = binary.BigEndian.Uint32(packet[offset+4 : offset+8])
+ }
+
+ if player.health != 658 || player.maximumNano() != 380 || attack != 1820*time.Millisecond || recharge != 1640*time.Millisecond {
+ t.Fatalf("derived stats: health=%d nano=%d delays=%v/%v", player.health, player.maximumNano(), attack, recharge)
+ }
+ if values[18] != 60 || values[21] != 120 || values[100] != 100 || values[120] != 100 || values[152] != 200 || values[132] != 100 {
+ t.Fatalf("base stats sent as effective skills: %v", values)
+ }
+}
+
+func TestCharacterStatsPersistThroughProfileEditAndRestart(t *testing.T) {
+ world := newTestServer(t)
+ player := world.newCharacter()
+ destination := player.userData()
+ destination.Stats.Stamina = 60
+ destination.Stats.BodyDevelopment = 200
+
+ if err := world.updateUser(destination); err != nil {
+ t.Fatal(err)
+ }
+ restarted := newServer()
+
+ if restarted.characters[1].baseStats().Stamina != 60 || restarted.characters[1].baseStats().BodyDevelopment != 200 || restarted.characters[1].health != 658 {
+ t.Fatalf("stats lost across restart: %+v", restarted.characters[1])
+ }
+}
+
+func TestCharacterStatsProfileEditClampsBothResources(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _, _ := newRegenerationWorld()
+ world.characters[1].stats = defaultCharacterStats()
+ world.characters[1].stats.BodyDevelopment = 300
+ world.characters[1].stats.NanoPool = 300
+ world.characters[1].health, world.characters[1].nano = 500, 500
+ destination := world.characters[1].userData()
+ destination.Stats = defaultCharacterStats()
+
+ err := world.updateUser(destination)
+
+ if err != nil || world.characters[1].health != 37 || world.characters[1].nano != 35 {
+ t.Fatalf("resources exceed edited stats: %+v, %v", world.characters[1], err)
+ }
+}
+
+func TestRegenerationUsesEditedAbilitiesAndBodyDevelopment(t *testing.T) {
+ for _, sitting := range []bool{false, true} {
+ world, _, start := newRegenerationWorld()
+ world.characters[1].stats = defaultCharacterStats()
+ world.characters[1].stats.Stamina, world.characters[1].stats.Psychic = 60, 120
+ world.characters[1].stats.BodyDevelopment, world.characters[1].stats.NanoPool = 200, 100
+ world.characters[1].sitting = sitting
+
+ for second := 2; second <= 54; second += 2 {
+ world.advanceRegeneration(start.Add(time.Duration(second) * time.Second))
+ }
+
+ health, nano := uint32(25), uint32(10)
+ if sitting {
+ health, nano = 42, 22
+ }
+ if world.characters[1].health != health || world.characters[1].nano != nano {
+ t.Fatalf("edited recovery sitting=%t: %+v", sitting, world.characters[1])
+ }
+ }
+}
+
+func TestRegenerationHandlesMinimumIntervals(t *testing.T) {
+ world, _, start := newRegenerationWorld()
+ world.characters[1].stats = defaultCharacterStats()
+ world.characters[1].stats.Stamina, world.characters[1].stats.Psychic = 1000, 1000
+
+ world.advanceRegeneration(start.Add(2 * time.Second))
+
+ if world.characters[1].health != 25 || world.characters[1].nano != 5 {
+ t.Fatalf("minimum interval recovery: %+v", world.characters[1])
+ }
+}
+
+func TestCharacterStatsAttackTimingPreservesNativeFloatRounding(t *testing.T) {
+ stats := defaultCharacterStats()
+ stats.PhysicalInitiative = 385
+ player := (&userData{ID: 1, Level: 1, Appearance: 1 << 4, Stats: stats}).character()
+ player.aggDef = -100
+
+ attack, recharge := player.attackDelays()
+
+ if attack != 2350*time.Millisecond || recharge != 1700*time.Millisecond {
+ t.Fatalf("native float timing: %v/%v", attack, recharge)
+ }
+}
diff --git a/server/target_protocol.go b/server/target_protocol.go
@@ -15,14 +15,18 @@ func targetPacket(packet []byte) []byte {
packet = packet[:93]
case 0x271b3a6b:
packet[36] = '0'
+ flags := binary.BigEndian.Uint32(packet[37:41])
// Appearance has a wider race field and shifts every subsequent field.
appearance := uint32(binary.BigEndian.Uint16(packet[67:69]))
packed := appearance&3 | (appearance>>2&3)<<3 | (appearance>>4&7)<<5
packed |= (appearance>>7&3)<<8 | (appearance>>9&3)<<10 | (appearance>>11&31)<<12
+ if flags&1 != 0 && appearance>>4&7 == 6 {
+ // Local PvE creatures use the monster side for enemy targeting.
+ packed = packed&^7 | 3
+ }
tail := append([]byte(nil), packet[69:]...)
packet = binary.BigEndian.AppendUint32(packet[:67], packed)
packet = append(packet, tail...)
- flags := binary.BigEndian.Uint32(packet[37:41])
nameEnd := 72 + int(packet[71])
if flags&1 != 0 {
// kkr.dll SimpleChar 0x10082da0: DWORD and four shorts after NPC names.
@@ -55,6 +59,15 @@ func targetPacket(packet []byte) []byte {
tail = append([]byte(nil), packet[len(packet)-4:]...)
packet = append(packet[:len(packet)-4], 0, 0, 0)
packet = append(packet, tail...)
+ // Supply the client's unarmed weapon in slot 0 for hit animation and damage.
+ if flags&1 != 0 {
+ // Tab targeting requires NPC stat 194 (InPlay), supplied by flag bit 1.
+ flags |= 2
+ }
+ binary.BigEndian.PutUint32(packet[37:41], flags|0x100)
+ for _, value := range []uint32{2018, 43712, 43713, 100, 1} {
+ packet = binary.BigEndian.AppendUint32(packet, value)
+ }
case 0x29304349:
// FullCharacter has seven encoded lists before its stats.
tail := append([]byte(nil), packet[64:]...)
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -10,6 +10,38 @@ import (
"time"
)
+func TestTargetCharactersIncludeUnarmedWeapon(t *testing.T) {
+ for _, actor := range []*character{
+ {id: 1, name: "Player", appearance: 0x629, health: 100},
+ {id: 1000000, name: "Leet", appearance: 0xe5, npc: true, health: 100},
+ {id: 1000001, name: "Guard", appearance: 0x315, npc: true, health: 100},
+ } {
+ t.Run(actor.name, func(t *testing.T) {
+ packet := characterPacket(actor)
+
+ packet = targetPacket(packet)
+ packet = packet[:binary.BigEndian.Uint16(packet[6:8])]
+
+ if binary.BigEndian.Uint32(packet[30:34])&0x100 == 0 {
+ t.Fatal("missing weapon template flag")
+ }
+ if actor.npc && binary.BigEndian.Uint32(packet[30:34])&2 == 0 {
+ t.Fatal("NPC is not in play for Tab targeting")
+ }
+ if actor.name == "Leet" {
+ if binary.BigEndian.Uint32(packet[60:64]) != 0x1cb {
+ t.Fatal("creature appearance did not retain its model fields with monster side")
+ }
+ } else if binary.BigEndian.Uint32(packet[60:64])&7 != 1 {
+ t.Fatal("player or human NPC faction changed")
+ }
+ if got := hex.EncodeToString(packet[len(packet)-20:]); got != "000007e20000aac00000aac10000006400000001" {
+ t.Fatalf("unarmed weapon list: %s", got)
+ }
+ })
+ }
+}
+
func TestTargetWorldInitializationUsesRecoveredLayouts(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
@@ -47,10 +79,10 @@ initialized:
if len(playfield) != 86 || player[29] != '0' || hex.EncodeToString(player[60:65]) != "0000062911" || string(player[65:82]) != "Local Explorer 1\x00" {
t.Fatalf("target playfield or player: %x %x", playfield, player)
}
- if hex.EncodeToString(npc[60:89]) != "000001c90b456469746564204e50430000000000000000000000000007" {
+ if hex.EncodeToString(npc[60:89]) != "000001cb0b456469746564204e50430000000000000000000000000007" {
t.Fatalf("target NPC appearance, name and new stats: %x", npc[60:89])
}
- if hex.EncodeToString(full[57:73]) != "000003f100003f100000003600000001" {
+ if hex.EncodeToString(full[57:73]) != "000003f10000667a0000003600000001" {
t.Fatalf("target seventh list and first stat: %x", full[57:73])
}
}
diff --git a/server/users.go b/server/users.go
@@ -20,28 +20,30 @@ import (
// User IDs are stable; each local user currently owns one character.
type userData struct {
- ID uint32 `yaml:"id"`
- Name string `yaml:"name"`
- Playfield uint32 `yaml:"playfield"`
- Position [3]float32 `yaml:"position,flow"`
- Rotation [4]float32 `yaml:"rotation,flow"`
- Appearance uint16 `yaml:"appearance"`
- MonsterData uint32 `yaml:"monster_data"`
- Level uint16 `yaml:"level"`
- Running bool `yaml:"running"`
- ReturnDoor *doorOrigin `yaml:"return_door,omitempty"`
+ ID uint32 `yaml:"id"`
+ Name string `yaml:"name"`
+ Playfield uint32 `yaml:"playfield"`
+ Position [3]float32 `yaml:"position,flow"`
+ Rotation [4]float32 `yaml:"rotation,flow"`
+ Appearance uint16 `yaml:"appearance"`
+ MonsterData uint32 `yaml:"monster_data"`
+ Level uint16 `yaml:"level"`
+ Stats characterStats `yaml:"stats"`
+ Running bool `yaml:"running"`
+ ReturnDoor *doorOrigin `yaml:"return_door,omitempty"`
BrowserTokenHash string `yaml:"browser_token_hash,omitempty"`
}
type playerProfile struct {
- ID uint32 `yaml:"id"`
- Name string `yaml:"name"`
- Appearance uint16 `yaml:"appearance"`
- MonsterData uint32 `yaml:"monster_data"`
- Level uint16 `yaml:"level"`
- Running bool `yaml:"running"`
- BrowserTokenHash string `yaml:"browser_token_hash,omitempty"`
+ ID uint32 `yaml:"id"`
+ Name string `yaml:"name"`
+ Appearance uint16 `yaml:"appearance"`
+ MonsterData uint32 `yaml:"monster_data"`
+ Level uint16 `yaml:"level"`
+ Stats characterStats `yaml:"stats"`
+ Running bool `yaml:"running"`
+ BrowserTokenHash string `yaml:"browser_token_hash,omitempty"`
}
type playerPosition struct {
@@ -53,14 +55,18 @@ type playerPosition struct {
func (character *character) userData() userData {
return userData{character.id, character.name, character.playfield, character.position,
- character.rotation, character.appearance, character.monsterData, character.level, character.running, character.returnDoor, character.browserTokenHash}
+ character.rotation, character.appearance, character.monsterData, character.level, character.baseStats(), character.running, character.returnDoor, character.browserTokenHash}
}
func (data userData) character() *character {
- return &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position,
+ character := &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position,
rotation: data.Rotation, appearance: data.Appearance, monsterData: data.MonsterData, level: data.Level,
running: data.Running,
+ stats: data.Stats,
returnDoor: data.ReturnDoor, browserTokenHash: data.BrowserTokenHash}
+ character.stats = character.baseStats()
+ character.health = character.maximumHealth()
+ return character
}
func (data userData) validate() error {
@@ -77,6 +83,10 @@ func (data userData) validate() error {
if data.Level == 0 {
return fmt.Errorf("level must be at least 1")
}
+ if data.Stats != (characterStats{}) && (data.Stats.Strength == 0 || data.Stats.Agility == 0 || data.Stats.Stamina == 0 ||
+ data.Stats.Intelligence == 0 || data.Stats.Sense == 0 || data.Stats.Psychic == 0) {
+ return fmt.Errorf("abilities must be at least 1")
+ }
for index, value := range data.Position {
minimum, maximum := float32(0), float32(8191.875)
if index == 1 {
@@ -141,7 +151,7 @@ func (server *server) loadUsers() error {
}
user := userData{
ID: profile.ID, Name: profile.Name, Appearance: profile.Appearance,
- MonsterData: profile.MonsterData, Level: profile.Level, Running: profile.Running,
+ MonsterData: profile.MonsterData, Level: profile.Level, Stats: profile.Stats, Running: profile.Running,
BrowserTokenHash: profile.BrowserTokenHash,
Playfield: position.Playfield, Position: position.Position,
Rotation: position.Rotation, ReturnDoor: position.ReturnDoor,
@@ -180,7 +190,7 @@ func (server *server) users_locked() []userData {
func (server *server) saveUser_locked(character *character) error {
// Ordinary movement never rewrites identity, credentials or character properties.
profile := playerProfile{character.id, character.name, character.appearance, character.monsterData,
- character.level, character.running, character.browserTokenHash}
+ character.level, character.baseStats(), character.running, character.browserTokenHash}
if profile == character.savedProfile {
return nil
}
diff --git a/server/world.go b/server/world.go
@@ -84,7 +84,8 @@ func characterPacket(character *character) []byte {
for _, value := range []uint32{0, 0, 0} {
body = binary.BigEndian.AppendUint32(body, value)
}
- for _, value := range []uint16{10, 10, 10, 10} {
+ stats := character.baseStats()
+ for _, value := range []uint16{stats.Strength, stats.Agility, stats.Stamina, stats.Intelligence} {
body = binary.BigEndian.AppendUint16(body, value)
}
}
@@ -93,7 +94,7 @@ func characterPacket(character *character) []byte {
} else {
body = append(body, byte(character.level))
}
- for _, value := range []uint32{100, 100, character.monsterData} {
+ for _, value := range []uint32{character.maximumHealth(), character.health, character.monsterData} {
body = binary.BigEndian.AppendUint32(body, value)
}
body = binary.BigEndian.AppendUint16(body, 100)
@@ -145,7 +146,13 @@ func fullCharacterPacket(character *character) []byte {
for range 6 {
body = binary.BigEndian.AppendUint32(body, 1009)
}
- stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {47, 1}, {60, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, 10}, {17, 10}, {18, 10}, {19, 10}, {20, 10}, {21, 10}, {27, 100}, {123, 100}, {124, 100}}
+ base := character.baseStats()
+ stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, 1}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, 100}, {124, 100}, {37, character.titleLevel()}}
+ stats = append(stats, [2]uint32{51, uint32(character.aggDef)})
+ stats = append(stats, [2]uint32{47, uint32(character.appearance >> 2 & 3)})
+ stats = append(stats, [2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano()})
+ stats = append(stats, [2]uint32{100, uint32(base.MartialArts)}, [2]uint32{120, uint32(base.PhysicalInitiative)},
+ [2]uint32{152, uint32(base.BodyDevelopment)}, [2]uint32{132, uint32(base.NanoPool)})
body = binary.BigEndian.AppendUint32(body, uint32(len(stats)+1)*1009)
for _, stat := range stats {
body = binary.BigEndian.AppendUint32(body, stat[0])
diff --git a/server/world_actions.go b/server/world_actions.go
@@ -0,0 +1,97 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+ "time"
+)
+
+func (server *server) handlePosture(client *worldClient, body []byte) error {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ character := server.characters[client.id]
+ if server.clients[client.id] != client || !client.ready || client.loading || character.health == 0 {
+ server.mutex.Unlock()
+ return nil
+ }
+ character.sitting = binary.BigEndian.Uint32(body[16:20]) == 86
+ playfield := character.playfield
+ server.mutex.Unlock()
+
+ // Publish posture before another resource update uses its rest modifier.
+ response := n3Packet(0x5e477770, 50000, client.id, body[16:])
+ server.broadcast(playfield, client.id, response)
+ return client.send(response)
+}
+
+func (server *server) handleCharacterReady(client *worldClient) error {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ if server.clients[client.id] != client || !client.ready {
+ server.mutex.Unlock()
+ return nil
+ }
+ client.loading = false
+ playfield := server.characters[client.id].playfield
+ server.mutex.Unlock()
+
+ response := n3Packet(0x570c2039, 50000, client.id, nil)
+ server.broadcast(playfield, client.id, response)
+ return client.send(response)
+}
+
+func (server *server) handleMovement(client *worldClient, body []byte) error {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ if client.target {
+ if len(body) < 33 {
+ return fmt.Errorf("short 14.9.1 movement message")
+ }
+ body = append(body[:16:16], decodeMovement1491(body[16:33])...)
+ }
+ if len(body) < 48 {
+ return fmt.Errorf("short character movement message")
+ }
+ server.mutex.Lock()
+ character := server.characters[client.id]
+ // Portal attempts can report the old position while a new zone loads.
+ if server.clients[client.id] != client || !client.ready || client.loading || character.health == 0 {
+ server.mutex.Unlock()
+ return nil
+ }
+ for i := range character.position {
+ character.position[i] = math.Float32frombits(binary.BigEndian.Uint32(body[20+i*4:]))
+ }
+ for i := range character.rotation {
+ character.rotation[i] = math.Float32frombits(binary.BigEndian.Uint32(body[32+i*4:]))
+ }
+ playfield := character.playfield
+ client.movementStarted = time.Now()
+ switch binary.BigEndian.Uint32(body[16:20]) {
+ case 1:
+ client.forward = 1
+ case 3:
+ client.forward = -1
+ case 2, 4:
+ client.forward = 0
+ case 22, 23:
+ character.running = binary.BigEndian.Uint32(body[16:20]) == 23
+ }
+ traceLog.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position)
+ destination := server.zoneDestination_locked(character, client)
+ if destination != nil {
+ server.mutex.Unlock()
+ traceLog.Printf("Character %d zoning %d -> %d", client.id, playfield, destination.Playfield)
+ return server.updateUser_locked(*destination)
+ }
+ if err := server.saveUser_locked(character); err != nil {
+ server.mutex.Unlock()
+ return err
+ }
+ server.mutex.Unlock()
+ server.broadcast(playfield, client.id, n3Packet(0x54111123, 50000, client.id, body[16:]))
+ return nil
+}
diff --git a/server/world_output_test.go b/server/world_output_test.go
@@ -0,0 +1,227 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "net"
+ "sync"
+ "testing"
+ "time"
+)
+
+type shortWorldConn struct {
+ net.Conn
+ closed bool
+}
+
+type blockingCloseConn struct {
+ net.Conn
+ started chan struct{}
+ release chan struct{}
+}
+
+func (conn *blockingCloseConn) Close() error {
+ close(conn.started)
+ <-conn.release
+ return conn.Conn.Close()
+}
+
+func TestWorldReplacementDoesNotWaitForOldTransportClose(t *testing.T) {
+ world, _ := newCombatWorld()
+ host, peer := net.Pipe()
+ conn := &blockingCloseConn{Conn: host, started: make(chan struct{}), release: make(chan struct{})}
+ old := world.clients[1]
+ old.conn = conn
+ old.startWriter(conn)
+ replacement := &combatInterestConn{input: bytes.NewReader(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}))}
+ done := make(chan error, 1)
+ t.Cleanup(func() { close(conn.release); peer.Close(); old.finishWriter(); <-done })
+
+ go func() { done <- world.serveWorldClient(&worldClient{conn: replacement}); close(done) }()
+ select {
+ case <-conn.started:
+ case <-time.After(time.Second):
+ t.Fatal("replaced transport was not closed")
+ }
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(250 * time.Millisecond):
+ t.Fatal("replacing a session waited for the old transport's close handshake")
+ }
+}
+
+func (conn *shortWorldConn) SetWriteDeadline(time.Time) error { return nil }
+func (conn *shortWorldConn) Write(packet []byte) (int, error) { return len(packet) - 1, nil }
+func (conn *shortWorldConn) Close() error {
+ conn.closed = true
+ return nil
+}
+
+func TestWorldOutputPreservesOrderAndOwnsQueuedPacketBytes(t *testing.T) {
+ host, peer := net.Pipe()
+ peer.SetReadDeadline(time.Now().Add(time.Second))
+ client := &worldClient{conn: host, id: 7, target: true}
+ client.startWriter(client.conn)
+ t.Cleanup(func() { peer.Close(); client.finishWriter() })
+ first := attackPacket(1, 1000000)
+ expected := targetPacket(attackPacket(1, 1000000))
+ binary.BigEndian.PutUint32(expected[12:16], 7)
+
+ if err := client.send(first); err != nil {
+ t.Fatal(err)
+ }
+ first[40] = 99
+ if err := client.send(stopFightPacket(1)); err != nil {
+ t.Fatal(err)
+ }
+ attack, err := readPacket(peer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stop, err := readPacket(peer)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if !bytes.Equal(attack, expected[:binary.BigEndian.Uint16(expected[6:8])]) || binary.BigEndian.Uint32(stop[16:20]) != 0x4a41203e {
+ t.Fatalf("queued bytes changed or reordered: %x %x", attack, stop)
+ }
+}
+
+func TestWorldOutputRejectsQueueOverflowAndReleasesPendingBytes(t *testing.T) {
+ host, peer := net.Pipe()
+ conn := &stalledCombatConn{Conn: host, started: make(chan struct{})}
+ client := &worldClient{conn: conn, id: 1}
+ client.startWriter(client.conn)
+ t.Cleanup(func() { peer.Close(); client.finishWriter() })
+ if err := client.send(systemPacket(0, nil)); err != nil {
+ t.Fatal(err)
+ }
+ <-conn.started
+ packet := systemPacket(0, make([]byte, 60000))
+
+ var sendErr error
+ for range 150 {
+ if sendErr = client.send(packet); sendErr != nil {
+ break
+ }
+ }
+ // Release the in-flight write after overflow has discarded pending output.
+ peer.Close()
+ select {
+ case <-client.writeDone:
+ case <-time.After(time.Second):
+ t.Fatal("queue overflow did not close the blocked writer")
+ }
+
+ if sendErr == nil || !errors.Is(client.send(packet), net.ErrClosed) || len(client.outgoing) != 0 || client.outgoingBytes != 0 {
+ t.Fatalf("overflow left an open queue: err=%v bytes=%d", sendErr, client.outgoingBytes)
+ }
+}
+
+func TestWorldOutputShortWriteClosesTheConnection(t *testing.T) {
+ conn := &shortWorldConn{}
+ client := &worldClient{conn: conn, id: 1}
+ client.startWriter(client.conn)
+ t.Cleanup(client.finishWriter)
+
+ if err := client.send(systemPacket(0, nil)); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-client.writeDone:
+ case <-time.After(time.Second):
+ t.Fatal("short write left the writer running")
+ }
+
+ if !conn.closed || !errors.Is(client.send(systemPacket(0, nil)), net.ErrClosed) {
+ t.Fatal("short write left the protocol stream usable")
+ }
+}
+
+func TestWorldOutputUnresponsivePeerIsDisconnected(t *testing.T) {
+ host, peer := net.Pipe()
+ client := &worldClient{conn: host, id: 1}
+ client.startWriter(client.conn)
+ t.Cleanup(func() { peer.Close(); client.finishWriter() })
+
+ if err := client.send(systemPacket(0, nil)); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-client.writeDone:
+ case <-time.After(6 * time.Second):
+ t.Fatal("unresponsive peer outlived its write deadline")
+ }
+
+ if !errors.Is(client.send(systemPacket(0, nil)), net.ErrClosed) || client.outgoingBytes != 0 {
+ t.Fatal("timed out output remained usable")
+ }
+}
+
+func TestWorldOutputConcurrentProducersPreserveEachPacketSequence(t *testing.T) {
+ host, peer := net.Pipe()
+ peer.SetReadDeadline(time.Now().Add(3 * time.Second))
+ client := &worldClient{conn: host, id: 1}
+ client.startWriter(client.conn)
+ t.Cleanup(func() { peer.Close(); client.finishWriter() })
+ var producers sync.WaitGroup
+ sendErrors := make(chan error, 4)
+
+ for producer := range uint32(4) {
+ producers.Add(1)
+ go func() {
+ defer producers.Done()
+ for sequence := range uint32(100) {
+ body := binary.BigEndian.AppendUint32(nil, producer)
+ body = binary.BigEndian.AppendUint32(body, sequence)
+ if err := client.send(systemPacket(0, body)); err != nil {
+ sendErrors <- err
+ return
+ }
+ }
+ }()
+ }
+ producers.Wait()
+ close(sendErrors)
+ for err := range sendErrors {
+ t.Fatal(err)
+ }
+ counts := [4]uint32{}
+ for range 400 {
+ packet, err := readPacket(peer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ producer, sequence := binary.BigEndian.Uint32(packet[20:24]), binary.BigEndian.Uint32(packet[24:28])
+ if producer >= 4 || sequence != counts[producer] {
+ t.Fatalf("interleaved or reordered stream: %x counts=%v", packet, counts)
+ }
+ counts[producer]++
+ }
+
+ if counts != [4]uint32{100, 100, 100, 100} {
+ t.Fatalf("lost packets: %v", counts)
+ }
+}
+
+func TestWorldOutputDrainsAcceptedPacketsWhenSessionEnds(t *testing.T) {
+ conn := &combatInterestConn{input: bytes.NewReader(nil)}
+ client := &worldClient{conn: conn, id: 1}
+ client.startWriter(client.conn)
+ packet := systemPacket(0, []byte{1, 2, 3, 4})
+ if err := client.send(packet); err != nil {
+ t.Fatal(err)
+ }
+
+ client.finishWriter()
+
+ if len(conn.packets) != 1 || !bytes.Equal(conn.packets[0][20:24], []byte{1, 2, 3, 4}) {
+ t.Fatalf("session shutdown dropped accepted output: %x", conn.packets)
+ }
+}
diff --git a/server/zoning.go b/server/zoning.go
@@ -163,6 +163,8 @@ func (server *server) checkZoneCrossings() {
}
func (server *server) advanceZoneCrossings(now time.Time) {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
// The native client sends start/stop controls rather than every walking frame.
// Predict only trigger checks; received coordinates remain authoritative.
server.mutex.Lock()
@@ -172,6 +174,9 @@ func (server *server) advanceZoneCrossings(now time.Time) {
continue
}
character := *server.characters[id]
+ if character.health == 0 {
+ continue
+ }
character.position = predictedPosition_locked(&character, client, now)
if destination := server.zoneDestination_locked(&character, client); destination != nil {
destinations = append(destinations, *destination)
@@ -179,7 +184,7 @@ func (server *server) advanceZoneCrossings(now time.Time) {
}
server.mutex.Unlock()
for _, destination := range destinations {
- if err := server.updateUser(destination); err != nil {
+ if err := server.updateUser_locked(destination); err != nil {
log.Printf("Automatic zoning: %v", err)
}
}