diff --git a/Projects/Scripts/Accounting/Accounts.cs b/Projects/Scripts/Accounting/Accounts.cs index d5d01b165..c00abd807 100644 --- a/Projects/Scripts/Accounting/Accounts.cs +++ b/Projects/Scripts/Accounting/Accounts.cs @@ -21,7 +21,7 @@ namespace Server.Accounting EventSink.WorldSave += Save; } - public static ICollection GetAccounts() => m_Accounts.Values; + public static IEnumerable GetAccounts() => m_Accounts.Values; public static IAccount GetAccount(string username) { diff --git a/Projects/Scripts/Commands/Add.cs b/Projects/Scripts/Commands/Add.cs index 60e144037..0f4fd118d 100644 --- a/Projects/Scripts/Commands/Add.cs +++ b/Projects/Scripts/Commands/Add.cs @@ -426,7 +426,7 @@ namespace Server.Commands from.SendMessage(sb.ToString()); } - private static void TileBox_Callback(Mobile from, Map map, Point3D start, Point3D end, TileState ts) + private static void TileBox_Callback(Mobile from, Point3D start, Point3D end, TileState ts) { bool mapAvg = false; @@ -453,7 +453,7 @@ namespace Server.Commands if (e.Length >= 1) BoundingBoxPicker.Begin(from, (map, start, end) => - TileBox_Callback(from, map, start, end, new TileState(TileZType.Start, 0, e.Arguments, outline))); + TileBox_Callback(from, start, end, new TileState(TileZType.Start, 0, e.Arguments, outline))); else from.SendMessage("Format: {0} [params] [set {{ ...}}]", outline ? "Outline" : "Tile"); @@ -515,7 +515,7 @@ namespace Server.Commands subArgs[i] = e.Arguments[i + 1]; BoundingBoxPicker.Begin(from, (map, start, end) => - TileBox_Callback(from, map, start, end, new TileState(TileZType.Fixed, e.GetInt32(0), subArgs, outline))); + TileBox_Callback(from, start, end, new TileState(TileZType.Fixed, e.GetInt32(0), subArgs, outline))); } else { @@ -530,7 +530,7 @@ namespace Server.Commands if (e.Length >= 1) BoundingBoxPicker.Begin(from, (map, start, end) => - TileBox_Callback(from, map, start, end, new TileState(TileZType.MapAverage, 0, e.Arguments, outline))); + TileBox_Callback(from, start, end, new TileState(TileZType.MapAverage, 0, e.Arguments, outline))); else from.SendMessage("Format: {0}Avg [params] [set {{ ...}}]", outline ? "Outline" : "Tile"); diff --git a/Projects/Scripts/Commands/Decorate.cs b/Projects/Scripts/Commands/Decorate.cs index 5475fb6eb..a326c8ca9 100644 --- a/Projects/Scripts/Commands/Decorate.cs +++ b/Projects/Scripts/Commands/Decorate.cs @@ -931,8 +931,7 @@ namespace Server.Commands for (int j = 0; j < maps.Length; ++j) { - if (item == null) - item = Construct(); + item ??= Construct(); if (item == null) continue; diff --git a/Projects/Scripts/Commands/DecorateMag.cs b/Projects/Scripts/Commands/DecorateMag.cs index 38997aaad..ebc8ff146 100644 --- a/Projects/Scripts/Commands/DecorateMag.cs +++ b/Projects/Scripts/Commands/DecorateMag.cs @@ -929,8 +929,7 @@ namespace Server.Commands for (int j = 0; j < maps.Length; ++j) { - if (item == null) - item = Construct(); + item ??= Construct(); if (item == null) continue; diff --git a/Projects/Scripts/Commands/Docs.cs b/Projects/Scripts/Commands/Docs.cs index c0e1fd763..c5aff2b29 100644 --- a/Projects/Scripts/Commands/Docs.cs +++ b/Projects/Scripts/Commands/Docs.cs @@ -82,8 +82,7 @@ namespace Server.Commands if (baseInfo == null) m_Types[baseType] = baseInfo = new TypeInfo(baseType); - if (baseInfo.m_Derived == null) - baseInfo.m_Derived = new List(); + baseInfo.m_Derived ??= new List(); baseInfo.m_Derived.Add(info); } @@ -97,8 +96,7 @@ namespace Server.Commands if (decInfo == null) m_Types[decType] = decInfo = new TypeInfo(decType); - if (decInfo.m_Nested == null) - decInfo.m_Nested = new List(); + decInfo.m_Nested ??= new List(); decInfo.m_Nested.Add(info); } @@ -115,8 +113,7 @@ namespace Server.Commands if (ifaceInfo == null) m_Types[iface] = ifaceInfo = new TypeInfo(iface); - if (ifaceInfo.m_Derived == null) - ifaceInfo.m_Derived = new List(); + ifaceInfo.m_Derived ??= new List(); ifaceInfo.m_Derived.Add(info); } @@ -265,20 +262,13 @@ namespace Server.Commands typeName = name ?? type.Name; - if (fnam == null) fileName = $"docs/types/{SanitizeType(type.Name)}.html"; - else fileName = $"{fnam}.html"; + fileName = fnam == null ? $"docs/types/{SanitizeType(type.Name)}.html" : $"{fnam}.html"; if (link == null) - { - if (DontLink(type)) //if ( DontLink( type.Name ) ) - linkName = $"{SanitizeType(type.Name)}"; - else - linkName = $"{SanitizeType(type.Name)}"; - } + linkName = DontLink(type) ? $"{SanitizeType(type.Name)}" + : $"{SanitizeType(type.Name)}"; else - { linkName = link; - } //Console.WriteLine( typeName+":"+fileName+":"+linkName ); } @@ -604,8 +594,7 @@ namespace Server.Commands } } - if (aliased == null) - aliased = realType?.Name ?? ""; + aliased ??= realType?.Name ?? ""; } return string.Concat(prepend, aliased, append, name); diff --git a/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs b/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs index 6db1c7a08..b47e8001a 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs @@ -160,8 +160,8 @@ namespace Server.Commands.Generic FieldAttributes.Private | FieldAttributes.InitOnly ); -// parseMethod.Invoke(null, -// parseArgs.Length == 2 ? new object[] {toParse, (int) parseArgs[1]} : new object[] {toParse}); + // parseMethod.Invoke(null, + // parseArgs.Length == 2 ? new object[] {toParse, (int) parseArgs[1]} : new object[] {toParse}); il.Emit(OpCodes.Ldarg_0); diff --git a/Projects/Scripts/Commands/Generic/Extensions/Compilers/DistinctCompiler.cs b/Projects/Scripts/Commands/Generic/Extensions/Compilers/DistinctCompiler.cs index b12cfac41..ea88b6ce5 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/Compilers/DistinctCompiler.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/Compilers/DistinctCompiler.cs @@ -192,8 +192,7 @@ namespace Server.Commands.Generic MethodInfo getHashCode = active.GetMethod("GetHashCode", Type.EmptyTypes); - if (getHashCode == null) - getHashCode = typeof(T).GetMethod("GetHashCode", Type.EmptyTypes); + getHashCode ??= typeof(T).GetMethod("GetHashCode", Type.EmptyTypes); if (active != typeof(int)) { @@ -256,4 +255,4 @@ namespace Server.Commands.Generic return (IComparer)Activator.CreateInstance(comparerType); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs b/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs index 682f4681c..cc3fcf846 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs @@ -32,8 +32,7 @@ namespace Server.Commands.Generic prop.CheckAccess(from); } - if (assembly == null) - assembly = new AssemblyEmitter("__dynamic"); + assembly ??= new AssemblyEmitter("__dynamic"); m_Comparer = DistinctCompiler.Compile(assembly, baseType, m_Properties.ToArray()); } diff --git a/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs b/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs index 5f2684cdb..63a7c1c03 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs @@ -31,8 +31,7 @@ namespace Server.Commands.Generic order.Property.CheckAccess(from); } - if (assembly == null) - assembly = new AssemblyEmitter("__dynamic"); + assembly ??= new AssemblyEmitter("__dynamic"); m_Comparer = SortCompiler.Compile(assembly, baseType, m_Orders.ToArray()); } diff --git a/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs b/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs index 72519c9c5..6124e0e34 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs @@ -30,8 +30,7 @@ namespace Server.Commands.Generic public void Compile(ref AssemblyEmitter emitter) { - if (emitter == null) - emitter = new AssemblyEmitter("__dynamic"); + emitter ??= new AssemblyEmitter("__dynamic"); m_Conditionals = new IConditional[m_Conditions.Length]; diff --git a/Projects/Scripts/Commands/Properties.cs b/Projects/Scripts/Commands/Properties.cs index 60ed30a2f..b04d71b77 100644 --- a/Projects/Scripts/Commands/Properties.cs +++ b/Projects/Scripts/Commands/Properties.cs @@ -382,7 +382,7 @@ namespace Server.Commands if (IsEnum(type)) try { - toSet = Enum.Parse(type, value, true); + toSet = Enum.Parse(type, value ?? "", true); } catch { diff --git a/Projects/Scripts/Engines/BulkOrders/Books/BOBLargeSubEntry.cs b/Projects/Scripts/Engines/BulkOrders/Books/BOBLargeSubEntry.cs index 6b3af0caa..da36719dd 100644 --- a/Projects/Scripts/Engines/BulkOrders/Books/BOBLargeSubEntry.cs +++ b/Projects/Scripts/Engines/BulkOrders/Books/BOBLargeSubEntry.cs @@ -46,7 +46,7 @@ namespace Server.Engines.BulkOrders { writer.WriteEncodedInt(0); // version - writer.Write(ItemType == null ? null : ItemType.FullName); + writer.Write(ItemType?.FullName); writer.WriteEncodedInt(AmountCur); writer.WriteEncodedInt(Number); diff --git a/Projects/Scripts/Engines/BulkOrders/Books/BOBSmallEntry.cs b/Projects/Scripts/Engines/BulkOrders/Books/BOBSmallEntry.cs index 60713aaa1..a4f9c865a 100644 --- a/Projects/Scripts/Engines/BulkOrders/Books/BOBSmallEntry.cs +++ b/Projects/Scripts/Engines/BulkOrders/Books/BOBSmallEntry.cs @@ -84,7 +84,7 @@ namespace Server.Engines.BulkOrders { writer.WriteEncodedInt(0); // version - writer.Write(ItemType == null ? null : ItemType.FullName); + writer.Write(ItemType?.FullName); writer.Write(RequireExceptional); diff --git a/Projects/Scripts/Engines/BulkOrders/LargeBulkEntry.cs b/Projects/Scripts/Engines/BulkOrders/LargeBulkEntry.cs index 87ae14ed0..7aa70f639 100644 --- a/Projects/Scripts/Engines/BulkOrders/LargeBulkEntry.cs +++ b/Projects/Scripts/Engines/BulkOrders/LargeBulkEntry.cs @@ -66,8 +66,7 @@ namespace Server.Engines.BulkOrders public static SmallBulkEntry[] GetEntries( string type, string name ) { - if (m_Cache == null) - m_Cache = new Dictionary>(); + m_Cache ??= new Dictionary>(); if (!m_Cache.TryGetValue( type, out Dictionary table )) m_Cache[type] = table = new Dictionary(); @@ -112,7 +111,7 @@ namespace Server.Engines.BulkOrders public void Serialize(IGenericWriter writer ) { writer.Write( m_Amount ); - writer.Write( Details.Type == null ? null : Details.Type.FullName ); + writer.Write( Details.Type?.FullName ); writer.Write( Details.Number ); writer.Write( Details.Graphic ); } diff --git a/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs b/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs index 9a8c93cac..055b873c8 100644 --- a/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs +++ b/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs @@ -19,7 +19,6 @@ namespace Server.Engines.BulkOrders switch (Utility.Random(14)) { default: - case 0: entries = LargeBulkEntry.ConvertEntries(this, LargeBulkEntry.Farmer); break; case 1: diff --git a/Projects/Scripts/Engines/BulkOrders/Rewards.cs b/Projects/Scripts/Engines/BulkOrders/Rewards.cs index c427bb54f..9b20f201f 100644 --- a/Projects/Scripts/Engines/BulkOrders/Rewards.cs +++ b/Projects/Scripts/Engines/BulkOrders/Rewards.cs @@ -357,7 +357,13 @@ namespace Server.Engines.BulkOrders int[][][] goldTable = m_GoldTable; int typeIndex = ComputeType(type, itemCount); - int quanIndex = quantity == 20 ? 2 : quantity == 15 ? 1 : 0; + int quanIndex = quantity switch + { + 20 => 2, + 15 => 1, + _ => 0 + }; + int mtrlIndex = material >= BulkMaterialType.DullCopper && material <= BulkMaterialType.Valorite ? 1 + (material - BulkMaterialType.DullCopper) : 0; @@ -599,11 +605,28 @@ namespace Server.Engines.BulkOrders { int[][][] goldTable = Core.AOS ? m_AosGoldTable : m_OldGoldTable; - int typeIndex = (itemCount == 6 ? 3 : itemCount == 5 ? 2 : itemCount == 4 ? 1 : 0) * 2 + (exceptional ? 1 : 0); - int quanIndex = quantity == 20 ? 2 : quantity == 15 ? 1 : 0; - int mtrlIndex = material == BulkMaterialType.Barbed ? 3 : - material == BulkMaterialType.Horned ? 2 : - material == BulkMaterialType.Spined ? 1 : 0; + int typeIndex = itemCount switch + { + 6 => 3, + 5 => 2, + 4 => 1, + _ => 0 + } * 2 + (exceptional ? 1 : 0); + + int quanIndex = quantity switch + { + 20 => 2, + 15 => 1, + _ => 0 + }; + + int mtrlIndex = material switch + { + BulkMaterialType.Barbed => 3, + BulkMaterialType.Horned => 2, + BulkMaterialType.Spined => 1, + _ => 0 + }; int gold = goldTable[typeIndex][quanIndex][mtrlIndex]; diff --git a/Projects/Scripts/Engines/BulkOrders/SmallBOD.cs b/Projects/Scripts/Engines/BulkOrders/SmallBOD.cs index f1ff16236..ac5b47c55 100644 --- a/Projects/Scripts/Engines/BulkOrders/SmallBOD.cs +++ b/Projects/Scripts/Engines/BulkOrders/SmallBOD.cs @@ -180,7 +180,7 @@ namespace Server.Engines.BulkOrders writer.Write(0); // version writer.Write(m_AmountCur); - writer.Write(Type == null ? null : Type.FullName); + writer.Write(Type?.FullName); writer.Write(m_Number); writer.Write(Graphic); } diff --git a/Projects/Scripts/Engines/BulkOrders/SmallSmithBOD.cs b/Projects/Scripts/Engines/BulkOrders/SmallSmithBOD.cs index c4d44f0d4..381699c2d 100644 --- a/Projects/Scripts/Engines/BulkOrders/SmallSmithBOD.cs +++ b/Projects/Scripts/Engines/BulkOrders/SmallSmithBOD.cs @@ -135,7 +135,7 @@ namespace Server.Engines.BulkOrders if (item != null) { bool allRequiredSkills = true; - double chance = item.GetSuccessChance(m, null, system, false, ref allRequiredSkills); + double chance = item.GetSuccessChance(m, null, system, false, out allRequiredSkills); if (allRequiredSkills && chance >= 0.0) { diff --git a/Projects/Scripts/Engines/BulkOrders/SmallTailorBOD.cs b/Projects/Scripts/Engines/BulkOrders/SmallTailorBOD.cs index 6340753f8..f860413df 100644 --- a/Projects/Scripts/Engines/BulkOrders/SmallTailorBOD.cs +++ b/Projects/Scripts/Engines/BulkOrders/SmallTailorBOD.cs @@ -133,7 +133,7 @@ namespace Server.Engines.BulkOrders if (item != null) { bool allRequiredSkills = true; - double chance = item.GetSuccessChance(m, null, system, false, ref allRequiredSkills); + double chance = item.GetSuccessChance(m, null, system, false, out allRequiredSkills); if (allRequiredSkills && chance >= 0.0) { diff --git a/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs b/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs index 5b5504e34..daf1de5b1 100644 --- a/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs +++ b/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs @@ -331,12 +331,10 @@ namespace Server.Engines.CannedEvil killer.SendLocalizedMessage(1049524); // You have received a scroll of power! if (killer.Alive) - { killer.AddToBackpack(scroll); - } else { - if (killer?.Corpse.Deleted == false) + if (killer.Corpse.Deleted == false) killer.Corpse.DropItem(scroll); else killer.AddToBackpack(scroll); diff --git a/Projects/Scripts/Engines/Chat/Packets.cs b/Projects/Scripts/Engines/Chat/Packets.cs index 3d8bfd563..7ffef69c8 100644 --- a/Projects/Scripts/Engines/Chat/Packets.cs +++ b/Projects/Scripts/Engines/Chat/Packets.cs @@ -6,11 +6,8 @@ namespace Server.Engines.Chat { public ChatMessagePacket(Mobile who, int number, string param1, string param2) : base(0xB2) { - if (param1 == null) - param1 = string.Empty; - - if (param2 == null) - param2 = string.Empty; + param1 ??= string.Empty; + param2 ??= string.Empty; EnsureCapacity(13 + (param1.Length + param2.Length) * 2); @@ -25,4 +22,4 @@ namespace Server.Engines.Chat m_Stream.WriteBigUniNull(param2); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/ConPVP/DuelContext.cs b/Projects/Scripts/Engines/ConPVP/DuelContext.cs index 74a1ab83e..0e14694cb 100644 --- a/Projects/Scripts/Engines/ConPVP/DuelContext.cs +++ b/Projects/Scripts/Engines/ConPVP/DuelContext.cs @@ -163,52 +163,48 @@ namespace Server.Engines.ConPVP string title = null; string option; - if (spell is ArcanistSpell) + switch (spell) { - title = "Spellweaving"; - option = spell.Name; - } - else if (spell is PaladinSpell) - { - title = "Chivalry"; - option = spell.Name; - } - else if (spell is NecromancerSpell) - { - title = "Necromancy"; - option = spell.Name; - } - else if (spell is NinjaSpell) - { - title = "Ninjitsu"; - option = spell.Name; - } - else if (spell is SamuraiSpell) - { - title = "Bushido"; - option = spell.Name; - } - else if (spell is MagerySpell magerySpell) - { - title = magerySpell.Circle switch - { - SpellCircle.First => "1st Circle", - SpellCircle.Second => "2nd Circle", - SpellCircle.Third => "3rd Circle", - SpellCircle.Fourth => "4th Circle", - SpellCircle.Fifth => "5th Circle", - SpellCircle.Sixth => "6th Circle", - SpellCircle.Seventh => "7th Circle", - SpellCircle.Eighth => "8th Circle", - _ => title - }; + case ArcanistSpell _: + title = "Spellweaving"; + option = spell.Name; + break; + case PaladinSpell _: + title = "Chivalry"; + option = spell.Name; + break; + case NecromancerSpell _: + title = "Necromancy"; + option = spell.Name; + break; + case NinjaSpell _: + title = "Ninjitsu"; + option = spell.Name; + break; + case SamuraiSpell _: + title = "Bushido"; + option = spell.Name; + break; + case MagerySpell magerySpell: + title = magerySpell.Circle switch + { + SpellCircle.First => "1st Circle", + SpellCircle.Second => "2nd Circle", + SpellCircle.Third => "3rd Circle", + SpellCircle.Fourth => "4th Circle", + SpellCircle.Fifth => "5th Circle", + SpellCircle.Sixth => "6th Circle", + SpellCircle.Seventh => "7th Circle", + SpellCircle.Eighth => "8th Circle", + _ => null + }; - option = magerySpell.Name; - } - else - { - title = "Other Spell"; - option = spell.Name; + option = magerySpell.Name; + break; + default: + title = "Other Spell"; + option = spell.Name; + break; } if (title == null || option == null || Ruleset.GetOption(title, option)) diff --git a/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs b/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs index 02a56cb8f..42ac03d21 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs @@ -550,19 +550,21 @@ namespace Server.Engines.ConPVP else if (m_Path.Count > 0) MoveToWorld(m_Path.Last); - int myZ = Map.GetAverageZ(X, Y); + int myZ = Map?.GetAverageZ(X, Y) ?? 0; - StaticTile[] statics = Map.Tiles.GetStaticTiles(X, Y, true); - for (int j = 0; j < statics.Length; j++) - { - StaticTile t = statics[j]; + StaticTile[] statics = Map?.Tiles?.GetStaticTiles(X, Y, true); - ItemData id = TileData.ItemTable[t.ID & TileData.MaxItemValue]; - height = id.CalcHeight; + if (statics != null) + for (int j = 0; j < statics.Length; j++) + { + StaticTile t = statics[j]; - if (t.Z + height > myZ && t.Z + height <= Z) - myZ = t.Z + height; - } + ItemData id = TileData.ItemTable[t.ID & TileData.MaxItemValue]; + height = id.CalcHeight; + + if (t.Z + height > myZ && t.Z + height <= Z) + myZ = t.Z + height; + } IPooledEnumerable eable = GetItemsInRange(0); foreach (Item item in eable) @@ -1428,8 +1430,7 @@ namespace Server.Engines.ConPVP { if (m_Bomb != null && Controller != null) { - if (m_UnhideCallback == null) - m_UnhideCallback = UnhideBomb; + m_UnhideCallback ??= UnhideBomb; m_Bomb.Visible = false; m_Bomb.MoveToWorld(Controller.BombHome, Controller.Map); Timer.DelayCall(TimeSpan.FromSeconds(Utility.RandomMinMax(5, 15)), m_UnhideCallback); @@ -1504,7 +1505,7 @@ namespace Server.Engines.ConPVP private void DelayBounce_Callback(Mobile mob, Container corpse) { - DuelPlayer dp = mob is PlayerMobile mobile ? mobile.DuelPlayer : null; + DuelPlayer dp = (mob as PlayerMobile)?.DuelPlayer; m_Context.RemoveAggressions(mob); @@ -1722,7 +1723,9 @@ namespace Server.Engines.ConPVP for (int i = 0; i < m_Context.Participants.Count; ++i) { - if (!(m_Context.Participants[i] is Participant p) || p.Players == null) + Participant p = m_Context.Participants[i]; + + if (p?.Players == null) continue; for (int j = 0; j < p.Players.Length; ++j) @@ -1736,7 +1739,7 @@ namespace Server.Engines.ConPVP } } - if (i == winner.TeamID) + if (i == winner?.TeamID) continue; if (p.Players != null) diff --git a/Projects/Scripts/Engines/ConPVP/Games/CTF.cs b/Projects/Scripts/Engines/ConPVP/Games/CTF.cs index b7e3a55a5..190067c3f 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/CTF.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/CTF.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text; using Server.Gumps; using Server.Items; @@ -113,6 +114,9 @@ namespace Server.Engines.ConPVP { CTFTeamInfo teamInfo = entries[i] as CTFTeamInfo; + if (teamInfo == null) + continue; + AddImage(30, 70 + i * 75, 10152); AddImage(30, 85 + i * 75, 10151); AddImage(30, 100 + i * 75, 10151); @@ -878,7 +882,7 @@ namespace Server.Engines.ConPVP private void DelayBounce_Callback(Mobile mob, Container corpse) { - DuelPlayer dp = mob is PlayerMobile mobile ? mobile.DuelPlayer : null; + DuelPlayer dp = (mob as PlayerMobile)?.DuelPlayer; m_Context.RemoveAggressions(mob); @@ -943,15 +947,8 @@ namespace Server.Engines.ConPVP if (ourFlagCarrier != null && GetTeamInfo(ourFlagCarrier) == teamInfo) { - for (int j = 0; j < ourFlagCarrier.Aggressors.Count; ++j) - { - if (!(ourFlagCarrier.Aggressors[j] is AggressorInfo aggr) || - aggr.Defender != ourFlagCarrier || aggr.Attacker != mob) - continue; - + if (ourFlagCarrier.Aggressors.Any(aggr => aggr.Defender == ourFlagCarrier && aggr.Attacker == mob)) playerInfo.Score += 2; // helped defend guy capturing enemy flag - break; - } if (mob.Map == ourFlagCarrier.Map && ourFlagCarrier.InRange(mob, 12)) playerInfo.Score += 1; // helped defend guy capturing enemy flag @@ -1143,7 +1140,7 @@ namespace Server.Engines.ConPVP } } - if (i == winner.TeamID) + if (i == winner?.TeamID) continue; for (int j = 0; j < p.Players.Length; ++j) @@ -1151,7 +1148,8 @@ namespace Server.Engines.ConPVP p.Players[j].Eliminated = true; } - m_Context.Finish(m_Context.Participants[winner.TeamID]); + if (winner != null) + m_Context.Finish(m_Context.Participants[winner.TeamID]); } public override void OnStop() diff --git a/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs b/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs index 187c7b9ac..4025b0516 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs @@ -521,7 +521,7 @@ namespace Server.Engines.ConPVP private void DelayBounce_Callback(Mobile mob, Container corpse) { - DuelPlayer dp = mob is PlayerMobile mobile ? mobile.DuelPlayer : null; + DuelPlayer dp = (mob as PlayerMobile)?.DuelPlayer; m_Context.RemoveAggressions(mob); diff --git a/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs b/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs index 61cb7c562..d30302da7 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs @@ -171,8 +171,7 @@ namespace Server.Engines.ConPVP King = m; - if (m_KingTimer == null) - m_KingTimer = new KingTimer(this); + m_KingTimer ??= new KingTimer(this); m_KingTimer.Stop(); m_KingTimer.StartHillTicker(); @@ -450,11 +449,7 @@ namespace Server.Engines.ConPVP AddBorderedText(160 + 10, 85 + i * 75, 100, 20, "Captures:", 0xFFC000, BlackColor32); AddBorderedText(160 + 15, 105 + i * 75, 100, 20, teamInfo.Captures.ToString("N0"), 0xFFC000, BlackColor32); - string leader = null; - if (teamInfo.Leader != null) - leader = teamInfo.Leader.Name; - if (leader == null) - leader = "(none)"; + string leader = teamInfo.Leader?.Name ?? "(none)"; AddBorderedText(235 + 10, 85 + i * 75, 250, 20, "Leader:", 0xFFC000, BlackColor32); AddBorderedText(235 + 15, 105 + i * 75, 250, 20, leader, 0xFFC000, BlackColor32); @@ -893,7 +888,7 @@ namespace Server.Engines.ConPVP private void DelayBounce_Callback(Mobile mob, Container corpse) { - DuelPlayer dp = mob is PlayerMobile mobile ? mobile.DuelPlayer : null; + DuelPlayer dp = (mob as PlayerMobile)?.DuelPlayer; m_Context.RemoveAggressions(mob); @@ -1113,7 +1108,8 @@ namespace Server.Engines.ConPVP for (int i = 0; i < m_Context.Participants.Count; ++i) { - if (!(m_Context.Participants[i] is Participant p) || p.Players == null) + Participant p = m_Context.Participants[i]; + if (p.Players == null) continue; for (int j = 0; j < p.Players.Length; ++j) diff --git a/Projects/Scripts/Engines/ConPVP/Gumps/ConfirmSignupGump.cs b/Projects/Scripts/Engines/ConPVP/Gumps/ConfirmSignupGump.cs index 3b527071c..c62c1725a 100644 --- a/Projects/Scripts/Engines/ConPVP/Gumps/ConfirmSignupGump.cs +++ b/Projects/Scripts/Engines/ConPVP/Gumps/ConfirmSignupGump.cs @@ -10,533 +10,533 @@ using Server.Targeting; namespace Server.Engines.ConPVP { -public class ConfirmSignupGump : Gump -{ - private const int BlackColor32 = 0x000008; - private const int LabelColor32 = 0xFFFFFF; - private Mobile m_From; - private List m_Players; - private Mobile m_Registrar; - private Tournament m_Tournament; - - public ConfirmSignupGump(Mobile from, Mobile registrar, Tournament tourney, List players) : base(50, 50) + public class ConfirmSignupGump : Gump { - m_From = from; - m_Registrar = registrar; - m_Tournament = tourney; - m_Players = players; + private const int BlackColor32 = 0x000008; + private const int LabelColor32 = 0xFFFFFF; + private Mobile m_From; + private List m_Players; + private Mobile m_Registrar; + private Tournament m_Tournament; - m_From.CloseGump(); - m_From.CloseGump(); - m_From.CloseGump(); - m_From.CloseGump(); - - #region Rules - - Ruleset ruleset = tourney.Ruleset; - Ruleset basedef = ruleset.Base; - - int height = 185 + 60 + 12; - - int changes = 0; - - BitArray defs; - - if (ruleset.Flavors.Count > 0) + public ConfirmSignupGump(Mobile from, Mobile registrar, Tournament tourney, List players) : base(50, 50) { - defs = new BitArray(basedef.Options); + m_From = from; + m_Registrar = registrar; + m_Tournament = tourney; + m_Players = players; - for (int i = 0; i < ruleset.Flavors.Count; ++i) - defs.Or(ruleset.Flavors[i].Options); + m_From.CloseGump(); + m_From.CloseGump(); + m_From.CloseGump(); + m_From.CloseGump(); - height += ruleset.Flavors.Count * 18; - } - else - { - defs = basedef.Options; - } + #region Rules - BitArray opts = ruleset.Options; + Ruleset ruleset = tourney.Ruleset; + Ruleset basedef = ruleset.Base; - for (int i = 0; i < opts.Length; ++i) - if (defs[i] != opts[i]) - ++changes; + int height = 185 + 60 + 12; - height += changes * 22; + int changes = 0; - height += 10 + 22 + 25 + 25; + BitArray defs; - if (tourney.PlayersPerParticipant > 1) - height += 36 + tourney.PlayersPerParticipant * 20; - - #endregion - - Closable = false; - - AddPage(0); - - //AddBackground( 0, 0, 400, 220, 9150 ); - AddBackground(1, 1, 398, height, 3600); - //AddBackground( 16, 15, 369, 189, 9100 ); - - AddImageTiled(16, 15, 369, height - 29, 3604); - AddAlphaRegion(16, 15, 369, height - 29); - - AddImage(215, -43, 0xEE40); - //AddImage( 330, 141, 0x8BA ); - - StringBuilder sb = new StringBuilder(); - - if (tourney.TourneyType == TourneyType.FreeForAll) - { - sb.Append("FFA"); - } - else if (tourney.TourneyType == TourneyType.RandomTeam) - { - sb.Append(tourney.ParticipantsPerMatch); - sb.Append("-Team"); - } - else if (tourney.TourneyType == TourneyType.Faction) - { - sb.Append(tourney.ParticipantsPerMatch); - sb.Append("-Team Faction"); - } - else if (tourney.TourneyType == TourneyType.RedVsBlue) - { - sb.Append("Red v Blue"); - } - else - { - for (int i = 0; i < tourney.ParticipantsPerMatch; ++i) + if (ruleset.Flavors.Count > 0) { - if (sb.Length > 0) - sb.Append('v'); + defs = new BitArray(basedef.Options); - sb.Append(tourney.PlayersPerParticipant); + for (int i = 0; i < ruleset.Flavors.Count; ++i) + defs.Or(ruleset.Flavors[i].Options); + + height += ruleset.Flavors.Count * 18; } - } - - if (tourney.EventController != null) - sb.Append(' ').Append(tourney.EventController.Title); - - sb.Append(" Tournament Signup"); - - AddBorderedText(22, 22, 294, 20, Center(sb.ToString()), LabelColor32, BlackColor32); - AddBorderedText(22, 50, 294, 40, "You have requested to join the tournament. Do you accept the rules?", 0xB0C868, - BlackColor32); - - AddImageTiled(32, 88, 264, 1, 9107); - AddImageTiled(42, 90, 264, 1, 9157); - - #region Rules - - int y = 100; - - var groupText = tourney.GroupType switch - { - GroupingType.HighVsLow => "High vs Low", - GroupingType.Nearest => "Closest opponent", - GroupingType.Random => "Random", - _ => null - }; - - AddBorderedText(35, y, 190, 20, $"Grouping: {groupText}", LabelColor32, BlackColor32); - y += 20; - - var tieText = tourney.TieType switch - { - TieType.Random => "Random", - TieType.Highest => "Highest advances", - TieType.Lowest => "Lowest advances", - TieType.FullAdvancement => (tourney.ParticipantsPerMatch == 2 ? "Both advance" : "Everyone advances"), - TieType.FullElimination => (tourney.ParticipantsPerMatch == 2 ? "Both eliminated" : "Everyone eliminated"), - _ => null - }; - - AddBorderedText(35, y, 190, 20, $"Tiebreaker: {tieText}", LabelColor32, BlackColor32); - y += 20; - - string sdText = "Off"; - - if (tourney.SuddenDeath > TimeSpan.Zero) - { - sdText = $"{(int)tourney.SuddenDeath.TotalMinutes}:{tourney.SuddenDeath.Seconds:D2}"; - - if (tourney.SuddenDeathRounds > 0) - sdText = $"{sdText} (first {tourney.SuddenDeathRounds} rounds)"; else - sdText = $"{sdText} (all rounds)"; - } + { + defs = basedef.Options; + } - AddBorderedText(35, y, 240, 20, $"Sudden Death: {sdText}", LabelColor32, BlackColor32); - y += 20; - - y += 6; - AddImageTiled(32, y - 1, 264, 1, 9107); - AddImageTiled(42, y + 1, 264, 1, 9157); - y += 6; - - AddBorderedText(35, y, 190, 20, $"Ruleset: {basedef.Title}", LabelColor32, BlackColor32); - y += 20; - - for (int i = 0; i < ruleset.Flavors.Count; ++i, y += 18) - AddBorderedText(35, y, 190, 20, $" + {ruleset.Flavors[i].Title}", LabelColor32, BlackColor32); - - y += 4; - - if (changes > 0) - { - AddBorderedText(35, y, 190, 20, "Modifications:", LabelColor32, BlackColor32); - y += 20; + BitArray opts = ruleset.Options; for (int i = 0; i < opts.Length; ++i) if (defs[i] != opts[i]) + ++changes; + + height += changes * 22; + + height += 10 + 22 + 25 + 25; + + if (tourney.PlayersPerParticipant > 1) + height += 36 + tourney.PlayersPerParticipant * 20; + + #endregion + + Closable = false; + + AddPage(0); + + //AddBackground( 0, 0, 400, 220, 9150 ); + AddBackground(1, 1, 398, height, 3600); + //AddBackground( 16, 15, 369, 189, 9100 ); + + AddImageTiled(16, 15, 369, height - 29, 3604); + AddAlphaRegion(16, 15, 369, height - 29); + + AddImage(215, -43, 0xEE40); + //AddImage( 330, 141, 0x8BA ); + + StringBuilder sb = new StringBuilder(); + + if (tourney.TourneyType == TourneyType.FreeForAll) + { + sb.Append("FFA"); + } + else if (tourney.TourneyType == TourneyType.RandomTeam) + { + sb.Append(tourney.ParticipantsPerMatch); + sb.Append("-Team"); + } + else if (tourney.TourneyType == TourneyType.Faction) + { + sb.Append(tourney.ParticipantsPerMatch); + sb.Append("-Team Faction"); + } + else if (tourney.TourneyType == TourneyType.RedVsBlue) + { + sb.Append("Red v Blue"); + } + else + { + for (int i = 0; i < tourney.ParticipantsPerMatch; ++i) { - string name = ruleset.Layout.FindByIndex(i); + if (sb.Length > 0) + sb.Append('v'); - if (name != null) // sanity - { - AddImage(35, y, opts[i] ? 0xD3 : 0xD2); - AddBorderedText(60, y, 165, 22, name, LabelColor32, BlackColor32); - } - - y += 22; + sb.Append(tourney.PlayersPerParticipant); } - } - else - { - AddBorderedText(35, y, 190, 20, "Modifications: None", LabelColor32, BlackColor32); + } + + if (tourney.EventController != null) + sb.Append(' ').Append(tourney.EventController.Title); + + sb.Append(" Tournament Signup"); + + AddBorderedText(22, 22, 294, 20, Center(sb.ToString()), LabelColor32, BlackColor32); + AddBorderedText(22, 50, 294, 40, "You have requested to join the tournament. Do you accept the rules?", 0xB0C868, + BlackColor32); + + AddImageTiled(32, 88, 264, 1, 9107); + AddImageTiled(42, 90, 264, 1, 9157); + + #region Rules + + int y = 100; + + var groupText = tourney.GroupType switch + { + GroupingType.HighVsLow => "High vs Low", + GroupingType.Nearest => "Closest opponent", + GroupingType.Random => "Random", + _ => null + }; + + AddBorderedText(35, y, 190, 20, $"Grouping: {groupText}", LabelColor32, BlackColor32); y += 20; - } - #endregion + var tieText = tourney.TieType switch + { + TieType.Random => "Random", + TieType.Highest => "Highest advances", + TieType.Lowest => "Lowest advances", + TieType.FullAdvancement => (tourney.ParticipantsPerMatch == 2 ? "Both advance" : "Everyone advances"), + TieType.FullElimination => (tourney.ParticipantsPerMatch == 2 ? "Both eliminated" : "Everyone eliminated"), + _ => null + }; - #region Team + AddBorderedText(35, y, 190, 20, $"Tiebreaker: {tieText}", LabelColor32, BlackColor32); + y += 20; + + string sdText = "Off"; + + if (tourney.SuddenDeath > TimeSpan.Zero) + { + sdText = $"{(int)tourney.SuddenDeath.TotalMinutes}:{tourney.SuddenDeath.Seconds:D2}"; + + if (tourney.SuddenDeathRounds > 0) + sdText = $"{sdText} (first {tourney.SuddenDeathRounds} rounds)"; + else + sdText = $"{sdText} (all rounds)"; + } + + AddBorderedText(35, y, 240, 20, $"Sudden Death: {sdText}", LabelColor32, BlackColor32); + y += 20; + + y += 6; + AddImageTiled(32, y - 1, 264, 1, 9107); + AddImageTiled(42, y + 1, 264, 1, 9157); + y += 6; + + AddBorderedText(35, y, 190, 20, $"Ruleset: {basedef.Title}", LabelColor32, BlackColor32); + y += 20; + + for (int i = 0; i < ruleset.Flavors.Count; ++i, y += 18) + AddBorderedText(35, y, 190, 20, $" + {ruleset.Flavors[i].Title}", LabelColor32, BlackColor32); + + y += 4; + + if (changes > 0) + { + AddBorderedText(35, y, 190, 20, "Modifications:", LabelColor32, BlackColor32); + y += 20; + + for (int i = 0; i < opts.Length; ++i) + if (defs[i] != opts[i]) + { + string name = ruleset.Layout.FindByIndex(i); + + if (name != null) // sanity + { + AddImage(35, y, opts[i] ? 0xD3 : 0xD2); + AddBorderedText(60, y, 165, 22, name, LabelColor32, BlackColor32); + } + + y += 22; + } + } + else + { + AddBorderedText(35, y, 190, 20, "Modifications: None", LabelColor32, BlackColor32); + y += 20; + } + + #endregion + + #region Team + + if (tourney.PlayersPerParticipant > 1) + { + y += 8; + AddImageTiled(32, y - 1, 264, 1, 9107); + AddImageTiled(42, y + 1, 264, 1, 9157); + y += 8; + + AddBorderedText(35, y, 190, 20, "Your Team", LabelColor32, BlackColor32); + y += 20; + + for (int i = 0; i < players.Count; ++i, y += 20) + { + if (i == 0) + AddImage(35, y, 0xD2); + else + AddGoldenButton(35, y, 1 + i); + + AddBorderedText(60, y, 200, 20, players[i].Name, LabelColor32, BlackColor32); + } + + for (int i = players.Count; i < tourney.PlayersPerParticipant; ++i, y += 20) + { + if (i == 0) + AddImage(35, y, 0xD2); + else + AddGoldenButton(35, y, 1 + i); + + AddBorderedText(60, y, 200, 20, "(Empty)", LabelColor32, BlackColor32); + } + } + + #endregion - if (tourney.PlayersPerParticipant > 1) - { y += 8; AddImageTiled(32, y - 1, 264, 1, 9107); AddImageTiled(42, y + 1, 264, 1, 9157); y += 8; - AddBorderedText(35, y, 190, 20, "Your Team", LabelColor32, BlackColor32); - y += 20; + AddRadio(24, y, 9727, 9730, true, 1); + AddBorderedText(60, y + 5, 250, 20, "Yes, I wish to join the tournament.", LabelColor32, BlackColor32); + y += 35; - for (int i = 0; i < players.Count; ++i, y += 20) - { - if (i == 0) - AddImage(35, y, 0xD2); - else - AddGoldenButton(35, y, 1 + i); + AddRadio(24, y, 9727, 9730, false, 2); + AddBorderedText(60, y + 5, 250, 20, "No, I do not wish to join.", LabelColor32, BlackColor32); + y += 35; - AddBorderedText(60, y, 200, 20, players[i].Name, LabelColor32, BlackColor32); - } - - for (int i = players.Count; i < tourney.PlayersPerParticipant; ++i, y += 20) - { - if (i == 0) - AddImage(35, y, 0xD2); - else - AddGoldenButton(35, y, 1 + i); - - AddBorderedText(60, y, 200, 20, "(Empty)", LabelColor32, BlackColor32); - } + y -= 3; + AddButton(314, y, 247, 248, 1); } - #endregion + public string Center(string text) => $"
{text}
"; - y += 8; - AddImageTiled(32, y - 1, 264, 1, 9107); - AddImageTiled(42, y + 1, 264, 1, 9157); - y += 8; + public string Color(string text, int color) => $"{text}"; - AddRadio(24, y, 9727, 9730, true, 1); - AddBorderedText(60, y + 5, 250, 20, "Yes, I wish to join the tournament.", LabelColor32, BlackColor32); - y += 35; - - AddRadio(24, y, 9727, 9730, false, 2); - AddBorderedText(60, y + 5, 250, 20, "No, I do not wish to join.", LabelColor32, BlackColor32); - y += 35; - - y -= 3; - AddButton(314, y, 247, 248, 1); - } - - public string Center(string text) => $"
{text}
"; - - public string Color(string text, int color) => $"{text}"; - - private void AddBorderedText(int x, int y, int width, int height, string text, int color, int borderColor) - { - AddColoredText(x - 1, y - 1, width, height, text, borderColor); - AddColoredText(x - 1, y + 1, width, height, text, borderColor); - AddColoredText(x + 1, y - 1, width, height, text, borderColor); - AddColoredText(x + 1, y + 1, width, height, text, borderColor); - AddColoredText(x, y, width, height, text, color); - } - - private void AddColoredText(int x, int y, int width, int height, string text, int color) - { - if (color == 0) - AddHtml(x, y, width, height, text); - else - AddHtml(x, y, width, height, Color(text, color)); - } - - public void AddGoldenButton(int x, int y, int bid) - { - AddButton(x, y, 0xD2, 0xD2, bid); - AddButton(x + 3, y + 3, 0xD8, 0xD8, bid); - } - - public override void OnResponse(NetState sender, RelayInfo info) - { - if (info.ButtonID == 1 && info.IsSwitched(1)) + private void AddBorderedText(int x, int y, int width, int height, string text, int color, int borderColor) { - Tournament tourney = m_Tournament; - Mobile from = m_From; + AddColoredText(x - 1, y - 1, width, height, text, borderColor); + AddColoredText(x - 1, y + 1, width, height, text, borderColor); + AddColoredText(x + 1, y - 1, width, height, text, borderColor); + AddColoredText(x + 1, y + 1, width, height, text, borderColor); + AddColoredText(x, y, width, height, text, color); + } - switch (tourney.Stage) + private void AddColoredText(int x, int y, int width, int height, string text, int color) + { + if (color == 0) + AddHtml(x, y, width, height, text); + else + AddHtml(x, y, width, height, Color(text, color)); + } + + public void AddGoldenButton(int x, int y, int bid) + { + AddButton(x, y, 0xD2, 0xD2, bid); + AddButton(x + 3, y + 3, 0xD8, 0xD8, bid); + } + + public override void OnResponse(NetState sender, RelayInfo info) + { + if (info.ButtonID == 1 && info.IsSwitched(1)) { - case TournamentStage.Fighting: + Tournament tourney = m_Tournament; + Mobile from = m_From; + + switch (tourney.Stage) { - if (m_Registrar != null) + case TournamentStage.Fighting: { - if (m_Tournament.HasParticipant(from)) - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, "Excuse me? You are already signed up.", from.NetState); - else - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "The tournament has already begun. You are too late to signup now.", - from.NetState); - } + if (m_Registrar != null) + { + if (m_Tournament.HasParticipant(from)) + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, "Excuse me? You are already signed up.", from.NetState); + else + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "The tournament has already begun. You are too late to signup now.", + from.NetState); + } - break; - } - case TournamentStage.Inactive: - { - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, "The tournament is closed.", from.NetState); - - break; - } - case TournamentStage.Signup: - { - if (m_Players.Count != tourney.PlayersPerParticipant) - { - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, "You have not yet chosen your team.", from.NetState); - - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); break; } - - Ladder ladder = Ladder.Instance; - - for (int i = 0; i < m_Players.Count; ++i) + case TournamentStage.Inactive: { - Mobile mob = m_Players[i]; + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, "The tournament is closed.", from.NetState); - LadderEntry entry = ladder?.Find(mob); - - if (entry != null && Ladder.GetLevel(entry.Experience) < tourney.LevelRequirement) - { - if (m_Registrar != null) - { - if (mob == from) - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, "You have not yet proven yourself a worthy dueler.", from.NetState); - else - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, $"{mob.Name} has not yet proven themselves a worthy dueler.", - from.NetState); - } - - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - return; - } - - if (tourney.IsFactionRestricted && Faction.Find(mob) == null) + break; + } + case TournamentStage.Signup: + { + if (m_Players.Count != tourney.PlayersPerParticipant) { m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, "Only those who have declared their faction allegiance may participate.", - from.NetState); + 0x35, false, "You have not yet chosen your team.", from.NetState); m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - return; + break; } - if (tourney.HasParticipant(mob)) + Ladder ladder = Ladder.Instance; + + for (int i = 0; i < m_Players.Count; ++i) { - if (m_Registrar != null) + Mobile mob = m_Players[i]; + + LadderEntry entry = ladder?.Find(mob); + + if (entry != null && Ladder.GetLevel(entry.Experience) < tourney.LevelRequirement) { - if (mob == from) - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, "You have already entered this tournament.", from.NetState); - else - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, $"{mob.Name} has already entered this tournament.", from.NetState); + if (m_Registrar != null) + { + if (mob == from) + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, "You have not yet proven yourself a worthy dueler.", from.NetState); + else + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, $"{mob.Name} has not yet proven themselves a worthy dueler.", + from.NetState); + } + + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + return; } - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - return; + if (tourney.IsFactionRestricted && Faction.Find(mob) == null) + { + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, "Only those who have declared their faction allegiance may participate.", + from.NetState); + + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + return; + } + + if (tourney.HasParticipant(mob)) + { + if (m_Registrar != null) + { + if (mob == from) + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, "You have already entered this tournament.", from.NetState); + else + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, $"{mob.Name} has already entered this tournament.", from.NetState); + } + + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + return; + } + + if (mob is PlayerMobile mobile && mobile.DuelContext != null) + { + if (mob == from) + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, + "You are already assigned to a duel. You must yield it before joining this tournament.", + from.NetState); + else + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, + $"{mobile.Name} is already assigned to a duel. They must yield it before joining this tournament.", + from.NetState); + + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + return; + } } - if (mob is PlayerMobile mobile && mobile.DuelContext != null) + if (m_Registrar != null) { - if (mob == from) - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, - "You are already assigned to a duel. You must yield it before joining this tournament.", - from.NetState); + string fmt; + + if (tourney.PlayersPerParticipant == 1) + fmt = + "As you say m'{0}. I've written your name to the bracket. The tournament will begin {1}."; + else if (tourney.PlayersPerParticipant == 2) + fmt = + "As you wish m'{0}. The tournament will begin {1}, but first you must name your partner."; else - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, - $"{mobile.Name} is already assigned to a duel. They must yield it before joining this tournament.", - from.NetState); + fmt = "As you wish m'{0}. The tournament will begin {1}, but first you must name your team."; - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - return; + string timeUntil; + int minutesUntil = (int)Math.Round((tourney.SignupStart + tourney.SignupPeriod - DateTime.UtcNow) + .TotalMinutes); + + if (minutesUntil == 0) + timeUntil = "momentarily"; + else + timeUntil = $"in {minutesUntil} minute{(minutesUntil == 1 ? "" : "s")}"; + + m_Registrar.PrivateOverheadMessage(MessageType.Regular, + 0x35, false, string.Format(fmt, from.Female ? "Lady" : "Lord", timeUntil), from.NetState); } + + TourneyParticipant part = new TourneyParticipant(from); + part.Players.Clear(); + part.Players.AddRange(m_Players); + + tourney.Participants.Add(part); + + break; } + } + } + else if (info.ButtonID > 1) + { + int index = info.ButtonID - 1; - if (m_Registrar != null) - { - string fmt; - - if (tourney.PlayersPerParticipant == 1) - fmt = - "As you say m'{0}. I've written your name to the bracket. The tournament will begin {1}."; - else if (tourney.PlayersPerParticipant == 2) - fmt = - "As you wish m'{0}. The tournament will begin {1}, but first you must name your partner."; - else - fmt = "As you wish m'{0}. The tournament will begin {1}, but first you must name your team."; - - string timeUntil; - int minutesUntil = (int)Math.Round((tourney.SignupStart + tourney.SignupPeriod - DateTime.UtcNow) - .TotalMinutes); - - if (minutesUntil == 0) - timeUntil = "momentarily"; - else - timeUntil = $"in {minutesUntil} minute{(minutesUntil == 1 ? "" : "s")}"; - - m_Registrar.PrivateOverheadMessage(MessageType.Regular, - 0x35, false, string.Format(fmt, from.Female ? "Lady" : "Lord", timeUntil), from.NetState); - } - - TourneyParticipant part = new TourneyParticipant(from); - part.Players.Clear(); - part.Players.AddRange(m_Players); - - tourney.Participants.Add(part); - - break; + if (index > 0 && index < m_Players.Count) + { + m_Players.RemoveAt(index); + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + } + else if (m_Players.Count < m_Tournament.PlayersPerParticipant) + { + m_From.BeginTarget(12, false, TargetFlags.None, AddPlayer_OnTarget); + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); } } } - else if (info.ButtonID > 1) + + private void AddPlayer_OnTarget(Mobile from, object obj) { - int index = info.ButtonID - 1; - - if (index > 0 && index < m_Players.Count) - { - m_Players.RemoveAt(index); - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - } - else if (m_Players.Count < m_Tournament.PlayersPerParticipant) - { - m_From.BeginTarget(12, false, TargetFlags.None, AddPlayer_OnTarget); - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - } - } - } - - private void AddPlayer_OnTarget(Mobile from, object obj) - { - if (!(obj is Mobile mob) || mob == from) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "Excuse me?", from.NetState); - } - else if (!mob.Player) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - if (mob.Body.IsHuman) - mob.SayTo(from, 1005443); // Nay, I would rather stay here and watch a nail rust. - else - mob.SayTo(from, 1005444); // The creature ignores your offer. - } - else if (AcceptDuelGump.IsIgnored(mob, from) || mob.Blessed) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "They ignore your invitation.", from.NetState); - } - else - { - if (!(mob is PlayerMobile pm)) - return; - - if (pm.DuelContext != null) + if (!(obj is Mobile mob) || mob == from) { m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "They are already assigned to another duel.", from.NetState); + 0x22, false, "Excuse me?", from.NetState); } - else if (mob.HasGump()) + else if (!mob.Player) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + if (mob.Body.IsHuman) + mob.SayTo(from, 1005443); // Nay, I would rather stay here and watch a nail rust. + else + mob.SayTo(from, 1005444); // The creature ignores your offer. + } + else if (AcceptDuelGump.IsIgnored(mob, from) || mob.Blessed) { m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "They have already been offered a partnership.", from.NetState); - } - else if (mob.HasGump()) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "They are already trying to join this tournament.", from.NetState); - } - else if (m_Players.Contains(mob)) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "You have already named them as a team member.", from.NetState); - } - else if (m_Tournament.HasParticipant(mob)) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "They have already entered this tournament.", from.NetState); - } - else if (m_Players.Count >= m_Tournament.PlayersPerParticipant) - { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x22, false, "Your team is full.", from.NetState); + 0x22, false, "They ignore your invitation.", from.NetState); } else { - m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); - mob.SendGump(new AcceptTeamGump(from, mob, m_Tournament, m_Registrar, m_Players)); + if (!(mob is PlayerMobile pm)) + return; - m_Registrar?.PrivateOverheadMessage(MessageType.Regular, - 0x59, false, - $"As you command m'{(from.Female ? "Lady" : "Lord")}. I've given your offer to {mob.Name}.", - from.NetState); + if (pm.DuelContext != null) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "They are already assigned to another duel.", from.NetState); + } + else if (mob.HasGump()) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "They have already been offered a partnership.", from.NetState); + } + else if (mob.HasGump()) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "They are already trying to join this tournament.", from.NetState); + } + else if (m_Players.Contains(mob)) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "You have already named them as a team member.", from.NetState); + } + else if (m_Tournament.HasParticipant(mob)) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "They have already entered this tournament.", from.NetState); + } + else if (m_Players.Count >= m_Tournament.PlayersPerParticipant) + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x22, false, "Your team is full.", from.NetState); + } + else + { + m_From.SendGump(new ConfirmSignupGump(m_From, m_Registrar, m_Tournament, m_Players)); + mob.SendGump(new AcceptTeamGump(from, mob, m_Tournament, m_Registrar, m_Players)); + + m_Registrar?.PrivateOverheadMessage(MessageType.Regular, + 0x59, false, + $"As you command m'{(from.Female ? "Lady" : "Lord")}. I've given your offer to {mob.Name}.", + from.NetState); + } } } } } -} diff --git a/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs b/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs index f1359bae4..56d0b76fe 100644 --- a/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs +++ b/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs @@ -28,13 +28,9 @@ namespace Server.Engines.ConPVP from.CloseGump(); RulesetLayout depthCounter = page; - int depth = 0; while (depthCounter != null) - { - ++depth; depthCounter = depthCounter.Parent; - } int count = page.Children.Length + page.Options.Length; diff --git a/Projects/Scripts/Engines/ConPVP/Gumps/TournamentBracketGump.cs b/Projects/Scripts/Engines/ConPVP/Gumps/TournamentBracketGump.cs index b78222b09..52dcaeaf5 100644 --- a/Projects/Scripts/Engines/ConPVP/Gumps/TournamentBracketGump.cs +++ b/Projects/Scripts/Engines/ConPVP/Gumps/TournamentBracketGump.cs @@ -350,9 +350,10 @@ namespace Server.Engines.ConPVP AddLeftArrow(25, 11, ToButtonID(0, 0)); AddHtml(25, 35, 250, 20, Center("Rounds")); -// List levelsList = m_List != null -// ? Utility.CastListCovariant(m_List) -// : new List(tourney.Pyramid.Levels); + + // List levelsList = m_List != null + // ? Utility.CastListCovariant(m_List) + // : new List(tourney.Pyramid.Levels); StartPage(out int index, out int count, out int y, 12); diff --git a/Projects/Scripts/Engines/ConPVP/Ladder.cs b/Projects/Scripts/Engines/ConPVP/Ladder.cs index 0502a874b..d24aeff74 100644 --- a/Projects/Scripts/Engines/ConPVP/Ladder.cs +++ b/Projects/Scripts/Engines/ConPVP/Ladder.cs @@ -13,8 +13,7 @@ namespace Server.Engines.ConPVP Ladder = new Ladder(); - if (Ladder.Instance == null) - Ladder.Instance = Ladder; + Ladder.Instance ??= Ladder; } public LadderController(Serial serial) : base(serial) diff --git a/Projects/Scripts/Engines/ConPVP/Trophy.cs b/Projects/Scripts/Engines/ConPVP/Trophy.cs index 3efaa23dc..c8c3f60e0 100644 --- a/Projects/Scripts/Engines/ConPVP/Trophy.cs +++ b/Projects/Scripts/Engines/ConPVP/Trophy.cs @@ -81,8 +81,7 @@ namespace Server.Items { base.OnAdded(parent); - if (Owner == null) - Owner = RootParent as Mobile; + Owner ??= RootParent as Mobile; } public override void OnSingleClick(Mobile from) @@ -111,4 +110,4 @@ namespace Server.Items }; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Craft/Core/CraftGumpItem.cs b/Projects/Scripts/Engines/Craft/Core/CraftGumpItem.cs index 02badb300..7edce2b0a 100644 --- a/Projects/Scripts/Engines/Craft/Core/CraftGumpItem.cs +++ b/Projects/Scripts/Engines/Craft/Core/CraftGumpItem.cs @@ -154,9 +154,8 @@ namespace Server.Engines.Craft if (context != null) resIndex = m_CraftItem.UseSubRes2 ? context.LastResourceIndex2 : context.LastResourceIndex; - bool allRequiredSkills = true; double chance = m_CraftItem.GetSuccessChance(m_From, resIndex > -1 ? res.GetAt(resIndex).ItemType : null, - m_CraftSystem, false, ref allRequiredSkills); + m_CraftSystem, false, out _); double excepChance = m_CraftItem.GetExceptionalChance(m_CraftSystem, chance, m_From); if (chance < 0.0) diff --git a/Projects/Scripts/Engines/Craft/Core/CraftItem.cs b/Projects/Scripts/Engines/Craft/Core/CraftItem.cs index 23611a3ed..14bd4d135 100644 --- a/Projects/Scripts/Engines/Craft/Core/CraftItem.cs +++ b/Projects/Scripts/Engines/Craft/Core/CraftItem.cs @@ -682,12 +682,12 @@ namespace Server.Engines.Craft public bool CheckSkills(Mobile from, Type typeRes, CraftSystem craftSystem, ref int quality, ref bool allRequiredSkills) => - CheckSkills(from, typeRes, craftSystem, ref quality, ref allRequiredSkills, true); + CheckSkills(from, typeRes, craftSystem, ref quality, out allRequiredSkills, true); public bool CheckSkills(Mobile from, Type typeRes, CraftSystem craftSystem, ref int quality, - ref bool allRequiredSkills, bool gainSkills) + out bool allRequiredSkills, bool gainSkills) { - double chance = GetSuccessChance(from, typeRes, craftSystem, gainSkills, ref allRequiredSkills); + double chance = GetSuccessChance(from, typeRes, craftSystem, gainSkills, out allRequiredSkills); if (GetExceptionalChance(craftSystem, chance, from) > Utility.RandomDouble()) quality = 2; @@ -696,7 +696,7 @@ namespace Server.Engines.Craft } public double GetSuccessChance(Mobile from, Type typeRes, CraftSystem craftSystem, bool gainSkills, - ref bool allRequiredSkills) + out bool allRequiredSkills) { double minMainSkill = 0.0; double maxMainSkill = 0.0; @@ -750,8 +750,8 @@ namespace Server.Engines.Craft if (RequiredExpansion == Expansion.None || from.NetState?.SupportsExpansion(RequiredExpansion) == true) { - bool allRequiredSkills = true; - double chance = GetSuccessChance(from, typeRes, craftSystem, false, ref allRequiredSkills); + bool allRequiredSkills; + double chance = GetSuccessChance(from, typeRes, craftSystem, false, out allRequiredSkills); if (allRequiredSkills && chance >= 0.0) { @@ -1100,7 +1100,7 @@ namespace Server.Engines.Craft int quality = 1; bool allRequiredSkills = true; - m_CraftItem.CheckSkills(m_From, m_TypeRes, m_CraftSystem, ref quality, ref allRequiredSkills, false); + m_CraftItem.CheckSkills(m_From, m_TypeRes, m_CraftSystem, ref quality, out allRequiredSkills, false); CraftContext context = m_CraftSystem.GetContext(m_From); diff --git a/Projects/Scripts/Engines/Craft/Core/Enhance.cs b/Projects/Scripts/Engines/Craft/Core/Enhance.cs index e2fe21aa0..d634d1545 100644 --- a/Projects/Scripts/Engines/Craft/Core/Enhance.cs +++ b/Projects/Scripts/Engines/Craft/Core/Enhance.cs @@ -51,8 +51,7 @@ namespace Server.Engines.Craft if (craftItem == null || craftItem.Resources.Count == 0) return EnhanceResult.BadItem; - bool allRequiredSkills = false; - if (craftItem.GetSuccessChance(from, resType, craftSystem, false, ref allRequiredSkills) <= 0.0) + if (craftItem.GetSuccessChance(from, resType, craftSystem, false, out _) <= 0.0) return EnhanceResult.NoSkill; CraftResourceInfo info = CraftResources.GetInfo(resource); @@ -322,4 +321,4 @@ namespace Server.Engines.Craft } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs b/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs index c68c961ab..4e708cff3 100644 --- a/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs +++ b/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs @@ -149,18 +149,18 @@ namespace Server.Engines.Craft public override void InitCraftList() { /* - Synthax for a SIMPLE craft item + Syntax for a SIMPLE craft item AddCraft( ObjectType, Group, MinSkill, MaxSkill, ResourceType, Amount, Message ) ObjectType : The type of the object you want to add to the build list. - Group : The group in wich the object will be showed in the craft menu. - MinSkill : The minimum of skill value - MaxSkill : The maximum of skill value + Group : The group in which the object will be showed in the craft menu. + MinSkill : The minimum of skill value + MaxSkill : The maximum of skill value ResourceType : The type of the resource the mobile need to create the item - Amount : The amount of the ResourceType it need to create the item - Message : String or Int for Localized. The message that will be sent to the mobile, if the specified resource is missing. + Amount : The amount of the ResourceType it need to create the item + Message : String or Int for Localized. The message that will be sent to the mobile, if the specified resource is missing. - Synthax for a COMPLEXE craft item. A complexe item is an item that need either more than + Syntax for a COMPLEX craft item. A complex item is an item that need either more than only one skill, or more than only one resource. Coming soon.... @@ -183,7 +183,7 @@ namespace Server.Engines.Craft #endregion - int index = -1; + int index; #region Platemail diff --git a/Projects/Scripts/Engines/Factions/Core/Faction.cs b/Projects/Scripts/Engines/Factions/Core/Faction.cs index b0269f106..373a7cb30 100644 --- a/Projects/Scripts/Engines/Factions/Core/Faction.cs +++ b/Projects/Scripts/Engines/Factions/Core/Faction.cs @@ -898,8 +898,7 @@ namespace Server.Factions public static void HandleDeath(Mobile victim, Mobile killer) { - if (killer == null) - killer = victim.FindMostRecentDamager(true); + killer ??= victim.FindMostRecentDamager(true); PlayerState killerState = PlayerState.Find(killer); Container killerPack = killer?.Backpack; diff --git a/Projects/Scripts/Engines/Factions/Core/PlayerState.cs b/Projects/Scripts/Engines/Factions/Core/PlayerState.cs index 19b97ec4b..41b564f94 100644 --- a/Projects/Scripts/Engines/Factions/Core/PlayerState.cs +++ b/Projects/Scripts/Engines/Factions/Core/PlayerState.cs @@ -260,8 +260,7 @@ namespace Server.Factions public void OnGivenSilverTo(Mobile mob) { - if (SilverGiven == null) - SilverGiven = new List(); + SilverGiven ??= new List(); SilverGiven.Add(new SilverGivenEntry(mob)); } diff --git a/Projects/Scripts/Engines/Factions/Core/Town.cs b/Projects/Scripts/Engines/Factions/Core/Town.cs index 9c7e3552a..ea6980227 100644 --- a/Projects/Scripts/Engines/Factions/Core/Town.cs +++ b/Projects/Scripts/Engines/Factions/Core/Town.cs @@ -252,7 +252,7 @@ namespace Server.Factions public void ConstructGuardLists() { - GuardDefinition[] defs = Owner == null ? new GuardDefinition[0] : Owner.Definition.Guards; + GuardDefinition[] defs = Owner?.Definition.Guards ?? new GuardDefinition[0]; GuardLists = new List(); diff --git a/Projects/Scripts/Engines/Harvest/Fishing.cs b/Projects/Scripts/Engines/Harvest/Fishing.cs index 79064a01d..1b1f7af0d 100644 --- a/Projects/Scripts/Engines/Harvest/Fishing.cs +++ b/Projects/Scripts/Engines/Harvest/Fishing.cs @@ -23,7 +23,7 @@ namespace Server.Engines.Harvest new MutateEntry(0.0, 125.0, -2375.0, false, typeof(PrizedFish), typeof(WondrousFish), typeof(TrulyRareFish), typeof(PeculiarFish)), new MutateEntry(0.0, 105.0, -420.0, false, typeof(Boots), typeof(Shoes), typeof(Sandals), typeof(ThighBoots)), - new MutateEntry(0.0, 200.0, -200.0, false, new Type[1] { null }) + new MutateEntry(0.0, 200.0, -200.0, false, new Type[] { null }) }; private static int[] m_WaterTiles = diff --git a/Projects/Scripts/Engines/Help/PageQueueGump.cs b/Projects/Scripts/Engines/Help/PageQueueGump.cs index a87f3d40e..5fbb7defa 100644 --- a/Projects/Scripts/Engines/Help/PageQueueGump.cs +++ b/Projects/Scripts/Engines/Help/PageQueueGump.cs @@ -145,8 +145,7 @@ namespace Server.Engines.Help public static void Save() { - if (List == null) - List = Load(); + List ??= Load(); try { diff --git a/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs b/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs index 391ff6a21..cd7ece20e 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs @@ -14,8 +14,7 @@ namespace Server.Engines.MLQuests public static void EnsureExistence() { - if (m_Instance == null) - m_Instance = new MLQuestPersistence(); + m_Instance ??= new MLQuestPersistence(); } public override void Serialize(IGenericWriter writer) @@ -55,4 +54,4 @@ namespace Server.Engines.MLQuests MLQuest.Deserialize(reader, version); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs b/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs index 35cb5f035..f3f5fda59 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs @@ -433,8 +433,7 @@ namespace Server.Engines.MLQuests foreach (BaseObjectiveInstance objective in instance.Objectives) if (!objective.Expired && objective is KillObjectiveInstance kill) { - if (type == null) - type = mob.GetType(); + type ??= mob.GetType(); if (kill.AddKill(mob, type)) { @@ -477,8 +476,7 @@ namespace Server.Engines.MLQuests instance.Quester = quester; } - if (deliverInstance == null) - deliverInstance = instance; + deliverInstance ??= instance; break; // don't return, we may have to complete more deliveries } @@ -563,8 +561,7 @@ namespace Server.Engines.MLQuests * Save first quest that reaches the CanOffer call. * If no quests are valid at all, return this quest for displaying the CanOffer error message. */ - if (fallback == null) - fallback = quest; + fallback ??= quest; if (quest.CanOffer(quester, pm, context, false)) m_EligiblePool.Add(quest); diff --git a/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs b/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs index 34192da86..30255f3b4 100644 --- a/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs +++ b/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs @@ -100,9 +100,8 @@ namespace Server.Engines.MLQuests.Mobiles if (m.CanSee(this) && m.InLOS(this) && m.CanBeginAction(this)) { - if (shoutPacket == null) - shoutPacket = Packet.Acquire(new MessageLocalized(Serial, Body, MessageType.Regular, 946, 3, - 1078099, Name, "")); // Double Click On Me For Help! + shoutPacket ??= Packet.Acquire(new MessageLocalized(Serial, Body, MessageType.Regular, 946, 3, + 1078099, Name, "")); // Double Click On Me For Help! state.Send(shoutPacket); } @@ -135,4 +134,4 @@ namespace Server.Engines.MLQuests.Mobiles Frozen = true; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs b/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs index e09d23520..1ca44ef83 100644 --- a/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs +++ b/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs @@ -162,7 +162,6 @@ namespace Server.PathAlgorithms.SlowAStar switch (i) { default: - case 0: x = 0; y = -1; break; @@ -272,4 +271,4 @@ namespace Server.PathAlgorithms.SlowAStar return null; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Plants/PlantItem.cs b/Projects/Scripts/Engines/Plants/PlantItem.cs index 9cd03c379..c47312bea 100644 --- a/Projects/Scripts/Engines/Plants/PlantItem.cs +++ b/Projects/Scripts/Engines/Plants/PlantItem.cs @@ -84,8 +84,7 @@ namespace Server.Engines.Plants } else { - if (PlantSystem == null) - PlantSystem = new PlantSystem(this, false); + PlantSystem ??= new PlantSystem(this, false); int hits = (int)(PlantSystem.MaxHits * ratio); diff --git a/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs b/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs index 1ca3ed054..f02deb1c9 100644 --- a/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs +++ b/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs @@ -326,18 +326,15 @@ namespace Server.Engines.Quests if (completed && restartDelay > TimeSpan.Zero || !completed && restartDelay == TimeSpan.MaxValue) { - List doneQuests = From.DoneQuests; - - if (doneQuests == null) - From.DoneQuests = doneQuests = new List(); + From.DoneQuests ??= new List(); bool found = false; Type ourQuestType = GetType(); - for (int i = 0; i < doneQuests.Count; ++i) + for (int i = 0; i < From.DoneQuests.Count; ++i) { - QuestRestartInfo restartInfo = doneQuests[i]; + QuestRestartInfo restartInfo = From.DoneQuests[i]; if (restartInfo.QuestType == ourQuestType) { @@ -348,7 +345,7 @@ namespace Server.Engines.Quests } if (!found) - doneQuests.Add(new QuestRestartInfo(ourQuestType, restartDelay)); + From.DoneQuests.Add(new QuestRestartInfo(ourQuestType, restartDelay)); } } } diff --git a/Projects/Scripts/Engines/Spawner/Spawner.cs b/Projects/Scripts/Engines/Spawner/Spawner.cs index eb45bb788..c1f0df49d 100644 --- a/Projects/Scripts/Engines/Spawner/Spawner.cs +++ b/Projects/Scripts/Engines/Spawner/Spawner.cs @@ -293,8 +293,7 @@ namespace Server.Mobiles public void Defrag() { - if (Entries == null) - Entries = new List(); + Entries ??= new List(); for (int i = 0; i < Entries.Count; ++i) Entries[i].Defrag(this); @@ -302,8 +301,6 @@ namespace Server.Mobiles public void OnTick() { -// DoTimer( m_Spawned.Count >= m_Count ); - if (m_Group) { Defrag(); @@ -318,15 +315,6 @@ namespace Server.Mobiles Spawn(); } -/* - if ( m_Running && m_Timer != null ) - { - if ( m_Spawned.Count >= m_Count && m_Timer.Running ) - DoTimer( true ); - else if ( m_Spawned.Count < m_Count && !m_Timer.Running ) - DoTimer( false ); - } -*/ DoTimer(); } @@ -915,8 +903,7 @@ namespace Server.Mobiles if (SpawnerType.GetType(typeName) == null) { - if (m_WarnTimer == null) - m_WarnTimer = new WarnTimer(); + m_WarnTimer ??= new WarnTimer(); m_WarnTimer.Add(Location, Map, typeName); } diff --git a/Projects/Scripts/Engines/Treasures of Tokuno/TreasuresOfTokuno.cs b/Projects/Scripts/Engines/Treasures of Tokuno/TreasuresOfTokuno.cs index a4d88794c..eaf7eae38 100644 --- a/Projects/Scripts/Engines/Treasures of Tokuno/TreasuresOfTokuno.cs +++ b/Projects/Scripts/Engines/Treasures of Tokuno/TreasuresOfTokuno.cs @@ -136,7 +136,7 @@ namespace Server.Misc //This is the Exponentional regression with only 2 datapoints. //A log. func would also work, but it didn't make as much sense. - //This function isn't OSI exact beign that I don't know OSI's func they used ;p + //This function isn't OSI exact being that I don't know OSI's func they used ;p int x = pm.ToTTotalMonsterFame; //const double A = 8.63316841 * Math.Pow( 10, -4 ); diff --git a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs index 79fd81970..b5c08596f 100644 --- a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs +++ b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs @@ -372,8 +372,7 @@ namespace Server.Mobiles { state.Mobile.ProcessDelta(); - if (p == null) - p = Packet.Acquire(new UpdateStatueAnimation(this, 1, m_Animation, m_Frames)); + p ??= Packet.Acquire(new UpdateStatueAnimation(this, 1, m_Animation, m_Frames)); state.Send(p); } diff --git a/Projects/Scripts/Gumps/AdminGump.cs b/Projects/Scripts/Gumps/AdminGump.cs index fbc3db4b3..a9d63360d 100644 --- a/Projects/Scripts/Gumps/AdminGump.cs +++ b/Projects/Scripts/Gumps/AdminGump.cs @@ -587,8 +587,7 @@ namespace Server.Gumps } case AdminGumpPage.Accounts: { - if (m_List == null) - m_List = new List(); + m_List ??= new List(); List rads = state as List; @@ -1214,7 +1213,6 @@ namespace Server.Gumps case AccessLevel.Seer: return 0x144; case AccessLevel.GameMaster: return 0x21; case AccessLevel.Counselor: return 0x2; - case AccessLevel.Player: default: { if (m.Kills >= 5) @@ -1525,7 +1523,7 @@ namespace Server.Gumps { IPAddress[] ips = a.LoginIPs; - if (ips.Length != 0 && ip == ips[0] && AccountHandler.IPTable.ContainsKey(ips[0])) + if (ips.Length != 0 && Equals(ip, ips[0]) && AccountHandler.IPTable.ContainsKey(ips[0])) --AccountHandler.IPTable[ip]; List newList = new List(ips); diff --git a/Projects/Scripts/Gumps/Guilds/GuildGump.cs b/Projects/Scripts/Gumps/Guilds/GuildGump.cs index a4a884096..9841c2e59 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildGump.cs @@ -1,3 +1,4 @@ +using System; using Server.Guilds; using Server.Network; @@ -48,12 +49,10 @@ namespace Server.Gumps if (fealty == null || !guild.IsMember(fealty)) fealty = leader; - if (fealty == null) - fealty = beholder; + fealty ??= beholder; - string fealtyName; - - if ((fealtyName = fealty.Name) == null || (fealtyName = fealtyName.Trim()).Length <= 0) + string fealtyName = fealty.Name?.Trim(); + if (string.IsNullOrWhiteSpace(fealtyName)) fealtyName = "(empty)"; if (beholder == fealty) diff --git a/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs b/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs index 6ae8e735d..e2d1f648f 100644 --- a/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs +++ b/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs @@ -185,9 +185,7 @@ namespace Server.Guilds public override void OnResponse(NetState sender, RelayInfo info) { - PlayerMobile pm = sender.Mobile as PlayerMobile; - - if (!IsMember(pm, guild)) + if (!(sender.Mobile is PlayerMobile pm && IsMember(pm, guild))) return; RankDefinition playerRank = pm.GuildRank; diff --git a/Projects/Scripts/Gumps/Props/PropsGump.cs b/Projects/Scripts/Gumps/Props/PropsGump.cs index 57b9acb48..f2216008e 100644 --- a/Projects/Scripts/Gumps/Props/PropsGump.cs +++ b/Projects/Scripts/Gumps/Props/PropsGump.cs @@ -153,9 +153,7 @@ namespace Server.Gumps if (parent != null) { - if (m_Stack == null) - m_Stack = new Stack(); - + m_Stack ??= new Stack(); m_Stack.Push(parent); } @@ -599,7 +597,7 @@ namespace Server.Gumps { MethodInfo parseMethod = t.GetMethod("Parse", new[] { typeof(string) }); - return parseMethod.Invoke(null, new object[] { s }); + return parseMethod?.Invoke(null, new object[] { s }); } throw new Exception("bad"); diff --git a/Projects/Scripts/Gumps/Props/SetBodyGump.cs b/Projects/Scripts/Gumps/Props/SetBodyGump.cs index 43f1ee237..6669f04d1 100644 --- a/Projects/Scripts/Gumps/Props/SetBodyGump.cs +++ b/Projects/Scripts/Gumps/Props/SetBodyGump.cs @@ -127,7 +127,6 @@ namespace Server.Gumps switch (index) { default: - case 0: type = ModelBodyType.Monsters; list = m_Monster; break; @@ -284,12 +283,12 @@ namespace Server.Gumps public int CompareTo(InternalEntry comp) { - int v = Name.CompareTo(comp.Name); + if (Name == null && comp.Name == null) + return 0; - if (v == 0) - Body.CompareTo(comp.Body); + int v = Name?.CompareTo(comp.Name) ?? 1; - return v; + return v == 0 ? Body.CompareTo(comp.Body) : v; } } } diff --git a/Projects/Scripts/Gumps/Props/SetGump.cs b/Projects/Scripts/Gumps/Props/SetGump.cs index 918eab063..1f66ed375 100644 --- a/Projects/Scripts/Gumps/Props/SetGump.cs +++ b/Projects/Scripts/Gumps/Props/SetGump.cs @@ -71,14 +71,12 @@ namespace Server.Gumps bool isBody = prop.IsDefined(typeof(BodyAttribute), false); object val = prop.GetValue(m_Object, null); - string initialText; - - if (val == null) - initialText = ""; - else if (val is TextDefinition definition) - initialText = definition.GetValue(); - else - initialText = val.ToString(); + string initialText = val switch + { + null => "", + TextDefinition definition => definition.GetValue(), + _ => val.ToString() + }; AddPage(0); diff --git a/Projects/Scripts/Gumps/SkillsGump.cs b/Projects/Scripts/Gumps/SkillsGump.cs index 31a4c881d..6ef7dd730 100644 --- a/Projects/Scripts/Gumps/SkillsGump.cs +++ b/Projects/Scripts/Gumps/SkillsGump.cs @@ -257,7 +257,7 @@ namespace Server.Gumps x -= OldStyle ? OffsetSize : 0; AddImageTiled(x, y, emptyWidth + (OldStyle ? OffsetSize * 2 : 0), EntryHeight, EntryGumpID); - AddLabel(x + TextOffsetX, y, TextHue, group.Name); + AddLabel(x + TextOffsetX, y, TextHue, group?.Name ?? ""); x += emptyWidth + (OldStyle ? OffsetSize * 2 : 0); x += OffsetSize; @@ -306,7 +306,6 @@ namespace Server.Gumps switch (sk.Lock) { default: - case SkillLock.Up: buttonID1 = 0x983; buttonID2 = 0x983; xOffset = 6; diff --git a/Projects/Scripts/Items/Addons/BaseAddonContainerDeed.cs b/Projects/Scripts/Items/Addons/BaseAddonContainerDeed.cs index 9c241cf74..b424b7b15 100644 --- a/Projects/Scripts/Items/Addons/BaseAddonContainerDeed.cs +++ b/Projects/Scripts/Items/Addons/BaseAddonContainerDeed.cs @@ -46,10 +46,7 @@ namespace Server.Items public virtual int OnCraft(int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue) { - Type resourceType = typeRes; - - if (resourceType == null) - resourceType = craftItem.Resources.GetAt(0).ItemType; + Type resourceType = typeRes ?? craftItem.Resources.GetAt(0).ItemType; Resource = CraftResources.GetFromType(resourceType); diff --git a/Projects/Scripts/Items/Armor/BaseArmor.cs b/Projects/Scripts/Items/Armor/BaseArmor.cs index 5990f9cd1..451420f8c 100644 --- a/Projects/Scripts/Items/Armor/BaseArmor.cs +++ b/Projects/Scripts/Items/Armor/BaseArmor.cs @@ -486,10 +486,7 @@ namespace Server.Items if (makersMark) Crafter = from; - Type resourceType = typeRes; - - if (resourceType == null) - resourceType = craftItem.Resources.GetAt(0).ItemType; + Type resourceType = typeRes ?? craftItem.Resources.GetAt(0).ItemType; Resource = CraftResources.GetFromType(resourceType); PlayerConstructed = true; @@ -1271,8 +1268,7 @@ namespace Server.Items } } - if (SkillBonuses == null) - SkillBonuses = new AosSkillBonuses(this); + SkillBonuses ??= new AosSkillBonuses(this); Mobile m = Parent as Mobile; diff --git a/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs b/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs index c117315c8..64656111b 100644 --- a/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs +++ b/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs @@ -1,3 +1,5 @@ +using System; + namespace Server.Items { public class ElvenGlasses : BaseArmor @@ -126,10 +128,11 @@ namespace Server.Items WeaponAttributes = new AosWeaponAttributes(this); } + [Flags] private enum SaveFlag { None = 0x00000000, WeaponAttributes = 0x00000001 } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Books/BaseBook.cs b/Projects/Scripts/Items/Books/BaseBook.cs index 628fd91d6..846f41f8c 100644 --- a/Projects/Scripts/Items/Books/BaseBook.cs +++ b/Projects/Scripts/Items/Books/BaseBook.cs @@ -69,7 +69,7 @@ namespace Server.Items } // Intended for defined books only - public BaseBook(int itemID, bool writable) : this(itemID, 0) + public BaseBook(int itemID, bool writable) : this(itemID, 0, writable) { } diff --git a/Projects/Scripts/Items/Clothing/BaseClothing.cs b/Projects/Scripts/Items/Clothing/BaseClothing.cs index 64412e7ce..63fdf08c3 100644 --- a/Projects/Scripts/Items/Clothing/BaseClothing.cs +++ b/Projects/Scripts/Items/Clothing/BaseClothing.cs @@ -152,10 +152,7 @@ namespace Server.Items if (DefaultResource != CraftResource.None) { - Type resourceType = typeRes; - - if (resourceType == null) - resourceType = craftItem.Resources.GetAt(0).ItemType; + Type resourceType = typeRes ?? craftItem.Resources.GetAt(0).ItemType; Resource = CraftResources.GetFromType(resourceType); } diff --git a/Projects/Scripts/Items/Deeds/CommodityDeed.cs b/Projects/Scripts/Items/Deeds/CommodityDeed.cs index 02e0dd25b..3ee40fdc4 100644 --- a/Projects/Scripts/Items/Deeds/CommodityDeed.cs +++ b/Projects/Scripts/Items/Deeds/CommodityDeed.cs @@ -85,13 +85,9 @@ namespace Server.Items if (Commodity != null) { - string args; - - if (Commodity.Name == null) - args = - $"#{(Commodity is ICommodity commodity ? commodity.DescriptionNumber : Commodity.LabelNumber)}\t{Commodity.Amount}"; - else - args = $"{Commodity.Name}\t{Commodity.Amount}"; + var args = Commodity.Name == null ? + $"#{(Commodity is ICommodity commodity ? commodity.DescriptionNumber : Commodity.LabelNumber)}\t{Commodity.Amount}" : + $"{Commodity.Name}\t{Commodity.Amount}"; list.Add(1060658, args); // ~1_val~: ~2_val~ } diff --git a/Projects/Scripts/Items/Deeds/DragonBardingDeed.cs b/Projects/Scripts/Items/Deeds/DragonBardingDeed.cs index a7e87d744..c190eac1e 100644 --- a/Projects/Scripts/Items/Deeds/DragonBardingDeed.cs +++ b/Projects/Scripts/Items/Deeds/DragonBardingDeed.cs @@ -64,10 +64,7 @@ namespace Server.Items if (makersMark) Crafter = from; - Type resourceType = typeRes; - - if (resourceType == null) - resourceType = craftItem.Resources.GetAt(0).ItemType; + Type resourceType = typeRes ?? craftItem.Resources.GetAt(0).ItemType; Resource = CraftResources.GetFromType(resourceType); diff --git a/Projects/Scripts/Items/Jewels/BaseJewel.cs b/Projects/Scripts/Items/Jewels/BaseJewel.cs index 29945e75a..d21de181c 100644 --- a/Projects/Scripts/Items/Jewels/BaseJewel.cs +++ b/Projects/Scripts/Items/Jewels/BaseJewel.cs @@ -131,10 +131,7 @@ namespace Server.Items public int OnCraft(int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue) { - Type resourceType = typeRes; - - if (resourceType == null) - resourceType = craftItem.Resources.GetAt(0).ItemType; + Type resourceType = typeRes ?? craftItem.Resources.GetAt(0).ItemType; Resource = CraftResources.GetFromType(resourceType); diff --git a/Projects/Scripts/Items/Misc/Corpses/Corpse.cs b/Projects/Scripts/Items/Misc/Corpses/Corpse.cs index 154317b0c..ad540e512 100644 --- a/Projects/Scripts/Items/Misc/Corpses/Corpse.cs +++ b/Projects/Scripts/Items/Misc/Corpses/Corpse.cs @@ -347,8 +347,7 @@ namespace Server.Items if (Aggressors.Count == 0 || Items.Count == 0) return; - if (m_InstancedItems == null) - m_InstancedItems = new Dictionary(); + m_InstancedItems ??= new Dictionary(); List m_Stackables = new List(); List m_Unstackables = new List(); @@ -427,8 +426,7 @@ namespace Server.Items if (InstancedCorpse) { - if (m_InstancedItems == null) - m_InstancedItems = new Dictionary(); + m_InstancedItems ??= new Dictionary(); m_InstancedItems.Add(carved, new InstancedItemInfo(carved, carver)); } @@ -836,8 +834,7 @@ namespace Server.Items if (item == null) return; - if (m_RestoreTable == null) - m_RestoreTable = new Dictionary(); + m_RestoreTable ??= new Dictionary(); m_RestoreTable[item] = loc; } diff --git a/Projects/Scripts/Items/Misc/EffectController.cs b/Projects/Scripts/Items/Misc/EffectController.cs index 6638370e5..1d23419ef 100644 --- a/Projects/Scripts/Items/Misc/EffectController.cs +++ b/Projects/Scripts/Items/Misc/EffectController.cs @@ -261,13 +261,7 @@ namespace Server.Items public void PlaySound(IEntity trigger) { - IEntity ent = null; - - if (PlaySoundAtTrigger) - ent = trigger; - - if (ent == null) - ent = this; + IEntity ent = PlaySoundAtTrigger ? trigger : this; Effects.PlaySound((ent as Item)?.GetWorldLocation() ?? ent.Location, ent.Map, SoundID); } @@ -292,13 +286,8 @@ namespace Server.Items public void InternalDoEffect(IEntity trigger) { - IEntity from = m_Source, to = m_Target; - - if (from == null) - from = trigger; - - if (to == null) - to = trigger; + IEntity from = m_Source ?? trigger; + IEntity to = m_Target ?? trigger; switch (EffectType) { @@ -334,4 +323,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Misc/Firebomb.cs b/Projects/Scripts/Items/Misc/Firebomb.cs index 3be4a023a..ea1bb7115 100644 --- a/Projects/Scripts/Items/Misc/Firebomb.cs +++ b/Projects/Scripts/Items/Misc/Firebomb.cs @@ -66,8 +66,7 @@ namespace Server.Items from.SendLocalizedMessage(1060581); // You've already lit it! Better throw it now! } - if (m_Users == null) - m_Users = new List(); + m_Users ??= new List(); if (!m_Users.Contains(from)) m_Users.Add(from); diff --git a/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs b/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs index 29544a59a..30dc3abfc 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs @@ -76,8 +76,7 @@ namespace Server.Items from.RevealingAction(); - if (Users == null) - Users = new List(); + Users ??= new List(); if (!Users.Contains(from)) Users.Add(from); diff --git a/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs b/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs index 9c0692773..60e0d65c7 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs @@ -810,11 +810,8 @@ namespace Server.Items } } - if (Attributes == null) - Attributes = new AosAttributes(this); - - if (SkillBonuses == null) - SkillBonuses = new AosSkillBonuses(this); + Attributes ??= new AosAttributes(this); + SkillBonuses ??= new AosSkillBonuses(this); if (Core.AOS && Parent is Mobile mobile) SkillBonuses.AddTo(mobile); diff --git a/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs b/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs index 665dd1535..7ff01a088 100644 --- a/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs +++ b/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs @@ -387,7 +387,7 @@ namespace Server.Items double toHeal = min + Utility.RandomDouble() * (max - min); if (Patient.Body.IsMonster || Patient.Body.IsAnimal) - toHeal += Patient.HitsMax / 100; + toHeal += Patient.HitsMax / 100.0; if (Core.AOS) toHeal -= toHeal * Slips * 0.35; // TODO: Verify algorithm diff --git a/Projects/Scripts/Items/Skill Items/Misc/RecipeScroll.cs b/Projects/Scripts/Items/Skill Items/Misc/RecipeScroll.cs index 994230dda..53e190a8d 100644 --- a/Projects/Scripts/Items/Skill Items/Misc/RecipeScroll.cs +++ b/Projects/Scripts/Items/Skill Items/Misc/RecipeScroll.cs @@ -66,8 +66,7 @@ namespace Server.Items { if (!pm.HasRecipe(r)) { - bool allRequiredSkills = true; - double chance = r.CraftItem.GetSuccessChance(pm, null, r.CraftSystem, false, ref allRequiredSkills); + double chance = r.CraftItem.GetSuccessChance(pm, null, r.CraftSystem, false, out var allRequiredSkills); if (allRequiredSkills && chance >= 0.0) { diff --git a/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs b/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs index f7607b45b..4fb9761a1 100644 --- a/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs +++ b/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs @@ -274,13 +274,7 @@ namespace Server.Items private void InternalUpdatePetName() { - BaseCreature pet = Pet; - - if (pet == null) - PetName = ""; - else - PetName = pet.Name; - + PetName = Pet?.Name ?? ""; InvalidateProperties(); } diff --git a/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs b/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs index 743eb07d5..5cf050e98 100644 --- a/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs +++ b/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs @@ -63,8 +63,7 @@ namespace Server.Items public void TurnOn() { - if (m_Fire == null) - m_Fire = new Item(); + m_Fire ??= new Item(); m_Fire.ItemID = 0x19AB; m_Fire.Movable = false; diff --git a/Projects/Scripts/Items/Talismans/TalismanSlayer.cs b/Projects/Scripts/Items/Talismans/TalismanSlayer.cs index 15b84549a..badbeea1a 100644 --- a/Projects/Scripts/Items/Talismans/TalismanSlayer.cs +++ b/Projects/Scripts/Items/Talismans/TalismanSlayer.cs @@ -83,7 +83,7 @@ namespace Server.Items public static bool Slays(TalismanSlayerName name, Mobile m) { if (m == null || !m_Table.TryGetValue(name, out Type[] types) || types == null) - return false;; + return false; Type type = m.GetType(); diff --git a/Projects/Scripts/Items/Traps/FlameSpurtTrap.cs b/Projects/Scripts/Items/Traps/FlameSpurtTrap.cs index b1f7143e0..c98651238 100644 --- a/Projects/Scripts/Items/Traps/FlameSpurtTrap.cs +++ b/Projects/Scripts/Items/Traps/FlameSpurtTrap.cs @@ -18,8 +18,7 @@ namespace Server.Items public virtual void StartTimer() { - if (m_Timer == null) - m_Timer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0), Refresh); + m_Timer ??= Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0), Refresh); } public virtual void StopTimer() diff --git a/Projects/Scripts/Items/Weapons/BaseWeapon.cs b/Projects/Scripts/Items/Weapons/BaseWeapon.cs index 9c3dcdc16..c938c653b 100644 --- a/Projects/Scripts/Items/Weapons/BaseWeapon.cs +++ b/Projects/Scripts/Items/Weapons/BaseWeapon.cs @@ -107,10 +107,7 @@ namespace Server.Items PlayerConstructed = true; - Type resourceType = typeRes; - - if (resourceType == null) - resourceType = craftItem.Resources.GetAt(0).ItemType; + Type resourceType = typeRes ?? craftItem.Resources.GetAt(0).ItemType; if (Core.AOS) { diff --git a/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs b/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs index 46d81fb5f..fff827dc4 100644 --- a/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs +++ b/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs @@ -144,8 +144,7 @@ namespace Server.Items if (!pm.Warmode) { - if (m_RecoveryTimer == null) - m_RecoveryTimer = Timer.DelayCall(TimeSpan.FromSeconds(10), pm.RecoverAmmo); + m_RecoveryTimer ??= Timer.DelayCall(TimeSpan.FromSeconds(10), pm.RecoverAmmo); if (!m_RecoveryTimer.Running) m_RecoveryTimer.Start(); diff --git a/Projects/Scripts/Misc/AOS.cs b/Projects/Scripts/Misc/AOS.cs index cd64b917b..84a8c963d 100644 --- a/Projects/Scripts/Misc/AOS.cs +++ b/Projects/Scripts/Misc/AOS.cs @@ -1019,8 +1019,7 @@ namespace Server if (!GetValues(i, out SkillName skill, out double bonus)) continue; - if (m_Mods == null) - m_Mods = new List(); + m_Mods ??= new List(); SkillMod sk = new DefaultSkillMod(skill, true, bonus); sk.ObeyCap = true; diff --git a/Projects/Scripts/Misc/Email.cs b/Projects/Scripts/Misc/Email.cs index 7481f3a0f..dd9b05329 100644 --- a/Projects/Scripts/Misc/Email.cs +++ b/Projects/Scripts/Misc/Email.cs @@ -40,7 +40,7 @@ namespace Server.Misc writer.WriteLine(@$" ModernUO Speech Log Page - {pageType} - From: '{sender.RawName}', Account: '{((sender.Account is Account accSend) ? accSend.Username : " ??? ")}' + From: '{sender.RawName}', Account: '{(sender.Account is Account accSend ? accSend.Username : " ??? ")}' Location: {sender.Location} [{sender.Map}] Sent on: {time.Year}/{time.Month:00}/{time.Day:00} {time.Hour}:{time.Minute:00}:{time.Second:00} diff --git a/Projects/Scripts/Misc/Guild.cs b/Projects/Scripts/Misc/Guild.cs index 20fe9186a..3122401e7 100644 --- a/Projects/Scripts/Misc/Guild.cs +++ b/Projects/Scripts/Misc/Guild.cs @@ -345,9 +345,7 @@ namespace Server.Guilds if (state != null) { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Alliance, hue, 3, - from.Language, from.Name, text)); + p ??= Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Alliance, hue, 3, from.Language, from.Name, text)); state.Send(p); } @@ -936,10 +934,9 @@ namespace Server.Guilds if (!NewGuildSystem) return; - if (killer == null) - killer = victim.FindMostRecentDamager(false); + killer ??= victim.FindMostRecentDamager(false); - if (killer == null || victim.Guild == null || killer.Guild == null) + if (killer?.Guild == null || victim.Guild == null) return; Guild victimGuild = GetAllianceLeader(victim.Guild as Guild); @@ -1148,24 +1145,10 @@ namespace Server.Guilds } } - if (AllyDeclarations == null) - AllyDeclarations = new List(); - - if (AllyInvitations == null) - AllyInvitations = new List(); - - - if (AcceptedWars == null) - AcceptedWars = new List(); - - if (PendingWars == null) - PendingWars = new List(); - - - /* - if ( ( !NewGuildSystem && m_Guildstone == null )|| m_Members.Count == 0 ) - Disband(); - */ + AllyDeclarations ??= new List(); + AllyInvitations ??= new List(); + AcceptedWars ??= new List(); + PendingWars ??= new List(); Timer.DelayCall(TimeSpan.Zero, VerifyGuild_Callback); } @@ -1343,9 +1326,7 @@ namespace Server.Guilds if (state != null) { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Guild, hue, 3, - from.Language, from.Name, text)); + p ??= Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Guild, hue, 3, from.Language, from.Name, text)); state.Send(p); } diff --git a/Projects/Scripts/Misc/ShardPoller.cs b/Projects/Scripts/Misc/ShardPoller.cs index 120549bf1..7d0a7b84d 100644 --- a/Projects/Scripts/Misc/ShardPoller.cs +++ b/Projects/Scripts/Misc/ShardPoller.cs @@ -465,8 +465,7 @@ namespace Server.Misc public void QueuePoll(ShardPoller poller) { - if (m_Polls == null) - m_Polls = new Queue(4); + m_Polls ??= new Queue(4); m_Polls.Enqueue(poller); } @@ -479,11 +478,15 @@ namespace Server.Misc { if (m_Polls?.Count > 0) { - ShardPoller poller = m_Polls.Dequeue(); + ShardPoller shardPoller = m_Polls.Dequeue(); - if (poller != null) + if (shardPoller != null) Timer.DelayCall(TimeSpan.FromSeconds(1.0), - () => m_From.SendGump(new ShardPollGump(m_From, poller, false, m_Polls))); + data => + { + var (mobile, poller, polls) = data; + m_From.SendGump(new ShardPollGump(mobile, poller, false, polls)); + }, (m_From, shardPoller, m_Polls)); } if (info.ButtonID == 1) diff --git a/Projects/Scripts/Misc/SocketOptions.cs b/Projects/Scripts/Misc/SocketOptions.cs index 56d12f2d7..3a59aac2c 100644 --- a/Projects/Scripts/Misc/SocketOptions.cs +++ b/Projects/Scripts/Misc/SocketOptions.cs @@ -1,5 +1,4 @@ using System.Net; -using System.Net.Sockets; namespace Server { diff --git a/Projects/Scripts/Misc/VendorGenerator.cs b/Projects/Scripts/Misc/VendorGenerator.cs index 40451ac82..3e450fe0f 100644 --- a/Projects/Scripts/Misc/VendorGenerator.cs +++ b/Projects/Scripts/Misc/VendorGenerator.cs @@ -413,9 +413,9 @@ namespace Server floor.Add(p); for (int xo = -1; xo <= 1; ++xo) - for (int yo = -1; yo <= 1; ++yo) - if ((xo != 0 || yo != 0) && IsFloor(map, x + xo, y + yo, false)) - RecurseFindFloor(map, x + xo, y + yo, floor); + for (int yo = -1; yo <= 1; ++yo) + if ((xo != 0 || yo != 0) && IsFloor(map, x + xo, y + yo, false)) + RecurseFindFloor(map, x + xo, y + yo, floor); } [Flags] diff --git a/Projects/Scripts/Mobiles/AI/AnimalAI.cs b/Projects/Scripts/Mobiles/AI/AnimalAI.cs index 9cc4585ea..8912d8e73 100644 --- a/Projects/Scripts/Mobiles/AI/AnimalAI.cs +++ b/Projects/Scripts/Mobiles/AI/AnimalAI.cs @@ -121,8 +121,7 @@ namespace Server.Mobiles { AcquireFocusMob(m_Mobile.RangePerception * 2, m_Mobile.FightMode, true, false, true); - if (m_Mobile.FocusMob == null) - m_Mobile.FocusMob = m_Mobile.Combatant; + m_Mobile.FocusMob ??= m_Mobile.Combatant; return base.DoActionFlee(); } diff --git a/Projects/Scripts/Mobiles/BaseCreature.cs b/Projects/Scripts/Mobiles/BaseCreature.cs index e2e1fa026..561422140 100644 --- a/Projects/Scripts/Mobiles/BaseCreature.cs +++ b/Projects/Scripts/Mobiles/BaseCreature.cs @@ -403,9 +403,9 @@ namespace Server.Mobiles } } - public virtual bool IsNecroFamiliar => Summoned && m_ControlMaster != null && - SummonFamiliarSpell.Table.TryGetValue(m_ControlMaster, out BaseCreature bc) && - bc == this; + public virtual bool IsNecroFamiliar => + Summoned && m_ControlMaster != null && + SummonFamiliarSpell.Table.TryGetValue(m_ControlMaster, out BaseCreature bc) && bc == this; public virtual bool DeleteCorpseOnDeath => !Core.AOS && m_bSummoned; @@ -3732,8 +3732,7 @@ namespace Server.Mobiles public virtual void AddPetFriend(Mobile m) { - if (Friends == null) - Friends = new List(); + Friends ??= new List(); Friends.Add(m); } diff --git a/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs b/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs index 3273e5fd8..763fc9246 100644 --- a/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs +++ b/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs @@ -326,11 +326,11 @@ namespace Server.Mobiles private bool TimeToSpare() => m_Owner.NextCombatTime - Core.TickCount > 1000; - private bool OutOfMaxDistance(Mobile target) => !m_Owner.InRange(target, m_Owner.Weapon.MaxRange); + private bool OutOfMaxDistance(IPoint2D target) => !m_Owner.InRange(target, m_Owner.Weapon.MaxRange); - private bool InMinDistance(Mobile target) => m_Owner.InRange(target, 4); + private bool InMinDistance(IPoint2D target) => m_Owner.InRange(target, 4); - private void TeleportTo(Mobile target) + private void TeleportTo(IEntity target) { Point3D from = m_Owner.Location; Point3D to = target.Location; diff --git a/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/Succubus.cs b/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/Succubus.cs index 5197e253f..d95848ad5 100644 --- a/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/Succubus.cs +++ b/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/Succubus.cs @@ -61,10 +61,10 @@ namespace Server.Mobiles foreach (Mobile m in eable) { if (m == this || !CanBeHarmful(m) || - !(m is BaseCreature creature && (creature.Controlled || creature.Summoned || creature.Team != Team) || - m.Player)) + !(m.Player || m is BaseCreature creature && + (creature.Controlled || creature.Summoned || creature.Team != Team))) continue; - + DoHarmful(m); m.FixedParticles(0x374A, 10, 15, 5013, 0x496, 0, EffectLayer.Waist); @@ -77,7 +77,7 @@ namespace Server.Mobiles Hits += toDrain; m.Damage(toDrain, this); } - + eable.Free(); } @@ -109,4 +109,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Monsters/ML/Special/Meraktus.cs b/Projects/Scripts/Mobiles/Monsters/ML/Special/Meraktus.cs index 4b04c4e43..a905126af 100644 --- a/Projects/Scripts/Mobiles/Monsters/ML/Special/Meraktus.cs +++ b/Projects/Scripts/Mobiles/Monsters/ML/Special/Meraktus.cs @@ -184,7 +184,7 @@ namespace Server.Mobiles continue; if (m is PlayerMobile pm && pm.Mounted) - pm.Mount.Rider = null; + pm.Mount.Rider = null; int damage = (int)(m.Hits * 0.6); if (damage < 10) diff --git a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs index 1c9f8d259..9c6655414 100644 --- a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs +++ b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs @@ -76,8 +76,7 @@ namespace Server.Mobiles { OpenedBy = from; - if (m_Timer == null) - m_Timer = new DecayTimer(this); + m_Timer ??= new DecayTimer(this); if (!m_Timer.Running) m_Timer.Start(); diff --git a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs index fa289478d..f29936ee6 100644 --- a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs +++ b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs @@ -35,8 +35,7 @@ namespace Server.Mobiles Body = 0x15; BaseSoundID = 0xDB; break; - default: - case 5: // slime + default: // slime Body = 51; BaseSoundID = 456; break; diff --git a/Projects/Scripts/Mobiles/PlayerMobile.cs b/Projects/Scripts/Mobiles/PlayerMobile.cs index 5a607ac1b..88863f64b 100644 --- a/Projects/Scripts/Mobiles/PlayerMobile.cs +++ b/Projects/Scripts/Mobiles/PlayerMobile.cs @@ -1882,7 +1882,7 @@ namespace Server.Mobiles pointsToGain += (int)Math.Sqrt(GameTime.TotalSeconds * 4); pointsToGain *= 5; - pointsToGain += (int)Math.Pow(Skills.Total / 250, 2); + pointsToGain += (int)Math.Pow(Skills.Total / 250.0, 2); if (VirtueHelper.Award(m, VirtueName.Justice, pointsToGain, ref gainedPath)) { @@ -1894,7 +1894,7 @@ namespace Server.Mobiles m.FixedParticles(0x375A, 9, 20, 5027, EffectLayer.Waist); m.PlaySound(0x1F7); - m_NextJustAward = DateTime.UtcNow + TimeSpan.FromMinutes(pointsToGain / 3); + m_NextJustAward = DateTime.UtcNow + TimeSpan.FromMinutes(pointsToGain / 3.0); } } } @@ -2010,9 +2010,7 @@ namespace Server.Mobiles if (mob?.AccessLevel >= AccessLevel.GameMaster && mob.AccessLevel > from.AccessLevel) { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Regular, from.SpeechHue, 3, - from.Language, from.Name, text)); + p ??= Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Regular, from.SpeechHue, 3, from.Language, from.Name, text)); ns.Send(p); } @@ -2358,32 +2356,23 @@ namespace Server.Mobiles } } - if (RecentlyReported == null) - RecentlyReported = new List(); + RecentlyReported ??= new List(); // Professions weren't verified on 1.0 RC0 if (!CharacterCreation.VerifyProfession(Profession)) Profession = 0; - if (PermaFlags == null) - PermaFlags = new List(); + PermaFlags ??= new List(); + JusticeProtectors ??= new List(); + BOBFilter ??= new BOBFilter(); - if (JusticeProtectors == null) - JusticeProtectors = new List(); - - if (BOBFilter == null) - BOBFilter = new BOBFilter(); - - if (m_GuildRank == null) - m_GuildRank = - RankDefinition - .Member; //Default to member if going from older version to new version (only time it should be null) + //Default to member if going from older version to new version (only time it should be null) + m_GuildRank ??= RankDefinition.Member; if (LastOnline == DateTime.MinValue && Account != null) LastOnline = ((Account)Account).LastLogin; - if (ChampionTitles == null) - ChampionTitles = new ChampionTitleInfo(); + ChampionTitles ??= new ChampionTitleInfo(); if (AccessLevel > AccessLevel.Player) m_IgnoreMobiles = true; @@ -2797,9 +2786,10 @@ namespace Server.Mobiles for (int i = AutoStabled.Count - 1; i >= 0; --i) { - BaseCreature pet = AutoStabled[i] as BaseCreature; + if (!(AutoStabled[i] is BaseCreature pet)) + continue; - if (pet?.Deleted == true) + if (pet.Deleted) { pet.IsStabled = false; pet.StabledBy = null; @@ -3099,22 +3089,15 @@ namespace Server.Mobiles if (ammo == null) continue; - string name = ammo.Name; + ammo.Amount = kvp.Value; - if (name == null) + string name = ammo.Name ?? ammo switch { - if (ammo is Arrow) - name = "arrow"; - else if (ammo is Bolt) - name = "bolt"; - } - - if (name != null && ammo.Amount > 1) - name = $"{name}s"; - - if (name == null) - name = $"#{ammo.LabelNumber}"; + Arrow _ => $"arrow{(ammo.Amount != 1 ? "s" : "")}", + Bolt _ => $"bolt{(ammo.Amount != 1 ? "s" : "")}", + _ => $"#{ammo.LabelNumber}" + }; PlaceInBackpack(ammo); SendLocalizedMessage(1073504, $"{ammo.Amount}\t{name}"); // You recover ~1_NUM~ ~2_AMMO~. @@ -3779,10 +3762,7 @@ namespace Server.Mobiles m_DuelPlayer = value; - if (m_DuelPlayer == null) - DuelContext = null; - else - DuelContext = m_DuelPlayer.Participant.Context; + DuelContext = m_DuelPlayer?.Participant.Context; bool isInTourney = DuelContext?.Finished == false && DuelContext.m_Tournament != null; @@ -4435,8 +4415,7 @@ namespace Server.Mobiles if (m_Values == null || index < 0 || index >= m_Values.Length) return 0; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); return m_Values[index].Value; } @@ -4446,16 +4425,14 @@ namespace Server.Mobiles if (m_Values == null || index < 0 || index >= m_Values.Length) return DateTime.MinValue; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); return m_Values[index].LastDecay; } public void SetValue(int index, int value) { - if (m_Values == null) - m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; if (value < 0) value = 0; @@ -4463,36 +4440,31 @@ namespace Server.Mobiles if (index < 0 || index >= m_Values.Length) return; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); m_Values[index].Value = value; } public void Award(int index, int value) { - if (m_Values == null) - m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; if (index < 0 || index >= m_Values.Length || value <= 0) return; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); m_Values[index].Value += value; } public void Atrophy(int index, int value) { - if (m_Values == null) - m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; if (index < 0 || index >= m_Values.Length || value <= 0) return; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); int before = m_Values[index].Value; @@ -4518,8 +4490,7 @@ namespace Server.Mobiles for (int i = 0; i < length; i++) { - if (titles.m_Values[i] == null) - titles.m_Values[i] = new TitleInfo(); + titles.m_Values[i] ??= new TitleInfo(); TitleInfo.Serialize(writer, titles.m_Values[i]); } @@ -4531,8 +4502,7 @@ namespace Server.Mobiles if (t == null) return; - if (t.m_Values == null) - t.m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + t.m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; for (int i = 0; i < t.m_Values.Length; i++) if (t.GetLastDecay(i) + LossDelay < DateTime.UtcNow) @@ -4546,14 +4516,9 @@ namespace Server.Mobiles if (t == null) return; - if (t.m_Values == null) - t.m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + t.m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; - int count = 1; - - for (int i = 0; i < t.m_Values.Length; i++) - if (t.m_Values[i].Value > 900) - count++; + int count = 1 + t.m_Values.Count(t1 => t1.Value > 900); t.Harrower = Math.Max(count, t.Harrower); //Harrower titles never decay. } @@ -4611,8 +4576,7 @@ namespace Server.Mobiles public virtual void AcquireRecipe(int recipeID) { - if (m_AcquiredRecipes == null) - m_AcquiredRecipes = new Dictionary(); + m_AcquiredRecipes ??= new Dictionary(); m_AcquiredRecipes[recipeID] = true; } @@ -4648,8 +4612,7 @@ namespace Server.Mobiles RemoveBuff(b); //Check & subsequently remove the old one. - if (m_BuffTable == null) - m_BuffTable = new Dictionary(); + m_BuffTable ??= new Dictionary(); m_BuffTable.Add(b.ID, b); diff --git a/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs b/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs index 3deb1f011..3354c0948 100644 --- a/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs +++ b/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs @@ -50,8 +50,7 @@ namespace Server.Mobiles public TownCrierEntry AddEntry(string[] lines, TimeSpan duration) { - if (Entries == null) - Entries = new List(); + Entries ??= new List(); TownCrierEntry tce = new TownCrierEntry(lines, duration); @@ -204,10 +203,7 @@ namespace Server.Mobiles owner.GetRandomEntry(); // force expiration checks - int count = 0; - - if (entries != null) - count = entries.Count; + int count = entries?.Count ?? 0; AddImageTiled(0, 0, 300, 38 + (count == 0 ? 20 : count * 85), 0xA40); AddAlphaRegion(1, 1, 298, 36 + (count == 0 ? 20 : count * 85)); @@ -384,15 +380,13 @@ namespace Server.Mobiles public TownCrierEntry AddEntry(string[] lines, TimeSpan duration) { - if (Entries == null) - Entries = new List(); + Entries ??= new List(); TownCrierEntry tce = new TownCrierEntry(lines, duration); Entries.Add(tce); - if (m_AutoShoutTimer == null) - m_AutoShoutTimer = Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), AutoShout_Callback); + m_AutoShoutTimer ??= Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), AutoShout_Callback); return tce; } @@ -417,8 +411,7 @@ namespace Server.Mobiles public void ForceBeginAutoShout() { - if (m_AutoShoutTimer == null) - m_AutoShoutTimer = Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), AutoShout_Callback); + m_AutoShoutTimer ??= Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), AutoShout_Callback); } private void AutoShout_Callback() @@ -433,9 +426,8 @@ namespace Server.Mobiles } else if (m_NewsTimer == null) { - int index = 0; m_NewsTimer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(3.0), - () => ShoutNews_Callback(tce, index)); + () => ShoutNews_Callback(tce, 0)); PublicOverheadMessage(MessageType.Regular, 0x3B2, 502976); // Hear ye! Hear ye! } @@ -478,9 +470,8 @@ namespace Server.Mobiles } else { - int index = 0; m_NewsTimer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(3.0), - () => ShoutNews_Callback(tce, index)); + () => ShoutNews_Callback(tce, 0)); PublicOverheadMessage(MessageType.Regular, 0x3B2, 502978); // Some of the latest news! } diff --git a/Projects/Scripts/Mobiles/Vendors/PlayerVendor.cs b/Projects/Scripts/Mobiles/Vendors/PlayerVendor.cs index c950f1c64..10cb857ee 100644 --- a/Projects/Scripts/Mobiles/Vendors/PlayerVendor.cs +++ b/Projects/Scripts/Mobiles/Vendors/PlayerVendor.cs @@ -584,8 +584,7 @@ namespace Server.Mobiles { if (House.IsOwner(Owner)) // Move to moving crate { - if (House.MovingCrate == null) - House.MovingCrate = new MovingCrate(House); + House.MovingCrate ??= new MovingCrate(House); if (HoldGold > 0) Banker.Deposit(House.MovingCrate, HoldGold); diff --git a/Projects/Scripts/Mobiles/Vendors/RentedVendor.cs b/Projects/Scripts/Mobiles/Vendors/RentedVendor.cs index 7e889489c..1b28aa786 100644 --- a/Projects/Scripts/Mobiles/Vendors/RentedVendor.cs +++ b/Projects/Scripts/Mobiles/Vendors/RentedVendor.cs @@ -129,8 +129,7 @@ namespace Server.Mobiles { if (RentalGold > 0 && House?.IsAosRules == true) { - if (House.MovingCrate == null) - House.MovingCrate = new MovingCrate(House); + House.MovingCrate ??= new MovingCrate(House); Banker.Deposit(House.MovingCrate, RentalGold); RentalGold = 0; diff --git a/Projects/Scripts/Mobiles/Vendors/VendorInventory.cs b/Projects/Scripts/Mobiles/Vendors/VendorInventory.cs index 93f60ff02..039e8dadc 100644 --- a/Projects/Scripts/Mobiles/Vendors/VendorInventory.cs +++ b/Projects/Scripts/Mobiles/Vendors/VendorInventory.cs @@ -116,8 +116,7 @@ namespace Server.Mobiles { if (m_Inventory.Gold > 0) { - if (house.MovingCrate == null) - house.MovingCrate = new MovingCrate(house); + house.MovingCrate ??= new MovingCrate(house); Banker.Deposit(house.MovingCrate, m_Inventory.Gold); } @@ -134,4 +133,4 @@ namespace Server.Mobiles } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Multis/BaseHouse.cs b/Projects/Scripts/Multis/BaseHouse.cs index 673cb8f6a..f80e95403 100644 --- a/Projects/Scripts/Multis/BaseHouse.cs +++ b/Projects/Scripts/Multis/BaseHouse.cs @@ -995,8 +995,7 @@ namespace Server.Multis public void DropToMovingCrate(Item item) { - if (MovingCrate == null) - MovingCrate = new MovingCrate(this); + MovingCrate ??= new MovingCrate(this); MovingCrate.DropItem(item); } @@ -2594,32 +2593,16 @@ namespace Server.Multis Account acct = mob.Account as Account; Mobile trans = null; - for (int i = 0; i < acct.Length; ++i) - if (acct[i] != null && acct[i] != mob) - trans = acct[i]; + if (acct != null) + for (int i = 0; i < acct.Length; ++i) + if (acct[i] != null && acct[i] != mob) + trans = acct[i]; for (int i = 0; i < houses.Count; ++i) { BaseHouse house = houses[i]; - bool canClaim = false; - - if (trans == null) - canClaim = house.CoOwners.Count > 0; - /*{ - for ( int j = 0; j < house.CoOwners.Count; ++j ) - { - Mobile check = house.CoOwners[j] as Mobile; - - if ( check != null && !check.Deleted && !HasAccountHouse( check ) ) - { - canClaim = true; - break; - } - } - }*/ - - if (trans == null && !canClaim) + if (trans == null && house.CoOwners.Count == 0) Timer.DelayCall(TimeSpan.Zero, house.Delete); else house.Owner = trans; @@ -2801,21 +2784,8 @@ namespace Server.Multis AllHouses.Remove(this); } - public static bool HasHouse(Mobile m) - { - if (m == null || !m_Table.TryGetValue(m, out List list)) - return false; - - for (int i = 0; i < list.Count; ++i) - { - BaseHouse h = list[i]; - - if (!h.Deleted) - return true; - } - - return false; - } + public static bool HasHouse(Mobile m) => + m != null && m_Table.TryGetValue(m, out List list) && list.Any(h => !h.Deleted); public static bool HasAccountHouse(Mobile m) { @@ -2829,35 +2799,15 @@ namespace Server.Multis return false; } - public bool IsOwner(Mobile m) - { - if (m == null) - return false; + public bool IsOwner(Mobile m) => + m != null && (m == m_Owner || m.AccessLevel >= AccessLevel.GameMaster || + IsAosRules && AccountHandler.CheckAccount(m, m_Owner)); - if (m == m_Owner || m.AccessLevel >= AccessLevel.GameMaster) - return true; + public bool IsCoOwner(Mobile m) => + m != null && CoOwners != null && + (IsOwner(m) || CoOwners.Contains(m) || !IsAosRules && AccountHandler.CheckAccount(m, m_Owner)); - return IsAosRules && AccountHandler.CheckAccount(m, m_Owner); - } - - public bool IsCoOwner(Mobile m) - { - if (m == null || CoOwners == null) - return false; - - if (IsOwner(m) || CoOwners.Contains(m)) - return true; - - return !IsAosRules && AccountHandler.CheckAccount(m, m_Owner); - } - - public bool IsGuildMember(Mobile m) - { - if (m == null || Owner?.Guild == null) - return false; - - return m.Guild == Owner.Guild; - } + public bool IsGuildMember(Mobile m) => m != null && Owner?.Guild != null && m.Guild == Owner.Guild; public void RemoveKeys(Mobile m) { @@ -2866,8 +2816,7 @@ namespace Server.Multis uint keyValue = 0; for (int i = 0; keyValue == 0 && i < Doors.Count; ++i) - if (Doors[i] is BaseDoor door) - keyValue = door.KeyValue; + keyValue = Doors[i].KeyValue; Key.RemoveKeys(m, keyValue); } @@ -2879,30 +2828,23 @@ namespace Server.Multis if (Doors != null) for (int i = 0; i < Doors.Count; ++i) - if (Doors[i] is BaseDoor door) - door.KeyValue = keyValue; + Doors[i].KeyValue = keyValue; } public void RemoveLocks() { if (Doors != null) for (int i = 0; i < Doors.Count; ++i) - if (Doors[i] is BaseDoor door) - { - door.KeyValue = 0; - door.Locked = false; - } + { + BaseDoor door = Doors[i]; + door.KeyValue = 0; + door.Locked = false; + } } public virtual HouseDeed GetDeed() => null; - public bool IsFriend(Mobile m) - { - if (m == null || Friends == null) - return false; - - return IsCoOwner(m) || Friends.Contains(m); - } + public bool IsFriend(Mobile m) => m != null && Friends != null && (IsCoOwner(m) || Friends.Contains(m)); public bool IsBanned(Mobile m) { diff --git a/Projects/Scripts/Multis/Boats/BaseBoat.cs b/Projects/Scripts/Multis/Boats/BaseBoat.cs index 62019dcd3..1e992560c 100644 --- a/Projects/Scripts/Multis/Boats/BaseBoat.cs +++ b/Projects/Scripts/Multis/Boats/BaseBoat.cs @@ -1185,44 +1185,44 @@ namespace Server.Multis MultiComponentList newComponents = MultiData.GetComponents(itemID); for (int x = 0; x < newComponents.Width; ++x) - for (int y = 0; y < newComponents.Height; ++y) + for (int y = 0; y < newComponents.Height; ++y) + { + int tx = p.X + newComponents.Min.X + x; + int ty = p.Y + newComponents.Min.Y + y; + + if (newComponents.Tiles[x][y].Length == 0 || Contains(tx, ty)) + continue; + + LandTile landTile = map.Tiles.GetLandTile(tx, ty); + StaticTile[] tiles = map.Tiles.GetStaticTiles(tx, ty, true); + + bool hasWater = landTile.Z == p.Z && + (landTile.ID >= 168 && landTile.ID <= 171 || landTile.ID >= 310 && landTile.ID <= 311); + + // int z = p.Z; + + //int landZ = 0, landAvg = 0, landTop = 0; + + //map.GetAverageZ( tx, ty, ref landZ, ref landAvg, ref landTop ); + + //if ( !landTile.Ignored && top > landZ && landTop > z ) + // return false; + + for (int i = 0; i < tiles.Length; ++i) { - int tx = p.X + newComponents.Min.X + x; - int ty = p.Y + newComponents.Min.Y + y; + StaticTile tile = tiles[i]; + bool isWater = tile.ID >= 0x1796 && tile.ID <= 0x17B2; - if (newComponents.Tiles[x][y].Length == 0 || Contains(tx, ty)) - continue; - - LandTile landTile = map.Tiles.GetLandTile(tx, ty); - StaticTile[] tiles = map.Tiles.GetStaticTiles(tx, ty, true); - - bool hasWater = landTile.Z == p.Z && - (landTile.ID >= 168 && landTile.ID <= 171 || landTile.ID >= 310 && landTile.ID <= 311); - - // int z = p.Z; - - //int landZ = 0, landAvg = 0, landTop = 0; - - //map.GetAverageZ( tx, ty, ref landZ, ref landAvg, ref landTop ); - - //if ( !landTile.Ignored && top > landZ && landTop > z ) - // return false; - - for (int i = 0; i < tiles.Length; ++i) - { - StaticTile tile = tiles[i]; - bool isWater = tile.ID >= 0x1796 && tile.ID <= 0x17B2; - - if (tile.Z == p.Z && isWater) - hasWater = true; - else if (tile.Z >= p.Z && !isWater) - return false; - } - - if (!hasWater) + if (tile.Z == p.Z && isWater) + hasWater = true; + else if (tile.Z >= p.Z && !isWater) return false; } + if (!hasWater) + return false; + } + IPooledEnumerable eable = map.GetItemsInBounds(new Rectangle2D(p.X + newComponents.Min.X, p.Y + newComponents.Min.Y, newComponents.Width, newComponents.Height)); diff --git a/Projects/Scripts/Multis/HouseFoundation.cs b/Projects/Scripts/Multis/HouseFoundation.cs index e156a4341..568fc39a8 100644 --- a/Projects/Scripts/Multis/HouseFoundation.cs +++ b/Projects/Scripts/Multis/HouseFoundation.cs @@ -300,8 +300,7 @@ namespace Server.Multis public void AddFixtures(Mobile from, MultiTileEntry[] list) { - if (Fixtures == null) - Fixtures = new List(); + Fixtures ??= new List(); uint keyValue = 0; @@ -530,7 +529,6 @@ namespace Server.Multis switch (door.Facing) { default: - case DoorFacing.WestCW: linkFacing = DoorFacing.EastCCW; xOffset = 1; yOffset = 0; @@ -618,7 +616,6 @@ namespace Server.Multis switch (type) { default: - case FoundationType.DarkWood: corner = 0x0014; east = 0x0015; south = 0x0016; @@ -1284,7 +1281,6 @@ namespace Server.Multis switch (dir) { default: - case 0: // North { xStart = x; yStart = y + height; diff --git a/Projects/Scripts/Regions/GuardedRegion.cs b/Projects/Scripts/Regions/GuardedRegion.cs index 39a6df5d8..fdaa135e0 100644 --- a/Projects/Scripts/Regions/GuardedRegion.cs +++ b/Projects/Scripts/Regions/GuardedRegion.cs @@ -195,8 +195,6 @@ namespace Server.Regions public override void OnExit(Mobile m) { -// if (IsDisabled()) - return; } public override void OnSpeech(SpeechEventArgs args) diff --git a/Projects/Scripts/Regions/Spawning/SpawnEntry.cs b/Projects/Scripts/Regions/Spawning/SpawnEntry.cs index 814aa3907..3c9499f03 100644 --- a/Projects/Scripts/Regions/Spawning/SpawnEntry.cs +++ b/Projects/Scripts/Regions/Spawning/SpawnEntry.cs @@ -264,9 +264,7 @@ namespace Server.Regions if (entity != null) { - if (m_RemoveList == null) - m_RemoveList = new List(); - + m_RemoveList ??= new List(); m_RemoveList.Add(entity); } } diff --git a/Projects/Scripts/Regions/Spawning/SpawnPersistence.cs b/Projects/Scripts/Regions/Spawning/SpawnPersistence.cs index d0146df6c..996917682 100644 --- a/Projects/Scripts/Regions/Spawning/SpawnPersistence.cs +++ b/Projects/Scripts/Regions/Spawning/SpawnPersistence.cs @@ -15,8 +15,7 @@ namespace Server.Regions public static void EnsureExistence() { - if (m_Instance == null) - m_Instance = new SpawnPersistence(); + m_Instance ??= new SpawnPersistence(); } public override void Serialize(IGenericWriter writer) @@ -54,4 +53,4 @@ namespace Server.Regions } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Skills/Hiding.cs b/Projects/Scripts/Skills/Hiding.cs index c136c666e..dde7e5e9a 100644 --- a/Projects/Scripts/Skills/Hiding.cs +++ b/Projects/Scripts/Skills/Hiding.cs @@ -30,13 +30,10 @@ namespace Server.SkillHandlers BaseHouse house = BaseHouse.FindHouseAt(m); if (house?.IsFriend(m) == true) - { bonus = 100.0; - } else if (!Core.AOS) { - if (house == null) - house = BaseHouse.FindHouseAt(new Point3D(m.X - 1, m.Y, 127), m.Map, 16) ?? + house ??= BaseHouse.FindHouseAt(new Point3D(m.X - 1, m.Y, 127), m.Map, 16) ?? BaseHouse.FindHouseAt(new Point3D(m.X + 1, m.Y, 127), m.Map, 16) ?? BaseHouse.FindHouseAt(new Point3D(m.X, m.Y - 1, 127), m.Map, 16) ?? BaseHouse.FindHouseAt(new Point3D(m.X, m.Y + 1, 127), m.Map, 16); diff --git a/Projects/Scripts/Skills/Poisoning.cs b/Projects/Scripts/Skills/Poisoning.cs index 31d7940e7..c83e5b066 100644 --- a/Projects/Scripts/Skills/Poisoning.cs +++ b/Projects/Scripts/Skills/Poisoning.cs @@ -19,7 +19,7 @@ namespace Server.SkillHandlers m.SendLocalizedMessage(502137); // Select the poison you wish to use - return TimeSpan.FromSeconds(10.0); // 10 second delay before beign able to re-use a skill + return TimeSpan.FromSeconds(10.0); // 10 second delay before being able to re-use a skill } private class InternalTargetPoison : Target @@ -167,4 +167,4 @@ namespace Server.SkillHandlers } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Skills/RemoveTrap.cs b/Projects/Scripts/Skills/RemoveTrap.cs index e6cf9440f..92e236214 100644 --- a/Projects/Scripts/Skills/RemoveTrap.cs +++ b/Projects/Scripts/Skills/RemoveTrap.cs @@ -27,10 +27,10 @@ namespace Server.SkillHandlers { m.Target = new InternalTarget(); - m.SendLocalizedMessage(502368); // Wich trap will you attempt to disarm? + m.SendLocalizedMessage(502368); // Which trap will you attempt to disarm? } - return TimeSpan.FromSeconds(10.0); // 10 second delay before beign able to re-use a skill + return TimeSpan.FromSeconds(10.0); // 10 second delay before being able to re-use a skill } private class InternalTarget : Target diff --git a/Projects/Scripts/Skills/SpiritSpeak.cs b/Projects/Scripts/Skills/SpiritSpeak.cs index d24077635..9f94e5c60 100644 --- a/Projects/Scripts/Skills/SpiritSpeak.cs +++ b/Projects/Scripts/Skills/SpiritSpeak.cs @@ -127,7 +127,7 @@ namespace Server.SkillHandlers public override void OnCast() { IPooledEnumerable eable = Caster.GetItemsInRange(3); - Corpse toChannel = eable.FirstOrDefault(item => item is Corpse corpse && !corpse.Channeled); + Corpse toChannel = eable.FirstOrDefault(corpse => !corpse.Channeled); eable.Free(); int min = 1 + (int)(Caster.Skills.SpiritSpeak.Value * 0.25); diff --git a/Projects/Scripts/Skills/Tracking.cs b/Projects/Scripts/Skills/Tracking.cs index 391c88e0b..db6f9650f 100644 --- a/Projects/Scripts/Skills/Tracking.cs +++ b/Projects/Scripts/Skills/Tracking.cs @@ -25,7 +25,7 @@ namespace Server.SkillHandlers m.CloseGump(); m.SendGump(new TrackWhatGump(m)); - return TimeSpan.FromSeconds(10.0); // 10 second delay before beign able to re-use a skill + return TimeSpan.FromSeconds(10.0); // 10 second delay before being able to re-use a skill } public static void AddInfo(Mobile tracker, Mobile target) diff --git a/Projects/Scripts/Spells/Base/SpellHelper.cs b/Projects/Scripts/Spells/Base/SpellHelper.cs index 3283b17f1..b5e31d6a3 100644 --- a/Projects/Scripts/Spells/Base/SpellHelper.cs +++ b/Projects/Scripts/Spells/Base/SpellHelper.cs @@ -604,7 +604,7 @@ namespace Server.Spells // Always allow monsters to teleport if (caster is BaseCreature bc && !bc.Controlled && !bc.Summoned && (type == TravelCheckType.TeleportTo || type == TravelCheckType.TeleportFrom)) - return true; + return true; m_TravelCaster = caster; m_TravelType = type; @@ -794,12 +794,9 @@ namespace Server.Spells #region Dueling if (Region.Find(loc, map).GetRegion() != null) - { - PlayerMobile pm = caster as PlayerMobile; - - if (pm.DuelContext?.Started != true || pm.DuelPlayer?.Eliminated != false) + if (caster is PlayerMobile pm && (pm.DuelContext?.Started != true || pm.DuelPlayer?.Eliminated != false)) return true; - } + #endregion GuardedRegion reg = Region.Find(loc, map).GetRegion(); diff --git a/Projects/Scripts/Spells/Chivalry/DispelEvil.cs b/Projects/Scripts/Spells/Chivalry/DispelEvil.cs index d76a6bebc..9677bb90c 100644 --- a/Projects/Scripts/Spells/Chivalry/DispelEvil.cs +++ b/Projects/Scripts/Spells/Chivalry/DispelEvil.cs @@ -74,7 +74,7 @@ namespace Server.Spells.Chivalry if (evil) { // TODO: Is this right? - double fleeChance = (100 - Math.Sqrt(m.Fame / 2)) * chiv * dispelSkill; + double fleeChance = (100 - Math.Sqrt(m.Fame / 2.0)) * chiv * dispelSkill; fleeChance /= 1000000; if (fleeChance > Utility.RandomDouble()) bc.BeginFlee(TimeSpan.FromSeconds(30.0)); diff --git a/Projects/Scripts/Spells/Eighth/AirElemental.cs b/Projects/Scripts/Spells/Eighth/AirElemental.cs index 0aec5b631..fb5c60b0f 100644 --- a/Projects/Scripts/Spells/Eighth/AirElemental.cs +++ b/Projects/Scripts/Spells/Eighth/AirElemental.cs @@ -39,7 +39,7 @@ namespace Server.Spells.Eighth { if (CheckSequence()) { - TimeSpan duration = TimeSpan.FromSeconds(2 * Caster.Skills.Magery.Fixed / 5); + TimeSpan duration = TimeSpan.FromSeconds(2 * Caster.Skills.Magery.Fixed / 5.0); if (Core.AOS) SpellHelper.Summon(new SummonedAirElemental(), Caster, 0x217, duration, false, false); diff --git a/Projects/Scripts/Spells/Eighth/EarthElemental.cs b/Projects/Scripts/Spells/Eighth/EarthElemental.cs index 18dfceb2a..53c93a25b 100644 --- a/Projects/Scripts/Spells/Eighth/EarthElemental.cs +++ b/Projects/Scripts/Spells/Eighth/EarthElemental.cs @@ -39,7 +39,7 @@ namespace Server.Spells.Eighth { if (CheckSequence()) { - TimeSpan duration = TimeSpan.FromSeconds(2 * Caster.Skills.Magery.Fixed / 5); + TimeSpan duration = TimeSpan.FromSeconds(2 * Caster.Skills.Magery.Fixed / 5.0); if (Core.AOS) SpellHelper.Summon(new SummonedEarthElemental(), Caster, 0x217, duration, false, false); diff --git a/Projects/Scripts/Spells/Fifth/SummonCreature.cs b/Projects/Scripts/Spells/Fifth/SummonCreature.cs index 4786ce796..2450b148b 100644 --- a/Projects/Scripts/Spells/Fifth/SummonCreature.cs +++ b/Projects/Scripts/Spells/Fifth/SummonCreature.cs @@ -70,7 +70,7 @@ namespace Server.Spells.Fifth TimeSpan duration; if (Core.AOS) - duration = TimeSpan.FromSeconds(2 * Caster.Skills.Magery.Fixed / 5); + duration = TimeSpan.FromSeconds(2 * Caster.Skills.Magery.Fixed / 5.0); else duration = TimeSpan.FromSeconds(4.0 * Caster.Skills.Magery.Value); diff --git a/Projects/Scripts/Spells/Fourth/FireField.cs b/Projects/Scripts/Spells/Fourth/FireField.cs index 24ea7ce32..9b38f4a89 100644 --- a/Projects/Scripts/Spells/Fourth/FireField.cs +++ b/Projects/Scripts/Spells/Fourth/FireField.cs @@ -65,7 +65,7 @@ namespace Server.Spells.Fourth TimeSpan duration; if (Core.AOS) - duration = TimeSpan.FromSeconds((15 + Caster.Skills.Magery.Fixed / 5) / 4); + duration = TimeSpan.FromSeconds((15 + Caster.Skills.Magery.Fixed / 5.0) / 4.0); else duration = TimeSpan.FromSeconds(4.0 + Caster.Skills.Magery.Value * 0.5); diff --git a/Projects/Scripts/Spells/Spellweaving/ArcaneCircle.cs b/Projects/Scripts/Spells/Spellweaving/ArcaneCircle.cs index c42b706c7..0b9757de1 100644 --- a/Projects/Scripts/Spells/Spellweaving/ArcaneCircle.cs +++ b/Projects/Scripts/Spells/Spellweaving/ArcaneCircle.cs @@ -112,7 +112,7 @@ namespace Server.Spells.Spellweaving // Everyone gets the Arcane Focus, power capped elsewhere weavers.AddRange(Caster.GetMobilesInRange(1) .Where(m => m != Caster && m is PlayerMobile && Caster.CanBeBeneficial(m, false) && - Math.Abs(Caster.Skills.Spellweaving.Value - m.Skills.Spellweaving.Value) <= 20)); + Math.Abs(Caster.Skills.Spellweaving.Value - m.Skills.Spellweaving.Value) <= 20)); return weavers; } diff --git a/Projects/Server/Buffers/MemoryPoolSlab.cs b/Projects/Server/Buffers/MemoryPoolSlab.cs index 38be52e5b..4461e572d 100644 --- a/Projects/Server/Buffers/MemoryPoolSlab.cs +++ b/Projects/Server/Buffers/MemoryPoolSlab.cs @@ -55,7 +55,7 @@ namespace System.Buffers _isDisposed = true; Array = null; - NativePointer = IntPtr.Zero;; + NativePointer = IntPtr.Zero; if (_gcHandle.IsAllocated) _gcHandle.Free(); } diff --git a/Projects/Server/Buffers/SlabMemoryPool.cs b/Projects/Server/Buffers/SlabMemoryPool.cs index acde6b894..2a73a87a6 100644 --- a/Projects/Server/Buffers/SlabMemoryPool.cs +++ b/Projects/Server/Buffers/SlabMemoryPool.cs @@ -106,7 +106,7 @@ namespace System.Buffers var basePtr = slab.NativePointer; // Page align the blocks - var offset = (int)((((ulong)basePtr + (uint)_blockSize - 1) & ~((uint)_blockSize - 1)) - (ulong)basePtr); + var offset = (int)((((ulong)basePtr + _blockSize - 1) & ~((uint)_blockSize - 1)) - (ulong)basePtr); // Ensure page aligned Debug.Assert(((ulong)basePtr + (uint)offset) % _blockSize == 0); diff --git a/Projects/Server/Effects.cs b/Projects/Server/Effects.cs index ead626d02..e58b1c2b7 100644 --- a/Projects/Server/Effects.cs +++ b/Projects/Server/Effects.cs @@ -63,8 +63,7 @@ namespace Server { state.Mobile.ProcessDelta(); - if (playSound == null) - playSound = Packet.Acquire(new PlaySound(soundID, p)); + playSound ??= Packet.Acquire(new PlaySound(soundID, p)); state.Send(playSound); } @@ -103,21 +102,18 @@ namespace Server { if (SendParticlesTo(state)) { - if (preEffect == null) - preEffect = Packet.Acquire(new TargetParticleEffect(e, 0, 10, 5, 0, 0, 5031, 3, 0)); + preEffect ??= Packet.Acquire(new TargetParticleEffect(e, 0, 10, 5, 0, 0, 5031, 3, 0)); state.Send(preEffect); } - if (boltEffect == null) - boltEffect = Packet.Acquire(new BoltEffect(e, hue)); + boltEffect ??= Packet.Acquire(new BoltEffect(e, hue)); state.Send(boltEffect); if (sound) { - if (playSound == null) - playSound = Packet.Acquire(new PlaySound(0x29, e)); + playSound ??= Packet.Acquire(new PlaySound(0x29, e)); state.Send(playSound); } @@ -178,16 +174,13 @@ namespace Server if (SendParticlesTo(state)) { - if (particles == null) - particles = Packet.Acquire(new LocationParticleEffect(e, itemID, speed, duration, hue, - renderMode, effect, unknown)); + particles ??= Packet.Acquire(new LocationParticleEffect(e, itemID, speed, duration, hue, renderMode, effect, unknown)); state.Send(particles); } else if (itemID != 0) { - if (regular == null) - regular = Packet.Acquire(new LocationEffect(e, itemID, speed, duration, hue, renderMode)); + regular ??= Packet.Acquire(new LocationEffect(e, itemID, speed, duration, hue, renderMode)); state.Send(regular); } @@ -257,16 +250,13 @@ namespace Server if (SendParticlesTo(state)) { - if (particles == null) - particles = Packet.Acquire(new TargetParticleEffect(target, itemID, speed, duration, hue, - renderMode, effect, (int)layer, unknown)); + particles ??= Packet.Acquire(new TargetParticleEffect(target, itemID, speed, duration, hue, renderMode, effect, (int)layer, unknown)); state.Send(particles); } else if (itemID != 0) { - if (regular == null) - regular = Packet.Acquire(new TargetEffect(target, itemID, speed, duration, hue, renderMode)); + regular ??= Packet.Acquire(new TargetEffect(target, itemID, speed, duration, hue, renderMode)); state.Send(regular); } @@ -340,18 +330,14 @@ namespace Server if (SendParticlesTo(state)) { - if (particles == null) - particles = Packet.Acquire(new MovingParticleEffect(from, to, itemID, speed, duration, - fixedDirection, explodes, hue, renderMode, effect, explodeEffect, explodeSound, layer, - unknown)); + 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) { - if (regular == null) - regular = Packet.Acquire(new MovingEffect(from, to, itemID, speed, duration, fixedDirection, - explodes, hue, renderMode)); + regular ??= Packet.Acquire(new MovingEffect(from, to, itemID, speed, duration, fixedDirection, explodes, hue, renderMode)); state.Send(regular); } @@ -370,7 +356,7 @@ namespace Server { if (map == null) return; - + IPooledEnumerable eable = map.GetClientsInRange(origin); p.Acquire(); @@ -390,7 +376,7 @@ namespace Server { if (map == null) return; - + IPooledEnumerable eable = map.GetClientsInRange(new Point3D(origin)); p.Acquire(); @@ -406,4 +392,4 @@ namespace Server eable.Free(); } } -} \ No newline at end of file +} diff --git a/Projects/Server/EventSink.cs b/Projects/Server/EventSink.cs index f93416e65..89a131305 100644 --- a/Projects/Server/EventSink.cs +++ b/Projects/Server/EventSink.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; using System.Net; -using System.Net.Sockets; using Microsoft.AspNetCore.Connections; using Server.Accounting; using Server.Guilds; diff --git a/Projects/Server/Gumps/GumpEntry.cs b/Projects/Server/Gumps/GumpEntry.cs index 732125b15..54ba4b573 100644 --- a/Projects/Server/Gumps/GumpEntry.cs +++ b/Projects/Server/Gumps/GumpEntry.cs @@ -44,32 +44,27 @@ namespace Server.Gumps protected void Delta(ref uint var, uint val) { - if (var != val) - var = val; + var = val; } protected void Delta(ref int var, int val) { - if (var != val) - var = val; + var = val; } protected void Delta(ref bool var, bool val) { - if (var != val) - var = val; + var = val; } protected void Delta(ref string var, string val) { - if (var != val) - var = val; + var = val; } protected void Delta(ref object[] var, object[] val) { - if (var != val) - var = val; + var = val; } public abstract string Compile(NetState ns); diff --git a/Projects/Server/Item.cs b/Projects/Server/Item.cs index 63d1d972b..c20ec7ea4 100644 --- a/Projects/Server/Item.cs +++ b/Projects/Server/Item.cs @@ -1522,26 +1522,26 @@ namespace Server { } - /// - /// Overridable. Method checked to see if the elemental resistances of this Item conflict with another Item on the - /// . - /// - /// - /// - /// - /// True - /// - /// There is a confliction. The elemental resistance bonuses of this Item should not be applied to the - /// - /// - /// - /// - /// False - /// There is no confliction. The bonuses should be applied. - /// - /// - /// - public virtual bool CheckPropertyConfliction(Mobile m) => false; + /// + /// Overridable. Method checked to see if the elemental resistances of this Item conflict with another Item on the + /// . + /// + /// + /// + /// + /// True + /// + /// There is a confliction. The elemental resistance bonuses of this Item should not be applied to the + /// + /// + /// + /// + /// False + /// There is no confliction. The bonuses should be applied. + /// + /// + /// + public virtual bool CheckPropertyConfliction(Mobile m) => false; /// /// Overridable. Sends the object property list to . @@ -1697,23 +1697,23 @@ namespace Server list.Add(1062203, "{0}", m.Name); // Blessed for ~1_NAME~ } - /// - /// Overridable. Fills an with everything applicable. By default, this invokes - /// , then Item.GetChildProperties or - /// Mobile.GetChildProperties. This method should be overridden to add any custom - /// properties. - /// - public virtual void GetProperties(ObjectPropertyList list) + /// + /// Overridable. Fills an with everything applicable. By default, this invokes + /// , then Item.GetChildProperties or + /// Mobile.GetChildProperties. This method should be overridden to add any custom + /// properties. + /// + public virtual void GetProperties(ObjectPropertyList list) { AddNameProperties(list); } - /// - /// Overridable. Event invoked when a child () is building it's . - /// Recursively calls Item.GetChildProperties or - /// Mobile.GetChildProperties. - /// - public virtual void GetChildProperties(ObjectPropertyList list, Item item) + /// + /// Overridable. Event invoked when a child () is building it's . + /// Recursively calls Item.GetChildProperties or + /// Mobile.GetChildProperties. + /// + public virtual void GetChildProperties(ObjectPropertyList list, Item item) { if (m_Parent is Item parentItem) parentItem.GetChildProperties(list, item); @@ -1721,12 +1721,12 @@ namespace Server parentMobile.GetChildProperties(list, item); } - /// - /// Overridable. Event invoked when a child () is building it's Name - /// . Recursively calls Item.GetChildNameProperties or - /// Mobile.GetChildNameProperties. - /// - public virtual void GetChildNameProperties(ObjectPropertyList list, Item item) + /// + /// Overridable. Event invoked when a child () is building it's Name + /// . Recursively calls Item.GetChildNameProperties or + /// Mobile.GetChildNameProperties. + /// + public virtual void GetChildNameProperties(ObjectPropertyList list, Item item) { if (m_Parent is Item parentItem) parentItem.GetChildNameProperties(list, item); @@ -1788,24 +1788,24 @@ namespace Server } } - /// - /// Overridable. Method checked to see if this item may be equipped while casting a spell. By default, this returns false. It - /// is overridden on spellbook and spell channeling weapons or shields. - /// - /// True if it may, false if not. - /// - /// - /// public override bool AllowEquippedCast( Mobile from ) - /// { - /// if ( from.Int >= 100 ) - /// return true; - /// - /// return base.AllowEquippedCast( from ); - /// } - /// When placed in an Item script, the item may be cast when equipped if the has 100 or more - /// intelligence. Otherwise, it will drop to their backpack. - /// - public virtual bool AllowEquippedCast(Mobile from) => false; + /// + /// Overridable. Method checked to see if this item may be equipped while casting a spell. By default, this returns false. It + /// is overridden on spellbook and spell channeling weapons or shields. + /// + /// True if it may, false if not. + /// + /// + /// public override bool AllowEquippedCast( Mobile from ) + /// { + /// if ( from.Int >= 100 ) + /// return true; + /// + /// return base.AllowEquippedCast( from ); + /// } + /// When placed in an Item script, the item may be cast when equipped if the has 100 or more + /// intelligence. Otherwise, it will drop to their backpack. + /// + public virtual bool AllowEquippedCast(Mobile from) => false; public virtual bool CheckConflictingLayer(Mobile m, Item item, Layer layer) => m_Layer == layer; @@ -2824,8 +2824,7 @@ namespace Server if (m.CanSee(this) && m.InRange(worldLoc, GetUpdateRange(m))) { - if (p == null) - p = Packet.Acquire(new MessageLocalized(Serial, m_ItemID, type, hue, 3, number, Name, args)); + p ??= Packet.Acquire(new MessageLocalized(Serial, m_ItemID, type, hue, 3, number, Name, args)); state.Send(p); } diff --git a/Projects/Server/Items/Container.cs b/Projects/Server/Items/Container.cs index 02669f962..dca428fc6 100644 --- a/Projects/Server/Items/Container.cs +++ b/Projects/Server/Items/Container.cs @@ -485,9 +485,6 @@ namespace Server.Items int extraItems = 0; int extraWeight = 0; -// from.SendMessage( String.Format( "There are {0} items in this container.", this.Items.Count ) ); -// from.SendMessage( String.Format( "There are {0} items being dropped into this container.", droppedItems.Length ) ); - for (int i = 0; i < droppedItems.Length; i++) { Item dropped = droppedItems[i]; @@ -679,8 +676,7 @@ namespace Server.Items if (!contains) { - if (Openers == null) - Openers = new List(); + Openers ??= new List(); Openers.Add(opener); } @@ -692,7 +688,10 @@ namespace Server.Items public virtual void SendContentTo(NetState state) { - if (state?.ContainerGridLines == true) + if (state == null) + return; + + if (state.ContainerGridLines) state.Send(new ContainerContent6017(state.Mobile, this)); else state.Send(new ContainerContent(state.Mobile, this)); @@ -1646,8 +1645,7 @@ namespace Server.Items ContainerData data = new ContainerData(gumpID, bounds, dropSound); - if (Default == null) - Default = data; + Default ??= data; if (split.Length >= 4) { @@ -1672,8 +1670,7 @@ namespace Server.Items } } - if (Default == null) - Default = new ContainerData(0x3C, new Rectangle2D(44, 65, 142, 94), 0x48); + Default ??= new ContainerData(0x3C, new Rectangle2D(44, 65, 142, 94), 0x48); } public ContainerData(int gumpID, Rectangle2D bounds, int dropSound) diff --git a/Projects/Server/LibUv/Internal/UvWriteReq.cs b/Projects/Server/LibUv/Internal/UvWriteReq.cs index 1b30c4ccb..29b8b4e9f 100644 --- a/Projects/Server/LibUv/Internal/UvWriteReq.cs +++ b/Projects/Server/LibUv/Internal/UvWriteReq.cs @@ -76,6 +76,9 @@ namespace Libuv.Internal nBuffers++; var pBuffers = (LibuvFunctions.uv_buf_t*)_bufs; + if (pBuffers == null) + throw new NullReferenceException(); + if (nBuffers > BUFFER_COUNT) { // create and pin buffer array when it's larger than the pre-allocated one @@ -83,6 +86,8 @@ namespace Libuv.Internal var gcHandle = GCHandle.Alloc(bufArray, GCHandleType.Pinned); _pins.Add(gcHandle); pBuffers = (LibuvFunctions.uv_buf_t*)gcHandle.AddrOfPinnedObject(); + if (pBuffers == null) + throw new NullReferenceException(); } if (nBuffers == 1) @@ -149,12 +154,15 @@ namespace Libuv.Internal UvStreamHandle handle, ArraySegment> bufs, UvStreamHandle sendHandle, - Action callback, - object state) + Action callback, object state + ) { try { var pBuffers = (LibuvFunctions.uv_buf_t*)_bufs; + if (pBuffers == null) + throw new NullReferenceException(); + var nBuffers = bufs.Count; if (nBuffers > BUFFER_COUNT) { @@ -163,12 +171,14 @@ namespace Libuv.Internal var gcHandle = GCHandle.Alloc(bufArray, GCHandleType.Pinned); _pins.Add(gcHandle); pBuffers = (LibuvFunctions.uv_buf_t*)gcHandle.AddrOfPinnedObject(); + if (pBuffers == null) + throw new NullReferenceException(); } for (var index = 0; index < nBuffers; index++) { // create and pin each segment being written - var buf = bufs.Array[bufs.Offset + index]; + var buf = bufs.Array?[bufs.Offset + index] ?? throw new Exception("buffs.Array is null"); var gcHandle = GCHandle.Alloc(buf.Array, GCHandleType.Pinned); _pins.Add(gcHandle); diff --git a/Projects/Server/Main.cs b/Projects/Server/Main.cs index 1f394a095..291742a68 100644 --- a/Projects/Server/Main.cs +++ b/Projects/Server/Main.cs @@ -537,7 +537,7 @@ namespace Server BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) == null) { - if (warningSb == null) warningSb = new StringBuilder(); + warningSb ??= new StringBuilder(); warningSb.AppendLine(" - No Serialize() method"); } @@ -548,7 +548,7 @@ namespace Server BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) == null) { - if (warningSb == null) warningSb = new StringBuilder(); + warningSb ??= new StringBuilder(); warningSb.AppendLine(" - No Deserialize() method"); } diff --git a/Projects/Server/Map.cs b/Projects/Server/Map.cs index 9f7235197..ce21385e6 100644 --- a/Projects/Server/Map.cs +++ b/Projects/Server/Map.cs @@ -456,8 +456,7 @@ namespace Server pool = _FixPool.Dequeue(); } - if (pool == null) - pool = new List(128); // Arbitrary limit + pool ??= new List(128); // Arbitrary limit IPooledEnumerable eable = map.GetItemsInRange(new Point3D(x, y, 0), 0); diff --git a/Projects/Server/Mobile.cs b/Projects/Server/Mobile.cs index a2e8842ab..99148447b 100644 --- a/Projects/Server/Mobile.cs +++ b/Projects/Server/Mobile.cs @@ -22,6 +22,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Linq; using System.Text; using System.Threading.Tasks; using Server.Accounting; @@ -762,8 +763,7 @@ namespace Server { UpdateTotal(m_Holding, TotalType.Weight, m_Holding.TotalWeight + m_Holding.PileWeight); - if (m_Holding.HeldBy == null) - m_Holding.HeldBy = this; + m_Holding.HeldBy ??= this; } } } @@ -928,7 +928,6 @@ namespace Server if (m_Combatant == null) { m_ExpireCombatant?.Stop(); - m_CombatTimer?.Stop(); m_ExpireCombatant = null; @@ -936,14 +935,10 @@ namespace Server } else { - if (m_ExpireCombatant == null) - m_ExpireCombatant = new ExpireCombatantTimer(this); - + m_ExpireCombatant ??= new ExpireCombatantTimer(this); m_ExpireCombatant.Start(); - if (m_CombatTimer == null) - m_CombatTimer = new CombatTimer(this); - + m_CombatTimer ??= new CombatTimer(this); m_CombatTimer.Start(); } @@ -1129,7 +1124,7 @@ namespace Server [CommandProperty(AccessLevel.GameMaster)] public Container Corpse{ get; set; } - public static char[] GhostChars{ get; set; } = new char[2] { 'o', 'O' }; + public static char[] GhostChars{ get; set; } = { 'o', 'O' }; public static bool NoSpeechLOS{ get; set; } @@ -1459,8 +1454,7 @@ namespace Server m_Target?.Cancel(this, TargetCancelType.Disconnected); - if (m_QuestArrow != null) - QuestArrow = null; + QuestArrow = null; m_Spell?.OnConnectionChanged(); @@ -1542,11 +1536,7 @@ namespace Server public string Language { get => m_Language; - set - { - if (m_Language != value) - m_Language = value; - } + set => m_Language = value; } [CommandProperty(AccessLevel.GameMaster)] @@ -1633,13 +1623,7 @@ namespace Server [CommandProperty(AccessLevel.GameMaster)] public virtual string Name { - get - { - if (m_NameMod != null) - return m_NameMod; - - return m_Name; - } + get => m_NameMod ?? m_Name; set { if (m_Name != value) // I'm leaving out the && m_NameMod == null @@ -1938,8 +1922,7 @@ namespace Server if (m_MountItem?.Deleted == false && m_MountItem.Parent == this) item = m_MountItem; - if (item == null) - item = FindItemOnLayer(Layer.Mount); + item ??= FindItemOnLayer(Layer.Mount); if (!(item is IMountItem mountItem)) return null; @@ -2563,8 +2546,7 @@ namespace Server if (m.IsDeadBondedPet) { - if (deadPacket == null) - deadPacket = Packet.Acquire(new BondedStatus(0, m.Serial, 1)); + deadPacket ??= Packet.Acquire(new BondedStatus(0, m.Serial, 1)); state.Send(deadPacket); } @@ -2586,16 +2568,14 @@ namespace Server if (sendHealthbarPoison) { - if (hbpPacket == null) - hbpPacket = Packet.Acquire(new HealthbarPoison(m)); + hbpPacket ??= Packet.Acquire(new HealthbarPoison(m)); state.Send(hbpPacket); } if (sendHealthbarYellow) { - if (hbyPacket == null) - hbyPacket = Packet.Acquire(new HealthbarYellow(m)); + hbyPacket ??= Packet.Acquire(new HealthbarYellow(m)); state.Send(hbyPacket); } @@ -2619,49 +2599,34 @@ namespace Server { if (m.CanBeRenamedBy(beholder)) { - if (statPacketTrue == null) - statPacketTrue = Packet.Acquire(new MobileStatusCompact(true, m)); + statPacketTrue ??= Packet.Acquire(new MobileStatusCompact(true, m)); state.Send(statPacketTrue); } else { - if (statPacketFalse == null) - statPacketFalse = Packet.Acquire(new MobileStatusCompact(false, m)); + statPacketFalse ??= Packet.Acquire(new MobileStatusCompact(false, m)); state.Send(statPacketFalse); } } else if (sendHits) { - if (hitsPacket == null) - hitsPacket = Packet.Acquire(new MobileHitsN(m)); + hitsPacket ??= Packet.Acquire(new MobileHitsN(m)); state.Send(hitsPacket); } if (sendHair) { - if (hairPacket == null) - { - if (removeHair) - hairPacket = Packet.Acquire(new RemoveHair(m)); - else - hairPacket = Packet.Acquire(new HairEquipUpdate(m)); - } + hairPacket ??= removeHair ? Packet.Acquire(new RemoveHair(m)) : Packet.Acquire(new HairEquipUpdate(m)); state.Send(hairPacket); } if (sendFacialHair) { - if (facialhairPacket == null) - { - if (removeFacialHair) - facialhairPacket = Packet.Acquire(new RemoveFacialHair(m)); - else - facialhairPacket = Packet.Acquire(new FacialHairEquipUpdate(m)); - } + facialhairPacket ??= removeFacialHair ? Packet.Acquire(new RemoveFacialHair(m)) : Packet.Acquire(new FacialHairEquipUpdate(m)); state.Send(facialhairPacket); } @@ -2718,9 +2683,9 @@ namespace Server writer.Write(hairflag); if ((hairflag & 0x01) != 0) - m_Hair.Serialize(writer); + m_Hair?.Serialize(writer); if ((hairflag & 0x02) != 0) - m_FacialHair.Serialize(writer); + m_FacialHair?.Serialize(writer); writer.Write(Race); @@ -2855,8 +2820,7 @@ namespace Server public virtual void UpdateResistances() { - if (Resistances == null) - Resistances = new int[5] { int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue }; + Resistances ??= new[] { int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue }; bool delta = false; @@ -2873,8 +2837,7 @@ namespace Server public virtual int GetResistance(ResistanceType type) { - if (Resistances == null) - Resistances = new int[5] { int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue }; + Resistances ??= new[] { int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue }; int v = (int)type; @@ -2894,7 +2857,7 @@ namespace Server public virtual void AddResistanceMod(ResistanceMod toAdd) { - if (ResistanceMods == null) ResistanceMods = new List(); + ResistanceMods ??= new List(); ResistanceMods.Add(toAdd); UpdateResistances(); @@ -2915,8 +2878,7 @@ namespace Server public virtual void ComputeResistances() { - if (Resistances == null) - Resistances = new int[] { int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue }; + Resistances ??= new[] { int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue }; for (int i = 0; i < Resistances.Length; ++i) Resistances[i] = 0; @@ -2965,20 +2927,11 @@ namespace Server } } - public virtual int GetMinResistance(ResistanceType type) - { - return int.MinValue; - } + public virtual int GetMinResistance(ResistanceType type) => int.MinValue; - public virtual int GetMaxResistance(ResistanceType type) - { - return m_Player ? MaxPlayerResistance : int.MaxValue; - } + public virtual int GetMaxResistance(ResistanceType type) => m_Player ? MaxPlayerResistance : int.MaxValue; - public int GetAOSStatus(int index) - { - return AOSStatusHandler?.Invoke(this, index) ?? 0; - } + public int GetAOSStatus(int index) => AOSStatusHandler?.Invoke(this, index) ?? 0; public virtual void SendPropertiesTo(Mobile from) { @@ -3004,10 +2957,7 @@ namespace Server } } - public virtual string ApplyNameSuffix(string suffix) - { - return suffix; - } + public virtual string ApplyNameSuffix(string suffix) => suffix; public virtual void AddNameProperties(ObjectPropertyList list) { @@ -3026,10 +2976,8 @@ namespace Server BaseGuild guild = m_Guild; if (guild != null && (m_Player || m_DisplayGuildTitle)) - { suffix = suffix.Length > 0 ? $"{suffix} [{Utility.FixHtml(guild.Abbreviation)}]" : $"[{Utility.FixHtml(guild.Abbreviation)}]"; - } suffix = ApplyNameSuffix(suffix); @@ -3250,37 +3198,19 @@ namespace Server Warmode = value; } - public bool InLOS(Mobile target) - { - if (Deleted || m_Map == null) - return false; - if (target == this || m_AccessLevel > AccessLevel.Player) - return true; + public bool InLOS(Mobile target) => + !Deleted && m_Map != null && + (target == this || m_AccessLevel > AccessLevel.Player || m_Map.LineOfSight(this, target)); - return m_Map.LineOfSight(this, target); - } + public bool InLOS(object target) => + !Deleted && m_Map != null && + (target == this || m_AccessLevel > AccessLevel.Player || target is Item item && item.RootParent == this + || m_Map.LineOfSight(this, target)); - public bool InLOS(object target) - { - if (Deleted || m_Map == null) - return false; - if (target == this || m_AccessLevel > AccessLevel.Player) - return true; - if (target is Item item && item.RootParent == this) - return true; + public bool InLOS(Point3D target) => + !Deleted && m_Map != null && (m_AccessLevel > AccessLevel.Player || m_Map.LineOfSight(this, target)); - return m_Map.LineOfSight(this, target); - } - - public bool InLOS(Point3D target) - { - return !Deleted && m_Map != null && (m_AccessLevel > AccessLevel.Player || m_Map.LineOfSight(this, target)); - } - - public bool BeginAction() - { - return BeginAction(typeof(T)); - } + public bool BeginAction() => BeginAction(typeof(T)); public bool BeginAction(object toLock) { @@ -3299,20 +3229,11 @@ namespace Server return false; } - public bool CanBeginAction() - { - return CanBeginAction(typeof(T)); - } + public bool CanBeginAction() => CanBeginAction(typeof(T)); - public bool CanBeginAction(object toLock) - { - return _actions == null || !_actions.Contains(toLock); - } + public bool CanBeginAction(object toLock) => _actions?.Contains(toLock) != true; - public void EndAction() - { - EndAction(typeof(T)); - } + public void EndAction() => EndAction(typeof(T)); public void EndAction(object toLock) { @@ -3324,10 +3245,7 @@ namespace Server } } - public virtual TimeSpan GetLogoutDelay() - { - return Region.GetLogoutDelay(this); - } + public virtual TimeSpan GetLogoutDelay() => Region.GetLogoutDelay(this); public void Paralyze(TimeSpan duration) { @@ -3351,10 +3269,7 @@ namespace Server } } - public override string ToString() - { - return $"0x{Serial.Value:X} \"{Name}\""; - } + public override string ToString() => $"0x{Serial.Value:X} \"{Name}\""; public virtual void SendSkillMessage() { @@ -3384,7 +3299,7 @@ namespace Server public virtual void ClearHand(Item item) { - if (item != null && item.Movable && !item.AllowEquippedCast(this)) + if (item?.Movable == true && !item.AllowEquippedCast(this)) { Container pack = Backpack; @@ -3401,10 +3316,7 @@ namespace Server Combatant = m; } - public virtual bool CheckAttack(Mobile m) - { - return Utility.InUpdateRange(this, m) && CanSee(m) && InLOS(m); - } + public virtual bool CheckAttack(Mobile m) => Utility.InUpdateRange(this, m) && CanSee(m) && InLOS(m); /// /// Overridable. Virtual event invoked after the property has changed. @@ -3438,10 +3350,7 @@ namespace Server return Math.Sqrt(xDelta * xDelta + yDelta * yDelta); } - public virtual void AggressiveAction(Mobile aggressor) - { - AggressiveAction(aggressor, false); - } + public virtual void AggressiveAction(Mobile aggressor) => AggressiveAction(aggressor, false); public virtual void AggressiveAction(Mobile aggressor, bool criminal) { @@ -3614,22 +3523,14 @@ namespace Server UpdateAggrExpire(); } - public virtual int GetTotal(TotalType type) - { - switch (type) + public virtual int GetTotal(TotalType type) => + type switch { - case TotalType.Gold: - return m_TotalGold; - - case TotalType.Items: - return m_TotalItems; - - case TotalType.Weight: - return m_TotalWeight; - } - - return 0; - } + TotalType.Gold => m_TotalGold, + TotalType.Items => m_TotalItems, + TotalType.Weight => m_TotalWeight, + _ => 0 + }; public virtual void UpdateTotal(Item sender, TotalType type, int delta) { @@ -3638,7 +3539,7 @@ namespace Server switch (type) { - case TotalType.Gold: + default: m_TotalGold += delta; Delta(MobileDelta.Gold); break; @@ -3687,26 +3588,15 @@ namespace Server OnWeightChange(oldWeight); } - public void ClearQuestArrow() - { - m_QuestArrow = null; - } + public void ClearQuestArrow() => m_QuestArrow = null; - public void ClearTarget() - { - m_Target = null; - } + public void ClearTarget() => m_Target = null; - public Target BeginTarget(int range, bool allowGround, TargetFlags flags, TargetCallback callback) - { - return Target = new SimpleTarget(range, flags, allowGround, callback); - } + public Target BeginTarget(int range, bool allowGround, TargetFlags flags, TargetCallback callback) => Target = new SimpleTarget(range, flags, allowGround, callback); public Target BeginTarget(int range, bool allowGround, TargetFlags flags, TargetStateCallback callback, - T state) - { - return Target = new SimpleStateTarget(range, flags, allowGround, callback, state); - } + T state) => + Target = new SimpleStateTarget(range, flags, allowGround, callback, state); /// /// Overridable. Virtual event invoked after the Target property has changed. @@ -3715,10 +3605,7 @@ namespace Server { } - public virtual bool CheckContextMenuDisplay(IEntity target) - { - return true; - } + public virtual bool CheckContextMenuDisplay(IEntity target) => true; private bool InternalOnMove(Direction d) { @@ -3757,10 +3644,7 @@ namespace Server m_EndQueue = Core.TickCount; } - public virtual bool CheckMovement(Direction d, out int newZ) - { - return Movement.Movement.CheckMovement(this, d, out newZ); - } + public virtual bool CheckMovement(Direction d, out int newZ) => Movement.Movement.CheckMovement(this, d, out newZ); public virtual bool Move(Direction d) { @@ -3921,8 +3805,7 @@ namespace Server if (FwdEnabled && m_NetState != null && m_AccessLevel < FwdAccessOverride && (!FwdUOTDOverride || !m_NetState.IsUOTDClient)) { - if (m_MoveRecords == null) - m_MoveRecords = new Queue(6); + m_MoveRecords ??= new Queue(6); while (m_MoveRecords.Count > 0) { @@ -4032,8 +3915,8 @@ namespace Server } for (int i = 0; i < cache.Length; ++i) - for (int j = 0; j < cache[i].Length; ++j) - Packet.Release(ref cache[i][j]); + for (int j = 0; j < cache[i].Length; ++j) + Packet.Release(ref cache[i][j]); for (int i = 0; i < m_MoveList.Count; ++i) { @@ -4059,15 +3942,9 @@ namespace Server { } - public int ComputeMovementSpeed() - { - return ComputeMovementSpeed(Direction, false); - } + public int ComputeMovementSpeed() => ComputeMovementSpeed(Direction, false); - public int ComputeMovementSpeed(Direction dir) - { - return ComputeMovementSpeed(dir, true); - } + public int ComputeMovementSpeed(Direction dir) => ComputeMovementSpeed(dir, true); public virtual int ComputeMovementSpeed(Direction dir, bool checkTurning) { @@ -4085,22 +3962,13 @@ namespace Server /// Overridable. Virtual event invoked when a Mobile moves off this Mobile. /// /// True if the move is allowed, false if not. - public virtual bool OnMoveOff(Mobile m) - { - return true; - } + public virtual bool OnMoveOff(Mobile m) => true; /// /// Overridable. Event invoked when a Mobile moves over this Mobile. /// /// True if the move is allowed, false if not. - public virtual bool OnMoveOver(Mobile m) - { - if (m_Map == null || Deleted) - return true; - - return m.CheckShove(this); - } + public virtual bool OnMoveOver(Mobile m) => m_Map == null || Deleted || m.CheckShove(this); public virtual bool CheckShove(Mobile shoved) { @@ -4160,19 +4028,13 @@ namespace Server Region.OnCriminalAction(this, message); } - public virtual bool IsSnoop(Mobile from) - { - return from != this; - } + public virtual bool IsSnoop(Mobile from) => from != this; /// /// Overridable. Any call to will silently fail if this method returns false. /// /// - public virtual bool CheckResurrect() - { - return true; - } + public virtual bool CheckResurrect() => true; /// /// Overridable. Event invoked before the Mobile is resurrected. @@ -4325,30 +4187,15 @@ namespace Server m_AutoManifestTimer?.Stop(); } - public virtual bool AllowSkillUse(SkillName name) - { - return true; - } + public virtual bool AllowSkillUse(SkillName name) => true; - public virtual bool UseSkill(SkillName name) - { - return Skills.UseSkill(this, name); - } + public virtual bool UseSkill(SkillName name) => Skills.UseSkill(this, name); - public virtual bool UseSkill(int skillID) - { - return Skills.UseSkill(this, skillID); - } + public virtual bool UseSkill(int skillID) => Skills.UseSkill(this, skillID); - public virtual DeathMoveResult GetParentMoveResultFor(Item item) - { - return item.OnParentDeath(this); - } + public virtual DeathMoveResult GetParentMoveResultFor(Item item) => item.OnParentDeath(this); - public virtual DeathMoveResult GetInventoryMoveResultFor(Item item) - { - return item.OnInventoryDeath(this); - } + public virtual DeathMoveResult GetInventoryMoveResultFor(Item item) => item.OnInventoryDeath(this); public virtual void Kill() { @@ -4490,8 +4337,7 @@ namespace Server foreach (NetState state in eable) if (state != m_NetState) { - if (animPacket == null) - animPacket = Packet.Acquire(new DeathAnimation(this, c)); + animPacket ??= Packet.Acquire(new DeathAnimation(this, c)); state.Send(animPacket); @@ -5045,13 +4891,7 @@ namespace Server return false; } - public virtual bool CheckHearsMutatedSpeech(Mobile m, object context) - { - if (context == m_GhostMutateContext) - return m.Alive && !m.CanHearGhosts; - - return true; - } + public virtual bool CheckHearsMutatedSpeech(Mobile m, object context) => context != m_GhostMutateContext || m.Alive && !m.CanHearGhosts; private void AddSpeechItemsFrom(List list, Container cont) { @@ -5178,9 +5018,7 @@ namespace Server if (ns != null) { - if (regp == null) - regp = Packet.Acquire(new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, - text)); + regp ??= Packet.Acquire(new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, text)); ns.Send(regp); } @@ -5193,9 +5031,7 @@ namespace Server if (ns != null) { - if (mutp == null) - mutp = Packet.Acquire(new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, - mutatedText)); + mutp ??= Packet.Acquire(new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, mutatedText)); ns.Send(mutp); } @@ -5381,18 +5217,7 @@ namespace Server if (list == null) de.Responsible = list = new List(); - DamageEntry resp = null; - - for (int i = 0; i < list.Count; ++i) - { - DamageEntry check = list[i]; - - if (check.Damager == master) - { - resp = check; - break; - } - } + DamageEntry resp = list.FirstOrDefault(check => check.Damager == master); if (resp == null) list.Add(resp = new DamageEntry(master)); @@ -5570,15 +5395,13 @@ namespace Server { if (ns.DamagePacket) { - if (pNew == null) - pNew = Packet.Acquire(new DamagePacket(this, amount)); + pNew ??= Packet.Acquire(new DamagePacket(this, amount)); ns.Send(pNew); } else { - if (pOld == null) - pOld = Packet.Acquire(new DamagePacketOld(this, amount)); + pOld ??= Packet.Acquire(new DamagePacketOld(this, amount)); ns.Send(pOld); } @@ -5965,8 +5788,7 @@ namespace Server if (m_Criminal) { - if (m_ExpireCriminal == null) - m_ExpireCriminal = new ExpireCriminalTimer(this); + m_ExpireCriminal ??= new ExpireCriminalTimer(this); m_ExpireCriminal.Start(); } @@ -6027,8 +5849,7 @@ namespace Server { if (CanRegenHits) { - if (m_HitsTimer == null) - m_HitsTimer = new HitsTimer(this); + m_HitsTimer ??= new HitsTimer(this); m_HitsTimer.Start(); } @@ -6046,8 +5867,7 @@ namespace Server { if (CanRegenStam) { - if (m_StamTimer == null) - m_StamTimer = new StamTimer(this); + m_StamTimer ??= new StamTimer(this); m_StamTimer.Start(); } @@ -6065,8 +5885,7 @@ namespace Server { if (CanRegenMana) { - if (m_ManaTimer == null) - m_ManaTimer = new ManaTimer(this); + m_ManaTimer ??= new ManaTimer(this); m_ManaTimer.Start(); } @@ -6899,10 +6718,7 @@ namespace Server { } - public bool HasFreeHand() - { - return FindItemOnLayer(Layer.TwoHanded) == null; - } + public bool HasFreeHand() => FindItemOnLayer(Layer.TwoHanded) == null; public virtual IWeapon GetDefaultWeapon() { @@ -7022,7 +6838,7 @@ namespace Server if (!from.CheckTrade(this, offer, cont, true, true, 0, 0)) return false; - if (cont == null) cont = theirState.AddTrade(ourState); + cont ??= theirState.AddTrade(ourState); if (offer != null) cont.DropItem(offer); @@ -7278,16 +7094,13 @@ namespace Server Parallel.ForEach(m_DeltaQueue, m => m.ProcessDelta()); m_DeltaQueue.Clear(); } - else - { - while (m_DeltaQueue.Count > 0) - m_DeltaQueue.Dequeue().ProcessDelta(); - } + else while (m_DeltaQueue.TryDequeue(out Mobile m)) + m.ProcessDelta(); _processing = false; - while (m_DeltaQueueR.Count > 0) - m_DeltaQueueR.Dequeue().ProcessDelta(); + while (m_DeltaQueueR.TryDequeue(out Mobile m)) + m.ProcessDelta(); } public virtual void OnKillsChange(int oldValue) @@ -7384,14 +7197,9 @@ namespace Server if (guild != null && (m_DisplayGuildTitle || m_Player && guild.Type != GuildType.Regular)) { - string title = GuildTitle; + string title = GuildTitle?.Trim() ?? ""; string type; - if (title == null) - title = ""; - else - title = title.Trim(); - if (guild.Type >= 0 && (int)guild.Type < m_GuildTypes.Length) type = m_GuildTypes[(int)guild.Type]; else @@ -7441,25 +7249,17 @@ namespace Server PrivateOverheadMessage(MessageType.Label, hue, AsciiClickMessage, val, from.NetState); } - public bool CheckSkill(SkillName skill, double minSkill, double maxSkill) - { - return SkillCheckLocationHandler?.Invoke(this, skill, minSkill, maxSkill) == true; - } + public bool CheckSkill(SkillName skill, double minSkill, double maxSkill) => + SkillCheckLocationHandler?.Invoke(this, skill, minSkill, maxSkill) == true; - public bool CheckSkill(SkillName skill, double chance) - { - return SkillCheckDirectLocationHandler?.Invoke(this, skill, chance) == true; - } + public bool CheckSkill(SkillName skill, double chance) => + SkillCheckDirectLocationHandler?.Invoke(this, skill, chance) == true; - public bool CheckTargetSkill(SkillName skill, object target, double minSkill, double maxSkill) - { - return SkillCheckTargetHandler?.Invoke(this, skill, target, minSkill, maxSkill) == true; - } + public bool CheckTargetSkill(SkillName skill, object target, double minSkill, double maxSkill) => + SkillCheckTargetHandler?.Invoke(this, skill, target, minSkill, maxSkill) == true; - public bool CheckTargetSkill(SkillName skill, object target, double chance) - { - return SkillCheckDirectTargetHandler?.Invoke(this, skill, target, chance) == true; - } + public bool CheckTargetSkill(SkillName skill, object target, double chance) => + SkillCheckDirectTargetHandler?.Invoke(this, skill, target, chance) == true; public virtual void DisruptiveAction() { @@ -8064,20 +7864,14 @@ namespace Server } } - public Prompt BeginPrompt(PromptStateCallback callback, PromptStateCallback cancelCallback, T state) - { - return Prompt = new SimpleStatePrompt(callback, cancelCallback, state); - } + public Prompt BeginPrompt(PromptStateCallback callback, PromptStateCallback cancelCallback, T state) => + Prompt = new SimpleStatePrompt(callback, cancelCallback, state); - public Prompt BeginPrompt(PromptStateCallback callback, bool callbackHandlesCancel, T state) - { - return Prompt = new SimpleStatePrompt(callback, callbackHandlesCancel, state); - } + public Prompt BeginPrompt(PromptStateCallback callback, bool callbackHandlesCancel, T state) => + Prompt = new SimpleStatePrompt(callback, callbackHandlesCancel, state); - public Prompt BeginPrompt(PromptStateCallback callback, T state) - { - return BeginPrompt(callback, false, state); - } + public Prompt BeginPrompt(PromptStateCallback callback, T state) => + BeginPrompt(callback, false, state); public Prompt Prompt { @@ -8092,8 +7886,8 @@ namespace Server m_Prompt = null; - if (oldPrompt != null && newPrompt != null) - oldPrompt.OnCancel(this); + if (newPrompt != null) + oldPrompt?.OnCancel(this); m_Prompt = newPrompt; @@ -8479,15 +8273,9 @@ namespace Server #region Harmful Checks/Actions - public virtual bool CanBeHarmful(Mobile target) - { - return CanBeHarmful(target, true); - } + public virtual bool CanBeHarmful(Mobile target) => CanBeHarmful(target, true); - public virtual bool CanBeHarmful(Mobile target, bool message) - { - return CanBeHarmful(target, message, false); - } + public virtual bool CanBeHarmful(Mobile target, bool message) => CanBeHarmful(target, message, false); public virtual bool CanBeHarmful(Mobile target, bool message, bool ignoreOurBlessedness) { @@ -8520,13 +8308,7 @@ namespace Server return true; } - public virtual bool IsHarmfulCriminal(Mobile target) - { - if (this == target) - return false; - - return Notoriety.Compute(this, target) == Notoriety.Innocent; - } + public virtual bool IsHarmfulCriminal(Mobile target) => this != target && Notoriety.Compute(this, target) == Notoriety.Innocent; /// /// Overridable. Event invoked when the Mobile does a harmful action. @@ -8745,8 +8527,7 @@ namespace Server if (Hits < HitsMax) { - if (m_HitsTimer == null) - m_HitsTimer = new HitsTimer(this); + m_HitsTimer ??= new HitsTimer(this); m_HitsTimer.Start(); } @@ -8816,8 +8597,7 @@ namespace Server if (Stam < StamMax) { - if (m_StamTimer == null) - m_StamTimer = new StamTimer(this); + m_StamTimer ??= new StamTimer(this); m_StamTimer.Start(); } @@ -8887,8 +8667,7 @@ namespace Server if (Mana < ManaMax) { - if (m_ManaTimer == null) - m_ManaTimer = new ManaTimer(this); + m_ManaTimer ??= new ManaTimer(this); m_ManaTimer.Start(); } @@ -8978,8 +8757,7 @@ namespace Server { if (CanRegenHits) { - if (m_HitsTimer == null) - m_HitsTimer = new HitsTimer(this); + m_HitsTimer ??= new HitsTimer(this); m_HitsTimer.Start(); } @@ -9032,8 +8810,7 @@ namespace Server { if (CanRegenStam) { - if (m_StamTimer == null) - m_StamTimer = new StamTimer(this); + m_StamTimer ??= new StamTimer(this); m_StamTimer.Start(); } @@ -9095,8 +8872,7 @@ namespace Server { if (CanRegenMana) { - if (m_ManaTimer == null) - m_ManaTimer = new ManaTimer(this); + m_ManaTimer ??= new ManaTimer(this); m_ManaTimer.Start(); } @@ -9352,20 +9128,14 @@ namespace Server [CommandProperty(AccessLevel.GameMaster)] public int HairItemID { - get - { - if (m_Hair == null) - return 0; - - return m_Hair.ItemID; - } + get => m_Hair?.ItemID ?? 0; set { if (m_Hair == null && value > 0) m_Hair = new HairInfo(value); else if (value <= 0) m_Hair = null; - else + else if (m_Hair != null) m_Hair.ItemID = value; Delta(MobileDelta.Hair); @@ -9380,10 +9150,7 @@ namespace Server { get { - if (m_FacialHair == null) - return 0; - - return m_FacialHair.ItemID; + return m_FacialHair?.ItemID ?? 0; } set { @@ -9391,7 +9158,7 @@ namespace Server m_FacialHair = new FacialHairInfo(value); else if (value <= 0) m_FacialHair = null; - else + else if (m_FacialHair != null) m_FacialHair.ItemID = value; Delta(MobileDelta.FacialHair); @@ -9404,12 +9171,7 @@ namespace Server [CommandProperty(AccessLevel.GameMaster)] public int HairHue { - get - { - if (m_Hair == null) - return 0; - return m_Hair.Hue; - } + get => m_Hair?.Hue ?? 0; set { if (m_Hair != null) @@ -9423,13 +9185,7 @@ namespace Server [CommandProperty(AccessLevel.GameMaster)] public int FacialHairHue { - get - { - if (m_FacialHair == null) - return 0; - - return m_FacialHair.Hue; - } + get => m_FacialHair?.Hue ?? 0; set { if (m_FacialHair != null) @@ -9785,29 +9541,23 @@ namespace Server #region InRange - public bool InRange(Point2D p, int range) - { - return p.m_X >= m_Location.m_X - range - && p.m_X <= m_Location.m_X + range - && p.m_Y >= m_Location.m_Y - range - && p.m_Y <= m_Location.m_Y + range; - } + public bool InRange(Point2D p, int range) => + p.m_X >= m_Location.m_X - range + && p.m_X <= m_Location.m_X + range + && p.m_Y >= m_Location.m_Y - range + && p.m_Y <= m_Location.m_Y + range; - public bool InRange(Point3D p, int range) - { - return p.m_X >= m_Location.m_X - range - && p.m_X <= m_Location.m_X + range - && p.m_Y >= m_Location.m_Y - range - && p.m_Y <= m_Location.m_Y + range; - } + public bool InRange(Point3D p, int range) => + p.m_X >= m_Location.m_X - range + && p.m_X <= m_Location.m_X + range + && p.m_Y >= m_Location.m_Y - range + && p.m_Y <= m_Location.m_Y + range; - public bool InRange(IPoint2D p, int range) - { - return p.X >= m_Location.m_X - range - && p.X <= m_Location.m_X + range - && p.Y >= m_Location.m_Y - range - && p.Y <= m_Location.m_Y + range; - } + public bool InRange(IPoint2D p, int range) => + p.X >= m_Location.m_X - range + && p.X <= m_Location.m_X + range + && p.Y >= m_Location.m_Y - range + && p.Y <= m_Location.m_Y + range; #endregion @@ -9879,27 +9629,9 @@ namespace Server public Item ArmsArmor => FindItemOnLayer(Layer.Arms); - public Item LegsArmor - { - get - { - if (!(FindItemOnLayer(Layer.InnerLegs) is Item ar)) - ar = FindItemOnLayer(Layer.Pants); + public Item LegsArmor => FindItemOnLayer(Layer.InnerLegs) ?? FindItemOnLayer(Layer.Pants); - return ar; - } - } - - public Item ChestArmor - { - get - { - if (!(FindItemOnLayer(Layer.InnerTorso) is Item ar)) - ar = FindItemOnLayer(Layer.Shirt); - - return ar; - } - } + public Item ChestArmor => FindItemOnLayer(Layer.InnerTorso) ?? FindItemOnLayer(Layer.Shirt); public Item Talisman => FindItemOnLayer(Layer.Talisman); diff --git a/Projects/Server/Network/MessagePump.cs b/Projects/Server/Network/MessagePump.cs index 3904d73aa..91b24bc92 100644 --- a/Projects/Server/Network/MessagePump.cs +++ b/Projects/Server/Network/MessagePump.cs @@ -23,8 +23,6 @@ using System; using System.Buffers; using System.Collections.Concurrent; using System.Net; -using System.Threading.Tasks; -using SignalR; namespace Server.Network { diff --git a/Projects/Server/Network/NetState.cs b/Projects/Server/Network/NetState.cs index 290f6a6e9..a37902ffa 100644 --- a/Projects/Server/Network/NetState.cs +++ b/Projects/Server/Network/NetState.cs @@ -30,7 +30,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Server.Accounting; -using Server.Diagnostics; using Server.Gumps; using Server.HuePickers; using Server.Items; @@ -302,8 +301,7 @@ namespace Server.Network public void AddMenu(IMenu menu) { - if (Menus == null) - Menus = new List(); + Menus ??= new List(); if (Menus.Count < MenuCap) Menus.Add(menu); @@ -331,8 +329,7 @@ namespace Server.Network public void AddHuePicker(HuePicker huePicker) { - if (HuePickers == null) - HuePickers = new List(); + HuePickers ??= new List(); if (HuePickers.Count < HuePickerCap) HuePickers.Add(huePicker); @@ -360,8 +357,7 @@ namespace Server.Network public void AddGump(Gump gump) { - if (Gumps == null) - Gumps = new List(); + Gumps ??= new List(); if (Gumps.Count < GumpCap) Gumps.Add(gump); @@ -435,7 +431,9 @@ namespace Server.Network ConnectedOn = DateTime.UtcNow; Console.WriteLine("Client: {0}: Connected. [{1} Online]", this, Instances.Count); - _ = ProcessRecvs(pump); +#pragma warning disable 4014 + ProcessRecvs(pump); +#pragma warning restore 4014 CreatedCallback?.Invoke(this); } @@ -566,9 +564,7 @@ namespace Server.Network private int m_Disposing; - public bool IsDisposing { get => m_Disposing != 0; - private set => m_Disposing = value ? 1 : 0; - } + public bool IsDisposing => m_Disposing != 0; public virtual void Dispose() { diff --git a/Projects/Server/Network/PacketHandlers.cs b/Projects/Server/Network/PacketHandlers.cs index beda676b3..97f7c5b79 100644 --- a/Projects/Server/Network/PacketHandlers.cs +++ b/Projects/Server/Network/PacketHandlers.cs @@ -2092,8 +2092,7 @@ namespace Server.Network race = Race.Races[(byte)(genderRace / 2)]; } - if (race == null) - race = Race.DefaultRace; + race ??= Race.DefaultRace; CityInfo[] info = state.CityInfo; IAccount a = state.Account; diff --git a/Projects/Server/Network/Packets.cs b/Projects/Server/Network/Packets.cs index 7cf9e74ef..f2c45d137 100644 --- a/Projects/Server/Network/Packets.cs +++ b/Projects/Server/Network/Packets.cs @@ -165,7 +165,7 @@ namespace Server.Network public DisplaySecureTrade(Mobile them, Container first, Container second, string name) : base(0x6F) { - if (name == null) name = ""; + name ??= ""; EnsureCapacity(18 + name.Length); @@ -405,13 +405,9 @@ namespace Server.Network m_Stream.Write((ushort)state.Item.Amount); m_Stream.Write((ushort)state.Price); - string name = state.Item.Name; - - if (name == null || (name = name.Trim()).Length <= 0) - name = state.Name; - - if (name == null) - name = ""; + string name = state.Item.Name?.Trim(); + if (string.IsNullOrWhiteSpace(name)) + name = state.Name ?? ""; m_Stream.Write((ushort)name.Length); m_Stream.WriteAsciiFixed(name, (ushort)name.Length); @@ -979,14 +975,9 @@ namespace Server.Network { public DisplayProfile(bool realSerial, Mobile m, string header, string body, string footer) : base(0xB8) { - if (header == null) - header = ""; - - if (body == null) - body = ""; - - if (footer == null) - footer = ""; + header ??= ""; + body ??= ""; + footer ??= ""; EnsureCapacity(12 + header.Length + footer.Length * 2 + body.Length * 2); @@ -2104,7 +2095,7 @@ namespace Server.Network { public LaunchBrowser(string url) : base(0xA5) { - if (url == null) url = ""; + url ??= ""; EnsureCapacity(4 + url.Length); @@ -2121,8 +2112,8 @@ namespace Server.Network public MessageLocalized(Serial serial, int graphic, MessageType type, int hue, int font, int number, string name, string args) : base(0xC1) { - if (name == null) name = ""; - if (args == null) args = ""; + name ??= ""; + args ??= ""; if (hue == 0) hue = 0x3B2; @@ -2570,7 +2561,7 @@ namespace Server.Network { public DisplayGump(Gump g, string layout, string[] text) : base(0xB0) { - if (layout == null) layout = ""; + layout ??= ""; EnsureCapacity(256); @@ -2673,7 +2664,7 @@ namespace Server.Network { public ScrollMessage(int type, int tip, string text) : base(0xA6) { - if (text == null) text = ""; + text ??= ""; EnsureCapacity(10 + text.Length); @@ -2755,12 +2746,12 @@ namespace Server.Network flags |= Value; - if (ns.Account is IAccount acct && acct.Limit >= 6) + if (ns.Account.Limit >= 6) { flags |= FeatureFlags.LiveAccount; flags &= ~FeatureFlags.UOTD; - if (acct.Limit > 6) + if (ns.Account.Limit > 6) flags |= FeatureFlags.SeventhCharacterSlot; else flags |= FeatureFlags.SixthCharacterSlot; @@ -3618,11 +3609,8 @@ namespace Server.Network public AsciiMessage(Serial serial, int graphic, MessageType type, int hue, int font, string name, string text) : base(0x1C) { - if (name == null) - name = ""; - - if (text == null) - text = ""; + name ??= ""; + text ??= ""; if (hue == 0) hue = 0x3B2; @@ -3645,8 +3633,8 @@ namespace Server.Network string text) : base(0xAE) { if (string.IsNullOrEmpty(lang)) lang = "ENU"; - if (name == null) name = ""; - if (text == null) text = ""; + name ??= ""; + text ??= ""; if (hue == 0) hue = 0x3B2; @@ -4051,9 +4039,9 @@ namespace Server.Network public MessageLocalizedAffix(Serial serial, int graphic, MessageType messageType, int hue, int font, int number, string name, AffixType affixType, string affix, string args) : base(0xCC) { - if (name == null) name = ""; - if (affix == null) affix = ""; - if (args == null) args = ""; + name ??= ""; + affix ??= ""; + args ??= ""; if (hue == 0) hue = 0x3B2; @@ -4128,8 +4116,8 @@ namespace Server.Network { public DisplaySignGump(Serial serial, int gumpID, string unknown, string caption) : base(0x8B) { - if (unknown == null) unknown = ""; - if (caption == null) caption = ""; + unknown ??= ""; + caption ??= ""; EnsureCapacity(16 + unknown.Length + caption.Length); diff --git a/Projects/Server/ObjectPropertyList.cs b/Projects/Server/ObjectPropertyList.cs index abb437934..b1b09aa56 100644 --- a/Projects/Server/ObjectPropertyList.cs +++ b/Projects/Server/ObjectPropertyList.cs @@ -106,8 +106,7 @@ namespace Server if (number == 0) return; - if (arguments == null) - arguments = ""; + arguments ??= ""; if (Header == 0) { diff --git a/Projects/Server/Persistence/BinaryMemoryWriter.cs b/Projects/Server/Persistence/BinaryMemoryWriter.cs index 266cc76cf..5cc2f0a51 100644 --- a/Projects/Server/Persistence/BinaryMemoryWriter.cs +++ b/Projects/Server/Persistence/BinaryMemoryWriter.cs @@ -44,7 +44,7 @@ namespace Server dataFile.Write(buffer, 0, length); - if (indexBuffer == null) indexBuffer = new byte[20]; + indexBuffer ??= new byte[20]; indexBuffer[0] = (byte)typeCode; indexBuffer[1] = (byte)(typeCode >> 8); @@ -77,4 +77,4 @@ namespace Server return length; } } -} \ No newline at end of file +} diff --git a/Projects/Server/Persistence/FileQueue.cs b/Projects/Server/Persistence/FileQueue.cs index 082c11ded..3ec5af2f5 100644 --- a/Projects/Server/Persistence/FileQueue.cs +++ b/Projects/Server/Persistence/FileQueue.cs @@ -167,8 +167,7 @@ namespace Server while (size > 0) { - if (buffered.buffer == null) - buffered.buffer = ArrayPool.Shared.Rent(bufferSize); + buffered.buffer ??= ArrayPool.Shared.Rent(bufferSize); byte[] page = buffered.buffer; // buffer page int pageSpace = page.Length - buffered.length; // available bytes in page diff --git a/Projects/Server/Persistence/SequentialFileWriter.cs b/Projects/Server/Persistence/SequentialFileWriter.cs index 9b1d327b6..8682e7185 100644 --- a/Projects/Server/Persistence/SequentialFileWriter.cs +++ b/Projects/Server/Persistence/SequentialFileWriter.cs @@ -66,7 +66,7 @@ namespace Server } else { - if (writeCallback == null) writeCallback = OnWrite; + writeCallback ??= OnWrite; fileStream.BeginWrite(chunk.Buffer, chunk.Offset, chunk.Size, writeCallback, chunk); } @@ -78,7 +78,7 @@ namespace Server fileStream.EndWrite(asyncResult); - chunk.Commit(); + chunk?.Commit(); } public override void Write(byte[] buffer, int offset, int size) @@ -117,4 +117,4 @@ namespace Server fileStream.SetLength(value); } } -} \ No newline at end of file +} diff --git a/Projects/Server/Persistence/StandardSaveStrategy.cs b/Projects/Server/Persistence/StandardSaveStrategy.cs index 7b09f748f..d65de691d 100644 --- a/Projects/Server/Persistence/StandardSaveStrategy.cs +++ b/Projects/Server/Persistence/StandardSaveStrategy.cs @@ -103,7 +103,7 @@ namespace Server idx.Write(m.m_TypeRef); idx.Write(m.Serial); idx.Write(start); - idx.Write((int)(m.SaveBuffer.Position)); + idx.Write((int)m.SaveBuffer.Position); m.SaveBuffer.WriteTo(bin); m.FreeCache(); @@ -201,7 +201,7 @@ namespace Server idx.Write(0); //guilds have no typeid idx.Write(guild.Id); idx.Write(start); - idx.Write((int)(guild.SaveBuffer.Position)); + idx.Write((int)guild.SaveBuffer.Position); guild.SaveBuffer.WriteTo(bin); } diff --git a/Projects/Server/Sector.cs b/Projects/Server/Sector.cs index 32d9810cf..ae9ef8b94 100644 --- a/Projects/Server/Sector.cs +++ b/Projects/Server/Sector.cs @@ -91,7 +91,7 @@ namespace Server private void Add(ref List list, T value) { - if (list == null) list = new List(); + list ??= new List(); list.Add(value); } diff --git a/Projects/Server/Serialization/BinaryFileReader.cs b/Projects/Server/Serialization/BinaryFileReader.cs index fea89ead6..5d21a0faf 100644 --- a/Projects/Server/Serialization/BinaryFileReader.cs +++ b/Projects/Server/Serialization/BinaryFileReader.cs @@ -1,259 +1,275 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Text; -using Server.Guilds; - -namespace Server -{ - public sealed class BinaryFileReader : IGenericReader - { - private BinaryReader m_File; - - public BinaryFileReader(BinaryReader br) => m_File = br; - - public long Position => m_File.BaseStream.Position; - - public void Close() - { - m_File.Close(); - } - - public long Seek(long offset, SeekOrigin origin) => m_File.BaseStream.Seek(offset, origin); - - public string ReadString() => ReadByte() != 0 ? m_File.ReadString() : null; - - public DateTime ReadDeltaTime() - { - long ticks = m_File.ReadInt64(); - long now = DateTime.UtcNow.Ticks; - - if (ticks > 0 && ticks + now < 0) - return DateTime.MaxValue; - if (ticks < 0 && ticks + now < 0) - return DateTime.MinValue; - - try - { - return new DateTime(now + ticks); - } - catch - { - if (ticks > 0) return DateTime.MaxValue; - return DateTime.MinValue; - } - } - - public IPAddress ReadIPAddress() => new IPAddress(m_File.ReadInt64()); - - public int ReadEncodedInt() - { - int v = 0, shift = 0; - byte b; - - do - { - b = m_File.ReadByte(); - v |= (b & 0x7F) << shift; - shift += 7; - } while (b >= 0x80); - - return v; - } - - public DateTime ReadDateTime() => new DateTime(m_File.ReadInt64()); - - public DateTimeOffset ReadDateTimeOffset() - { - long ticks = m_File.ReadInt64(); - TimeSpan offset = new TimeSpan(m_File.ReadInt64()); - - return new DateTimeOffset(ticks, offset); - } - - public TimeSpan ReadTimeSpan() => new TimeSpan(m_File.ReadInt64()); - - public decimal ReadDecimal() => m_File.ReadDecimal(); - - public long ReadLong() => m_File.ReadInt64(); - - public ulong ReadULong() => m_File.ReadUInt64(); - - public int ReadInt() => m_File.ReadInt32(); - - public uint ReadUInt() => m_File.ReadUInt32(); - - public short ReadShort() => m_File.ReadInt16(); - - public ushort ReadUShort() => m_File.ReadUInt16(); - - public double ReadDouble() => m_File.ReadDouble(); - - public float ReadFloat() => m_File.ReadSingle(); - - public char ReadChar() => m_File.ReadChar(); - - public byte ReadByte() => m_File.ReadByte(); - - public sbyte ReadSByte() => m_File.ReadSByte(); - - public bool ReadBool() => m_File.ReadBoolean(); - - public Point3D ReadPoint3D() => new Point3D(ReadInt(), ReadInt(), ReadInt()); - - public Point2D ReadPoint2D() => new Point2D(ReadInt(), ReadInt()); - - public Rectangle2D ReadRect2D() => new Rectangle2D(ReadPoint2D(), ReadPoint2D()); - - public Rectangle3D ReadRect3D() => new Rectangle3D(ReadPoint3D(), ReadPoint3D()); - - public Map ReadMap() => Map.Maps[ReadByte()]; - - public IEntity ReadEntity() - { - Serial serial = ReadUInt(); - IEntity entity = World.FindEntity(serial); - if (entity == null) - return new Entity(serial, new Point3D(0, 0, 0), Map.Internal); - return entity; - } - - public Item ReadItem() => World.FindItem(ReadUInt()); - - public Mobile ReadMobile() => World.FindMobile(ReadUInt()); - - public BaseGuild ReadGuild() => BaseGuild.Find(ReadUInt()); - - public T ReadItem() where T : Item => ReadItem() as T; - - public T ReadMobile() where T : Mobile => ReadMobile() as T; - - public T ReadGuild() where T : BaseGuild => ReadGuild() as T; - - public List ReadStrongItemList() => ReadStrongItemList(); - - public List ReadStrongItemList() where T : Item - { - int count = ReadInt(); - - if (count > 0) - { - List list = new List(count); - - for (int i = 0; i < count; ++i) - if (ReadItem() is T item) - list.Add(item); - - return list; - } - - return new List(); - } - - public HashSet ReadItemSet() => ReadItemSet(); - - public HashSet ReadItemSet() where T : Item - { - int count = ReadInt(); - - if (count > 0) - { - HashSet set = new HashSet(); - - for (int i = 0; i < count; ++i) - if (ReadItem() is T item) - set.Add(item); - - return set; - } - - return new HashSet(); - } - - public List ReadStrongMobileList() => ReadStrongMobileList(); - - public List ReadStrongMobileList() where T : Mobile - { - int count = ReadInt(); - - if (count > 0) - { - List list = new List(count); - - for (int i = 0; i < count; ++i) - if (ReadMobile() is T m) - list.Add(m); - - return list; - } - - return new List(); - } - - public HashSet ReadMobileSet() => ReadMobileSet(); - - public HashSet ReadMobileSet() where T : Mobile - { - int count = ReadInt(); - - if (count > 0) - { - HashSet set = new HashSet(); - - for (int i = 0; i < count; ++i) - if (ReadMobile() is T item) - set.Add(item); - - return set; - } - - return new HashSet(); - } - - public List ReadStrongGuildList() => ReadStrongGuildList(); - - public List ReadStrongGuildList() where T : BaseGuild - { - int count = ReadInt(); - - if (count > 0) - { - List list = new List(count); - - for (int i = 0; i < count; ++i) - if (ReadGuild() is T g) - list.Add(g); - - return list; - } - - return new List(); - } - - public HashSet ReadGuildSet() => ReadGuildSet(); - - public HashSet ReadGuildSet() where T : BaseGuild - { - int count = ReadInt(); - - if (count > 0) - { - HashSet set = new HashSet(); - - for (int i = 0; i < count; ++i) - if (ReadGuild() is T item) - set.Add(item); - - return set; - } - - return new HashSet(); - } - - public Race ReadRace() => Race.Races[ReadByte()]; - - public bool End() => m_File.PeekChar() == -1; - } - -} +/************************************************************************* + * ModernUO * + * Copyright (C) 2019 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: BinaryFileReader.cs * + * Created: 2019/12/30 - Updated: 2020/01/18 * + * * + * 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 . * + *************************************************************************/ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using Server.Guilds; + +namespace Server +{ + public sealed class BinaryFileReader : IGenericReader + { + private BinaryReader m_File; + + public BinaryFileReader(BinaryReader br) => m_File = br; + + public long Position => m_File.BaseStream.Position; + + public void Close() + { + m_File.Close(); + } + + public long Seek(long offset, SeekOrigin origin) => m_File.BaseStream.Seek(offset, origin); + + public string ReadString() => ReadByte() != 0 ? m_File.ReadString() : null; + + public DateTime ReadDeltaTime() + { + long ticks = m_File.ReadInt64(); + long now = DateTime.UtcNow.Ticks; + + if (ticks > 0 && ticks + now < 0) + return DateTime.MaxValue; + if (ticks < 0 && ticks + now < 0) + return DateTime.MinValue; + + try + { + return new DateTime(now + ticks); + } + catch + { + return ticks > 0 ? DateTime.MaxValue : DateTime.MinValue; + } + } + + public IPAddress ReadIPAddress() => new IPAddress(m_File.ReadInt64()); + + public int ReadEncodedInt() + { + int v = 0, shift = 0; + byte b; + + do + { + b = m_File.ReadByte(); + v |= (b & 0x7F) << shift; + shift += 7; + } while (b >= 0x80); + + return v; + } + + public DateTime ReadDateTime() => new DateTime(m_File.ReadInt64()); + + public DateTimeOffset ReadDateTimeOffset() + { + long ticks = m_File.ReadInt64(); + TimeSpan offset = new TimeSpan(m_File.ReadInt64()); + + return new DateTimeOffset(ticks, offset); + } + + public TimeSpan ReadTimeSpan() => new TimeSpan(m_File.ReadInt64()); + + public decimal ReadDecimal() => m_File.ReadDecimal(); + + public long ReadLong() => m_File.ReadInt64(); + + public ulong ReadULong() => m_File.ReadUInt64(); + + public int ReadInt() => m_File.ReadInt32(); + + public uint ReadUInt() => m_File.ReadUInt32(); + + public short ReadShort() => m_File.ReadInt16(); + + public ushort ReadUShort() => m_File.ReadUInt16(); + + public double ReadDouble() => m_File.ReadDouble(); + + public float ReadFloat() => m_File.ReadSingle(); + + public char ReadChar() => m_File.ReadChar(); + + public byte ReadByte() => m_File.ReadByte(); + + public sbyte ReadSByte() => m_File.ReadSByte(); + + public bool ReadBool() => m_File.ReadBoolean(); + + public Point3D ReadPoint3D() => new Point3D(ReadInt(), ReadInt(), ReadInt()); + + public Point2D ReadPoint2D() => new Point2D(ReadInt(), ReadInt()); + + public Rectangle2D ReadRect2D() => new Rectangle2D(ReadPoint2D(), ReadPoint2D()); + + public Rectangle3D ReadRect3D() => new Rectangle3D(ReadPoint3D(), ReadPoint3D()); + + public Map ReadMap() => Map.Maps[ReadByte()]; + + public IEntity ReadEntity() + { + Serial serial = ReadUInt(); + return World.FindEntity(serial) ?? new Entity(serial, new Point3D(0, 0, 0), Map.Internal); + } + + public Item ReadItem() => World.FindItem(ReadUInt()); + + public Mobile ReadMobile() => World.FindMobile(ReadUInt()); + + public BaseGuild ReadGuild() => BaseGuild.Find(ReadUInt()); + + public T ReadItem() where T : Item => ReadItem() as T; + + public T ReadMobile() where T : Mobile => ReadMobile() as T; + + public T ReadGuild() where T : BaseGuild => ReadGuild() as T; + + public List ReadStrongItemList() => ReadStrongItemList(); + + public List ReadStrongItemList() where T : Item + { + int count = ReadInt(); + + if (count > 0) + { + List list = new List(count); + + for (int i = 0; i < count; ++i) + if (ReadItem() is T item) + list.Add(item); + + return list; + } + + return new List(); + } + + public HashSet ReadItemSet() => ReadItemSet(); + + public HashSet ReadItemSet() where T : Item + { + int count = ReadInt(); + + if (count > 0) + { + HashSet set = new HashSet(); + + for (int i = 0; i < count; ++i) + if (ReadItem() is T item) + set.Add(item); + + return set; + } + + return new HashSet(); + } + + public List ReadStrongMobileList() => ReadStrongMobileList(); + + public List ReadStrongMobileList() where T : Mobile + { + int count = ReadInt(); + + if (count > 0) + { + List list = new List(count); + + for (int i = 0; i < count; ++i) + if (ReadMobile() is T m) + list.Add(m); + + return list; + } + + return new List(); + } + + public HashSet ReadMobileSet() => ReadMobileSet(); + + public HashSet ReadMobileSet() where T : Mobile + { + int count = ReadInt(); + + if (count > 0) + { + HashSet set = new HashSet(); + + for (int i = 0; i < count; ++i) + if (ReadMobile() is T item) + set.Add(item); + + return set; + } + + return new HashSet(); + } + + public List ReadStrongGuildList() => ReadStrongGuildList(); + + public List ReadStrongGuildList() where T : BaseGuild + { + int count = ReadInt(); + + if (count > 0) + { + List list = new List(count); + + for (int i = 0; i < count; ++i) + if (ReadGuild() is T g) + list.Add(g); + + return list; + } + + return new List(); + } + + public HashSet ReadGuildSet() => ReadGuildSet(); + + public HashSet ReadGuildSet() where T : BaseGuild + { + int count = ReadInt(); + + if (count > 0) + { + HashSet set = new HashSet(); + + for (int i = 0; i < count; ++i) + if (ReadGuild() is T item) + set.Add(item); + + return set; + } + + return new HashSet(); + } + + public Race ReadRace() => Race.Races[ReadByte()]; + + public bool End() => m_File.PeekChar() == -1; + } + +} diff --git a/Projects/Server/Serialization/BinaryFileWriter.cs b/Projects/Server/Serialization/BinaryFileWriter.cs index 42de3bb00..33e18a801 100644 --- a/Projects/Server/Serialization/BinaryFileWriter.cs +++ b/Projects/Server/Serialization/BinaryFileWriter.cs @@ -1,660 +1,681 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Net; -using Server.Guilds; - -namespace Server -{ - public class BinaryFileWriter : IGenericWriter - { - private const int LargeByteBufferSize = 256; - - private byte[] m_Buffer; - - private byte[] m_CharacterBuffer; - - private Encoding m_Encoding; - private Stream m_File; - - private int m_Index; - private int m_MaxBufferChars; - - private long m_Position; - - private char[] m_SingleCharBuffer = new char[1]; - private bool PrefixStrings; - - public BinaryFileWriter(Stream strm, bool prefixStr) - { - PrefixStrings = prefixStr; - m_Encoding = Utility.UTF8; - m_Buffer = new byte[BufferSize]; - m_File = strm; - } - - public BinaryFileWriter(string filename, bool prefixStr) - { - PrefixStrings = prefixStr; - m_Buffer = new byte[BufferSize]; - m_File = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None); - m_Encoding = Utility.UTF8WithEncoding; - } - - protected virtual int BufferSize => 64 * 1024; - - public long Position => m_Position + m_Index; - - public Stream UnderlyingStream - { - get - { - if (m_Index > 0) - Flush(); - - return m_File; - } - } - - public void Flush() - { - if (m_Index > 0) - { - m_Position += m_Index; - - m_File.Write(m_Buffer, 0, m_Index); - m_Index = 0; - } - } - - public void Close() - { - if (m_Index > 0) - Flush(); - - m_File.Close(); - } - - public void WriteEncodedInt(int value) - { - uint v = (uint)value; - - while (v >= 0x80) - { - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = (byte)(v | 0x80); - v >>= 7; - } - - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = (byte)v; - } - - internal void InternalWriteString(string value) - { - int length = m_Encoding.GetByteCount(value); - - WriteEncodedInt(length); - - if (m_CharacterBuffer == null) - { - m_CharacterBuffer = new byte[LargeByteBufferSize]; - m_MaxBufferChars = LargeByteBufferSize / m_Encoding.GetMaxByteCount(1); - } - - if (length > LargeByteBufferSize) - { - int current = 0; - int charsLeft = value.Length; - - while (charsLeft > 0) - { - int charCount = charsLeft > m_MaxBufferChars ? m_MaxBufferChars : charsLeft; - int byteLength = m_Encoding.GetBytes(value, current, charCount, m_CharacterBuffer, 0); - - if (m_Index + byteLength > m_Buffer.Length) - Flush(); - - Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); - m_Index += byteLength; - - current += charCount; - charsLeft -= charCount; - } - } - else - { - int byteLength = m_Encoding.GetBytes(value, 0, value.Length, m_CharacterBuffer, 0); - - if (m_Index + byteLength > m_Buffer.Length) - Flush(); - - Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); - m_Index += byteLength; - } - } - - public void Write(string value) - { - if (PrefixStrings) - { - if (value == null) - { - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = 0; - } - else - { - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = 1; - - InternalWriteString(value); - } - } - else - { - InternalWriteString(value); - } - } - - public void Write(DateTime value) - { - Write(value.Ticks); - } - - public void Write(DateTimeOffset value) - { - Write(value.Ticks); - Write(value.Offset.Ticks); - } - - public void WriteDeltaTime(DateTime value) - { - long ticks = value.Ticks; - long now = DateTime.UtcNow.Ticks; - - TimeSpan d; - - try - { - d = new TimeSpan(ticks - now); - } - catch - { - d = TimeSpan.MaxValue; - } - - Write(d); - } - - public void Write(IPAddress value) - { - Write(Utility.GetLongAddressValue(value)); - } - - public void Write(TimeSpan value) - { - Write(value.Ticks); - } - - public void Write(decimal value) - { - int[] bits = decimal.GetBits(value); - - for (int i = 0; i < bits.Length; ++i) - Write(bits[i]); - } - - public void Write(long value) - { - if (m_Index + 8 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Buffer[m_Index + 4] = (byte)(value >> 32); - m_Buffer[m_Index + 5] = (byte)(value >> 40); - m_Buffer[m_Index + 6] = (byte)(value >> 48); - m_Buffer[m_Index + 7] = (byte)(value >> 56); - m_Index += 8; - } - - public void Write(ulong value) - { - if (m_Index + 8 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Buffer[m_Index + 4] = (byte)(value >> 32); - m_Buffer[m_Index + 5] = (byte)(value >> 40); - m_Buffer[m_Index + 6] = (byte)(value >> 48); - m_Buffer[m_Index + 7] = (byte)(value >> 56); - m_Index += 8; - } - - public void Write(int value) - { - if (m_Index + 4 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Index += 4; - } - - public void Write(uint value) - { - if (m_Index + 4 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Index += 4; - } - - public void Write(short value) - { - if (m_Index + 2 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Index += 2; - } - - public void Write(ushort value) - { - if (m_Index + 2 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Index += 2; - } - - public unsafe void Write(double value) - { - if (m_Index + 8 > m_Buffer.Length) - Flush(); - - fixed (byte* pBuffer = m_Buffer) - { - *(double*)(pBuffer + m_Index) = value; - } - - m_Index += 8; - } - - public unsafe void Write(float value) - { - if (m_Index + 4 > m_Buffer.Length) - Flush(); - - fixed (byte* pBuffer = m_Buffer) - { - *(float*)(pBuffer + m_Index) = value; - } - - m_Index += 4; - } - - public void Write(char value) - { - if (m_Index + 8 > m_Buffer.Length) - Flush(); - - m_SingleCharBuffer[0] = value; - - int byteCount = m_Encoding.GetBytes(m_SingleCharBuffer, 0, 1, m_Buffer, m_Index); - m_Index += byteCount; - } - - public void Write(byte value) - { - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = value; - } - - public void Write(byte[] value) - { - Write(value, value.Length); - } - - public void Write(byte[] value, int length) - { - if ((m_Index + length) > m_Buffer.Length) - Flush(); - - Buffer.BlockCopy(value, 0, m_Buffer, m_Index, length); - m_Index += length; - } - public void Write(sbyte value) - { - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = (byte)value; - } - - public void Write(bool value) - { - if (m_Index + 1 > m_Buffer.Length) - Flush(); - - m_Buffer[m_Index++] = (byte)(value ? 1 : 0); - } - - public void Write(Point3D value) - { - Write(value.m_X); - Write(value.m_Y); - Write(value.m_Z); - } - - public void Write(Point2D value) - { - Write(value.m_X); - Write(value.m_Y); - } - - public void Write(Rectangle2D value) - { - Write(value.Start); - Write(value.End); - } - - public void Write(Rectangle3D value) - { - Write(value.Start); - Write(value.End); - } - - public void Write(Map value) - { - if (value != null) - Write((byte)value.MapIndex); - else - Write((byte)0xFF); - } - - public void Write(Race value) - { - if (value != null) - Write((byte)value.RaceIndex); - else - Write((byte)0xFF); - } - - public void WriteEntity(IEntity value) - { - if (value?.Deleted != false) - Write(Serial.MinusOne); - else - Write(value.Serial); - } - - public void Write(Item value) - { - if (value?.Deleted != false) - Write(Serial.MinusOne); - else - Write(value.Serial); - } - - public void Write(Mobile value) - { - if (value?.Deleted != false) - Write(Serial.MinusOne); - else - Write(value.Serial); - } - - public void Write(BaseGuild value) - { - if (value == null) - Write(0); - else - Write(value.Id); - } - - public void WriteItem(T value) where T : Item - { - Write(value); - } - - public void WriteMobile(T value) where T : Mobile - { - Write(value); - } - - public void WriteGuild(T value) where T : BaseGuild - { - Write(value); - } - - public void Write(List list) - { - Write(list, false); - } - - public void Write(List list, bool tidy) - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void WriteItemList(List list) where T : Item - { - WriteItemList(list, false); - } - - public void WriteItemList(List list, bool tidy) where T : Item - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void Write(HashSet set) - { - Write(set, false); - } - - public void Write(HashSet set, bool tidy) - { - if (tidy) set.RemoveWhere(item => item.Deleted); - - Write(set.Count); - - foreach (Item item in set) Write(item); - } - - public void WriteItemSet(HashSet set) where T : Item - { - WriteItemSet(set, false); - } - - public void WriteItemSet(HashSet set, bool tidy) where T : Item - { - if (tidy) set.RemoveWhere(item => item.Deleted); - - Write(set.Count); - - foreach (T item in set) Write(item); - } - - public void Write(List list) - { - Write(list, false); - } - - public void Write(List list, bool tidy) - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void WriteMobileList(List list) where T : Mobile - { - WriteMobileList(list, false); - } - - public void WriteMobileList(List list, bool tidy) where T : Mobile - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void Write(HashSet set) - { - Write(set, false); - } - - public void Write(HashSet set, bool tidy) - { - if (tidy) set.RemoveWhere(mobile => mobile.Deleted); - - Write(set.Count); - - foreach (Mobile mob in set) Write(mob); - } - - public void WriteMobileSet(HashSet set) where T : Mobile - { - WriteMobileSet(set, false); - } - - public void WriteMobileSet(HashSet set, bool tidy) where T : Mobile - { - if (tidy) set.RemoveWhere(mob => mob.Deleted); - - Write(set.Count); - - foreach (T mob in set) Write(mob); - } - - public void Write(List list) - { - Write(list, false); - } - - public void Write(List list, bool tidy) - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Disbanded) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void WriteGuildList(List list) where T : BaseGuild - { - WriteGuildList(list, false); - } - - public void WriteGuildList(List list, bool tidy) where T : BaseGuild - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Disbanded) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void Write(HashSet set) - { - Write(set, false); - } - - public void Write(HashSet set, bool tidy) - { - if (tidy) set.RemoveWhere(guild => guild.Disbanded); - - Write(set.Count); - - foreach (BaseGuild guild in set) Write(guild); - } - - public void WriteGuildSet(HashSet set) where T : BaseGuild - { - WriteGuildSet(set, false); - } - - public void WriteGuildSet(HashSet set, bool tidy) where T : BaseGuild - { - if (tidy) set.RemoveWhere(guild => guild.Disbanded); - - Write(set.Count); - - foreach (T guild in set) Write(guild); - } - } - -} +/************************************************************************* + * ModernUO * + * Copyright (C) 2019 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: BinaryFileWriter.cs * + * Created: 2019/12/30 - Updated: 2020/01/18 * + * * + * 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 . * + *************************************************************************/ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Net; +using Server.Guilds; + +namespace Server +{ + public class BinaryFileWriter : IGenericWriter + { + private const int LargeByteBufferSize = 256; + + private byte[] m_Buffer; + + private byte[] m_CharacterBuffer; + + private Encoding m_Encoding; + private Stream m_File; + + private int m_Index; + private int m_MaxBufferChars; + + private long m_Position; + + private char[] m_SingleCharBuffer = new char[1]; + private bool PrefixStrings; + + public BinaryFileWriter(Stream strm, bool prefixStr) + { + PrefixStrings = prefixStr; + m_Encoding = Utility.UTF8; + m_Buffer = new byte[BufferSize]; + m_File = strm; + } + + public BinaryFileWriter(string filename, bool prefixStr) + { + PrefixStrings = prefixStr; + m_Buffer = new byte[BufferSize]; + m_File = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None); + m_Encoding = Utility.UTF8WithEncoding; + } + + protected virtual int BufferSize => 64 * 1024; + + public long Position => m_Position + m_Index; + + public Stream UnderlyingStream + { + get + { + if (m_Index > 0) + Flush(); + + return m_File; + } + } + + public void Flush() + { + if (m_Index > 0) + { + m_Position += m_Index; + + m_File.Write(m_Buffer, 0, m_Index); + m_Index = 0; + } + } + + public void Close() + { + if (m_Index > 0) + Flush(); + + m_File.Close(); + } + + public void WriteEncodedInt(int value) + { + uint v = (uint)value; + + while (v >= 0x80) + { + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = (byte)(v | 0x80); + v >>= 7; + } + + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = (byte)v; + } + + internal void InternalWriteString(string value) + { + int length = m_Encoding.GetByteCount(value); + + WriteEncodedInt(length); + + if (m_CharacterBuffer == null) + { + m_CharacterBuffer = new byte[LargeByteBufferSize]; + m_MaxBufferChars = LargeByteBufferSize / m_Encoding.GetMaxByteCount(1); + } + + if (length > LargeByteBufferSize) + { + int current = 0; + int charsLeft = value.Length; + + while (charsLeft > 0) + { + int charCount = charsLeft > m_MaxBufferChars ? m_MaxBufferChars : charsLeft; + int byteLength = m_Encoding.GetBytes(value, current, charCount, m_CharacterBuffer, 0); + + if (m_Index + byteLength > m_Buffer.Length) + Flush(); + + Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); + m_Index += byteLength; + + current += charCount; + charsLeft -= charCount; + } + } + else + { + int byteLength = m_Encoding.GetBytes(value, 0, value.Length, m_CharacterBuffer, 0); + + if (m_Index + byteLength > m_Buffer.Length) + Flush(); + + Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); + m_Index += byteLength; + } + } + + public void Write(string value) + { + if (PrefixStrings) + { + if (value == null) + { + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = 0; + } + else + { + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = 1; + + InternalWriteString(value); + } + } + else + { + InternalWriteString(value); + } + } + + public void Write(DateTime value) + { + Write(value.Ticks); + } + + public void Write(DateTimeOffset value) + { + Write(value.Ticks); + Write(value.Offset.Ticks); + } + + public void WriteDeltaTime(DateTime value) + { + long ticks = value.Ticks; + long now = DateTime.UtcNow.Ticks; + + TimeSpan d; + + try + { + d = new TimeSpan(ticks - now); + } + catch + { + d = TimeSpan.MaxValue; + } + + Write(d); + } + + public void Write(IPAddress value) + { + Write(Utility.GetLongAddressValue(value)); + } + + public void Write(TimeSpan value) + { + Write(value.Ticks); + } + + public void Write(decimal value) + { + int[] bits = decimal.GetBits(value); + + for (int i = 0; i < bits.Length; ++i) + Write(bits[i]); + } + + public void Write(long value) + { + if (m_Index + 8 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Buffer[m_Index + 4] = (byte)(value >> 32); + m_Buffer[m_Index + 5] = (byte)(value >> 40); + m_Buffer[m_Index + 6] = (byte)(value >> 48); + m_Buffer[m_Index + 7] = (byte)(value >> 56); + m_Index += 8; + } + + public void Write(ulong value) + { + if (m_Index + 8 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Buffer[m_Index + 4] = (byte)(value >> 32); + m_Buffer[m_Index + 5] = (byte)(value >> 40); + m_Buffer[m_Index + 6] = (byte)(value >> 48); + m_Buffer[m_Index + 7] = (byte)(value >> 56); + m_Index += 8; + } + + public void Write(int value) + { + if (m_Index + 4 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Index += 4; + } + + public void Write(uint value) + { + if (m_Index + 4 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Index += 4; + } + + public void Write(short value) + { + if (m_Index + 2 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Index += 2; + } + + public void Write(ushort value) + { + if (m_Index + 2 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Index += 2; + } + + public unsafe void Write(double value) + { + if (m_Index + 8 > m_Buffer.Length) + Flush(); + + fixed (byte* pBuffer = m_Buffer) + { + *(double*)(pBuffer + m_Index) = value; + } + + m_Index += 8; + } + + public unsafe void Write(float value) + { + if (m_Index + 4 > m_Buffer.Length) + Flush(); + + fixed (byte* pBuffer = m_Buffer) + { + *(float*)(pBuffer + m_Index) = value; + } + + m_Index += 4; + } + + public void Write(char value) + { + if (m_Index + 8 > m_Buffer.Length) + Flush(); + + m_SingleCharBuffer[0] = value; + + int byteCount = m_Encoding.GetBytes(m_SingleCharBuffer, 0, 1, m_Buffer, m_Index); + m_Index += byteCount; + } + + public void Write(byte value) + { + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = value; + } + + public void Write(byte[] value) + { + Write(value, value.Length); + } + + public void Write(byte[] value, int length) + { + if (m_Index + length > m_Buffer.Length) + Flush(); + + Buffer.BlockCopy(value, 0, m_Buffer, m_Index, length); + m_Index += length; + } + public void Write(sbyte value) + { + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = (byte)value; + } + + public void Write(bool value) + { + if (m_Index + 1 > m_Buffer.Length) + Flush(); + + m_Buffer[m_Index++] = (byte)(value ? 1 : 0); + } + + public void Write(Point3D value) + { + Write(value.m_X); + Write(value.m_Y); + Write(value.m_Z); + } + + public void Write(Point2D value) + { + Write(value.m_X); + Write(value.m_Y); + } + + public void Write(Rectangle2D value) + { + Write(value.Start); + Write(value.End); + } + + public void Write(Rectangle3D value) + { + Write(value.Start); + Write(value.End); + } + + public void Write(Map value) + { + if (value != null) + Write((byte)value.MapIndex); + else + Write((byte)0xFF); + } + + public void Write(Race value) + { + if (value != null) + Write((byte)value.RaceIndex); + else + Write((byte)0xFF); + } + + public void WriteEntity(IEntity value) + { + if (value?.Deleted != false) + Write(Serial.MinusOne); + else + Write(value.Serial); + } + + public void Write(Item value) + { + if (value?.Deleted != false) + Write(Serial.MinusOne); + else + Write(value.Serial); + } + + public void Write(Mobile value) + { + if (value?.Deleted != false) + Write(Serial.MinusOne); + else + Write(value.Serial); + } + + public void Write(BaseGuild value) + { + if (value == null) + Write(0); + else + Write(value.Id); + } + + public void WriteItem(T value) where T : Item + { + Write(value); + } + + public void WriteMobile(T value) where T : Mobile + { + Write(value); + } + + public void WriteGuild(T value) where T : BaseGuild + { + Write(value); + } + + public void Write(List list) + { + Write(list, false); + } + + public void Write(List list, bool tidy) + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void WriteItemList(List list) where T : Item + { + WriteItemList(list, false); + } + + public void WriteItemList(List list, bool tidy) where T : Item + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void Write(HashSet set) + { + Write(set, false); + } + + public void Write(HashSet set, bool tidy) + { + if (tidy) set.RemoveWhere(item => item.Deleted); + + Write(set.Count); + + foreach (Item item in set) Write(item); + } + + public void WriteItemSet(HashSet set) where T : Item + { + WriteItemSet(set, false); + } + + public void WriteItemSet(HashSet set, bool tidy) where T : Item + { + if (tidy) set.RemoveWhere(item => item.Deleted); + + Write(set.Count); + + foreach (T item in set) Write(item); + } + + public void Write(List list) + { + Write(list, false); + } + + public void Write(List list, bool tidy) + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void WriteMobileList(List list) where T : Mobile + { + WriteMobileList(list, false); + } + + public void WriteMobileList(List list, bool tidy) where T : Mobile + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void Write(HashSet set) + { + Write(set, false); + } + + public void Write(HashSet set, bool tidy) + { + if (tidy) set.RemoveWhere(mobile => mobile.Deleted); + + Write(set.Count); + + foreach (Mobile mob in set) Write(mob); + } + + public void WriteMobileSet(HashSet set) where T : Mobile + { + WriteMobileSet(set, false); + } + + public void WriteMobileSet(HashSet set, bool tidy) where T : Mobile + { + if (tidy) set.RemoveWhere(mob => mob.Deleted); + + Write(set.Count); + + foreach (T mob in set) Write(mob); + } + + public void Write(List list) + { + Write(list, false); + } + + public void Write(List list, bool tidy) + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Disbanded) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void WriteGuildList(List list) where T : BaseGuild + { + WriteGuildList(list, false); + } + + public void WriteGuildList(List list, bool tidy) where T : BaseGuild + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Disbanded) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void Write(HashSet set) + { + Write(set, false); + } + + public void Write(HashSet set, bool tidy) + { + if (tidy) set.RemoveWhere(guild => guild.Disbanded); + + Write(set.Count); + + foreach (BaseGuild guild in set) Write(guild); + } + + public void WriteGuildSet(HashSet set) where T : BaseGuild + { + WriteGuildSet(set, false); + } + + public void WriteGuildSet(HashSet set, bool tidy) where T : BaseGuild + { + if (tidy) set.RemoveWhere(guild => guild.Disbanded); + + Write(set.Count); + + foreach (T guild in set) Write(guild); + } + } + +} diff --git a/Projects/Server/Serialization/BufferWriter.cs b/Projects/Server/Serialization/BufferWriter.cs index 9d814ec7d..82a3a4972 100644 --- a/Projects/Server/Serialization/BufferWriter.cs +++ b/Projects/Server/Serialization/BufferWriter.cs @@ -1,645 +1,650 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Net; -using Server.Guilds; - -namespace Server -{ - public class BufferWriter : IGenericWriter - { - private const int LargeByteBufferSize = 256; - - private byte[] m_Buffer; - - private byte[] m_CharacterBuffer; - - private Encoding m_Encoding; - - private int m_Index; - private int m_MaxBufferChars; - - private char[] m_SingleCharBuffer = new char[1]; - private bool PrefixStrings; - - public BufferWriter(bool prefixStr) - { - PrefixStrings = prefixStr; - m_Encoding = Utility.UTF8; - m_Buffer = new byte[BufferSize]; - } - - protected virtual int BufferSize { - get { - if (m_Buffer != null) - { - return m_Buffer.Length; - } - return 64; - } } - - public long Position => m_Index; - - public byte[] Data { get { return m_Buffer; } } - - public void Close() - { - } - public void Flush() - { - m_Index = 0; - } - - private void Expand() - { - byte[] newBuffer = new byte[BufferSize * 2]; - Buffer.BlockCopy(m_Buffer, 0, newBuffer, 0, m_Buffer.Length); - m_Buffer = newBuffer; - } - - public void WriteEncodedInt(int value) - { - uint v = (uint)value; - - while (v >= 0x80) - { - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = (byte)(v | 0x80); - v >>= 7; - } - - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = (byte)v; - } - - internal void InternalWriteString(string value) - { - int length = m_Encoding.GetByteCount(value); - - WriteEncodedInt(length); - - if (m_CharacterBuffer == null) - { - m_CharacterBuffer = new byte[LargeByteBufferSize]; - m_MaxBufferChars = LargeByteBufferSize / m_Encoding.GetMaxByteCount(1); - } - - if (length > LargeByteBufferSize) - { - int current = 0; - int charsLeft = value.Length; - - while (charsLeft > 0) - { - int charCount = charsLeft > m_MaxBufferChars ? m_MaxBufferChars : charsLeft; - int byteLength = m_Encoding.GetBytes(value, current, charCount, m_CharacterBuffer, 0); - - if (m_Index + byteLength > m_Buffer.Length) - Expand(); - - Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); - m_Index += byteLength; - - current += charCount; - charsLeft -= charCount; - } - } - else - { - int byteLength = m_Encoding.GetBytes(value, 0, value.Length, m_CharacterBuffer, 0); - - if (m_Index + byteLength > m_Buffer.Length) - Expand(); - - Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); - m_Index += byteLength; - } - } - - public void Write(string value) - { - if (PrefixStrings) - { - if (value == null) - { - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = 0; - } - else - { - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = 1; - - InternalWriteString(value); - } - } - else - { - InternalWriteString(value); - } - } - - public void Write(DateTime value) - { - Write(value.Ticks); - } - - public void Write(DateTimeOffset value) - { - Write(value.Ticks); - Write(value.Offset.Ticks); - } - - public void WriteDeltaTime(DateTime value) - { - long ticks = value.Ticks; - long now = DateTime.UtcNow.Ticks; - - TimeSpan d; - - try - { - d = new TimeSpan(ticks - now); - } - catch - { - d = TimeSpan.MaxValue; - } - - Write(d); - } - - public void Write(IPAddress value) - { - Write(Utility.GetLongAddressValue(value)); - } - - public void Write(TimeSpan value) - { - Write(value.Ticks); - } - - public void Write(decimal value) - { - int[] bits = decimal.GetBits(value); - - for (int i = 0; i < bits.Length; ++i) - Write(bits[i]); - } - - public void Write(long value) - { - if (m_Index + 8 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Buffer[m_Index + 4] = (byte)(value >> 32); - m_Buffer[m_Index + 5] = (byte)(value >> 40); - m_Buffer[m_Index + 6] = (byte)(value >> 48); - m_Buffer[m_Index + 7] = (byte)(value >> 56); - m_Index += 8; - } - - public void Write(ulong value) - { - if (m_Index + 8 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Buffer[m_Index + 4] = (byte)(value >> 32); - m_Buffer[m_Index + 5] = (byte)(value >> 40); - m_Buffer[m_Index + 6] = (byte)(value >> 48); - m_Buffer[m_Index + 7] = (byte)(value >> 56); - m_Index += 8; - } - - public void Write(int value) - { - if (m_Index + 4 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Index += 4; - } - - public void Write(uint value) - { - if (m_Index + 4 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Buffer[m_Index + 2] = (byte)(value >> 16); - m_Buffer[m_Index + 3] = (byte)(value >> 24); - m_Index += 4; - } - - public void Write(short value) - { - if (m_Index + 2 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Index += 2; - } - - public void Write(ushort value) - { - if (m_Index + 2 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index] = (byte)value; - m_Buffer[m_Index + 1] = (byte)(value >> 8); - m_Index += 2; - } - - public unsafe void Write(double value) - { - if (m_Index + 8 > m_Buffer.Length) - Expand(); - - fixed (byte* pBuffer = m_Buffer) - { - *(double*)(pBuffer + m_Index) = value; - } - - m_Index += 8; - } - - public unsafe void Write(float value) - { - if (m_Index + 4 > m_Buffer.Length) - Expand(); - - fixed (byte* pBuffer = m_Buffer) - { - *(float*)(pBuffer + m_Index) = value; - } - - m_Index += 4; - } - - public void Write(char value) - { - if (m_Index + 8 > m_Buffer.Length) - Expand(); - - m_SingleCharBuffer[0] = value; - - int byteCount = m_Encoding.GetBytes(m_SingleCharBuffer, 0, 1, m_Buffer, m_Index); - m_Index += byteCount; - } - - public void Write(byte value) - { - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = value; - } - - public void Write(byte[] value) - { - Write(value, value.Length); - } - - public void Write(byte[] value, int length) - { - if ((m_Index + length) > m_Buffer.Length) - Expand(); - - Buffer.BlockCopy(value, 0, m_Buffer, m_Index, length); - m_Index += length; - } - public void Write(sbyte value) - { - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = (byte)value; - } - - public void Write(bool value) - { - if (m_Index + 1 > m_Buffer.Length) - Expand(); - - m_Buffer[m_Index++] = (byte)(value ? 1 : 0); - } - - public void Write(Point3D value) - { - Write(value.m_X); - Write(value.m_Y); - Write(value.m_Z); - } - - public void Write(Point2D value) - { - Write(value.m_X); - Write(value.m_Y); - } - - public void Write(Rectangle2D value) - { - Write(value.Start); - Write(value.End); - } - - public void Write(Rectangle3D value) - { - Write(value.Start); - Write(value.End); - } - - public void Write(Map value) - { - if (value != null) - Write((byte)value.MapIndex); - else - Write((byte)0xFF); - } - - public void Write(Race value) - { - if (value != null) - Write((byte)value.RaceIndex); - else - Write((byte)0xFF); - } - - public void WriteEntity(IEntity value) - { - if (value?.Deleted != false) - Write(Serial.MinusOne); - else - Write(value.Serial); - } - - public void Write(Item value) - { - if (value?.Deleted != false) - Write(Serial.MinusOne); - else - Write(value.Serial); - } - - public void Write(Mobile value) - { - if (value?.Deleted != false) - Write(Serial.MinusOne); - else - Write(value.Serial); - } - - public void Write(BaseGuild value) - { - if (value == null) - Write(0); - else - Write(value.Id); - } - - public void WriteItem(T value) where T : Item - { - Write(value); - } - - public void WriteMobile(T value) where T : Mobile - { - Write(value); - } - - public void WriteGuild(T value) where T : BaseGuild - { - Write(value); - } - - public void Write(List list) - { - Write(list, false); - } - - public void Write(List list, bool tidy) - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void WriteItemList(List list) where T : Item - { - WriteItemList(list, false); - } - - public void WriteItemList(List list, bool tidy) where T : Item - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void Write(HashSet set) - { - Write(set, false); - } - - public void Write(HashSet set, bool tidy) - { - if (tidy) set.RemoveWhere(item => item.Deleted); - - Write(set.Count); - - foreach (Item item in set) Write(item); - } - - public void WriteItemSet(HashSet set) where T : Item - { - WriteItemSet(set, false); - } - - public void WriteItemSet(HashSet set, bool tidy) where T : Item - { - if (tidy) set.RemoveWhere(item => item.Deleted); - - Write(set.Count); - - foreach (T item in set) Write(item); - } - - public void Write(List list) - { - Write(list, false); - } - - public void Write(List list, bool tidy) - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void WriteMobileList(List list) where T : Mobile - { - WriteMobileList(list, false); - } - - public void WriteMobileList(List list, bool tidy) where T : Mobile - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Deleted) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void Write(HashSet set) - { - Write(set, false); - } - - public void Write(HashSet set, bool tidy) - { - if (tidy) set.RemoveWhere(mobile => mobile.Deleted); - - Write(set.Count); - - foreach (Mobile mob in set) Write(mob); - } - - public void WriteMobileSet(HashSet set) where T : Mobile - { - WriteMobileSet(set, false); - } - - public void WriteMobileSet(HashSet set, bool tidy) where T : Mobile - { - if (tidy) set.RemoveWhere(mob => mob.Deleted); - - Write(set.Count); - - foreach (T mob in set) Write(mob); - } - - public void Write(List list) - { - Write(list, false); - } - - public void Write(List list, bool tidy) - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Disbanded) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void WriteGuildList(List list) where T : BaseGuild - { - WriteGuildList(list, false); - } - - public void WriteGuildList(List list, bool tidy) where T : BaseGuild - { - if (tidy) - for (int i = 0; i < list.Count;) - if (list[i].Disbanded) - list.RemoveAt(i); - else - ++i; - - Write(list.Count); - - for (int i = 0; i < list.Count; ++i) - Write(list[i]); - } - - public void Write(HashSet set) - { - Write(set, false); - } - - public void Write(HashSet set, bool tidy) - { - if (tidy) set.RemoveWhere(guild => guild.Disbanded); - - Write(set.Count); - - foreach (BaseGuild guild in set) Write(guild); - } - - public void WriteGuildSet(HashSet set) where T : BaseGuild - { - WriteGuildSet(set, false); - } - - public void WriteGuildSet(HashSet set, bool tidy) where T : BaseGuild - { - if (tidy) set.RemoveWhere(guild => guild.Disbanded); - - Write(set.Count); - - foreach (T guild in set) Write(guild); - } - - public void WriteTo(IGenericWriter writer) - { - writer.Write(Data, (int)Position); - } - } -} +/************************************************************************* + * ModernUO * + * Copyright (C) 2019 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: BufferWriter.cs * + * Created: 2019/12/30 - Updated: 2020/01/18 * + * * + * 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 . * + *************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using Server.Guilds; + +namespace Server +{ + public class BufferWriter : IGenericWriter + { + private const int LargeByteBufferSize = 256; + + private byte[] m_Buffer; + + private byte[] m_CharacterBuffer; + + private Encoding m_Encoding; + + private int m_Index; + private int m_MaxBufferChars; + + private char[] m_SingleCharBuffer = new char[1]; + private bool PrefixStrings; + + public BufferWriter(bool prefixStr) + { + PrefixStrings = prefixStr; + m_Encoding = Utility.UTF8; + m_Buffer = new byte[BufferSize]; + } + + protected virtual int BufferSize => m_Buffer?.Length ?? 64; + + public long Position => m_Index; + + public byte[] Data => m_Buffer; + + public void Close() + { + } + public void Flush() + { + m_Index = 0; + } + + private void Expand() + { + byte[] newBuffer = new byte[BufferSize * 2]; + Buffer.BlockCopy(m_Buffer, 0, newBuffer, 0, m_Buffer.Length); + m_Buffer = newBuffer; + } + + public void WriteEncodedInt(int value) + { + uint v = (uint)value; + + while (v >= 0x80) + { + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = (byte)(v | 0x80); + v >>= 7; + } + + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = (byte)v; + } + + internal void InternalWriteString(string value) + { + int length = m_Encoding.GetByteCount(value); + + WriteEncodedInt(length); + + if (m_CharacterBuffer == null) + { + m_CharacterBuffer = new byte[LargeByteBufferSize]; + m_MaxBufferChars = LargeByteBufferSize / m_Encoding.GetMaxByteCount(1); + } + + if (length > LargeByteBufferSize) + { + int current = 0; + int charsLeft = value.Length; + + while (charsLeft > 0) + { + int charCount = charsLeft > m_MaxBufferChars ? m_MaxBufferChars : charsLeft; + int byteLength = m_Encoding.GetBytes(value, current, charCount, m_CharacterBuffer, 0); + + if (m_Index + byteLength > m_Buffer.Length) + Expand(); + + Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); + m_Index += byteLength; + + current += charCount; + charsLeft -= charCount; + } + } + else + { + int byteLength = m_Encoding.GetBytes(value, 0, value.Length, m_CharacterBuffer, 0); + + if (m_Index + byteLength > m_Buffer.Length) + Expand(); + + Buffer.BlockCopy(m_CharacterBuffer, 0, m_Buffer, m_Index, byteLength); + m_Index += byteLength; + } + } + + public void Write(string value) + { + if (PrefixStrings) + { + if (value == null) + { + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = 0; + } + else + { + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = 1; + + InternalWriteString(value); + } + } + else + { + InternalWriteString(value); + } + } + + public void Write(DateTime value) + { + Write(value.Ticks); + } + + public void Write(DateTimeOffset value) + { + Write(value.Ticks); + Write(value.Offset.Ticks); + } + + public void WriteDeltaTime(DateTime value) + { + long ticks = value.Ticks; + long now = DateTime.UtcNow.Ticks; + + TimeSpan d; + + try + { + d = new TimeSpan(ticks - now); + } + catch + { + d = TimeSpan.MaxValue; + } + + Write(d); + } + + public void Write(IPAddress value) + { + Write(Utility.GetLongAddressValue(value)); + } + + public void Write(TimeSpan value) + { + Write(value.Ticks); + } + + public void Write(decimal value) + { + int[] bits = decimal.GetBits(value); + + for (int i = 0; i < bits.Length; ++i) + Write(bits[i]); + } + + public void Write(long value) + { + if (m_Index + 8 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Buffer[m_Index + 4] = (byte)(value >> 32); + m_Buffer[m_Index + 5] = (byte)(value >> 40); + m_Buffer[m_Index + 6] = (byte)(value >> 48); + m_Buffer[m_Index + 7] = (byte)(value >> 56); + m_Index += 8; + } + + public void Write(ulong value) + { + if (m_Index + 8 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Buffer[m_Index + 4] = (byte)(value >> 32); + m_Buffer[m_Index + 5] = (byte)(value >> 40); + m_Buffer[m_Index + 6] = (byte)(value >> 48); + m_Buffer[m_Index + 7] = (byte)(value >> 56); + m_Index += 8; + } + + public void Write(int value) + { + if (m_Index + 4 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Index += 4; + } + + public void Write(uint value) + { + if (m_Index + 4 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Buffer[m_Index + 2] = (byte)(value >> 16); + m_Buffer[m_Index + 3] = (byte)(value >> 24); + m_Index += 4; + } + + public void Write(short value) + { + if (m_Index + 2 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Index += 2; + } + + public void Write(ushort value) + { + if (m_Index + 2 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index] = (byte)value; + m_Buffer[m_Index + 1] = (byte)(value >> 8); + m_Index += 2; + } + + public unsafe void Write(double value) + { + if (m_Index + 8 > m_Buffer.Length) + Expand(); + + fixed (byte* pBuffer = m_Buffer) + { + *(double*)(pBuffer + m_Index) = value; + } + + m_Index += 8; + } + + public unsafe void Write(float value) + { + if (m_Index + 4 > m_Buffer.Length) + Expand(); + + fixed (byte* pBuffer = m_Buffer) + { + *(float*)(pBuffer + m_Index) = value; + } + + m_Index += 4; + } + + public void Write(char value) + { + if (m_Index + 8 > m_Buffer.Length) + Expand(); + + m_SingleCharBuffer[0] = value; + + int byteCount = m_Encoding.GetBytes(m_SingleCharBuffer, 0, 1, m_Buffer, m_Index); + m_Index += byteCount; + } + + public void Write(byte value) + { + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = value; + } + + public void Write(byte[] value) + { + Write(value, value.Length); + } + + public void Write(byte[] value, int length) + { + if (m_Index + length > m_Buffer.Length) + Expand(); + + Buffer.BlockCopy(value, 0, m_Buffer, m_Index, length); + m_Index += length; + } + public void Write(sbyte value) + { + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = (byte)value; + } + + public void Write(bool value) + { + if (m_Index + 1 > m_Buffer.Length) + Expand(); + + m_Buffer[m_Index++] = (byte)(value ? 1 : 0); + } + + public void Write(Point3D value) + { + Write(value.m_X); + Write(value.m_Y); + Write(value.m_Z); + } + + public void Write(Point2D value) + { + Write(value.m_X); + Write(value.m_Y); + } + + public void Write(Rectangle2D value) + { + Write(value.Start); + Write(value.End); + } + + public void Write(Rectangle3D value) + { + Write(value.Start); + Write(value.End); + } + + public void Write(Map value) + { + if (value != null) + Write((byte)value.MapIndex); + else + Write((byte)0xFF); + } + + public void Write(Race value) + { + if (value != null) + Write((byte)value.RaceIndex); + else + Write((byte)0xFF); + } + + public void WriteEntity(IEntity value) + { + Write(value?.Deleted != false ? Serial.MinusOne : value.Serial); + } + + public void Write(Item value) + { + Write(value?.Deleted != false ? Serial.MinusOne : value.Serial); + } + + public void Write(Mobile value) + { + Write(value?.Deleted != false ? Serial.MinusOne : value.Serial); + } + + public void Write(BaseGuild value) + { + if (value == null) + Write(0); + else + Write(value.Id); + } + + public void WriteItem(T value) where T : Item + { + Write(value); + } + + public void WriteMobile(T value) where T : Mobile + { + Write(value); + } + + public void WriteGuild(T value) where T : BaseGuild + { + Write(value); + } + + public void Write(List list) + { + Write(list, false); + } + + public void Write(List list, bool tidy) + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void WriteItemList(List list) where T : Item + { + WriteItemList(list, false); + } + + public void WriteItemList(List list, bool tidy) where T : Item + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void Write(HashSet set) + { + Write(set, false); + } + + public void Write(HashSet set, bool tidy) + { + if (tidy) set.RemoveWhere(item => item.Deleted); + + Write(set.Count); + + foreach (Item item in set) Write(item); + } + + public void WriteItemSet(HashSet set) where T : Item + { + WriteItemSet(set, false); + } + + public void WriteItemSet(HashSet set, bool tidy) where T : Item + { + if (tidy) set.RemoveWhere(item => item.Deleted); + + Write(set.Count); + + foreach (T item in set) Write(item); + } + + public void Write(List list) + { + Write(list, false); + } + + public void Write(List list, bool tidy) + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void WriteMobileList(List list) where T : Mobile + { + WriteMobileList(list, false); + } + + public void WriteMobileList(List list, bool tidy) where T : Mobile + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Deleted) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void Write(HashSet set) + { + Write(set, false); + } + + public void Write(HashSet set, bool tidy) + { + if (tidy) set.RemoveWhere(mobile => mobile.Deleted); + + Write(set.Count); + + foreach (Mobile mob in set) Write(mob); + } + + public void WriteMobileSet(HashSet set) where T : Mobile + { + WriteMobileSet(set, false); + } + + public void WriteMobileSet(HashSet set, bool tidy) where T : Mobile + { + if (tidy) set.RemoveWhere(mob => mob.Deleted); + + Write(set.Count); + + foreach (T mob in set) Write(mob); + } + + public void Write(List list) + { + Write(list, false); + } + + public void Write(List list, bool tidy) + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Disbanded) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void WriteGuildList(List list) where T : BaseGuild + { + WriteGuildList(list, false); + } + + public void WriteGuildList(List list, bool tidy) where T : BaseGuild + { + if (tidy) + for (int i = 0; i < list.Count;) + if (list[i].Disbanded) + list.RemoveAt(i); + else + ++i; + + Write(list.Count); + + for (int i = 0; i < list.Count; ++i) + Write(list[i]); + } + + public void Write(HashSet set) + { + Write(set, false); + } + + public void Write(HashSet set, bool tidy) + { + if (tidy) set.RemoveWhere(guild => guild.Disbanded); + + Write(set.Count); + + foreach (BaseGuild guild in set) Write(guild); + } + + public void WriteGuildSet(HashSet set) where T : BaseGuild + { + WriteGuildSet(set, false); + } + + public void WriteGuildSet(HashSet set, bool tidy) where T : BaseGuild + { + if (tidy) set.RemoveWhere(guild => guild.Disbanded); + + Write(set.Count); + + foreach (T guild in set) Write(guild); + } + + public void WriteTo(IGenericWriter writer) + { + writer.Write(Data, (int)Position); + } + } +} diff --git a/Projects/Server/Serialization/IGenericReader.cs b/Projects/Server/Serialization/IGenericReader.cs index 3d520eed9..125426a82 100644 --- a/Projects/Server/Serialization/IGenericReader.cs +++ b/Projects/Server/Serialization/IGenericReader.cs @@ -1,57 +1,78 @@ -using System; -using System.Collections.Generic; -using System.Net; -using Server.Guilds; - -namespace Server -{ - public interface IGenericReader - { - string ReadString(); - DateTime ReadDateTime(); - DateTimeOffset ReadDateTimeOffset(); - TimeSpan ReadTimeSpan(); - DateTime ReadDeltaTime(); - decimal ReadDecimal(); - long ReadLong(); - ulong ReadULong(); - int ReadInt(); - uint ReadUInt(); - short ReadShort(); - ushort ReadUShort(); - double ReadDouble(); - float ReadFloat(); - char ReadChar(); - byte ReadByte(); - sbyte ReadSByte(); - bool ReadBool(); - int ReadEncodedInt(); - IPAddress ReadIPAddress(); - Point3D ReadPoint3D(); - Point2D ReadPoint2D(); - Rectangle2D ReadRect2D(); - Rectangle3D ReadRect3D(); - Map ReadMap(); - IEntity ReadEntity(); - Item ReadItem(); - Mobile ReadMobile(); - BaseGuild ReadGuild(); - T ReadItem() where T : Item; - T ReadMobile() where T : Mobile; - T ReadGuild() where T : BaseGuild; - List ReadStrongItemList(); - List ReadStrongItemList() where T : Item; - List ReadStrongMobileList(); - List ReadStrongMobileList() where T : Mobile; - List ReadStrongGuildList(); - List ReadStrongGuildList() where T : BaseGuild; - HashSet ReadItemSet(); - HashSet ReadItemSet() where T : Item; - HashSet ReadMobileSet(); - HashSet ReadMobileSet() where T : Mobile; - HashSet ReadGuildSet(); - HashSet ReadGuildSet() where T : BaseGuild; - Race ReadRace(); - bool End(); - } -} +/************************************************************************* + * ModernUO * + * Copyright (C) 2019 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: IGenericReader.cs * + * Created: 2019/12/30 - Updated: 2020/01/18 * + * * + * 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 . * + *************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Net; +using Server.Guilds; + +namespace Server +{ + public interface IGenericReader + { + string ReadString(); + DateTime ReadDateTime(); + DateTimeOffset ReadDateTimeOffset(); + TimeSpan ReadTimeSpan(); + DateTime ReadDeltaTime(); + decimal ReadDecimal(); + long ReadLong(); + ulong ReadULong(); + int ReadInt(); + uint ReadUInt(); + short ReadShort(); + ushort ReadUShort(); + double ReadDouble(); + float ReadFloat(); + char ReadChar(); + byte ReadByte(); + sbyte ReadSByte(); + bool ReadBool(); + int ReadEncodedInt(); + IPAddress ReadIPAddress(); + Point3D ReadPoint3D(); + Point2D ReadPoint2D(); + Rectangle2D ReadRect2D(); + Rectangle3D ReadRect3D(); + Map ReadMap(); + IEntity ReadEntity(); + Item ReadItem(); + Mobile ReadMobile(); + BaseGuild ReadGuild(); + T ReadItem() where T : Item; + T ReadMobile() where T : Mobile; + T ReadGuild() where T : BaseGuild; + List ReadStrongItemList(); + List ReadStrongItemList() where T : Item; + List ReadStrongMobileList(); + List ReadStrongMobileList() where T : Mobile; + List ReadStrongGuildList(); + List ReadStrongGuildList() where T : BaseGuild; + HashSet ReadItemSet(); + HashSet ReadItemSet() where T : Item; + HashSet ReadMobileSet(); + HashSet ReadMobileSet() where T : Mobile; + HashSet ReadGuildSet(); + HashSet ReadGuildSet() where T : BaseGuild; + Race ReadRace(); + bool End(); + } +} diff --git a/Projects/Server/Serialization/IGenericWriter.cs b/Projects/Server/Serialization/IGenericWriter.cs index 7ad07d519..ba59ac051 100644 --- a/Projects/Server/Serialization/IGenericWriter.cs +++ b/Projects/Server/Serialization/IGenericWriter.cs @@ -1,91 +1,112 @@ -using System; -using System.Collections.Generic; -using System.Net; -using Server.Guilds; - -namespace Server -{ - public interface IGenericWriter - { - long Position { get; } - - void Close(); - - void Write(string value); - void Write(DateTime value); - void Write(DateTimeOffset value); - void Write(TimeSpan value); - void Write(decimal value); - void Write(long value); - void Write(ulong value); - void Write(int value); - void Write(uint value); - void Write(short value); - void Write(ushort value); - void Write(double value); - void Write(float value); - void Write(char value); - void Write(byte value); - void Write(byte[] value); - void Write(byte[] value, int length); - void Write(sbyte value); - void Write(bool value); - void WriteEncodedInt(int value); - void Write(IPAddress value); - - void WriteDeltaTime(DateTime value); - - void Write(Point3D value); - void Write(Point2D value); - void Write(Rectangle2D value); - void Write(Rectangle3D value); - void Write(Map value); - - void WriteEntity(IEntity value); - void Write(Item value); - void Write(Mobile value); - void Write(BaseGuild value); - - void WriteItem(T value) where T : Item; - void WriteMobile(T value) where T : Mobile; - void WriteGuild(T value) where T : BaseGuild; - - void Write(Race value); - - void Write(List list); - void Write(List list, bool tidy); - - void WriteItemList(List list) where T : Item; - void WriteItemList(List list, bool tidy) where T : Item; - - void Write(HashSet list); - void Write(HashSet list, bool tidy); - - void WriteItemSet(HashSet set) where T : Item; - void WriteItemSet(HashSet set, bool tidy) where T : Item; - - void Write(List list); - void Write(List list, bool tidy); - - void WriteMobileList(List list) where T : Mobile; - void WriteMobileList(List list, bool tidy) where T : Mobile; - - void Write(HashSet list); - void Write(HashSet list, bool tidy); - - void WriteMobileSet(HashSet set) where T : Mobile; - void WriteMobileSet(HashSet set, bool tidy) where T : Mobile; - - void Write(List list); - void Write(List list, bool tidy); - - void WriteGuildList(List list) where T : BaseGuild; - void WriteGuildList(List list, bool tidy) where T : BaseGuild; - - void Write(HashSet list); - void Write(HashSet list, bool tidy); - - void WriteGuildSet(HashSet set) where T : BaseGuild; - void WriteGuildSet(HashSet set, bool tidy) where T : BaseGuild; - } -} +/************************************************************************* + * ModernUO * + * Copyright (C) 2019 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: IGenericWriter.cs * + * Created: 2019/12/30 - Updated: 2020/01/18 * + * * + * 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 . * + *************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Net; +using Server.Guilds; + +namespace Server +{ + public interface IGenericWriter + { + long Position { get; } + + void Close(); + + void Write(string value); + void Write(DateTime value); + void Write(DateTimeOffset value); + void Write(TimeSpan value); + void Write(decimal value); + void Write(long value); + void Write(ulong value); + void Write(int value); + void Write(uint value); + void Write(short value); + void Write(ushort value); + void Write(double value); + void Write(float value); + void Write(char value); + void Write(byte value); + void Write(byte[] value); + void Write(byte[] value, int length); + void Write(sbyte value); + void Write(bool value); + void WriteEncodedInt(int value); + void Write(IPAddress value); + + void WriteDeltaTime(DateTime value); + + void Write(Point3D value); + void Write(Point2D value); + void Write(Rectangle2D value); + void Write(Rectangle3D value); + void Write(Map value); + + void WriteEntity(IEntity value); + void Write(Item value); + void Write(Mobile value); + void Write(BaseGuild value); + + void WriteItem(T value) where T : Item; + void WriteMobile(T value) where T : Mobile; + void WriteGuild(T value) where T : BaseGuild; + + void Write(Race value); + + void Write(List list); + void Write(List list, bool tidy); + + void WriteItemList(List list) where T : Item; + void WriteItemList(List list, bool tidy) where T : Item; + + void Write(HashSet list); + void Write(HashSet list, bool tidy); + + void WriteItemSet(HashSet set) where T : Item; + void WriteItemSet(HashSet set, bool tidy) where T : Item; + + void Write(List list); + void Write(List list, bool tidy); + + void WriteMobileList(List list) where T : Mobile; + void WriteMobileList(List list, bool tidy) where T : Mobile; + + void Write(HashSet list); + void Write(HashSet list, bool tidy); + + void WriteMobileSet(HashSet set) where T : Mobile; + void WriteMobileSet(HashSet set, bool tidy) where T : Mobile; + + void Write(List list); + void Write(List list, bool tidy); + + void WriteGuildList(List list) where T : BaseGuild; + void WriteGuildList(List list, bool tidy) where T : BaseGuild; + + void Write(HashSet list); + void Write(HashSet list, bool tidy); + + void WriteGuildSet(HashSet set) where T : BaseGuild; + void WriteGuildSet(HashSet set, bool tidy) where T : BaseGuild; + } +} diff --git a/Projects/Server/Serialization/ISerializable.cs b/Projects/Server/Serialization/ISerializable.cs index 06dc4912c..17a3df60a 100644 --- a/Projects/Server/Serialization/ISerializable.cs +++ b/Projects/Server/Serialization/ISerializable.cs @@ -1,15 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Server -{ - public interface ISerializable - { - BufferWriter SaveBuffer { get; } - int TypeReference { get; } - uint SerialIdentity { get; } - void Serialize(); - void Serialize(IGenericWriter writer); - } -} +/************************************************************************* + * ModernUO * + * Copyright (C) 2019 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: ISerializable.cs * + * Created: 2019/12/30 - Updated: 2020/01/18 * + * * + * 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 . * + *************************************************************************/ + +namespace Server +{ + public interface ISerializable + { + BufferWriter SaveBuffer { get; } + int TypeReference { get; } + uint SerialIdentity { get; } + void Serialize(); + void Serialize(IGenericWriter writer); + } +} diff --git a/Projects/Server/TileMatrix.cs b/Projects/Server/TileMatrix.cs index 953da3dd7..44dc98601 100644 --- a/Projects/Server/TileMatrix.cs +++ b/Projects/Server/TileMatrix.cs @@ -191,14 +191,10 @@ namespace Server if (x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight) return; - if (m_StaticTiles[x] == null) - m_StaticTiles[x] = new StaticTile[BlockHeight][][][]; - + m_StaticTiles[x] ??= new StaticTile[BlockHeight][][][]; m_StaticTiles[x][y] = value; - if (m_StaticPatches[x] == null) - m_StaticPatches[x] = new int[BlockHeight + 31 >> 5]; - + m_StaticPatches[x] ??= new int[BlockHeight + 31 >> 5]; m_StaticPatches[x][y >> 5] |= 1 << (y & 0x1F); } @@ -208,8 +204,7 @@ namespace Server if (x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight || DataStream == null || IndexStream == null) return EmptyStaticBlock; - if (m_StaticTiles[x] == null) - m_StaticTiles[x] = new StaticTile[BlockHeight][][][]; + m_StaticTiles[x] ??= new StaticTile[BlockHeight][][][]; StaticTile[][][] tiles = m_StaticTiles[x][y]; @@ -287,14 +282,10 @@ namespace Server if (x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight) return; - if (m_LandTiles[x] == null) - m_LandTiles[x] = new LandTile[BlockHeight][]; - + m_LandTiles[x] ??= new LandTile[BlockHeight][]; m_LandTiles[x][y] = value; - if (m_LandPatches[x] == null) - m_LandPatches[x] = new int[BlockHeight + 31 >> 5]; - + m_LandPatches[x] ??= new int[BlockHeight + 31 >> 5]; m_LandPatches[x][y >> 5] |= 1 << (y & 0x1F); } @@ -304,8 +295,7 @@ namespace Server if (x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight || MapStream == null) return m_InvalidLandBlock; - if (m_LandTiles[x] == null) - m_LandTiles[x] = new LandTile[BlockHeight][]; + m_LandTiles[x] ??= new LandTile[BlockHeight][]; LandTile[] tiles = m_LandTiles[x][y]; diff --git a/Projects/Server/Utilities/Utility.cs b/Projects/Server/Utilities/Utility.cs index 52bd579ee..8c37f5b5d 100644 --- a/Projects/Server/Utilities/Utility.cs +++ b/Projects/Server/Utilities/Utility.cs @@ -129,7 +129,7 @@ namespace Server sb.Append(value); } - public static string Intern(string str) => str == null ? null : str.Length == 0 ? string.Empty : string.Intern(str); + public static string Intern(string str) => str?.Length > 0 ? string.Intern(str) : str; public static void Intern(ref string str) { @@ -138,8 +138,7 @@ namespace Server public static IPAddress Intern(IPAddress ipAddress) { - if (_ipAddressTable == null) - _ipAddressTable = new Dictionary(); + _ipAddressTable ??= new Dictionary(); if (!_ipAddressTable.TryGetValue(ipAddress, out IPAddress interned)) { diff --git a/Projects/Server/VirtueInfo.cs b/Projects/Server/VirtueInfo.cs index 933f100ad..5aa02b815 100644 --- a/Projects/Server/VirtueInfo.cs +++ b/Projects/Server/VirtueInfo.cs @@ -121,18 +121,11 @@ namespace Server set => SetValue(7, value); } - public int GetValue(int index) - { - if (Values == null) - return 0; - return Values[index]; - } + public int GetValue(int index) => Values?[index] ?? 0; public void SetValue(int index, int value) { - if (Values == null) - Values = new int[8]; - + Values ??= new int[8]; Values[index] = value; }