Reduces the world-save freeze window from ~740ms to ~78ms (measured on a synthetic 10M-entity / 1.7GB world, 24 cores, through the real pipeline classes) by removing the per-entity handoff between the game loop and the serialization workers, fixing how large indivisible payloads are scheduled, rewriting the BufferWriter hot path, removing per-entity placement state entirely, and finally replacing the global serialized-types tracking with a per-file type table (idx v4) that also shrinks idx files by ~21% and speeds the background write phase. The pipeline has also been validated end-to-end on live-copy worlds in the multi-million-entity range, where the freeze is drain-bound (real `Serialize()` costs far more CPU per byte than synthetic writes) — the same structural wins hold, and entity/file round-trips are byte-clean across both load paths.
## The problem
The freeze window is `max(main-thread handoff, slowest worker drain)`:
1. **The producer was the bottleneck.** The main thread round-robined every entity through per-worker `ConcurrentQueue`s — two interlocked ops per entity, ~740ms of freeze floor at 10M entities before any serialization happened.
2. **Round-robin distributes count, not cost.** "Deep" systems (50MB generic persistence blobs) and "thick" entities (100K-item storage keys) landed on arbitrary workers, producing lopsided drain times on large worlds.
3. **Worst-case scheduling.** `GenericEntityPersistence.Serialize` pushed its self-payload *after* all entities, and generic persistences sort last in the registry — so the biggest indivisible blobs started serializing at the very end, extending the freeze by their entire duration.
## The fix
**Commit 1 — chunked handoff + LPT scheduling + heap pre-sizing:**
- Pooled 4096-entity chunks published to one shared queue; workers pull chunks and load-balance dynamically (a worker busy with a thick entity simply takes fewer chunks).
- `Persistence.SerializeAll` pushes systems largest-first (LPT) using the previous save's payload size (or loaded file size on first boot); self-payloads get dedicated single-entity chunks so they overlap the entity stream instead of ending it.
- Worker heaps pre-size from the loaded save's `.bin` totals, eliminating copy-on-grow inside the first save's freeze.
- `SpinWait` backoff in the drain loop (never `Sleep(1)`), per-worker balance stats logged in debug builds (the call site is compiled out of Release), 1MB snapshot write buffer.
**Commit 2 — workers iterate the dictionaries directly + main thread joins the drain:**
- `GenericEntityPersistence` publishes 4096-slot ranges over its dictionary's backing entries array; workers serialize occupied slots (`value != null`) directly through a `ShadowEntry<TValue>` struct mirroring the runtime's private `Entry` layout. Safe because the dictionary is frozen during `Saving` (mutations divert to the pending safety queues).
- The layout is **proven at startup before any code reads through it**: validation measures the true `Entry` stride via precise allocation accounting (guaranteeing all shadow reads are in-bounds), then verifies every key/value of a churned, resized, freelist-exercised dictionary — reading value slots as raw pointer bits only, never materializing a managed reference until the layout is proven. If a future runtime changes `Dictionary` internals, validation fails with a logged warning and saves fall back to the (fully maintained) enumerate-and-push path.
- The main thread joins the drain via an inline worker after publishing, instead of idling — worth a full worker share, proportionally more on low-core hosts.
**Commit 3 — 2.2x faster BufferWriter write path, single-pass short strings:**
- PGO already devirtualizes and inlines every `IGenericWriter.Write` callsite (interface vs concrete measured identical) — the real per-write cost was the non-inlinable `Index` setter (range-check throw path + per-write high-water tracking) plus span bounds checks. Writes now reserve capacity once, then do an unaligned store through a ref with a raw index increment; the high-water mark folds at Seek/Resize instead of per write.
- Class-level implementations of the hottest default interface methods keep nested writes inlined (a DIM re-dispatches on `this` even at a devirtualized callsite).
- Strings of 85 chars or fewer encode once into a stack scratch instead of walking the string twice (`GetByteCount` + `GetBytes`). Byte output is identical.
- Measured: 34.4 → 15.7 ns/entity on a generated-style write mix; end-to-end freeze ~99ms → ~74-82ms.
**Commit 4 — branch-free fallback push loop:**
- A bare `foreach { PushToCache(entity); }` runs at 2.3ns/entity; the same loop carrying a per-entity heavy-check runs 2.3x slower — the cost is the fatter loop body defeating tight-loop codegen. Entity-level >1MB payloads are rare enough to ride in shared chunks; system self-payloads (the large ones) are still explicitly scheduled largest-first.
**Commit 5 — drop the 9-byte per-entity placement state; snapshots write from worker segment logs:**
- Every `ISerializable` carried `SerializedThread/SerializedPosition/SerializedLength` so `WriteSnapshot` could gather each entity's bytes from the worker heaps in dictionary order. But the idx records absolute positions — bin order is free — so the snapshot is now written in worker-heap order and the join inverts: workers log segments (owner, slot range, heap start) plus one length per record as they serialize; positions are implicit because a worker's writes are contiguous, and identity comes from re-walking the same snapshot slots in the same order (stable until `PostWorldSave`).
- Chunks are persistence-homogeneous (the partial chunk publishes at each `SerializeAll` boundary) so segments route to files by owner with zero per-entity state. Self-payloads keep placement as three private fields on the handful of persistence instances.
- Net: 9 bytes (plus padding) of resident state removed from every item, mobile, guild, and account on every shard; three interface-property stores per entity leave the drain hot path (stamping dirtied one cache line per entity mid-freeze — the lengths log is one sequential stream); each segment's bytes hit the bin as a single span write instead of one copy per entity, speeding the background write phase; and `IGenericSerializable` shrinks to just `Serialize(IGenericWriter)`. Transient cost: ~4 bytes per entity in pooled per-worker logs, released after each write. The save format was unchanged at this point (idx v3, same loader); the v4 bump comes later in the branch.
**Commit 6 — staged file writes replace memory-mapped snapshot writing:**
- `MemoryMapFileWriter` is removed. `FileBufferWriter` composes through the full `BufferWriter` raw write path into a pooled staging block that drains to the file as large sequential positional writes (`RandomAccess.Write`); seeks flush the block and move the file offset, so backwards patches (the idx entity count) become small positional writes.
- Memory-mapped composition paid a soft page fault on every composed page plus unpredictable dirty-section teardown stalls at dispose — measured ~4x slower end-to-end than staged writes at snapshot sizes.
**Commits 7–11 — idx v4: per-file type table replaces SerializedTypes.db and all runtime type tracking:**
- Previously every `Write(Type)` from every worker enqueued into a shared `ConcurrentQueue<Type>` during the freeze (interlocked writes on a shared cache line, millions of mostly-duplicate entries), the background phase drained and deduped it all into a `HashSet`, and the snapshot recomputed `xxHash64(Type.FullName)` once per entity record (~5.4M redundant hashes per save on a large world) to write 9-byte tag+hash idx records plus a global `SerializedTypes.db`.
- The db's only real job was diagnostics: the string name behind "Type `<X>` was not found. Delete all of those types?" during idx loading. That map now lives in the idx itself: each `GenericEntityPersistence<T>` keeps an insertion-ordered `Type -> ushort` table, hydrated at `AddEntity` and on every deserialize path — one dictionary `TryAdd` per entity add on the game thread, amortized across gameplay, and provably immutable while the background writer reads it (adds divert to the pending queues during saves).
- idx v4 layout: the table (names only) is written before the records; records reference it by 2-byte index, shrinking from 33 to 26 bytes (−21%). The loader resolves each table name **once** (`FindTypeByHash(ComputeHash64(name))` — semantically identical to v3 resolution, `TypeAlias` included) into a constructor array, and each record becomes an array index instead of an 8-byte hash read plus dictionary probe. The unresolved-type prompt now surfaces once per type, with the name.
- Deleted outright: `World.SerializedTypes`, the drain/dedupe pass in `WriteFiles`, `BufferWriter`'s type tracking (its `Write(Type)` is now pure — payload format unchanged: tag byte + xxHash64), `FileBufferWriter`'s typeSet parameter, `Persistence.WriteSerializedTypesSnapshot`, and the adhoc db write. SerializedTypes.db is no longer produced.
- **Backward compatibility:** v0–v3 saves (including their SerializedTypes.db and legacy tdb files) load exactly as before, and every legacy load path hydrates the new table so the first v4 save after an upgrade is complete. Stale db files in existing save folders are simply ignored. Verified live: a v3 save boots, saves as v4 (Items.idx −20.2% on a dev world), and reloads with identical entity counts.
## Measured (synthetic 10M entities / 1.7GB, 64+64+32MB system blobs, 24x 2MB thick entities, dense write profile, 24 cores)
| Metric | Before | After |
|---|---|---|
| Steady-state freeze | ~740 ms | **~78 ms** |
| Main-thread publish cost | ~740 ms | **~0.1 ms** |
| Steady-state allocations | 0 | 0 (by iter 2) |
| Worker byte-load spread | 2x | ~1.15x |
The freeze is now bound by pure serialize throughput (payload / cores).
## Tests
- 779 Server.Tests + 501 UOContent.Tests pass.
- New across the branch: chunk fill/flush/owner-boundary tests, pool reuse/clear tests, an end-to-end multi-worker drain through the real wake/push/flush/pause protocol, a 50K-entry churn equivalence test for the shadow iteration re-walk (the exact pairing the snapshot writer relies on), byte-level BufferWriter output/position pins, `RuntimeLayoutIsSupported` so a silent fallback on a future runtime upgrade fails loudly in CI, and a full snapshot **round-trip test** that serializes 25K entities plus a self-payload through real workers, writes the idx/bin from the segment logs, and reloads them through the standard loader (now in v4 format).
- For idx v4 specifically: `FileBufferWriter` staging/drain/seek-patch and oversized-item tests, type-table registration tests, a hand-written v4 fixture proving an unresolvable type name skips only its own records through the console confirmation flow, and a hand-written **legacy v3 fixture** proving old saves still load and hydrate the type table for their next save.
## Trade-offs
- Chunk scheduling is nondeterministic, so worker heaps ratchet to each worker's max-ever draw rather than a fixed share. With slot ranges the balance is tight (~1.15x), so the effect is small; a shared slab pool remains an option if production shows retention creep.
- Entity-level heavy items inside slot ranges are serialized wherever they're encountered (no LPT for them); worst-case tail is one thick entity's serialize time (~ms). System self-payloads — the large ones — are still explicitly scheduled largest-first.
- Snapshot-write error granularity is per segment rather than per entity (heap-bounds bugs were the only thing the per-entity catch ever caught; idx metadata reads keep per-record granularity).
- idx v4 is a save-format version bump: old saves load unchanged through the preserved legacy paths, but saves written by this branch require this loader. Per-persistence type tables cap at 65,535 distinct entity types per boot (hard throw, orders of magnitude of headroom), and a type's table slot persists until restart even if its last entity is deleted — a few stale name entries per file, by design.
1154 lines
31 KiB
C#
1154 lines
31 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Xml;
|
|
using ModernUO.CodeGeneratedEvents;
|
|
using ModernUO.Serialization;
|
|
using Server.Accounting.Security;
|
|
using Server.Misc;
|
|
using Server.Mobiles;
|
|
using Server.Multis;
|
|
using Server.Network;
|
|
using Server.Systems.FeatureFlags;
|
|
|
|
namespace Server.Accounting;
|
|
|
|
[PropertyObject]
|
|
[SerializationGenerator(6)]
|
|
public partial class Account : IAccount, IComparable<Account>
|
|
{
|
|
public static readonly TimeSpan YoungDuration = TimeSpan.FromHours(40.0);
|
|
public static readonly TimeSpan InactiveDuration = TimeSpan.FromDays(180.0);
|
|
public static readonly TimeSpan EmptyInactiveDuration = TimeSpan.FromDays(30.0);
|
|
|
|
[InternString]
|
|
[SerializableField(0, setter: "private")]
|
|
private string _username;
|
|
|
|
[SerializableField(1)]
|
|
private PasswordProtectionAlgorithm _passwordAlgorithm;
|
|
|
|
[SerializableField(2)]
|
|
private string _password;
|
|
|
|
[SerializableField(3)]
|
|
private AccessLevel _accessLevel;
|
|
|
|
[SerializableField(4)]
|
|
private int _flags;
|
|
|
|
[SerializableField(5)]
|
|
private DateTime _lastLogin;
|
|
|
|
/// <summary>
|
|
/// This amount represents the current amount of Gold owned by the player.
|
|
/// The value does not include the value of Platinum and ranges from
|
|
/// 0 to 999,999,999 by default.
|
|
/// </summary>
|
|
[SerializableField(6, setter: "private")]
|
|
[SerializedCommandProperty(AccessLevel.Administrator)]
|
|
public int _totalGold;
|
|
|
|
/// <summary>
|
|
/// This amount represents the current amount of Platinum owned by the player.
|
|
/// The value does not include the value of Gold and ranges from
|
|
/// 0 to 2,147,483,647 by default.
|
|
/// One Platinum represents the value of CurrencyThreshold in Gold.
|
|
/// </summary>
|
|
[SerializableField(7, setter: "private")]
|
|
[SerializedCommandProperty(AccessLevel.Administrator)]
|
|
public int _totalPlat;
|
|
|
|
private Mobile[] _mobiles;
|
|
|
|
[SerializableProperty(9)]
|
|
public List<AccountComment> Comments
|
|
{
|
|
get => _comments ??= [];
|
|
private set
|
|
{
|
|
_comments = value;
|
|
this.MarkDirty();
|
|
}
|
|
}
|
|
|
|
[SerializableProperty(10)]
|
|
public List<AccountTag> Tags
|
|
{
|
|
get => _tags ??= [];
|
|
private set
|
|
{
|
|
_tags = value;
|
|
this.MarkDirty();
|
|
}
|
|
}
|
|
|
|
[SerializableField(11)]
|
|
private IPAddress[] _loginIPs;
|
|
|
|
/// <summary>
|
|
/// Gets the total game time of this account, also considering the game time of characters
|
|
/// that have been deleted.
|
|
/// </summary>
|
|
[SerializableProperty(12)]
|
|
public TimeSpan TotalGameTime
|
|
{
|
|
get
|
|
{
|
|
for (var i = 0; i < _mobiles.Length; i++)
|
|
{
|
|
if (_mobiles[i] is PlayerMobile m && m.NetState != null)
|
|
{
|
|
return _totalGameTime + (Core.Now - m.SessionStart);
|
|
}
|
|
}
|
|
|
|
return _totalGameTime;
|
|
}
|
|
private set
|
|
{
|
|
_totalGameTime = value;
|
|
this.MarkDirty();
|
|
}
|
|
}
|
|
|
|
[SerializableField(13)]
|
|
[SerializedCommandProperty(AccessLevel.Administrator)]
|
|
private string _email;
|
|
|
|
private Timer m_YoungTimer;
|
|
|
|
public Account(string username, string password) : this(Accounts.NewAccount)
|
|
{
|
|
_username = username;
|
|
|
|
SetPassword(password);
|
|
|
|
_accessLevel = AccessLevel.Player;
|
|
|
|
_lastLogin = Core.Now;
|
|
_totalGameTime = TimeSpan.Zero;
|
|
|
|
_mobiles = new Mobile[7];
|
|
|
|
_loginIPs = [];
|
|
|
|
Accounts.Add(this);
|
|
this.MarkDirty();
|
|
}
|
|
|
|
public Account(XmlElement node)
|
|
{
|
|
Serial = Accounts.NewAccount;
|
|
|
|
_username = Utility.GetText(node["username"], "empty");
|
|
|
|
Enum.TryParse(Utility.GetText(node["passwordAlgorithm"], null), true, out _passwordAlgorithm);
|
|
|
|
// Backward compatibility with RunUO/ServUO
|
|
if (_passwordAlgorithm == PasswordProtectionAlgorithm.None)
|
|
{
|
|
var upgraded =
|
|
UpgradePassword(
|
|
Utility.GetText(node["newSecureCryptPassword"], null),
|
|
PasswordProtectionAlgorithm.SHA2
|
|
) ||
|
|
UpgradePassword(Utility.GetText(node["newCryptPassword"], null), PasswordProtectionAlgorithm.SHA1) ||
|
|
UpgradePassword(Utility.GetText(node["cryptPassword"], null), PasswordProtectionAlgorithm.MD5);
|
|
|
|
// Automatically upgrade plain passwords to current algorithm.
|
|
if (!upgraded)
|
|
{
|
|
SetPassword(Utility.GetText(node["password"], null));
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_password = Utility.GetText(node["password"], null);
|
|
}
|
|
|
|
Enum.TryParse(Utility.GetText(node["accessLevel"], "Player"), true, out _accessLevel);
|
|
_flags = Utility.GetXMLInt32(Utility.GetText(node["flags"], "0"), 0);
|
|
Created = Utility.GetXMLDateTime(Utility.GetText(node["created"], null), Core.Now);
|
|
_lastLogin = Utility.GetXMLDateTime(Utility.GetText(node["lastLogin"], null), Core.Now);
|
|
|
|
_totalGold = Utility.GetXMLInt32(Utility.GetText(node["totalGold"], "0"), 0);
|
|
_totalPlat = Utility.GetXMLInt32(Utility.GetText(node["totalPlat"], "0"), 0);
|
|
|
|
_mobiles = LoadMobiles(node);
|
|
_comments = LoadComments(node);
|
|
_tags = LoadTags(node);
|
|
_loginIPs = LoadAddressList(node);
|
|
|
|
for (var i = 0; i < _mobiles.Length; ++i)
|
|
{
|
|
if (_mobiles[i] != null)
|
|
{
|
|
_mobiles[i].Account = this;
|
|
}
|
|
}
|
|
|
|
var totalGameTime = Utility.GetXMLTimeSpan(Utility.GetText(node["totalGameTime"], null), TimeSpan.Zero);
|
|
if (totalGameTime == TimeSpan.Zero)
|
|
{
|
|
for (var i = 0; i < _mobiles.Length; i++)
|
|
{
|
|
if (_mobiles[i] is PlayerMobile m)
|
|
{
|
|
totalGameTime += m.GameTime;
|
|
}
|
|
}
|
|
}
|
|
|
|
_totalGameTime = totalGameTime;
|
|
|
|
if (Young)
|
|
{
|
|
CheckYoung();
|
|
}
|
|
|
|
Accounts.Add(this);
|
|
this.MarkDirty();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Object detailing information about the hardware of the last person to log into this account
|
|
/// </summary>
|
|
public HardwareInfo HardwareInfo { get; set; }
|
|
|
|
/// <summary>
|
|
/// Gets or sets a flag indicating if this account is banned.
|
|
/// </summary>
|
|
public bool Banned
|
|
{
|
|
get
|
|
{
|
|
var isBanned = GetFlag(0);
|
|
|
|
if (!isBanned)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (GetBanTags(out var banTime, out var banDuration))
|
|
{
|
|
if (banDuration != TimeSpan.MaxValue && Core.Now >= banTime + banDuration)
|
|
{
|
|
SetUnspecifiedBan(null); // clear
|
|
Banned = false;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
set => SetFlag(0, value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets or sets a flag indicating if the characters created on this account will have the young status.
|
|
/// </summary>
|
|
public bool Young
|
|
{
|
|
get => ContentFeatureFlags.YoungPlayerSystem && !GetFlag(1);
|
|
set
|
|
{
|
|
SetFlag(1, !value);
|
|
|
|
m_YoungTimer?.Stop();
|
|
m_YoungTimer = null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// An account is considered inactive based upon LastLogin and InactiveDuration. If the account is empty, it is based upon
|
|
/// EmptyInactiveDuration
|
|
/// </summary>
|
|
public bool Inactive
|
|
{
|
|
get
|
|
{
|
|
if (AccessLevel != AccessLevel.Player)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var inactiveLength = Core.Now - _lastLogin;
|
|
|
|
return inactiveLength > (Count == 0 ? EmptyInactiveDuration : InactiveDuration);
|
|
}
|
|
}
|
|
|
|
public TimeSpan AccountAge => Core.Now - Created;
|
|
|
|
[CommandProperty(AccessLevel.GameMaster, readOnly: true)]
|
|
public DateTime Created { get; set; } = Core.Now;
|
|
|
|
public Serial Serial { get; set; }
|
|
|
|
[AfterDeserialization(false)]
|
|
private void AfterDeserialization()
|
|
{
|
|
if (_comments?.Count == 0)
|
|
{
|
|
_comments = null;
|
|
}
|
|
|
|
if (_tags?.Count == 0)
|
|
{
|
|
_tags = null;
|
|
}
|
|
|
|
for (var i = 0; i < _mobiles.Length; ++i)
|
|
{
|
|
if (_mobiles[i] != null)
|
|
{
|
|
_mobiles[i].Account = this;
|
|
}
|
|
}
|
|
|
|
if (_totalGameTime == TimeSpan.Zero)
|
|
{
|
|
for (var i = 0; i < _mobiles.Length; i++)
|
|
{
|
|
if (_mobiles[i] is PlayerMobile m)
|
|
{
|
|
_totalGameTime += m.GameTime;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (Young)
|
|
{
|
|
CheckYoung();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deletes the account, all characters of the account, and all houses of those characters
|
|
/// </summary>
|
|
public void Delete()
|
|
{
|
|
for (var i = 0; i < Length; ++i)
|
|
{
|
|
var m = this[i];
|
|
|
|
if (m == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var list = BaseHouse.GetHouses(m);
|
|
|
|
for (var j = 0; j < list.Count; ++j)
|
|
{
|
|
list[j].Delete();
|
|
}
|
|
|
|
m.Delete();
|
|
|
|
m.Account = null;
|
|
_mobiles[i] = null;
|
|
}
|
|
|
|
if (_loginIPs.Length != 0 && AccountHandler.IPTable.ContainsKey(_loginIPs[0]))
|
|
{
|
|
--AccountHandler.IPTable[_loginIPs[0]];
|
|
}
|
|
|
|
Deleted = true;
|
|
Accounts.Remove(this);
|
|
}
|
|
|
|
public bool Deleted { get; private set; }
|
|
|
|
public bool TrySetUsername(string username)
|
|
{
|
|
if (username == _username || Accounts.GetAccount(username) != null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
Accounts.Remove(this);
|
|
Username = username;
|
|
Accounts.Add(this);
|
|
return true;
|
|
}
|
|
|
|
public void SetPassword(string plainPassword)
|
|
{
|
|
var phrase = _passwordAlgorithm is PasswordProtectionAlgorithm.SHA1 or PasswordProtectionAlgorithm.SHA2
|
|
? $"{_username}{plainPassword}"
|
|
: plainPassword;
|
|
|
|
Password = AccountSecurity.CurrentPasswordProtection.EncryptPassword(phrase);
|
|
PasswordAlgorithm = AccountSecurity.CurrentAlgorithm;
|
|
}
|
|
|
|
public bool CheckPassword(string plainPassword)
|
|
{
|
|
var phrase = _passwordAlgorithm is PasswordProtectionAlgorithm.SHA1 or PasswordProtectionAlgorithm.SHA2
|
|
? $"{_username}{plainPassword}"
|
|
: plainPassword;
|
|
|
|
var ok = AccountSecurity.GetPasswordProtection(_passwordAlgorithm).ValidatePassword(Password, phrase);
|
|
if (!ok)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// Upgrade the password protection in case we change the algorithm
|
|
if (_passwordAlgorithm != AccountSecurity.CurrentAlgorithm)
|
|
{
|
|
SetPassword(plainPassword);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the current number of characters on this account.
|
|
/// </summary>
|
|
public int Count
|
|
{
|
|
get
|
|
{
|
|
var count = 0;
|
|
|
|
for (var i = 0; i < Length; i++)
|
|
{
|
|
if (this[i] != null)
|
|
{
|
|
count++;
|
|
}
|
|
}
|
|
|
|
return count;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the maximum amount of characters allowed to be created on this account. Values other than 1, 5, 6, or 7 are not
|
|
/// supported by the client.
|
|
/// </summary>
|
|
public int Limit => Core.SA ? 7 : Core.AOS ? 6 : 5;
|
|
|
|
/// <summary>
|
|
/// Gets the maximum amount of characters that this account can hold.
|
|
/// </summary>
|
|
public int Length => _mobiles.Length;
|
|
|
|
/// <summary>
|
|
/// Gets or sets the character at a specified index for this account. Out of bound index values are handled; null returned
|
|
/// for get, ignored for set.
|
|
/// </summary>
|
|
public Mobile this[int index]
|
|
{
|
|
get
|
|
{
|
|
if (index >= 0 && index < _mobiles.Length)
|
|
{
|
|
var m = _mobiles[index];
|
|
|
|
if (m?.Deleted != true)
|
|
{
|
|
return m;
|
|
}
|
|
|
|
// This is the only place that clears a mobile for garbage collection
|
|
// outside of an entire account deletion.
|
|
m.Account = null;
|
|
_mobiles[index] = null;
|
|
this.MarkDirty();
|
|
}
|
|
|
|
return null;
|
|
}
|
|
set
|
|
{
|
|
if (index >= 0 && index < _mobiles.Length)
|
|
{
|
|
if (_mobiles[index] != null)
|
|
{
|
|
_mobiles[index].Account = null;
|
|
}
|
|
|
|
_mobiles[index] = value;
|
|
this.MarkDirty();
|
|
|
|
if (_mobiles[index] != null)
|
|
{
|
|
_mobiles[index].Account = this;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public int CompareTo(IAccount other) => string.CompareOrdinal(Username, other?.Username);
|
|
|
|
/// <summary>
|
|
/// Attempts to deposit the given amount of Gold into this account.
|
|
/// If the given amount is greater than the CurrencyThreshold,
|
|
/// Platinum will be deposited to offset the difference.
|
|
/// </summary>
|
|
/// <param name="amount">Amount to deposit.</param>
|
|
/// <returns>True if successful, false if amount given is less than or equal to zero.</returns>
|
|
public bool DepositGold(int amount)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var plat = Math.DivRem(amount, AccountGold.CurrencyThreshold, out var gold);
|
|
TotalPlat += plat;
|
|
TotalGold += gold;
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Attempts to deposit the given amount of Platinum into this account.
|
|
/// </summary>
|
|
/// <param name="amount">Amount to deposit.</param>
|
|
/// <returns>True if successful, false if amount given is less than or equal to zero.</returns>
|
|
public bool DepositPlat(int amount)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
TotalPlat += amount;
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Attempts to withdraw the given amount of Gold from this account.
|
|
/// If the given amount is greater than the CurrencyThreshold,
|
|
/// Platinum will be withdrawn to offset the difference.
|
|
/// </summary>
|
|
/// <param name="amount">Amount to withdraw.</param>
|
|
/// <returns>True if successful, false if balance was too low.</returns>
|
|
public bool WithdrawGold(int amount)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (amount > _totalGold)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
TotalGold -= amount;
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Attempts to withdraw the given amount of Platinum from this account.
|
|
/// </summary>
|
|
/// <param name="amount">Amount to withdraw.</param>
|
|
/// <returns>True if successful, false if balance was too low.</returns>
|
|
public bool WithdrawPlat(int amount)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (amount > _totalPlat)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
TotalPlat -= amount;
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns total gold inclusive of platinum.
|
|
/// This is strictly for backwards compatibility
|
|
/// </summary>
|
|
/// <returns>Total gold, capped at Int32.MaxValue</returns>
|
|
public long GetTotalGold() => _totalGold + _totalPlat * AccountGold.CurrencyThreshold;
|
|
|
|
public int CompareTo(Account other) => string.CompareOrdinal(_username, other?._username);
|
|
|
|
/// <summary>
|
|
/// Gets the value of a specific flag in the Flags bitfield.
|
|
/// </summary>
|
|
/// <param name="index">The zero-based flag index.</param>
|
|
public bool GetFlag(int index) => (_flags & (1 << index)) != 0;
|
|
|
|
/// <summary>
|
|
/// Sets the value of a specific flag in the Flags bitfield.
|
|
/// </summary>
|
|
/// <param name="index">The zero-based flag index.</param>
|
|
/// <param name="value">The value to set.</param>
|
|
public void SetFlag(int index, bool value)
|
|
{
|
|
if (value)
|
|
{
|
|
Flags |= 1 << index;
|
|
}
|
|
else
|
|
{
|
|
Flags &= ~(1 << index);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a new tag to this account. This method does not check for duplicate names.
|
|
/// </summary>
|
|
/// <param name="name">New tag name.</param>
|
|
/// <param name="value">New tag value.</param>
|
|
public void AddTag(string name, string value)
|
|
{
|
|
Tags.Add(new AccountTag(name, value));
|
|
this.MarkDirty();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes all tags with the specified name from this account.
|
|
/// </summary>
|
|
/// <param name="name">Tag name to remove.</param>
|
|
public void RemoveTag(string name)
|
|
{
|
|
if (_tags == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
for (var i = _tags.Count - 1; i >= 0; --i)
|
|
{
|
|
if (i >= _tags.Count)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var tag = _tags[i];
|
|
|
|
if (tag.Name == name)
|
|
{
|
|
_tags.RemoveAt(i);
|
|
this.MarkDirty();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Modifies an existing tag or adds a new tag if no tag exists.
|
|
/// </summary>
|
|
/// <param name="name">Tag name.</param>
|
|
/// <param name="value">Tag value.</param>
|
|
public void SetTag(string name, string value)
|
|
{
|
|
for (var i = 0; i < Tags.Count; ++i)
|
|
{
|
|
var tag = _tags[i];
|
|
|
|
if (tag.Name == name)
|
|
{
|
|
tag.Value = value;
|
|
this.MarkDirty();
|
|
return;
|
|
}
|
|
}
|
|
|
|
AddTag(name, value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the value of a tag -or- null if there are no tags with the specified name.
|
|
/// </summary>
|
|
/// <param name="name">Name of the desired tag value.</param>
|
|
public string GetTag(string name)
|
|
{
|
|
for (var i = 0; i < Tags.Count; ++i)
|
|
{
|
|
var tag = _tags[i];
|
|
|
|
if (tag.Name == name)
|
|
{
|
|
return tag.Value;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public void SetUnspecifiedBan(Mobile from)
|
|
{
|
|
SetBanTags(from, DateTime.MinValue, TimeSpan.Zero);
|
|
}
|
|
|
|
public void SetBanTags(Mobile from, DateTime banTime, TimeSpan banDuration)
|
|
{
|
|
if (from == null)
|
|
{
|
|
RemoveTag("BanDealer");
|
|
}
|
|
else
|
|
{
|
|
SetTag("BanDealer", from.ToString());
|
|
}
|
|
|
|
if (banTime == DateTime.MinValue)
|
|
{
|
|
RemoveTag("BanTime");
|
|
}
|
|
else
|
|
{
|
|
SetTag("BanTime", XmlConvert.ToString(banTime, XmlDateTimeSerializationMode.Utc));
|
|
}
|
|
|
|
if (banDuration == TimeSpan.Zero)
|
|
{
|
|
RemoveTag("BanDuration");
|
|
}
|
|
else
|
|
{
|
|
SetTag("BanDuration", banDuration.ToString());
|
|
}
|
|
}
|
|
|
|
public bool GetBanTags(out DateTime banTime, out TimeSpan banDuration)
|
|
{
|
|
var tagDuration = GetTag("BanDuration");
|
|
|
|
banTime = Utility.GetXMLDateTime(GetTag("BanTime"), DateTime.MinValue);
|
|
|
|
if (tagDuration == "Infinite")
|
|
{
|
|
banDuration = TimeSpan.MaxValue;
|
|
}
|
|
else if (tagDuration != null)
|
|
{
|
|
banDuration = Utility.ToTimeSpan(tagDuration);
|
|
}
|
|
else
|
|
{
|
|
banDuration = TimeSpan.Zero;
|
|
}
|
|
|
|
return banTime != DateTime.MinValue && banDuration != TimeSpan.Zero;
|
|
}
|
|
|
|
public static void Initialize()
|
|
{
|
|
EventSink.Connected += EventSink_Connected;
|
|
EventSink.Disconnected += EventSink_Disconnected;
|
|
}
|
|
|
|
private static void EventSink_Connected(Mobile m)
|
|
{
|
|
if (m.Account is not Account acc)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (acc.Young && acc.m_YoungTimer == null)
|
|
{
|
|
acc.m_YoungTimer = new YoungTimer(acc);
|
|
acc.m_YoungTimer.Start();
|
|
}
|
|
}
|
|
|
|
private static void EventSink_Disconnected(Mobile m)
|
|
{
|
|
if (m.Account is not Account acc)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (acc.m_YoungTimer != null)
|
|
{
|
|
acc.m_YoungTimer.Stop();
|
|
acc.m_YoungTimer = null;
|
|
}
|
|
|
|
if (m is not PlayerMobile pm)
|
|
{
|
|
return;
|
|
}
|
|
|
|
acc.TotalGameTime += Core.Now - pm.SessionStart;
|
|
}
|
|
|
|
[OnEvent(nameof(PlayerMobile.PlayerLoginEvent))]
|
|
public static void OnLogin(PlayerMobile pm)
|
|
{
|
|
if (pm.Account is not Account acc || !pm.Young || !acc.Young)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var ts = YoungDuration - acc.TotalGameTime;
|
|
var hours = Math.Max((int)ts.TotalHours, 0);
|
|
|
|
if (hours == 1)
|
|
{
|
|
pm.SendAsciiMessage($"You will enjoy the benefits and relatively safe status of a young player for {hours} more hour.");
|
|
}
|
|
else
|
|
{
|
|
pm.SendAsciiMessage($"You will enjoy the benefits and relatively safe status of a young player for {hours} more hours.");
|
|
}
|
|
}
|
|
|
|
public void RemoveYoungStatus(int message)
|
|
{
|
|
Young = false;
|
|
|
|
for (var i = 0; i < _mobiles.Length; i++)
|
|
{
|
|
if (_mobiles[i] is PlayerMobile { Young: true } m)
|
|
{
|
|
m.Young = false;
|
|
|
|
if (m.NetState != null)
|
|
{
|
|
if (message > 0)
|
|
{
|
|
m.SendLocalizedMessage(message);
|
|
}
|
|
|
|
// You are no longer considered a young player of Ultima Online,
|
|
// and are no longer subject to the limitations and benefits of being in that caste.
|
|
m.SendLocalizedMessage(1019039);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public void CheckYoung()
|
|
{
|
|
if (TotalGameTime >= YoungDuration)
|
|
{
|
|
// You are old enough to be considered an adult, and have outgrown your status as a young player!
|
|
RemoveYoungStatus(1019038);
|
|
}
|
|
}
|
|
|
|
private bool UpgradePassword(string password, PasswordProtectionAlgorithm algorithm)
|
|
{
|
|
if (password == null || algorithm < _passwordAlgorithm)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
PasswordAlgorithm = algorithm;
|
|
Password = password.ReplaceOrdinal("-", string.Empty);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deserializes a list of IPAddress values from an xml element.
|
|
/// </summary>
|
|
/// <param name="node">The XmlElement from which to deserialize.</param>
|
|
/// <returns>Address list. Value will never be null.</returns>
|
|
private static IPAddress[] LoadAddressList(XmlElement node)
|
|
{
|
|
IPAddress[] list;
|
|
var addressList = node["addressList"];
|
|
|
|
if (addressList != null)
|
|
{
|
|
var count = Utility.GetXMLInt32(Utility.GetAttribute(addressList, "count", "0"), 0);
|
|
|
|
list = new IPAddress[count];
|
|
|
|
count = 0;
|
|
|
|
foreach (XmlElement ip in addressList.GetElementsByTagName("ip"))
|
|
{
|
|
if (count < list.Length)
|
|
{
|
|
if (IPAddress.TryParse(Utility.GetText(ip, null), out var address))
|
|
{
|
|
list[count] = Utility.Intern(address);
|
|
count++;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (count != list.Length)
|
|
{
|
|
var old = list;
|
|
list = new IPAddress[count];
|
|
|
|
for (var i = 0; i < count && i < old.Length; ++i)
|
|
{
|
|
list[i] = old[i];
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
list = [];
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deserializes a list of Mobile instances from an xml element.
|
|
/// </summary>
|
|
/// <param name="node">The XmlElement instance from which to deserialize.</param>
|
|
/// <returns>Mobile list. Value will never be null.</returns>
|
|
private static Mobile[] LoadMobiles(XmlElement node)
|
|
{
|
|
var list = new Mobile[7];
|
|
var chars = node["chars"];
|
|
|
|
// int length = Accounts.GetInt32( Accounts.GetAttribute( chars, "length", "6" ), 6 );
|
|
// list = new Mobile[length];
|
|
// Above is legacy, no longer used
|
|
|
|
if (chars != null)
|
|
{
|
|
foreach (XmlElement ele in chars.GetElementsByTagName("char"))
|
|
{
|
|
try
|
|
{
|
|
var index = Utility.GetXMLInt32(Utility.GetAttribute(ele, "index", "0"), 0);
|
|
var serial = (Serial)Utility.GetXMLUInt32(Utility.GetText(ele, "0"), 0);
|
|
|
|
if (index >= 0 && index < list.Length)
|
|
{
|
|
list[index] = World.FindMobile(serial);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// ignored
|
|
}
|
|
}
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deserializes a list of AccountComment instances from an xml element.
|
|
/// </summary>
|
|
/// <param name="node">The XmlElement from which to deserialize.</param>
|
|
/// <returns>Comment list. Value will never be null.</returns>
|
|
private static List<AccountComment> LoadComments(XmlElement node)
|
|
{
|
|
List<AccountComment> list = null;
|
|
var comments = node["comments"];
|
|
|
|
if (comments != null)
|
|
{
|
|
list = [];
|
|
|
|
foreach (XmlElement comment in comments.GetElementsByTagName("comment"))
|
|
{
|
|
try
|
|
{
|
|
list.Add(new AccountComment(comment));
|
|
}
|
|
catch
|
|
{
|
|
// ignored
|
|
}
|
|
}
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deserializes a list of AccountTag instances from an xml element.
|
|
/// </summary>
|
|
/// <param name="node">The XmlElement from which to deserialize.</param>
|
|
/// <returns>Tag list. Value will never be null.</returns>
|
|
private static List<AccountTag> LoadTags(XmlElement node)
|
|
{
|
|
List<AccountTag> list = null;
|
|
var tags = node["tags"];
|
|
|
|
if (tags != null)
|
|
{
|
|
list = [];
|
|
|
|
foreach (XmlElement tag in tags.GetElementsByTagName("tag"))
|
|
{
|
|
try
|
|
{
|
|
list.Add(new AccountTag(tag));
|
|
}
|
|
catch
|
|
{
|
|
// ignored
|
|
}
|
|
}
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if a specific NetState is allowed access to this account.
|
|
/// </summary>
|
|
/// <param name="ns">NetState instance to check.</param>
|
|
/// <returns>True if allowed, false if not.</returns>
|
|
public bool HasAccess(NetState ns) => ns != null && HasAccess(ns.Address);
|
|
|
|
public bool HasAccess(IPAddress ipAddress)
|
|
{
|
|
var level = AccountHandler.LockdownLevel;
|
|
|
|
if (level <= AccessLevel.Player || _accessLevel >= level)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
for (var i = 0; i < Length; ++i)
|
|
{
|
|
var m = this[i];
|
|
|
|
if (m?.AccessLevel >= level)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Records the IP address of 'ns' in its 'LoginIPs' list.
|
|
/// </summary>
|
|
/// <param name="ns">NetState instance to record.</param>
|
|
public void LogAccess(NetState ns)
|
|
{
|
|
if (ns != null)
|
|
{
|
|
LogAccess(ns.Address);
|
|
}
|
|
}
|
|
|
|
public void LogAccess(IPAddress ipAddress)
|
|
{
|
|
if (_loginIPs.Length == 0)
|
|
{
|
|
AccountHandler.IPTable.TryGetValue(ipAddress, out var result);
|
|
AccountHandler.IPTable[ipAddress] = result + 1;
|
|
}
|
|
|
|
var contains = false;
|
|
|
|
for (var i = 0; !contains && i < _loginIPs.Length; ++i)
|
|
{
|
|
contains = _loginIPs[i].Equals(ipAddress);
|
|
}
|
|
|
|
if (contains)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var old = _loginIPs;
|
|
LoginIPs = new IPAddress[old.Length + 1];
|
|
|
|
for (var i = 0; i < old.Length; ++i)
|
|
{
|
|
LoginIPs[i] = old[i];
|
|
}
|
|
|
|
LoginIPs[old.Length] = ipAddress;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if a specific NetState is allowed access to this account. If true, the NetState IPAddress is added to the address
|
|
/// list.
|
|
/// </summary>
|
|
/// <param name="ns">NetState instance to check.</param>
|
|
/// <returns>True if allowed, false if not.</returns>
|
|
public bool CheckAccess(NetState ns) => ns != null && CheckAccess(ns.Address);
|
|
|
|
public bool CheckAccess(IPAddress ipAddress)
|
|
{
|
|
var hasAccess = HasAccess(ipAddress);
|
|
|
|
if (hasAccess)
|
|
{
|
|
LogAccess(ipAddress);
|
|
}
|
|
|
|
return hasAccess;
|
|
}
|
|
|
|
public override string ToString() => _username;
|
|
|
|
private class YoungTimer : Timer
|
|
{
|
|
private readonly Account m_Account;
|
|
|
|
public YoungTimer(Account account)
|
|
: base(TimeSpan.FromMinutes(1.0), TimeSpan.FromMinutes(1.0))
|
|
{
|
|
m_Account = account;
|
|
}
|
|
|
|
protected override void OnTick()
|
|
{
|
|
m_Account.CheckYoung();
|
|
}
|
|
}
|
|
|
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
|
public Enumerator GetEnumerator() => new(_mobiles);
|
|
|
|
[SerializableProperty(8, useField: nameof(_mobiles))]
|
|
public Enumerator Mobiles
|
|
{
|
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
|
get => GetEnumerator();
|
|
}
|
|
|
|
public ref struct Enumerator
|
|
{
|
|
private readonly Mobile[] _mobiles;
|
|
private int _index;
|
|
private Mobile _current;
|
|
|
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
|
internal Enumerator(Mobile[] mobs)
|
|
{
|
|
_mobiles = mobs;
|
|
_index = 0;
|
|
_current = default;
|
|
}
|
|
|
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
|
public bool MoveNext()
|
|
{
|
|
var localList = _mobiles;
|
|
|
|
while ((uint)_index < (uint)localList.Length)
|
|
{
|
|
_current = localList[_index++];
|
|
if (_current?.Deleted == false)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public Mobile Current
|
|
{
|
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
|
get => _current;
|
|
}
|
|
}
|
|
}
|