aorecomp

Anarchy Online classic in the browser

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


commit 948e6af8f4ca36d8ff57b937990e50feef872f79
parent 55b204bbce93d4b3069a2b545a384ffba0d1d7e7
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 15:15:13 +0000

Support wielded Briefcase through authored weapon rules

Diffstat:
MTODO.md | 22+++++++++++++++++-----
Adocs/briefcase-weapon.md | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/combat-client-stats.md | 9++++++---
Mdocs/remote-bank.md | 9+++++----
Mserver/backpacks.go | 15++++++++++-----
Aserver/briefcase_weapon_test.go | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 62++++++++++++++++++++++++++++++++++++--------------------------
Mserver/equipment.go | 23+++++------------------
Mserver/main.go | 2+-
Aserver/weapon_stats.go | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/weapon_stats_test.go | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 582 insertions(+), 62 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -883,11 +883,23 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah requirement feedback, repeated use, filled-bag transfers, movement closure and reconnect; protocol tests cover known closed bags and invalid/stale sources. See [remote bank access](docs/remote-bank.md). -- [ ] Support wielding Briefcase of Holding and using its equipped page-101 - source. Implement its researched equip requirements, weapon attacks, specials, - OnWear modifiers and OnHit effects, keeping those separate from bank Use. - Verify equip/remove, persistence, profession/skill/title boundaries, combat - Use rejection, repeated use and failed operations with the native WASM UI. +- [x] Support wielding Briefcase of Holding and using its equipped page-101 + source. Authored attack weights, initiative, equip requirements and OE criteria + use shared weapon rules. Verify normal attacks, OnWear modifiers, equip/remove, + persistence, profession/skill/title boundaries, combat Use rejection, repeated + use and failed operations. See [Briefcase weapon support](docs/briefcase-weapon.md). +- [ ] Complete Briefcase specials and hit effects: general Brawl/Dimach plus + Psychic -17, Psychology +52 and Psychology +22 proc programs. Research original + proc triggers, rolls, resistance/NCU admission and target rules; cover strain + replacement, signed effective stats, skill-buff propagation, NPC persistence, + expiry/death/respawn and atomic outcomes before enabling them. Critical hits + and applying the XP modifier to awarded XP remain the shared combat milestones. +- [ ] Preserve signed effective abilities and skills throughout server stat + calculations. Negative worn modifiers and Psychic debuffs must feed signed + ability trickle without unsigned wrap or an invented zero floor. Direct skill + nano modifiers must affect requirements, attack rating and derived skills. + Cover values below zero, overlapping effects, removal and restart against + the original getter chain; see [Briefcase research](docs/briefcase-weapon.md). - [ ] Research bank CASH/XP semantics and the original server's filled-backpack deletion policy; current zero fields and recursive deletion are reconstruction policies. Also establish the original combat-state producer/expiry and remote diff --git a/docs/briefcase-weapon.md b/docs/briefcase-weapon.md @@ -0,0 +1,132 @@ +# Briefcase weapon support + +Briefcase of Holding 205736 can be equipped in the right hand, removed and +used through an equipped page101 reference to open the bank. Its normal attacks +use the shared weapon clock, range, damage and persistence paths. This does +not complete its Brawl, Dimach, critical or hit-effect behavior. + +## Authored rules and shared calculations + +The original fixed-QL100 item has a 0.1-second equip delay. Wield action8 +requires Bureaucrat, Psychology >299 and title level >3, joined by AND. Unlike +bank Use3, the authored equip expression has no combat predicate. The existing +server combat-swap gate still applies to equipment changes. + +| Field | Original value | +| --- | --- | +| Attack weight | Psychology162, 100% | +| Defense weight | Duck Explosives153, 100% | +| Minimum / maximum / critical bonus | 50 / 125 / 91 | +| Base attack / recharge | 125 / 125 centiseconds | +| Initiative440 | Melee Initiative118 | +| Range287 | 2 metres, before actor extents | +| OnWear | Sensory Improvement122 +5, Sneak Attack146 +10, XP modifier319 +1 | + +The server reads each admitted weapon's action8 predicates for equipping and +overequipping, and its section12 weights for attack rating. This replaces the +assumption that every melee weapon uses 1-Hand Edged and every ranged weapon +uses Pistol. Each weighted skill term is divided by 100 separately; stat276 +is added only when their sum is positive. Fists retain their native MA-plus-276 +fallback. Initiative is selected by authored stat440. + +The Briefcase omits DamageType436. Native WeaponItem constructors seed that +field with Melee91; an explicitly invalid value instead falls back to +Projectile90. A getter returning zero for both cases would lose this distinction. +NoAmmo and clip size -1 mean attacks and bank use consume no ammunition. + +Overequipping scans every strict-bound predicate in action8, including title. +The stored denominators are Psychology299 and title3; they are distinct from +the strict admission thresholds300 and4. Profession equality is not an OE +criterion. Each criterion contributes `min(4,(required-actual)*5/required)` +below its denominator, and the worst tier wins. The recovered endpoint penalty +and the existing provisional AR/armor ordering are described in +[overequipping](overequipping.md). + +| Effective Psychology, title4 | OE tier | Adjusted min / max / critical bonus | +| --- | --- | --- | +| >=240 | 0 | 50 / 125 / 91 | +| 180..239 | 1 | 38 / 94 / 69 | +| 120..179 | 2 | 25 / 63 / 46 | +| 60..119 | 3 | 13 / 32 / 23 | +| <=59 | 4 | 0 / 0 / 0 | + +At Psychology300, title3 retains full effectiveness, title2 gives tier1 and +title1 gives tier3. Dropping below an equip requirement does not remove the +owned item. Ordinary moves still commit before equipment publication. Invalid +source pages, stale sequences and failed persistence cannot open a bank or +publish a new weapon or modifiers. + +## Original evidence and remaining work + +The item resource identity and exact payload hash are retained in +[remote bank evidence](remote-bank.md). The additional research is under +`local/briefcase-weapon-research/`: `content/` preserves all four raw item/nano +records, offsets and hashes; `native/` preserves the original KKR snapshot, +44 validated citations and complete records. + +Original KKR `1008f1f0` supplies the separate signed multiply/divide operations +for attack weights; `10090f10` supplies the action8 OE scan. Live constructor +`100abb20` establishes defaults420=-1,436=91,440=119. Briefcase overrides440 +with118. Native initialization `100b2830` runs OnActivate53076, whose tuple is +consumed by `100ac610` to configure the hit visual effect, not a damage or proc +roll. Full weapon attachment applies the item's OnWear modifiers; runtime +owner/observer checks are needed to detect missing or duplicate application. + +OnHit53089 authors three CastChance entries: target14/program207287/20%, +target2/program207284/3%, target2/program207288/3%. Their programs contain +single Modify effects: Psychic -17 for300 seconds, Psychology +52 and +22 for +2500 seconds each. There are no recursive child programs. The client-local +effect gate excludes53089, so enabling it needs authoritative server outcomes. +Static client target14 routing follows the fight target, with selected-target +fallback; it does not settle original-server proc victim or probability rules. + +Those procs remain disabled until their admission, resistance/NCU, replacement +and persistence rules are established. Existing friendly-buff machinery needs +extension for NPC effects and skill modifiers. Native effective-stat getters +preserve signed values without a zero floor; a hostile Psychic debuff must not +wrap through unsigned arithmetic or invent a clamp. Brawl/Dimach need their +general special-action implementation. Global miss/critical resolution and +kill-XP awards, including modifier319, remain separate TODOs. + +## Verification + +Go tests cover strict profession/skill/title admission, the exact equip timer, +every Psychology OE boundary and title penalties, restored effectiveness, +equipped-use source pages, replay, combat rejection and failed persistence. +The shared calculations have checks for separate weight truncation, AllOff's +positive-sum gate, authored initiative/default selection and omitted damage +type against armor. Existing axe, pistol and armor regressions remain in place. + +The full Go suite passed (`go test ./server/...`, 388.597 seconds for the server). +Affected equipment, weapon, bank, backpack and ammunition paths passed twice +under the race detector (184.173 seconds). Process-crash recovery is run +separately because repeated instrumented child initialization exceeded the +initial combined run's default timeout; the timeout log is retained rather +than counted as a passing run. The isolated crash-recovery race run passed +all four cases (474.436 seconds, `-count=1 -timeout=15m`). +`go vet -stdversion=false ./server/...` passed; +the existing declared-toolchain/WaitGroup.Go mismatch remains tracked in TODO. + +Two Chromium WASM clients used GPU OpenGL4.5 through the normal LAN +preview. Native pickup/place equipped the same Briefcase, and both clients +applied exactly +5/+10/+1 to the corresponding modifier maps. The equipped +shortcut produced page101/slot6 Use, opened the bank repeatedly and worked +after browser reload. A real combat request produced matching owner/observer +melee-hit and death packets. A server-rejected bank Use occurred between the +attack request and the hit; bank use succeeded again after combat ended. + +The native owner's attack rating and damage fields matched Psychology299 +retention and Psychology239 tier1. That equipped identity and tier survived +a real server restart. Remote weapon fields are not used to infer the owner's +OE calculation; the server's hit packet supplies the observer's damage. +Removal cleared the three modifiers for both clients. At239, native re-equipping +displayed the Psychology300 requirement and sent no move. Restoring300 allowed +the same item to equip again with one contribution, and a second removal +returned both clients to baseline. SQLite snapshots preserve all three fixture +instances, quantities and unrelated placements, with no allocation or consumption. + +The retained `local/briefcase-weapon-smoke/verification.json` checks snapshots, +native object/modifier reads, wire packets and rejection feedback. Browser and +adapter errors were empty. Both test clients and their owned fixtures were +cleaned up; all other database rows were unchanged by cleanup, and the single +LAN preview was restored. diff --git a/docs/combat-client-stats.md b/docs/combat-client-stats.md @@ -215,9 +215,12 @@ omission is different from an explicitly invalid value. ## Weapon and nano timing Weapon attack and recharge use the initiative selected by item stat 440. -The fallback for an out-of-range stat ID is Melee Initiative 118. Melee 118, -Ranged 119 and Physical 120 therefore feed the same recovered weapon formula; -the item chooses which skill applies. With `I` the effective initiative: +Attack `1007ab40` passes that stat directly to the actor getter; recharge +`1007ac10` substitutes Melee Initiative 118 when it is negative or above 1200. +Live WeaponItem constructor `100abb20` defaults the field to Ranged Initiative +119; authored data overrides it. The admitted server weapons select valid +Melee 118 or Ranged 119; tests also cover Physical 120 and the omitted-field +default. With `I` the effective initiative: ``` effective_init = I if I <= 1200 else 1200 + (I-1200)/3 diff --git a/docs/remote-bank.md b/docs/remote-bank.md @@ -80,10 +80,11 @@ The implementation uses the server's existing incoming-or-outgoing combat predicate. The original producer and expiry of that state, original-server repeat policy and the bank's lifetime after source removal remain unresolved. -Wielded page101 Use is established in the original engine but is not yet -implemented here. The Briefcase still needs weapon/equip support, OnWear -modifiers and OnHit effects. Its Equip8 predicate lacks the Use3 combat -restriction, so those events must stay distinct. These are explicit TODOs. +Wielded page101 Use, equipment and normal attacks are implemented through the +[shared weapon rules](briefcase-weapon.md). Its Equip8 predicate lacks the +Use3 combat restriction, so those events stay distinct. General combat equipment +changes still use the existing combat-swap policy. Specials and OnHit effects +remain explicit TODOs. ## Verification diff --git a/server/backpacks.go b/server/backpacks.go @@ -62,11 +62,12 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error server.mutex.Lock() defer server.mutex.Unlock() player := server.characters[client.id] + page := binary.BigEndian.Uint32(body[40:44]) if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || client.equipment != nil || binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || binary.BigEndian.Uint32(body[28:32]) > 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || binary.BigEndian.Uint32(body[36:40]) != client.id || - (binary.BigEndian.Uint32(body[40:44]) != 104 && binary.BigEndian.Uint32(body[40:44]) != 102 && binary.BigEndian.Uint32(body[40:44]) != 107 && binary.BigEndian.Uint32(body[40:44]) != 51017) { + (page != 104 && page != 101 && page != 102 && page != 107 && page != 51017) { return nil } sequence := binary.BigEndian.Uint32(body[20:24]) @@ -74,7 +75,7 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error return nil } client.useSequence = sequence - if binary.BigEndian.Uint32(body[40:44]) == 107 { + if page == 107 { // Known carried contents remain usable after their bag window closes. slot := binary.BigEndian.Uint32(body[44:48]) bag := client.backpacks[slot>>16].id @@ -88,9 +89,11 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error } return nil } - if binary.BigEndian.Uint32(body[40:44]) == 104 { + if page == 104 || page == 101 { index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Slot == binary.BigEndian.Uint32(body[44:48]) + return item.Slot == binary.BigEndian.Uint32(body[44:48]) && + (page == 104 && item.Slot >= 64 && item.Slot < 94 || + page == 101 && item.Slot == 6 && item.isWieldableWeapon()) }) if index >= 0 { switch player.inventory.Items[index].Template { @@ -111,8 +114,10 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error } } } + if page == 101 { + return nil + } slot := binary.BigEndian.Uint32(body[44:48]) - page := binary.BigEndian.Uint32(body[40:44]) if page == 104 && (slot < 64 || slot >= 94) { return nil } diff --git a/server/briefcase_weapon_test.go b/server/briefcase_weapon_test.go @@ -0,0 +1,200 @@ +package main + +import ( + "bytes" + "encoding/binary" + "slices" + "testing" + "time" +) + +func equipTestBriefcase(t *testing.T, world *server) { + t.Helper() + client := world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 69, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("Briefcase equip was not admitted") + } + world.advanceEquipment(client.equipment.readyAt) +} + +func TestBriefcaseWeaponEquipUseRemoveAndRestart(t *testing.T) { + world, conn := newRemoteBankWorld(t) + player, client := world.characters[1], world.clients[1] + before, _ := readTestItemStore(world) + started := time.Now() + if err := world.handleInventory(client, inventoryMovePacket(1, 69, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil || client.equipment.readyAt.Before(started.Add(100*time.Millisecond)) || client.equipment.readyAt.After(time.Now().Add(100*time.Millisecond)) { + t.Fatal("Briefcase did not start its authored equip delay") + } + world.advanceEquipment(client.equipment.readyAt.Add(-time.Nanosecond)) + pending, _ := readTestItemStore(world) + if !bytes.Equal(before, pending) { + t.Fatal("Briefcase moved before its equipment timer") + } + + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t) + t.Cleanup(func() { restarted.db.Close() }) + conn.packets = nil + request := backpackUseRequest(1, 6, 1)[20:] + binary.BigEndian.PutUint32(request[40:44], 101) + err := world.handleOwnedItemUse(client, request) + + if err != nil || client.bank == nil || player.attackWeapon() == nil || player.attackWeapon().ID != 205736 || + restarted.characters[1].attackWeapon() == nil || restarted.characters[1].inventory.Items[5].Slot != 6 || + player.equipmentBonus(122) != 5 || player.equipmentBonus(146) != 10 || player.equipmentBonus(319) != 1 || + len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || binary.BigEndian.Uint32(conn.packets[0][53:57]) != 101 { + t.Fatalf("wielded Briefcase lost its identity, effects or bank Use: %v %+v %x", err, player.inventory.Items, conn.packets) + } + if err := world.handleInventory(client, itemMovePacket(1, 6, 111)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + removed := newTestInventoryServer(t) + t.Cleanup(func() { removed.db.Close() }) + if player.attackWeapon() != nil || removed.characters[1].attackWeapon() != nil || player.equipmentBonus(122) != 0 || + player.equipmentBonus(146) != 0 || player.equipmentBonus(319) != 0 || removed.nextItem != 6 || + !slices.ContainsFunc(removed.characters[1].inventory.Items, func(item ownedItem) bool { return item.ID == 6 && item.Slot == 69 && item.Count == 1 }) { + t.Fatal("removing Briefcase retained its effects or changed the instance") + } +} + +func TestBriefcaseWeaponEquipRequirementBoundaries(t *testing.T) { + for _, scenario := range []string{"qualified", "Psychology 299", "title 3", "other profession", "left hand"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newRemoteBankWorld(t) + player, client := world.characters[1], world.clients[1] + destination := uint32(6) + switch scenario { + case "Psychology 299": + player.stats.TradeRepair.Psychology = 297 + case "title 3": + player.level = 99 + case "other profession": + player.profession = 7 + case "left hand": + destination = 8 + } + before, _ := readTestItemStore(world) + + err := world.handleInventory(client, inventoryMovePacket(1, 69, destination)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || (client.equipment != nil) != (scenario == "qualified") { + t.Fatal("equip admission differs from authored requirements", err) + } + }) + } +} + +func TestBriefcaseWeaponDamageUsesAuthoredSkillAndEveryOERequirement(t *testing.T) { + for _, scenario := range []struct { + psychology, level uint16 + minimum, maximum uint32 + }{ + {300, 100, 87, 218}, {299, 100, 87, 218}, {240, 100, 80, 200}, + {239, 100, 60, 150}, {180, 100, 55, 136}, {179, 100, 36, 91}, + {120, 100, 32, 81}, {119, 100, 16, 41}, {60, 100, 14, 36}, {59, 100, 0, 0}, + {300, 99, 87, 218}, {300, 49, 66, 164}, {300, 14, 22, 56}, + } { + world, _ := newRemoteBankWorld(t) + equipTestBriefcase(t, world) + player := world.characters[1] + player.stats.Abilities.Intelligence, player.stats.Abilities.Sense = 1, 1 + player.stats.TradeRepair.Psychology, player.level = scenario.psychology, scenario.level + player.stats.Melee.OneHandEdged, player.stats.Ranged.Pistol = 5000, 5000 + + minimum := player.normalDamage(world.characters[1000000], func(uint32) uint32 { return 0 }) + maximum := player.normalDamage(world.characters[1000000], func(limit uint32) uint32 { return limit - 1 }) + + if minimum != scenario.minimum || maximum != scenario.maximum || player.attackRating() != uint32(scenario.psychology) { + t.Fatalf("Psychology %d level %d: got %d..%d AR%d, want %d..%d", scenario.psychology, scenario.level, minimum, maximum, player.attackRating(), scenario.minimum, scenario.maximum) + } + } +} + +func TestBriefcaseWeaponCombatUseRejectedWithoutLosingEquipment(t *testing.T) { + world, conn := newRemoteBankWorld(t) + equipTestBriefcase(t, world) + world.characters[1].fighting = 1000000 + before, _ := readTestItemStore(world) + conn.packets = nil + request := backpackUseRequest(1, 6, 1)[20:] + binary.BigEndian.PutUint32(request[40:44], 101) + + err := world.handleOwnedItemUse(world.clients[1], request) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || world.clients[1].bank != nil || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 || world.characters[1].inventory.Items[5].Slot != 6 { + t.Fatal("combat Use consumed, removed or activated the Briefcase", err) + } +} + +func TestBriefcaseWeaponRejectsMismatchedUseSourcePages(t *testing.T) { + for _, scenario := range []string{"ordinary page for equipped weapon", "equipped page for inventory", "wrong weapon slot", "replayed use"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newRemoteBankWorld(t) + client := world.clients[1] + request := backpackUseRequest(1, 6, 1)[20:] + binary.BigEndian.PutUint32(request[40:44], 101) + if scenario != "equipped page for inventory" { + equipTestBriefcase(t, world) + } + switch scenario { + case "ordinary page for equipped weapon": + binary.BigEndian.PutUint32(request[40:44], 104) + case "equipped page for inventory": + binary.BigEndian.PutUint32(request[44:48], 69) + case "wrong weapon slot": + binary.BigEndian.PutUint32(request[44:48], 8) + case "replayed use": + if err := world.handleOwnedItemUse(client, request); err != nil { + t.Fatal(err) + } + if err := world.handleBankClose(client, characterActionPacket(1, [5]uint32{106})[20:]); err != nil { + t.Fatal(err) + } + } + before, _ := readTestItemStore(world) + conn.packets = nil + + err := world.handleOwnedItemUse(client, request) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || client.bank != nil || len(conn.packets) != 0 { + t.Fatal("mismatched or replayed source opened the bank", err) + } + }) + } +} + +func TestBriefcaseWeaponFailedEquipDoesNotPublishEffects(t *testing.T) { + world, conn := newRemoteBankWorld(t) + player, client := world.characters[1], world.clients[1] + before, _ := readTestItemStore(world) + if _, err := world.db.Exec("CREATE TRIGGER fail_briefcase_location BEFORE INSERT ON item_locations WHEN NEW.item_id=6 BEGIN SELECT RAISE(ABORT, 'fixture location failure'); END"); err != nil { + t.Fatal(err) + } + conn.packets = nil + + err := world.handleInventory(client, inventoryMovePacket(1, 69, 6)[20:]) + if client.equipment == nil { + t.Fatal("equip did not start", err) + } + world.advanceEquipment(client.equipment.readyAt) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || player.attackWeapon() != nil || player.equipmentBonus(122) != 0 || player.equipmentBonus(146) != 0 || player.equipmentBonus(319) != 0 { + t.Fatal("failed equip changed durable state or active effects", err) + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) != 0x47537a24 { + t.Fatalf("failed equip published weapon/effect data: %x", packet) + } + } +} diff --git a/server/combat.go b/server/combat.go @@ -95,11 +95,14 @@ func (character *character) attackDelays() (time.Duration, time.Duration) { stats := character.baseStats() weapon := character.attackWeapon() if weapon != nil { - initiative := character.effectiveSkill(118, stats.Speed.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) - if itemStat(weapon, 420) == 2 { - initiative = character.effectiveSkill(119, stats.Speed.RangedInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + // WeaponItem defaults to RangedInit; authored 440 selects the actual skill. + initiative := uint32(119) + for _, stat := range weapon.Stats { + if stat[0] == 440 { + initiative = stat[1] + } } - return weaponDelays(weapon, int32(initiative), character.aggDef) + return weaponDelays(weapon, character.effectiveStat(initiative), character.aggDef) } initiative := character.effectiveSkill(120, stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) return weaponDelays(nil, int32(initiative), character.aggDef) @@ -141,12 +144,26 @@ func (character *character) attackRating() uint32 { stats := character.baseStats() weapon := character.attackWeapon() if weapon == nil { - return character.effectiveSkill(100, stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30}) + return uint32(int32(character.effectiveSkill(100, stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30})) + character.equipmentBonus(276)) + } + // kkr.dll 1008f1f0 divides each authored skill contribution separately. + var rating int32 + for _, section := range weapon.Sections { + if section.Type != 4 || section.Subtype != 4 || section.Entries == nil { + continue + } + for _, entry := range *section.Entries { + if entry.Type != nil && *entry.Type == 12 { + for _, weight := range *entry.Stats { + rating += character.effectiveStat(weight[0]) * int32(weight[1]) / 100 + } + } + } } - if itemStat(weapon, 420) == 2 { - return character.effectiveSkill(112, stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) + if rating > 0 { + rating += character.equipmentBonus(276) } - return character.effectiveSkill(103, stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) + return uint32(rating) } func (attacker *character) normalDamage(target *character, roll func(uint32) uint32) uint32 { @@ -154,7 +171,13 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin minimum, maximum, damageType := uint32(3), uint32(5), uint32(91) weapon := attacker.attackWeapon() if weapon != nil { - minimum, maximum, damageType = itemStat(weapon, 286), itemStat(weapon, 285), itemStat(weapon, 436) + minimum, maximum = itemStat(weapon, 286), itemStat(weapon, 285) + // kkr.dll 100abb20 seeds omitted DamageType436 with MeleeAC91. + for _, stat := range weapon.Stats { + if stat[0] == 436 { + damageType = stat[1] + } + } // kkr.dll FUN_100ab7b0 accepts the eight ACs and NanoAC, else ProjectileAC. if (damageType < 90 || damageType > 97) && damageType != 168 { damageType = 90 @@ -163,27 +186,14 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin minimum, maximum = 5, 5 } - // Player fists use MA; the axe and pistol use their authored attack skills. + // Player fists use MA; equipped weapons use their authored attack skills. // NPC attack skills remain unknown. Fractional endpoint truncation is provisional. if !attacker.npc { - stats := attacker.baseStats() rating := attacker.attackRating() if weapon != nil { - // Native OE checks every supported weapon requirement. - // FUN_10090f10/100ab8a0: tier = trunc(5*(1-skill/requirement)). - brawling := attacker.effectiveSkill(142, stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) - fastAttack := attacker.effectiveSkill(147, stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) - skill := min(rating, brawling, fastAttack) - requirement := uint32(4) - if itemStat(weapon, 420) == 2 { - skill = min(rating, attacker.effectiveSkill(150, stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0})) - requirement = 5 - } - if skill < requirement { - tier := min(4, (requirement-skill)*5/requirement) - minimum -= minimum * tier / 4 - maximum -= maximum * tier / 4 - } + tier := attacker.weaponOverequippingTier(weapon) + minimum -= minimum * tier / 4 + maximum -= maximum * tier / 4 } minimum += minimum * rating / 400 maximum += maximum * rating / 400 diff --git a/server/equipment.go b/server/equipment.go @@ -27,7 +27,7 @@ func (item ownedItem) fitsEquipmentSlot(slot uint32) bool { if item.isKodaik() || item.isYalmaha() { return slot == 1 } - if item.isKineticAxe() || item.isFlechettePistol() { + if item.isWieldableWeapon() { return slot == 6 } if item.isMetaplast() { @@ -68,13 +68,8 @@ func (character *character) canEquip(item ownedItem) bool { stats := character.baseStats() return character.effectiveAbility(16) > 5 && character.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 10 } - if item.isKineticAxe() { - return character.canWieldKineticAxe() - } - if item.isFlechettePistol() { - stats := character.baseStats() - return character.effectiveSkill(112, stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) > 5 && - character.effectiveSkill(150, stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0}) > 5 + if item.isWieldableWeapon() { + return character.weaponRequirementsMet(item) } if item.isMetaplast() { low, high := item.templateIDs() @@ -157,7 +152,7 @@ func (character *character) attackWeapon() *gamedata.Item { return gamedata.ItemTemplates[character.combatProfile.Weapon] } for _, item := range character.inventory.Items { - if item.Slot == 6 && (item.isKineticAxe() || item.isFlechettePistol()) { + if item.Slot == 6 && item.isWieldableWeapon() { return gamedata.ItemTemplates[item.Template] } } @@ -173,14 +168,6 @@ func itemStat(item *gamedata.Item, stat uint32) uint32 { return 0 } -func (character *character) canWieldKineticAxe() bool { - // Template 209283's Wield action requires all three effective skills > 4. - stats := character.baseStats() - return character.effectiveSkill(103, stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) >= 5 && - character.effectiveSkill(142, stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) >= 5 && - character.effectiveSkill(147, stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) >= 5 -} - func itemMovePacket(owner, source, destination uint32) []byte { page := uint32(104) if source == 1 || source == 6 || source == 7 || source >= 9 && source <= 14 { @@ -365,7 +352,7 @@ func weaponUnequipPacket(owner uint32) []byte { func equippedWeaponPackets(character *character) [][]byte { for _, item := range character.inventory.Items { - if item.Slot != 6 || !item.isKineticAxe() && !item.isFlechettePistol() { + if item.Slot != 6 || !item.isWieldableWeapon() { continue } // kkr.dll sub_360B2440: version 11, parent, playfield, identity and page/slot bytes. diff --git a/server/main.go b/server/main.go @@ -509,7 +509,7 @@ func (server *server) serveWorldClient(client *worldClient) error { var err error if len(body) == 56 && binary.BigEndian.Uint32(body[24:28]) == 5 { err = server.handleReload(client, body) - } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 102 || binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 107 || binary.BigEndian.Uint32(body[40:44]) == 51017) { + } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 101 || binary.BigEndian.Uint32(body[40:44]) == 102 || binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 107 || binary.BigEndian.Uint32(body[40:44]) == 51017) { err = server.handleOwnedItemUse(client, body) } else if len(body) == 48 && binary.BigEndian.Uint32(body[40:44]) == 51035 { err = server.handleShopUse(client, body) diff --git a/server/weapon_stats.go b/server/weapon_stats.go @@ -0,0 +1,83 @@ +package main + +import "ao/server/gamedata" + +func (item ownedItem) isWieldableWeapon() bool { + return item.isKineticAxe() || item.isFlechettePistol() || + item.Type == 51018 && item.Template == 205736 && item.Quality == 100 +} + +func (character *character) effectiveStat(stat uint32) int32 { + switch stat { + case 16, 17, 18, 19, 20, 21: + return int32(character.effectiveAbility(stat)) + case 37: + return int32(character.titleLevel()) + case 54: + return int32(character.level) + case 60: + return int32(character.profession) + } + stats := character.baseStats() + for _, field := range stats.trainingStats() { + if field.stat == stat { + return int32(character.effectiveSkill(stat, *field.value, gamedata.IPTraining.Weights[stat])) + } + } + return 0 +} + +func (character *character) weaponRequirementsMet(item ownedItem) bool { + // Supported weapon action-8 lists contain equality/strict bounds joined by AND. + for _, section := range gamedata.ItemTemplates[item.Template].Sections { + if section.Actions == nil { + continue + } + for _, action := range *section.Actions { + if action.Type != 8 { + continue + } + for _, requirement := range action.Requirements { + switch requirement.Operator { + case 0: + if character.effectiveStat(uint32(requirement.Stat)) != requirement.Value { + return false + } + case 2: + if character.effectiveStat(uint32(requirement.Stat)) <= requirement.Value { + return false + } + case 4: + // Conjunction has no independent stat predicate. + default: + return false + } + } + } + } + return true +} + +func (character *character) weaponOverequippingTier(weapon *gamedata.Item) uint32 { + // kkr.dll 10090f10 scans every action-8 operator-2 predicate, including title. + var tier uint32 + for _, section := range weapon.Sections { + if section.Actions == nil { + continue + } + for _, action := range *section.Actions { + if action.Type != 8 { + continue + } + for _, requirement := range action.Requirements { + if requirement.Operator == 2 { + actual := character.effectiveStat(uint32(requirement.Stat)) + if actual < requirement.Value { + tier = max(tier, min(4, uint32((int64(requirement.Value)-int64(actual))*5/int64(requirement.Value)))) + } + } + } + } + } + return tier +} diff --git a/server/weapon_stats_test.go b/server/weapon_stats_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "ao/server/gamedata" + "slices" + "testing" + "time" +) + +func TestWeaponRatingTruncatesEachAuthoredWeightBeforeAllOff(t *testing.T) { + for _, scenario := range []struct { + edged, pistol uint16 + rating uint32 + }{{1, 1, 0}, {5, 9, 15}, {9, 5, 15}, {400, 200, 309}} { + world, _ := newEquipmentWorld(t) + player := world.characters[1] + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandEdged, player.stats.Ranged.Pistol = scenario.edged, scenario.pistol + original := gamedata.ItemTemplates[209283] + weapon := *original + weights := [][2]uint32{{103, 50}, {112, 50}} + kind := uint32(12) + entries := []gamedata.ItemEntry{{Type: &kind, Stats: &weights}} + stat, amount := int32(276), int32(9) + functions := []gamedata.ItemFunction{{ID: 53045, Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &amount}}}} + weapon.Sections = []gamedata.ItemSection{{Type: 4, Subtype: 4, Entries: &entries}, {Type: 14, Subtype: 19, Entries: &entries}, {Type: 2, Subtype: 14, Functions: &functions}} + gamedata.ItemTemplates[209283] = &weapon + t.Cleanup(func() { gamedata.ItemTemplates[209283] = original }) + + rating := player.attackRating() + + if rating != scenario.rating { + t.Fatalf("skills %d/%d: got rating %d, want %d", scenario.edged, scenario.pistol, rating, scenario.rating) + } + gamedata.ItemTemplates[209283] = original + } +} + +func TestWeaponInitiativeUsesAuthoredStatAndNativeDefaults(t *testing.T) { + for _, scenario := range []struct { + stat uint32 + attack, recharge time.Duration + }{{118, 1990 * time.Millisecond, 1990 * time.Millisecond}, {119, 1500 * time.Millisecond, time.Second}, {120, time.Second, time.Second}, {0, 1500 * time.Millisecond, time.Second}} { + world, _ := newEquipmentWorld(t) + player := world.characters[1] + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + player.stats.Speed.MeleeInitiative, player.stats.Speed.RangedInitiative, player.stats.Speed.PhysicalInitiative = 0, 298, 598 + original := gamedata.ItemTemplates[209283] + weapon := *original + weapon.Stats = slices.Clone(original.Stats) + for index, stat := range weapon.Stats { + if stat[0] == 440 { + weapon.Stats[index][1] = scenario.stat + if scenario.stat == 0 { + weapon.Stats = slices.Delete(weapon.Stats, index, index+1) + } + break + } + } + gamedata.ItemTemplates[209283] = &weapon + t.Cleanup(func() { gamedata.ItemTemplates[209283] = original }) + + attack, recharge := player.attackDelays() + + if attack != scenario.attack || recharge != scenario.recharge { + t.Fatalf("initiative stat %d: got %v/%v, want %v/%v", scenario.stat, attack, recharge, scenario.attack, scenario.recharge) + } + gamedata.ItemTemplates[209283] = original + } +} + +func TestBriefcaseWeaponOmittedDamageTypeUsesMeleeArmor(t *testing.T) { + world, _ := newArmorDamageWorld(t) + attacker := &character{level: 100, stats: testCharacterStats(), inventory: playerInventory{ + Items: []ownedItem{{ID: 10, Type: 51018, Template: 205736, Quality: 100, Slot: 6, Count: 1}}, + }} + attacker.stats.TradeRepair.Psychology = 298 + + damage := attacker.normalDamage(world.characters[1], func(limit uint32) uint32 { return limit - 1 }) + + if damage != 131 { + t.Fatalf("omitted damage type did not use melee armor: %d", damage) + } +}