aorecomp

Anarchy Online classic in the browser

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


commit 3097e5e97b9b5e7534ce31de0dc0ed4327a745cf
parent 40043e0012737cbc0d30f5472583f1a36277f1f3
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 05:03:48 +0000

Add durable pistol ammunition and native reload

Diffstat:
MTODO.md | 11++++++++---
Adocs/ranged-weapons.md | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/world-state.md | 3++-
Mserver/armor_test.go | 4++--
Mserver/attack_rating_test.go | 2+-
Mserver/backpacks_test.go | 18+++++++++---------
Mserver/belts_test.go | 2+-
Mserver/combat.go | 42++++++++++++++++++++++++++++++++----------
Mserver/control_data_test.go | 6+++---
Mserver/database_test.go | 4++--
Mserver/equipment.go | 24+++++++++++++++++++-----
Mserver/equipment_test.go | 34+++++++++++++++++++++++++++++++---
Mserver/flying_vehicle_test.go | 6+++---
Mserver/implants_test.go | 4++--
Mserver/inventory.go | 11++++++-----
Mserver/inventory_test.go | 2+-
Mserver/item_database.go | 10+++++-----
Mserver/item_pages.go | 4++--
Mserver/item_store.go | 15++++++++-------
Mserver/item_store_test.go | 2+-
Mserver/loot_test.go | 2+-
Mserver/main.go | 8+++++++-
Mserver/nano_casting.go | 2+-
Mserver/overequipping_test.go | 2+-
Aserver/ranged.go | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/ranged_test.go | 354+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/reclaim_test.go | 24++++++++++++------------
Mserver/stacks.go | 2+-
Mserver/stacks_test.go | 20++++++++++----------
Mserver/state.go | 1+
Mserver/target_protocol.go | 13+++++++++----
Mserver/vehicle_test.go | 4++--
Mserver/world.go | 2+-
Mserver/world.sql | 3++-
34 files changed, 832 insertions(+), 101 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -127,11 +127,11 @@ its boundary checks and original-server evidence limits are recorded in ## Additional weapon actions -- [ ] Fire one ranged weapon with a loaded magazine. Check: it attacks outside +- [x] Fire one ranged weapon with a loaded magazine. Check: it attacks outside melee range, uses its own timing and consumes one round per applicable shot. -- [ ] Stop firing when the magazine is empty. Check: an empty weapon cannot +- [x] Stop firing when the magazine is empty. Check: an empty weapon cannot continue dealing damage or create ammunition on reconnect. -- [ ] Reload that weapon. Check: compatible inventory ammunition fills the +- [x] Reload that weapon. Check: compatible inventory ammunition fills the magazine after the correct delay and the total round count is conserved. - [ ] Implement one melee special. Check: a suitable weapon/character can use the action once, with native feedback and an enforced skill lock. @@ -142,6 +142,11 @@ its boundary checks and original-server evidence limits are recorded in - [ ] Swap a weapon during combat. Check: swapping cannot bypass an existing recharge or leave results queued for a removed weapon. +The QL 1 Flechette Pistol and Bullets are the verified example. Native reload +replies update the loaded count at reload start and block firing until the +timer completes. See [pistol ammunition and reload](docs/ranged-weapons.md) +for exact records, protocol, tests and remaining reconstruction assumptions. + ## NPC profiles and behavior - [x] Give one creature at one level an explicit combat profile. Check: its diff --git a/docs/ranged-weapons.md b/docs/ranged-weapons.md @@ -0,0 +1,131 @@ +# Conventional pistol and ammunition + +The supported example is the exact QL 1 Rusty OT M-10 Flechette Pistol, +template 123742, with QL 1 Bullets, template 21605. It occupies the right hand. +The catalog also permits the left hand; dual wield and left-hand scheduling +remain separate TODOs. Unsupported wear requests receive a source-slot reply +so the native client can restore the inventory item. + +## Catalog rules + +The embedded 14.9.1 records provide: + +| Property | Pistol value | +| --- | --- | +| Damage | 3-12 projectile, critical bonus 12 | +| Attack / recharge / equip delay | 1.25 / 1.25 / 1.50 seconds | +| Range | 22 meters before native actor-extent adjustments | +| Ammunition / capacity | Bullets (stat 420 = 2), 20 rounds | +| Attack / defense skill | 100% Pistol / 100% Dodge-Ranged | +| Wield requirements | Pistol > 5 and Fling Shot > 5 | + +The pistol uses Ranged Initiative and the existing aggression/timing rules. +Its attack rating uses Pistol with 60% Agility and 40% Sense trickle-down; +Fling Shot uses Agility. The requirement's raw value 5 is also used for the +native overequipping calculation. Critical hits, misses and Fling Shot are +not implemented by this milestone. + +The [AOPPA source mirror](https://github.com/Noeda/aoppa) provides the stat and +ammo enumeration names (`output-xml.map`), record interpretation (`parser.cc`) +and requirement operators (`output-xml.cc`). The selected game's records, +rather than the mirror's later expansion data, supply these values. + +## Native protocol + +The original 14.9.1 `kkr.dll` (SHA-256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`) +provides the reload contract: + +- `N3Msg_UseItem`, address `0x1002acd0`: synthetic identity type `0xdead` + sends CharacterAction `0x5e477770` with `{106,0,0,0,0}`. +- `N3Msg_UseItemOnItem`, `0x1002a8b0`: GenericCmd `0x52526858`, command 5, + supplies the source ammunition and target weapon. Actual WASM controls + send source `(104, inventorySlot)` and target `(101,6)` for the right hand. + The persistent weapon identity is accepted as well. +- GenericCmd receives its ordinary success/rejection ACK with the original + sequence. A repeated sequence cannot consume ammunition again. The global + CharacterAction request has no GenericCmd ACK. +- Reload `0x26515e61` carries seven DWORDs: source page, source slot, weapon + type, weapon instance ID, remaining stack count, loaded count and remove-stack + boolean. The source slot is translated from internal 64..93 to native 48..77; + the weapon instance ID is preserved. +- Reader/activation `0x10080bf0`/`0x10080ca0`, then holder `0x1007bca0`, update + the stack and weapon stat 26 immediately and start a category-5 reload timer. + Completion in `0x1007bdf0` uses one raw RechargeDelay phase and sends no + completion request. The weapon cannot fire during that delay. +- Timer interruption `0x100529a0` resets an active attack and pauses remaining + recharge. The server resumes with a full attack phase after an interrupted + attack, or preserves remaining recharge before the next attack. +- AttackInfo `0x1007a660` writes the authoritative remaining ammunition into + weapon stat 26. An animation alone is not evidence of round consumption. + +The native `WeaponItem` stat array can be inspected without executing guest +methods: subtract `0x8c` from its registered dynel pointer, follow `[base+4]` +then `[container+4]`, and read signed DWORD index 26. Constructor +`sub_360ABA20` in `client/game/kkr.dll/lifted-0051.c` establishes the subobject +offset; getter `sub_36003000` in `lifted-0000.c` establishes the array access. + +## Server policy and durability + +The original server's stack selection and transfer policy were not recovered. +This implementation chooses the lowest compatible ordinary inventory slot +for a global reload, and transfers as many available rounds as fit from that +one stack. Explicit use consumes only the named stack. Reloading a full weapon, +missing/wrong ammunition, a foreign item, an invalid session, or overlapping +equipment/nano/reload work cannot transfer rounds. + +Loaded ammunition is an `items.ammo` scalar. Each shot commits its one-round +debit before damage or AttackInfo is published. Reload commits loaded rounds, +source-stack reduction/removal and the weapon deadline in one transaction +before publishing ACK/Reload. Failed saves leave the live state unchanged. +Equipment moves, admin assignment, backpacks, reclaim and restart preserve +the instance's loaded count. Other item types cannot have nonzero ammunition; +the pistol cannot exceed its catalog capacity. There are no schema migrations +for earlier development databases. + +Automatic reload, multiple-stack reload, left-hand weapons, cancellation policy +and original-server timing beyond the recovered native timer remain open. +The native reply changes the displayed loaded count at reload start; firing +remains blocked until completion. + +## Verification + +`server/ranged_test.go` covers deadline boundaries, Ranged Initiative, shared +AttackInfo counts, empty magazines, restart, full/partial reload, stack removal, +repeated explicit requests, both weapon identity forms, interrupted attack and +recharge, invalid requests, failed shot/reload transactions, wield requirements +and ammunition preservation through equipment changes. The equipment regression +also verifies corrective replies for unsupported wear slots and unchanged +durable inventory. These focused checks do not replace the broader gameplay +audits in `TODO.md`. + +The two-client WASM check uses the one normal HTTPS development server. Native +controls equipped the pistol, hit a real profiled Leet from outside melee range, +and reduced the magazine from 3 to 2. Reconnecting after a server restart kept +2 loaded rounds and the five-round source stack. Picking up the visible Bullets +stack and right-clicking the worn pistol sent command 5 with target `(101,6)`; +the source stack vanished, native stat 26 and SQLite both became 7, and chat +reported `Reloading` followed by `Reloading completed`. The manual controls +checks exposed the wear-slot request form; an identity-only unit test had +missed it. No adapter or page errors occurred in those runs. + +After that reload, seven native projectile hits dealt 7, 10, 9, 7, 5, 8 and 10 +damage to the real Leet. Both clients' native target HP became 44 from 100; +both weapon objects and SQLite reached zero loaded rounds, with no remaining +ammunition stack. A displayed shot was counted only with its damage result and +durable round debit. +An empty-magazine retry left the native and durable loaded counts at zero and +produced no further projectile damage. Both clients continued to agree on +target HP as the NPC regenerated. +A second normal-server restart and WASM reconnect restored the empty weapon +with native stat 26 still zero and no replacement ammunition stack. + +The earlier disappearing-equipment report is still an open regression audit. +The missing reply for unsupported slots is reproduced by a server test, but +has not established the cause of that historical player report. +The final WASM rejection check created Worn Metaplast Armor Helmet 85557, +assigned it to ordinary inventory and used native auto-equip. The client sent +destination 18 (head), which this server does not support. The corrective reply +kept the helmet visibly in inventory, left the head empty and preserved the +same instance in SQLite. The focused regression uses that exact template and +native destination. diff --git a/docs/world-state.md b/docs/world-state.md @@ -11,7 +11,8 @@ The database contains: - `npcs`: live NPC poses, health, roaming state, damage contributors, corpse cash/ownership/expiry and respawn deadlines, including expired actors whose replacements are still pending. -- `items`: globally unique item IDs and instance properties. +- `items`: globally unique item IDs, stack counts, loaded ammunition and other + instance properties. - `item_locations`: inventory, equipment, backpack, reclaim and corpse slots. - `chat_history`: private history per participant, indexed by owner and order. diff --git a/server/armor_test.go b/server/armor_test.go @@ -50,7 +50,7 @@ func TestArmorNativeMoveDelayAndRestart(t *testing.T) { world.advanceEquipment(finish) restarted := newTestInventoryServer(t) - if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64, 1}, {2, 51022, 85686, 1, 21, 1}, {3, 51022, 85638, 1, 66, 1}}) { + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}, {ID: 2, Type: 51022, Template: 85686, Quality: 1, Slot: 21, Count: 1}, {ID: 3, Type: 51022, Template: 85638, Quality: 1, Slot: 66, Count: 1}}) { t.Fatalf("armor identity or slot did not persist: %+v", restarted.characters[1].inventory) } if len(conn.packets) != 2 || len(observer.packets) != 1 || @@ -126,7 +126,7 @@ func TestArmorRejectsRequirementsAndInterruptedWear(t *testing.T) { case "unsupported identity": player.inventory.Items[1].Type = 51018 case "occupied": - player.inventory.Items = append(player.inventory.Items, ownedItem{4, 51022, 85686, 1, 21, 1}) + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 4, Type: 51022, Template: 85686, Quality: 1, Slot: 21, Count: 1}) } before := append([]ownedItem(nil), player.inventory.Items...) diff --git a/server/attack_rating_test.go b/server/attack_rating_test.go @@ -84,7 +84,7 @@ func TestAttackRatingFistEndpointsIncludeZeroSkill(t *testing.T) { func TestAttackRatingScaledMinimumPrecedesArmor(t *testing.T) { world, _ := newArmorDamageWorld(t) attacker := &character{stats: defaultCharacterStats(), inventory: playerInventory{ - Items: []ownedItem{{1, 51018, 209283, 1, 6, 1}}, + Items: []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}, }} attacker.stats.Melee.OneHandEdged = 398 var hits []uint32 diff --git a/server/backpacks_test.go b/server/backpacks_test.go @@ -126,8 +126,8 @@ func TestBackpackNativeWireTransferAndRestart(t *testing.T) { binary.BigEndian.Uint32(put[45:49]) != 0 || binary.BigEndian.Uint32(taken[33:37]) != 1<<16 || binary.BigEndian.Uint32(taken[45:49]) != 77 { t.Fatalf("native backpack fields changed: %x %x %x %x %x", ack, chest, contents, put, taken) } - if !reflect.DeepEqual(stored.Containers, map[uint32][]ownedItem{3: {{5, 51018, 121567, 1, 0, 1}}}) || - len(restarted.inventory.Containers) != 0 || !slices.Contains(restarted.inventory.Items, ownedItem{5, 51018, 121567, 1, 93, 1}) || restarted.inventory.LastID != 5 { + if !reflect.DeepEqual(stored.Containers, map[uint32][]ownedItem{3: {{ID: 5, Type: 51018, Template: 121567, Quality: 1, Count: 1}}}) || + len(restarted.inventory.Containers) != 0 || !slices.Contains(restarted.inventory.Items, ownedItem{ID: 5, Type: 51018, Template: 121567, Quality: 1, Slot: 93, Count: 1}) || restarted.inventory.LastID != 5 { t.Fatalf("transfer changed item identity or failed persistence: %+v %+v", stored, restarted.inventory) } } @@ -153,7 +153,7 @@ func TestBackpackTransferBetweenClosedAndOpenBags(t *testing.T) { err := world.handleInventory(client, backpackMoveRequest(107, 1<<16, 51017, 4, 111)[20:]) restarted := newTestInventoryServer(t).characters[1] - if err != nil || !reflect.DeepEqual(restarted.inventory.Containers, map[uint32][]ownedItem{4: {{5, 51018, 121567, 1, 0, 1}}}) || len(restarted.inventory.Items) != 4 { + if err != nil || !reflect.DeepEqual(restarted.inventory.Containers, map[uint32][]ownedItem{4: {{ID: 5, Type: 51018, Template: 121567, Quality: 1, Count: 1}}}) || len(restarted.inventory.Items) != 4 { t.Fatalf("closed bag placement or bag-to-bag transfer failed: %+v %v", restarted.inventory, err) } } @@ -286,7 +286,7 @@ func TestBackpackStackSplitJoinAndDelete(t *testing.T) { err := world.handleInventory(client, action(112, 1<<16, 152030, 152030)) restarted := newTestInventoryServer(t).characters[1] - if err != nil || !reflect.DeepEqual(joined.Containers[3], []ownedItem{{1, 51005, 152030, 42, 0, 3}}) || len(restarted.inventory.Containers) != 0 || restarted.inventory.LastID != 6 { + if err != nil || !reflect.DeepEqual(joined.Containers[3], []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 0, Count: 3}}) || len(restarted.inventory.Containers) != 0 || restarted.inventory.LastID != 6 { t.Fatalf("bag stack actions lost quantities/identities: %+v %+v %v", joined, restarted.inventory, err) } } @@ -317,8 +317,8 @@ func TestBackpackContentsSurviveReclaim(t *testing.T) { err := world.handleInventory(client, reclaimTakeRequest(uint32(slot))) world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]) - if err != nil || !reflect.DeepEqual(contents, []ownedItem{{1, 51005, 152030, 42, 0, 3}}) || - !reflect.DeepEqual(player.inventory.Containers[3], contents) || !slices.Contains(player.inventory.Items, ownedItem{3, 51017, 99228, 1, 64, 1}) || !client.backpacks[1].open { + if err != nil || !reflect.DeepEqual(contents, []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 0, Count: 3}}) || + !reflect.DeepEqual(player.inventory.Containers[3], contents) || !slices.Contains(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}) || !client.backpacks[1].open { t.Fatalf("reclaim lost a filled backpack or its contents: %+v %v", player.inventory, err) } } @@ -347,7 +347,7 @@ func TestBackpackSaveRejectsOrphanedAndDuplicateContents(t *testing.T) { world, _ := newBackpackWorld(t) inventory := world.characters[1].inventory inventory.LastID = 7 - inventory.Containers = map[uint32][]ownedItem{3: {{6, 51018, 121567, 1, 0, 1}}} + inventory.Containers = map[uint32][]ownedItem{3: {{ID: 6, Type: 51018, Template: 121567, Quality: 1, Count: 1}}} switch scenario { case "orphan": inventory.Containers[99] = inventory.Containers[3] @@ -355,11 +355,11 @@ func TestBackpackSaveRejectsOrphanedAndDuplicateContents(t *testing.T) { case "duplicate": inventory.Containers[3][0].ID = 1 case "nested": - inventory.Containers[3][0] = ownedItem{6, 51017, 99228, 1, 0, 1} + inventory.Containers[3][0] = ownedItem{ID: 6, Type: 51017, Template: 99228, Quality: 1, Slot: 0, Count: 1} case "outside capacity": inventory.Containers[3][0].Slot = 21 case "occupied": - inventory.Containers[3] = append(inventory.Containers[3], ownedItem{7, 51018, 121567, 1, 0, 1}) + inventory.Containers[3] = append(inventory.Containers[3], ownedItem{ID: 7, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}) } err := world.saveInventory_locked(world.characters[1], inventory) diff --git a/server/belts_test.go b/server/belts_test.go @@ -178,7 +178,7 @@ func TestBeltRejectsAnyOccupiedDeckPosition(t *testing.T) { world.handleInventory(client, inventoryMovePacket(1, 67, 7)[20:]) world.advanceEquipment(client.equipment.readyAt) // The native rule checks occupied positions, regardless of item class. - player.inventory.Items = append(player.inventory.Items, ownedItem{7, 51018, 121567, 1, slot, 1}) + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 7, Type: 51018, Template: 121567, Quality: 1, Slot: slot, Count: 1}) world.handleInventory(client, itemMovePacket(1, 7, 111)[20:]) diff --git a/server/combat.go b/server/combat.go @@ -87,14 +87,17 @@ func weaponDelays(weapon *gamedata.Item, initiative, aggDef int32) (time.Duratio func (character *character) attackDelays() (time.Duration, time.Duration) { if character.npc { if character.combatProfile != nil { - return weaponDelays(character.meleeWeapon(), character.combatProfile.Initiative, character.combatProfile.AggDef) + return weaponDelays(character.attackWeapon(), character.combatProfile.Initiative, character.combatProfile.AggDef) } return time.Second, time.Second } stats := character.baseStats() - weapon := character.meleeWeapon() + weapon := character.attackWeapon() if weapon != nil { initiative := stats.effectiveSkill(stats.Speed.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + if itemStat(weapon, 420) == 2 { + initiative = stats.effectiveSkill(stats.Speed.RangedInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + } return weaponDelays(weapon, int32(initiative), character.aggDef) } initiative := stats.effectiveSkill(stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) @@ -136,7 +139,7 @@ func (character *character) maximumNano() uint32 { func (attacker *character) normalDamage(target *character, roll func(uint32) uint32) uint32 { // Exact catalog endpoints and the weapon's native protection type. minimum, maximum, damageType := uint32(3), uint32(5), uint32(91) - weapon := attacker.meleeWeapon() + weapon := attacker.attackWeapon() if weapon != nil { minimum, maximum, damageType = itemStat(weapon, 286), itemStat(weapon, 285), itemStat(weapon, 436) // kkr.dll FUN_100ab7b0 accepts the eight ACs and NanoAC, else ProjectileAC. @@ -147,7 +150,7 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin minimum, maximum = 5, 5 } - // Player fists use MA; the supported axe uses 100% 1-Hand Edged. + // Player fists use MA; the axe and pistol use their authored attack skills. // NPC attack skills remain unknown. Fractional endpoint truncation is provisional. if !attacker.npc { stats := attacker.baseStats() @@ -155,13 +158,19 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin if weapon != nil { rating = stats.effectiveSkill(stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) - // The axe's three action-8 requirements are 4. Native OE checks them all. + // Native OE checks every supported weapon requirement. // FUN_10090f10/100ab8a0: tier = trunc(5*(1-skill/requirement)). brawling := stats.effectiveSkill(stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) fastAttack := stats.effectiveSkill(stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) skill := min(rating, brawling, fastAttack) - if skill < 4 { - tier := min(4, (4-skill)*5/4) + requirement := uint32(4) + if itemStat(weapon, 420) == 2 { + rating = stats.effectiveSkill(stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) + skill = min(rating, stats.effectiveSkill(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 } @@ -201,7 +210,7 @@ func (server *server) combatInRange_locked(attacker, target *character, now time } x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] itemRange := uint32(2) - if weapon := attacker.meleeWeapon(); weapon != nil { + if weapon := attacker.attackWeapon(); weapon != nil { itemRange = itemStat(weapon, 287) } // FUN_10078cb0 adds the attacker's extent twice and the target's once. @@ -305,6 +314,13 @@ func (server *server) advanceCombat(now time.Time) { if now.Before(attacker.nextAttack) { continue } + if fired, err := server.consumeBullet_locked(attacker); err != nil || !fired { + if err != nil { + log.Printf("Ammunition: %v", err) + } + server.stopAttack_locked(attacker, updates) + continue + } damage := min(attacker.normalDamage(target, rand.Uint32N), target.health) if damage == target.health && !target.npc { @@ -401,10 +417,16 @@ 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) slot := uint32(0) - if !attacker.npc && attacker.meleeWeapon() != nil { + ammo := uint32(0xffffffff) + if !attacker.npc && attacker.attackWeapon() != nil { slot = 6 } - for _, value := range []uint32{0xffffffff, slot, 50000, target.id, 0, 4} { + for _, item := range attacker.inventory.Items { + if item.Slot == 6 && item.isFlechettePistol() { + ammo = item.Ammo + } + } + for _, value := range []uint32{ammo, slot, 50000, target.id, 0, 4} { body = binary.BigEndian.AppendUint32(body, value) } if target.health == 0 { diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -101,8 +101,8 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing t.Fatalf("global registry: %+v", restarted.items) } inventory := restarted.characters[1].inventory - if len(inventory.Items) != 2 || inventory.Items[0] != (ownedItem{1, 51018, 121567, 1, 64, 1}) || inventory.Items[1] != (ownedItem{2, 51017, 99228, 1, 65, 1}) || - len(inventory.Containers[2]) != 1 || inventory.Containers[2][0] != (ownedItem{3, 51018, 121567, 1, 0, 1}) { + if len(inventory.Items) != 2 || inventory.Items[0] != (ownedItem{ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1}) || inventory.Items[1] != (ownedItem{ID: 2, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}) || + len(inventory.Containers[2]) != 1 || inventory.Containers[2][0] != (ownedItem{ID: 3, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}) { t.Fatalf("slot references lost their items: %+v", inventory) } if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), "Solar-Powered Pistol") || !strings.Contains(page.Body.String(), "Explorer (1)") || @@ -136,7 +136,7 @@ func TestControlItemCanBeUnassignedAndTransferredWithoutChangingID(t *testing.T) t.Fatalf("unassignment or transfer failed: %d %d", cleared.Code, transferred.Code) } if len(restarted.characters[1].inventory.Items) != 0 || len(restarted.characters[2].inventory.Items) != 1 || - restarted.characters[2].inventory.Items[0] != (ownedItem{1, 51018, 121567, 1, 93, 1}) || restarted.nextItem != 2 { + restarted.characters[2].inventory.Items[0] != (ownedItem{ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 93, Count: 1}) || restarted.nextItem != 2 { t.Fatal("transfer lost identity or reused a global ID") } } diff --git a/server/database_test.go b/server/database_test.go @@ -109,7 +109,7 @@ func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { npc.health, npc.position = 0, [3]float32{53, 14, 57} npc.roaming = &npcRoaming{home: [3]float32{52, 14, 56}, destination: [3]float32{54, 14, 58}, nextMove: now.Add(time.Second)} npc.corpse = &npcCorpse{looter: 1, credits: 87, expiresAt: now.Add(180 * time.Second), - items: []ownedItem{{17, 51018, 121567, 1, 0, 1}}} + items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} world.corpseExpiry = []*character{npc} world.npcRespawns = []npcRespawn{{npc, now.Add(100 * time.Second)}} response := postControlForm(world, "/control/time", url.Values{"hour": {"9"}, "minute": {"17"}}) @@ -161,7 +161,7 @@ func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) { npc := world.characters[1000000] npc.health = 0 npc.roaming = &npcRoaming{home: [3]float32{52, 14, 56}} - npc.corpse = &npcCorpse{expiresAt: now.Add(time.Second), items: []ownedItem{{17, 51018, 121567, 1, 0, 1}}} + npc.corpse = &npcCorpse{expiresAt: now.Add(time.Second), items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} world.corpseExpiry = []*character{npc} world.npcRespawns = []npcRespawn{{npc, now.Add(3 * time.Second)}} if err := world.flushWorld(); err != nil { diff --git a/server/equipment.go b/server/equipment.go @@ -24,7 +24,7 @@ func (item ownedItem) fitsEquipmentSlot(slot uint32) bool { if item.isKodaik() || item.isYalmaha() { return slot == 1 } - if item.isKineticAxe() { + if item.isKineticAxe() || item.isFlechettePistol() { return slot == 6 } if item.Type == 51022 && item.Template == 85685 && item.Quality == 200 { @@ -69,6 +69,11 @@ func (character *character) canEquip(item ownedItem) bool { if item.isKineticAxe() { return character.canWieldKineticAxe() } + if item.isFlechettePistol() { + stats := character.baseStats() + return stats.effectiveSkill(stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) > 5 && + stats.effectiveSkill(stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0}) > 5 + } if item.Template == 85685 { return character.baseStats().Abilities.Strength > 460 && character.baseStats().Abilities.Agility > 510 } @@ -116,12 +121,12 @@ func (character *character) canMoveEquipment(item ownedItem, destination uint32, return destination < 9 || destination > 14 || destination-9 < character.inventory.equipmentBonus(45) } -func (character *character) meleeWeapon() *gamedata.Item { +func (character *character) attackWeapon() *gamedata.Item { if character.npc && character.combatProfile != nil { return gamedata.ItemTemplates[character.combatProfile.Weapon] } for _, item := range character.inventory.Items { - if item.Slot == 6 && item.isKineticAxe() { + if item.Slot == 6 && (item.isKineticAxe() || item.isFlechettePistol()) { return gamedata.ItemTemplates[item.Template] } } @@ -279,7 +284,7 @@ func weaponUnequipPacket(owner uint32) []byte { func equippedWeaponPackets(character *character) [][]byte { for _, item := range character.inventory.Items { - if item.Slot != 6 || !item.isKineticAxe() { + if item.Slot != 6 || !item.isKineticAxe() && !item.isFlechettePistol() { continue } // kkr.dll sub_360B2440: version 11, parent, playfield, identity and page/slot bytes. @@ -289,9 +294,18 @@ func equippedWeaponPackets(character *character) [][]byte { } 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} { + count := uint32(3027) + if item.isFlechettePistol() { + count = 4036 + } + for _, value := range []uint32{count, 23, item.Template, 701, item.Quality} { body = binary.BigEndian.AppendUint32(body, value) } + if item.isFlechettePistol() { + body = binary.BigEndian.AppendUint32(body, 26) + body = binary.BigEndian.AppendUint32(body, item.Ammo) + } + body = binary.BigEndian.AppendUint32(body, 0) return [][]byte{n3Packet(0x3b1d2268, item.Type, item.ID, body)} } return nil diff --git a/server/equipment_test.go b/server/equipment_test.go @@ -61,8 +61,8 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) { world.advanceEquipment(world.clients[1].equipment.readyAt) unequipped := newTestInventoryServer(t) - if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 6, 1}}) || - !reflect.DeepEqual(unequipped.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64, 1}}) { + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}) || + !reflect.DeepEqual(unequipped.characters[1].inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}}) { t.Fatal("equipment move changed identity or did not survive restart") } if len(conn.packets) != 4 || len(observer.packets) != 3 { @@ -115,6 +115,34 @@ func TestEquipmentRequiresEachEffectiveSkillAtFive(t *testing.T) { } } +func TestEquipmentUnsupportedWearSlotRestoresInventoryItem(t *testing.T) { + world, conn := newEquipmentWorld(t) + inventory := world.characters[1].inventory + inventory.Items[0].Type, inventory.Items[0].Template = 51022, 85557 + if err := world.saveInventory_locked(world.characters[1], inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + request := inventoryMovePacket(1, 48, 18)[20:] + decodeInventory1491(request) + err = world.handleInventory(world.clients[1], request) + after, readErr := readTestItemStore(world) + restarted := newTestInventoryServer(t) + + if err != nil || readErr != nil || !bytes.Equal(before, after) || world.clients[1].equipment != nil || + !reflect.DeepEqual(world.characters[1].inventory.Items, restarted.characters[1].inventory.Items) { + t.Fatal("rejected equipment move changed the item", err, readErr) + } + if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x47537a24 || + binary.BigEndian.Uint32(conn.packets[0][33:37]) != 48 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 48 { + t.Fatalf("rejected wear slot left the native move pending: %x", conn.packets) + } +} + 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) { @@ -144,7 +172,7 @@ func TestEquipmentCompletionRechecksStateAndPreservesFailedSave(t *testing.T) { world.advanceEquipment(finish) - if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64, 1}}) { + if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}}) { t.Fatalf("interrupted equip changed inventory: %+v", world.characters[1].inventory) } }) diff --git a/server/flying_vehicle_test.go b/server/flying_vehicle_test.go @@ -49,7 +49,7 @@ func TestFlyingVehicleEquipRemovalAndRestart(t *testing.T) { world.advanceEquipment(client.equipment.readyAt) restored := newTestInventoryServer(t).characters[1] if !restored.flying() || restored.stats.Navigation.VehicleAir != 79 || restored.inventory.equipmentBonus(156) != 150 || - restored.inventory.Items[0] != (ownedItem{1, 51022, 117322, 30, 1, 1}) || len(equippedItemPackets(restored)) != 1 { + restored.inventory.Items[0] != (ownedItem{ID: 1, Type: 51022, Template: 117322, Quality: 30, Slot: 1, Count: 1}) || len(equippedItemPackets(restored)) != 1 { t.Fatal("worn Yalmaha, flight effects or trained skill did not survive restart") } world.characters[1000000].playfield, world.characters[1000000].position = 800, player.position @@ -67,7 +67,7 @@ func TestFlyingVehicleEquipRemovalAndRestart(t *testing.T) { restored = newTestInventoryServer(t).characters[1] if restored.flying() || restored.driving() || restored.inventory.equipmentBonus(156) != 0 || - restored.inventory.Items[0] != (ownedItem{1, 51022, 117322, 30, 64, 1}) || len(equippedItemPackets(restored)) != 0 { + restored.inventory.Items[0] != (ownedItem{ID: 1, Type: 51022, Template: 117322, Quality: 30, Slot: 64, Count: 1}) || len(equippedItemPackets(restored)) != 0 { t.Fatal("removing the Yalmaha lost its identity or retained its effects") } if len(observer.packets) != 2 || binary.BigEndian.Uint32(observer.packets[0][45:49]) != 6 || @@ -179,7 +179,7 @@ func TestFlyingVehicleSnapshotPreservesGroundMode(t *testing.T) { for _, running := range []bool{false, true} { t.Run(map[bool]string{false: "walking", true: "running"}[running], func(t *testing.T) { player := &character{id: 1, name: "Pilot", appearance: 0x515, level: 1, running: running, - inventory: playerInventory{Items: []ownedItem{{1, 51022, 117322, 30, 1, 1}}}} + inventory: playerInventory{Items: []ownedItem{{ID: 1, Type: 51022, Template: 117322, Quality: 30, Slot: 1, Count: 1}}}} packet := targetPacket(characterPacket(player)) start := bytes.Index(packet, []byte("Pilot\x00")) + len("Pilot") + 40 diff --git a/server/implants_test.go b/server/implants_test.go @@ -44,7 +44,7 @@ func TestImplantClinicEquipBonusesAndRestart(t *testing.T) { restarted := newTestInventoryServer(t) restored := restarted.characters[1] - if player.inventory.equipmentBonus(91) != 14 || player.inventory.equipmentBonus(90) != 6 || player.inventory.equipmentBonus(94) != 2 || player.meleeWeapon() == nil { + if player.inventory.equipmentBonus(91) != 14 || player.inventory.equipmentBonus(90) != 6 || player.inventory.equipmentBonus(94) != 2 || player.attackWeapon() == nil { t.Fatalf("independent equipment bonuses: %+v", player.inventory.Items) } if !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 5 || restored.inventory.equipmentBonus(91) != 14 || @@ -94,7 +94,7 @@ func TestImplantRequirementsAndNativeSlotConversion(t *testing.T) { case "wrong type": player.inventory.Items[4].Type = 51005 case "occupied": - player.inventory.Items = append(player.inventory.Items, ownedItem{6, 51022, 101173, 1, 37, 1}) + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 6, Type: 51022, Template: 101173, Quality: 1, Slot: 37, Count: 1}) } request := inventoryMovePacket(1, 52, destination)[20:] diff --git a/server/inventory.go b/server/inventory.go @@ -16,6 +16,7 @@ type ownedItem struct { Quality uint32 Slot uint32 Count uint16 + Ammo uint32 } type reclaimItem struct { @@ -49,7 +50,7 @@ func (inventory playerInventory) validate() error { slots := make(map[uint32]bool) bags := make(map[uint32]bool) for _, item := range inventory.Items { - if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Count == 0 || + if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Count == 0 || !item.validAmmo() || (item.Count != 1 && !item.isStackable()) || (item.Slot < 64 && !item.fitsEquipmentSlot(item.Slot)) || item.Slot >= 94 || slots[item.Slot] { @@ -67,7 +68,7 @@ func (inventory playerInventory) validate() error { } } for _, entry := range inventory.Reclaim { - if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Count == 0 || + if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Count == 0 || !entry.Item.validAmmo() || (entry.Item.Count != 1 && !entry.Item.isStackable()) || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { return fmt.Errorf("invalid reclaim item identity or slot") } @@ -83,7 +84,7 @@ func (inventory playerInventory) validate() error { var occupied [21]bool for _, item := range items { if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Type == 51017 || - item.Count == 0 || (item.Count != 1 && !item.isStackable()) || item.Slot >= 21 || occupied[item.Slot] { + item.Count == 0 || !item.validAmmo() || (item.Count != 1 && !item.isStackable()) || item.Slot >= 21 || occupied[item.Slot] { return fmt.Errorf("invalid backpack item identity or slot") } ids[item.ID], occupied[item.Slot] = true, true @@ -130,7 +131,7 @@ func (server *server) grantItem_locked(character *character, template uint32) (b inventory := character.inventory inventory.LastID = server.nextItem + 1 inventory.Items = slices.Clone(character.inventory.Items) - item := ownedItem{inventory.LastID, definition.HeaderWords[0], template, *definition.Quality, slot, 1} + item := ownedItem{ID: inventory.LastID, Type: definition.HeaderWords[0], Template: template, Quality: *definition.Quality, Slot: slot, Count: 1} if item.isStackable() { item.Count = uint16(itemStat(definition, 212)) } @@ -193,7 +194,7 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return nil } destination := binary.BigEndian.Uint32(body[32:36]) - if key == 0x47537a24 && (sourceSlot < 64 || destination == 1 || destination == 6 || destination == 7 || destination >= 9 && destination <= 14 || destination == 21 || destination == 30 || destination == 37) { + if key == 0x47537a24 && (sourceSlot < 64 || destination < 64) { if binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id { return nil } diff --git a/server/inventory_test.go b/server/inventory_test.go @@ -183,7 +183,7 @@ func TestInventoryRejectsForeignOccupiedAndStaleRequests(t *testing.T) { world, conn := newCombatWorld() world.characters[1].inventory = playerInventory{LastID: 2, Items: []ownedItem{ - {1, 51018, 121567, 1, 64, 1}, {2, 51018, 121567, 1, 65, 1}, + {ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1}, {ID: 2, Type: 51018, Template: 121567, Quality: 1, Slot: 65, Count: 1}, }} client := world.clients[1] packet := inventoryMovePacket(1, 64, 72) diff --git a/server/item_database.go b/server/item_database.go @@ -104,10 +104,10 @@ func (server *server) persistItems_locked(store itemStore) error { } for id, record := range store.Items { previous, exists := server.items[id] - if exists && previous.Type == record.Type && previous.Template == record.Template && previous.Quality == record.Quality && previous.Count == record.Count { + if exists && previous.Type == record.Type && previous.Template == record.Template && previous.Quality == record.Quality && previous.Count == record.Count && previous.Ammo == record.Ammo { continue } - if _, err := tx.Exec("INSERT INTO items (id, type, template, quality, count) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET type=excluded.type, template=excluded.template, quality=excluded.quality, count=excluded.count", id, record.Type, record.Template, record.Quality, record.Count); err != nil { + if _, err := tx.Exec("INSERT INTO items (id, type, template, quality, count, ammo) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET type=excluded.type, template=excluded.template, quality=excluded.quality, count=excluded.count, ammo=excluded.ammo", id, record.Type, record.Template, record.Quality, record.Count, record.Ammo); err != nil { return err } } @@ -169,14 +169,14 @@ func (server *server) readItems() (itemStore, error) { if err := db.QueryRow("SELECT last_item_id FROM world WHERE id=1").Scan(&store.LastID); err != nil { return store, err } - rows, err := db.Query("SELECT id, type, template, quality, count FROM items") + rows, err := db.Query("SELECT id, type, template, quality, count, ammo FROM items") if err != nil { return store, err } for rows.Next() { var id uint32 var record itemRecord - if err := rows.Scan(&id, &record.Type, &record.Template, &record.Quality, &record.Count); err != nil { + if err := rows.Scan(&id, &record.Type, &record.Template, &record.Quality, &record.Count, &record.Ammo); err != nil { rows.Close() return store, err } @@ -287,7 +287,7 @@ func (server *server) readItems() (itemStore, error) { return store, fmt.Errorf("item %d belongs to unknown corpse %d", id, corpse.Int64) } record := store.Items[id] - store.Corpses[npc.id] = append(store.Corpses[npc.id], ownedItem{id, record.Type, record.Template, record.Quality, slot, record.Count}) + store.Corpses[npc.id] = append(store.Corpses[npc.id], ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: slot, Count: record.Count, Ammo: record.Ammo}) } } return store, rows.Err() diff --git a/server/item_pages.go b/server/item_pages.go @@ -234,7 +234,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "</select></label> <button>Choose player</button></form>") if selectedName != "" { fmt.Fprintf(w, "<form method='post' action='control/items/%d'><input type='hidden' name='action' value='assign'><input type='hidden' name='owner' value='%d'><label>Free slot for %s <select name='destination' required>", id, owner, html.EscapeString(selectedName)) - item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count} + item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count, Ammo: record.Ammo} for _, destination := range controlItemSlots(selectedInventory, item) { label := equipmentSlots[destination.slot] if destination.bag != 0 { @@ -331,7 +331,7 @@ func (server *server) assignItem(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count} + item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count, Ammo: record.Ammo} if server.itemLocations_locked()[uint32(id)].label != "" || !slices.Contains(controlItemSlots(player.inventory, item), destination) { server.mutex.Unlock() http.Error(w, "Item is already assigned or destination is not a free compatible slot", http.StatusBadRequest) diff --git a/server/item_store.go b/server/item_store.go @@ -15,6 +15,7 @@ type itemRecord struct { Template uint32 `yaml:"template"` Quality uint32 `yaml:"quality"` Count uint16 `yaml:"count"` + Ammo uint32 `yaml:"ammo,omitempty"` Slots map[string]*uint32 `yaml:"slots,omitempty"` } @@ -69,7 +70,7 @@ func (inventory playerInventory) references() inventoryReferences { } func recordItem(item ownedItem, contents []ownedItem) itemRecord { - record := itemRecord{Type: item.Type, Template: item.Template, Quality: item.Quality, Count: item.Count} + record := itemRecord{Type: item.Type, Template: item.Template, Quality: item.Quality, Count: item.Count, Ammo: item.Ammo} if item.isSmallBackpack() { record.Slots = emptyItemSlots(21) for _, contained := range contents { @@ -94,7 +95,7 @@ func referencedItems(slots map[string]*uint32, first, count uint32, records map[ if !exists { return nil, fmt.Errorf("slot %s references unknown item %d", name, *id) } - items = append(items, ownedItem{*id, record.Type, record.Template, record.Quality, first + uint32(number) - 1, record.Count}) + items = append(items, ownedItem{ID: *id, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: first + uint32(number) - 1, Count: record.Count, Ammo: record.Ammo}) } // Native state keeps instance order stable while placement is addressed by slot. slices.SortFunc(items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) }) @@ -125,7 +126,7 @@ func (references inventoryReferences) inventory(records map[uint32]itemRecord, l if !exists { return inventory, fmt.Errorf("slot %s references unknown item %d", name, *id) } - inventory.Items = append(inventory.Items, ownedItem{*id, record.Type, record.Template, record.Quality, slot, record.Count}) + inventory.Items = append(inventory.Items, ownedItem{ID: *id, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: slot, Count: record.Count, Ammo: record.Ammo}) } } slices.SortFunc(inventory.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) }) @@ -138,7 +139,7 @@ func (references inventoryReferences) inventory(records map[uint32]itemRecord, l if !exists || slot < 64 { return inventory, fmt.Errorf("invalid reclaim slot %q", entry.Slot) } - inventory.Reclaim = append(inventory.Reclaim, reclaimItem{ownedItem{entry.ID, record.Type, record.Template, record.Quality, slot, record.Count}, entry.AvailableAt}) + inventory.Reclaim = append(inventory.Reclaim, reclaimItem{ownedItem{ID: entry.ID, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: slot, Count: record.Count, Ammo: record.Ammo}, entry.AvailableAt}) } for _, item := range append(slices.Clone(inventory.Items), reclaimItems(inventory.Reclaim)...) { if !item.isSmallBackpack() { @@ -235,7 +236,7 @@ func (server *server) writeItemStore_locked(store itemStore) error { contents := slices.Clone(items) for index, item := range contents { record := store.Items[item.ID] - contents[index] = ownedItem{item.ID, record.Type, record.Template, record.Quality, item.Slot, record.Count} + contents[index] = ownedItem{ID: item.ID, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: item.Slot, Count: record.Count, Ammo: record.Ammo} } server.characters[id].corpse.items = contents } @@ -292,8 +293,8 @@ func (store itemStore) validate() error { } } for id, record := range store.Items { - item := ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count} - if id == 0 || id > store.LastID || item.Count == 0 || item.Count != 1 && !item.isStackable() { + item := ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count, Ammo: record.Ammo} + if id == 0 || id > store.LastID || item.Count == 0 || !item.validAmmo() || item.Count != 1 && !item.isStackable() { return fmt.Errorf("invalid item instance %d", id) } if len(record.Slots) != 0 && !item.isSmallBackpack() { diff --git a/server/item_store_test.go b/server/item_store_test.go @@ -95,7 +95,7 @@ func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) { t.Fatalf("assignment status: %d %d %d %d: %s", occupied.Code, placed.Code, bag.Code, contained.Code, contained.Body.String()) } if len(restarted.characters[1].inventory.Items) != 3 || restarted.characters[1].inventory.Items[1].ID != 2 || restarted.characters[1].inventory.Items[1].Slot != 65 || - len(restarted.characters[1].inventory.Containers[3]) != 1 || restarted.characters[1].inventory.Containers[3][0] != (ownedItem{4, 51018, 121567, 1, 20, 1}) { + len(restarted.characters[1].inventory.Containers[3]) != 1 || restarted.characters[1].inventory.Containers[3][0] != (ownedItem{ID: 4, Type: 51018, Template: 121567, Quality: 1, Slot: 20, Count: 1}) { t.Fatal("item or backpack assignment did not survive restart") } } diff --git a/server/loot_test.go b/server/loot_test.go @@ -128,7 +128,7 @@ func TestLootFillsTheLastNativeInventorySlot(t *testing.T) { len(world.characters[1000000].corpse.items) != 0 { t.Fatalf("last-slot pickup failed: %v", err) } - if !slices.Contains(restarted.characters[1].inventory.Items, ownedItem{17, 51005, 42640, 1, 93, 1}) { + if !slices.Contains(restarted.characters[1].inventory.Items, ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 93, Count: 1}) { t.Fatalf("last-slot ownership changed: %+v", restarted.characters[1].inventory.Items) } } diff --git a/server/main.go b/server/main.go @@ -439,7 +439,9 @@ func (server *server) serveWorldClient(client *worldClient) error { } case 0x52526858: var err error - if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 51017) { + 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]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 51017) { err = server.handleOwnedItemUse(client, body) } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51005 || binary.BigEndian.Uint32(body[40:44]) == 51059) { err = server.handleTerminalUse(client, body) @@ -470,6 +472,10 @@ func (server *server) serveWorldClient(client *worldClient) error { if err := server.handleNanoCast(client, body); err != nil { return err } + case 106: + if err := server.handleReload(client, body); err != nil { + return err + } case 109, 110: if err := server.handleReclaim(client, body); err != nil { return err diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -80,7 +80,7 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error { server.sendCombatUpdates(updates) return nil } - if binary.BigEndian.Uint32(body[16:20]) != 19 || client.nanoCast != nil || !now.After(player.nanoRechargeUntil) { + if binary.BigEndian.Uint32(body[16:20]) != 19 || client.nanoCast != nil || now.Before(client.reloadUntil) || !now.After(player.nanoRechargeUntil) { server.mutex.Unlock() return nil } diff --git a/server/overequipping_test.go b/server/overequipping_test.go @@ -75,7 +75,7 @@ func TestOverequippingIncludesTrickleAndRecoversAfterRestart(t *testing.T) { func TestOverequippingAdjustedMinimumPrecedesArmor(t *testing.T) { world, _ := newArmorDamageWorld(t) attacker := &character{stats: defaultCharacterStats(), inventory: playerInventory{ - Items: []ownedItem{{1, 51018, 209283, 1, 6, 1}}, + Items: []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}, }} attacker.stats.Melee.OneHandEdged, attacker.stats.Body.Brawling = 398, 1 diff --git a/server/ranged.go b/server/ranged.go @@ -0,0 +1,161 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "slices" + "time" +) + +func (item ownedItem) isFlechettePistol() bool { + return item.Type == 51018 && item.Template == 123742 && item.Quality == 1 +} + +func (item ownedItem) validAmmo() bool { + if item.isFlechettePistol() { + return item.Ammo <= itemStat(gamedata.ItemTemplates[123742], 212) + } + return item.Ammo == 0 +} + +func (server *server) consumeBullet_locked(attacker *character) (bool, error) { + for index, item := range attacker.inventory.Items { + if item.Slot != 6 || !item.isFlechettePistol() { + continue + } + if item.Ammo == 0 { + return false, nil + } + // Persist the debit before a shot can damage the target or reach observers. + inventory := attacker.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[index].Ammo-- + if err := server.saveInventory_locked(attacker, inventory); err != nil { + return false, err + } + return true, nil + } + return true, nil +} + +func (server *server) handleReload(client *worldClient, body []byte) error { + if len(body) != 36 && len(body) != 56 { + return fmt.Errorf("invalid reload request length") + } + explicit := binary.BigEndian.Uint32(body) == 0x52526858 + if explicit { + if len(body) != 56 || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 5 || + binary.BigEndian.Uint32(body[28:32]) > 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || + binary.BigEndian.Uint32(body[36:40]) != client.id { + return nil + } + } else if len(body) != 36 || binary.BigEndian.Uint32(body) != 0x5e477770 || binary.BigEndian.Uint32(body[16:20]) != 106 || + binary.BigEndian.Uint64(body[20:28]) != 0 || binary.BigEndian.Uint64(body[28:36]) != 0 { + return nil + } + + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id { + server.mutex.Unlock() + return nil + } + var packets [][]byte + var acknowledgement []byte + if explicit { + sequence := binary.BigEndian.Uint32(body[20:24]) + if sequence <= client.useSequence { + server.mutex.Unlock() + return nil + } + client.useSequence = sequence + acknowledgement = append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(acknowledgement, 2) + } + + // A global request names no items; select the lowest compatible ordinary slot. + weapon := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == 6 && item.isFlechettePistol() }) + ammo := -1 + for index, item := range player.inventory.Items { + if item.Type == 51005 && item.Template == 21605 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && + (!explicit || binary.BigEndian.Uint32(body[40:44]) == 104 && binary.BigEndian.Uint32(body[44:48]) == item.Slot) && + (ammo < 0 || item.Slot < player.inventory.Items[ammo].Slot) { + ammo = index + } + } + now := time.Now() + accepted := weapon >= 0 && ammo >= 0 && client.equipment == nil && client.nanoCast == nil && + !now.Before(client.reloadUntil) && !player.driving() + if accepted && explicit { + targetType, targetID := binary.BigEndian.Uint32(body[48:52]), binary.BigEndian.Uint32(body[52:56]) + accepted = targetType == 101 && targetID == 6 || targetType == 51018 && targetID == player.inventory.Items[weapon].ID + } + if accepted && player.inventory.Items[weapon].Ammo < 20 { + source, gun := player.inventory.Items[ammo], player.inventory.Items[weapon] + loaded := min(uint32(source.Count), 20-gun.Ammo) + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[weapon].Ammo += loaded + inventory.Items[ammo].Count -= uint16(loaded) + if inventory.Items[ammo].Count == 0 { + inventory.Items = slices.Delete(inventory.Items, ammo, ammo+1) + } + + // Pause recharge, or restart an interrupted attack, as in native 100529a0. + candidate := *player + candidate.inventory = inventory + delay := time.Duration(itemStat(gamedata.ItemTemplates[123742], 210)) * 10 * time.Millisecond + readyAt := now.Add(delay) + if candidate.fighting != 0 && now.Before(candidate.rechargeUntil) { + candidate.rechargeUntil = candidate.rechargeUntil.Add(delay) + candidate.nextAttack = candidate.nextAttack.Add(delay) + } else { + if candidate.rechargeUntil.Before(readyAt) { + candidate.rechargeUntil = readyAt + } + if candidate.fighting != 0 { + attack, _ := candidate.attackDelays() + candidate.nextAttack = candidate.rechargeUntil.Add(attack) + } + } + + // Store both sides of the transfer and its deadline before publishing success. + store, err := server.itemStore_locked(player, inventory) + if err == nil { + store.edited = &candidate + err = server.writeItemStore_locked(store) + } + if err != nil { + server.mutex.Unlock() + return err + } + *player = candidate + client.reloadUntil = readyAt + if explicit { + binary.BigEndian.PutUint32(acknowledgement, 1) + } + remaining, remove := uint32(source.Count)-loaded, uint32(0) + if remaining == 0 { + remove = 1 + } + var response []byte + for _, value := range []uint32{104, source.Slot, gun.Type, gun.ID, remaining, gun.Ammo + loaded, remove} { + response = binary.BigEndian.AppendUint32(response, value) + } + packets = append(packets, n3Packet(0x26515e61, 50000, player.id, response)) + } + if explicit { + packets = append([][]byte{n3Packet(0x52526858, 50000, player.id, acknowledgement)}, packets...) + } + server.mutex.Unlock() + for _, packet := range packets { + if err := client.send(packet); err != nil { + return err + } + } + return nil +} diff --git a/server/ranged_test.go b/server/ranged_test.go @@ -0,0 +1,354 @@ +package main + +import ( + "bytes" + "encoding/binary" + "net/http" + "net/url" + "testing" + "time" +) + +func newRangedWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) + world, conn := newCombatWorld() + t.Cleanup(func() { world.db.Close() }) + player := world.characters[1] + player.name, player.level, player.appearance = "Pistol Owner", 1, 277 + player.rotation[3] = 1 + player.stats = defaultCharacterStats() + world.characters[1000000].position = [3]float32{20, 0, 0} + world.characters[1000000].health = 1000 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 2, Items: []ownedItem{ + {ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: 3}, + {ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: 100}, + }} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + return world, conn +} + +func TestRangedShotConsumesOneRoundAtItsDeadlineForBothObservers(t *testing.T) { + world, conn := newRangedWorld(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, npcs: map[uint32]bool{1000000: true}} + world.characters[1].stats.Speed.MeleeInitiative = 1200 + world.characters[1].stats.Melee.OneHandEdged = 800 + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + hit := world.characters[1].nextAttack + + world.advanceCombat(hit.Add(-time.Nanosecond)) + if world.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1000000].health != 1000 { + t.Fatal("shot preceded its deadline") + } + world.advanceCombat(hit) + world.advanceCombat(hit) + restarted := newTestInventoryServer(t) + + if world.characters[1000000].health < 988 || world.characters[1000000].health > 997 || world.characters[1].inventory.Items[0].Ammo != 2 || restarted.characters[1].inventory.Items[0].Ammo != 2 || restarted.characters[1].inventory.Items[1].Count != 100 { + t.Fatal("shot used wrong damage or ammunition", world.characters[1000000].health) + } + if world.characters[1].nextAttack.Sub(hit) != 3950*time.Millisecond { + t.Fatal("pistol used the wrong initiative clock", world.characters[1].nextAttack.Sub(hit)) + } + var first, second []byte + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 { + first = packet + } + } + for _, packet := range observer.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 { + second = packet + } + } + if first == nil || !bytes.Equal(first[16:], second[16:]) || binary.BigEndian.Uint32(first[33:37]) != 2 || binary.BigEndian.Uint32(first[37:41]) != 6 { + t.Fatalf("shot did not share its loaded count and slot: %x %x", first, second) + } +} + +func TestRangedEmptyMagazineCannotFireOrRefillAfterRestart(t *testing.T) { + world, _ := newRangedWorld(t) + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + + for range 4 { + world.advanceCombat(world.characters[1].nextAttack) + } + health := world.characters[1000000].health + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + world.advanceCombat(world.characters[1].nextAttack) + restarted := newTestInventoryServer(t) + + if world.characters[1].fighting != 0 || world.characters[1].inventory.Items[0].Ammo != 0 || restarted.characters[1].inventory.Items[0].Ammo != 0 || world.characters[1000000].health != health || restarted.characters[1].inventory.Items[1].Count != 100 { + t.Fatal("empty weapon dealt damage or created rounds") + } +} + +func TestRangedFailedShotSaveLeavesDamageAndAmmoUnchanged(t *testing.T) { + world, conn := newRangedWorld(t) + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + world.db.Exec("CREATE TRIGGER fail_ammo BEFORE UPDATE OF ammo ON items WHEN NEW.id = 1 BEGIN SELECT RAISE(FAIL, 'test save failure'); END") + hit := world.characters[1].nextAttack + conn.packets = nil + + world.advanceCombat(hit) + restarted := newTestInventoryServer(t) + + if world.characters[1000000].health != 1000 || world.characters[1].inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1].fighting != 0 { + t.Fatal("failed debit changed damage or ammunition") + } + if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x4a41203e { + t.Fatalf("failed debit published a shot: %x", conn.packets) + } +} + +func TestReloadTransfersRoundsAtomicallyAndRestoresItsDeadline(t *testing.T) { + world, conn := newRangedWorld(t) + request := characterActionPacket(1, [5]uint32{106})[20:] + before := time.Now() + + err := world.handleReload(world.clients[1], request) + world.handleReload(world.clients[1], request) + restarted := newTestInventoryServer(t) + + if err != nil || world.characters[1].inventory.Items[0].Ammo != 20 || world.characters[1].inventory.Items[1].Count != 83 || restarted.characters[1].inventory.Items[0].Ammo != 20 || restarted.characters[1].inventory.Items[1].Count != 83 { + t.Fatal("reload failed or changed the total rounds", err) + } + if restarted.characters[1].rechargeUntil.Before(before.Add(1250*time.Millisecond)) || restarted.characters[1].rechargeUntil.After(time.Now().Add(1250*time.Millisecond)) { + t.Fatal("reload deadline did not survive restart") + } + if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x26515e61 || !bytes.Equal(conn.packets[0][29:57], []byte{0, 0, 0, 104, 0, 0, 0, 48, 0, 0, 0xc7, 0x4a, 0, 0, 0, 1, 0, 0, 0, 83, 0, 0, 0, 20, 0, 0, 0, 0}) { + t.Fatalf("reload wire fields: %x", conn.packets) + } +} + +func TestReloadPausesRemainingRechargeBeforeAnotherAttack(t *testing.T) { + world, _ := newRangedWorld(t) + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + world.advanceCombat(world.characters[1].nextAttack) + next, recharge := world.characters[1].nextAttack, world.characters[1].rechargeUntil + health := world.characters[1000000].health + + err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + world.advanceCombat(next) + world.advanceCombat(next.Add(1250*time.Millisecond - time.Nanosecond)) + + if err != nil || world.characters[1].nextAttack != next.Add(1250*time.Millisecond) || world.characters[1].rechargeUntil != recharge.Add(1250*time.Millisecond) || world.characters[1000000].health != health { + t.Fatal("reload shortened the active weapon cycle", err) + } +} + +func TestReloadUsesOnlyAvailableRoundsAndRemovesAnEmptyStack(t *testing.T) { + world, conn := newRangedWorld(t) + world.characters[1].inventory.Items[1].Count = 5 + if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil { + t.Fatal(err) + } + + err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + restarted := newTestInventoryServer(t) + + if err != nil || len(restarted.characters[1].inventory.Items) != 1 || restarted.characters[1].inventory.Items[0].Ammo != 8 || len(restarted.items) != 1 { + t.Fatal("partial reload lost or created ammunition", err) + } + if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 0 || binary.BigEndian.Uint32(conn.packets[0][49:53]) != 8 || binary.BigEndian.Uint32(conn.packets[0][53:57]) != 1 { + t.Fatalf("empty-stack reply: %x", conn.packets) + } +} + +func explicitReloadRequest(sequence, source, weapon uint32) []byte { + var body []byte + for _, value := range []uint32{0, sequence, 5, 0, 50000, 1, 104, source, 51018, weapon} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x52526858, 50000, 1, body)[20:] +} + +func TestReloadExplicitAmmoUseAcknowledgesOnceAndTranslatesItsSlot(t *testing.T) { + world, conn := newRangedWorld(t) + request := explicitReloadRequest(1, 48, 1) + decodeInventory1491(request) + + err := world.handleReload(world.clients[1], request) + world.handleReload(world.clients[1], request) + + if err != nil || world.characters[1].inventory.Items[0].Ammo != 20 || world.characters[1].inventory.Items[1].Count != 83 || len(conn.packets) != 2 { + t.Fatal("explicit reload repeated or failed", err) + } + if binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x52526858 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 || binary.BigEndian.Uint32(conn.packets[0][57:61]) != 48 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x26515e61 { + t.Fatalf("explicit reload acknowledgement: %x", conn.packets) + } +} + +func TestReloadAcceptsNativeEquippedWeaponSlot(t *testing.T) { + world, conn := newRangedWorld(t) + request := explicitReloadRequest(1, 48, 6) + binary.BigEndian.PutUint32(request[48:52], 101) + decodeInventory1491(request) + + err := world.handleReload(world.clients[1], request) + restarted := newTestInventoryServer(t) + + if err != nil || restarted.characters[1].inventory.Items[0].Ammo != 20 || restarted.characters[1].inventory.Items[1].Count != 83 || len(conn.packets) != 2 { + t.Fatal("native wear-slot reload did not conserve rounds", err) + } + if binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 || binary.BigEndian.Uint32(conn.packets[1][37:41]) != 51018 || binary.BigEndian.Uint32(conn.packets[1][41:45]) != 1 { + t.Fatalf("reload did not resolve the owned weapon instance: %x", conn.packets) + } +} + +func TestReloadRestartsAnInterruptedAttackAfterItsDelay(t *testing.T) { + world, _ := newRangedWorld(t) + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + attack, _ := world.characters[1].attackDelays() + health := world.characters[1000000].health + + err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + ready := world.clients[1].reloadUntil + world.advanceCombat(ready.Add(attack - time.Nanosecond)) + before := world.characters[1000000].health + world.advanceCombat(ready.Add(attack)) + + if err != nil || before != health || world.characters[1000000].health >= health || world.characters[1].inventory.Items[0].Ammo != 19 { + t.Fatal("interrupted attack did not restart after reload", err) + } +} + +func TestReloadRejectsInvalidRequestsWithoutChangingRounds(t *testing.T) { + for _, scenario := range []string{"foreign owner", "foreign actor", "foreign weapon", "wrong ammo page", "wrong ammo slot", "missing ammo", "unsupported weapon", "full", "dead", "loading", "not ready", "stale", "equipment", "nano", "reloading"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newRangedWorld(t) + player, client := world.characters[1], world.clients[1] + request := explicitReloadRequest(1, 64, 1) + expected := uint32(3) + switch scenario { + case "foreign owner": + binary.BigEndian.PutUint32(request[8:12], 2) + case "foreign actor": + binary.BigEndian.PutUint32(request[36:40], 2) + case "foreign weapon": + binary.BigEndian.PutUint32(request[52:56], 2) + case "wrong ammo page": + binary.BigEndian.PutUint32(request[40:44], 107) + case "wrong ammo slot": + binary.BigEndian.PutUint32(request[44:48], 65) + case "missing ammo": + player.inventory.Items[1].Template = 85366 + case "unsupported weapon": + player.inventory.Items[0].Template = 209283 + player.inventory.Items[0].Ammo = 0 + expected = 0 + case "full": + player.inventory.Items[0].Ammo = 20 + expected = 20 + case "dead": + player.health = 0 + case "loading": + client.loading = true + case "not ready": + client.ready = false + case "stale": + world.clients[1] = &worldClient{} + case "equipment": + client.equipment = &equipmentMove{} + case "nano": + client.nanoCast = &nanoCast{} + case "reloading": + client.reloadUntil = time.Now().Add(time.Second) + } + + err := world.handleReload(client, request) + + if err != nil || player.inventory.Items[0].Ammo != expected || player.inventory.Items[1].Count != 100 { + t.Fatal("invalid reload changed ammunition", err) + } + }) + } +} + +func TestReloadFailedTransactionKeepsBothSidesAndDeadline(t *testing.T) { + world, conn := newRangedWorld(t) + if _, err := world.db.Exec("CREATE TRIGGER fail_ammo BEFORE UPDATE OF ammo ON items WHEN NEW.id = 1 BEGIN SELECT RAISE(FAIL, 'test save failure'); END"); err != nil { + t.Fatal(err) + } + + err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + restarted := newTestInventoryServer(t) + + if err == nil || len(conn.packets) != 0 || world.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1].inventory.Items[1].Count != 100 || !world.characters[1].rechargeUntil.IsZero() || !world.clients[1].reloadUntil.IsZero() { + t.Fatal("failed reload published or modified live state") + } + if restarted.characters[1].inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[1].Count != 100 || !restarted.characters[1].rechargeUntil.IsZero() { + t.Fatal("failed transfer persisted partially") + } +} + +func TestPistolEquipmentUsesItsRequirementsAndPreservesLoadedRounds(t *testing.T) { + world, _ := newRangedWorld(t) + player, client := world.characters[1], world.clients[1] + + err := world.handleInventory(client, itemMovePacket(1, 6, 111)[20:]) + world.advanceEquipment(client.equipment.readyAt) + if err != nil || player.inventory.Items[0].Slot != 65 { + t.Fatal("pistol did not leave the equipped slot", err) + } + player.stats.Abilities.Agility, player.stats.Abilities.Sense = 1, 1 + player.stats.Ranged.Pistol = 5 + player.stats.Ranged.FlingShot = 6 + world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:]) + if client.equipment != nil { + t.Fatal("pistol equipped below its requirement") + } + player.stats.Ranged.Pistol = 6 + world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:]) + if client.equipment == nil { + t.Fatal("qualifying pistol request was rejected") + } + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t) + + if player.inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[0].Slot != 6 { + t.Fatal("equip or restart changed loaded rounds") + } + packet := targetPacket(equippedWeaponPackets(player)[0]) + if binary.BigEndian.Uint32(packet[55:59]) != 4036 || binary.BigEndian.Uint32(packet[75:79]) != 26 || binary.BigEndian.Uint32(packet[79:83]) != 3 { + t.Fatalf("weapon instance did not initialize its magazine: %x", packet) + } +} + +func TestPistolControlAssignmentPreservesLoadedRounds(t *testing.T) { + world, _ := newRangedWorld(t) + world.baseURL = "/" + created := postControlForm(world, "/control/items", url.Values{"template": {"123742"}}) + if created.Code != http.StatusSeeOther { + t.Fatal("could not create pistol", created.Code) + } + data := "type: 51018\ntemplate: 123742\nquality: 1\ncount: 1\nammo: 9\n" + + edited := postControlForm(world, "/control/items/3", url.Values{"data": {data}}) + assigned := postControlForm(world, "/control/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}}) + restarted := newTestInventoryServer(t) + + if edited.Code != http.StatusSeeOther || assigned.Code != http.StatusSeeOther || restarted.items[3].Ammo != 9 || len(restarted.characters[1].inventory.Items) != 3 || restarted.characters[1].inventory.Items[2].Ammo != 9 { + t.Fatal("control assignment lost loaded rounds", edited.Code, assigned.Code) + } +} + +func TestPistolControlRejectsAmmoAboveCapacity(t *testing.T) { + world, _ := newRangedWorld(t) + world.baseURL = "/" + data := "type: 51018\ntemplate: 123742\nquality: 1\ncount: 1\nammo: 21\n" + + response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + restarted := newTestInventoryServer(t) + + if response.Code != http.StatusBadRequest || world.characters[1].inventory.Items[0].Ammo != 3 || restarted.items[1].Ammo != 3 { + t.Fatal("invalid loaded count replaced the item", response.Code) + } +} diff --git a/server/reclaim_test.go b/server/reclaim_test.go @@ -37,7 +37,7 @@ func newReclaimWorld(t *testing.T) (*server, *combatTestConn) { t.Fatal(err) } player.inventory = playerInventory{LastID: 3, Items: []ownedItem{ - {1, 51018, 209283, 1, 6, 1}, {2, 51018, 121567, 1, 64, 1}, {3, 51005, 42640, 1, 65, 1}, + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}, {ID: 2, Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1}, {ID: 3, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, }} world.nextItem = 3 if err := world.saveInventory_locked(player, player.inventory); err != nil { @@ -139,7 +139,7 @@ func TestReclaimPendingThenPrivatePickupPersistsOnce(t *testing.T) { if binary.BigEndian.Uint32(moved[16:20]) != 0x47537a24 || binary.BigEndian.Uint32(moved[29:33]) != 106 || binary.BigEndian.Uint32(moved[45:49]) != 49 { t.Fatalf("incorrect native pickup: %x", moved) } - expected := ownedItem{3, 51005, 42640, 1, 65, 1} + expected := ownedItem{ID: 3, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1} if len(player.inventory.Items) != 3 || player.inventory.Items[2] != expected || len(player.inventory.Reclaim) != 0 || len(conn.packets) != count || !reflect.DeepEqual(player.inventory.Items, restarted.characters[1].inventory.Items) || len(restarted.characters[1].inventory.Reclaim) != 0 || restarted.characters[1].inventory.LastID != player.inventory.LastID { @@ -152,7 +152,7 @@ func TestReclaimRejectsInvalidOpenAndPickup(t *testing.T) { t.Run(scenario, func(t *testing.T) { world, conn := newReclaimWorld(t) player, client := world.characters[1], world.clients[1] - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Second)}} player.inventory.LastID = 4 world.handleReclaim(client, reclaimRequest(109)) request := reclaimTakeRequest(0) @@ -209,7 +209,7 @@ func TestReclaimFullInventoryAndFailedPickupSaveRetainSource(t *testing.T) { t.Run(scenario, func(t *testing.T) { world, conn := newReclaimWorld(t) player, client := world.characters[1], world.clients[1] - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Second)}} player.inventory.LastID = 4 world.nextItem = 4 if scenario == "full" { @@ -237,8 +237,8 @@ func TestReclaimConcurrentPickupKeepsOtherWindowSlotsStable(t *testing.T) { player, client := world.characters[1], world.clients[1] player.inventory.LastID = 5 player.inventory.Reclaim = []reclaimItem{ - {ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}, - {ownedItem{5, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}, + {ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Second)}, + {ownedItem{ID: 5, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Second)}, } world.handleReclaim(client, reclaimRequest(109)) var group sync.WaitGroup @@ -267,7 +267,7 @@ func TestReclaimSurvivesOtherInventoryTransactions(t *testing.T) { world, _ := newReclaimWorld(t) player, client := world.characters[1], world.clients[1] player.inventory.LastID = 4 - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(time.Minute).UTC()}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(time.Minute).UTC()}} world.nextItem = 4 expected := slices.Clone(player.inventory.Reclaim) @@ -315,7 +315,7 @@ func TestReclaimLargePoolRemainsAvailableAcrossWindows(t *testing.T) { player, client := world.characters[1], world.clients[1] player.inventory.LastID = 104 for id := uint32(4); id <= 104; id++ { - player.inventory.Reclaim = append(player.inventory.Reclaim, reclaimItem{ownedItem{id, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}) + player.inventory.Reclaim = append(player.inventory.Reclaim, reclaimItem{ownedItem{ID: id, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Second)}) } world.handleReclaim(client, reclaimRequest(109)) @@ -334,7 +334,7 @@ func TestReclaimLargePoolRemainsAvailableAcrossWindows(t *testing.T) { func TestReclaimPreventsInsuranceUntilEmptied(t *testing.T) { world, conn := newReclaimWorld(t) player := world.characters[1] - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Second)}} err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:]) @@ -351,7 +351,7 @@ func TestReclaimNativeWireRoundTripAndRestart(t *testing.T) { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - player.inventory = playerInventory{LastID: 17, Reclaim: []reclaimItem{{ownedItem{17, 51005, 42640, 1, 64, 1}, time.Now().Add(-time.Second).UTC()}}} + player.inventory = playerInventory{LastID: 17, Reclaim: []reclaimItem{{ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}, time.Now().Add(-time.Second).UTC()}}} if err := world.saveInventory_locked(player, player.inventory); err != nil { t.Fatal(err) } @@ -389,7 +389,7 @@ func TestReclaimNativeWireRoundTripAndRestart(t *testing.T) { binary.BigEndian.Uint32(closed[29:33]) != 110 { t.Fatalf("incorrect native reclaim round trip: %x %x %x %x", acknowledged, contents, moved, closed) } - if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{17, 51005, 42640, 1, 64, 1}}) || len(restarted.characters[1].inventory.Reclaim) != 0 { + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}}) || len(restarted.characters[1].inventory.Reclaim) != 0 { t.Fatal("native pickup did not persist its sole owner") } } @@ -400,7 +400,7 @@ func TestReclaimSaveRejectsDuplicateAndInvalidIdentities(t *testing.T) { world, _ := newReclaimWorld(t) player := world.characters[1] player.inventory.LastID = 4 - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().UTC()}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().UTC()}} switch scenario { case "owned duplicate": player.inventory.Reclaim[0].Item.ID = 3 diff --git a/server/stacks.go b/server/stacks.go @@ -8,7 +8,7 @@ import ( ) func (item ownedItem) isStackable() bool { - return item.Type == 51005 && (item.Template == 152030 && item.Quality == 42 || (item.Template == 85366 || item.Template == 25812) && item.Quality == 1) + return item.Type == 51005 && (item.Template == 152030 && item.Quality == 42 || (item.Template == 85366 || item.Template == 25812 || item.Template == 21605) && item.Quality == 1) } func (server *server) changeStack_locked(client *worldClient, index int, body []byte) error { diff --git a/server/stacks_test.go b/server/stacks_test.go @@ -49,7 +49,7 @@ func TestStackJoinSplitRepeatAndRestartPreserveQuantities(t *testing.T) { if err := world.handleInventory(world.clients[1], stackActionPacket(1, 53, 65, 64)[20:]); err != nil { t.Fatal(err) } - if !reflect.DeepEqual(player.inventory.Items, []ownedItem{{2, 51005, 152030, 42, 65, 6}}) { + if !reflect.DeepEqual(player.inventory.Items, []ownedItem{{ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 6}}) { t.Fatalf("join did not retain the first identity: %+v", player.inventory) } request := stackActionPacket(1, 52, 65, 2)[20:] @@ -58,7 +58,7 @@ func TestStackJoinSplitRepeatAndRestartPreserveQuantities(t *testing.T) { restarted := newTestInventoryServer(t).characters[1] packet := targetPacket(fullCharacterPacket(restarted)) - expected := []ownedItem{{2, 51005, 152030, 42, 65, 2}, {3, 51005, 152030, 42, 64, 4}} + expected := []ownedItem{{ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 2}, {ID: 3, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 4}} if !reflect.DeepEqual(player.inventory.Items, expected) || !reflect.DeepEqual(restarted.inventory.Items, expected) || restarted.inventory.LastID != 3 || player.inventory.LastID != 3 || world.nextItem != 3 || len(conn.packets) != 2 { t.Fatalf("split lost quantities or repeated allocation: %+v restart %+v packets %d", player.inventory, restarted.inventory, len(conn.packets)) @@ -117,7 +117,7 @@ func TestStackNativeWireDoesNotTranslateRetainedCountAsASlot(t *testing.T) { binary.BigEndian.Uint32(join[29:33]) != 53 || binary.BigEndian.Uint32(join[37:41]) != 48 || binary.BigEndian.Uint32(join[45:49]) != 50 { t.Fatalf("native split count or join slots were mistranslated: %x %x", split, join) } - expected := []ownedItem{{1, 51005, 152030, 42, 64, 100}, {2, 51005, 152030, 42, 65, 3}} + expected := []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 100}, {ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 3}} if !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory.Items, expected) { t.Fatal("native round trip changed the combined quantity") } @@ -147,7 +147,7 @@ func TestStackRejectsInvalidQuantitiesAndOwnership(t *testing.T) { player.inventory.Items[1].Quality, player.inventory.Items[1].Count = 41, 1 case "other item": request = stackActionPacket(1, 53, 64, 65)[20:] - player.inventory.Items[1] = ownedItem{2, 51018, 121567, 1, 65, 1} + player.inventory.Items[1] = ownedItem{ID: 2, Type: 51018, Template: 121567, Quality: 1, Slot: 65, Count: 1} case "foreign owner": request = stackActionPacket(2, 52, 64, 1)[20:] case "foreign source page": @@ -185,8 +185,8 @@ func TestStackJoinPreventsUnsignedShortOverflow(t *testing.T) { second uint16 expected []ownedItem }{ - {25535, []ownedItem{{1, 51005, 152030, 42, 64, 65535}}}, - {25536, []ownedItem{{1, 51005, 152030, 42, 64, 40000}, {2, 51005, 152030, 42, 65, 25536}}}, + {25535, []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 65535}}}, + {25536, []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 40000}, {ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 25536}}}, } { world, _ := newStackWorld(t) player := world.characters[1] @@ -238,8 +238,8 @@ func TestStackConcurrentRepeatDoesNotDuplicateQuantity(t *testing.T) { action, argument uint32 expected []ownedItem }{ - {52, 1, []ownedItem{{1, 51005, 152030, 42, 64, 1}, {2, 51005, 152030, 42, 65, 3}, {3, 51005, 152030, 42, 66, 2}}}, - {53, 65, []ownedItem{{1, 51005, 152030, 42, 64, 6}}}, + {52, 1, []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 1}, {ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 3}, {ID: 3, Type: 51005, Template: 152030, Quality: 42, Slot: 66, Count: 2}}}, + {53, 65, []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 6}}}, } { world, conn := newStackWorld(t) request := stackActionPacket(1, scenario.action, 64, scenario.argument)[20:] @@ -302,8 +302,8 @@ func TestStackRejectedSplitRebuildsOnlySupportedStacks(t *testing.T) { } func TestStackCountsSurviveCorpseAndReclaimEncoding(t *testing.T) { - corpse := &character{id: 1000000, corpse: &npcCorpse{items: []ownedItem{{1, 51005, 152030, 42, 0, 9}}}} - player := &character{id: 1, inventory: playerInventory{Reclaim: []reclaimItem{{Item: ownedItem{2, 51005, 152030, 42, 64, 7}}}}} + corpse := &character{id: 1000000, corpse: &npcCorpse{items: []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 0, Count: 9}}}} + player := &character{id: 1, inventory: playerInventory{Reclaim: []reclaimItem{{Item: ownedItem{ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 7}}}}} loot := targetPacket(lootInventoryPacket(1, corpse, true)) reclaim := targetPacket(reclaimInventoryPacket(player, []uint32{2})) diff --git a/server/state.go b/server/state.go @@ -73,6 +73,7 @@ type worldClient struct { dialogue *npcDialogue equipment *equipmentMove nanoCast *nanoCast + reloadUntil time.Time lootCorpse uint32 reclaimItems []uint32 backpacks map[uint32]backpackHandle diff --git a/server/target_protocol.go b/server/target_protocol.go @@ -119,9 +119,13 @@ func targetPacket(packet []byte) []byte { binary.BigEndian.PutUint32(packet[60:64], binary.BigEndian.Uint32(packet[60:64])-16) } case 0x52526858: - if len(packet) == 68 && binary.BigEndian.Uint32(packet[60:64]) == 104 { + if (len(packet) == 68 || len(packet) == 76) && binary.BigEndian.Uint32(packet[60:64]) == 104 { binary.BigEndian.PutUint32(packet[64:68], binary.BigEndian.Uint32(packet[64:68])-16) } + case 0x26515e61: + if binary.BigEndian.Uint32(packet[36:40]) == 104 { + binary.BigEndian.PutUint32(packet[40:44], binary.BigEndian.Uint32(packet[40:44])-16) + } case 0x5e477770: action := binary.BigEndian.Uint32(packet[36:40]) if (action == 52 || action == 53 || action == 112) && binary.BigEndian.Uint32(packet[40:44]) == 104 { @@ -153,7 +157,7 @@ func targetPacket(packet []byte) []byte { } func decodeInventory1491(body []byte) { - if len(body) == 48 && binary.BigEndian.Uint32(body) == 0x52526858 && binary.BigEndian.Uint32(body[40:44]) == 104 { + if (len(body) == 48 || len(body) == 56) && binary.BigEndian.Uint32(body) == 0x52526858 && binary.BigEndian.Uint32(body[40:44]) == 104 { binary.BigEndian.PutUint32(body[44:48], decodeInventorySlot1491(binary.BigEndian.Uint32(body[44:48]))) return } @@ -166,7 +170,7 @@ func decodeInventory1491(body []byte) { binary.BigEndian.PutUint32(body[20:24], decodeInventorySlot1491(binary.BigEndian.Uint32(body[20:24]))) } destination := binary.BigEndian.Uint32(body[32:36]) - if binary.BigEndian.Uint32(body[24:28]) == 50000 && destination != 1 && destination != 6 && destination != 7 && !(destination >= 9 && destination <= 14) && destination != 21 && destination != 30 && destination != 37 && destination != 111 { + if binary.BigEndian.Uint32(body[24:28]) == 50000 && destination >= 48 && destination != 111 { binary.BigEndian.PutUint32(body[32:36], decodeInventorySlot1491(destination)) } case 0x5e477770: @@ -182,7 +186,8 @@ func decodeInventory1491(body []byte) { func decodeInventorySlot1491(slot uint32) uint32 { if slot < 48 || slot >= 78 { - return 0 + // Keep malformed inventory slots outside both inventory and equipment. + return 94 } return slot + 16 } diff --git a/server/vehicle_test.go b/server/vehicle_test.go @@ -175,7 +175,7 @@ func TestGroundVehicleRemovalRestoresEffectsAndAllowsCombat(t *testing.T) { t.Fatal(err) } - if restored.inventory.Items[0] != (ownedItem{1, 51022, 117294, 15, 64, 1}) || restored.inventory.equipmentBonus(156) != 0 || + if restored.inventory.Items[0] != (ownedItem{ID: 1, Type: 51022, Template: 117294, Quality: 15, Slot: 64, Count: 1}) || restored.inventory.equipmentBonus(156) != 0 || restored.physicalExtent() != 2 || len(equippedItemPackets(restored)) != 0 || player.fighting != 1000000 { t.Fatal("removal lost identity or failed to restore speed, scale and fighting") } @@ -258,7 +258,7 @@ func TestGroundVehicleRemovalFromFullInventoryKeepsTheVehicle(t *testing.T) { player.inventory.Items[0].Slot = 1 player.inventory.LastID = 93 for slot := uint32(64); slot < 94; slot++ { - player.inventory.Items = append(player.inventory.Items, ownedItem{slot, 51018, 121567, 1, slot, 1}) + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: slot, Type: 51018, Template: 121567, Quality: 1, Slot: slot, Count: 1}) } if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil { diff --git a/server/world.go b/server/world.go @@ -175,7 +175,7 @@ func fullCharacterPacket(character *character) []byte { body = binary.BigEndian.AppendUint32(body, uint32(len(character.inventory.Items)+1)*1009) for _, item := range character.inventory.Items { flags := uint32(1) - if item.isSmallBackpack() || item.isKineticAxe() && item.Slot == 6 { + if item.isSmallBackpack() || (item.isKineticAxe() || item.isFlechettePistol()) && item.Slot == 6 { flags = 2 } for _, value := range []uint32{item.Slot, flags<<16 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { diff --git a/server/world.sql b/server/world.sql @@ -163,7 +163,8 @@ CREATE TABLE IF NOT EXISTS items ( type INTEGER NOT NULL, template INTEGER NOT NULL, quality INTEGER NOT NULL, - count INTEGER NOT NULL CHECK (count BETWEEN 1 AND 65535) + count INTEGER NOT NULL CHECK (count BETWEEN 1 AND 65535), + ammo INTEGER NOT NULL DEFAULT 0 CHECK (ammo BETWEEN 0 AND 4294967295) ); CREATE TABLE IF NOT EXISTS item_locations ( item_id INTEGER PRIMARY KEY REFERENCES items(id),