ModernUO/Projects/UOContent/Engines/Virtues/VirtueSystem.cs
Kamron Batman cce035f1c3
fix: Removes unnecessary dictionary removal guards (#2565)
## What

`Dictionary<K,V>.Remove` and `HashSet<T>.Remove` do not bump the collection's version, so removing an entry during a `foreach` does not invalidate the enumerator. A number of loops were still paying for a `PooledRefQueue`/`PooledRefList` to collect keys and drain them in a second pass. This drops those guards.

## Why it's safe

Verified against .NET 10.0.10 rather than taken on trust, since the documented guarantee covers only `Dictionary<TKey,TValue>.Remove` while several of these call sites are `HashSet<T>` or enumerate `.Keys`/`.Values`:

| Case | Result |
|---|---|
| `Dictionary` foreach + `Remove` | safe, all entries visited |
| `Dictionary.Keys` / `.Values` foreach + `Remove` | safe, all entries visited |
| `HashSet` foreach + `Remove` | safe, all entries visited |
| `Dictionary` foreach + `Remove` **then `Add`** | throws `InvalidOperationException` |

Reflection on `_version` confirms the mechanism: neither `Dictionary.Remove` nor `HashSet.Remove` touches it. Because `Remove` never bumps the version, the `Keys` and `Values` enumerators are just as safe as the dictionary's own, even though only `Dictionary.Remove` documents the behaviour. No entries were skipped in any case.

The `HashSet` half is confirmed by [stephentoub on dotnet/dotnet-api-docs#8177](https://github.com/dotnet/dotnet-api-docs/issues/8177#issuecomment-1167251052): *"Both HashSet and Dictionary have been improved to support removal during enumeration. The docs may just benefit from updating."* The gap is in the documentation, not the runtime.

`Remove` followed by `Add` in the same enumeration still throws. That is the line this PR does not cross.

## Guards removed

`VisibilityList`, `ChampionTitleSystem`, `Channel`, `BombingRun`, `Ruleset`, `PuzzleChest`, `RaceChangeGump`, `StepCache`, `PlayerMurderSystem`, `VirtueSystem`, `ProjectedItem`, `StaminaSystem`, `AIGroupMovement`, `PromotedGuard`, `AutoDenylist`, `LoginAllowlist`, `AntiMacroSystem`, `DetectHidden`.

Both collection kinds are covered: `Dictionary` (including loops over `.Keys` and `.Values`) and `HashSet` (`ProjectedItem._active`, `PlayerMurderSystem._contextTerms`, `StaminaSystem._resetHash`). In `StaminaSystem.ResetTimer` the `Count == queue.Count → Clear()` branch goes away with the queue — it only existed to avoid paying for N individual removes.

Where the collection supports it, `Contains` + `Remove` and `TryGetValue` + `Remove` also collapse into a single lookup (`if (list.Remove(x))`, `if (m_Pending.Remove(ns, out var state))`).

`Utility.Tidy<K,V>` keeps its two branches: when `K` is serializable the value is not inspected, otherwise the value is. Only the serializable side may be cast, so `Dictionary<Mobile, int>` and `Dictionary<Mobile, string>` stay valid.

## Deliberately unchanged

**`BaseCreature.LoyaltyTimer.OnTick`** keeps its deferred-delete queue. Removing from `World.Mobiles` while enumerating it is safe, but `Mobile.Delete()` is not a `Remove` — it runs `OnDelete`/`OnAfterDelete`, the `OnParentDeleted` cascade over the creature's pack, `DropHolding()`, and region and guild callbacks. Anything in that surface that constructs a `Mobile` is an `Add` into the dictionary being enumerated, which does invalidate it. `BaseHire.PayTimer.OnTick` has the same shape and is likewise untouched.

**Spatial-query buffers** — `GuardedRegion.CallGuards`, `Thunderstorm`, `Exorcism`, `LeverPuzzleController`, `BaseCreature.TeleportPets` — are a different hazard. They buffer the result of a range query because the drain moves or harms mobiles, which mutates sectors mid-enumeration.

**Re-entrant drains.** The `_users` sets in `Firebomb` and the explosion, conflagration and confusion-blast potions look like this pattern but are not: the loop collects, `Clear()`s, and only then runs `Target.Cancel` on each, which can re-enter. `AnimalTrainer` enumerates `pm.Stabled` and drains through `RemoveStabled`, which nulls the `Stabled` field once it empties — safe for an in-flight enumerator, which holds the set reference rather than the field, but subtle enough not to be worth inlining on a cold path.

## Verification

`dotnet build` clean with 0 warnings; 810 Server and 684 UOContent tests pass.
2026-08-08 11:50:01 -07:00

392 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ModernUO.CodeGeneratedEvents;
using Server.Collections;
using Server.Logging;
using Server.Mobiles;
namespace Server.Engines.Virtues;
public enum VirtueLevel
{
None,
Seeker,
Follower,
Knight
}
[Flags]
public enum VirtueName
{
Humility,
Sacrifice,
Compassion,
Spirituality,
Valor,
Honor,
Justice,
Honesty
}
public class VirtueSystem : GenericPersistence
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(VirtueSystem));
private static readonly Dictionary<PlayerMobile, VirtueContext> _playerVirtues = new();
private static VirtueSystem _virtueSystemPersistence;
public static void Configure()
{
_virtueSystemPersistence = new VirtueSystem();
}
public VirtueSystem() : base("Virtues", 10)
{
}
private static void FixVirtue(Mobile m, int[] virtueValues)
{
if (m is not PlayerMobile pm)
{
return;
}
var virtues = pm.Virtues;
for (var i = 0; i < virtueValues.Length; i++)
{
var val = virtueValues[i];
if (val > 0)
{
virtues.SetValue(i, val);
}
}
}
public static void Initialize()
{
var migrations = Mobile.VirtueMigrations;
if (migrations?.Count > 0)
{
foreach (var (m, values) in migrations)
{
FixVirtue(m, values);
}
}
}
[OnEvent(nameof(PlayerMobile.PlayerDeletedEvent))]
public static void OnPlayerDeleted(PlayerMobile pm) => _playerVirtues.Remove(pm);
public override void Serialize(IGenericWriter writer)
{
writer.WriteEncodedInt(0); // version
writer.WriteEncodedInt(_playerVirtues.Count);
foreach (var (pm, virtues) in _playerVirtues)
{
writer.Write(pm);
virtues.Serialize(writer);
}
}
public override void Deserialize(IGenericReader reader)
{
reader.ReadEncodedInt(); // version
var contextCount = reader.ReadEncodedInt();
for (var i = 0; i < contextCount; i++)
{
var player = reader.ReadEntity<PlayerMobile>();
var virtues = new VirtueContext();
virtues.Deserialize(reader);
if (player != null && virtues.IsUsed())
{
_playerVirtues.Add(player, virtues);
}
}
}
public static VirtueContext GetVirtues(PlayerMobile from) =>
from != null && _playerVirtues.TryGetValue(from, out var context) ? context : null;
public static VirtueContext GetOrCreateVirtues(PlayerMobile from)
{
if (from == null)
{
return null;
}
ref var context = ref CollectionsMarshal.GetValueRefOrAddDefault(_playerVirtues, from, out var exists);
if (!exists)
{
context = new VirtueContext();
}
return context;
}
public static bool IsHighestPath(PlayerMobile from, VirtueName virtue) =>
GetVirtues(from)?.GetValue((int)virtue) >= GetMaxAmount(virtue);
public static VirtueLevel GetLevel(Mobile from, VirtueName virtue)
{
var v = GetVirtues(from as PlayerMobile)?.GetValue((int)virtue) ?? 0;
int vl;
if (v < 4000)
{
vl = 0;
}
else if (v >= GetMaxAmount(virtue))
{
vl = 3;
}
else
{
vl = (v + 9999) / 10000;
}
return (VirtueLevel)vl;
}
public static string GetName(VirtueName virtue) =>
virtue switch
{
VirtueName.Humility => "Humility",
VirtueName.Sacrifice => "Sacrifice",
VirtueName.Compassion => "Compassion",
VirtueName.Spirituality => "Spirituality",
VirtueName.Valor => "Valor",
VirtueName.Honor => "Honor",
VirtueName.Justice => "Justice",
VirtueName.Honesty => "Honesty",
_ => ""
};
public static string GetLowerCaseName(VirtueName virtue) =>
virtue switch
{
VirtueName.Humility => "humility",
VirtueName.Sacrifice => "sacrifice",
VirtueName.Compassion => "compassion",
VirtueName.Spirituality => "spirituality",
VirtueName.Valor => "valor",
VirtueName.Honor => "honor",
VirtueName.Justice => "justice",
VirtueName.Honesty => "honesty",
_ => ""
};
public static int GetMaxAmount(VirtueName virtue) =>
virtue switch
{
VirtueName.Honor => 20000,
VirtueName.Sacrifice => 22000,
_ => 21000
};
public static int GetGainedLocalizedMessage(VirtueName virtue) =>
virtue switch
{
VirtueName.Sacrifice => 1054160, // You have gained in sacrifice.
VirtueName.Compassion => 1053002, // You have gained in compassion.
VirtueName.Spirituality => 1155832, // You have gained in Spirituality.
VirtueName.Valor => 1054030, // You have gained in Valor!
VirtueName.Honor => 1063225, // You have gained in Honor.
VirtueName.Justice => 1049363, // You have gained in Justice.
VirtueName.Humility => 1052070, // You have gained in Humility.
_ => 0
};
public static int GetGainedAPathLocalizedMessage(VirtueName virtue) =>
virtue switch
{
VirtueName.Sacrifice => 1052008, // You have gained a path in Sacrifice!
VirtueName.Spirituality => 1155833, // "You have gained a path in Spirituality!" (Why are there quotes?)
VirtueName.Valor => 1054032, // You have gained a path in Valor!
VirtueName.Honor => 1063226, // You have gained a path in Honor!
VirtueName.Justice => 1049367, // You have gained a path in Justice!
VirtueName.Humility => 1155811, // You have gained a path in Humility!
_ => 0
};
public static int GetHightestPathLocalizedMessage(VirtueName virtue) =>
virtue switch
{
VirtueName.Compassion => 1053003, // You have achieved the highest path of compassion and can no longer gain any further.
VirtueName.Spirituality => 1155831, // You cannot gain more Spirituality.
VirtueName.Valor => 1054031, // You have achieved the highest path in Valor and can no longer gain any further.
VirtueName.Honor => 1063228, // You cannot gain more Honor.
VirtueName.Justice => 1049534, // You cannot gain more Justice.
VirtueName.Humility => 1155808, // You cannot gain more Humility.
VirtueName.Honesty => 1153771, // You have achieved the highest path in Honesty and can no longer gain any further.
_ => 1052050, // You have achieved the highest path in this virtue.
};
public static bool Award(PlayerMobile from, VirtueName virtue, int amount, ref bool gainedPath)
{
var virtues = from.Virtues;
var current = virtues.GetValue((int)virtue);
var maxAmount = GetMaxAmount(virtue);
if (current >= maxAmount)
{
return false;
}
if (current + amount >= maxAmount)
{
amount = maxAmount - current;
}
var oldLevel = GetLevel(from, virtue);
virtues.SetValue((int)virtue, current + amount);
gainedPath = GetLevel(from, virtue) != oldLevel;
return true;
}
public static bool Atrophy(PlayerMobile from, VirtueName virtue, int amount = 1)
{
var virtues = GetVirtues(from);
if (virtues == null)
{
return false;
}
var current = virtues.GetValue((int)virtue);
if (current - amount >= 0)
{
virtues.SetValue((int)virtue, current - amount);
}
else
{
virtues.SetValue((int)virtue, 0);
}
return current > 0;
}
public static bool IsSeeker(PlayerMobile from, VirtueName virtue) => GetLevel(from, virtue) >= VirtueLevel.Seeker;
public static bool IsFollower(PlayerMobile from, VirtueName virtue) => GetLevel(from, virtue) >= VirtueLevel.Follower;
public static bool IsKnight(PlayerMobile from, VirtueName virtue) => GetLevel(from, virtue) >= VirtueLevel.Knight;
public static void AwardVirtue(PlayerMobile pm, VirtueName virtue, int amount)
{
var virtues = GetOrCreateVirtues(pm);
if (virtue == VirtueName.Compassion)
{
if (virtues.CompassionGains > 0 && Core.Now > virtues.NextCompassionDay)
{
virtues.NextCompassionDay = DateTime.MinValue;
virtues.CompassionGains = 0;
}
if (virtues.CompassionGains >= 5)
{
pm.SendLocalizedMessage(1053004); // You must wait about a day before you can gain in compassion again.
return;
}
}
var gainedPath = false;
var virtueName = GetName(virtue);
if (Award(pm, virtue, amount, ref gainedPath))
{
if (gainedPath)
{
var gainedPathMessage = GetGainedAPathLocalizedMessage(virtue);
if (gainedPathMessage != 0)
{
pm.SendLocalizedMessage(gainedPathMessage);
}
else
{
pm.SendMessage($"You have gained a path in {virtueName}!");
}
}
else
{
var gainMessage = GetGainedLocalizedMessage(virtue);
if (gainMessage != 0)
{
pm.SendLocalizedMessage(gainMessage);
}
else
{
pm.SendMessage($"You have gained in {virtueName}.");
}
}
if (virtue == VirtueName.Compassion)
{
virtues.NextCompassionDay = Core.Now + TimeSpan.FromDays(1.0);
if (++virtues.CompassionGains >= 5)
{
// You must wait about a day before you can gain in compassion again.
pm.SendLocalizedMessage(1053004);
}
}
}
else
{
pm.SendLocalizedMessage(GetHightestPathLocalizedMessage(virtue));
}
}
public static void CheckAtrophies(PlayerMobile pm)
{
SacrificeVirtue.CheckAtrophy(pm);
JusticeVirtue.CheckAtrophy(pm);
CompassionVirtue.CheckAtrophy(pm);
ValorVirtue.CheckAtrophy(pm);
}
private class VirtueTimer : Timer
{
public VirtueTimer() : base(TimeSpan.FromMinutes(5.0), TimeSpan.FromMinutes(5.0))
{
}
public static void Initialize()
{
new VirtueTimer().Start();
}
protected override void OnTick()
{
if (_playerVirtues.Count == 0)
{
return;
}
// This is not particularly efficient. If it gets too slow, then use a different architecture.
foreach (var (player, virtues) in _playerVirtues)
{
CheckAtrophies(player);
if (!virtues.IsUsed())
{
_playerVirtues.Remove(player);
}
}
}
~VirtueTimer()
{
VirtueSystem.logger.Error($"{nameof(VirtueTimer)} is no longer running!");
}
}
}