commit 45899e1bc930d524df90c074e9df8e173e31012a
parent 4cb635327de979d133d9337a7412634744e45816
Author: anon <anon@example.com>
Date: Sat, 24 Oct 2026 16:16:20 +0000
Add Fast Attack's normal-damage path and fix weapon re-equip
Handle native Fast Attack alongside Fling through authored capabilities and
the shared atomic damage/cooldown transaction. Keep critical selection,
historical action gates and exact recharge arithmetic explicit TODOs.
Retire the owner's detached native weapon on unequip. The original client
ignores full updates for an existing identity, leaving fists and no special
action when the same item is equipped again without this retirement.
Validate Go server and race suites, forced-crash recovery for both specials,
21 Linux/WASM result contracts, and actual two-client damage, cooldown,
restart and same-item equipment round trips without item loss.
Diffstat:
16 files changed, 581 insertions(+), 124 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -93,6 +93,10 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md).
- [x] Equip and unequip one melee weapon. Check: its appearance and base attack
data replace fists; unequipping restores fists, including for another observer.
+- [x] Re-equip the same weapon instance after removal. Check: owner and observer
+ restore its combat weapon, native special actions and existing skill lock;
+ its inventory identity/count survive. Full updates skip existing native
+ instances, so unequip must retire the owner's detached instance as well.
- [x] Enforce that weapon's requirements. Check: a character below one required
skill cannot equip it, while a qualifying character can.
- [x] Equip one armor piece. Check: the correct native slot and appearance
@@ -199,6 +203,9 @@ Normal-hit additions and weapon-range modifiers are described in
magazine after the correct delay and the total round count is conserved.
- [ ] Implement one melee special. Check: a suitable weapon/character can use
the action once, with native feedback and an enforced skill lock.
+ The Kinetic Axe now has a shared-handler Fast Attack normal-damage prototype.
+ Keep this open for critical selection, historical action gates, exact reuse
+ floor/rounding and SkillLockModifier. See [Fast Attack](docs/fast-attack.md).
Brawl's original content, capability gates, request/result and lock contracts
are recorded in [Brawl research](docs/brawl.md). Its own skill-to-QL selector
and stun outcome rules remain unproven; do not reuse MA's tentative selector
diff --git a/client/tests/fling_result.c b/client/tests/fling_result.c
@@ -121,7 +121,13 @@ int main(void)
{1, 0, 0, 50, 4, -1, 142, 6},
{1, 0, 0, 50, 0, -1, 142, 8},
{1, 0, 1, 50, 0, -1, 142, 0},
- {1, 0, 2, 50, 0, -1, 142, 0}
+ {1, 0, 2, 50, 0, -1, 142, 0},
+ {1, 0, 0, 50, 0, -1, 147, 6},
+ {0, 1, 0, 48, 0, -1, 147, 6},
+ {0, 0, 0, 49, 0, -1, 147, 6},
+ {1, 0, 0, 50, 4, -1, 147, 6},
+ {1, 0, 1, 50, 0, -1, 147, 6},
+ {1, 0, 2, 50, 0, -1, 147, 6}
};
for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
lookups = names = feedbacks = reads = writes = deaths = ammo_updates = 0;
@@ -163,5 +169,5 @@ int main(void)
assert(deaths == (death_reason != 0) && ammo_updates == 1);
}
}
- puts("native Fling/Brawl result: target damage, named feedback, slot/ammunition and death routing passed");
+ puts("native weapon special result: target damage, named feedback, slot/ammunition and death routing passed");
}
diff --git a/docs/brawl.md b/docs/brawl.md
@@ -111,7 +111,8 @@ gaps separate from the proven request and result contracts.
`client/tests/fling_result.c` exercises the unchanged lifted result activation
for Fling150 and Brawl142. Brawl cases cover owner, target and observer feedback,
fist slot0, equipped slots6/8, no-ammo sentinel-1, death routing and either missing
-actor. All15 cases pass in Linux and WASM with identical output. The fixture
+actor. Its15 Fling/Brawl cases and six Fast Attack cases pass in Linux and WASM
+with identical output. The fixture
tests result activation and dispatch boundaries; it does not roll Brawl damage
or prove the server's choice of a result slot. Build/run logs are retained in
`local/brawl-research/`.
diff --git a/docs/fast-attack.md b/docs/fast-attack.md
@@ -0,0 +1,132 @@
+# Fast Attack: supported branch and remaining rules
+
+The QL1 Kinetic Axe209283 supports native Fast Attack147 through the shared
+weapon-special handler. It publishes named damage feedback and an independent,
+persistent skill lock. This is a prototype of the normal-damage branch;
+critical selection and the historical rules below remain open.
+
+## Original content and native path
+
+The original14.9.1 axe has capability30 bit18, damage5..20 with critical bonus5,
+attack/recharge125 centiseconds, range2 meters and MeleeAC91 damage. It attacks
+with100%1-Hand Edged103. Its equip requirements are103,147 and142 each greater
+than4. Fast Attack is a requirement and recharge input, not the authored normal
+attack-map skill. The axe has NoAmmo and Clip-1; it needs no ammunition debit.
+The currently supported fists, pistol and Briefcase lack Fast Attack capability.
+Five complete original resource payloads, hashes and offsets are retained in
+`local/fast-attack-research/content/`.
+
+Original KKR SHA256 is
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Its equipped callback100ad0b0 registers Fast Attack147 from capability0x40000
+with the weapon's identity as action source. Unequipping removes the action if
+the other hand lacks it, without erasing the separate skill lock. Unlike Brawl,
+no implicit147 item row is needed to create the action. An unnecessary implicit
+row could also change the queued special's execution source.
+
+The default N binding is established by original CCR binding evidence
+`ev_3dff589882a6c4f42e12afb434b594089dd46f9bd63d70e693e8b79b3ec4f06f`.
+The generic sender1002c090 checks target, skill lock, hand capability, range and
+line of sight, then sends target identity and skill147 in CharSecSpecAttackIIR
+`0x51492120`. Its request contains no slot; native hand eligibility order does
+not establish authoritative damage-weapon selection.
+
+SpecialAttackInfo `0x754f1115` applies one target HP subtraction and named
+special feedback. The server sends slot6, damage, ammo-1, target identity,
+skill147 and weapon death reason4 for a kill. The result has no critical/miss
+field. Shared CharacterAction170/164 publishes/restores/clears the lock by147.
+Exact original records and coverage limits are in
+`local/fast-attack-research/native/ledger.md`.
+
+## Recharge evidence and reconstruction policy
+
+The February2,2003 [player discussion](https://archives.jeuxonline.info/fils/163094.html)
+reports the same formula for Fast Attack and Fling: weapon attack delay times15,
+minus special skill divided by100 seconds. This is a period secondhand report
+attributed to official-forum investigations, without measurements or exact
+rounding/floor. The server uses the base item delay and effective special skill,
+rounds up to whole seconds and retains a provisional one-second lower guard.
+The axe at effective skill8 therefore receives19 seconds. Initiative and AggDef
+do not change this reconstruction's special deadline.
+
+Native helper100ab060 independently computes Fast/Fling using signed attack
+delay and skill, a float32 store after multiplication by15, then a500cs floor
+and truncation. However, its only observed direct caller10079700 discards that
+result. This proves client arithmetic, including a5s floor, without proving an
+active local timer or the original server's floor/whole-second conversion.
+Resolving that difference and SkillLockModifier382 remains required.
+
+The attributed [15.5.5 patch notes](https://wiki.aodb.us/wiki/Patch_15.5#Version_15.5.5)
+introduce defensive checks for Fast Attack and remove SkillLockModifier's reuse
+effect. Those later rules are not imported into14.9.1. The notes are preserved
+in a mirror; the original official article remains unavailable.
+
+## Server behavior and limits
+
+The shared handler accepts147/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. Line of sight remains the
+existing combat TODO; dual wield and its source selection are not implemented.
+
+Fast Attack currently reuses normal weapon damage, including weapon attack
+rating, AC, overequipping and damage additions. The precise special distribution,
+critical selection and arithmetic ordering are not established. The action
+preserves existing normal-attack/recharge and nano-cast clocks. It triggers NPC
+retaliation and contribution/corpse/respawn handling, without starting the owner's
+normal attack. Historical start/animation/interruption rules remain open.
+
+Damage and its skill lock use the existing atomic SQLite outcome transaction
+before publishing live state or feedback. Repeated requests cannot bypass it;
+reconnect restores the deadline and expiry clears the in-memory lock once,
+without per-tick database writes. Weapon changes do not clear the stored lock.
+
+## Verification
+
+`server/fast_attack_test.go` covers owner/observer result bytes, damage range,
+no ammunition/item loss, its own persistent lock,25 invalid-use cases, concurrent
+duplicates, normal recharge/cast independence, four database-failure boundaries,
+killing outcomes and restart/expiry. Existing Fling cases exercise the shared
+handler as regression coverage. `server/fling_crash_test.go` additionally covers
+both specials with forced termination before/after commit for living/killing
+hits, then duplicate retries and a second database reopen.
+
+`client/tests/fling_result.c` runs the unchanged native result activation. Its
+21 cases include six Fast Attack cases for owner/defender/observer feedback,
+ammunition-1, death and either missing actor. External boundaries are stubbed;
+these tests do not determine server damage probabilities or rendering.
+
+Two headed Chromium WASM clients on the GPU exercised N through the shared
+HTTPS preview. They received matching26- and15-point Fast Attack results with
+ammo-1. The first hit changed the Leet from100 to74 in both native clients and
+SQLite. The second gave59 in both clients; the database snapshot had already
+advanced one3-point NPC recovery tick to62. An immediate repeated N generated
+no second request, and the next accepted attack followed native lock expiry.
+
+A real server restart restored a native147 lock with173 seconds remaining.
+Its stored deadline was explicitly extended for cold server/two-client loading;
+this checks persistence and UI restoration, not the normal recharge formula.
+The equipped action was locked and N sent no request.
+
+Removal/re-equip testing exposed a native lifecycle gap: the owner kept the
+detached world instance, so activation100b38b0 ignored its next full update.
+Unequip now retires that instance for owner and observer after action97, before
+the inventory acknowledgement. With the fix, removal restored fists and erased
+action147 while preserving the lock. Re-equipping the same axe restored slot6,
+weapon identity164 and locked action147; its remaining lock fell from127 to121
+seconds without resetting. Both clients received the item retirement, and the
+owned item retained count1/ammo0 across every inventory/equipment round trip.
+Native source evidence is in `local/fast-attack-research/native/re-equip.md`.
+
+All three browser runs reported no page errors or unimplemented adapters.
+Their contexts were closed, only the owned characters/item were removed, and
+SQLite integrity passed with unrelated rows unchanged by cleanup. Captures,
+screenshots, probes, controlled-deadline metadata and the verifier are under
+`local/fast-attack-smoke/`. The single shared preview remains on default ports.
+
+Final validation passed: `go test ./server/... -count=1` (server440.653s,
+gamedata7.601s), two runs of focused equipment/special/remote-bank race checks
+(134.297s), `go vet -stdversion=false ./server/...`, and21 native result cases
+on Linux and WASM with identical output. The full suite includes all eight
+before/after-commit living/killing crash scenarios for Fling and Fast Attack.
diff --git a/docs/fling-shot.md b/docs/fling-shot.md
@@ -72,8 +72,9 @@ Fresh REA evidence is in `local/fling-shot-research/native-evidence.json`:
## Server behavior and limits
-The handler accepts only the authenticated, ready 14.9.1 owner, a visible living
-creature in range, the supported right-hand pistol and special 150. It rejects
+The shared weapon-special handler accepts Fling150 with the supported right-hand
+pistol and Fast Attack147 with the axe. Fling requires the authenticated, ready
+14.9.1 owner and a visible living creature in range. It rejects
dead/loading/replaced sessions, other owners, player targets, empty clips,
active reload/equip, sitting, vehicles and an existing lock. Some of those action
gates are reconstruction policy pending period verification. Server line of
@@ -105,7 +106,8 @@ forced process termination immediately around commit is covered below.
## Verification
`server/fling_crash_test.go` starts real child processes with disposable SQLite
-databases. For both a living and a killing hit, the parent sends a forced kill
+databases for both Fling and Fast Attack. For both a living and a killing hit,
+the parent sends a forced kill
at either SQLite's commit hook or the first native special-result write. The
commit-hook stop occurs after the transaction's writes and before commit;
the output stop occurs after commit and before any result bytes are published.
@@ -134,11 +136,12 @@ before expiry. Raw captures and cleanup records are under
the single shared preview and existing item records were preserved.
`client/tests/fling_result.c` executes unchanged `sub_360B2CB0` from
-`client/game/kkr.dll/lifted-0053.c`. Eight Linux and WASM cases verify target-only
+`client/game/kkr.dll/lifted-0053.c`. Its eight Fling cases verify target-only
HP subtraction once, attacker/defender/observer feedback categories, ammo values
3/0/-1 forwarded unchanged, death routing and missing actors. External identity,
stat, feedback and ammo boundaries are stubbed; this does not test rendering,
-the network reader or original server formulas.
+the network reader or original server formulas. The fixture also includes seven
+Brawl and six Fast Attack cases; all21 run in Linux and WASM.
`server/fling_shot_test.go` covers owner/observer results, ammunition conservation,
concurrent duplicates, normal recharge and nano-cast independence, invalid and
diff --git a/docs/inventory.md b/docs/inventory.md
@@ -282,8 +282,12 @@ owner and binds hand slots on inventory page 1. The native equip handler
behavior. No full-character appearance refresh is needed for live equipment.
Unequip sends native CharacterAction 97 with parameter 2 equal to slot 6,
-followed by the owner's container acknowledgement. Observers also receive an
-item despawn (`0x36510078`) so they do not retain the removed weapon instance.
+followed by an item despawn (`0x36510078`) for owner and observers, then the
+owner's container acknowledgement. Full-update activation100b38b0 immediately
+returns when the item dynel already exists. CharacterAction97 detaches that
+dynel without destroying it, so the owner must also retire it before the same
+item can be equipped again. The persistent inventory instance is retained;
+the despawn retires its native world representation.
The native holder restores its existing Martial Arts fists. New connections
receive the character before the weapon instance; the owner also receives its
persistent FullCharacter inventory before the weapon update. Packets and state
@@ -295,6 +299,14 @@ full inventory, native payloads, weapon damage/slot/initiative, and restoration
of fist data. Manual WASM captures and the isolated fixture are retained in
`local/equipment-smoke/`.
+The same-instance round trip is also covered by
+`TestWeaponUnequipRetiresNativeInstanceForOwnerAndObserver`. Actual two-client
+WASM testing under `local/fast-attack-smoke/` reproduced the stale owner dynel,
+then verified retirement/recreation restores the weapon and its locked Fast
+Attack action without losing its inventory identity or count. Original full
+update activation and despawn evidence is retained in
+`local/fast-attack-research/native/re-equip.md`.
+
Two WASM clients verified axe appearance, matching combat text and damage,
unequip icons and removal for the observer, and subsequent 3..5 fist hits.
Repeated equipment and equipped reconnect/server-restart checks retained item
diff --git a/server/equipment.go b/server/equipment.go
@@ -301,11 +301,8 @@ func (server *server) advanceEquipment(now time.Time) {
}
if move.source == 6 {
server.queueCombat_locked(updates, character, character, weaponUnequipPacket(client.id))
- for id, observer := range server.clients {
- if id != client.id && observer.ready && !observer.loading && server.characters[id].playfield == character.playfield {
- updates[observer] = append(updates[observer], n3Packet(0x36510078, 51018, move.itemID, nil))
- }
- }
+ // FullUpdate100b38b0 ignores an existing dynel; retire it for re-equip.
+ server.queueCombat_locked(updates, character, character, n3Packet(0x36510078, item.Type, move.itemID, nil))
}
updates[client] = append(updates[client], itemMovePacket(client.id, move.source, move.requestedSlot))
if move.destination == 1 || move.destination == 7 || move.destination >= 9 && move.destination <= 14 || move.destination >= 16 && move.destination < 32 || move.destination == 37 {
diff --git a/server/equipment_test.go b/server/equipment_test.go
@@ -66,7 +66,7 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) {
!reflect.DeepEqual(unequipped.characters[1].inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}}) {
t.Fatal("equipment move changed identity or did not survive restart")
}
- if len(conn.packets) != 4 || len(observer.packets) != 3 {
+ if len(conn.packets) != 5 || len(observer.packets) != 3 {
t.Fatalf("equipment replication: owner=%d observer=%d", len(conn.packets), len(observer.packets))
}
if binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x47537a24 ||
@@ -74,7 +74,7 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) {
binary.BigEndian.Uint32(observer.packets[0][20:24]) != 51018 ||
binary.BigEndian.Uint32(observer.packets[2][16:20]) != 0x36510078 ||
binary.BigEndian.Uint32(conn.packets[2][29:33]) != 97 ||
- binary.BigEndian.Uint32(conn.packets[3][45:49]) != 111 {
+ binary.BigEndian.Uint32(conn.packets[4][45:49]) != 111 {
t.Fatalf("native equipment packets: %x %x", conn.packets, observer.packets)
}
length := binary.BigEndian.Uint16(conn.packets[1][6:8])
@@ -83,6 +83,37 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) {
}
}
+func TestWeaponUnequipRetiresNativeInstanceForOwnerAndObserver(t *testing.T) {
+ world, owner := newEquipmentWorld(t)
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true}
+ if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceEquipment(world.clients[1].equipment.readyAt)
+ owner.packets, observer.packets = nil, nil
+
+ err := world.handleInventory(world.clients[1], itemMovePacket(1, 6, 111)[20:])
+ world.advanceEquipment(world.clients[1].equipment.readyAt)
+ restored := newTestInventoryServer(t)
+
+ if err != nil || !reflect.DeepEqual(restored.characters[1].inventory.Items,
+ []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}}) {
+ t.Fatal("retiring the native weapon lost or moved the owned item incorrectly", err)
+ }
+ if len(owner.packets) != 3 || len(observer.packets) != 2 ||
+ binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x5e477770 ||
+ binary.BigEndian.Uint32(owner.packets[0][29:33]) != 97 ||
+ binary.BigEndian.Uint32(owner.packets[1][16:20]) != 0x36510078 ||
+ binary.BigEndian.Uint32(owner.packets[1][20:24]) != 51018 ||
+ binary.BigEndian.Uint32(owner.packets[1][24:28]) != 1 ||
+ !bytes.Equal(owner.packets[1][16:], observer.packets[1][16:]) ||
+ binary.BigEndian.Uint32(owner.packets[2][16:20]) != 0x47537a24 {
+ t.Fatalf("owner/observer did not retire the detached weapon before its next full update: %x / %x", owner.packets, observer.packets)
+ }
+}
+
func TestEquipmentRequiresEachEffectiveSkillAtFive(t *testing.T) {
for _, skill := range []string{"one hand edged", "brawling", "fast attack"} {
t.Run(skill, func(t *testing.T) {
diff --git a/server/fast_attack_test.go b/server/fast_attack_test.go
@@ -0,0 +1,238 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+)
+
+func fastAttackRequest(owner, target uint32) []byte {
+ var body []byte
+ for _, value := range []uint32{50000, target, 147} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x51492120, 50000, owner, body)
+}
+
+func newFastAttackWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, conn := newEquipmentWorld(t)
+ world.nextNPC = 1000001
+ world.characters[1000000].health = 1000
+ if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceEquipment(world.clients[1].equipment.readyAt)
+ conn.packets = nil
+ return world, conn
+}
+
+func TestFastAttackPublishesWeaponDamageAndPersistsItsOwnLock(t *testing.T) {
+ world, owner := newFastAttackWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Melee.OneHandEdged = 400
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true, npcs: map[uint32]bool{1000000: true}}
+ inventory := player.inventory
+ inventory.Items = append([]ownedItem(nil), player.inventory.Items...)
+ started := time.Now()
+
+ err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:])
+ restored := newTestInventoryServer(t)
+
+ if err != nil || target.health < 960 || target.health > 990 || target.fighting != 1 ||
+ target.damageContributors[damageContributor{player: 1}] != 1000-target.health ||
+ !reflect.DeepEqual(player.inventory, inventory) ||
+ !reflect.DeepEqual(restored.characters[1].inventory.Items, inventory.Items) ||
+ !restored.characters[1].specialAttackLocks[147].Equal(player.specialAttackLocks[147]) ||
+ player.specialAttackLocks[147].Before(started.Add(19*time.Second)) ||
+ player.specialAttackLocks[147].After(time.Now().Add(19*time.Second)) || !player.specialAttackLocks[150].IsZero() {
+ t.Fatalf("Fast Attack damage, inventory or durable lock mismatch: HP=%d locks=%v, %v", target.health, player.specialAttackLocks, err)
+ }
+ if len(owner.packets) != 3 || len(observer.packets) != 2 ||
+ binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x754f1115 ||
+ !bytes.Equal(owner.packets[0][16:], observer.packets[0][16:]) ||
+ binary.BigEndian.Uint32(owner.packets[0][29:33]) != 6 ||
+ binary.BigEndian.Uint32(owner.packets[0][33:37]) != 1000-target.health ||
+ binary.BigEndian.Uint32(owner.packets[0][37:41]) != ^uint32(0) ||
+ binary.BigEndian.Uint32(owner.packets[0][45:49]) != target.id ||
+ binary.BigEndian.Uint32(owner.packets[0][49:53]) != 147 ||
+ binary.BigEndian.Uint32(owner.packets[1][29:33]) != 170 ||
+ binary.BigEndian.Uint32(owner.packets[1][41:45]) != 147 ||
+ binary.BigEndian.Uint32(owner.packets[1][45:49]) != 19 {
+ t.Fatalf("Fast Attack native result/lock mismatch: %x", owner.packets)
+ }
+}
+
+func TestFastAttackRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
+ for _, scenario := range []string{"unready", "loading", "replaced", "old client", "dead owner", "wrong owner", "wrong owner type", "wrong target type", "unsupported skill", "unknown target", "player target", "dead target", "hidden target", "other zone", "out of melee range", "sitting", "driving", "equip pending", "reloading", "locked", "unarmed", "stored axe", "pistol", "briefcase", "unsupported quality"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn := newFastAttackWorld(t)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ request := fastAttackRequest(1, 1000000)[20:]
+ switch scenario {
+ case "unready":
+ client.ready = false
+ case "loading":
+ client.loading = true
+ case "replaced":
+ world.clients[1] = &worldClient{id: 1}
+ case "old client":
+ client.target = false
+ case "dead owner":
+ player.health = 0
+ case "wrong owner":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "wrong owner type":
+ binary.BigEndian.PutUint32(request[4:8], 51018)
+ case "wrong target type":
+ binary.BigEndian.PutUint32(request[16:20], 51018)
+ case "unsupported skill":
+ binary.BigEndian.PutUint32(request[24:28], 142)
+ case "unknown target":
+ binary.BigEndian.PutUint32(request[20:24], 2000000)
+ case "player target":
+ target.npc = false
+ case "dead target":
+ target.health = 0
+ case "hidden target":
+ delete(client.npcs, 1000000)
+ case "other zone":
+ target.playfield = 705
+ case "out of melee range":
+ target.position[0] = 20
+ case "sitting":
+ player.sitting = true
+ case "driving":
+ player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51022, Template: 117294, Quality: 15, Slot: 1, Count: 1})
+ case "equip pending":
+ client.equipment = &equipmentMove{}
+ case "reloading":
+ client.reloadUntil = time.Now().Add(time.Hour)
+ case "locked":
+ player.specialAttackLocks = map[uint32]time.Time{147: time.Now().Add(time.Hour)}
+ case "unarmed":
+ player.inventory.Items = nil
+ case "stored axe":
+ player.inventory.Items[0].Slot = 64
+ case "pistol":
+ player.inventory.Items[0].Template, player.inventory.Items[0].Ammo = 123742, 3
+ case "briefcase":
+ player.inventory.Items[0].Template, player.inventory.Items[0].Quality = 205736, 100
+ case "unsupported quality":
+ player.inventory.Items[0].Quality = 2
+ }
+ deadline := player.specialAttackLocks[147]
+ health := target.health
+
+ err := world.handleWeaponSpecial(client, request)
+
+ if err != nil || target.health != health || player.specialAttackLocks[147] != deadline || len(conn.packets) != 0 {
+ t.Fatalf("invalid Fast Attack changed state: HP=%d locks=%v, %v", target.health, player.specialAttackLocks, err)
+ }
+ })
+ }
+}
+
+func TestFastAttackConcurrentRequestsApplyOnceWithoutResettingAttackOrCast(t *testing.T) {
+ world, conn := newFastAttackWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ world.handleCombat(client, attackPacket(1, 1000000)[20:])
+ world.advanceCombat(player.nextAttack)
+ attack, recharge, health := player.nextAttack, player.rechargeUntil, world.characters[1000000].health
+ cast := &nanoCast{target: 1000000, readyAt: time.Now().Add(time.Second)}
+ client.nanoCast = cast
+ conn.packets = nil
+ var calls sync.WaitGroup
+
+ for range 8 {
+ calls.Go(func() {
+ if err := world.handleWeaponSpecial(client, fastAttackRequest(1, 1000000)[20:]); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+ calls.Wait()
+ count := 0
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x754f1115 {
+ count++
+ }
+ }
+
+ if count != 1 || world.characters[1000000].health >= health || player.nextAttack != attack ||
+ player.rechargeUntil != recharge || client.nanoCast != cast {
+ t.Fatal("Fast Attack duplicated its hit or reset normal attack/cast state")
+ }
+}
+
+func TestFastAttackFailedOutcomePublishesNothingAndRollsBackItsLock(t *testing.T) {
+ for _, statement := range []string{
+ "CREATE TRIGGER fail_special BEFORE INSERT ON special_attack_locks BEGIN SELECT RAISE(FAIL, 'test lock failure'); END",
+ "CREATE TRIGGER fail_special BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'test health failure'); END",
+ "CREATE TRIGGER fail_special BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'test NPC failure'); END",
+ "CREATE TRIGGER fail_special BEFORE INSERT ON npc_damage_contributors BEGIN SELECT RAISE(FAIL, 'test contribution failure'); END",
+ } {
+ world, conn := newFastAttackWorld(t)
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:])
+ restored := newTestInventoryServer(t)
+
+ if err == nil || world.characters[1000000].health != 1000 || len(conn.packets) != 0 ||
+ len(world.characters[1].specialAttackLocks) != 0 || len(restored.characters[1].specialAttackLocks) != 0 {
+ t.Fatal("failed Fast Attack changed durable/live outcome or published feedback")
+ }
+ }
+}
+
+func TestFastAttackKillAndCooldownRecoverTogether(t *testing.T) {
+ world, conn := newFastAttackWorld(t)
+ target := world.characters[1000000]
+ target.health, target.monsterData, target.level = 1, 17655, 1
+ target.combatProfile = gamedata.NPCCombatProfiles[17655][1]
+
+ err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:])
+ restored := newTestInventoryServer(t)
+ corpse := restored.characters[1000000]
+ deadline := restored.characters[1].specialAttackLocks[147]
+
+ if err != nil || corpse.health != 0 || corpse.corpse == nil || corpse.corpse.looter != 1 ||
+ corpse.corpse.expiresAt.IsZero() || len(restored.npcRespawns) != 1 ||
+ !deadline.Equal(world.characters[1].specialAttackLocks[147]) ||
+ binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 ||
+ binary.BigEndian.Uint32(conn.packets[0][53:57]) != 4 {
+ t.Fatal("Fast Attack kill/corpse/lock did not recover atomically", err)
+ }
+}
+
+func TestFastAttackStoredLockRejectsAfterRestartAndExpiresOnce(t *testing.T) {
+ world, _ := newFastAttackWorld(t)
+ if err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+ conn := &combatTestConn{}
+ restored.clients = map[uint32]*worldClient{1: {id: 1, ready: true, target: true, conn: conn, npcs: map[uint32]bool{1000000: true}}}
+ deadline, health := restored.characters[1].specialAttackLocks[147], restored.characters[1000000].health
+
+ err := restored.handleWeaponSpecial(restored.clients[1], fastAttackRequest(1, 1000000)[20:])
+ restored.advanceItemEffects(deadline.Add(-time.Nanosecond))
+ if len(conn.packets) != 0 || restored.characters[1000000].health != health {
+ t.Fatal("restarted Fast Attack bypassed its persisted lock")
+ }
+ restored.advanceItemEffects(deadline)
+ restored.advanceItemEffects(deadline.Add(time.Second))
+
+ if err != nil || len(conn.packets) != 1 || !restored.characters[1].specialAttackLocks[147].IsZero() ||
+ binary.BigEndian.Uint32(conn.packets[0][29:33]) != 164 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 147 {
+ t.Fatal("Fast Attack lock did not expire exactly once", err)
+ }
+}
diff --git a/server/fling_crash_test.go b/server/fling_crash_test.go
@@ -8,6 +8,7 @@ import (
"encoding/json"
"os"
"os/exec"
+ "reflect"
"strings"
"testing"
"time"
@@ -33,7 +34,15 @@ func (conn *flingCrashConn) Write(packet []byte) (int, error) {
func runFlingCrashChild(t *testing.T, mode string) {
t.Helper()
- world, output := newRangedWorld(t)
+ var world *server
+ var output *combatTestConn
+ request := flingShotRequest(1, 1000000)
+ if strings.Contains(mode, "/fast/") {
+ world, output = newFastAttackWorld(t)
+ request = fastAttackRequest(1, 1000000)
+ } else {
+ world, output = newRangedWorld(t)
+ }
target := world.characters[1000000]
target.health, target.monsterData, target.level = 100, 17655, 1
target.combatProfile = gamedata.NPCCombatProfiles[17655][1]
@@ -74,7 +83,7 @@ func runFlingCrashChild(t *testing.T, mode string) {
} else {
world.clients[1].conn = &flingCrashConn{checkpoint: checkpoint}
}
- if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
+ if err := world.handleWeaponSpecial(world.clients[1], request[20:]); err != nil {
t.Fatal(err)
}
t.Fatal("shot completed without reaching its crash boundary")
@@ -85,8 +94,19 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
runFlingCrashChild(t, mode)
return
}
- for _, mode := range []string{"before/living", "after/living", "before/kill", "after/kill"} {
+ for _, mode := range []string{"before/living", "after/living", "before/kill", "after/kill", "before/fast/living", "after/fast/living", "before/fast/kill", "after/fast/kill"} {
t.Run(mode, func(t *testing.T) {
+ skill := uint32(150)
+ request := flingShotRequest(1, 1000000)
+ inventory := []ownedItem{
+ {ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: 3},
+ {ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: 100},
+ }
+ if strings.Contains(mode, "/fast/") {
+ skill = 147
+ request = fastAttackRequest(1, 1000000)
+ inventory = []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}
+ }
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
@@ -148,7 +168,7 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
if checkpoint.Published != 0 {
t.Fatal("shot published feedback before its commit boundary")
}
- if player.inventory.Items[0].Ammo != 3 || player.inventory.Items[1].Count != 100 {
+ if !reflect.DeepEqual(player.inventory.Items, inventory) {
t.Fatal("crash changed pre-15.5 ammunition")
}
if strings.HasPrefix(mode, "before/") {
@@ -161,7 +181,8 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
t.Fatalf("first post-commit output was not the native special result: %x", checkpoint.Packet)
}
damage := binary.BigEndian.Uint32(checkpoint.Packet[33:37])
- if damage == 0 || damage > initialHealth || target.health != initialHealth-damage || !player.specialAttackLocks[150].After(time.Now()) ||
+ if damage == 0 || damage > initialHealth || target.health != initialHealth-damage || !player.specialAttackLocks[skill].After(time.Now()) ||
+ binary.BigEndian.Uint32(checkpoint.Packet[49:53]) != skill ||
initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != damage {
t.Fatalf("committed shot was lost or partially recovered: HP=%d damage=%d lock=%v", target.health, damage, player.specialAttackLocks)
}
@@ -177,7 +198,7 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
output := &combatTestConn{}
restored.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: output, npcs: map[uint32]bool{1000000: true}}
for range 2 {
- if err := restored.handleFlingShot(restored.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
+ if err := restored.handleWeaponSpecial(restored.clients[1], request[20:]); err != nil {
t.Fatal(err)
}
}
@@ -192,8 +213,8 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
}
again := newTestInventoryServer(t)
if target.health >= initialHealth || initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != initialHealth-target.health ||
- again.characters[1000000].health != target.health || !again.characters[1].specialAttackLocks[150].Equal(player.specialAttackLocks[150]) ||
- again.characters[1].inventory.Items[0].Ammo != 3 || again.characters[1].inventory.Items[1].Count != 100 {
+ again.characters[1000000].health != target.health || !again.characters[1].specialAttackLocks[skill].Equal(player.specialAttackLocks[skill]) ||
+ !reflect.DeepEqual(again.characters[1].inventory.Items, inventory) {
t.Fatal("retry lost or duplicated a durable damage, cooldown or ammunition outcome")
}
if initialHealth == 1 && (again.characters[1000000].corpse == nil || again.characters[1000000].corpse.looter != 1 || len(again.npcRespawns) != 1 ||
diff --git a/server/fling_shot.go b/server/fling_shot.go
@@ -1,80 +0,0 @@
-package main
-
-import (
- "ao/server/gamedata"
- "encoding/binary"
- "fmt"
- "math/rand/v2"
- "time"
-)
-
-func (player *character) flingShotLockSeconds() uint32 {
- // February 2003 formula: attack delay * 15 - Fling Shot / 100.
- // Whole-second rounding and the minimum are provisional; see docs/fling-shot.md.
- skill := player.effectiveSkill(150, player.baseStats().Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0})
- centiseconds := int64(itemStat(gamedata.ItemTemplates[123742], 294))*15 - int64(skill)
- return uint32(max(1, (centiseconds+99)/100))
-}
-
-func (server *server) handleFlingShot(client *worldClient, body []byte) error {
- if len(body) != 28 {
- return fmt.Errorf("invalid secondary special attack length")
- }
- server.updateMutex.Lock()
- defer server.updateMutex.Unlock()
- server.mutex.Lock()
- player := server.characters[client.id]
- 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 || binary.BigEndian.Uint32(body[24:28]) != 150 {
- server.mutex.Unlock()
- return nil
- }
- target := server.characters[binary.BigEndian.Uint32(body[20:24])]
- now := time.Now()
- if 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) ||
- player.sitting || player.driving() || client.equipment != nil || now.Before(client.reloadUntil) ||
- now.Before(player.specialAttackLocks[150]) {
- server.mutex.Unlock()
- return nil
- }
- var gun *ownedItem
- for index := range player.inventory.Items {
- if player.inventory.Items[index].Slot == 6 && player.inventory.Items[index].isFlechettePistol() {
- gun = &player.inventory.Items[index]
- break
- }
- }
- if gun == nil || gun.Ammo == 0 {
- server.mutex.Unlock()
- return nil
- }
-
- // Prepare a detached result so a failed transaction changes no live actor.
- seconds := player.flingShotLockSeconds()
- damage := min(player.normalDamage(target, rand.Uint32N), target.health)
- candidate := prepareDamage(player, target, damage, now)
- if err := server.saveSpecialAttack_locked(player, &candidate, 150, now.Add(time.Duration(seconds)*time.Second), now); err != nil {
- server.mutex.Unlock()
- return err
- }
- previous := *target
- *target = candidate
- updates := make(map[*worldClient][][]byte)
- // Pre-15.5.5 specials do not deduct ammunition or use defensive hit checks.
- var result []byte
- death := uint32(0)
- if target.health == 0 {
- death = 4
- }
- for _, value := range []uint32{6, damage, gun.Ammo, 50000, target.id, 150, 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, 150, seconds))
- server.finishDamageEffects_locked(player, target, previous, now, updates)
- server.mutex.Unlock()
- server.sendCombatUpdates(updates)
- return nil
-}
diff --git a/server/fling_shot_test.go b/server/fling_shot_test.go
@@ -26,7 +26,7 @@ func TestFlingShotDamagesOnceWithoutConsumingPre155Ammunition(t *testing.T) {
world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
started := time.Now()
- err := world.handleFlingShot(world.clients[1], flingShotRequest(1, target.id)[20:])
+ err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, target.id)[20:])
restored := newTestInventoryServer(t).characters[1]
if err != nil || target.health < 988 || target.health > 997 || player.inventory.Items[0].Ammo != 3 ||
@@ -59,7 +59,7 @@ func TestFlingShotDoesNotResetNormalAttackOrNanoClocks(t *testing.T) {
client.nanoCast = &nanoCast{target: 1000000, readyAt: time.Now().Add(time.Second)}
cast := client.nanoCast
- err := world.handleFlingShot(client, flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(client, flingShotRequest(1, 1000000)[20:])
if err != nil || world.characters[1000000].health == 1000 || player.nextAttack != attack ||
player.rechargeUntil != recharge || client.nanoCast != cast || player.fighting != 1000000 {
@@ -75,7 +75,7 @@ func TestFlingShotDoesNotConsumeNormalShotAndWorksDuringWeaponRecharge(t *testin
attack, recharge := player.nextAttack, player.rechargeUntil
health := world.characters[1000000].health
- err := world.handleFlingShot(client, flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(client, flingShotRequest(1, 1000000)[20:])
if err != nil || world.characters[1000000].health >= health || player.inventory.Items[0].Ammo != 2 ||
player.nextAttack != attack || player.rechargeUntil != recharge {
@@ -91,7 +91,7 @@ func TestFlingShotConcurrentRepeatedRequestsShareOneLock(t *testing.T) {
for range 8 {
calls.Go(func() {
- if err := world.handleFlingShot(client, request); err != nil {
+ if err := world.handleWeaponSpecial(client, request); err != nil {
t.Error(err)
}
})
@@ -168,7 +168,7 @@ func TestFlingShotRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
health := target.health
deadline := player.specialAttackLocks[150]
- err := world.handleFlingShot(client, request)
+ err := world.handleWeaponSpecial(client, request)
if err != nil || target.health != health || player.specialAttackLocks[150] != deadline || len(conn.packets) != 0 {
t.Fatalf("rejected special changed health/lock/output: %d -> %d, %v", health, target.health, err)
@@ -182,7 +182,7 @@ func TestFlingShotMalformedLengthReturnsError(t *testing.T) {
world, conn := newRangedWorld(t)
request := append(flingShotRequest(1, 1000000)[20:], 0)[:length]
- err := world.handleFlingShot(world.clients[1], request)
+ err := world.handleWeaponSpecial(world.clients[1], request)
if err == nil || world.characters[1000000].health != 1000 || len(conn.packets) != 0 {
t.Fatal("malformed special changed game state")
@@ -196,7 +196,7 @@ func TestFlingShotSaveFailureDoesNotPublishOrDamage(t *testing.T) {
t.Fatal(err)
}
- err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:])
if err == nil || world.characters[1000000].health != 1000 || len(world.characters[1].specialAttackLocks) != 0 || len(conn.packets) != 0 {
t.Fatal("failed special lock save published a hit or changed live state")
@@ -214,7 +214,7 @@ func TestFlingShotOutcomeFailureRollsBackLockAndNPCState(t *testing.T) {
t.Fatal(err)
}
- err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:])
var health, locks int
if err := world.db.QueryRow("SELECT health FROM characters WHERE id=1000000").Scan(&health); err != nil {
t.Fatal(err)
@@ -233,7 +233,7 @@ func TestFlingShotOutcomeFailureRollsBackLockAndNPCState(t *testing.T) {
func TestFlingShotPersistsDamageAndContributionBeforeAnyCheckpoint(t *testing.T) {
world, _ := newRangedWorld(t)
- err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:])
var health, contribution uint32
if err := world.db.QueryRow("SELECT health FROM characters WHERE id=1000000").Scan(&health); err != nil {
t.Fatal(err)
@@ -265,7 +265,7 @@ func TestFlingShotKillingSaveFailurePreservesCorpseAndContributors(t *testing.T)
t.Fatal(err)
}
- err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:])
restored := newTestInventoryServer(t)
if err == nil || target.health != 1 || target.corpse.looter != 2 || !target.corpse.expiresAt.IsZero() ||
@@ -279,7 +279,7 @@ func TestFlingShotKillingSaveFailurePreservesCorpseAndContributors(t *testing.T)
func TestFlingShotLockSurvivesProfileEditAndBlocksAfterRestart(t *testing.T) {
world, _ := newRangedWorld(t)
player := world.characters[1]
- if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
+ if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
deadline := player.specialAttackLocks[150]
@@ -293,7 +293,7 @@ func TestFlingShotLockSurvivesProfileEditAndBlocksAfterRestart(t *testing.T) {
restored.clients = map[uint32]*worldClient{1: {id: 1, ready: true, target: true, conn: conn, npcs: map[uint32]bool{1000000: true}}}
restored.characters[1000000] = &character{id: 1000000, npc: true, appearance: 229, playfield: 950, health: 1000}
if err == nil {
- err = restored.handleFlingShot(restored.clients[1], flingShotRequest(1, 1000000)[20:])
+ err = restored.handleWeaponSpecial(restored.clients[1], flingShotRequest(1, 1000000)[20:])
}
if err != nil || world.characters[1].specialAttackLocks[150] != deadline ||
@@ -304,7 +304,7 @@ func TestFlingShotLockSurvivesProfileEditAndBlocksAfterRestart(t *testing.T) {
func TestFlingShotLockExpiryUnlocksOnceAndDoesNotChurnDatabase(t *testing.T) {
world, conn := newRangedWorld(t)
- if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
+ if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
deadline := world.characters[1].specialAttackLocks[150]
@@ -328,7 +328,7 @@ func TestFlingShotLockExpiryUnlocksOnceAndDoesNotChurnDatabase(t *testing.T) {
func TestFlingShotExpiredStoredLockDoesNotReturnAfterRestart(t *testing.T) {
world, _ := newRangedWorld(t)
- if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
+ if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
if _, err := world.db.Exec("UPDATE special_attack_locks SET locked_until=?", time.Now().Add(-time.Second)); err != nil {
@@ -344,7 +344,7 @@ func TestFlingShotExpiredStoredLockDoesNotReturnAfterRestart(t *testing.T) {
func TestFlingShotReconnectPublishesRemainingLockBeforeReady(t *testing.T) {
world, _ := newRangedWorld(t)
- if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
+ if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
world.clients[1].conn = &combatInterestConn{}
@@ -376,7 +376,7 @@ func TestFlingShotKillingHitUsesCorpseAndContributionLifecycle(t *testing.T) {
target.level = 1
target.combatProfile = gamedata.NPCCombatProfiles[17655][1]
- err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:])
+ err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:])
var health, looter uint32
var corpse bool
var respawn, expiry time.Time
diff --git a/server/main.go b/server/main.go
@@ -494,7 +494,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
return err
}
case 0x51492120:
- if err := server.handleFlingShot(client, body); err != nil {
+ if err := server.handleWeaponSpecial(client, body); err != nil {
return err
}
case 0x3e205660:
diff --git a/server/signed_stats_test.go b/server/signed_stats_test.go
@@ -133,7 +133,7 @@ func TestSignedDirectInitiativeAndSpecialSkillKeepTheirSign(t *testing.T) {
attack, recharge := player.attackDelays()
cast := player.nanoCastDelay(29618)
- lock := player.flingShotLockSeconds()
+ lock := player.weaponSpecialLockSeconds(gamedata.ItemTemplates[123742], 150)
if attack != 2*time.Second || recharge != 2010*time.Millisecond || cast != 2634999990*time.Nanosecond || lock != 21 {
t.Fatalf("signed timing: %v/%v cast %v lock %d", attack, recharge, cast, lock)
diff --git a/server/team_loot_test.go b/server/team_loot_test.go
@@ -39,7 +39,7 @@ func TestTeamLootNanoAndFlingUseTheSameDurableTeamAward(t *testing.T) {
t.Fatal(err)
}
world.advanceNanos(world.clients[1].nanoCast.readyAt.Add(time.Nanosecond))
- } else if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, npc.id)[20:]); err != nil {
+ } else if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, npc.id)[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t)
diff --git a/server/weapon_special.go b/server/weapon_special.go
@@ -0,0 +1,89 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "math/rand/v2"
+ "time"
+)
+
+func (player *character) weaponSpecialLockSeconds(weapon *gamedata.Item, skill uint32) uint32 {
+ // February 2003 formula: attack delay * 15 - special skill / 100.
+ // Whole-second rounding and the minimum are provisional; see docs/fling-shot.md.
+ centiseconds := int64(itemStat(weapon, 294))*15 - int64(player.effectiveStat(skill))
+ return uint32(max(1, (centiseconds+99)/100))
+}
+
+func (server *server) handleWeaponSpecial(client *worldClient, body []byte) error {
+ if len(body) != 28 {
+ return fmt.Errorf("invalid secondary special attack length")
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ player := server.characters[client.id]
+ 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 != 150) {
+ server.mutex.Unlock()
+ return nil
+ }
+ target := server.characters[binary.BigEndian.Uint32(body[20:24])]
+ now := time.Now()
+ if 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) ||
+ player.sitting || player.driving() || client.equipment != nil || now.Before(client.reloadUntil) ||
+ now.Before(player.specialAttackLocks[skill]) {
+ server.mutex.Unlock()
+ return nil
+ }
+ // WeaponItem 100aaf10: Fast Attack uses capability bit18, Fling bit12.
+ capability := uint32(1 << 12)
+ if skill == 147 {
+ capability = 1 << 18
+ }
+ var item *ownedItem
+ for index := range player.inventory.Items {
+ if player.inventory.Items[index].Slot == 6 && player.inventory.Items[index].isWieldableWeapon() {
+ item = &player.inventory.Items[index]
+ break
+ }
+ }
+ if item == nil || itemStat(gamedata.ItemTemplates[item.Template], 30)&capability == 0 || skill == 150 && item.Ammo == 0 {
+ server.mutex.Unlock()
+ return nil
+ }
+
+ // Prepare a detached result so a failed transaction changes no live actor.
+ seconds := player.weaponSpecialLockSeconds(gamedata.ItemTemplates[item.Template], skill)
+ damage := min(player.normalDamage(target, rand.Uint32N), target.health)
+ candidate := prepareDamage(player, target, damage, now)
+ if err := server.saveSpecialAttack_locked(player, &candidate, skill, now.Add(time.Duration(seconds)*time.Second), now); err != nil {
+ server.mutex.Unlock()
+ return err
+ }
+ previous := *target
+ *target = candidate
+ updates := make(map[*worldClient][][]byte)
+ // Pre-15.5.5 specials do not deduct ammunition or use defensive hit checks.
+ var result []byte
+ death := uint32(0)
+ ammunition := ^uint32(0)
+ if skill == 150 {
+ ammunition = item.Ammo
+ }
+ if target.health == 0 {
+ death = 4
+ }
+ for _, value := range []uint32{6, 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))
+ server.finishDamageEffects_locked(player, target, previous, now, updates)
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+ return nil
+}