ModernUO/Projects/UOContent/Skills/AntiMacroSystem.cs
Kamron Batman 392c4e16d5
refactor: Changes BaseCreature to the SerializationGenerator (delta save requirement) (#2611)
The pure SerializationGenerator conversion of `BaseCreature`, split out of #2592 so it can serve as the reference for converting every other large hand-written class in the Delta Saves project (#7, phase 3). Two behaviour changes from #2592 are deliberately not here and follow in their own PRs on top of this one: `SpeedClass`, and the collapse of `ControlMaster`/`SummonMaster` into one reference (a creature can lose or keep either independently: Blade Spirits and Energy Vortexes are summoned but never controlled, EnragedCreature and talisman summons keep a summon master with neither flag set).

## What this is

- `BaseCreature` becomes `[SerializationGenerator(23, false)]` with a `[SerializableField]` per serialized slot and `[SaveFlag]` elision on nearly every field, so a stock creature serializes to its version plus flags. Field orders run 0..53 with no gaps (54 fields).
- The hand-written reader stays as `private void Deserialize(IGenericReader reader, int version)` for every pre-codegen version (0..22); post-codegen bumps use `MigrateFrom` from here on. `[AfterDeserialization]` carries the post-load fixups main did after reading (stat timers, AI type, followers, reacquire seeding).
- `ControlMaster` and `SummonMaster` stay two independent fields with main's semantics, each elided when null.
- `DamageMin`/`DamageMax`/`ActiveSpeed`/`PassiveSpeed` are no longer virtual (nothing in the tree overrode them); comments swept to the constraints that matter.
- Direct writes to serialized backing fields outside the generated setters (`SetDamage`, `SetResistance`, the move-speed helpers, the loot flag, feed loyalty, the delete timer) call `this.MarkDirty()`, matching the #2609 standard, so the class is ready for delta saves once `Mobile` is audited.
- Schema `Server.Mobiles.BaseCreature.v23.json` regenerated by the tool (a second run produces no diff).

## Deferred to follow-up PRs

SpeedClass: the serialized `_speedClass` field, `DefaultSpeedClass` replacing the type constant, `ApplySpeedClass`/`OnSpeedClassChange`, "None means custom", the four-speeds-as-one-block elision, `NPCSpeeds.FindEntry(SpeedLevel)`, the constructor fallback to Medium, and their tests.

Master references: serializing one `Master` with a `Controlled`/`Summoned` fan-out and the `SetControlMaster` lockstep.

## Tests

UOContent.Tests 776 / Server.Tests 855 green. `BaseCreatureSerializationTests` covers: a default creature elides to version + flags; a populated creature round-trips with exact byte consumption; back-to-back saves are byte-identical; an uncontrolled summon keeps its SummonMaster; byte-authentic v22 legacy streams (replicas of main's `Serialize`) load through the legacy reader for a wild tamable, a controlled pet, a controlled summon with an anchored `SummonEnd`, and a summon-master-only creature (the EnragedCreature shape); a running delete timer round-trips through `[DeserializeTimer]`; `Friends`, `CurrentWayPoint` and `HomeMap` round-trip; a `BaseVendor` stub round-trips the generated BaseVendor v2 → generated BaseCreature v23 chain.

## Behaviour notes for reviewers

- `ActiveMoveSpeed`/`PassiveMoveSpeed` getters return the raw override (0 = inherit); `CurrentMoveSpeed` is the resolved pace.
- Speeds elided as table defaults re-snap to the current `npc-speeds.json` on load, so table edits reach unmodified spawns on restart.
- `GetSpeeds` no longer throws on the save/load path when the table has no entry for the type: saves elide against the creature's own values and loads keep the stream. Construction still throws (`InvalidOperationException`, was `KeyNotFoundException`). An elided load with no table entry would otherwise resume at speed 0, so `[AfterDeserialization]` logs once and paces it at Medium.
- `virtual` removed from `ActiveSpeed`, `PassiveSpeed`, `DamageMin`, `DamageMax` (no overrides in the tree; forks may have some).
- `ControlMaster`, `SummonMaster`, `ControlOrder`, `Tamable`, `IsParagon` are `[SerializableProperty]` over hand-written setters because follower bookkeeping must run before the assignment, which a `fieldChanged` hook cannot express; the wire format is identical.

## Prerequisites for cherry-picking
#2609 (BaseVendor is already generated on top of BaseCreature) and SerializationGenerator 4.1.0.
2026-09-06 14:11:51 -07:00

270 lines
7.8 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json.Serialization;
using ModernUO.CodeGeneratedEvents;
using Server.Json;
using Server.Mobiles;
namespace Server.Misc;
public static class AntiMacroSystem
{
// *** NOTE ***: Modifying these values will not change an already created antimacro.json file!
private static readonly bool[] _antiMacroSkillDefaults =
{
false, // Alchemy = 0,
true, // Anatomy = 1,
true, // AnimalLore = 2,
true, // ItemID = 3,
true, // ArmsLore = 4,
false, // Parry = 5,
true, // Begging = 6,
false, // Blacksmith = 7,
false, // Fletching = 8,
true, // Peacemaking = 9,
true, // Camping = 10,
false, // Carpentry = 11,
false, // Cartography = 12,
false, // Cooking = 13,
true, // DetectHidden = 14,
true, // Discordance = 15,
true, // EvalInt = 16,
true, // Healing = 17,
true, // Fishing = 18,
true, // Forensics = 19,
true, // Herding = 20,
true, // Hiding = 21,
true, // Provocation = 22,
false, // Inscribe = 23,
true, // Lockpicking = 24,
true, // Magery = 25,
true, // MagicResist = 26,
false, // Tactics = 27,
true, // Snooping = 28,
true, // Musicianship = 29,
true, // Poisoning = 30,
false, // Archery = 31,
true, // SpiritSpeak = 32,
true, // Stealing = 33,
false, // Tailoring = 34,
true, // AnimalTaming = 35,
true, // TasteID = 36,
false, // Tinkering = 37,
true, // Tracking = 38,
true, // Veterinary = 39,
false, // Swords = 40,
false, // Macing = 41,
false, // Fencing = 42,
false, // Wrestling = 43,
true, // Lumberjacking = 44,
true, // Mining = 45,
true, // Meditation = 46,
true, // Stealth = 47,
true, // RemoveTrap = 48,
true, // Necromancy = 49,
false, // Focus = 50,
true, // Chivalry = 51
true, // Bushido = 52
true, // Ninjitsu = 53
true, // Spellweaving
true, // Mysticism = 55
true, // Imbuing = 56
false, // Throwing = 57
};
private static Dictionary<Mobile, PlayerAntiMacro> _antiMacroTable;
private static Dictionary<Mobile, Timer> _logoutCleanup;
private const string _antiMacroPath = "Configuration/antimacro.json";
public static AntiMacroSettings Settings { get; private set; }
public static void Configure()
{
var path = Path.Combine(Core.BaseDirectory, _antiMacroPath);
if (File.Exists(path))
{
Settings = JsonConfig.Deserialize<AntiMacroSettings>(path);
}
else
{
Settings = new AntiMacroSettings
{
Enabled = false,
Allowance = 3,
LocationSize = 5,
Expire = TimeSpan.FromMinutes(5.0),
SkillsThatUseAntiMacro = new BitArray(_antiMacroSkillDefaults)
};
JsonConfig.Serialize(Path.Join(Core.BaseDirectory, _antiMacroPath), Settings);
}
}
public static void Initialize()
{
EventSink.WorldSave += OnWorldSave;
EventSink.Logout += OnLogout;
}
private static void OnWorldSave()
{
if (_antiMacroTable == null)
{
return;
}
var now = Core.Now;
foreach (var (m, antiMacro) in _antiMacroTable)
{
if (antiMacro._lastExpiration <= now)
{
_antiMacroTable.Remove(m);
}
else
{
antiMacro.CleanExpired();
}
}
}
[OnEvent(nameof(PlayerMobile.PlayerLoginEvent))]
public static void OnLogin(PlayerMobile pm)
{
// Stop the clear out timer
if (_logoutCleanup?.Remove(pm, out var timer) == true)
{
timer.Stop();
}
}
private static void OnLogout(Mobile m)
{
if (_antiMacroTable?.TryGetValue(m, out var antiMacro) != true)
{
return;
}
if (antiMacro._lastExpiration < Core.Now)
{
_antiMacroTable.Remove(m);
return;
}
_logoutCleanup ??= new Dictionary<Mobile, Timer>();
if (_logoutCleanup.TryGetValue(m, out var timer))
{
timer.Stop();
}
else
{
_logoutCleanup[m] = timer = Timer.DelayCall(Settings.Expire, CleanupPlayer, m);
}
timer.Start();
}
public static void CleanupPlayer(Mobile pm)
{
if (_antiMacroTable?.Remove(pm, out var antiMacro) == true)
{
// Hint to GC that we don't want this
antiMacro._antiMacroTracking.Clear();
antiMacro._antiMacroTracking = null;
}
if (_logoutCleanup?.Remove(pm, out var timer) == true)
{
timer.Stop();
}
}
public static bool UseAntiMacro(int skillId) =>
skillId >= 0 && skillId < Settings.SkillsThatUseAntiMacro.Length && Settings.SkillsThatUseAntiMacro[skillId];
public static bool AntiMacroCheck(PlayerMobile pm, Skill skill, object obj)
{
if (!Settings.Enabled || obj == null || pm.AccessLevel != AccessLevel.Player || !UseAntiMacro(skill.Info.SkillID))
{
return true;
}
_antiMacroTable ??= new Dictionary<Mobile, PlayerAntiMacro>();
// Hot path so use optimized code
ref var antiMacro = ref CollectionsMarshal.GetValueRefOrAddDefault(_antiMacroTable, pm, out var exists);
if (!exists)
{
antiMacro = new PlayerAntiMacro();
}
return antiMacro.AntiMacroCheck(skill, obj);
}
public record AntiMacroSettings
{
// How many times may we use the same location/target for gain
public int Allowance { get; init; }
// The size of each location, make this smaller so players dont have to move as far
public int LocationSize { get; init; }
public bool Enabled { get; init; }
// How long do we remember targets/locations?
public TimeSpan Expire { get; init; }
[JsonConverter(typeof(BitArrayEnumIndexConverter<SkillName>))]
public BitArray SkillsThatUseAntiMacro { get; init; }
}
private class PlayerAntiMacro
{
// This can get quite large. If a player is logged in for a while, this can be promoted to Gen 2 and
// become a memory leak.
public Dictionary<(Skill, object), CountAndTimeStamp> _antiMacroTracking = new();
public DateTime _lastExpiration;
public bool AntiMacroCheck(Skill skill, object obj)
{
var now = Core.Now;
// Potential hot path, so use optimized code
ref var _countTimeStamp =
ref CollectionsMarshal.GetValueRefOrAddDefault(_antiMacroTracking, (skill, obj), out var exists);
_countTimeStamp._count++;
if (!exists || _countTimeStamp._expiration <= now || _countTimeStamp._count < Settings.Allowance)
{
_countTimeStamp._expiration = _lastExpiration = now + Settings.Expire;
return true;
}
return false;
}
public void CleanExpired()
{
var now = Core.Now;
foreach (var (key, countAndTimeStamp) in _antiMacroTracking)
{
if (countAndTimeStamp._count <= 0 || countAndTimeStamp._expiration <= now)
{
_antiMacroTracking.Remove(key);
}
}
}
}
private struct CountAndTimeStamp
{
public int _count;
public DateTime _expiration;
}
}