aorecomp

Anarchy Online classic in the browser

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


commit 9008962bf2a9b41bf5211b37c659e692518d3618
parent a083777bd248a21c260ea1d11805002d47b543ce
Author: anon <anon@example.com>
Date:   Fri,  6 Nov 2026 01:33:16 +0000

Implement Dimach with independent damage and persistent cooldown

Diffstat:
MTODO.md | 6++++--
Mdocs/brawl.md | 10++++++----
Mdocs/combat-fist-selection.md | 11++++++-----
Adocs/dimach.md | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/early-shop-stock.md | 6+++---
Mdocs/fast-attack.md | 5+++--
Aserver/browser_dimach_test.go | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/dimach_test.go | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/fast_attack_test.go | 2+-
Mserver/target_protocol.go | 4++--
Mserver/target_protocol_test.go | 2+-
Mserver/weapon_special.go | 49+++++++++++++++++++++++++++++++++++++------------
Mserver/world.go | 6+++---
Atools/client/test_dimach.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 587 insertions(+), 35 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -144,8 +144,10 @@ research separately. More screenshots and test cases do not count as new gamepla 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. + [Dimach](docs/dimach.md) now has its independent item damage, native action + and persistent 30-minute cooldown, with the same fists/Sledgehammer input + and recovery checks. Aimed Shot remains an explicit weapon-special gap and + 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 @@ -85,8 +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. -Player spawn packets now supply implicit Martial Arts100 and Brawl142, with -Brawl endpoints70292/70293. NPC spawn profiles retain their existing attack row. +Player spawn packets now supply implicit Martial Arts100, Brawl142 and +[Dimach144](dimach.md), 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`. @@ -189,5 +190,6 @@ 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. +This completes the Brawl rejection within A5. [Dimach](dimach.md) is now also +implemented; Aimed Shot and the rest of the open A5/A7 criteria remain separate +work. diff --git a/docs/combat-fist-selection.md b/docs/combat-fist-selection.md @@ -51,11 +51,12 @@ skill key. `FUN_1007bff0` looks up key 100 and may bind its WeaponBase to controller slot 0. If that key is absent, it returns without creating a default weapon or clearing the old slot. -The current server supplies `{43712,43713,100,1}` for players in -`server/target_protocol.go`. This is a reconstruction choice, not evidence of -the original server's pair. Its last field is named `weaponParameter` because -calling it quality would assert a meaning the constructor does not establish. -The NPC profile similarly retains its existing actor-level value in that field. +The current server supplies `{43712,43713,100,1}` for player MA in +`server/world.go`, followed by the [Brawl](brawl.md) and [Dimach](dimach.md) +implicit rows. These are reconstruction choices, not evidence of the original +server's complete list. The last field's meaning remains unresolved; calling +it quality would assert a meaning the constructor does not establish. The NPC +profile similarly retains its existing actor-level value in that field. `SpecialAttackWeapon` (`0x1d3c0f1c`) uses reader `FUN_10083f00` and activation `FUN_10083fb0`. It initializes the map only when empty, then binds key 100. diff --git a/docs/dimach.md b/docs/dimach.md @@ -0,0 +1,105 @@ +# Dimach on fists and early melee weapons + +Dimach (144) now has a native actor-owned action and an authoritative outcome for +fists and supported weapons with Can30 bit26, including the stocked +Sledgehammer. The shared special handler previously ignored144, and player +spawn packets did not supply its implicit item. The issued Martial Artist +guidance explicitly tells the player to use Brawl and Dimach from Command View. + +## Original contract + +The 14.9.1 catalog contains Dimach Item42033 at QL1 and42032 at QL500. Minimum and +maximum damage are both1 at QL1 and2000 at QL500; critical bonus is1 at both ends. +The attack map is100% Dimach144 and the defense map is50% Psychic21. Range287 +is10 metres, AttackDelay294 is1cs and RechargeDelay210 is180000cs. DamageType +is omitted, retaining the native WeaponItem MeleeAC91 default. + +Both records exclude the Ranged bit of WieldedWeapons274 in their Use criteria. +OnUse contains Sphere53030 with resource43464 and HeadText53057 `Dimach`. +These are presentation effects, not an extra damage, nano cost, stun or heal. +Original payload hashes are: + +- 42033: `59d1b1c37a13ffbe0fa45850ac9304bd648b6760f31232a0892a9c45d68a1631` +- 42032: `33ecbd942710f1027ef346aeeb57636e2ad778b4f52c949ecf2bc39b34e13078` + +The retained original KKR evidence in +`local/old/fast-attack-research/native/` and `local/old/brawl-research/native/` +establishes the shared sender1002c090, bit26 in100aaf10, actor-owned dispatch +in10057680 and implicit registration10078920. Recharge helper100ab060 reads +the implicit144 item's RechargeDelay. Its observed caller discards the return, +so the helper alone does not prove original authoritative timing. Result +activation100b2cb0 handles named damage and HP, while shared actions170/164 +start and remove the native skill lock. + +Player spawn packets now include MA100, Brawl142 and Dimach144; NPCs retain +their single attack row. Dimach uses the original low/high pair42033/42032. +The fourth row parameter remains1, matching the existing player rows; it is +not a claim about native item quality. Initial construction1007b9a0 uses actor +level. Server damage selection remains independent of that client initializer. + +## Explicit alpha rules and evidence limits + +The provisional selector is effective Dimach divided by two, truncated and +clamped toQL1..500. Existing rounded catalog interpolation supplies the item. +The shared provisional hit curve uses its Dimach/Psychic ratings; the shared +critical probability, attack-rating scaling, MeleeAC floor and melee damage +bonuses then apply. This retains the authored critical bonus instead of +substituting held-weapon, Brawl or Martial Arts damage. Initiative, equipped +weapon delay and profession do not change its authored30-minute base cooldown. +Shared SkillLockModifier382 scaling applies to the deadline and client lock. + +The limited period-source search did not resolve original skill-to-quality, +damage scaling, critical selection or rounding. These remain explicit alpha +choices. Later profession-specific Dimach heals/recharge are outside14.9.1. +Reopen the search for a conflicting period measurement or an original server +artifact addressing one of these questions, rather than repeating broad searches. + +The skill's descriptive text says to use it after a successful martial-arts +move, but the item's Use criteria and recovered generic sender do not establish +that history gate. The alpha therefore uses the proven ordinary request gates +without inventing a required preceding MA hit. Range is ten metres plus actor +extents, with shared line of sight. Held weapons must have bit26; sitting, +vehicles, loading, equip/reload activity and an active144 lock reject the request. +Dual-wield selection and player targets remain outside the supported path. + +Damage, contribution, corpse/loot/XP and the persistent144 deadline commit +together before live state or success feedback. Misses still spend the action's +cooldown. Result slot0/ammo-1 preserves inventory and ammunition. Normal weapon +attack/recharge and Brawl's independent lock are unchanged. Reconnect and cold +recovery retain the deadline; expiry uses shared lock cleanup. + +Native input uses K. Matching active fights receive the existing special +notification before named damage and cooldown. Idle startup and exact authored +Sphere presentation retain the shared animation limitations; named feedback and +HP are verified rather than claiming a complete visual-effects reconstruction. + +## Verification + +`TestDimach*` reproduces the ignored request before the fix and covers item +quality endpoints, odd skill rounding, unarmed/held-weapon independence, +Psychic rather than EvadeClose defense, critical/missed hits, authored range, +invalid requests, duplicate and cold retries, unchanged normal/Brawl clocks, +controlled deadline expiry and atomic failed-write/retry outcomes. + +`TestBrowserDimach` uses real targeting, Q and K, then repeats K before and +after reconnect with the unshortened30-minute lock. It compares native and +server HP and retains exact inventory. Fists use ordinary level-one Martial +Artist creation; the stockedQL10 Sledgehammer uses the cap-checked level-ten +fixture. Critical rolls are deterministic, ordinary swings are held, and a +nearby original Leet has controlled1000HP. This is not earned progression or +purchase-affordability evidence. Cold loading checks the outcome and exact +deadline; expiry is tested with a controlled server clock instead of waiting +thirty minutes in the browser. + +November 5: all 42 selected server test roots pass, covering Dimach, Brawl, +Burst, Fast Attack, Fling and the expanded player spawn list. Both native cases +pass in 45.09 seconds: fists deal 10 and the Sledgehammer fixture deals 35 under +the controlled critical roll. Evidence is retained under +`local/alpha-dimach/20261105-173113/{fists,sledgehammer}/`, including screenshots, +native traces and `verification.json`. The screenshots show named Dimach damage; +the browser reports no errors. Logs are `regressions.log` and `browser.log` in +`local/alpha-dimach/`. Go vet, JavaScript syntax and diff checks also pass. +Owned browser and server sessions were closed before the final build. + +This completes the demonstrated Dimach rejection within A5. Aimed Shot and +the remaining A5/A7 criteria stay open. diff --git a/docs/early-shop-stock.md b/docs/early-shop-stock.md @@ -214,9 +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. [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 +handler. [Brawl](brawl.md) and [Dimach](dimach.md) now support fists and the +stocked Sledgehammer. Gripo Aimed Shot remains unimplemented; stock does not +complete it. 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 @@ -70,8 +70,9 @@ 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. [Brawl142](brawl.md) uses a separate implicit -damage item and also admits unarmed actors in the shared handler. +selection remain unimplemented. [Brawl142](brawl.md) and [Dimach144](dimach.md) +use separate implicit damage items and also admit 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/server/browser_dimach_test.go b/server/browser_dimach_test.go @@ -0,0 +1,112 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" +) + +func TestBrowserDimach(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native fists and stocked Sledgehammer Dimach") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/alpha-dimach", 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 := 10 + 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 = 35 + } + world.combatRoll = func(uint32) uint32 { return 0 } + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("dimach"))) + 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[144]), "remaining": time.Until(player.skillLocks[144]).Seconds(), "inventory": player.inventory, "level": player.level, + "ip": player.stats.ImprovementPoints, "damage": damage, "weapon": name}) + }) + 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 Dimach from ordinary swings, retaining real equip/lock updates. + world.advanceEquipment(now) + world.advanceItemEffects(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_dimach.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-damage) || !reflect.DeepEqual(cold.characters[2].inventory, player.inventory) || + !cold.characters[2].skillLocks[144].Equal(player.skillLocks[144]) || cold.characters[2].skillLocks[144].IsZero() { + t.Fatal("native Dimach damage, ownership or lock changed on cold recovery") + } + }) + } +} diff --git a/server/dimach_test.go b/server/dimach_test.go @@ -0,0 +1,230 @@ +package main + +import ( + "encoding/binary" + "fmt" + "reflect" + "testing" + "time" +) + +func dimachRequest(owner, target uint32) []byte { + request := flingShotRequest(owner, target) + binary.BigEndian.PutUint32(request[len(request)-4:], 144) + return request +} + +func newDimachWorld(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.Dimach = 20 + world.characters[1000000].health = 1000 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + return world, output +} + +func TestDimachCommitsItsOwnDamageAndThirtyMinuteLock(t *testing.T) { + world, output := newDimachWorld(t) + player, target := world.characters[1], world.characters[1000000] + inventory := player.inventory + before := time.Now() + + err := world.handleWeaponSpecial(world.clients[1], dimachRequest(1, target.id)[20:]) + cold := newTestInventoryServer(t) + + if err != nil || target.health != 962 || len(target.activeNanos) != 0 || + player.skillLocks[144].Before(before.Add(30*time.Minute)) || player.skillLocks[144].After(time.Now().Add(30*time.Minute)) || + !player.skillLocks[142].IsZero() || !reflect.DeepEqual(inventory, player.inventory) { + t.Fatal("Dimach omitted its damage/lock or changed Brawl/inventory", target.health, player.skillLocks, err) + } + if cold.characters[target.id].health != 962 || !cold.characters[1].skillLocks[144].Equal(player.skillLocks[144]) { + t.Fatal("Dimach damage or cooldown did not recover") + } + 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][37:41]) != ^uint32(0) || binary.BigEndian.Uint32(output.packets[0][49:53]) != 144 { + t.Fatal("Dimach result did not identify fist slot, no ammo and skill144") + } +} + +func TestDimachUsesOwnSkillAndItemWithFistsOrSledgehammer(t *testing.T) { + for _, scenario := range []struct { + skill uint16 + damage uint32 + }{{0, 0}, {3, 1}, {20, 38}, {21, 38}, {1000, 7000}, {1001, 7005}} { + for _, armed := range []bool{false, true} { + t.Run(fmt.Sprint(scenario.skill, "/", armed), func(t *testing.T) { + world, _ := newDimachWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.stats.Body.Dimach, player.stats.Body.MartialArts, player.stats.Body.Brawling = scenario.skill, 1000, 1000 + target.health = 10000 + if armed { + player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 129026, Quality: 10, Count: 1, Slot: 6}} + } + + err := world.handleWeaponSpecial(world.clients[1], dimachRequest(1, target.id)[20:]) + + if err != nil || target.health != 10000-scenario.damage || player.skillLocks[144].IsZero() { + t.Fatal("Dimach used held weapon, MA, Brawl or incorrect endpoint", target.health, err) + } + }) + } + } +} + +func TestDimachRejectsInvalidUseWithoutOutcome(t *testing.T) { + for _, scenario := range []string{"pistol", "axe", "range", "reload", "equipping", "locked", "sitting", "hidden", "unready", "owner", "dead"} { + t.Run(scenario, func(t *testing.T) { + world, output := newDimachWorld(t) + player, client := world.characters[1], world.clients[1] + request := dimachRequest(1, 1000000)[20:] + switch scenario { + case "pistol", "axe": + template := uint32(123742) + if scenario == "axe" { + template = 209283 + } + player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: template, Quality: 1, Count: 1, Slot: 6}} + case "range": + world.characters[1000000].position[0] = 20 + case "reload": + client.reloadUntil = time.Now().Add(time.Minute) + case "equipping": + client.equipment = &equipmentMove{} + case "locked": + player.setSkillLock_locked(144, 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[144] + + err := world.handleWeaponSpecial(client, request) + + if err != nil || world.characters[1000000].health != 1000 || !player.skillLocks[144].Equal(deadline) || + !reflect.DeepEqual(player.inventory, before) || len(output.packets) != 0 { + t.Fatal("rejected Dimach changed state or feedback", err) + } + }) + } +} + +func TestDimachUsesAuthoredRangeAndPsychicDefense(t *testing.T) { + for _, scenario := range []string{"range", "evade", "psychic", "critical", "Brawl locked"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newDimachWorld(t) + target := world.characters[1000000] + expected := uint32(962) + world.combatRoll = func(limit uint32) uint32 { return limit - 1 } + switch scenario { + case "range": + target.position[0] = 9 + case "evade": + target.stats.Speed.EvadeClose = 10000 + case "psychic": + target.stats.Abilities.Psychic = 10000 + expected = 1000 + case "critical": + world.combatRoll = func(uint32) uint32 { return 0 } + expected = 961 + case "Brawl locked": + world.characters[1].setSkillLock_locked(142, time.Now().Add(time.Minute)) + } + if scenario != "psychic" { + target.stats.Abilities.Psychic = 1 + } + + err := world.handleWeaponSpecial(world.clients[1], dimachRequest(1, target.id)[20:]) + + if err != nil || target.health != expected || world.characters[1].skillLocks[144].IsZero() { + t.Fatal("Dimach ignored its authored range/defense or lost a miss lock", target.health, expected, err) + } + }) + } +} + +func TestDimachRetriesAndColdRecoveryPreserveIndependentDeadline(t *testing.T) { + world, _ := newDimachWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleCombat(client, attackPacket(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + attack, recharge := player.nextAttack, player.rechargeUntil + for range 2 { + if err := world.handleWeaponSpecial(client, dimachRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + } + cold := newTestInventoryServer(t) + cold.clients[1] = &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + + err := cold.handleWeaponSpecial(cold.clients[1], dimachRequest(1, 1000000)[20:]) + + if err != nil || world.characters[1000000].health != 962 || cold.characters[1000000].health != 962 || + player.nextAttack != attack || player.rechargeUntil != recharge || !player.skillLocks[142].IsZero() { + t.Fatal("Dimach retry changed damage, normal attack clock or Brawl lock", err) + } + // Advance only the controlled server lock clock; do not wait thirty minutes. + cold.advanceItemEffects(cold.characters[1].skillLocks[144]) + cold.combatRoll = landedCombatRoll + if err := cold.handleWeaponSpecial(cold.clients[1], dimachRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + if cold.characters[1000000].health != 924 || cold.characters[1].skillLocks[144].IsZero() { + t.Fatal("expired Dimach did not execute again exactly once") + } +} + +func TestDimachFailedKillRollsBackDamageLockLootAndExperience(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 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 := newDimachWorld(t) + player, target := world.characters[1], world.characters[1000000] + world.combatRoll = func(uint32) uint32 { return 0 } + target.health = 1 + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("CREATE TRIGGER fail_dimach " + failure); err != nil { + t.Fatal(err) + } + + err := world.handleWeaponSpecial(world.clients[1], dimachRequest(1, target.id)[20:]) + cold := newTestInventoryServer(t) + + if err == nil || target.health != 1 || target.corpse != nil || !player.skillLocks[144].IsZero() || player.experience != 0 || + cold.characters[1].experience != 0 || !cold.characters[1].skillLocks[144].IsZero() || cold.characters[target.id].health != 1 || len(output.packets) != 0 { + t.Fatal("failed Dimach retained partial kill effects", err) + } + if _, err := world.db.Exec("DROP TRIGGER fail_dimach"); err != nil { + t.Fatal(err) + } + if err := world.handleWeaponSpecial(world.clients[1], dimachRequest(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + cold = newTestInventoryServer(t) + if target.health != 0 || target.corpse == nil || len(target.corpse.items) != 1 || target.corpse.credits != 1 || + player.experience != 100 || cold.characters[1].experience != 100 || cold.characters[1].skillLocks[144].IsZero() || cold.characters[target.id].corpse == nil { + t.Fatal("retried Dimach kill did not commit exactly once") + } + }) + } +} 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], 144) + binary.BigEndian.PutUint32(request[24:28], 143) case "unknown target": binary.BigEndian.PutUint32(request[20:24], 2000000) case "player target": diff --git a/server/target_protocol.go b/server/target_protocol.go @@ -75,10 +75,10 @@ func targetPacket(packet []byte) []byte { packet = append(converted, packet[cursor:]...) } // Three empty byte-counted groups separate the final encoded lists. - // Player spawns carry both MA and Brawl; NPC spawns carry their attack row. + // Players carry MA, Brawl and Dimach; NPCs carry their attack row. tailLength := 24 if flags&1 == 0 { - tailLength += 16 + tailLength += 32 } tail = append([]byte(nil), packet[len(packet)-tailLength:]...) packet = append(packet[:len(packet)-tailLength], 0, 0, 0) diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -52,7 +52,7 @@ func TestTargetCharactersIncludeUnarmedWeapon(t *testing.T) { } want := "000000000003f1000007e20000aac00000aac10000006400000001" if !actor.npc { - want = "000000000003f100000bd30000aac00000aac1000000640000000100011294000112950000008e00000001" + want = "000000000003f100000fc40000aac00000aac1000000640000000100011294000112950000008e000000010000a4310000a4300000009000000001" } 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 @@ -31,24 +31,29 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro server.mutex.Lock() player := server.characters[client.id] skill := binary.BigEndian.Uint32(body[24:28]) + implicit := skill == 142 || skill == 144 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 != 142 && skill != 147 && skill != 148 && skill != 150) { + binary.BigEndian.Uint32(body[16:20]) != 50000 || (!implicit && 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 || skill != 142 && !server.combatInRange_locked(player, target, now) || !server.combatVisible_locked(player, target, now) || + target.playfield != player.playfield || !implicit && !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() return nil } - // WeaponItem 100aaf10: Fast Attack bit18, Burst bit11, Fling bit12. + // WeaponItem 100aaf10 supplies each special's held-weapon capability. capability := uint32(1 << 12) - if skill == 147 { + if skill == 142 { + capability = 1 << 25 + } else if skill == 144 { + capability = 1 << 26 + } else if skill == 147 { capability = 1 << 18 } else if skill == 148 { capability = 1 << 11 @@ -60,17 +65,21 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro break } } - if skill == 142 { - // The implicit Brawl item has its own three-metre range and excludes ranged weapons. + if implicit { + // Implicit specials have their own range and exclude unsupported held weapons. for _, held := range player.inventory.Items { - if (held.Slot == 6 || held.Slot == 8) && held.isWieldableWeapon() && held.templateStat(30)&(1<<25) == 0 { + if (held.Slot == 6 || held.Slot == 8) && held.isWieldableWeapon() && held.templateStat(30)&capability == 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() + distance := float32(3) + if skill == 144 { + distance = 10 + } + distance += player.physicalExtent() + target.physicalExtent() if x*x+y*y+z*z > distance*distance { server.mutex.Unlock() return nil @@ -82,7 +91,9 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro // Prepare a detached result so a failed transaction changes no live actor. seconds := uint32(15) - if skill != 142 { + if skill == 144 { + seconds = 1800 + } else if !implicit { seconds = player.weaponSpecialLockSeconds(player.attackWeapon(), skill) } var damage uint32 @@ -91,6 +102,20 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro if skill == 142 { candidate, stunned = server.prepareBrawl_locked(player, target, now) damage = target.health - candidate.health + } else if skill == 144 { + // Provisional skill-to-QL and hit/critical rules; see docs/dimach.md. + value, _ := player.effectiveStat(144) + quality := uint32(min(500, max(1, value/2))) + weapon := interpolateWeapon(gamedata.ItemTemplates[42033], gamedata.ItemTemplates[42032], quality) + if server.itemAttackLands_locked(player, target, weapon) { + roll := server.combatRoll + if roll == nil { + roll = rand.Uint32N + } + 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)) + } } else if skill == 148 { // Three independent noncritical hits; no later defensive checks or ammo debit. roll := server.combatRoll @@ -120,18 +145,18 @@ 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])) } - // These specials do not deduct ammunition. Brawl uses its own defense check. + // These specials do not deduct ammunition. Implicit attacks use their own defenses. var result []byte death := uint32(0) ammunition := ^uint32(0) - if skill != 142 && skill != 147 && item.usesAmmo() { + if !implicit && skill != 147 && item.usesAmmo() { ammunition = item.Ammo } if target.health == 0 { death = 4 } slot := uint32(6) - if skill == 142 { + if implicit { slot = 0 } for _, value := range []uint32{slot, damage, ammunition, 50000, target.id, skill, death} { diff --git a/server/world.go b/server/world.go @@ -173,15 +173,15 @@ func characterPacket(character *character) []byte { } count := uint32(2018) if !character.npc { - count = 3027 + count = 4036 } 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. + // Native Brawl/Dimach dispatch requires actor-owned implicit action sources. // The fourth row word is unresolved; retain the existing player parameter1. - for _, value := range []uint32{70292, 70293, 142, 1} { + for _, value := range []uint32{70292, 70293, 142, 1, 42033, 42032, 144, 1} { body = binary.BigEndian.AppendUint32(body, value) } } diff --git a/tools/client/test_dimach.mjs b/tools/client/test_dimach.mjs @@ -0,0 +1,74 @@ +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: 'dimach', 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 Dimach 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('KeyK'); + await waitServer('Dimach damage and lock committed', state => state.health === 1000-state.damage && state.locked); + await checkNative(1000-evidence.initial.damage); + evidence.first = await server(); + assert(evidence.first.remaining > 1790 && evidence.first.remaining <= 1800); + assert.deepEqual(evidence.first.inventory, evidence.equipped.inventory); + await game.save(output + '/first'); + + await game.key('KeyK'); + assert.equal((await server()).health, evidence.first.health); + 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'); + + 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('KeyK'); + evidence.retried = await server(); + assert.equal(evidence.retried.health, evidence.first.health); + assert(evidence.retried.locked && evidence.retried.remaining > 1700); + assert.deepEqual(evidence.retried.inventory, evidence.first.inventory); + assert.deepEqual(game.errors, []); + console.log('PASS:', evidence.initial.weapon, 'native Dimach, thirty-minute cooldown, unchanged inventory and reconnect'); +} 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(); } +}