Fixes formatting (#200)

This commit is contained in:
Kamron Batman 2020-08-25 18:53:35 -07:00 • committed by GitHub
parent 1f651992d7
commit 86b7b3aed1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
209 changed files with 51326 additions and 50397 deletions

View file

@ -25,178 +25,179 @@ using System.IO;
namespace Server
{
public class AggressorInfo {
private static readonly Queue<AggressorInfo> m_Pool = new Queue<AggressorInfo>();
private Mobile m_Attacker, m_Defender;
private bool m_CanReportMurder;
private bool m_CriminalAggression;
private DateTime m_LastCombatTime;
private bool m_Queued;
private bool m_Reported;
private AggressorInfo(Mobile attacker, Mobile defender, bool criminal)
public class AggressorInfo
{
m_Attacker = attacker;
m_Defender = defender;
private static readonly Queue<AggressorInfo> m_Pool = new Queue<AggressorInfo>();
private Mobile m_Attacker, m_Defender;
private bool m_CanReportMurder;
private bool m_CriminalAggression;
private DateTime m_LastCombatTime;
m_CanReportMurder = criminal;
m_CriminalAggression = criminal;
private bool m_Queued;
private bool m_Reported;
Refresh();
private AggressorInfo(Mobile attacker, Mobile defender, bool criminal)
{
m_Attacker = attacker;
m_Defender = defender;
m_CanReportMurder = criminal;
m_CriminalAggression = criminal;
Refresh();
}
public static TimeSpan ExpireDelay { get; set; } = TimeSpan.FromMinutes(2.0);
public bool Expired
{
get
{
if (m_Queued)
DumpAccess();
return m_Attacker.Deleted || m_Defender.Deleted || DateTime.UtcNow >= m_LastCombatTime + ExpireDelay;
}
}
public bool CriminalAggression
{
get
{
if (m_Queued)
DumpAccess();
return m_CriminalAggression;
}
set
{
if (m_Queued)
DumpAccess();
m_CriminalAggression = value;
}
}
public Mobile Attacker
{
get
{
if (m_Queued)
DumpAccess();
return m_Attacker;
}
}
public Mobile Defender
{
get
{
if (m_Queued)
DumpAccess();
return m_Defender;
}
}
public DateTime LastCombatTime
{
get
{
if (m_Queued)
DumpAccess();
return m_LastCombatTime;
}
}
public bool Reported
{
get
{
if (m_Queued)
DumpAccess();
return m_Reported;
}
set
{
if (m_Queued)
DumpAccess();
m_Reported = value;
}
}
public bool CanReportMurder
{
get
{
if (m_Queued)
DumpAccess();
return m_CanReportMurder;
}
set
{
if (m_Queued)
DumpAccess();
m_CanReportMurder = value;
}
}
public static AggressorInfo Create(Mobile attacker, Mobile defender, bool criminal)
{
AggressorInfo info;
if (m_Pool.Count > 0)
{
info = m_Pool.Dequeue();
info.m_Attacker = attacker;
info.m_Defender = defender;
info.m_CanReportMurder = criminal;
info.m_CriminalAggression = criminal;
info.m_Queued = false;
info.Refresh();
}
else
{
info = new AggressorInfo(attacker, defender, criminal);
}
return info;
}
public void Free()
{
if (m_Queued)
return;
m_Queued = true;
m_Pool.Enqueue(this);
}
public static void DumpAccess()
{
using var op = new StreamWriter("warnings.log", true);
op.WriteLine("Warning: Access to queued AggressorInfo:");
op.WriteLine(new StackTrace());
op.WriteLine();
op.WriteLine();
}
public void Refresh()
{
if (m_Queued)
DumpAccess();
m_LastCombatTime = DateTime.UtcNow;
m_Reported = false;
}
}
public static TimeSpan ExpireDelay { get; set; } = TimeSpan.FromMinutes(2.0);
public bool Expired
{
get
{
if (m_Queued)
DumpAccess();
return m_Attacker.Deleted || m_Defender.Deleted || DateTime.UtcNow >= m_LastCombatTime + ExpireDelay;
}
}
public bool CriminalAggression
{
get
{
if (m_Queued)
DumpAccess();
return m_CriminalAggression;
}
set
{
if (m_Queued)
DumpAccess();
m_CriminalAggression = value;
}
}
public Mobile Attacker
{
get
{
if (m_Queued)
DumpAccess();
return m_Attacker;
}
}
public Mobile Defender
{
get
{
if (m_Queued)
DumpAccess();
return m_Defender;
}
}
public DateTime LastCombatTime
{
get
{
if (m_Queued)
DumpAccess();
return m_LastCombatTime;
}
}
public bool Reported
{
get
{
if (m_Queued)
DumpAccess();
return m_Reported;
}
set
{
if (m_Queued)
DumpAccess();
m_Reported = value;
}
}
public bool CanReportMurder
{
get
{
if (m_Queued)
DumpAccess();
return m_CanReportMurder;
}
set
{
if (m_Queued)
DumpAccess();
m_CanReportMurder = value;
}
}
public static AggressorInfo Create(Mobile attacker, Mobile defender, bool criminal)
{
AggressorInfo info;
if (m_Pool.Count > 0)
{
info = m_Pool.Dequeue();
info.m_Attacker = attacker;
info.m_Defender = defender;
info.m_CanReportMurder = criminal;
info.m_CriminalAggression = criminal;
info.m_Queued = false;
info.Refresh();
}
else
{
info = new AggressorInfo(attacker, defender, criminal);
}
return info;
}
public void Free()
{
if (m_Queued)
return;
m_Queued = true;
m_Pool.Enqueue(this);
}
public static void DumpAccess()
{
using var op = new StreamWriter("warnings.log", true);
op.WriteLine("Warning: Access to queued AggressorInfo:");
op.WriteLine(new StackTrace());
op.WriteLine();
op.WriteLine();
}
public void Refresh()
{
if (m_Queued)
DumpAccess();
m_LastCombatTime = DateTime.UtcNow;
m_Reported = false;
}
}
}

View file

@ -1,169 +1,177 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AssemblyHandler.cs - Created: 2019/08/02 - Updated: 2020/05/09 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace Server
{
public static class AssemblyHandler
{
private static readonly Dictionary<Assembly, TypeCache> m_TypeCaches = new Dictionary<Assembly, TypeCache>();
private static TypeCache m_NullCache;
public static Assembly[] Assemblies { get; set; }
public static void LoadScripts(string[] files)
{
var assemblies = new Assembly[files.Length];
for (int i = 0; i < files.Length; i++) assemblies[i] = AssemblyLoadContext.Default.LoadFromAssemblyPath(files[i]);
Assemblies = assemblies;
}
public static void Invoke(string method)
{
var invoke = new List<MethodInfo>();
for (var a = 0; a < Assemblies.Length; ++a)
invoke.AddRange(Assemblies[a].GetTypes()
.Select(t => t.GetMethod(method, BindingFlags.Static | BindingFlags.Public)).Where(m => m != null));
invoke.Sort(new CallPriorityComparer());
for (var i = 0; i < invoke.Count; ++i)
invoke[i].Invoke(null, null);
}
public static TypeCache GetTypeCache(Assembly asm)
{
if (asm == null)
return m_NullCache ??= new TypeCache(null);
if (m_TypeCaches.TryGetValue(asm, out var c))
return c;
return m_TypeCaches[asm] = new TypeCache(asm);
}
public static Type FindFirstTypeForName(string name, bool ignoreCase = false, Func<Type, bool> predicate = null)
{
if (string.IsNullOrWhiteSpace(name)) return null;
var types = FindTypesByName(name, ignoreCase).ToList();
if (types.Count == 0)
return null;
if (predicate != null)
return types.FirstOrDefault(predicate);
if (types.Count == 1)
return types[0];
// Try to find the closest match if there is no predicate.
// Check for exact match of the FullName or Name
// Then check for case-insensitive match of FullName or Name
// Otherwise just return the first entry
var stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
return types.FirstOrDefault(x =>
stringComparer.Equals(x.FullName, name) || stringComparer.Equals(x.Name, name)) ??
types[0];
}
public static List<Type> FindTypesByName(string name, bool ignoreCase = false)
{
var types = new List<Type>();
if (ignoreCase)
name = name.ToLower();
for (var i = 0; i < Assemblies.Length; i++)
types.AddRange(GetTypeCache(Assemblies[i])[name]);
if (types.Count == 0)
types.AddRange(GetTypeCache(Core.Assembly)[name]);
return types;
}
public static string EnsureDirectory(string dir)
{
var path = Path.Combine(Core.BaseDirectory, dir);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
}
public class TypeCache
{
private readonly Dictionary<string, int[]> m_NameMap = new Dictionary<string, int[]>();
private readonly Type[] m_Types;
public IEnumerable<Type> Types => m_Types;
public IEnumerable<string> Names => m_NameMap.Keys;
public IEnumerable<Type> this[string name] =>
m_NameMap.TryGetValue(name, out var value) ? value.Select(x => m_Types[x]) : Array.Empty<Type>();
public TypeCache(Assembly asm)
{
m_Types = asm?.GetTypes() ?? Type.EmptyTypes;
var nameMap = new Dictionary<string, HashSet<int>>();
HashSet<int> refs;
Action<int, string> addToRefs = (index, key) =>
{
if (nameMap.TryGetValue(key, out refs))
{
refs.Add(index);
}
else
{
refs = new HashSet<int> { index };
nameMap.Add(key, refs);
}
};
var aliasType = typeof(TypeAliasAttribute);
for (var i = 0; i < m_Types.Length; i++)
{
var current = m_Types[i];
addToRefs(i, current.Name);
addToRefs(i, current.Name.ToLower());
addToRefs(i, current.FullName);
addToRefs(i, current.FullName?.ToLower());
if (current.GetCustomAttribute(aliasType, false) is TypeAliasAttribute alias)
for (var j = 0; j < alias.Aliases.Length; j++)
{
addToRefs(i, alias.Aliases[j]);
addToRefs(i, alias.Aliases[j].ToLower());
}
}
foreach (var (key, value) in nameMap)
m_NameMap[key] = value.ToArray();
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AssemblyHandler.cs - Created: 2019/08/02 - Updated: 2020/05/09 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace Server
{
public static class AssemblyHandler
{
private static readonly Dictionary<Assembly, TypeCache> m_TypeCaches = new Dictionary<Assembly, TypeCache>();
private static TypeCache m_NullCache;
public static Assembly[] Assemblies { get; set; }
public static void LoadScripts(string[] files)
{
var assemblies = new Assembly[files.Length];
for (var i = 0; i < files.Length; i++)
assemblies[i] = AssemblyLoadContext.Default.LoadFromAssemblyPath(files[i]);
Assemblies = assemblies;
}
public static void Invoke(string method)
{
var invoke = new List<MethodInfo>();
for (var a = 0; a < Assemblies.Length; ++a)
invoke.AddRange(
Assemblies[a]
.GetTypes()
.Select(t => t.GetMethod(method, BindingFlags.Static | BindingFlags.Public))
.Where(m => m != null)
);
invoke.Sort(new CallPriorityComparer());
for (var i = 0; i < invoke.Count; ++i)
invoke[i].Invoke(null, null);
}
public static TypeCache GetTypeCache(Assembly asm)
{
if (asm == null)
return m_NullCache ??= new TypeCache(null);
if (m_TypeCaches.TryGetValue(asm, out var c))
return c;
return m_TypeCaches[asm] = new TypeCache(asm);
}
public static Type FindFirstTypeForName(string name, bool ignoreCase = false, Func<Type, bool> predicate = null)
{
if (string.IsNullOrWhiteSpace(name)) return null;
var types = FindTypesByName(name, ignoreCase).ToList();
if (types.Count == 0)
return null;
if (predicate != null)
return types.FirstOrDefault(predicate);
if (types.Count == 1)
return types[0];
// Try to find the closest match if there is no predicate.
// Check for exact match of the FullName or Name
// Then check for case-insensitive match of FullName or Name
// Otherwise just return the first entry
var stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
return types.FirstOrDefault(
x =>
stringComparer.Equals(x.FullName, name) || stringComparer.Equals(x.Name, name)
) ??
types[0];
}
public static List<Type> FindTypesByName(string name, bool ignoreCase = false)
{
var types = new List<Type>();
if (ignoreCase)
name = name.ToLower();
for (var i = 0; i < Assemblies.Length; i++)
types.AddRange(GetTypeCache(Assemblies[i])[name]);
if (types.Count == 0)
types.AddRange(GetTypeCache(Core.Assembly)[name]);
return types;
}
public static string EnsureDirectory(string dir)
{
var path = Path.Combine(Core.BaseDirectory, dir);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
}
public class TypeCache
{
private readonly Dictionary<string, int[]> m_NameMap = new Dictionary<string, int[]>();
private readonly Type[] m_Types;
public TypeCache(Assembly asm)
{
m_Types = asm?.GetTypes() ?? Type.EmptyTypes;
var nameMap = new Dictionary<string, HashSet<int>>();
HashSet<int> refs;
Action<int, string> addToRefs = (index, key) =>
{
if (nameMap.TryGetValue(key, out refs))
{
refs.Add(index);
}
else
{
refs = new HashSet<int> { index };
nameMap.Add(key, refs);
}
};
var aliasType = typeof(TypeAliasAttribute);
for (var i = 0; i < m_Types.Length; i++)
{
var current = m_Types[i];
addToRefs(i, current.Name);
addToRefs(i, current.Name.ToLower());
addToRefs(i, current.FullName);
addToRefs(i, current.FullName?.ToLower());
if (current.GetCustomAttribute(aliasType, false) is TypeAliasAttribute alias)
for (var j = 0; j < alias.Aliases.Length; j++)
{
addToRefs(i, alias.Aliases[j]);
addToRefs(i, alias.Aliases[j].ToLower());
}
}
foreach (var (key, value) in nameMap)
m_NameMap[key] = value.ToArray();
}
public IEnumerable<Type> Types => m_Types;
public IEnumerable<string> Names => m_NameMap.Keys;
public IEnumerable<Type> this[string name] =>
m_NameMap.TryGetValue(name, out var value) ? value.Select(x => m_Types[x]) : Array.Empty<Type>();
}
}

View file

@ -1,152 +1,153 @@
/***************************************************************************
* Attributes.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Server
{
[AttributeUsage(AttributeTargets.Property)]
public class HueAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Property)]
public class BodyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class PropertyObjectAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class NoSortAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class CallPriorityAttribute : Attribute
{
public CallPriorityAttribute(int priority) => Priority = priority;
public int Priority { get; set; }
}
public class CallPriorityComparer : IComparer<MethodInfo>
{
public int Compare(MethodInfo x, MethodInfo y)
{
if (x == null && y == null)
return 0;
if (x == null)
return 1;
if (y == null)
return -1;
var xPriority = GetPriority(x);
var yPriority = GetPriority(y);
if (xPriority > yPriority)
return 1;
if (xPriority < yPriority)
return -1;
return 0;
}
private int GetPriority(MethodInfo mi)
{
var objs = mi.GetCustomAttributes(typeof(CallPriorityAttribute), true);
if (objs.Length == 0)
return 0;
if (!(objs[0] is CallPriorityAttribute attr))
return 0;
return attr.Priority;
}
}
[AttributeUsage(AttributeTargets.Class)]
public class TypeAliasAttribute : Attribute
{
public TypeAliasAttribute(params string[] aliases) => Aliases = aliases;
public string[] Aliases { get; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class ParsableAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public class CustomEnumAttribute : Attribute
{
public CustomEnumAttribute(string[] names) => Names = names;
public string[] Names { get; }
}
[AttributeUsage(AttributeTargets.Constructor)]
public class ConstructibleAttribute : Attribute
{
public ConstructibleAttribute() : this(AccessLevel.Player) // Lowest accesslevel for current functionality (Level determined by access to [add)
{
}
public ConstructibleAttribute(AccessLevel accessLevel) => AccessLevel = accessLevel;
public AccessLevel AccessLevel { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class CommandPropertyAttribute : Attribute
{
public CommandPropertyAttribute(AccessLevel level, bool readOnly)
{
ReadLevel = level;
ReadOnly = readOnly;
}
public CommandPropertyAttribute(AccessLevel level) : this(level, level)
{
}
public CommandPropertyAttribute(AccessLevel readLevel, AccessLevel writeLevel)
{
ReadLevel = readLevel;
WriteLevel = writeLevel;
}
public AccessLevel ReadLevel { get; }
public AccessLevel WriteLevel { get; }
public bool ReadOnly { get; }
}
}
/***************************************************************************
* Attributes.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Server
{
[AttributeUsage(AttributeTargets.Property)]
public class HueAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Property)]
public class BodyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class PropertyObjectAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class NoSortAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class CallPriorityAttribute : Attribute
{
public CallPriorityAttribute(int priority) => Priority = priority;
public int Priority { get; set; }
}
public class CallPriorityComparer : IComparer<MethodInfo>
{
public int Compare(MethodInfo x, MethodInfo y)
{
if (x == null && y == null)
return 0;
if (x == null)
return 1;
if (y == null)
return -1;
var xPriority = GetPriority(x);
var yPriority = GetPriority(y);
if (xPriority > yPriority)
return 1;
if (xPriority < yPriority)
return -1;
return 0;
}
private int GetPriority(MethodInfo mi)
{
var objs = mi.GetCustomAttributes(typeof(CallPriorityAttribute), true);
if (objs.Length == 0)
return 0;
if (!(objs[0] is CallPriorityAttribute attr))
return 0;
return attr.Priority;
}
}
[AttributeUsage(AttributeTargets.Class)]
public class TypeAliasAttribute : Attribute
{
public TypeAliasAttribute(params string[] aliases) => Aliases = aliases;
public string[] Aliases { get; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class ParsableAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public class CustomEnumAttribute : Attribute
{
public CustomEnumAttribute(string[] names) => Names = names;
public string[] Names { get; }
}
[AttributeUsage(AttributeTargets.Constructor)]
public class ConstructibleAttribute : Attribute
{
public ConstructibleAttribute() :
this(AccessLevel.Player) // Lowest accesslevel for current functionality (Level determined by access to [add)
{
}
public ConstructibleAttribute(AccessLevel accessLevel) => AccessLevel = accessLevel;
public AccessLevel AccessLevel { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class CommandPropertyAttribute : Attribute
{
public CommandPropertyAttribute(AccessLevel level, bool readOnly)
{
ReadLevel = level;
ReadOnly = readOnly;
}
public CommandPropertyAttribute(AccessLevel level) : this(level, level)
{
}
public CommandPropertyAttribute(AccessLevel readLevel, AccessLevel writeLevel)
{
ReadLevel = readLevel;
WriteLevel = writeLevel;
}
public AccessLevel ReadLevel { get; }
public AccessLevel WriteLevel { get; }
public bool ReadOnly { get; }
}
}

View file

@ -1,106 +1,106 @@
/***************************************************************************
* BaseVendor.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
namespace Server
{
public class BuyItemStateComparer : IComparer<BuyItemState>
{
public int Compare(BuyItemState l, BuyItemState r)
{
if (l == null && r == null) return 0;
if (l == null) return -1;
if (r == null) return 1;
return l.MySerial.CompareTo(r.MySerial);
}
}
public class BuyItemResponse
{
public BuyItemResponse(Serial serial, int amount)
{
Serial = serial;
Amount = amount;
}
public Serial Serial { get; }
public int Amount { get; }
}
public class SellItemResponse
{
public SellItemResponse(Item i, int amount)
{
Item = i;
Amount = amount;
}
public Item Item { get; }
public int Amount { get; }
}
public class SellItemState
{
public SellItemState(Item item, int price, string name)
{
Item = item;
Price = price;
Name = name;
}
public Item Item { get; }
public int Price { get; }
public string Name { get; }
}
public class BuyItemState
{
public BuyItemState(string name, Serial cont, Serial serial, int price, int amount, int itemID, int hue)
{
Description = name;
ContainerSerial = cont;
MySerial = serial;
Price = price;
Amount = amount;
ItemID = itemID;
Hue = hue;
}
public int Price { get; }
public Serial MySerial { get; }
public Serial ContainerSerial { get; }
public int ItemID { get; }
public int Amount { get; }
public int Hue { get; }
public string Description { get; }
}
}
/***************************************************************************
* BaseVendor.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
namespace Server
{
public class BuyItemStateComparer : IComparer<BuyItemState>
{
public int Compare(BuyItemState l, BuyItemState r)
{
if (l == null && r == null) return 0;
if (l == null) return -1;
if (r == null) return 1;
return l.MySerial.CompareTo(r.MySerial);
}
}
public class BuyItemResponse
{
public BuyItemResponse(Serial serial, int amount)
{
Serial = serial;
Amount = amount;
}
public Serial Serial { get; }
public int Amount { get; }
}
public class SellItemResponse
{
public SellItemResponse(Item i, int amount)
{
Item = i;
Amount = amount;
}
public Item Item { get; }
public int Amount { get; }
}
public class SellItemState
{
public SellItemState(Item item, int price, string name)
{
Item = item;
Price = price;
Name = name;
}
public Item Item { get; }
public int Price { get; }
public string Name { get; }
}
public class BuyItemState
{
public BuyItemState(string name, Serial cont, Serial serial, int price, int amount, int itemID, int hue)
{
Description = name;
ContainerSerial = cont;
MySerial = serial;
Price = price;
Amount = amount;
ItemID = itemID;
Hue = hue;
}
public int Price { get; }
public Serial MySerial { get; }
public Serial ContainerSerial { get; }
public int ItemID { get; }
public int Amount { get; }
public int Hue { get; }
public string Description { get; }
}
}

View file

@ -1,170 +1,171 @@
/***************************************************************************
* Body.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.IO;
namespace Server
{
public enum BodyType : byte
{
Empty,
Monster,
Sea,
Animal,
Human,
Equipment
}
public readonly struct Body : IEquatable<object>, IEquatable<Body>, IEquatable<int>
{
private static readonly BodyType[] m_Types = Array.Empty<BodyType>();
static Body()
{
if (File.Exists("Data/bodyTable.cfg"))
{
using var ip = new StreamReader("Data/bodyTable.cfg");
m_Types = new BodyType[0x1000];
string line;
while ((line = ip.ReadLine()) != null)
{
if (line.Length == 0 || line.StartsWith("#"))
continue;
var split = line.Split('\t');
if (int.TryParse(split[0], out var bodyID) && Enum.TryParse(split[1], true, out BodyType type) && bodyID >= 0 &&
bodyID < m_Types.Length)
{
m_Types[bodyID] = type;
}
else
{
Console.WriteLine("Warning: Invalid bodyTable entry:");
Console.WriteLine(line);
}
}
}
else
{
Console.WriteLine("Warning: Data/bodyTable.cfg does not exist");
}
}
public Body(int bodyID) => BodyID = bodyID;
public BodyType Type => BodyID >= 0 && BodyID < m_Types.Length ? m_Types[BodyID] : BodyType.Empty;
public bool IsHuman => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Human
&& BodyID != 402
&& BodyID != 403
&& BodyID != 607
&& BodyID != 608
&& BodyID != 694
&& BodyID != 695
&& BodyID != 970;
public bool IsGargoyle => BodyID == 666
|| BodyID == 667
|| BodyID == 694
|| BodyID == 695;
public bool IsMale => BodyID == 183
|| BodyID == 185
|| BodyID == 400
|| BodyID == 402
|| BodyID == 605
|| BodyID == 607
|| BodyID == 666
|| BodyID == 694
|| BodyID == 750;
public bool IsFemale => BodyID == 184
|| BodyID == 186
|| BodyID == 401
|| BodyID == 403
|| BodyID == 606
|| BodyID == 608
|| BodyID == 667
|| BodyID == 695
|| BodyID == 751;
public bool IsGhost => BodyID == 402
|| BodyID == 403
|| BodyID == 607
|| BodyID == 608
|| BodyID == 694
|| BodyID == 695
|| BodyID == 970;
public bool IsMonster => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Monster;
public bool IsAnimal => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Animal;
public bool IsEmpty => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Empty;
public bool IsSea => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Sea;
public bool IsEquipment => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Equipment;
public int BodyID { get; }
public static implicit operator int(Body a) => a.BodyID;
public static implicit operator Body(int a) => new Body(a);
public override string ToString() => $"0x{BodyID:X}";
public override int GetHashCode() => BodyID.GetHashCode();
public override bool Equals(object o) => o is Body b && b.BodyID == BodyID;
public bool Equals(Body b) => b.BodyID == BodyID;
public bool Equals(int number) => number == BodyID;
public static bool operator ==(Body l, Body r) => l.BodyID == r.BodyID;
public static bool operator !=(Body l, Body r) => l.BodyID != r.BodyID;
public static bool operator >(Body l, Body r) => l.BodyID > r.BodyID;
public static bool operator >=(Body l, Body r) => l.BodyID >= r.BodyID;
public static bool operator <(Body l, Body r) => l.BodyID < r.BodyID;
public static bool operator <=(Body l, Body r) => l.BodyID <= r.BodyID;
}
}
/***************************************************************************
* Body.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.IO;
namespace Server
{
public enum BodyType : byte
{
Empty,
Monster,
Sea,
Animal,
Human,
Equipment
}
public readonly struct Body : IEquatable<object>, IEquatable<Body>, IEquatable<int>
{
private static readonly BodyType[] m_Types = Array.Empty<BodyType>();
static Body()
{
if (File.Exists("Data/bodyTable.cfg"))
{
using var ip = new StreamReader("Data/bodyTable.cfg");
m_Types = new BodyType[0x1000];
string line;
while ((line = ip.ReadLine()) != null)
{
if (line.Length == 0 || line.StartsWith("#"))
continue;
var split = line.Split('\t');
if (int.TryParse(split[0], out var bodyID) && Enum.TryParse(split[1], true, out BodyType type) &&
bodyID >= 0 &&
bodyID < m_Types.Length)
{
m_Types[bodyID] = type;
}
else
{
Console.WriteLine("Warning: Invalid bodyTable entry:");
Console.WriteLine(line);
}
}
}
else
{
Console.WriteLine("Warning: Data/bodyTable.cfg does not exist");
}
}
public Body(int bodyID) => BodyID = bodyID;
public BodyType Type => BodyID >= 0 && BodyID < m_Types.Length ? m_Types[BodyID] : BodyType.Empty;
public bool IsHuman => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Human
&& BodyID != 402
&& BodyID != 403
&& BodyID != 607
&& BodyID != 608
&& BodyID != 694
&& BodyID != 695
&& BodyID != 970;
public bool IsGargoyle => BodyID == 666
|| BodyID == 667
|| BodyID == 694
|| BodyID == 695;
public bool IsMale => BodyID == 183
|| BodyID == 185
|| BodyID == 400
|| BodyID == 402
|| BodyID == 605
|| BodyID == 607
|| BodyID == 666
|| BodyID == 694
|| BodyID == 750;
public bool IsFemale => BodyID == 184
|| BodyID == 186
|| BodyID == 401
|| BodyID == 403
|| BodyID == 606
|| BodyID == 608
|| BodyID == 667
|| BodyID == 695
|| BodyID == 751;
public bool IsGhost => BodyID == 402
|| BodyID == 403
|| BodyID == 607
|| BodyID == 608
|| BodyID == 694
|| BodyID == 695
|| BodyID == 970;
public bool IsMonster => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Monster;
public bool IsAnimal => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Animal;
public bool IsEmpty => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Empty;
public bool IsSea => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Sea;
public bool IsEquipment => BodyID >= 0
&& BodyID < m_Types.Length
&& m_Types[BodyID] == BodyType.Equipment;
public int BodyID { get; }
public static implicit operator int(Body a) => a.BodyID;
public static implicit operator Body(int a) => new Body(a);
public override string ToString() => $"0x{BodyID:X}";
public override int GetHashCode() => BodyID.GetHashCode();
public override bool Equals(object o) => o is Body b && b.BodyID == BodyID;
public bool Equals(Body b) => b.BodyID == BodyID;
public bool Equals(int number) => number == BodyID;
public static bool operator ==(Body l, Body r) => l.BodyID == r.BodyID;
public static bool operator !=(Body l, Body r) => l.BodyID != r.BodyID;
public static bool operator >(Body l, Body r) => l.BodyID > r.BodyID;
public static bool operator >=(Body l, Body r) => l.BodyID >= r.BodyID;
public static bool operator <(Body l, Body r) => l.BodyID < r.BodyID;
public static bool operator <=(Body l, Body r) => l.BodyID <= r.BodyID;
}
}

View file

@ -1,306 +1,309 @@
// Copyright (c) Harry Pierson. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Buffers
{
public ref struct BufferReader<T>
{
private readonly bool usingSequence;
private readonly ReadOnlySequence<T> sequence;
private SequencePosition currentPosition;
private SequencePosition nextPosition;
private bool moreData;
private readonly long length;
public BufferReader(ReadOnlySpan<T> span)
{
usingSequence = false;
CurrentSpanIndex = 0;
Consumed = 0;
sequence = default;
currentPosition = default;
length = span.Length;
CurrentSpan = span;
nextPosition = default;
moreData = span.Length > 0;
}
public BufferReader(in ReadOnlySequence<T> sequence)
{
usingSequence = true;
CurrentSpanIndex = 0;
Consumed = 0;
this.sequence = sequence;
currentPosition = sequence.Start;
length = -1;
var first = sequence.First.Span;
CurrentSpan = first;
nextPosition = sequence.GetPosition(first.Length);
moreData = first.Length > 0;
if (!moreData && !sequence.IsSingleSegment)
{
moreData = true;
GetNextSpan();
}
}
public readonly bool End => !moreData;
public ReadOnlySpan<T> CurrentSpan { get; private set; }
public int CurrentSpanIndex { get; private set; }
public readonly ReadOnlySpan<T> UnreadSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => CurrentSpan.Slice(CurrentSpanIndex);
}
public long Consumed { get; private set; }
public readonly long Remaining => Length - Consumed;
public readonly long Length
{
get
{
if (length < 0)
// Cast-away readonly to initialize lazy field
Volatile.Write(ref Unsafe.AsRef(length), sequence.Length);
return length;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool TryPeek([MaybeNullWhen(false)] out T value)
{
if (moreData)
{
value = CurrentSpan[CurrentSpanIndex];
return true;
}
value = default!;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryRead([MaybeNullWhen(false)] out T value)
{
if (End)
{
value = default!;
return false;
}
value = CurrentSpan[CurrentSpanIndex];
CurrentSpanIndex++;
Consumed++;
if (CurrentSpanIndex >= CurrentSpan.Length)
{
if (usingSequence)
GetNextSpan();
else
moreData = false;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Rewind(long count)
{
if ((ulong)count > (ulong)Consumed) throw new ArgumentOutOfRangeException(nameof(count));
Consumed -= count;
if (CurrentSpanIndex >= count)
{
CurrentSpanIndex -= (int)count;
moreData = true;
}
else if (usingSequence)
{
// Current segment doesn't have enough data, scan backward through segments
RetreatToPreviousSpan(Consumed);
}
else
{
throw new ArgumentOutOfRangeException(nameof(count), $"Rewind went past the start of the memory by {count}.");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void RetreatToPreviousSpan(long consumed)
{
ResetReader();
Advance(consumed);
}
private void ResetReader()
{
CurrentSpanIndex = 0;
Consumed = 0;
currentPosition = sequence.Start;
nextPosition = currentPosition;
if (sequence.TryGet(ref nextPosition, out var memory))
{
moreData = true;
if (memory.Length == 0)
{
CurrentSpan = default;
// No data in the first span, move to one with data
GetNextSpan();
}
else
{
CurrentSpan = memory.Span;
}
}
else
{
// No data in any spans and at end of sequence
moreData = false;
CurrentSpan = default;
}
}
private void GetNextSpan()
{
if (!sequence.IsSingleSegment)
{
var previousNextPosition = nextPosition;
while (sequence.TryGet(ref nextPosition, out var memory))
{
currentPosition = previousNextPosition;
if (memory.Length > 0)
{
CurrentSpan = memory.Span;
CurrentSpanIndex = 0;
return;
}
CurrentSpan = default;
CurrentSpanIndex = 0;
previousNextPosition = nextPosition;
}
}
moreData = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Advance(long count)
{
const long TooBigOrNegative = unchecked((long)0xFFFFFFFF80000000);
if ((count & TooBigOrNegative) == 0 && CurrentSpan.Length - CurrentSpanIndex > (int)count)
{
CurrentSpanIndex += (int)count;
Consumed += count;
}
else if (usingSequence)
{
// Can't satisfy from the current span
AdvanceToNextSpan(count);
}
else if (CurrentSpan.Length - CurrentSpanIndex == (int)count)
{
CurrentSpanIndex += (int)count;
Consumed += count;
moreData = false;
}
else
{
throw new ArgumentOutOfRangeException(nameof(count));
}
}
private void AdvanceToNextSpan(long count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
Consumed += count;
while (moreData)
{
var remaining = CurrentSpan.Length - CurrentSpanIndex;
if (remaining > count)
{
CurrentSpanIndex += (int)count;
count = 0;
break;
}
// As there may not be any further segments we need to
// push the current index to the end of the span.
CurrentSpanIndex += remaining;
count -= remaining;
GetNextSpan();
if (count == 0) break;
}
if (count != 0)
{
// Not enough data left- adjust for where we actually ended and throw
Consumed -= count;
throw new ArgumentOutOfRangeException(nameof(count));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool TryCopyTo(Span<T> destination)
{
// This API doesn't advance to facilitate conditional advancement based on the data returned.
// We don't provide an advance option to allow easier utilizing of stack allocated destination spans.
// (Because we can make this method readonly we can guarantee that we won't capture the span.)
var firstSpan = UnreadSpan;
if (firstSpan.Length >= destination.Length)
{
firstSpan.Slice(0, destination.Length).CopyTo(destination);
return true;
}
// Not enough in the current span to satisfy the request, fall through to the slow path
return TryCopyMultisegment(destination);
}
internal readonly bool TryCopyMultisegment(Span<T> destination)
{
// If we don't have enough to fill the requested buffer, return false
if (Remaining < destination.Length)
return false;
var firstSpan = UnreadSpan;
firstSpan.CopyTo(destination);
var copied = firstSpan.Length;
var next = nextPosition;
while (sequence.TryGet(ref next, out var nextSegment))
if (nextSegment.Length > 0)
{
var nextSpan = nextSegment.Span;
var toCopy = Math.Min(nextSpan.Length, destination.Length - copied);
nextSpan.Slice(0, toCopy).CopyTo(destination.Slice(copied));
copied += toCopy;
if (copied >= destination.Length) break;
}
return true;
}
}
}
// Copyright (c) Harry Pierson. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Buffers
{
public ref struct BufferReader<T>
{
private readonly bool usingSequence;
private readonly ReadOnlySequence<T> sequence;
private SequencePosition currentPosition;
private SequencePosition nextPosition;
private bool moreData;
private readonly long length;
public BufferReader(ReadOnlySpan<T> span)
{
usingSequence = false;
CurrentSpanIndex = 0;
Consumed = 0;
sequence = default;
currentPosition = default;
length = span.Length;
CurrentSpan = span;
nextPosition = default;
moreData = span.Length > 0;
}
public BufferReader(in ReadOnlySequence<T> sequence)
{
usingSequence = true;
CurrentSpanIndex = 0;
Consumed = 0;
this.sequence = sequence;
currentPosition = sequence.Start;
length = -1;
var first = sequence.First.Span;
CurrentSpan = first;
nextPosition = sequence.GetPosition(first.Length);
moreData = first.Length > 0;
if (!moreData && !sequence.IsSingleSegment)
{
moreData = true;
GetNextSpan();
}
}
public readonly bool End => !moreData;
public ReadOnlySpan<T> CurrentSpan { get; private set; }
public int CurrentSpanIndex { get; private set; }
public readonly ReadOnlySpan<T> UnreadSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => CurrentSpan.Slice(CurrentSpanIndex);
}
public long Consumed { get; private set; }
public readonly long Remaining => Length - Consumed;
public readonly long Length
{
get
{
if (length < 0)
// Cast-away readonly to initialize lazy field
Volatile.Write(ref Unsafe.AsRef(length), sequence.Length);
return length;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool TryPeek([MaybeNullWhen(false)] out T value)
{
if (moreData)
{
value = CurrentSpan[CurrentSpanIndex];
return true;
}
value = default!;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryRead([MaybeNullWhen(false)] out T value)
{
if (End)
{
value = default!;
return false;
}
value = CurrentSpan[CurrentSpanIndex];
CurrentSpanIndex++;
Consumed++;
if (CurrentSpanIndex >= CurrentSpan.Length)
{
if (usingSequence)
GetNextSpan();
else
moreData = false;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Rewind(long count)
{
if ((ulong)count > (ulong)Consumed) throw new ArgumentOutOfRangeException(nameof(count));
Consumed -= count;
if (CurrentSpanIndex >= count)
{
CurrentSpanIndex -= (int)count;
moreData = true;
}
else if (usingSequence)
{
// Current segment doesn't have enough data, scan backward through segments
RetreatToPreviousSpan(Consumed);
}
else
{
throw new ArgumentOutOfRangeException(
nameof(count),
$"Rewind went past the start of the memory by {count}."
);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void RetreatToPreviousSpan(long consumed)
{
ResetReader();
Advance(consumed);
}
private void ResetReader()
{
CurrentSpanIndex = 0;
Consumed = 0;
currentPosition = sequence.Start;
nextPosition = currentPosition;
if (sequence.TryGet(ref nextPosition, out var memory))
{
moreData = true;
if (memory.Length == 0)
{
CurrentSpan = default;
// No data in the first span, move to one with data
GetNextSpan();
}
else
{
CurrentSpan = memory.Span;
}
}
else
{
// No data in any spans and at end of sequence
moreData = false;
CurrentSpan = default;
}
}
private void GetNextSpan()
{
if (!sequence.IsSingleSegment)
{
var previousNextPosition = nextPosition;
while (sequence.TryGet(ref nextPosition, out var memory))
{
currentPosition = previousNextPosition;
if (memory.Length > 0)
{
CurrentSpan = memory.Span;
CurrentSpanIndex = 0;
return;
}
CurrentSpan = default;
CurrentSpanIndex = 0;
previousNextPosition = nextPosition;
}
}
moreData = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Advance(long count)
{
const long TooBigOrNegative = unchecked((long)0xFFFFFFFF80000000);
if ((count & TooBigOrNegative) == 0 && CurrentSpan.Length - CurrentSpanIndex > (int)count)
{
CurrentSpanIndex += (int)count;
Consumed += count;
}
else if (usingSequence)
{
// Can't satisfy from the current span
AdvanceToNextSpan(count);
}
else if (CurrentSpan.Length - CurrentSpanIndex == (int)count)
{
CurrentSpanIndex += (int)count;
Consumed += count;
moreData = false;
}
else
{
throw new ArgumentOutOfRangeException(nameof(count));
}
}
private void AdvanceToNextSpan(long count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
Consumed += count;
while (moreData)
{
var remaining = CurrentSpan.Length - CurrentSpanIndex;
if (remaining > count)
{
CurrentSpanIndex += (int)count;
count = 0;
break;
}
// As there may not be any further segments we need to
// push the current index to the end of the span.
CurrentSpanIndex += remaining;
count -= remaining;
GetNextSpan();
if (count == 0) break;
}
if (count != 0)
{
// Not enough data left- adjust for where we actually ended and throw
Consumed -= count;
throw new ArgumentOutOfRangeException(nameof(count));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool TryCopyTo(Span<T> destination)
{
// This API doesn't advance to facilitate conditional advancement based on the data returned.
// We don't provide an advance option to allow easier utilizing of stack allocated destination spans.
// (Because we can make this method readonly we can guarantee that we won't capture the span.)
var firstSpan = UnreadSpan;
if (firstSpan.Length >= destination.Length)
{
firstSpan.Slice(0, destination.Length).CopyTo(destination);
return true;
}
// Not enough in the current span to satisfy the request, fall through to the slow path
return TryCopyMultisegment(destination);
}
internal readonly bool TryCopyMultisegment(Span<T> destination)
{
// If we don't have enough to fill the requested buffer, return false
if (Remaining < destination.Length)
return false;
var firstSpan = UnreadSpan;
firstSpan.CopyTo(destination);
var copied = firstSpan.Length;
var next = nextPosition;
while (sequence.TryGet(ref next, out var nextSegment))
if (nextSegment.Length > 0)
{
var nextSpan = nextSegment.Span;
var toCopy = Math.Min(nextSpan.Length, destination.Length - copied);
nextSpan.Slice(0, toCopy).CopyTo(destination.Slice(copied));
copied += toCopy;
if (copied >= destination.Length) break;
}
return true;
}
}
}

View file

@ -1,177 +1,177 @@
// Copyright (c) Harry Pierson. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Buffers
{
public static class BufferReaderExtensions
{
private static unsafe bool TryRead<T>(ref this BufferReader<byte> reader, out T value)
where T : unmanaged
{
var span = reader.UnreadSpan;
if (span.Length < sizeof(T)) return TryReadMultisegment(ref reader, out value);
value = Unsafe.ReadUnaligned<T>(ref MemoryMarshal.GetReference(span));
reader.Advance(sizeof(T));
return true;
}
private static unsafe bool TryReadMultisegment<T>(ref BufferReader<byte> reader, out T value)
where T : unmanaged
{
// Not enough data in the current segment, try to peek for the data we need.
T buffer = default;
var tempSpan = new Span<byte>(&buffer, sizeof(T));
if (!reader.TryCopyTo(tempSpan))
{
value = default;
return false;
}
value = Unsafe.ReadUnaligned<T>(ref MemoryMarshal.GetReference(tempSpan));
reader.Advance(sizeof(T));
return true;
}
public static bool TryRead(ref this BufferReader<byte> reader, out sbyte value)
{
if (TryRead(ref reader, out byte byteValue))
{
value = unchecked((sbyte)byteValue);
return true;
}
value = default;
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out short value) =>
BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out short value) =>
!BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
private static bool TryReadReverseEndianness(ref BufferReader<byte> reader, out short value)
{
if (reader.TryRead(out value))
{
value = BinaryPrimitives.ReverseEndianness(value);
return true;
}
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out ushort value)
{
if (TryReadLittleEndian(ref reader, out short signedvalue))
{
value = unchecked((ushort)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out ushort value)
{
if (TryReadBigEndian(ref reader, out short signedvalue))
{
value = unchecked((ushort)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out int value) =>
BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out int value) =>
!BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
private static bool TryReadReverseEndianness(ref BufferReader<byte> reader, out int value)
{
if (reader.TryRead(out value))
{
value = BinaryPrimitives.ReverseEndianness(value);
return true;
}
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out uint value)
{
if (TryReadLittleEndian(ref reader, out int signedvalue))
{
value = unchecked((uint)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out uint value)
{
if (TryReadBigEndian(ref reader, out int signedvalue))
{
value = unchecked((uint)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out long value) =>
BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out long value) =>
!BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
private static bool TryReadReverseEndianness(ref BufferReader<byte> reader, out long value)
{
if (reader.TryRead(out value))
{
value = BinaryPrimitives.ReverseEndianness(value);
return true;
}
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out ulong value)
{
if (TryReadLittleEndian(ref reader, out long signedvalue))
{
value = unchecked((ulong)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out ulong value)
{
if (TryReadBigEndian(ref reader, out long signedvalue))
{
value = unchecked((ulong)signedvalue);
return true;
}
value = default;
return false;
}
}
}
// Copyright (c) Harry Pierson. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Buffers
{
public static class BufferReaderExtensions
{
private static unsafe bool TryRead<T>(ref this BufferReader<byte> reader, out T value)
where T : unmanaged
{
var span = reader.UnreadSpan;
if (span.Length < sizeof(T)) return TryReadMultisegment(ref reader, out value);
value = Unsafe.ReadUnaligned<T>(ref MemoryMarshal.GetReference(span));
reader.Advance(sizeof(T));
return true;
}
private static unsafe bool TryReadMultisegment<T>(ref BufferReader<byte> reader, out T value)
where T : unmanaged
{
// Not enough data in the current segment, try to peek for the data we need.
T buffer = default;
var tempSpan = new Span<byte>(&buffer, sizeof(T));
if (!reader.TryCopyTo(tempSpan))
{
value = default;
return false;
}
value = Unsafe.ReadUnaligned<T>(ref MemoryMarshal.GetReference(tempSpan));
reader.Advance(sizeof(T));
return true;
}
public static bool TryRead(ref this BufferReader<byte> reader, out sbyte value)
{
if (TryRead(ref reader, out byte byteValue))
{
value = unchecked((sbyte)byteValue);
return true;
}
value = default;
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out short value) =>
BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out short value) =>
!BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
private static bool TryReadReverseEndianness(ref BufferReader<byte> reader, out short value)
{
if (reader.TryRead(out value))
{
value = BinaryPrimitives.ReverseEndianness(value);
return true;
}
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out ushort value)
{
if (TryReadLittleEndian(ref reader, out short signedvalue))
{
value = unchecked((ushort)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out ushort value)
{
if (TryReadBigEndian(ref reader, out short signedvalue))
{
value = unchecked((ushort)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out int value) =>
BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out int value) =>
!BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
private static bool TryReadReverseEndianness(ref BufferReader<byte> reader, out int value)
{
if (reader.TryRead(out value))
{
value = BinaryPrimitives.ReverseEndianness(value);
return true;
}
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out uint value)
{
if (TryReadLittleEndian(ref reader, out int signedvalue))
{
value = unchecked((uint)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out uint value)
{
if (TryReadBigEndian(ref reader, out int signedvalue))
{
value = unchecked((uint)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out long value) =>
BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out long value) =>
!BitConverter.IsLittleEndian ? reader.TryRead(out value) : TryReadReverseEndianness(ref reader, out value);
private static bool TryReadReverseEndianness(ref BufferReader<byte> reader, out long value)
{
if (reader.TryRead(out value))
{
value = BinaryPrimitives.ReverseEndianness(value);
return true;
}
return false;
}
public static bool TryReadLittleEndian(ref this BufferReader<byte> reader, out ulong value)
{
if (TryReadLittleEndian(ref reader, out long signedvalue))
{
value = unchecked((ulong)signedvalue);
return true;
}
value = default;
return false;
}
public static bool TryReadBigEndian(ref this BufferReader<byte> reader, out ulong value)
{
if (TryReadBigEndian(ref reader, out long signedvalue))
{
value = unchecked((ulong)signedvalue);
return true;
}
value = default;
return false;
}
}
}

View file

@ -1,143 +1,145 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
namespace System.Buffers
{
/// <summary>
/// A fast access struct that wraps <see cref="IBufferWriter{T}"/>.
/// </summary>
/// <typeparam name="T">The type of element to be written.</typeparam>
internal ref struct BufferWriter<T> where T : IBufferWriter<byte>
{
/// <summary>
/// The underlying <see cref="IBufferWriter{T}"/>.
/// </summary>
private T _output;
/// <summary>
/// The result of the last call to <see cref="IBufferWriter{T}.GetSpan(int)"/>, less any bytes already "consumed" with <see cref="Advance(int)"/>.
/// Backing field for the <see cref="Span"/> property.
/// </summary>
private Span<byte> _span;
/// <summary>
/// The number of uncommitted bytes (all the calls to <see cref="Advance(int)"/> since the last call to <see cref="Commit"/>).
/// </summary>
private int _buffered;
/// <summary>
/// The total number of bytes written with this writer.
/// Backing field for the <see cref="BytesCommitted"/> property.
/// </summary>
private long _bytesCommitted;
/// <summary>
/// Initializes a new instance of the <see cref="BufferWriter{T}"/> struct.
/// </summary>
/// <param name="output">The <see cref="IBufferWriter{T}"/> to be wrapped.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BufferWriter(T output)
{
_buffered = 0;
_bytesCommitted = 0;
_output = output;
_span = output.GetSpan();
}
/// <summary>
/// Gets the result of the last call to <see cref="IBufferWriter{T}.GetSpan(int)"/>.
/// </summary>
public Span<byte> Span => _span;
/// <summary>
/// Gets the total number of bytes written with this writer.
/// </summary>
public long BytesCommitted => _bytesCommitted;
/// <summary>
/// Calls <see cref="IBufferWriter{T}.Advance(int)"/> on the underlying writer
/// with the number of uncommitted bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Commit()
{
var buffered = _buffered;
if (buffered > 0)
{
_bytesCommitted += buffered;
_buffered = 0;
_output.Advance(buffered);
}
}
/// <summary>
/// Used to indicate that part of the buffer has been written to.
/// </summary>
/// <param name="count">The number of bytes written to.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Advance(int count)
{
_buffered += count;
_span = _span.Slice(count);
}
/// <summary>
/// Copies the caller's buffer into this writer and calls <see cref="Advance(int)"/> with the length of the source buffer.
/// </summary>
/// <param name="source">The buffer to copy in.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ReadOnlySpan<byte> source)
{
if (_span.Length >= source.Length)
{
source.CopyTo(_span);
Advance(source.Length);
}
else
{
WriteMultiBuffer(source);
}
}
/// <summary>
/// Acquires a new buffer if necessary to ensure that some given number of bytes can be written to a single buffer.
/// </summary>
/// <param name="count">The number of bytes that must be allocated in a single buffer.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Ensure(int count = 1)
{
if (_span.Length < count) EnsureMore(count);
}
/// <summary>
/// Gets a fresh span to write to, with an optional minimum size.
/// </summary>
/// <param name="count">The minimum size for the next requested buffer.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnsureMore(int count = 0)
{
if (_buffered > 0) Commit();
_span = _output.GetSpan(count);
}
/// <summary>
/// Copies the caller's buffer into this writer, potentially across multiple buffers from the underlying writer.
/// </summary>
/// <param name="source">The buffer to copy into this writer.</param>
private void WriteMultiBuffer(ReadOnlySpan<byte> source)
{
while (source.Length > 0)
{
if (_span.Length == 0) EnsureMore();
var writable = Math.Min(source.Length, _span.Length);
source.Slice(0, writable).CopyTo(_span);
source = source.Slice(writable);
Advance(writable);
}
}
}
}
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
namespace System.Buffers
{
/// <summary>
/// A fast access struct that wraps <see cref="IBufferWriter{T}" />.
/// </summary>
/// <typeparam name="T">The type of element to be written.</typeparam>
internal ref struct BufferWriter<T> where T : IBufferWriter<byte>
{
/// <summary>
/// The underlying <see cref="IBufferWriter{T}" />.
/// </summary>
private T _output;
/// <summary>
/// The result of the last call to <see cref="IBufferWriter{T}.GetSpan(int)" />, less any bytes already "consumed" with
/// <see cref="Advance(int)" />.
/// Backing field for the <see cref="Span" /> property.
/// </summary>
private Span<byte> _span;
/// <summary>
/// The number of uncommitted bytes (all the calls to <see cref="Advance(int)" /> since the last call to
/// <see cref="Commit" />).
/// </summary>
private int _buffered;
/// <summary>
/// The total number of bytes written with this writer.
/// Backing field for the <see cref="BytesCommitted" /> property.
/// </summary>
private long _bytesCommitted;
/// <summary>
/// Initializes a new instance of the <see cref="BufferWriter{T}" /> struct.
/// </summary>
/// <param name="output">The <see cref="IBufferWriter{T}" /> to be wrapped.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BufferWriter(T output)
{
_buffered = 0;
_bytesCommitted = 0;
_output = output;
_span = output.GetSpan();
}
/// <summary>
/// Gets the result of the last call to <see cref="IBufferWriter{T}.GetSpan(int)" />.
/// </summary>
public Span<byte> Span => _span;
/// <summary>
/// Gets the total number of bytes written with this writer.
/// </summary>
public long BytesCommitted => _bytesCommitted;
/// <summary>
/// Calls <see cref="IBufferWriter{T}.Advance(int)" /> on the underlying writer
/// with the number of uncommitted bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Commit()
{
var buffered = _buffered;
if (buffered > 0)
{
_bytesCommitted += buffered;
_buffered = 0;
_output.Advance(buffered);
}
}
/// <summary>
/// Used to indicate that part of the buffer has been written to.
/// </summary>
/// <param name="count">The number of bytes written to.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Advance(int count)
{
_buffered += count;
_span = _span.Slice(count);
}
/// <summary>
/// Copies the caller's buffer into this writer and calls <see cref="Advance(int)" /> with the length of the source buffer.
/// </summary>
/// <param name="source">The buffer to copy in.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ReadOnlySpan<byte> source)
{
if (_span.Length >= source.Length)
{
source.CopyTo(_span);
Advance(source.Length);
}
else
{
WriteMultiBuffer(source);
}
}
/// <summary>
/// Acquires a new buffer if necessary to ensure that some given number of bytes can be written to a single buffer.
/// </summary>
/// <param name="count">The number of bytes that must be allocated in a single buffer.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Ensure(int count = 1)
{
if (_span.Length < count) EnsureMore(count);
}
/// <summary>
/// Gets a fresh span to write to, with an optional minimum size.
/// </summary>
/// <param name="count">The minimum size for the next requested buffer.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnsureMore(int count = 0)
{
if (_buffered > 0) Commit();
_span = _output.GetSpan(count);
}
/// <summary>
/// Copies the caller's buffer into this writer, potentially across multiple buffers from the underlying writer.
/// </summary>
/// <param name="source">The buffer to copy into this writer.</param>
private void WriteMultiBuffer(ReadOnlySpan<byte> source)
{
while (source.Length > 0)
{
if (_span.Length == 0) EnsureMore();
var writable = Math.Min(source.Length, _span.Length);
source.Slice(0, writable).CopyTo(_span);
source = source.Slice(writable);
Advance(writable);
}
}
}
}

View file

@ -1,57 +1,58 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Buffers
{
/// <summary>
/// Block tracking object used by the byte buffer memory pool. A slab is a large allocation which is divided into smaller blocks. The
/// individual blocks are then treated as independent array segments.
/// </summary>
public sealed class MemoryPoolBlock : IMemoryOwner<byte>
{
private readonly int _offset;
private readonly int _length;
/// <summary>
/// This object cannot be instantiated outside of the static Create method
/// </summary>
internal MemoryPoolBlock(SlabMemoryPool pool, MemoryPoolSlab slab, int offset, int length)
{
_offset = offset;
_length = length;
Pool = pool;
Slab = slab;
Memory = MemoryMarshal.CreateFromPinnedArray(slab.Array, _offset, _length);
}
/// <summary>
/// Back-reference to the memory pool which this block was allocated from. It may only be returned to this pool.
/// </summary>
public SlabMemoryPool Pool { get; }
/// <summary>
/// Back-reference to the slab from which this block was taken, or null if it is one-time-use memory.
/// </summary>
public MemoryPoolSlab Slab { get; }
public Memory<byte> Memory { get; }
~MemoryPoolBlock()
{
Pool.RefreshBlock(Slab, _offset, _length);
}
public void Dispose()
{
Pool.Return(this);
}
public void Lease()
{
}
}
}
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Buffers
{
/// <summary>
/// Block tracking object used by the byte buffer memory pool. A slab is a large allocation which is divided into smaller
/// blocks. The
/// individual blocks are then treated as independent array segments.
/// </summary>
public sealed class MemoryPoolBlock : IMemoryOwner<byte>
{
private readonly int _length;
private readonly int _offset;
/// <summary>
/// This object cannot be instantiated outside of the static Create method
/// </summary>
internal MemoryPoolBlock(SlabMemoryPool pool, MemoryPoolSlab slab, int offset, int length)
{
_offset = offset;
_length = length;
Pool = pool;
Slab = slab;
Memory = MemoryMarshal.CreateFromPinnedArray(slab.Array, _offset, _length);
}
/// <summary>
/// Back-reference to the memory pool which this block was allocated from. It may only be returned to this pool.
/// </summary>
public SlabMemoryPool Pool { get; }
/// <summary>
/// Back-reference to the slab from which this block was taken, or null if it is one-time-use memory.
/// </summary>
public MemoryPoolSlab Slab { get; }
public Memory<byte> Memory { get; }
public void Dispose()
{
Pool.Return(this);
}
~MemoryPoolBlock()
{
Pool.RefreshBlock(Slab, _offset, _length);
}
public void Lease()
{
}
}
}

View file

@ -1,11 +1,11 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace System.Buffers
{
public static class SlabMemoryPoolFactory
{
public static MemoryPool<byte> Create() => CreateSlabMemoryPool();
public static MemoryPool<byte> CreateSlabMemoryPool() => new SlabMemoryPool();
}
}
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace System.Buffers
{
public static class SlabMemoryPoolFactory
{
public static MemoryPool<byte> Create() => CreateSlabMemoryPool();
public static MemoryPool<byte> CreateSlabMemoryPool() => new SlabMemoryPool();
}
}

View file

@ -1,75 +1,76 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Buffers
{
/// <summary>
/// Slab tracking object used by the byte buffer memory pool. A slab is a large allocation which is divided into smaller blocks. The
/// individual blocks are then treated as independent array segments.
/// </summary>
public class MemoryPoolSlab : IDisposable
{
/// <summary>
/// This handle pins the managed array in memory until the slab is disposed. This prevents it from being
/// relocated and enables any subsections of the array to be used as native memory pointers to P/Invoked API calls.
/// </summary>
private GCHandle _gcHandle;
private bool _isDisposed;
public MemoryPoolSlab(byte[] data)
{
Array = data;
_gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
NativePointer = _gcHandle.AddrOfPinnedObject();
}
/// <summary>
/// True as long as the blocks from this slab are to be considered returnable to the pool. In order to shrink the
/// memory pool size an entire slab must be removed. That is done by (1) setting IsActive to false and removing the
/// slab from the pool's _slabs collection, (2) as each block currently in use is Return()ed to the pool it will
/// be allowed to be garbage collected rather than re-pooled, and (3) when all block tracking objects are garbage
/// collected and the slab is no longer references the slab will be garbage collected and the memory unpinned will
/// be unpinned by the slab's Dispose.
/// </summary>
public bool IsActive => !_isDisposed;
public IntPtr NativePointer { get; private set; }
public byte[] Array { get; private set; }
public static MemoryPoolSlab Create(int length)
{
// allocate and pin requested memory length
var array = new byte[length];
// allocate and return slab tracking object
return new MemoryPoolSlab(array);
}
protected void Dispose(bool disposing)
{
if (_isDisposed) return;
_isDisposed = true;
Array = null;
NativePointer = IntPtr.Zero;
if (_gcHandle.IsAllocated) _gcHandle.Free();
}
~MemoryPoolSlab()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Buffers
{
/// <summary>
/// Slab tracking object used by the byte buffer memory pool. A slab is a large allocation which is divided into smaller
/// blocks. The
/// individual blocks are then treated as independent array segments.
/// </summary>
public class MemoryPoolSlab : IDisposable
{
/// <summary>
/// This handle pins the managed array in memory until the slab is disposed. This prevents it from being
/// relocated and enables any subsections of the array to be used as native memory pointers to P/Invoked API calls.
/// </summary>
private GCHandle _gcHandle;
private bool _isDisposed;
public MemoryPoolSlab(byte[] data)
{
Array = data;
_gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
NativePointer = _gcHandle.AddrOfPinnedObject();
}
/// <summary>
/// True as long as the blocks from this slab are to be considered returnable to the pool. In order to shrink the
/// memory pool size an entire slab must be removed. That is done by (1) setting IsActive to false and removing the
/// slab from the pool's _slabs collection, (2) as each block currently in use is Return()ed to the pool it will
/// be allowed to be garbage collected rather than re-pooled, and (3) when all block tracking objects are garbage
/// collected and the slab is no longer references the slab will be garbage collected and the memory unpinned will
/// be unpinned by the slab's Dispose.
/// </summary>
public bool IsActive => !_isDisposed;
public IntPtr NativePointer { get; private set; }
public byte[] Array { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public static MemoryPoolSlab Create(int length)
{
// allocate and pin requested memory length
var array = new byte[length];
// allocate and return slab tracking object
return new MemoryPoolSlab(array);
}
protected void Dispose(bool disposing)
{
if (_isDisposed) return;
_isDisposed = true;
Array = null;
NativePointer = IntPtr.Zero;
if (_gcHandle.IsAllocated) _gcHandle.Free();
}
~MemoryPoolSlab()
{
Dispose(false);
}
}
}

View file

@ -1,51 +1,53 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Buffers
{
public static class MemoryPoolThrowHelper
{
public static void ThrowArgumentOutOfRangeException(int sourceLength, int offset)
{
throw GetArgumentOutOfRangeException(sourceLength, offset);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(int sourceLength, int offset) =>
(uint)offset > (uint)sourceLength
? new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.offset))
: new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.length));
public static void ThrowArgumentOutOfRangeException_BufferRequestTooLarge(int maxSize)
{
throw GetArgumentOutOfRangeException_BufferRequestTooLarge(maxSize);
}
public static void ThrowObjectDisposedException(ExceptionArgument argument)
{
throw GetObjectDisposedException(argument);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException_BufferRequestTooLarge(int maxSize) =>
new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.size),
$"Cannot allocate more than {maxSize} bytes in a single buffer");
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectDisposedException GetObjectDisposedException(ExceptionArgument argument) =>
new ObjectDisposedException(GetArgumentName(argument));
private static string GetArgumentName(ExceptionArgument argument) => argument.ToString();
public enum ExceptionArgument
{
size,
offset,
length,
MemoryPoolBlock,
MemoryPool
}
}
}
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Buffers
{
public static class MemoryPoolThrowHelper
{
public enum ExceptionArgument
{
size,
offset,
length,
MemoryPoolBlock,
MemoryPool
}
public static void ThrowArgumentOutOfRangeException(int sourceLength, int offset)
{
throw GetArgumentOutOfRangeException(sourceLength, offset);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(int sourceLength, int offset) =>
(uint)offset > (uint)sourceLength
? new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.offset))
: new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.length));
public static void ThrowArgumentOutOfRangeException_BufferRequestTooLarge(int maxSize)
{
throw GetArgumentOutOfRangeException_BufferRequestTooLarge(maxSize);
}
public static void ThrowObjectDisposedException(ExceptionArgument argument)
{
throw GetObjectDisposedException(argument);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException_BufferRequestTooLarge(int maxSize) =>
new ArgumentOutOfRangeException(
GetArgumentName(ExceptionArgument.size),
$"Cannot allocate more than {maxSize} bytes in a single buffer"
);
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectDisposedException GetObjectDisposedException(ExceptionArgument argument) =>
new ObjectDisposedException(GetArgumentName(argument));
private static string GetArgumentName(ExceptionArgument argument) => argument.ToString();
}
}

View file

@ -1,179 +1,187 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Concurrent;
using System.Threading;
namespace System.Buffers
{
/// <summary>
/// Used to allocate and distribute re-usable blocks of memory.
/// </summary>
public sealed class SlabMemoryPool : MemoryPool<byte>
{
/// <summary>
/// The size of a block. 4096 is chosen because most operating systems use 4k pages.
/// </summary>
private const int _blockSize = 4096;
/// <summary>
/// Allocating 32 contiguous blocks per slab makes the slab size 128k. This is larger than the 85k size which will place the memory
/// in the large object heap. This means the GC will not try to relocate this array, so the fact it remains pinned does not negatively
/// affect memory management's compactification.
/// </summary>
private const int _blockCount = 32;
/// <summary>
/// Max allocation block size for pooled blocks,
/// larger values can be leased but they will be disposed after use rather than returned to the pool.
/// </summary>
public override int MaxBufferSize { get; } = _blockSize;
/// <summary>
/// The size of a block. 4096 is chosen because most operating systems use 4k pages.
/// </summary>
public static int BlockSize => _blockSize;
/// <summary>
/// 4096 * 32 gives you a slabLength of 128k contiguous bytes allocated per slab
/// </summary>
private static readonly int _slabLength = _blockSize * _blockCount;
/// <summary>
/// Thread-safe collection of blocks which are currently in the pool. A slab will pre-allocate all of the block tracking objects
/// and add them to this collection. When memory is requested it is taken from here first, and when it is returned it is re-added.
/// </summary>
private readonly ConcurrentQueue<MemoryPoolBlock> _blocks = new ConcurrentQueue<MemoryPoolBlock>();
/// <summary>
/// Thread-safe collection of slabs which have been allocated by this pool. As long as a slab is in this collection and slab.IsActive,
/// the blocks will be added to _blocks when returned.
/// </summary>
private readonly ConcurrentStack<MemoryPoolSlab> _slabs = new ConcurrentStack<MemoryPoolSlab>();
/// <summary>
/// This is part of implementing the IDisposable pattern.
/// </summary>
private bool _isDisposed; // To detect redundant calls
private int _totalAllocatedBlocks;
private readonly object _disposeSync = new object();
/// <summary>
/// This default value passed in to Rent to use the default value for the pool.
/// </summary>
private const int AnySize = -1;
public override IMemoryOwner<byte> Rent(int size = AnySize)
{
if (size > _blockSize) MemoryPoolThrowHelper.ThrowArgumentOutOfRangeException_BufferRequestTooLarge(_blockSize);
var block = Lease();
return block;
}
/// <summary>
/// Called to take a block from the pool.
/// </summary>
/// <returns>The block that is reserved for the called. It must be passed to Return when it is no longer being used.</returns>
private MemoryPoolBlock Lease()
{
if (_isDisposed)
MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPool);
if (_blocks.TryDequeue(out var block))
{
// block successfully taken from the stack - return it
block.Lease();
return block;
}
// no blocks available - grow the pool
block = AllocateSlab();
block.Lease();
return block;
}
/// <summary>
/// Internal method called when a block is requested and the pool is empty. It allocates one additional slab, creates all of the
/// block tracking objects, and adds them all to the pool.
/// </summary>
private MemoryPoolBlock AllocateSlab()
{
#pragma warning disable CA2000 // Dispose objects before losing scope
var slab = MemoryPoolSlab.Create(_slabLength);
#pragma warning restore CA2000 // Dispose objects before losing scope
_slabs.Push(slab);
var basePtr = slab.NativePointer;
// Page align the blocks
var offset = (int)((((ulong)basePtr + _blockSize - 1) & ~((uint)_blockSize - 1)) - (ulong)basePtr);
var blockCount = (_slabLength - offset) / _blockSize;
Interlocked.Add(ref _totalAllocatedBlocks, blockCount);
MemoryPoolBlock block = null;
for (var i = 0; i < blockCount; i++)
{
block = new MemoryPoolBlock(this, slab, offset, _blockSize);
if (i != blockCount - 1) // last block
Return(block);
offset += _blockSize;
}
return block;
}
/// <summary>
/// Called to return a block to the pool. Once Return has been called the memory no longer belongs to the caller, and
/// Very Bad Things will happen if the memory is read of modified subsequently. If a caller fails to call Return and the
/// block tracking object is garbage collected, the block tracking object's finalizer will automatically re-create and return
/// a new tracking object into the pool. This will only happen if there is a bug in the server, however it is necessary to avoid
/// leaving "dead zones" in the slab due to lost block tracking objects.
/// </summary>
/// <param name="block">The block to return. It must have been acquired by calling Lease on the same memory pool instance.</param>
internal void Return(MemoryPoolBlock block)
{
if (!_isDisposed)
_blocks.Enqueue(block);
else
GC.SuppressFinalize(block);
}
// This method can ONLY be called from the finalizer of MemoryPoolBlock
internal void RefreshBlock(MemoryPoolSlab slab, int offset, int length)
{
lock (_disposeSync)
{
if (!_isDisposed && slab?.IsActive == true)
// Need to make a new object because this one is being finalized
// Note, this must be called within the _disposeSync lock because the block
// could be disposed at the same time as the finalizer.
Return(new MemoryPoolBlock(this, slab, offset, length));
}
}
protected override void Dispose(bool disposing)
{
if (_isDisposed) return;
lock (_disposeSync)
{
_isDisposed = true;
if (disposing)
while (_slabs.TryPop(out var slab))
// dispose managed state (managed objects).
slab.Dispose();
// Discard blocks in pool
while (_blocks.TryDequeue(out var block)) GC.SuppressFinalize(block);
}
}
}
}
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Concurrent;
using System.Threading;
namespace System.Buffers
{
/// <summary>
/// Used to allocate and distribute re-usable blocks of memory.
/// </summary>
public sealed class SlabMemoryPool : MemoryPool<byte>
{
/// <summary>
/// The size of a block. 4096 is chosen because most operating systems use 4k pages.
/// </summary>
private const int _blockSize = 4096;
/// <summary>
/// Allocating 32 contiguous blocks per slab makes the slab size 128k. This is larger than the 85k size which will place the
/// memory
/// in the large object heap. This means the GC will not try to relocate this array, so the fact it remains pinned does not
/// negatively
/// affect memory management's compactification.
/// </summary>
private const int _blockCount = 32;
/// <summary>
/// This default value passed in to Rent to use the default value for the pool.
/// </summary>
private const int AnySize = -1;
/// <summary>
/// 4096 * 32 gives you a slabLength of 128k contiguous bytes allocated per slab
/// </summary>
private static readonly int _slabLength = _blockSize * _blockCount;
/// <summary>
/// Thread-safe collection of blocks which are currently in the pool. A slab will pre-allocate all of the block tracking
/// objects
/// and add them to this collection. When memory is requested it is taken from here first, and when it is returned it is
/// re-added.
/// </summary>
private readonly ConcurrentQueue<MemoryPoolBlock> _blocks = new ConcurrentQueue<MemoryPoolBlock>();
private readonly object _disposeSync = new object();
/// <summary>
/// Thread-safe collection of slabs which have been allocated by this pool. As long as a slab is in this collection and
/// slab.IsActive,
/// the blocks will be added to _blocks when returned.
/// </summary>
private readonly ConcurrentStack<MemoryPoolSlab> _slabs = new ConcurrentStack<MemoryPoolSlab>();
/// <summary>
/// This is part of implementing the IDisposable pattern.
/// </summary>
private bool _isDisposed; // To detect redundant calls
private int _totalAllocatedBlocks;
/// <summary>
/// Max allocation block size for pooled blocks,
/// larger values can be leased but they will be disposed after use rather than returned to the pool.
/// </summary>
public override int MaxBufferSize { get; } = _blockSize;
/// <summary>
/// The size of a block. 4096 is chosen because most operating systems use 4k pages.
/// </summary>
public static int BlockSize => _blockSize;
public override IMemoryOwner<byte> Rent(int size = AnySize)
{
if (size > _blockSize) MemoryPoolThrowHelper.ThrowArgumentOutOfRangeException_BufferRequestTooLarge(_blockSize);
var block = Lease();
return block;
}
/// <summary>
/// Called to take a block from the pool.
/// </summary>
/// <returns>The block that is reserved for the called. It must be passed to Return when it is no longer being used.</returns>
private MemoryPoolBlock Lease()
{
if (_isDisposed)
MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPool);
if (_blocks.TryDequeue(out var block))
{
// block successfully taken from the stack - return it
block.Lease();
return block;
}
// no blocks available - grow the pool
block = AllocateSlab();
block.Lease();
return block;
}
/// <summary>
/// Internal method called when a block is requested and the pool is empty. It allocates one additional slab, creates all of
/// the
/// block tracking objects, and adds them all to the pool.
/// </summary>
private MemoryPoolBlock AllocateSlab()
{
#pragma warning disable CA2000 // Dispose objects before losing scope
var slab = MemoryPoolSlab.Create(_slabLength);
#pragma warning restore CA2000 // Dispose objects before losing scope
_slabs.Push(slab);
var basePtr = slab.NativePointer;
// Page align the blocks
var offset = (int)((((ulong)basePtr + _blockSize - 1) & ~((uint)_blockSize - 1)) - (ulong)basePtr);
var blockCount = (_slabLength - offset) / _blockSize;
Interlocked.Add(ref _totalAllocatedBlocks, blockCount);
MemoryPoolBlock block = null;
for (var i = 0; i < blockCount; i++)
{
block = new MemoryPoolBlock(this, slab, offset, _blockSize);
if (i != blockCount - 1) // last block
Return(block);
offset += _blockSize;
}
return block;
}
/// <summary>
/// Called to return a block to the pool. Once Return has been called the memory no longer belongs to the caller, and
/// Very Bad Things will happen if the memory is read of modified subsequently. If a caller fails to call Return and the
/// block tracking object is garbage collected, the block tracking object's finalizer will automatically re-create and
/// return
/// a new tracking object into the pool. This will only happen if there is a bug in the server, however it is necessary to
/// avoid
/// leaving "dead zones" in the slab due to lost block tracking objects.
/// </summary>
/// <param name="block">The block to return. It must have been acquired by calling Lease on the same memory pool instance.</param>
internal void Return(MemoryPoolBlock block)
{
if (!_isDisposed)
_blocks.Enqueue(block);
else
GC.SuppressFinalize(block);
}
// This method can ONLY be called from the finalizer of MemoryPoolBlock
internal void RefreshBlock(MemoryPoolSlab slab, int offset, int length)
{
lock (_disposeSync)
{
if (!_isDisposed && slab?.IsActive == true)
// Need to make a new object because this one is being finalized
// Note, this must be called within the _disposeSync lock because the block
// could be disposed at the same time as the finalizer.
Return(new MemoryPoolBlock(this, slab, offset, length));
}
}
protected override void Dispose(bool disposing)
{
if (_isDisposed) return;
lock (_disposeSync)
{
_isDisposed = true;
if (disposing)
while (_slabs.TryPop(out var slab))
// dispose managed state (managed objects).
slab.Dispose();
// Discard blocks in pool
while (_blocks.TryDequeue(out var block)) GC.SuppressFinalize(block);
}
}
}
}

View file

@ -1,214 +1,214 @@
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Text;
using Server;
namespace System.Buffers
{
public static class SpanExtensions
{
// Extensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ushort value) => BinaryPrimitives.WriteUInt16BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, short value) => BinaryPrimitives.WriteInt16BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, uint value) => BinaryPrimitives.WriteUInt32BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, int value) => BinaryPrimitives.WriteInt32BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, byte value) => span[0] = value;
// Ref Extensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, ReadOnlySpan<byte> data)
{
data.CopyTo(span.Slice(pos, data.Length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, bool value)
{
span[pos++] = value ? (byte)1 : (byte)0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, byte value) => span[pos++] = value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, ushort value)
{
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), value);
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, short value)
{
BinaryPrimitives.WriteInt16BigEndian(span.Slice(pos, 2), value);
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, uint value)
{
BinaryPrimitives.WriteUInt32BigEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, uint value)
{
BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, int value)
{
BinaryPrimitives.WriteInt32BigEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, int value)
{
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, Serial value)
{
BinaryPrimitives.WriteUInt32BigEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, ulong value)
{
BinaryPrimitives.WriteUInt64BigEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, long value)
{
BinaryPrimitives.WriteInt64BigEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, ulong value)
{
BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, long value)
{
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAscii(this Span<byte> span, ref int pos, string value)
{
int length = value.Length;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAscii(this Span<byte> span, ref int pos, string value, int max)
{
int length = value.Length <= max ? value.Length : max;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAsciiNull(this Span<byte> span, ref int pos, string value)
{
int length = value.Length;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
#if NO_LOCAL_INIT
span[pos] = 0; // Null terminator
#endif
pos++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAsciiNull(this Span<byte> span, ref int pos, string value, int max)
{
var length = value.Length < max ? value.Length : max - 1;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
#if NO_LOCAL_INIT
span[pos] = 0; // Null terminator
#endif
pos++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAsciiFixed(this Span<byte> span, ref int pos, string value, int amount)
{
var length = value.Length <= amount ? value.Length : amount;
#if NO_LOCAL_INIT
int bytesWritten = Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
if (bytesWritten < amount)
span.Slice(pos + bytesWritten, amount - bytesWritten).Clear();
#else
Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
#endif
pos += amount;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteBigUni(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.BigEndianUnicode.GetBytes(value, span.Slice(pos));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLittleUni(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.Unicode.GetBytes(value, span.Slice(pos));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteBigUniNull(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.BigEndianUnicode.GetBytes(value, span.Slice(pos));
#if NO_LOCAL_INIT
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), 0); // Null terminator
#endif
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLittleUniNull(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.Unicode.GetBytes(value, span.Slice(pos));
#if NO_LOCAL_INIT
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), 0); // Null terminator
#endif
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, Point3D p)
{
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), (ushort)p.X);
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos + 2, 2), (ushort)p.Y);
span[pos + 4] = (byte)p.Z;
pos += 5;
}
}
}
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Text;
using Server;
namespace System.Buffers
{
public static class SpanExtensions
{
// Extensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ushort value) => BinaryPrimitives.WriteUInt16BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, short value) => BinaryPrimitives.WriteInt16BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, uint value) => BinaryPrimitives.WriteUInt32BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, int value) => BinaryPrimitives.WriteInt32BigEndian(span, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, byte value) => span[0] = value;
// Ref Extensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, ReadOnlySpan<byte> data)
{
data.CopyTo(span.Slice(pos, data.Length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, bool value)
{
span[pos++] = value ? (byte)1 : (byte)0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, byte value) => span[pos++] = value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, ushort value)
{
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), value);
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, short value)
{
BinaryPrimitives.WriteInt16BigEndian(span.Slice(pos, 2), value);
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, uint value)
{
BinaryPrimitives.WriteUInt32BigEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, uint value)
{
BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, int value)
{
BinaryPrimitives.WriteInt32BigEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, int value)
{
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, Serial value)
{
BinaryPrimitives.WriteUInt32BigEndian(span.Slice(pos, 4), value);
pos += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, ulong value)
{
BinaryPrimitives.WriteUInt64BigEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, long value)
{
BinaryPrimitives.WriteInt64BigEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, ulong value)
{
BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLE(this Span<byte> span, ref int pos, long value)
{
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(pos, 8), value);
pos += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAscii(this Span<byte> span, ref int pos, string value)
{
var length = value.Length;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAscii(this Span<byte> span, ref int pos, string value, int max)
{
var length = value.Length <= max ? value.Length : max;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAsciiNull(this Span<byte> span, ref int pos, string value)
{
var length = value.Length;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
#if NO_LOCAL_INIT
span[pos] = 0; // Null terminator
#endif
pos++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAsciiNull(this Span<byte> span, ref int pos, string value, int max)
{
var length = value.Length < max ? value.Length : max - 1;
pos += Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
#if NO_LOCAL_INIT
span[pos] = 0; // Null terminator
#endif
pos++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteAsciiFixed(this Span<byte> span, ref int pos, string value, int amount)
{
var length = value.Length <= amount ? value.Length : amount;
#if NO_LOCAL_INIT
int bytesWritten = Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
if (bytesWritten < amount)
span.Slice(pos + bytesWritten, amount - bytesWritten).Clear();
#else
Encoding.ASCII.GetBytes(value.AsSpan(0, length), span.Slice(pos, length));
#endif
pos += amount;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteBigUni(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.BigEndianUnicode.GetBytes(value, span.Slice(pos));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLittleUni(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.Unicode.GetBytes(value, span.Slice(pos));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteBigUniNull(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.BigEndianUnicode.GetBytes(value, span.Slice(pos));
#if NO_LOCAL_INIT
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), 0); // Null terminator
#endif
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLittleUniNull(this Span<byte> span, ref int pos, string value)
{
pos += Encoding.Unicode.GetBytes(value, span.Slice(pos));
#if NO_LOCAL_INIT
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), 0); // Null terminator
#endif
pos += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(this Span<byte> span, ref int pos, Point3D p)
{
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos, 2), (ushort)p.X);
BinaryPrimitives.WriteUInt16BigEndian(span.Slice(pos + 2, 2), (ushort)p.Y);
span[pos + 4] = (byte)p.Z;
pos += 5;
}
}
}

View file

@ -1,81 +1,88 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: CityInfo.cs - Created: 2019/10/04 - Updated: 2020/01/19 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
namespace Server
{
public sealed class CityInfo
{
private Point3D m_Location;
public CityInfo(string city, string building, int description, int x, int y, int z, Map m)
{
City = city;
Building = building;
Description = description;
Location = new Point3D(x, y, z);
Map = m;
}
public CityInfo(string city, string building, int x, int y, int z, Map m) : this(city, building, 0, x, y, z, m)
{
}
public CityInfo(string city, string building, int description, int x, int y, int z) : this(city, building,
description, x, y, z, Map.Trammel)
{
}
public CityInfo(string city, string building, int x, int y, int z) : this(city, building, 0, x, y, z, Map.Trammel)
{
}
public string City { get; set; }
public string Building { get; set; }
public int Description { get; set; }
public int X
{
get => m_Location.X;
set => m_Location.X = value;
}
public int Y
{
get => m_Location.Y;
set => m_Location.Y = value;
}
public int Z
{
get => m_Location.Z;
set => m_Location.Z = value;
}
public Point3D Location
{
get => m_Location;
set => m_Location = value;
}
public Map Map { get; set; }
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: CityInfo.cs - Created: 2019/10/04 - Updated: 2020/01/19 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
namespace Server
{
public sealed class CityInfo
{
private Point3D m_Location;
public CityInfo(string city, string building, int description, int x, int y, int z, Map m)
{
City = city;
Building = building;
Description = description;
Location = new Point3D(x, y, z);
Map = m;
}
public CityInfo(string city, string building, int x, int y, int z, Map m) : this(city, building, 0, x, y, z, m)
{
}
public CityInfo(string city, string building, int description, int x, int y, int z) : this(
city,
building,
description,
x,
y,
z,
Map.Trammel
)
{
}
public CityInfo(string city, string building, int x, int y, int z) : this(city, building, 0, x, y, z, Map.Trammel)
{
}
public string City { get; set; }
public string Building { get; set; }
public int Description { get; set; }
public int X
{
get => m_Location.X;
set => m_Location.X = value;
}
public int Y
{
get => m_Location.Y;
set => m_Location.Y = value;
}
public int Z
{
get => m_Location.Z;
set => m_Location.Z = value;
}
public Point3D Location
{
get => m_Location;
set => m_Location = value;
}
public Map Map { get; set; }
}
}

View file

@ -1,207 +1,207 @@
/***************************************************************************
* ClientVersion.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace Server
{
public enum ClientType
{
Regular,
UOTD,
God,
SA
}
public class ClientVersion : IComparable<ClientVersion>, IComparer<ClientVersion>
{
public ClientVersion(int maj, int min, int rev, int pat, ClientType type = ClientType.Regular)
{
Major = maj;
Minor = min;
Revision = rev;
Patch = pat;
Type = type;
SourceString = ToStringImpl();
}
public ClientVersion(string fmt)
{
SourceString = fmt;
try
{
fmt = fmt.ToLower();
var br1 = fmt.IndexOf('.');
var br2 = fmt.IndexOf('.', br1 + 1);
var br3 = br2 + 1;
while (br3 < fmt.Length && char.IsDigit(fmt, br3))
br3++;
Major = Utility.ToInt32(fmt.Substring(0, br1));
Minor = Utility.ToInt32(fmt.Substring(br1 + 1, br2 - br1 - 1));
Revision = Utility.ToInt32(fmt.Substring(br2 + 1, br3 - br2 - 1));
if (br3 < fmt.Length)
{
if (Major <= 5 && Minor <= 0 && Revision <= 6) // Anything before 5.0.7
{
if (!char.IsWhiteSpace(fmt, br3))
Patch = fmt[br3] - 'a' + 1;
}
else
{
Patch = Utility.ToInt32(fmt.Substring(br3 + 1, fmt.Length - br3 - 1));
}
}
if (fmt.IndexOf("god") >= 0 || fmt.IndexOf("gq") >= 0)
Type = ClientType.God;
else if (fmt.IndexOf("third dawn") >= 0 || fmt.IndexOf("uo:td") >= 0 || fmt.IndexOf("uotd") >= 0 ||
fmt.IndexOf("uo3d") >= 0 || fmt.IndexOf("uo:3d") >= 0)
Type = ClientType.UOTD;
else
Type = ClientType.Regular;
}
catch
{
Major = 0;
Minor = 0;
Revision = 0;
Patch = 0;
Type = ClientType.Regular;
}
}
public int Major { get; }
public int Minor { get; }
public int Revision { get; }
public int Patch { get; }
public ClientType Type { get; }
public string SourceString { get; }
public int CompareTo(ClientVersion o)
{
if (o == null)
return 1;
if (Major > o.Major)
return 1;
if (Major < o.Major)
return -1;
if (Minor > o.Minor)
return 1;
if (Minor < o.Minor)
return -1;
if (Revision > o.Revision)
return 1;
if (Revision < o.Revision)
return -1;
if (Patch > o.Patch)
return 1;
if (Patch < o.Patch)
return -1;
return 0;
}
public static bool operator ==(ClientVersion l, ClientVersion r) => Compare(l, r) == 0;
public static bool operator !=(ClientVersion l, ClientVersion r) => Compare(l, r) != 0;
public static bool operator >=(ClientVersion l, ClientVersion r) => Compare(l, r) >= 0;
public static bool operator >(ClientVersion l, ClientVersion r) => Compare(l, r) > 0;
public static bool operator <=(ClientVersion l, ClientVersion r) => Compare(l, r) <= 0;
public static bool operator <(ClientVersion l, ClientVersion r) => Compare(l, r) < 0;
public override int GetHashCode() => Major ^ Minor ^ Revision ^ Patch ^ (int)Type;
int IComparer<ClientVersion>.Compare(ClientVersion x, ClientVersion y) => Compare(x, y);
public override bool Equals(object obj)
{
var v = obj as ClientVersion;
return Major == v?.Major
&& Minor == v.Minor
&& Revision == v.Revision
&& Patch == v.Patch
&& Type == v.Type;
}
private string ToStringImpl()
{
var builder = new StringBuilder(16);
builder.Append(Major);
builder.Append('.');
builder.Append(Minor);
builder.Append('.');
builder.Append(Revision);
if (Major <= 5 && Minor <= 0 && Revision <= 6) // Anything before 5.0.7
{
if (Patch > 0)
builder.Append((char)('a' + (Patch - 1)));
}
else
{
builder.Append('.');
builder.Append(Patch);
}
if (Type != ClientType.Regular)
{
builder.Append(' ');
builder.Append(Type.ToString());
}
return builder.ToString();
}
public override string ToString() => ToStringImpl();
public static bool IsNull(object x) => ReferenceEquals(x, null);
public static int Compare(ClientVersion a, ClientVersion b)
{
if (IsNull(a) && IsNull(b))
return 0;
if (IsNull(a))
return -1;
if (IsNull(b))
return 1;
return a.CompareTo(b);
}
}
}
/***************************************************************************
* ClientVersion.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace Server
{
public enum ClientType
{
Regular,
UOTD,
God,
SA
}
public class ClientVersion : IComparable<ClientVersion>, IComparer<ClientVersion>
{
public ClientVersion(int maj, int min, int rev, int pat, ClientType type = ClientType.Regular)
{
Major = maj;
Minor = min;
Revision = rev;
Patch = pat;
Type = type;
SourceString = ToStringImpl();
}
public ClientVersion(string fmt)
{
SourceString = fmt;
try
{
fmt = fmt.ToLower();
var br1 = fmt.IndexOf('.');
var br2 = fmt.IndexOf('.', br1 + 1);
var br3 = br2 + 1;
while (br3 < fmt.Length && char.IsDigit(fmt, br3))
br3++;
Major = Utility.ToInt32(fmt.Substring(0, br1));
Minor = Utility.ToInt32(fmt.Substring(br1 + 1, br2 - br1 - 1));
Revision = Utility.ToInt32(fmt.Substring(br2 + 1, br3 - br2 - 1));
if (br3 < fmt.Length)
{
if (Major <= 5 && Minor <= 0 && Revision <= 6) // Anything before 5.0.7
{
if (!char.IsWhiteSpace(fmt, br3))
Patch = fmt[br3] - 'a' + 1;
}
else
{
Patch = Utility.ToInt32(fmt.Substring(br3 + 1, fmt.Length - br3 - 1));
}
}
if (fmt.IndexOf("god") >= 0 || fmt.IndexOf("gq") >= 0)
Type = ClientType.God;
else if (fmt.IndexOf("third dawn") >= 0 || fmt.IndexOf("uo:td") >= 0 || fmt.IndexOf("uotd") >= 0 ||
fmt.IndexOf("uo3d") >= 0 || fmt.IndexOf("uo:3d") >= 0)
Type = ClientType.UOTD;
else
Type = ClientType.Regular;
}
catch
{
Major = 0;
Minor = 0;
Revision = 0;
Patch = 0;
Type = ClientType.Regular;
}
}
public int Major { get; }
public int Minor { get; }
public int Revision { get; }
public int Patch { get; }
public ClientType Type { get; }
public string SourceString { get; }
public int CompareTo(ClientVersion o)
{
if (o == null)
return 1;
if (Major > o.Major)
return 1;
if (Major < o.Major)
return -1;
if (Minor > o.Minor)
return 1;
if (Minor < o.Minor)
return -1;
if (Revision > o.Revision)
return 1;
if (Revision < o.Revision)
return -1;
if (Patch > o.Patch)
return 1;
if (Patch < o.Patch)
return -1;
return 0;
}
int IComparer<ClientVersion>.Compare(ClientVersion x, ClientVersion y) => Compare(x, y);
public static bool operator ==(ClientVersion l, ClientVersion r) => Compare(l, r) == 0;
public static bool operator !=(ClientVersion l, ClientVersion r) => Compare(l, r) != 0;
public static bool operator >=(ClientVersion l, ClientVersion r) => Compare(l, r) >= 0;
public static bool operator >(ClientVersion l, ClientVersion r) => Compare(l, r) > 0;
public static bool operator <=(ClientVersion l, ClientVersion r) => Compare(l, r) <= 0;
public static bool operator <(ClientVersion l, ClientVersion r) => Compare(l, r) < 0;
public override int GetHashCode() => Major ^ Minor ^ Revision ^ Patch ^ (int)Type;
public override bool Equals(object obj)
{
var v = obj as ClientVersion;
return Major == v?.Major
&& Minor == v.Minor
&& Revision == v.Revision
&& Patch == v.Patch
&& Type == v.Type;
}
private string ToStringImpl()
{
var builder = new StringBuilder(16);
builder.Append(Major);
builder.Append('.');
builder.Append(Minor);
builder.Append('.');
builder.Append(Revision);
if (Major <= 5 && Minor <= 0 && Revision <= 6) // Anything before 5.0.7
{
if (Patch > 0)
builder.Append((char)('a' + (Patch - 1)));
}
else
{
builder.Append('.');
builder.Append(Patch);
}
if (Type != ClientType.Regular)
{
builder.Append(' ');
builder.Append(Type.ToString());
}
return builder.ToString();
}
public override string ToString() => ToStringImpl();
public static bool IsNull(object x) => ReferenceEquals(x, null);
public static int Compare(ClientVersion a, ClientVersion b)
{
if (IsNull(a) && IsNull(b))
return 0;
if (IsNull(a))
return -1;
if (IsNull(b))
return 1;
return a.CompareTo(b);
}
}
}

View file

@ -1,75 +1,76 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ArraySet.cs - Created: 2019/10/04 - Updated: 2019/12/30 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Server.Collections
{
public class ArraySet<T> : IList<T>
{
private readonly List<T> m_List = new List<T>();
public T this[int index]
{
get => m_List[index];
set => m_List[index] = value;
}
public int Count => m_List.Count;
public bool IsReadOnly => false;
public int Add(T item)
{
var indexOf = m_List.IndexOf(item);
if (indexOf >= 0) return indexOf;
m_List.Add(item);
return m_List.Count - 1;
}
public void Clear() => m_List.Clear();
public bool Contains(T item) => m_List.Contains(item);
public void CopyTo(T[] array) => m_List.CopyTo(array);
public void CopyTo(T[] array, int arrayIndex) => m_List.CopyTo(array, arrayIndex);
public void CopyTo(int index, T[] array, int arrayIndex, int count) => m_List.CopyTo(index, array, arrayIndex, count);
public IEnumerator<T> GetEnumerator() => m_List.GetEnumerator();
public int IndexOf(T item) => m_List.IndexOf(item);
public void Insert(int index, T item) => throw new NotImplementedException();
public bool Remove(T item) => throw new NotImplementedException();
public void RemoveAt(int index) => throw new NotImplementedException();
void ICollection<T>.Add(T item) => m_List.Add(item);
IEnumerator IEnumerable.GetEnumerator() => m_List.GetEnumerator();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ArraySet.cs - Created: 2019/10/04 - Updated: 2019/12/30 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Server.Collections
{
public class ArraySet<T> : IList<T>
{
private readonly List<T> m_List = new List<T>();
public T this[int index]
{
get => m_List[index];
set => m_List[index] = value;
}
public int Count => m_List.Count;
public bool IsReadOnly => false;
public void Clear() => m_List.Clear();
public bool Contains(T item) => m_List.Contains(item);
public void CopyTo(T[] array, int arrayIndex) => m_List.CopyTo(array, arrayIndex);
public IEnumerator<T> GetEnumerator() => m_List.GetEnumerator();
public int IndexOf(T item) => m_List.IndexOf(item);
public void Insert(int index, T item) => throw new NotImplementedException();
public bool Remove(T item) => throw new NotImplementedException();
public void RemoveAt(int index) => throw new NotImplementedException();
void ICollection<T>.Add(T item) => m_List.Add(item);
IEnumerator IEnumerable.GetEnumerator() => m_List.GetEnumerator();
public int Add(T item)
{
var indexOf = m_List.IndexOf(item);
if (indexOf >= 0) return indexOf;
m_List.Add(item);
return m_List.Count - 1;
}
public void CopyTo(T[] array) => m_List.CopyTo(array);
public void CopyTo(int index, T[] array, int arrayIndex, int count) =>
m_List.CopyTo(index, array, arrayIndex, count);
}
}

View file

@ -1,245 +1,245 @@
/***************************************************************************
* Commands.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using Server.Network;
namespace Server
{
public delegate void CommandEventHandler(CommandEventArgs e);
public class CommandEventArgs : EventArgs
{
public CommandEventArgs(Mobile mobile, string command, string argString, string[] arguments)
{
Mobile = mobile;
Command = command;
ArgString = argString;
Arguments = arguments;
}
public Mobile Mobile { get; }
public string Command { get; }
public string ArgString { get; }
public string[] Arguments { get; }
public int Length => Arguments.Length;
public string GetString(int index)
{
if (index < 0 || index >= Arguments.Length)
return "";
return Arguments[index];
}
public int GetInt32(int index)
{
if (index < 0 || index >= Arguments.Length)
return 0;
return Utility.ToInt32(Arguments[index]);
}
public uint GetUInt32(int index)
{
if (index < 0 || index >= Arguments.Length)
return 0;
return Utility.ToUInt32(Arguments[index]);
}
public bool GetBoolean(int index)
{
if (index < 0 || index >= Arguments.Length)
return false;
return Utility.ToBoolean(Arguments[index]);
}
public double GetDouble(int index)
{
if (index < 0 || index >= Arguments.Length)
return 0.0;
return Utility.ToDouble(Arguments[index]);
}
public TimeSpan GetTimeSpan(int index)
{
if (index < 0 || index >= Arguments.Length)
return TimeSpan.Zero;
return Utility.ToTimeSpan(Arguments[index]);
}
}
public static partial class EventSink
{
public static event Action<CommandEventArgs> Command;
public static void InvokeCommand(CommandEventArgs e) => Command?.Invoke(e);
}
public class CommandEntry : IComparable<CommandEntry>
{
public CommandEntry(string command, CommandEventHandler handler, AccessLevel accessLevel)
{
Command = command;
Handler = handler;
AccessLevel = accessLevel;
}
public string Command { get; }
public CommandEventHandler Handler { get; }
public AccessLevel AccessLevel { get; }
public int CompareTo(CommandEntry e) => e == null ? 1 : Command.CompareTo(e.Command);
}
public static class CommandSystem
{
public static string Prefix { get; set; } = "[";
public static Dictionary<string, CommandEntry> Entries { get; } =
new Dictionary<string, CommandEntry>(StringComparer.OrdinalIgnoreCase);
public static AccessLevel BadCommandIgnoreLevel { get; set; } = AccessLevel.Player;
public static string[] Split(string value)
{
var array = value.ToCharArray();
var list = new List<string>();
var start = 0;
while (start < array.Length)
{
var c = array[start];
if (c == '"')
{
++start;
var end = start;
while (end < array.Length)
if (array[end] != '"' || array[end - 1] == '\\')
++end;
else
break;
list.Add(value.Substring(start, end - start));
start = end + 2;
}
else if (c != ' ')
{
var end = start;
while (end < array.Length)
if (array[end] != ' ')
++end;
else
break;
list.Add(value.Substring(start, end - start));
start = end + 1;
}
else
{
++start;
}
}
return list.ToArray();
}
public static void Register(string command, AccessLevel access, CommandEventHandler handler)
{
Entries[command] = new CommandEntry(command, handler, access);
}
public static bool Handle(Mobile from, string text, MessageType type = MessageType.Regular)
{
if (!text.StartsWith(Prefix) && type != MessageType.Command)
return false;
if (type != MessageType.Command)
text = text.Substring(Prefix.Length);
var indexOf = text.IndexOf(' ');
string command;
string[] args;
string argString;
if (indexOf >= 0)
{
argString = text.Substring(indexOf + 1);
command = text.Substring(0, indexOf);
args = Split(argString);
}
else
{
argString = "";
command = text.ToLower();
args = Array.Empty<string>();
}
Entries.TryGetValue(command, out var entry);
if (entry != null)
{
if (from.AccessLevel >= entry.AccessLevel)
{
if (entry.Handler != null)
{
var e = new CommandEventArgs(from, command, argString, args);
entry.Handler(e);
EventSink.InvokeCommand(e);
}
}
else
{
if (from.AccessLevel <= BadCommandIgnoreLevel)
return false;
from.SendMessage("You do not have access to that command.");
}
}
else
{
if (from.AccessLevel <= BadCommandIgnoreLevel)
return false;
from.SendMessage("That is not a valid command.");
}
return true;
}
}
}
/***************************************************************************
* Commands.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using Server.Network;
namespace Server
{
public delegate void CommandEventHandler(CommandEventArgs e);
public class CommandEventArgs : EventArgs
{
public CommandEventArgs(Mobile mobile, string command, string argString, string[] arguments)
{
Mobile = mobile;
Command = command;
ArgString = argString;
Arguments = arguments;
}
public Mobile Mobile { get; }
public string Command { get; }
public string ArgString { get; }
public string[] Arguments { get; }
public int Length => Arguments.Length;
public string GetString(int index)
{
if (index < 0 || index >= Arguments.Length)
return "";
return Arguments[index];
}
public int GetInt32(int index)
{
if (index < 0 || index >= Arguments.Length)
return 0;
return Utility.ToInt32(Arguments[index]);
}
public uint GetUInt32(int index)
{
if (index < 0 || index >= Arguments.Length)
return 0;
return Utility.ToUInt32(Arguments[index]);
}
public bool GetBoolean(int index)
{
if (index < 0 || index >= Arguments.Length)
return false;
return Utility.ToBoolean(Arguments[index]);
}
public double GetDouble(int index)
{
if (index < 0 || index >= Arguments.Length)
return 0.0;
return Utility.ToDouble(Arguments[index]);
}
public TimeSpan GetTimeSpan(int index)
{
if (index < 0 || index >= Arguments.Length)
return TimeSpan.Zero;
return Utility.ToTimeSpan(Arguments[index]);
}
}
public static partial class EventSink
{
public static event Action<CommandEventArgs> Command;
public static void InvokeCommand(CommandEventArgs e) => Command?.Invoke(e);
}
public class CommandEntry : IComparable<CommandEntry>
{
public CommandEntry(string command, CommandEventHandler handler, AccessLevel accessLevel)
{
Command = command;
Handler = handler;
AccessLevel = accessLevel;
}
public string Command { get; }
public CommandEventHandler Handler { get; }
public AccessLevel AccessLevel { get; }
public int CompareTo(CommandEntry e) => e == null ? 1 : Command.CompareTo(e.Command);
}
public static class CommandSystem
{
public static string Prefix { get; set; } = "[";
public static Dictionary<string, CommandEntry> Entries { get; } =
new Dictionary<string, CommandEntry>(StringComparer.OrdinalIgnoreCase);
public static AccessLevel BadCommandIgnoreLevel { get; set; } = AccessLevel.Player;
public static string[] Split(string value)
{
var array = value.ToCharArray();
var list = new List<string>();
var start = 0;
while (start < array.Length)
{
var c = array[start];
if (c == '"')
{
++start;
var end = start;
while (end < array.Length)
if (array[end] != '"' || array[end - 1] == '\\')
++end;
else
break;
list.Add(value.Substring(start, end - start));
start = end + 2;
}
else if (c != ' ')
{
var end = start;
while (end < array.Length)
if (array[end] != ' ')
++end;
else
break;
list.Add(value.Substring(start, end - start));
start = end + 1;
}
else
{
++start;
}
}
return list.ToArray();
}
public static void Register(string command, AccessLevel access, CommandEventHandler handler)
{
Entries[command] = new CommandEntry(command, handler, access);
}
public static bool Handle(Mobile from, string text, MessageType type = MessageType.Regular)
{
if (!text.StartsWith(Prefix) && type != MessageType.Command)
return false;
if (type != MessageType.Command)
text = text.Substring(Prefix.Length);
var indexOf = text.IndexOf(' ');
string command;
string[] args;
string argString;
if (indexOf >= 0)
{
argString = text.Substring(indexOf + 1);
command = text.Substring(0, indexOf);
args = Split(argString);
}
else
{
argString = "";
command = text.ToLower();
args = Array.Empty<string>();
}
Entries.TryGetValue(command, out var entry);
if (entry != null)
{
if (from.AccessLevel >= entry.AccessLevel)
{
if (entry.Handler != null)
{
var e = new CommandEventArgs(from, command, argString, args);
entry.Handler(e);
EventSink.InvokeCommand(e);
}
}
else
{
if (from.AccessLevel <= BadCommandIgnoreLevel)
return false;
from.SendMessage("You do not have access to that command.");
}
}
else
{
if (from.AccessLevel <= BadCommandIgnoreLevel)
return false;
from.SendMessage("That is not a valid command.");
}
return true;
}
}
}

View file

@ -1,278 +1,277 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerConfiguration.cs *
* Created: 2019/10/04 - Updated: 2020/07/03 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.Json.Serialization;
using Server.Json;
namespace Server
{
public static class ServerConfiguration
{
private const string m_RelPath = "Configuration/modernuo.json";
private static readonly string m_FilePath = Path.Join(Core.BaseDirectory, m_RelPath);
private static ServerSettings m_Settings;
private static bool m_Mocked;
public static List<string> DataDirectories => m_Settings.dataDirectories;
public static List<IPEndPoint> Listeners => m_Settings.listeners;
public static string GetSetting(string key, string defaultValue)
{
m_Settings.settings.TryGetValue(key, out string value);
return value == "(-null-)" ? null : value ?? defaultValue;
}
public static int GetSetting(string key, int defaultValue)
{
m_Settings.settings.TryGetValue(key, out string strValue);
return int.TryParse(strValue, out int value) ? value : defaultValue;
}
public static bool GetSetting(string key, bool defaultValue)
{
m_Settings.settings.TryGetValue(key, out string strValue);
return bool.TryParse(strValue, out bool value) ? value : defaultValue;
}
public static T GetSetting<T>(string key, T defaultValue) where T : struct, Enum
{
m_Settings.settings.TryGetValue(key, out string strValue);
return Enum.TryParse(strValue, out T value) ? value : defaultValue;
}
public static string GetOrUpdateSetting(string key, string defaultValue)
{
if (m_Settings.settings.TryGetValue(key, out string value))
return value;
SetSetting(key, value = defaultValue);
return value;
}
public static int GetOrUpdateSetting(string key, int defaultValue)
{
int value;
if (m_Settings.settings.TryGetValue(key, out string strValue))
value = int.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static bool GetOrUpdateSetting(string key, bool defaultValue)
{
bool value;
if (m_Settings.settings.TryGetValue(key, out string strValue))
value = bool.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static TimeSpan GetOrUpdateSetting(string key, TimeSpan defaultValue)
{
TimeSpan value;
if (m_Settings.settings.TryGetValue(key, out string strValue))
value = TimeSpan.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static T GetOrUpdateSetting<T>(string key, T defaultValue) where T : struct, Enum
{
T value;
if (m_Settings.settings.TryGetValue(key, out string strValue))
value = Enum.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static void SetSetting(string key, string value)
{
m_Settings.settings[key] = value;
Save();
}
public static T GetMetadata<T>(string key) where T : class
{
m_Settings.metadata.TryGetValue(key, out object value);
return value as T;
}
public static void SetMetadata(string key, object value)
{
m_Settings.metadata[key] = value;
}
// If mock is enabled we skip the console readline.
public static void Load(bool mocked = false)
{
m_Mocked = mocked;
bool updated = false;
if (File.Exists(m_FilePath))
{
Console.Write($"Core: Reading configuration from {m_RelPath}...");
m_Settings = JsonConfig.Deserialize<ServerSettings>(m_FilePath);
if (m_Settings == null)
{
Utility.PushColor(ConsoleColor.Red);
Console.WriteLine("failed");
Utility.PopColor();
throw new Exception("Core: Server configuration failed to deserialize.");
}
Console.WriteLine("done");
}
else
{
updated = true;
m_Settings = new ServerSettings();
}
if (mocked)
return;
if (m_Settings.dataDirectories.Count == 0)
{
updated = true;
Utility.PushColor(ConsoleColor.DarkYellow);
Console.WriteLine("Core: Server configuration is missing data directories.");
Utility.PopColor();
m_Settings.dataDirectories.AddRange(GetDataDirectories());
}
if (m_Settings.listeners.Count == 0)
{
updated = true;
Utility.PushColor(ConsoleColor.DarkYellow);
Console.WriteLine("Core: Server is missing socket listener IP addresses.");
Utility.PopColor();
m_Settings.listeners.AddRange(GetListeners());
}
if (updated)
{
Save();
Utility.PushColor(ConsoleColor.Green);
Console.WriteLine($"Core: Configuration saved to {m_RelPath}.");
Utility.PopColor();
}
}
internal class ServerSettings
{
[JsonPropertyName("dataDirectories")]
public List<string> dataDirectories { get; set; } = new List<string>();
[JsonPropertyName("listeners")]
public List<IPEndPoint> listeners { get; set; } = new List<IPEndPoint>();
[JsonPropertyName("settings")]
public Dictionary<string, string> settings { get; set; } = new Dictionary<string, string>();
[JsonExtensionData]
public Dictionary<string, object> metadata { get; set; } = new Dictionary<string, object>();
}
private static List<string> GetDataDirectories()
{
Console.WriteLine("Please enter the absolute path to the Ultima Online data:");
List<string> directories = new List<string>();
do
{
Console.Write("{0}> ", directories.Count > 0 ? "[finish] " : " ");
var directory = Console.ReadLine();
if (string.IsNullOrWhiteSpace(directory)) break;
if (Directory.Exists(directory))
{
directories.Add(directory);
Console.WriteLine("Core: Path {0} added.", directory);
}
else
Console.WriteLine("Core: Path does not exist. ({0})");
} while (true);
return directories;
}
private static List<IPEndPoint> GetListeners()
{
Console.WriteLine("Please enter the IP and ports to listen:");
Console.WriteLine(" - Only enter IP addresses directly bound to this machine");
Console.WriteLine(" - To listen to all IP addresses enter 0.0.0.0");
List<IPEndPoint> ips = new List<IPEndPoint>();
do
{ // IP:Port?
Console.Write("[{0}]> ", ips.Count > 0 ? "finish" : "0.0.0.0:2593");
var ipStr = Console.ReadLine();
if (string.IsNullOrWhiteSpace(ipStr)) break;
if (ipStr.IndexOf(":", StringComparison.Ordinal) == -1)
ipStr += ":2593";
if (IPEndPoint.TryParse(ipStr, out var ip))
{
ips.Add(ip);
Console.WriteLine("Core: {0} added.", ipStr);
}
else
{
Console.WriteLine("Core: {0} is not a valid IP or port");
}
} while (true);
if (ips.Count == 0)
ips.Add(new IPEndPoint(IPAddress.Any, 2593));
return ips;
}
public static void Save()
{
if (m_Mocked) return;
JsonConfig.Serialize(m_FilePath, m_Settings);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerConfiguration.cs *
* Created: 2019/10/04 - Updated: 2020/07/03 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.Json.Serialization;
using Server.Json;
namespace Server
{
public static class ServerConfiguration
{
private const string m_RelPath = "Configuration/modernuo.json";
private static readonly string m_FilePath = Path.Join(Core.BaseDirectory, m_RelPath);
private static ServerSettings m_Settings;
private static bool m_Mocked;
public static List<string> DataDirectories => m_Settings.dataDirectories;
public static List<IPEndPoint> Listeners => m_Settings.listeners;
public static string GetSetting(string key, string defaultValue)
{
m_Settings.settings.TryGetValue(key, out var value);
return value == "(-null-)" ? null : value ?? defaultValue;
}
public static int GetSetting(string key, int defaultValue)
{
m_Settings.settings.TryGetValue(key, out var strValue);
return int.TryParse(strValue, out var value) ? value : defaultValue;
}
public static bool GetSetting(string key, bool defaultValue)
{
m_Settings.settings.TryGetValue(key, out var strValue);
return bool.TryParse(strValue, out var value) ? value : defaultValue;
}
public static T GetSetting<T>(string key, T defaultValue) where T : struct, Enum
{
m_Settings.settings.TryGetValue(key, out var strValue);
return Enum.TryParse(strValue, out T value) ? value : defaultValue;
}
public static string GetOrUpdateSetting(string key, string defaultValue)
{
if (m_Settings.settings.TryGetValue(key, out var value))
return value;
SetSetting(key, value = defaultValue);
return value;
}
public static int GetOrUpdateSetting(string key, int defaultValue)
{
int value;
if (m_Settings.settings.TryGetValue(key, out var strValue))
value = int.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static bool GetOrUpdateSetting(string key, bool defaultValue)
{
bool value;
if (m_Settings.settings.TryGetValue(key, out var strValue))
value = bool.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static TimeSpan GetOrUpdateSetting(string key, TimeSpan defaultValue)
{
TimeSpan value;
if (m_Settings.settings.TryGetValue(key, out var strValue))
value = TimeSpan.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static T GetOrUpdateSetting<T>(string key, T defaultValue) where T : struct, Enum
{
T value;
if (m_Settings.settings.TryGetValue(key, out var strValue))
value = Enum.TryParse(strValue, out value) ? value : defaultValue;
else
SetSetting(key, (value = defaultValue).ToString());
return value;
}
public static void SetSetting(string key, string value)
{
m_Settings.settings[key] = value;
Save();
}
public static T GetMetadata<T>(string key) where T : class
{
m_Settings.metadata.TryGetValue(key, out var value);
return value as T;
}
public static void SetMetadata(string key, object value)
{
m_Settings.metadata[key] = value;
}
// If mock is enabled we skip the console readline.
public static void Load(bool mocked = false)
{
m_Mocked = mocked;
var updated = false;
if (File.Exists(m_FilePath))
{
Console.Write($"Core: Reading configuration from {m_RelPath}...");
m_Settings = JsonConfig.Deserialize<ServerSettings>(m_FilePath);
if (m_Settings == null)
{
Utility.PushColor(ConsoleColor.Red);
Console.WriteLine("failed");
Utility.PopColor();
throw new Exception("Core: Server configuration failed to deserialize.");
}
Console.WriteLine("done");
}
else
{
updated = true;
m_Settings = new ServerSettings();
}
if (mocked)
return;
if (m_Settings.dataDirectories.Count == 0)
{
updated = true;
Utility.PushColor(ConsoleColor.DarkYellow);
Console.WriteLine("Core: Server configuration is missing data directories.");
Utility.PopColor();
m_Settings.dataDirectories.AddRange(GetDataDirectories());
}
if (m_Settings.listeners.Count == 0)
{
updated = true;
Utility.PushColor(ConsoleColor.DarkYellow);
Console.WriteLine("Core: Server is missing socket listener IP addresses.");
Utility.PopColor();
m_Settings.listeners.AddRange(GetListeners());
}
if (updated)
{
Save();
Utility.PushColor(ConsoleColor.Green);
Console.WriteLine($"Core: Configuration saved to {m_RelPath}.");
Utility.PopColor();
}
}
private static List<string> GetDataDirectories()
{
Console.WriteLine("Please enter the absolute path to the Ultima Online data:");
var directories = new List<string>();
do
{
Console.Write("{0}> ", directories.Count > 0 ? "[finish] " : " ");
var directory = Console.ReadLine();
if (string.IsNullOrWhiteSpace(directory)) break;
if (Directory.Exists(directory))
{
directories.Add(directory);
Console.WriteLine("Core: Path {0} added.", directory);
}
else
{
Console.WriteLine("Core: Path does not exist. ({0})");
}
} while (true);
return directories;
}
private static List<IPEndPoint> GetListeners()
{
Console.WriteLine("Please enter the IP and ports to listen:");
Console.WriteLine(" - Only enter IP addresses directly bound to this machine");
Console.WriteLine(" - To listen to all IP addresses enter 0.0.0.0");
var ips = new List<IPEndPoint>();
do
{
// IP:Port?
Console.Write("[{0}]> ", ips.Count > 0 ? "finish" : "0.0.0.0:2593");
var ipStr = Console.ReadLine();
if (string.IsNullOrWhiteSpace(ipStr)) break;
if (ipStr.IndexOf(":", StringComparison.Ordinal) == -1)
ipStr += ":2593";
if (IPEndPoint.TryParse(ipStr, out var ip))
{
ips.Add(ip);
Console.WriteLine("Core: {0} added.", ipStr);
}
else
{
Console.WriteLine("Core: {0} is not a valid IP or port");
}
} while (true);
if (ips.Count == 0)
ips.Add(new IPEndPoint(IPAddress.Any, 2593));
return ips;
}
public static void Save()
{
if (m_Mocked) return;
JsonConfig.Serialize(m_FilePath, m_Settings);
}
internal class ServerSettings
{
[JsonPropertyName("dataDirectories")] public List<string> dataDirectories { get; set; } = new List<string>();
[JsonPropertyName("listeners")] public List<IPEndPoint> listeners { get; set; } = new List<IPEndPoint>();
[JsonPropertyName("settings")]
public Dictionary<string, string> settings { get; set; } = new Dictionary<string, string>();
[JsonExtensionData] public Dictionary<string, object> metadata { get; set; } = new Dictionary<string, object>();
}
}
}

View file

@ -1,83 +1,84 @@
/***************************************************************************
* ContextMenu.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
using System.Linq;
namespace Server.ContextMenus
{
/// <summary>
/// Represents the state of an active context menu. This includes who opened the menu, the menu's focus object, and a list of
/// <see cref="ContextMenuEntry">entries</see> that the menu is composed of.
/// <seealso cref="ContextMenuEntry" />
/// </summary>
public class ContextMenu
{
/// <summary>
/// Instantiates a new ContextMenu instance.
/// </summary>
/// <param name="from">
/// The <see cref="Mobile" /> who opened this ContextMenu.
/// <seealso cref="From" />
/// </param>
/// <param name="target">
/// The <see cref="Mobile" /> or <see cref="Item" /> for which this ContextMenu is on.
/// <seealso cref="Target" />
/// </param>
public ContextMenu(Mobile from, IEntity target)
{
From = from;
Target = target;
var list = new List<ContextMenuEntry>();
if (target is Mobile mobile)
mobile.GetContextMenuEntries(from, list);
else if (target is Item item)
item.GetContextMenuEntries(from, list);
Entries = list.ToArray();
for (var i = 0; i < Entries.Length; ++i)
Entries[i].Owner = this;
}
/// <summary>
/// Gets the <see cref="Mobile" /> who opened this ContextMenu.
/// </summary>
public Mobile From { get; }
/// <summary>
/// Gets an object of the <see cref="Mobile" /> or <see cref="Item" /> for which this ContextMenu is on.
/// </summary>
public IEntity Target { get; }
/// <summary>
/// Gets the list of <see cref="ContextMenuEntry">entries</see> contained in this ContextMenu.
/// </summary>
public ContextMenuEntry[] Entries { get; }
/// <summary>
/// Returns true if this ContextMenu requires packet version 2.
/// </summary>
public bool RequiresNewPacket =>
Entries.Any(t => t.Number < 3000000 || t.Number > 3032767);
}
}
/***************************************************************************
* ContextMenu.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
using System.Linq;
namespace Server.ContextMenus
{
/// <summary>
/// Represents the state of an active context menu. This includes who opened the menu, the menu's focus object, and a list
/// of
/// <see cref="ContextMenuEntry">entries</see> that the menu is composed of.
/// <seealso cref="ContextMenuEntry" />
/// </summary>
public class ContextMenu
{
/// <summary>
/// Instantiates a new ContextMenu instance.
/// </summary>
/// <param name="from">
/// The <see cref="Mobile" /> who opened this ContextMenu.
/// <seealso cref="From" />
/// </param>
/// <param name="target">
/// The <see cref="Mobile" /> or <see cref="Item" /> for which this ContextMenu is on.
/// <seealso cref="Target" />
/// </param>
public ContextMenu(Mobile from, IEntity target)
{
From = from;
Target = target;
var list = new List<ContextMenuEntry>();
if (target is Mobile mobile)
mobile.GetContextMenuEntries(from, list);
else if (target is Item item)
item.GetContextMenuEntries(from, list);
Entries = list.ToArray();
for (var i = 0; i < Entries.Length; ++i)
Entries[i].Owner = this;
}
/// <summary>
/// Gets the <see cref="Mobile" /> who opened this ContextMenu.
/// </summary>
public Mobile From { get; }
/// <summary>
/// Gets an object of the <see cref="Mobile" /> or <see cref="Item" /> for which this ContextMenu is on.
/// </summary>
public IEntity Target { get; }
/// <summary>
/// Gets the list of <see cref="ContextMenuEntry">entries</see> contained in this ContextMenu.
/// </summary>
public ContextMenuEntry[] Entries { get; }
/// <summary>
/// Returns true if this ContextMenu requires packet version 2.
/// </summary>
public bool RequiresNewPacket =>
Entries.Any(t => t.Number < 3000000 || t.Number > 3032767);
}
}

View file

@ -1,98 +1,99 @@
/***************************************************************************
* ContextMenuEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.ContextMenus
{
/// <summary>
/// Represents a single entry of a <see cref="ContextMenu">context menu</see>.
/// <seealso cref="ContextMenu" />
/// </summary>
public class ContextMenuEntry
{
/// <summary>
/// Instantiates a new ContextMenuEntry with a given <see cref="Number">localization number</see> (<paramref name="number" />)
/// and <see cref="Range">maximum range</see> (<paramref name="range" />).
/// </summary>
/// <param name="number">
/// The localization number containing the name of this entry.
/// <seealso cref="Number" />
/// </param>
/// <param name="range">
/// The maximum range at which this entry can be used.
/// <seealso cref="Range" />
/// </param>
public ContextMenuEntry(int number, int range = -1)
{
if (number <= 0x7FFF) // Legacy code support
Number = 3000000 + number;
else
Number = number;
Range = range;
Enabled = true;
Color = 0xFFFF;
}
/// <summary>
/// Gets or sets additional <see cref="CMEFlags">flags</see> used in client communication.
/// </summary>
public CMEFlags Flags { get; set; }
/// <summary>
/// Gets or sets the <see cref="ContextMenu" /> that owns this entry.
/// </summary>
public ContextMenu Owner { get; set; }
/// <summary>
/// Gets or sets the localization number containing the name of this entry.
/// </summary>
public int Number { get; set; }
/// <summary>
/// Gets or sets the maximum range at which this entry may be used, in tiles. A value of -1 signifies no maximum range.
/// </summary>
public int Range { get; set; }
/// <summary>
/// Gets or sets the color for this entry. Format is A1-R5-G5-B5.
/// </summary>
public int Color { get; set; }
/// <summary>
/// Gets or sets whether this entry is enabled. When false, the entry will appear in a gray hue and <see cref="OnClick" />
/// will never be invoked.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Gets a value indicating if non local use of this entry is permitted.
/// </summary>
public virtual bool NonLocalUse => false;
/// <summary>
/// Overridable. Virtual event invoked when the entry is clicked.
/// </summary>
public virtual void OnClick()
{
}
}
}
/***************************************************************************
* ContextMenuEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.ContextMenus
{
/// <summary>
/// Represents a single entry of a <see cref="ContextMenu">context menu</see>.
/// <seealso cref="ContextMenu" />
/// </summary>
public class ContextMenuEntry
{
/// <summary>
/// Instantiates a new ContextMenuEntry with a given <see cref="Number">localization number</see> (
/// <paramref name="number" />)
/// and <see cref="Range">maximum range</see> (<paramref name="range" />).
/// </summary>
/// <param name="number">
/// The localization number containing the name of this entry.
/// <seealso cref="Number" />
/// </param>
/// <param name="range">
/// The maximum range at which this entry can be used.
/// <seealso cref="Range" />
/// </param>
public ContextMenuEntry(int number, int range = -1)
{
if (number <= 0x7FFF) // Legacy code support
Number = 3000000 + number;
else
Number = number;
Range = range;
Enabled = true;
Color = 0xFFFF;
}
/// <summary>
/// Gets or sets additional <see cref="CMEFlags">flags</see> used in client communication.
/// </summary>
public CMEFlags Flags { get; set; }
/// <summary>
/// Gets or sets the <see cref="ContextMenu" /> that owns this entry.
/// </summary>
public ContextMenu Owner { get; set; }
/// <summary>
/// Gets or sets the localization number containing the name of this entry.
/// </summary>
public int Number { get; set; }
/// <summary>
/// Gets or sets the maximum range at which this entry may be used, in tiles. A value of -1 signifies no maximum range.
/// </summary>
public int Range { get; set; }
/// <summary>
/// Gets or sets the color for this entry. Format is A1-R5-G5-B5.
/// </summary>
public int Color { get; set; }
/// <summary>
/// Gets or sets whether this entry is enabled. When false, the entry will appear in a gray hue and <see cref="OnClick" />
/// will never be invoked.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Gets a value indicating if non local use of this entry is permitted.
/// </summary>
public virtual bool NonLocalUse => false;
/// <summary>
/// Overridable. Virtual event invoked when the entry is clicked.
/// </summary>
public virtual void OnClick()
{
}
}
}

View file

@ -1,34 +1,34 @@
/***************************************************************************
* OpenBackpackEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server.ContextMenus
{
public class OpenBackpackEntry : ContextMenuEntry
{
private readonly Mobile m_Mobile;
public OpenBackpackEntry(Mobile m) : base(6145) => m_Mobile = m;
public override void OnClick()
{
m_Mobile.Use(m_Mobile.Backpack);
}
}
}
/***************************************************************************
* OpenBackpackEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server.ContextMenus
{
public class OpenBackpackEntry : ContextMenuEntry
{
private readonly Mobile m_Mobile;
public OpenBackpackEntry(Mobile m) : base(6145) => m_Mobile = m;
public override void OnClick()
{
m_Mobile.Use(m_Mobile.Backpack);
}
}
}

View file

@ -1,35 +1,35 @@
/***************************************************************************
* PaperdollEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server.ContextMenus
{
public class PaperdollEntry : ContextMenuEntry
{
private readonly Mobile m_Mobile;
public PaperdollEntry(Mobile m) : base(6123, 18) => m_Mobile = m;
public override void OnClick()
{
if (m_Mobile.CanPaperdollBeOpenedBy(Owner.From))
m_Mobile.DisplayPaperdollTo(Owner.From);
}
}
}
/***************************************************************************
* PaperdollEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server.ContextMenus
{
public class PaperdollEntry : ContextMenuEntry
{
private readonly Mobile m_Mobile;
public PaperdollEntry(Mobile m) : base(6123, 18) => m_Mobile = m;
public override void OnClick()
{
if (m_Mobile.CanPaperdollBeOpenedBy(Owner.From))
m_Mobile.DisplayPaperdollTo(Owner.From);
}
}
}

View file

@ -1,88 +1,94 @@
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Server.Diagnostics
{
public abstract class BaseProfile
{
private readonly Stopwatch _stopwatch;
protected BaseProfile(string name)
{
Name = name;
_stopwatch = new Stopwatch();
}
public string Name { get; }
public long Count { get; private set; }
public TimeSpan AverageTime => TimeSpan.FromTicks(TotalTime.Ticks / Math.Max(Count, 1));
public TimeSpan PeakTime { get; private set; }
public TimeSpan TotalTime { get; private set; }
public static void WriteAll<T>(TextWriter op, IEnumerable<T> profiles) where T : BaseProfile
{
var list = new List<T>(profiles);
list.Sort((a, b) => -a.TotalTime.CompareTo(b.TotalTime));
foreach (var prof in list)
{
prof.WriteTo(op);
op.WriteLine();
}
}
public virtual void Start()
{
if (_stopwatch.IsRunning) _stopwatch.Reset();
_stopwatch.Start();
}
public virtual void Finish()
{
var elapsed = _stopwatch.Elapsed;
TotalTime += elapsed;
if (elapsed > PeakTime) PeakTime = elapsed;
Count++;
_stopwatch.Reset();
}
public virtual void WriteTo(TextWriter op)
{
op.Write("{0,-100} {1,12:N0} {2,12:F5} {3,-12:F5} {4,12:F5}", Name, Count, AverageTime.TotalSeconds,
PeakTime.TotalSeconds, TotalTime.TotalSeconds);
}
}
}
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Server.Diagnostics
{
public abstract class BaseProfile
{
private readonly Stopwatch _stopwatch;
protected BaseProfile(string name)
{
Name = name;
_stopwatch = new Stopwatch();
}
public string Name { get; }
public long Count { get; private set; }
public TimeSpan AverageTime => TimeSpan.FromTicks(TotalTime.Ticks / Math.Max(Count, 1));
public TimeSpan PeakTime { get; private set; }
public TimeSpan TotalTime { get; private set; }
public static void WriteAll<T>(TextWriter op, IEnumerable<T> profiles) where T : BaseProfile
{
var list = new List<T>(profiles);
list.Sort((a, b) => -a.TotalTime.CompareTo(b.TotalTime));
foreach (var prof in list)
{
prof.WriteTo(op);
op.WriteLine();
}
}
public virtual void Start()
{
if (_stopwatch.IsRunning) _stopwatch.Reset();
_stopwatch.Start();
}
public virtual void Finish()
{
var elapsed = _stopwatch.Elapsed;
TotalTime += elapsed;
if (elapsed > PeakTime) PeakTime = elapsed;
Count++;
_stopwatch.Reset();
}
public virtual void WriteTo(TextWriter op)
{
op.Write(
"{0,-100} {1,12:N0} {2,12:F5} {3,-12:F5} {4,12:F5}",
Name,
Count,
AverageTime.TotalSeconds,
PeakTime.TotalSeconds,
TotalTime.TotalSeconds
);
}
}
}

View file

@ -1,47 +1,47 @@
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Server.Diagnostics
{
public class GumpProfile : BaseProfile
{
private static readonly Dictionary<Type, GumpProfile> _profiles = new Dictionary<Type, GumpProfile>();
public GumpProfile(Type type) : base(type.FullName)
{
}
public static IEnumerable<GumpProfile> Profiles => _profiles.Values;
public static GumpProfile Acquire(Type type)
{
if (!Core.Profiling)
return null;
if (!_profiles.TryGetValue(type, out var prof))
_profiles.Add(type, prof = new GumpProfile(type));
return prof;
}
}
}
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Server.Diagnostics
{
public class GumpProfile : BaseProfile
{
private static readonly Dictionary<Type, GumpProfile> _profiles = new Dictionary<Type, GumpProfile>();
public GumpProfile(Type type) : base(type.FullName)
{
}
public static IEnumerable<GumpProfile> Profiles => _profiles.Values;
public static GumpProfile Acquire(Type type)
{
if (!Core.Profiling)
return null;
if (!_profiles.TryGetValue(type, out var prof))
_profiles.Add(type, prof = new GumpProfile(type));
return prof;
}
}
}

View file

@ -1,108 +1,109 @@
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Server.Diagnostics
{
public abstract class BasePacketProfile : BaseProfile
{
protected BasePacketProfile(string name) : base(name)
{
}
public long TotalLength { get; private set; }
public double AverageLength => (double)TotalLength / Math.Max(Count, 1);
public void Finish(long length)
{
Finish();
TotalLength += length;
}
public override void WriteTo(TextWriter op)
{
base.WriteTo(op);
op.Write("\t{0,12:F2} {1,-12:N0}", AverageLength, TotalLength);
}
}
public class PacketSendProfile : BasePacketProfile
{
private static readonly Dictionary<Type, PacketSendProfile> _profiles = new Dictionary<Type, PacketSendProfile>();
private long _created;
public PacketSendProfile(Type type) : base(type.FullName)
{
}
public static IEnumerable<PacketSendProfile> Profiles => _profiles.Values;
[MethodImpl(MethodImplOptions.Synchronized)]
public static PacketSendProfile Acquire(Type type)
{
if (!_profiles.TryGetValue(type, out var prof))
_profiles.Add(type, prof = new PacketSendProfile(type));
return prof;
}
public void Increment()
{
Interlocked.Increment(ref _created);
}
public override void WriteTo(TextWriter op)
{
base.WriteTo(op);
op.Write("\t{0,12:N0}", _created);
}
}
public class PacketReceiveProfile : BasePacketProfile
{
private static readonly Dictionary<int, PacketReceiveProfile> _profiles = new Dictionary<int, PacketReceiveProfile>();
public PacketReceiveProfile(int packetId)
: base($"0x{packetId:X2}")
{
}
public static IEnumerable<PacketReceiveProfile> Profiles => _profiles.Values;
[MethodImpl(MethodImplOptions.Synchronized)]
public static PacketReceiveProfile Acquire(int packetId)
{
if (!_profiles.TryGetValue(packetId, out var prof))
_profiles.Add(packetId, prof = new PacketReceiveProfile(packetId));
return prof;
}
}
}
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Server.Diagnostics
{
public abstract class BasePacketProfile : BaseProfile
{
protected BasePacketProfile(string name) : base(name)
{
}
public long TotalLength { get; private set; }
public double AverageLength => (double)TotalLength / Math.Max(Count, 1);
public void Finish(long length)
{
Finish();
TotalLength += length;
}
public override void WriteTo(TextWriter op)
{
base.WriteTo(op);
op.Write("\t{0,12:F2} {1,-12:N0}", AverageLength, TotalLength);
}
}
public class PacketSendProfile : BasePacketProfile
{
private static readonly Dictionary<Type, PacketSendProfile> _profiles = new Dictionary<Type, PacketSendProfile>();
private long _created;
public PacketSendProfile(Type type) : base(type.FullName)
{
}
public static IEnumerable<PacketSendProfile> Profiles => _profiles.Values;
[MethodImpl(MethodImplOptions.Synchronized)]
public static PacketSendProfile Acquire(Type type)
{
if (!_profiles.TryGetValue(type, out var prof))
_profiles.Add(type, prof = new PacketSendProfile(type));
return prof;
}
public void Increment()
{
Interlocked.Increment(ref _created);
}
public override void WriteTo(TextWriter op)
{
base.WriteTo(op);
op.Write("\t{0,12:N0}", _created);
}
}
public class PacketReceiveProfile : BasePacketProfile
{
private static readonly Dictionary<int, PacketReceiveProfile>
_profiles = new Dictionary<int, PacketReceiveProfile>();
public PacketReceiveProfile(int packetId)
: base($"0x{packetId:X2}")
{
}
public static IEnumerable<PacketReceiveProfile> Profiles => _profiles.Values;
[MethodImpl(MethodImplOptions.Synchronized)]
public static PacketReceiveProfile Acquire(int packetId)
{
if (!_profiles.TryGetValue(packetId, out var prof))
_profiles.Add(packetId, prof = new PacketReceiveProfile(packetId));
return prof;
}
}
}

View file

@ -1,48 +1,48 @@
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Server.Diagnostics
{
public class TargetProfile : BaseProfile
{
private static readonly Dictionary<Type, TargetProfile> _profiles = new Dictionary<Type, TargetProfile>();
public TargetProfile(Type type)
: base(type.FullName)
{
}
public static IEnumerable<TargetProfile> Profiles => _profiles.Values;
public static TargetProfile Acquire(Type type)
{
if (!Core.Profiling)
return null;
if (!_profiles.TryGetValue(type, out var prof))
_profiles.Add(type, prof = new TargetProfile(type));
return prof;
}
}
}
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Server.Diagnostics
{
public class TargetProfile : BaseProfile
{
private static readonly Dictionary<Type, TargetProfile> _profiles = new Dictionary<Type, TargetProfile>();
public TargetProfile(Type type)
: base(type.FullName)
{
}
public static IEnumerable<TargetProfile> Profiles => _profiles.Values;
public static TargetProfile Acquire(Type type)
{
if (!Core.Profiling)
return null;
if (!_profiles.TryGetValue(type, out var prof))
_profiles.Add(type, prof = new TargetProfile(type));
return prof;
}
}
}

View file

@ -1,61 +1,61 @@
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
using System.IO;
namespace Server.Diagnostics
{
public class TimerProfile : BaseProfile
{
private static readonly Dictionary<string, TimerProfile> _profiles = new Dictionary<string, TimerProfile>();
public TimerProfile(string name)
: base(name)
{
}
public static IEnumerable<TimerProfile> Profiles => _profiles.Values;
public long Created { get; set; }
public long Started { get; set; }
public long Stopped { get; set; }
public static TimerProfile Acquire(string name)
{
if (!Core.Profiling)
return null;
if (!_profiles.TryGetValue(name, out var prof))
_profiles.Add(name, prof = new TimerProfile(name));
return prof;
}
public override void WriteTo(TextWriter op)
{
base.WriteTo(op);
op.Write("\t{0,12:N0} {1,12:N0} {2,-12:N0}", Created, Started, Stopped);
}
}
}
/***************************************************************************
* PacketProfile.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
using System.IO;
namespace Server.Diagnostics
{
public class TimerProfile : BaseProfile
{
private static readonly Dictionary<string, TimerProfile> _profiles = new Dictionary<string, TimerProfile>();
public TimerProfile(string name)
: base(name)
{
}
public static IEnumerable<TimerProfile> Profiles => _profiles.Values;
public long Created { get; set; }
public long Started { get; set; }
public long Stopped { get; set; }
public static TimerProfile Acquire(string name)
{
if (!Core.Profiling)
return null;
if (!_profiles.TryGetValue(name, out var prof))
_profiles.Add(name, prof = new TimerProfile(name));
return prof;
}
public override void WriteTo(TextWriter op)
{
base.WriteTo(op);
op.Write("\t{0,12:N0} {1,12:N0} {2,-12:N0}", Created, Started, Stopped);
}
}
}

View file

@ -1,398 +1,501 @@
/***************************************************************************
* Effects.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server
{
public enum EffectLayer
{
Head = 0,
RightHand = 1,
LeftHand = 2,
Waist = 3,
LeftFoot = 4,
RightFoot = 5,
CenterFeet = 7
}
public enum ParticleSupportType
{
Full,
Detect,
None
}
public static class Effects
{
public static ParticleSupportType ParticleSupportType { get; set; } = ParticleSupportType.Detect;
public static bool SendParticlesTo(NetState state) =>
ParticleSupportType == ParticleSupportType.Full ||
(ParticleSupportType == ParticleSupportType.Detect && state.IsUOTDClient);
public static void PlaySound(IPoint3D p, Map map, int soundID)
{
if (soundID <= -1)
return;
if (map != null)
{
Packet playSound = null;
var eable = map.GetClientsInRange(new Point3D(p));
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
playSound ??= Packet.Acquire(new PlaySound(soundID, p));
state.Send(playSound);
}
Packet.Release(playSound);
eable.Free();
}
}
public static void SendBoltEffect(IEntity e)
{
SendBoltEffect(e, true, 0);
}
public static void SendBoltEffect(IEntity e, bool sound)
{
SendBoltEffect(e, sound, 0);
}
public static void SendBoltEffect(IEntity e, bool sound, int hue)
{
var map = e.Map;
if (map == null)
return;
e.ProcessDelta();
Packet preEffect = null, boltEffect = null, playSound = null;
var eable = map.GetClientsInRange(e.Location);
foreach (var state in eable)
if (state.Mobile.CanSee(e))
{
if (SendParticlesTo(state))
{
preEffect ??= Packet.Acquire(new TargetParticleEffect(e, 0, 10, 5, 0, 0, 5031, 3, 0));
state.Send(preEffect);
}
boltEffect ??= Packet.Acquire(new BoltEffect(e, hue));
state.Send(boltEffect);
if (sound)
{
playSound ??= Packet.Acquire(new PlaySound(0x29, e));
state.Send(playSound);
}
}
Packet.Release(preEffect);
Packet.Release(boltEffect);
Packet.Release(playSound);
eable.Free();
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration)
{
SendLocationEffect(p, map, itemID, duration, 10, 0, 0);
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration, int speed)
{
SendLocationEffect(p, map, itemID, duration, speed, 0, 0);
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration, int hue, int renderMode)
{
SendLocationEffect(p, map, itemID, duration, 10, hue, renderMode);
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration, int speed, int hue,
int renderMode)
{
SendPacket(p, map, new LocationEffect(p, itemID, speed, duration, hue, renderMode));
}
public static void SendLocationParticles(IEntity e, int itemID, int speed, int duration, int effect)
{
SendLocationParticles(e, itemID, speed, duration, 0, 0, effect, 0);
}
public static void SendLocationParticles(IEntity e, int itemID, int speed, int duration, int effect, int unknown)
{
SendLocationParticles(e, itemID, speed, duration, 0, 0, effect, unknown);
}
public static void SendLocationParticles(IEntity e, int itemID, int speed, int duration, int hue, int renderMode,
int effect, int unknown)
{
var map = e.Map;
if (map != null)
{
Packet particles = null, regular = null;
var eable = map.GetClientsInRange(e.Location);
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
if (SendParticlesTo(state))
{
particles ??=
Packet.Acquire(new LocationParticleEffect(e, itemID, speed, duration, hue, renderMode, effect, unknown));
state.Send(particles);
}
else if (itemID != 0)
{
regular ??= Packet.Acquire(new LocationEffect(e, itemID, speed, duration, hue, renderMode));
state.Send(regular);
}
}
Packet.Release(particles);
Packet.Release(regular);
eable.Free();
}
// SendPacket( e.Location, e.Map, new LocationParticleEffect( e, itemID, speed, duration, hue, renderMode, effect, unknown ) );
}
public static void SendTargetEffect(IEntity target, int itemID, int duration)
{
SendTargetEffect(target, itemID, duration, 0, 0);
}
public static void SendTargetEffect(IEntity target, int itemID, int speed, int duration)
{
SendTargetEffect(target, itemID, speed, duration, 0, 0);
}
public static void SendTargetEffect(IEntity target, int itemID, int duration, int hue, int renderMode)
{
SendTargetEffect(target, itemID, 10, duration, hue, renderMode);
}
public static void SendTargetEffect(IEntity target, int itemID, int speed, int duration, int hue, int renderMode)
{
if (target is Mobile mobile)
mobile.ProcessDelta();
SendPacket(target.Location, target.Map, new TargetEffect(target, itemID, speed, duration, hue, renderMode));
}
public static void SendTargetParticles(IEntity target, int itemID, int speed, int duration, int effect,
EffectLayer layer)
{
SendTargetParticles(target, itemID, speed, duration, 0, 0, effect, layer, 0);
}
public static void SendTargetParticles(IEntity target, int itemID, int speed, int duration, int effect,
EffectLayer layer, int unknown)
{
SendTargetParticles(target, itemID, speed, duration, 0, 0, effect, layer, unknown);
}
public static void SendTargetParticles(IEntity target, int itemID, int speed, int duration, int hue, int renderMode,
int effect, EffectLayer layer, int unknown)
{
if (target is Mobile mobile)
mobile.ProcessDelta();
var map = target.Map;
if (map != null)
{
Packet particles = null, regular = null;
var eable = map.GetClientsInRange(target.Location);
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
if (SendParticlesTo(state))
{
particles ??= Packet.Acquire(new TargetParticleEffect(target, itemID, speed, duration, hue, renderMode, effect,
(int)layer, unknown));
state.Send(particles);
}
else if (itemID != 0)
{
regular ??= Packet.Acquire(new TargetEffect(target, itemID, speed, duration, hue, renderMode));
state.Send(regular);
}
}
Packet.Release(particles);
Packet.Release(regular);
eable.Free();
}
// SendPacket( target.Location, target.Map, new TargetParticleEffect( target, itemID, speed, duration, hue, renderMode, effect, (int)layer, unknown ) );
}
public static void SendMovingEffect(IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int hue = 0, int renderMode = 0)
{
if (from is Mobile mobile)
mobile.ProcessDelta();
if (to is Mobile mobile1)
mobile1.ProcessDelta();
SendPacket(from.Location, from.Map,
new MovingEffect(from, to, itemID, speed, duration, fixedDirection, explodes, hue, renderMode));
}
public static void SendMovingParticles(IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int effect, int explodeEffect, int explodeSound)
{
SendMovingParticles(from, to, itemID, speed, duration, fixedDirection, explodes, 0, 0, effect, explodeEffect,
explodeSound, 0);
}
public static void SendMovingParticles(IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int effect, int explodeEffect, int explodeSound, int unknown)
{
SendMovingParticles(from, to, itemID, speed, duration, fixedDirection, explodes, 0, 0, effect, explodeEffect,
explodeSound, unknown);
}
public static void SendMovingParticles(IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int hue, int renderMode, int effect, int explodeEffect, int explodeSound,
int unknown)
{
SendMovingParticles(from, to, itemID, speed, duration, fixedDirection, explodes, hue, renderMode, effect,
explodeEffect, explodeSound, (EffectLayer)255, unknown);
}
public static void SendMovingParticles(IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int hue, int renderMode, int effect, int explodeEffect, int explodeSound,
EffectLayer layer, int unknown)
{
if (from is Mobile fromMob)
fromMob.ProcessDelta();
if (to is Mobile toMob)
toMob.ProcessDelta();
var map = from.Map;
if (map != null)
{
Packet particles = null, regular = null;
var eable = map.GetClientsInRange(from.Location);
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
if (SendParticlesTo(state))
{
particles ??= Packet.Acquire(new MovingParticleEffect(from, to, itemID, speed, duration,
fixedDirection, explodes, hue, renderMode, effect, explodeEffect, explodeSound, layer, unknown));
state.Send(particles);
}
else if (itemID > 1)
{
regular ??= Packet.Acquire(new MovingEffect(from, to, itemID, speed, duration, fixedDirection, explodes, hue,
renderMode));
state.Send(regular);
}
}
Packet.Release(particles);
Packet.Release(regular);
eable.Free();
}
// SendPacket( from.Location, from.Map, new MovingParticleEffect( from, to, itemID, speed, duration, fixedDirection, explodes, hue, renderMode, effect, explodeEffect, explodeSound, unknown ) );
}
public static void SendPacket(Point3D origin, Map map, Packet p)
{
if (map == null)
return;
var eable = map.GetClientsInRange(origin);
p.Acquire();
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
state.Send(p);
}
p.Release();
eable.Free();
}
public static void SendPacket(IPoint3D origin, Map map, Packet p)
{
if (map == null)
return;
var eable = map.GetClientsInRange(new Point3D(origin));
p.Acquire();
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
state.Send(p);
}
p.Release();
eable.Free();
}
}
}
/***************************************************************************
* Effects.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server
{
public enum EffectLayer
{
Head = 0,
RightHand = 1,
LeftHand = 2,
Waist = 3,
LeftFoot = 4,
RightFoot = 5,
CenterFeet = 7
}
public enum ParticleSupportType
{
Full,
Detect,
None
}
public static class Effects
{
public static ParticleSupportType ParticleSupportType { get; set; } = ParticleSupportType.Detect;
public static bool SendParticlesTo(NetState state) =>
ParticleSupportType == ParticleSupportType.Full ||
ParticleSupportType == ParticleSupportType.Detect && state.IsUOTDClient;
public static void PlaySound(IPoint3D p, Map map, int soundID)
{
if (soundID <= -1)
return;
if (map != null)
{
Packet playSound = null;
var eable = map.GetClientsInRange(new Point3D(p));
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
playSound ??= Packet.Acquire(new PlaySound(soundID, p));
state.Send(playSound);
}
Packet.Release(playSound);
eable.Free();
}
}
public static void SendBoltEffect(IEntity e)
{
SendBoltEffect(e, true, 0);
}
public static void SendBoltEffect(IEntity e, bool sound)
{
SendBoltEffect(e, sound, 0);
}
public static void SendBoltEffect(IEntity e, bool sound, int hue)
{
var map = e.Map;
if (map == null)
return;
e.ProcessDelta();
Packet preEffect = null, boltEffect = null, playSound = null;
var eable = map.GetClientsInRange(e.Location);
foreach (var state in eable)
if (state.Mobile.CanSee(e))
{
if (SendParticlesTo(state))
{
preEffect ??= Packet.Acquire(new TargetParticleEffect(e, 0, 10, 5, 0, 0, 5031, 3, 0));
state.Send(preEffect);
}
boltEffect ??= Packet.Acquire(new BoltEffect(e, hue));
state.Send(boltEffect);
if (sound)
{
playSound ??= Packet.Acquire(new PlaySound(0x29, e));
state.Send(playSound);
}
}
Packet.Release(preEffect);
Packet.Release(boltEffect);
Packet.Release(playSound);
eable.Free();
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration)
{
SendLocationEffect(p, map, itemID, duration, 10, 0, 0);
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration, int speed)
{
SendLocationEffect(p, map, itemID, duration, speed, 0, 0);
}
public static void SendLocationEffect(IPoint3D p, Map map, int itemID, int duration, int hue, int renderMode)
{
SendLocationEffect(p, map, itemID, duration, 10, hue, renderMode);
}
public static void SendLocationEffect(
IPoint3D p, Map map, int itemID, int duration, int speed, int hue,
int renderMode
)
{
SendPacket(p, map, new LocationEffect(p, itemID, speed, duration, hue, renderMode));
}
public static void SendLocationParticles(IEntity e, int itemID, int speed, int duration, int effect)
{
SendLocationParticles(e, itemID, speed, duration, 0, 0, effect, 0);
}
public static void SendLocationParticles(IEntity e, int itemID, int speed, int duration, int effect, int unknown)
{
SendLocationParticles(e, itemID, speed, duration, 0, 0, effect, unknown);
}
public static void SendLocationParticles(
IEntity e, int itemID, int speed, int duration, int hue, int renderMode,
int effect, int unknown
)
{
var map = e.Map;
if (map != null)
{
Packet particles = null, regular = null;
var eable = map.GetClientsInRange(e.Location);
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
if (SendParticlesTo(state))
{
particles ??=
Packet.Acquire(
new LocationParticleEffect(e, itemID, speed, duration, hue, renderMode, effect, unknown)
);
state.Send(particles);
}
else if (itemID != 0)
{
regular ??= Packet.Acquire(new LocationEffect(e, itemID, speed, duration, hue, renderMode));
state.Send(regular);
}
}
Packet.Release(particles);
Packet.Release(regular);
eable.Free();
}
// SendPacket( e.Location, e.Map, new LocationParticleEffect( e, itemID, speed, duration, hue, renderMode, effect, unknown ) );
}
public static void SendTargetEffect(IEntity target, int itemID, int duration)
{
SendTargetEffect(target, itemID, duration, 0, 0);
}
public static void SendTargetEffect(IEntity target, int itemID, int speed, int duration)
{
SendTargetEffect(target, itemID, speed, duration, 0, 0);
}
public static void SendTargetEffect(IEntity target, int itemID, int duration, int hue, int renderMode)
{
SendTargetEffect(target, itemID, 10, duration, hue, renderMode);
}
public static void SendTargetEffect(IEntity target, int itemID, int speed, int duration, int hue, int renderMode)
{
if (target is Mobile mobile)
mobile.ProcessDelta();
SendPacket(target.Location, target.Map, new TargetEffect(target, itemID, speed, duration, hue, renderMode));
}
public static void SendTargetParticles(
IEntity target, int itemID, int speed, int duration, int effect,
EffectLayer layer
)
{
SendTargetParticles(target, itemID, speed, duration, 0, 0, effect, layer, 0);
}
public static void SendTargetParticles(
IEntity target, int itemID, int speed, int duration, int effect,
EffectLayer layer, int unknown
)
{
SendTargetParticles(target, itemID, speed, duration, 0, 0, effect, layer, unknown);
}
public static void SendTargetParticles(
IEntity target, int itemID, int speed, int duration, int hue, int renderMode,
int effect, EffectLayer layer, int unknown
)
{
if (target is Mobile mobile)
mobile.ProcessDelta();
var map = target.Map;
if (map != null)
{
Packet particles = null, regular = null;
var eable = map.GetClientsInRange(target.Location);
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
if (SendParticlesTo(state))
{
particles ??= Packet.Acquire(
new TargetParticleEffect(
target,
itemID,
speed,
duration,
hue,
renderMode,
effect,
(int)layer,
unknown
)
);
state.Send(particles);
}
else if (itemID != 0)
{
regular ??= Packet.Acquire(new TargetEffect(target, itemID, speed, duration, hue, renderMode));
state.Send(regular);
}
}
Packet.Release(particles);
Packet.Release(regular);
eable.Free();
}
// SendPacket( target.Location, target.Map, new TargetParticleEffect( target, itemID, speed, duration, hue, renderMode, effect, (int)layer, unknown ) );
}
public static void SendMovingEffect(
IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int hue = 0, int renderMode = 0
)
{
if (from is Mobile mobile)
mobile.ProcessDelta();
if (to is Mobile mobile1)
mobile1.ProcessDelta();
SendPacket(
from.Location,
from.Map,
new MovingEffect(from, to, itemID, speed, duration, fixedDirection, explodes, hue, renderMode)
);
}
public static void SendMovingParticles(
IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int effect, int explodeEffect, int explodeSound
)
{
SendMovingParticles(
from,
to,
itemID,
speed,
duration,
fixedDirection,
explodes,
0,
0,
effect,
explodeEffect,
explodeSound,
0
);
}
public static void SendMovingParticles(
IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int effect, int explodeEffect, int explodeSound, int unknown
)
{
SendMovingParticles(
from,
to,
itemID,
speed,
duration,
fixedDirection,
explodes,
0,
0,
effect,
explodeEffect,
explodeSound,
unknown
);
}
public static void SendMovingParticles(
IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int hue, int renderMode, int effect, int explodeEffect, int explodeSound,
int unknown
)
{
SendMovingParticles(
from,
to,
itemID,
speed,
duration,
fixedDirection,
explodes,
hue,
renderMode,
effect,
explodeEffect,
explodeSound,
(EffectLayer)255,
unknown
);
}
public static void SendMovingParticles(
IEntity from, IEntity to, int itemID, int speed, int duration,
bool fixedDirection, bool explodes, int hue, int renderMode, int effect, int explodeEffect, int explodeSound,
EffectLayer layer, int unknown
)
{
if (from is Mobile fromMob)
fromMob.ProcessDelta();
if (to is Mobile toMob)
toMob.ProcessDelta();
var map = from.Map;
if (map != null)
{
Packet particles = null, regular = null;
var eable = map.GetClientsInRange(from.Location);
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
if (SendParticlesTo(state))
{
particles ??= Packet.Acquire(
new MovingParticleEffect(
from,
to,
itemID,
speed,
duration,
fixedDirection,
explodes,
hue,
renderMode,
effect,
explodeEffect,
explodeSound,
layer,
unknown
)
);
state.Send(particles);
}
else if (itemID > 1)
{
regular ??= Packet.Acquire(
new MovingEffect(
from,
to,
itemID,
speed,
duration,
fixedDirection,
explodes,
hue,
renderMode
)
);
state.Send(regular);
}
}
Packet.Release(particles);
Packet.Release(regular);
eable.Free();
}
// SendPacket( from.Location, from.Map, new MovingParticleEffect( from, to, itemID, speed, duration, fixedDirection, explodes, hue, renderMode, effect, explodeEffect, explodeSound, unknown ) );
}
public static void SendPacket(Point3D origin, Map map, Packet p)
{
if (map == null)
return;
var eable = map.GetClientsInRange(origin);
p.Acquire();
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
state.Send(p);
}
p.Release();
eable.Free();
}
public static void SendPacket(IPoint3D origin, Map map, Packet p)
{
if (map == null)
return;
var eable = map.GetClientsInRange(new Point3D(origin));
p.Acquire();
foreach (var state in eable)
{
state.Mobile.ProcessDelta();
state.Send(p);
}
p.Release();
eable.Free();
}
}
}

View file

@ -1,52 +1,52 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AccountLoginEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Network;
namespace Server
{
public class AccountLoginEventArgs : EventArgs
{
public AccountLoginEventArgs(NetState state, string username, string password)
{
State = state;
Username = username;
Password = password;
}
public NetState State { get; }
public string Username { get; }
public string Password { get; }
public bool Accepted { get; set; }
public ALRReason RejectReason { get; set; }
}
public static partial class EventSink
{
public static event Action<AccountLoginEventArgs> AccountLogin;
public static void InvokeAccountLogin(AccountLoginEventArgs e) => AccountLogin?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AccountLoginEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Network;
namespace Server
{
public class AccountLoginEventArgs : EventArgs
{
public AccountLoginEventArgs(NetState state, string username, string password)
{
State = state;
Username = username;
Password = password;
}
public NetState State { get; }
public string Username { get; }
public string Password { get; }
public bool Accepted { get; set; }
public ALRReason RejectReason { get; set; }
}
public static partial class EventSink
{
public static event Action<AccountLoginEventArgs> AccountLogin;
public static void InvokeAccountLogin(AccountLoginEventArgs e) => AccountLogin?.Invoke(e);
}
}

View file

@ -1,75 +1,75 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AggressiveActionEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
public class AggressiveActionEventArgs : EventArgs
{
private static readonly Queue<AggressiveActionEventArgs> m_Pool = new Queue<AggressiveActionEventArgs>();
private AggressiveActionEventArgs(Mobile aggressed, Mobile aggressor, bool criminal)
{
Aggressed = aggressed;
Aggressor = aggressor;
Criminal = criminal;
}
public Mobile Aggressed { get; private set; }
public Mobile Aggressor { get; private set; }
public bool Criminal { get; private set; }
public static AggressiveActionEventArgs Create(Mobile aggressed, Mobile aggressor, bool criminal)
{
AggressiveActionEventArgs args;
if (m_Pool.Count > 0)
{
args = m_Pool.Dequeue();
args.Aggressed = aggressed;
args.Aggressor = aggressor;
args.Criminal = criminal;
}
else
{
args = new AggressiveActionEventArgs(aggressed, aggressor, criminal);
}
return args;
}
public void Free()
{
m_Pool.Enqueue(this);
}
}
public static partial class EventSink
{
public static event Action<AggressiveActionEventArgs> AggressiveAction;
public static void InvokeAggressiveAction(AggressiveActionEventArgs e) => AggressiveAction?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AggressiveActionEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
public class AggressiveActionEventArgs : EventArgs
{
private static readonly Queue<AggressiveActionEventArgs> m_Pool = new Queue<AggressiveActionEventArgs>();
private AggressiveActionEventArgs(Mobile aggressed, Mobile aggressor, bool criminal)
{
Aggressed = aggressed;
Aggressor = aggressor;
Criminal = criminal;
}
public Mobile Aggressed { get; private set; }
public Mobile Aggressor { get; private set; }
public bool Criminal { get; private set; }
public static AggressiveActionEventArgs Create(Mobile aggressed, Mobile aggressor, bool criminal)
{
AggressiveActionEventArgs args;
if (m_Pool.Count > 0)
{
args = m_Pool.Dequeue();
args.Aggressed = aggressed;
args.Aggressor = aggressor;
args.Criminal = criminal;
}
else
{
args = new AggressiveActionEventArgs(aggressed, aggressor, criminal);
}
return args;
}
public void Free()
{
m_Pool.Enqueue(this);
}
}
public static partial class EventSink
{
public static event Action<AggressiveActionEventArgs> AggressiveAction;
public static void InvokeAggressiveAction(AggressiveActionEventArgs e) => AggressiveAction?.Invoke(e);
}
}

View file

@ -1,111 +1,113 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: CharacterCreatedEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Accounting;
using Server.Network;
namespace Server
{
public class CharacterCreatedEventArgs : EventArgs
{
public CharacterCreatedEventArgs(NetState state, IAccount a, string name, bool female, int hue, int str, int dex,
int intel, CityInfo city, SkillNameValue[] skills, int shirtHue, int pantsHue, int hairID, int hairHue,
int beardID, int beardHue, int profession, Race race)
{
State = state;
Account = a;
Name = name;
Female = female;
Hue = hue;
Str = str;
Dex = dex;
Int = intel;
City = city;
Skills = skills;
ShirtHue = shirtHue;
PantsHue = pantsHue;
HairID = hairID;
HairHue = hairHue;
BeardID = beardID;
BeardHue = beardHue;
Profession = profession;
Race = race;
}
public NetState State { get; }
public IAccount Account { get; }
public Mobile Mobile { get; set; }
public string Name { get; }
public bool Female { get; }
public int Hue { get; }
public int Str { get; }
public int Dex { get; }
public int Int { get; }
public CityInfo City { get; }
public SkillNameValue[] Skills { get; }
public int ShirtHue { get; }
public int PantsHue { get; }
public int HairID { get; }
public int HairHue { get; }
public int BeardID { get; }
public int BeardHue { get; }
public int Profession { get; set; }
public Race Race { get; }
}
public struct SkillNameValue
{
public SkillName Name { get; }
public int Value { get; }
public SkillNameValue(SkillName name, int value)
{
Name = name;
Value = value;
}
}
public static partial class EventSink
{
public static event Action<CharacterCreatedEventArgs> CharacterCreated;
public static void InvokeCharacterCreated(CharacterCreatedEventArgs e) => CharacterCreated?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: CharacterCreatedEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Accounting;
using Server.Network;
namespace Server
{
public class CharacterCreatedEventArgs : EventArgs
{
public CharacterCreatedEventArgs(
NetState state, IAccount a, string name, bool female, int hue, int str, int dex,
int intel, CityInfo city, SkillNameValue[] skills, int shirtHue, int pantsHue, int hairID, int hairHue,
int beardID, int beardHue, int profession, Race race
)
{
State = state;
Account = a;
Name = name;
Female = female;
Hue = hue;
Str = str;
Dex = dex;
Int = intel;
City = city;
Skills = skills;
ShirtHue = shirtHue;
PantsHue = pantsHue;
HairID = hairID;
HairHue = hairHue;
BeardID = beardID;
BeardHue = beardHue;
Profession = profession;
Race = race;
}
public NetState State { get; }
public IAccount Account { get; }
public Mobile Mobile { get; set; }
public string Name { get; }
public bool Female { get; }
public int Hue { get; }
public int Str { get; }
public int Dex { get; }
public int Int { get; }
public CityInfo City { get; }
public SkillNameValue[] Skills { get; }
public int ShirtHue { get; }
public int PantsHue { get; }
public int HairID { get; }
public int HairHue { get; }
public int BeardID { get; }
public int BeardHue { get; }
public int Profession { get; set; }
public Race Race { get; }
}
public struct SkillNameValue
{
public SkillName Name { get; }
public int Value { get; }
public SkillNameValue(SkillName name, int value)
{
Name = name;
Value = value;
}
}
public static partial class EventSink
{
public static event Action<CharacterCreatedEventArgs> CharacterCreated;
public static void InvokeCharacterCreated(CharacterCreatedEventArgs e) => CharacterCreated?.Invoke(e);
}
}

View file

@ -1,41 +1,41 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: CreateGuildEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Guilds;
namespace Server
{
public class CreateGuildEventArgs : EventArgs
{
public CreateGuildEventArgs(uint id) => Id = id;
public uint Id { get; set; }
public BaseGuild Guild { get; set; }
}
public static partial class EventSink
{
public static event Action<CreateGuildEventArgs> CreateGuild;
public static void InvokeCreateGuild(CreateGuildEventArgs e) => CreateGuild?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: CreateGuildEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Guilds;
namespace Server
{
public class CreateGuildEventArgs : EventArgs
{
public CreateGuildEventArgs(uint id) => Id = id;
public uint Id { get; set; }
public BaseGuild Guild { get; set; }
}
public static partial class EventSink
{
public static event Action<CreateGuildEventArgs> CreateGuild;
public static void InvokeCreateGuild(CreateGuildEventArgs e) => CreateGuild?.Invoke(e);
}
}

View file

@ -1,168 +1,172 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: EventSink.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using Server.Network;
namespace Server
{
public static partial class EventSink
{
public static event Action<Mobile> OpenDoorMacroUsed;
public static void InvokeOpenDoorMacroUsed(Mobile m) => OpenDoorMacroUsed?.Invoke(m);
public static event Action<Mobile> Login;
public static void InvokeLogin(Mobile m) => Login?.Invoke(m);
public static event Action<Mobile, int> HungerChanged;
public static void InvokeHungerChanged(Mobile mobile, int oldValue) => HungerChanged?.Invoke(mobile, oldValue);
public static event Action Shutdown;
public static void InvokeShutdown() => Shutdown?.Invoke();
public static event Action<Mobile> HelpRequest;
public static void InvokeHelpRequest(Mobile m) => HelpRequest?.Invoke(m);
public static event Action<Mobile> DisarmRequest;
public static void InvokeDisarmRequest(Mobile m) => DisarmRequest?.Invoke(m);
public static event Action<Mobile> StunRequest;
public static void InvokeStunRequest(Mobile m) => StunRequest?.Invoke(m);
public static event Action<Mobile, int> OpenSpellbookRequest;
public static void InvokeOpenSpellbookRequest(Mobile m, int type) => OpenSpellbookRequest?.Invoke(m, type);
public static event Action<Mobile, int, Item> CastSpellRequest;
public static void InvokeCastSpellRequest(Mobile m, int spellID, Item book) =>
CastSpellRequest?.Invoke(m, spellID, book);
public static event Action<Mobile, Item, Mobile> BandageTargetRequest;
public static void InvokeBandageTargetRequest(Mobile m, Item bandage, Mobile target) =>
BandageTargetRequest?.Invoke(m, bandage, target);
public static event Action<Mobile, string> AnimateRequest;
public static void InvokeAnimateRequest(Mobile m, string action) => AnimateRequest?.Invoke(m, action);
public static event Action<Mobile> Logout;
public static void InvokeLogout(Mobile m) => Logout?.Invoke(m);
public static event Action<Mobile> Connected;
public static void InvokeConnected(Mobile m) => Connected?.Invoke(m);
public static event Action<Mobile> Disconnected;
public static void InvokeDisconnected(Mobile m) => Disconnected?.Invoke(m);
public static event Action<Mobile, Mobile, string> RenameRequest;
public static void InvokeRenameRequest(Mobile from, Mobile target, string name) =>
RenameRequest?.Invoke(from, target, name);
public static event Action<Mobile> PlayerDeath;
public static void InvokePlayerDeath(Mobile m) => PlayerDeath?.Invoke(m);
public static event Action<Mobile, Mobile> VirtueGumpRequest;
public static void InvokeVirtueGumpRequest(Mobile beholder, Mobile beheld) =>
VirtueGumpRequest?.Invoke(beholder, beheld);
public static event Action<Mobile, Mobile, int> VirtueItemRequest;
public static void InvokeVirtueItemRequest(Mobile beholder, Mobile beheld, int gumpID) =>
VirtueItemRequest?.Invoke(beholder, beheld, gumpID);
public static event Action<Mobile, int> VirtueMacroRequest;
public static void InvokeVirtueMacroRequest(Mobile mobile, int virtueID) => VirtueMacroRequest?.Invoke(mobile, virtueID);
public static event Action<Mobile> ChatRequest;
public static void InvokeChatRequest(Mobile m) => ChatRequest?.Invoke(m);
public static event Action<Mobile, Mobile> PaperdollRequest;
public static void InvokePaperdollRequest(Mobile beholder, Mobile beheld) => PaperdollRequest?.Invoke(beholder, beheld);
public static event Action<Mobile, Mobile> ProfileRequest;
public static void InvokeProfileRequest(Mobile beholder, Mobile beheld) => ProfileRequest?.Invoke(beholder, beheld);
public static event Action<Mobile, Mobile, string> ChangeProfileRequest;
public static void InvokeChangeProfileRequest(Mobile beholder, Mobile beheld, string text) =>
ChangeProfileRequest?.Invoke(beholder, beheld, text);
public static event Action<NetState, int> DeleteRequest;
public static void InvokeDeleteRequest(NetState state, int index) => DeleteRequest?.Invoke(state, index);
public static event Action WorldLoad;
public static void InvokeWorldLoad() => WorldLoad?.Invoke();
public static event Action<bool> WorldSave;
public static void InvokeWorldSave(bool sendMessage) => WorldSave?.Invoke(sendMessage);
public static event Action<Mobile, int> SetAbility;
public static void InvokeSetAbility(Mobile mobile, int index) => SetAbility?.Invoke(mobile, index);
public static event Action ServerStarted;
public static void InvokeServerStarted() => ServerStarted?.Invoke();
public static event Action<Mobile> GuildGumpRequest;
public static void InvokeGuildGumpRequest(Mobile m) => GuildGumpRequest?.Invoke(m);
public static event Action<Mobile> QuestGumpRequest;
public static void InvokeQuestGumpRequest(Mobile m) => QuestGumpRequest?.Invoke(m);
public static event Action<NetState, ClientVersion> ClientVersionReceived;
public static void InvokeClientVersionReceived(NetState state, ClientVersion cv) =>
ClientVersionReceived?.Invoke(state, cv);
public static event Action<Mobile, List<Serial>> EquipMacro;
public static void InvokeEquipMacro(Mobile m, List<Serial> list)
{
if (list?.Count > 0)
EquipMacro?.Invoke(m, list);
}
public static event Action<Mobile, List<Layer>> UnequipMacro;
public static void InvokeUnequipMacro(Mobile m, List<Layer> layers)
{
if (layers?.Count > 0)
UnequipMacro?.Invoke(m, layers);
}
public static event Action<Mobile, IEntity, int> TargetedSpell;
public static void InvokeTargetedSpell(Mobile m, IEntity target, int spellId) =>
TargetedSpell?.Invoke(m, target, spellId);
public static event Action<Mobile, IEntity, int> TargetedSkillUse;
public static void InvokeTargetedSkillUse(Mobile m, IEntity target, int skillId) =>
TargetedSkillUse?.Invoke(m, target, skillId);
public static event Action<Mobile, Item, short> TargetByResourceMacro;
public static void InvokeTargetByResourceMacro(Mobile m, Item item, short resourceType) =>
TargetByResourceMacro?.Invoke(m, item, resourceType);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: EventSink.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using Server.Network;
namespace Server
{
public static partial class EventSink
{
public static event Action<Mobile> OpenDoorMacroUsed;
public static void InvokeOpenDoorMacroUsed(Mobile m) => OpenDoorMacroUsed?.Invoke(m);
public static event Action<Mobile> Login;
public static void InvokeLogin(Mobile m) => Login?.Invoke(m);
public static event Action<Mobile, int> HungerChanged;
public static void InvokeHungerChanged(Mobile mobile, int oldValue) => HungerChanged?.Invoke(mobile, oldValue);
public static event Action Shutdown;
public static void InvokeShutdown() => Shutdown?.Invoke();
public static event Action<Mobile> HelpRequest;
public static void InvokeHelpRequest(Mobile m) => HelpRequest?.Invoke(m);
public static event Action<Mobile> DisarmRequest;
public static void InvokeDisarmRequest(Mobile m) => DisarmRequest?.Invoke(m);
public static event Action<Mobile> StunRequest;
public static void InvokeStunRequest(Mobile m) => StunRequest?.Invoke(m);
public static event Action<Mobile, int> OpenSpellbookRequest;
public static void InvokeOpenSpellbookRequest(Mobile m, int type) => OpenSpellbookRequest?.Invoke(m, type);
public static event Action<Mobile, int, Item> CastSpellRequest;
public static void InvokeCastSpellRequest(Mobile m, int spellID, Item book) =>
CastSpellRequest?.Invoke(m, spellID, book);
public static event Action<Mobile, Item, Mobile> BandageTargetRequest;
public static void InvokeBandageTargetRequest(Mobile m, Item bandage, Mobile target) =>
BandageTargetRequest?.Invoke(m, bandage, target);
public static event Action<Mobile, string> AnimateRequest;
public static void InvokeAnimateRequest(Mobile m, string action) => AnimateRequest?.Invoke(m, action);
public static event Action<Mobile> Logout;
public static void InvokeLogout(Mobile m) => Logout?.Invoke(m);
public static event Action<Mobile> Connected;
public static void InvokeConnected(Mobile m) => Connected?.Invoke(m);
public static event Action<Mobile> Disconnected;
public static void InvokeDisconnected(Mobile m) => Disconnected?.Invoke(m);
public static event Action<Mobile, Mobile, string> RenameRequest;
public static void InvokeRenameRequest(Mobile from, Mobile target, string name) =>
RenameRequest?.Invoke(from, target, name);
public static event Action<Mobile> PlayerDeath;
public static void InvokePlayerDeath(Mobile m) => PlayerDeath?.Invoke(m);
public static event Action<Mobile, Mobile> VirtueGumpRequest;
public static void InvokeVirtueGumpRequest(Mobile beholder, Mobile beheld) =>
VirtueGumpRequest?.Invoke(beholder, beheld);
public static event Action<Mobile, Mobile, int> VirtueItemRequest;
public static void InvokeVirtueItemRequest(Mobile beholder, Mobile beheld, int gumpID) =>
VirtueItemRequest?.Invoke(beholder, beheld, gumpID);
public static event Action<Mobile, int> VirtueMacroRequest;
public static void InvokeVirtueMacroRequest(Mobile mobile, int virtueID) =>
VirtueMacroRequest?.Invoke(mobile, virtueID);
public static event Action<Mobile> ChatRequest;
public static void InvokeChatRequest(Mobile m) => ChatRequest?.Invoke(m);
public static event Action<Mobile, Mobile> PaperdollRequest;
public static void InvokePaperdollRequest(Mobile beholder, Mobile beheld) =>
PaperdollRequest?.Invoke(beholder, beheld);
public static event Action<Mobile, Mobile> ProfileRequest;
public static void InvokeProfileRequest(Mobile beholder, Mobile beheld) => ProfileRequest?.Invoke(beholder, beheld);
public static event Action<Mobile, Mobile, string> ChangeProfileRequest;
public static void InvokeChangeProfileRequest(Mobile beholder, Mobile beheld, string text) =>
ChangeProfileRequest?.Invoke(beholder, beheld, text);
public static event Action<NetState, int> DeleteRequest;
public static void InvokeDeleteRequest(NetState state, int index) => DeleteRequest?.Invoke(state, index);
public static event Action WorldLoad;
public static void InvokeWorldLoad() => WorldLoad?.Invoke();
public static event Action<bool> WorldSave;
public static void InvokeWorldSave(bool sendMessage) => WorldSave?.Invoke(sendMessage);
public static event Action<Mobile, int> SetAbility;
public static void InvokeSetAbility(Mobile mobile, int index) => SetAbility?.Invoke(mobile, index);
public static event Action ServerStarted;
public static void InvokeServerStarted() => ServerStarted?.Invoke();
public static event Action<Mobile> GuildGumpRequest;
public static void InvokeGuildGumpRequest(Mobile m) => GuildGumpRequest?.Invoke(m);
public static event Action<Mobile> QuestGumpRequest;
public static void InvokeQuestGumpRequest(Mobile m) => QuestGumpRequest?.Invoke(m);
public static event Action<NetState, ClientVersion> ClientVersionReceived;
public static void InvokeClientVersionReceived(NetState state, ClientVersion cv) =>
ClientVersionReceived?.Invoke(state, cv);
public static event Action<Mobile, List<Serial>> EquipMacro;
public static void InvokeEquipMacro(Mobile m, List<Serial> list)
{
if (list?.Count > 0)
EquipMacro?.Invoke(m, list);
}
public static event Action<Mobile, List<Layer>> UnequipMacro;
public static void InvokeUnequipMacro(Mobile m, List<Layer> layers)
{
if (layers?.Count > 0)
UnequipMacro?.Invoke(m, layers);
}
public static event Action<Mobile, IEntity, int> TargetedSpell;
public static void InvokeTargetedSpell(Mobile m, IEntity target, int spellId) =>
TargetedSpell?.Invoke(m, target, spellId);
public static event Action<Mobile, IEntity, int> TargetedSkillUse;
public static void InvokeTargetedSkillUse(Mobile m, IEntity target, int skillId) =>
TargetedSkillUse?.Invoke(m, target, skillId);
public static event Action<Mobile, Item, short> TargetByResourceMacro;
public static void InvokeTargetByResourceMacro(Mobile m, Item item, short resourceType) =>
TargetByResourceMacro?.Invoke(m, item, resourceType);
}
}

View file

@ -1,45 +1,45 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: FastWalkEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Network;
namespace Server
{
public class FastWalkEventArgs : EventArgs
{
public FastWalkEventArgs(NetState state)
{
NetState = state;
Blocked = false;
}
public NetState NetState { get; }
public bool Blocked { get; set; }
}
public static partial class EventSink
{
public static event Action<FastWalkEventArgs> FastWalk;
public static void InvokeFastWalk(FastWalkEventArgs e) => FastWalk?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: FastWalkEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Network;
namespace Server
{
public class FastWalkEventArgs : EventArgs
{
public FastWalkEventArgs(NetState state)
{
NetState = state;
Blocked = false;
}
public NetState NetState { get; }
public bool Blocked { get; set; }
}
public static partial class EventSink
{
public static event Action<FastWalkEventArgs> FastWalk;
public static void InvokeFastWalk(FastWalkEventArgs e) => FastWalk?.Invoke(e);
}
}

View file

@ -1,52 +1,52 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GameLoginEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Network;
namespace Server
{
public class GameLoginEventArgs : EventArgs
{
public GameLoginEventArgs(NetState state, string un, string pw)
{
State = state;
Username = un;
Password = pw;
}
public NetState State { get; }
public string Username { get; }
public string Password { get; }
public bool Accepted { get; set; }
public CityInfo[] CityInfo { get; set; }
}
public static partial class EventSink
{
public static event Action<GameLoginEventArgs> GameLogin;
public static void InvokeGameLogin(GameLoginEventArgs e) => GameLogin?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GameLoginEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Server.Network;
namespace Server
{
public class GameLoginEventArgs : EventArgs
{
public GameLoginEventArgs(NetState state, string un, string pw)
{
State = state;
Username = un;
Password = pw;
}
public NetState State { get; }
public string Username { get; }
public string Password { get; }
public bool Accepted { get; set; }
public CityInfo[] CityInfo { get; set; }
}
public static partial class EventSink
{
public static event Action<GameLoginEventArgs> GameLogin;
public static void InvokeGameLogin(GameLoginEventArgs e) => GameLogin?.Invoke(e);
}
}

View file

@ -1,74 +1,74 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MovementEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
public class MovementEventArgs : EventArgs
{
private static readonly Queue<MovementEventArgs> m_Pool = new Queue<MovementEventArgs>();
public MovementEventArgs(Mobile mobile, Direction dir)
{
Mobile = mobile;
Direction = dir;
}
public Mobile Mobile { get; private set; }
public Direction Direction { get; private set; }
public bool Blocked { get; set; }
public static MovementEventArgs Create(Mobile mobile, Direction dir)
{
MovementEventArgs args;
if (m_Pool.Count > 0)
{
args = m_Pool.Dequeue();
args.Mobile = mobile;
args.Direction = dir;
args.Blocked = false;
}
else
{
args = new MovementEventArgs(mobile, dir);
}
return args;
}
public void Free()
{
m_Pool.Enqueue(this);
}
}
public static partial class EventSink
{
public static event Action<MovementEventArgs> Movement;
public static void InvokeMovement(MovementEventArgs e) => Movement?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MovementEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
public class MovementEventArgs : EventArgs
{
private static readonly Queue<MovementEventArgs> m_Pool = new Queue<MovementEventArgs>();
public MovementEventArgs(Mobile mobile, Direction dir)
{
Mobile = mobile;
Direction = dir;
}
public Mobile Mobile { get; private set; }
public Direction Direction { get; private set; }
public bool Blocked { get; set; }
public static MovementEventArgs Create(Mobile mobile, Direction dir)
{
MovementEventArgs args;
if (m_Pool.Count > 0)
{
args = m_Pool.Dequeue();
args.Mobile = mobile;
args.Direction = dir;
args.Blocked = false;
}
else
{
args = new MovementEventArgs(mobile, dir);
}
return args;
}
public void Free()
{
m_Pool.Enqueue(this);
}
}
public static partial class EventSink
{
public static event Action<MovementEventArgs> Movement;
public static void InvokeMovement(MovementEventArgs e) => Movement?.Invoke(e);
}
}

View file

@ -1,40 +1,40 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerCrashedEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
public class ServerCrashedEventArgs : EventArgs
{
public ServerCrashedEventArgs(Exception e) => Exception = e;
public Exception Exception { get; }
public bool Close { get; set; }
}
public static partial class EventSink
{
public static event Action<ServerCrashedEventArgs> ServerCrashed;
public static void InvokeServerCrashed(ServerCrashedEventArgs e) => ServerCrashed?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerCrashedEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
public class ServerCrashedEventArgs : EventArgs
{
public ServerCrashedEventArgs(Exception e) => Exception = e;
public Exception Exception { get; }
public bool Close { get; set; }
}
public static partial class EventSink
{
public static event Action<ServerCrashedEventArgs> ServerCrashed;
public static void InvokeServerCrashed(ServerCrashedEventArgs e) => ServerCrashed?.Invoke(e);
}
}

View file

@ -1,63 +1,63 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerListEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.Net;
using Server.Accounting;
using Server.Network;
namespace Server
{
public class ServerListEventArgs : EventArgs
{
public ServerListEventArgs(NetState state, IAccount account)
{
State = state;
Account = account;
Servers = new List<ServerInfo>();
}
public NetState State { get; }
public IAccount Account { get; }
public bool Rejected { get; set; }
public List<ServerInfo> Servers { get; }
public void AddServer(string name, IPEndPoint address)
{
AddServer(name, 0, TimeZoneInfo.Local, address);
}
public void AddServer(string name, int fullPercent, TimeZoneInfo tz, IPEndPoint address)
{
Servers.Add(new ServerInfo(name, fullPercent, tz, address));
}
}
public static partial class EventSink
{
public static event Action<ServerListEventArgs> ServerList;
public static void InvokeServerList(ServerListEventArgs e) => ServerList?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ServerListEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.Net;
using Server.Accounting;
using Server.Network;
namespace Server
{
public class ServerListEventArgs : EventArgs
{
public ServerListEventArgs(NetState state, IAccount account)
{
State = state;
Account = account;
Servers = new List<ServerInfo>();
}
public NetState State { get; }
public IAccount Account { get; }
public bool Rejected { get; set; }
public List<ServerInfo> Servers { get; }
public void AddServer(string name, IPEndPoint address)
{
AddServer(name, 0, TimeZoneInfo.Local, address);
}
public void AddServer(string name, int fullPercent, TimeZoneInfo tz, IPEndPoint address)
{
Servers.Add(new ServerInfo(name, fullPercent, tz, address));
}
}
public static partial class EventSink
{
public static event Action<ServerListEventArgs> ServerList;
public static void InvokeServerList(ServerListEventArgs e) => ServerList?.Invoke(e);
}
}

View file

@ -1,45 +1,45 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SocketConnectionEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Microsoft.AspNetCore.Connections;
namespace Server
{
public class SocketConnectEventArgs : EventArgs
{
public SocketConnectEventArgs(ConnectionContext c)
{
Context = c;
AllowConnection = true;
}
public ConnectionContext Context { get; }
public bool AllowConnection { get; set; }
}
public static partial class EventSink
{
public static event Action<SocketConnectEventArgs> SocketConnect;
public static void InvokeSocketConnect(SocketConnectEventArgs e) => SocketConnect?.Invoke(e);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SocketConnectionEvent.cs *
* Created: 2020/04/11 - Updated: 2020/04/11 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using Microsoft.AspNetCore.Connections;
namespace Server
{
public class SocketConnectEventArgs : EventArgs
{
public SocketConnectEventArgs(ConnectionContext c)
{
Context = c;
AllowConnection = true;
}
public ConnectionContext Context { get; }
public bool AllowConnection { get; set; }
}
public static partial class EventSink
{
public static event Action<SocketConnectEventArgs> SocketConnect;
public static void InvokeSocketConnect(SocketConnectEventArgs e) => SocketConnect?.Invoke(e);
}
}

View file

@ -1,46 +1,46 @@
using System;
using Server.Network;
namespace Server
{
public class SpeechEventArgs : EventArgs
{
public SpeechEventArgs(Mobile mobile, string speech, MessageType type, int hue, int[] keywords)
{
Mobile = mobile;
Speech = speech;
Type = type;
Hue = hue;
Keywords = keywords;
}
public Mobile Mobile { get; }
public string Speech { get; set; }
public MessageType Type { get; }
public int Hue { get; }
public int[] Keywords { get; }
public bool Handled { get; set; }
public bool Blocked { get; set; }
public bool HasKeyword(int keyword)
{
for (var i = 0; i < Keywords.Length; ++i)
if (Keywords[i] == keyword)
return true;
return false;
}
}
public static partial class EventSink
{
public static event Action<SpeechEventArgs> Speech;
public static void InvokeSpeech(SpeechEventArgs e) => Speech?.Invoke(e);
}
}
using System;
using Server.Network;
namespace Server
{
public class SpeechEventArgs : EventArgs
{
public SpeechEventArgs(Mobile mobile, string speech, MessageType type, int hue, int[] keywords)
{
Mobile = mobile;
Speech = speech;
Type = type;
Hue = hue;
Keywords = keywords;
}
public Mobile Mobile { get; }
public string Speech { get; set; }
public MessageType Type { get; }
public int Hue { get; }
public int[] Keywords { get; }
public bool Handled { get; set; }
public bool Blocked { get; set; }
public bool HasKeyword(int keyword)
{
for (var i = 0; i < Keywords.Length; ++i)
if (Keywords[i] == keyword)
return true;
return false;
}
}
public static partial class EventSink
{
public static event Action<SpeechEventArgs> Speech;
public static void InvokeSpeech(SpeechEventArgs e) => Speech?.Invoke(e);
}
}

View file

@ -1,338 +1,353 @@
/***************************************************************************
* ExpansionInfo.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public enum Expansion
{
None,
T2A,
UOR,
UOTD,
LBR,
AOS,
SE,
ML,
SA,
HS,
TOL,
EJ
}
[Flags]
public enum ClientFlags
{
None = 0x00000000,
Felucca = 0x00000001,
Trammel = 0x00000002,
Ilshenar = 0x00000004,
Malas = 0x00000008,
Tokuno = 0x00000010,
TerMur = 0x00000020,
Unk1 = 0x00000040,
Unk2 = 0x00000080,
UOTD = 0x00000100
}
[Flags]
public enum FeatureFlags
{
None = 0x00000000,
T2A = 0x00000001,
UOR = 0x00000002,
UOTD = 0x00000004,
LBR = 0x00000008,
AOS = 0x00000010,
SixthCharacterSlot = 0x00000020,
SE = 0x00000040,
ML = 0x00000080,
EigthAge = 0x00000100,
NinthAge = 0x00000200, /* Crystal/Shadow Custom House Tiles */
TenthAge = 0x00000400,
IncreasedStorage = 0x00000800, /* Increased Housing/Bank Storage */
SeventhCharacterSlot = 0x00001000,
RoleplayFaces = 0x00002000,
TrialAccount = 0x00004000,
LiveAccount = 0x00008000,
SA = 0x00010000,
HS = 0x00020000,
Gothic = 0x00040000,
Rustic = 0x00080000,
Jungle = 0x00100000,
Shadowguard = 0x00200000,
TOL = 0x00400000,
EJ = 0x00800000,
ExpansionNone = None,
ExpansionT2A = T2A,
ExpansionUOR = ExpansionT2A | UOR,
ExpansionUOTD = ExpansionUOR | UOTD,
ExpansionLBR = ExpansionUOTD | LBR,
ExpansionAOS = ExpansionLBR | AOS | LiveAccount,
ExpansionSE = ExpansionAOS | SE,
ExpansionML = ExpansionSE | ML | NinthAge,
ExpansionSA = ExpansionML | SA | Gothic | Rustic,
ExpansionHS = ExpansionSA | HS,
ExpansionTOL = ExpansionHS | TOL | Jungle | Shadowguard,
ExpansionEJ = ExpansionTOL | EJ
}
[Flags]
public enum CharacterListFlags
{
None = 0x00000000,
Unk1 = 0x00000001,
OverwriteConfigButton = 0x00000002,
OneCharacterSlot = 0x00000004,
ContextMenus = 0x00000008,
SlotLimit = 0x00000010,
AOS = 0x00000020,
SixthCharacterSlot = 0x00000040,
SE = 0x00000080,
ML = 0x00000100,
Unk2 = 0x00000200,
UO3DClientType = 0x00000400,
Unk3 = 0x00000800,
SeventhCharacterSlot = 0x00001000,
Unk4 = 0x00002000,
NewMovementSystem = 0x00004000,
NewFeluccaAreas = 0x00008000,
ExpansionNone = ContextMenus,
ExpansionT2A = ContextMenus,
ExpansionUOR = ContextMenus,
ExpansionUOTD = ContextMenus,
ExpansionLBR = ContextMenus,
ExpansionAOS = ContextMenus | AOS,
ExpansionSE = ExpansionAOS | SE,
ExpansionML = ExpansionSE | ML,
ExpansionSA = ExpansionML,
ExpansionHS = ExpansionSA,
ExpansionTOL = ExpansionHS,
ExpansionEJ = ExpansionTOL
}
[Flags]
public enum HousingFlags
{
None = 0x0,
AOS = 0x10,
SE = 0x40,
ML = 0x80,
Crystal = 0x200,
SA = 0x10000,
HS = 0x20000,
Gothic = 0x40000,
Rustic = 0x80000,
Jungle = 0x100000,
Shadowguard = 0x200000,
TOL = 0x400000,
EJ = 0x800000,
HousingAOS = AOS,
HousingSE = HousingAOS | SE,
HousingML = HousingSE | ML | Crystal,
HousingSA = HousingML | SA | Gothic | Rustic,
HousingHS = HousingSA | HS,
HousingTOL = HousingHS | TOL | Jungle | Shadowguard,
HousingEJ = HousingTOL | EJ
}
public class ExpansionInfo
{
static ExpansionInfo()
{
Table = new[]
{
new ExpansionInfo(
0,
"None",
ClientFlags.None,
FeatureFlags.ExpansionNone,
CharacterListFlags.ExpansionNone,
HousingFlags.None),
new ExpansionInfo(
1,
"The Second Age",
ClientFlags.Felucca,
FeatureFlags.ExpansionT2A,
CharacterListFlags.ExpansionT2A,
HousingFlags.None),
new ExpansionInfo(
2,
"Renaissance",
ClientFlags.Trammel,
FeatureFlags.ExpansionUOR,
CharacterListFlags.ExpansionUOR,
HousingFlags.None),
new ExpansionInfo(
3,
"Third Dawn",
ClientFlags.Ilshenar,
FeatureFlags.ExpansionUOTD,
CharacterListFlags.ExpansionUOTD,
HousingFlags.None),
new ExpansionInfo(
4,
"Blackthorn's Revenge",
ClientFlags.Ilshenar,
FeatureFlags.ExpansionLBR,
CharacterListFlags.ExpansionLBR,
HousingFlags.None),
new ExpansionInfo(
5,
"Age of Shadows",
ClientFlags.Malas,
FeatureFlags.ExpansionAOS,
CharacterListFlags.ExpansionAOS,
HousingFlags.HousingAOS),
new ExpansionInfo(
6,
"Samurai Empire",
ClientFlags.Tokuno,
FeatureFlags.ExpansionSE,
CharacterListFlags.ExpansionSE,
HousingFlags.HousingSE),
new ExpansionInfo(
7,
"Mondain's Legacy",
new ClientVersion("5.0.0a"),
FeatureFlags.ExpansionML,
CharacterListFlags.ExpansionML,
HousingFlags.HousingML),
new ExpansionInfo(
8,
"Stygian Abyss",
ClientFlags.TerMur,
FeatureFlags.ExpansionSA,
CharacterListFlags.ExpansionSA,
HousingFlags.HousingSA),
new ExpansionInfo(
9,
"High Seas",
new ClientVersion("7.0.9.0"),
FeatureFlags.ExpansionHS,
CharacterListFlags.ExpansionHS,
HousingFlags.HousingHS),
new ExpansionInfo(
10,
"Time of Legends",
new ClientVersion("7.0.45.65"),
FeatureFlags.ExpansionTOL,
CharacterListFlags.ExpansionTOL,
HousingFlags.HousingTOL),
new ExpansionInfo(
11,
"Endless Journey",
new ClientVersion("7.0.61.0"),
FeatureFlags.ExpansionEJ,
CharacterListFlags.ExpansionEJ,
HousingFlags.HousingEJ)
};
}
public ExpansionInfo(
int id,
string name,
ClientFlags clientFlags,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
HousingFlags customHousingFlag)
: this(id, name, supportedFeatures, charListFlags, customHousingFlag) =>
ClientFlags = clientFlags;
public ExpansionInfo(
int id,
string name,
ClientVersion requiredClient,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
HousingFlags customHousingFlag)
: this(id, name, supportedFeatures, charListFlags, customHousingFlag) =>
RequiredClient = requiredClient;
private ExpansionInfo(
int id,
string name,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
HousingFlags customHousingFlag)
{
ID = id;
Name = name;
SupportedFeatures = supportedFeatures;
CharacterListFlags = charListFlags;
CustomHousingFlag = customHousingFlag;
}
public static ExpansionInfo CoreExpansion => GetInfo(Core.Expansion);
public static ExpansionInfo[] Table { get; }
public int ID { get; }
public string Name { get; set; }
public ClientFlags ClientFlags { get; set; }
public FeatureFlags SupportedFeatures { get; set; }
public CharacterListFlags CharacterListFlags { get; set; }
public ClientVersion RequiredClient { get; set; }
public HousingFlags CustomHousingFlag { get; set; }
public static FeatureFlags GetFeatures(Expansion ex)
{
var info = GetInfo(ex);
if (info != null) return info.SupportedFeatures;
return ex switch
{
Expansion.None => FeatureFlags.ExpansionNone,
Expansion.T2A => FeatureFlags.ExpansionT2A,
Expansion.UOR => FeatureFlags.ExpansionUOR,
Expansion.UOTD => FeatureFlags.ExpansionUOTD,
Expansion.LBR => FeatureFlags.ExpansionLBR,
Expansion.AOS => FeatureFlags.ExpansionAOS,
Expansion.SE => FeatureFlags.ExpansionSE,
Expansion.ML => FeatureFlags.ExpansionML,
Expansion.SA => FeatureFlags.ExpansionSA,
Expansion.HS => FeatureFlags.ExpansionHS,
Expansion.TOL => FeatureFlags.ExpansionTOL,
Expansion.EJ => FeatureFlags.EJ,
_ => FeatureFlags.ExpansionNone
};
}
public static ExpansionInfo GetInfo(Expansion ex) => GetInfo((int)ex);
public static ExpansionInfo GetInfo(int ex)
{
var v = ex;
if (v < 0 || v >= Table.Length) v = 0;
return Table[v];
}
public override string ToString() => Name;
}
}
/***************************************************************************
* ExpansionInfo.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public enum Expansion
{
None,
T2A,
UOR,
UOTD,
LBR,
AOS,
SE,
ML,
SA,
HS,
TOL,
EJ
}
[Flags]
public enum ClientFlags
{
None = 0x00000000,
Felucca = 0x00000001,
Trammel = 0x00000002,
Ilshenar = 0x00000004,
Malas = 0x00000008,
Tokuno = 0x00000010,
TerMur = 0x00000020,
Unk1 = 0x00000040,
Unk2 = 0x00000080,
UOTD = 0x00000100
}
[Flags]
public enum FeatureFlags
{
None = 0x00000000,
T2A = 0x00000001,
UOR = 0x00000002,
UOTD = 0x00000004,
LBR = 0x00000008,
AOS = 0x00000010,
SixthCharacterSlot = 0x00000020,
SE = 0x00000040,
ML = 0x00000080,
EigthAge = 0x00000100,
NinthAge = 0x00000200, /* Crystal/Shadow Custom House Tiles */
TenthAge = 0x00000400,
IncreasedStorage = 0x00000800, /* Increased Housing/Bank Storage */
SeventhCharacterSlot = 0x00001000,
RoleplayFaces = 0x00002000,
TrialAccount = 0x00004000,
LiveAccount = 0x00008000,
SA = 0x00010000,
HS = 0x00020000,
Gothic = 0x00040000,
Rustic = 0x00080000,
Jungle = 0x00100000,
Shadowguard = 0x00200000,
TOL = 0x00400000,
EJ = 0x00800000,
ExpansionNone = None,
ExpansionT2A = T2A,
ExpansionUOR = ExpansionT2A | UOR,
ExpansionUOTD = ExpansionUOR | UOTD,
ExpansionLBR = ExpansionUOTD | LBR,
ExpansionAOS = ExpansionLBR | AOS | LiveAccount,
ExpansionSE = ExpansionAOS | SE,
ExpansionML = ExpansionSE | ML | NinthAge,
ExpansionSA = ExpansionML | SA | Gothic | Rustic,
ExpansionHS = ExpansionSA | HS,
ExpansionTOL = ExpansionHS | TOL | Jungle | Shadowguard,
ExpansionEJ = ExpansionTOL | EJ
}
[Flags]
public enum CharacterListFlags
{
None = 0x00000000,
Unk1 = 0x00000001,
OverwriteConfigButton = 0x00000002,
OneCharacterSlot = 0x00000004,
ContextMenus = 0x00000008,
SlotLimit = 0x00000010,
AOS = 0x00000020,
SixthCharacterSlot = 0x00000040,
SE = 0x00000080,
ML = 0x00000100,
Unk2 = 0x00000200,
UO3DClientType = 0x00000400,
Unk3 = 0x00000800,
SeventhCharacterSlot = 0x00001000,
Unk4 = 0x00002000,
NewMovementSystem = 0x00004000,
NewFeluccaAreas = 0x00008000,
ExpansionNone = ContextMenus,
ExpansionT2A = ContextMenus,
ExpansionUOR = ContextMenus,
ExpansionUOTD = ContextMenus,
ExpansionLBR = ContextMenus,
ExpansionAOS = ContextMenus | AOS,
ExpansionSE = ExpansionAOS | SE,
ExpansionML = ExpansionSE | ML,
ExpansionSA = ExpansionML,
ExpansionHS = ExpansionSA,
ExpansionTOL = ExpansionHS,
ExpansionEJ = ExpansionTOL
}
[Flags]
public enum HousingFlags
{
None = 0x0,
AOS = 0x10,
SE = 0x40,
ML = 0x80,
Crystal = 0x200,
SA = 0x10000,
HS = 0x20000,
Gothic = 0x40000,
Rustic = 0x80000,
Jungle = 0x100000,
Shadowguard = 0x200000,
TOL = 0x400000,
EJ = 0x800000,
HousingAOS = AOS,
HousingSE = HousingAOS | SE,
HousingML = HousingSE | ML | Crystal,
HousingSA = HousingML | SA | Gothic | Rustic,
HousingHS = HousingSA | HS,
HousingTOL = HousingHS | TOL | Jungle | Shadowguard,
HousingEJ = HousingTOL | EJ
}
public class ExpansionInfo
{
static ExpansionInfo()
{
Table = new[]
{
new ExpansionInfo(
0,
"None",
ClientFlags.None,
FeatureFlags.ExpansionNone,
CharacterListFlags.ExpansionNone,
HousingFlags.None
),
new ExpansionInfo(
1,
"The Second Age",
ClientFlags.Felucca,
FeatureFlags.ExpansionT2A,
CharacterListFlags.ExpansionT2A,
HousingFlags.None
),
new ExpansionInfo(
2,
"Renaissance",
ClientFlags.Trammel,
FeatureFlags.ExpansionUOR,
CharacterListFlags.ExpansionUOR,
HousingFlags.None
),
new ExpansionInfo(
3,
"Third Dawn",
ClientFlags.Ilshenar,
FeatureFlags.ExpansionUOTD,
CharacterListFlags.ExpansionUOTD,
HousingFlags.None
),
new ExpansionInfo(
4,
"Blackthorn's Revenge",
ClientFlags.Ilshenar,
FeatureFlags.ExpansionLBR,
CharacterListFlags.ExpansionLBR,
HousingFlags.None
),
new ExpansionInfo(
5,
"Age of Shadows",
ClientFlags.Malas,
FeatureFlags.ExpansionAOS,
CharacterListFlags.ExpansionAOS,
HousingFlags.HousingAOS
),
new ExpansionInfo(
6,
"Samurai Empire",
ClientFlags.Tokuno,
FeatureFlags.ExpansionSE,
CharacterListFlags.ExpansionSE,
HousingFlags.HousingSE
),
new ExpansionInfo(
7,
"Mondain's Legacy",
new ClientVersion("5.0.0a"),
FeatureFlags.ExpansionML,
CharacterListFlags.ExpansionML,
HousingFlags.HousingML
),
new ExpansionInfo(
8,
"Stygian Abyss",
ClientFlags.TerMur,
FeatureFlags.ExpansionSA,
CharacterListFlags.ExpansionSA,
HousingFlags.HousingSA
),
new ExpansionInfo(
9,
"High Seas",
new ClientVersion("7.0.9.0"),
FeatureFlags.ExpansionHS,
CharacterListFlags.ExpansionHS,
HousingFlags.HousingHS
),
new ExpansionInfo(
10,
"Time of Legends",
new ClientVersion("7.0.45.65"),
FeatureFlags.ExpansionTOL,
CharacterListFlags.ExpansionTOL,
HousingFlags.HousingTOL
),
new ExpansionInfo(
11,
"Endless Journey",
new ClientVersion("7.0.61.0"),
FeatureFlags.ExpansionEJ,
CharacterListFlags.ExpansionEJ,
HousingFlags.HousingEJ
)
};
}
public ExpansionInfo(
int id,
string name,
ClientFlags clientFlags,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
HousingFlags customHousingFlag
)
: this(id, name, supportedFeatures, charListFlags, customHousingFlag) =>
ClientFlags = clientFlags;
public ExpansionInfo(
int id,
string name,
ClientVersion requiredClient,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
HousingFlags customHousingFlag
)
: this(id, name, supportedFeatures, charListFlags, customHousingFlag) =>
RequiredClient = requiredClient;
private ExpansionInfo(
int id,
string name,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
HousingFlags customHousingFlag
)
{
ID = id;
Name = name;
SupportedFeatures = supportedFeatures;
CharacterListFlags = charListFlags;
CustomHousingFlag = customHousingFlag;
}
public static ExpansionInfo CoreExpansion => GetInfo(Core.Expansion);
public static ExpansionInfo[] Table { get; }
public int ID { get; }
public string Name { get; set; }
public ClientFlags ClientFlags { get; set; }
public FeatureFlags SupportedFeatures { get; set; }
public CharacterListFlags CharacterListFlags { get; set; }
public ClientVersion RequiredClient { get; set; }
public HousingFlags CustomHousingFlag { get; set; }
public static FeatureFlags GetFeatures(Expansion ex)
{
var info = GetInfo(ex);
if (info != null) return info.SupportedFeatures;
return ex switch
{
Expansion.None => FeatureFlags.ExpansionNone,
Expansion.T2A => FeatureFlags.ExpansionT2A,
Expansion.UOR => FeatureFlags.ExpansionUOR,
Expansion.UOTD => FeatureFlags.ExpansionUOTD,
Expansion.LBR => FeatureFlags.ExpansionLBR,
Expansion.AOS => FeatureFlags.ExpansionAOS,
Expansion.SE => FeatureFlags.ExpansionSE,
Expansion.ML => FeatureFlags.ExpansionML,
Expansion.SA => FeatureFlags.ExpansionSA,
Expansion.HS => FeatureFlags.ExpansionHS,
Expansion.TOL => FeatureFlags.ExpansionTOL,
Expansion.EJ => FeatureFlags.EJ,
_ => FeatureFlags.ExpansionNone
};
}
public static ExpansionInfo GetInfo(Expansion ex) => GetInfo((int)ex);
public static ExpansionInfo GetInfo(int ex)
{
var v = ex;
if (v < 0 || v >= Table.Length) v = 0;
return Table[v];
}
public override string ToString() => Name;
}
}

View file

@ -1,122 +1,123 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point2D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
[Parsable]
public struct Point2D :
IPoint2D, IComparable<Point2D>, IComparable<IPoint2D>, IEquatable<object>, IEquatable<Point2D>, IEquatable<IPoint2D>
{
internal int m_X;
internal int m_Y;
public static readonly Point2D Zero = new Point2D(0, 0);
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_X;
set => m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Y;
set => m_Y = value;
}
public Point2D(int x, int y)
{
m_X = x;
m_Y = y;
}
public Point2D(IPoint2D p) : this(p.X, p.Y)
{
}
public override string ToString() => $"({m_X}, {m_Y})";
public static Point2D Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int x);
start = end;
end = value.IndexOf(')', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int y);
return new Point2D(x, y);
}
public bool Equals(Point2D other) => m_X == other.m_X && m_Y == other.m_Y;
public bool Equals(IPoint2D other) =>
!ReferenceEquals(other, null) && m_X == other.X && m_Y == other.Y;
public override bool Equals(object obj) => obj is Point2D other && Equals(other);
public override int GetHashCode() => HashCode.Combine(m_X, m_Y);
public static bool operator ==(Point2D l, Point2D r) => l.m_X == r.m_X && l.m_Y == r.m_Y;
public static bool operator !=(Point2D l, Point2D r) => l.m_X != r.m_X || l.m_Y != r.m_Y;
public static bool operator ==(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X == r.X && l.m_Y == r.Y;
public static bool operator !=(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && (l.m_X != r.X || l.m_Y != r.Y);
public static bool operator >(Point2D l, Point2D r) => l.m_X > r.m_X && l.m_Y > r.m_Y;
public static bool operator >(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X > r.X && l.m_Y > r.Y;
public static bool operator <(Point2D l, Point2D r) => l.m_X < r.m_X && l.m_Y < r.m_Y;
public static bool operator <(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X < r.X && l.m_Y < r.Y;
public static bool operator >=(Point2D l, Point2D r) => l.m_X >= r.m_X && l.m_Y >= r.m_Y;
public static bool operator >=(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X >= r.X && l.m_Y >= r.Y;
public static bool operator <=(Point2D l, Point2D r) => l.m_X <= r.m_X && l.m_Y <= r.m_Y;
public static bool operator <=(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X <= r.X && l.m_Y <= r.Y;
public int CompareTo(Point2D other)
{
var xComparison = m_X.CompareTo(other.m_X);
if (xComparison != 0) return xComparison;
return m_Y.CompareTo(other.m_Y);
}
public int CompareTo(IPoint2D other)
{
var xComparison = m_X.CompareTo(other.X);
if (xComparison != 0) return xComparison;
return m_Y.CompareTo(other.Y);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point2D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
[Parsable]
public struct Point2D
: IPoint2D, IComparable<Point2D>, IComparable<IPoint2D>, IEquatable<object>, IEquatable<Point2D>,
IEquatable<IPoint2D>
{
internal int m_X;
internal int m_Y;
public static readonly Point2D Zero = new Point2D(0, 0);
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_X;
set => m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Y;
set => m_Y = value;
}
public Point2D(int x, int y)
{
m_X = x;
m_Y = y;
}
public Point2D(IPoint2D p) : this(p.X, p.Y)
{
}
public override string ToString() => $"({m_X}, {m_Y})";
public static Point2D Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var x);
start = end;
end = value.IndexOf(')', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var y);
return new Point2D(x, y);
}
public bool Equals(Point2D other) => m_X == other.m_X && m_Y == other.m_Y;
public bool Equals(IPoint2D other) =>
!ReferenceEquals(other, null) && m_X == other.X && m_Y == other.Y;
public override bool Equals(object obj) => obj is Point2D other && Equals(other);
public override int GetHashCode() => HashCode.Combine(m_X, m_Y);
public static bool operator ==(Point2D l, Point2D r) => l.m_X == r.m_X && l.m_Y == r.m_Y;
public static bool operator !=(Point2D l, Point2D r) => l.m_X != r.m_X || l.m_Y != r.m_Y;
public static bool operator ==(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X == r.X && l.m_Y == r.Y;
public static bool operator !=(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && (l.m_X != r.X || l.m_Y != r.Y);
public static bool operator >(Point2D l, Point2D r) => l.m_X > r.m_X && l.m_Y > r.m_Y;
public static bool operator >(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X > r.X && l.m_Y > r.Y;
public static bool operator <(Point2D l, Point2D r) => l.m_X < r.m_X && l.m_Y < r.m_Y;
public static bool operator <(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X < r.X && l.m_Y < r.Y;
public static bool operator >=(Point2D l, Point2D r) => l.m_X >= r.m_X && l.m_Y >= r.m_Y;
public static bool operator >=(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X >= r.X && l.m_Y >= r.Y;
public static bool operator <=(Point2D l, Point2D r) => l.m_X <= r.m_X && l.m_Y <= r.m_Y;
public static bool operator <=(Point2D l, IPoint2D r) => !ReferenceEquals(r, null) && l.m_X <= r.X && l.m_Y <= r.Y;
public int CompareTo(Point2D other)
{
var xComparison = m_X.CompareTo(other.m_X);
if (xComparison != 0) return xComparison;
return m_Y.CompareTo(other.m_Y);
}
public int CompareTo(IPoint2D other)
{
var xComparison = m_X.CompareTo(other.X);
if (xComparison != 0) return xComparison;
return m_Y.CompareTo(other.Y);
}
}
}

View file

@ -1,150 +1,151 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
[Parsable]
public struct Point3D :
IPoint3D, IComparable<Point3D>, IComparable<IPoint3D>, IEquatable<object>, IEquatable<Point3D>, IEquatable<IPoint3D>
{
internal int m_X;
internal int m_Y;
internal int m_Z;
public static readonly Point3D Zero = new Point3D(0, 0, 0);
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_X;
set => m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Y;
set => m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Z
{
get => m_Z;
set => m_Z = value;
}
public Point3D(IPoint3D p) : this(p.X, p.Y, p.Z)
{
}
public Point3D(IPoint2D p, int z) : this(p.X, p.Y, z)
{
}
public Point3D(int x, int y, int z)
{
m_X = x;
m_Y = y;
m_Z = z;
}
public override string ToString() => $"({m_X}, {m_Y}, {m_Z})";
public bool Equals(Point3D other) => m_X == other.m_X && m_Y == other.m_Y && m_Z == other.m_Z;
public bool Equals(IPoint3D other) =>
!ReferenceEquals(other, null) && m_X == other.X && m_Y == other.Y && m_Z == other.Z;
public override bool Equals(object obj) => obj is Point3D other && Equals(other);
public override int GetHashCode() => HashCode.Combine(m_X, m_Y, m_Z);
public static Point3D Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int x);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int y);
start = end;
end = value.IndexOf(')', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int z);
return new Point3D(x, y, z);
}
public static bool operator ==(Point3D l, Point3D r) => l.m_X == r.m_X && l.m_Y == r.m_Y && l.m_Z == r.m_Z;
public static bool operator ==(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X == r.X && l.m_Y == r.Y && l.m_Z == r.Z;
public static bool operator !=(Point3D l, Point3D r) => l.m_X != r.m_X || l.m_Y != r.m_Y || l.m_Z != r.m_Z;
public static bool operator !=(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && (l.m_X != r.X || l.m_Y != r.Y || l.m_Z != r.Z);
public static bool operator >(Point3D l, Point3D r) => l.m_X > r.m_X && l.m_Y > r.m_Y && l.m_Z > r.m_Z;
public static bool operator >(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X > r.X && l.m_Y > r.Y && l.m_Z > r.Z;
public static bool operator <(Point3D l, Point3D r) => l.m_X < r.m_X && l.m_Y < r.m_Y && l.m_Z > r.m_Z;
public static bool operator <(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X < r.X && l.m_Y < r.Y && l.m_Z > r.Z;
public static bool operator >=(Point3D l, Point3D r) => l.m_X >= r.m_X && l.m_Y >= r.m_Y && l.m_Z > r.m_Z;
public static bool operator >=(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X >= r.X && l.m_Y >= r.Y && l.m_Z > r.Z;
public static bool operator <=(Point3D l, Point3D r) => l.m_X <= r.m_X && l.m_Y <= r.m_Y && l.m_Z > r.m_Z;
public static bool operator <=(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X <= r.X && l.m_Y <= r.Y && l.m_Z > r.Z;
public int CompareTo(Point3D other)
{
var xComparison = m_X.CompareTo(other.m_X);
if (xComparison != 0) return xComparison;
var yComparison = m_Y.CompareTo(other.m_Y);
if (yComparison != 0) return yComparison;
return m_Z.CompareTo(other.m_Z);
}
public int CompareTo(IPoint3D other)
{
var xComparison = m_X.CompareTo(other.X);
if (xComparison != 0) return xComparison;
var yComparison = m_Y.CompareTo(other.Y);
if (yComparison != 0) return yComparison;
return m_Z.CompareTo(other.Z);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
[Parsable]
public struct Point3D
: IPoint3D, IComparable<Point3D>, IComparable<IPoint3D>, IEquatable<object>, IEquatable<Point3D>,
IEquatable<IPoint3D>
{
internal int m_X;
internal int m_Y;
internal int m_Z;
public static readonly Point3D Zero = new Point3D(0, 0, 0);
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_X;
set => m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Y;
set => m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Z
{
get => m_Z;
set => m_Z = value;
}
public Point3D(IPoint3D p) : this(p.X, p.Y, p.Z)
{
}
public Point3D(IPoint2D p, int z) : this(p.X, p.Y, z)
{
}
public Point3D(int x, int y, int z)
{
m_X = x;
m_Y = y;
m_Z = z;
}
public override string ToString() => $"({m_X}, {m_Y}, {m_Z})";
public bool Equals(Point3D other) => m_X == other.m_X && m_Y == other.m_Y && m_Z == other.m_Z;
public bool Equals(IPoint3D other) =>
!ReferenceEquals(other, null) && m_X == other.X && m_Y == other.Y && m_Z == other.Z;
public override bool Equals(object obj) => obj is Point3D other && Equals(other);
public override int GetHashCode() => HashCode.Combine(m_X, m_Y, m_Z);
public static Point3D Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var x);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var y);
start = end;
end = value.IndexOf(')', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var z);
return new Point3D(x, y, z);
}
public static bool operator ==(Point3D l, Point3D r) => l.m_X == r.m_X && l.m_Y == r.m_Y && l.m_Z == r.m_Z;
public static bool operator ==(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X == r.X && l.m_Y == r.Y && l.m_Z == r.Z;
public static bool operator !=(Point3D l, Point3D r) => l.m_X != r.m_X || l.m_Y != r.m_Y || l.m_Z != r.m_Z;
public static bool operator !=(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && (l.m_X != r.X || l.m_Y != r.Y || l.m_Z != r.Z);
public static bool operator >(Point3D l, Point3D r) => l.m_X > r.m_X && l.m_Y > r.m_Y && l.m_Z > r.m_Z;
public static bool operator >(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X > r.X && l.m_Y > r.Y && l.m_Z > r.Z;
public static bool operator <(Point3D l, Point3D r) => l.m_X < r.m_X && l.m_Y < r.m_Y && l.m_Z > r.m_Z;
public static bool operator <(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X < r.X && l.m_Y < r.Y && l.m_Z > r.Z;
public static bool operator >=(Point3D l, Point3D r) => l.m_X >= r.m_X && l.m_Y >= r.m_Y && l.m_Z > r.m_Z;
public static bool operator >=(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X >= r.X && l.m_Y >= r.Y && l.m_Z > r.Z;
public static bool operator <=(Point3D l, Point3D r) => l.m_X <= r.m_X && l.m_Y <= r.m_Y && l.m_Z > r.m_Z;
public static bool operator <=(Point3D l, IPoint3D r) =>
!ReferenceEquals(r, null) && l.m_X <= r.X && l.m_Y <= r.Y && l.m_Z > r.Z;
public int CompareTo(Point3D other)
{
var xComparison = m_X.CompareTo(other.m_X);
if (xComparison != 0) return xComparison;
var yComparison = m_Y.CompareTo(other.m_Y);
if (yComparison != 0) return yComparison;
return m_Z.CompareTo(other.m_Z);
}
public int CompareTo(IPoint3D other)
{
var xComparison = m_X.CompareTo(other.X);
if (xComparison != 0) return xComparison;
var yComparison = m_Y.CompareTo(other.Y);
if (yComparison != 0) return yComparison;
return m_Z.CompareTo(other.Z);
}
}
}

View file

@ -1,94 +1,96 @@
/***************************************************************************
* Point3DList.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server
{
public class Point3DList
{
private static readonly Point3D[] m_EmptyList = System.Array.Empty<Point3D>();
private Point3D[] m_List;
public Point3DList()
{
m_List = new Point3D[8];
Count = 0;
}
public int Count { get; private set; }
public Point3D Last => m_List[Count - 1];
public Point3D this[int index] => m_List[index];
public void Clear()
{
Count = 0;
}
public void Add(int x, int y, int z)
{
if (Count + 1 > m_List.Length)
{
var old = m_List;
m_List = new Point3D[old.Length * 2];
for (var i = 0; i < old.Length; ++i)
m_List[i] = old[i];
}
m_List[Count].m_X = x;
m_List[Count].m_Y = y;
m_List[Count].m_Z = z;
++Count;
}
public void Add(Point3D p)
{
if (Count + 1 > m_List.Length)
{
var old = m_List;
m_List = new Point3D[old.Length * 2];
for (var i = 0; i < old.Length; ++i)
m_List[i] = old[i];
}
m_List[Count].m_X = p.m_X;
m_List[Count].m_Y = p.m_Y;
m_List[Count].m_Z = p.m_Z;
++Count;
}
public Point3D[] ToArray()
{
if (Count == 0)
return m_EmptyList;
var list = new Point3D[Count];
for (var i = 0; i < Count; ++i)
list[i] = m_List[i];
Count = 0;
return list;
}
}
}
/***************************************************************************
* Point3DList.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public class Point3DList
{
private static readonly Point3D[] m_EmptyList = Array.Empty<Point3D>();
private Point3D[] m_List;
public Point3DList()
{
m_List = new Point3D[8];
Count = 0;
}
public int Count { get; private set; }
public Point3D Last => m_List[Count - 1];
public Point3D this[int index] => m_List[index];
public void Clear()
{
Count = 0;
}
public void Add(int x, int y, int z)
{
if (Count + 1 > m_List.Length)
{
var old = m_List;
m_List = new Point3D[old.Length * 2];
for (var i = 0; i < old.Length; ++i)
m_List[i] = old[i];
}
m_List[Count].m_X = x;
m_List[Count].m_Y = y;
m_List[Count].m_Z = z;
++Count;
}
public void Add(Point3D p)
{
if (Count + 1 > m_List.Length)
{
var old = m_List;
m_List = new Point3D[old.Length * 2];
for (var i = 0; i < old.Length; ++i)
m_List[i] = old[i];
}
m_List[Count].m_X = p.m_X;
m_List[Count].m_Y = p.m_Y;
m_List[Count].m_Z = p.m_Z;
++Count;
}
public Point3D[] ToArray()
{
if (Count == 0)
return m_EmptyList;
var list = new Point3D[Count];
for (var i = 0; i < Count; ++i)
list[i] = m_List[i];
Count = 0;
return list;
}
}
}

View file

@ -1,141 +1,141 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle2D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
namespace Server
{
[NoSort]
[Parsable]
[PropertyObject]
public struct Rectangle2D
{
private Point2D m_Start;
private Point2D m_End;
public Rectangle2D(IPoint2D start, IPoint2D end)
{
m_Start = new Point2D(start);
m_End = new Point2D(end);
}
public Rectangle2D(int x, int y, int width, int height)
{
m_Start = new Point2D(x, y);
m_End = new Point2D(x + width, y + height);
}
public void Set(int x, int y, int width, int height)
{
m_Start = new Point2D(x, y);
m_End = new Point2D(x + width, y + height);
}
public static Rectangle2D Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int x);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int y);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int w);
start = end;
end = value.IndexOf(')', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int h);
return new Rectangle2D(x, y, w, h);
}
[CommandProperty(AccessLevel.Counselor)]
public Point2D Start
{
get => m_Start;
set => m_Start = value;
}
[CommandProperty(AccessLevel.Counselor)]
public Point2D End
{
get => m_End;
set => m_End = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_Start.m_X;
set => m_Start.m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Start.m_Y;
set => m_Start.m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Width
{
get => m_End.m_X - m_Start.m_X;
set => m_End.m_X = m_Start.m_X + value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Height
{
get => m_End.m_Y - m_Start.m_Y;
set => m_End.m_Y = m_Start.m_Y + value;
}
public void MakeHold(Rectangle2D r)
{
if (r.m_Start.m_X < m_Start.m_X)
m_Start.m_X = r.m_Start.m_X;
if (r.m_Start.m_Y < m_Start.m_Y)
m_Start.m_Y = r.m_Start.m_Y;
if (r.m_End.m_X > m_End.m_X)
m_End.m_X = r.m_End.m_X;
if (r.m_End.m_Y > m_End.m_Y)
m_End.m_Y = r.m_End.m_Y;
}
public bool Contains(Point3D p) =>
m_Start.m_X <= p.m_X && m_Start.m_Y <= p.m_Y && m_End.m_X > p.m_X && m_End.m_Y > p.m_Y;
public bool Contains(Point2D p) =>
m_Start.m_X <= p.m_X && m_Start.m_Y <= p.m_Y && m_End.m_X > p.m_X && m_End.m_Y > p.m_Y;
public bool Contains(IPoint2D p) => m_Start <= p && m_End > p;
public override string ToString() => $"({X}, {Y})+({Width}, {Height})";
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle2D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
namespace Server
{
[NoSort]
[Parsable]
[PropertyObject]
public struct Rectangle2D
{
private Point2D m_Start;
private Point2D m_End;
public Rectangle2D(IPoint2D start, IPoint2D end)
{
m_Start = new Point2D(start);
m_End = new Point2D(end);
}
public Rectangle2D(int x, int y, int width, int height)
{
m_Start = new Point2D(x, y);
m_End = new Point2D(x + width, y + height);
}
public void Set(int x, int y, int width, int height)
{
m_Start = new Point2D(x, y);
m_End = new Point2D(x + width, y + height);
}
public static Rectangle2D Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var x);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var y);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var w);
start = end;
end = value.IndexOf(')', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var h);
return new Rectangle2D(x, y, w, h);
}
[CommandProperty(AccessLevel.Counselor)]
public Point2D Start
{
get => m_Start;
set => m_Start = value;
}
[CommandProperty(AccessLevel.Counselor)]
public Point2D End
{
get => m_End;
set => m_End = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_Start.m_X;
set => m_Start.m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Start.m_Y;
set => m_Start.m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Width
{
get => m_End.m_X - m_Start.m_X;
set => m_End.m_X = m_Start.m_X + value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Height
{
get => m_End.m_Y - m_Start.m_Y;
set => m_End.m_Y = m_Start.m_Y + value;
}
public void MakeHold(Rectangle2D r)
{
if (r.m_Start.m_X < m_Start.m_X)
m_Start.m_X = r.m_Start.m_X;
if (r.m_Start.m_Y < m_Start.m_Y)
m_Start.m_Y = r.m_Start.m_Y;
if (r.m_End.m_X > m_End.m_X)
m_End.m_X = r.m_End.m_X;
if (r.m_End.m_Y > m_End.m_Y)
m_End.m_Y = r.m_End.m_Y;
}
public bool Contains(Point3D p) =>
m_Start.m_X <= p.m_X && m_Start.m_Y <= p.m_Y && m_End.m_X > p.m_X && m_End.m_Y > p.m_Y;
public bool Contains(Point2D p) =>
m_Start.m_X <= p.m_X && m_Start.m_Y <= p.m_Y && m_End.m_X > p.m_X && m_End.m_Y > p.m_Y;
public bool Contains(IPoint2D p) => m_Start <= p && m_End > p;
public override string ToString() => $"({X}, {Y})+({Width}, {Height})";
}
}

View file

@ -1,123 +1,123 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle3D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
namespace Server
{
[NoSort]
[PropertyObject]
public struct Rectangle3D
{
private Point3D m_Start;
private Point3D m_End;
public Rectangle3D(Point3D start, Point3D end)
{
m_Start = start;
m_End = end;
}
public Rectangle3D(int x, int y, int z, int width, int height, int depth)
{
m_Start = new Point3D(x, y, z);
m_End = new Point3D(x + width, y + height, z + depth);
}
[CommandProperty(AccessLevel.Counselor)]
public Point3D Start
{
get => m_Start;
set => m_Start = value;
}
[CommandProperty(AccessLevel.Counselor)]
public Point3D End
{
get => m_End;
set => m_End = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_Start.m_X;
set => m_Start.m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Start.m_Y;
set => m_Start.m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Z
{
get => m_Start.m_Z;
set => m_Start.m_Z = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Width => m_End.X - m_Start.X;
[CommandProperty(AccessLevel.Counselor)]
public int Height => m_End.Y - m_Start.Y;
[CommandProperty(AccessLevel.Counselor)]
public int Depth => m_End.Z - m_Start.Z;
public void MakeHold(Rectangle3D r)
{
if (r.m_Start.m_X < m_Start.m_X)
m_Start.m_X = r.m_Start.m_X;
if (r.m_Start.m_Y < m_Start.m_Y)
m_Start.m_Y = r.m_Start.m_Y;
if (r.m_Start.m_Z < m_Start.m_Z)
m_Start.m_Z = r.m_Start.m_Z;
if (r.m_End.m_X > m_End.m_X)
m_End.m_X = r.m_End.m_X;
if (r.m_End.m_Y > m_End.m_Y)
m_End.m_Y = r.m_End.m_Y;
if (r.m_End.m_Z < m_End.m_Z)
m_End.m_Z = r.m_End.m_Z;
}
public bool Contains(Point3D p) =>
p.m_X >= m_Start.m_X
&& p.m_X < m_End.m_X
&& p.m_Y >= m_Start.m_Y
&& p.m_Y < m_End.m_Y
&& p.m_Z >= m_Start.m_Z
&& p.m_Z < m_End.m_Z;
public bool Contains(IPoint3D p) =>
p.X >= m_Start.m_X
&& p.X < m_End.m_X
&& p.Y >= m_Start.m_Y
&& p.Y < m_End.m_Y
&& p.Z >= m_Start.m_Z
&& p.Z < m_End.m_Z;
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle3D.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
namespace Server
{
[NoSort]
[PropertyObject]
public struct Rectangle3D
{
private Point3D m_Start;
private Point3D m_End;
public Rectangle3D(Point3D start, Point3D end)
{
m_Start = start;
m_End = end;
}
public Rectangle3D(int x, int y, int z, int width, int height, int depth)
{
m_Start = new Point3D(x, y, z);
m_End = new Point3D(x + width, y + height, z + depth);
}
[CommandProperty(AccessLevel.Counselor)]
public Point3D Start
{
get => m_Start;
set => m_Start = value;
}
[CommandProperty(AccessLevel.Counselor)]
public Point3D End
{
get => m_End;
set => m_End = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_Start.m_X;
set => m_Start.m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Start.m_Y;
set => m_Start.m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Z
{
get => m_Start.m_Z;
set => m_Start.m_Z = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Width => m_End.X - m_Start.X;
[CommandProperty(AccessLevel.Counselor)]
public int Height => m_End.Y - m_Start.Y;
[CommandProperty(AccessLevel.Counselor)]
public int Depth => m_End.Z - m_Start.Z;
public void MakeHold(Rectangle3D r)
{
if (r.m_Start.m_X < m_Start.m_X)
m_Start.m_X = r.m_Start.m_X;
if (r.m_Start.m_Y < m_Start.m_Y)
m_Start.m_Y = r.m_Start.m_Y;
if (r.m_Start.m_Z < m_Start.m_Z)
m_Start.m_Z = r.m_Start.m_Z;
if (r.m_End.m_X > m_End.m_X)
m_End.m_X = r.m_End.m_X;
if (r.m_End.m_Y > m_End.m_Y)
m_End.m_Y = r.m_End.m_Y;
if (r.m_End.m_Z < m_End.m_Z)
m_End.m_Z = r.m_End.m_Z;
}
public bool Contains(Point3D p) =>
p.m_X >= m_Start.m_X
&& p.m_X < m_End.m_X
&& p.m_Y >= m_Start.m_Y
&& p.m_Y < m_End.m_Y
&& p.m_Z >= m_Start.m_Z
&& p.m_Z < m_End.m_Z;
public bool Contains(IPoint3D p) =>
p.X >= m_Start.m_X
&& p.X < m_End.m_X
&& p.Y >= m_Start.m_Y
&& p.Y < m_End.m_Y
&& p.Z >= m_Start.m_Z
&& p.Z < m_End.m_Z;
}
}

View file

@ -1,173 +1,174 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: WorldLocation.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
[Parsable]
public struct WorldLocation : IPoint3D, IComparable<WorldLocation>, IEquatable<object>, IEquatable<WorldLocation>, IEquatable<IEntity>
{
internal Point3D m_Loc;
internal Map m_Map;
public static readonly WorldLocation Zero = new WorldLocation(0, 0, 0, Map.Internal);
[CommandProperty(AccessLevel.Counselor)]
public Point3D Location
{
get => m_Loc;
set => m_Loc = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_Loc.m_X;
set => m_Loc.m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Loc.m_Y;
set => m_Loc.m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Z
{
get => m_Loc.m_Z;
set => m_Loc.m_Z = value;
}
[CommandProperty(AccessLevel.Counselor)]
public Map Map
{
get => m_Map;
set => m_Map = value;
}
public WorldLocation(IEntity e) : this(e.Location.X, e.Location.Y, e.Location.Z, e.Map)
{
}
public WorldLocation(IPoint2D p, Map map) : this(p.X, p.Y, 0, map)
{
}
public WorldLocation(int x, int y, Map map) : this(x, y, 0, map)
{
}
public WorldLocation(IPoint3D p, Map map) : this(p.X, p.Y, p.Z, map)
{
}
public WorldLocation(int x, int y, int z, Map map)
{
m_Loc.m_X = x;
m_Loc.m_Y = y;
m_Loc.m_Z = z;
m_Map = map;
}
public override string ToString() =>
$"({m_Loc.m_X}, {m_Loc.m_Y}, {m_Loc.m_Z}, {m_Map?.ToString() ?? "(-null-)"})";
public bool Equals(WorldLocation other) =>
m_Loc.Equals(other.m_Loc) && m_Map.MapID == other.m_Map.MapID;
public bool Equals(IEntity other) =>
!ReferenceEquals(other, null) && m_Loc == other.Location &&
m_Map.MapID == other.Map.MapID;
public override bool Equals(object obj) =>
obj is WorldLocation other && Equals(other);
public override int GetHashCode() => HashCode.Combine(m_Loc, m_Map);
public int CompareTo(WorldLocation other)
{
var locComparison = m_Loc.CompareTo(other.m_Loc);
if (locComparison != 0) return locComparison;
return Comparer<Map>.Default.Compare(m_Map, other.m_Map);
}
public static implicit operator Point3D(WorldLocation worldLocation) => worldLocation.Location;
public static bool operator ==(WorldLocation l, WorldLocation r) =>
l.m_Loc == r.m_Loc && l.m_Map == r.m_Map;
public static bool operator ==(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc == r.Location && l.m_Map == r.Map;
public static bool operator !=(WorldLocation l, WorldLocation r) => l.m_Loc != r.m_Loc && l.m_Map != r.m_Map;
public static bool operator !=(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc != r.Location && l.m_Map != r.Map;
public static bool operator >(WorldLocation l, WorldLocation r) => l.m_Loc > r.m_Loc && l.m_Map == r.m_Map;
public static bool operator >(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc > r.Location && l.m_Map == r.Map;
public static bool operator <(WorldLocation l, WorldLocation r) => l.m_Loc < r.m_Loc && l.m_Map == r.m_Map;
public static bool operator <(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc < r.Location && l.m_Map == r.Map;
public static bool operator >=(WorldLocation l, WorldLocation r) => l.m_Loc >= r.m_Loc && l.m_Map == r.m_Map;
public static bool operator >=(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc >= r.Location && l.m_Map == r.Map;
public static bool operator <=(WorldLocation l, WorldLocation r) => l.m_Loc <= r.m_Loc && l.m_Map == r.m_Map;
public static bool operator <=(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc <= r.Location && l.m_Map == r.Map;
public static WorldLocation Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int x);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int y);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out int z);
start = end;
end = value.IndexOf(')', start + 1);
var map = Map.Parse(value.Substring(start + 1, end - (start + 1)).Trim());
return new WorldLocation(x, y, z, map);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: WorldLocation.cs - Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
[Parsable]
public struct WorldLocation
: IPoint3D, IComparable<WorldLocation>, IEquatable<object>, IEquatable<WorldLocation>, IEquatable<IEntity>
{
internal Point3D m_Loc;
internal Map m_Map;
public static readonly WorldLocation Zero = new WorldLocation(0, 0, 0, Map.Internal);
[CommandProperty(AccessLevel.Counselor)]
public Point3D Location
{
get => m_Loc;
set => m_Loc = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int X
{
get => m_Loc.m_X;
set => m_Loc.m_X = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Y
{
get => m_Loc.m_Y;
set => m_Loc.m_Y = value;
}
[CommandProperty(AccessLevel.Counselor)]
public int Z
{
get => m_Loc.m_Z;
set => m_Loc.m_Z = value;
}
[CommandProperty(AccessLevel.Counselor)]
public Map Map
{
get => m_Map;
set => m_Map = value;
}
public WorldLocation(IEntity e) : this(e.Location.X, e.Location.Y, e.Location.Z, e.Map)
{
}
public WorldLocation(IPoint2D p, Map map) : this(p.X, p.Y, 0, map)
{
}
public WorldLocation(int x, int y, Map map) : this(x, y, 0, map)
{
}
public WorldLocation(IPoint3D p, Map map) : this(p.X, p.Y, p.Z, map)
{
}
public WorldLocation(int x, int y, int z, Map map)
{
m_Loc.m_X = x;
m_Loc.m_Y = y;
m_Loc.m_Z = z;
m_Map = map;
}
public override string ToString() =>
$"({m_Loc.m_X}, {m_Loc.m_Y}, {m_Loc.m_Z}, {m_Map?.ToString() ?? "(-null-)"})";
public bool Equals(WorldLocation other) =>
m_Loc.Equals(other.m_Loc) && m_Map.MapID == other.m_Map.MapID;
public bool Equals(IEntity other) =>
!ReferenceEquals(other, null) && m_Loc == other.Location &&
m_Map.MapID == other.Map.MapID;
public override bool Equals(object obj) =>
obj is WorldLocation other && Equals(other);
public override int GetHashCode() => HashCode.Combine(m_Loc, m_Map);
public int CompareTo(WorldLocation other)
{
var locComparison = m_Loc.CompareTo(other.m_Loc);
if (locComparison != 0) return locComparison;
return Comparer<Map>.Default.Compare(m_Map, other.m_Map);
}
public static implicit operator Point3D(WorldLocation worldLocation) => worldLocation.Location;
public static bool operator ==(WorldLocation l, WorldLocation r) =>
l.m_Loc == r.m_Loc && l.m_Map == r.m_Map;
public static bool operator ==(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc == r.Location && l.m_Map == r.Map;
public static bool operator !=(WorldLocation l, WorldLocation r) => l.m_Loc != r.m_Loc && l.m_Map != r.m_Map;
public static bool operator !=(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc != r.Location && l.m_Map != r.Map;
public static bool operator >(WorldLocation l, WorldLocation r) => l.m_Loc > r.m_Loc && l.m_Map == r.m_Map;
public static bool operator >(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc > r.Location && l.m_Map == r.Map;
public static bool operator <(WorldLocation l, WorldLocation r) => l.m_Loc < r.m_Loc && l.m_Map == r.m_Map;
public static bool operator <(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc < r.Location && l.m_Map == r.Map;
public static bool operator >=(WorldLocation l, WorldLocation r) => l.m_Loc >= r.m_Loc && l.m_Map == r.m_Map;
public static bool operator >=(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc >= r.Location && l.m_Map == r.Map;
public static bool operator <=(WorldLocation l, WorldLocation r) => l.m_Loc <= r.m_Loc && l.m_Map == r.m_Map;
public static bool operator <=(WorldLocation l, IEntity r) =>
!ReferenceEquals(r, null) && l.m_Loc <= r.Location && l.m_Map == r.Map;
public static WorldLocation Parse(string value)
{
var start = value.IndexOf('(');
var end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var x);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var y);
start = end;
end = value.IndexOf(',', start + 1);
Utility.ToInt32(value.Substring(start + 1, end - (start + 1)).Trim(), out var z);
start = end;
end = value.IndexOf(')', start + 1);
var map = Map.Parse(value.Substring(start + 1, end - (start + 1)).Trim());
return new WorldLocation(x, y, z, map);
}
}
}

View file

@ -1,108 +1,106 @@
/***************************************************************************
* Guild.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
using System.Linq;
namespace Server.Guilds
{
public enum GuildType
{
Regular,
Chaos,
Order
}
public abstract class BaseGuild : ISerializable
{
private readonly BufferWriter m_SaveBuffer;
public BufferWriter SaveBuffer => m_SaveBuffer;
private static Serial m_NextID = 1;
protected BaseGuild(uint id) // serialization ctor
{
Serial = id;
List.Add(Serial, this);
if (Serial + 1 > m_NextID)
m_NextID = Serial + 1;
m_SaveBuffer = new BufferWriter(true);
}
protected BaseGuild()
{
Serial = m_NextID++;
List.Add(Serial, this);
m_SaveBuffer = new BufferWriter(true);
}
[CommandProperty(AccessLevel.Counselor)]
public Serial Serial { get; }
public abstract string Abbreviation { get; set; }
public abstract string Name { get; set; }
public abstract GuildType Type { get; set; }
public abstract bool Disbanded { get; }
public static Dictionary<uint, BaseGuild> List { get; } = new Dictionary<uint, BaseGuild>();
public int TypeRef => 0;
public void Serialize()
{
SaveBuffer.Flush();
Serialize(SaveBuffer);
}
public abstract void Serialize(IGenericWriter writer);
public abstract void Deserialize(IGenericReader reader);
public abstract void OnDelete(Mobile mob);
public static BaseGuild Find(uint id)
{
List.TryGetValue(id, out var g);
return g;
}
public static BaseGuild FindByName(string name) => List.Values.FirstOrDefault(g => g.Name == name);
public static BaseGuild FindByAbbrev(string abbr) => List.Values.FirstOrDefault(g => g.Abbreviation == abbr);
public static List<BaseGuild> Search(string find)
{
var words = find.ToLower().Split(' ');
var results = new List<BaseGuild>();
foreach (var g in List.Values)
{
var name = g.Name.ToLower();
if (words.All(t => name.IndexOf(t) != -1))
results.Add(g);
}
return results;
}
public override string ToString() => $"0x{Serial:X} \"{Name} [{Abbreviation}]\"";
}
}
/***************************************************************************
* Guild.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System.Collections.Generic;
using System.Linq;
namespace Server.Guilds
{
public enum GuildType
{
Regular,
Chaos,
Order
}
public abstract class BaseGuild : ISerializable
{
private static Serial m_NextID = 1;
protected BaseGuild(uint id) // serialization ctor
{
Serial = id;
List.Add(Serial, this);
if (Serial + 1 > m_NextID)
m_NextID = Serial + 1;
SaveBuffer = new BufferWriter(true);
}
protected BaseGuild()
{
Serial = m_NextID++;
List.Add(Serial, this);
SaveBuffer = new BufferWriter(true);
}
public abstract string Abbreviation { get; set; }
public abstract string Name { get; set; }
public abstract GuildType Type { get; set; }
public abstract bool Disbanded { get; }
public static Dictionary<uint, BaseGuild> List { get; } = new Dictionary<uint, BaseGuild>();
public BufferWriter SaveBuffer { get; }
[CommandProperty(AccessLevel.Counselor)]
public Serial Serial { get; }
public int TypeRef => 0;
public void Serialize()
{
SaveBuffer.Flush();
Serialize(SaveBuffer);
}
public abstract void Serialize(IGenericWriter writer);
public abstract void Deserialize(IGenericReader reader);
public abstract void OnDelete(Mobile mob);
public static BaseGuild Find(uint id)
{
List.TryGetValue(id, out var g);
return g;
}
public static BaseGuild FindByName(string name) => List.Values.FirstOrDefault(g => g.Name == name);
public static BaseGuild FindByAbbrev(string abbr) => List.Values.FirstOrDefault(g => g.Abbreviation == abbr);
public static List<BaseGuild> Search(string find)
{
var words = find.ToLower().Split(' ');
var results = new List<BaseGuild>();
foreach (var g in List.Values)
{
var name = g.Name.ToLower();
if (words.All(t => name.IndexOf(t) != -1))
results.Add(g);
}
return results;
}
public override string ToString() => $"0x{Serial:X} \"{Name} [{Abbreviation}]\"";
}
}

View file

@ -1,291 +1,317 @@
/***************************************************************************
* Gump.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using Server.Network;
namespace Server.Gumps
{
public class Gump
{
private static uint m_NextSerial = 1;
private static readonly byte[] m_BeginLayout = StringToBuffer("{ ");
private static readonly byte[] m_EndLayout = StringToBuffer(" }");
private static readonly byte[] m_NoMove = StringToBuffer("{ nomove }");
private static readonly byte[] m_NoClose = StringToBuffer("{ noclose }");
private static readonly byte[] m_NoDispose = StringToBuffer("{ nodispose }");
private static readonly byte[] m_NoResize = StringToBuffer("{ noresize }");
public List<string> Strings { get; }
internal int m_TextEntries, m_Switches;
public Gump(int x, int y)
{
do
{
Serial = m_NextSerial++;
} while (Serial == 0); // standard client apparently doesn't send a gump response packet if serial == 0
X = x;
Y = y;
TypeID = GetTypeID(GetType());
Entries = new List<GumpEntry>();
Strings = new List<string>();
}
public int TypeID { get; }
public List<GumpEntry> Entries { get; }
public uint Serial { get; set; }
public int X { get; set; }
public int Y { get; set; }
public bool Disposable { get; set; } = true;
public bool Resizable { get; set; } = true;
public bool Draggable { get; set; } = true;
public bool Closable { get; set; } = true;
public static int GetTypeID(Type type) => type?.FullName?.GetHashCode() ?? -1;
public void AddPage(int page)
{
Add(new GumpPage(page));
}
public void AddAlphaRegion(int x, int y, int width, int height)
{
Add(new GumpAlphaRegion(x, y, width, height));
}
public void AddBackground(int x, int y, int width, int height, int gumpID)
{
Add(new GumpBackground(x, y, width, height, gumpID));
}
public void AddButton(int x, int y, int normalID, int pressedID, int buttonID,
GumpButtonType type = GumpButtonType.Reply, int param = 0)
{
Add(new GumpButton(x, y, normalID, pressedID, buttonID, type, param));
}
public void AddCheck(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
Add(new GumpCheck(x, y, inactiveID, activeID, initialState, switchID));
}
public void AddGroup(int group)
{
Add(new GumpGroup(group));
}
public void AddTooltip(int number, string args = null)
{
Add(new GumpTooltip(number, args));
}
public void AddHtml(int x, int y, int width, int height, string text, bool background = false, bool scrollbar = false)
{
Add(new GumpHtml(x, y, width, height, text, background, scrollbar));
}
public void AddHtmlLocalized(int x, int y, int width, int height, int number, bool background = false,
bool scrollbar = false)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, background, scrollbar));
}
public void AddHtmlLocalized(int x, int y, int width, int height, int number, int color, bool background = false,
bool scrollbar = false)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, color, background, scrollbar));
}
public void AddHtmlLocalized(int x, int y, int width, int height, int number, string args, int color,
bool background = false, bool scrollbar = false)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, args, color, background, scrollbar));
}
public void AddImage(int x, int y, int gumpID, int hue = 0)
{
Add(new GumpImage(x, y, gumpID, hue));
}
public void AddImageTiled(int x, int y, int width, int height, int gumpID)
{
Add(new GumpImageTiled(x, y, width, height, gumpID));
}
public void AddImageTiledButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type,
int param, int itemID, int hue, int width, int height, int localizedTooltip = -1)
{
Add(new GumpImageTileButton(x, y, normalID, pressedID, buttonID, type, param, itemID, hue, width, height,
localizedTooltip));
}
public void AddItem(int x, int y, int itemID, int hue = 0)
{
Add(new GumpItem(x, y, itemID, hue));
}
public void AddLabel(int x, int y, int hue, string text)
{
Add(new GumpLabel(x, y, hue, text));
}
public void AddLabelCropped(int x, int y, int width, int height, int hue, string text)
{
Add(new GumpLabelCropped(x, y, width, height, hue, text));
}
public void AddRadio(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
Add(new GumpRadio(x, y, inactiveID, activeID, initialState, switchID));
}
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText)
{
Add(new GumpTextEntry(x, y, width, height, hue, entryID, initialText));
}
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText, int size)
{
Add(new GumpTextEntryLimited(x, y, width, height, hue, entryID, initialText, size));
}
public void AddItemProperty(uint serial)
{
Add(new GumpItemProperty(serial));
}
public void AddSpriteImage(int x, int y, int gumpID, int width, int height, int sx, int sy)
{
Add(new GumpSpriteImage(x, y, gumpID, width, height, sx, sy));
}
public void AddECHandleInput()
{
Add(new GumpECHandleInput());
}
public void AddGumpIDOverride(int gumpID)
{
Add(new GumpMasterGump(gumpID));
}
public void Add(GumpEntry g)
{
if (g.Parent != this)
g.Parent = this;
else if (!Entries.Contains(g))
Entries.Add(g);
}
public void Remove(GumpEntry g)
{
if (g == null || !Entries.Contains(g))
return;
Entries.Remove(g);
g.Parent = null;
}
public int Intern(string value)
{
var indexOf = Strings.IndexOf(value);
if (indexOf >= 0) return indexOf;
Strings.Add(value);
return Strings.Count - 1;
}
public void SendTo(NetState state)
{
state.AddGump(this);
state.Send(Compile(state));
}
public static byte[] StringToBuffer(string str) => Encoding.ASCII.GetBytes(str);
public Packet Compile(NetState ns = null)
{
IGumpWriter disp;
if (ns?.Unpack == true)
disp = new DisplayGumpPacked(this);
else
disp = new DisplayGumpFast(this);
if (!Draggable)
disp.AppendLayout(m_NoMove);
if (!Closable)
disp.AppendLayout(m_NoClose);
if (!Disposable)
disp.AppendLayout(m_NoDispose);
if (!Resizable)
disp.AppendLayout(m_NoResize);
var count = Entries.Count;
for (var i = 0; i < count; ++i)
{
var e = Entries[i];
disp.AppendLayout(m_BeginLayout);
e.AppendTo(ns, disp);
disp.AppendLayout(m_EndLayout);
}
disp.WriteStrings(Strings);
disp.Flush();
m_TextEntries = disp.TextEntries;
m_Switches = disp.Switches;
return (Packet)disp;
}
public virtual void OnResponse(NetState sender, RelayInfo info)
{
}
public virtual void OnServerClose(NetState owner)
{
}
}
}
/***************************************************************************
* Gump.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using Server.Network;
namespace Server.Gumps
{
public class Gump
{
private static uint m_NextSerial = 1;
private static readonly byte[] m_BeginLayout = StringToBuffer("{ ");
private static readonly byte[] m_EndLayout = StringToBuffer(" }");
private static readonly byte[] m_NoMove = StringToBuffer("{ nomove }");
private static readonly byte[] m_NoClose = StringToBuffer("{ noclose }");
private static readonly byte[] m_NoDispose = StringToBuffer("{ nodispose }");
private static readonly byte[] m_NoResize = StringToBuffer("{ noresize }");
internal int m_TextEntries, m_Switches;
public Gump(int x, int y)
{
do
{
Serial = m_NextSerial++;
} while (Serial == 0); // standard client apparently doesn't send a gump response packet if serial == 0
X = x;
Y = y;
TypeID = GetTypeID(GetType());
Entries = new List<GumpEntry>();
Strings = new List<string>();
}
public List<string> Strings { get; }
public int TypeID { get; }
public List<GumpEntry> Entries { get; }
public uint Serial { get; set; }
public int X { get; set; }
public int Y { get; set; }
public bool Disposable { get; set; } = true;
public bool Resizable { get; set; } = true;
public bool Draggable { get; set; } = true;
public bool Closable { get; set; } = true;
public static int GetTypeID(Type type) => type?.FullName?.GetHashCode() ?? -1;
public void AddPage(int page)
{
Add(new GumpPage(page));
}
public void AddAlphaRegion(int x, int y, int width, int height)
{
Add(new GumpAlphaRegion(x, y, width, height));
}
public void AddBackground(int x, int y, int width, int height, int gumpID)
{
Add(new GumpBackground(x, y, width, height, gumpID));
}
public void AddButton(
int x, int y, int normalID, int pressedID, int buttonID,
GumpButtonType type = GumpButtonType.Reply, int param = 0
)
{
Add(new GumpButton(x, y, normalID, pressedID, buttonID, type, param));
}
public void AddCheck(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
Add(new GumpCheck(x, y, inactiveID, activeID, initialState, switchID));
}
public void AddGroup(int group)
{
Add(new GumpGroup(group));
}
public void AddTooltip(int number, string args = null)
{
Add(new GumpTooltip(number, args));
}
public void AddHtml(
int x, int y, int width, int height, string text, bool background = false, bool scrollbar = false
)
{
Add(new GumpHtml(x, y, width, height, text, background, scrollbar));
}
public void AddHtmlLocalized(
int x, int y, int width, int height, int number, bool background = false,
bool scrollbar = false
)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, background, scrollbar));
}
public void AddHtmlLocalized(
int x, int y, int width, int height, int number, int color, bool background = false,
bool scrollbar = false
)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, color, background, scrollbar));
}
public void AddHtmlLocalized(
int x, int y, int width, int height, int number, string args, int color,
bool background = false, bool scrollbar = false
)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, args, color, background, scrollbar));
}
public void AddImage(int x, int y, int gumpID, int hue = 0)
{
Add(new GumpImage(x, y, gumpID, hue));
}
public void AddImageTiled(int x, int y, int width, int height, int gumpID)
{
Add(new GumpImageTiled(x, y, width, height, gumpID));
}
public void AddImageTiledButton(
int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type,
int param, int itemID, int hue, int width, int height, int localizedTooltip = -1
)
{
Add(
new GumpImageTileButton(
x,
y,
normalID,
pressedID,
buttonID,
type,
param,
itemID,
hue,
width,
height,
localizedTooltip
)
);
}
public void AddItem(int x, int y, int itemID, int hue = 0)
{
Add(new GumpItem(x, y, itemID, hue));
}
public void AddLabel(int x, int y, int hue, string text)
{
Add(new GumpLabel(x, y, hue, text));
}
public void AddLabelCropped(int x, int y, int width, int height, int hue, string text)
{
Add(new GumpLabelCropped(x, y, width, height, hue, text));
}
public void AddRadio(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
Add(new GumpRadio(x, y, inactiveID, activeID, initialState, switchID));
}
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText)
{
Add(new GumpTextEntry(x, y, width, height, hue, entryID, initialText));
}
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText, int size)
{
Add(new GumpTextEntryLimited(x, y, width, height, hue, entryID, initialText, size));
}
public void AddItemProperty(uint serial)
{
Add(new GumpItemProperty(serial));
}
public void AddSpriteImage(int x, int y, int gumpID, int width, int height, int sx, int sy)
{
Add(new GumpSpriteImage(x, y, gumpID, width, height, sx, sy));
}
public void AddECHandleInput()
{
Add(new GumpECHandleInput());
}
public void AddGumpIDOverride(int gumpID)
{
Add(new GumpMasterGump(gumpID));
}
public void Add(GumpEntry g)
{
if (g.Parent != this)
g.Parent = this;
else if (!Entries.Contains(g))
Entries.Add(g);
}
public void Remove(GumpEntry g)
{
if (g == null || !Entries.Contains(g))
return;
Entries.Remove(g);
g.Parent = null;
}
public int Intern(string value)
{
var indexOf = Strings.IndexOf(value);
if (indexOf >= 0) return indexOf;
Strings.Add(value);
return Strings.Count - 1;
}
public void SendTo(NetState state)
{
state.AddGump(this);
state.Send(Compile(state));
}
public static byte[] StringToBuffer(string str) => Encoding.ASCII.GetBytes(str);
public Packet Compile(NetState ns = null)
{
IGumpWriter disp;
if (ns?.Unpack == true)
disp = new DisplayGumpPacked(this);
else
disp = new DisplayGumpFast(this);
if (!Draggable)
disp.AppendLayout(m_NoMove);
if (!Closable)
disp.AppendLayout(m_NoClose);
if (!Disposable)
disp.AppendLayout(m_NoDispose);
if (!Resizable)
disp.AppendLayout(m_NoResize);
var count = Entries.Count;
for (var i = 0; i < count; ++i)
{
var e = Entries[i];
disp.AppendLayout(m_BeginLayout);
e.AppendTo(ns, disp);
disp.AppendLayout(m_EndLayout);
}
disp.WriteStrings(Strings);
disp.Flush();
m_TextEntries = disp.TextEntries;
m_Switches = disp.Switches;
return (Packet)disp;
}
public virtual void OnResponse(NetState sender, RelayInfo info)
{
}
public virtual void OnServerClose(NetState owner)
{
}
}
}

View file

@ -1,56 +1,56 @@
/***************************************************************************
* GumpAlphaRegion.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpAlphaRegion : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("checkertrans");
public GumpAlphaRegion(int x, int y, int width, int height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public override string Compile(NetState ns) => $"{{ checkertrans {X} {Y} {Width} {Height} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
}
}
}
/***************************************************************************
* GumpAlphaRegion.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpAlphaRegion : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("checkertrans");
public GumpAlphaRegion(int x, int y, int width, int height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public override string Compile(NetState ns) => $"{{ checkertrans {X} {Y} {Width} {Height} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
}
}
}

View file

@ -1,60 +1,60 @@
/***************************************************************************
* GumpBackground.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpBackground : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("resizepic");
public GumpBackground(int x, int y, int width, int height, int gumpID)
{
X = x;
Y = y;
Width = width;
Height = height;
GumpID = gumpID;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int GumpID { get; set; }
public override string Compile(NetState ns) => $"{{ resizepic {X} {Y} {GumpID} {Width} {Height} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(GumpID);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
}
}
}
/***************************************************************************
* GumpBackground.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpBackground : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("resizepic");
public GumpBackground(int x, int y, int width, int height, int gumpID)
{
X = x;
Y = y;
Width = width;
Height = height;
GumpID = gumpID;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int GumpID { get; set; }
public override string Compile(NetState ns) => $"{{ resizepic {X} {Y} {GumpID} {Width} {Height} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(GumpID);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
}
}
}

View file

@ -1,76 +1,78 @@
/***************************************************************************
* GumpButton.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public enum GumpButtonType
{
Page = 0,
Reply = 1
}
public class GumpButton : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("button");
public GumpButton(int x, int y, int normalID, int pressedID, int buttonID,
GumpButtonType type = GumpButtonType.Reply, int param = 0)
{
X = x;
Y = y;
NormalID = normalID;
PressedID = pressedID;
ButtonID = buttonID;
Type = type;
Param = param;
}
public int X { get; set; }
public int Y { get; set; }
public int NormalID { get; set; }
public int PressedID { get; set; }
public int ButtonID { get; set; }
public GumpButtonType Type { get; set; }
public int Param { get; set; }
public override string Compile(NetState ns) =>
$"{{ button {X} {Y} {NormalID} {PressedID} {(int)Type} {Param} {ButtonID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(NormalID);
disp.AppendLayout(PressedID);
disp.AppendLayout((int)Type);
disp.AppendLayout(Param);
disp.AppendLayout(ButtonID);
}
}
}
/***************************************************************************
* GumpButton.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public enum GumpButtonType
{
Page = 0,
Reply = 1
}
public class GumpButton : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("button");
public GumpButton(
int x, int y, int normalID, int pressedID, int buttonID,
GumpButtonType type = GumpButtonType.Reply, int param = 0
)
{
X = x;
Y = y;
NormalID = normalID;
PressedID = pressedID;
ButtonID = buttonID;
Type = type;
Param = param;
}
public int X { get; set; }
public int Y { get; set; }
public int NormalID { get; set; }
public int PressedID { get; set; }
public int ButtonID { get; set; }
public GumpButtonType Type { get; set; }
public int Param { get; set; }
public override string Compile(NetState ns) =>
$"{{ button {X} {Y} {NormalID} {PressedID} {(int)Type} {Param} {ButtonID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(NormalID);
disp.AppendLayout(PressedID);
disp.AppendLayout((int)Type);
disp.AppendLayout(Param);
disp.AppendLayout(ButtonID);
}
}
}

View file

@ -1,67 +1,67 @@
/***************************************************************************
* GumpCheck.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpCheck : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("checkbox");
public GumpCheck(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
X = x;
Y = y;
InactiveID = inactiveID;
ActiveID = activeID;
InitialState = initialState;
SwitchID = switchID;
}
public int X { get; set; }
public int Y { get; set; }
public int InactiveID { get; set; }
public int ActiveID { get; set; }
public bool InitialState { get; set; }
public int SwitchID { get; set; }
public override string Compile(NetState ns) =>
$"{{ checkbox {X} {Y} {InactiveID} {ActiveID} {(InitialState ? 1 : 0)} {SwitchID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(InactiveID);
disp.AppendLayout(ActiveID);
disp.AppendLayout(InitialState);
disp.AppendLayout(SwitchID);
disp.Switches++;
}
}
}
/***************************************************************************
* GumpCheck.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpCheck : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("checkbox");
public GumpCheck(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
X = x;
Y = y;
InactiveID = inactiveID;
ActiveID = activeID;
InitialState = initialState;
SwitchID = switchID;
}
public int X { get; set; }
public int Y { get; set; }
public int InactiveID { get; set; }
public int ActiveID { get; set; }
public bool InitialState { get; set; }
public int SwitchID { get; set; }
public override string Compile(NetState ns) =>
$"{{ checkbox {X} {Y} {InactiveID} {ActiveID} {(InitialState ? 1 : 0)} {SwitchID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(InactiveID);
disp.AppendLayout(ActiveID);
disp.AppendLayout(InitialState);
disp.AppendLayout(SwitchID);
disp.Switches++;
}
}
}

View file

@ -1,37 +1,36 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpECHandleInput.cs *
* Created: 2020/04/24 - Updated: 2020/04/24 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpECHandleInput : GumpEntry
{
public override string Compile(NetState ns) => "{ echandleinput }";
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("echandleinput");
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpECHandleInput.cs *
* Created: 2020/04/24 - Updated: 2020/04/24 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpECHandleInput : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("echandleinput");
public override string Compile(NetState ns) => "{ echandleinput }";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
}
}
}

View file

@ -1,48 +1,48 @@
/***************************************************************************
* GumpEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public abstract class GumpEntry
{
private Gump m_Parent;
public Gump Parent
{
get => m_Parent;
set
{
if (m_Parent != value)
{
m_Parent?.Remove(this);
m_Parent = value;
m_Parent?.Add(this);
}
}
}
public abstract string Compile(NetState ns);
public abstract void AppendTo(NetState ns, IGumpWriter disp);
}
}
/***************************************************************************
* GumpEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public abstract class GumpEntry
{
private Gump m_Parent;
public Gump Parent
{
get => m_Parent;
set
{
if (m_Parent != value)
{
m_Parent?.Remove(this);
m_Parent = value;
m_Parent?.Add(this);
}
}
}
public abstract string Compile(NetState ns);
public abstract void AppendTo(NetState ns, IGumpWriter disp);
}
}

View file

@ -1,41 +1,41 @@
/***************************************************************************
* GumpGroup.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpGroup : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("group");
public GumpGroup(int group) => Group = group;
public int Group { get; set; }
public override string Compile(NetState ns) => $"{{ group {Group} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Group);
}
}
}
/***************************************************************************
* GumpGroup.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpGroup : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("group");
public GumpGroup(int group) => Group = group;
public int Group { get; set; }
public override string Compile(NetState ns) => $"{{ group {Group} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Group);
}
}
}

View file

@ -1,69 +1,69 @@
/***************************************************************************
* GumpHtml.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpHtml : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("htmlgump");
public GumpHtml(int x, int y, int width, int height, string text, bool background, bool scrollbar)
{
X = x;
Y = y;
Width = width;
Height = height;
Text = text;
Background = background;
Scrollbar = scrollbar;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Text { get; set; }
public bool Background { get; set; }
public bool Scrollbar { get; set; }
public override string Compile(NetState ns) =>
$"{{ htmlgump {X} {Y} {Width} {Height} {Parent.Intern(Text)} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Parent.Intern(Text));
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
}
}
}
/***************************************************************************
* GumpHtml.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpHtml : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("htmlgump");
public GumpHtml(int x, int y, int width, int height, string text, bool background, bool scrollbar)
{
X = x;
Y = y;
Width = width;
Height = height;
Text = text;
Background = background;
Scrollbar = scrollbar;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Text { get; set; }
public bool Background { get; set; }
public bool Scrollbar { get; set; }
public override string Compile(NetState ns) =>
$"{{ htmlgump {X} {Y} {Width} {Height} {Parent.Intern(Text)} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Parent.Intern(Text));
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
}
}
}

View file

@ -1,172 +1,178 @@
/***************************************************************************
* GumpHtmlLocalized.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public enum GumpHtmlLocalizedType
{
Plain,
Color,
Args
}
public class GumpHtmlLocalized : GumpEntry
{
private static readonly byte[] m_LayoutNamePlain = Gump.StringToBuffer("xmfhtmlgump");
private static readonly byte[] m_LayoutNameColor = Gump.StringToBuffer("xmfhtmlgumpcolor");
private static readonly byte[] m_LayoutNameArgs = Gump.StringToBuffer("xmfhtmltok");
public GumpHtmlLocalized(int x, int y, int width, int height, int number,
bool background = false, bool scrollbar = false)
{
X = x;
Y = y;
Width = width;
Height = height;
Number = number;
Background = background;
Scrollbar = scrollbar;
Type = GumpHtmlLocalizedType.Plain;
}
public GumpHtmlLocalized(int x, int y, int width, int height, int number, int color,
bool background = false, bool scrollbar = false)
{
X = x;
Y = y;
Width = width;
Height = height;
Number = number;
Color = color;
Background = background;
Scrollbar = scrollbar;
Type = GumpHtmlLocalizedType.Color;
}
public GumpHtmlLocalized(int x, int y, int width, int height, int number, string args, int color,
bool background = false, bool scrollbar = false)
{
// Are multiple arguments unsupported? And what about non ASCII arguments?
X = x;
Y = y;
Width = width;
Height = height;
Number = number;
Args = args;
Color = color;
Background = background;
Scrollbar = scrollbar;
Type = GumpHtmlLocalizedType.Args;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Number { get; set; }
public string Args { get; set; }
public int Color { get; set; }
public bool Background { get; set; }
public bool Scrollbar { get; set; }
public GumpHtmlLocalizedType Type { get; set; }
public override string Compile(NetState ns)
{
return Type switch
{
GumpHtmlLocalizedType.Plain =>
$"{{ xmfhtmlgump {X} {Y} {Width} {Height} {Number} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} }}",
GumpHtmlLocalizedType.Color =>
$"{{ xmfhtmlgumpcolor {X} {Y} {Width} {Height} {Number} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} {Color} }}",
_ =>
$"{{ xmfhtmltok {X} {Y} {Width} {Height} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} {Color} {Number} @{Args}@ }}"
};
}
public override void AppendTo(NetState ns, IGumpWriter disp)
{
switch (Type)
{
case GumpHtmlLocalizedType.Plain:
{
disp.AppendLayout(m_LayoutNamePlain);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Number);
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
break;
}
case GumpHtmlLocalizedType.Color:
{
disp.AppendLayout(m_LayoutNameColor);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Number);
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
disp.AppendLayout(Color);
break;
}
case GumpHtmlLocalizedType.Args:
{
disp.AppendLayout(m_LayoutNameArgs);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
disp.AppendLayout(Color);
disp.AppendLayout(Number);
disp.AppendLayout(Args);
break;
}
}
}
}
}
/***************************************************************************
* GumpHtmlLocalized.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public enum GumpHtmlLocalizedType
{
Plain,
Color,
Args
}
public class GumpHtmlLocalized : GumpEntry
{
private static readonly byte[] m_LayoutNamePlain = Gump.StringToBuffer("xmfhtmlgump");
private static readonly byte[] m_LayoutNameColor = Gump.StringToBuffer("xmfhtmlgumpcolor");
private static readonly byte[] m_LayoutNameArgs = Gump.StringToBuffer("xmfhtmltok");
public GumpHtmlLocalized(
int x, int y, int width, int height, int number,
bool background = false, bool scrollbar = false
)
{
X = x;
Y = y;
Width = width;
Height = height;
Number = number;
Background = background;
Scrollbar = scrollbar;
Type = GumpHtmlLocalizedType.Plain;
}
public GumpHtmlLocalized(
int x, int y, int width, int height, int number, int color,
bool background = false, bool scrollbar = false
)
{
X = x;
Y = y;
Width = width;
Height = height;
Number = number;
Color = color;
Background = background;
Scrollbar = scrollbar;
Type = GumpHtmlLocalizedType.Color;
}
public GumpHtmlLocalized(
int x, int y, int width, int height, int number, string args, int color,
bool background = false, bool scrollbar = false
)
{
// Are multiple arguments unsupported? And what about non ASCII arguments?
X = x;
Y = y;
Width = width;
Height = height;
Number = number;
Args = args;
Color = color;
Background = background;
Scrollbar = scrollbar;
Type = GumpHtmlLocalizedType.Args;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Number { get; set; }
public string Args { get; set; }
public int Color { get; set; }
public bool Background { get; set; }
public bool Scrollbar { get; set; }
public GumpHtmlLocalizedType Type { get; set; }
public override string Compile(NetState ns)
{
return Type switch
{
GumpHtmlLocalizedType.Plain =>
$"{{ xmfhtmlgump {X} {Y} {Width} {Height} {Number} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} }}",
GumpHtmlLocalizedType.Color =>
$"{{ xmfhtmlgumpcolor {X} {Y} {Width} {Height} {Number} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} {Color} }}",
_ =>
$"{{ xmfhtmltok {X} {Y} {Width} {Height} {(Background ? 1 : 0)} {(Scrollbar ? 1 : 0)} {Color} {Number} @{Args}@ }}"
};
}
public override void AppendTo(NetState ns, IGumpWriter disp)
{
switch (Type)
{
case GumpHtmlLocalizedType.Plain:
{
disp.AppendLayout(m_LayoutNamePlain);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Number);
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
break;
}
case GumpHtmlLocalizedType.Color:
{
disp.AppendLayout(m_LayoutNameColor);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Number);
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
disp.AppendLayout(Color);
break;
}
case GumpHtmlLocalizedType.Args:
{
disp.AppendLayout(m_LayoutNameArgs);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Background);
disp.AppendLayout(Scrollbar);
disp.AppendLayout(Color);
disp.AppendLayout(Number);
disp.AppendLayout(Args);
break;
}
}
}
}
}

View file

@ -1,63 +1,63 @@
/***************************************************************************
* GumpImage.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpImage : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("gumppic");
private static readonly byte[] m_HueEquals = Gump.StringToBuffer(" hue=");
public GumpImage(int x, int y, int gumpID, int hue = 0)
{
X = x;
Y = y;
GumpID = gumpID;
Hue = hue;
}
public int X { get; set; }
public int Y { get; set; }
public int GumpID { get; set; }
public int Hue { get; set; }
public override string Compile(NetState ns) =>
Hue == 0 ? $"{{ gumppic {X} {Y} {GumpID} }}" : $"{{ gumppic {X} {Y} {GumpID} hue={Hue} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(GumpID);
if (Hue != 0)
{
disp.AppendLayout(m_HueEquals);
disp.AppendLayoutNS(Hue);
}
}
}
}
/***************************************************************************
* GumpImage.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpImage : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("gumppic");
private static readonly byte[] m_HueEquals = Gump.StringToBuffer(" hue=");
public GumpImage(int x, int y, int gumpID, int hue = 0)
{
X = x;
Y = y;
GumpID = gumpID;
Hue = hue;
}
public int X { get; set; }
public int Y { get; set; }
public int GumpID { get; set; }
public int Hue { get; set; }
public override string Compile(NetState ns) =>
Hue == 0 ? $"{{ gumppic {X} {Y} {GumpID} }}" : $"{{ gumppic {X} {Y} {GumpID} hue={Hue} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(GumpID);
if (Hue != 0)
{
disp.AppendLayout(m_HueEquals);
disp.AppendLayoutNS(Hue);
}
}
}
}

View file

@ -1,121 +1,123 @@
/***************************************************************************
* GumpImageTileButton.cs
* -------------------
* begin : April 26, 2005
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpImageTileButton : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("buttontileart");
private static readonly byte[] m_LayoutTooltip = Gump.StringToBuffer(" }{ tooltip");
private GumpButtonType m_Type;
// Note, on OSI, The tooltip supports ONLY clilocs as far as I can figure out, and the tooltip ONLY works after the buttonTileArt (as far as I can tell from testing)
public GumpImageTileButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param,
int itemID, int hue, int width, int height, int localizedTooltip = -1)
{
X = x;
Y = y;
NormalID = normalID;
PressedID = pressedID;
ButtonID = buttonID;
m_Type = type;
Param = param;
ItemID = itemID;
Hue = hue;
Width = width;
Height = height;
LocalizedTooltip = localizedTooltip;
}
public int X { get; set; }
public int Y { get; set; }
public int NormalID { get; set; }
public int PressedID { get; set; }
public int ButtonID { get; set; }
public GumpButtonType Type
{
get => m_Type;
set
{
if (m_Type != value)
{
m_Type = value;
var parent = Parent;
}
}
}
public int Param { get; set; }
public int ItemID { get; set; }
public int Hue { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int LocalizedTooltip { get; set; }
public override string Compile(NetState ns)
{
if (LocalizedTooltip > 0)
return
$"{{ buttontileart {X} {Y} {NormalID} {PressedID} {(int)m_Type} {Param} {ButtonID} {ItemID} {Hue} {Width} {Height} }}{{ tooltip {LocalizedTooltip} }}";
return
$"{{ buttontileart {X} {Y} {NormalID} {PressedID} {(int)m_Type} {Param} {ButtonID} {ItemID} {Hue} {Width} {Height} }}";
}
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(NormalID);
disp.AppendLayout(PressedID);
disp.AppendLayout((int)m_Type);
disp.AppendLayout(Param);
disp.AppendLayout(ButtonID);
disp.AppendLayout(ItemID);
disp.AppendLayout(Hue);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
if (LocalizedTooltip > 0)
{
disp.AppendLayout(m_LayoutTooltip);
disp.AppendLayout(LocalizedTooltip);
}
}
}
}
/***************************************************************************
* GumpImageTileButton.cs
* -------------------
* begin : April 26, 2005
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpImageTileButton : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("buttontileart");
private static readonly byte[] m_LayoutTooltip = Gump.StringToBuffer(" }{ tooltip");
private GumpButtonType m_Type;
// Note, on OSI, The tooltip supports ONLY clilocs as far as I can figure out, and the tooltip ONLY works after the buttonTileArt (as far as I can tell from testing)
public GumpImageTileButton(
int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param,
int itemID, int hue, int width, int height, int localizedTooltip = -1
)
{
X = x;
Y = y;
NormalID = normalID;
PressedID = pressedID;
ButtonID = buttonID;
m_Type = type;
Param = param;
ItemID = itemID;
Hue = hue;
Width = width;
Height = height;
LocalizedTooltip = localizedTooltip;
}
public int X { get; set; }
public int Y { get; set; }
public int NormalID { get; set; }
public int PressedID { get; set; }
public int ButtonID { get; set; }
public GumpButtonType Type
{
get => m_Type;
set
{
if (m_Type != value)
{
m_Type = value;
var parent = Parent;
}
}
}
public int Param { get; set; }
public int ItemID { get; set; }
public int Hue { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int LocalizedTooltip { get; set; }
public override string Compile(NetState ns)
{
if (LocalizedTooltip > 0)
return
$"{{ buttontileart {X} {Y} {NormalID} {PressedID} {(int)m_Type} {Param} {ButtonID} {ItemID} {Hue} {Width} {Height} }}{{ tooltip {LocalizedTooltip} }}";
return
$"{{ buttontileart {X} {Y} {NormalID} {PressedID} {(int)m_Type} {Param} {ButtonID} {ItemID} {Hue} {Width} {Height} }}";
}
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(NormalID);
disp.AppendLayout(PressedID);
disp.AppendLayout((int)m_Type);
disp.AppendLayout(Param);
disp.AppendLayout(ButtonID);
disp.AppendLayout(ItemID);
disp.AppendLayout(Hue);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
if (LocalizedTooltip > 0)
{
disp.AppendLayout(m_LayoutTooltip);
disp.AppendLayout(LocalizedTooltip);
}
}
}
}

View file

@ -1,60 +1,60 @@
/***************************************************************************
* GumpImageTiled.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpImageTiled : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("gumppictiled");
public GumpImageTiled(int x, int y, int width, int height, int gumpID)
{
X = x;
Y = y;
Width = width;
Height = height;
GumpID = gumpID;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int GumpID { get; set; }
public override string Compile(NetState ns) => $"{{ gumppictiled {X} {Y} {Width} {Height} {GumpID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(GumpID);
}
}
}
/***************************************************************************
* GumpImageTiled.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpImageTiled : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("gumppictiled");
public GumpImageTiled(int x, int y, int width, int height, int gumpID)
{
X = x;
Y = y;
Width = width;
Height = height;
GumpID = gumpID;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int GumpID { get; set; }
public override string Compile(NetState ns) => $"{{ gumppictiled {X} {Y} {Width} {Height} {GumpID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(GumpID);
}
}
}

View file

@ -1,60 +1,60 @@
/***************************************************************************
* GumpItem.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpItem : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("tilepic");
private static readonly byte[] m_LayoutNameHue = Gump.StringToBuffer("tilepichue");
public GumpItem(int x, int y, int itemID, int hue = 0)
{
X = x;
Y = y;
ItemID = itemID;
Hue = hue;
}
public int X { get; set; }
public int Y { get; set; }
public int ItemID { get; set; }
public int Hue { get; set; }
public override string Compile(NetState ns) =>
Hue == 0 ? $"{{ tilepic {X} {Y} {ItemID} }}" : $"{{ tilepichue {X} {Y} {ItemID} {Hue} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(Hue == 0 ? m_LayoutName : m_LayoutNameHue);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(ItemID);
if (Hue != 0)
disp.AppendLayout(Hue);
}
}
}
/***************************************************************************
* GumpItem.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpItem : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("tilepic");
private static readonly byte[] m_LayoutNameHue = Gump.StringToBuffer("tilepichue");
public GumpItem(int x, int y, int itemID, int hue = 0)
{
X = x;
Y = y;
ItemID = itemID;
Hue = hue;
}
public int X { get; set; }
public int Y { get; set; }
public int ItemID { get; set; }
public int Hue { get; set; }
public override string Compile(NetState ns) =>
Hue == 0 ? $"{{ tilepic {X} {Y} {ItemID} }}" : $"{{ tilepichue {X} {Y} {ItemID} {Hue} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(Hue == 0 ? m_LayoutName : m_LayoutNameHue);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(ItemID);
if (Hue != 0)
disp.AppendLayout(Hue);
}
}
}

View file

@ -1,41 +1,41 @@
/***************************************************************************
* GumpItemProperty.cs
* -------------------
* begin : May 26, 2013
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpItemProperty : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("itemproperty");
public GumpItemProperty(uint serial) => Serial = serial;
public uint Serial { get; set; }
public override string Compile(NetState ns) => $"{{ itemproperty {Serial} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Serial);
}
}
}
/***************************************************************************
* GumpItemProperty.cs
* -------------------
* begin : May 26, 2013
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpItemProperty : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("itemproperty");
public GumpItemProperty(uint serial) => Serial = serial;
public uint Serial { get; set; }
public override string Compile(NetState ns) => $"{{ itemproperty {Serial} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Serial);
}
}
}

View file

@ -1,56 +1,56 @@
/***************************************************************************
* GumpLabel.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpLabel : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("text");
public GumpLabel(int x, int y, int hue, string text)
{
X = x;
Y = y;
Hue = hue;
Text = text;
}
public int X { get; set; }
public int Y { get; set; }
public int Hue { get; set; }
public string Text { get; set; }
public override string Compile(NetState ns) => $"{{ text {X} {Y} {Hue} {Parent.Intern(Text)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Hue);
disp.AppendLayout(Parent.Intern(Text));
}
}
}
/***************************************************************************
* GumpLabel.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpLabel : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("text");
public GumpLabel(int x, int y, int hue, string text)
{
X = x;
Y = y;
Hue = hue;
Text = text;
}
public int X { get; set; }
public int Y { get; set; }
public int Hue { get; set; }
public string Text { get; set; }
public override string Compile(NetState ns) => $"{{ text {X} {Y} {Hue} {Parent.Intern(Text)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Hue);
disp.AppendLayout(Parent.Intern(Text));
}
}
}

View file

@ -1,65 +1,65 @@
/***************************************************************************
* GumpLabelCropped.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpLabelCropped : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("croppedtext");
public GumpLabelCropped(int x, int y, int width, int height, int hue, string text)
{
X = x;
Y = y;
Width = width;
Height = height;
Hue = hue;
Text = text;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Hue { get; set; }
public string Text { get; set; }
public override string Compile(NetState ns) =>
$"{{ croppedtext {X} {Y} {Width} {Height} {Hue} {Parent.Intern(Text)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Hue);
disp.AppendLayout(Parent.Intern(Text));
}
}
}
/***************************************************************************
* GumpLabelCropped.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpLabelCropped : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("croppedtext");
public GumpLabelCropped(int x, int y, int width, int height, int hue, string text)
{
X = x;
Y = y;
Width = width;
Height = height;
Hue = hue;
Text = text;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Hue { get; set; }
public string Text { get; set; }
public override string Compile(NetState ns) =>
$"{{ croppedtext {X} {Y} {Width} {Height} {Hue} {Parent.Intern(Text)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Hue);
disp.AppendLayout(Parent.Intern(Text));
}
}
}

View file

@ -1,42 +1,42 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpMasterGump.cs *
* Created: 2020/04/24 - Updated: 2020/04/24 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpMasterGump : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("mastergump");
public GumpMasterGump(int gumpID) => GumpID = gumpID;
public int GumpID { get; set; }
public override string Compile(NetState ns) => $"{{ mastergump {GumpID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(GumpID);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpMasterGump.cs *
* Created: 2020/04/24 - Updated: 2020/04/24 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpMasterGump : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("mastergump");
public GumpMasterGump(int gumpID) => GumpID = gumpID;
public int GumpID { get; set; }
public override string Compile(NetState ns) => $"{{ mastergump {GumpID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(GumpID);
}
}
}

View file

@ -1,41 +1,41 @@
/***************************************************************************
* GumpPage.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpPage : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("page");
public GumpPage(int page) => Page = page;
public int Page { get; set; }
public override string Compile(NetState ns) => $"{{ page {Page} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Page);
}
}
}
/***************************************************************************
* GumpPage.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpPage : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("page");
public GumpPage(int page) => Page = page;
public int Page { get; set; }
public override string Compile(NetState ns) => $"{{ page {Page} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Page);
}
}
}

View file

@ -1,67 +1,67 @@
/***************************************************************************
* GumpRadio.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpRadio : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("radio");
public GumpRadio(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
X = x;
Y = y;
InactiveID = inactiveID;
ActiveID = activeID;
InitialState = initialState;
SwitchID = switchID;
}
public int X { get; set; }
public int Y { get; set; }
public int InactiveID { get; set; }
public int ActiveID { get; set; }
public bool InitialState { get; set; }
public int SwitchID { get; set; }
public override string Compile(NetState ns) =>
$"{{ radio {X} {Y} {InactiveID} {ActiveID} {(InitialState ? 1 : 0)} {SwitchID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(InactiveID);
disp.AppendLayout(ActiveID);
disp.AppendLayout(InitialState);
disp.AppendLayout(SwitchID);
disp.Switches++;
}
}
}
/***************************************************************************
* GumpRadio.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpRadio : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("radio");
public GumpRadio(int x, int y, int inactiveID, int activeID, bool initialState, int switchID)
{
X = x;
Y = y;
InactiveID = inactiveID;
ActiveID = activeID;
InitialState = initialState;
SwitchID = switchID;
}
public int X { get; set; }
public int Y { get; set; }
public int InactiveID { get; set; }
public int ActiveID { get; set; }
public bool InitialState { get; set; }
public int SwitchID { get; set; }
public override string Compile(NetState ns) =>
$"{{ radio {X} {Y} {InactiveID} {ActiveID} {(InitialState ? 1 : 0)} {SwitchID} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(InactiveID);
disp.AppendLayout(ActiveID);
disp.AppendLayout(InitialState);
disp.AppendLayout(SwitchID);
disp.Switches++;
}
}
}

View file

@ -1,48 +1,48 @@
using Server.Network;
namespace Server.Gumps
{
public class GumpSpriteImage : GumpEntry
{
public GumpSpriteImage(int x, int y, int gumpID, int width, int height, int sx, int sy)
{
X = x;
Y = y;
GumpID = gumpID;
Width = width;
Height = height;
SX = sx;
SY = sy;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int GumpID { get; set; }
public int SX { get; set; }
public int SY { get; set; }
public override string Compile(NetState ns) => $"{{ picinpic {X} {Y} {GumpID} {Width} {Height} {SX} {SY} }}";
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("picinpic");
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(GumpID);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(SX);
disp.AppendLayout(SY);
}
}
}
using Server.Network;
namespace Server.Gumps
{
public class GumpSpriteImage : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("picinpic");
public GumpSpriteImage(int x, int y, int gumpID, int width, int height, int sx, int sy)
{
X = x;
Y = y;
GumpID = gumpID;
Width = width;
Height = height;
SX = sx;
SY = sy;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int GumpID { get; set; }
public int SX { get; set; }
public int SY { get; set; }
public override string Compile(NetState ns) => $"{{ picinpic {X} {Y} {GumpID} {Width} {Height} {SX} {SY} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(GumpID);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(SX);
disp.AppendLayout(SY);
}
}
}

View file

@ -1,71 +1,71 @@
/***************************************************************************
* GumpTextEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpTextEntry : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("textentry");
public GumpTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText)
{
X = x;
Y = y;
Width = width;
Height = height;
Hue = hue;
EntryID = entryID;
InitialText = initialText;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Hue { get; set; }
public int EntryID { get; set; }
public string InitialText { get; set; }
public override string Compile(NetState ns) =>
$"{{ textentry {X} {Y} {Width} {Height} {Hue} {EntryID} {Parent.Intern(InitialText)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Hue);
disp.AppendLayout(EntryID);
disp.AppendLayout(Parent.Intern(InitialText));
disp.TextEntries++;
}
}
}
/***************************************************************************
* GumpTextEntry.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpTextEntry : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("textentry");
public GumpTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText)
{
X = x;
Y = y;
Width = width;
Height = height;
Hue = hue;
EntryID = entryID;
InitialText = initialText;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Hue { get; set; }
public int EntryID { get; set; }
public string InitialText { get; set; }
public override string Compile(NetState ns) =>
$"{{ textentry {X} {Y} {Width} {Height} {Hue} {EntryID} {Parent.Intern(InitialText)} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Hue);
disp.AppendLayout(EntryID);
disp.AppendLayout(Parent.Intern(InitialText));
disp.TextEntries++;
}
}
}

View file

@ -1,75 +1,77 @@
/***************************************************************************
* GumpTextEntryLimited.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpTextEntryLimited : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("textentrylimited");
public GumpTextEntryLimited(int x, int y, int width, int height, int hue, int entryID, string initialText, int size = 0)
{
X = x;
Y = y;
Width = width;
Height = height;
Hue = hue;
EntryID = entryID;
InitialText = initialText;
Size = size;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Hue { get; set; }
public int EntryID { get; set; }
public string InitialText { get; set; }
public int Size { get; set; }
public override string Compile(NetState ns) =>
$"{{ textentrylimited {X} {Y} {Width} {Height} {Hue} {EntryID} {Parent.Intern(InitialText)} {Size} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Hue);
disp.AppendLayout(EntryID);
disp.AppendLayout(Parent.Intern(InitialText));
disp.AppendLayout(Size);
disp.TextEntries++;
}
}
}
/***************************************************************************
* GumpTextEntryLimited.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpTextEntryLimited : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("textentrylimited");
public GumpTextEntryLimited(
int x, int y, int width, int height, int hue, int entryID, string initialText, int size = 0
)
{
X = x;
Y = y;
Width = width;
Height = height;
Hue = hue;
EntryID = entryID;
InitialText = initialText;
Size = size;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Hue { get; set; }
public int EntryID { get; set; }
public string InitialText { get; set; }
public int Size { get; set; }
public override string Compile(NetState ns) =>
$"{{ textentrylimited {X} {Y} {Width} {Height} {Hue} {EntryID} {Parent.Intern(InitialText)} {Size} }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(X);
disp.AppendLayout(Y);
disp.AppendLayout(Width);
disp.AppendLayout(Height);
disp.AppendLayout(Hue);
disp.AppendLayout(EntryID);
disp.AppendLayout(Parent.Intern(InitialText));
disp.AppendLayout(Size);
disp.TextEntries++;
}
}
}

View file

@ -1,48 +1,48 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpTooltip.cs - Created: 2020/04/24 - Updated: 2020/04/24 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpTooltip : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("tooltip");
public GumpTooltip(int number, string args)
{
Number = number;
Args = args;
}
public int Number { get; set; }
public string Args { get; set; }
public override string Compile(NetState ns) => $"{{ tooltip {Number} @{Args}@ }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Number);
disp.AppendLayout(Args);
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpTooltip.cs - Created: 2020/04/24 - Updated: 2020/04/24 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using Server.Network;
namespace Server.Gumps
{
public class GumpTooltip : GumpEntry
{
private static readonly byte[] m_LayoutName = Gump.StringToBuffer("tooltip");
public GumpTooltip(int number, string args)
{
Number = number;
Args = args;
}
public int Number { get; set; }
public string Args { get; set; }
public override string Compile(NetState ns) => $"{{ tooltip {Number} @{Args}@ }}";
public override void AppendTo(NetState ns, IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(Number);
disp.AppendLayout(Args);
}
}
}

View file

@ -1,69 +1,69 @@
/***************************************************************************
* RelayInfo.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server.Gumps
{
public class TextRelay
{
public TextRelay(int entryID, string text)
{
EntryID = entryID;
Text = text;
}
public int EntryID { get; }
public string Text { get; }
}
public class RelayInfo
{
public RelayInfo(int buttonID, int[] switches, TextRelay[] textEntries)
{
ButtonID = buttonID;
Switches = switches;
TextEntries = textEntries;
}
public int ButtonID { get; }
public int[] Switches { get; }
public TextRelay[] TextEntries { get; }
public bool IsSwitched(int switchID)
{
for (var i = 0; i < Switches.Length; ++i)
if (Switches[i] == switchID)
return true;
return false;
}
public TextRelay GetTextEntry(int entryID)
{
for (var i = 0; i < TextEntries.Length; ++i)
if (TextEntries[i].EntryID == entryID)
return TextEntries[i];
return null;
}
}
}
/***************************************************************************
* RelayInfo.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
namespace Server.Gumps
{
public class TextRelay
{
public TextRelay(int entryID, string text)
{
EntryID = entryID;
Text = text;
}
public int EntryID { get; }
public string Text { get; }
}
public class RelayInfo
{
public RelayInfo(int buttonID, int[] switches, TextRelay[] textEntries)
{
ButtonID = buttonID;
Switches = switches;
TextEntries = textEntries;
}
public int ButtonID { get; }
public int[] Switches { get; }
public TextRelay[] TextEntries { get; }
public bool IsSwitched(int switchID)
{
for (var i = 0; i < Switches.Length; ++i)
if (Switches[i] == switchID)
return true;
return false;
}
public TextRelay GetTextEntry(int entryID)
{
for (var i = 0; i < TextEntries.Length; ++i)
if (TextEntries[i].EntryID == entryID)
return TextEntries[i];
return null;
}
}
}

View file

@ -1,53 +1,53 @@
/***************************************************************************
* HuePicker.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.HuePickers
{
public class HuePicker
{
private static int m_NextSerial = 1;
public HuePicker(int itemID)
{
do
{
Serial = m_NextSerial++;
} while (Serial == 0);
ItemID = itemID;
}
public int Serial { get; }
public int ItemID { get; }
public virtual void OnResponse(int hue)
{
}
public void SendTo(NetState state)
{
state.Send(new DisplayHuePicker(this));
state.AddHuePicker(this);
}
}
}
/***************************************************************************
* HuePicker.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server.HuePickers
{
public class HuePicker
{
private static int m_NextSerial = 1;
public HuePicker(int itemID)
{
do
{
Serial = m_NextSerial++;
} while (Serial == 0);
ItemID = itemID;
}
public int Serial { get; }
public int ItemID { get; }
public virtual void OnResponse(int hue)
{
}
public void SendTo(NetState state)
{
state.Send(new DisplayHuePicker(this));
state.AddHuePicker(this);
}
}
}

View file

@ -1,126 +1,126 @@
/***************************************************************************
* IAccount.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server.Accounting
{
public static class AccountGold
{
public static bool Enabled = false;
/// <summary>
/// This amount specifies the value at which point Gold turns to Platinum.
/// By default, when 1,000,000,000 Gold is accumulated, it will transform
/// into 1 Platinum.
/// !!! WARNING !!!
/// The client is designed to perceive the currency threashold at 1,000,000,000
/// if you change this, it may cause unexpected results when using secure trading.
/// </summary>
public static int CurrencyThreshold = 1000000000;
/// <summary>
/// Enables or Disables automatic conversion of Gold and Checks to Bank Currency
/// when they are added to a bank box container.
/// </summary>
public static bool ConvertOnBank = true;
/// <summary>
/// Enables or Disables automatic conversion of Gold and Checks to Bank Currency
/// when they are added to a secure trade container.
/// </summary>
public static bool ConvertOnTrade = false;
}
public interface IGoldAccount
{
/// <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>
[CommandProperty(AccessLevel.Administrator)]
int TotalGold { get; }
/// <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>
[CommandProperty(AccessLevel.Administrator)]
int TotalPlat { get; }
/// <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>
bool DepositGold(int amount);
/// <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>
bool DepositPlat(int amount);
/// <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>
bool WithdrawGold(int amount);
/// <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>
bool WithdrawPlat(int amount);
/// <summary>
/// Returns total gold inclusive of platinum, capped to Int32.
/// This is strictly for backwards compatibility
/// </summary>
/// <returns>Total gold, capped at Int32.MaxValue</returns>
long GetTotalGold();
}
public interface IAccount : IGoldAccount, IComparable<IAccount>
{
string Username { get; set; }
string Email { get; set; }
AccessLevel AccessLevel { get; set; }
int Length { get; }
int Limit { get; }
int Count { get; }
Mobile this[int index] { get; set; }
void Delete();
void SetPassword(string password);
bool CheckPassword(string password);
}
}
/***************************************************************************
* IAccount.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server.Accounting
{
public static class AccountGold
{
public static bool Enabled = false;
/// <summary>
/// This amount specifies the value at which point Gold turns to Platinum.
/// By default, when 1,000,000,000 Gold is accumulated, it will transform
/// into 1 Platinum.
/// !!! WARNING !!!
/// The client is designed to perceive the currency threashold at 1,000,000,000
/// if you change this, it may cause unexpected results when using secure trading.
/// </summary>
public static int CurrencyThreshold = 1000000000;
/// <summary>
/// Enables or Disables automatic conversion of Gold and Checks to Bank Currency
/// when they are added to a bank box container.
/// </summary>
public static bool ConvertOnBank = true;
/// <summary>
/// Enables or Disables automatic conversion of Gold and Checks to Bank Currency
/// when they are added to a secure trade container.
/// </summary>
public static bool ConvertOnTrade = false;
}
public interface IGoldAccount
{
/// <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>
[CommandProperty(AccessLevel.Administrator)]
int TotalGold { get; }
/// <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>
[CommandProperty(AccessLevel.Administrator)]
int TotalPlat { get; }
/// <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>
bool DepositGold(int amount);
/// <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>
bool DepositPlat(int amount);
/// <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>
bool WithdrawGold(int amount);
/// <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>
bool WithdrawPlat(int amount);
/// <summary>
/// Returns total gold inclusive of platinum, capped to Int32.
/// This is strictly for backwards compatibility
/// </summary>
/// <returns>Total gold, capped at Int32.MaxValue</returns>
long GetTotalGold();
}
public interface IAccount : IGoldAccount, IComparable<IAccount>
{
string Username { get; set; }
string Email { get; set; }
AccessLevel AccessLevel { get; set; }
int Length { get; }
int Limit { get; }
int Count { get; }
Mobile this[int index] { get; set; }
void Delete();
void SetPassword(string password);
bool CheckPassword(string password);
}
}

View file

@ -1,103 +1,103 @@
/***************************************************************************
* IEntity.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public interface IEntity : IPoint3D, IComparable<IEntity>
{
Serial Serial { get; }
Point3D Location { get; }
Map Map { get; }
bool Deleted { get; }
void MoveToWorld(Point3D location, Map map);
void Delete();
void ProcessDelta();
bool InRange(Point2D p, int range);
bool InRange(Point3D p, int range);
bool InRange(IPoint2D p, int range);
}
public class Entity : IEntity, IComparable<Entity>
{
public Entity(Serial serial, Point3D loc, Map map)
{
Serial = serial;
Location = loc;
Map = map;
Deleted = false;
}
public int CompareTo(Entity other) => CompareTo((IEntity)other);
public int CompareTo(IEntity other) => other == null ? -1 : Serial.CompareTo(other.Serial);
public Serial Serial { get; }
public Point3D Location { get; private set; }
public int X => Location.X;
public int Y => Location.Y;
public int Z => Location.Z;
public Map Map { get; private set; }
public virtual void MoveToWorld(Point3D newLocation, Map map)
{
Location = newLocation;
Map = map;
}
public bool Deleted { get; }
public void Delete()
{
}
public void ProcessDelta()
{
}
public bool InRange(Point2D p, int range) =>
p.m_X >= Location.m_X - range
&& p.m_X <= Location.m_X + range
&& p.m_Y >= Location.m_Y - range
&& p.m_Y <= Location.m_Y + range;
public bool InRange(Point3D p, int range) =>
p.m_X >= Location.m_X - range
&& p.m_X <= Location.m_X + range
&& p.m_Y >= Location.m_Y - range
&& p.m_Y <= Location.m_Y + range;
public bool InRange(IPoint2D p, int range) =>
p.X >= Location.m_X - range
&& p.X <= Location.m_X + range
&& p.Y >= Location.m_Y - range
&& p.Y <= Location.m_Y + range;
}
}
/***************************************************************************
* IEntity.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public interface IEntity : IPoint3D, IComparable<IEntity>
{
Serial Serial { get; }
Point3D Location { get; }
Map Map { get; }
bool Deleted { get; }
void MoveToWorld(Point3D location, Map map);
void Delete();
void ProcessDelta();
bool InRange(Point2D p, int range);
bool InRange(Point3D p, int range);
bool InRange(IPoint2D p, int range);
}
public class Entity : IEntity, IComparable<Entity>
{
public Entity(Serial serial, Point3D loc, Map map)
{
Serial = serial;
Location = loc;
Map = map;
Deleted = false;
}
public int CompareTo(Entity other) => CompareTo((IEntity)other);
public int CompareTo(IEntity other) => other == null ? -1 : Serial.CompareTo(other.Serial);
public Serial Serial { get; }
public Point3D Location { get; private set; }
public int X => Location.X;
public int Y => Location.Y;
public int Z => Location.Z;
public Map Map { get; private set; }
public virtual void MoveToWorld(Point3D newLocation, Map map)
{
Location = newLocation;
Map = map;
}
public bool Deleted { get; }
public void Delete()
{
}
public void ProcessDelta()
{
}
public bool InRange(Point2D p, int range) =>
p.m_X >= Location.m_X - range
&& p.m_X <= Location.m_X + range
&& p.m_Y >= Location.m_Y - range
&& p.m_Y <= Location.m_Y + range;
public bool InRange(Point3D p, int range) =>
p.m_X >= Location.m_X - range
&& p.m_X <= Location.m_X + range
&& p.m_Y >= Location.m_Y - range
&& p.m_Y <= Location.m_Y + range;
public bool InRange(IPoint2D p, int range) =>
p.X >= Location.m_X - range
&& p.X <= Location.m_X + range
&& p.Y >= Location.m_Y - range
&& p.Y <= Location.m_Y + range;
}
}

View file

@ -1,44 +1,44 @@
/***************************************************************************
* Insensitive.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
public static class Insensitive
{
public static IComparer<string> Comparer { get; } = StringComparer.OrdinalIgnoreCase;
public static int Compare(string a, string b) => Comparer.Compare(a, b);
public static bool Equals(string a, string b) =>
(a == null && b == null) || (a != null && b != null && a.Length == b.Length && Comparer.Compare(a, b) == 0);
public static bool StartsWith(string a, string b) =>
a != null && b != null && a.Length >= b.Length && Comparer.Compare(a.Substring(0, b.Length), b) == 0;
public static bool EndsWith(string a, string b) =>
a != null && b != null && a.Length >= b.Length && Comparer.Compare(a.Substring(a.Length - b.Length), b) == 0;
public static bool Contains(string a, string b) =>
a != null && b != null && a.Length >= b.Length && a.IndexOf(b, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
/***************************************************************************
* Insensitive.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Server
{
public static class Insensitive
{
public static IComparer<string> Comparer { get; } = StringComparer.OrdinalIgnoreCase;
public static int Compare(string a, string b) => Comparer.Compare(a, b);
public static bool Equals(string a, string b) =>
a == null && b == null || a != null && b != null && a.Length == b.Length && Comparer.Compare(a, b) == 0;
public static bool StartsWith(string a, string b) =>
a != null && b != null && a.Length >= b.Length && Comparer.Compare(a.Substring(0, b.Length), b) == 0;
public static bool EndsWith(string a, string b) =>
a != null && b != null && a.Length >= b.Length && Comparer.Compare(a.Substring(a.Length - b.Length), b) == 0;
public static bool Contains(string a, string b) =>
a != null && b != null && a.Length >= b.Length && a.IndexOf(b, StringComparison.OrdinalIgnoreCase) >= 0;
}
}

View file

@ -1,95 +1,95 @@
/***************************************************************************
* Interfaces.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public interface IPoint2D
{
int X { get; }
int Y { get; }
}
public interface IPoint3D : IPoint2D
{
int Z { get; }
}
public interface ICarvable
{
void Carve(Mobile from, Item item);
}
public interface IWeapon
{
int MaxRange { get; }
void OnBeforeSwing(Mobile attacker, Mobile defender);
TimeSpan OnSwing(Mobile attacker, Mobile defender);
TimeSpan OnSwing(Mobile attacker, Mobile defender, double damageBonus);
void GetStatusDamage(Mobile from, out int min, out int max);
}
public interface IHued
{
int HuedItemID { get; }
}
public interface ISpell
{
bool IsCasting { get; }
void OnCasterHurt();
void OnCasterKilled();
void OnConnectionChanged();
bool OnCasterMoving(Direction d);
bool OnCasterEquipping(Item item);
bool OnCasterUsingObject(IEntity entity);
bool OnCastInTown(Region r);
void FinishSequence();
}
public interface IParty
{
void OnStamChanged(Mobile m);
void OnManaChanged(Mobile m);
void OnStatsQuery(Mobile beholder, Mobile beheld);
}
// TODO: Add SpawnMap and change Spawner.Map to use it
public interface ISpawner : IEntity
{
bool UnlinkOnTaming { get; }
Point3D HomeLocation { get; }
int HomeRange { get; }
Region Region { get; }
bool ReturnOnDeactivate { get; }
void Remove(ISpawnable spawn);
Point3D GetSpawnPosition(ISpawnable spawned, Map map);
void Respawn();
}
public interface ISpawnable : IEntity
{
ISpawner Spawner { get; set; }
void OnBeforeSpawn(Point3D location, Map map);
void OnAfterSpawn();
}
}
/***************************************************************************
* Interfaces.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server
{
public interface IPoint2D
{
int X { get; }
int Y { get; }
}
public interface IPoint3D : IPoint2D
{
int Z { get; }
}
public interface ICarvable
{
void Carve(Mobile from, Item item);
}
public interface IWeapon
{
int MaxRange { get; }
void OnBeforeSwing(Mobile attacker, Mobile defender);
TimeSpan OnSwing(Mobile attacker, Mobile defender);
TimeSpan OnSwing(Mobile attacker, Mobile defender, double damageBonus);
void GetStatusDamage(Mobile from, out int min, out int max);
}
public interface IHued
{
int HuedItemID { get; }
}
public interface ISpell
{
bool IsCasting { get; }
void OnCasterHurt();
void OnCasterKilled();
void OnConnectionChanged();
bool OnCasterMoving(Direction d);
bool OnCasterEquipping(Item item);
bool OnCasterUsingObject(IEntity entity);
bool OnCastInTown(Region r);
void FinishSequence();
}
public interface IParty
{
void OnStamChanged(Mobile m);
void OnManaChanged(Mobile m);
void OnStatsQuery(Mobile beholder, Mobile beheld);
}
// TODO: Add SpawnMap and change Spawner.Map to use it
public interface ISpawner : IEntity
{
bool UnlinkOnTaming { get; }
Point3D HomeLocation { get; }
int HomeRange { get; }
Region Region { get; }
bool ReturnOnDeactivate { get; }
void Remove(ISpawnable spawn);
Point3D GetSpawnPosition(ISpawnable spawned, Map map);
void Respawn();
}
public interface ISpawnable : IEntity
{
ISpawner Spawner { get; set; }
void OnBeforeSpawn(Point3D location, Map map);
void OnAfterSpawn();
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,60 +1,64 @@
/***************************************************************************
* ItemBounds.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.IO;
namespace Server
{
public static class ItemBounds
{
static ItemBounds()
{
Table = new Rectangle2D[TileData.ItemTable.Length];
if (File.Exists("Data/Binary/Bounds.bin"))
{
using var fs = new FileStream("Data/Binary/Bounds.bin", FileMode.Open, FileAccess.Read,
FileShare.Read);
var bin = new BinaryReader(fs);
var count = Math.Min(Table.Length, (int)(fs.Length / 8));
for (var i = 0; i < count; ++i)
{
int xMin = bin.ReadInt16();
int yMin = bin.ReadInt16();
int xMax = bin.ReadInt16();
int yMax = bin.ReadInt16();
Table[i].Set(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1);
}
bin.Close();
}
else
{
Console.WriteLine("Warning: Data/Binary/Bounds.bin does not exist");
}
}
public static Rectangle2D[] Table { get; }
}
}
/***************************************************************************
* ItemBounds.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.IO;
namespace Server
{
public static class ItemBounds
{
static ItemBounds()
{
Table = new Rectangle2D[TileData.ItemTable.Length];
if (File.Exists("Data/Binary/Bounds.bin"))
{
using var fs = new FileStream(
"Data/Binary/Bounds.bin",
FileMode.Open,
FileAccess.Read,
FileShare.Read
);
var bin = new BinaryReader(fs);
var count = Math.Min(Table.Length, (int)(fs.Length / 8));
for (var i = 0; i < count; ++i)
{
int xMin = bin.ReadInt16();
int yMin = bin.ReadInt16();
int xMax = bin.ReadInt16();
int yMax = bin.ReadInt16();
Table[i].Set(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1);
}
bin.Close();
}
else
{
Console.WriteLine("Warning: Data/Binary/Bounds.bin does not exist");
}
}
public static Rectangle2D[] Table { get; }
}
}

View file

@ -1,136 +1,136 @@
/***************************************************************************
* BaseMulti.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server.Items
{
public abstract class BaseMulti : Item
{
public BaseMulti(int itemID) : base(itemID) => Movable = false;
public BaseMulti(Serial serial) : base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public override int ItemID
{
get => base.ItemID;
set
{
if (base.ItemID != value)
{
var facet = Parent == null ? Map : null;
facet?.OnLeave(this);
base.ItemID = value;
facet?.OnEnter(this);
}
}
}
public override int LabelNumber
{
get
{
var mcl = Components;
if (mcl.List.Length > 0)
{
int id = mcl.List[0].ItemId;
if (id < 0x4000)
return 1020000 + id;
return 1078872 + id;
}
return base.LabelNumber;
}
}
public virtual bool AllowsRelativeDrop => false;
public virtual MultiComponentList Components => MultiData.GetComponents(ItemID);
[Obsolete("Replace with calls to OnLeave and OnEnter surrounding component invalidation.", true)]
public virtual void RefreshComponents()
{
if (Parent == null)
{
var facet = Map;
if (facet != null)
{
facet.OnLeave(this);
facet.OnEnter(this);
}
}
}
public override int GetMaxUpdateRange() => 22;
public override int GetUpdateRange(Mobile m) => 22;
public virtual bool Contains(Point2D p) => Contains(p.m_X, p.m_Y);
public virtual bool Contains(Point3D p) => Contains(p.m_X, p.m_Y);
public virtual bool Contains(IPoint3D p) => Contains(p.X, p.Y);
public virtual bool Contains(int x, int y)
{
var mcl = Components;
x -= X + mcl.Min.m_X;
y -= Y + mcl.Min.m_Y;
return x >= 0
&& x < mcl.Width
&& y >= 0
&& y < mcl.Height
&& mcl.Tiles[x][y].Length > 0;
}
public bool Contains(Mobile m) => m.Map == Map && Contains(m.X, m.Y);
public bool Contains(Item item) => item.Map == Map && Contains(item.X, item.Y);
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(1); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
if (version == 0)
if (ItemID >= 0x4000)
ItemID -= 0x4000;
}
}
}
/***************************************************************************
* BaseMulti.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
namespace Server.Items
{
public abstract class BaseMulti : Item
{
public BaseMulti(int itemID) : base(itemID) => Movable = false;
public BaseMulti(Serial serial) : base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public override int ItemID
{
get => base.ItemID;
set
{
if (base.ItemID != value)
{
var facet = Parent == null ? Map : null;
facet?.OnLeave(this);
base.ItemID = value;
facet?.OnEnter(this);
}
}
}
public override int LabelNumber
{
get
{
var mcl = Components;
if (mcl.List.Length > 0)
{
int id = mcl.List[0].ItemId;
if (id < 0x4000)
return 1020000 + id;
return 1078872 + id;
}
return base.LabelNumber;
}
}
public virtual bool AllowsRelativeDrop => false;
public virtual MultiComponentList Components => MultiData.GetComponents(ItemID);
[Obsolete("Replace with calls to OnLeave and OnEnter surrounding component invalidation.", true)]
public virtual void RefreshComponents()
{
if (Parent == null)
{
var facet = Map;
if (facet != null)
{
facet.OnLeave(this);
facet.OnEnter(this);
}
}
}
public override int GetMaxUpdateRange() => 22;
public override int GetUpdateRange(Mobile m) => 22;
public virtual bool Contains(Point2D p) => Contains(p.m_X, p.m_Y);
public virtual bool Contains(Point3D p) => Contains(p.m_X, p.m_Y);
public virtual bool Contains(IPoint3D p) => Contains(p.X, p.Y);
public virtual bool Contains(int x, int y)
{
var mcl = Components;
x -= X + mcl.Min.m_X;
y -= Y + mcl.Min.m_Y;
return x >= 0
&& x < mcl.Width
&& y >= 0
&& y < mcl.Height
&& mcl.Tiles[x][y].Length > 0;
}
public bool Contains(Mobile m) => m.Map == Map && Contains(m.X, m.Y);
public bool Contains(Item item) => item.Map == Map && Contains(item.X, item.Y);
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(1); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
if (version == 0)
if (ItemID >= 0x4000)
ItemID -= 0x4000;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,132 +1,137 @@
/***************************************************************************
* Containers.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Accounting;
using Server.Network;
namespace Server.Items
{
public class BankBox : Container
{
public BankBox(Serial serial) : base(serial)
{
}
public BankBox(Mobile owner) : base(0xE7C)
{
Layer = Layer.Bank;
Movable = false;
Owner = owner;
}
public override int DefaultMaxWeight => 0;
public override bool IsVirtualItem => true;
public Mobile Owner { get; private set; }
public bool Opened { get; private set; }
public static bool SendDeleteOnClose { get; set; }
public void Open()
{
Opened = true;
if (Owner != null)
{
Owner.PrivateOverheadMessage(MessageType.Regular, 0x3B2, true,
$"Bank container has {TotalItems} items, {TotalWeight} stones", Owner.NetState);
Owner.Send(new EquipUpdate(this));
DisplayTo(Owner);
}
}
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
writer.Write(Owner);
writer.Write(Opened);
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
switch (version)
{
case 0:
{
Owner = reader.ReadMobile();
Opened = reader.ReadBool();
if (Owner == null)
Delete();
break;
}
}
if (ItemID == 0xE41)
ItemID = 0xE7C;
}
public void Close()
{
Opened = false;
if (SendDeleteOnClose)
Owner?.Send(RemovePacket);
}
public override void OnSingleClick(Mobile from)
{
}
public override void OnDoubleClick(Mobile from)
{
}
public override DeathMoveResult OnParentDeath(Mobile parent) => DeathMoveResult.RemainEquipped;
public override bool IsAccessibleTo(Mobile check) =>
((check == Owner && Opened) || check.AccessLevel >= AccessLevel.GameMaster) && base.IsAccessibleTo(check);
public override bool OnDragDrop(Mobile from, Item dropped) =>
((from == Owner && Opened) || from.AccessLevel >= AccessLevel.GameMaster) && base.OnDragDrop(from, dropped);
public override bool OnDragDropInto(Mobile from, Item item, Point3D p) =>
((from == Owner && Opened) || from.AccessLevel >= AccessLevel.GameMaster) &&
base.OnDragDropInto(from, item, p);
public override int GetTotal(TotalType type)
{
if (AccountGold.Enabled && Owner?.Account != null && type == TotalType.Gold)
return Owner.Account.TotalGold;
return base.GetTotal(type);
}
}
}
/***************************************************************************
* Containers.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Accounting;
using Server.Network;
namespace Server.Items
{
public class BankBox : Container
{
public BankBox(Serial serial) : base(serial)
{
}
public BankBox(Mobile owner) : base(0xE7C)
{
Layer = Layer.Bank;
Movable = false;
Owner = owner;
}
public override int DefaultMaxWeight => 0;
public override bool IsVirtualItem => true;
public Mobile Owner { get; private set; }
public bool Opened { get; private set; }
public static bool SendDeleteOnClose { get; set; }
public void Open()
{
Opened = true;
if (Owner != null)
{
Owner.PrivateOverheadMessage(
MessageType.Regular,
0x3B2,
true,
$"Bank container has {TotalItems} items, {TotalWeight} stones",
Owner.NetState
);
Owner.Send(new EquipUpdate(this));
DisplayTo(Owner);
}
}
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
writer.Write(Owner);
writer.Write(Opened);
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
switch (version)
{
case 0:
{
Owner = reader.ReadMobile();
Opened = reader.ReadBool();
if (Owner == null)
Delete();
break;
}
}
if (ItemID == 0xE41)
ItemID = 0xE7C;
}
public void Close()
{
Opened = false;
if (SendDeleteOnClose)
Owner?.Send(RemovePacket);
}
public override void OnSingleClick(Mobile from)
{
}
public override void OnDoubleClick(Mobile from)
{
}
public override DeathMoveResult OnParentDeath(Mobile parent) => DeathMoveResult.RemainEquipped;
public override bool IsAccessibleTo(Mobile check) =>
(check == Owner && Opened || check.AccessLevel >= AccessLevel.GameMaster) && base.IsAccessibleTo(check);
public override bool OnDragDrop(Mobile from, Item dropped) =>
(from == Owner && Opened || from.AccessLevel >= AccessLevel.GameMaster) && base.OnDragDrop(from, dropped);
public override bool OnDragDropInto(Mobile from, Item item, Point3D p) =>
(from == Owner && Opened || from.AccessLevel >= AccessLevel.GameMaster) &&
base.OnDragDropInto(from, item, p);
public override int GetTotal(TotalType type)
{
if (AccountGold.Enabled && Owner?.Account != null && type == TotalType.Gold)
return Owner.Account.TotalGold;
return base.GetTotal(type);
}
}
}

View file

@ -1,116 +1,116 @@
/***************************************************************************
* SecureTradeContainer.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Accounting;
using Server.Network;
namespace Server.Items
{
public class SecureTradeContainer : Container
{
public SecureTradeContainer(SecureTrade trade) : base(0x1E5E)
{
Trade = trade;
Movable = false;
}
public SecureTradeContainer(Serial serial) : base(serial)
{
}
public SecureTrade Trade { get; }
public override bool CheckHold(Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight)
{
if (item == Trade.From.VirtualCheck || item == Trade.To.VirtualCheck) return true;
var to = Trade.From.Container != this ? Trade.From.Mobile : Trade.To.Mobile;
return m.CheckTrade(to, item, this, message, checkItems, plusItems, plusWeight);
}
public override bool CheckLift(Mobile from, Item item, ref LRReason reject)
{
reject = LRReason.CannotLift;
return false;
}
public override bool IsAccessibleTo(Mobile check) =>
IsChildOf(check) && Trade?.Valid == true && base.IsAccessibleTo(check);
public override void OnItemAdded(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnItemRemoved(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnSubItemAdded(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnSubItemRemoved(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public void ClearChecks()
{
if (Trade == null)
return;
if (Trade.From?.IsDisposed == false)
Trade.From.Accepted = false;
if (Trade.To?.IsDisposed == false)
Trade.To.Accepted = false;
Trade.Update();
}
public override bool IsChildVisibleTo(Mobile m, Item child) =>
child is VirtualCheck
? AccountGold.Enabled && m.NetState?.NewSecureTrading != true
: base.IsChildVisibleTo(m, child);
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
}
}
}
/***************************************************************************
* SecureTradeContainer.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Accounting;
using Server.Network;
namespace Server.Items
{
public class SecureTradeContainer : Container
{
public SecureTradeContainer(SecureTrade trade) : base(0x1E5E)
{
Trade = trade;
Movable = false;
}
public SecureTradeContainer(Serial serial) : base(serial)
{
}
public SecureTrade Trade { get; }
public override bool CheckHold(Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight)
{
if (item == Trade.From.VirtualCheck || item == Trade.To.VirtualCheck) return true;
var to = Trade.From.Container != this ? Trade.From.Mobile : Trade.To.Mobile;
return m.CheckTrade(to, item, this, message, checkItems, plusItems, plusWeight);
}
public override bool CheckLift(Mobile from, Item item, ref LRReason reject)
{
reject = LRReason.CannotLift;
return false;
}
public override bool IsAccessibleTo(Mobile check) =>
IsChildOf(check) && Trade?.Valid == true && base.IsAccessibleTo(check);
public override void OnItemAdded(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnItemRemoved(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnSubItemAdded(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnSubItemRemoved(Item item)
{
if (!(item is VirtualCheck))
ClearChecks();
}
public void ClearChecks()
{
if (Trade == null)
return;
if (Trade.From?.IsDisposed == false)
Trade.From.Accepted = false;
if (Trade.To?.IsDisposed == false)
Trade.To.Accepted = false;
Trade.Update();
}
public override bool IsChildVisibleTo(Mobile m, Item child) =>
child is VirtualCheck
? AccountGold.Enabled && m.NetState?.NewSecureTrading != true
: base.IsChildVisibleTo(m, child);
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
}
}
}

View file

@ -1,353 +1,353 @@
using Server.Gumps;
using Server.Network;
namespace Server.Items
{
public sealed class VirtualCheck : Item
{
// TODO: Move to configuration
public static bool UseEditGump = false;
private int m_Gold;
private int m_Plat;
public VirtualCheck(int plat = 0, int gold = 0)
: base(0x14F0)
{
Plat = plat;
Gold = gold;
Movable = false;
}
public VirtualCheck(Serial serial)
: base(serial)
{
}
public override bool IsVirtualItem => true;
public override bool DisplayWeight => false;
public override bool DisplayLootType => false;
public override double DefaultWeight => 0;
public override string DefaultName => "Offer Of Currency";
public EditGump Editor { get; private set; }
[CommandProperty(AccessLevel.Administrator)]
public int Plat
{
get => m_Plat;
set
{
m_Plat = value;
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.Administrator)]
public int Gold
{
get => m_Gold;
set
{
m_Gold = value;
InvalidateProperties();
}
}
public override bool IsAccessibleTo(Mobile check)
{
var c = GetSecureTradeCont();
if (check == null || c == null) return base.IsAccessibleTo(check);
return c.RootParent == check && IsChildOf(c);
}
public override void OnDoubleClickSecureTrade(Mobile from)
{
if (UseEditGump && IsAccessibleTo(from))
{
if (Editor?.Check?.Deleted != false)
{
Editor = new EditGump(from, this);
Editor.Send();
}
else
{
Editor.Refresh(true);
}
}
else
{
if (Editor != null)
{
Editor.Close();
Editor = null;
}
base.OnDoubleClickSecureTrade(from);
}
}
public override void OnSingleClick(Mobile from)
{
LabelTo(from, "Offer: {0:#,0} platinum, {1:#,0} gold", Plat, Gold);
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
list.Add(1060738, $"{Plat:#,0} platinum, {Gold:#,0} gold"); // value: ~1_val~
}
public void UpdateTrade(Mobile user)
{
var c = GetSecureTradeCont();
if (c?.Trade == null) return;
if (user == c.Trade.From.Mobile)
c.Trade.UpdateFromCurrency();
else if (user == c.Trade.To.Mobile) c.Trade.UpdateToCurrency();
c.ClearChecks();
}
public override void OnAfterDelete()
{
base.OnAfterDelete();
if (Editor != null)
{
Editor.Close();
Editor = null;
}
}
public override void Serialize(IGenericWriter writer)
{
}
public override void Deserialize(IGenericReader reader)
{
Delete();
}
public class EditGump : Gump
{
public enum Buttons
{
Close,
Clear,
Accept,
AllPlat,
AllGold
}
private int m_Plat, m_Gold;
public EditGump(Mobile user, VirtualCheck check)
: base(50, 50)
{
User = user;
Check = check;
m_Plat = Check.Plat;
m_Gold = Check.Gold;
Closable = true;
Disposable = true;
Draggable = true;
Resizable = false;
User.CloseGump<EditGump>();
CompileLayout();
}
public Mobile User { get; }
public VirtualCheck Check { get; private set; }
public override void OnServerClose(NetState owner)
{
base.OnServerClose(owner);
if (Check?.Deleted == false)
Check.UpdateTrade(User);
}
public void Close()
{
User.CloseGump<EditGump>();
if (Check?.Deleted == false)
Check.UpdateTrade(User);
else
Check = null;
}
public void Send()
{
if (Check?.Deleted == false)
User.SendGump(this);
else
Close();
}
public void Refresh(bool recompile)
{
if (Check?.Deleted != false)
{
Close();
return;
}
if (recompile)
CompileLayout();
Close();
Send();
}
private void CompileLayout()
{
if (Check?.Deleted != false)
return;
Entries.ForEach(e => e.Parent = null);
Entries.Clear();
AddPage(0);
AddBackground(0, 0, 400, 160, 3500);
// Title
AddImageTiled(25, 35, 350, 3, 96);
AddImage(10, 8, 113);
AddImage(360, 8, 113);
var title =
$"<BASEFONT COLOR=#FF2F4F4F><CENTER>BANK OF {User.RawName.ToUpper()}</CENTER>";
AddHtml(40, 15, 320, 20, title);
// Platinum Row
AddBackground(15, 60, 175, 20, 9300);
AddBackground(20, 45, 165, 30, 9350);
AddItem(20, 45, 3826); // Plat
AddLabel(60, 50, 0, User.Account.TotalPlat.ToString("#,0"));
AddButton(195, 50, 95, 95, (int)Buttons.AllPlat); // ->
AddBackground(210, 60, 175, 20, 9300);
AddBackground(215, 45, 165, 30, 9350);
AddTextEntry(225, 50, 145, 20, 0, 0, m_Plat.ToString(), User.Account.TotalPlat.ToString().Length);
// Gold Row
AddBackground(15, 100, 175, 20, 9300);
AddBackground(20, 85, 165, 30, 9350);
AddItem(20, 85, 3823); // Gold
AddLabel(60, 90, 0, User.Account.TotalGold.ToString("#,0"));
AddButton(195, 90, 95, 95, (int)Buttons.AllGold); // ->
AddBackground(210, 100, 175, 20, 9300);
AddBackground(215, 85, 165, 30, 9350);
AddTextEntry(225, 90, 145, 20, 0, 1, m_Gold.ToString(), User.Account.TotalGold.ToString().Length);
// Buttons
AddButton(20, 128, 12006, 12007, (int)Buttons.Close);
AddButton(215, 128, 12003, 12004, (int)Buttons.Clear);
AddButton(305, 128, 12000, 12002, (int)Buttons.Accept);
}
public override void OnResponse(NetState sender, RelayInfo info)
{
if (Check?.Deleted != false || sender.Mobile != User)
{
Close();
return;
}
bool refresh = false, updated = false;
switch ((Buttons)info.ButtonID)
{
case Buttons.Close:
break;
case Buttons.Clear:
{
m_Plat = m_Gold = 0;
refresh = true;
}
break;
case Buttons.Accept:
{
var platText = info.GetTextEntry(0).Text;
var goldText = info.GetTextEntry(1).Text;
if (!int.TryParse(platText, out m_Plat))
{
User.SendMessage("That is not a valid amount of platinum.");
refresh = true;
}
else if (!int.TryParse(goldText, out m_Gold))
{
User.SendMessage("That is not a valid amount of gold.");
refresh = true;
}
else
{
var totalPlat = User.Account.TotalPlat;
var totalGold = User.Account.TotalGold;
if (totalPlat < m_Plat || totalGold < m_Gold)
{
m_Plat = User.Account.TotalPlat;
m_Gold = User.Account.TotalGold;
User.SendMessage("You do not have that much currency.");
refresh = true;
}
else
{
Check.Plat = m_Plat;
Check.Gold = m_Gold;
updated = true;
}
}
}
break;
case Buttons.AllPlat:
{
m_Plat = User.Account.TotalPlat;
refresh = true;
}
break;
case Buttons.AllGold:
{
m_Gold = User.Account.TotalGold;
refresh = true;
}
break;
}
if (updated)
User.SendMessage("Your offer has been updated.");
if (refresh && Check?.Deleted == false)
{
Refresh(true);
return;
}
Close();
}
}
}
}
using Server.Gumps;
using Server.Network;
namespace Server.Items
{
public sealed class VirtualCheck : Item
{
// TODO: Move to configuration
public static bool UseEditGump = false;
private int m_Gold;
private int m_Plat;
public VirtualCheck(int plat = 0, int gold = 0)
: base(0x14F0)
{
Plat = plat;
Gold = gold;
Movable = false;
}
public VirtualCheck(Serial serial)
: base(serial)
{
}
public override bool IsVirtualItem => true;
public override bool DisplayWeight => false;
public override bool DisplayLootType => false;
public override double DefaultWeight => 0;
public override string DefaultName => "Offer Of Currency";
public EditGump Editor { get; private set; }
[CommandProperty(AccessLevel.Administrator)]
public int Plat
{
get => m_Plat;
set
{
m_Plat = value;
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.Administrator)]
public int Gold
{
get => m_Gold;
set
{
m_Gold = value;
InvalidateProperties();
}
}
public override bool IsAccessibleTo(Mobile check)
{
var c = GetSecureTradeCont();
if (check == null || c == null) return base.IsAccessibleTo(check);
return c.RootParent == check && IsChildOf(c);
}
public override void OnDoubleClickSecureTrade(Mobile from)
{
if (UseEditGump && IsAccessibleTo(from))
{
if (Editor?.Check?.Deleted != false)
{
Editor = new EditGump(from, this);
Editor.Send();
}
else
{
Editor.Refresh(true);
}
}
else
{
if (Editor != null)
{
Editor.Close();
Editor = null;
}
base.OnDoubleClickSecureTrade(from);
}
}
public override void OnSingleClick(Mobile from)
{
LabelTo(from, "Offer: {0:#,0} platinum, {1:#,0} gold", Plat, Gold);
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
list.Add(1060738, $"{Plat:#,0} platinum, {Gold:#,0} gold"); // value: ~1_val~
}
public void UpdateTrade(Mobile user)
{
var c = GetSecureTradeCont();
if (c?.Trade == null) return;
if (user == c.Trade.From.Mobile)
c.Trade.UpdateFromCurrency();
else if (user == c.Trade.To.Mobile) c.Trade.UpdateToCurrency();
c.ClearChecks();
}
public override void OnAfterDelete()
{
base.OnAfterDelete();
if (Editor != null)
{
Editor.Close();
Editor = null;
}
}
public override void Serialize(IGenericWriter writer)
{
}
public override void Deserialize(IGenericReader reader)
{
Delete();
}
public class EditGump : Gump
{
public enum Buttons
{
Close,
Clear,
Accept,
AllPlat,
AllGold
}
private int m_Plat, m_Gold;
public EditGump(Mobile user, VirtualCheck check)
: base(50, 50)
{
User = user;
Check = check;
m_Plat = Check.Plat;
m_Gold = Check.Gold;
Closable = true;
Disposable = true;
Draggable = true;
Resizable = false;
User.CloseGump<EditGump>();
CompileLayout();
}
public Mobile User { get; }
public VirtualCheck Check { get; private set; }
public override void OnServerClose(NetState owner)
{
base.OnServerClose(owner);
if (Check?.Deleted == false)
Check.UpdateTrade(User);
}
public void Close()
{
User.CloseGump<EditGump>();
if (Check?.Deleted == false)
Check.UpdateTrade(User);
else
Check = null;
}
public void Send()
{
if (Check?.Deleted == false)
User.SendGump(this);
else
Close();
}
public void Refresh(bool recompile)
{
if (Check?.Deleted != false)
{
Close();
return;
}
if (recompile)
CompileLayout();
Close();
Send();
}
private void CompileLayout()
{
if (Check?.Deleted != false)
return;
Entries.ForEach(e => e.Parent = null);
Entries.Clear();
AddPage(0);
AddBackground(0, 0, 400, 160, 3500);
// Title
AddImageTiled(25, 35, 350, 3, 96);
AddImage(10, 8, 113);
AddImage(360, 8, 113);
var title =
$"<BASEFONT COLOR=#FF2F4F4F><CENTER>BANK OF {User.RawName.ToUpper()}</CENTER>";
AddHtml(40, 15, 320, 20, title);
// Platinum Row
AddBackground(15, 60, 175, 20, 9300);
AddBackground(20, 45, 165, 30, 9350);
AddItem(20, 45, 3826); // Plat
AddLabel(60, 50, 0, User.Account.TotalPlat.ToString("#,0"));
AddButton(195, 50, 95, 95, (int)Buttons.AllPlat); // ->
AddBackground(210, 60, 175, 20, 9300);
AddBackground(215, 45, 165, 30, 9350);
AddTextEntry(225, 50, 145, 20, 0, 0, m_Plat.ToString(), User.Account.TotalPlat.ToString().Length);
// Gold Row
AddBackground(15, 100, 175, 20, 9300);
AddBackground(20, 85, 165, 30, 9350);
AddItem(20, 85, 3823); // Gold
AddLabel(60, 90, 0, User.Account.TotalGold.ToString("#,0"));
AddButton(195, 90, 95, 95, (int)Buttons.AllGold); // ->
AddBackground(210, 100, 175, 20, 9300);
AddBackground(215, 85, 165, 30, 9350);
AddTextEntry(225, 90, 145, 20, 0, 1, m_Gold.ToString(), User.Account.TotalGold.ToString().Length);
// Buttons
AddButton(20, 128, 12006, 12007, (int)Buttons.Close);
AddButton(215, 128, 12003, 12004, (int)Buttons.Clear);
AddButton(305, 128, 12000, 12002, (int)Buttons.Accept);
}
public override void OnResponse(NetState sender, RelayInfo info)
{
if (Check?.Deleted != false || sender.Mobile != User)
{
Close();
return;
}
bool refresh = false, updated = false;
switch ((Buttons)info.ButtonID)
{
case Buttons.Close:
break;
case Buttons.Clear:
{
m_Plat = m_Gold = 0;
refresh = true;
}
break;
case Buttons.Accept:
{
var platText = info.GetTextEntry(0).Text;
var goldText = info.GetTextEntry(1).Text;
if (!int.TryParse(platText, out m_Plat))
{
User.SendMessage("That is not a valid amount of platinum.");
refresh = true;
}
else if (!int.TryParse(goldText, out m_Gold))
{
User.SendMessage("That is not a valid amount of gold.");
refresh = true;
}
else
{
var totalPlat = User.Account.TotalPlat;
var totalGold = User.Account.TotalGold;
if (totalPlat < m_Plat || totalGold < m_Gold)
{
m_Plat = User.Account.TotalPlat;
m_Gold = User.Account.TotalGold;
User.SendMessage("You do not have that much currency.");
refresh = true;
}
else
{
Check.Plat = m_Plat;
Check.Gold = m_Gold;
updated = true;
}
}
}
break;
case Buttons.AllPlat:
{
m_Plat = User.Account.TotalPlat;
refresh = true;
}
break;
case Buttons.AllGold:
{
m_Gold = User.Account.TotalGold;
refresh = true;
}
break;
}
if (updated)
User.SendMessage("Your offer has been updated.");
if (refresh && Check?.Deleted == false)
{
Refresh(true);
return;
}
Close();
}
}
}
}

View file

@ -1,153 +1,153 @@
/***************************************************************************
* VirtualHair.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server
{
public abstract class BaseHairInfo
{
protected BaseHairInfo(int itemid, int hue = 0)
{
ItemID = itemid;
Hue = hue;
}
protected BaseHairInfo(IGenericReader reader)
{
var version = reader.ReadInt();
switch (version)
{
case 0:
{
ItemID = reader.ReadInt();
Hue = reader.ReadInt();
break;
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int ItemID { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public int Hue { get; set; }
public virtual void Serialize(IGenericWriter writer)
{
writer.Write(0); // version
writer.Write(ItemID);
writer.Write(Hue);
}
}
public class HairInfo : BaseHairInfo
{
public HairInfo(int itemid)
: base(itemid)
{
}
public HairInfo(int itemid, int hue)
: base(itemid, hue)
{
}
public HairInfo(IGenericReader reader)
: base(reader)
{
}
// TODO: Can we make this higher for newer clients?
public static uint FakeSerial(Mobile parent) => 0x7FFFFFFF - 0x400 - parent.Serial * 4;
}
public class FacialHairInfo : BaseHairInfo
{
public FacialHairInfo(int itemid)
: base(itemid)
{
}
public FacialHairInfo(int itemid, int hue)
: base(itemid, hue)
{
}
public FacialHairInfo(IGenericReader reader)
: base(reader)
{
}
// TOOD: Can we make this higher for newer clients?
public static uint FakeSerial(Mobile parent) => 0x7FFFFFFF - 0x400 - 1 - parent.Serial * 4;
}
public sealed class HairEquipUpdate : Packet
{
public HairEquipUpdate(Mobile parent)
: base(0x2E, 15)
{
var hue = parent.SolidHueOverride >= 0 ? parent.SolidHueOverride : parent.HairHue;
Stream.Write(HairInfo.FakeSerial(parent));
Stream.Write((short)parent.HairItemID);
Stream.Write((byte)0);
Stream.Write((byte)Layer.Hair);
Stream.Write(parent.Serial);
Stream.Write((short)hue);
}
}
public sealed class FacialHairEquipUpdate : Packet
{
public FacialHairEquipUpdate(Mobile parent)
: base(0x2E, 15)
{
var hue = parent.SolidHueOverride >= 0 ? parent.SolidHueOverride : parent.FacialHairHue;
Stream.Write(FacialHairInfo.FakeSerial(parent));
Stream.Write((short)parent.FacialHairItemID);
Stream.Write((byte)0);
Stream.Write((byte)Layer.FacialHair);
Stream.Write(parent.Serial);
Stream.Write((short)hue);
}
}
public sealed class RemoveHair : Packet
{
public RemoveHair(Mobile parent)
: base(0x1D, 5)
{
Stream.Write(HairInfo.FakeSerial(parent));
}
}
public sealed class RemoveFacialHair : Packet
{
public RemoveFacialHair(Mobile parent)
: base(0x1D, 5)
{
Stream.Write(FacialHairInfo.FakeSerial(parent));
}
}
}
/***************************************************************************
* VirtualHair.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using Server.Network;
namespace Server
{
public abstract class BaseHairInfo
{
protected BaseHairInfo(int itemid, int hue = 0)
{
ItemID = itemid;
Hue = hue;
}
protected BaseHairInfo(IGenericReader reader)
{
var version = reader.ReadInt();
switch (version)
{
case 0:
{
ItemID = reader.ReadInt();
Hue = reader.ReadInt();
break;
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int ItemID { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public int Hue { get; set; }
public virtual void Serialize(IGenericWriter writer)
{
writer.Write(0); // version
writer.Write(ItemID);
writer.Write(Hue);
}
}
public class HairInfo : BaseHairInfo
{
public HairInfo(int itemid)
: base(itemid)
{
}
public HairInfo(int itemid, int hue)
: base(itemid, hue)
{
}
public HairInfo(IGenericReader reader)
: base(reader)
{
}
// TODO: Can we make this higher for newer clients?
public static uint FakeSerial(Mobile parent) => 0x7FFFFFFF - 0x400 - parent.Serial * 4;
}
public class FacialHairInfo : BaseHairInfo
{
public FacialHairInfo(int itemid)
: base(itemid)
{
}
public FacialHairInfo(int itemid, int hue)
: base(itemid, hue)
{
}
public FacialHairInfo(IGenericReader reader)
: base(reader)
{
}
// TOOD: Can we make this higher for newer clients?
public static uint FakeSerial(Mobile parent) => 0x7FFFFFFF - 0x400 - 1 - parent.Serial * 4;
}
public sealed class HairEquipUpdate : Packet
{
public HairEquipUpdate(Mobile parent)
: base(0x2E, 15)
{
var hue = parent.SolidHueOverride >= 0 ? parent.SolidHueOverride : parent.HairHue;
Stream.Write(HairInfo.FakeSerial(parent));
Stream.Write((short)parent.HairItemID);
Stream.Write((byte)0);
Stream.Write((byte)Layer.Hair);
Stream.Write(parent.Serial);
Stream.Write((short)hue);
}
}
public sealed class FacialHairEquipUpdate : Packet
{
public FacialHairEquipUpdate(Mobile parent)
: base(0x2E, 15)
{
var hue = parent.SolidHueOverride >= 0 ? parent.SolidHueOverride : parent.FacialHairHue;
Stream.Write(FacialHairInfo.FakeSerial(parent));
Stream.Write((short)parent.FacialHairItemID);
Stream.Write((byte)0);
Stream.Write((byte)Layer.FacialHair);
Stream.Write(parent.Serial);
Stream.Write((short)hue);
}
}
public sealed class RemoveHair : Packet
{
public RemoveHair(Mobile parent)
: base(0x1D, 5)
{
Stream.Write(HairInfo.FakeSerial(parent));
}
}
public sealed class RemoveFacialHair : Packet
{
public RemoveFacialHair(Mobile parent)
: base(0x1D, 5)
{
Stream.Write(FacialHairInfo.FakeSerial(parent));
}
}
}

View file

@ -1,42 +1,42 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: IPEndPointConverter.cs *
* Created: 2020/07/03 - Updated: 2020/07/03 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class IPEndPointConverter : JsonConverter<IPEndPoint>
{
public override IPEndPoint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (IPEndPoint.TryParse(reader.GetString(), out var ipep))
return ipep;
throw new JsonException("IPEndPoint must be in the correct format");
}
public override void Write(Utf8JsonWriter writer, IPEndPoint value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString());
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: IPEndPointConverter.cs *
* Created: 2020/07/03 - Updated: 2020/07/03 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class IPEndPointConverter : JsonConverter<IPEndPoint>
{
public override IPEndPoint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (IPEndPoint.TryParse(reader.GetString(), out var ipep))
return ipep;
throw new JsonException("IPEndPoint must be in the correct format");
}
public override void Write(Utf8JsonWriter writer, IPEndPoint value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString());
}
}

View file

@ -1,35 +1,36 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: IPEndPointConverterFactory.cs *
* Created: 2020/07/03 - Updated: 2020/07/03 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class IPEndPointConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(IPEndPoint);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => new IPEndPointConverter();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: IPEndPointConverterFactory.cs *
* Created: 2020/07/03 - Updated: 2020/07/03 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class IPEndPointConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(IPEndPoint);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new IPEndPointConverter();
}
}

View file

@ -1,35 +1,35 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MapConverter.cs - Created: 2020/04/12 - Updated: 2020/05/02 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class MapConverter : JsonConverter<Map>
{
public override Map Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> Map.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, Map value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.Name);
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MapConverter.cs - Created: 2020/04/12 - Updated: 2020/05/02 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class MapConverter : JsonConverter<Map>
{
public override Map Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> Map.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, Map value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.Name);
}
}

View file

@ -1,34 +1,35 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MapConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class MapConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Map);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => new MapConverter();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: MapConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class MapConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Map);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new MapConverter();
}
}

View file

@ -1,105 +1,105 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point2DConverter.cs *
* Created: 2020/04/12 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point2DConverter : JsonConverter<Point2D>
{
private Point2D DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[2];
var count = 0;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 2)
data[count] = reader.GetInt32();
count++;
}
}
if (count > 2)
throw new JsonException("Point2D must be an array of x, y");
return new Point2D(data[0], data[1]);
}
private Point2D DeserializeObj(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[2];
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid json structure for Point2D object");
var key = reader.GetString();
var i = key switch
{
"x" => 0,
"y" => 1,
_ => throw new JsonException($"Invalid property {key} for Point2D")
};
reader.Read();
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException($"Value for {key} must be a number");
data[i] = reader.GetInt32();
}
return new Point2D(data[0], data[1]);
}
public override Point2D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, Point2D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteEndArray();
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point2DConverter.cs *
* Created: 2020/04/12 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point2DConverter : JsonConverter<Point2D>
{
private Point2D DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[2];
var count = 0;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 2)
data[count] = reader.GetInt32();
count++;
}
}
if (count > 2)
throw new JsonException("Point2D must be an array of x, y");
return new Point2D(data[0], data[1]);
}
private Point2D DeserializeObj(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[2];
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid json structure for Point2D object");
var key = reader.GetString();
var i = key switch
{
"x" => 0,
"y" => 1,
_ => throw new JsonException($"Invalid property {key} for Point2D")
};
reader.Read();
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException($"Value for {key} must be a number");
data[i] = reader.GetInt32();
}
return new Point2D(data[0], data[1]);
}
public override Point2D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, Point2D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteEndArray();
}
}
}

View file

@ -1,34 +1,36 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point2DConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point2DConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Point2D) || typeToConvert == typeof(IPoint2D);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => new Point2DConverter();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point2DConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point2DConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) =>
typeToConvert == typeof(Point2D) || typeToConvert == typeof(IPoint2D);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new Point2DConverter();
}
}

View file

@ -1,107 +1,107 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3DConverter.cs *
* Created: 2020/04/12 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point3DConverter : JsonConverter<Point3D>
{
private Point3D DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[3];
var count = 0;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 3)
data[count] = reader.GetInt32();
count++;
}
}
if (count > 3)
throw new JsonException("Point3D must be an array of x, y, z");
return new Point3D(data[0], data[1], data[2]);
}
private Point3D DeserializeObj(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[3];
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid json structure for Point3D object");
var key = reader.GetString();
var i = key switch
{
"x" => 0,
"y" => 1,
"z" => 2,
_ => throw new JsonException($"Invalid property {key} for Point3D")
};
reader.Read();
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException($"Value for {key} must be a number");
data[i] = reader.GetInt32();
}
return new Point3D(data[0], data[1], data[2]);
}
public override Point3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, Point3D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteNumberValue(value.Z);
writer.WriteEndArray();
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3DConverter.cs *
* Created: 2020/04/12 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point3DConverter : JsonConverter<Point3D>
{
private Point3D DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[3];
var count = 0;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 3)
data[count] = reader.GetInt32();
count++;
}
}
if (count > 3)
throw new JsonException("Point3D must be an array of x, y, z");
return new Point3D(data[0], data[1], data[2]);
}
private Point3D DeserializeObj(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[3];
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid json structure for Point3D object");
var key = reader.GetString();
var i = key switch
{
"x" => 0,
"y" => 1,
"z" => 2,
_ => throw new JsonException($"Invalid property {key} for Point3D")
};
reader.Read();
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException($"Value for {key} must be a number");
data[i] = reader.GetInt32();
}
return new Point3D(data[0], data[1], data[2]);
}
public override Point3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, Point3D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteNumberValue(value.Z);
writer.WriteEndArray();
}
}
}

View file

@ -1,34 +1,36 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3DConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point3DConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Point3D) || typeToConvert == typeof(IPoint3D);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => new Point3DConverter();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3DConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Point3DConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) =>
typeToConvert == typeof(Point3D) || typeToConvert == typeof(IPoint3D);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new Point3DConverter();
}
}

View file

@ -1,156 +1,156 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle3DConverter.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Rectangle3DConverter : JsonConverter<Rectangle3D>
{
private Rectangle3D DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[6];
var count = 0;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 6)
data[count] = reader.GetInt32();
count++;
}
}
if (count > 6)
throw new JsonException("Rectangle3D must be an array of x, y, z, h, w, d");
return new Rectangle3D(data[0], data[1], data[2], data[3], data[4], data[5]);
}
private Rectangle3D DeserializeObj(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
Span<int> data = stackalloc int[6];
// 0 - xyzwhd, 1 - x1y1z1x2y2z2, 2 - start/end
int objType = -1;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid json structure for Rectangle3D object");
var key = reader.GetString();
reader.Read();
if (key == "start" || key == "end")
{
if (objType > -1 && objType != 2)
throw new JsonException("Rectangle3D must have a start/end, or x/y/z/w/h/d, but not both.");
objType = 2;
var point3D = reader.ToObject<Point3D>(options);
var offset = key == "end" ? 3 : 0;
data[0 + offset] = point3D.X;
data[1 + offset] = point3D.Y;
data[1 + offset] = point3D.Z;
continue;
}
var i = key switch
{
"x" => 0,
"y" => 1,
"z" => 2,
"w" => 3,
"width" => 3,
"h" => 4,
"height" => 4,
"d" => 5,
"depth" => 5,
"x1" => 10,
"y1" => 11,
"z1" => 12,
"x2" => 13,
"y2" => 14,
"z2" => 15,
_ => throw new JsonException($"Invalid property {key} for Rectangle3D")
};
if (i < 10)
{
if (objType > -1 && objType != 0)
throw new JsonException("Rectangle3D must have a start/end, or x/y/z/w/h/d, but not both.");
objType = 0;
data[i] = reader.GetInt32();
continue;
}
if (objType > -1 && objType != 1)
throw new JsonException("Rectangle3D must have a start/end, or x/y/z/w/h/d, but not both.");
objType = 1;
data[i - 10] = reader.GetInt32();
}
return objType == 0
? new Rectangle3D(data[0], data[1], data[2], data[3], data[4], data[5])
: new Rectangle3D(
new Point3D(data[0], data[1], data[2]),
new Point3D(data[3], data[4], data[5])
);
}
public override Rectangle3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader, options),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, Rectangle3D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.Start.X);
writer.WriteNumberValue(value.Start.Y);
writer.WriteNumberValue(value.Start.Z);
writer.WriteNumberValue(value.Width);
writer.WriteNumberValue(value.Height);
writer.WriteNumberValue(value.Depth);
writer.WriteEndArray();
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle3DConverter.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Rectangle3DConverter : JsonConverter<Rectangle3D>
{
private Rectangle3D DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[6];
var count = 0;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 6)
data[count] = reader.GetInt32();
count++;
}
}
if (count > 6)
throw new JsonException("Rectangle3D must be an array of x, y, z, h, w, d");
return new Rectangle3D(data[0], data[1], data[2], data[3], data[4], data[5]);
}
private Rectangle3D DeserializeObj(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
Span<int> data = stackalloc int[6];
// 0 - xyzwhd, 1 - x1y1z1x2y2z2, 2 - start/end
var objType = -1;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid json structure for Rectangle3D object");
var key = reader.GetString();
reader.Read();
if (key == "start" || key == "end")
{
if (objType > -1 && objType != 2)
throw new JsonException("Rectangle3D must have a start/end, or x/y/z/w/h/d, but not both.");
objType = 2;
var point3D = reader.ToObject<Point3D>(options);
var offset = key == "end" ? 3 : 0;
data[0 + offset] = point3D.X;
data[1 + offset] = point3D.Y;
data[1 + offset] = point3D.Z;
continue;
}
var i = key switch
{
"x" => 0,
"y" => 1,
"z" => 2,
"w" => 3,
"width" => 3,
"h" => 4,
"height" => 4,
"d" => 5,
"depth" => 5,
"x1" => 10,
"y1" => 11,
"z1" => 12,
"x2" => 13,
"y2" => 14,
"z2" => 15,
_ => throw new JsonException($"Invalid property {key} for Rectangle3D")
};
if (i < 10)
{
if (objType > -1 && objType != 0)
throw new JsonException("Rectangle3D must have a start/end, or x/y/z/w/h/d, but not both.");
objType = 0;
data[i] = reader.GetInt32();
continue;
}
if (objType > -1 && objType != 1)
throw new JsonException("Rectangle3D must have a start/end, or x/y/z/w/h/d, but not both.");
objType = 1;
data[i - 10] = reader.GetInt32();
}
return objType == 0
? new Rectangle3D(data[0], data[1], data[2], data[3], data[4], data[5])
: new Rectangle3D(
new Point3D(data[0], data[1], data[2]),
new Point3D(data[3], data[4], data[5])
);
}
public override Rectangle3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader, options),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, Rectangle3D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.Start.X);
writer.WriteNumberValue(value.Start.Y);
writer.WriteNumberValue(value.Start.Z);
writer.WriteNumberValue(value.Width);
writer.WriteNumberValue(value.Height);
writer.WriteNumberValue(value.Depth);
writer.WriteEndArray();
}
}
}

View file

@ -1,35 +1,35 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle3DConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Rectangle3DConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Rectangle3D);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new Rectangle3DConverter();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Rectangle3DConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class Rectangle3DConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Rectangle3D);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new Rectangle3DConverter();
}
}

View file

@ -1,36 +1,36 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TimeSpanConverter.cs *
* Created: 2020/04/12 - Updated: 2020/05/02 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class TimeSpanConverter : JsonConverter<TimeSpan>
{
public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> TimeSpan.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString());
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TimeSpanConverter.cs *
* Created: 2020/04/12 - Updated: 2020/05/02 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class TimeSpanConverter : JsonConverter<TimeSpan>
{
public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> TimeSpan.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString());
}
}

View file

@ -1,34 +1,35 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TimeSpanConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class TimeSpanConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(TimeSpan);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => new TimeSpanConverter();
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TimeSpanConverterFactory.cs *
* Created: 2020/05/23 - Updated: 2020/05/23 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class TimeSpanConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(TimeSpan);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
new TimeSpanConverter();
}
}

View file

@ -1,160 +1,160 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: WorldLocationConverter.cs *
* Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class WorldLocationConverter : JsonConverter<WorldLocation>
{
private WorldLocation DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[3];
var count = 0;
bool hasMap = false;
Map map = null;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 3)
data[count] = reader.GetInt32();
else if (count == 3)
map = Map.Maps[reader.GetInt32()];
count++;
}
if (reader.TokenType == JsonTokenType.String)
{
map = Map.Parse(reader.GetString());
break;
}
}
if (!hasMap || count < 3 || count > 4)
throw new JsonException("WorldLocation must be an array of x, y, z, and map");
return new WorldLocation(data[0], data[1], data[2], map);
}
private WorldLocation DeserializeObj(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
Span<int> data = stackalloc int[3];
int count = 0;
bool hasLoc = false;
bool hasXYZ = false;
bool hasMap = false;
Map map = null;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid Json structure for WorldLocation object");
var key = reader.GetString();
var i = key switch
{
"x" => 0,
"y" => 1,
"z" => 2,
"loc" => 3,
"map" => 4,
_ => 5
};
if (i == 5)
continue;
reader.Read();
if (i < 3)
{
if (hasLoc)
throw new JsonException("WorldLocation must have loc or x, y, z, but not both");
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException($"Value for {key} must be a number");
hasXYZ = true;
data[i] = reader.GetInt32();
continue;
}
if (i == 3)
{
if (hasXYZ)
throw new JsonException("WorldLocation must have loc or x, y, z, but not both");
hasLoc = true;
Point3D loc = new Point3DConverter().Read(ref reader, typeof(Point3D), options);
data[0] = loc.X;
data[1] = loc.Y;
data[2] = loc.Z;
count = 3;
continue;
}
map = reader.TokenType switch
{
JsonTokenType.String => Map.Parse(reader.GetString()),
JsonTokenType.Number => Map.Maps[reader.GetInt32()],
_ => throw new JsonException($"Value for {key} must be a number or string")
};
}
if (!hasMap || count < 2)
throw new JsonException("WorldLocation must have an x, y, z, and map properties");
return new WorldLocation(data[0], data[1], data[2], map);
}
public override WorldLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader, options),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, WorldLocation value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteNumberValue(value.Z);
writer.WriteStringValue(value.Map.ToString());
writer.WriteEndArray();
}
}
}
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: WorldLocationConverter.cs *
* Created: 2020/05/31 - Updated: 2020/05/31 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Json
{
public class WorldLocationConverter : JsonConverter<WorldLocation>
{
private WorldLocation DeserializeArray(ref Utf8JsonReader reader)
{
Span<int> data = stackalloc int[3];
var count = 0;
var hasMap = false;
Map map = null;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType == JsonTokenType.Number)
{
if (count < 3)
data[count] = reader.GetInt32();
else if (count == 3)
map = Map.Maps[reader.GetInt32()];
count++;
}
if (reader.TokenType == JsonTokenType.String)
{
map = Map.Parse(reader.GetString());
break;
}
}
if (!hasMap || count < 3 || count > 4)
throw new JsonException("WorldLocation must be an array of x, y, z, and map");
return new WorldLocation(data[0], data[1], data[2], map);
}
private WorldLocation DeserializeObj(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
Span<int> data = stackalloc int[3];
var count = 0;
var hasLoc = false;
var hasXYZ = false;
var hasMap = false;
Map map = null;
while (true)
{
reader.Read();
if (reader.TokenType == JsonTokenType.EndObject)
break;
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Invalid Json structure for WorldLocation object");
var key = reader.GetString();
var i = key switch
{
"x" => 0,
"y" => 1,
"z" => 2,
"loc" => 3,
"map" => 4,
_ => 5
};
if (i == 5)
continue;
reader.Read();
if (i < 3)
{
if (hasLoc)
throw new JsonException("WorldLocation must have loc or x, y, z, but not both");
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException($"Value for {key} must be a number");
hasXYZ = true;
data[i] = reader.GetInt32();
continue;
}
if (i == 3)
{
if (hasXYZ)
throw new JsonException("WorldLocation must have loc or x, y, z, but not both");
hasLoc = true;
var loc = new Point3DConverter().Read(ref reader, typeof(Point3D), options);
data[0] = loc.X;
data[1] = loc.Y;
data[2] = loc.Z;
count = 3;
continue;
}
map = reader.TokenType switch
{
JsonTokenType.String => Map.Parse(reader.GetString()),
JsonTokenType.Number => Map.Maps[reader.GetInt32()],
_ => throw new JsonException($"Value for {key} must be a number or string")
};
}
if (!hasMap || count < 2)
throw new JsonException("WorldLocation must have an x, y, z, and map properties");
return new WorldLocation(data[0], data[1], data[2], map);
}
public override WorldLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.StartArray => DeserializeArray(ref reader),
JsonTokenType.StartObject => DeserializeObj(ref reader, options),
_ => throw new JsonException("Invalid Json for Point3D")
};
public override void Write(Utf8JsonWriter writer, WorldLocation value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteNumberValue(value.Z);
writer.WriteStringValue(value.Map.ToString());
writer.WriteEndArray();
}
}
}

Some files were not shown because too many files have changed in this diff Show more