ModernUO/Projects/UOContent/Items/Weapons/Ranged/BaseRanged.cs
Kamron Batman a7bb8a8222
refactor(archery): centralize SE ammo auto-recovery off PlayerMobile (#2496)
## Summary

Streamlines the SE-era archery ammo auto-recovery (recovering spent arrows/bolts after a miss). The mechanic was previously spread across four unrelated trigger points and a weapon-scoped timer that was divorced from the recovery state living on `PlayerMobile`. It also contained dead code.

### Problems fixed
- **Dead `!Warmode` gate** — `OnMiss` only runs from `OnSwing`, which requires warmode to fire, so the `if (!pm.Warmode)` branch that started the recovery timer could never trigger.
- **Scattered, divorced state** — banked ammo lived on `PlayerMobile.RecoverableAmmo` while the timer lived on the weapon (`_recoveryTimerToken`), and recovery was kicked off from four different places (`OnWarmodeChanged`, `PlayerMobile.OnDamage` kill, `BaseCreature.OnDamage` kill, `OnBeforeDeath`).
- **Per-player footprint** — every `PlayerMobile` carried a `RecoverableAmmo` field even though ~99% never miss with a bow (and most are offline).

### New design — `AmmoRecovery` side table
- All state (banked ammo + one repeating timer) is keyed by player in a static dictionary, so only players who actually miss carry any state. Transient by design — this was never serialized.
- **One feed point:** `OnMiss` banks the spent ammo type and starts the player's timer.
- **One drain point:** the timer self-gates and gathers ammo into the backpack only once the archer has disengaged — **alive, out of warmode, and not running** — otherwise it retries next tick, so banked ammo is never lost while online.
- **"Not running" allows standing still _or_ walking.** The `Direction.Running` bit is stale after a player stops, so it's paired with movement recency (`LastMoveTime`); only an *actively* running archer is blocked.
- Removed the redundant scattered triggers, the dead `!Warmode` branch, `RecoverableAmmo`, `RecoverAmmo()`, and the now-empty `OnWarmodeChanged` override. `PlayerMobile.OnDelete` calls `AmmoRecovery.Forget`.

### Behavior notes
- On death, banked ammo is **no longer flushed to the corpse** — it stays banked and is recovered after resurrection once the archer settles (player keeps it rather than dropping it to looters).
- `OnHit` immediate recovery (the ~40% arrow-to-defender behavior) is **unchanged**.

## Test plan
- [x] `dotnet build Projects/UOContent/UOContent.csproj -c Release` — succeeds, 0 warnings, 0 errors.
- [ ] In-game (SE era): miss bow shots, then disengage (drop warmode + stop) and confirm the "You recover N arrows/bolts" message and backpack contents; confirm recovery does **not** fire while running and **does** while walking/standing.
2026-06-21 23:22:55 -07:00

297 lines
10 KiB
C#

using System;
using ModernUO.Serialization;
using Server.Mobiles;
using Server.Network;
using Server.Spells;
using Server.Engines.Craft;
namespace Server.Items
{
[SerializationGenerator(0, false)]
public abstract partial class BaseRanged : BaseMeleeWeapon
{
[SerializableField(0)]
[InvalidateProperties]
[SerializedCommandProperty(AccessLevel.GameMaster)]
private bool _balanced;
[SerializableField(1)]
[InvalidateProperties]
[SerializedCommandProperty(AccessLevel.GameMaster)]
private int _velocity;
public BaseRanged(int itemID) : base(itemID)
{
}
public abstract int EffectID { get; }
public abstract Type AmmoType { get; }
public abstract Item Ammo { get; }
public override int DefHitSound => 0x234;
public override int DefMissSound => 0x238;
public override SkillName DefSkill => SkillName.Archery;
public override WeaponType DefType => WeaponType.Ranged;
public override WeaponAnimation DefAnimation => WeaponAnimation.ShootXBow;
public override SkillName AccuracySkill => SkillName.Archery;
public override TimeSpan OnSwing(Mobile attacker, Mobile defender, double damageBonus = 1.0)
{
// WeaponAbility a = WeaponAbility.GetCurrentAbility( attacker );
// Make sure we've been standing still for .25/.5/1 second depending on Era
if (Core.TickCount - attacker.LastMoveTime >= (Core.SE ? 250 : Core.AOS ? 500 : 1000) ||
Core.AOS && WeaponAbility.GetCurrentAbility(attacker) is MovingShot)
{
var canSwing = true;
if (Core.AOS)
{
canSwing = !attacker.Paralyzed && !attacker.Frozen;
if (canSwing)
{
// On OSI you can swing + hold a cast at the same time
canSwing = attacker.Spell is not Spell { IsCasting: true, BlocksMovement: true };
}
}
if ((attacker as PlayerMobile)?.DuelContext?.CheckItemEquip(attacker, this) == false)
{
canSwing = false;
}
if (canSwing && attacker.HarmfulCheck(defender))
{
attacker.DisruptiveAction();
attacker.NetState.SendSwing(attacker.Serial, defender.Serial);
if (attacker is BaseCreature bc && bc.TriggerAbility(MonsterAbilityTrigger.CombatAction, defender))
{
return GetDelay(attacker);
}
if (OnFired(attacker, defender))
{
if (CheckHit(attacker, defender))
{
OnHit(attacker, defender);
}
else
{
OnMiss(attacker, defender);
}
}
else if (WeaponAbility.GetCurrentAbility(attacker) is LightningArrow lightningArrow)
{
// Lightning Arrow doesn't require ammunition
attacker.MovingParticles(defender, EffectID, 18, 1, false, false, 0, 0, 0, 0, 0, EffectLayer.RightHand, 0);
lightningArrow.OnHit(attacker, defender, 0, new WorldLocation(defender));
}
}
attacker.RevealingAction();
return GetDelay(attacker);
}
attacker.RevealingAction();
return TimeSpan.FromSeconds(0.25);
}
public override void OnHit(Mobile attacker, Mobile defender, double damageBonus = 1)
{
if (attacker.Player && !defender.Player && (defender.Body.IsAnimal || defender.Body.IsMonster) &&
Utility.RandomDouble() < 0.4 && Ammo is { } ammo && !defender.AddToBackpack(ammo))
{
ammo.Delete();
}
if (Core.ML && _velocity > 0)
{
var bonus = (int)attacker.GetDistanceToSqrt(defender);
if (bonus > 0 && _velocity > Utility.Random(100))
{
AOS.Damage(defender, attacker, bonus * 3, 100, 0, 0, 0, 0);
if (attacker.Player)
{
attacker.SendLocalizedMessage(1072794); // Your arrow hits its mark with velocity!
}
if (defender.Player)
{
defender.SendLocalizedMessage(1072795); // You have been hit by an arrow with velocity!
}
}
}
base.OnHit(attacker, defender, damageBonus);
}
public override void OnMiss(Mobile attacker, Mobile defender)
{
if (attacker.Player && Utility.RandomDouble() < 0.4)
{
if (Core.SE)
{
if (attacker is PlayerMobile pm)
{
// Bank the spent ammo; it is gathered back up once the archer disengages.
AmmoRecovery.Bank(pm, AmmoType);
}
}
else
{
Ammo?.MoveToWorld(
new Point3D(
defender.X + Utility.RandomMinMax(-1, 1),
defender.Y + Utility.RandomMinMax(-1, 1),
defender.Z
),
defender.Map
);
}
}
base.OnMiss(attacker, defender);
}
public virtual bool OnFired(Mobile attacker, Mobile defender)
{
if (attacker.Player)
{
var quiver = attacker.FindItemOnLayer<BaseQuiver>(Layer.Cloak);
var pack = attacker.Backpack;
if (quiver == null || Utility.Random(100) >= quiver.LowerAmmoCost)
{
// consume ammo
if (quiver?.ConsumeTotal(AmmoType) == true)
{
quiver.InvalidateWeight();
}
else if (pack?.ConsumeTotal(AmmoType) != true)
{
return false;
}
}
else if (quiver.FindItemByType(AmmoType) == null && pack?.FindItemByType(AmmoType) == null)
{
// lower ammo cost should not work when we have no ammo at all
return false;
}
}
attacker.MovingParticles(defender, EffectID, 18, 1, false, false, 0, 0, 0, 0, 0, EffectLayer.RightHand, 0);
return true;
}
public override int OnCraft(
int quality,
bool makersMark,
Mobile from,
CraftSystem craftSystem,
Type typeRes,
BaseTool tool,
CraftItem craftItem,
int resHue
)
{
var result = base.OnCraft(quality, makersMark, from, craftSystem, typeRes, tool, craftItem, resHue);
if (Core.ML)
{
ApplyWoodBonuses(typeRes);
}
return result;
}
private void ApplyWoodBonuses(Type resource)
{
var craftResource = CraftResources.GetFromType(resource);
switch (craftResource)
{
case CraftResource.OakWood:
{
Attributes.Luck += 40;
Attributes.WeaponDamage += 5;
break;
}
case CraftResource.AshWood:
{
Attributes.WeaponSpeed += 10;
WeaponAttributes.LowerStatReq += 20;
break;
}
case CraftResource.YewWood:
{
Attributes.AttackChance += 5;
Attributes.WeaponDamage += 10;
break;
}
case CraftResource.Bloodwood:
{
Attributes.RegenHits += 2;
WeaponAttributes.HitLeechHits += 16;
break;
}
case CraftResource.Heartwood:
{
ApplyHeartwoodBonus();
break;
}
case CraftResource.Frostwood:
{
AosElementDamages.Physical = 60;
AosElementDamages.Cold = 40;
Attributes.WeaponDamage += 12;
break;
}
}
}
private void ApplyHeartwoodBonus()
{
switch (Utility.Random(6))
{
case 0:
{
Attributes.Luck += 40;
break;
}
case 1:
{
WeaponAttributes.DurabilityBonus += 50;
break;
}
case 2:
{
WeaponAttributes.LowerStatReq += 20;
break;
}
case 3:
{
Attributes.WeaponSpeed += 10;
break;
}
case 4:
{
Attributes.AttackChance += 5;
break;
}
case 5:
{
WeaponAttributes.HitLeechHits += 10;
break;
}
}
}
}
}