aorecomp

Anarchy Online classic in the browser

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


commit 53c68ea8d37a92a52327c61024bae21dcda751ba
parent 19ebde862defbf582b48f5fcb34c8b9812d93e58
Author: anon <anon@example.com>
Date:   Thu, 22 Oct 2026 04:48:31 +0000

Equip and replicate the first melee weapon

Diffstat:
MDEVELOPERS.md | 10+++++++---
MTODO.md | 4++--
Mdocs/combat-regeneration.md | 5+++--
Mdocs/combat-rules.md | 10++++++++--
Mdocs/inventory.md | 97++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mserver/combat.go | 27++++++++++++++++++++++-----
Aserver/equipment.go | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/equipment_test.go | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/load.go | 6++++++
Mserver/inventory.go | 28++++++++++++++++------------
Mserver/main.go | 6++++++
Mserver/roaming.go | 1+
Mserver/state.go | 1+
13 files changed, 539 insertions(+), 47 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -147,7 +147,7 @@ the server log while live chat remains available. [Server controls](http://127.0.0.1:8080/control) provide character editing, teleporting and time controls. -Basic unarmed PvE combat is available against creature NPCs. Stand within four +Basic PvE combat is available against creature NPCs. Stand within four metres, select one with Tab or a click, then press Q (or the mobile Attack button). Q stops your own attacks, while an opponent already retaliating continues until you leave melee range. Player fists use the shipped QL 1 @@ -164,8 +164,12 @@ attack/recharge phases. Those NPC profiles, fixed fist QL, always-hit attacks and the four-meter range are reconstruction choices. See [combat rules and evidence](docs/combat-rules.md) for the remaining gaps. Human NPCs and players are protected. Defeated creatures remain dead -until the server restarts; reload the game to revive a defeated player. Weapon -equipment, specials, nanos, loot and XP are not implemented. +until the server restarts; reload the game to revive a defeated player. +An owned QL 1 Kinetic Axe can be equipped in the right hand outside combat. +Its requirements, equip delay, appearance, base damage and Melee Initiative +timing are supported; unequipping restores fists. See +[inventory and equipment](docs/inventory.md). Other equipment, combat swaps, +specials, nanos, loot and XP are not implemented. The [client combat reconstruction](docs/combat-client-reconstruction.md) maps native formulas, action scheduling, messages and effects to server obligations diff --git a/TODO.md b/TODO.md @@ -44,9 +44,9 @@ recorded in [inventory behavior](docs/inventory.md). ## Equipment, one kind at a time -- [ ] Equip and unequip one melee weapon. Check: its appearance and base attack +- [x] Equip and unequip one melee weapon. Check: its appearance and base attack data replace fists; unequipping restores fists, including for another observer. -- [ ] Enforce that weapon's requirements. Check: a character below one required +- [x] Enforce that weapon's requirements. Check: a character below one required skill cannot equip it, while a qualifying character can. - [ ] Equip one armor piece. Check: the correct native slot and appearance update, and its armor stats appear and disappear with equip/unequip. diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md @@ -62,8 +62,9 @@ Older profiles with no stats retain abilities 10 and these eight base skills 5. Profiles saved before the four melee skills were added receive base values 5 for the missing fields. Explicitly saved zero skill values remain zero. The native Skills window displays 7 for each new skill at the default abilities, -including ability trickle. These fields prepare the weapon equipment milestone; -server attacks still use fists and Physical Initiative. +including ability trickle. QL 1 Kinetic Axe attacks use Melee Initiative; +unequipping restores fists and Physical Initiative. Its requirements also use +the effective 1h Edged, Brawling and Fast Attack values. Saving writes the explicit stats to `data/players/<id>/player.yaml`. Values survive profile edits, teleporting and restart; location saving still writes only `position.yaml`. Lowering resource maximums clamps current health/nano. diff --git a/docs/combat-rules.md b/docs/combat-rules.md @@ -24,18 +24,24 @@ Development and Soldier title formula, including matching profession 60 and title 37 in FullCharacter. The default level 1 Solitus has 37 HP. See [starting stats](combat-starting-stats.md) for the resource values. -Six abilities and four combat skills are now persistent, editable character +Six abilities and eight trained skills are now persistent, editable character data. Health, nano, attack timing and regeneration derive from those values and native ability trickle. Player recovery is authoritative, with absolute quiet corrections to reconcile the client's prediction. See [resource synchronization](combat-regeneration.md) for the rules and scope. +The first supported melee weapon is QL 1 Kinetic Axe, template 209283. It uses +the catalog's 5..20 base damage and attack/recharge delays with Melee Initiative. +Its three skill requirements, 1.5-second equip delay, persistent right-hand slot +and native owner/observer replication are described in +[inventory and equipment](inventory.md). Combat swapping is not implemented. + The server still selects QL 1 regardless of MA skill, omits hit/critical rolls and armor, and uses NPC 100 health and 5 damage with 1s/1s timing. The uniform normal-damage roll is a reconstruction choice; the item establishes the endpoints, not the historical server's random distribution. The four-meter range approximates physical extents, and there is no server line-of-sight -test. Equipment, nanos, specials, aggression/taunt AI, reclaim, loot, XP and +test. Other equipment, nanos, specials, aggression/taunt AI, reclaim, loot, XP and respawn are not implemented. Reload revival is a local test convenience. These limitations prevent a claim of canonical combat balance. The [NPC balance search](combat-npc-balance.md) identifies authentic Leet Bite diff --git a/docs/inventory.md b/docs/inventory.md @@ -16,7 +16,8 @@ Profile edits and zoning preserve inventory independently of profile fields. Only individual items at an exact catalog quality are supported. Template endpoints are identical; arbitrary-quality interpolation, stacks, backpacks, -equipment, loot and starter loadouts remain separate milestones. +loot and starter loadouts remain separate milestones. QL 1 Kinetic Axe equipment +is described below; other equipment is not supported yet. ## Native messages @@ -45,7 +46,8 @@ verified with the native WASM icon, tooltip and QL 1 details window. `ContainerAddItem` (`0x47537a24`) carries source page/slot, target owner identity and destination slot. The server accepts only an authenticated current session's own ordinary inventory and an empty destination. It saves before acknowledging -the move. Equipment and cross-owner/container transfers are rejected. This +the move. Cross-owner/container transfers are rejected. The supported weapon +also moves between ordinary inventory and the right hand as described below. This layout is corroborated by the local AOtomation `ContainerAddItemMessage` and CellAO `ContainerAddItemMessageHandler` reference sources; it is not the message used by the native same-window visual rearrangement described below. @@ -99,25 +101,6 @@ existing FIFO output queue. Manual WASM evidence is retained locally under `local/inventory-smoke/`: QL 1 details, native rearrangement, held menu, confirmation, deletion and packet logs. -## Melee equipment investigation - -The next fixture uses QL 1 Kinetic Axe, template 209283, from -`server/gamedata/items/items_165.yaml`. Its Wield action requires 1h Edged 103, -Fast Attack 147 and Brawling 142 each greater than 4. The shipped skill-weight -resources are recorded in [editable stats](combat-regeneration.md). The item has -5..20 base damage, attack/recharge delays 125 centiseconds and equip delay 150 -centiseconds. These are catalog values, before combat modifiers. - -The shipped help file `cd_image/text/help/How to Wear and equip things.txt` -documents left-click pickup and placement into Wear. Capturing that path in -the WASM client produced `ContainerAddItem` with source page 104, source slot -64, target character identity and destination 6 (right hand). Taking it back -into inventory produced source page 101, slot 6, and destination 111 (next free -inventory slot). A temporary server probe echoing the move changed the native -inventory/Wear icons but did not draw the weapon on the actor. Production still -rejects these equipment moves; appearance, weapon binding, requirements and -equip timing must be implemented together before checking off that milestone. -Local captures and the temporary probe are in `local/equipment-smoke/`. The isolated fixture grants one pistol before native world initialization. Deletion was checked after reload, and a second simultaneous WASM visitor showed only its own pistol while the first visitor's inventory stayed empty. The @@ -129,3 +112,75 @@ has initial, resume and second-character passes. Run `storage-test.html`, `storage-test.html?resume` and `storage-test.html?other&resume` in one browser context to check persistence and isolation. Chromium and Firefox pass those checks alongside the existing cache and viewport cases. + + +## Melee equipment + +QL 1 Kinetic Axe, template 209283, is the first supported weapon. Its definition +is in `server/gamedata/items/items_165.yaml`. The Wield action requires effective +1h Edged 103, Fast Attack 147 and Brawling 142 each greater than 4. The shipped +skill-weight resources are recorded in [editable stats](combat-regeneration.md). +The catalog supplies 5..20 base damage, attack/recharge delays 125 centiseconds, +equip delay 150 centiseconds, Melee Initiative 118 and mesh 40079 +(`weapon_handaxe.abiff`). Damage scaling, armor, criticals and specials remain +separate milestones; the normal-damage distribution is still provisional. + +The native Wear window accepts left-click pickup from inventory and placement +into the right hand. `ContainerAddItem` uses source page 104 and logical slot +64..93, target owner identity, and destination 6. Unequip requests use page 101, +slot 6, and destination 111 (next free inventory slot). The server selects the +first free logical inventory slot, but echoes the original requested placement +111. Replacing that sentinel with the resolved slot leaves the native Wear icon +unchanged. Ordinary visual ordering still uses the browser preferences above. + +Equipment moves wait 1.5 seconds on the existing 250 ms world tick. The item +remains at its source until the delay completes and the complete inventory +saves atomically. Repeated inventory requests cannot restart the timer or remove +the pending item. Completion rechecks requirements, destination occupancy and +session state. Full inventory and failed saves preserve the equipped item. +Equipping during combat or outstanding recharge is currently rejected; combat +swapping is not yet implemented, and this restriction is not a historical rule. + +The native `WeaponItemFullUpdate` (`0x3b1d2268`) creates the visible owned weapon +and supplies combat data to both owner and observers. Its outer identity is the +persistent item identity, type 51018. The 14.9.1 payload is: + +| Field | Value for this weapon | +| --- | --- | +| Version, uint32 | 11 | +| Parent identity | 50000, owner ID | +| Playfield, uint32 | Current playfield | +| Auxiliary identity | 0, 0 | +| Inventory page and slot, two bytes | 1, 6 | +| Encoded stat list | 3027, then pairs 23/template ID and 701/quality | +| Trailing data length, uint32 | 0 | + +`client/game/kkr.dll/lifted-0053.c`, `sub_360B2440` reads this layout; +`sub_360B2830` loads StaticInstance 23 and applies item-quality stat 701. +`client/game/kkr.dll/lifted-0029.c`, `sub_36063340` attaches the item to its +owner and binds hand slots on inventory page 1. The native equip handler +`sub_360AD0B0` in `client/game/kkr.dll/lifted-0051.c` applies the mesh and weapon +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. +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 +changes use the same update/state lock order as combat. + +`server/equipment_test.go` checks skill boundaries, equip delay, repeated +requests, persistence, failed writes, changed requirements, stale sessions, +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/`. + +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 +ID 1, template 209283 and QL 1. The active-combat unequip attempt retained the +weapon; removal succeeded after disengaging. During forced server downtime, +one worker startup emitted an `Event` error; both clients subsequently loaded +and completed the equipped combat/removal checks. That startup failure is a +separate browser reconnect issue to investigate. diff --git a/server/combat.go b/server/combat.go @@ -1,6 +1,7 @@ package main import ( + "ao/server/gamedata" "encoding/binary" "fmt" "log" @@ -67,15 +68,19 @@ func (server *server) handleCombat(client *worldClient, body []byte) error { return nil } -func unarmedDelays(initiative, aggDef int32) (time.Duration, time.Duration) { +func weaponDelays(weapon *gamedata.Item, initiative, aggDef int32) (time.Duration, time.Duration) { // kkr.dll FUN_1007ab40/FUN_1007ac10, QL 1 fist ItemDelay/RechargeDelay 125. + attackBase, rechargeBase := uint32(125), uint32(125) + if weapon != nil { + attackBase, rechargeBase = itemStat(weapon, 294), itemStat(weapon, 210) + } effective := float64(initiative) * 0.5 if initiative > 1200 { effective = 600 + float64(initiative-1200)*float64(float32(1.0/6)) } // Native float stores precede AggDef subtraction and centisecond truncation. - attack := float64(float32(200-effective*float64(float32(1.0/3)))) - float64(aggDef) - recharge := float64(float32(200-effective*float64(float32(2.0/3)))) - float64(aggDef) + attack := float64(float32(float64(attackBase+75)-effective*float64(float32(1.0/3)))) - float64(aggDef) + recharge := float64(float32(float64(rechargeBase+75)-effective*float64(float32(2.0/3)))) - float64(aggDef) return time.Duration(max(100, int(attack))) * 10 * time.Millisecond, time.Duration(max(100, int(recharge))) * 10 * time.Millisecond } @@ -84,8 +89,13 @@ func (character *character) attackDelays() (time.Duration, time.Duration) { return time.Second, time.Second } stats := character.baseStats() + weapon := character.meleeWeapon() + if weapon != nil { + initiative := stats.effectiveSkill(stats.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + return weaponDelays(weapon, int32(initiative), character.aggDef) + } initiative := stats.effectiveSkill(stats.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) - return unarmedDelays(int32(initiative), character.aggDef) + return weaponDelays(nil, int32(initiative), character.aggDef) } func (character *character) titleLevel() uint32 { @@ -211,6 +221,9 @@ func (server *server) advanceCombat(now time.Time) { damage := rand.Uint32N(3) + 3 if attacker.npc { damage = 5 + } else if weapon := attacker.meleeWeapon(); weapon != nil { + minimum, maximum := itemStat(weapon, 286), itemStat(weapon, 285) + damage = minimum + rand.Uint32N(maximum-minimum+1) } damage = min(damage, target.health) target.health -= damage @@ -263,7 +276,11 @@ func (server *server) sendCombatUpdates(updates map[*worldClient][][]byte) { func hitPacket(attacker, target *character, damage uint32) []byte { // kkr.dll 0x100aec00: damage, ammo, slot, target identity, death reason and result. body := binary.BigEndian.AppendUint32(nil, damage) - for _, value := range []uint32{0xffffffff, 0, 50000, target.id, 0, 4} { + slot := uint32(0) + if attacker.meleeWeapon() != nil { + slot = 6 + } + for _, value := range []uint32{0xffffffff, slot, 50000, target.id, 0, 4} { body = binary.BigEndian.AppendUint32(body, value) } if target.health == 0 { diff --git a/server/equipment.go b/server/equipment.go @@ -0,0 +1,174 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "log" + "slices" + "time" +) + +type equipmentMove struct { + itemID uint32 + source uint32 + destination uint32 + requestedSlot uint32 + readyAt time.Time +} + +func (item ownedItem) isKineticAxe() bool { + return item.Type == 51018 && item.Template == 209283 && item.Quality == 1 +} + +func (character *character) meleeWeapon() *gamedata.Item { + for _, item := range character.inventory.Items { + if item.Slot == 6 && item.isKineticAxe() { + return gamedata.ItemTemplates[item.Template] + } + } + return nil +} + +func itemStat(item *gamedata.Item, stat uint32) uint32 { + for _, value := range item.Stats { + if value[0] == stat { + return value[1] + } + } + return 0 +} + +func (character *character) canWieldKineticAxe() bool { + // Template 209283's Wield action requires all three effective skills > 4. + stats := character.baseStats() + return stats.effectiveSkill(stats.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) >= 5 && + stats.effectiveSkill(stats.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) >= 5 && + stats.effectiveSkill(stats.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) >= 5 +} + +func itemMovePacket(owner, source, destination uint32) []byte { + page := uint32(104) + if source == 6 { + page = 101 + } + var body []byte + for _, value := range []uint32{page, source, 50000, owner, destination} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x47537a24, 50000, owner, body) +} + +func (server *server) equipmentBlocked_locked(character *character, now time.Time) bool { + // Combat swaps are a separate milestone; do not replace an active attack phase. + if now.Before(character.rechargeUntil) { + return true + } + for _, attacker := range server.fighting { + if attacker.id == character.id || attacker.fighting == character.id { + return true + } + } + return false +} + +func (server *server) beginEquipment_locked(client *worldClient, index int, destination uint32) error { + character := server.characters[client.id] + item := character.inventory.Items[index] + requestedSlot := destination + if destination == 111 && item.Slot == 6 { + for destination = 64; destination < 94; destination++ { + if !slices.ContainsFunc(character.inventory.Items, func(other ownedItem) bool { return other.Slot == destination }) { + break + } + } + } + if !item.isKineticAxe() || destination == item.Slot || + (destination != 6 && (destination < 64 || destination >= 94)) || + (destination == 6 && !character.canWieldKineticAxe()) || + slices.ContainsFunc(character.inventory.Items, func(other ownedItem) bool { return other.Slot == destination }) || + server.equipmentBlocked_locked(character, time.Now()) { + return client.send(itemMovePacket(client.id, item.Slot, item.Slot)) + } + + // Leave the owned item at its source until the catalog's equip delay expires. + delay := time.Duration(itemStat(gamedata.ItemTemplates[item.Template], 211)) * 10 * time.Millisecond + client.equipment = &equipmentMove{item.ID, item.Slot, destination, requestedSlot, time.Now().Add(delay)} + return nil +} + +func (server *server) advanceEquipment(now time.Time) { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + updates := make(map[*worldClient][][]byte) + for _, client := range server.clients { + move := client.equipment + if move == nil || now.Before(move.readyAt) { + continue + } + client.equipment = nil + character := server.characters[client.id] + if !client.ready || client.loading || character.health == 0 { + continue + } + index := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.ID == move.itemID && item.Slot == move.source }) + if index < 0 { + continue + } + if server.equipmentBlocked_locked(character, now) || + (move.destination == 6 && !character.canWieldKineticAxe()) || + slices.ContainsFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == move.destination }) { + updates[client] = append(updates[client], itemMovePacket(client.id, move.source, move.source)) + continue + } + + // Save the entire move before publishing inventory or appearance changes. + inventory := playerInventory{LastID: character.inventory.LastID, Items: slices.Clone(character.inventory.Items)} + inventory.Items[index].Slot = move.destination + if err := server.saveInventory_locked(character, inventory); err != nil { + log.Printf("Equipment: %v", err) + updates[client] = append(updates[client], itemMovePacket(client.id, move.source, move.source)) + continue + } + 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)) + } + } + } + updates[client] = append(updates[client], itemMovePacket(client.id, move.source, move.requestedSlot)) + server.queueCombat_locked(updates, character, character, equippedWeaponPackets(character)...) + } + server.mutex.Unlock() + server.sendCombatUpdates(updates) +} + +func weaponUnequipPacket(owner uint32) []byte { + var body []byte + for _, value := range []uint32{97, 0, 0, 0, 6} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x5e477770, 50000, owner, body) +} + +func equippedWeaponPackets(character *character) [][]byte { + for _, item := range character.inventory.Items { + if item.Slot != 6 || !item.isKineticAxe() { + continue + } + // kkr.dll sub_360B2440: version 11, parent, playfield, identity and page/slot bytes. + var body []byte + for _, value := range []uint32{11, 50000, character.id, character.playfield, 0, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + body = append(body, 1, 6) + // sub_360B2830 loads StaticInstance 23, then applies item-quality stat 701. + for _, value := range []uint32{3027, 23, item.Template, 701, item.Quality, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + return [][]byte{n3Packet(0x3b1d2268, item.Type, item.ID, body)} + } + return nil +} diff --git a/server/equipment_test.go b/server/equipment_test.go @@ -0,0 +1,217 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "encoding/hex" + "os" + "reflect" + "testing" + "time" +) + +func newEquipmentWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) + world, conn := newCombatWorld() + player := world.characters[1] + player.name, player.level, player.appearance = "Axe Owner", 1, 277 + player.rotation[3] = 1 + player.stats = defaultCharacterStats() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, 209283); err != nil || !granted { + t.Fatalf("grant axe: %v %v", granted, err) + } + return world, conn +} + +func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) { + world, conn := 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} + request := inventoryMovePacket(1, 64, 6)[20:] + before, err := os.ReadFile("data/players/1/inventory.yaml") + if err != nil { + t.Fatal(err) + } + + started := time.Now() + if err := world.handleInventory(world.clients[1], request); err != nil { + t.Fatal(err) + } + finish := world.clients[1].equipment.readyAt + if finish.Before(started.Add(1500*time.Millisecond)) || finish.After(time.Now().Add(1500*time.Millisecond)) { + t.Fatalf("equip delay differs from the catalog: %v", finish.Sub(started)) + } + world.handleInventory(world.clients[1], request) + world.handleInventory(world.clients[1], inventoryDeletePacket(1, 64)[20:]) + world.advanceEquipment(finish.Add(-time.Nanosecond)) + unchanged, err := os.ReadFile("data/players/1/inventory.yaml") + if err != nil || !bytes.Equal(before, unchanged) || len(conn.packets) != 0 || world.clients[1].equipment.readyAt != finish { + t.Fatalf("pending equip changed the item or timer: %v", err) + } + world.advanceEquipment(finish) + restarted := newTestInventoryServer(t) + if err := world.handleInventory(world.clients[1], itemMovePacket(1, 6, 111)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(world.clients[1].equipment.readyAt) + unequipped := newTestInventoryServer(t) + + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 6}}) || + !reflect.DeepEqual(unequipped.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64}}) { + t.Fatal("equipment move changed identity or did not survive restart") + } + if len(conn.packets) != 4 || 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 || + binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x3b1d2268 || + 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 { + t.Fatalf("native equipment packets: %x %x", conn.packets, observer.packets) + } + length := binary.BigEndian.Uint16(conn.packets[1][6:8]) + if hex.EncodeToString(conn.packets[1][29:length]) != "0000000b0000c35000000001000003b60000000000000000010600000bd30000001700033183000002bd0000000100000000" { + t.Fatalf("native weapon instance: %x", conn.packets[1]) + } +} + +func TestEquipmentRequiresEachEffectiveSkillAtFive(t *testing.T) { + for _, skill := range []string{"one hand edged", "brawling", "fast attack"} { + t.Run(skill, func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player := world.characters[1] + player.stats.OneHandEdged, player.stats.Brawling, player.stats.FastAttack = 3, 3, 3 + switch skill { + case "one hand edged": + player.stats.OneHandEdged = 2 + case "brawling": + player.stats.Brawling = 2 + case "fast attack": + player.stats.FastAttack = 2 + } + + err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + if err != nil || world.clients[1].equipment != nil || player.inventory.Items[0].Slot != 64 { + t.Fatalf("effective skill 4 equipped the axe: %v", err) + } + player.stats.OneHandEdged, player.stats.Brawling, player.stats.FastAttack = 3, 3, 3 + err = world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + if err != nil || world.clients[1].equipment == nil { + t.Fatalf("effective skill 5 failed to equip: %v", err) + } + world.advanceEquipment(world.clients[1].equipment.readyAt) + + if player.inventory.Items[0].Slot != 6 { + t.Fatal("qualifying axe did not reach the right hand") + } + }) + } +} + +func TestEquipmentCompletionRechecksStateAndPreservesFailedSave(t *testing.T) { + for _, scenario := range []string{"requirements", "own combat", "incoming combat", "recharge", "loading", "dead", "replaced session", "failed save"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newEquipmentWorld(t) + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + finish := world.clients[1].equipment.readyAt + switch scenario { + case "requirements": + world.characters[1].stats.Brawling = 0 + case "own combat": + world.characters[1].fighting = 1000000 + world.fighting[1] = world.characters[1] + case "incoming combat": + world.characters[1000000].fighting = 1 + world.fighting[1000000] = world.characters[1000000] + case "recharge": + world.characters[1].rechargeUntil = finish.Add(time.Second) + case "loading": + world.clients[1].loading = true + case "dead": + world.characters[1].health = 0 + case "replaced session": + world.clients[1] = &worldClient{id: 1, ready: true} + case "failed save": + os.Remove("data/players/1/inventory.yaml") + os.Mkdir("data/players/1/inventory.yaml", 0700) + } + + world.advanceEquipment(finish) + + if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64}}) { + t.Fatalf("interrupted equip changed inventory: %+v", world.characters[1].inventory) + } + }) + } +} + +func TestEquipmentFullInventoryDoesNotLoseEquippedWeapon(t *testing.T) { + world, _ := newEquipmentWorld(t) + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + for range 30 { + if granted, err := world.grantItem_locked(world.characters[1], 121567); err != nil || !granted { + t.Fatalf("fill inventory: %v %v", granted, err) + } + } + before := playerInventory{world.characters[1].inventory.LastID, append([]ownedItem(nil), world.characters[1].inventory.Items...)} + + err := world.handleInventory(world.clients[1], itemMovePacket(1, 6, 111)[20:]) + + if err != nil || world.clients[1].equipment != nil || !reflect.DeepEqual(before, world.characters[1].inventory) { + t.Fatalf("full inventory lost the equipped axe: %v", err) + } +} + +func TestEquipmentSelectsAxeDamageSlotAndMeleeInitiative(t *testing.T) { + world, conn := newEquipmentWorld(t) + world.characters[1].stats.PhysicalInitiative = 600 + world.characters[1].stats.MeleeInitiative = 0 + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + + attack, recharge := world.characters[1].attackDelays() + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + conn.packets = nil + world.advanceCombat(world.characters[1].nextAttack) + damage := binary.BigEndian.Uint32(conn.packets[0][29:33]) + + if attack != 1990*time.Millisecond || recharge != 1990*time.Millisecond || + damage < 5 || damage > 20 || world.characters[1000000].health != 100-damage || + binary.BigEndian.Uint32(conn.packets[0][37:41]) != 6 { + t.Fatalf("axe attack data: delays=%v/%v damage=%d packet=%x", attack, recharge, damage, conn.packets[0]) + } + weapon := gamedata.ItemTemplates[209283] + if itemStat(weapon, 209) != 40079 || itemStat(weapon, 211) != 150 || itemStat(weapon, 294) != 125 || itemStat(weapon, 210) != 125 { + t.Fatal("axe appearance or timing differs from the catalog") + } +} + +func TestEquipmentUnequipRestoresFistTimingAndSlot(t *testing.T) { + world, conn := newEquipmentWorld(t) + world.characters[1].stats.PhysicalInitiative = 600 + world.characters[1].stats.MeleeInitiative = 0 + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + + world.handleInventory(world.clients[1], itemMovePacket(1, 6, 111)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + attack, recharge := world.characters[1].attackDelays() + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + conn.packets = nil + world.advanceCombat(world.characters[1].nextAttack) + damage := binary.BigEndian.Uint32(conn.packets[0][29:33]) + + if attack != time.Second || recharge != time.Second || damage < 3 || damage > 5 || + binary.BigEndian.Uint32(conn.packets[0][37:41]) != 0 { + t.Fatalf("unequip did not restore fists: %v/%v damage=%d packet=%x", attack, recharge, damage, conn.packets[0]) + } +} diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -21,6 +21,7 @@ var ( PopulationEvidence NPCExtractionEvidence Monsters []Monster Items ItemCatalog + ItemTemplates = make(map[uint32]*Item) MapCoordinates MapCoordinateData TerrainEvidence TerrainExtractionEvidence Playfields map[uint32]Playfield @@ -108,6 +109,11 @@ func init() { for _, name := range parts { loadItems(name) } + for index := range Items.Items { + if Items.Items[index].RecordType == 1000020 { + ItemTemplates[Items.Items[index].ID] = &Items.Items[index] + } + } } func loadYAML(name string, value any) { diff --git a/server/inventory.go b/server/inventory.go @@ -27,7 +27,8 @@ func (inventory playerInventory) validate() error { slots := make(map[uint32]bool) for _, item := range inventory.Items { if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || - item.Slot < 64 || item.Slot >= 94 || slots[item.Slot] { + (item.Slot != 6 && (item.Slot < 64 || item.Slot >= 94)) || slots[item.Slot] || + (item.Slot == 6 && !item.isKineticAxe()) { return fmt.Errorf("invalid inventory item identity or slot") } ids[item.ID], slots[item.Slot] = true, true @@ -49,14 +50,8 @@ func (server *server) saveInventory_locked(character *character, inventory playe func (server *server) grantItem_locked(character *character, template uint32) (bool, error) { // Start with exact catalog qualities; arbitrary QL interpolation is separate. - var definition *gamedata.Item - for index := range gamedata.Items.Items { - if gamedata.Items.Items[index].ID == template { - definition = &gamedata.Items.Items[index] - break - } - } - if definition == nil || definition.RecordType != 1000020 || definition.Quality == nil { + definition := gamedata.ItemTemplates[template] + if definition == nil || definition.Quality == nil { return false, fmt.Errorf("unknown item template %d", template) } var slot uint32 @@ -92,18 +87,27 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { server.mutex.Lock() defer server.mutex.Unlock() character := server.characters[client.id] - if server.clients[client.id] != client || !client.ready || client.loading || character.health == 0 || + if server.clients[client.id] != client || !client.ready || client.loading || character.health == 0 || client.equipment != nil || binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id { return nil } - // Only this character's ordinary inventory page is supported here. + // Page identities must agree with this owner's actual logical slot. sourceType, sourceSlot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24]) if key == 0x5e477770 { sourceType, sourceSlot = binary.BigEndian.Uint32(body[20:24]), binary.BigEndian.Uint32(body[24:28]) } index := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == sourceSlot }) - if sourceType != 104 || index < 0 { + if index < 0 || (sourceSlot != 6 && sourceType != 104) || (sourceSlot == 6 && sourceType != 101) { + return nil + } + if key == 0x47537a24 && (sourceSlot == 6 || binary.BigEndian.Uint32(body[32:36]) == 6) { + if binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id { + return nil + } + return server.beginEquipment_locked(client, index, binary.BigEndian.Uint32(body[32:36])) + } + if sourceSlot == 6 { return nil } inventory := playerInventory{LastID: character.inventory.LastID, Items: slices.Clone(character.inventory.Items)} diff --git a/server/main.go b/server/main.go @@ -317,6 +317,7 @@ func (server *server) serveWorldClient(client *worldClient) error { for id, other := range server.characters { if id != character.id && other.playfield == character.playfield && server.clients[id] != nil { updates = append(updates, characterPacket(other)) + updates = append(updates, equippedWeaponPackets(other)...) if other.health == 0 { updates = append(updates, deathPacket(other)) } @@ -328,9 +329,11 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, server.chatServerPacket(conn)) } updates = append(updates, fullCharacterPacket(character)) + updates = append(updates, equippedWeaponPackets(character)...) updates = append(updates, server.combatInterest_locked(client, nil)...) updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked())) spawn := characterPacket(character) + equipment := equippedWeaponPackets(character) playfield := character.playfield server.mutex.Unlock() server.sendCombatUpdates(combatUpdates) @@ -345,6 +348,9 @@ func (server *server) serveWorldClient(client *worldClient) error { client.ready = true server.mutex.Unlock() server.broadcast(playfield, character.id, spawn) + for _, packet := range equipment { + server.broadcast(playfield, character.id, packet) + } server.updateMutex.Unlock() } case 5: diff --git a/server/roaming.go b/server/roaming.go @@ -20,6 +20,7 @@ func (server *server) roamNPCs() { defer ticker.Stop() for now := range ticker.C { server.advanceNPCs(now) + server.advanceEquipment(now) server.advanceCombat(now) server.advanceRegeneration(now) } diff --git a/server/state.go b/server/state.go @@ -54,6 +54,7 @@ type worldClient struct { regenerationSeconds uint32 npcs map[uint32]bool dialogue *npcDialogue + equipment *equipmentMove } func (client *worldClient) send(packet []byte) error {