commit a083777bd248a21c260ea1d11805002d47b543ce
parent be1c1b09be604371b0957f3543df5979c221ca78
Author: anon <anon@example.com>
Date: Fri, 6 Nov 2026 01:26:31 +0000
Implement Brawl damage, stun and persistent cooldown
Diffstat:
16 files changed, 689 insertions(+), 42 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -141,8 +141,11 @@ research separately. More screenshots and test cases do not count as new gamepla
damage/rewards and native inventory/reconnect checks at level one.
[Burst](docs/burst.md) now executes for the issued Solar SMG and stocked
Kerans, retaining ammunition under the pre-15.5 policy and committing its
- damage/rewards with a persistent cooldown. Brawl/Dimach and Aimed Shot remain
- explicit weapon-special gaps.
+ damage/rewards with a persistent cooldown. [Brawl](docs/brawl.md) now has its
+ native action, independent damage item, timed stun and atomic persistent
+ cooldown, with fists and stocked Sledgehammer input/recovery checks.
+ Dimach and Aimed Shot remain explicit weapon-special gaps; Aimed Shot depends
+ on the unfinished sneak/concealment lifecycle.
Remaining profession essentials stay open. The
[bounded earned affordability sample](docs/early-shop-stock.md#earned-affordability-sample-november-5)
now completes an ordinary level-two Omni mission, buys and wears gloves,
diff --git a/docs/brawl.md b/docs/brawl.md
@@ -1,8 +1,9 @@
-# Brawl: original content and native contracts
+# Brawl on fists and early melee weapons
-Brawl is not yet implemented by the server. This investigation establishes the
-shipped content and client contracts without substituting a wielded weapon's
-normal damage or Martial Arts skill-to-QL rule for Brawl's own calculation.
+Brawl now executes through the shared special-attack handler, using its own
+item, skill, damage, stun and persistent cooldown. Fists and Brawl-capable held
+weapons are admitted. The original content below establishes the contract;
+unrecovered server balance rules are explicitly bounded by the alpha policy.
## Authored content
@@ -84,10 +85,9 @@ ranged specials, but omits Brawl142 and Dimach144. The initializer supplies a
Brawl icon mapping without creating its action. Merely setting Brawling or
equipping a Brawl-capable weapon does not invoke the shown registration path.
-The current server supplies only implicit Martial Arts100. Brawl implementation
-must also supply the appropriate implicit item row so the native client creates
-its action. Adding that row alone would expose a request without implementing
-its authoritative outcome. Exact source records and heap layout are retained in
+Player spawn packets now supply implicit Martial Arts100 and Brawl142, with
+Brawl endpoints70292/70293. NPC spawn profiles retain their existing attack row.
+The Brawl row creates the native actor-owned action. Exact source records and heap layout are retained in
`local/brawl-research/native/action-availability.md`.
## Evidence limits and implementation work
@@ -98,15 +98,42 @@ not give Brawl skill/2. The existing bounded Rustot emulator search recovered
no verified period artifact. Current Auno70293 has matching headline values but
also lists later revisions; it is not substituted for the shipped payload.
-Before implementing Brawl outcomes, establish or explicitly bound the
-skill-to-QL selector, effective/base skill input, odd and endpoint rounding,
-attack-rating/AC/critical arithmetic and cooldown rules. Stun handling also
-needs authoritative chance, target, resistance/NCU, interruption, overlap,
-expiry/death/respawn and persistence behavior. Preserve the existing atomic
-special damage/lock/corpse transaction when adding these effects. Keep these
-gaps separate from the proven request and result contracts.
-
-## Verification
+## Explicit alpha policy
+
+Effective Brawling142 divided by two, truncated and clamped toQL1..500,
+selects the damage item. This is a provisional server rule, not a conclusion
+from the MA discussion or native actor-level initializer. Existing catalog
+interpolation supplies damage endpoints. Brawl uses its authored Brawling attack
+and EvadeClose defense with the shared provisional hit curve, critical chance,
+attack-rating scaling, MeleeAC reduction and melee damage bonus. Held-weapon
+damage, its equip requirements and Martial Arts do not replace those inputs.
+The base cooldown is the authored1500cs, with shared SkillLockModifier handling.
+
+The OnUse stun chance is provisionally interpolated and rounded from10% to20%
+over the same quality range, rolled independently even on a missed Brawl.
+Living creature targets receive program125772 for three seconds without a
+second resistance roll or NCU admission. Its mask6 stops movement and ordinary
+attacks. Supported creature opponents do not cast nanos, so NPC cast
+interruption is not claimed. The same stun refreshes its deadline; unrelated
+effects remain intact. Death clears it through the existing damage lifecycle.
+Expiry restores the remaining permissions and attack eligibility. Restart
+restores its checkpointed remaining duration, following existing NPC nano rules.
+
+Range is the Brawl item's three metres plus actor extents, with shared line of
+sight. Supported held weapons must advertise Can bit25; sitting, driving,
+loading, equipping, reloading and locked requests are rejected. There is no
+item or ammunition cost. Results use slot0 and ammo-1, preserving held weapons.
+Normal attack/recharge clocks remain unchanged. Native matching-fight animation
+uses the existing special notification; idle animation remains a shared limit.
+
+Damage, stun, skill lock, contributions and any corpse/loot/XP commit in the
+same transaction before live state or success feedback. The native proc is
+published through action177 only after commitment. These rules support the
+early-game path without claiming recovered historical server balance. Reopen
+historical research only for a conflicting period measurement or original
+server artifact that resolves one of these specific provisional rules.
+
+## Prior contract verification
`client/tests/fling_result.c` exercises the unchanged lifted result activation
for Fling150 and Brawl142. Brawl cases cover owner, target and observer feedback,
@@ -130,3 +157,37 @@ cleanup. The owned browser was closed, only its character/items were removed,
SQLite integrity passed and all unrelated rows remained unchanged by cleanup.
The single shared preview was restored on its default ports. Wire data,
screenshots, probes and verification are in `local/brawl-input-smoke/`.
+
+## November5 implementation verification
+
+The first server regression reproduced the ignored142 request: no damage,
+stun or lock. `TestBrawl*` now covers skill endpoints/rounding, fists versus a
+held Sledgehammer, critical and missed hits, independent stun rolls, root
+overlap, refresh, blocked retaliation, expiry, rejected requests, unchanged
+normal attack clocks, repeated use and cold recovery. Ignored/failed writes at
+lock, damage, active-nano, loot and XP boundaries roll back the entire outcome;
+retry commits it once.
+
+Adding the implicit Brawl row exposed a fixed-size spawn-tail assumption in
+the14.9.1 converter. The converter now preserves the player MA/Brawl list and
+the NPC single attack row. The packet regression checks the entire list and
+preceding empty groups; both native fixtures load and reconnect successfully.
+
+`TestBrowserBrawl` uses real targeting, Q and B input with newly created
+level-one Martial Artist fists and a cap-checked level-ten stocked Sledgehammer
+fixture. Under deterministic critical/proc rolls they deal9 and33 damage per
+Brawl respectively. Each waits for ordinary three-second stun expiry, retries
+while locked, reconnects, waits for native15-second unlock and uses B again.
+Server and native HP agree, exact inventory is unchanged and cold loading
+preserves damage and the lock. Ordinary swings are held to isolate Brawl; the
+Leet's placement/1000HP and the upgrade are controlled, not earned progression.
+
+The two-case browser run passes in68.13seconds. Screenshots were inspected and
+the owned browser/server sessions were closed. Evidence is under
+`local/alpha-brawl/20261105-172414/{fists,sledgehammer}/`, including native
+traces, screenshots and `verification.json`. The broader124-root server run
+passes (`regressions.log`), as do JavaScript syntax, diff checks and Go vet.
+The final focused Brawl run is recorded in `brawl-final.log`.
+
+This completes the Brawl rejection within A5. Dimach, Aimed Shot and the rest
+of the open A5/A7 criteria remain separate work.
diff --git a/docs/early-shop-stock.md b/docs/early-shop-stock.md
@@ -214,8 +214,9 @@ coverage are in [M-10 pistols](catalog-weapons.md), [E-Beamers](e-beamer.md),
[Vektors](vektor-shotguns.md), [Sledgehammers](sledgehammer.md),
[Gripo rifles](gripo-rifles.md) and [Kerans SMGs](kerans.md). All six support ordinary
attacks. M-10/E-Beamer Fling and [Kerans Burst](burst.md) use the shared special
-handler. Sledgehammer Brawl/Dimach and Gripo Aimed Shot remain unimplemented
-shared actions; stock does not complete them. The Kerans also applies its
+handler. [Brawl](brawl.md) now supports fists and the stocked Sledgehammer.
+Dimach and Gripo Aimed Shot remain unimplemented shared actions; stock does not
+complete them. The Kerans also applies its
original +2 Sense wear bonus.
Unfinished profession essentials remain outstanding. These funded checks do not
establish that ordinary early rewards can pay the listed prices.
diff --git a/docs/fast-attack.md b/docs/fast-attack.md
@@ -64,13 +64,14 @@ in a mirror; the original official article remains unavailable.
## Server behavior and limits
-The shared handler accepts147/148/150 only for a ready authenticated owner, visible
+The weapon branches accept147/148/150 only for a ready authenticated owner, visible
living creature in range and supported right-hand weapon with the relevant
capability. Sitting, vehicles, equip/reload activity and an active lock reject
the request without damage or success feedback. Several action gates remain
reconstruction policy pending period verification. The handler uses the shared
[combat visibility](combat-visibility.md) checks; dual wield and its source
-selection remain unimplemented.
+selection remain unimplemented. [Brawl142](brawl.md) uses a separate implicit
+damage item and also admits unarmed actors in the shared handler.
Fast Attack reuses ordinary or critical weapon damage, including weapon attack
rating, AC, overequipping and damage additions. The precise special distribution
diff --git a/docs/player-movement.md b/docs/player-movement.md
@@ -259,6 +259,17 @@ Helper26/32 changes primary6/preferred and presentation/Features128, preserving
rest, velocity, controls and gravity. The server request/acknowledgement policy
and concealment/visibility rules remain unresolved; incoming26/32 stay excluded.
+November5 A5 dependency check: Aimed Shot on the issued Agent rifle and stocked
+Gripo requires this lifecycle. The shipped
+`cd_image/text/help/How do I play this Game in a Team.txt` describes a concealed
+puller's opening shot against an unsuspecting target. The retained movement
+producer/helper evidence establishes163/162/26/32 but does not establish the
+server's concealment contest, cancellation or observer visibility policy. The
+bounded check stopped at that boundary. Implement a documented, coherent
+concealment policy and test the native handshake before admitting Aimed Shot;
+do not repeat broad historical searches without a concrete new source or
+reproduced packet failure to investigate.
+
## Water and retained rest
Water entry submits helper24 through ordinary admission, replacing seated8 with
diff --git a/server/brawl.go b/server/brawl.go
@@ -0,0 +1,44 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "math/rand/v2"
+ "slices"
+ "time"
+)
+
+func (character *character) brawlStunned() bool {
+ return slices.ContainsFunc(character.activeNanos, func(effect activeNano) bool { return effect.program == 125772 })
+}
+
+func (server *server) prepareBrawl_locked(player, target *character, now time.Time) (character, bool) {
+ // Provisional server selector, independent of the native actor-level initializer.
+ skill, _ := player.effectiveStat(142)
+ quality := uint32(min(500, max(1, skill/2)))
+ weapon := interpolateWeapon(gamedata.ItemTemplates[70292], gamedata.ItemTemplates[70293], quality)
+ roll := server.combatRoll
+ if roll == nil {
+ roll = rand.Uint32N
+ }
+ damage := uint32(0)
+ if server.itemAttackLands_locked(player, target, weapon) {
+ chance := min(100, max(0, int64(3)+int64(player.equipmentBonus(379))+int64(player.nanoBonus(379))))
+ critical := int64(roll(100)) < chance
+ damage = min(target.health, player.itemDamage(target, weapon, critical, roll))
+ }
+ candidate := server.prepareWeaponDamage_locked(player, target, damage, now)
+ // Authored OnUse can stun even on a miss. Refresh this program only; no NCU debit.
+ chance := uint32(interpolateItemValue(10, 20, 1, 500, quality))
+ stunned := candidate.health != 0 && roll(100) < chance
+ if stunned {
+ candidate.activeNanos = slices.DeleteFunc(slices.Clone(candidate.activeNanos), func(effect activeNano) bool { return effect.program == 125772 })
+ candidate.activeNanos = append(candidate.activeNanos, activeNano{program: 125772, caster: player.id, remaining: 3 * time.Second, expiresAt: now.Add(3 * time.Second)})
+ if candidate.motion != nil {
+ motion := *candidate.motion
+ motion.moving = false
+ candidate.motion, candidate.running = &motion, false
+ }
+ candidate.movement.velocity, candidate.movement.speed = [3]float32{}, 0
+ }
+ return candidate, stunned
+}
diff --git a/server/brawl_test.go b/server/brawl_test.go
@@ -0,0 +1,276 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func brawlRequest(owner, target uint32) []byte {
+ request := flingShotRequest(owner, target)
+ binary.BigEndian.PutUint32(request[len(request)-4:], 142)
+ return request
+}
+
+func TestBrawlUsesEffectiveSkillAndOwnItemWithOrWithoutWeapon(t *testing.T) {
+ for _, scenario := range []struct {
+ skill uint16
+ damage uint32
+ }{{0, 0}, {3, 2}, {20, 11}, {21, 11}, {1000, 1750}, {1001, 1751}} {
+ for _, armed := range []bool{false, true} {
+ t.Run(fmt.Sprint(scenario.skill, "/", armed), func(t *testing.T) {
+ world, _ := newBrawlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Body.Brawling, player.stats.Body.MartialArts = scenario.skill, 1000
+ target.health = 10000
+ world.combatRoll = landedCombatRoll
+ if armed {
+ player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 129026, Quality: 10, Count: 1, Slot: 6}}
+ }
+
+ err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:])
+
+ if err != nil || target.health != 10000-scenario.damage || len(target.activeNanos) != 0 || player.skillLocks[142].IsZero() {
+ t.Fatal("Brawl used a held weapon/MA damage or wrong skill endpoint", target.health, err)
+ }
+ })
+ }
+ }
+}
+
+func TestBrawlMissCanStunAndDoesNotSpendAmmunitionOrRepeat(t *testing.T) {
+ world, _ := newBrawlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 9999
+ }
+ return 0
+ }
+ target.stats.Speed.EvadeClose = 10000
+ before := player.inventory
+ if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ attack, recharge := player.nextAttack, player.rechargeUntil
+
+ for range 2 {
+ if err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if target.health != 1000 || len(target.activeNanos) != 1 || player.skillLocks[142].IsZero() ||
+ player.nextAttack != attack || player.rechargeUntil != recharge || !reflect.DeepEqual(player.inventory, before) {
+ t.Fatal("Brawl miss, duplicate, inventory or ordinary attack clock changed")
+ }
+}
+
+func TestBrawlStunStopsPursuitAndAttacksUntilExpiry(t *testing.T) {
+ world, _ := newBrawlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ target.motion = &npcMotion{moving: true, home: target.position, destination: player.position}
+ target.running = true
+ if err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ deadline := target.activeNanos[0].expiresAt
+ health := player.health
+ target.nextAttack = deadline.Add(-time.Second)
+
+ world.advanceCombat(deadline.Add(-time.Nanosecond))
+
+ if player.health != health || target.motion.moving || target.running || !target.movementRestricted() {
+ t.Fatal("stunned creature moved or retaliated", player.health, target.motion)
+ }
+ world.advanceNanos(deadline)
+ world.advanceCombat(deadline)
+ if target.movementRestricted() || len(target.activeNanos) != 0 || player.health >= health {
+ t.Fatal("expired stun did not restore retaliation", player.health, health, target.activeNanos)
+ }
+ if cold := newTestInventoryServer(t); cold.characters[target.id].movementRestricted() {
+ t.Fatal("expired stun returned on restart")
+ }
+}
+
+func TestBrawlStunChanceUsesQualityAndPreservesIndependentRoot(t *testing.T) {
+ for _, scenario := range []struct {
+ skill uint16
+ roll uint32
+ stunned bool
+ }{{20, 9, true}, {20, 10, false}, {1000, 19, true}, {1000, 20, false}} {
+ t.Run(fmt.Sprint(scenario.skill, "/", scenario.roll), func(t *testing.T) {
+ world, _ := newBrawlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Body.Brawling = scenario.skill
+ target.stats.Speed.EvadeClose = 10000
+ target.activeNanos = []activeNano{{program: 42110, caster: player.id, expiresAt: time.Now().Add(time.Minute)}}
+ world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 9999
+ }
+ return scenario.roll
+ }
+
+ err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:])
+
+ if err != nil || target.brawlStunned() != scenario.stunned || !target.movementRestricted() || target.health != 1000 {
+ t.Fatal("wrong stun chance or unrelated root lost", target.activeNanos, err)
+ }
+ world.advanceNanos(time.Now().Add(3 * time.Second))
+ if target.brawlStunned() || !target.movementRestricted() || len(target.activeNanos) != 1 || target.activeNanos[0].program != 42110 {
+ t.Fatal("stun expiry cleared another effect")
+ }
+ })
+ }
+}
+
+func TestBrawlRefreshesExistingStunWithoutDuplicates(t *testing.T) {
+ world, _ := newBrawlWorld(t)
+ target := world.characters[1000000]
+ previous := time.Now().Add(time.Second)
+ target.activeNanos = []activeNano{{program: 125772, caster: 1, expiresAt: previous}}
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:])
+ cold := newTestInventoryServer(t)
+
+ if err != nil || len(target.activeNanos) != 1 || !target.activeNanos[0].expiresAt.After(previous) ||
+ len(cold.characters[target.id].activeNanos) != 1 || !cold.characters[target.id].brawlStunned() {
+ t.Fatal("stun refresh duplicated or failed to persist the new duration", target.activeNanos, err)
+ }
+}
+
+func TestBrawlFailedOutcomeRollsBackDamageStunLockAndRewards(t *testing.T) {
+ for index, failure := range []string{
+ "BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(IGNORE); END",
+ "BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL,'target'); END",
+ "BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(IGNORE); END",
+ "BEFORE INSERT ON items BEGIN SELECT RAISE(FAIL,'loot'); END",
+ "BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END",
+ } {
+ t.Run(fmt.Sprint(index), func(t *testing.T) {
+ world, output := newBrawlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ if index >= 3 {
+ target.health = 1
+ }
+ before := target.health
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER fail_brawl " + failure); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:])
+ cold := newTestInventoryServer(t)
+
+ if err == nil || target.health != before || len(target.activeNanos) != 0 || target.corpse != nil ||
+ !player.skillLocks[142].IsZero() || player.experience != 0 || len(output.packets) != 0 ||
+ cold.characters[target.id].health != before || len(cold.characters[target.id].activeNanos) != 0 ||
+ !cold.characters[1].skillLocks[142].IsZero() || cold.characters[1].experience != 0 {
+ t.Fatal("failed Brawl retained a partial outcome", err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_brawl"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ cold = newTestInventoryServer(t)
+ if index >= 3 {
+ if target.health != 0 || target.corpse == nil || len(target.corpse.items) != 1 || player.experience != 100 ||
+ cold.characters[1].experience != 100 || cold.characters[target.id].corpse == nil || len(target.activeNanos) != 0 {
+ t.Fatal("retried Brawl kill did not commit once")
+ }
+ } else if target.health != 976 || !target.movementRestricted() || !cold.characters[target.id].movementRestricted() {
+ t.Fatal("retried Brawl did not commit damage and stun")
+ }
+ })
+ }
+}
+
+func newBrawlWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, output := newKillExperienceWorld(t, "unarmed")
+ player := world.characters[1]
+ player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
+ player.stats.Body.Brawling = 20
+ world.characters[1000000].health = 1000
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ return world, output
+}
+
+func TestBrawlCommitsOwnDamageStunAndCooldown(t *testing.T) {
+ world, output := newBrawlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ before := time.Now()
+
+ err := world.handleWeaponSpecial(world.clients[1], brawlRequest(1, target.id)[20:])
+ cold := newTestInventoryServer(t)
+
+ if err != nil || target.health != 976 || len(target.activeNanos) != 1 || target.activeNanos[0].program != 125772 ||
+ !target.movementRestricted() || player.skillLocks[142].Before(before.Add(15*time.Second)) ||
+ player.skillLocks[142].After(time.Now().Add(15*time.Second)) {
+ t.Fatal("Brawl omitted its own damage, stun or cooldown", target.health, target.activeNanos, player.skillLocks, err)
+ }
+ if cold.characters[target.id].health != 976 || !cold.characters[target.id].movementRestricted() ||
+ !cold.characters[1].skillLocks[142].Equal(player.skillLocks[142]) {
+ t.Fatal("Brawl outcome did not recover atomically")
+ }
+ if binary.BigEndian.Uint32(output.packets[0][16:20]) != 0x754f1115 ||
+ binary.BigEndian.Uint32(output.packets[0][29:33]) != 0 || binary.BigEndian.Uint32(output.packets[0][49:53]) != 142 {
+ t.Fatal("unarmed Brawl result did not identify slot zero and skill 142")
+ }
+}
+
+func TestBrawlRejectsInvalidUseWithoutOutcome(t *testing.T) {
+ for _, scenario := range []string{"ranged", "range", "reload", "equipping", "locked", "sitting", "hidden", "unready", "owner", "dead"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newBrawlWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ request := brawlRequest(1, 1000000)[20:]
+ switch scenario {
+ case "ranged":
+ player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 123742, Quality: 1, Count: 1, Slot: 6}}
+ case "range":
+ world.characters[1000000].position[0] = 10
+ case "reload":
+ client.reloadUntil = time.Now().Add(time.Minute)
+ case "equipping":
+ client.equipment = &equipmentMove{}
+ case "locked":
+ player.setSkillLock_locked(142, time.Now().Add(time.Minute))
+ case "sitting":
+ player.sitting = true
+ case "hidden":
+ delete(client.npcs, 1000000)
+ case "unready":
+ client.ready = false
+ case "owner":
+ binary.BigEndian.PutUint32(request[8:], 2)
+ case "dead":
+ player.health = 0
+ }
+ before, deadline := player.inventory, player.skillLocks[142]
+
+ err := world.handleWeaponSpecial(client, request)
+
+ if err != nil || world.characters[1000000].health != 1000 || len(world.characters[1000000].activeNanos) != 0 ||
+ !player.skillLocks[142].Equal(deadline) || !reflect.DeepEqual(player.inventory, before) || len(output.packets) != 0 {
+ t.Fatal("rejected Brawl changed state or feedback", err)
+ }
+ })
+ }
+}
diff --git a/server/browser_brawl_test.go b/server/browser_brawl_test.go
@@ -0,0 +1,113 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserBrawl(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for native fists and stocked Sledgehammer Brawl")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/alpha-brawl", time.Now().Format("20060102-150405"))
+ for _, name := range []string{"fists", "sledgehammer"} {
+ t.Run(name, func(t *testing.T) {
+ world := newTestServer(t)
+ fields := creationForm()
+ fields.Set("profession", "2")
+ if response := creationRequest(world, accountVisitor(t, world), fields); response.Code != http.StatusNoContent {
+ t.Fatal(response.Code, response.Body.String())
+ }
+ player := world.characters[2]
+ damage := 9
+ if name == "sledgehammer" {
+ // The stocked QL10 upgrade uses the existing cap-checked checkpoint.
+ trainBasicShopWeaponFixture(t, player)
+ player.inventory.Items[3].Type, player.inventory.Items[3].Template, player.inventory.Items[3].Quality = 51018, 129026, 10
+ damage = 33
+ }
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("brawl")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ var target *character
+ for _, actor := range world.characters {
+ if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) {
+ target = actor
+ }
+ }
+ if target == nil {
+ t.Fatal("original Leet unavailable")
+ }
+ forward, _ := bodyAxes(player.rotation)
+ target.position = [3]float32{player.position[0] + 2*forward[0], player.position[1], player.position[2] + 2*forward[2]}
+ target.health = 1000
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"target": target.id, "health": target.health, "fighting": player.fighting,
+ "locked": time.Now().Before(player.skillLocks[142]), "inventory": player.inventory, "level": player.level,
+ "ip": player.stats.ImprovementPoints, "damage": damage, "weapon": name, "stunned": target.brawlStunned()})
+ })
+ host := httptest.NewServer(mux)
+ defer host.Close()
+ defer closeTestSessions(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ // Isolate Brawl from ordinary swings, retaining real equip/lock/stun expiry.
+ world.advanceEquipment(now)
+ world.advanceItemEffects(now)
+ world.advanceNanos(now)
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_brawl.mjs"), host.URL, filepath.Join(output, name))
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ cancel()
+ <-stopped
+ closeTestSessions(t, world)
+ t.Logf("Browser artifacts: %s", filepath.Join(output, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ if cold.characters[target.id].health != uint32(1000-2*damage) || !reflect.DeepEqual(cold.characters[2].inventory, player.inventory) ||
+ !cold.characters[2].skillLocks[142].Equal(player.skillLocks[142]) || cold.characters[2].skillLocks[142].IsZero() {
+ t.Fatal("native Brawl damage, ownership or lock changed on cold recovery")
+ }
+ })
+ }
+}
diff --git a/server/combat.go b/server/combat.go
@@ -251,9 +251,12 @@ func (server *server) weaponHit_locked(attacker, target *character) (uint32, boo
}
func (attacker *character) weaponDamage(target *character, critical bool, roll func(uint32) uint32) uint32 {
+ return attacker.itemDamage(target, attacker.attackWeapon(), critical, roll)
+}
+
+func (attacker *character) itemDamage(target *character, weapon *gamedata.Item, critical bool, roll func(uint32) uint32) uint32 {
// Exact catalog endpoints and the weapon's native protection type.
minimum, maximum, bonus, damageType := uint32(3), uint32(5), uint32(3), uint32(91)
- weapon := attacker.attackWeapon()
if weapon != nil {
minimum, maximum = itemStat(weapon, 286), itemStat(weapon, 285)
bonus = itemStat(weapon, 284)
@@ -280,7 +283,7 @@ func (attacker *character) weaponDamage(target *character, critical bool, roll f
// Player fists use MA; equipped weapons use their authored attack skills.
// NPC attack skills remain unknown. Fractional endpoint truncation is provisional.
if !attacker.npc {
- rating := attacker.attackRating()
+ rating := attacker.weaponRating(weapon, 12)
if weapon != nil {
tier := attacker.weaponOverequippingTier(weapon)
minimum -= minimum * tier / 4
@@ -449,7 +452,7 @@ func (server *server) advanceCombat(now time.Time) {
}
continue
}
- if now.Before(attacker.nextAttack) {
+ if attacker.brawlStunned() || now.Before(attacker.nextAttack) {
continue
}
damage, result := uint32(0), uint32(3)
diff --git a/server/fast_attack_test.go b/server/fast_attack_test.go
@@ -93,7 +93,7 @@ func TestFastAttackRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
case "wrong target type":
binary.BigEndian.PutUint32(request[16:20], 51018)
case "unsupported skill":
- binary.BigEndian.PutUint32(request[24:28], 142)
+ binary.BigEndian.PutUint32(request[24:28], 144)
case "unknown target":
binary.BigEndian.PutUint32(request[20:24], 2000000)
case "player target":
diff --git a/server/nano_buffs.go b/server/nano_buffs.go
@@ -321,7 +321,7 @@ func (server *server) loadActiveNanos() error {
periodic := damageOverTimeNano(effect.program)
healing := healingOverTimeNano(effect.program)
payment := effect.program == 43372 && delayedHealthPaymentNano(43374)
- if effect.program != 157490 && !payment && !statBuffNano(effect.program) && !passiveDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil {
+ if effect.program != 157490 && effect.program != 125772 && !payment && !statBuffNano(effect.program) && !passiveDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil {
return fmt.Errorf("character %d has an unsupported active nano %d", id, effect.program)
}
if periodic != nil {
diff --git a/server/target_protocol.go b/server/target_protocol.go
@@ -75,8 +75,13 @@ func targetPacket(packet []byte) []byte {
packet = append(converted, packet[cursor:]...)
}
// Three empty byte-counted groups separate the final encoded lists.
- tail = append([]byte(nil), packet[len(packet)-24:]...)
- packet = append(packet[:len(packet)-24], 0, 0, 0)
+ // Player spawns carry both MA and Brawl; NPC spawns carry their attack row.
+ tailLength := 24
+ if flags&1 == 0 {
+ tailLength += 16
+ }
+ tail = append([]byte(nil), packet[len(packet)-tailLength:]...)
+ packet = append(packet[:len(packet)-tailLength], 0, 0, 0)
packet = append(packet, tail...)
if flags&1 != 0 {
// Tab targeting requires NPC stat 194 (InPlay), supplied by flag bit 1.
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -50,8 +50,12 @@ func TestTargetCharactersIncludeUnarmedWeapon(t *testing.T) {
} else if binary.BigEndian.Uint32(packet[60:64])&7 != uint32(actor.appearance>>9&3) {
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)
+ want := "000000000003f1000007e20000aac00000aac10000006400000001"
+ if !actor.npc {
+ want = "000000000003f100000bd30000aac00000aac1000000640000000100011294000112950000008e00000001"
+ }
+ if got := hex.EncodeToString(packet[len(packet)-len(want)/2:]); got != want {
+ t.Fatalf("implicit weapon lists and preceding empty groups: %s", got)
}
})
}
diff --git a/server/weapon_special.go b/server/weapon_special.go
@@ -33,14 +33,14 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
skill := binary.BigEndian.Uint32(body[24:28])
if server.clients[client.id] != client || !client.target || !client.ready || client.loading || player.health == 0 ||
binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id ||
- binary.BigEndian.Uint32(body[16:20]) != 50000 || (skill != 147 && skill != 148 && skill != 150) {
+ binary.BigEndian.Uint32(body[16:20]) != 50000 || (skill != 142 && skill != 147 && skill != 148 && skill != 150) {
server.mutex.Unlock()
return nil
}
target := server.characters[binary.BigEndian.Uint32(body[20:24])]
now := time.Now()
if target == nil || !target.npc || target.pet != nil || target.appearance>>4&7 != 6 || !client.npcs[target.id] || target.health == 0 ||
- target.playfield != player.playfield || !server.combatInRange_locked(player, target, now) || !server.combatVisible_locked(player, target, now) ||
+ target.playfield != player.playfield || skill != 142 && !server.combatInRange_locked(player, target, now) || !server.combatVisible_locked(player, target, now) ||
player.sitting || player.driving() || client.equipment != nil || now.Before(client.reloadUntil) ||
now.Before(player.skillLocks[skill]) {
server.mutex.Unlock()
@@ -60,15 +60,38 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
break
}
}
- if item == nil || item.templateStat(30)&capability == 0 || skill != 147 && item.usesAmmo() && item.Ammo == 0 {
+ if skill == 142 {
+ // The implicit Brawl item has its own three-metre range and excludes ranged weapons.
+ for _, held := range player.inventory.Items {
+ if (held.Slot == 6 || held.Slot == 8) && held.isWieldableWeapon() && held.templateStat(30)&(1<<25) == 0 {
+ server.mutex.Unlock()
+ return nil
+ }
+ }
+ first, second := predictedPosition_locked(player, now), predictedPosition_locked(target, now)
+ x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2]
+ distance := float32(3) + player.physicalExtent() + target.physicalExtent()
+ if x*x+y*y+z*z > distance*distance {
+ server.mutex.Unlock()
+ return nil
+ }
+ } else if item == nil || item.templateStat(30)&capability == 0 || skill != 147 && item.usesAmmo() && item.Ammo == 0 {
server.mutex.Unlock()
return nil
}
// Prepare a detached result so a failed transaction changes no live actor.
- seconds := player.weaponSpecialLockSeconds(player.attackWeapon(), skill)
+ seconds := uint32(15)
+ if skill != 142 {
+ seconds = player.weaponSpecialLockSeconds(player.attackWeapon(), skill)
+ }
var damage uint32
- if skill == 148 {
+ var candidate character
+ var stunned bool
+ if skill == 142 {
+ candidate, stunned = server.prepareBrawl_locked(player, target, now)
+ damage = target.health - candidate.health
+ } else if skill == 148 {
// Three independent noncritical hits; no later defensive checks or ammo debit.
roll := server.combatRoll
if roll == nil {
@@ -81,7 +104,9 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
} else {
damage, _ = server.weaponHit_locked(player, target)
}
- candidate := server.prepareWeaponDamage_locked(player, target, damage, now)
+ if skill != 142 {
+ candidate = server.prepareWeaponDamage_locked(player, target, damage, now)
+ }
award, err := server.saveSpecialAttack_locked(player, &candidate, skill, now.Add(time.Duration(player.skillLockSeconds(seconds))*time.Second), now)
if err != nil {
server.mutex.Unlock()
@@ -95,21 +120,29 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
if player.fighting == target.id {
server.queueCombat_locked(updates, player, target, n3Packet(0x51492120, 50000, player.id, body[16:28]))
}
- // Pre-15.5.5 specials do not deduct ammunition or use defensive hit checks.
+ // These specials do not deduct ammunition. Brawl uses its own defense check.
var result []byte
death := uint32(0)
ammunition := ^uint32(0)
- if skill != 147 && item.usesAmmo() {
+ if skill != 142 && skill != 147 && item.usesAmmo() {
ammunition = item.Ammo
}
if target.health == 0 {
death = 4
}
- for _, value := range []uint32{6, damage, ammunition, 50000, target.id, skill, death} {
+ slot := uint32(6)
+ if skill == 142 {
+ slot = 0
+ }
+ for _, value := range []uint32{slot, damage, ammunition, 50000, target.id, skill, death} {
result = binary.BigEndian.AppendUint32(result, value)
}
server.queueCombat_locked(updates, player, target, n3Packet(0x754f1115, 50000, player.id, result))
updates[client] = append(updates[client], skillLockPacket(player.id, skill, seconds))
+ if stunned {
+ server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{177, 53019, 125772, player.id, 300}))
+ server.finishResourceChange_locked(updates, target, previous, now)
+ }
server.finishDamageEffects_locked(player, target, previous, now, updates)
server.applyExperienceAward_locked(award, now, updates)
server.mutex.Unlock()
diff --git a/server/world.go b/server/world.go
@@ -171,9 +171,20 @@ func characterPacket(character *character) []byte {
if character.npc && character.combatProfile != nil {
low, high, quality = character.combatProfile.Weapon[0], character.combatProfile.Weapon[1], uint32(character.level)
}
- for _, value := range []uint32{2018, low, high, 100, quality} {
+ count := uint32(2018)
+ if !character.npc {
+ count = 3027
+ }
+ for _, value := range []uint32{count, low, high, 100, quality} {
body = binary.BigEndian.AppendUint32(body, value)
}
+ if !character.npc {
+ // Native Brawl dispatch requires an actor-owned implicit action source.
+ // The fourth row word is unresolved; retain the existing player parameter1.
+ for _, value := range []uint32{70292, 70293, 142, 1} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ }
return n3Packet(0x271b3a6b, 50000, character.id, body)
}
diff --git a/tools/client/test_brawl.mjs b/tools/client/test_brawl.mjs
@@ -0,0 +1,81 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [
+ '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+let game;
+const evidence = {};
+try {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'brawl', url}]);
+ const page = await context.newPage();
+ game = await GameTest.attach(page);
+ const server = async () => (await page.request.get(url + '/test-state')).json();
+ const waitServer = (label, predicate) => game.waitFor(label, async () => predicate(await server()));
+ const checkNative = async health => game.wait('native Brawl HP agrees', state =>
+ state.actors.find(actor => actor.type === 50000 && actor.id === evidence.initial.target)?.stats[27] === health);
+ await page.goto(url);
+ await game.ready();
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ await game.key('KeyI');
+ evidence.initial = await server();
+ if (evidence.initial.weapon === 'sledgehammer') {
+ const cell = game.state.grids.flatMap(grid => grid.cells).find(cell => cell.identity[0] === 104 && cell.identity[1] === 51 && !cell.dummy);
+ assert(cell, 'stocked Sledgehammer is visible');
+ await game.click((cell.bounds[0]+cell.bounds[2])/2, (cell.bounds[1]+cell.bounds[3])/2, 'right');
+ await waitServer('Sledgehammer equipped normally', state => state.inventory.Items.some(item => item.ID === 4 && item.Slot === 6));
+ await game.wait('native equipped weapon ready', state => game.local(state).weapons.some(weapon => weapon.slot === 6));
+ }
+ evidence.equipped = await server();
+ await game.key('Tab');
+ await game.wait('original Leet selected', state => state.selected[0] === 50000 && state.selected[1] === evidence.initial.target);
+ await game.key('KeyQ');
+ await waitServer('normal fight started', state => state.fighting === evidence.initial.target);
+ await game.key('KeyB');
+ await waitServer('Brawl damage, stun and lock committed', state => state.health === 1000-state.damage && state.locked && state.stunned);
+ await checkNative(1000-evidence.initial.damage);
+ evidence.first = await server();
+ assert.deepEqual(evidence.first.inventory, evidence.equipped.inventory);
+ await game.save(output + '/first');
+
+ await game.key('KeyB');
+ assert.equal((await server()).health, evidence.first.health);
+ await waitServer('three-second stun expires', state => !state.stunned);
+ await page.reload();
+ await game.ready();
+ evidence.reconnected = await server();
+ assert(evidence.reconnected.locked);
+ assert.equal(evidence.reconnected.health, evidence.first.health);
+ assert.deepEqual(evidence.reconnected.inventory, evidence.first.inventory);
+ await checkNative(evidence.first.health);
+ await game.save(output + '/reconnected');
+
+ // Wait for the real server deadline and native unlock rather than shortening it.
+ await game.wait('native Brawl unlock received', () => game.events.some(event => {
+ if (event.direction !== 'framereceived' || event.opcode !== '5e477770') return false;
+ const packet = Buffer.from(event.hex, 'hex');
+ return packet.readUInt32BE(29) === 164 && packet.readUInt32BE(45) === 142;
+ }), 60000);
+ assert(!(await server()).locked);
+ await game.click(...await game.pick(50000, evidence.initial.target));
+ await game.key('KeyQ');
+ await waitServer('fight resumed', state => state.fighting === evidence.initial.target);
+ await game.key('KeyB');
+ await waitServer('second Brawl commits after expiry', state => state.health === 1000-2*state.damage && state.locked && state.stunned);
+ await checkNative(1000-2*evidence.initial.damage);
+ evidence.second = await server();
+ assert.deepEqual(evidence.second.inventory, evidence.first.inventory);
+ assert.deepEqual(game.errors, []);
+ console.log('PASS:', evidence.initial.weapon, 'native Brawl, stun expiry, cooldown, unchanged inventory, reconnect and repeat');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ if (game) await game.save(output + '/final');
+ } finally { await browser.close(); }
+}